From albertito_g at hotmail.com  Thu Sep  1 00:02:31 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Wed, 31 Aug 2005 22:02:31 +0000
Subject: [Tutor] Tail -f problem
In-Reply-To: <ELEJKMPCKBHFKEFBJAOMMEGJCBAA.nick@javacat.f2s.com>
Message-ID: <BAY106-F238D158FADA6129566EA7D89A10@phx.gbl>

Hey Nick

About the mysql upgrade (by the way thanks for the reply) I have downloaded 
the rpm fron mysql.com along with the installation manual..I will give it a 
try

The code you sent in the hyperlink looks neat...I will try it out since the 
page hasn't much documentation about this example in particular

Thanks a lot

Alberto

>From: "Nick Lunt" <nick at javacat.f2s.com>
>To: "Alberto Troiano" <albertito_g at hotmail.com>, <tutor at python.org>
>Subject: Re: [Tutor] Tail -f problem
>Date: Wed, 31 Aug 2005 22:38:42 +0100
>
>Hi Alberto,
>
>
> > -----Original Message-----
> > From: tutor-bounces+nick=javacat.f2s.com at python.org
> > [mailto:tutor-bounces+nick=javacat.f2s.com at python.org]On Behalf Of
> > Alberto Troiano
> > Sent: 31 August 2005 22:01
> > To: tutor at python.org
> > Subject: [Tutor] Tail -f problem
> >
> >
> > Hey
> >
>I thought about tail-f
> > /var/log/radacct/max/detail but this thing opens a console and I
> > won't end
> > but how can I get the output of the command to python..
>
>Have a look here for a possible solution to your tail -f problem
>http://twistedmatrix.com/projects/core/documentation/examples/filewatch.py
>
>
> > I know the second option has nothing to do with this forum but if anyone
> > knows of any manual to upgrade MySQL over Linux Red HAt I would 
>appreciate
>
>If your using a recent Redhat then try this as root (im on a windows box at
>the moment so this is untested)
>
>$ yum upgrade mysql mysql-server
>
>Naturally this will only work if your current mysql install is an RPM.
>
>Cheers
>Nick .
>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



From rxdamian at gmail.com  Thu Sep  1 04:18:16 2005
From: rxdamian at gmail.com (Damian)
Date: Wed, 31 Aug 2005 21:18:16 -0500
Subject: [Tutor] Need directions toward programming...
Message-ID: <1eac597d0508311918303fca42@mail.gmail.com>

Just go to the "4th" paragraph to read my main concern.
 Hi I'm a 18 years old student (well not for now), who's interested in 
programming and everything you can do with it, but I got a problem, honestly 
is more like a misdirection problem, I live in Mexico and to be honest the 
studies about programming sucks!. 
 When I got in my 1st year in the best technical high school, the first 
language a teacher show us was quick basic and even after 6 months of 
classes everything we did was 5 programs that do simple arithmetic 
operations, but that's not the worst part after 3 years at the last 
semester, we needed to write a system that manage databases for practical 
uses (well not really, it was just to pass the class) for the final grades, 
but the only language we knew more or less, and that was enough to pass the 
class (just because of the graphical design!) was Visual Basic 6.0, you can 
imagine the troubles a lived declaring constant changing variables (a = b, b 
= b + 1...), after some time of studying complex syntax's and variable types 
declarations I finished just a few forms (scripts), but at least I was proud 
that they were practical in real life, I was writing an Algebra learning 
software. The day of the examination came and I was confident that my work 
was incomplete, I was sure that I'll failed the subject but then I received 
the news, I got an 8 of 10, that was great considering my small program, I 
tough that maybe the teacher appreciated my effort on the code but then I 
saw the others students grades and their works, I was shocked, I couldn't 
believe it, the people who finished their project got an 10 or 9, but that's 
not the reason of my anger, they got a great grade for a work that was 
just...fine, the only thing that was at a level of the grade was the design; 
the project itself contained a lot of bugs, and the teacher didn't take that 
in consideration for the grades, I was pissed off !, I asked myself how is 
possible that a programming language teacher qualified the projects without 
taken into account the bugs, I was really angry, in that moment I realized 
that all the time that I spent in programming in that school was a waste...
 That's why I'm concerned about my education, in the beginning I write 
"well, not for now", I was speaking about a decision a made just before 
getting in an University, I decide to study by myself, I tough "if the 
educational system sucks, then I'll have to take my education on my hands", 
and here I am now, oh! sorry for the long post I think I was motivated or 
something, the real goal of my post is to find some direction toward my 
education in this field, I'm aiming to become a System Analyst and 
Programmer (I don't know how is named that occupation in US), and I want to 
create a revolutionary system in this city replacing the high cost windows 
systems of the companies with a Linux based one; in the University they're 
still teaching Visual Basic on the last semesters, that's why I want to take 
the most of my time learning dynamic languages instead of the proprietary 
ones.
 When I finished the python tutorial I was amazed about the simplicity of 
the code, but because I got no real life experience, I don't know what can I 
do with this knowledge, I know that practicing and reading code examples is 
a must!, but I would like to know real life experiences of some people 
toward programming with Python and toward programming in general, and if you 
can recommend me some books or tutorials of python (ex. real life examples) 
or toward the technical aspect of programming (multiple inheritance, control 
flow, etc.), so I can get an idea of the whole aspect of language 
programming.
 Really thanks for taking your time to answer my post, and sorry if I got 
some awful grammar errors, it's been a while since I writed in English.
 Note: I added my Visual Basic incomplete project just if you have curiosity 
about my work.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050831/630bfd3e/attachment.html
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Final High School Project.rar
Type: application/octet-stream
Size: 54357 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050831/630bfd3e/FinalHighSchoolProject-0001.obj

From benvinger at yahoo.co.uk  Thu Sep  1 13:28:41 2005
From: benvinger at yahoo.co.uk (Ben Vinger)
Date: Thu, 1 Sep 2005 12:28:41 +0100 (BST)
Subject: [Tutor] PYTHON????
In-Reply-To: <000501c5ad06$b5eb4170$6401a8c0@mortgage0tgfr4>
Message-ID: <20050901112841.96784.qmail@web25806.mail.ukl.yahoo.com>

The Python interpreter already contain the code for
multiplication, so you don't need to write it.  You
can just use it:

x = raw_input('give the first number')
y = raw_input('give the second number')
print x,  ' times ', y, ' is', int(x) * int( y)

Or in the interactive interpreter you can just:

>>> 2 * 4
8

Good Luck!


--- luckygoodluck at optonline.net wrote:

> Dear Python,
>  How does a calculator multiply? I want to create a
> computer software that can multiply. How do I
> program the computer to multiply? 
> > _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



	
	
		
___________________________________________________________ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com

From lists at janeden.org  Thu Sep  1 13:33:19 2005
From: lists at janeden.org (Jan Eden)
Date: Thu,  1 Sep 2005 13:33:19 +0200
Subject: [Tutor] datetime.date objects from SQL query?
Message-ID: <r02010500-1039-324489111ADC11DA82BD000A959B4026@[10.149.23.208]>

Hi,

I use the following query (simplified):

self.dbh.execute("SELECT anreise, abreise FROM buchungen WHERE ferienhaus = '%(ferienhaus)s'" % { 'ferienhaus': ferienhaus} )

Both anreise and abreise are date fields. I initially wrote a little function to turn ISO formatted date strings into a datetime.date object

def StringToDate(datestring):
    year, month, day = datestring.split('-')
    datum = datetime.date(int(year), int(month), int(day))
    return datum

But it looks as if the value of both anreise and abreise is returned as datetime.date objects automatically! This is great - but how does this happen?

Thanks,

Jan
-- 
Life's unfair - but root password helps!

From jhe13586 at bigpond.net.au  Thu Sep  1 14:05:02 2005
From: jhe13586 at bigpond.net.au (Joal Heagney)
Date: Thu, 01 Sep 2005 22:05:02 +1000
Subject: [Tutor] PYTHON????
In-Reply-To: <000501c5ad06$b5eb4170$6401a8c0@mortgage0tgfr4>
References: <000501c5ad06$b5eb4170$6401a8c0@mortgage0tgfr4>
Message-ID: <df6qpg$uf4$1@sea.gmane.org>

luckygoodluck at optonline.net wrote:
> Dear Python,
>  How does a calculator multiply? I want to create a computer software that can multiply. How do I program the computer to multiply? 

Basically the same way you multiply two big numbers on paper, by long 
multiplication.

E.g. Human 24 * 51

   24 *
   51
----
   24   (1 * 24)
120    (5 * 24 and shift one to the left)
----
1224

In order to do long-multiplication, humans need to know the powers from 
1x to 9x, and they have to do carry operations.

However, computers do muliplication in binary, where the only digits are 
0 and 1. Computers don't have to remember times tables.

E.g. Computer 24 * 51

24 in binary is 11000
51 in binary is 110011

How I convert decimal to binary:

What is the bigest power of 2 that is still smaller than the number?
64 > 51 > 32
32 is the largest power.

				Digits from Left
51 / 32 = 1 with 19 remainder     First digit:  1
19 / 16 = 1 with 3 remainder      Second digit: 1
  3 /  8 = 0 with 3 remainder      Third digit:  0
  3 /  4 = 0 with 3 remainder      Fourth digit: 0
  3 /  2 = 1 with 1 remainder      Fifth digit:  1
  1 /  1 = 1 with 0 remainder      Sixth digit:  1

Long Multiplication:

       11000 *
      110011
    --------
       11000  (Multiply 11000 by 1)
      11000   (Multiply 11000 by 1, shift to the left 1)
     00000    (Multiply 11000 by 0, shift to the left 2)
    00000     (Multiply 11000 by 0, shift to the left 3)
   11000      (Multiply 11000 by 1, shift to the left 4)
  11000       (Multiply 11000 by 1, shift to the left 5)
-----------
  1210121000  (My own private representation.)
-----------
  2010201000  (Twos are carried by adding 1 to the left.)
-----------
10011001000  (The binary answer.)

So 11000 * 101001 = 10011001000 in binary

How I convert binary back to decimal:
  1    0   0   1   1    0   0   1   0   0   0
1024 512 256 128  64  32  16   8   4   2   1

1024 + 128 + 64 + 8 = 1228

10011001000 in decimal is 1228

As you can see, the hardest part is the conversion to and from binary to 
decimal.

Joal


From lists at janeden.org  Thu Sep  1 15:56:55 2005
From: lists at janeden.org (Jan Eden)
Date: Thu,  1 Sep 2005 15:56:55 +0200
Subject: [Tutor] PYTHON????
In-Reply-To: <000501c5ad06$b5eb4170$6401a8c0@mortgage0tgfr4>
Message-ID: <r02010500-1039-423929D51AF011DA82BD000A959B4026@[10.149.23.208]>

luckygoodluck at optonline.net wrote on 29.08.2005:

>Dear Python,
> How does a calculator multiply? I want to create a computer software that can 
>multiply. How do I program the computer to multiply? 

Could this be a spammer aiming at mailing lists?

- Jan
-- 
The day Microsoft makes something that doesn't suck is the day they start selling vacuum cleaners.

From cpu.crazy at gmail.com  Thu Sep  1 16:03:01 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Thu, 01 Sep 2005 08:03:01 -0600
Subject: [Tutor] Need directions toward programming...
Message-ID: <43170A15.4030702@gmail.com>

Hi,

I sympathize (is that right?) I live in guatemala and the education 
system here sucks (luckily I'm homeschooled). I picked up Python after a 
year with Quick BASIC and 5 months later made my own GUI (Graphical User 
Interface if you don't know already...) program.

First off you'll need the python interpreter for your OS (Windows, 
Linux, Mac OS) from http://www.python.org/download/ then Download these 
ebooks: A Byte of Python and Learning to Program (sorry I don't know the 
URL but if you seach google (within qutotes [eg: "A Byte of Python"]) 
you'll find them quickly. Then complete Learning to Program First and A 
Byte of Python second..... let's see... I had money so I bought some 
O'reilly books, although you can find them illegally on the internet. 
Any help for more good free ebooks for beginners from you people out 
there? ;-)

Hope this helps. The process helped me.
Joseph

From ewalker at micron.com  Thu Sep  1 16:03:43 2005
From: ewalker at micron.com (Eric Walker)
Date: Thu, 1 Sep 2005 08:03:43 -0600
Subject: [Tutor] PYTHON????
In-Reply-To: <r02010500-1039-423929D51AF011DA82BD000A959B4026@[10.149.23.208]>
References: <r02010500-1039-423929D51AF011DA82BD000A959B4026@[10.149.23.208]>
Message-ID: <200509010803.43077.ewalker@micron.com>

Could be but the first time I get something hes going on the filter...

E....


On Thursday 01 September 2005 07:56 am, Jan Eden wrote:
> luckygoodluck at optonline.net wrote on 29.08.2005:
> >Dear Python,
> > How does a calculator multiply? I want to create a computer software that
> > can multiply. How do I program the computer to multiply?
>
> Could this be a spammer aiming at mailing lists?
>
> - Jan

From kent37 at tds.net  Thu Sep  1 16:25:41 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Sep 2005 10:25:41 -0400
Subject: [Tutor] Need directions toward programming...
In-Reply-To: <43170A15.4030702@gmail.com>
References: <43170A15.4030702@gmail.com>
Message-ID: <43170F65.5030609@tds.net>

Joseph Quigley wrote:
> Any help for more good free ebooks for beginners from you people out 
> there? ;-)

There are many online resources for learning Python listed here
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

or if you want something for programmers look here:
http://wiki.python.org/moin/BeginnersGuide/Programmers

Kent

From kent37 at tds.net  Thu Sep  1 17:12:51 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 01 Sep 2005 11:12:51 -0400
Subject: [Tutor] [Fwd: PyChecker lives, version 0.8.15 released]
Message-ID: <43171A73.9060302@tds.net>

Forwarding this to the tutor list because we had a bit of discussion about PyChecker recently. In particular this release fixes spurious warnings in Python 2.4 for Using is (not) None.

Kent


-------- Original Message --------
Subject: PyChecker lives, version 0.8.15 released
Date: Wed, 31 Aug 2005 22:08:05 -0700
From: Neal Norwitz <nnorwitz at gmail.com>
To: python-list at python.org, python-announce at python.org
Newsgroups: comp.lang.python

Special thanks to Ken Pronovici.  He did a lot of work for this
release and helped ensure it occurred.

Version 0.8.15 of PyChecker is available.  It's been over a year since
the last release.  Wow, time really does fly.  Since it's been so long
I'm sure I screwed something up, treat it delicately.  It may have bugs
and erase your hard drive.  If that happens, look on the bright side, 
you won't have any more bugs. :-)

        PyChecker is a tool for finding bugs in Python source code.
        It finds problems that are typically caught by a compiler for less
        dynamic languages, like C and C++.  It is similar to lint.

Comments, criticisms, new ideas, and other feedback is welcome.

Since I expect there may be a bit more bugs than normal, I will try to
put out another release in a few weeks.  Please file bug reports
including problems with installation, false positives, &c on Source Forge.
You are welcome to use the mailling list to discuss anything pychecker 
related, including ideas for new checks.

Changes from 0.8.14 to 0.8.15:

  * Fix spurious warning about catching string exceptions
  * Don't barf if there is # -*- encoding: ... -*- lines and unicode strings
  * setup.py was rewritten to honor --root, --home, etc options
  * Fix internal error on processing nested scopes
  * Fix constant tuples in Python 2.4
  * Don't warn about implicit/explicit returns in Python 2.4, we can't tell
  * Fix crash when __slots__ was an instance w/o __len__
  * Fix bug that declared {}.pop to only take one argument, it takes 1 or 2
  * Fix spurious warning when using tuples for exceptions
  * Fix spurious warning <stack> / <stack> 
  * Fix spurious warnings for sets module about __cmp__, __hash__
  * Changed abstract check to require raising NotImplementedError
    rather than raising any error
  * Fix spurious warnings in Python 2.4 for Using is (not) None warnings
  * Fix spurious warnings for some instances of No class attribute found
  * Fix spurious warnings for implicit returns when using nested functions

PyChecker is available on Source Forge:
    Web page:           http://pychecker.sourceforge.net/
    Project page:       http://sourceforge.net/projects/pychecker/
    Mailing List:       pychecker-list at lists.sourceforge.net

Neal
--
pychecker-list at lists.sourceforge.net

From falcon3166 at hotmail.com  Thu Sep  1 20:22:07 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Thu, 1 Sep 2005 12:22:07 -0600
Subject: [Tutor] How to save updated values in a program?
Message-ID: <BAY106-DAV176695266D003B07BD7292C4A00@phx.gbl>

Hey all,

How do I save updated values in a program when it quits? Are the new values automatically saved, or do I have to code it in to the program in order to save the updated values?

I need to know because I have a currency exchange program that is updated manually by the user, and I want to know if every time I exit, the next time I enter the program I have to rechange the values.

Thanks,
Nathan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050901/e333c8f9/attachment.html

From dyoo at hkn.eecs.berkeley.edu  Thu Sep  1 21:15:42 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 1 Sep 2005 12:15:42 -0700 (PDT)
Subject: [Tutor] How to save updated values in a program?
In-Reply-To: <BAY106-DAV176695266D003B07BD7292C4A00@phx.gbl>
Message-ID: <Pine.LNX.4.44.0509011207350.19920-100000@hkn.eecs.berkeley.edu>



On Thu, 1 Sep 2005, Nathan Pinno wrote:

> How do I save updated values in a program when it quits? Are the new
> values automatically saved, or do I have to code it in to the program in
> order to save the updated values?

Hi Nathan,

We'll have to do something explicit to save them.

In the past, some computer systems had a notion of saving the "image" of
the whole working environment.  From what I understand, the Smalltalk
language did something like this.  By having a notion of saving this
environmental "image", these systems made it very easy to restore the
state of the system.  We just restore the environment image, and all our
variables came back to life.

But, on the flip side, it made it very difficult to distribute programs to
other people: it became difficult to disentangle the parts of the
environment that dealt with the program from the rest of the system.

So for the most part, the rest of the computing industry went the other
direction, toward not saving anything unless explicitely saved it in files
or databases.  And that's the state of things in Python.


Take a look at the 'shelve' module:

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

It's a module that provides a dictionary-like object: that dictionary
object is actually tied to disk, so anything that goes into the dictionary
gets saved.  Try it out, and if you have questions with it, please feel
free to bring it up onto the list.

Good luck!


From frank.l.lane at boeing.com  Thu Sep  1 21:20:19 2005
From: frank.l.lane at boeing.com (Lane, Frank L)
Date: Thu, 1 Sep 2005 14:20:19 -0500
Subject: [Tutor] doh!
Message-ID: <C3871B74409A854EA9B6F4EEB92088070110FB56@XCH-SE-1V2.se.nos.boeing.com>

Hi,

 

My threading question was not valid, and I have to apologize for it. My
screw up was to put the open and close parentheses after my procedure
name in the invocation (i.e. i wrote
threading.Thread(target=modname.funcname(),name=name)).

 

I also learned that even if the tabs and spaces line up in the editor
they don't count the same and give you a syntax error.

 

Please excuse my error.

 

Thanks,

Frank

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

From alan.gauld at freenet.co.uk  Thu Sep  1 22:59:14 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Thu, 1 Sep 2005 21:59:14 +0100
Subject: [Tutor] Need directions toward programming...
References: <1eac597d0508311918303fca42@mail.gmail.com>
Message-ID: <007c01c5af38$03452660$0201a8c0@xp>

Hi Damian,

> studies about programming sucks!.

This seems to be a common problem, maybe because many teachers aren't
really trainied in how to teach programming and only know the basics
themselves! Its usually a bit better at university level.

> language a teacher show us was quick basic

QuickBasic isn't too bad to start with but only for a short spell.
But learning about line numbers and GoTo etc can be seen as good
historical background. One local univesity teaches students by
starting with machine code (ot assembler!) and then moves on
through Assembler to Basic then Pascal and C and eventually to
Java (used to be C++) and then finishes off with Haskelol and Prolog.

In other words they try to take the students through the historical
development of programming over a 3 year period.

> the project itself contained a lot of bugs, and the teacher didn't 
> take that
> in consideration for the grades, I was pissed off !,

Thats bad!

> getting in an University, I decide to study by myself,

Unfortunately that could be seriously career limiting. Most big
computer companies still expect at least a bachelors degree (and
many insist on a Masters) before they hire you. Smaller companies
will take on with less formal wqualifications but you will always
be bucking the system and some jobs will be forever shut off.

Add to that the fact that you will be unlikely to self study the
mathematical foundatons needed to really undertstand copmputing
theory - Predicate and Lambda Calculus, Queuing theory, Simulation,
Type theory, etc etc.

> the most of my time learning dynamic languages instead of
> the proprietary ones.

There are plenty of proprietary dynamic languages and a few non
dynamic public ones. Dynamic usually refers to those which are
interpreted rather than compiled, or at least havce a dynamic type 
system.

> can recommend me some books or tutorials of python

There are lots of sites with recommendations on that.

> toward the technical aspect of programming

Try the following:

Code Complete - McConnell

Programming Pearls - Jon Bentley

The Pragmatic Programmer - Hunt, Thomas

Structure and Interpretation of Computer Programs
(available online!) - Abelman, Sussman

How to Design Programs - ???
(also online)

Art of Computer Programming - Knuth

> (multiple inheritance, control flow, etc.), so I can get an idea of 
> the
> whole aspect of language programming.

Take time to explote other languages, Ruby, Smalltalk, Haskell and 
Lisp
are all good alternative world-views.

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


From john at fouhy.net  Fri Sep  2 00:46:29 2005
From: john at fouhy.net (John Fouhy)
Date: Fri, 2 Sep 2005 10:46:29 +1200
Subject: [Tutor] doh!
In-Reply-To: <C3871B74409A854EA9B6F4EEB92088070110FB56@XCH-SE-1V2.se.nos.boeing.com>
References: <C3871B74409A854EA9B6F4EEB92088070110FB56@XCH-SE-1V2.se.nos.boeing.com>
Message-ID: <5e58f2e405090115466009be89@mail.gmail.com>

On 02/09/05, Lane, Frank L <frank.l.lane at boeing.com> wrote:
> I also learned that even if the tabs and spaces line up in the editor they
> don't count the same and give you a syntax error. 

Hi Frank,

What editor are you using?  And does it have a proportional or a
monospaced font?

-- 
John.

From tegmine at gmail.com  Fri Sep  2 04:03:03 2005
From: tegmine at gmail.com (Luis N)
Date: Thu, 1 Sep 2005 19:03:03 -0700
Subject: [Tutor] Python2.3.4, PySqlite2 and Solaris
Message-ID: <77bfa81a0509011903180b89d6@mail.gmail.com>

Hi,

After fighting with installing pysqlite2, (although you require the
.tar.gz for a *Nix build, the header file required, sqlite3.h, was
actually in the source .zip supplied for windows users sans a unix
build environment)

Anyway, I have pysqlite2, but:

Python 2.3.4 (#1, Aug 23 2004, 13:59:34)
[GCC 3.2.3] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> from pysqlite2 import dbapi2 as sqlite
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/home/rbnewby/lib/python/pysqlite2/dbapi2.py", line 32, in ?
    from pysqlite2._sqlite import *
ImportError: ld.so.1: python: fatal: relocation error: file
/home/NaN/lib/python/pysqlite2/_sqlite.so: symbol sqlite3_libversion:
referenced symbol not found

However,

bash-2.05$ ldd -s _sqlite.so

   find object=libsqlite.so.0; required by ./_sqlite.so
    search path=/usr/openwin/lib  (LD_LIBRARY_PATH)
    trying path=/usr/openwin/lib/libsqlite.so.0
    search path=/home/NaN/lib  (RPATH from file ./_sqlite.so)
    trying path=/home/NaN/lib/libsqlite.so.0
        libsqlite.so.0 =>        /home/NaN/lib/libsqlite.so.0

I'm a little confused why a python process wouldn't also be able to
find the required library.

Any insights about what's happening would be appreciated.

Luis

From JAnema2 at mts.net  Fri Sep  2 07:13:30 2005
From: JAnema2 at mts.net (Jack Anema)
Date: Fri, 2 Sep 2005 00:13:30 -0500
Subject: [Tutor] Test to see if this gets out
Message-ID: <004301c5af7d$0f0e10c0$6501a8c0@acerd3e20d0d7f>

TEST

Jack Anema
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050902/d0163369/attachment.htm

From JAnema2 at mts.net  Fri Sep  2 07:16:23 2005
From: JAnema2 at mts.net (Jack Anema)
Date: Fri, 2 Sep 2005 00:16:23 -0500
Subject: [Tutor] TEST  to see if this gets out
Message-ID: <005101c5af7d$75e1c3f0$6501a8c0@acerd3e20d0d7f>

TEST

Jack Anema
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050902/c77104f2/attachment.html

From lists at janeden.org  Fri Sep  2 09:13:04 2005
From: lists at janeden.org (Jan Eden)
Date: Fri,  2 Sep 2005 09:13:04 +0200
Subject: [Tutor] datetime.date objects from SQL query?
In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC0226A687@chbnt01.alpha.wd.govt.nz>
Message-ID: <r02010500-1039-01A6A01A1B8111DA950A000A959B4026@[10.149.23.208]>

Hi Liam,

Liam Clarke-Hutchinson wrote on 02.09.2005:

>Hi Jan,
>
>Are you using pysqlite? If so, then let me quote from the pysqlite
>docs -
>
>"pysqlite has default adapters for the date and datetime types in
>the datetime module. They will be sent as ISO dates/ISO timestamps
>to SQLite."
>
>
>Personally, I think pysqlite is a rocking DBAPI, and I applaud
>Gerhard H?ring for such a useful project.
>
>Regards,
>
>Liam Clarke
>
>(If you're not using pysqlite, it'll be a similar case of the DB's
>types being mapped to Python types.)

I actually use MySQLdb, and you're right: It seems to use the datetime module to handle values of date columns. I am still amazed about the nice features of MySQLdb and my unability to learn about them from pydoc MySQLdb.

Thanks,

Jan
-- 
Life's unfair - but root password helps!

From dyoo at hkn.eecs.berkeley.edu  Fri Sep  2 09:59:29 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 2 Sep 2005 00:59:29 -0700 (PDT)
Subject: [Tutor] TEST  to see if this gets out
In-Reply-To: <005101c5af7d$75e1c3f0$6501a8c0@acerd3e20d0d7f>
Message-ID: <Pine.LNX.4.44.0509020057370.20104-100000@hkn.eecs.berkeley.edu>



On Fri, 2 Sep 2005, Jack Anema wrote:

> TEST


Hi Jack,

We're here.  Do you have a question about learning Python?


From tegmine at gmail.com  Fri Sep  2 10:00:05 2005
From: tegmine at gmail.com (Luis N)
Date: Fri, 2 Sep 2005 01:00:05 -0700
Subject: [Tutor] Python2.3.4, PySqlite2 and Solaris
In-Reply-To: <77bfa81a0509011903180b89d6@mail.gmail.com>
References: <77bfa81a0509011903180b89d6@mail.gmail.com>
Message-ID: <77bfa81a05090201005ab0b63e@mail.gmail.com>

On 9/1/05, Luis N <tegmine at gmail.com> wrote:
> Hi,
> 
> After fighting with installing pysqlite2

Apologizes, I started over. It went much better the second time.

bash-2.05$ test-pysqlite
..............................................................................................................................................
----------------------------------------------------------------------
Ran 142 tests in 0.672s

> 
> Luis
>

From dyoo at hkn.eecs.berkeley.edu  Fri Sep  2 10:07:18 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 2 Sep 2005 01:07:18 -0700 (PDT)
Subject: [Tutor] Python2.3.4, PySqlite2 and Solaris
In-Reply-To: <77bfa81a0509011903180b89d6@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509020059310.20104-100000@hkn.eecs.berkeley.edu>



> Python 2.3.4 (#1, Aug 23 2004, 13:59:34)
> [GCC 3.2.3] on sunos5
> Type "help", "copyright", "credits" or "license" for more information.
> >>> from pysqlite2 import dbapi2 as sqlite
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "/home/rbnewby/lib/python/pysqlite2/dbapi2.py", line 32, in ?
>     from pysqlite2._sqlite import *
> ImportError: ld.so.1: python: fatal: relocation error: file
> /home/NaN/lib/python/pysqlite2/_sqlite.so: symbol sqlite3_libversion:
> referenced symbol not found

Hi Luis,

This means that Python can physically find a 'sqlite' library, but that
what it had found does not appear to be compatible with the version that
the pysqlite module expects.  Is it possible that you have an older
version of sqlite?

You may also want to send your question to the pysqlite mailing list.  We
on Python-Tutor probably aren't that familiar with pysqlite installation.
You may be able to get better help from the pysqlite folks:

    http://lists.initd.org/mailman/listinfo/pysqlite


From thp at ttpcom.com  Fri Sep  2 11:45:11 2005
From: thp at ttpcom.com (Tom Playford)
Date: Fri, 02 Sep 2005 10:45:11 +0100
Subject: [Tutor] Batch file to detect if Python is installed
Message-ID: <43181F27.1010608@ttpcom.com>

Dear Omniscient List,

Does anyone know of a cunning method to detect whether Python is
installed using a batch file?

I'd like a batch file to execute an .exe if Python IS NOT installed, and
execute a .py if Python IS installed.

This is my first foray into the disturbing world of windows batch files,
and I don't like it very much.


Thanks in advance,

Tom


P.S. I do realise this is a little off topic... It does involve Python
and programming... just not programming in Python.


From Goofball223 at wmconnect.com  Fri Sep  2 15:48:43 2005
From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com)
Date: Fri, 2 Sep 2005 09:48:43 EDT
Subject: [Tutor] FIREWALLS
Message-ID: <1b9.1af0d866.3049b23b@wmconnect.com>



I used python several months ago to write a simple program now i went back to 
use it to rewrite the same program and when I try to run it it says that my 
firewalls may be to secure. everytime the program runs in python it restarts 
and just has empty lines. how do I change my firewalls to be able to run a 
program in python? I have tried using different versions of python
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050902/a7245d3b/attachment.htm

From python at patm.net  Fri Sep  2 17:36:03 2005
From: python at patm.net (Pat Martin)
Date: Fri, 02 Sep 2005 08:36:03 -0700
Subject: [Tutor] Directory permission and ACLs
Message-ID: <43187163.8030503@patm.net>

I am new to python and wanted to write a program that looks at directory 
permissions and ext3 ACLs and also change them if needed. What modules 
would I be looking at for those functions?

Thank you.
Pat

From servando at mac.com  Fri Sep  2 18:27:43 2005
From: servando at mac.com (Servando Garcia)
Date: Fri, 2 Sep 2005 11:27:43 -0500
Subject: [Tutor] convert binary to ascii
Message-ID: <24f8a3f28521e002caadd84b322ac548@mac.com>

Hello
	List it has been a long time.
Here is my question : sam in binary is  01110011  01100001  01101101.   
   if given 01110011  01100001  01101101  how would I go back to ascii.
  I guess am asking is there a module that will do this conversion for 
me. I have looked at binascii but have been up able to found a good 
example to work from.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: text/enriched
Size: 540 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050902/c2cf1b62/attachment.bin

From jsmith at medplus.com  Fri Sep  2 19:03:05 2005
From: jsmith at medplus.com (Smith, Jeff)
Date: Fri, 2 Sep 2005 13:03:05 -0400
Subject: [Tutor] Problem building Python on HP-UX
Message-ID: <3B05FA2AD704244BB0CAB99D8026F5551A29BE@medexch2.medplus.com>

I'm trying to build Python 2.4.1 on HP-UX 11.00 with full tcl/tk IDLE
support.  So far, I haven't had any luck.  I always wind up getting
errors of the form:

ld: DP relative code in file
/ptg/devtools/hppa1.1/pre/lib/libtk8.4.a(tkWindow.o) - shared library
must be position independent.  Use +z or +Z to recompile.

I have tried building tcl/tk without any configure options as well as
with --disable-shared and --disable-load but this doesn't help.

Anyone seen anything like this or know how to get around it?

Jeff

From travislspencer at gmail.com  Fri Sep  2 19:34:05 2005
From: travislspencer at gmail.com (Travis Spencer)
Date: Fri, 2 Sep 2005 10:34:05 -0700
Subject: [Tutor] Directory permission and ACLs
In-Reply-To: <43187163.8030503@patm.net>
References: <43187163.8030503@patm.net>
Message-ID: <e3b7bac0509021034354ccf69@mail.gmail.com>

On 9/2/05, Pat Martin <python at patm.net> wrote:
> I am new to python and wanted to write a program that looks at directory
> permissions and ext3 ACLs and also change them if needed. What modules
> would I be looking at for those functions?

os and os.path:

* http://docs.python.org/lib/module-os.html
* http://docs.python.org/lib/module-os.path.html

stat and shutil might be useful too.

HTH.

-- 

Regards,

Travis Spencer

From Goofball223 at wmconnect.com  Fri Sep  2 15:44:45 2005
From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com)
Date: Fri, 2 Sep 2005 09:44:45 EDT
Subject: [Tutor] FIREWALLS
Message-ID: <30.79f4f261.3049b14d@wmconnect.com>

I used python several months ago to write a simple program now i went back to 
use it to rewrite the same program and when I try to run it it says that my 
firewalls may be to secure. everytime the program runs in python it restarts 
and just has empty lines. how do I change my firewalls to be able to run a 
program in python? I have tried using different versions of python
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050902/1637c826/attachment.html

From dyoo at hkn.eecs.berkeley.edu  Fri Sep  2 19:48:28 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 2 Sep 2005 10:48:28 -0700 (PDT)
Subject: [Tutor] convert binary to ascii
In-Reply-To: <24f8a3f28521e002caadd84b322ac548@mac.com>
Message-ID: <Pine.LNX.4.44.0509021042410.9311-100000@hkn.eecs.berkeley.edu>



On Fri, 2 Sep 2005, Servando Garcia wrote:

> Here is my question : sam in binary is  01110011  01100001  01101101.
>    if given 01110011  01100001  01101101  how would I go back to ascii.


Hi Servando:

If we have strings of ones and zeros, we can turn those into numbers by
using the int() function.  For example:

######
>>> int("101", 2)
5
>>> int("110", 2)
6
>>> int("111", 2)
7
######

For more information on int(), see:

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


There is also a function to convert ordinals back into their ascii
character values.  Take a look at:

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

and search for the word "ASCII": you should see a function there that will
help.


From travislspencer at gmail.com  Fri Sep  2 20:09:07 2005
From: travislspencer at gmail.com (Travis Spencer)
Date: Fri, 2 Sep 2005 11:09:07 -0700
Subject: [Tutor] convert binary to ascii
In-Reply-To: <24f8a3f28521e002caadd84b322ac548@mac.com>
References: <24f8a3f28521e002caadd84b322ac548@mac.com>
Message-ID: <e3b7bac0509021109582317a5@mail.gmail.com>

On 9/2/05, Servando Garcia <servando at mac.com> wrote:
> Hello

Hey Servando,

> Here is my question : sam in binary is  01110011  01100001  01101101.
>    if given 01110011  01100001  01101101  how would I go back to ascii.
>   I guess am asking is there a module that will do this conversion for
> me. 

I don't know about module, but it isn't hard to do it yourself.  Here
is one way:

#!/bin/env python

import sys

for line in sys.stdin:
    result = ""

    for binaryStr in line.split():
        j = len(binaryStr) - 1
        i = charCodeOfBinaryStr = 0

        while j > 0:
            charCodeOfBinaryStr += int(binaryStr[j]) * 2 ** i
            j -= 1
            i += 1

        result += chr(charCodeOfBinaryStr)

    print result

Here is the output of your binary string:

$ python btoa.py <<< "01110011  01100001  01101101"
sam

Its a really common algorithm.  Google for "change of base algorithm"
and you'll probably find lots of explinations.

HTH.

-- 

Regards,

Travis Spencer

From alan.gauld at freenet.co.uk  Fri Sep  2 20:13:09 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Fri, 2 Sep 2005 19:13:09 +0100
Subject: [Tutor] Batch file to detect if Python is installed
References: <43181F27.1010608@ttpcom.com>
Message-ID: <00c301c5afe9$f9e98a40$0201a8c0@xp>

> Does anyone know of a cunning method to detect whether Python is
> installed using a batch file?

Search the registry using the reg command:


------------------ DOS session -------------
C:\WINDOWS>reg query "hkcu\software\Pytho"

Error:  The system was unable to find the specified registry key or 
value

C:\WINDOWS>reg query "hkcu\software\Python"

! REG.EXE VERSION 3.0

HKEY_CURRENT_USER\software\Python

C:\WINDOWS>

---------------------------------------------

Next question - How to detect that you got a result other than an 
error?

Use ERRORLEVEL

ERRORLEVEL will return 0 if the last command had no errors
or an error number otherwise.

Thus something like:

@ECHO OFF
reg query "hkcu\software\Python"
if ERRORLEVEL 1 GOTO NOPYTHON
python myscrip.py
...
GOTO :EOF
:NOPYTHON
REM use dos commands here


> P.S. I do realise this is a little off topic... It does involve 
> Python
> and programming... just not programming in Python.

Seems relevant to me... BUT if you can be sure Windows Host Scripting 
is
installed ands active that is much much easier to use...

Alan G.


From travislspencer at gmail.com  Fri Sep  2 20:14:11 2005
From: travislspencer at gmail.com (Travis Spencer)
Date: Fri, 2 Sep 2005 11:14:11 -0700
Subject: [Tutor] convert binary to ascii
In-Reply-To: <Pine.LNX.4.44.0509021042410.9311-100000@hkn.eecs.berkeley.edu>
References: <24f8a3f28521e002caadd84b322ac548@mac.com>
	<Pine.LNX.4.44.0509021042410.9311-100000@hkn.eecs.berkeley.edu>
Message-ID: <e3b7bac05090211144312ccb1@mail.gmail.com>

On 9/2/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:

Hey Danny,

> If we have strings of ones and zeros, we can turn those into numbers by
> using the int() function.  For example:
> 
> ######
> >>> int("101", 2)
> 5
> >>> int("110", 2)
> 6
> >>> int("111", 2)
> 7

Oh, that's nice.  I guess my solution was the total C hacker's way;
not very pythonic :-)  Thanks for the info.

-- 

Regards,

Travis Spencer

From me at scottoertel.info  Fri Sep  2 21:08:43 2005
From: me at scottoertel.info (Scott Oertel)
Date: Fri, 02 Sep 2005 12:08:43 -0700
Subject: [Tutor] mod_python.publisher
Message-ID: <4318A33B.6080808@scottoertel.info>

I'm having an issue with mod_python.publisher,

supposedly i should be able to just place this code

def index():
   return "This is only a test."

into test.py and when placed into my browser it should run the index 
function by default, but instead i get a 404 error.

i'm running Apache/1.3.33 (Unix) mod_python/2.7.11 Python/2.2.3



-Scott Oertel

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

From alan.gauld at freenet.co.uk  Fri Sep  2 21:18:13 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Fri, 2 Sep 2005 20:18:13 +0100
Subject: [Tutor] FIREWALLS
References: <30.79f4f261.3049b14d@wmconnect.com>
Message-ID: <010a01c5aff3$10c11450$0201a8c0@xp>


>I used python several months ago to write a simple program now i went 
>back to
> use it to rewrite the same program and when I try to run it it says 
> that my
> firewalls may be too secure.

Are you using IDLE? THe latest versions of IDLE issue a warning of 
this type.

What happens if you just run your program from the OS commamd line?

> and just has empty lines. how do I change my firewalls to be able to 
> run a
> program in python? I have tried using different versions of python

If its not in IDLE then it will depend on what your program is doing.

Can you post the error message? And if its not too long the code too?

It saves us from guessing... :-)

Alan G. 


From python at jayloden.com  Fri Sep  2 21:33:02 2005
From: python at jayloden.com (Jay Loden)
Date: Fri, 2 Sep 2005 15:33:02 -0400
Subject: [Tutor] Invoking bash from within a python program
In-Reply-To: <42FF1DE5.8030807@dsl.pipex.com>
References: <Pine.LNX.4.44.0508131258130.29852-100000@hkn.eecs.berkeley.edu>
	<42FF1DE5.8030807@dsl.pipex.com>
Message-ID: <200509021533.02550.python@jayloden.com>

Watch yourself on this one, slocate can often return some unexpected results 
for file searches, and the last thing you want to do is delete something 
important while trying to remove the latest game you installed. 

Also, if you're installing from source you can often run "make uninstall" to 
remove the installed files. 

And finally, the Vinay's suggestion of a simple one liner shell script is much 
simpler and probably as fast or faster than anything you come up with in 
Python.

Just figured I'd lend some words of warning to you as someone who's made 
similar mistakes in the past ;)

-Jay

On Sunday 14 August 2005 6:33 am, joe_schmoe wrote:
> The basic idea I was toying around with is to create a delete/uninstall
> program that would take the output of slocate and iterate through that
> deleting all of the files associated with the program

From me at scottoertel.info  Fri Sep  2 21:59:33 2005
From: me at scottoertel.info (Scott Oertel)
Date: Fri, 02 Sep 2005 12:59:33 -0700
Subject: [Tutor] mod_python.publisher
In-Reply-To: <4318A33B.6080808@scottoertel.info>
References: <4318A33B.6080808@scottoertel.info>
Message-ID: <4318AF25.9020007@scottoertel.info>

Scott Oertel wrote:

> I'm having an issue with mod_python.publisher,
>
> supposedly i should be able to just place this code
>
> def index():
>    return "This is only a test."
>
> into test.py and when placed into my browser it should run the index 
> function by default, but instead i get a 404 error.
>
> i'm running Apache/1.3.33 (Unix) mod_python/2.7.11 Python/2.2.3
>
>
>
> -Scott Oertel
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>
Just for fun i decided to upgrade the python version to 2.4.1

Apache/1.3.33 (Unix) mod_python/2.7.11 Python/2.4.1 mod_gzip/1.3.26.1a 
mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 
FrontPage/5.0.2.2635 mod_ssl/2.8.22 OpenSSL/0.9.7a PHP-CGI/0.1b

still no luck   =(
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050902/372f5b86/attachment.htm

From dyoo at hkn.eecs.berkeley.edu  Sat Sep  3 00:07:55 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 2 Sep 2005 15:07:55 -0700 (PDT)
Subject: [Tutor] mod_python.publisher
In-Reply-To: <4318AF25.9020007@scottoertel.info>
Message-ID: <Pine.LNX.4.44.0509021456340.4854-100000@hkn.eecs.berkeley.edu>



On Fri, 2 Sep 2005, Scott Oertel wrote:

> Scott Oertel wrote:
>
> > I'm having an issue with mod_python.publisher,
> >
> > supposedly i should be able to just place this code
> >
> > def index():
> >    return "This is only a test."
> >
> > into test.py and when placed into my browser it should run the index
> > function by default, but instead i get a 404 error.

Hi Scott,

The question you're asking is pretty specific to mod_python; you may get
better help by asking the mod_python mailing list.

    http://mailman.modpython.org/mailman/listinfo/mod_python

We on Tutor don't have special expertise on mod_python, and you may be
better served by asking the mod_python folks for help.


Anyway, take a closer look at:

    http://www.modpython.org/live/current/doc-html/hand-pub-alg-trav.html

Their example functions all take a request object.  Are you sure you don't
need to include the request as an argument of the default index handler?


From keridee at jayco.net  Thu Sep  1 01:59:36 2005
From: keridee at jayco.net (Jacob S.)
Date: Wed, 31 Aug 2005 18:59:36 -0500
Subject: [Tutor] Sort a Set
References: <430B23BD.8000409@SoftHome.net>
Message-ID: <06b401c5b00d$0d176e70$255428cf@JSLAPTOP>

How about this?  Not only does it count each element, but you can also get a 
sorted set without using set!

a = [24,24,24,16,16,15,15]
b = {}
for i in a:
    try: b[i] += 1
    except KeyError: b[i] = 1
print b
li = b.keys()
print li
li.sort()
print li
li.reverse()
print li

has output

{24: 3, 16: 4, 15: 2}
[24, 16, 15]
[15, 16, 24]
[24, 16, 15]

Respectfully,
Jacob Schmidt

----- Original Message ----- 
From: "Jonas Melian" <jonasmg at softhome.net>
To: <tutor at python.org>
Sent: Tuesday, August 23, 2005 8:25 AM
Subject: [Tutor] Sort a Set


>I get a list of repeated numbers  [24, 24, 24, 16, 16, 15, 15 ]
> Is possible get it without repeated numbers, without using set()?
>
> If I use set, then the list is unsorted and i cann't sorting it.
>
> For get the values i use:
>
> [x[0] for x in cardTmp]
>
> or:
>
> from itertools import imap
> for i in imap(lambda x: x[0], cardTmp): print i
>
> A idea it would be create a generator that will return elements one by
> one, and then it would be possible know if that element is in the new
> list. But generators are in 2.4
>
>
> Python 2.3.5
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From keridee at jayco.net  Thu Sep  1 02:20:00 2005
From: keridee at jayco.net (Jacob S.)
Date: Wed, 31 Aug 2005 19:20:00 -0500
Subject: [Tutor] Counting help
References: <430B645D.4050505@scottoertel.info>
Message-ID: <06b501c5b00d$0e4c1de0$255428cf@JSLAPTOP>

I'll do this again, just because I like sending email.

Very similar to Alan G.'s -- but with the do first, ask forgiveness later

a = ["Joe Smith", "Joe Smith", "Jack Smith", "Sam Love", "Joe Smith"]
b = {}
for x in a:
    try: b[x] += 1
    except KeyError: b[x] = 1

Access count like this, of course,

>>> b["Joe Smith"]
3
>>>

Jacob Schmidt

----- Original Message ----- 
From: "Scott Oertel" <me at scottoertel.info>
To: <Tutor at python.org>
Sent: Tuesday, August 23, 2005 1:01 PM
Subject: [Tutor] Counting help


>I have extracted a list of names, i.e.
> 
> "Joe Smith"
> "Joe Smith"
> "Jack Smith"
> "Sam Love"
> "Joe Smith"
> 
> I need to be able to count the occurances of these names and I really 
> don't have any idea where to begin.
> 
> Any ideas?  excuse me this is my first post to this list, I hope I 
> included enough information.
> 
> 
> -Scott Oertel
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From carroll at tjc.com  Sat Sep  3 00:55:41 2005
From: carroll at tjc.com (Terry Carroll)
Date: Fri, 2 Sep 2005 15:55:41 -0700 (PDT)
Subject: [Tutor] re.findall(), but with overlaps?
Message-ID: <Pine.LNX.4.44.0509021548040.30307-100000@violet.rahul.net>


A friend of mine got bitten by an expectations bug.  he was using 
re.findall to look for all occurances of strings matching a pattern, and a 
substring he *knew* was in there did not pop out.

the bug was that it overlapped another matching substring, and findall 
only returns non-overlapping strings.  This is documented; he just missed 
it.

But he asked me, is there a standard method to get even overlapped
strings?

Cut to its basics, here's an artificial example:

>>> import re
>>> rexp=re.compile("B.B")
>>> sequence="BABBEBIB"
>>> rexp.findall(sequence)
['BAB', 'BEB']

What he would have wanted was  the list ['BAB', 'BEB', 'BIB']; but since 
the last 'B' in "BEB" is also the firt 'B' in "BIB", "BIB" is not picked 
up.

After looking through the docs, I couldn't find a way to do this in 
standard methods, so I gave him a quick RYO solution:

>>> def myfindall(regex, seq):
...    resultlist=[]
...    pos=0
...
...    while True:
...       result = regex.search(seq, pos)
...       if result is None:
...          break
...       resultlist.append(seq[result.start():result.end()])
...       pos = result.start()+1
...    return resultlist
...
>>> myfindall(rexp,sequence)
['BAB', 'BEB', 'BIB']

But just curious; are we reinventing the wheel here?  Is there already a 
way to match even overlapping substrings?  I'm surprised I can't find one.


From keridee at jayco.net  Sat Sep  3 02:27:29 2005
From: keridee at jayco.net (Jacob S.)
Date: Fri, 2 Sep 2005 19:27:29 -0500
Subject: [Tutor] Generate 8 digit random number
References: <BAY106-F19AD43D39922BCF850E56289AD0@phx.gbl>
Message-ID: <098701c5b01e$4e1a6fb0$255428cf@JSLAPTOP>

> Hey Tutors
>
> I saw a lot of responses...After analyze them I have resumed two 
> approaches
>
> 1.- Generate a random number from 0 to 99999999 and fill this number with
> zeros (Almost everyone's approach)
> 2.- Generate 8 random numbers and join them (Pietro and someone else)
>
> Which one of this is more randomic? I mean which one of these has lower
> chances to get duplicates?
> Until now I'm using approach number 2.......Unless anyone has something
> against it...

Frankly,
    I would probably prefer #1 because it's probably faster. (You're just 
generating one number, and calling 1or 2 functions on it as opposed to at 
least 1 random and 1 function for each digit)

Secondly, in both cases, there is the chance that you will get duplicates~~
So the best way to do that is save passwords already generated in a list.

######  Try this #######

import random
import cPickle  ## This is to save passwords already generated between 
program runs.

def getlist():
    try:
        fileobj = file("passwords.lst","r")
        returnlist = cPickle.load(fileobj)
        fileobj.close()
    except IOError:
        returnlist = []
    return returnlist

def generate():
    return str(random.randrange(0,99999999)).zfill(8)  ## Not that this is 
the best, but it is concise

def close(li):
    obj = file("passwords.lst","w")
    cPickle.dump(li,obj)
    obj.close()


masterlist = getlist()

num = 0
while 1:
    while num in masterlist:
        num = generate()
    masterlist.append(num)
    print num
    m = raw_input()
    if m == 'quit':
        close(masterlist)
        break
######################

Okay, I believe it will work, I haven't tested it though. Any problems, 
grouch at me, please.

Respectfully,
Jacob 


From tlinux at comcast.net  Sat Sep  3 04:14:30 2005
From: tlinux at comcast.net (Tom Strickland)
Date: Fri, 02 Sep 2005 21:14:30 -0500
Subject: [Tutor] Print Output Location in Windows XP
Message-ID: <43190706.8030500@comcast.net>

Up until now I have been running my Python programs in Linux. I just 
wrote one in Windows XP and I can't find the print output. The Python 
program has a print statement, and when I run the program a black window 
opens and I can see printing going on. However, when it's finished 
printing, the output window closes.

How do I get the output window to stay open, or where is the output stored?

Thanks!

Tom Strickland


From daniel at thewatkins.org.uk  Sat Sep  3 05:22:06 2005
From: daniel at thewatkins.org.uk (Daniel Watkins)
Date: Sat, 03 Sep 2005 04:22:06 +0100
Subject: [Tutor] Print Output Location in Windows XP
In-Reply-To: <9AA4216B8A36B9429BB00C546DF6D27201B4F3@schubert.OxbridgeTechnology.local>
References: <9AA4216B8A36B9429BB00C546DF6D27201B4F3@schubert.OxbridgeTechnology.local>
Message-ID: <1125717726.4023.4.camel@amdbert.oxbridgetechnology.local>

On Sat, 2005-09-03 at 03:30 +0100, Tom Strickland wrote:
> 
> How do I get the output window to stay open, or where is the output
> stored?

You can open up a command prompt before running the program, which will
allow you to see the output as the program runs. You get to this by
'Start > Run..' or something similar. As you're using XP, you then type
in 'cmd' which should bring up a command line. Navigate your way to the
appropriate place and run the program.

Alternatively, you could dump the output into a text file, but I have no
idea how to do that in Windows so someone else'll have to pick that up
for you.

Hope that helps,
Dan


From geon at post.cz  Sat Sep  3 05:39:41 2005
From: geon at post.cz (geon)
Date: Sat, 03 Sep 2005 05:39:41 +0200
Subject: [Tutor] Print Output Location in Windows XP
In-Reply-To: <43190706.8030500@comcast.net>
References: <43190706.8030500@comcast.net>
Message-ID: <43191AFD.2070801@post.cz>

Tom Strickland napsal(a):

>Up until now I have been running my Python programs in Linux. I just 
>wrote one in Windows XP and I can't find the print output. The Python 
>program has a print statement, and when I run the program a black window 
>opens and I can see printing going on. However, when it's finished 
>printing, the output window closes.
>
>How do I get the output window to stay open, or where is the output stored?
>
>  
>
You could:

* put raw_input() statement on the last line in your program
* run python with "-i" argument . i means "stay interactive after run". 
example : python -i myfile.py

Hope this helps

-- 
geon



From mosinu at earthlink.net  Sat Sep  3 05:43:46 2005
From: mosinu at earthlink.net (Will Harris)
Date: Fri, 02 Sep 2005 23:43:46 -0400
Subject: [Tutor] Print Output Location in Windows XP
In-Reply-To: <43190706.8030500@comcast.net>
References: <43190706.8030500@comcast.net>
Message-ID: <43191BF2.5030205@earthlink.net>

Something I do is like

raw_input("\n\nPress enter to exit.")

at the end, this works if all you want to do is see the text on the screen.

Tom Strickland wrote:

>Up until now I have been running my Python programs in Linux. I just 
>wrote one in Windows XP and I can't find the print output. The Python 
>program has a print statement, and when I run the program a black window 
>opens and I can see printing going on. However, when it's finished 
>printing, the output window closes.
>
>How do I get the output window to stay open, or where is the output stored?
>
>Thanks!
>
>Tom Strickland
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>


From kent37 at tds.net  Sat Sep  3 06:03:00 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 03 Sep 2005 00:03:00 -0400
Subject: [Tutor] re.findall(), but with overlaps?
In-Reply-To: <Pine.LNX.4.44.0509021548040.30307-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0509021548040.30307-100000@violet.rahul.net>
Message-ID: <43192074.7080202@tds.net>

Terry Carroll wrote:
> But he asked me, is there a standard method to get even overlapped
> strings?
> 
> After looking through the docs, I couldn't find a way to do this in 
> standard methods, so I gave him a quick RYO solution:
> 
> 
>>>>def myfindall(regex, seq):
> 
> ...    resultlist=[]
> ...    pos=0
> ...
> ...    while True:
> ...       result = regex.search(seq, pos)
> ...       if result is None:
> ...          break
> ...       resultlist.append(seq[result.start():result.end()])
> ...       pos = result.start()+1
> ...    return resultlist
> ...
> 
>>>>myfindall(rexp,sequence)
> 
> ['BAB', 'BEB', 'BIB']
> 
> But just curious; are we reinventing the wheel here?  Is there already a 
> way to match even overlapping substrings?  I'm surprised I can't find one.

AFAIK that is the way to do it.  You can shorten it a little by using result.group() instead of seq[result.start():result.end()].

Kent


From alan.gauld at freenet.co.uk  Sat Sep  3 09:31:08 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Sat, 3 Sep 2005 08:31:08 +0100
Subject: [Tutor] Print Output Location in Windows XP
References: <43190706.8030500@comcast.net>
Message-ID: <012401c5b059$741a0f50$0201a8c0@xp>


> Up until now I have been running my Python programs in Linux. I just
> wrote one in Windows XP and I can't find the print output. The 
> Python program has a print statement, and when I run the program a 
> black window opens and I can see printing going on.

Thats a standard Windows command box. Print goes to stdout which 
appears
in that box. You can hide the box by renaming your script .pyw and 
then
you won't see your print output at all!

> However, when it's finished printing, the output window closes.
> How do I get the output window to stay open, or where is the output 
> stored?

There are several approaches to this, starting with the easiest:

1) Run the program from an existing command prompt

2) Use a raw_input('Hit ENTER to close...') line at the end of your 
program

3) Modify the file assosciation to run the ptrogram with pyhon -i
   This leaves you in the python interpreter at the end of the
   run - useful for debugging

4) Create a shortcut to your script and use that to run it,
   modify the shortcut to not close the window when finished.

HTH.

BTW What happened on Linux? If you run a python program by double
clicking the script file from a GUI where does stdout go? I've never
tried that, being a command line junkie, but surely a similar prooblem
ensues?

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


From alan.gauld at freenet.co.uk  Sat Sep  3 14:34:04 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Sat, 3 Sep 2005 13:34:04 +0100
Subject: [Tutor] New GUI module
Message-ID: <013d01c5b083$c54ed750$0201a8c0@xp>

I haven't seen this mentioned on the list, but has anyone else noticed
that v2.4 now includes the Tix GUI library in addition to Tkinter. Tix
is a collection of more advanced Tk widgets (trees, tables etc) 
similar
in many ways to PMW.

Just in case its useful to anyone.

Alan G.


From kent37 at tds.net  Sat Sep  3 16:14:38 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 03 Sep 2005 10:14:38 -0400
Subject: [Tutor] New GUI module
In-Reply-To: <013d01c5b083$c54ed750$0201a8c0@xp>
References: <013d01c5b083$c54ed750$0201a8c0@xp>
Message-ID: <4319AFCE.2010703@tds.net>

Alan,

Thanks for the pointer, I never noticed that either. But looking back, Tix has actually been included since Python 2.2! It was not listed in the What's New document for that release so it was easy to miss. It *was* listed in the What's New for Python 2.3; not as a new module but as receiving "various bug fixes and updates".

Module index for Python 2.2.3: http://www.python.org/doc/2.2.3/modindex.html
What's new for Python 2.2.3: http://www.python.org/doc/2.2.3/whatsnew/whatsnew22.html
What's new for Python 2.3.5: http://www.python.org/doc/2.3.5/whatsnew/node18.html

Has anyone here played with the TixApps on this site:
http://starship.python.net/crew/mike/

The IDE Studio and SpecTix look interesting.

Kent

Alan G wrote:
> I haven't seen this mentioned on the list, but has anyone else noticed
> that v2.4 now includes the Tix GUI library in addition to Tkinter. Tix
> is a collection of more advanced Tk widgets (trees, tables etc) 
> similar
> in many ways to PMW.
> 
> Just in case its useful to anyone.
> 
> Alan G.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From cpu.crazy at gmail.com  Sat Sep  3 16:59:29 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Sat, 03 Sep 2005 08:59:29 -0600
Subject: [Tutor] Game Engine HowTos?
Message-ID: <4319BA51.3080309@gmail.com>

Are there any Game engine tutorials or howto's for Python? Because I 
googled and can't find any? I'm considering making my own game engine in 
Python with some C/C++ as well.

Or does anyone know of a good Game Engine writing tutorial in another 
language?


From byron at christianfreebies.com  Sat Sep  3 17:06:22 2005
From: byron at christianfreebies.com (Byron)
Date: Sat, 03 Sep 2005 08:06:22 -0700
Subject: [Tutor] Game Engine HowTos?
In-Reply-To: <4319BA51.3080309@gmail.com>
References: <4319BA51.3080309@gmail.com>
Message-ID: <4319BBEE.10006@christianfreebies.com>

Joseph Quigley wrote:
> Or does anyone know of a good Game Engine writing tutorial in another 
> language?


I believe this is what you are looking for:
http://www.pygame.org/

Byron
---


From carroll at tjc.com  Sat Sep  3 18:01:16 2005
From: carroll at tjc.com (Terry Carroll)
Date: Sat, 3 Sep 2005 09:01:16 -0700 (PDT)
Subject: [Tutor] re.findall(), but with overlaps?
In-Reply-To: <43192074.7080202@tds.net>
Message-ID: <Pine.LNX.4.44.0509030900370.4894-100000@violet.rahul.net>

On Sat, 3 Sep 2005, Kent Johnson wrote:

> AFAIK that is the way to do it.

I may put in an enhancement request to change the name of re.findall to 
re.findsome.


From kent37 at tds.net  Sat Sep  3 19:42:21 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 03 Sep 2005 13:42:21 -0400
Subject: [Tutor] re.findall(), but with overlaps?
In-Reply-To: <Pine.LNX.4.44.0509030900370.4894-100000@violet.rahul.net>
References: <Pine.LNX.4.44.0509030900370.4894-100000@violet.rahul.net>
Message-ID: <4319E07D.7090502@tds.net>

Terry Carroll wrote:
> On Sat, 3 Sep 2005, Kent Johnson wrote:
> 
> 
>>AFAIK that is the way to do it.
> 
> 
> I may put in an enhancement request to change the name of re.findall to 
> re.findsome.

Or maybe findnonoverlapping. But I would say your chances of getting the name changed are slim to none, the Python developers are extremely reluctant to make changes that break existing code. You might want to suggest aliasing findall instead of replacing it.

Kent


From carroll at tjc.com  Sat Sep  3 22:25:56 2005
From: carroll at tjc.com (Terry Carroll)
Date: Sat, 3 Sep 2005 13:25:56 -0700 (PDT)
Subject: [Tutor] re.findall(), but with overlaps?
In-Reply-To: <4319E07D.7090502@tds.net>
Message-ID: <Pine.LNX.4.44.0509031325160.4894-100000@violet.rahul.net>

On Sat, 3 Sep 2005, Kent Johnson wrote:

> But I would say your chances of getting the name changed are slim to
> none, the Python developers are extremely reluctant to make changes that
> break existing code.

Yeah, I know.  I was mostly joking.

Mostly.


From dyoo at hkn.eecs.berkeley.edu  Sat Sep  3 23:38:46 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 3 Sep 2005 14:38:46 -0700 (PDT)
Subject: [Tutor] re.findall(), but with overlaps?
In-Reply-To: <Pine.LNX.4.44.0509030900370.4894-100000@violet.rahul.net>
Message-ID: <Pine.LNX.4.44.0509031416410.24464-100000@hkn.eecs.berkeley.edu>



> I may put in an enhancement request to change the name of re.findall to
> re.findsome.

Hi Terry,

A typical use of regular expressions is to break text into a sequence of
non-overlapping tokens.  There's nothing that technically stops us from
applying the theory of regular expressions to get overlapping matches, but
that use case is rare enough that it probably won't get into the Standard
Library anytime soon.  A third-party approach, to write customized code
that allow overlaps, will probably work better.

You may want to ask on comp.lang.python and see if someone else has had
the need for overlapping matches --- there might be other people who've
run into that problem too.

I've helped to adapt a specialized pattern matcher for Python; not sure if
this might interest you, but:

    http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/

and the Aho-Corasick search automaton that I've adapted does do
overlapping matches of keywords:

######
>>> import ahocorasick
>>> tree = ahocorasick.KeywordTree()
>>> for i in range(ord('A'), ord('Z') + 1):
...     tree.add('B' + chr(i) + 'B')
...
>>> tree.make()
>>> tree.findall('BABBEBIB', allow_overlaps = True)
<generator object at 0x403a9fec>
>>> list(tree.findall('BABBEBIB', allow_overlaps = True))
[(0, 3), (3, 6), (5, 8)]
######

The ahocorasick module doesn't provide full regexp power (and the example
shows that I have to simulate wildcards... *grin*), but it might still be
useful, depending on what you're really trying to do.  The link above also
refers to Nicolas Nehuen's 'pytst' module, which might also be useful for
you.

Best of wishes to you!


From servando at mac.com  Sun Sep  4 00:20:57 2005
From: servando at mac.com (Servando Garcia)
Date: Sat, 3 Sep 2005 17:20:57 -0500
Subject: [Tutor] Thanks
Message-ID: <64ae8c030df0a80f72ef2e3860c83ab4@mac.com>

My thanks to the list. With your help each day I convert another C++ 
die hard to python.


From jhe13586 at bigpond.net.au  Sun Sep  4 01:53:35 2005
From: jhe13586 at bigpond.net.au (Joal Heagney)
Date: Sun, 04 Sep 2005 09:53:35 +1000
Subject: [Tutor] Program to lock folders under win32
In-Reply-To: <c225925305052605006940fe87@mail.gmail.com>
References: <c225925305052605006940fe87@mail.gmail.com>
Message-ID: <dfdd1v$c8s$1@sea.gmane.org>

Mark Kels wrote:
> Hi list.
> 
> I want to make a program to lock folders (so the user can only access
> them if he knows the password) under win32, the only problem is that I
> have no idea how to start or what to do. Do you guys have any ideas of
> how to do it?
> 
> Thanks!
> 
> 
Other option might be to see if there's any native programs/support for 
encrypted folders with passwords. Something like an encrypted zip file, 
but the operating system recognises that it's meant to be treated as a 
folder.

(Note that the password/encryption on ordinary zip files is rather weak 
and definatly shouldn't be used for anything that absolutely has to be 
kept secret.)

Joal


From kent37 at tds.net  Sun Sep  4 02:20:31 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 03 Sep 2005 20:20:31 -0400
Subject: [Tutor] Thanks
In-Reply-To: <64ae8c030df0a80f72ef2e3860c83ab4@mac.com>
References: <64ae8c030df0a80f72ef2e3860c83ab4@mac.com>
Message-ID: <431A3DCF.4020107@tds.net>

Wow! Congratulations! I wish I had 1/10 your success in converting Java diehards.

Kent

Servando Garcia wrote:
> My thanks to the list. With your help each day I convert another C++ 
> die hard to python.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From byron at christianfreebies.com  Sun Sep  4 03:15:54 2005
From: byron at christianfreebies.com (Byron)
Date: Sat, 03 Sep 2005 18:15:54 -0700
Subject: [Tutor] Program to lock folders under win32
In-Reply-To: <dfdd1v$c8s$1@sea.gmane.org>
References: <c225925305052605006940fe87@mail.gmail.com>
	<dfdd1v$c8s$1@sea.gmane.org>
Message-ID: <431A4ACA.50609@christianfreebies.com>

>>I want to make a program to lock folders (so the user can only access
>>them if he knows the password) under win32, the only problem is that I
>>have no idea how to start or what to do. Do you guys have any ideas of
>>how to do it?

Normally, one would accomplish this via Windows file / folder 
permissions.  However, it also requires that you are working with a MS 
Windows domain server environment.

If you wish to accomplish this using non-Microsoft technology, you can 
always use a password protected web folder.  It will provide read only 
access.  If you wish to provide uploading rights, then you can always 
setup FTP abilities, etc.

Byron
---


From byron at christianfreebies.com  Sun Sep  4 14:42:09 2005
From: byron at christianfreebies.com (Byron)
Date: Sun, 04 Sep 2005 05:42:09 -0700
Subject: [Tutor] Program to lock folders under win32
In-Reply-To: <b2f0cd9e050904024410138d38@mail.gmail.com>
References: <c225925305052605006940fe87@mail.gmail.com>	
	<dfdd1v$c8s$1@sea.gmane.org> <431A4ACA.50609@christianfreebies.com>
	<b2f0cd9e050904024410138d38@mail.gmail.com>
Message-ID: <431AEBA1.9060703@christianfreebies.com>

Oliver Maunder wrote:
> There's a program called Magic Folders which does this - 
> http://www.pc-magic.com/des.htm#mf
> This actually hides the folders, rather than locking them.  However,  it 
> seems to be integrated with the operating system at a very low level. I 
> don't think you'd be able to get this kind of integration with a Python 
> program.

Hi Oliver,

Yeah, Magic Folders used to be a favorite program of mine.  Only problem 
(that I knew it used to have -- the problem still might be there, not 
sure) is that if you used any of the Windows "repair" or maintenance 
tools on your system, such as defrag or diskscan, you can lose your data.

Magic Folders creates a file system on the hard drive that "looks" like 
lost clusters.  Because of this, Windows jumps in and tries to "fix" it 
for you.  Not good!  ;-)

Byron
---


From alan.gauld at freenet.co.uk  Sun Sep  4 16:28:11 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Sun, 4 Sep 2005 15:28:11 +0100
Subject: [Tutor] New GUI module
References: <013d01c5b083$c54ed750$0201a8c0@xp> <4319AFCE.2010703@tds.net>
Message-ID: <001501c5b15c$e0e68b00$0201a8c0@xp>

> Tix has actually been included since Python 2.2!

Wow! I only noticed it coz I was browsing the module index for 
something
else, but knew Tix from my TCl programming days. I took a look and 
sure
enough it was the same thing.

> The IDE Studio and SpecTix look interesting.

SpecTix is an enhancement of the older SpecTcl which I used when I
did Tcl GUI programming. Its quite easy to use although in common
with mamy such tools the code it produces is not particularly pretty.

I've never tried IDE Studio...

Alan G.
Currently learning JSP with the aid of the NetBeans IDE...
Next step: integrating Jython with JSP and NetBeans... :-) 


From rick at niof.net  Sun Sep  4 16:30:31 2005
From: rick at niof.net (Rick Pasotto)
Date: Sun, 4 Sep 2005 10:30:31 -0400
Subject: [Tutor] New GUI module
In-Reply-To: <001501c5b15c$e0e68b00$0201a8c0@xp>
References: <013d01c5b083$c54ed750$0201a8c0@xp> <4319AFCE.2010703@tds.net>
	<001501c5b15c$e0e68b00$0201a8c0@xp>
Message-ID: <20050904143031.GU6717@niof.net>

On Sun, Sep 04, 2005 at 03:28:11PM +0100, Alan G wrote:
> > Tix has actually been included since Python 2.2!

But there are still no *python* docs. The Tcl docs are very confusing.

-- 
"Happiness is the interval between periods of unhappiness."
		-- Don Marquis
    Rick Pasotto    rick at niof.net    http://www.niof.net

From alan.gauld at freenet.co.uk  Sun Sep  4 16:37:43 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Sun, 4 Sep 2005 15:37:43 +0100
Subject: [Tutor] Program to lock folders under win32
References: <c225925305052605006940fe87@mail.gmail.com>
	<dfdd1v$c8s$1@sea.gmane.org>
Message-ID: <002101c5b15e$362e3fd0$0201a8c0@xp>

>> I want to make a program to lock folders (so the user can only 
>> access
>> them if he knows the password) under win32

If it's Windows NT or later folder password protection is standard(I 
think!).
If it's Windows 2000 or later you get file encryption too (although
as expected from Microsoft its full of security holes by default!)
If it's XP Pro you can add zipped folders too...

I think there are registry hacks to turn on these facilities
in XP Home too...

You can access the hooks using the WSH objects and a COM interface
such as the winall package.

HTH,

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


From olivermaunder at gmail.com  Sun Sep  4 11:45:18 2005
From: olivermaunder at gmail.com (Oliver Maunder)
Date: Sun, 4 Sep 2005 10:45:18 +0100
Subject: [Tutor] Program to lock folders under win32
In-Reply-To: <b2f0cd9e050904024410138d38@mail.gmail.com>
References: <c225925305052605006940fe87@mail.gmail.com>
	<dfdd1v$c8s$1@sea.gmane.org> <431A4ACA.50609@christianfreebies.com>
	<b2f0cd9e050904024410138d38@mail.gmail.com>
Message-ID: <b2f0cd9e050904024562f64487@mail.gmail.com>

On 04/09/05, Byron <byron at christianfreebies.com> wrote:
> 
> >>I want to make a program to lock folders (so the user can only access
> >>them if he knows the password) under win32, the only problem is that I
> >>have no idea how to start or what to do. Do you guys have any ideas of 
> >>how to do it?


There's a program called Magic Folders which does this - 
http://www.pc-magic.com/des.htm#mf
This actually hides the folders, rather than locking them. However, it seems 
to be integrated with the operating system at a very low level. I don't 
think you'd be able to get this kind of integration with a Python program.

Normally, one would accomplish this via Windows file / folder
> permissions. However, it also requires that you are working with a MS 
> Windows domain server environment.


This would also require that you are using NTFS rather than FAT32.

An approach I'd look at is this: When the folder is "locked", your Python 
program reads the contents of the folder, and writes the data into an 
encrypted file. To unlock the folder, the program reads the encrypted file 
and recreates the file/folder structure.

I'm new to Python myself, so I'm not sure how you'd implement this. I'm sure 
there are modules to handle encryption but you'd have to work out how to 
organise your data file. You could create a dictionary, with the keys being 
the filenames and the values being the file contents. Someone on this list 
mentioned the "shelve" module a couple of days ago - this is apparently an 
easy way to save a dictionary to disk.

Anyway - just my idea - feel free to discuss or dismiss it!

Olly

(by the way - it's my first post. Hello everyone!)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050904/0127e806/attachment.html

From kent37 at tds.net  Sun Sep  4 20:50:08 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 04 Sep 2005 14:50:08 -0400
Subject: [Tutor] New GUI module
In-Reply-To: <001501c5b15c$e0e68b00$0201a8c0@xp>
References: <013d01c5b083$c54ed750$0201a8c0@xp> <4319AFCE.2010703@tds.net>
	<001501c5b15c$e0e68b00$0201a8c0@xp>
Message-ID: <431B41E0.5080409@tds.net>

Alan G wrote:
> Currently learning JSP with the aid of the NetBeans IDE...
> Next step: integrating Jython with JSP and NetBeans... :-)

It's very easy to write a servlet in Jython, Jython ships with Java wrapper class that will load a Jython servlet and delegate to it. A nice dynamic way to develop a web site is to use Jython servlets as controllers and your favorite template engine (I like Velocity) for the views. Should work with a type-2 JSP setup as well. And some of the Java web frameworks have done some work to allow actions to be written in Jython.

Kent


From alan.gauld at btinternet.com  Mon Sep  5 00:41:34 2005
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 4 Sep 2005 23:41:34 +0100
Subject: [Tutor] New GUI module
References: <013d01c5b083$c54ed750$0201a8c0@xp>
	<4319AFCE.2010703@tds.net><001501c5b15c$e0e68b00$0201a8c0@xp>
	<431B41E0.5080409@tds.net>
Message-ID: <dfft4s$fb0$1@sea.gmane.org>

>> Currently learning JSP with the aid of the NetBeans IDE...
>> Next step: integrating Jython with JSP and NetBeans... :-)
>
> It's very easy to write a servlet in Jython,

Its not the beans/servlet side that's beating me, its the JSP 
magic
tags stuff. The only web programming I've done has been boring
old CGI and JSP requires me to turn my brain inside out...

But an awful lot of magic happens with these mysterious tags.
I'm working through the NetBeans tutorials and also "JSP for
Dummies"(!!). But now I have to go on a 4 day business trip
so I'll forget half what I've learned! :-(

Alan G. 




From dyoo at hkn.eecs.berkeley.edu  Mon Sep  5 02:31:35 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 4 Sep 2005 17:31:35 -0700 (PDT)
Subject: [Tutor] CREATING  A  PR.EXE  FROM  A  PR.PY (fwd)
Message-ID: <Pine.LNX.4.44.0509041727460.30558-100000@hkn.eecs.berkeley.edu>

[Forwarding to tutor at python.org.

Jack, next time, please don't send questions directly to me: send them off
to the tutor at python.org address.  There are two benefits to this: it
allows the group to answer your questions, and if also helps others who
may have similar questions.  See:

    http://www.gweep.ca/~edmonds/usenet/ml-etiquette.html

for more explanation of this.]


---------- Forwarded message ----------
Date: Sun, 4 Sep 2005 13:38:58 -0500
From: Jack Anema <JAnema2 at mts.net>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Cc: Janema at uvic.ca
Subject: CREATING  A  PR.EXE  FROM  A  PR.PY

Can you or someone give me very specific instructions required to create a
_.EXE     file from a     _.PY     file.

I have spent a lot of time looking through FAQ's at
http://www.python.org/doc/faq/   , having gone through all 7 sections
sections.

I have also gone to   http://starship.python.net/crew/theller/py2exe/
and tried to use the general comments there.

I did download and install     *win-py2.4.exe .    This installed
successfully as far as I can see.  There were no error messages and
REMOVEPY2EXE.EXE      was created in my      PYTHON24     folder.

The machine I am running, is running    XP professional, 2002.  It has a
Pentiuum(R) 4, 1.8 Ghz CPU.  The drive has 37 GB free.

I am by no means a computer expert but I am not illiterate either.  I have
used MS Quick Basic for many years.  In the past I have also used APL and
Fortran on various machines over the years.  I just am not familiar enough
with Python and have not been able to find the detailed data I need to do
what I want.  Up to a month ago I had never heard of Python and I badly need
the ability to make programs run as EXE files.

Can you or someone supply the very specific instructions to do this?  I
would also be perfectly willing to arrange with someone to call them at
their convenience and do it over the phone and compensate the person for
their effort and time.

I sincerely and very much appreciate anyone's response and help!  Thank you!
Jack Anema.

----- Original Message -----
From: "Danny Yoo" <dyoo at hkn.eecs.berkeley.edu>
To: "Jack Anema" <JAnema2 at mts.net>
Cc: <Tutor at python.org>
Sent: Friday, September 02, 2005 2:59 AM
Subject: Re: [Tutor] TEST to see if this gets out


>
>
> On Fri, 2 Sep 2005, Jack Anema wrote:
>
>> TEST
>
>
> Hi Jack,
>
> We're here.  Do you have a question about learning Python?
>
>




From JAnema2 at mts.net  Mon Sep  5 04:06:16 2005
From: JAnema2 at mts.net (Jack Anema)
Date: Sun, 4 Sep 2005 21:06:16 -0500
Subject: [Tutor] CREATING  A  PR.EXE  FROM  A  PR.PY
Message-ID: <001d01c5b1be$66134a50$6501a8c0@acerd3e20d0d7f>

Can you or someone give me very specific instructions as to how to create an      _.EXE      file from a       _.PY      file.

I have spent a lot of time looking through all 7 sections of FAQ's at     http://www.python.org/doc/faq/    and many other sights.

I have also gone to     http://starship.python.net/crew/theller/py2exe/      and tried to use the general comments there.

I did download and install     *win-py2.4.exe .    This installed successfully as far as I can see.  There were no error messages and        REMOVEPY2EXE.EXE      was created in my      PYTHON24     folder.

The machine I am running, is running    XP professional, 2002.  It has a Pentiuum(R) 4, 1.8 Ghz CPU.  The drive has 37 GB free.

I am by no means a computer expert but I am not illiterate either.  I have used MS Quick Basic for many years.  In the past I have also used APL and Fortran on various machines over the years.  I just am not familiar enough with Python and have not been able to find the detailed data I need to do what I want.  Up to a month ago I had never heard of Python and I badly need the ability to make      *.PY     programs files run as     *.EXE            files.

Can you or someone supply the very specific instructions to do this?  I would also be perfectly willing to arrange with someone to call them at their convenience and do it over the phone and compensate the person for their effort and time.

I sincerely and very much appreciate anyone's response and help!  Thank you!
Jack Anema.

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

From lists at janeden.org  Mon Sep  5 10:07:37 2005
From: lists at janeden.org (Jan Eden)
Date: Mon,  5 Sep 2005 10:07:37 +0200
Subject: [Tutor] mod_python on OS X
Message-ID: <r02010500-1039-1FA92A061DE411DA9ECA000A959B4026@[10.149.23.208]>

Hi,

I just tried installing mod_python on OS X (10.3.9). Installation went fine, and Apache starts up without complaining:

Apache/2.0.53 (Unix) DAV/2 PHP/5.0.1 mod_python/3.1.4 Python/2.4.1 mod_perl/2.0.1 Perl/v5.8.1 configured -- resuming normal       operations                                                                                                                                   

But when trying to actually use mod_python, I get:

[Sat Sep 03 23:01:52 2005] [notice] child pid 2334 exit signal Bus error (10)
[Sat Sep 03 23:01:53 2005] [notice] child pid 2333 exit signal Bus error (10)

I searched the mod_python mailing list archives, but all hints and suggestions pointed to the installation stage.

TIA,

Jan
-- 
Hanlon's Razor: Never attribute to malice that which can be adequately explained by stupidity.

From dyoo at hkn.eecs.berkeley.edu  Mon Sep  5 13:53:16 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 5 Sep 2005 04:53:16 -0700 (PDT)
Subject: [Tutor] mod_python on OS X
In-Reply-To: <r02010500-1039-1FA92A061DE411DA9ECA000A959B4026@[10.149.23.208]>
Message-ID: <Pine.LNX.4.44.0509050442070.3159-100000@hkn.eecs.berkeley.edu>



On Mon, 5 Sep 2005, Jan Eden wrote:

> I just tried installing mod_python on OS X (10.3.9). Installation went
> fine, and Apache starts up without complaining:
>
> Apache/2.0.53 (Unix) DAV/2 PHP/5.0.1 mod_python/3.1.4 Python/2.4.1
> mod_perl/2.0.1 Perl/v5.8.1 configured -- resuming normal operations
>
> But when trying to actually use mod_python, I get:
>
> [Sat Sep 03 23:01:52 2005] [notice] child pid 2334 exit signal Bus error (10)
> [Sat Sep 03 23:01:53 2005] [notice] child pid 2333 exit signal Bus error (10)
>
> I searched the mod_python mailing list archives, but all hints and
> suggestions pointed to the installation stage.


Hi Jan,

Hmmm... Try posting that onto the mod-python mailing list.  Bus Error
indicates a low-level issue, and probably does mean that somthing got
messed up during the installation.  (But it could also mean a bug in
mod_python: it's so hard to tell since it's a C extension.  *sigh*)

It looks that you have a locally customized verison of Python on your
system.  (As far as I know, Apple doesn't package Python 2.4 yet)  Did you
make sure to install mod_python by using that customized Python, rather
than the system default?


The folks on the mod_python mailing list will probably know more about
this, so I'd strongly recommend asking them:

    http://mailman.modpython.org/mailman/listinfo/mod_python

Tell them more details about how you installed mod_python --- the exact
terminal lines you entered will be very helpful.

Also, note that people on their list have been documenting their
grievances about this:  *grin*

   http://www.modpython.org/pipermail/mod_python/2004-June/015800.html

His problem sounds very similar to yours, (though they report it with
Apache 1.3) so I'd check with them and see if this has been fixed yet.


From lists at janeden.org  Mon Sep  5 21:45:02 2005
From: lists at janeden.org (Jan Eden)
Date: Mon,  5 Sep 2005 21:45:02 +0200
Subject: [Tutor] mod_python on OS X
In-Reply-To: <Pine.LNX.4.44.0509050442070.3159-100000@hkn.eecs.berkeley.edu>
Message-ID: <r02010500-1039-8D404AEF1E4511DA9AFF000A959B4026@[192.168.2.100]>

Hi Danny,

Danny Yoo wrote on 05.09.2005:

>
>On Mon, 5 Sep 2005, Jan Eden wrote:

>>[Sat Sep 03 23:01:52 2005] [notice] child pid 2334 exit signal Bus
>>error (10) [Sat Sep 03 23:01:53 2005] [notice] child pid 2333 exit
>>signal Bus error (10)
>
>It looks that you have a locally customized verison of Python on
>your system.  (As far as I know, Apple doesn't package Python 2.4
>yet)  Did you make sure to install mod_python by using that
>customized Python, rather than the system default?
>
I did.
>
>The folks on the mod_python mailing list will probably know more
>about this, so I'd strongly recommend asking them:
>
Yes, it is probably the best thing to do, but I wanted to avoid getting involved with yet another mailing list. *sigh*

Many thanks,

Jan
-- 
Unix is user friendly - it's just picky about it's friends.

From cpu.crazy at gmail.com  Sun Sep  4 17:08:55 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Sun, 04 Sep 2005 09:08:55 -0600
Subject: [Tutor] Game Engine HowTos?
In-Reply-To: <mailman.29.1125828009.2110.tutor@python.org>
References: <mailman.29.1125828009.2110.tutor@python.org>
Message-ID: <431B0E07.7090802@gmail.com>

Byron Wrote:

>I believe this is what you are looking for:
>http://www.pygame.org/
>
>Byron
>---
>  
>
Pygame? Well I'll take a look... do they have documentation for Game 
Engine writing?


From byron at christianfreebies.com  Mon Sep  5 23:04:54 2005
From: byron at christianfreebies.com (Byron)
Date: Mon, 05 Sep 2005 14:04:54 -0700
Subject: [Tutor] Game Engine HowTos?
In-Reply-To: <431B0E07.7090802@gmail.com>
References: <mailman.29.1125828009.2110.tutor@python.org>
	<431B0E07.7090802@gmail.com>
Message-ID: <431CB2F6.9090807@christianfreebies.com>

Joseph Quigley wrote:
> Pygame? Well I'll take a look... do they have documentation for Game 
> Engine writing?

I know that PyGame is a Python-based game engine in which one can use to 
write / develop computer games.  However, I am not sure if they allow 
you to be able to "re-write" the engine itself.  If you check their 
site, which seems to be well documented, I am sure that you can find out.

Byron
---


From me at scottoertel.info  Tue Sep  6 08:46:22 2005
From: me at scottoertel.info (Scott Oertel)
Date: Tue, 06 Sep 2005 09:46:22 +0300
Subject: [Tutor] CREATING  A  PR.EXE  FROM  A  PR.PY
In-Reply-To: <001d01c5b1be$66134a50$6501a8c0@acerd3e20d0d7f>
References: <001d01c5b1be$66134a50$6501a8c0@acerd3e20d0d7f>
Message-ID: <431D3B3E.9000702@scottoertel.info>

Jack Anema wrote:

> Can you or someone give me very specific instructions as to how to 
> create an      _.EXE      file from a       _.PY      file.
>
> I have spent a lot of time looking through all 7 sections of FAQ's 
> at     http://www.python.org/doc/faq/    and many other sights.
>
> I have also gone to    
>  http://starship.python.net/crew/theller/py2exe/      and tried to use 
> the general comments there.
>
> I did download and install     *win-py2.4.exe .    This installed 
> successfully as far as I can see.  There were no error messages 
> and        REMOVEPY2EXE.EXE      was created in my      PYTHON24     
> folder.
>
> The machine I am running, is running    XP professional, 2002.  It has 
> a Pentiuum(R) 4, 1.8 Ghz CPU.  The drive has 37 GB free.
>
> I am by no means a computer expert but I am not illiterate either.  I 
> have used MS Quick Basic for many years.  In the past I have also used 
> APL and Fortran on various machines over the years.  I just am not 
> familiar enough with Python and have not been able to find the 
> detailed data I need to do what I want.  Up to a month ago I had never 
> heard of Python and I badly need the ability to make      *.PY     
> programs files run as     *.EXE            files.
>
> Can you or someone supply the very specific instructions to do this?  
> I would also be perfectly willing to arrange with someone to call them 
> at their convenience and do it over the phone and compensate the 
> person for their effort and time.
>
> I sincerely and very much appreciate anyone's response and help!  
> Thank you!
> Jack Anema.
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>
Try using py2exe it works pretty well for compiling .py into a portable 
.exe distribution.


http://starship.python.net/crew/theller/py2exe/


-Scott Oertel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050906/274d4e7c/attachment.htm

From rabidpoobear at gmail.com  Tue Sep  6 08:58:09 2005
From: rabidpoobear at gmail.com (luke)
Date: Tue, 6 Sep 2005 01:58:09 -0500
Subject: [Tutor] Game Engine HowTos?
References: <mailman.29.1125828009.2110.tutor@python.org>
	<431B0E07.7090802@gmail.com>
Message-ID: <003201c5b2b0$57a7cc50$c6db1a93@403R>

>>I believe this is what you are looking for:
>>http://www.pygame.org/
>>
> Pygame? Well I'll take a look... do they have documentation for Game
> Engine writing?

why didn't you look before you asked? just curious.
Pygame is a library that gives you easy, low-level access to the graphics 
buffer
and the sound as well.
it has commands for blitting images and drawing primitive shapes on the 
screen.
so it isn't a game engine.
it's what goes under the game engine, doing all the dirty drawing work for 
you.

I don't think there are game engine tutorials on the site explicitly,
but you should be able to figure out how to write one if you look through 
the
other tutorials.
also, you might want to look into joining the pygame mailing list.
they are very helpful.
-Luke

Afterthought:
This e-mail was entirely pointless I apologize but I am sending it anyway
because I wasted my time writing it. 


From genietdev0 at iol.ie  Tue Sep  6 11:17:19 2005
From: genietdev0 at iol.ie (Victor Reijs)
Date: Tue, 06 Sep 2005 10:17:19 +0100
Subject: [Tutor] dialog boxes
Message-ID: <431D5E9F.5040100@iol.ie>

Hello all of you,

I want to use yes/no-, text-, info-, checklist- dialog boxes in my image
manipulation program (on a Windows XP Pro system using python 2.2 and
2.3). What is the best way to do this?

Thanks for your feedback.


All the best,


Victor



From kent37 at tds.net  Tue Sep  6 11:53:31 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Sep 2005 05:53:31 -0400
Subject: [Tutor] Game Engine HowTos?
In-Reply-To: <4319BA51.3080309@gmail.com>
References: <4319BA51.3080309@gmail.com>
Message-ID: <431D671B.1060008@tds.net>

Googling "python game engine" gives some interesting hits including existing game engines that might be useful examples and some low-level toolkits you might want to use. Or you might want to join efforts with one of the open-source engines and work on that.

Kent

Joseph Quigley wrote:
> Are there any Game engine tutorials or howto's for Python? Because I 
> googled and can't find any? I'm considering making my own game engine in 
> Python with some C/C++ as well.
> 
> Or does anyone know of a good Game Engine writing tutorial in another 
> language?
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From frank.l.lane at boeing.com  Tue Sep  6 13:44:29 2005
From: frank.l.lane at boeing.com (Lane, Frank L)
Date: Tue, 6 Sep 2005 06:44:29 -0500
Subject: [Tutor] Is there an easy way to combine dictionaries?
Message-ID: <C3871B74409A854EA9B6F4EEB92088070110FB63@XCH-SE-1V2.se.nos.boeing.com>

Hi List,
 
Is there an easy way to combine dictionaries?
 
e.g.
 
a = {}
b = {}
 
a = {'a':'a', 'b':'b', 'c':'c'}
b = {'1':1, '2':2, '3':3}
c = a + b # doesn't seem to work
 
desired:
c = {'a':'a', 'b':'b', 'c':'c', '1':1, '2':2, '3':3}
 
Thanks,
Frank
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050906/0ba16fc4/attachment.htm

From pierre.barbier at cirad.fr  Tue Sep  6 13:58:23 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Tue, 06 Sep 2005 13:58:23 +0200
Subject: [Tutor] Is there an easy way to combine dictionaries?
In-Reply-To: <C3871B74409A854EA9B6F4EEB92088070110FB63@XCH-SE-1V2.se.nos.boeing.com>
References: <C3871B74409A854EA9B6F4EEB92088070110FB63@XCH-SE-1V2.se.nos.boeing.com>
Message-ID: <431D845F.60409@cirad.fr>

Is this what you want ?

c = dict(a)
c.update(b)

Pierre

Lane, Frank L a ?crit :
> Hi List,
>  
> Is there an easy way to combine dictionaries?
>  
> e.g.
>  
> a = {}
> b = {}
>  
> a = {'a':'a', 'b':'b', 'c':'c'}
> b = {'1':1, '2':2, '3':3}
> c = a + b # doesn't seem to work
>  
> desired:
> c = {'a':'a', 'b':'b', 'c':'c', '1':1, '2':2, '3':3}
>  
> Thanks,
> Frank
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68

From byron at christianfreebies.com  Tue Sep  6 15:43:22 2005
From: byron at christianfreebies.com (Byron)
Date: Tue, 06 Sep 2005 06:43:22 -0700
Subject: [Tutor] Is there an easy way to combine dictionaries?
In-Reply-To: <C3871B74409A854EA9B6F4EEB92088070110FB63@XCH-SE-1V2.se.nos.boeing.com>
References: <C3871B74409A854EA9B6F4EEB92088070110FB63@XCH-SE-1V2.se.nos.boeing.com>
Message-ID: <431D9CFA.9090805@christianfreebies.com>

Lane, Frank L wrote:
> Is there an easy way to combine dictionaries?

Hi Frank,

Yes, there is -- please see the "addDict" method that I have provided below:

Byron
---

def addDicts(a, b):
	c = {}
	for item in a:
		c[item] = a[item]
	for item in b:
		c[item] = b[item]
	return c


a = {'a':'a', 'b':'b', 'c':'c'}
b = {'1':1, '2':2, '3':3}
c = addDicts(a, b)

print c


From nephish at xit.net  Tue Sep  6 16:59:59 2005
From: nephish at xit.net (nephish)
Date: Tue, 06 Sep 2005 09:59:59 -0500
Subject: [Tutor] threading problem in GUI
Message-ID: <431DAEEF.9090209@xit.net>

Hello there !
i am having a problem with threading.
OK, i have this GUI app that i am building with pygtk.
there is a process (four actually, just working on getting one right now)
that needs to run in the background.
there is a button that starts the background function. But, it locks up 
the gui. it doesn't run in the background, it locks everything up. It 
still runs though.
one of the things this background process is to do is updata a viewable
area on the GUI. Now when run from a terminal, when i hit CTRL+C
it stops the thread, but doesnt kill the GUI, and the TextView gets 
updated right then with everything it should have gotten before.


def Serial1():
            print 'running serial 1'
            ser = serial.Serial('/dev/ttyS15', 2400, timeout=None)
            loopy = 1
            i = 1
            while loopy < 5:   
                x_Now = strftime('%Y-%m-%d %H:%M:%S')
                i = i + 1                   
                a = ser.read(1)#read one byte       
                a = ord(a) # change byte to integer
                if (a < 64 )or (a > 127):
                    continue       
                b = ser.read(1)
                b = ord(b)
                if (b < 64 )or (b > 127):
                    continue
                c = ser.read(1)
                c = ord(c)
                if c < 92:
                    continue
                d = ser.read(1)
                d = ord(d)
                if d < 128:
                    continue
                Sensor_ID = (a & 63) + (b & 63) * 64 + (c & 1) * 4096
                Status = (c & 62) / 2 + (d & 63) * 32
                c = int(c)
                d = int(d)
                x_Now = strftime('%Y-%m-%d %H:%M:%S')
                f = open('/home/piv/PivData/tmp/Serial/'+str(i), 'w')
                Input1Data = 
str(Sensor_ID)+'\t'+str(Status)+'\t--------->\t'+x_Now+'\n'
                Input1Iter = self.Input1Buffer.get_end_iter()
                self.Input1Buffer.insert(Input1Iter, 
Input1Data)               
                
f.write(str(Sensor_ID)+'\n'+str(c)+'\n'+str(d)+'\n'+str(Status)+'\n'+x_Now)       

                f.close()
        thread.start_new(Serial1())

the code may not be best form, i am still fairly new at this. so i am 
also open to
any constructive critisism.

thanks
shawn

From pierre.barbier at cirad.fr  Tue Sep  6 17:32:15 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Tue, 06 Sep 2005 17:32:15 +0200
Subject: [Tutor] threading problem in GUI
In-Reply-To: <431DAEEF.9090209@xit.net>
References: <431DAEEF.9090209@xit.net>
Message-ID: <431DB67F.9060601@cirad.fr>

nephish a ?crit :
> Hello there !

Hello,

> i am having a problem with threading.
> OK, i have this GUI app that i am building with pygtk.
> there is a process (four actually, just working on getting one right now)
> that needs to run in the background.

Please, do not mix "process" and "threads" ... there very different ...
you're talking about threads here, so you want Threads to run in the
background ...

> there is a button that starts the background function. But, it locks up 
> the gui. it doesn't run in the background, it locks everything up. It 
> still runs though.

That's just normal ... if you read PyGtk documentation, you'll see you
need to initialise PyGtk to handle threads :

http://www.async.com.br/faq/pygtk/index.py?req=index -> 20. The GTK
Mainloop and Threading

http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq20.006.htp
-> This is exactly your problem !

http://www.pygtk.org/pygtk2reference/gdk-functions.html#function-gdk--threads-init

This is done like this :

# First call to PyGtk function ever
gtk.gdk.threads_init()
# Here initialize what you want
[...]
# Launch the Gtk loop
gtk.gdk.threads_enter() # Unneeded if you don't want to call GUI
                        # functions from other threads
gtk.main()
gtk.gdk.threads_leave() # Needed only with threads_enter

> one of the things this background process is to do is updata a viewable
> area on the GUI. Now when run from a terminal, when i hit CTRL+C
> it stops the thread, but doesnt kill the GUI, and the TextView gets 
> updated right then with everything it should have gotten before.
> 
> 
> def Serial1():
>             print 'running serial 1'
>             ser = serial.Serial('/dev/ttyS15', 2400, timeout=None)
>             loopy = 1
>             i = 1
>             while loopy < 5:   
>                 x_Now = strftime('%Y-%m-%d %H:%M:%S')
>                 i = i + 1                   
>                 a = ser.read(1)#read one byte       
>                 a = ord(a) # change byte to integer
>                 if (a < 64 )or (a > 127):
>                     continue       
>                 b = ser.read(1)
>                 b = ord(b)
>                 if (b < 64 )or (b > 127):
>                     continue
>                 c = ser.read(1)
>                 c = ord(c)
>                 if c < 92:
>                     continue
>                 d = ser.read(1)
>                 d = ord(d)
>                 if d < 128:
>                     continue
>                 Sensor_ID = (a & 63) + (b & 63) * 64 + (c & 1) * 4096
>                 Status = (c & 62) / 2 + (d & 63) * 32
>                 c = int(c)
>                 d = int(d)
>                 x_Now = strftime('%Y-%m-%d %H:%M:%S')
>                 f = open('/home/piv/PivData/tmp/Serial/'+str(i), 'w')
>                 Input1Data = 
> str(Sensor_ID)+'\t'+str(Status)+'\t--------->\t'+x_Now+'\n'
>                 Input1Iter = self.Input1Buffer.get_end_iter()
>                 self.Input1Buffer.insert(Input1Iter, 
> Input1Data)               
>                 
> f.write(str(Sensor_ID)+'\n'+str(c)+'\n'+str(d)+'\n'+str(Status)+'\n'+x_Now)       
> 
>                 f.close()
>         thread.start_new(Serial1())
> 
> the code may not be best form, i am still fairly new at this. so i am 
> also open to
> any constructive critisism.
> 
> thanks
> shawn
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68

From nephish at xit.net  Tue Sep  6 18:41:01 2005
From: nephish at xit.net (nephish)
Date: Tue, 06 Sep 2005 11:41:01 -0500
Subject: [Tutor] threading problem in GUI
In-Reply-To: <431DB67F.9060601@cirad.fr>
References: <431DAEEF.9090209@xit.net> <431DB67F.9060601@cirad.fr>
Message-ID: <431DC69D.2070501@xit.net>

Pierre Barbier de Reuille wrote:

>nephish a ?crit :
>  
>
>>Hello there !
>>    
>>
>
>Hello,
>
>  
>
>>i am having a problem with threading.
>>OK, i have this GUI app that i am building with pygtk.
>>there is a process (four actually, just working on getting one right now)
>>that needs to run in the background.
>>    
>>
>
>Please, do not mix "process" and "threads" ... there very different ...
>you're talking about threads here, so you want Threads to run in the
>background ...
>
>  
>
>>there is a button that starts the background function. But, it locks up 
>>the gui. it doesn't run in the background, it locks everything up. It 
>>still runs though.
>>    
>>
>
>That's just normal ... if you read PyGtk documentation, you'll see you
>need to initialise PyGtk to handle threads :
>
>http://www.async.com.br/faq/pygtk/index.py?req=index -> 20. The GTK
>Mainloop and Threading
>
>http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq20.006.htp
>-> This is exactly your problem !
>
>http://www.pygtk.org/pygtk2reference/gdk-functions.html#function-gdk--threads-init
>
>This is done like this :
>
># First call to PyGtk function ever
>gtk.gdk.threads_init()
># Here initialize what you want
>[...]
># Launch the Gtk loop
>gtk.gdk.threads_enter() # Unneeded if you don't want to call GUI
>                        # functions from other threads
>gtk.main()
>gtk.gdk.threads_leave() # Needed only with threads_enter
>
>  
>
>>one of the things this background process is to do is updata a viewable
>>area on the GUI. Now when run from a terminal, when i hit CTRL+C
>>it stops the thread, but doesnt kill the GUI, and the TextView gets 
>>updated right then with everything it should have gotten before.
>>
>>
>>def Serial1():
>>            print 'running serial 1'
>>            ser = serial.Serial('/dev/ttyS15', 2400, timeout=None)
>>            loopy = 1
>>            i = 1
>>            while loopy < 5:   
>>                x_Now = strftime('%Y-%m-%d %H:%M:%S')
>>                i = i + 1                   
>>                a = ser.read(1)#read one byte       
>>                a = ord(a) # change byte to integer
>>                if (a < 64 )or (a > 127):
>>                    continue       
>>                b = ser.read(1)
>>                b = ord(b)
>>                if (b < 64 )or (b > 127):
>>                    continue
>>                c = ser.read(1)
>>                c = ord(c)
>>                if c < 92:
>>                    continue
>>                d = ser.read(1)
>>                d = ord(d)
>>                if d < 128:
>>                    continue
>>                Sensor_ID = (a & 63) + (b & 63) * 64 + (c & 1) * 4096
>>                Status = (c & 62) / 2 + (d & 63) * 32
>>                c = int(c)
>>                d = int(d)
>>                x_Now = strftime('%Y-%m-%d %H:%M:%S')
>>                f = open('/home/piv/PivData/tmp/Serial/'+str(i), 'w')
>>                Input1Data = 
>>str(Sensor_ID)+'\t'+str(Status)+'\t--------->\t'+x_Now+'\n'
>>                Input1Iter = self.Input1Buffer.get_end_iter()
>>                self.Input1Buffer.insert(Input1Iter, 
>>Input1Data)               
>>                
>>f.write(str(Sensor_ID)+'\n'+str(c)+'\n'+str(d)+'\n'+str(Status)+'\n'+x_Now)       
>>
>>                f.close()
>>        thread.start_new(Serial1())
>>
>>the code may not be best form, i am still fairly new at this. so i am 
>>also open to
>>any constructive critisism.
>>
>>thanks
>>shawn
>>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>>    
>>
>
>  
>
ok, i am still having a little problem understanding.
tried it but i don't know if i have things set in the right order.

 
gtk.gdk.threads_init()
# Here initialize what you want
[...]
# Launch the Gtk loop
gtk.gdk.threads_enter() # Unneeded if you don't want to call GUI
                        # functions from other threads
gtk.main()
gtk.gdk.threads_leave() # Needed only with threads_enter

at the part where you wrote 
# Here initialize what you want
[...]
is that where i define the function that will run the thread?

i get the part about having the enter and leave
i just seem to have a hang up (so to speak) with where the function gets defined.
do i need to build it as a class like the example in the link you sent?

thanks for your help on this



From pierre.barbier at cirad.fr  Tue Sep  6 19:05:33 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Tue, 06 Sep 2005 19:05:33 +0200
Subject: [Tutor] threading problem in GUI
In-Reply-To: <431DC69D.2070501@xit.net>
References: <431DAEEF.9090209@xit.net> <431DB67F.9060601@cirad.fr>
	<431DC69D.2070501@xit.net>
Message-ID: <431DCC5D.4090108@cirad.fr>



nephish a ?crit :
> Pierre Barbier de Reuille wrote:
> 
> [...]
> ok, i am still having a little problem understanding.
> tried it but i don't know if i have things set in the right order.
> 
> 
> gtk.gdk.threads_init()
> # Here initialize what you want
> [...]
> # Launch the Gtk loop
> gtk.gdk.threads_enter() # Unneeded if you don't want to call GUI
>                        # functions from other threads
> gtk.main()
> gtk.gdk.threads_leave() # Needed only with threads_enter
> 
> at the part where you wrote # Here initialize what you want
> [...]
> is that where i define the function that will run the thread?
> 
> i get the part about having the enter and leave
> i just seem to have a hang up (so to speak) with where the function gets
> defined.
> do i need to build it as a class like the example in the link you sent?

Well, no you don't need to create a class.

As for the place where to put your function, it's not a problem, [...]
is the place where you will *execute* some initialization code (if
needed) before you launch your interface. That's all (typically that's
where you will instanciate your widgets).

> 
> thanks for your help on this
> 
Your welcome,

Pierre

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68

From nephish at xit.net  Tue Sep  6 21:06:36 2005
From: nephish at xit.net (nephish)
Date: Tue, 06 Sep 2005 14:06:36 -0500
Subject: [Tutor] threading problem in GUI
In-Reply-To: <431DCC5D.4090108@cirad.fr>
References: <431DAEEF.9090209@xit.net> <431DB67F.9060601@cirad.fr>
	<431DC69D.2070501@xit.net> <431DCC5D.4090108@cirad.fr>
Message-ID: <431DE8BC.2060607@xit.net>

Pierre Barbier de Reuille wrote:

>nephish a ?crit :
>  
>
>>Pierre Barbier de Reuille wrote:
>>
>>[...]
>>ok, i am still having a little problem understanding.
>>tried it but i don't know if i have things set in the right order.
>>
>>
>>gtk.gdk.threads_init()
>># Here initialize what you want
>>[...]
>># Launch the Gtk loop
>>gtk.gdk.threads_enter() # Unneeded if you don't want to call GUI
>>                       # functions from other threads
>>gtk.main()
>>gtk.gdk.threads_leave() # Needed only with threads_enter
>>
>>at the part where you wrote # Here initialize what you want
>>[...]
>>is that where i define the function that will run the thread?
>>
>>i get the part about having the enter and leave
>>i just seem to have a hang up (so to speak) with where the function gets
>>defined.
>>do i need to build it as a class like the example in the link you sent?
>>    
>>
>
>Well, no you don't need to create a class.
>
>As for the place where to put your function, it's not a problem, [...]
>is the place where you will *execute* some initialization code (if
>needed) before you launch your interface. That's all (typically that's
>where you will instanciate your widgets).
>
>  
>
>>thanks for your help on this
>>
>>    
>>
>Your welcome,
>
>Pierre
>
>  
>
ok, i am still kinda stuck.
im posting what i think is necessary, because the whole thing is rather 
long.
so here goes.

#!/usr/bin/python

import os
import time
from time import strftime

import sys
import gtk
import pygtk
import serial
import threading
from threading import Thread
import tokenize
import gtk.glade
import weakref
import inspect
import re


gtk.gdk.threads_init()

def main(self):
        gtk.gdk.threads_enter()
        gtk.main()
        gtk.gdk.threads_leave()

def on_StartEnginesButton_clicked(self, widget, *args):
        print "on_StartEnginesButton_clicked called with self.%s" % 
widget.get_name()
        Input1Iter = self.Input1Buffer.get_end_iter()
        Input2Iter = self.Input2Buffer.get_end_iter()
        Input1Data = 'Reading Serial device ttyS14 \n'
        Input2Data = 'Reading Serial device ttys15 \n'
        self.Input1Buffer.insert(Input1Iter, Input1Data)
        self.Input2Buffer.insert(Input2Iter, Input2Data)       
        time.sleep(2)
        def Serial1():       
            print 'running serial 1'
            ser = serial.Serial('/dev/ttyS15', 2400, timeout=None)
            loopy = 1
            i = 1
            while loopy < 5:               
                for x in range(5):
                    i = i + 1                   
                    a = ser.read(1)#read one byte       
                    a = ord(a) # change byte to integer
                    if (a < 64 )or (a > 127):
                        break     
                    b = ser.read(1)
                    b = ord(b)
                    if (b < 64 )or (b > 127):
                        break
                    c = ser.read(1)
                    c = ord(c)
                    if c < 92:
                        break
                    d = ser.read(1)
                    d = ord(d)
                    if d < 128:
                        break
                    Sensor_ID = (a & 63) + (b & 63) * 64 + (c & 1) * 4096
                    Status = (c & 62) / 2 + (d & 63) * 32
                    c = int(c)
                    d = int(d)
                    x_Now = strftime('%Y-%m-%d %H:%M:%S')      
                    gtk.threads_enter()
                    Input1Data = 
str(Sensor_ID)+'\t'+str(Status)+'\t--------->\t'+x_Now+'\n'
                    Input1Iter = self.Input1Buffer.get_end_iter()
                    self.Input1Buffer.insert(Input1Iter, Input1Data)
                    gtk.threads_leave()
                    f = open('/home/piv/PivData/tmp/Serial/'+str(i), 'w')
                    
f.write(str(Sensor_ID)+'\n'+str(c)+'\n'+str(d)+'\n'+str(Status)+'\n'+x_Now)       

                    f.close()
        Thread.start(Serial1())

thanks, i am learning from several sources. two books from O'Reilly, and 
a dozen or so websites,
not everybody does everything the same way . if something here looks 
alarming, please let me know.

thanks

From frank.l.lane at boeing.com  Tue Sep  6 22:02:50 2005
From: frank.l.lane at boeing.com (Lane, Frank L)
Date: Tue, 6 Sep 2005 15:02:50 -0500
Subject: [Tutor] General Information Request
Message-ID: <C3871B74409A854EA9B6F4EEB92088070110FB6B@XCH-SE-1V2.se.nos.boeing.com>

Hi List,
 
I wanted to write to ask about help reading the Python documentation.
 
I found a really neat technique on the web using a built in called
"apply", with it you can do struct.pack() using an array for the values.
I can't find the technique in the release documentation and what's there
says apply is deprecated, use the new function (**args, *kwargs) or
something like that.  That has to be one of the most inscrutable things
I've ever seen in print.
 
I also saw a technique for building a dictionary out of two arrays,
which I also can't read:
    dict([(['one', 'two'][i-2], i) for i in (2,3)])
 
Is this just something that I have to get accustomed to or are there
pointers that help us read python-speak better?
 
Any explanation of the usage of function and the loop for building
dictionaries will be greatly appreciated!
 
Thanks,
Frank
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050906/9c49dcab/attachment.htm

From mac at Wireless.Com  Tue Sep  6 22:22:36 2005
From: mac at Wireless.Com (Mike Cheponis)
Date: Tue, 6 Sep 2005 13:22:36 -0700 (PDT)
Subject: [Tutor] Combining dictionaries
Message-ID: <Pine.NEB.4.63.0509061319350.2610@S.Culver.Net>


>Is this what you want ?
>
>c = dict(a)
>c.update(b)
>
>Pierre


>> Is there an easy way to combine dictionaries?
>>
>> a = {}
>> b = {}
>> 
>> a = {'a':'a', 'b':'b', 'c':'c'}
>> b = {'1':1, '2':2, '3':3}
>> c = a + b # doesn't seem to work
>> 
>> desired:
>> c = {'a':'a', 'b':'b', 'c':'c', '1':1, '2':2, '3':3}
>> 
>> Frank


No, that's not what he wants.

He wants c = a + b to work when a and b are dictionaries.

Why is Python broken in such an obvious way?

Thanks -Mike

From ewalker at micron.com  Tue Sep  6 22:32:52 2005
From: ewalker at micron.com (Eric Walker)
Date: Tue, 6 Sep 2005 14:32:52 -0600
Subject: [Tutor] win32 properties tab
Message-ID: <200509061432.52567.ewalker@micron.com>

Is there a way to pull the info listed on the properties tab , say of an image 
file from windows with python.. All the meta data...ie
Title, Subject, Keywords, Comments, Author

Any Ideas?

-- 
Eric Walker
EDA/CAD Engineer
Work: 208-368-2573

From dyoo at hkn.eecs.berkeley.edu  Tue Sep  6 22:57:01 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 6 Sep 2005 13:57:01 -0700 (PDT)
Subject: [Tutor] General Information Request
In-Reply-To: <C3871B74409A854EA9B6F4EEB92088070110FB6B@XCH-SE-1V2.se.nos.boeing.com>
Message-ID: <Pine.LNX.4.44.0509061306370.21731-100000@hkn.eecs.berkeley.edu>



On Tue, 6 Sep 2005, Lane, Frank L wrote:

> I found a really neat technique on the web using a built in called
> "apply", with it you can do struct.pack() using an array for the values.
> I can't find the technique in the release documentation and what's there
> says apply is deprecated, use the new function (**args, *kwargs) or
> something like that.


Hi Frank,

Python allows us to write functions that take a variable number of
arguments.  (For the moment, let's ignore the kwargs stuff.)

For example:

######
>>> def wave_at_all(*people):
...     for p in people:
...         print "waving at", p
...
>>>
>>> wave_at_all()
>>>
>>> wave_at_all("euclid")
waving at euclid
>>>
>>> wave_at_all("frank", "lloyd", "wright")
waving at frank
waving at lloyd
waving at wright
######


When we have these functions that can take variable number of arguments,
it's often nice to be able to feed a list directly into them, without
having to destructure them.


That's where apply comes in:

######
>>> apply(wave_at_all, ["jane", "doe"])
waving at jane
waving at doe
######

Without apply, this example might have been written as:

######
some_list = ['jane', 'doe']
first_name, second_name = some_list
wave_at_all(first_name, second_name)
######

But the problem with this, though, is that this approach doesn't scale: it
doesn't work for lists of arbitrary length, because in the general case,
we won't know in advance how many elements we need to "destructure" or
yank out of a list.

So one reason why apply() exists is to allow us to use
variable-length-argument-eating functions with lists.  (That was a
mouthful.  *grin*)  It's not the only reason, but it's a big one.


Notationally, apply() seemed a little weird to many Python programmers, so
the Python implementors added an alternative syntax in Python 2.0:

    apply(some_function, list_of_arguments)

        ==>

    some_function(*list_of_arguments)

(See: http://www.amk.ca/python/2.0/index.html#SECTION0001010000000000000000)


Does this make sense so far?  Please feel free to ask questions about
this.




> I also saw a technique for building a dictionary out of two arrays,
> which I also can't read:
>
>     dict([(['one', 'two'][i-2], i) for i in (2,3)])
>
> Is this just something that I have to get accustomed to or are there
> pointers that help us read python-speak better?

I can't read this either.  Truthfully, this looks horrible.  *grin*


What's happening is that there's a list comprehension nested in there, and
the expression as a whole feels very convoluted to me.  Here, let's break
it down a bit.

    mapping = dict([(['one', 'two'][i-2], i) for i in (2,3)])

        ==>

    keys_and_values = [(['one', 'two'][i-2], i)
                       for i in (2, 3)]
    mapping = dict(keys_and_values)


This also looks fairly ugly.  (It also worries me because it looks like
there's an off-by-one bug: why is 'one' being mapped to 2?)


We can remove the use of the list comprehension altogether:

    keys_and_values = [(['one', 'two'][i-2], i)
                       for i in (2, 3)]
    mapping = dict(keys_and_values)

        ==>

    keys = ['one', 'two']
    values = [2, 3]
    mapping = dict(zip(keys, values))



Best of wishes to you!


From dyoo at hkn.eecs.berkeley.edu  Tue Sep  6 23:07:18 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 6 Sep 2005 14:07:18 -0700 (PDT)
Subject: [Tutor] Combining dictionaries
In-Reply-To: <Pine.NEB.4.63.0509061319350.2610@S.Culver.Net>
Message-ID: <Pine.LNX.4.44.0509061357300.32279-100000@hkn.eecs.berkeley.edu>

> No, that's not what he wants.
>
> He wants c = a + b to work when a and b are dictionaries.
>
> Why is Python broken in such an obvious way?


Hi Mike:

It might not be obvious.  If a and b overlap so that they share keys, then
we might have the following situation:

    c1 = a + b
    c2 = b + a

Are c1 and c2 the same?

One possible problem is that this kind of "merging" operation on
dictionaries isn't "commutative".  And notationally, addition is supposed
to be so.  Forcing the notation of arithmetic on dictionaries is
seductive, but it can invite logical errors.

Best of wishes to you!


From mac at Wireless.Com  Wed Sep  7 01:14:32 2005
From: mac at Wireless.Com (Mike Cheponis)
Date: Tue, 6 Sep 2005 16:14:32 -0700 (PDT)
Subject: [Tutor] Combining dictionaries
In-Reply-To: <Pine.LNX.4.44.0509061357300.32279-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509061357300.32279-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.NEB.4.63.0509061600260.2610@S.Culver.Net>

On Tue, 6 Sep 2005, Danny Yoo wrote:

>> No, that's not what he wants.
>>
>> He wants c = a + b to work when a and b are dictionaries.
>>
>> Why is Python broken in such an obvious way?


> It might not be obvious.  If a and b overlap so that they share keys, then
> we might have the following situation:

I did consider that, but of course, "update" has to deal with that issue already.



>    c1 = a + b
>    c2 = b + a
>
> Are c1 and c2 the same?

Answer: maybe


> One possible problem is that this kind of "merging" operation on
> dictionaries isn't "commutative".  And notationally, addition is supposed
> to be so.  Forcing the notation of arithmetic on dictionaries is
> seductive, but it can invite logical errors.

( See my note, below, on the "*" operator [1]. )


Then use an operator like "++" which would be non-commutative "addition".

>>> a={1:1,2:2}
>>> b={2:22,3:3}
>>> c=dict(a)
>>> c.update(b)         # This would be c = a ++ b
>>> c
{1: 1, 2: 22, 3: 3}

>>> c=dict(b)
>>> c.update(a)         # This would be c = b ++ a
>>> c
{1: 1, 2: 2, 3: 3}


Seems like a straightforward improvement.

--------------------------

[1] Speaking of things that are suprising:


>>> "foo"   "bar "*3
'foobar foobar foobar '

>>> "foo" + "bar "*3
'foobar bar bar '


This also seems like a nasty bug (to me, at least).  Because one would think that the "*"
operator would bind more closely than the '"' or implied concatenation would.

How can I actively help fix these Python bugs?




> Best of wishes to you!

Same to you!


Thanks!  -Mike

From dyoo at hkn.eecs.berkeley.edu  Wed Sep  7 02:31:51 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 6 Sep 2005 17:31:51 -0700 (PDT)
Subject: [Tutor] Combining dictionaries
In-Reply-To: <Pine.NEB.4.63.0509061600260.2610@S.Culver.Net>
Message-ID: <Pine.LNX.4.44.0509061653590.24590-100000@hkn.eecs.berkeley.edu>



> >> He wants c = a + b to work when a and b are dictionaries.
> >>
> >> Why is Python broken in such an obvious way?
>
> > It might not be obvious.  If a and b overlap so that they share keys,
> > then we might have the following situation:
>
> I did consider that, but of course, "update" has to deal with that issue
> already.


Hi Mike,

Yes.  The name "update" is provokative enough, though, that it implies
something is being mutated, so there's no expectation of symmetry.



> Then use an operator like "++" which would be non-commutative
> "addition".
>
> >>> a={1:1,2:2}
> >>> b={2:22,3:3}
> >>> c=dict(a)
> >>> c.update(b)         # This would be c = a ++ b
> >>> c
> {1: 1, 2: 22, 3: 3}
>
> >>> c=dict(b)
> >>> c.update(a)         # This would be c = b ++ a
> >>> c
> {1: 1, 2: 2, 3: 3}


Let's make a function out of this:

######
def merge_dictionaries(a, b):
    """Returns a new dictionary whose key/value pairs will either come
    from dictionary a or b.  The mappings in 'a' take precedence over
    those in 'b'."""
    c = dict(b)
    c.update(a)
    return c
######

Would this be sufficient?



> >>> "foo"   "bar "*3
> 'foobar foobar foobar '
>
> >>> "foo" + "bar "*3
> 'foobar bar bar '
>
> This also seems like a nasty bug (to me, at least).  Because one would
> think that the "*" operator would bind more closely than the '"' or
> implied concatenation would.

I see what you're trying to do, but it won't work:  implicit literal
string concatenation only works between literal strings, that is, strings
that we enter with quotes.

Don't use it: it's easy to misunderstand what it's doing.  What you're
seeing above is not technically a bug: it's working as designed.  What you
mean to say is that it's unexpected to you, and that's true: I don't like
it either.  *grin*

But this one probably won't be cleaned up anytime soon:  too many programs
depend on it behaving this way now.  I do hope that the mythical Python
3000 gets rid of the feature, though, because almost every time I see
implicit literal string concatention on tutor, the user is mistaking what
it is doing.


If you want to report bugs and help improve Python, see:

    http://python.org/dev/

which has links to things like the bug tracker and the community process
that's used to improve Python.


Hope this helps!


------------------------------------------------------------------------

(Advanced aside/rant: Implied string literal concatentation is actually a
sore spot for me.  I now personally think it was a design mistake to have
it in the Python language, because it's really common for folks to get
confused with it, and the efficiency benefit, in my opinion, isn't worth
the confusion.

The implicit string concatentation between the string literals is being
done at compile time, at the time when Python builds the bytecodes, and
not when the program is actually running.  We can see this with a concrete
example:

##################################################################
>>> import dis
>>> def t1():
...     return "hello " "world"
...
>>> def t2():
...     return "hello" + "world"
...
>>> def t3():
...     return "hello world"
...
>>> dis.dis(t1)
  2           0 LOAD_CONST               1 ('hello world')
              3 RETURN_VALUE
              4 LOAD_CONST               0 (None)
              7 RETURN_VALUE
>>> dis.dis(t2)
  2           0 LOAD_CONST               1 ('hello')
              3 LOAD_CONST               2 ('world')
              6 BINARY_ADD
              7 RETURN_VALUE
              8 LOAD_CONST               0 (None)
             11 RETURN_VALUE
>>> dis.dis(t3)
  2           0 LOAD_CONST               1 ('hello world')
              3 RETURN_VALUE
              4 LOAD_CONST               0 (None)
              7 RETURN_VALUE
##################################################################

What most people probably expect is that t1 and t2 are the same.  But what
this example is contrary to expectation: it shows us is that t1 and t3 are
the same.

It's one of the few places where the distinction between run-time and
compile-time exists in Python, and it's such a special case situation that
I can't imagine it really helping performance out in Python, where so much
else is done when we actually run the program.

And we already have the same kind of behavior out of:

######
>>> "hello\
... world"
'helloworld'
######

so I really don't see the need why implicit string literal concatenation
is in Python.  End of rant.)


From jburk at radical.ca  Wed Sep  7 03:23:54 2005
From: jburk at radical.ca (John Burk)
Date: Tue, 6 Sep 2005 18:23:54 -0700
Subject: [Tutor] how to create a generic instance of an object?
Message-ID: <95FDCB82EFF3B9449865BF7D55FD2FF77BD74B@radmail.radical.ca>

I've got a base class "Asset", and currently have about 20 sub-classes
(assetTypes) that will inherit from it, with more to follow, I'm sure.
All of the assetTypes will have the same methods, but they'll be
polymorphic; each assetType's methodA() will do something slightly
different from it's sibling assetTypes.

What I want to do is to pass in the assetType at runTime via an external
script, create a new instance of it, and then run that instance's
methods.  That way I won't have to have 20 or more " if assetType== "
if/elif statements, and maintaining the script that creates new
instances won't become a nightmare.

And changing the base class' __init__ to contain another if/elif every
time someone adds another assetType seems to be so wrong, I rejected
that approach out of hand.  I want to design this thing so that the base
class doesn't need to know about all the sub-classes.

Perhaps I'm taking the wrong approach here with the Asset/AssetType
base-class/sub-class organization; it's beginning to feel that way.

I've tried something like this:

<asset.py>
class Asset: pass

<foo.py>
class Foo(Asset): pass

<script.py>
from asset import Asset
from foo import Foo

klass = 'Foo'
o = klass()

which gets me 'string not callable', which is kind of expected.

On p.325 of the O'Reilly Learning Python (2nd ed.), there's an example
of generic instance creation, but the values passed in are class
objects, not strings...  I'm guessing that this works because it's all
in the same module, so it knows that the things in the tuple iterated
over in the foreach are classes.

Any ideas?  I'm an old hand at perl (10+ years), but very new to Python,
so please be patient.

John Burk



From john at fouhy.net  Wed Sep  7 03:45:58 2005
From: john at fouhy.net (John Fouhy)
Date: Wed, 7 Sep 2005 13:45:58 +1200
Subject: [Tutor]  how to create a generic instance of an object?
In-Reply-To: <5e58f2e405090618442e6676bc@mail.gmail.com>
References: <95FDCB82EFF3B9449865BF7D55FD2FF77BD74B@radmail.radical.ca>
	<5e58f2e405090618442e6676bc@mail.gmail.com>
Message-ID: <5e58f2e405090618451ecc4c1e@mail.gmail.com>

On 07/09/05, John Burk <jburk at radical.ca> wrote:
> What I want to do is to pass in the assetType at runTime via an external
> script, create a new instance of it, and then run that instance's
> methods.  That way I won't have to have 20 or more " if assetType== "
> if/elif statements, and maintaining the script that creates new
> instances won't become a nightmare.

Would it be practical to use a dict?  Something like:

class Foo(Asset):
 pass
class Bar(Asset):
 pass

assetDict = { 'Foo':Foo, 'Bar':Bar }

You could split it out into modules too:

### AssetDict.py ###
assetDict = {}
###

### Foo.py ###
from Asset import Asset
import AssetDict

class Foo(Asset):
 pass
AssetDict.assetDict['Foo'] = Foo
###

### script.py ###
import AssetDict

klass = 'Foo'
o = AssetDict.assetDict[klass]()
###

Where is the class type coming from? Is it not feasible for you to
just do everything in terms of class objects? (which can be imported,
passed around, etc. just as easily as strings can be)

--
John.

From dyoo at hkn.eecs.berkeley.edu  Wed Sep  7 03:54:58 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 6 Sep 2005 18:54:58 -0700 (PDT)
Subject: [Tutor] how to create a generic instance of an object?
In-Reply-To: <95FDCB82EFF3B9449865BF7D55FD2FF77BD74B@radmail.radical.ca>
Message-ID: <Pine.LNX.4.44.0509061845001.678-100000@hkn.eecs.berkeley.edu>



> Perhaps I'm taking the wrong approach here with the Asset/AssetType
> base-class/sub-class organization; it's beginning to feel that way.
>
> I've tried something like this:
>
> <asset.py>
> class Asset: pass
>
> <foo.py>
> class Foo(Asset): pass
>
> <script.py>
> from asset import Asset
> from foo import Foo
>
> klass = 'Foo'
> o = klass()
>
> which gets me 'string not callable', which is kind of expected.


Hi John,

It sounds like you're trying to do some kind of dynamic linking.  Python
has a builtin called "__import__" that can help: it allows us to do module
import, given an arbitrary name.

Your example above might be written as:

#####################################################################
<asset.py>
class Asset: pass

<foo.py>
class Foo(Asset): pass

<script.py>

def dynamic_lookup(module_name, class_name):
    module_object = __import__(module_name)
    class_object = getattr(module_object, class_name)
    return class_object

klass = dynamic_lookup('foo', 'Foo')
o = klass()
#####################################################################

This can be easily abused.  *grin* But for what you're trying, it might be
what you're looking for.  For more information on __import__, see:

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


Hope this helps!


From raikage at gmail.com  Wed Sep  7 04:20:26 2005
From: raikage at gmail.com (Dax Reyes)
Date: Wed, 7 Sep 2005 10:20:26 +0800
Subject: [Tutor] CREATING A PR.EXE FROM A PR.PY
In-Reply-To: <001d01c5b1be$66134a50$6501a8c0@acerd3e20d0d7f>
References: <001d01c5b1be$66134a50$6501a8c0@acerd3e20d0d7f>
Message-ID: <962bfc3f0509061920102e0424@mail.gmail.com>

Hello Jack,

Do you still need help regarding exe creation?
In case you do. Here are some notes I took way back in 2003.

you must create a setup.py
put something like

from distutils.core import setup
import py2exe
sbiGui = ['samplemodule', 'samplemodule.checkstatus','samplemodule.client']
sbiModules = ['anothermodule']
setup(  name="TestApp",version="1.62",
        scripts=["TestAppMain.py"],
        description="Test App",
        author="Dakila Reyes II",
        author_email="dareyes at up.edu.ph",
        url="http://whatever_put_url_here.com/",
        packages= sbiGui + sbiModules,
        data_files=[('BMP',['BMP/ARW01DN.BMP','BMP/ARW01LT.BMP','BMP/ARW01RT.BMP
','BMP/ARW01UP.BMP','BMP/logo.bmp'])],
        )

create a setup.cfg also

[py2exe]
version-companyname=Dax Reyes Solutions
version-legalcopyright=Dax Reyes
version-filedescription = TestApp Modules
version-fileversion = 1.0.0.1
version-legaltrademarks = Blah blah blah.
version-productname = TestApp
version-productversion = 1.1.1.0

Then after that
go to the current directory where TestAppMain.py and setup.py reside.
Then run
c:\your_python_install_dir\python setup.py py2exe -w -O2

This will create a subdirectory dist\TestApp that contains the exe.

*Note Check the -O2 flag, not sure what will be the side effects to your app.

Hope this helps. 

If you need to also package it into a nice simple installer. I might
be able to help.

Regards,

On 9/5/05, Jack Anema <JAnema2 at mts.net> wrote:
>  
> Can you or someone give me very specific instructions as to how to create an
>      _.EXE      file from a       _.PY      file.
> 
> I have spent a lot of time looking through all 7 sections of FAQ's at    
> http://www.python.org/doc/faq/    and many other sights.
> 
> I have also gone to    
> http://starship.python.net/crew/theller/py2exe/      and
> tried to use the general comments there.
> 
> I did download and install     *win-py2.4.exe .    This installed
> successfully as far as I can see.  There were no error messages and       
> REMOVEPY2EXE.EXE      was created in my      PYTHON24     folder.
> 
> The machine I am running, is running    XP professional, 2002.  It has a
> Pentiuum(R) 4, 1.8 Ghz CPU.  The drive has 37 GB free.
> 
> I am by no means a computer expert but I am not illiterate either.  I have
> used MS Quick Basic for many years.  In the past I have also used APL and
> Fortran on various machines over the years.  I just am not familiar enough
> with Python and have not been able to find the detailed data I need to do
> what I want.  Up to a month ago I had never heard of Python and I badly need
> the ability to make      *.PY     programs files run as     *.EXE           
> files.
> 
> Can you or someone supply the very specific instructions to do this?  I
> would also be perfectly willing to arrange with someone to call them at
> their convenience and do it over the phone and compensate the person for
> their effort and time.
> 
> I sincerely and very much appreciate anyone's response and help!  Thank you!
> Jack Anema.
> 
>  
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
>

From shitizb at yahoo.com  Wed Sep  7 04:25:50 2005
From: shitizb at yahoo.com (Shitiz Bansal)
Date: Tue, 6 Sep 2005 19:25:50 -0700 (PDT)
Subject: [Tutor] smtp error
Message-ID: <20050907022550.97280.qmail@web53801.mail.yahoo.com>

does this error make sense to anyone?

Traceback (most recent call last):
  File "C:/Documents and
Settings/Administrator/Desktop/lkp.py", line 46, in
-toplevel-
    s.sendmail(msg['From'], i, msg.as_string())
  File "C:\Python24\lib\smtplib.py", line 692, in
sendmail
    raise SMTPDataError(code, resp)
SMTPDataError: (550, 'Invalid recipient:
shitizb at yahoo.com')



heres the complete code:
# Import smtplib for the actual sending function
import smtplib

# Here are the email pacakge modules we'll need
import base64
import cStringIO
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
COMMASPACE = ', '
import email
# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject']=raw_input("Subject:") 
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] =raw_input("From:")
kk = raw_input("To filename:")
# Guarantees the message ends in a newline
msg.epilogue = ''
file1=raw_input("text measage file:")
fp = open(file1, 'rb')
img = MIMEText(fp.read())
fp.close()
msg.attach(img)
file=raw_input("File to attach:")
fp = open(file, 'rb')
contentType="application/octet-stream"
contentsEncoded=cStringIO.StringIO()
mainType=contentType[:contentType.find("/")]
cte="base64"
base64.encode(fp,contentsEncoded)
subMsg=email.Message.Message()
subMsg.add_header("Content-transfer-encoding",cte)
subMsg.set_payload(contentsEncoded.getvalue())
contentsEncoded.close()

fp.close()
msg.attach(subMsg)
fp=open(kk,'r')
# Send the email via our own SMTP server.
mailadds=fp.readlines()
for i in mailadds:
    msg['To']=i
    s = smtplib.SMTP()
    s.connect()
    s.sendmail(msg['From'], i, msg.as_string())
    s.close()




	
		
______________________________________________________
Click here to donate to the Hurricane Katrina relief effort.
http://store.yahoo.com/redcross-donate3/

From kent37 at tds.net  Wed Sep  7 05:24:12 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Sep 2005 23:24:12 -0400
Subject: [Tutor] how to create a generic instance of an object?
In-Reply-To: <95FDCB82EFF3B9449865BF7D55FD2FF77BD74B@radmail.radical.ca>
References: <95FDCB82EFF3B9449865BF7D55FD2FF77BD74B@radmail.radical.ca>
Message-ID: <431E5D5C.7070406@tds.net>

John Burk wrote:
> I've got a base class "Asset", and currently have about 20 sub-classes
> (assetTypes) that will inherit from it, with more to follow, I'm sure.
> All of the assetTypes will have the same methods, but they'll be
> polymorphic; each assetType's methodA() will do something slightly
> different from it's sibling assetTypes.
> 
> What I want to do is to pass in the assetType at runTime via an external
> script, create a new instance of it, and then run that instance's
> methods.  That way I won't have to have 20 or more " if assetType== "
> if/elif statements, and maintaining the script that creates new
> instances won't become a nightmare.
> 
> I've tried something like this:
> 
> <asset.py>
> class Asset: pass
> 
> <foo.py>
> class Foo(Asset): pass
> 
> <script.py>
> from asset import Asset
> from foo import Foo
> 
> klass = 'Foo'
> o = klass()
> 
> which gets me 'string not callable', which is kind of expected.

Try 
  klass = globals()['Foo']
  o = klass()

Alternately you could import all the Asset classes into a module with

<assets.py>
from asset import Asset
from foo import Foo
etc

then in your main script use
import assets
klass = getattr(assets, 'Foo')
o = klass()

Then the main script doesn't need to know any of the details of which asset types are defined.

Kent


From bgailer at alum.rpi.edu  Wed Sep  7 05:43:27 2005
From: bgailer at alum.rpi.edu (bob)
Date: Tue, 06 Sep 2005 20:43:27 -0700
Subject: [Tutor] Combining dictionaries
In-Reply-To: <Pine.NEB.4.63.0509061600260.2610@S.Culver.Net>
References: <Pine.LNX.4.44.0509061357300.32279-100000@hkn.eecs.berkeley.edu>
	<Pine.NEB.4.63.0509061600260.2610@S.Culver.Net>
Message-ID: <6.1.2.0.0.20050906182819.032e65a8@mail.mric.net>

At 04:14 PM 9/6/2005, Mike Cheponis wrote:
>On Tue, 6 Sep 2005, Danny Yoo wrote:[snip]
>
>How can I actively help fix these Python bugs?

I am concerned when you use the term "bugs". The behaviors you describe are 
part of the design of Python, and they work as designed. To me a bug is a 
failure of something to work as designed.

<dig> Microsoft has much more practice designing things that don't work as 
designed than the Python development team. </dig> Even as I attempt to type 
this I am reminded that Eudora also has a lot of experience delivering 
buggy (or at least user-unfriendly) software.

How to influence the evolution of Python?

0 - subclass things that you wish behaved the way you want, then write 
magic methods e.g. __add__ and __radd__ to provide new behavior for +.

1 - develop modules that add features. Promote them thru sourceforge or 
Useless Python or the Vaults of Parnassus or the Python Cookbook, and 
certainly thru this e-mail list.

2 - write PEPs. See http://www.python.org/peps/ for the PEPs written to 
date. Someplace there's a PEP writing guideline, but I don't know where. 
Some PEPs make it into the language. 


From dyoo at hkn.eecs.berkeley.edu  Wed Sep  7 07:26:41 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 6 Sep 2005 22:26:41 -0700 (PDT)
Subject: [Tutor] Literal string concatenation (Was: Re: Combining
	dictionaries)
In-Reply-To: <6.1.2.0.0.20050906182819.032e65a8@mail.mric.net>
Message-ID: <Pine.LNX.4.44.0509062151230.24359-100000@hkn.eecs.berkeley.edu>



On Tue, 6 Sep 2005, bob wrote:

> At 04:14 PM 9/6/2005, Mike Cheponis wrote:
> >On Tue, 6 Sep 2005, Danny Yoo wrote:[snip]
> >
> >How can I actively help fix these Python bugs?
>
> I am concerned when you use the term "bugs". The behaviors you describe
> are part of the design of Python, and they work as designed. To me a bug
> is a failure of something to work as designed.

Hi Bob,

This is one of those fuzzy boundary conditions, though.  It's not
technically a bug, but people mistake what it's meant for so much that I
consider it a Python wart.

Here's a small sample of people misusing or misunderstanding literal
string concatenation:

    http://mail.python.org/pipermail/python-list/2002-May/106643.html
    http://mail.python.org/pipermail/tutor/2003-December/027170.html
    http://mail.python.org/pipermail/python-list/2005-April/277513.html

Granted, people sometimes make mistakes because they're just doing random
stuff.

The last one post, though, makes it very clear that the person has seen
examples of literal string concatenation before, and is naturally trying
to generalize the conceptual pattern.  That is, given previous experience,
the beginner is trying to integrate the idea with the rest of that
knowledge, and to much surprise, it doesn't work.

I can't blind myself and say that it's the beginner's fault for not
reading the reference manual.  Implicit literal string concatenation is
just one of those non-integrating special cases that smells kludgy. It
doesn't really help one learn the rest of the language, and I assert that
it causes problems, for both beginners and professionals. I too have made
the mistake of doing something like this in my own programs:

    ['this', 'is'
     'a', 'list',
     'of', 'strings']

Here, a comma (or a missing one!) makes a big difference.  If I make this
mistake, to keep my dignity and ego, I have to convince myself that other
people can make the same error.  *grin*


I don't harbor any illusions about getting this "fixed": it's part of the
way Python's grammar works, and it's not going away anytime soon.  But
it's something I do feel sad about.

Talk to you later!


From dyoo at hkn.eecs.berkeley.edu  Wed Sep  7 07:39:28 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 6 Sep 2005 22:39:28 -0700 (PDT)
Subject: [Tutor] smtp error
In-Reply-To: <20050907022550.97280.qmail@web53801.mail.yahoo.com>
Message-ID: <Pine.LNX.4.44.0509062227550.24359-100000@hkn.eecs.berkeley.edu>



On Tue, 6 Sep 2005, Shitiz Bansal wrote:

> does this error make sense to anyone?
>
> Traceback (most recent call last):
>   File "C:/Documents and
> Settings/Administrator/Desktop/lkp.py", line 46, in
> -toplevel-
>     s.sendmail(msg['From'], i, msg.as_string())
>   File "C:\Python24\lib\smtplib.py", line 692, in
> sendmail
>     raise SMTPDataError(code, resp)
> SMTPDataError: (550, 'Invalid recipient:
> shitizb at yahoo.com')

Hello,

According to:

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

the second argument to 's.sendmail()' needs to be a list, even if it is a
list of a single element.  I'm not positive that this is the bug, but it's
a possible error.  The code also mentions that it's talking to your local
SMTP mail server.  Is that right?

Otherwise, I'm not quite sure yet.  Try turning on smtplib's debug mode by
doing:

    s.set_debuglevel(1)

and try again: it should spit out more debugging information to help us
see what's going on.


Good luck!


From pierre.barbier at cirad.fr  Tue Sep  6 22:43:27 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Tue, 06 Sep 2005 22:43:27 +0200
Subject: [Tutor] threading problem in GUI
In-Reply-To: <431DE8BC.2060607@xit.net>
References: <431DAEEF.9090209@xit.net> <431DB67F.9060601@cirad.fr>
	<431DC69D.2070501@xit.net> <431DCC5D.4090108@cirad.fr>
	<431DE8BC.2060607@xit.net>
Message-ID: <431DFF6F.9070404@cirad.fr>

Ok, comments inside your code ...

nephish a ?crit :
> Pierre Barbier de Reuille wrote:
> 
>> nephish a ?crit :
>>  
>>
>>> Pierre Barbier de Reuille wrote:
>>>
>>> [...]
>>> ok, i am still having a little problem understanding.
>>> tried it but i don't know if i have things set in the right order.
>>>
>>>
>>> gtk.gdk.threads_init()
>>> # Here initialize what you want
>>> [...]
>>> # Launch the Gtk loop
>>> gtk.gdk.threads_enter() # Unneeded if you don't want to call GUI
>>>                       # functions from other threads
>>> gtk.main()
>>> gtk.gdk.threads_leave() # Needed only with threads_enter
>>>
>>> at the part where you wrote # Here initialize what you want
>>> [...]
>>> is that where i define the function that will run the thread?
>>>
>>> i get the part about having the enter and leave
>>> i just seem to have a hang up (so to speak) with where the function gets
>>> defined.
>>> do i need to build it as a class like the example in the link you sent?
>>>   
>>
>>
>> Well, no you don't need to create a class.
>>
>> As for the place where to put your function, it's not a problem, [...]
>> is the place where you will *execute* some initialization code (if
>> needed) before you launch your interface. That's all (typically that's
>> where you will instanciate your widgets).
>>
>>  
>>
>>> thanks for your help on this
>>>
>>>   
>>
>> Your welcome,
>>
>> Pierre
>>
>>  
>>
> ok, i am still kinda stuck.
> im posting what i think is necessary, because the whole thing is rather
> long.
> so here goes.
> 
> #!/usr/bin/python
> 
> import os
> import time
> from time import strftime
> 
> import sys
> import gtk
> import pygtk
> import serial
> import threading
> from threading import Thread
> import tokenize
> import gtk.glade
> import weakref
> import inspect
> import re
> 
> 
> gtk.gdk.threads_init()
> 
> def main(self):
>        gtk.gdk.threads_enter()
>        gtk.main()
>        gtk.gdk.threads_leave()
> 
> def on_StartEnginesButton_clicked(self, widget, *args):
>        print "on_StartEnginesButton_clicked called with self.%s" %
> widget.get_name()
>        Input1Iter = self.Input1Buffer.get_end_iter()
>        Input2Iter = self.Input2Buffer.get_end_iter()
>        Input1Data = 'Reading Serial device ttyS14 \n'
>        Input2Data = 'Reading Serial device ttys15 \n'
>        self.Input1Buffer.insert(Input1Iter, Input1Data)
>        self.Input2Buffer.insert(Input2Iter, Input2Data)             
> time.sleep(2)
>        def Serial1():                  print 'running serial 1'
>            ser = serial.Serial('/dev/ttyS15', 2400, timeout=None)
>            loopy = 1
>            i = 1
>            while loopy < 5:                              for x in range(5):
>                    i = i + 1                                      a =
> ser.read(1)#read one byte                          a = ord(a) # change
> byte to integer
>                    if (a < 64 )or (a > 127):
>                        break                        b = ser.read(1)
>                    b = ord(b)
>                    if (b < 64 )or (b > 127):
>                        break
>                    c = ser.read(1)
>                    c = ord(c)
>                    if c < 92:
>                        break
>                    d = ser.read(1)
>                    d = ord(d)
>                    if d < 128:
>                        break
>                    Sensor_ID = (a & 63) + (b & 63) * 64 + (c & 1) * 4096
>                    Status = (c & 62) / 2 + (d & 63) * 32
>                    c = int(c)
>                    d = int(d)
>                    x_Now = strftime('%Y-%m-%d %H:%M:%S')     
>                    gtk.threads_enter()
>                    Input1Data =
> str(Sensor_ID)+'\t'+str(Status)+'\t--------->\t'+x_Now+'\n'
>                    Input1Iter = self.Input1Buffer.get_end_iter()
>                    self.Input1Buffer.insert(Input1Iter, Input1Data)
>                    gtk.threads_leave()
>                    f = open('/home/piv/PivData/tmp/Serial/'+str(i), 'w')
>                   
> f.write(str(Sensor_ID)+'\n'+str(c)+'\n'+str(d)+'\n'+str(Status)+'\n'+x_Now)      
> 
>                    f.close()
>        Thread.start(Serial1())

hehehe ... got it !

Serial1() just call the function ... it will be evaluated and then the
result will be sent to Thread.start ...

So try:

Thread.start(Serial)

> 
> thanks, i am learning from several sources. two books from O'Reilly, and
> a dozen or so websites,
> not everybody does everything the same way . if something here looks
> alarming, please let me know.
> 
> thanks
> 

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68


From kent37 at tds.net  Wed Sep  7 11:49:46 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Sep 2005 05:49:46 -0400
Subject: [Tutor] smtp error
In-Reply-To: <Pine.LNX.4.44.0509062227550.24359-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509062227550.24359-100000@hkn.eecs.berkeley.edu>
Message-ID: <431EB7BA.2040402@tds.net>

Danny Yoo wrote:
> According to:
> 
>     http://www.python.org/doc/lib/SMTP-objects.html
> 
> the second argument to 's.sendmail()' needs to be a list, even if it is a
> list of a single element.  I'm not positive that this is the bug, but it's
> a possible error.

The docs are incorrect and the latest version has been fixed - you can pass a single string to sendmail().
http://www.python.org/dev/doc/devel/lib/SMTP-objects.html

Kent


From kent37 at tds.net  Wed Sep  7 12:04:01 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Sep 2005 06:04:01 -0400
Subject: [Tutor] smtp error
In-Reply-To: <20050907022550.97280.qmail@web53801.mail.yahoo.com>
References: <20050907022550.97280.qmail@web53801.mail.yahoo.com>
Message-ID: <431EBB11.4010402@tds.net>

Shitiz Bansal wrote:
> does this error make sense to anyone?
> 
> Traceback (most recent call last):
>   File "C:/Documents and
> Settings/Administrator/Desktop/lkp.py", line 46, in
> -toplevel-
>     s.sendmail(msg['From'], i, msg.as_string())
>   File "C:\Python24\lib\smtplib.py", line 692, in
> sendmail
>     raise SMTPDataError(code, resp)
> SMTPDataError: (550, 'Invalid recipient:
> shitizb at yahoo.com')

The error message is coming from your SMTP server, not from Python. Maybe the server is not correctly configured to forward mail to external addresses?

Kent


From kim.d at tesco.net  Wed Sep  7 12:50:31 2005
From: kim.d at tesco.net (kim.d@tesco.net)
Date: Wed, 7 Sep 2005 10:50:31 +0000
Subject: [Tutor] Making Applets
Message-ID: <20050907105033.PXMP267.aamta03-winn.mailhost.ntl.com@smtp.tesco.net>

I am a complete beginner with Python, so apologies if this is a silly question 
with an obvious answer.

I am using Python on an Apple running 10.3, and write scripts as text 
documents which I then call from the Terminal. I am told that the scripts can 
be made into applets and that documents can be dragged and dropped onto 
them.

Is this the case? How do I do this?


From ml.cyresse at gmail.com  Wed Sep  7 13:34:33 2005
From: ml.cyresse at gmail.com (mailing list)
Date: Wed, 7 Sep 2005 23:34:33 +1200
Subject: [Tutor] OT - email & imaplib modules
Message-ID: <b6f3249e050907043444545284@mail.gmail.com>

Hi all, 

Just musing. 

Even though I'm familiar with imaplib & IMAP, and most of the email
modules, I still find them somewhat... obtuse to work with.

The IMAP protocol is rather exposed in imaplib, and you have to read
RFCs and fiddle to sort the format required for IMAP commands.

For an example, I asked an acquaintance who's overjoyed at finding
Ruby after working in PHP to show me how Ruby handled IMAP.

Here's a Ruby line/Python line breakdown of how they compare.

imap = Net::IMAP.new('mail.example.com')
imap = imaplib.IMAP4('mail.example.com')

imap.authenticate('LOGIN', 'joe_user', 'joes_password') 
imap.login('joe_user', 'joes_password')

imap.select('INBOX') #switch to the inbox
imap.select() #In Python it defaults to INBOX

imap.search(["FROM","person at diddlywink.com"]).each do |message_id| #for each
for message_id in imap.search(None, '(FROM
"person at diddlywink.com")')[1][0].split(" "):

response = imap.fetch(message_id, "RFC822.TEXT") #fetch the text
response = imap.fetch(message_ID, "RFC822.TEXT")

puts response.attr['RFC822.TEXT'] #print the text
print response[1][0][1] #print the text

imap.store(message_id, "+FLAGS", [:Deleted]) #flag to delete
imap.store(message_id, "+FLAGS", "\Deleted")

end
#No Python equivalent

imap.close #close mailbox, delete all flagged as delete as well (no
need to imap.expunge)
imap.close()

imap.disconnect #close session
imap.logout()

I also find the nesting horrible to deal with. An imap fetch will
return a tuple, where the last item is ')'. I know that this line  -
for message_id in imap.search(None, '(FROM
"person at diddlywink.com")')[1][0].split(" ")

isn't the clearest way to do it, but I was going for line for line. :)

The email.Message object is also quite complex to learn.

Now, I'm aware the both modules allow you to do incredibly complex
things. But I'm of the opinion that simple things should be.

I'm not sure what's being worked on for Py3K, but I really hope
imaplib and email are.

Would adding a layer over each to simplify things be bad or good? For
instance, instead of IMAP using and returning IMAP specific strings,
why not do stuff like imap.search("FROM", "x at y.com") and then let the
object handle the brackets and quotes etc, and accept ranges of
messages as a list, and why not have ranges returned as something
iterable?

Ditto with email.Message, how about methods to access email parts, as
per the various RFC's? So calling msg.attachments() lists all
attachments, or msg.format() shows what formatting the email is (text,
RTF, HTML) , or msg.body() returns the BODY/TEXT portion?

It's like Pythoncard, a layer of abstraction makes 90% of what you do
easier, and the other 10% you can still do the manual way.

I don't know, I'm also tempted to try and write those layers, if
anyone would benefit from them. But yeah, would it be better or worse
for people to not have to learn the niceties of RFC3501 formal syntax
section to use imap?

/end idle ponderings

Regards, 

Liam Clarke

From kent37 at tds.net  Wed Sep  7 13:43:27 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Sep 2005 07:43:27 -0400
Subject: [Tutor] [Fwd: py2exe 0.6.1 released]
Message-ID: <431ED25F.8040602@tds.net>

I thought this announcement might be of interest here since a frequent question on the list is "How can I build a single-file exe from my Python program?" and until now the answer has been, "You can't."

Kent

-------- Original Message --------
Subject: py2exe 0.6.1 released
Date: Mon, 05 Sep 2005 21:55:19 +0200
From: Thomas Heller <theller at python.net>
To: python-list at python.org
Newsgroups: comp.lang.python


py2exe 0.6.1 released
=====================

py2exe is a Python distutils extension which converts python scripts
into executable windows programs, able to run without requiring a
python installation.  Console and Windows (GUI) applications, windows
NT services, exe and dll COM servers are supported.

Changes in this release:

    * py2exe can now bundle binary extensions and dlls into the
      library-archive or the executable itself.  This allows to
      finally build real single-file executables.

      The bundled dlls and pyds are loaded at runtime by some special
      code that emulates the Windows LoadLibrary function - they are
      never unpacked to the file system.

      This part of the code is distributed under the MPL 1.1, so this
      license is now pulled in by py2exe.
      
    * By default py2exe now includes the codecs module and the
      encodings package.
      
    * Several other fixes.

Homepage:

    <http://starship.python.net/crew/theller/py2exe>

Download from the usual location:

    <http://sourceforge.net/project/showfiles.php?group_id=15583>

Enjoy,

Thomas



From nephish at xit.net  Wed Sep  7 16:52:34 2005
From: nephish at xit.net (nephish)
Date: Wed, 07 Sep 2005 09:52:34 -0500
Subject: [Tutor] [tutor] threading problem in GUI
Message-ID: <431EFEB2.3030308@xit.net>



	Serial1() just call the function ... it will be evaluated and then the
	result will be sent to Thread.start ...

	So try:

	Thread.start(Serial)


ok,
so far the thread runs fine in the background, but just does not send the output to the 
textbuffer, and hangs up the rest of the show.

i think i am off in how i have the gtk.main() set up
and how the main class is set up

class SimpleGladeApp:
    def __init__(self, path, root=None, domain=None, **kwargs):        
        if os.path.isfile(path):
            self.glade_path = path
        else:
            glade_dir = os.path.dirname( sys.argv[0] )
            self.glade_path = os.path.join(glade_dir, path)
        for key, value in kwargs.items():
            try:
                setattr(self, key, weakref.proxy(value) )
            except TypeError:
                setattr(self, key, value)
        self.glade = None
        self.install_custom_handler(self.custom_handler)
        self.glade = self.create_glade(self.glade_path, root, domain)
        if root:
            self.main_widget = self.get_widget(root)
        else:
            self.main_widget = None
        self.normalize_names()
        self.add_callbacks(self)
        self.new()
	
    def main(self):
        gtk.gdk.threads_enter()
        gtk.main()
        gtk.gdk.threads_leave() 

class Main(SimpleGladeApp):
    def __init__(self, path="pivcontrolcenter.glade",
                 root="Main",
                 domain=app_name, **kwargs):
        path = os.path.join(glade_dir, path)
        SimpleGladeApp.__init__(self, path, root, domain, **kwargs)

    def on_StartEnginesButton_clicked(self, widget, *args):
        print "on_StartEnginesButton_clicked called with self.%s" % widget.get_name()        
        Input1Iter = self.Input1Buffer.get_end_iter()
        Input2Iter = self.Input2Buffer.get_end_iter()
        Input1Data = 'Reading Serial device ttyS14 \n'
        Input2Data = 'Reading Serial device ttys15 \n'
        self.Input1Buffer.insert(Input1Iter, Input1Data)
        self.Input2Buffer.insert(Input2Iter, Input2Data)        
        time.sleep(1)
        def Serial1():            
            print 'running serial 1'            
            ser = serial.Serial('/dev/ttyS15', 2400, timeout=None)
            loopy = 1
            i = 1
            while loopy < 5:                
                for x in range(5):                    
                    i = i + 1                    
                    a = ser.read(1)#read one byte        
                    a = ord(a) # change byte to integer
                    if (a < 64 )or (a > 127):
                        break                    
                    b = ser.read(1)
                    b = ord(b)
                    if (b < 64 )or (b > 127):
                        break
                    c = ser.read(1)
                    c = ord(c)
                    if c < 92:
                        break                    
                    d = ser.read(1)
                    d = ord(d)
                    if d < 128:
                        break
                    Sensor_ID = (a & 63) + (b & 63) * 64 + (c & 1) * 4096
                    Status = (c & 62) / 2 + (d & 63) * 32
                    c = int(c)
                    d = int(d)
                    x_Now = strftime('%Y-%m-%d %H:%M:%S')                   
                    #gtk.threads_enter()                    
                    Input1Data = str(Sensor_ID)+'\t'+str(Status)+'\t--------->\t'+x_Now+'\n'
                    Input1Iter = self.Input1Buffer.get_end_iter()
                    self.Input1Buffer.insert(Input1Iter, Input1Data)
                    #gtk.threads_leave()                    
                    f = open('/home/piv/PivData/tmp/Serial/'+str(i), 'w')
                    f.write(str(Sensor_ID)+'\n'+str(c)+'\n'+str(d)+'\n'+str(Status)+'\n'+x_Now)       
                    f.close()        
        Thread.start(Serial1())

def main():
    main = Main()
    #gtk.threads_enter()
    main.run()
    #gtk.threads_leave()

if __name__ == "__main__": 
    #gtk.threads_enter()   
    main()
    #gtk.threads_leave() 

lots of comments, been trying this several ways.

cheers
shawn 






From nephish at xit.net  Wed Sep  7 16:59:54 2005
From: nephish at xit.net (nephish)
Date: Wed, 07 Sep 2005 09:59:54 -0500
Subject: [Tutor] [tutor] threading problem in GUI
In-Reply-To: <431EFEB2.3030308@xit.net>
References: <431EFEB2.3030308@xit.net>
Message-ID: <431F006A.6000802@xit.net>

nephish wrote:

>	Serial1() just call the function ... it will be evaluated and then the
>	result will be sent to Thread.start ...
>
>	So try:
>
>	Thread.start(Serial)
>
>
>ok,
>so far the thread runs fine in the background, but just does not send the output to the 
>textbuffer, and hangs up the rest of the show.
>
>i think i am off in how i have the gtk.main() set up
>and how the main class is set up
>
>class SimpleGladeApp:
>    def __init__(self, path, root=None, domain=None, **kwargs):        
>        if os.path.isfile(path):
>            self.glade_path = path
>        else:
>            glade_dir = os.path.dirname( sys.argv[0] )
>            self.glade_path = os.path.join(glade_dir, path)
>        for key, value in kwargs.items():
>            try:
>                setattr(self, key, weakref.proxy(value) )
>            except TypeError:
>                setattr(self, key, value)
>        self.glade = None
>        self.install_custom_handler(self.custom_handler)
>        self.glade = self.create_glade(self.glade_path, root, domain)
>        if root:
>            self.main_widget = self.get_widget(root)
>        else:
>            self.main_widget = None
>        self.normalize_names()
>        self.add_callbacks(self)
>        self.new()
>	
>    def main(self):
>        gtk.gdk.threads_enter()
>        gtk.main()
>        gtk.gdk.threads_leave() 
>
>class Main(SimpleGladeApp):
>    def __init__(self, path="pivcontrolcenter.glade",
>                 root="Main",
>                 domain=app_name, **kwargs):
>        path = os.path.join(glade_dir, path)
>        SimpleGladeApp.__init__(self, path, root, domain, **kwargs)
>
>    def on_StartEnginesButton_clicked(self, widget, *args):
>        print "on_StartEnginesButton_clicked called with self.%s" % widget.get_name()        
>        Input1Iter = self.Input1Buffer.get_end_iter()
>        Input2Iter = self.Input2Buffer.get_end_iter()
>        Input1Data = 'Reading Serial device ttyS14 \n'
>        Input2Data = 'Reading Serial device ttys15 \n'
>        self.Input1Buffer.insert(Input1Iter, Input1Data)
>        self.Input2Buffer.insert(Input2Iter, Input2Data)        
>        time.sleep(1)
>        def Serial1():            
>            print 'running serial 1'            
>            ser = serial.Serial('/dev/ttyS15', 2400, timeout=None)
>            loopy = 1
>            i = 1
>            while loopy < 5:                
>                for x in range(5):                    
>                    i = i + 1                    
>                    a = ser.read(1)#read one byte        
>                    a = ord(a) # change byte to integer
>                    if (a < 64 )or (a > 127):
>                        break                    
>                    b = ser.read(1)
>                    b = ord(b)
>                    if (b < 64 )or (b > 127):
>                        break
>                    c = ser.read(1)
>                    c = ord(c)
>                    if c < 92:
>                        break                    
>                    d = ser.read(1)
>                    d = ord(d)
>                    if d < 128:
>                        break
>                    Sensor_ID = (a & 63) + (b & 63) * 64 + (c & 1) * 4096
>                    Status = (c & 62) / 2 + (d & 63) * 32
>                    c = int(c)
>                    d = int(d)
>                    x_Now = strftime('%Y-%m-%d %H:%M:%S')                   
>                    #gtk.threads_enter()                    
>                    Input1Data = str(Sensor_ID)+'\t'+str(Status)+'\t--------->\t'+x_Now+'\n'
>                    Input1Iter = self.Input1Buffer.get_end_iter()
>                    self.Input1Buffer.insert(Input1Iter, Input1Data)
>                    #gtk.threads_leave()                    
>                    f = open('/home/piv/PivData/tmp/Serial/'+str(i), 'w')
>                    f.write(str(Sensor_ID)+'\n'+str(c)+'\n'+str(d)+'\n'+str(Status)+'\n'+x_Now)       
>                    f.close()        
>        Thread.start(Serial1())
>
>def main():
>    main = Main()
>    #gtk.threads_enter()
>    main.run()
>    #gtk.threads_leave()
>
>if __name__ == "__main__": 
>    #gtk.threads_enter()   
>    main()
>    #gtk.threads_leave() 
>
>lots of comments, been trying this several ways.
>
>cheers
>shawn 
>
>
>
>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
one more thing.
if i uncomment the lines
gtk.threads_enter()
and
gtk.threads_leave()
the whole thing locks up when the function is called.
the gui, and the thread both lock up.

thanks

From pierre.barbier at cirad.fr  Wed Sep  7 18:21:34 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Wed, 07 Sep 2005 18:21:34 +0200
Subject: [Tutor] [tutor] threading problem in GUI
In-Reply-To: <431F006A.6000802@xit.net>
References: <431EFEB2.3030308@xit.net> <431F006A.6000802@xit.net>
Message-ID: <431F138E.9090709@cirad.fr>

nephish a ?crit :
> 
> one more thing.
> if i uncomment the lines
> gtk.threads_enter()
> and
> gtk.threads_leave()
> the whole thing locks up when the function is called.
> the gui, and the thread both lock up.

Well, that's just normal. However, what you should do is to send a
signal from your thread with the text to append in your textbuffer.
Then, you catch the signal in your main widget to show it !

To emit a signal use :

    gtk.gdk.threads_enter()
    self.emit("writing", str)
    gtk.gdk.threads_leave()

To catch it:


    emitting_object.connect("writing", self.method_handling_to_signal)

Well, I used that and it just work ! Using the signal does not solve any
threading problem but allow you to separate between the event and the
answer to the event, which is a good habit to take !

Pierre


-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68

From nephish at xit.net  Wed Sep  7 18:32:21 2005
From: nephish at xit.net (nephish)
Date: Wed, 07 Sep 2005 11:32:21 -0500
Subject: [Tutor] [tutor] threading problem in GUI
In-Reply-To: <431F138E.9090709@cirad.fr>
References: <431EFEB2.3030308@xit.net> <431F006A.6000802@xit.net>
	<431F138E.9090709@cirad.fr>
Message-ID: <431F1615.3010905@xit.net>

Pierre Barbier de Reuille wrote:

>nephish a ?crit :
>  
>
>>one more thing.
>>if i uncomment the lines
>>gtk.threads_enter()
>>and
>>gtk.threads_leave()
>>the whole thing locks up when the function is called.
>>the gui, and the thread both lock up.
>>    
>>
>
>Well, that's just normal. However, what you should do is to send a
>signal from your thread with the text to append in your textbuffer.
>Then, you catch the signal in your main widget to show it !
>
>To emit a signal use :
>
>    gtk.gdk.threads_enter()
>    self.emit("writing", str)
>    gtk.gdk.threads_leave()
>
>To catch it:
>
>
>    emitting_object.connect("writing", self.method_handling_to_signal)
>
>Well, I used that and it just work ! Using the signal does not solve any
>threading problem but allow you to separate between the event and the
>answer to the event, which is a good habit to take !
>
>Pierre
>
>
>  
>
cool, will try.
where exactly do i put this line? Just right in the main loop?

emitting_object.connect("writing", self.method_handling_to_signal)


thanks !

From bgailer at alum.rpi.edu  Wed Sep  7 19:10:55 2005
From: bgailer at alum.rpi.edu (bob)
Date: Wed, 07 Sep 2005 10:10:55 -0700
Subject: [Tutor] Combining dictionaries
In-Reply-To: <Pine.NEB.4.63.0509062150090.2610@S.Culver.Net>
References: <Pine.LNX.4.44.0509061357300.32279-100000@hkn.eecs.berkeley.edu>
	<Pine.NEB.4.63.0509061600260.2610@S.Culver.Net>
	<6.1.2.0.0.20050906182819.032e65a8@mail.mric.net>
	<Pine.NEB.4.63.0509062150090.2610@S.Culver.Net>
Message-ID: <6.1.2.0.0.20050907082921.032f1b70@mail.mric.net>

I enjoy "philosophical" discussions like this. To help us have common 
terminology I present some quotes from dictionary.com:

---------------------------------------------------------------
bug:

An unwanted and unintended property of a program or piece of hardware, 
especially one that causes it to malfunction. Antonym of feature.

---------------------------------------------------------------
feature:

An intended property or behaviour (as of a program). Whether it is good or 
not is immaterial (but if bad, it is also a misfeature)

---------------------------------------------------------------
misfeature:

A feature that eventually causes lossage, possibly because it is not 
adequate for a new situation that has evolved. Since it results from a 
deliberate and properly implemented feature, a misfeature is not a bug. Nor 
is it a simple unforeseen side effect; the term implies that the feature in 
question was carefully planned, but its long-term consequences were not 
accurately or adequately predicted (which is quite different from not 
having thought ahead at all). A misfeature can be a particularly stubborn 
problem to resolve, because fixing it usually involves a substantial 
philosophical change to the structure of the system involved.

Many misfeatures (especially in user-interface design) arise because the 
designers/implementors mistake their personal tastes for laws of nature. 
Often a former feature becomes a misfeature because trade-offs were made 
whose parameters subsequently change (possibly only in the judgment of the 
implementors). "Well, yeah, it is kind of a misfeature that file names are 
limited to six characters, but the original implementors wanted to save 
directory space and we"re stuck with it for now."

-----end of definitions ----------------------------------

>Does not it seem odd that if a and b are dictionaries, c = a + b does not
>result in their union?

Given that the (relatively new) set type in Python, use boolean operators & 
and | for union and intersection, I'd prefer & to +.

>Does it not seem to violate the Principal of Least Astonishment to notice
>what print "spam " "eggs"*3 does?

Any language that imposes operator precedence will have unexpected 
outcomes. That is why I have always liked APL, which has no precedence. 
Strictly right-to-left evaluation with () to group operations in some other 
order.

>And, surely, you are not suggesting that Python 2.4 represents the zenith of
>programming language design?

I certainly hope not. I am merely asserting that there is a design that has 
evolved over 14 or so years, and that my ability to use a language depends 
on my learning it rather than expecting it to behave the way I want 
(expect) it to.

Having worked with APL I am always disappointed that Python does not have 
native array operations. I 'd like to write [1,2,3] + [2,4,6] and get 
[3,6,9], and +/[1,2,3] and get 6. Unfortunately Python does not work that way.

Having recently used Javascript I find it has features that make some 
aspects of programming easier than Python!

>Incidentally, I've been writing compilers and interpreters since 1968 and have
>an EECS degree from MIT, so I do have a clue.

I started studying formal language theory (on my own) in 1972, maintained 
the APL interpreter in 1975 and devised and helped implement my first 
language in 1976. My BSEE from RPI predates any CS departments.

Bob Gailer
phone 510 978 4454  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050907/ed9b8b1e/attachment.html

From ewalker at micron.com  Wed Sep  7 20:35:52 2005
From: ewalker at micron.com (Eric Walker)
Date: Wed, 7 Sep 2005 12:35:52 -0600
Subject: [Tutor] Combining dictionaries
In-Reply-To: <6.1.2.0.0.20050907082921.032f1b70@mail.mric.net>
References: <Pine.LNX.4.44.0509061357300.32279-100000@hkn.eecs.berkeley.edu>
	<Pine.NEB.4.63.0509062150090.2610@S.Culver.Net>
	<6.1.2.0.0.20050907082921.032f1b70@mail.mric.net>
Message-ID: <200509071235.52423.ewalker@micron.com>

On Wednesday 07 September 2005 11:10 am, bob wrote:
> I enjoy "philosophical" discussions like this. To help us have common
> terminology I present some quotes from dictionary.com:
>
> ---------------------------------------------------------------
> bug:
>
> An unwanted and unintended property of a program or piece of hardware,
> especially one that causes it to malfunction. Antonym of feature.
>
> ---------------------------------------------------------------
> feature:
>
> An intended property or behaviour (as of a program). Whether it is good or
> not is immaterial (but if bad, it is also a misfeature)
>
> ---------------------------------------------------------------
> misfeature:
>
> A feature that eventually causes lossage, possibly because it is not
> adequate for a new situation that has evolved. Since it results from a
> deliberate and properly implemented feature, a misfeature is not a bug. Nor
> is it a simple unforeseen side effect; the term implies that the feature in
> question was carefully planned, but its long-term consequences were not
> accurately or adequately predicted (which is quite different from not
> having thought ahead at all). A misfeature can be a particularly stubborn
> problem to resolve, because fixing it usually involves a substantial
> philosophical change to the structure of the system involved.
>
> Many misfeatures (especially in user-interface design) arise because the
> designers/implementors mistake their personal tastes for laws of nature.
> Often a former feature becomes a misfeature because trade-offs were made
> whose parameters subsequently change (possibly only in the judgment of the
> implementors). "Well, yeah, it is kind of a misfeature that file names are
> limited to six characters, but the original implementors wanted to save
> directory space and we"re stuck with it for now."
>
> -----end of definitions ----------------------------------
>
> >Does not it seem odd that if a and b are dictionaries, c = a + b does not
> >result in their union?
>
> Given that the (relatively new) set type in Python, use boolean operators &
> and | for union and intersection, I'd prefer & to +.
>
> >Does it not seem to violate the Principal of Least Astonishment to notice
> >what print "spam " "eggs"*3 does?
>
> Any language that imposes operator precedence will have unexpected
> outcomes. That is why I have always liked APL, which has no precedence.
> Strictly right-to-left evaluation with () to group operations in some other
> order.
>
> >And, surely, you are not suggesting that Python 2.4 represents the zenith
> > of programming language design?
>
> I certainly hope not. I am merely asserting that there is a design that has
> evolved over 14 or so years, and that my ability to use a language depends
> on my learning it rather than expecting it to behave the way I want
> (expect) it to.
>
> Having worked with APL I am always disappointed that Python does not have
> native array operations. I 'd like to write [1,2,3] + [2,4,6] and get
> [3,6,9], and +/[1,2,3] and get 6. Unfortunately Python does not work that
> way.
>
> Having recently used Javascript I find it has features that make some
> aspects of programming easier than Python!
>
> >Incidentally, I've been writing compilers and interpreters since 1968 and
> > have an EECS degree from MIT, so I do have a clue.
>
> I started studying formal language theory (on my own) in 1972, maintained
> the APL interpreter in 1975 and devised and helped implement my first
> language in 1976. My BSEE from RPI predates any CS departments.
>
> Bob Gailer
> phone 510 978 4454


WOW!!,
Nice to know we have some heavy hitters monitoring this list.
-- 
Eric Walker
EDA/CAD Engineer
Work: 208-368-2573

From alan.gauld at freenet.co.uk  Wed Sep  7 21:59:37 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Wed, 7 Sep 2005 20:59:37 +0100
Subject: [Tutor] Making Applets
References: <20050907105033.PXMP267.aamta03-winn.mailhost.ntl.com@smtp.tesco.net>
Message-ID: <001f01c5b3e6$ad50c990$0201a8c0@xp>

> I am using Python on an Apple running 10.3, and write scripts as 
> text
> documents which I then call from the Terminal. I am told that the 
> scripts can
> be made into applets and that documents can be dragged and dropped 
> onto
> them.
>
> Is this the case? How do I do this?

Yes you can do it however although I have an iBook and occasionally 
write python
on it I've never done any Apple specific stuff.

I believe MacPython has links to the libraries for doing true applets 
and
also you can turn a regular python script into a pseudo applet by 
using
applescript

But thats all I know (and even that is hearsay!) so I suspect you need 
to
ask again on the MacPython programming list, they will know there what 
to
do I'm sure.

Sorry, but I suspect its just a tad too specialised a topic for the 
tutor list.

Alan G.
(Now someone will post the answer and prove me wrong - again! :-) 


From jburk at radical.ca  Wed Sep  7 22:02:16 2005
From: jburk at radical.ca (John Burk)
Date: Wed, 7 Sep 2005 13:02:16 -0700
Subject: [Tutor] how to create a generic instance of an object?
Message-ID: <95FDCB82EFF3B9449865BF7D55FD2FF79CDE33@radmail.radical.ca>



-----Original Message-----
From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu] 
Sent: Tuesday, September 06, 2005 6:55 PM
To: John Burk
Cc: tutor at python.org
Subject: Re: [Tutor] how to create a generic instance of an object?

Hi John,

It sounds like you're trying to do some kind of dynamic linking.  Python
has a builtin called "__import__" that can help: it allows us to do
module
import, given an arbitrary name.

Your example above might be written as:

#####################################################################
<asset.py>
class Asset: pass

<foo.py>
class Foo(Asset): pass

<script.py>

def dynamic_lookup(module_name, class_name):
    module_object = __import__(module_name)
    class_object = getattr(module_object, class_name)
    return class_object

klass = dynamic_lookup('foo', 'Foo')
o = klass()
#####################################################################

This can be easily abused.  *grin* But for what you're trying, it might
be
what you're looking for.  For more information on __import__, see:

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


Hope this helps!



And the winner is Danny Yoo, for the cleanest implementation.  Some of
my design goals for this class heirarchy were:

* end-users of the class heirarchy should be able to add new sub-classes
without modifying any of the other base or sub-classes.

* an exhaustive list of all sub-classes should be unneccesary

* likewise, any front-end script that uses this class shouldn't have a
long list of 'import' statements.

Danny's method helped me meet all these goals.  

The approach outlined above models the 'import <module>' behavior.  I'm
using a namespace to differentiate all our home-grown classes and
modules, and because I'm trying to model the 'from rad.<class> import
<Class>, my implementation looks like:

=============================================================
def dynamic_lookup(module_name, class_name):
    module_object = __import__(module_name, globals(), locals(),
[class_name])
    class_object = getattr(module_object, class_name)
    return class_object

aType = 'foo'
aName = 'bar'

klass = dynamic_lookup( 'rad.' + aType, aType.capitalize() )
o = klass(aName)
=============================================================

Thanks to all who replied.  

johnb

From nephish at xit.net  Wed Sep  7 22:09:20 2005
From: nephish at xit.net (nephish)
Date: Wed, 07 Sep 2005 15:09:20 -0500
Subject: [Tutor] [tutor] threading problem in GUI
In-Reply-To: <431F138E.9090709@cirad.fr>
References: <431EFEB2.3030308@xit.net> <431F006A.6000802@xit.net>
	<431F138E.9090709@cirad.fr>
Message-ID: <431F48F0.2000503@xit.net>

Pierre Barbier de Reuille wrote:

>nephish a ?crit :
>  
>
>>one more thing.
>>if i uncomment the lines
>>gtk.threads_enter()
>>and
>>gtk.threads_leave()
>>the whole thing locks up when the function is called.
>>the gui, and the thread both lock up.
>>    
>>
>
>Well, that's just normal. However, what you should do is to send a
>signal from your thread with the text to append in your textbuffer.
>Then, you catch the signal in your main widget to show it !
>
>To emit a signal use :
>
>    gtk.gdk.threads_enter()
>    self.emit("writing", str)
>    gtk.gdk.threads_leave()
>
>To catch it:
>
>
>    emitting_object.connect("writing", self.method_handling_to_signal)
>
>Well, I used that and it just work ! Using the signal does not solve any
>threading problem but allow you to separate between the event and the
>answer to the event, which is a good habit to take !
>
>Pierre
>
>
>  
>
I finally got it working !!
thanks so much for all your help
i would not have gotten it working without you,
(or this mailing list)

God bless
shawn

From pierre.barbier at cirad.fr  Thu Sep  8 09:43:14 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Thu, 08 Sep 2005 09:43:14 +0200
Subject: [Tutor] [tutor] threading problem in GUI
In-Reply-To: <431F48F0.2000503@xit.net>
References: <431EFEB2.3030308@xit.net> <431F006A.6000802@xit.net>
	<431F138E.9090709@cirad.fr> <431F48F0.2000503@xit.net>
Message-ID: <431FEB92.5000401@cirad.fr>

Great :)

Just to be clear about that: you can see the "connect" line as a dynamic
registration process (with the symetric disconnect operation available
via ... "disconnect"). The only thing you need is to connect (at
runtime) the even before it's called (obvious isn't it ? ;) ), but you
have no other constraint. You can even choose to connect/disconnect
events when they are used/unused ... You can also connect a single event
many times (to different functions) or you can connect many events to
the same function. This is the "power" of this system :) Like now if you
want to log your strings on a file, you just define the function writing
in the file and connect the event to this function: you'll have both the
GUI and the log-file outputs !

This is, AFAIK, the best existing implementation for user interfaces !

Pierre

nephish a ?crit :
> Pierre Barbier de Reuille wrote:
> 
>> nephish a ?crit :
>>  
>>
>>> one more thing.
>>> if i uncomment the lines
>>> gtk.threads_enter()
>>> and
>>> gtk.threads_leave()
>>> the whole thing locks up when the function is called.
>>> the gui, and the thread both lock up.
>>>   
>>
>>
>> Well, that's just normal. However, what you should do is to send a
>> signal from your thread with the text to append in your textbuffer.
>> Then, you catch the signal in your main widget to show it !
>>
>> To emit a signal use :
>>
>>    gtk.gdk.threads_enter()
>>    self.emit("writing", str)
>>    gtk.gdk.threads_leave()
>>
>> To catch it:
>>
>>
>>    emitting_object.connect("writing", self.method_handling_to_signal)
>>
>> Well, I used that and it just work ! Using the signal does not solve any
>> threading problem but allow you to separate between the event and the
>> answer to the event, which is a good habit to take !
>>
>> Pierre
>>
>>
>>  
>>
> I finally got it working !!
> thanks so much for all your help
> i would not have gotten it working without you,
> (or this mailing list)
> 
> God bless
> shawn
> 

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68

From janos.juhasz at VELUX.com  Thu Sep  8 14:15:28 2005
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Thu, 8 Sep 2005 14:15:28 +0200
Subject: [Tutor] Emulate jetdirect
In-Reply-To: <mailman.51.1126173614.14249.tutor@python.org>
Message-ID: <OF0D76122D.95EBB4CA-ONC1257076.003DFDA6-C1257076.004355B2@velux.com>

Hi All,

I just would make some kind of printer filter for an HP printer, that is
connected to a jetdirect printserver.

The functionality is something like this:
netcat -l -p 9100 | filter.py | netcat 10.36.11.11 9100

I would like to make it as a simple socketserver in python for the port
9100, reading from the socket and sending it to the real jetdirect
printserver over another socket. So it is kind of printer proxy server.
The filter would make some text processing with regular expressions on each
line.

Another wish to use it as an intelligent printer, that can send the
printout to the e-mail address, that is somewhere in the printout. To send
order response via a printing.

netcat -l -p 9100 | senditasemail.py


Can someone show me any example to start it ?


J?nos


From nephish at xit.net  Thu Sep  8 15:23:54 2005
From: nephish at xit.net (nephish)
Date: Thu, 08 Sep 2005 08:23:54 -0500
Subject: [Tutor] [tutor] threading problem in GUI
In-Reply-To: <431FEB92.5000401@cirad.fr>
References: <431EFEB2.3030308@xit.net>
	<431F006A.6000802@xit.net>	<431F138E.9090709@cirad.fr>
	<431F48F0.2000503@xit.net> <431FEB92.5000401@cirad.fr>
Message-ID: <43203B6A.9030507@xit.net>

Pierre Barbier de Reuille wrote:

>Great :)
>
>Just to be clear about that: you can see the "connect" line as a dynamic
>registration process (with the symetric disconnect operation available
>via ... "disconnect"). The only thing you need is to connect (at
>runtime) the even before it's called (obvious isn't it ? ;) ), but you
>have no other constraint. You can even choose to connect/disconnect
>events when they are used/unused ... You can also connect a single event
>many times (to different functions) or you can connect many events to
>the same function. This is the "power" of this system :) Like now if you
>want to log your strings on a file, you just define the function writing
>in the file and connect the event to this function: you'll have both the
>GUI and the log-file outputs !
>
>This is, AFAIK, the best existing implementation for user interfaces !
>
>Pierre
>
>nephish a ?crit :
>  
>
>>Pierre Barbier de Reuille wrote:
>>
>>    
>>
>>>nephish a ?crit :
>>> 
>>>
>>>      
>>>
>>>>one more thing.
>>>>if i uncomment the lines
>>>>gtk.threads_enter()
>>>>and
>>>>gtk.threads_leave()
>>>>the whole thing locks up when the function is called.
>>>>the gui, and the thread both lock up.
>>>>  
>>>>        
>>>>
>>>Well, that's just normal. However, what you should do is to send a
>>>signal from your thread with the text to append in your textbuffer.
>>>Then, you catch the signal in your main widget to show it !
>>>
>>>To emit a signal use :
>>>
>>>   gtk.gdk.threads_enter()
>>>   self.emit("writing", str)
>>>   gtk.gdk.threads_leave()
>>>
>>>To catch it:
>>>
>>>
>>>   emitting_object.connect("writing", self.method_handling_to_signal)
>>>
>>>Well, I used that and it just work ! Using the signal does not solve any
>>>threading problem but allow you to separate between the event and the
>>>answer to the event, which is a good habit to take !
>>>
>>>Pierre
>>>
>>>
>>> 
>>>
>>>      
>>>
>>I finally got it working !!
>>thanks so much for all your help
>>i would not have gotten it working without you,
>>(or this mailing list)
>>
>>God bless
>>shawn
>>
>>    
>>
>
>  
>
indeed. i really want to get into this stuff more.
i think a whole lot of what i have been doing could really be
done easier and cleaner.
thanks for everything,
shawn

From andrade1 at umbc.edu  Thu Sep  8 16:06:46 2005
From: andrade1 at umbc.edu (andrade1@umbc.edu)
Date: Thu, 8 Sep 2005 10:06:46 -0400 (EDT)
Subject: [Tutor] python strings?
Message-ID: <3062.130.85.91.225.1126188406.squirrel@130.85.91.225>

below is my program. what i would like to do is to get the last line to
print the number of years that the user enters and also the principal




# A program to compute the value of an investment
# years into the future

def main():
    print "This program calculates the future value of an investment over
years"

    principal = input("Enter the initial principal: ")
    apr = input("Enter the annual interest rate: ")
    years = input("Enter the number of years: ")

    for i in range(10):
        principal = principal * (1 + apr)

    print "The value in years is", principal

main()



From kim.d at tesco.net  Thu Sep  8 16:33:27 2005
From: kim.d at tesco.net (kim.d@tesco.net)
Date: Thu, 8 Sep 2005 14:33:27 +0000
Subject: [Tutor] Making Applets
Message-ID: <20050908143329.MTPE13203.aamta01-winn.mailhost.ntl.com@smtp.tesco.net>

Alan G. wrote:
<<<I believe MacPython has links to the libraries for doing true applets>>>

<<<I suspect you need to ask again on the MacPython programming list>>>

Thanks, Alan. I'll give it a look.


From frank.l.lane at boeing.com  Thu Sep  8 16:49:39 2005
From: frank.l.lane at boeing.com (Lane, Frank L)
Date: Thu, 8 Sep 2005 09:49:39 -0500
Subject: [Tutor] input/output redirection
Message-ID: <C3871B74409A854EA9B6F4EEB92088070110FB6F@XCH-SE-1V2.se.nos.boeing.com>

Hi List,
 
I wanted to take the stdout of a process and redirect it to stdin of a
python script, then after playing with the input in the script I want to
send it back to stdout (all of this to be done while the original
process runs happily along).  I can't seem to figure out the correct
syntax if this is possible.
 
e.g.
 
C:\> runner.exe | script.py
C:\> runner.exe > script.py  # this overwrites your script!:-)
 
e.g.
 
#!/usr/bin/env python
import re
 
while 1:
    packet = sys.stdin.read()
    if field in packet:
        # change it and put it back on the command window and get the
next bunch of stuff
        sys.stdout.write()
 
I hope my question/intention is clear.
 
Thanks to the list!  This is the best list I've ever belonged to.  There
are a lot of knowledgeable people who help, and no one ever flames you
for asking questions out of ignorance.
 
Thanks,
Frank
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050908/9a0bdc59/attachment.html

From javier at ruere.com.ar  Thu Sep  8 17:58:44 2005
From: javier at ruere.com.ar (Javier Ruere)
Date: Thu, 08 Sep 2005 12:58:44 -0300
Subject: [Tutor] input/output redirection
In-Reply-To: <C3871B74409A854EA9B6F4EEB92088070110FB6F@XCH-SE-1V2.se.nos.boeing.com>
References: <C3871B74409A854EA9B6F4EEB92088070110FB6F@XCH-SE-1V2.se.nos.boeing.com>
Message-ID: <dfpmoi$2g8$1@sea.gmane.org>

Lane, Frank L wrote:
> Hi List,
>  
> I wanted to take the stdout of a process and redirect it to stdin of a
> python script, then after playing with the input in the script I want to
> send it back to stdout (all of this to be done while the original
> process runs happily along).  I can't seem to figure out the correct
> syntax if this is possible.
>  
> e.g.
>  
> C:\> runner.exe | script.py
> C:\> runner.exe > script.py  # this overwrites your script!:-)
>  
> e.g.
>  
> #!/usr/bin/env python
> import re
>  
> while 1:
>     packet = sys.stdin.read()

  In the previous line, all input is read which is not ideal. Depending on the input a single line or part of it should be read so that the script can start working before runner.exe finishes.
  Now, once you have a workable chunck of the input, you can happily process it and write it out.

>     if field in packet:
>         # change it and put it back on the command window and get the
> next bunch of stuff
>         sys.stdout.write()

  In the previous line, write is called with no arguments. It should recieve the string to output.

> I hope my question/intention is clear.

  The given code is not a working example. It would help if the code was more complete.

Javier


From daniel at thewatkins.org.uk  Thu Sep  8 18:39:21 2005
From: daniel at thewatkins.org.uk (Daniel Watkins)
Date: Thu, 08 Sep 2005 17:39:21 +0100
Subject: [Tutor] python strings?
In-Reply-To: <9AA4216B8A36B9429BB00C546DF6D27201B541@schubert.OxbridgeTechnology.local>
References: <9AA4216B8A36B9429BB00C546DF6D27201B541@schubert.OxbridgeTechnology.local>
Message-ID: <1126197561.10048.15.camel@amdbert.oxbridgetechnology.local>

On Thu, 2005-09-08 at 15:15 +0100, andrade1 at umbc.edu wrote:
>     for i in range(10): 
>         principal = principal * (1 + apr)
To calculate compound interest, you in fact don't need to use a loop at
all (you could use: 'final = principal * (apr ** years)') but if you
really want to use a loop, I would use a while loop (although this may
not be the best way involving loops, my loop-fu isn't great).
The while loop would look like:
	while years:
		principal = principal * (1 + apr)
		years = years - 1
If you planned to use fractions of years, then you need to tweak this.

>     print "The value in years is", principal
To actually answer your question, in order to print this correctly, you
need to tell Python to convert the integer (principal) to a string by
using the built-in function str() like so:
	print "The value in years is", str(principal)

To include the years, you would just add 'str(years)' in an appropriate
position, although if you've used the while loop, then referring to
years will simply give you 0, as you've been adjusting it. The solution
to this is to assign 'years' to a different variable initially (and use
one in the loop and the other here) in order to preserve it.


From dyoo at hkn.eecs.berkeley.edu  Thu Sep  8 20:13:55 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 8 Sep 2005 11:13:55 -0700 (PDT)
Subject: [Tutor] input/output redirection
In-Reply-To: <C3871B74409A854EA9B6F4EEB92088070110FB6F@XCH-SE-1V2.se.nos.boeing.com>
Message-ID: <Pine.LNX.4.44.0509081108100.11509-100000@hkn.eecs.berkeley.edu>



On Thu, 8 Sep 2005, Lane, Frank L wrote:

> I wanted to take the stdout of a process and redirect it to stdin of a
> python script, then after playing with the input in the script I want to
> send it back to stdout (all of this to be done while the original
> process runs happily along).  I can't seem to figure out the correct
> syntax if this is possible.
>
> e.g.
>
> C:\> runner.exe | script.py


Hi Frank,

You've almost got it.  The syntax above should have worked.  But the
problem here is that you're running into a problem with the way Windows
runs Python scripts.  Alan Gauld ran into this a few weeks ago:

    http://mail.python.org/pipermail/tutor/2005-August/041019.html

You may need to put a CMD wrapper around the Python script.  Apparently,
this makes Windows pleased enough to let it be used as part of a shell
pipeline.  The thread above should mention the workaround to get things
working.

Best of wishes!


From 3dbernard at gmail.com  Thu Sep  8 21:10:26 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Thu, 8 Sep 2005 15:10:26 -0400
Subject: [Tutor] Substring substitution
Message-ID: <61d0e2b405090812108d10cbf@mail.gmail.com>

Hello,

I have a string, and I use a regular expression to search a match in
it. When I find one, I would like to break down the string, using the
matched part of it, to be able to perform some formatting and to later
build a brand new string with the separate parts.

The regular expression part works ok, but my problem is to extract the
matched pattern from the string. I'm not sure how to do that...


sString = 'mt_03_04_04_anim'

# Create regular expression object
oRe = re.compile( "\d\d_\d\d\_\d\d" )

# Break-up path
aString = sString.split( os.sep )

# Iterate individual components
for i in range( 0, len( aString ) ):
	
	sSubString = aString[i]
	
	# Search with shot number of 2 digits
	oMatch = oRe.search( sSubString )

	if oMatch != None:
		# Replace last sequence of two digits by 3 digits!!


Any suggestion would be welcomed.


Thanks!
Bernard

From david at graniteweb.com  Thu Sep  8 21:18:06 2005
From: david at graniteweb.com (David Rock)
Date: Thu, 8 Sep 2005 14:18:06 -0500
Subject: [Tutor] input/output redirection
In-Reply-To: <C3871B74409A854EA9B6F4EEB92088070110FB6F@XCH-SE-1V2.se.nos.boeing.com>
References: <C3871B74409A854EA9B6F4EEB92088070110FB6F@XCH-SE-1V2.se.nos.boeing.com>
Message-ID: <20050908191806.GA16616@wdfs.graniteweb.com>

* Lane, Frank L <frank.l.lane at boeing.com> [2005-09-08 09:49]:
> Hi List,
>  
> I wanted to take the stdout of a process and redirect it to stdin of a
> python script, then after playing with the input in the script I want to
> send it back to stdout (all of this to be done while the original
> process runs happily along).  I can't seem to figure out the correct
> syntax if this is possible.
>  
> e.g.
>  
> C:\> runner.exe | script.py
> C:\> runner.exe > script.py  # this overwrites your script!:-)

I use fileinput for most of my stdin text processing. It also give me
the flexibility of using it as a pipe OR assigning a wordlist of files
to the script instead.

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

import fileinput
for line in fileinput.input():
    process(line)


-- 
David Rock
david at graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050908/af60c76f/attachment.pgp

From kent37 at tds.net  Thu Sep  8 21:36:30 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Sep 2005 15:36:30 -0400
Subject: [Tutor] Substring substitution
In-Reply-To: <61d0e2b405090812108d10cbf@mail.gmail.com>
References: <61d0e2b405090812108d10cbf@mail.gmail.com>
Message-ID: <432092BE.3080503@tds.net>

Bernard Lebel wrote:
> Hello,
> 
> I have a string, and I use a regular expression to search a match in
> it. When I find one, I would like to break down the string, using the
> matched part of it, to be able to perform some formatting and to later
> build a brand new string with the separate parts.
> 
> The regular expression part works ok, but my problem is to extract the
> matched pattern from the string. I'm not sure how to do that...
> 
> 
> sString = 'mt_03_04_04_anim'
> 
> # Create regular expression object
> oRe = re.compile( "\d\d_\d\d\_\d\d" )
> 
> # Break-up path
> aString = sString.split( os.sep )
> 
> # Iterate individual components
> for i in range( 0, len( aString ) ):
> 	
> 	sSubString = aString[i]
> 	
> 	# Search with shot number of 2 digits
> 	oMatch = oRe.search( sSubString )
> 
> 	if oMatch != None:
> 		# Replace last sequence of two digits by 3 digits!!

Hi Bernard,

It sounds like you need to put some groups into your regex and use re.sub().

By putting groups in the regex you can refer to pieces of the match. For example

 >>> import re
 >>> s  = 'mt_03_04_04_anim'
 >>> oRe = re.compile( "(\d\d_\d\d\_)(\d\d)" )
 >>> m = oRe.search(s)
 >>> m.group(1)
'03_04_'
 >>> m.group(2)
'04'

With re.sub(), you provide a replacement pattern that can refer to the groups from the match pattern. So to insert new characters between the groups is easy:

 >>> oRe.sub(r'\1XX\2', s)
'mt_03_04_XX04_anim'

This may be enough power to do what you want, I'm not sure from your description. But re.sub() has another trick up its sleeve - the replacement 'expression' can be a callable which is passed the match object and returns the string to replace it with. For example, if you wanted to find all the two digit numbers in a string and add one to them, you could do it like this:

 >>> def incMatch(m):
 ...   s = m.group(0) # use the whole match
 ...   return str(int(s)+1).zfill(2)
 ...
 >>> re.sub(r'\d\d', incMatch, '01_09_23')
'02_10_24'

This capability can be used to do complicated replacements.

Kent


From alan.gauld at freenet.co.uk  Thu Sep  8 21:52:40 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Thu, 8 Sep 2005 20:52:40 +0100
Subject: [Tutor] python strings?
References: <9AA4216B8A36B9429BB00C546DF6D27201B541@schubert.OxbridgeTechnology.local>
	<1126197561.10048.15.camel@amdbert.oxbridgetechnology.local>
Message-ID: <004a01c5b4ae$df084ee0$0201a8c0@xp>

>>     print "The value in years is", principal

> To actually answer your question, in order to print this correctly, 
> you
> need to tell Python to convert the integer (principal) to a string 
> by
> using the built-in function str() like so:

Not so. print automatically calls str() on all its arguments so
the programmer doesn't need to.

An alternative way to solve your probnlem is to use format strings:

print "Years = %s;\tPrincipal = %s" % (years,principal)

HTH,

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


From daniel at thewatkins.org.uk  Thu Sep  8 22:01:57 2005
From: daniel at thewatkins.org.uk (Daniel Watkins)
Date: Thu, 08 Sep 2005 21:01:57 +0100
Subject: [Tutor] python strings?
In-Reply-To: <000001c5b4af$ec8542c0$0400000a@OxbridgeTechnology.local>
References: <9AA4216B8A36B9429BB00C546DF6D27201B541@schubert.OxbridgeTechnology.local>
	<1126197561.10048.15.camel@amdbert.oxbridgetechnology.local>
	<000001c5b4af$ec8542c0$0400000a@OxbridgeTechnology.local>
Message-ID: <1126209718.10048.22.camel@amdbert.oxbridgetechnology.local>

On Thu, 2005-09-08 at 21:00 +0100, Alan G wrote:
> Not so. print automatically calls str() on all its arguments so
> the programmer doesn't need to.
So it does. I think I was trying to concatenate, which it doesn't like.
Sorry if I caused any confusion.

Dan


From 3dbernard at gmail.com  Thu Sep  8 22:15:02 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Thu, 8 Sep 2005 16:15:02 -0400
Subject: [Tutor] Substring substitution
In-Reply-To: <432092BE.3080503@tds.net>
References: <61d0e2b405090812108d10cbf@mail.gmail.com>
	<432092BE.3080503@tds.net>
Message-ID: <61d0e2b405090813157c6c2d0d@mail.gmail.com>

Hi Kent,

This is nice!

There is one thing though. When I run the oRe.sub() call, I get an error:


Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "\\Linuxserver\prod\XSI\WORKGROUP_4.0\Data\Scripts\pipeline\filesystem\bb_processshotdigits.py",
line 63, in ?
    processPath( r'C:\temp\MT_03_03_03\allo.txt', False )
  File "\\Linuxserver\prod\XSI\WORKGROUP_4.0\Data\Scripts\pipeline\filesystem\bb_processshotdigits.py",
line 45, in processPath
    else: sSubString = matchShot( sSubString )
  File "\\Linuxserver\prod\XSI\WORKGROUP_4.0\Data\Scripts\pipeline\filesystem\bb_processshotdigits.py",
line 11, in matchShot
    sNewString = oRe.sub( r'\10\2', sSubString )
  File "D:\Python24\Lib\sre.py", line 260, in filter
    return sre_parse.expand_template(template, match)
  File "D:\Python24\Lib\sre_parse.py", line 781, in expand_template
raise error, "invalid group reference"
sre_constants.error: invalid group reference



 This is my new match function:



def matchShot( sSubString ):
	
	# Create regular expression object
	oRe = re.compile( "(\d\d_\d\d\_)(\d\d)" )
	
	oMatch = oRe.search( sSubString )
	if oMatch != None:
		sNewString = oRe.sub( r'\10\2', sSubString )
		return sNewString
	else:
		return sSubString



I have read the sub() documentation entry but I have to confess that
made things more confusing for me...

Thanks again
Bernard



On 9/8/05, Kent Johnson <kent37 at tds.net> wrote:
> Bernard Lebel wrote:
> > Hello,
> >
> > I have a string, and I use a regular expression to search a match in
> > it. When I find one, I would like to break down the string, using the
> > matched part of it, to be able to perform some formatting and to later
> > build a brand new string with the separate parts.
> >
> > The regular expression part works ok, but my problem is to extract the
> > matched pattern from the string. I'm not sure how to do that...
> >
> >
> > sString = 'mt_03_04_04_anim'
> >
> > # Create regular expression object
> > oRe = re.compile( "\d\d_\d\d\_\d\d" )
> >
> > # Break-up path
> > aString = sString.split( os.sep )
> >
> > # Iterate individual components
> > for i in range( 0, len( aString ) ):
> >
> >       sSubString = aString[i]
> >
> >       # Search with shot number of 2 digits
> >       oMatch = oRe.search( sSubString )
> >
> >       if oMatch != None:
> >               # Replace last sequence of two digits by 3 digits!!
> 
> Hi Bernard,
> 
> It sounds like you need to put some groups into your regex and use re.sub().
> 
> By putting groups in the regex you can refer to pieces of the match. For example
> 
>  >>> import re
>  >>> s  = 'mt_03_04_04_anim'
>  >>> oRe = re.compile( "(\d\d_\d\d\_)(\d\d)" )
>  >>> m = oRe.search(s)
>  >>> m.group(1)
> '03_04_'
>  >>> m.group(2)
> '04'
> 
> With re.sub(), you provide a replacement pattern that can refer to the groups from the match pattern. So to insert new characters between the groups is easy:
> 
>  >>> oRe.sub(r'\1XX\2', s)
> 'mt_03_04_XX04_anim'
> 
> This may be enough power to do what you want, I'm not sure from your description. But re.sub() has another trick up its sleeve - the replacement 'expression' can be a callable which is passed the match object and returns the string to replace it with. For example, if you wanted to find all the two digit numbers in a string and add one to them, you could do it like this:
> 
>  >>> def incMatch(m):
>  ...   s = m.group(0) # use the whole match
>  ...   return str(int(s)+1).zfill(2)
>  ...
>  >>> re.sub(r'\d\d', incMatch, '01_09_23')
> '02_10_24'
> 
> This capability can be used to do complicated replacements.
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From olivermaunder at gmail.com  Thu Sep  8 20:31:27 2005
From: olivermaunder at gmail.com (Oliver Maunder)
Date: Thu, 8 Sep 2005 19:31:27 +0100
Subject: [Tutor] python strings?
In-Reply-To: <3062.130.85.91.225.1126188406.squirrel@130.85.91.225>
References: <3062.130.85.91.225.1126188406.squirrel@130.85.91.225>
Message-ID: <b2f0cd9e05090811318df4fe4@mail.gmail.com>

On 08/09/05, andrade1 at umbc.edu <andrade1 at umbc.edu> wrote:
> 
> below is my program. what i would like to do is to get the last line to
> print the number of years that the user enters and also the principal


There are a couple (at least!) of ways to get the values into the string 
that you print.

The first way is to pass several values to the print command:

print "The value in", years, "is", principal

Another way is to use placeholders:
print "The value in %d years is %.2f" % (years, principal)

The placeholders (shown by the % sign) get replaced by the variables in the 
list, in order. "%d" means format the value as an integer. "%.2f" means 
format it as a floating point value with two decimal places. See 
http://diveintopython.org/native_data_types/formatting_strings.html for more 
details.

You could replace the main bit of the program with a single line, if you're 
feeling brave!

principal = input("Enter the initial principal: ")
apr = input("Enter the annual interest rate: ")
years = input("Enter the number of years: ")
print "The value in %d years will be %.2f" % (years, principal * (1 + 
apr)**years)

Hope this is useful!

Olly





# A program to compute the value of an investment
> # years into the future
> 
> def main():
> print "This program calculates the future value of an investment over
> years"
> 
> principal = input("Enter the initial principal: ")
> apr = input("Enter the annual interest rate: ")
> years = input("Enter the number of years: ")
> 
> for i in range(10):
> principal = principal * (1 + apr)
> 
> print "The value in years is", principal
> 
> main()
> 
> 
> _______________________________________________
> 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/20050908/b45c1b56/attachment.htm

From 3dbernard at gmail.com  Thu Sep  8 22:53:42 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Thu, 8 Sep 2005 16:53:42 -0400
Subject: [Tutor] Substring substitution
In-Reply-To: <61d0e2b405090813157c6c2d0d@mail.gmail.com>
References: <61d0e2b405090812108d10cbf@mail.gmail.com>
	<432092BE.3080503@tds.net> <61d0e2b405090813157c6c2d0d@mail.gmail.com>
Message-ID: <61d0e2b405090813533105d805@mail.gmail.com>

Ok I think I understand what is going: I'm using a 0 in the
replacement argument, between the two groups. If I try with a letter
or other types of characters it works fine. So how can use a digit
here?

Thanks
Bernard


On 9/8/05, Bernard Lebel <3dbernard at gmail.com> wrote:
> Hi Kent,
> 
> This is nice!
> 
> There is one thing though. When I run the oRe.sub() call, I get an error:
> 
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "\\Linuxserver\prod\XSI\WORKGROUP_4.0\Data\Scripts\pipeline\filesystem\bb_processshotdigits.py",
> line 63, in ?
>     processPath( r'C:\temp\MT_03_03_03\allo.txt', False )
>   File "\\Linuxserver\prod\XSI\WORKGROUP_4.0\Data\Scripts\pipeline\filesystem\bb_processshotdigits.py",
> line 45, in processPath
>     else: sSubString = matchShot( sSubString )
>   File "\\Linuxserver\prod\XSI\WORKGROUP_4.0\Data\Scripts\pipeline\filesystem\bb_processshotdigits.py",
> line 11, in matchShot
>     sNewString = oRe.sub( r'\10\2', sSubString )
>   File "D:\Python24\Lib\sre.py", line 260, in filter
>     return sre_parse.expand_template(template, match)
>   File "D:\Python24\Lib\sre_parse.py", line 781, in expand_template
> raise error, "invalid group reference"
> sre_constants.error: invalid group reference
> 
> 
> 
>  This is my new match function:
> 
> 
> 
> def matchShot( sSubString ):
> 
>         # Create regular expression object
>         oRe = re.compile( "(\d\d_\d\d\_)(\d\d)" )
> 
>         oMatch = oRe.search( sSubString )
>         if oMatch != None:
>                 sNewString = oRe.sub( r'\10\2', sSubString )
>                 return sNewString
>         else:
>                 return sSubString
> 
> 
> 
> I have read the sub() documentation entry but I have to confess that
> made things more confusing for me...
> 
> Thanks again
> Bernard

From kent37 at tds.net  Fri Sep  9 00:12:32 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Sep 2005 18:12:32 -0400
Subject: [Tutor] Substring substitution
In-Reply-To: <61d0e2b405090813533105d805@mail.gmail.com>
References: <61d0e2b405090812108d10cbf@mail.gmail.com>	<432092BE.3080503@tds.net>
	<61d0e2b405090813157c6c2d0d@mail.gmail.com>
	<61d0e2b405090813533105d805@mail.gmail.com>
Message-ID: <4320B750.4080200@tds.net>

Bernard Lebel wrote:
> Ok I think I understand what is going: I'm using a 0 in the
> replacement argument, between the two groups. If I try with a letter
> or other types of characters it works fine. So how can use a digit
> here?

There is a longer syntax for \1 - \g<1> means the same thing but without the ambiguity of where it ends. So you can use r'\g<1>0\2' as your substitution string.

>>def matchShot( sSubString ):
>>
>>        # Create regular expression object
>>        oRe = re.compile( "(\d\d_\d\d\_)(\d\d)" )
>>
>>        oMatch = oRe.search( sSubString )
>>        if oMatch != None:
>>                sNewString = oRe.sub( r'\10\2', sSubString )
>>                return sNewString
>>        else:
>>                return sSubString

You don't have to do the search, oRe.sub() won't do anything if there is no match. Also if you are doing this a lot you should pull the re.compile() out of the function (so oRe is a module variable), this is an expensive step that only has to be done once.

You hinted in your original post that you are trying to find strings where the last _\d\d has only two digits. The re you are using will also match something like 'mt_03_04_044_anim' and your matchShot() will change that to 'mt_03_04_0044_anim'. If that is not what you want you have to put some kind of a guard at the end of the re - something that won't match a digit. If you always have the _ at the end it is easy, just use r"(\d\d_\d\d\_)(\d\d_)". If you can't count on the underscore you will have to be more clever.

Kent


From Goofball223 at wmconnect.com  Fri Sep  9 01:34:36 2005
From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com)
Date: Thu, 8 Sep 2005 19:34:36 EDT
Subject: [Tutor] making a table
Message-ID: <190.47bc4cf3.3052248c@wmconnect.com>

I would like to construct a table for my program but it does not seem to be 
coming out evenly. Could someone please let me know what to do so that 
everything will work out correctly?

def main():
    print "This program shows a table of Celsius temperatures and there 
Fahrenheit equivalents every 10 degrees from 0C to 100C"
    print "C F"
    for i in(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100):
        fahrenheit = (9.0/5.0) * i + 32
        print i
        print "   ",
        print fahrenheit
        
main() 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050908/720b1f83/attachment.html

From dyoo at hkn.eecs.berkeley.edu  Fri Sep  9 01:51:52 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 8 Sep 2005 16:51:52 -0700 (PDT)
Subject: [Tutor] making a table
In-Reply-To: <190.47bc4cf3.3052248c@wmconnect.com>
Message-ID: <Pine.LNX.4.44.0509081649440.9105-100000@hkn.eecs.berkeley.edu>



On Thu, 8 Sep 2005 Goofball223 at wmconnect.com wrote:

> I would like to construct a table for my program but it does not seem to
> be coming out evenly. Could someone please let me know what to do so
> that everything will work out correctly?

Hello,

I'll assume for the moment that you want, in your print statements:

>         print i
>         print "   ",
>         print fahrenheit

to see a single line of output.

I see that you have a trailing comma on the second print statement.  Can
you explain what the comma does there?

Good luck to you!


From bgailer at alum.rpi.edu  Fri Sep  9 04:46:54 2005
From: bgailer at alum.rpi.edu (bob)
Date: Thu, 08 Sep 2005 19:46:54 -0700
Subject: [Tutor] making a table
In-Reply-To: <190.47bc4cf3.3052248c@wmconnect.com>
References: <190.47bc4cf3.3052248c@wmconnect.com>
Message-ID: <6.1.2.0.0.20050908170605.032ddfd8@mail.mric.net>

At 04:34 PM 9/8/2005, Goofball223 at wmconnect.com wrote:
>I would like to construct a table for my program but it does not seem to 
>be coming out evenly. Could someone please let me know what to do so that 
>everything will work out correctly?
>
>def main():
>    print "This program shows a table of Celsius temperatures and there 
> Fahrenheit equivalents every 10 degrees from 0C to 100C"
>    print "C F"
>    for i in(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100):
>        fahrenheit = (9.0/5.0) * i + 32
>        print i
>        print "   ",
>        print fahrenheit
>
>main()

1 - you are getting C and F on different lines because there is no , after 
print i. After you fix that you will get:
C F
0     32.0
10     50.0
... similar lines deleted
40     104.0
... similar lines deleted
100     212.0

Now the trick is to get things lined up. Here % formatting comes in:

print "  C       F"
...
     print '%3s    %5.1f' % (i, farenheit)

Giving:
   C      F
   0     32.0
  10     50.0
etc. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050908/bd1759a8/attachment.html

From johan at accesstel.co.za  Fri Sep  9 09:05:28 2005
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Fri, 09 Sep 2005 09:05:28 +0200
Subject: [Tutor] making a table
In-Reply-To: <6.1.2.0.0.20050908170605.032ddfd8@mail.mric.net>
References: <190.47bc4cf3.3052248c@wmconnect.com>
	<6.1.2.0.0.20050908170605.032ddfd8@mail.mric.net>
Message-ID: <1126249528.8783.3.camel@KMA.accesstel>

def x():
...     print 'C    F'
...     for i in(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100):
...        fahrenheit = (9.0/5.0) * i + 32
...        print (`i` + '  ' + `fahrenheit`)

Simple but look OK,

Johan


On Thu, 2005-09-08 at 19:46 -0700, bob wrote:

> At 04:34 PM 9/8/2005, Goofball223 at wmconnect.com wrote:
> 
> > I would like to construct a table for my program but it does not
> > seem to be coming out evenly. Could someone please let me know what
> > to do so that everything will work out correctly? 
> > 
> > def main(): 
> >    print "This program shows a table of Celsius temperatures and
> > there Fahrenheit equivalents every 10 degrees from 0C to 100C" 
> >    print "C F" 
> >    for i in(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100): 
> >        fahrenheit = (9.0/5.0) * i + 32 
> >        print i 
> >        print "   ", 
> >        print fahrenheit 
> >         
> > main() 
> 
> 
> 1 - you are getting C and F on different lines because there is no ,
> after print i. After you fix that you will get:
> C F
> 0     32.0
> 10     50.0
> ... similar lines deleted
> 40     104.0
> ... similar lines deleted
> 100     212.0
> 
> Now the trick is to get things lined up. Here % formatting comes in:
> 
> print "  C       F"
> ...
>     print '%3s    %5.1f' % (i, farenheit)
> 
> Giving:
>   C      F
>   0     32.0
>  10     50.0
> etc. 
> 
> _______________________________________________
> 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/20050909/42d60d9a/attachment.htm

From ml.cyresse at gmail.com  Fri Sep  9 12:25:14 2005
From: ml.cyresse at gmail.com (mailing list)
Date: Fri, 9 Sep 2005 22:25:14 +1200
Subject: [Tutor] making a table
In-Reply-To: <190.47bc4cf3.3052248c@wmconnect.com>
References: <190.47bc4cf3.3052248c@wmconnect.com>
Message-ID: <b6f3249e05090903253293a79e@mail.gmail.com>

Hi Goofball223, 

Just a quick thing -

> for i in (0,10, 20, 30, 40, 50, 60, 70, 80, 90, 100):

Have you used range() before?

for i in range(10): 
     print i
 
0
1
2
3
4
5
6
7
8
9

It's handy for situations like yours. Also, you could use it like this - 

zeroToNine = range(10)
print zeroToNine 
[0,1,2,3,4,5,6,7,8,9]

for i in zeroToNine:
     print i

..Just a quick mention that range(x) counts up to, but not including
x. ( There's good reasons for this, which someone can explain if
needed.)

Also, by default it starts at zero, and increases by 1. You can change
these, however.

i.e. to create a list from 5 to 50 in increments of 5 - 

zeroToFifty = range(start = 5, stop = 55, step = 5)

Remember, it'll count up to but not including stop, so if you tell it
to count to two hundred in steps of 10, it'll count to 190, counting
to 16 by steps of 2 will count to 14. So always set it one step value
above what you want.

(start defaults to 0, step defaults to 1, hence you can just use
range(stop = 100) or
range(100) for short.)

You're looking good, however.

Cheers, 

Liam Clarke

On 9/9/05, Goofball223 at wmconnect.com <Goofball223 at wmconnect.com> wrote:
> I would like to construct a table for my program but it does not seem to be
> coming out evenly. Could someone please let me know what to do so that
> everything will work out correctly? 
>  
> def main(): 
>     print "This program shows a table of Celsius temperatures and there
> Fahrenheit equivalents every 10 degrees from 0C to 100C" 
>     print "C F" 
>     for i in(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100): 
>         fahrenheit = (9.0/5.0) * i + 32 
>         print i 
>         print "   ", 
>         print fahrenheit 
>          
> main() 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
>

From alan.gauld at freenet.co.uk  Fri Sep  9 12:26:36 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Fri, 9 Sep 2005 11:26:36 +0100
Subject: [Tutor] making a table
References: <190.47bc4cf3.3052248c@wmconnect.com>
Message-ID: <014f01c5b528$f55ded60$0201a8c0@xp>


>I would like to construct a table for my program but it does not seem 
>to be
> coming out evenly. Could someone please let me know what to do so 
> that
> everything will work out correctly?

The best way to build a table is to use a format string with every
field width specified explicitly. Thus in your example:

def main(min,max,step):
    """This program prints a table of Celsius temperatures
       and their Fahrenheit equivalents """
    fmt = "%4s    %4s"
    print fmt % ('C','F')
    for i in range(min, max, step):
        fahrenheit = (9.0/5.0) * i + 32
        print fmt % (i,farenheit)

main(0,101,10)

By applying the same format to the headings you ensure consistency and
by specifying the widths you get guaranteed text line-up. If you want
to print an HTML table you only need to add the tags to the format
string (although in that case you might want a different format
for the header)

I also parameterised the function so you can specify the range of
temperatures and the step size just for fun. :-)

Alan G 


From rob.andrews at gmail.com  Fri Sep  9 21:34:09 2005
From: rob.andrews at gmail.com (Rob Andrews)
Date: Fri, 9 Sep 2005 14:34:09 -0500
Subject: [Tutor] directory recursion
Message-ID: <8d757d2e05090912344abe0f17@mail.gmail.com>

I should already know this, and probably once did, but have never had
a real world use for it until now.

What's a nice, clean way to recursively scan through directories with
an arbitrary number of subdirectories?

In today's example, we're looking to grab the file name and third line
of the file for every text file in the directory tree, and dump into a
new text file. Everything but the walking of the tree was obvious
enough.

We used the following to grab the desired output from a single level
of directories:

import glob

for fileName in glob.glob('C:/stuff/jayfiles/*/*.txt'): # glob through
directories
    newFile = open('C:/stuff/jayfiles/newFile.txt', 'a') # open
newFile to append
    newFile.write(fileName) # append fileName to newFile
    newFile.write('\t') # append a tab after fileName
    currentFile = open(fileName, 'r') # open next file for reading
    currentFile.readline() # this and the following line go through...
    currentFile.readline() #            ...the 1st 2 lines of the file
    thirdLine = currentFile.readline() # modify this to print to text file
    newFile.write(thirdLine) # append thirdLine to newFile
    currentFile.close() # close currentFile
    newFile.close() # close newFile

-Rob

From dyoo at hkn.eecs.berkeley.edu  Fri Sep  9 21:59:14 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 9 Sep 2005 12:59:14 -0700 (PDT)
Subject: [Tutor] directory recursion
In-Reply-To: <8d757d2e05090912344abe0f17@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509091256550.3556-100000@hkn.eecs.berkeley.edu>



On Fri, 9 Sep 2005, Rob Andrews wrote:

> I should already know this, and probably once did, but have never had
> a real world use for it until now.
>
> What's a nice, clean way to recursively scan through directories with
> an arbitrary number of subdirectories?

Hi Rob,

You may want to look at os.walk():

    http://www.python.org/doc/lib/os-file-dir.html#l2h-1628

If you have questions on it, please feel free to ask!

Hope this helps!


From chris.arndt at web.de  Fri Sep  9 21:49:56 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Fri, 09 Sep 2005 20:49:56 +0100
Subject: [Tutor] directory recursion
In-Reply-To: <8d757d2e05090912344abe0f17@mail.gmail.com>
References: <8d757d2e05090912344abe0f17@mail.gmail.com>
Message-ID: <4321E764.6070703@web.de>

Rob Andrews schrieb:
> I should already know this, and probably once did, but have never had
> a real world use for it until now.
> 
> What's a nice, clean way to recursively scan through directories with
> an arbitrary number of subdirectories?

os.walk() is you friend! (Don't use os.path.walk() anymore)

"Off the top of my head":

for dir, dirnames, filenames in os.walk(topdir):
    for dir in dirnames:
        do_something_with_subdir(os.path.join(dir, dirname)
    for file in filenames:
        do_something_with_file(os.path.join(dir, filename)

HTH, Chris


From 3dbernard at gmail.com  Fri Sep  9 22:14:11 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri, 9 Sep 2005 16:14:11 -0400
Subject: [Tutor] Substring substitution
In-Reply-To: <4320B750.4080200@tds.net>
References: <61d0e2b405090812108d10cbf@mail.gmail.com>
	<432092BE.3080503@tds.net> <61d0e2b405090813157c6c2d0d@mail.gmail.com>
	<61d0e2b405090813533105d805@mail.gmail.com> <4320B750.4080200@tds.net>
Message-ID: <61d0e2b405090913144439593a@mail.gmail.com>

Hi Kent,

Once again, thanks a lot. Problem solved now, your suggestions work
like a charm. You were absolutely right about the last group matching.
I modified my matching pattern:

oRe = re.compile( "(\d\d_\d\d\_)(\d\d(\D|$))" )

Instead of

oRe = re.compile( "(\d\d_\d\d\_)(\d\d)" )


I had no idea you could put subgroups in groups, I tried that out of
inspiration and whoo it works. This is fantastic!

So here is the full script, followed by the output:


import os, re


def matchShot( sSubString, oRe ):
	
	sNewString = oRe.sub( r'\g<1>0\2', sSubString )
	return sNewString




def processPath( sString, bTest ):
	
	"""
	ARGUMENTS:
	sString (string): the path to process
	bTest (boolean): test the validity of paths at each step of the script
	"""
	
	# Create regular expression object
	oRe = re.compile( "(\d\d_\d\d\_)(\d\d(\D|$))" )
	
	
	if bTest == True:
		# Test validity of integral path
		if not os.path.exists( sString ): return None
		
	# Break-up path
	aString = sString.split( os.sep )
	
	aNewPath = []
	
	# Iterate individual components
	for sSubString in aString:
		
		
		if bTest == True:
			# Test if this part of the path is working with the current path
			sTempPath = '\\'.join( aNewPath )
			sTempPath += '%s%s' % ( '\\', sSubString )
			if not os.path.exists( sTempPath ): sSubString = matchShot( sSubString, oRe )
		else: sSubString = matchShot( sSubString, oRe )
		
		
		aNewPath.append( sSubString )
		
		
		if bTest == True:
			# Test again if path is valid with this substring
			sTempPath = '\\'.join( aNewPath )
			if not os.path.exists( sTempPath ): return None
	
	
	sNewPath = '\\'.join( aNewPath )
	print sNewPath




processPath( r'C:\temp\MT_03_03_03\allo.txt', False )
processPath( r'C:\temp\MT_03_04_04\mt_03_04_04_anim_v1.scn', False )
processPath( r'C:\temp\MT_03_05_005_anim\mt_03_05_05_anim_v1.scn', False )
processPath( r'C:\temp\MT_03_06_006\mt_03_06_006_anim_v1.scn', False )

# ============================================================

C:\temp\MT_03_03_003\allo.txt
C:\temp\MT_03_04_004\mt_03_04_004_anim_v1.scn
C:\temp\MT_03_05_005_anim\mt_03_05_005_anim_v1.scn
C:\temp\MT_03_06_006\mt_03_06_006_anim_v1.scn


This is exactly what I was after. Thanks a lot!!

Bernard




On 9/8/05, Kent Johnson <kent37 at tds.net> wrote:
> Bernard Lebel wrote:
> > Ok I think I understand what is going: I'm using a 0 in the
> > replacement argument, between the two groups. If I try with a letter
> > or other types of characters it works fine. So how can use a digit
> > here?
> 
> There is a longer syntax for \1 - \g<1> means the same thing but without the ambiguity of where it ends. So you can use r'\g<1>0\2' as your substitution string.
> 
> >>def matchShot( sSubString ):
> >>
> >>        # Create regular expression object
> >>        oRe = re.compile( "(\d\d_\d\d\_)(\d\d)" )
> >>
> >>        oMatch = oRe.search( sSubString )
> >>        if oMatch != None:
> >>                sNewString = oRe.sub( r'\10\2', sSubString )
> >>                return sNewString
> >>        else:
> >>                return sSubString
> 
> You don't have to do the search, oRe.sub() won't do anything if there is no match. Also if you are doing this a lot you should pull the re.compile() out of the function (so oRe is a module variable), this is an expensive step that only has to be done once.
> 
> You hinted in your original post that you are trying to find strings where the last _\d\d has only two digits. The re you are using will also match something like 'mt_03_04_044_anim' and your matchShot() will change that to 'mt_03_04_0044_anim'. If that is not what you want you have to put some kind of a guard at the end of the re - something that won't match a digit. If you always have the _ at the end it is easy, just use r"(\d\d_\d\d\_)(\d\d_)". If you can't count on the underscore you will have to be more clever.
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From kent37 at tds.net  Fri Sep  9 22:51:29 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Sep 2005 16:51:29 -0400
Subject: [Tutor] directory recursion
In-Reply-To: <8d757d2e05090912344abe0f17@mail.gmail.com>
References: <8d757d2e05090912344abe0f17@mail.gmail.com>
Message-ID: <4321F5D1.7010805@tds.net>

Rob Andrews wrote:
> I should already know this, and probably once did, but have never had
> a real world use for it until now.
> 
> What's a nice, clean way to recursively scan through directories with
> an arbitrary number of subdirectories?

Jason Orendorff's path module is awesome for this kind of job - it's as easy as this:

from path import path
basePath = path('C:/stuff/jayfiles')
for filePath in basePath.walkfiles('*.txt'):
  currentFile = open(filePath)
  # etc

Highly recommended.
http://www.jorendorff.com/articles/python/path/

Kent

> 
> In today's example, we're looking to grab the file name and third line
> of the file for every text file in the directory tree, and dump into a
> new text file. Everything but the walking of the tree was obvious
> enough.
> 
> We used the following to grab the desired output from a single level
> of directories:
> 
> import glob
> 
> for fileName in glob.glob('C:/stuff/jayfiles/*/*.txt'): # glob through
> directories
>     newFile = open('C:/stuff/jayfiles/newFile.txt', 'a') # open
> newFile to append
>     newFile.write(fileName) # append fileName to newFile
>     newFile.write('\t') # append a tab after fileName
>     currentFile = open(fileName, 'r') # open next file for reading
>     currentFile.readline() # this and the following line go through...
>     currentFile.readline() #            ...the 1st 2 lines of the file
>     thirdLine = currentFile.readline() # modify this to print to text file
>     newFile.write(thirdLine) # append thirdLine to newFile
>     currentFile.close() # close currentFile
>     newFile.close() # close newFile
> 
> -Rob
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From max_russell2000 at yahoo.co.uk  Fri Sep  9 23:04:56 2005
From: max_russell2000 at yahoo.co.uk (Max Russell)
Date: Fri, 9 Sep 2005 22:04:56 +0100 (BST)
Subject: [Tutor] mamelauncher
Message-ID: <20050909210456.12127.qmail@web25907.mail.ukl.yahoo.com>

Hi:

I've been working on this for ages and am having real
problems with getting the wiring for a selected game
to launch when I click OK.

I haven't added my error handling yet.

Can anyone help?

I've tried using spawn, system etc etc to no avail.

#Mame Launcher

#GUI launcher for MAME games

#First 'hack' 15th June 2005

#Hacking again 19th August



import sys, os, subprocess



from Tkinter import *



class Mamelaunch(Frame):

    """ GUI application to display MAME games in 

    a list, then launch them. """ 

    def __init__(self, master):

        """ Initialize the frame. """

        Frame.__init__(self, master)

        self.grid()

        self.create_widgets()

        self.listgames()



    def create_widgets(self):

        """ Create button, text, and entry widgets.
"""

        # create instruction label

        self.inst_lbl = Label(self, text = "Please
select a game")

        self.inst_lbl.grid(row = 0, column = 0,
columnspan = 2, sticky = W)



        # create label for password      

        self.pw_lbl = Label(self, text = "Click OK
when ready ")

        self.pw_lbl.grid(row = 12, column = 0, sticky
= W)

        

        #create the scrollbar for the listbox

        self.yScroll = Scrollbar ( self,
orient=VERTICAL )

        self.yScroll.grid ( row=1, column=1,
sticky=N+S )



        # create listbox to list games

        self.lstbx =Listbox(self, height = 20,
yscrollcommand=self.yScroll.set, borderwidth = 5,

                            relief = "sunken",
highlightcolor = "blue", selectbackground="orange",

                            selectmode="single")

        self.lstbx.grid(row = 1, column =
0,sticky=N+S+W)

        #lock the vertical scroll to the listbox.

        self.yScroll["command"] = self.lstbx.yview

        

        # create ok button

        self.submit_bttn = Button(self, text = "OK")

        self.submit_bttn.grid(row = 12, column = 1,
sticky = S+W)

        self.submit_bttn.bind("<Button-1>",
self.launchmame)



        # create quit button

        self.submit_bttn = Button(self, text = "Quit",
command = self.quit)

        self.submit_bttn.grid(row = 12, column = 2,
sticky = S+W)



    #Try reading list in prior to creating relevant
widgets

    def listgames(self):

        """reads list and populates listbox"""

        try:

            mamefile = open('C:\\mamelist.txt',
'r').readlines()

        except EnvironmentError:

            print "Please check file is in directory"

        else:

            #split list, populate listbox

            for game in mamefile:

                game = game.rstrip()

                self.lstbx.insert(END, game)

            

    def launchmame(self, event):

        """Mechanism to launch MAME game"""

        selection = self.lstbx.curselection()

        print selection

        os.system("C:\\mame096b\\mame.exe"+""+
selection)

        

#        try:

#            os.system(echo "game")

#        except:

#            SystemError(), "Command not found"



# main

root = Tk()

root.title("MAME Launcher")

root.geometry("220x330")



app = Mamelaunch(root)





root.mainloop()




		
___________________________________________________________ 
To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com

From dyoo at hkn.eecs.berkeley.edu  Fri Sep  9 23:23:33 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 9 Sep 2005 14:23:33 -0700 (PDT)
Subject: [Tutor] mamelauncher
In-Reply-To: <20050909210456.12127.qmail@web25907.mail.ukl.yahoo.com>
Message-ID: <Pine.LNX.4.44.0509091409390.3556-100000@hkn.eecs.berkeley.edu>



On Fri, 9 Sep 2005, Max Russell wrote:

> I've been working on this for ages and am having real problems with
> getting the wiring for a selected game to launch when I click OK.
>
> I haven't added my error handling yet.

[code cut]


Hi Max,

Hmmm... Out of curiosity, what happens if you try doing it without the
GUI?

Let's try to isolate the problem; it's not clear at the moment if there's
something weird with the GUI, or if there's something weird with the
os.system() call.

If you can write a quick test case that calls os.system() in the same way,
then we can be more sure what's causing the problem.


I see that you have a function called launchmame:

    def launchmame(self, event):
        selection = self.lstbx.curselection()
        os.system("C:\\mame096b\\mame.exe"+""+selection)

(Ah.  I do see a possible problem here, but I want YOU to see it too.
*grin*)



Try testing out the function:

######
def run_mame_selection(selection):
    os.system("C:\\mame096b\\mame.exe"+""+selection)
######

It's mostly a copy and paste of what you had in launchmame, except that we
explicitly pass in the selection string.  But try it out with a hardcoded
selection, and see if it succeeds.


As a side note, you may want to consider using the 'subprocess' module
instead of manually constructing command strings through string
concatenation: doing it by string concatenation is a bug-prone process.
'subprocess' is less bug-prone, and you can find out more here:

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


Good luck!


From alan.gauld at freenet.co.uk  Fri Sep  9 23:51:48 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Fri, 9 Sep 2005 22:51:48 +0100
Subject: [Tutor] mamelauncher
References: <20050909210456.12127.qmail@web25907.mail.ukl.yahoo.com>
Message-ID: <017501c5b588$ade828a0$0201a8c0@xp>

> I've been working on this for ages and am having real
> problems with getting the wiring for a selected game
> to launch when I click OK.

So what problems are you having? Do you get an error trace?
A superficial glance tells me only that
1) You might find using Tix will simplify your code(scrollable 
listboxes etc)
2) Your mailer seems to be adding extra lines, ie I assume the code 
isn't
   really double spaced? :-)

So whats the specific problem?
Oh yes - and what version of Python?

Alan G.

> I haven't added my error handling yet.
>
> Can anyone help?
>
> I've tried using spawn, system etc etc to no avail.
>
> #Mame Launcher
>
> #GUI launcher for MAME games
>
> #First 'hack' 15th June 2005
>
> #Hacking again 19th August
>
>
>
> import sys, os, subprocess
>
>
>
> from Tkinter import *
>
>
>
> class Mamelaunch(Frame):
>
>    """ GUI application to display MAME games in
>
>    a list, then launch them. """
>
>    def __init__(self, master):
>
>        """ Initialize the frame. """
>
>        Frame.__init__(self, master)
>
>        self.grid()
>
>        self.create_widgets()
>
>        self.listgames()
>
>
>
>    def create_widgets(self):
>
>        """ Create button, text, and entry widgets.
> """
>
>        # create instruction label
>
>        self.inst_lbl = Label(self, text = "Please
> select a game")
>
>        self.inst_lbl.grid(row = 0, column = 0,
> columnspan = 2, sticky = W)
>
>
>
>        # create label for password
>
>        self.pw_lbl = Label(self, text = "Click OK
> when ready ")
>
>        self.pw_lbl.grid(row = 12, column = 0, sticky
> = W)
>
>
>
>        #create the scrollbar for the listbox
>
>        self.yScroll = Scrollbar ( self,
> orient=VERTICAL )
>
>        self.yScroll.grid ( row=1, column=1,
> sticky=N+S )
>
>
>
>        # create listbox to list games
>
>        self.lstbx =Listbox(self, height = 20,
> yscrollcommand=self.yScroll.set, borderwidth = 5,
>
>                            relief = "sunken",
> highlightcolor = "blue", selectbackground="orange",
>
>                            selectmode="single")
>
>        self.lstbx.grid(row = 1, column =
> 0,sticky=N+S+W)
>
>        #lock the vertical scroll to the listbox.
>
>        self.yScroll["command"] = self.lstbx.yview
>
>
>
>        # create ok button
>
>        self.submit_bttn = Button(self, text = "OK")
>
>        self.submit_bttn.grid(row = 12, column = 1,
> sticky = S+W)
>
>        self.submit_bttn.bind("<Button-1>",
> self.launchmame)
>
>
>
>        # create quit button
>
>        self.submit_bttn = Button(self, text = "Quit",
> command = self.quit)
>
>        self.submit_bttn.grid(row = 12, column = 2,
> sticky = S+W)
>
>
>
>    #Try reading list in prior to creating relevant
> widgets
>
>    def listgames(self):
>
>        """reads list and populates listbox"""
>
>        try:
>
>            mamefile = open('C:\\mamelist.txt',
> 'r').readlines()
>
>        except EnvironmentError:
>
>            print "Please check file is in directory"
>
>        else:
>
>            #split list, populate listbox
>
>            for game in mamefile:
>
>                game = game.rstrip()
>
>                self.lstbx.insert(END, game)
>
>
>
>    def launchmame(self, event):
>
>        """Mechanism to launch MAME game"""
>
>        selection = self.lstbx.curselection()
>
>        print selection
>
>        os.system("C:\\mame096b\\mame.exe"+""+
> selection)
>
>
>
> #        try:
>
> #            os.system(echo "game")
>
> #        except:
>
> #            SystemError(), "Command not found"
>
>
>
> # main
>
> root = Tk()
>
> root.title("MAME Launcher")
>
> root.geometry("220x330")
>
>
>
> app = Mamelaunch(root)
>
>
>
>
>
> root.mainloop()
>
>
>
>
>
> ___________________________________________________________
> To help you stay safe and secure online, we've developed the all new 
> Yahoo! Security Centre. http://uk.security.yahoo.com
>
> 


From max_russell2000 at yahoo.co.uk  Sat Sep 10 09:41:52 2005
From: max_russell2000 at yahoo.co.uk (Max Russell)
Date: Sat, 10 Sep 2005 08:41:52 +0100 (BST)
Subject: [Tutor] mamelauncher
In-Reply-To: <017501c5b588$ade828a0$0201a8c0@xp>
Message-ID: <20050910074152.42208.qmail@web25902.mail.ukl.yahoo.com>

I was using 2.3 but upgraded to 2.4 last night because
I had read about the subprocess module (then Danny
also brought tat to my attention.)

The wierd spacing is just Yahoo, sorry!

I'm probably going to try the same project in WX and
then QT, just to get a flavour.

thanks
Max
--- Alan G <alan.gauld at freenet.co.uk> wrote:

> > I've been working on this for ages and am having
> real
> > problems with getting the wiring for a selected
> game
> > to launch when I click OK.
> 
> So what problems are you having? Do you get an error
> trace?
> A superficial glance tells me only that
> 1) You might find using Tix will simplify your
> code(scrollable 
> listboxes etc)
> 2) Your mailer seems to be adding extra lines, ie I
> assume the code 
> isn't
>    really double spaced? :-)
> 
> So whats the specific problem?
> Oh yes - and what version of Python?
> 
> Alan G.
> 
> > I haven't added my error handling yet.
> >
> > Can anyone help?
> >
> > I've tried using spawn, system etc etc to no
> avail.
> >
> > #Mame Launcher
> >
> > #GUI launcher for MAME games
> >
> > #First 'hack' 15th June 2005
> >
> > #Hacking again 19th August
> >
> >
> >
> > import sys, os, subprocess
> >
> >
> >
> > from Tkinter import *
> >
> >
> >
> > class Mamelaunch(Frame):
> >
> >    """ GUI application to display MAME games in
> >
> >    a list, then launch them. """
> >
> >    def __init__(self, master):
> >
> >        """ Initialize the frame. """
> >
> >        Frame.__init__(self, master)
> >
> >        self.grid()
> >
> >        self.create_widgets()
> >
> >        self.listgames()
> >
> >
> >
> >    def create_widgets(self):
> >
> >        """ Create button, text, and entry widgets.
> > """
> >
> >        # create instruction label
> >
> >        self.inst_lbl = Label(self, text = "Please
> > select a game")
> >
> >        self.inst_lbl.grid(row = 0, column = 0,
> > columnspan = 2, sticky = W)
> >
> >
> >
> >        # create label for password
> >
> >        self.pw_lbl = Label(self, text = "Click OK
> > when ready ")
> >
> >        self.pw_lbl.grid(row = 12, column = 0,
> sticky
> > = W)
> >
> >
> >
> >        #create the scrollbar for the listbox
> >
> >        self.yScroll = Scrollbar ( self,
> > orient=VERTICAL )
> >
> >        self.yScroll.grid ( row=1, column=1,
> > sticky=N+S )
> >
> >
> >
> >        # create listbox to list games
> >
> >        self.lstbx =Listbox(self, height = 20,
> > yscrollcommand=self.yScroll.set, borderwidth = 5,
> >
> >                            relief = "sunken",
> > highlightcolor = "blue",
> selectbackground="orange",
> >
> >                            selectmode="single")
> >
> >        self.lstbx.grid(row = 1, column =
> > 0,sticky=N+S+W)
> >
> >        #lock the vertical scroll to the listbox.
> >
> >        self.yScroll["command"] = self.lstbx.yview
> >
> >
> >
> >        # create ok button
> >
> >        self.submit_bttn = Button(self, text =
> "OK")
> >
> >        self.submit_bttn.grid(row = 12, column = 1,
> > sticky = S+W)
> >
> >        self.submit_bttn.bind("<Button-1>",
> > self.launchmame)
> >
> >
> >
> >        # create quit button
> >
> >        self.submit_bttn = Button(self, text =
> "Quit",
> > command = self.quit)
> >
> >        self.submit_bttn.grid(row = 12, column = 2,
> > sticky = S+W)
> >
> >
> >
> >    #Try reading list in prior to creating relevant
> > widgets
> >
> >    def listgames(self):
> >
> >        """reads list and populates listbox"""
> >
> >        try:
> >
> >            mamefile = open('C:\\mamelist.txt',
> > 'r').readlines()
> >
> >        except EnvironmentError:
> >
> >            print "Please check file is in
> directory"
> >
> >        else:
> >
> >            #split list, populate listbox
> >
> >            for game in mamefile:
> >
> >                game = game.rstrip()
> >
> >                self.lstbx.insert(END, game)
> >
> >
> >
> >    def launchmame(self, event):
> >
> >        """Mechanism to launch MAME game"""
> >
> >        selection = self.lstbx.curselection()
> >
> >        print selection
> >
> >        os.system("C:\\mame096b\\mame.exe"+""+
> > selection)
> >
> >
> >
> > #        try:
> >
> > #            os.system(echo "game")
> >
> > #        except:
> >
> > #            SystemError(), "Command not found"
> >
> >
> >
> > # main
> >
> > root = Tk()
> >
> > root.title("MAME Launcher")
> >
> > root.geometry("220x330")
> >
> >
> >
> > app = Mamelaunch(root)
> >
> >
> >
> >
> >
> > root.mainloop()
> >
> >
> >
> >
> >
> >
>
___________________________________________________________
> > To help you stay safe and secure online, we've
> developed the all new 
> > Yahoo! Security Centre.
> http://uk.security.yahoo.com
> >
> > 
> 
> 



		
___________________________________________________________ 
To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre. http://uk.security.yahoo.com

From billburns at pennswoods.net  Sun Sep 11 16:25:55 2005
From: billburns at pennswoods.net (Bill Burns)
Date: Sun, 11 Sep 2005 10:25:55 -0400
Subject: [Tutor] Parsing os.popen(command) output
Message-ID: <43243E73.8050603@pennswoods.net>

Hi,

I'm parsing some output from a command that I execute with os.popen.
This command (tiffinfo) displays information about Tiff images. The
solution I'm using does work, but I'm wondering there's a 'better' way
to do it.

Here's the typical output from the command:
[start output]
TIFF Directory at offset 0x8

   Subfile Type: (0 = 0x0)

   Image Width: 12000 Image Length: 16800

   Resolution: 400, 400 pixels/inch

   Bits/Sample: 1

   Compression Scheme: CCITT Group 4

   Photometric Interpretation: min-is-white

   Samples/Pixel: 1

   Rows/Strip: 16800

   Planar Configuration: single image plane

   DocumentName: buzzsaw.com
[end output]

I need to return the size (width & length) in inches of the Tiff. So I
need the information on lines:

Image Width: 12000 Image Length: 16800
Resolution: 400, 400 pixels/inch

Example: 12000 / 400 = 30 & 16800 / 400 = 42, so the Tiff is 30" x 42".

Here's how I'm doing it:
[start code]
import os
import re

filename = 'C:/Tiff Files/Large Tiffs/Nbm001.TIF'
command = 'tiffinfo "%s"' % (filename)
p = re.compile('\d+')

def getTiffWidthLength():
     tmp = []
     s = []
     r = []
     for line in os.popen(command).readlines():
         if line.startswith('  Image Width:') or \
            line.startswith('  Resolution:'):
            tmp.append(line.strip(' \n'))
     s.append(tmp[0])
     r.append(tmp[1])
     for wl in s:
         size = p.findall(wl)
     for i in r:
         res = p.findall(i)
     width = int(size[0]) / int(res[0])
     length = int(size[1]) / int(res[1])
     print (width, length)

if __name__ == '__main__':
     getTiffWidthLength()
[end code]

Like I said, it does work but can it be improved upon?

Thanks for any help.

Bill






From kent37 at tds.net  Sun Sep 11 16:47:58 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 11 Sep 2005 10:47:58 -0400
Subject: [Tutor] Parsing os.popen(command) output
In-Reply-To: <43243E73.8050603@pennswoods.net>
References: <43243E73.8050603@pennswoods.net>
Message-ID: <4324439E.9050707@tds.net>

Bill Burns wrote:
> Hi,
> 
> I'm parsing some output from a command that I execute with os.popen.
> 
> Here's the typical output from the command:
> [start output]
> TIFF Directory at offset 0x8
> 
>    Subfile Type: (0 = 0x0)
> 
>    Image Width: 12000 Image Length: 16800
> 
>    Resolution: 400, 400 pixels/inch
> 
>    Bits/Sample: 1
> 
>    Compression Scheme: CCITT Group 4
> 
>    Photometric Interpretation: min-is-white
> 
>    Samples/Pixel: 1
> 
>    Rows/Strip: 16800
> 
>    Planar Configuration: single image plane
> 
>    DocumentName: buzzsaw.com
> [end output]
> 
> I need to return the size (width & length) in inches of the Tiff. So I
> need the information on lines:
> 
> Image Width: 12000 Image Length: 16800
> Resolution: 400, 400 pixels/inch
> 
> Example: 12000 / 400 = 30 & 16800 / 400 = 42, so the Tiff is 30" x 42".
> 
> def getTiffWidthLength():
>      tmp = []
>      s = []
>      r = []
>      for line in os.popen(command).readlines():
>          if line.startswith('  Image Width:') or \
>             line.startswith('  Resolution:'):
>             tmp.append(line.strip(' \n'))
>      s.append(tmp[0])
>      r.append(tmp[1])
>      for wl in s:
>          size = p.findall(wl)
>      for i in r:
>          res = p.findall(i)
>      width = int(size[0]) / int(res[0])
>      length = int(size[1]) / int(res[1])
>      print (width, length)
> 
> if __name__ == '__main__':
>      getTiffWidthLength()
> [end code]

I would process the data as I find it rather than use all the helper lists. The data format is simple enough that str.split() can be used to extract it. I used float() instead of int() so it will get the correct answer when the dimensions are not whole inches. Something like this:

def getTiffWidthLength():
     for line in os.popen(command).readlines():
         if line.startswith('  Image Width:'):
            data = line.strip().split()
            rawWidth = float(data[2])
            rawLength = float(data[5])
         elif line.startswith('  Resolution:'):
            data = line.strip().split()
            wRes = float(data[1][1:])
            lRes = float(data[2])

     width = rawWidth / wRes
     length = rawLength / lRes
     print width, length

Kent


From mattwarren04 at msn.com  Sun Sep 11 18:50:43 2005
From: mattwarren04 at msn.com (Matt Warren)
Date: Sun, 11 Sep 2005 16:50:43 +0000
Subject: [Tutor] hey i need some help here
Message-ID: <BAY107-F15071B8683649FD207ADA5D09A0@phx.gbl>

I just started attempting to program and thought i would try python as my 
first tool. However following the beginners guide on their page it says to 
insert python as a command and that it should come up with the program 
information. When i insert python it says it is not recognizable as an 
internal or external command. can somebody help me?

_________________________________________________________________
Express yourself instantly with MSN Messenger! Download today - it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/


From benvinger at yahoo.co.uk  Sun Sep 11 19:02:46 2005
From: benvinger at yahoo.co.uk (Ben Vinger)
Date: Sun, 11 Sep 2005 18:02:46 +0100 (BST)
Subject: [Tutor] hey i need some help here
In-Reply-To: <BAY107-F15071B8683649FD207ADA5D09A0@phx.gbl>
Message-ID: <20050911170246.90702.qmail@web25801.mail.ukl.yahoo.com>

It is almost certain that you are using MS Windows,
and that Python is not in you "system path".
If so, here's what to do:

Add the top-level Python directory to your Windows
"PATH".  On Windows NT this is done with Control
Panel/System/Environment.  On Windows 2000 and Windows
XP it is done with Control
Panel/System/Advanced/Environment Variables.  Edit the
PATH environment variable in the System settings to
add C:\Python22 or C:\Program Files\Python22 (or
wherever you put Python)

(taken from
http://cars9.uchicago.edu/software/python/)

Ben

--- Matt Warren <mattwarren04 at msn.com> wrote:

> I just started attempting to program and thought i
> would try python as my 
> first tool. However following the beginners guide on
> their page it says to 
> insert python as a command and that it should come
> up with the program 
> information. When i insert python it says it is not
> recognizable as an 
> internal or external command. can somebody help me?
> 


		
___________________________________________________________ 
How much free photo storage do you get? Store your holiday 
snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com

From billburns at pennswoods.net  Sun Sep 11 21:04:32 2005
From: billburns at pennswoods.net (Bill Burns)
Date: Sun, 11 Sep 2005 15:04:32 -0400
Subject: [Tutor] Parsing os.popen(command) output
In-Reply-To: <4324439E.9050707@tds.net>
References: <43243E73.8050603@pennswoods.net> <4324439E.9050707@tds.net>
Message-ID: <43247FC0.9080606@pennswoods.net>

[Bill]
>>Here's the typical output from the command:
>>[start output]
>>TIFF Directory at offset 0x8
>>
>>   Subfile Type: (0 = 0x0)
>>
>>   Image Width: 12000 Image Length: 16800
>>
>>   Resolution: 400, 400 pixels/inch
>>
>>   Bits/Sample: 1
>>
>>   Compression Scheme: CCITT Group 4
>>
>>   Photometric Interpretation: min-is-white
>>
>>   Samples/Pixel: 1
>>
>>   Rows/Strip: 16800
>>
>>   Planar Configuration: single image plane
>>
>>   DocumentName: buzzsaw.com
>>[end output]
>>
>>I need to return the size (width & length) in inches of the Tiff. So I
>>need the information on lines:
>>
>>Image Width: 12000 Image Length: 16800
>>Resolution: 400, 400 pixels/inch
>>
>>Example: 12000 / 400 = 30 & 16800 / 400 = 42, so the Tiff is 30" x 42".
>>

[Kent]
> I would process the data as I find it rather than use all the helper lists. The data format is simple enough that str.split() can be used to extract it. I used float() instead of int() so it will get the correct answer when the dimensions are not whole inches. Something like this:
> 
> def getTiffWidthLength():
>      for line in os.popen(command).readlines():
>          if line.startswith('  Image Width:'):
>             data = line.strip().split()
>             rawWidth = float(data[2])
>             rawLength = float(data[5])
>          elif line.startswith('  Resolution:'):
>             data = line.strip().split()
>             wRes = float(data[1][1:])
>             lRes = float(data[2])
> 
>      width = rawWidth / wRes
>      length = rawLength / lRes
>      print width, length
> 

Kent,

Thank you for the reply! I knew there had to be a different way to do
it, I didn't like the three lists in there either :-)

One thing:
I had to change the line

wRes = float(data[1][1:])

it was returning '00,' (zero, zero, comma) instead of '400', so I
changed it to this:

wRes = float(data[1][:3])

but then I thought, what if I get a tif with a resolution that is <>
than 3 digits?

So I opted for this

wRes = float(data[1].strip(','))

which seems to work fine.

Thanks again!!

Bill




From singingxduck at gmail.com  Sun Sep 11 21:49:10 2005
From: singingxduck at gmail.com (Orri Ganel)
Date: Sun, 11 Sep 2005 15:49:10 -0400
Subject: [Tutor] Parsing os.popen(command) output
In-Reply-To: <43247FC0.9080606@pennswoods.net>
References: <43243E73.8050603@pennswoods.net> <4324439E.9050707@tds.net>
	<43247FC0.9080606@pennswoods.net>
Message-ID: <43248A36.5040600@gmail.com>

Bill Burns wrote:

>Kent,
>
>Thank you for the reply! I knew there had to be a different way to do
>it, I didn't like the three lists in there either :-)
>
>One thing:
>I had to change the line
>
>wRes = float(data[1][1:])
>
>it was returning '00,' (zero, zero, comma) instead of '400', so I
>changed it to this:
>
>wRes = float(data[1][:3])
>
>but then I thought, what if I get a tif with a resolution that is <>
>than 3 digits?
>
>So I opted for this
>
>wRes = float(data[1].strip(','))
>
>which seems to work fine.
>
>Thanks again!!
>
>Bill
>
>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
You could just do

wRes = float(data[1][:-1]) (up to the last digit, which would be the comma)

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.


From damien.gouteux at gmail.com  Sun Sep 11 22:47:34 2005
From: damien.gouteux at gmail.com (Damien Gouteux)
Date: Sun, 11 Sep 2005 22:47:34 +0200
Subject: [Tutor] Venom / Python23.dll missing
In-Reply-To: <43248A36.5040600@gmail.com>
References: <43243E73.8050603@pennswoods.net>
	<4324439E.9050707@tds.net>	<43247FC0.9080606@pennswoods.net>
	<43248A36.5040600@gmail.com>
Message-ID: <432497E6.4070609@gmail.com>

Hi all.
I try to run Venom, a Python binding for the Irrlicht engine. But I need 
python23.dll. This dll is generated by py2exe, but I have only Python 
2.4 installed on my PC, so I can have only python24.dll. If somebody 
could give a link to grap it, I will be pleased.
Thank you.
Damien G.

From billburns at pennswoods.net  Sun Sep 11 23:23:58 2005
From: billburns at pennswoods.net (Bill Burns)
Date: Sun, 11 Sep 2005 17:23:58 -0400
Subject: [Tutor] Parsing os.popen(command) output
In-Reply-To: <43248A36.5040600@gmail.com>
References: <43243E73.8050603@pennswoods.net> <4324439E.9050707@tds.net>
	<43247FC0.9080606@pennswoods.net> <43248A36.5040600@gmail.com>
Message-ID: <4324A06E.8020200@pennswoods.net>

Bill wrote:
>> So I opted for this
>>
>> wRes = float(data[1].strip(','))
>>
>> which seems to work fine.

Orri wrote:
> You could just do
> 
> wRes = float(data[1][:-1]) (up to the last digit, which would be the comma)

Orri,

Thank you!

I had never used slicing before (until today). I learn something new 
everyday!

Bill

From janos.juhasz at VELUX.com  Mon Sep 12 13:41:25 2005
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Mon, 12 Sep 2005 13:41:25 +0200
Subject: [Tutor] replace string in a sequentially read stream
In-Reply-To: <mailman.51.1126173614.14249.tutor@python.org>
Message-ID: <OF9160DA02.0D65E11B-ONC125707A.003C1535-C125707A.004037BB@velux.com>

Dear Guys,

I have to run the next regexp change in a stream:

import re

wrongcode = re.compile(r'(.*)b24704T')

f = open('testfile.txt')
while 1:
      sequence = f.read(1024)
      sequence = wrongcode.sub(r'\1b24700T', sequence)
      print sequence

My original solution was to keep the last part of the sequence till the
 next sequence hasn't been arrived


while 1:
      try:
            sequence = f.read(1024)
            try:
                  sequence = prevend + sequence
            except:
                  pass
            sequence = wrongcode.sub(r'\1b24700T', sequence)
            prevend = sequence[-20:] # keep the end of the sequence till we
haven't got the complete picture
            sequence = sequence[:-20]     # the first part was checked
correctly
            if not sequence:
                  print prevend
                  break
            print sequence
      except:
            break


In the real sample it works on an IP socket.

Have got someone better idea ?
Probably it is better to work with two sequence.



Best regards,
J?nos


From andy.dani at lycos.com  Mon Sep 12 14:35:52 2005
From: andy.dani at lycos.com (Andy Dani)
Date: Mon, 12 Sep 2005 07:35:52 -0500
Subject: [Tutor] upgrading from 2.3 to 2.4.1 on Mandrake Linux 10.1
Message-ID: <20050912123552.7301ACA08E@ws7-4.us4.outblaze.com>

Hi,

Which is the best location to install Python in Linux? Should it be under one directory or different (like lib, doc, bin etc.)?

I followed installation instructions in "inst.pdf" from python documents. I can see that Python 2.4.1 has been installed in /user/lib/local by standard installation procedure. When I launch my IDLE or "Python" at shell, Python 2.3 comes up! Why? Do I need to upgrade any other config files? 

Also, I am looking for help in upgrading xwPython package, OpenGL package, and installation of BOA constructor. They go in which directories?

Thank You

Nirav

-- 
_______________________________________________

Search for businesses by name, location, or phone number.  -Lycos Yellow Pages

http://r.lycos.com/r/yp_emailfooter/http://yellowpages.lycos.com/default.asp?SRC=lycos10


From alan.gauld at freenet.co.uk  Mon Sep 12 16:25:01 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Mon, 12 Sep 2005 15:25:01 +0100
Subject: [Tutor] hey i need some help here
References: <BAY107-F15071B8683649FD207ADA5D09A0@phx.gbl>
Message-ID: <005f01c5b7a5$c365c240$0201a8c0@xp>


>I just started attempting to program and thought i would try python 
>as my
> first tool. However following the beginners guide on their page it 
> says to insert python as a command and that it should come up with 
> the program information.

Have you downloaded Python and installed yet?
You need to do that before you can use it.

> When i insert python it says it is not recognizable as an internal 
> or external command. can somebody help me?

The installer should set everything up OK, but try typing

PATH

at the OS prompt and see if Python appears anywhere in
the output.

HTH,

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


From 3dbernard at gmail.com  Mon Sep 12 16:30:20 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon, 12 Sep 2005 10:30:20 -0400
Subject: [Tutor] Partly OT: order of renaming files and directories
Message-ID: <61d0e2b40509120730299a2efc@mail.gmail.com>

Hello,

I'm creating a script that will rename directories and files (hence
the regular expression thing I asked about last week). I just wanted
to ask if there is a recommended order to rename stuff, because I want
to avoid any potential problem.

What I mean:
I traverse some areas of the file server with os.walk(). If I want to
rename a directory, is it better that I rename the directory curretly
being visited, or should I iterate the files and directories in the
current directory and rename them instead?

To summarize.

Renaming the current directory:


# Iterate roots
for sRoot in aRoots:
	
	print '\nWalking root %s...\n' % sRoot
	
	# Walk-down root
	for sDir, aDirs, aFiles in os.walk( sRoot, True ):
		
		sNewDir = oReL.sub( r'\g<1>0\2', sDir )
		if sNewDir != sSubDir: print '%s changed to %s' % (sDir, sNewDir)
		else:
			sNewDir = oReQ.sub( r'\g<1>0\2', sDir )
			if sNewDir != sSubDir: print '%s changed to %s ' % (sDir, sNewDir)
	
	print 'Root %s DONE.' % sRoot



Renaming the content of the current directory:


# Iterate roots
for sRoot in aRoots:
	
	print '\nWalking root %s...\n' % sRoot
	
	# Walk-down root
	for sDir, aDirs, aFiles in os.walk( sRoot, True ):
		
		for sSubDir in aDirs:
			sNewSubDir = oReL.sub( r'\g<1>0\2', sSubDir )
			if sNewSubDir != sSubDir: print '%s changed to %s' % (sSubDir, sNewSubDir)
			else:
				sNewSubDir = oReQ.sub( r'\g<1>0\2', sSubDir )
				if sNewSubDir != sSubDir: print '%s changed to %s ' % (sSubDir, sNewSubDir)
	
	print 'Root %s DONE.' % sRoot


Thanks
Bernard

From kent37 at tds.net  Mon Sep 12 16:49:20 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 12 Sep 2005 10:49:20 -0400
Subject: [Tutor] Partly OT: order of renaming files and directories
In-Reply-To: <61d0e2b40509120730299a2efc@mail.gmail.com>
References: <61d0e2b40509120730299a2efc@mail.gmail.com>
Message-ID: <43259570.50209@tds.net>

Bernard Lebel wrote:
> Hello,
> 
> I'm creating a script that will rename directories and files (hence
> the regular expression thing I asked about last week). I just wanted
> to ask if there is a recommended order to rename stuff, because I want
> to avoid any potential problem.
> 
> What I mean:
> I traverse some areas of the file server with os.walk(). If I want to
> rename a directory, is it better that I rename the directory curretly
> being visited, or should I iterate the files and directories in the
> current directory and rename them instead?

Assuming you are going to actually rename the directories on disk (the code below just changes the names in a local string) I don't think the second approach will work as written. The list of directories yielded by os.walk() can be changed in the client to affect which sub-directories are iterated. From the docs on os.walk():

"...the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again."

So the list of dirnames is the list that will be attempted in the recursive step; if you rename them without updating dirnames the renamed subdir will not be found. At least that is how I read it; you could easily test this by trying it and looking at the log.

So I would do the first method. If you want to use the second approach I think you will have to modify dirnames as well as renaming the file on disk.

Kent
> 
> To summarize.
> 
> Renaming the current directory:
> 
> 
> # Iterate roots
> for sRoot in aRoots:
> 	
> 	print '\nWalking root %s...\n' % sRoot
> 	
> 	# Walk-down root
> 	for sDir, aDirs, aFiles in os.walk( sRoot, True ):
> 		
> 		sNewDir = oReL.sub( r'\g<1>0\2', sDir )
> 		if sNewDir != sSubDir: print '%s changed to %s' % (sDir, sNewDir)
> 		else:
> 			sNewDir = oReQ.sub( r'\g<1>0\2', sDir )
> 			if sNewDir != sSubDir: print '%s changed to %s ' % (sDir, sNewDir)
> 	
> 	print 'Root %s DONE.' % sRoot
> 
> 
> 
> Renaming the content of the current directory:
> 
> 
> # Iterate roots
> for sRoot in aRoots:
> 	
> 	print '\nWalking root %s...\n' % sRoot
> 	
> 	# Walk-down root
> 	for sDir, aDirs, aFiles in os.walk( sRoot, True ):
> 		
> 		for sSubDir in aDirs:
> 			sNewSubDir = oReL.sub( r'\g<1>0\2', sSubDir )
> 			if sNewSubDir != sSubDir: print '%s changed to %s' % (sSubDir, sNewSubDir)
> 			else:
> 				sNewSubDir = oReQ.sub( r'\g<1>0\2', sSubDir )
> 				if sNewSubDir != sSubDir: print '%s changed to %s ' % (sSubDir, sNewSubDir)
> 	
> 	print 'Root %s DONE.' % sRoot
> 
> 
> Thanks
> Bernard
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From rob.andrews at gmail.com  Mon Sep 12 16:55:49 2005
From: rob.andrews at gmail.com (Rob Andrews)
Date: Mon, 12 Sep 2005 09:55:49 -0500
Subject: [Tutor] directory recursion
In-Reply-To: <Pine.LNX.4.44.0509091256550.3556-100000@hkn.eecs.berkeley.edu>
References: <8d757d2e05090912344abe0f17@mail.gmail.com>
	<Pine.LNX.4.44.0509091256550.3556-100000@hkn.eecs.berkeley.edu>
Message-ID: <8d757d2e05091207552f1ed573@mail.gmail.com>

Thanks! That did the trick after very modest head scratching.

-Rob

On 9/9/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
> >
> > What's a nice, clean way to recursively scan through directories with
> > an arbitrary number of subdirectories?
> 
> Hi Rob,
> 
> You may want to look at os.walk():

From 3dbernard at gmail.com  Mon Sep 12 17:23:44 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon, 12 Sep 2005 11:23:44 -0400
Subject: [Tutor] Partly OT: order of renaming files and directories
In-Reply-To: <43259570.50209@tds.net>
References: <61d0e2b40509120730299a2efc@mail.gmail.com>
	<43259570.50209@tds.net>
Message-ID: <61d0e2b40509120823187c5480@mail.gmail.com>

Thanks Kent!

Bernard


On 9/12/05, Kent Johnson <kent37 at tds.net> wrote:
> Bernard Lebel wrote:
> > Hello,
> >
> > I'm creating a script that will rename directories and files (hence
> > the regular expression thing I asked about last week). I just wanted
> > to ask if there is a recommended order to rename stuff, because I want
> > to avoid any potential problem.
> >
> > What I mean:
> > I traverse some areas of the file server with os.walk(). If I want to
> > rename a directory, is it better that I rename the directory curretly
> > being visited, or should I iterate the files and directories in the
> > current directory and rename them instead?
> 
> Assuming you are going to actually rename the directories on disk (the code below just changes the names in a local string) I don't think the second approach will work as written. The list of directories yielded by os.walk() can be changed in the client to affect which sub-directories are iterated. From the docs on os.walk():
> 
> "...the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again."
> 
> So the list of dirnames is the list that will be attempted in the recursive step; if you rename them without updating dirnames the renamed subdir will not be found. At least that is how I read it; you could easily test this by trying it and looking at the log.
> 
> So I would do the first method. If you want to use the second approach I think you will have to modify dirnames as well as renaming the file on disk.
> 
> Kent
> >
> > To summarize.
> >
> > Renaming the current directory:
> >
> >
> > # Iterate roots
> > for sRoot in aRoots:
> >
> >       print '\nWalking root %s...\n' % sRoot
> >
> >       # Walk-down root
> >       for sDir, aDirs, aFiles in os.walk( sRoot, True ):
> >
> >               sNewDir = oReL.sub( r'\g<1>0\2', sDir )
> >               if sNewDir != sSubDir: print '%s changed to %s' % (sDir, sNewDir)
> >               else:
> >                       sNewDir = oReQ.sub( r'\g<1>0\2', sDir )
> >                       if sNewDir != sSubDir: print '%s changed to %s ' % (sDir, sNewDir)
> >
> >       print 'Root %s DONE.' % sRoot
> >
> >
> >
> > Renaming the content of the current directory:
> >
> >
> > # Iterate roots
> > for sRoot in aRoots:
> >
> >       print '\nWalking root %s...\n' % sRoot
> >
> >       # Walk-down root
> >       for sDir, aDirs, aFiles in os.walk( sRoot, True ):
> >
> >               for sSubDir in aDirs:
> >                       sNewSubDir = oReL.sub( r'\g<1>0\2', sSubDir )
> >                       if sNewSubDir != sSubDir: print '%s changed to %s' % (sSubDir, sNewSubDir)
> >                       else:
> >                               sNewSubDir = oReQ.sub( r'\g<1>0\2', sSubDir )
> >                               if sNewSubDir != sSubDir: print '%s changed to %s ' % (sSubDir, sNewSubDir)
> >
> >       print 'Root %s DONE.' % sRoot
> >
> >
> > Thanks
> > Bernard
> > _______________________________________________
> > 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
>

From klappnase at freenet.de  Mon Sep 12 19:31:32 2005
From: klappnase at freenet.de (Michael Lange)
Date: Mon, 12 Sep 2005 19:31:32 +0200
Subject: [Tutor] upgrading from 2.3 to 2.4.1 on Mandrake Linux 10.1
In-Reply-To: <20050912123552.7301ACA08E@ws7-4.us4.outblaze.com>
References: <20050912123552.7301ACA08E@ws7-4.us4.outblaze.com>
Message-ID: <20050912193132.4d4642a6.klappnase@freenet.de>

On Mon, 12 Sep 2005 07:35:52 -0500
"Andy Dani" <andy.dani at lycos.com> wrote:

> Hi,
> 
> Which is the best location to install Python in Linux? Should it be under one directory or different (like lib, doc, bin etc.)?
> 
> I followed installation instructions in "inst.pdf" from python documents. I can see that Python 2.4.1 has been installed in /user/lib/local by standard installation procedure. When I launch my IDLE or "Python" at shell, Python 2.3 comes up! Why? Do I need to upgrade any other config files? 
> 
> Also, I am looking for help in upgrading xwPython package, OpenGL package, and installation of BOA constructor. They go in which directories?
> 

Hi Nirav,

I recommend not to *upgrade* the existing python installation but simply install a second version.
The reason is that some system specific programs may depend on python-2.3 or one of the extensions
that are already installed.

If you are running Mandrake the best bet is to download mandrake's source rpm from 

   <http://fr2.rpmfind.net//linux/RPM/cooker/cooker/SRPMS/main/python-2.4.1-3mdk.src.html>

and build the binary RPM from it. After installing the RPM you should make sure
that the link "/usr/bin/python" points to "/usr/bin/python2.3" .

If you want to run the new python, just type "python2.4" (or in your scripts use the
shebang line "#!/usr/bin/env python2.4" )
(this should work if you already installed python-2.4 into /usr/local , too).

WxPython and OpenGL should probably be installed into the python2.x/site-packages directory,
BOA is (as far as I know) pure python and can be installed anywhere; if you want to run BOA with
python-2.4 you will probably have to edit the shebandg line in BOA's main program file (or type
python2.4 boa (or however the main program is called).

Maybe you can find mandrake source RPM's for these, too, which might make it easier for you
to install everything in the correct place.

I hope this helps

Michael

From max_russell2000 at yahoo.co.uk  Mon Sep 12 21:59:55 2005
From: max_russell2000 at yahoo.co.uk (Max Russell)
Date: Mon, 12 Sep 2005 20:59:55 +0100 (BST)
Subject: [Tutor] mamelauncher
In-Reply-To: <Pine.LNX.4.44.0509091409390.3556-100000@hkn.eecs.berkeley.edu>
Message-ID: <20050912195955.56224.qmail@web25908.mail.ukl.yahoo.com>

I've tried running that function, with a little Main
method like this:

import os

def run_mame_selection(selection):
    os.system("C:\\mame096b\\mame.exe"+""+selection)

#main
mine = "pacman"
run_mame_selection(mine)    

What I get is like a brief flash of the CMD prompt
like it is trying it and not waiting or getting some
kind of return.

I'm really not sure where I'm going wrong at all! I'll
try re-writing using sub-process as I've upped my
Python to 2.4.


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

> 
> 
> On Fri, 9 Sep 2005, Max Russell wrote:
> 
> > I've been working on this for ages and am having
> real problems with
> > getting the wiring for a selected game to launch
> when I click OK.
> >
> > I haven't added my error handling yet.
> 
> [code cut]
> 
> 
> Hi Max,
> 
> Hmmm... Out of curiosity, what happens if you try
> doing it without the
> GUI?
> 
> Let's try to isolate the problem; it's not clear at
> the moment if there's
> something weird with the GUI, or if there's
> something weird with the
> os.system() call.
> 
> If you can write a quick test case that calls
> os.system() in the same way,
> then we can be more sure what's causing the problem.
> 
> 
> I see that you have a function called launchmame:
> 
>     def launchmame(self, event):
>         selection = self.lstbx.curselection()
>        
> os.system("C:\\mame096b\\mame.exe"+""+selection)
> 
> (Ah.  I do see a possible problem here, but I want
> YOU to see it too.
> *grin*)
> 
> 
> 
> Try testing out the function:
> 
> ######
> def run_mame_selection(selection):
>     os.system("C:\\mame096b\\mame.exe"+""+selection)
> ######
> 
> It's mostly a copy and paste of what you had in
> launchmame, except that we
> explicitly pass in the selection string.  But try it
> out with a hardcoded
> selection, and see if it succeeds.
> 
> 
> As a side note, you may want to consider using the
> 'subprocess' module
> instead of manually constructing command strings
> through string
> concatenation: doing it by string concatenation is a
> bug-prone process.
> 'subprocess' is less bug-prone, and you can find out
> more here:
> 
>    
> http://www.python.org/doc/lib/module-subprocess.html
> 
> 
> Good luck!
> 
> 



		
___________________________________________________________ 
How much free photo storage do you get? Store your holiday 
snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com

From tuvas at email.arizona.edu  Mon Sep 12 21:59:10 2005
From: tuvas at email.arizona.edu (tuvas@email.arizona.edu)
Date: Mon, 12 Sep 2005 12:59:10 -0700
Subject: [Tutor] Python coding
Message-ID: <20050912125910.uaz7j4kgo88c804k@www.email.arizona.edu>

I am working on a project that we have built a C Text interface previously. We
want to be able to move this to a graphical interface, and after some studying,
we decided to use a python-based interface. We want to use as much of the old
code as possible, so we have decided to try an interface with python that will
send the old commands directly. EI, the old interface required that to do a
function called ping, you hit 0, so Python will basically tell the program to
hit 0. I have been looking up information on how to do this, and am coming up
short. Can you help me? Thank you!


From ewalker at micron.com  Mon Sep 12 22:16:59 2005
From: ewalker at micron.com (Eric Walker)
Date: Mon, 12 Sep 2005 14:16:59 -0600
Subject: [Tutor] Python coding
In-Reply-To: <20050912125910.uaz7j4kgo88c804k@www.email.arizona.edu>
References: <20050912125910.uaz7j4kgo88c804k@www.email.arizona.edu>
Message-ID: <200509121416.59522.ewalker@micron.com>

I think there is some software out there call SWIG that will create an 
interface to your C code within python...



On Monday 12 September 2005 01:59 pm, tuvas at email.arizona.edu wrote:
> I am working on a project that we have built a C Text interface previously.
> We want to be able to move this to a graphical interface, and after some
> studying, we decided to use a python-based interface. We want to use as
> much of the old code as possible, so we have decided to try an interface
> with python that will send the old commands directly. EI, the old interface
> required that to do a function called ping, you hit 0, so Python will
> basically tell the program to hit 0. I have been looking up information on
> how to do this, and am coming up short. Can you help me? Thank you!
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Eric Walker
EDA/CAD Engineer
Work: 208-368-2573

From alan.gauld at freenet.co.uk  Mon Sep 12 22:53:44 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Mon, 12 Sep 2005 21:53:44 +0100
Subject: [Tutor] mamelauncher
References: <20050912195955.56224.qmail@web25908.mail.ukl.yahoo.com>
Message-ID: <002001c5b7dc$10cebec0$0201a8c0@xp>

> import os
> 
> def run_mame_selection(selection):
>    os.system("C:\\mame096b\\mame.exe"+""+selection)
> 
> #main
> mine = "pacman"
> run_mame_selection(mine)    
> 
> What I get is like a brief flash of the CMD prompt

Open the command prompt first and run it from there.
(Or add a raw_input() line at the end.
We need to know what the error message looks like.
But it sounds like the problem is in the system call 
not your GUI stuff.

> try re-writing using sub-process as I've upped my
> Python to 2.4.

That might help but the system() call should work too, so 
I'd stick with it till we figure out whats happening.

HTH,

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

From kent37 at tds.net  Mon Sep 12 23:04:33 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 12 Sep 2005 17:04:33 -0400
Subject: [Tutor] Python coding
In-Reply-To: <20050912125910.uaz7j4kgo88c804k@www.email.arizona.edu>
References: <20050912125910.uaz7j4kgo88c804k@www.email.arizona.edu>
Message-ID: <4325ED61.5050502@tds.net>

tuvas at email.arizona.edu wrote:
> I am working on a project that we have built a C Text interface previously. We
> want to be able to move this to a graphical interface, and after some studying,
> we decided to use a python-based interface. We want to use as much of the old
> code as possible, so we have decided to try an interface with python that will
> send the old commands directly. EI, the old interface required that to do a
> function called ping, you hit 0, so Python will basically tell the program to
> hit 0. I have been looking up information on how to do this, and am coming up
> short. Can you help me? Thank you!

If you are running on Linux then pexpect may help you. (It requires the pty library module which is not available on Windows.)
http://pexpect.sourceforge.net/

Kent


From dyoo at hkn.eecs.berkeley.edu  Mon Sep 12 23:04:54 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 12 Sep 2005 14:04:54 -0700 (PDT)
Subject: [Tutor] mamelauncher
In-Reply-To: <002001c5b7dc$10cebec0$0201a8c0@xp>
Message-ID: <Pine.LNX.4.44.0509121401540.24967-100000@hkn.eecs.berkeley.edu>



On Mon, 12 Sep 2005, Alan G wrote:

> > def run_mame_selection(selection):
> >    os.system("C:\\mame096b\\mame.exe"+""+selection)

Hi Max,

If you're getting really stuck here, skip below for a hint.





Hint: in the defintion of run_mame_selection, there's some string
concatenation going on here:

######
def run_mame_selection(selection):
   os.system("C:\\mame096b\\mame.exe"+""+selection)
######

Why the empty string?


Best of wishes!


From cpu.crazy at gmail.com  Mon Sep 12 23:37:24 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Mon, 12 Sep 2005 15:37:24 -0600
Subject: [Tutor] Download an image of a site?
Message-ID: <4325F514.70800@gmail.com>

Hi,
I'm a Garfield fan and I thought that I'd make a program that would
enable me to read the online comics without opening firefox and typing
the url and waiting for all the other junk to load. Here's my code:

# import modules
import time
import urllib2


class data:
     # Define time and date
     todays_date = time.localtime(time.time())
     dayNum = time.strftime("%d", todays_date)
     monthNum = time.strftime("%m", todays_date)
     yearNum = time.strftime("%y", todays_date)
     yearNumFull = time.strftime("%Y", todays_date)

     # Define url and it's components
     stripName ="http://images.ucomics.com/comics/ga/%s/ga" % (yearNumFull)
     c_strip = "%s%s%s%s.gif" % (stripName, yearNum, monthNum, dayNum)
     f = ""

# Other info
c_strip_download = "Downloading Today's Garfield..."

# Errors
urllib2_URLError = """Temporary failure in name resolution.
This means that you may not be online or the site is down.
You may want to try again later."""

# Enough defining lets get our hands dirty.
try:
     data.f = urllib2.urlopen(data.c_strip)
except  urllib2.URLError:
     print urllib2_URLError

data.f.save("%s%s%s.gif" % (data.yearNum, data.monthNum, data.dayNum))

data.f.get()

I would like to know how to save the image to the computer's hard
drive. Is it something like f.save("%s%s%s.gif" % (yearNum, monthNum,
dayNum)) ?
thanks,
    Joseph





From glingl at aon.at  Tue Sep 13 01:15:58 2005
From: glingl at aon.at (Gregor Lingl)
Date: Tue, 13 Sep 2005 01:15:58 +0200
Subject: [Tutor] Annoying problem when importing a file (caused by IDLE?)
Message-ID: <43260C2E.40503@aon.at>

Hi pythonistas!

Recently I've encountered a very annoying problem when developing a 
program - more exactly a module - of several hundred lines using Idle. 
Of course I have a __name__=="__main__" section to test my classes,
which ran successfully every time, (except when there were bugs :-( in 
the code. ;-) )

moreover I use several test programs, which import that module.
When running these I got (repeatedly after doing some modifications) 
syntax error - messages, pointing to randomly scattered positions in the 
module file. Only random-hacking like deliberately inserting spaces in 
some expressions or deleting empty lines or comment-lines solved this
problem, which tends to re-occur after some more changes.

1) Did anybody experience similar behaviour?

2) Can anybody *explain* how it comes, that a module as a program for 
itself runs without problems, while it doesn't when imported by another 
program instead delivering incomprehensable syntax error messages? This 
occurs in the same way when running them from the commandline and even 
on different computers (running WindowsXP as os.)

3) Probably my file is contaminated by some non printing characters - 
although I don't know where they come from. Is there a simple way to 
check this assumption (e.g. using some simple editor, which shows these
"unfriendly" characters.)

4) I urgently feel, that I have to stop these annoyances. Do you know 
how I can do this?

Desperately

Gregor



-- 
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27



From cpu.crazy at gmail.com  Mon Sep 12 23:37:24 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Mon, 12 Sep 2005 15:37:24 -0600
Subject: [Tutor] Download an image of a site?
Message-ID: <4325F514.70800@gmail.com>

Hi,
I'm a Garfield fan and I thought that I'd make a program that would
enable me to read the online comics without opening firefox and typing
the url and waiting for all the other junk to load. Here's my code:

# import modules
import time
import urllib2


class data:
     # Define time and date
     todays_date = time.localtime(time.time())
     dayNum = time.strftime("%d", todays_date)
     monthNum = time.strftime("%m", todays_date)
     yearNum = time.strftime("%y", todays_date)
     yearNumFull = time.strftime("%Y", todays_date)

     # Define url and it's components
     stripName ="http://images.ucomics.com/comics/ga/%s/ga" % (yearNumFull)
     c_strip = "%s%s%s%s.gif" % (stripName, yearNum, monthNum, dayNum)
     f = ""

# Other info
c_strip_download = "Downloading Today's Garfield..."

# Errors
urllib2_URLError = """Temporary failure in name resolution.
This means that you may not be online or the site is down.
You may want to try again later."""

# Enough defining lets get our hands dirty.
try:
     data.f = urllib2.urlopen(data.c_strip)
except  urllib2.URLError:
     print urllib2_URLError

data.f.save("%s%s%s.gif" % (data.yearNum, data.monthNum, data.dayNum))

data.f.get()

I would like to know how to save the image to the computer's hard
drive. Is it something like f.save("%s%s%s.gif" % (yearNum, monthNum,
dayNum)) ?
thanks,
    Joseph





From cpu.crazy at gmail.com  Tue Sep 13 01:39:19 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Mon, 12 Sep 2005 17:39:19 -0600
Subject: [Tutor] Download an image of a site?
In-Reply-To: <1126562538.29089.10.camel@localhost.localdomain>
References: <4325F514.70800@gmail.com>
	<1126562538.29089.10.camel@localhost.localdomain>
Message-ID: <432611A7.7060608@gmail.com>

ZIYAD A. M. AL-BATLY wrote:

>Since you're running some kind of Unix (maybe Linux or FreeBSD), all
>these command are available for you.  By commands I mean: "cron",
>"wget", and "date".
>
>  
>
Wow. That's a good idea.. however this is a "gift" for someone who wants 
me to make a program to do it ( prefer python) and they use Windows XP 
(spit) (no offense, that's just my opinion.
For me this'll be perfect (till the program works, then I'll see wich is 
faster). Thanks

From wildcard2005 at comcast.net  Mon Sep 12 23:13:06 2005
From: wildcard2005 at comcast.net (Terry Kemmerer)
Date: Mon, 12 Sep 2005 14:13:06 -0700
Subject: [Tutor] Boa-Constructor
Message-ID: <1126559587.8796.12.camel@c-24-16-68-31.hsd1.wa.comcast.net>

Hey Guys,

I am trying to pick an IDE, and it seems to me that Boa-Constructor has
great potential. However, in searching google looking to see what others
have said, I am reading that the latest version of Boa-Constructor is
unstable at best and crashes a lot.....being said, at least, by those
promoting non-free IDE's. Yet, Boa-Constructor looks from the outside to
me, like a really great IDE. 

Does anyone who is using this latest version or who has tried this
latest version have any comments concerning its actual usability?

Thanks,

Terry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050912/983f1b13/attachment-0001.html

From nephish at xit.net  Tue Sep 13 01:57:34 2005
From: nephish at xit.net (nephish)
Date: Mon, 12 Sep 2005 18:57:34 -0500
Subject: [Tutor] Boa-Constructor
In-Reply-To: <1126559587.8796.12.camel@c-24-16-68-31.hsd1.wa.comcast.net>
References: <1126559587.8796.12.camel@c-24-16-68-31.hsd1.wa.comcast.net>
Message-ID: <432615EE.3080200@xit.net>

Terry Kemmerer wrote:

> Hey Guys,
>
> I am trying to pick an IDE, and it seems to me that Boa-Constructor 
> has great potential. However, in searching google looking to see what 
> others have said, I am reading that the latest version of 
> Boa-Constructor is unstable at best and crashes a lot.....being said, 
> at least, by those promoting non-free IDE's. Yet, Boa-Constructor 
> looks from the outside to me, like a really great IDE.
>
> Does anyone who is using this latest version or who has tried this 
> latest version have any comments concerning its actual usability?
>
> Thanks,
>
> Terry
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>
if you don't mind KDE, eric is really cool. I run gnome, but i use eric 
because of things like syntax error checking, etc.. i really dig it
sk

From cpu.crazy at gmail.com  Tue Sep 13 01:42:18 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Mon, 12 Sep 2005 17:42:18 -0600
Subject: [Tutor] Download an image of a site?
In-Reply-To: <1126562538.29089.10.camel@localhost.localdomain>
References: <4325F514.70800@gmail.com>
	<1126562538.29089.10.camel@localhost.localdomain>
Message-ID: <4326125A.80402@gmail.com>

ZIYAD A. M. AL-BATLY wrote:

>Since you're running some kind of Unix (maybe Linux or FreeBSD), all
>these command are available for you.  By commands I mean: "cron",
>"wget", and "date".
>
>  
>
Wow. That's a good idea.. however this is a "gift" for someone who wants 
me to make a program to do it ( prefer python) and they use Windows XP
For me this'll be perfect (till the program works, then I'll see wich is 
faster). Thanks


From kent37 at tds.net  Tue Sep 13 02:09:25 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 12 Sep 2005 20:09:25 -0400
Subject: [Tutor] Download an image of a site?
In-Reply-To: <4325F514.70800@gmail.com>
References: <4325F514.70800@gmail.com>
Message-ID: <432618B5.6080501@tds.net>

Joseph Quigley wrote:
> Hi,
> I'm a Garfield fan and I thought that I'd make a program that would
> enable me to read the online comics without opening firefox and typing
> the url and waiting for all the other junk to load. Here's my code:
> 
> # import modules
> import time
> import urllib2
> 
> 
> class data:
>      # Define time and date
>      todays_date = time.localtime(time.time())
>      dayNum = time.strftime("%d", todays_date)
>      monthNum = time.strftime("%m", todays_date)
>      yearNum = time.strftime("%y", todays_date)
>      yearNumFull = time.strftime("%Y", todays_date)
> 
>      # Define url and it's components
>      stripName ="http://images.ucomics.com/comics/ga/%s/ga" % (yearNumFull)
>      c_strip = "%s%s%s%s.gif" % (stripName, yearNum, monthNum, dayNum)
>      f = ""
> 
> # Other info
> c_strip_download = "Downloading Today's Garfield..."
> 
> # Errors
> urllib2_URLError = """Temporary failure in name resolution.
> This means that you may not be online or the site is down.
> You may want to try again later."""
> 
> # Enough defining lets get our hands dirty.
> try:
>      data.f = urllib2.urlopen(data.c_strip)
> except  urllib2.URLError:
>      print urllib2_URLError
> 
> data.f.save("%s%s%s.gif" % (data.yearNum, data.monthNum, data.dayNum))
> 
> data.f.get()

I don't think the object returned from urllib2.urlopen() has save() and get() methods. According to the docs urlopen() "returns a file-like object with two additional methods:

    * geturl() -- return the URL of the resource retrieved
    * info() -- return the meta-information of the page, as a dictionary-like object"

So you should treat data.f like an open file - use read() to get the contents into a variable. Then open a real (disk) file for writing and write it out. This section of the Python tutorial has a quick intro:
http://docs.python.org/tut/node9.html#SECTION009200000000000000000

Kent

> 
> I would like to know how to save the image to the computer's hard
> drive. Is it something like f.save("%s%s%s.gif" % (yearNum, monthNum,
> dayNum)) ?
> thanks,
>     Joseph
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From wildcard2005 at comcast.net  Tue Sep 13 03:12:16 2005
From: wildcard2005 at comcast.net (Terry Kemmerer)
Date: Mon, 12 Sep 2005 18:12:16 -0700
Subject: [Tutor] Boa-Constructor
In-Reply-To: <432615EE.3080200@xit.net>
References: <1126559587.8796.12.camel@c-24-16-68-31.hsd1.wa.comcast.net>
	<432615EE.3080200@xit.net>
Message-ID: <1126573936.8796.50.camel@c-24-16-68-31.hsd1.wa.comcast.net>

Nephish,

I run Mandriva Linux with Gnome, but also have the KDE desktop set up as
one of my optional desktops that I can log into for a session, and in
fact, I do run a lot of KDE stuff on gnome, like Konqueror, etc. 

I urpmi-ed Eric and will check it out. Thanks!

I liked the idea of Boa-Constructor because it is written with wxPython
and it is wxPython that I will be using on my eventual project, I
think.....  Although, so far, no one has responded to my usability
question concerning Boa-Constructor yet.

Terry




On Mon, 2005-09-12 at 18:57 -0500, nephish wrote:

> Terry Kemmerer wrote:
> 
> > Hey Guys,
> >
> > I am trying to pick an IDE, and it seems to me that Boa-Constructor 
> > has great potential. However, in searching google looking to see what 
> > others have said, I am reading that the latest version of 
> > Boa-Constructor is unstable at best and crashes a lot.....being said, 
> > at least, by those promoting non-free IDE's. Yet, Boa-Constructor 
> > looks from the outside to me, like a really great IDE.
> >
> > Does anyone who is using this latest version or who has tried this 
> > latest version have any comments concerning its actual usability?
> >
> > Thanks,
> >
> > Terry
> >
> >------------------------------------------------------------------------
> >
> >_______________________________________________
> >Tutor maillist  -  Tutor at python.org
> >http://mail.python.org/mailman/listinfo/tutor
> >  
> >
> if you don't mind KDE, eric is really cool. I run gnome, but i use eric 
> because of things like syntax error checking, etc.. i really dig it
> sk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050912/48b6a87f/attachment.html

From tktucker at gmail.com  Tue Sep 13 03:37:54 2005
From: tktucker at gmail.com (Tom Tucker)
Date: Mon, 12 Sep 2005 21:37:54 -0400
Subject: [Tutor] Where did those spaces come from?
Message-ID: <2a278ffe0509121837761767ef@mail.gmail.com>

Tutor,

Good evening! The goal is to parse a simple file and grab column one. 
Then print each value horizontally separated by a comma. 
Why is Python adding a space padding between each value? Please see below. 
Thanks ahead of time.




INPUT_FILE # unwanted lines removed
################################
5555 user at bdomain.com blah blah
1111 user at cdomain.com blah blah
3333 user at adomain.com blah blah
4444 user at edomain.com blah blah


OUTPUT DESIRED
##################
5555,1111,3333,4444


SCRIPT
#########
import re

input_file = open('/tmp/file','r')
number_match = re.compile('^\d+\s+\w+\@')
for line in input_file.readlines():
if number_match.match(line):
line = re.split('\s+', line)
print line[0],
print ",",


OUTPUT GENERATED
####################
5555 , 1111 , 3333 , 4444 ,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050912/844cae81/attachment.html

From dyoo at hkn.eecs.berkeley.edu  Tue Sep 13 03:55:39 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 12 Sep 2005 18:55:39 -0700 (PDT)
Subject: [Tutor] Where did those spaces come from?
In-Reply-To: <2a278ffe0509121837761767ef@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509121845380.12147-100000@hkn.eecs.berkeley.edu>



On Mon, 12 Sep 2005, Tom Tucker wrote:

> Good evening! The goal is to parse a simple file and grab column one.
> Then print each value horizontally separated by a comma.  Why is Python
> adding a space padding between each value? Please see below.  Thanks
> ahead of time.

Hi Tom,

The 'print' statement is hardcoded to add a space between elements.
print is meant to make output easy, at the cost of control.


If we need more fine-grained control over output, we may want to take a
look at the sys.stdout object; it's a file object that corresponds to the
output we send to the user.

#######
>>> import sys
>>> sys.stdout
<open file '<stdout>', mode 'w' at 0x2a060>
#######

As a file object, we can use the methods that files provide:

    http://www.python.org/doc/lib/bltin-file-objects.html

But the one we'll probably want is 'write()': the write() method of a file
object lets us send content out, without any adulteration:

######
>>> import sys
>>> for i in range(5):
...     sys.stdout.write('hello' + str(i))
...
hello0hello1hello2hello3hello4
######


We might have to be a little bit more careful with write(), because unlike
the print statement, the write() method isn't magical, and won't
automatically try to coerse objects to strings.  The code above shows that
we str() each number, and for good reason.  If we try without it, we'll
get a TypeError:

######
>>> sys.stdout.write(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: argument 1 must be string or read-only character buffer, not
int
######

So it just means we'll have to be more aware about the type of a value
when we use write().


For some more information, see:

    http://www.python.org/doc/tut/node9.html#SECTION009200000000000000000
    http://www.python.org/doc/tut/node9.html#SECTION009100000000000000000


Please feel free to ask more questions.  Good luck!


From hugonz-lists at h-lab.net  Tue Sep 13 06:48:32 2005
From: hugonz-lists at h-lab.net (=?UTF-8?B?SHVnbyBHb256w6FsZXogTW9udGV2ZXJkZQ==?=)
Date: Mon, 12 Sep 2005 23:48:32 -0500
Subject: [Tutor] Boa-Constructor
In-Reply-To: <1126559587.8796.12.camel@c-24-16-68-31.hsd1.wa.comcast.net>
References: <1126559587.8796.12.camel@c-24-16-68-31.hsd1.wa.comcast.net>
Message-ID: <43265A20.4030103@h-lab.net>

Also SPE is great.

http://www.stani.be/python/spe/blog/

Hugo

Terry Kemmerer wrote:
> Hey Guys,
> 
> I am trying to pick an IDE, and it seems to me that Boa-Constructor has 
> great potential. However, in searching google looking to see what others 
> have said, I am reading that the latest version of Boa-Constructor is 
> unstable at best and crashes a lot.....being said, at least, by those 
> promoting non-free IDE's. Yet, Boa-Constructor looks from the outside to 
> me, like a really great IDE.
> 
> Does anyone who is using this latest version or who has tried this 
> latest version have any comments concerning its actual usability?
> 
> Thanks,
> 
> Terry
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

From hanmlw at gmail.com  Tue Sep 13 11:29:05 2005
From: hanmlw at gmail.com (ray)
Date: Tue, 13 Sep 2005 17:29:05 +0800
Subject: [Tutor] socket question
Message-ID: <43269BE1.4080505@gmail.com>

When I receive a 4-bytes integer using socket.recv, it is stored in a 
string. How to convert this string to a integer?
Thanks  in advance.

From kent37 at tds.net  Tue Sep 13 11:41:23 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Sep 2005 05:41:23 -0400
Subject: [Tutor] socket question
In-Reply-To: <43269BE1.4080505@gmail.com>
References: <43269BE1.4080505@gmail.com>
Message-ID: <43269EC3.9080802@tds.net>

ray wrote:
> When I receive a 4-bytes integer using socket.recv, it is stored in a 
> string. How to convert this string to a integer?

Take a look at unpack() in module struct.

Kent


From tegmine at gmail.com  Tue Sep 13 12:18:38 2005
From: tegmine at gmail.com (Luis N)
Date: Tue, 13 Sep 2005 03:18:38 -0700
Subject: [Tutor] Boa-Constructor
In-Reply-To: <1126559587.8796.12.camel@c-24-16-68-31.hsd1.wa.comcast.net>
References: <1126559587.8796.12.camel@c-24-16-68-31.hsd1.wa.comcast.net>
Message-ID: <77bfa81a0509130318192b7bd3@mail.gmail.com>

On 9/12/05, Terry Kemmerer <wildcard2005 at comcast.net> wrote:
>  Hey Guys,
>  
>  I am trying to pick an IDE, and it seems to me that Boa-Constructor has great potential.


Did you check Boa out of CVS? It tends not to have an intermittent
schedule of releases.

Luis

From tegmine at gmail.com  Tue Sep 13 12:20:39 2005
From: tegmine at gmail.com (Luis N)
Date: Tue, 13 Sep 2005 03:20:39 -0700
Subject: [Tutor] Venom / Python23.dll missing
In-Reply-To: <432497E6.4070609@gmail.com>
References: <43243E73.8050603@pennswoods.net> <4324439E.9050707@tds.net>
	<43247FC0.9080606@pennswoods.net> <43248A36.5040600@gmail.com>
	<432497E6.4070609@gmail.com>
Message-ID: <77bfa81a050913032079d541a7@mail.gmail.com>

On 9/11/05, Damien Gouteux <damien.gouteux at gmail.com> wrote:
> Hi all.
> I try to run Venom, a Python binding for the Irrlicht engine. But I need python23.dll. 

Download a game from pygame.org

Luis.

From alan.gauld at freenet.co.uk  Tue Sep 13 13:22:22 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Tue, 13 Sep 2005 12:22:22 +0100
Subject: [Tutor] socket question
References: <43269BE1.4080505@gmail.com>
Message-ID: <007d01c5b855$6a188550$0201a8c0@xp>


> When I receive a 4-bytes integer using socket.recv, it is stored in 
> a
> string. How to convert this string to a integer?

Look at the struct module.
Its unpack method takes a format string which defines how the data
should be interpreted.

Have a look at the section at the end of my  file handling topic for
some info and examples of usage:

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


From arcege at gmail.com  Tue Sep 13 14:46:05 2005
From: arcege at gmail.com (Michael P. Reilly)
Date: Tue, 13 Sep 2005 08:46:05 -0400
Subject: [Tutor] Where did those spaces come from?
In-Reply-To: <2a278ffe0509121837761767ef@mail.gmail.com>
References: <2a278ffe0509121837761767ef@mail.gmail.com>
Message-ID: <7e5ba9220509130546767cc3ee@mail.gmail.com>

On 9/12/05, Tom Tucker <tktucker at gmail.com> wrote:
> 
> Tutor,
> 
> Good evening! The goal is to parse a simple file and grab column one. 
> Then print each value horizontally separated by a comma. 
> Why is Python adding a space padding between each value? Please see below. 
> 
> Thanks ahead of time.
> 
> 
> 
> 
> INPUT_FILE # unwanted lines removed
> ################################
> 5555 user at bdomain.com blah blah
> 1111 user at cdomain.com blah blah
> 3333 user at adomain.com blah blah
> 4444 user at edomain.com blah blah
> 
> 
> OUTPUT DESIRED
> ##################
> 5555,1111,3333,4444
> 
> 
> SCRIPT
> #########
> import re
> 
> input_file = open('/tmp/file','r')
> number_match = re.compile('^\d+\s+\w+\@')
> for line in input_file.readlines():
> if number_match.match(line):
> line = re.split('\s+', line)
> print line[0],
> print ",",
> 
> 
> OUTPUT GENERATED
> ####################
> 5555 , 1111 , 3333 , 4444 , 
> 
> 
To add to Danny's posting, I recently had to stream out an unknown list of 
values from a database, something like what you are doing. I created a class 
that formats the lines like you want and writes them out when the line gets 
close the the maximum length.

class Line:
 length = 72
 seperator = ', '
 def __init__(self):
 self.reset()
 def reset(self):
 self.contents = ''
 def __str__(self):
 return str(self.contents)
 def __len__(self):
 return len(self.contents)
 def __add__(self, other):
 o = str(other)
 l = len(o)
 s = len(self.seperator)
 if len(self) + l + s > self.length:
 self.flush()
 if self.contents:
 self.contents += self.seperator
 self.contents += str(other)
 return self
 def flush(self):
 if self.contents:
 self._print(self.contents)
 self.reset()
 def _print(self, line):
 print line

For your purposes, you would want to change the separator to just ','. Then 
you would just create an instance and add strings to it.
formatted_line = Line()
for line in input_file.readlines():
if number_match.match(line):
line = re.split(r'\s+', line)
formatted_line += line[0]
else:
formatted_line.flush() # clear anything left to print

HTH,
-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/20050913/c5679095/attachment.htm

From jacka at mts.net  Tue Sep 13 06:50:52 2005
From: jacka at mts.net (JackA)
Date: Mon, 12 Sep 2005 23:50:52 -0500
Subject: [Tutor] GETTING AN _.EXE VERSION OF _.PY program to run on a
	machine that does not have Python installed on it.
Message-ID: <00bd01c5b81e$b7e5d670$6601a8c0@Desk1>

I am attaching a word document copy of this EMail which might be easier to read and follow if your EMail window rearanges things to much.



I would like thank Dax Reyes and John Fouhy for taking the trouble to respond to my attempt to create an     _.EXE     from a     Python program.



The question now is; can the    PY2EXE    procedure make     PROG.EXE     ( Or a set of files. ) from      PROG.PY      that will allow      PROG.EXE      to run on a machine that does not have    Python    installed on it, and if so what has to be fixed and how?

I have created        PROG.EXE       from      PROG.PY       , but it appears   NOT   to be portable in that when I try to run     PROG.EXE     on my wife's machine which does not have   Python   installed on it I get a " See the logfile PROG.EXE log for details".  The logfile has the following ;




Traceback (most recent call last):

  File "PROG.PY", line 364, in ?

  File "PROG.PY", line 320, in Main

EOFError: EOF when reading a line



Lines 320 and 364 are shown below.  Line 364 is the last line of the program.  No line reference on the    EOFError    was given.

    filename=raw_input("Enter destination and filename as >  C:\Name.STR  <: ")                                                                                      # line 320 listed in traceback log.
Main()                                                                        # line 360 listed in traceback log.




The 6 lines of     PyToExe.PY     used to make     PROG.EXE      , is shown below starting with  ### in line #1.

###  PyToExe.PY = file name.    _.PY > _.EXE

from distutils.core import setup
import py2exe

setup(windows=['PROG.PY'])

The     DOS com line     command was :     PYTHON PyToExe.PY PY2EXE  .




The program,     PROG.PY     has no errors and runs fine under Python24, as does PROG.EXE      on a Python equipped machine.  Actually I can delete    PROG.EXE    and double click the      PROG.PY     icon in the     Python24    folder and it runs fine. 

 

I am running an XP machine with a 1.8 GHz CPU, 700 Meg of memory and 36 Gbyte of free space on disk.

I am attaching       PROG.PY       in case anyone has any questions on it.

 

At some point over the course of trying to run     PROG.EXE    it was indicated that      Python24.dll    was missing so it has been copied into the     DIST     folder where 

    PROG.EXE      is located as well as           WINDOWS\SYSTEM32\DRIVERS     ,           

        WINDOWS        and        WINDOWS\SYSTEM  .

Jack Anema
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050912/a495be0d/attachment.htm
-------------- next part --------------
A non-text attachment was scrubbed...
Name: AFTER EXE.doc
Type: application/msword
Size: 20992 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050912/a495be0d/AFTEREXE-0001.doc
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: PROG.PY
Url: http://mail.python.org/pipermail/tutor/attachments/20050912/a495be0d/PROG.pot

From dyoo at hkn.eecs.berkeley.edu  Tue Sep 13 19:27:09 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 13 Sep 2005 10:27:09 -0700 (PDT)
Subject: [Tutor] mamelauncher (fwd)
Message-ID: <Pine.LNX.4.44.0509131015320.9851-100000@hkn.eecs.berkeley.edu>


Hi Max,

[Keeping tutor at python.org in CC.  Please do not send replies only to me:
make sure tutor at python.org is being included in the reply.]



[Danny]
>> Hint: in the defintion of run_mame_selection, there's some string
>> concatenation going on here:
>>
>> ######
>> def run_mame_selection(selection):
>>    os.system("C:\\mame096b\\mame.exe"+""+selection)
>> ######
>>
>> Why the empty string?


[Max]
> Launching mame without any specified string from the command line
> defaults to PacMan, so I was trying that out!


I'm not quite sure I understand your response, and I'm also not quite sure
you understood my hint.  *grin*

Let's back up for a moment.

Ok, it sounds like if we just run mame.exe without any arguments, it
should run PacMan by default.  Can you try that out?

######
def run_packman():
    os.system("C:\\mame096b\\mame.exe")
######

Does this work?  I'm trying to see if we can isolate exactly where things
start to break and not work as expected.


Also, does this work?

######
def run_packman():
    os.system("C:\\mame096b\\mame.exe packman")
######


Finally, what about this?

######
def run_mame_selection(selection):
    os.system("C:\\mame096b\\mame.exe"+""+selection)

def run_packman():
    run_mame_selection('packman')
######


As a side note: you may want to test the programs through IDLE; if you run
the program through IDLE, then if you run into problems, you should still
be able to see the error message that comes up.

If you run the program as a standalone on Windows, debugging this is
slightly more complicated because Windows closes a program's windows as
soon as a program's done.

Good luck!


From dyoo at hkn.eecs.berkeley.edu  Tue Sep 13 19:33:36 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 13 Sep 2005 10:33:36 -0700 (PDT)
Subject: [Tutor] mamelauncher (fwd)
In-Reply-To: <Pine.LNX.4.44.0509131015320.9851-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0509131032030.9851-100000@hkn.eecs.berkeley.edu>

> Also, does this work?
>
> ######
> def run_packman():
>     os.system("C:\\mame096b\\mame.exe packman")
                                        ^^^^^^^

Gaaa.  My apologies: that was a typo.  Correct this (and other places
where I wrote 'packman') with whatever name you use to explicitly tell
MAME to run PacMan.


From dyoo at hkn.eecs.berkeley.edu  Tue Sep 13 19:47:53 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 13 Sep 2005 10:47:53 -0700 (PDT)
Subject: [Tutor] GETTING AN _.EXE VERSION OF _.PY program to run on a
 machine that does not have Python installed on it.
In-Reply-To: <00bd01c5b81e$b7e5d670$6601a8c0@Desk1>
Message-ID: <Pine.LNX.4.44.0509131034210.9851-100000@hkn.eecs.berkeley.edu>



On Mon, 12 Sep 2005, JackA wrote:

> I am attaching a word document copy of this EMail which might be easier
> to read and follow if your EMail window rearanges things to much.

Hi Jack,

Actually, please don't do that.  *grin*

Word documents are actually not really usable in a programming language
forum.  You're assuming that the recipients are using systems that are
capable of running Microsoft Word.  You might be surprised, but this is
not necessarily true.  For maximum utility, please stick to plain text
formats on Python-Tutor.  The page:

    http://expita.com/nomime.html

gives some more reasons for staying with plain text, at least on technical
mailing lists.


Anyway, to your question:

> I have created PROG.EXE from PROG.PY , but it appears NOT to be portable
> in that when I try to run PROG.EXE on my wife's machine which does not
> have Python installed on it I get a " See the logfile PROG.EXE log for
> details".  The logfile has the following ;
>
>
> Traceback (most recent call last):
>   File "PROG.PY", line 364, in ?
>   File "PROG.PY", line 320, in Main
> EOFError: EOF when reading a line


Ok, I have an idea of what's going on here.  Let's take a look at your
'setup.py' file.



> The 6 lines of PyToExe.PY used to make PROG.EXE , is shown below
> starting with ### in line #1.
>
> ###  PyToExe.PY = file name.    _.PY > _.EXE
>
> from distutils.core import setup
> import py2exe
>
> setup(windows=['PROG.PY'])
        ^^^^^^^

Ah.  Change the line in your setup from using 'windows' to 'console'.


You're not making a graphical "Windows" program, but one that depends on
the console.  Technially, a Microsoft Windows GUI program has no console,
and no access to standard input or output.  That's why your program
breaks: it's unable to use raw_input(), since that's explicitely meant to
talk to standard input.


So, instead, your setup.py should look like:

######
from distutils.core import setup
import py2exe

setup(console=['PROG.PY'])
######


Best of wishes to you.


From max_russell2000 at yahoo.co.uk  Tue Sep 13 20:10:13 2005
From: max_russell2000 at yahoo.co.uk (Max Russell)
Date: Tue, 13 Sep 2005 19:10:13 +0100 (BST)
Subject: [Tutor] mamelauncher (fwd)
In-Reply-To: <Pine.LNX.4.44.0509131032030.9851-100000@hkn.eecs.berkeley.edu>
Message-ID: <20050913181013.4764.qmail@web25910.mail.ukl.yahoo.com>

There actually seems to be a bit of a problem in the
interaction with the system when it launches mame.

If I run this:

import os

def run_mame_selection(selection):
    os.system("C:\\mame096b\\mame.exe"+ selection)
              
#main
selection = " tnzs"
run_mame_selection(selection)
raw_input()

mame reports files missing, but I can launch the game
manually- I suspect that this is some sort of error
that occurs normally but is bypassed on launch and
that  my one-shot attempt to launch the thing cannot
handle. I think I need to have a wee look at
subprocess!

ta

Max

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

> > Also, does this work?
> >
> > ######
> > def run_packman():
> >     os.system("C:\\mame096b\\mame.exe packman")
>                                         ^^^^^^^
> 
> Gaaa.  My apologies: that was a typo.  Correct this
> (and other places
> where I wrote 'packman') with whatever name you use
> to explicitly tell
> MAME to run PacMan.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



		
___________________________________________________________ 
How much free photo storage do you get? Store your holiday 
snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com

From hominid767 at yahoo.com  Tue Sep 13 22:37:04 2005
From: hominid767 at yahoo.com (jon freddy)
Date: Tue, 13 Sep 2005 13:37:04 -0700 (PDT)
Subject: [Tutor] (no subject)
Message-ID: <20050913203704.7021.qmail@web53512.mail.yahoo.com>

I am new to Python, about 1 day. And I downloaded from
python.org Pythong2.4, it has the command line and
junk. But what actuall program compiles the source of
python into a program? Any of the programs included in
the package? And also, is Python capable of writing an
OS?

Jon.

From david at graniteweb.com  Tue Sep 13 22:51:08 2005
From: david at graniteweb.com (David Rock)
Date: Tue, 13 Sep 2005 15:51:08 -0500
Subject: [Tutor] (no subject)
In-Reply-To: <20050913203704.7021.qmail@web53512.mail.yahoo.com>
References: <20050913203704.7021.qmail@web53512.mail.yahoo.com>
Message-ID: <20050913205108.GA20405@wdfs.graniteweb.com>

* jon freddy <hominid767 at yahoo.com> [2005-09-13 13:37]:
> I am new to Python, about 1 day. And I downloaded from
> python.org Pythong2.4, it has the command line and
> junk. But what actuall program compiles the source of
> python into a program? Any of the programs included in
> the package? And also, is Python capable of writing an
> OS?

Hi, Jon.

Python is an interpreted language, your script is "compiled" at runtime
by the main python executable, similar to perl. Your script maintains
its textfile identity. So the simple form of running a script is:
	python myscript

It _is_ possible to create a standalone binary, though. py2exe is a
common application to build an executable with.

Python is theoretically capable of being used to write an OS, but that
is an exercise that is probably left to theory. There are a lot of good
OS'es out there that would undoubtedly perform much better than a
PythonOS ever could. That doesn't mean it wouldn't be cool, though. :-)

-- 
David Rock
david at graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050913/b9e75b88/attachment.pgp

From dyoo at hkn.eecs.berkeley.edu  Tue Sep 13 23:31:22 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 13 Sep 2005 14:31:22 -0700 (PDT)
Subject: [Tutor] mamelauncher (fwd)
In-Reply-To: <20050913181013.4764.qmail@web25910.mail.ukl.yahoo.com>
Message-ID: <Pine.LNX.4.44.0509131411090.11497-100000@hkn.eecs.berkeley.edu>



On Tue, 13 Sep 2005, Max Russell wrote:

> There actually seems to be a bit of a problem in the interaction with
> the system when it launches mame.
>
> If I run this:
>
> import os
>
> def run_mame_selection(selection):
>     os.system("C:\\mame096b\\mame.exe"+ selection)
>
> #main
> selection = " tnzs"
> run_mame_selection(selection)
> raw_input()
>
> mame reports files missing, but I can launch the game manually- I
> suspect that this is some sort of error that occurs normally but is
> bypassed on launch and that my one-shot attempt to launch the thing
> cannot handle.

Hi Max,

Hmmmm... that'll be something you'll want to check then.  At least we can
see that there might be some problems there.  Do you know if the current
working directory matters to MAME, or if it's looking for any particular
environmental variables?

Perhaps you might want to post those errors on a MAME support group, to
see if other people know how to fix things properly.


By the way, I notice that you're accounting above for the possible bug of
having the selection text smushed right into the front of the selection
text by manually prepending a space:

######
> def run_mame_selection(selection):
>     os.system("C:\\mame096b\\mame.exe"+ selection)
> selection = " tnzs"
######

That was the bug that I thought was really causing problems, since's it
wasn't clear at all that the code was handling the possible issue of the
wordsrunningtogether.


But you may want to modify run_mame_selection so that it does the
prepending for you:

######
def run_mame_selection(selection):
    os.system("C:\\mame096b\\mame.exe %s" % selection)
######

That way, there's no possiblity of making that kind of mistake.
Unforunately, this isn't robust because if 'selection' itself contains
weird characters like quotes or spaces, that'll probably cause problems.


Instead, we can pass a real list of command line arguments and avoid
worrying about shell escape and quotation issues.  For example, instead
of:

######
>>> f = os.popen("ls -l /etc/passwd")
>>> f.read()
'-rw-r--r--  1 root root 1957 Jul 12 17:25 /etc/passwd\n'
######

it is preferable to do:

######
>>> child_stdin, child_stdout = os.popen2(['ls', '-l', '/etc/passwd'])
>>> child_stdout.read()
'-rw-r--r--  1 root root 1957 Jul 12 17:25 /etc/passwd\n'
######

If the filename here had spaces in it, then the first example with
os.popen() will probably break.  But the second with os.popen2 and the
list of explicit arguments should fare better.



> I think I need to have a wee look at subprocess!

Unfortunately, you'll probably run into similar problems with
'subprocess'.  I think the problem here is your MAME setup: it might be
expecting something in your environment that isn't there, like the correct
current working directory, or something else.  I don't know too much about
MAME, so I can't say in definite terms what's going on with the MAME error
messages.


Best of wishes to you!


From dyoo at hkn.eecs.berkeley.edu  Tue Sep 13 23:51:15 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 13 Sep 2005 14:51:15 -0700 (PDT)
Subject: [Tutor] Python as operating system?
In-Reply-To: <20050913205108.GA20405@wdfs.graniteweb.com>
Message-ID: <Pine.LNX.4.44.0509131432360.11497-100000@hkn.eecs.berkeley.edu>



> Python is theoretically capable of being used to write an OS, but that
> is an exercise that is probably left to theory. There are a lot of good
> OS'es out there that would undoubtedly perform much better than a
> PythonOS ever could. That doesn't mean it wouldn't be cool, though. :-)

I haven't looked at this too closely, but:

    http://sourceforge.net/projects/cleese

appears to show that the theory can be applied, even if it isn't
practical.  *grin*  Not sure if this project is still active, though.



[Off-topic from Python: there are several other mature systems written in
high level languages.  These systems could be considered as OS's in their
own right.  The Smalltalk folks, for example, have had this for a long
time;  Squeak could be considered a high-level operating system:

    http://www.squeak.org/

MrEd/DrScheme is another compelling example of a system that could be
considered a high-level operating system, given the environment that they
expose.  The paper: http://www.ccs.neu.edu/scheme/pubs/icfp99-ffkf.pdf
talks about this in more detail.]


Best of wishes!


From 3dbernard at gmail.com  Tue Sep 13 23:57:33 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Tue, 13 Sep 2005 17:57:33 -0400
Subject: [Tutor] Another regular expression question
Message-ID: <61d0e2b4050913145714553ac4@mail.gmail.com>

Hello, yet another regular expression question :-)

So I have this xml file that I'm trying to find a specific tag in. For
this I'm using a regular expression. Right now, the tag I'm trying to
find looks like this:

<sceneobject name="Camera_Root_bernard" type="CameraRoot">

So I'm using a regular expression to find:
sceneobject
type="CameraRoot"


My code looks like this:


import os, re


def searchTag( sPattern, sFile ):
	
	"""
	Scans a xml file to try to find a line that matches search criterias.
	
	ARGUMENTS:
	sPattern (string): regular expression pattern string
	sFile (string): full file path to scan
	
	RETURN VALUE: text line (string) or None
	"""
	
	oRe = re.compile( sPattern )
	
	if os.path.exists( sFile ) == False: return None
	else:
		oFile = file( sFile, 'r' )
		
		for sLine in oFile.xreadlines(): # read text
			oMatch = oRe.search( sLine ) # attempt a search
			if oMatch != None: # check if search returned success
				oFile.close()
				return sLine
		
		# Scan has yield no result, return None
		oFile.close()
		return None


sLine = searchTag( r'(sceneobject)(type="CameraRoot")', sFile )


The thing is that I suspect my regular expression pattern to be
incorrect because I always get None, but am at a loss here. Any advice
would be welcomed.


Thanks
Bernard

From kent37 at tds.net  Wed Sep 14 00:18:51 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Sep 2005 18:18:51 -0400
Subject: [Tutor] Another regular expression question
In-Reply-To: <61d0e2b4050913145714553ac4@mail.gmail.com>
References: <61d0e2b4050913145714553ac4@mail.gmail.com>
Message-ID: <4327504B.4090909@tds.net>

Bernard Lebel wrote:
> Hello, yet another regular expression question :-)
> 
> So I have this xml file that I'm trying to find a specific tag in. For
> this I'm using a regular expression. Right now, the tag I'm trying to
> find looks like this:
> 
> <sceneobject name="Camera_Root_bernard" type="CameraRoot">
> 
> So I'm using a regular expression to find:
> sceneobject
> type="CameraRoot"
> 
> 
> My code looks like this:
> 
> 
> import os, re
> 
> 
> def searchTag( sPattern, sFile ):
> 	
> 	"""
> 	Scans a xml file to try to find a line that matches search criterias.
> 	
> 	ARGUMENTS:
> 	sPattern (string): regular expression pattern string
> 	sFile (string): full file path to scan
> 	
> 	RETURN VALUE: text line (string) or None
> 	"""
> 	
> 	oRe = re.compile( sPattern )
> 	
> 	if os.path.exists( sFile ) == False: return None

No need to compare to False, you can just say
 	if not os.path.exists( sFile ): return None

> 	else:
> 		oFile = file( sFile, 'r' )
> 		
> 		for sLine in oFile.xreadlines(): # read text

  for sLine in oFile:
is more idiomatic and avoids reading the whole file at once.

> 			oMatch = oRe.search( sLine ) # attempt a search
> 			if oMatch != None: # check if search returned success
> 				oFile.close()
> 				return sLine
> 		
> 		# Scan has yield no result, return None
> 		oFile.close()
> 		return None
> 
> 
> sLine = searchTag( r'(sceneobject)(type="CameraRoot")', sFile )
> 
> 
> The thing is that I suspect my regular expression pattern to be
> incorrect because I always get None, but am at a loss here. Any advice
> would be welcomed.

You need something in the regex to match the part between 'sceneobject' and 'type="CameraRoot"'. The regex you are using expects them to be adjacent. Try
sLine = searchTag( r'(sceneobject).*?(type="CameraRoot")', sFile )

which means, match anything between the two strings, but the smallest amount possible (non-greedy).

It's also possible that the tag you are looking for spans multiple lines. In this case you should look at an XML parsing library.

Kent


From cpu.crazy at gmail.com  Tue Sep 13 16:51:09 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Tue, 13 Sep 2005 08:51:09 -0600
Subject: [Tutor] Download an image of a site?
Message-ID: <4326E75D.5080106@gmail.com>

Kent Johnson wrote:
> I don't think the object returned from urllib2.urlopen() has save() and get()       > methods. According to the docs urlopen() "returns a file-like object with two
> additional methods:
>
>    * geturl() -- return the URL of the resource retrieved
>    * info() -- return the meta-information of the page, as a dictionary-like object"
>
> So you should treat data.f like an open file - use read() to get the contents into a > variable. Then open a real (disk) file for writing and write it out. This section of > the Python tutorial has a quick intro:
>  http://docs.python.org/tut/node9.html#SECTION009200000000000000000
>
> Kent


Thanks. I will check this out and let you know if I can get it to work.



From denise.hartley at gmail.com  Wed Sep 14 04:27:23 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Tue, 13 Sep 2005 19:27:23 -0700
Subject: [Tutor] More IDE's (was: Boa-Constructor)
In-Reply-To: <77bfa81a0509130318192b7bd3@mail.gmail.com>
References: <1126559587.8796.12.camel@c-24-16-68-31.hsd1.wa.comcast.net>
	<77bfa81a0509130318192b7bd3@mail.gmail.com>
Message-ID: <8daabe5605091319277e7e6bef@mail.gmail.com>

This thread made me wonder:

Is anyone out there using Eclipse and PyDev? (I started using Eclipse
when I was toying around in Jython, and know others that are using it
for C/C++, but I am curious if others have tried out PyDev and what
they think).

~Denise

From alan.gauld at freenet.co.uk  Wed Sep 14 09:21:51 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Wed, 14 Sep 2005 08:21:51 +0100
Subject: [Tutor] mamelauncher (fwd)
References: <20050913181013.4764.qmail@web25910.mail.ukl.yahoo.com>
Message-ID: <00de01c5b8fc$fa2c8c20$0201a8c0@xp>


> There actually seems to be a bit of a problem in the
> interaction with the system when it launches mame.
> 
> If I run this:
> 
> import os
> 
> def run_mame_selection(selection):
>    os.system("C:\\mame096b\\mame.exe"+ selection)
>              
> #main
> selection = " tnzs"
> run_mame_selection(selection)
> raw_input()
> 
> mame reports files missing, but I can launch the game
> manually- I suspect that this is some sort of error
> that occurs normally but is bypassed on launch and
> that  my one-shot attempt to launch the thing cannot
> handle. I think I need to have a wee look at
> subprocess!

Subprocess is not likely to help. This is more likely to 
do with getting the right command set up for system to execute.

How did you get on with Danny's suggestions for launching Pacman?

When you launch it directly are you in the same directory 
as the game? Could it be looking for files in the current 
directory and not finding them where the python script lives?

Switching to Subprocess might have a few advantages later, 
but for now is simply going to distract from the real problem.

Also can you post the error messages you get, its much easier 
for us to figure out where the errors are occuring if we see 
the full error text.

Alan G

From alan.gauld at freenet.co.uk  Wed Sep 14 09:33:09 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Wed, 14 Sep 2005 08:33:09 +0100
Subject: [Tutor] (no subject)
References: <20050913203704.7021.qmail@web53512.mail.yahoo.com>
Message-ID: <00e201c5b8fe$8e475290$0201a8c0@xp>

>I am new to Python, about 1 day. And I downloaded from
> python.org Pythong2.4, it has the command line and
> junk. But what actuall program compiles the source of
> python into a program? 

When you run a python script python compiles the source 
internally before executing it. If your program imports 
modules, the imported code gets converted into compiled 
code and you will see it in the form of .pyc files.

Python works in a similar fashion to VB and Java in that 
it executes compiled byte code, not native machine code.
The Python program has the same function as both the 
Java compiler and JVM interpreter.

If you use Jython instead of Python you will find a separate 
python compiler that produces true Java code that then 
can be run under any JVM.

If you want to produce standalone windows executables 
there are several tools available, the simplest and 
most widely used being py2exe. This is not part of the 
standard distribution however. Basically what all these 
tools do is wrap the Python program and all of the 
modules you use into one single executable file - so 
its quite big and if you distribute several programs 
you duplicate python with each one!! In this case 
distributing the python scripts with a one-off version
of Python is a better option.

The included distutils package can simplify that process.

> And also, is Python capable of writing an OS?

Not really since python requires the python program to 
be present in some form and it itself needs an underlying 
OS. You could write an OS simulation as a learning 
excercise but it would need a minimal OS underlying it.
Python is a high level programming language aimed at 
developing applications with the minimum effort. If you 
really need to twiddle the bits n' bytes you are better 
off with C or assembler, just be prepared to write a 
lot of code...

HTH,

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

From alan.gauld at freenet.co.uk  Wed Sep 14 09:39:00 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Wed, 14 Sep 2005 08:39:00 +0100
Subject: [Tutor] Python as operating system?
References: <Pine.LNX.4.44.0509131432360.11497-100000@hkn.eecs.berkeley.edu>
Message-ID: <00f401c5b8ff$5fa30e60$0201a8c0@xp>

> MrEd/DrScheme is another compelling example of a system that could 
> be
> considered a high-level operating system, given the environment that 
> they
> expose.  The paper: 
> http://www.ccs.neu.edu/scheme/pubs/icfp99-ffkf.pdf
> talks about this in more detail.]

I have a friend who teaches Common Lisp programming at Columbia
University and he wrote a virtual Operating System in Lisp for
his courses. These pseudo OS environments are useful for learning
and allowing 'safe' modification of the OS without getting into
the murky deails of C but ultimately they all need a real OS
underneath to talk to the hardware.

Alan G. 


From alan.gauld at freenet.co.uk  Wed Sep 14 09:43:58 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Wed, 14 Sep 2005 08:43:58 +0100
Subject: [Tutor] Another regular expression question
References: <61d0e2b4050913145714553ac4@mail.gmail.com>
Message-ID: <00f801c5b900$112e1b20$0201a8c0@xp>

Hi Bernard,

> Hello, yet another regular expression question :-)
>
> So I have this xml file that I'm trying to find a 
> specific tag in. 

I'm always suspicious when I see regular expression 
and xml/html in the same context. regex are not good 
for parsing xml/html files and it's usually much easier 
to use a proper parser - such as beautiful soup.

http://www.crummy.com/software/BeautifulSoup/

Is there any special reason why you are using a regex 
sledgehammer to crack this particular nut? Or is it 
just to gain experience using regex?

Alan G.

From csotelop at yahoo.es  Wed Sep 14 12:46:39 2005
From: csotelop at yahoo.es (Carlos Eduardo Sotelo Pinto)
Date: Wed, 14 Sep 2005 05:46:39 -0500
Subject: [Tutor] (no subject)
In-Reply-To: <00e201c5b8fe$8e475290$0201a8c0@xp>
References: <20050913203704.7021.qmail@web53512.mail.yahoo.com>
	<00e201c5b8fe$8e475290$0201a8c0@xp>
Message-ID: <4327FF8F.9020905@yahoo.es>

Hi List.
All of you are right. It is similar to java, vb, but how it work?

Well, python script generates a compiled bytecode the first time that 
yuou run the main script in a machinne, and the interpreter execute this 
byte code.

It could be slower than a compiled language, because use an interpreter 
to run, but it is faster than a interepreted language, because the 
interpreted language ot generated a byt code, this one reads the secripts.

About operating system, it coulbe posible, but not at all. First to run 
an operative systems you need a low level language, like assembler, it 
could began the os, but the kernel could be in python.
just a c library or gcc and python interpreter. if you use assembler to 
run with c, u can use python for your python os


Alan G wrote:
>>I am new to Python, about 1 day. And I downloaded from
>>python.org Pythong2.4, it has the command line and
>>junk. But what actuall program compiles the source of
>>python into a program? 
> 
> 
> When you run a python script python compiles the source 
> internally before executing it. If your program imports 
> modules, the imported code gets converted into compiled 
> code and you will see it in the form of .pyc files.
> 
> Python works in a similar fashion to VB and Java in that 
> it executes compiled byte code, not native machine code.
> The Python program has the same function as both the 
> Java compiler and JVM interpreter.
> 
> If you use Jython instead of Python you will find a separate 
> python compiler that produces true Java code that then 
> can be run under any JVM.
> 
> If you want to produce standalone windows executables 
> there are several tools available, the simplest and 
> most widely used being py2exe. This is not part of the 
> standard distribution however. Basically what all these 
> tools do is wrap the Python program and all of the 
> modules you use into one single executable file - so 
> its quite big and if you distribute several programs 
> you duplicate python with each one!! In this case 
> distributing the python scripts with a one-off version
> of Python is a better option.
> 
> The included distutils package can simplify that process.
> 
> 
>>And also, is Python capable of writing an OS?
> 
> 
> Not really since python requires the python program to 
> be present in some form and it itself needs an underlying 
> OS. You could write an OS simulation as a learning 
> excercise but it would need a minimal OS underlying it.
> Python is a high level programming language aimed at 
> developing applications with the minimum effort. If you 
> really need to twiddle the bits n' bytes you are better 
> off with C or assembler, just be prepared to write a 
> lot of code...
> 
> HTH,
> 
> Alan G
> Author of the Learn to Program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
Atentamente:

*------------------------------------*  ,= ,-_-. =.
|Carlos E. Sotelo Pinto(KrLoS)       | ((_/)o o(\_))
|GNU/Linux User Registered # 379182  |  `-'(. .)`-'
|Tildes omitidas voluntariamente     |      \_/
*------------------------------------*
Bitacora de Vuelo <http://csotelop.blogsome.com/>
Sociedad Peruana de Computacion <http://www.spc.org.pe/>
Grupo de Usuarios GNU/Linux Arequipa <http://www.aqpglug.org.pe/>
Grupo de Usuarios Debian Arequipa <http://www.debianarequipa.org>
Grupo de Usuarios Debian Peru <http://www.debianperu.org/>
------------------------------------------------------------------------
La actitud del hacker:
Los hackers resuelven problemas y construyen cosas, y creen en la 
libertad y la ayuda voluntaria mutua. Para ser aceptado como hacker, 
deber?s comportarte como si tuvieras esta actitud en tu interior. Y para 
comportarte como si tuvieras esta actitud, deber?s creerte de verdad 
dicha actitud.


	
	
		
______________________________________________ 
Renovamos el Correo Yahoo! 
Nuevos servicios, m?s seguridad 
http://correo.yahoo.es

From 3dbernard at gmail.com  Wed Sep 14 15:08:36 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Wed, 14 Sep 2005 09:08:36 -0400
Subject: [Tutor] Another regular expression question
In-Reply-To: <00f801c5b900$112e1b20$0201a8c0@xp>
References: <61d0e2b4050913145714553ac4@mail.gmail.com>
	<00f801c5b900$112e1b20$0201a8c0@xp>
Message-ID: <61d0e2b4050914060866cf26a6@mail.gmail.com>

Thanks Alan,

I'll check BeautifulSoup asap.

I'm using regex simply because I have no clue where to start to parse
XML. I have read the various xml tools available in the Python
library, however I'm a complete loss at what to make out of them. Many
of them seem to use some programming standards, wich I am completely
unfamiliar with (this is the first time that I dig into XML writing
and parsing).

I don't know where to start to learn about all these standards, and as
usual with new programming things, the documentation is hard to
swallow (it usually is written more as a reference than a proper user
guide/tutorial). I have to admit this is very frustrating, so if I'm
looking at things from a wrong perspective please advise me, I need
it.

So right now I'm just taking a shortcut and using ultra-simple
re-based parser to retrieve the tags I'm looking for. I know it will
probably be slow, but hopefully I'll get familiar with sophisticated
parsing in the future and improve my code. As it stands right now,
even the re syntax is not super easy to learn.


Kent: That works (of course!). Thanks a bunch once again!


Thanks
Bernard

On 9/14/05, Alan G <alan.gauld at freenet.co.uk> wrote:
> Hi Bernard,
> 
> > Hello, yet another regular expression question :-)
> >
> > So I have this xml file that I'm trying to find a
> > specific tag in.
> 
> I'm always suspicious when I see regular expression
> and xml/html in the same context. regex are not good
> for parsing xml/html files and it's usually much easier
> to use a proper parser - such as beautiful soup.
> 
> http://www.crummy.com/software/BeautifulSoup/
> 
> Is there any special reason why you are using a regex
> sledgehammer to crack this particular nut? Or is it
> just to gain experience using regex?
> 
> Alan G.
>

From kent37 at tds.net  Wed Sep 14 15:36:47 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Sep 2005 09:36:47 -0400
Subject: [Tutor] Another regular expression question
In-Reply-To: <61d0e2b4050914060866cf26a6@mail.gmail.com>
References: <61d0e2b4050913145714553ac4@mail.gmail.com>	<00f801c5b900$112e1b20$0201a8c0@xp>
	<61d0e2b4050914060866cf26a6@mail.gmail.com>
Message-ID: <4328276F.5000309@tds.net>

Bernard Lebel wrote:
> Thanks Alan,
> 
> I'll check BeautifulSoup asap.
> 
> I'm using regex simply because I have no clue where to start to parse
> XML. I have read the various xml tools available in the Python
> library, however I'm a complete loss at what to make out of them. Many
> of them seem to use some programming standards, wich I am completely
> unfamiliar with (this is the first time that I dig into XML writing
> and parsing).
> 
> I don't know where to start to learn about all these standards, and as
> usual with new programming things, the documentation is hard to
> swallow (it usually is written more as a reference than a proper user
> guide/tutorial). I have to admit this is very frustrating, so if I'm
> looking at things from a wrong perspective please advise me, I need
> it.

I agree that the Python XML story is confusing even for the files in the standard library. Worse, the (IMO) best solutions are not to be found in the standard lib or PyXML at all.

The std lib and PyXML are based on the DOM and SAX standards. These standards were designed to be "language-neutral" - there are implementations in Python, Java and other languages. The good side of this is, if you learn how to use them, the knowledge is pretty portable to other languages. The bad side is, the APIs defined by the standard are IMO clunky and painful to use, especially in Python.

There is a current thread on comp.lang.python discussing this with good suggestions and pointers to more info:
http://groups.google.com/group/comp.lang.python/browse_frm/thread/a48891aa645ead13/dcd8fdc20b4b191b?hl=en#dcd8fdc20b4b191b

My personal preference is ElementTree. Beautiful Soup is good too though I have only tried it with HTML. If I was running on Linux I would try lxml which uses the ElementTree API and adds full XPath support. Amara looks like the Cadillac solution - big and cushy. I haven't tried it. Uche's articles (referenced in the thread above) have pointers to many other choices but these seem to be the most popular.

My favorite XML lib is actually dom4j which is in Java. It works great with Jython.

Kent

> 
> So right now I'm just taking a shortcut and using ultra-simple
> re-based parser to retrieve the tags I'm looking for. I know it will
> probably be slow, but hopefully I'll get familiar with sophisticated
> parsing in the future and improve my code. As it stands right now,
> even the re syntax is not super easy to learn.

For what you are doing re seems fine to me. You can get in trouble using re's with XML because of nested tags, variations in spelling and order, probably a bunch of other things. But for simple stuff it can work fine.

Kent

> 
> 
> Kent: That works (of course!). Thanks a bunch once again!
> 
> 
> Thanks
> Bernard
> 
> On 9/14/05, Alan G <alan.gauld at freenet.co.uk> wrote:
> 
>>Hi Bernard,
>>
>>
>>>Hello, yet another regular expression question :-)
>>>
>>>So I have this xml file that I'm trying to find a
>>>specific tag in.
>>
>>I'm always suspicious when I see regular expression
>>and xml/html in the same context. regex are not good
>>for parsing xml/html files and it's usually much easier
>>to use a proper parser - such as beautiful soup.
>>
>>http://www.crummy.com/software/BeautifulSoup/
>>
>>Is there any special reason why you are using a regex
>>sledgehammer to crack this particular nut? Or is it
>>just to gain experience using regex?
>>
>>Alan G.
>>
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From George.Flaherty at marketmax.com  Wed Sep 14 15:40:16 2005
From: George.Flaherty at marketmax.com (George Flaherty)
Date: Wed, 14 Sep 2005 09:40:16 -0400
Subject: [Tutor] More IDE's (was: Boa-Constructor)
Message-ID: <59CF9F456FAA9045B405C441EC916F3E02CE8639@MERC24.na.sas.com>

Yeah, I have been using PyDev with Eclipse. It is pretty good, since with the latest version the debugger is working and they have include the ability to add additional paths in the PYTHONPATH variable.

I honestly would prefer to use Emacs, but I have not found any tool that provides code-completion with python. Until I have been using Eclipse (with Emacs running minimized :)

-g

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of D. Hartley
Sent: Tuesday, September 13, 2005 10:27 PM
To: Python tutor
Subject: [Tutor] More IDE's (was: Boa-Constructor)

This thread made me wonder:

Is anyone out there using Eclipse and PyDev? (I started using Eclipse when I was toying around in Jython, and know others that are using it for C/C++, but I am curious if others have tried out PyDev and what they think).

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

From 3dbernard at gmail.com  Wed Sep 14 16:35:38 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Wed, 14 Sep 2005 10:35:38 -0400
Subject: [Tutor] Another regular expression question
In-Reply-To: <4328276F.5000309@tds.net>
References: <61d0e2b4050913145714553ac4@mail.gmail.com>
	<00f801c5b900$112e1b20$0201a8c0@xp>
	<61d0e2b4050914060866cf26a6@mail.gmail.com> <4328276F.5000309@tds.net>
Message-ID: <61d0e2b405091407353f4c29a4@mail.gmail.com>

Thanks for that pointer Kent, I'll check it out. Also thanks for
letting me know I'm not nuts! :-)

Alan's suggestion about BeautifulSoup is actually excellent. The
documentation is nice and the tool is very easy to use.

However is it normal that to parse a 2618 lines xml file it takes
20-30 seconds or so?


Thanks
Bernard



On 9/14/05, Kent Johnson <kent37 at tds.net> wrote:
> Bernard Lebel wrote:
> > Thanks Alan,
> >
> > I'll check BeautifulSoup asap.
> >
> > I'm using regex simply because I have no clue where to start to parse
> > XML. I have read the various xml tools available in the Python
> > library, however I'm a complete loss at what to make out of them. Many
> > of them seem to use some programming standards, wich I am completely
> > unfamiliar with (this is the first time that I dig into XML writing
> > and parsing).
> >
> > I don't know where to start to learn about all these standards, and as
> > usual with new programming things, the documentation is hard to
> > swallow (it usually is written more as a reference than a proper user
> > guide/tutorial). I have to admit this is very frustrating, so if I'm
> > looking at things from a wrong perspective please advise me, I need
> > it.
> 
> I agree that the Python XML story is confusing even for the files in the standard library. Worse, the (IMO) best solutions are not to be found in the standard lib or PyXML at all.
> 
> The std lib and PyXML are based on the DOM and SAX standards. These standards were designed to be "language-neutral" - there are implementations in Python, Java and other languages. The good side of this is, if you learn how to use them, the knowledge is pretty portable to other languages. The bad side is, the APIs defined by the standard are IMO clunky and painful to use, especially in Python.
> 
> There is a current thread on comp.lang.python discussing this with good suggestions and pointers to more info:
> http://groups.google.com/group/comp.lang.python/browse_frm/thread/a48891aa645ead13/dcd8fdc20b4b191b?hl=en#dcd8fdc20b4b191b
> 
> My personal preference is ElementTree. Beautiful Soup is good too though I have only tried it with HTML. If I was running on Linux I would try lxml which uses the ElementTree API and adds full XPath support. Amara looks like the Cadillac solution - big and cushy. I haven't tried it. Uche's articles (referenced in the thread above) have pointers to many other choices but these seem to be the most popular.
> 
> My favorite XML lib is actually dom4j which is in Java. It works great with Jython.
> 
> Kent
> 
> >
> > So right now I'm just taking a shortcut and using ultra-simple
> > re-based parser to retrieve the tags I'm looking for. I know it will
> > probably be slow, but hopefully I'll get familiar with sophisticated
> > parsing in the future and improve my code. As it stands right now,
> > even the re syntax is not super easy to learn.
> 
> For what you are doing re seems fine to me. You can get in trouble using re's with XML because of nested tags, variations in spelling and order, probably a bunch of other things. But for simple stuff it can work fine.
> 
> Kent
> 
> >
> >
> > Kent: That works (of course!). Thanks a bunch once again!
> >
> >
> > Thanks
> > Bernard
> >
> > On 9/14/05, Alan G <alan.gauld at freenet.co.uk> wrote:
> >
> >>Hi Bernard,
> >>
> >>
> >>>Hello, yet another regular expression question :-)
> >>>
> >>>So I have this xml file that I'm trying to find a
> >>>specific tag in.
> >>
> >>I'm always suspicious when I see regular expression
> >>and xml/html in the same context. regex are not good
> >>for parsing xml/html files and it's usually much easier
> >>to use a proper parser - such as beautiful soup.
> >>
> >>http://www.crummy.com/software/BeautifulSoup/
> >>
> >>Is there any special reason why you are using a regex
> >>sledgehammer to crack this particular nut? Or is it
> >>just to gain experience using regex?
> >>
> >>Alan G.
> >>
> >
> > _______________________________________________
> > 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
>

From kent37 at tds.net  Wed Sep 14 16:55:43 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Sep 2005 10:55:43 -0400
Subject: [Tutor] Another regular expression question
In-Reply-To: <61d0e2b405091407353f4c29a4@mail.gmail.com>
References: <61d0e2b4050913145714553ac4@mail.gmail.com>	<00f801c5b900$112e1b20$0201a8c0@xp>	<61d0e2b4050914060866cf26a6@mail.gmail.com>
	<4328276F.5000309@tds.net>
	<61d0e2b405091407353f4c29a4@mail.gmail.com>
Message-ID: <432839EF.9010507@tds.net>

Bernard Lebel wrote:
> Thanks for that pointer Kent, I'll check it out. Also thanks for
> letting me know I'm not nuts! :-)
> 
> Alan's suggestion about BeautifulSoup is actually excellent. The
> documentation is nice and the tool is very easy to use.
> 
> However is it normal that to parse a 2618 lines xml file it takes
> 20-30 seconds or so?

That seems slow to me unless the lines are really long! How many bytes is the file? But I don't have much experience with BeautifulSoup.

ElementTree is fast and cElementTree (the C implementation) is really fast. I have used it to read, process and write a 28 MB XML file, it took about 10 seconds.

Kent

> 
> 
> Thanks
> Bernard
> 
> 
> 
> On 9/14/05, Kent Johnson <kent37 at tds.net> wrote:
> 
>>Bernard Lebel wrote:
>>
>>>Thanks Alan,
>>>
>>>I'll check BeautifulSoup asap.
>>>
>>>I'm using regex simply because I have no clue where to start to parse
>>>XML. I have read the various xml tools available in the Python
>>>library, however I'm a complete loss at what to make out of them. Many
>>>of them seem to use some programming standards, wich I am completely
>>>unfamiliar with (this is the first time that I dig into XML writing
>>>and parsing).
>>>
>>>I don't know where to start to learn about all these standards, and as
>>>usual with new programming things, the documentation is hard to
>>>swallow (it usually is written more as a reference than a proper user
>>>guide/tutorial). I have to admit this is very frustrating, so if I'm
>>>looking at things from a wrong perspective please advise me, I need
>>>it.
>>
>>I agree that the Python XML story is confusing even for the files in the standard library. Worse, the (IMO) best solutions are not to be found in the standard lib or PyXML at all.
>>
>>The std lib and PyXML are based on the DOM and SAX standards. These standards were designed to be "language-neutral" - there are implementations in Python, Java and other languages. The good side of this is, if you learn how to use them, the knowledge is pretty portable to other languages. The bad side is, the APIs defined by the standard are IMO clunky and painful to use, especially in Python.
>>
>>There is a current thread on comp.lang.python discussing this with good suggestions and pointers to more info:
>>http://groups.google.com/group/comp.lang.python/browse_frm/thread/a48891aa645ead13/dcd8fdc20b4b191b?hl=en#dcd8fdc20b4b191b
>>
>>My personal preference is ElementTree. Beautiful Soup is good too though I have only tried it with HTML. If I was running on Linux I would try lxml which uses the ElementTree API and adds full XPath support. Amara looks like the Cadillac solution - big and cushy. I haven't tried it. Uche's articles (referenced in the thread above) have pointers to many other choices but these seem to be the most popular.
>>
>>My favorite XML lib is actually dom4j which is in Java. It works great with Jython.
>>
>>Kent
>>
>>
>>>So right now I'm just taking a shortcut and using ultra-simple
>>>re-based parser to retrieve the tags I'm looking for. I know it will
>>>probably be slow, but hopefully I'll get familiar with sophisticated
>>>parsing in the future and improve my code. As it stands right now,
>>>even the re syntax is not super easy to learn.
>>
>>For what you are doing re seems fine to me. You can get in trouble using re's with XML because of nested tags, variations in spelling and order, probably a bunch of other things. But for simple stuff it can work fine.
>>
>>Kent
>>
>>
>>>
>>>Kent: That works (of course!). Thanks a bunch once again!
>>>
>>>
>>>Thanks
>>>Bernard
>>>
>>>On 9/14/05, Alan G <alan.gauld at freenet.co.uk> wrote:
>>>
>>>
>>>>Hi Bernard,
>>>>
>>>>
>>>>
>>>>>Hello, yet another regular expression question :-)
>>>>>
>>>>>So I have this xml file that I'm trying to find a
>>>>>specific tag in.
>>>>
>>>>I'm always suspicious when I see regular expression
>>>>and xml/html in the same context. regex are not good
>>>>for parsing xml/html files and it's usually much easier
>>>>to use a proper parser - such as beautiful soup.
>>>>
>>>>http://www.crummy.com/software/BeautifulSoup/
>>>>
>>>>Is there any special reason why you are using a regex
>>>>sledgehammer to crack this particular nut? Or is it
>>>>just to gain experience using regex?
>>>>
>>>>Alan G.
>>>>
>>>
>>>_______________________________________________
>>>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
>>
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From 3dbernard at gmail.com  Wed Sep 14 17:01:59 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Wed, 14 Sep 2005 11:01:59 -0400
Subject: [Tutor] Another regular expression question
In-Reply-To: <432839EF.9010507@tds.net>
References: <61d0e2b4050913145714553ac4@mail.gmail.com>
	<00f801c5b900$112e1b20$0201a8c0@xp>
	<61d0e2b4050914060866cf26a6@mail.gmail.com> <4328276F.5000309@tds.net>
	<61d0e2b405091407353f4c29a4@mail.gmail.com> <432839EF.9010507@tds.net>
Message-ID: <61d0e2b405091408011b78436d@mail.gmail.com>

The file size is 112 Kb. Most lines look this way:

<parameter name="roty" type="Parameter" sourceclassname="nosource">


I'll give a try to ElementTree.


Bernard



On 9/14/05, Kent Johnson <kent37 at tds.net> wrote:
> Bernard Lebel wrote:
> > Thanks for that pointer Kent, I'll check it out. Also thanks for
> > letting me know I'm not nuts! :-)
> >
> > Alan's suggestion about BeautifulSoup is actually excellent. The
> > documentation is nice and the tool is very easy to use.
> >
> > However is it normal that to parse a 2618 lines xml file it takes
> > 20-30 seconds or so?
> 
> That seems slow to me unless the lines are really long! How many bytes is the file? But I don't have much experience with BeautifulSoup.
> 
> ElementTree is fast and cElementTree (the C implementation) is really fast. I have used it to read, process and write a 28 MB XML file, it took about 10 seconds.
> 
> Kent
> 
> >
> >
> > Thanks
> > Bernard
> >
> >
> >
> > On 9/14/05, Kent Johnson <kent37 at tds.net> wrote:
> >
> >>Bernard Lebel wrote:
> >>
> >>>Thanks Alan,
> >>>
> >>>I'll check BeautifulSoup asap.
> >>>
> >>>I'm using regex simply because I have no clue where to start to parse
> >>>XML. I have read the various xml tools available in the Python
> >>>library, however I'm a complete loss at what to make out of them. Many
> >>>of them seem to use some programming standards, wich I am completely
> >>>unfamiliar with (this is the first time that I dig into XML writing
> >>>and parsing).
> >>>
> >>>I don't know where to start to learn about all these standards, and as
> >>>usual with new programming things, the documentation is hard to
> >>>swallow (it usually is written more as a reference than a proper user
> >>>guide/tutorial). I have to admit this is very frustrating, so if I'm
> >>>looking at things from a wrong perspective please advise me, I need
> >>>it.
> >>
> >>I agree that the Python XML story is confusing even for the files in the standard library. Worse, the (IMO) best solutions are not to be found in the standard lib or PyXML at all.
> >>
> >>The std lib and PyXML are based on the DOM and SAX standards. These standards were designed to be "language-neutral" - there are implementations in Python, Java and other languages. The good side of this is, if you learn how to use them, the knowledge is pretty portable to other languages. The bad side is, the APIs defined by the standard are IMO clunky and painful to use, especially in Python.
> >>
> >>There is a current thread on comp.lang.python discussing this with good suggestions and pointers to more info:
> >>http://groups.google.com/group/comp.lang.python/browse_frm/thread/a48891aa645ead13/dcd8fdc20b4b191b?hl=en#dcd8fdc20b4b191b
> >>
> >>My personal preference is ElementTree. Beautiful Soup is good too though I have only tried it with HTML. If I was running on Linux I would try lxml which uses the ElementTree API and adds full XPath support. Amara looks like the Cadillac solution - big and cushy. I haven't tried it. Uche's articles (referenced in the thread above) have pointers to many other choices but these seem to be the most popular.
> >>
> >>My favorite XML lib is actually dom4j which is in Java. It works great with Jython.
> >>
> >>Kent
> >>
> >>
> >>>So right now I'm just taking a shortcut and using ultra-simple
> >>>re-based parser to retrieve the tags I'm looking for. I know it will
> >>>probably be slow, but hopefully I'll get familiar with sophisticated
> >>>parsing in the future and improve my code. As it stands right now,
> >>>even the re syntax is not super easy to learn.
> >>
> >>For what you are doing re seems fine to me. You can get in trouble using re's with XML because of nested tags, variations in spelling and order, probably a bunch of other things. But for simple stuff it can work fine.
> >>
> >>Kent
> >>
> >>
> >>>
> >>>Kent: That works (of course!). Thanks a bunch once again!
> >>>
> >>>
> >>>Thanks
> >>>Bernard
> >>>
> >>>On 9/14/05, Alan G <alan.gauld at freenet.co.uk> wrote:
> >>>
> >>>
> >>>>Hi Bernard,
> >>>>
> >>>>
> >>>>
> >>>>>Hello, yet another regular expression question :-)
> >>>>>
> >>>>>So I have this xml file that I'm trying to find a
> >>>>>specific tag in.
> >>>>
> >>>>I'm always suspicious when I see regular expression
> >>>>and xml/html in the same context. regex are not good
> >>>>for parsing xml/html files and it's usually much easier
> >>>>to use a proper parser - such as beautiful soup.
> >>>>
> >>>>http://www.crummy.com/software/BeautifulSoup/
> >>>>
> >>>>Is there any special reason why you are using a regex
> >>>>sledgehammer to crack this particular nut? Or is it
> >>>>just to gain experience using regex?
> >>>>
> >>>>Alan G.
> >>>>
> >>>
> >>>_______________________________________________
> >>>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
> >>
> >
> > _______________________________________________
> > 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
>

From kent37 at tds.net  Wed Sep 14 17:19:44 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Sep 2005 11:19:44 -0400
Subject: [Tutor] Another regular expression question
In-Reply-To: <61d0e2b405091408011b78436d@mail.gmail.com>
References: <61d0e2b4050913145714553ac4@mail.gmail.com>	
	<00f801c5b900$112e1b20$0201a8c0@xp>	
	<61d0e2b4050914060866cf26a6@mail.gmail.com>
	<4328276F.5000309@tds.net>	
	<61d0e2b405091407353f4c29a4@mail.gmail.com>
	<432839EF.9010507@tds.net>
	<61d0e2b405091408011b78436d@mail.gmail.com>
Message-ID: <43283F90.8000806@tds.net>

Bernard Lebel wrote:
> The file size is 112 Kb. Most lines look this way:
> 
> <parameter name="roty" type="Parameter" sourceclassname="nosource">
> 
> 
> I'll give a try to ElementTree.

To get you started:

from elementtree import ElementTree
doc = ElementTree.parse('myfile.xml')
for sceneobject in doc.findall('//sceneobject'):
  if sceneobject.get('type') == 'CameraRoot':
    # this is a sceneobject that you want
    print sceneobject.get('name')

One gotcha - if your XML uses namespaces, you have to prefix the namespace to the tag name in findall(). It will look something like
  d.findall('//{http://www.imsproject.org/xsd/imscp_rootv1p1p2}resource')

Let us know how long that takes...

Kent

> 
> 
> Bernard
> 
> 
> 
> On 9/14/05, Kent Johnson <kent37 at tds.net> wrote:
> 
>>Bernard Lebel wrote:
>>
>>>Thanks for that pointer Kent, I'll check it out. Also thanks for
>>>letting me know I'm not nuts! :-)
>>>
>>>Alan's suggestion about BeautifulSoup is actually excellent. The
>>>documentation is nice and the tool is very easy to use.
>>>
>>>However is it normal that to parse a 2618 lines xml file it takes
>>>20-30 seconds or so?
>>
>>That seems slow to me unless the lines are really long! How many bytes is the file? But I don't have much experience with BeautifulSoup.
>>
>>ElementTree is fast and cElementTree (the C implementation) is really fast. I have used it to read, process and write a 28 MB XML file, it took about 10 seconds.
>>
>>Kent
>>
>>
>>>
>>>Thanks
>>>Bernard
>>>
>>>
>>>
>>>On 9/14/05, Kent Johnson <kent37 at tds.net> wrote:
>>>
>>>
>>>>Bernard Lebel wrote:
>>>>
>>>>
>>>>>Thanks Alan,
>>>>>
>>>>>I'll check BeautifulSoup asap.
>>>>>
>>>>>I'm using regex simply because I have no clue where to start to parse
>>>>>XML. I have read the various xml tools available in the Python
>>>>>library, however I'm a complete loss at what to make out of them. Many
>>>>>of them seem to use some programming standards, wich I am completely
>>>>>unfamiliar with (this is the first time that I dig into XML writing
>>>>>and parsing).
>>>>>
>>>>>I don't know where to start to learn about all these standards, and as
>>>>>usual with new programming things, the documentation is hard to
>>>>>swallow (it usually is written more as a reference than a proper user
>>>>>guide/tutorial). I have to admit this is very frustrating, so if I'm
>>>>>looking at things from a wrong perspective please advise me, I need
>>>>>it.
>>>>
>>>>I agree that the Python XML story is confusing even for the files in the standard library. Worse, the (IMO) best solutions are not to be found in the standard lib or PyXML at all.
>>>>
>>>>The std lib and PyXML are based on the DOM and SAX standards. These standards were designed to be "language-neutral" - there are implementations in Python, Java and other languages. The good side of this is, if you learn how to use them, the knowledge is pretty portable to other languages. The bad side is, the APIs defined by the standard are IMO clunky and painful to use, especially in Python.
>>>>
>>>>There is a current thread on comp.lang.python discussing this with good suggestions and pointers to more info:
>>>>http://groups.google.com/group/comp.lang.python/browse_frm/thread/a48891aa645ead13/dcd8fdc20b4b191b?hl=en#dcd8fdc20b4b191b
>>>>
>>>>My personal preference is ElementTree. Beautiful Soup is good too though I have only tried it with HTML. If I was running on Linux I would try lxml which uses the ElementTree API and adds full XPath support. Amara looks like the Cadillac solution - big and cushy. I haven't tried it. Uche's articles (referenced in the thread above) have pointers to many other choices but these seem to be the most popular.
>>>>
>>>>My favorite XML lib is actually dom4j which is in Java. It works great with Jython.
>>>>
>>>>Kent
>>>>
>>>>
>>>>
>>>>>So right now I'm just taking a shortcut and using ultra-simple
>>>>>re-based parser to retrieve the tags I'm looking for. I know it will
>>>>>probably be slow, but hopefully I'll get familiar with sophisticated
>>>>>parsing in the future and improve my code. As it stands right now,
>>>>>even the re syntax is not super easy to learn.
>>>>
>>>>For what you are doing re seems fine to me. You can get in trouble using re's with XML because of nested tags, variations in spelling and order, probably a bunch of other things. But for simple stuff it can work fine.
>>>>
>>>>Kent
>>>>
>>>>
>>>>
>>>>>Kent: That works (of course!). Thanks a bunch once again!
>>>>>
>>>>>
>>>>>Thanks
>>>>>Bernard
>>>>>
>>>>>On 9/14/05, Alan G <alan.gauld at freenet.co.uk> wrote:
>>>>>
>>>>>
>>>>>
>>>>>>Hi Bernard,
>>>>>>
>>>>>>
>>>>>>
>>>>>>
>>>>>>>Hello, yet another regular expression question :-)
>>>>>>>
>>>>>>>So I have this xml file that I'm trying to find a
>>>>>>>specific tag in.
>>>>>>
>>>>>>I'm always suspicious when I see regular expression
>>>>>>and xml/html in the same context. regex are not good
>>>>>>for parsing xml/html files and it's usually much easier
>>>>>>to use a proper parser - such as beautiful soup.
>>>>>>
>>>>>>http://www.crummy.com/software/BeautifulSoup/
>>>>>>
>>>>>>Is there any special reason why you are using a regex
>>>>>>sledgehammer to crack this particular nut? Or is it
>>>>>>just to gain experience using regex?
>>>>>>
>>>>>>Alan G.
>>>>>>
>>>>>
>>>>>_______________________________________________
>>>>>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
>>>>
>>>
>>>_______________________________________________
>>>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
>>
> 
> 
> 


From matthew.williams at cancer.org.uk  Wed Sep 14 17:24:13 2005
From: matthew.williams at cancer.org.uk (Matt Williams)
Date: Wed, 14 Sep 2005 16:24:13 +0100
Subject: [Tutor] IDEs
In-Reply-To: <mailman.1072.1126709746.508.tutor@python.org>
References: <mailman.1072.1126709746.508.tutor@python.org>
Message-ID: <1126711453.4624.3.camel@dhcp0320.acl.icnet.uk>

I've used both PyDev and Wing IDE.

PyDev seems good, and is getting better. 
Wing is pay-for (although only $40 or so), but can be trialled. I thought
it was good, but had a huge problem trying to get it to play with a C library
I was using...

I've never managed to get Boa-Constructor to run...

As regards using wxPython - I thought it was ok, but frankly Glade was soooo
much easier..

(all IMHO)

Matt


From 3dbernard at gmail.com  Wed Sep 14 17:53:21 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Wed, 14 Sep 2005 11:53:21 -0400
Subject: [Tutor] Another regular expression question
In-Reply-To: <43283F90.8000806@tds.net>
References: <61d0e2b4050913145714553ac4@mail.gmail.com>
	<00f801c5b900$112e1b20$0201a8c0@xp>
	<61d0e2b4050914060866cf26a6@mail.gmail.com> <4328276F.5000309@tds.net>
	<61d0e2b405091407353f4c29a4@mail.gmail.com> <432839EF.9010507@tds.net>
	<61d0e2b405091408011b78436d@mail.gmail.com> <43283F90.8000806@tds.net>
Message-ID: <61d0e2b4050914085337925d5f@mail.gmail.com>

Hi Kent,

Well even before reading your last email I gave it a go, just parsing
the xml file and trying out some basic functions. It ran in less than
two seconds. I don't know why BeautifulSoup is taking so long...

Thanks for the "to get you started"!


Bernard



On 9/14/05, Kent Johnson <kent37 at tds.net> wrote:
> Bernard Lebel wrote:
> > The file size is 112 Kb. Most lines look this way:
> >
> > <parameter name="roty" type="Parameter" sourceclassname="nosource">
> >
> >
> > I'll give a try to ElementTree.
> 
> To get you started:
> 
> from elementtree import ElementTree
> doc = ElementTree.parse('myfile.xml')
> for sceneobject in doc.findall('//sceneobject'):
>   if sceneobject.get('type') == 'CameraRoot':
>     # this is a sceneobject that you want
>     print sceneobject.get('name')
> 
> One gotcha - if your XML uses namespaces, you have to prefix the namespace to the tag name in findall(). It will look something like
>   d.findall('//{http://www.imsproject.org/xsd/imscp_rootv1p1p2}resource')
> 
> Let us know how long that takes...
> 
> Kent
> 
> >
> >
> > Bernard
> >
> >
> >
> > On 9/14/05, Kent Johnson <kent37 at tds.net> wrote:
> >
> >>Bernard Lebel wrote:
> >>
> >>>Thanks for that pointer Kent, I'll check it out. Also thanks for
> >>>letting me know I'm not nuts! :-)
> >>>
> >>>Alan's suggestion about BeautifulSoup is actually excellent. The
> >>>documentation is nice and the tool is very easy to use.
> >>>
> >>>However is it normal that to parse a 2618 lines xml file it takes
> >>>20-30 seconds or so?
> >>
> >>That seems slow to me unless the lines are really long! How many bytes is the file? But I don't have much experience with BeautifulSoup.
> >>
> >>ElementTree is fast and cElementTree (the C implementation) is really fast. I have used it to read, process and write a 28 MB XML file, it took about 10 seconds.
> >>
> >>Kent
> >>
> >>
> >>>
> >>>Thanks
> >>>Bernard
> >>>
> >>>
> >>>
> >>>On 9/14/05, Kent Johnson <kent37 at tds.net> wrote:
> >>>
> >>>
> >>>>Bernard Lebel wrote:
> >>>>
> >>>>
> >>>>>Thanks Alan,
> >>>>>
> >>>>>I'll check BeautifulSoup asap.
> >>>>>
> >>>>>I'm using regex simply because I have no clue where to start to parse
> >>>>>XML. I have read the various xml tools available in the Python
> >>>>>library, however I'm a complete loss at what to make out of them. Many
> >>>>>of them seem to use some programming standards, wich I am completely
> >>>>>unfamiliar with (this is the first time that I dig into XML writing
> >>>>>and parsing).
> >>>>>
> >>>>>I don't know where to start to learn about all these standards, and as
> >>>>>usual with new programming things, the documentation is hard to
> >>>>>swallow (it usually is written more as a reference than a proper user
> >>>>>guide/tutorial). I have to admit this is very frustrating, so if I'm
> >>>>>looking at things from a wrong perspective please advise me, I need
> >>>>>it.
> >>>>
> >>>>I agree that the Python XML story is confusing even for the files in the standard library. Worse, the (IMO) best solutions are not to be found in the standard lib or PyXML at all.
> >>>>
> >>>>The std lib and PyXML are based on the DOM and SAX standards. These standards were designed to be "language-neutral" - there are implementations in Python, Java and other languages. The good side of this is, if you learn how to use them, the knowledge is pretty portable to other languages. The bad side is, the APIs defined by the standard are IMO clunky and painful to use, especially in Python.
> >>>>
> >>>>There is a current thread on comp.lang.python discussing this with good suggestions and pointers to more info:
> >>>>http://groups.google.com/group/comp.lang.python/browse_frm/thread/a48891aa645ead13/dcd8fdc20b4b191b?hl=en#dcd8fdc20b4b191b
> >>>>
> >>>>My personal preference is ElementTree. Beautiful Soup is good too though I have only tried it with HTML. If I was running on Linux I would try lxml which uses the ElementTree API and adds full XPath support. Amara looks like the Cadillac solution - big and cushy. I haven't tried it. Uche's articles (referenced in the thread above) have pointers to many other choices but these seem to be the most popular.
> >>>>
> >>>>My favorite XML lib is actually dom4j which is in Java. It works great with Jython.
> >>>>
> >>>>Kent
> >>>>
> >>>>
> >>>>
> >>>>>So right now I'm just taking a shortcut and using ultra-simple
> >>>>>re-based parser to retrieve the tags I'm looking for. I know it will
> >>>>>probably be slow, but hopefully I'll get familiar with sophisticated
> >>>>>parsing in the future and improve my code. As it stands right now,
> >>>>>even the re syntax is not super easy to learn.
> >>>>
> >>>>For what you are doing re seems fine to me. You can get in trouble using re's with XML because of nested tags, variations in spelling and order, probably a bunch of other things. But for simple stuff it can work fine.
> >>>>
> >>>>Kent
> >>>>
> >>>>
> >>>>
> >>>>>Kent: That works (of course!). Thanks a bunch once again!
> >>>>>
> >>>>>
> >>>>>Thanks
> >>>>>Bernard
> >>>>>
> >>>>>On 9/14/05, Alan G <alan.gauld at freenet.co.uk> wrote:
> >>>>>
> >>>>>
> >>>>>
> >>>>>>Hi Bernard,
> >>>>>>
> >>>>>>
> >>>>>>
> >>>>>>
> >>>>>>>Hello, yet another regular expression question :-)
> >>>>>>>
> >>>>>>>So I have this xml file that I'm trying to find a
> >>>>>>>specific tag in.
> >>>>>>
> >>>>>>I'm always suspicious when I see regular expression
> >>>>>>and xml/html in the same context. regex are not good
> >>>>>>for parsing xml/html files and it's usually much easier
> >>>>>>to use a proper parser - such as beautiful soup.
> >>>>>>
> >>>>>>http://www.crummy.com/software/BeautifulSoup/
> >>>>>>
> >>>>>>Is there any special reason why you are using a regex
> >>>>>>sledgehammer to crack this particular nut? Or is it
> >>>>>>just to gain experience using regex?
> >>>>>>
> >>>>>>Alan G.
> >>>>>>
> >>>>>
> >>>>>_______________________________________________
> >>>>>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
> >>>>
> >>>
> >>>_______________________________________________
> >>>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
> >>
> >
> >
> >
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From tim at johnsons-web.com  Wed Sep 14 18:22:05 2005
From: tim at johnsons-web.com (Tim Johnson)
Date: Wed, 14 Sep 2005 08:22:05 -0800
Subject: [Tutor] IDEs
In-Reply-To: <1126711453.4624.3.camel@dhcp0320.acl.icnet.uk>
References: <mailman.1072.1126709746.508.tutor@python.org>
	<1126711453.4624.3.camel@dhcp0320.acl.icnet.uk>
Message-ID: <20050914162205.GE1804@johnsons-web.com>

* Matt Williams <matthew.williams at cancer.org.uk> [050914 07:27]:
> I've used both PyDev and Wing IDE.
> 
> PyDev seems good, and is getting better. 
> Wing is pay-for (although only $40 or so), but can be trialled. I thought
> it was good, but had a huge problem trying to get it to play with a C library
> I was using...
> 
> I've never managed to get Boa-Constructor to run...
> 
> As regards using wxPython - I thought it was ok, but frankly Glade was soooo
> much easier..
 
  I use both (g)vim and emacs/Xemacs. You can compile the python
  interpreter directly into vim and that gives you access to all kinds
  of goodies from the vim community.

  The two forks of emacs both support a full-blown programming language
  of their own (elisp) that gives you in many ways a "mini-os" at
  your fingertips.

  And with Xemacs you can even have bitmaps for your backgroud, but
  of course that can be distracting, if you are (for instance) coding
  over the top of Mariah Carey.

  For Windows, the finest Shareware edit IMHO is Boxer.
  But if I programmed only in Python and only on windows, I'd
  use PythonWin.

  MTCW
  tim
  

-- 
Tim Johnson <tim at johnsons-web.com>
      http://www.alaska-internet-solutions.com

From alan.gauld at freenet.co.uk  Wed Sep 14 18:45:28 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Wed, 14 Sep 2005 17:45:28 +0100
Subject: [Tutor] Another regular expression question
References: <61d0e2b4050913145714553ac4@mail.gmail.com><00f801c5b900$112e1b20$0201a8c0@xp><61d0e2b4050914060866cf26a6@mail.gmail.com>
	<4328276F.5000309@tds.net>
	<61d0e2b405091407353f4c29a4@mail.gmail.com>
Message-ID: <012a01c5b94b$b6aca260$0201a8c0@xp>

> However is it normal that to parse a 2618 lines xml file 
> it takes 20-30 seconds or so?

Only if you are running it on an original Palm Pilot!

Seriously, I'd expect it to be more like 2-3 seconds.
Something fishy there.

Alan G.

From nephish at xit.net  Wed Sep 14 18:45:25 2005
From: nephish at xit.net (nephish)
Date: Wed, 14 Sep 2005 11:45:25 -0500
Subject: [Tutor] IDEs
In-Reply-To: <1126711453.4624.3.camel@dhcp0320.acl.icnet.uk>
References: <mailman.1072.1126709746.508.tutor@python.org>
	<1126711453.4624.3.camel@dhcp0320.acl.icnet.uk>
Message-ID: <432853A5.90900@xit.net>

Matt Williams wrote:

>I've used both PyDev and Wing IDE.
>
>PyDev seems good, and is getting better. 
>Wing is pay-for (although only $40 or so), but can be trialled. I thought
>it was good, but had a huge problem trying to get it to play with a C library
>I was using...
>
>I've never managed to get Boa-Constructor to run...
>
>As regards using wxPython - I thought it was ok, but frankly Glade was soooo
>much easier..
>
>(all IMHO)
>
>Matt
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
Yup, exactly why i use glade!
sk

From alan.gauld at freenet.co.uk  Wed Sep 14 19:12:41 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Wed, 14 Sep 2005 18:12:41 +0100
Subject: [Tutor] IDEs
References: <mailman.1072.1126709746.508.tutor@python.org><1126711453.4624.3.camel@dhcp0320.acl.icnet.uk>
	<20050914162205.GE1804@johnsons-web.com>
Message-ID: <014a01c5b94f$8549d310$0201a8c0@xp>

>  For Windows, the finest Shareware edit IMHO is Boxer.

Editor religious wars are nearly as bad as programming 
language wars but I can't resist.

My favourite windows editor these days is gvim. I've never got 
round to adding the python scripting feature, mainly because 
I try not to customize it too much. But its simple, fast and 
works the same on Linux, Mac and Windoze...

I used to be an emacs zealot but for some reason emacs never 
seemed comfortable on Windows.

>  But if I programmed only in Python and only on windows, I'd
>  use PythonWin.

Pythonwin is better than IDLE, but I still prefer gvim and a 
command line prompt. Although I confess to firing up Pyhonwin 
occasionally to use it's debugger!

Alan G.

PS I'm playing with JSP at the moment and am very impressed 
with the open source NetBeans IDE. It would be nice if someone 
modified it to work with Python! :-)


From kent37 at tds.net  Wed Sep 14 19:42:11 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Sep 2005 13:42:11 -0400
Subject: [Tutor] IDEs
In-Reply-To: <014a01c5b94f$8549d310$0201a8c0@xp>
References: <mailman.1072.1126709746.508.tutor@python.org><1126711453.4624.3.camel@dhcp0320.acl.icnet.uk>	<20050914162205.GE1804@johnsons-web.com>
	<014a01c5b94f$8549d310$0201a8c0@xp>
Message-ID: <432860F3.40309@tds.net>

Alan G wrote:
> PS I'm playing with JSP at the moment and am very impressed 
> with the open source NetBeans IDE. It would be nice if someone 
> modified it to work with Python! :-)

How about Jython? See https://coyote.dev.java.net/

Kent


From wildcard2005 at comcast.net  Wed Sep 14 20:12:37 2005
From: wildcard2005 at comcast.net (Terry Kemmerer)
Date: Wed, 14 Sep 2005 11:12:37 -0700
Subject: [Tutor] More IDE's (was: Boa-Constructor)
In-Reply-To: <59CF9F456FAA9045B405C441EC916F3E02CE8639@MERC24.na.sas.com>
References: <59CF9F456FAA9045B405C441EC916F3E02CE8639@MERC24.na.sas.com>
Message-ID: <1126721558.8845.5.camel@c-24-16-68-31.hsd1.wa.comcast.net>

Thanks. This was going to be another question of mine, as to what was
wrong with going the Emacs and Vim directions.

Terry


On Wed, 2005-09-14 at 09:40 -0400, George Flaherty wrote:

> Yeah, I have been using PyDev with Eclipse. It is pretty good, since with the latest version the debugger is working and they have include the ability to add additional paths in the PYTHONPATH variable.
> 
> I honestly would prefer to use Emacs, but I have not found any tool that provides code-completion with python. Until I have been using Eclipse (with Emacs running minimized :)
> 
> -g
> 
> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of D. Hartley
> Sent: Tuesday, September 13, 2005 10:27 PM
> To: Python tutor
> Subject: [Tutor] More IDE's (was: Boa-Constructor)
> 
> This thread made me wonder:
> 
> Is anyone out there using Eclipse and PyDev? (I started using Eclipse when I was toying around in Jython, and know others that are using it for C/C++, but I am curious if others have tried out PyDev and what they think).
> 
> ~Denise
> _______________________________________________
> 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050914/85e6799e/attachment.htm

From 3dbernard at gmail.com  Wed Sep 14 20:14:43 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Wed, 14 Sep 2005 14:14:43 -0400
Subject: [Tutor] Retrieving the text of a XML tag with ElementTree
Message-ID: <61d0e2b405091411146d3513ee@mail.gmail.com>

Hello,

Let say I have this XML chunk:


<?xml version="1.0"?>

<root>
  <sceneobject name="Camera_Root" fullname="Camera_Root" type="CameraRoot">
    <properties>
      <property name="Visibility" fullname="Camera_Root.visibility"
type="visibility">
        <parameters>
          <parameter scriptname="viewvis"
fullname="Camera_Root.visibility.viewvis" type="Parameter"
sourceclassname="nosource">False</parameter>


I wish to retrieve the "False" between the opening/closing tags.
I thought I could use something like:


from elementtree.ElementTree import parse

oTree = parse( r'C:\temp\Camera_Root.xml' )

for oXMLObject in oTree.findall( '//sceneobject' ):
	if oXMLObject.attrib[ 'type' ] == 'CameraRoot':
		
		oXMLProps = oXMLObject.find( 'properties' )
		
		# We found the tag
		for oXMLProp in oXMLProps.findall( 'property' ):
			if oXMLProp.attrib[ 'name' ] == 'Visibility':
				print oXMLProp.text


Now the print statements prints an empty line, wich is obviously not
what I'm after :-)


Thanks
Bernard

From 3dbernard at gmail.com  Wed Sep 14 20:28:25 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Wed, 14 Sep 2005 14:28:25 -0400
Subject: [Tutor] Retrieving the text of a XML tag with ElementTree
In-Reply-To: <61d0e2b405091411146d3513ee@mail.gmail.com>
References: <61d0e2b405091411146d3513ee@mail.gmail.com>
Message-ID: <61d0e2b405091411284186f29@mail.gmail.com>

Oops, false alarm.

I was reading the wrong tag.... (the <property> tag instead of a
<parameter> one).


Sorry!
Bernard



On 9/14/05, Bernard Lebel <3dbernard at gmail.com> wrote:
> Hello,
> 
> Let say I have this XML chunk:
> 
> 
> <?xml version="1.0"?>
> 
> <root>
>   <sceneobject name="Camera_Root" fullname="Camera_Root" type="CameraRoot">
>     <properties>
>       <property name="Visibility" fullname="Camera_Root.visibility"
> type="visibility">
>         <parameters>
>           <parameter scriptname="viewvis"
> fullname="Camera_Root.visibility.viewvis" type="Parameter"
> sourceclassname="nosource">False</parameter>
> 
> 
> I wish to retrieve the "False" between the opening/closing tags.
> I thought I could use something like:
> 
> 
> from elementtree.ElementTree import parse
> 
> oTree = parse( r'C:\temp\Camera_Root.xml' )
> 
> for oXMLObject in oTree.findall( '//sceneobject' ):
>         if oXMLObject.attrib[ 'type' ] == 'CameraRoot':
> 
>                 oXMLProps = oXMLObject.find( 'properties' )
> 
>                 # We found the tag
>                 for oXMLProp in oXMLProps.findall( 'property' ):
>                         if oXMLProp.attrib[ 'name' ] == 'Visibility':
>                                 print oXMLProp.text
> 
> 
> Now the print statements prints an empty line, wich is obviously not
> what I'm after :-)
> 
> 
> Thanks
> Bernard
>

From kent37 at tds.net  Wed Sep 14 20:36:41 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Sep 2005 14:36:41 -0400
Subject: [Tutor] Retrieving the text of a XML tag with ElementTree
In-Reply-To: <61d0e2b405091411146d3513ee@mail.gmail.com>
References: <61d0e2b405091411146d3513ee@mail.gmail.com>
Message-ID: <43286DB9.3050805@tds.net>



Bernard Lebel wrote:
> Hello,
> 
> Let say I have this XML chunk:
> 
> 
> <?xml version="1.0"?>
> 
> <root>
>   <sceneobject name="Camera_Root" fullname="Camera_Root" type="CameraRoot">
>     <properties>
>       <property name="Visibility" fullname="Camera_Root.visibility"
> type="visibility">
>         <parameters>
>           <parameter scriptname="viewvis"
> fullname="Camera_Root.visibility.viewvis" type="Parameter"
> sourceclassname="nosource">False</parameter>
> 
> 
> I wish to retrieve the "False" between the opening/closing tags.
> I thought I could use something like:
> 
> 
> from elementtree.ElementTree import parse
> 
> oTree = parse( r'C:\temp\Camera_Root.xml' )
> 
> for oXMLObject in oTree.findall( '//sceneobject' ):
> 	if oXMLObject.attrib[ 'type' ] == 'CameraRoot':
> 		
> 		oXMLProps = oXMLObject.find( 'properties' )
> 		
> 		# We found the tag
> 		for oXMLProp in oXMLProps.findall( 'property' ):
> 			if oXMLProp.attrib[ 'name' ] == 'Visibility':
> 				print oXMLProp.text
> 
> 
> Now the print statements prints an empty line, wich is obviously not
> what I'm after :-)

You have to dig a little more, the text is part of the <parameter> element, not the <property> element. Something like
		for oXMLProp in oXMLProps.findall( 'property' ):
			if oXMLProp.attrib[ 'name' ] == 'Visibility':
				for param in oXMLProp.findall('.//parameter'):
					print param.text

I really wish ElementTree supported full XPath expressions. If it did this whole thing would almost be a one-liner - something like

for param in oTree.findall( '//sceneobject[@type="CameraRoot"]/properties/property[@name="Visibility"]/parameters/parameter'):
  print param.text

Sigh. XPath really rocks. Anyone want to port lxml to Windows?

Kent



From davholla2002 at yahoo.co.uk  Wed Sep 14 20:58:07 2005
From: davholla2002 at yahoo.co.uk (David Holland)
Date: Wed, 14 Sep 2005 19:58:07 +0100 (BST)
Subject: [Tutor] Focus in tkinter
Message-ID: <20050914185807.52933.qmail@web25904.mail.ukl.yahoo.com>

I want to make the mouse focus in a GUI move to the
correct button/text entry widget.  Does anyone know
how to do this ?

Thanks in advance


David


	
	
		
___________________________________________________________ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com

From tim at johnsons-web.com  Wed Sep 14 21:21:27 2005
From: tim at johnsons-web.com (Tim Johnson)
Date: Wed, 14 Sep 2005 11:21:27 -0800
Subject: [Tutor] IDEs
In-Reply-To: <014a01c5b94f$8549d310$0201a8c0@xp>
References: <mailman.1072.1126709746.508.tutor@python.org>
	<1126711453.4624.3.camel@dhcp0320.acl.icnet.uk>
	<20050914162205.GE1804@johnsons-web.com>
	<014a01c5b94f$8549d310$0201a8c0@xp>
Message-ID: <20050914192127.GF1804@johnsons-web.com>

* Alan G <alan.gauld at freenet.co.uk> [050914 09:21]:
> >  For Windows, the finest Shareware edit IMHO is Boxer.
> 
> Editor religious wars are nearly as bad as programming 
> language wars but I can't resist.
 
  <grin> ERWs are a misdirection of energy IMHO. Talking about
         editors and languages *is* a good way to learn about
         the options available, however.

  If I were able to earn my living programming in only one language, I
  would use an editor the "fully understood" that language.  (thus
  pythonwin as an example). However, A typical work session for me would
  be writing code in python, rebol and javascript. In the same editor.
  With emacs/Xemacs I can customize so that I am using the same
  keystrokes for any language (say, navigating from one subroutine to
  another or inserting debugging stubs).

  Also, Emacs has a wonderful feature that I just can't live without:
  You can run a script interpreter within the editor and maintain
  asynchronous communication with it. It's called *comint mode*

  At the same time, I might be navigating among directories
  and text, html or other file resources and doing as-needs editing
  or search. Using Midnight Commander with vim as the default
  editor works wonderfully for this function and vim beats the
  pants off of emacs for adhoc editing and quick "on the fly"
  keymapping that might be needed for one particular editing
  session.

  BTW: Total Commander is a wonderful alternative to Midnight
       Commander on Windows. Shareware (about 39 bucks).

> My favourite windows editor these days is gvim. I've never got 
> round to adding the python scripting feature, mainly because 

  I would bet that compiling in the python binary on windows
  would be more daunting....

> I try not to customize it too much. But its simple, fast and 
> works the same on Linux, Mac and Windoze...
 
  I echo that gvim works exactly the same on those various platforms
  for me. I have found that comint mode in emacs doesn't work
  right (for me) on windows. 

> I used to be an emacs zealot but for some reason emacs never 
> seemed comfortable on Windows.
> 
> >  But if I programmed only in Python and only on windows, I'd
> >  use PythonWin.
> 
> Pythonwin is better than IDLE, but I still prefer gvim and a 
> command line prompt. Although I confess to firing up Pyhonwin 
> occasionally to use it's debugger!
 
  Bottom line is: Everyone's circumstances and needs differ.
  It's great having all these options!
  --
  tj (writing this email with vim)

> Alan G.
> 
> PS I'm playing with JSP at the moment and am very impressed 
> with the open source NetBeans IDE. It would be nice if someone 
> modified it to work with Python! :-)
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Tim Johnson <tim at johnsons-web.com>
      http://www.alaska-internet-solutions.com

From godoy at ieee.org  Wed Sep 14 21:28:09 2005
From: godoy at ieee.org (Jorge Godoy)
Date: 14 Sep 2005 16:28:09 -0300
Subject: [Tutor] IDEs
References: <mailman.1072.1126709746.508.tutor@python.org>
	<1126711453.4624.3.camel@dhcp0320.acl.icnet.uk>
	<20050914162205.GE1804@johnsons-web.com>
Message-ID: <87k6hjqwja.fsf@ieee.org>

Tim Johnson <tim at johnsons-web.com> writes:

>   And with Xemacs you can even have bitmaps for your backgroud, but
>   of course that can be distracting, if you are (for instance) coding
>   over the top of Mariah Carey.

On the other hand, it will be easy (?) to find bugs on her nipples... ;-) 


-- 
Jorge Godoy      <godoy at ieee.org>


From klappnase at freenet.de  Wed Sep 14 21:54:06 2005
From: klappnase at freenet.de (Michael Lange)
Date: Wed, 14 Sep 2005 21:54:06 +0200
Subject: [Tutor] Focus in tkinter
In-Reply-To: <20050914185807.52933.qmail@web25904.mail.ukl.yahoo.com>
References: <20050914185807.52933.qmail@web25904.mail.ukl.yahoo.com>
Message-ID: <20050914215406.022ed39c@rappelkiste>

On Wed, 14 Sep 2005 19:58:07 +0100 (BST)
David Holland <davholla2002 at yahoo.co.uk> wrote:

> I want to make the mouse focus in a GUI move to the
> correct button/text entry widget.  Does anyone know
> how to do this ?
> 

Hi David,

to set the focus to a particular widget you need the focus_Set() method:

b = Button(parent)
b.focus_set()

Maybe you want to have a look at Frederik Lundh's excellent Tkinter books:

   <http://www.effbot.org/tkinterbook>

or the more complete, but a little outdated version:

    <http://www.pythonware.com/library/tkinter/introduction/index.htm>

I hope this helps

Michael

From alan.gauld at freenet.co.uk  Wed Sep 14 23:07:43 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Wed, 14 Sep 2005 22:07:43 +0100
Subject: [Tutor] IDEs
References: <mailman.1072.1126709746.508.tutor@python.org><1126711453.4624.3.camel@dhcp0320.acl.icnet.uk>	<20050914162205.GE1804@johnsons-web.com><014a01c5b94f$8549d310$0201a8c0@xp>
	<432860F3.40309@tds.net>
Message-ID: <002701c5b970$5954c2d0$0201a8c0@xp>

>> with the open source NetBeans IDE. It would be nice if someone 
>> modified it to work with Python! :-)
>
> How about Jython? See https://coyote.dev.java.net/

My work is done for me!
I was seriously looking at wring a plug in to support Jython because
I couldn't see one listed on the official plug in page. It was looking 
a tad daunting, now I don't need to.

Excellent, thanks Kent.

Alan G.

PS Now off to find out what the heck 'Groovy' looks like! :-) 


From edhotchkiss at gmail.com  Wed Sep 14 23:58:29 2005
From: edhotchkiss at gmail.com (Ed Hotchkiss)
Date: Wed, 14 Sep 2005 17:58:29 -0400
Subject: [Tutor] running scripts with windows
Message-ID: <d1bf1fa2050914145859c9c18c@mail.gmail.com>

Hi everyone, I'm home for the next few weeks while I'm learning Python, and 
I'm not on a *NIX box, I'm using windows. How the hell do I run a Python 
script? Sorry if this is a 'dumb question'. 

-- 
edward hotchkiss
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050914/9f1bbc59/attachment.htm

From keridee at jayco.net  Thu Sep 15 00:28:08 2005
From: keridee at jayco.net (Jacob S.)
Date: Wed, 14 Sep 2005 17:28:08 -0500
Subject: [Tutor] running scripts with windows
References: <d1bf1fa2050914145859c9c18c@mail.gmail.com>
Message-ID: <014b01c5b97b$aecec6b0$6401a8c0@JSLAPTOP>

Well, if your python installation went correctly, all you should have to do is save the script with a .py extension and then double click on it.

Jacob

  ----- Original Message ----- 
  From: Ed Hotchkiss 
  To: tutor at python.org 
  Sent: Wednesday, September 14, 2005 4:58 PM
  Subject: [Tutor] running scripts with windows


  Hi everyone, I'm home for the next few weeks while I'm learning Python, and I'm not on a *NIX box, I'm using windows. How the hell do I run a Python script? Sorry if this is a 'dumb question'. 

  -- 
  edward hotchkiss 


------------------------------------------------------------------------------


  _______________________________________________
  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/20050914/36fefc8c/attachment.html

From john at fouhy.net  Thu Sep 15 00:28:26 2005
From: john at fouhy.net (John Fouhy)
Date: Thu, 15 Sep 2005 10:28:26 +1200
Subject: [Tutor] running scripts with windows
In-Reply-To: <d1bf1fa2050914145859c9c18c@mail.gmail.com>
References: <d1bf1fa2050914145859c9c18c@mail.gmail.com>
Message-ID: <5e58f2e405091415286d486815@mail.gmail.com>

On 15/09/05, Ed Hotchkiss <edhotchkiss at gmail.com> wrote:
> Hi everyone, I'm home for the next few weeks while I'm learning Python, and
> I'm not on a *NIX box, I'm using windows. How the hell do I run a Python
> script? Sorry if this is a 'dumb question'. 

Step 1 - install python :-) http://www.python.org/ has Windows binaries.

Step 2 - make sure python.exe is in your path.  You can edit your path
by right-clicking on "My computer" and following your nose.

Step 3 - get a command shell (eg, Start->Run->"cmd"). cd to the
directory where your script is and tyoe "python [scriptname]".

You can also double-click on the script name in Windows Explorer, but
the disadvantage of that is that the shell goes away as soon as your
script finishes, which makes seeing output hard.

Finally, if you're accustomed to unix, you might like to install
Cygwin (http://www.cygwin.com/)  It gives you a bash shell in Windows.
 Quite nice.

HTH!

-- 
John.

From eric.guirbal at cegetel.net  Thu Sep 15 01:05:47 2005
From: eric.guirbal at cegetel.net (Eric Guirbal)
Date: Thu, 15 Sep 2005 01:05:47 +0200
Subject: [Tutor] Curses and Konsole
Message-ID: <200509150105.47359.eric.guirbal@cegetel.net>

Hello,

I have been leaning Python for one week. My first project consist in doing  a
front end to a MySQL  database using the module curses. I have a little
display problem in a Konsole terminal. More precisely, when I apply the border
method, between each character _ one blank space is inserted. I checked the
variable $TERM. I think my program is clear because the same display problem
occur with Midnight Commander. By a similar problem posted on a debian list, I 
tried

import locale
locale.setlocale(locale.LC_ALL)

without success. On the other hand, it is ok in a xterm or rxvt 
terminal. I use python 2.3, ncurses 5.3 and Konsole 1.2.3 (KDE 3.1.3) and my
system is in iso-8859-15. All clue is welcome. 
Thanks.

-- 
Eric Guirbal


From cpu.crazy at gmail.com  Wed Sep 14 16:46:35 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Wed, 14 Sep 2005 08:46:35 -0600
Subject: [Tutor] (no subject)
Message-ID: <432837CB.3030603@gmail.com>

>
>
>> And also, is Python capable of writing an OS?
>  
>
Actually, yes. Google for "Python OS" and look for Unununium (or 
something like that. I can never remember). It has no kernel and to 
booting process may not exactly be in Python... but they say it's an OS 
written in Python and that it boots to the python interpreter.

Just a warning: it's no where near Mac OS (x), Windows (x) and Linux 2.x 
with a distro that you may be familiar with.


From travislspencer at gmail.com  Thu Sep 15 07:18:56 2005
From: travislspencer at gmail.com (Travis Spencer)
Date: Wed, 14 Sep 2005 22:18:56 -0700
Subject: [Tutor] Parsing os.popen(command) output
In-Reply-To: <43243E73.8050603@pennswoods.net>
References: <43243E73.8050603@pennswoods.net>
Message-ID: <e3b7bac050914221855d4a7bf@mail.gmail.com>

On 9/11/05, Bill Burns <billburns at pennswoods.net> wrote:
> Like I said, it does work but can it be improved upon?

The variable names could stand some improvement.  p, r, s, tmp, i,
etc. aren't very explanatory.  If you choose better names, your
coworkers, not to mention your future self, will be very thankful.

-- 

Regards,

Travis Spencer

From singletoned at gmail.com  Thu Sep 15 10:56:39 2005
From: singletoned at gmail.com (Ed Singleton)
Date: Thu, 15 Sep 2005 09:56:39 +0100
Subject: [Tutor] Multiple Simultaneous Loops
Message-ID: <34bb7f5b0509150156875464c@mail.gmail.com>

I roughly want to be able to do:

for f, x in bunch_of_files, range(z):

so that x iterates through my files, and y iterates through something else.

Is this something I can do?

If so, what would be the best way to create a range of indeterminate length?

If not, is there a nice way I can do it, rather than than incrementing
a variable (x = x + 1) every loop?

Or maybe can I access the number of times the loop has run?  ('x = x +
1' is so common there must be some more attractive shortcut).

So far in learning Python I've founbd that when I feel you should be
able to do something, then you can.  This seems a pretty intuitive
thing to want to do, so I'm sure it must be possible, but I can't find
anything on it.

Many thanks

Ed

From ajikoe at gmail.com  Thu Sep 15 11:16:28 2005
From: ajikoe at gmail.com (Pujo Aji)
Date: Thu, 15 Sep 2005 11:16:28 +0200
Subject: [Tutor] Multiple Simultaneous Loops
In-Reply-To: <34bb7f5b0509150156875464c@mail.gmail.com>
References: <34bb7f5b0509150156875464c@mail.gmail.com>
Message-ID: <cf5262d2050915021617768bf4@mail.gmail.com>

assume:
you have two list with the same size
L1 = [1,2,3]
L2 = [11,22,33]
 you can zip the L1 and L2 into L
L = zip(L1,L2) # L = [(1,11),(2,22),(3,33)] 
 then you can process:
for x in L:
 dosomething(x[0])...
 dosomething(x[1])...
 I'm not so sure about your problem but
If you want to do something parallel processing then you should go to 
threading or pyro.
 Cheers,
pujo


On 9/15/05, Ed Singleton <singletoned at gmail.com> wrote: 
> 
> I roughly want to be able to do:
> 
> for f, x in bunch_of_files, range(z):
> 
> so that x iterates through my files, and y iterates through something 
> else.
> 
> Is this something I can do?
> 
> If so, what would be the best way to create a range of indeterminate 
> length?
> 
> If not, is there a nice way I can do it, rather than than incrementing
> a variable (x = x + 1) every loop?
> 
> Or maybe can I access the number of times the loop has run? ('x = x +
> 1' is so common there must be some more attractive shortcut).
> 
> So far in learning Python I've founbd that when I feel you should be
> able to do something, then you can. This seems a pretty intuitive
> thing to want to do, so I'm sure it must be possible, but I can't find
> anything on it.
> 
> Many thanks
> 
> Ed
> _______________________________________________
> 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/20050915/6cbf6540/attachment-0001.html

From andreengels at gmail.com  Thu Sep 15 11:26:39 2005
From: andreengels at gmail.com (Andre Engels)
Date: Thu, 15 Sep 2005 11:26:39 +0200
Subject: [Tutor] Multiple Simultaneous Loops
In-Reply-To: <34bb7f5b0509150156875464c@mail.gmail.com>
References: <34bb7f5b0509150156875464c@mail.gmail.com>
Message-ID: <6faf39c90509150226154f08d2@mail.gmail.com>

On 9/15/05, Ed Singleton <singletoned at gmail.com> wrote:
> I roughly want to be able to do:
> 
> for x, y in bunch_of_files, range(z):
> 
> so that x iterates through my files, and y iterates through something else.
> 
> Is this something I can do?

It's not fully clear to me what you want to do. Do you want to go
through each pair x,y with x in bunch_of_files and y in range(z)? Then
you can do:

for x in bunch_of_files:
    for y in range(z):

Or do you want to have one value of y for each value of x? In that
case I think you'd want:
for y in range(len(bunch_of_files)):
    x = bunch_of_files[y]

> If so, what would be the best way to create a range of indeterminate length?

I don't think such a thing exists. Either it has some length or it
does not. There's nothing in between.

> If not, is there a nice way I can do it, rather than than incrementing
> a variable (x = x + 1) every loop?
> 
> Or maybe can I access the number of times the loop has run?  ('x = x +
> 1' is so common there must be some more attractive shortcut).

See my second example above?

Andre Engels

From pierre.barbier at cirad.fr  Thu Sep 15 11:39:08 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Thu, 15 Sep 2005 11:39:08 +0200
Subject: [Tutor] Multiple Simultaneous Loops
In-Reply-To: <cf5262d2050915021617768bf4@mail.gmail.com>
References: <34bb7f5b0509150156875464c@mail.gmail.com>
	<cf5262d2050915021617768bf4@mail.gmail.com>
Message-ID: <4329413C.2070806@cirad.fr>

You have a much simpler solution !
As this is a most common task to iterate on a sequence while keeping
track of the index, there is an object just for that :

for i,x in enumerate(iterable):
  # Here "i" is the index and "x" the element

Also, to get some "advance" iteration schemes, have a lot at the module
"itertools" ... there is a bunch of very usefull items in it (the most
usefull to me bzing "izip") !

Pierre

Pujo Aji a ?crit :
> assume:
> you have two list with the same size
> L1 = [1,2,3]
> L2 = [11,22,33]
>  you can zip the L1 and L2 into L
> L = zip(L1,L2) # L = [(1,11),(2,22),(3,33)] 
>  then you can process:
> for x in L:
>  dosomething(x[0])...
>  dosomething(x[1])...
>  I'm not so sure about your problem but
> If you want to do something parallel processing then you should go to 
> threading or pyro.
>  Cheers,
> pujo
> 
> 

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68

From kent37 at tds.net  Thu Sep 15 11:44:09 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Sep 2005 05:44:09 -0400
Subject: [Tutor] Multiple Simultaneous Loops
In-Reply-To: <34bb7f5b0509150156875464c@mail.gmail.com>
References: <34bb7f5b0509150156875464c@mail.gmail.com>
Message-ID: <43294269.3010302@tds.net>

Ed Singleton wrote:
> I roughly want to be able to do:
> 
> for f, x in bunch_of_files, range(z):
> 
> so that x iterates through my files, and y iterates through something else.
> 
> Is this something I can do?

In the general case use zip():
for f, x in zip(bunch_of_files, range(z)):

In this case, where the second item is just the index to the loop, use enumerate() instead of range() and zip()
for x, f in enumerate(bunch_of_files):

> If so, what would be the best way to create a range of indeterminate length?

itertools.count() generates an "unlimited" sequence.
 
> If not, is there a nice way I can do it, rather than than incrementing
> a variable (x = x + 1) every loop?
> 
> Or maybe can I access the number of times the loop has run?  ('x = x +
> 1' is so common there must be some more attractive shortcut).

enumerate()
 
> So far in learning Python I've founbd that when I feel you should be
> able to do something, then you can.

Yep :-)

Kent


From singletoned at gmail.com  Thu Sep 15 12:34:46 2005
From: singletoned at gmail.com (Ed Singleton)
Date: Thu, 15 Sep 2005 11:34:46 +0100
Subject: [Tutor] Multiple Simultaneous Loops
In-Reply-To: <43294269.3010302@tds.net>
References: <34bb7f5b0509150156875464c@mail.gmail.com>
	<43294269.3010302@tds.net>
Message-ID: <34bb7f5b050915033452c3b4d4@mail.gmail.com>

Wonderful, thank you all of you.

zip, enumerate, and count seem to do everything I want, though I do think

for f, x in bunch_of_files, range(z):

is a little more intuitive than

for f, x in zip(bunch_of_files, range(z)):

Thanks

Ed

On 15/09/05, Kent Johnson <kent37 at tds.net> wrote:
> Ed Singleton wrote:
> > I roughly want to be able to do:
> >
> > for f, x in bunch_of_files, range(z):
> >
> > so that x iterates through my files, and y iterates through something else.
> >
> > Is this something I can do?
> 
> In the general case use zip():
> for f, x in zip(bunch_of_files, range(z)):
> 
> In this case, where the second item is just the index to the loop, use enumerate() instead of range() and zip()
> for x, f in enumerate(bunch_of_files):
> 
> > If so, what would be the best way to create a range of indeterminate length?
> 
> itertools.count() generates an "unlimited" sequence.
> 
> > If not, is there a nice way I can do it, rather than than incrementing
> > a variable (x = x + 1) every loop?
> >
> > Or maybe can I access the number of times the loop has run?  ('x = x +
> > 1' is so common there must be some more attractive shortcut).
> 
> enumerate()
> 
> > So far in learning Python I've founbd that when I feel you should be
> > able to do something, then you can.
> 
> Yep :-)
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From chris.arndt at web.de  Thu Sep 15 19:12:57 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Thu, 15 Sep 2005 18:12:57 +0100
Subject: [Tutor] Aschenputtel problem
Message-ID: <4329AB99.7070806@web.de>

Hi,

I wonder if there is a shorter form of the following idiom:

list1 = []
list2 = []
for item in original_list:
    if condition(item):
        list1.append(item)
    else:
        list2.append(item)

(optional step:)

original_list[:] = list1


I call this the "Aschenputtel" problem, because it is described by the famous
quote from the fairy tale as told by the Grimm brothers:

"Die guten ins T?pfchen, die schlechten ins Kr?pfchen."

(The good ones in the pot, the bad ones in the crop)

Chris


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 278 bytes
Desc: OpenPGP digital signature
Url : http://mail.python.org/pipermail/tutor/attachments/20050915/d88c26f0/signature.pgp

From alan.gauld at freenet.co.uk  Thu Sep 15 19:16:19 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Thu, 15 Sep 2005 18:16:19 +0100
Subject: [Tutor] running scripts with windows
References: <d1bf1fa2050914145859c9c18c@mail.gmail.com>
Message-ID: <002001c5ba19$307e75f0$0201a8c0@xp>

If you are a Unix head using windows run to the cygwin site
and install the whole caboodle.

You'll think you are back in Unix land...

If thats impossible them open a DOS boc (aka Command Prompt)
and type

python foo.py

Or even just double click the file in Windows explorer...

Alan G.


----- Original Message ----- 
From: "Ed Hotchkiss" <edhotchkiss at gmail.com>
To: <tutor at python.org>
Sent: Wednesday, September 14, 2005 10:58 PM
Subject: [Tutor] running scripts with windows


Hi everyone, I'm home for the next few weeks while I'm learning 
Python, and
I'm not on a *NIX box, I'm using windows. How the hell do I run a 
Python
script? Sorry if this is a 'dumb question'.

-- 
edward hotchkiss


From alan.gauld at freenet.co.uk  Thu Sep 15 19:18:14 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Thu, 15 Sep 2005 18:18:14 +0100
Subject: [Tutor] running scripts with windows
References: <d1bf1fa2050914145859c9c18c@mail.gmail.com>
	<5e58f2e405091415286d486815@mail.gmail.com>
Message-ID: <002c01c5ba19$752f73c0$0201a8c0@xp>

> Cygwin (http://www.cygwin.com/)  It gives you a bash shell in 
> Windows.

Actually it gives you a whole Unix environment including X Windows
and over 500 unix command line tools plus GNU C, sendmail, etc etc...

Alan G.


From alan.gauld at freenet.co.uk  Thu Sep 15 19:22:43 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Thu, 15 Sep 2005 18:22:43 +0100
Subject: [Tutor] Multiple Simultaneous Loops
References: <34bb7f5b0509150156875464c@mail.gmail.com>
Message-ID: <004001c5ba1a$150c70a0$0201a8c0@xp>

> for f, x in bunch_of_files, range(z):

...
> Or maybe can I access the number of times the 
> loop has run?  

I think thats what enumerate does...


>>> for x,y in enumerate([1,3,5]):
...   print x,y
...
0 1
1 3
2 5
>>>


Yep, looks like what you need.

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





From kent37 at tds.net  Thu Sep 15 19:33:41 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Sep 2005 13:33:41 -0400
Subject: [Tutor] Aschenputtel problem
In-Reply-To: <4329AB99.7070806@web.de>
References: <4329AB99.7070806@web.de>
Message-ID: <4329B075.3080703@tds.net>

Christopher Arndt wrote:
> Hi,
> 
> I wonder if there is a shorter form of the following idiom:
> 
> list1 = []
> list2 = []
> for item in original_list:
>     if condition(item):
>         list1.append(item)
>     else:
>         list2.append(item)

I don't think so. You can write it as two list comprehensions which is shorter but it iterates the original list twice:
list1 = [item for item in original_list if condition(item)]
list2 = [item for item in original_list if not condition(item)]

Kent


From dyoo at hkn.eecs.berkeley.edu  Thu Sep 15 19:59:16 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 15 Sep 2005 10:59:16 -0700 (PDT)
Subject: [Tutor] GETTING AN _.EXE VERSION OF _.PY program to run on a
 machine that does not have Python installed on it. (fwd)
Message-ID: <Pine.LNX.4.44.0509151059140.16429-100000@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Wed, 14 Sep 2005 21:33:08 -0500
From: JackA <jacka at mts.net>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] GETTING AN _.EXE VERSION OF _.PY program to run on a
    machine that does not have Python installed on it.

Sorry for the boo boo but am learning and will remember.  No .DOC's.

With change of "Windows"  to "Console"  It is working as required.  Now that
the need to get it working is out of the way, I will have to take a better
look at Python.  From what I have seen in the on line information in the
course of doing this, I conclude seems to be an efficient lauguage.  I'l
have to see if I can find a couple of good books on it.

Thanks again and Jason is also very appreciative of all the help recieved.
Jack

----- Original Message -----
From: "Danny Yoo" <dyoo at hkn.eecs.berkeley.edu>
To: "JackA" <jacka at mts.net>
Cc: <tutor at python.org>
Sent: Tuesday, September 13, 2005 12:47 PM
Subject: Re: [Tutor] GETTING AN _.EXE VERSION OF _.PY program to run on a
machine that does not have Python installed on it.


>
>
> On Mon, 12 Sep 2005, JackA wrote:
>
>> I am attaching a word document copy of this EMail which might be easier
>> to read and follow if your EMail window rearanges things to much.
>
> Hi Jack,
>
> Actually, please don't do that.  *grin*
>
> Word documents are actually not really usable in a programming language
> forum.  You're assuming that the recipients are using systems that are
> capable of running Microsoft Word.  You might be surprised, but this is
> not necessarily true.  For maximum utility, please stick to plain text
> formats on Python-Tutor.  The page:
>
>    http://expita.com/nomime.html
>
> gives some more reasons for staying with plain text, at least on technical
> mailing lists.
>
>
> Anyway, to your question:
>
>> I have created PROG.EXE from PROG.PY , but it appears NOT to be portable
>> in that when I try to run PROG.EXE on my wife's machine which does not
>> have Python installed on it I get a " See the logfile PROG.EXE log for
>> details".  The logfile has the following ;
>>
>>
>> Traceback (most recent call last):
>>   File "PROG.PY", line 364, in ?
>>   File "PROG.PY", line 320, in Main
>> EOFError: EOF when reading a line
>
>
> Ok, I have an idea of what's going on here.  Let's take a look at your
> 'setup.py' file.
>
>
>
>> The 6 lines of PyToExe.PY used to make PROG.EXE , is shown below
>> starting with ### in line #1.
>>
>> ###  PyToExe.PY = file name.    _.PY > _.EXE
>>
>> from distutils.core import setup
>> import py2exe
>>
>> setup(windows=['PROG.PY'])
>        ^^^^^^^
>
> Ah.  Change the line in your setup from using 'windows' to 'console'.
>
>
> You're not making a graphical "Windows" program, but one that depends on
> the console.  Technially, a Microsoft Windows GUI program has no console,
> and no access to standard input or output.  That's why your program
> breaks: it's unable to use raw_input(), since that's explicitely meant to
> talk to standard input.
>
>
> So, instead, your setup.py should look like:
>
> ######
> from distutils.core import setup
> import py2exe
>
> setup(console=['PROG.PY'])
> ######
>
>
> Best of wishes to you.


From chris.arndt at web.de  Thu Sep 15 21:19:51 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Thu, 15 Sep 2005 20:19:51 +0100
Subject: [Tutor] GETTING AN _.EXE VERSION OF _.PY program to run on a
 machine that does not have Python installed on it. (fwd)
In-Reply-To: <Pine.LNX.4.44.0509151059140.16429-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509151059140.16429-100000@hkn.eecs.berkeley.edu>
Message-ID: <4329C957.8080304@web.de>

Danny Yoo schrieb:
> 
> ---------- Forwarded message ----------
> Date: Wed, 14 Sep 2005 21:33:08 -0500
> From: JackA <jacka at mts.net>
> To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] GETTING AN _.EXE VERSION OF _.PY program to run on a
>     machine that does not have Python installed on it.
> 
> Sorry for the boo boo but am learning and will remember.  No .DOC's.

Another gentle advice: Don't use ALL CAPS WRITING in the subject of your
emails. That's the equivalent to shouting in the online world and people will
just think you're a jerk (which is probably not true but people will think it
nevertheless).

Chris

From alan.gauld at btinternet.com  Thu Sep 15 23:13:02 2005
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 15 Sep 2005 22:13:02 +0100
Subject: [Tutor] Aschenputtel problem
References: <4329AB99.7070806@web.de>
Message-ID: <dgco3v$tia$1@sea.gmane.org>

> I wonder if there is a shorter form of the following idiom:

Bearing in mind that shorter is not necessarily better...

[condition(i) and list1.append(i) or list2.append(i) for i in 
original]

This returns a list of booleans that we throw away but the
list1,list2 containers will have been modified as required.

But the original code(below) is probably more reliable and 
clearer!

> list1 = []
> list2 = []
> for item in original_list:
>    if condition(item):
>        list1.append(item)
>    else:
>        list2.append(item)

> I call this the "Aschenputtel" problem, because it is described
> by the famous quote from the fairy tale as told by the
> Grimm brothers:
>
> "Die guten ins Töpfchen, die schlechten ins Kröpfchen."
> (The good ones in the pot, the bad ones in the crop)

HTH,

Alan G. 




From amonroe at columbus.rr.com  Thu Sep 15 23:23:32 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu, 15 Sep 2005 17:23:32 -0400
Subject: [Tutor] running scripts with windows
In-Reply-To: <002c01c5ba19$752f73c0$0201a8c0@xp>
References: <d1bf1fa2050914145859c9c18c@mail.gmail.com>
	<5e58f2e405091415286d486815@mail.gmail.com>
	<002c01c5ba19$752f73c0$0201a8c0@xp>
Message-ID: <88421082644.20050915172332@columbus.rr.com>

>> Cygwin (http://www.cygwin.com/)  It gives you a bash shell in 
>> Windows.

> Actually it gives you a whole Unix environment including X Windows
> and over 500 unix command line tools plus GNU C, sendmail, etc etc...

Watch out, because cygwin-native python can conflict with win32
python, if they're both in your path. Buddy of mine had various .py
files not work because of this.

Alan


From kent37 at tds.net  Thu Sep 15 23:29:36 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Sep 2005 17:29:36 -0400
Subject: [Tutor] Aschenputtel problem
In-Reply-To: <dgco3v$tia$1@sea.gmane.org>
References: <4329AB99.7070806@web.de> <dgco3v$tia$1@sea.gmane.org>
Message-ID: <4329E7C0.2010901@tds.net>

Alan Gauld wrote:
>>I wonder if there is a shorter form of the following idiom:
> 
> 
> Bearing in mind that shorter is not necessarily better...
> 
> [condition(i) and list1.append(i) or list2.append(i) for i in 
> original]

Hmm, no, this will always evaluate list2.append(i) because the value of list1.append(i) is None. You could use

[ (condition(i) and list1 or list2).append(i) for i in original ]

or

for i in original:
  (condition(i) and list1 or list2).append(i)

Kent


From George.Flaherty at marketmax.com  Thu Sep 15 23:33:20 2005
From: George.Flaherty at marketmax.com (George Flaherty)
Date: Thu, 15 Sep 2005 17:33:20 -0400
Subject: [Tutor] running scripts with windows...slightly OT
Message-ID: <59CF9F456FAA9045B405C441EC916F3E02D2F1DB@MERC24.na.sas.com>

Yeah be careful with some of the cygwin tools. I had an issue with the jar command being picked up from cygwin/bin instead of JAVA_HOME and it was corrupting the contents of a jar file.

-george

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of R. Alan Monroe
Sent: Thursday, September 15, 2005 5:24 PM
To: tutor at python.org
Subject: Re: [Tutor] running scripts with windows

>> Cygwin (http://www.cygwin.com/)  It gives you a bash shell in 
>> Windows.

> Actually it gives you a whole Unix environment including X Windows and 
> over 500 unix command line tools plus GNU C, sendmail, etc etc...

Watch out, because cygwin-native python can conflict with win32 python, if they're both in your path. Buddy of mine had various .py files not work because of this.

Alan

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

From rschroev_nospam_ml at fastmail.fm  Thu Sep 15 23:33:15 2005
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Thu, 15 Sep 2005 23:33:15 +0200
Subject: [Tutor] Aschenputtel problem
In-Reply-To: <dgco3v$tia$1@sea.gmane.org>
References: <4329AB99.7070806@web.de> <dgco3v$tia$1@sea.gmane.org>
Message-ID: <dgcpar$1k3$1@sea.gmane.org>

Alan Gauld schreef:
>>I wonder if there is a shorter form of the following idiom:
> 
> 
> Bearing in mind that shorter is not necessarily better...
> 
> [condition(i) and list1.append(i) or list2.append(i) for i in 
> original]

Alas, won't work. This is one of the cases where the ... and ... or ...
idiom doesn't work; this is why I don't like it and don't use it. The
problem is that list1.append(i) returns None, so list2.append(i) is
always called, even if list1.append(i) was already called:

>>> list1 = []
>>> list2 = []
>>> False and list1.append(2) or list2.append(2)
>>> list1, list2
([], [2])
>>> True and list1.append(4) or list2.append(4)
>>> list1, list2
([4], [2, 4])


-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven


From srini_iyyer_bio at yahoo.com  Thu Sep 15 23:39:41 2005
From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer)
Date: Thu, 15 Sep 2005 14:39:41 -0700 (PDT)
Subject: [Tutor] Please help with comparision in range of numbers
Message-ID: <20050915213941.79491.qmail@web31602.mail.mud.yahoo.com>

Hello group,

I have a data like this in tab-delim text.

1427021_s_at	chr7:102786983-102794499	(+)
1452285_a_at	chr7:102786983-102794499	(+)
1445553_at	chr7:102848766-102910961	(-)
1420925_at	chr7:102863841-102887410	(+)
1450041_a_at	chr7:102863841-102887410	(+)
1447553_x_at	chr7:102899711-102899995	(-)
1418478_at	chr7:102991513-103023463	(-)
1452892_at	chr7:103132162-103291925	(-)
1430157_at	chr7:103292083-103297768	(+)



First column represents the identifier. 
Second column representes the position of the
identifier on genome. Because many people might not
understand genome, lets consider it as a sequence
composed of A, T , G and C with lengths of thousands
of thousands of ATGCs. 

The analogy is something like:

Jill am driving from washington DC to Miami on I-95
South. 
Jack is driving from Miami to DC on I-95 North.

If we scale the I-95 South as (-) (negative direction)
from 0-1000000000 units (arbitary) and similarly, I-95
North as (+) (positive direction) again from 0-500,000
arbitarary units. 

My aims is to find if Jack and Jill happen to be in
Florence, south carolina then coordinates (considering
that they are apart 1 or 2 miles or units distance)
then they would be something like :
Jack    chr7:102863841-102887410	(+)
Jill	chr7:102886711-102899995	(-)


Then they are falling in the same range of coordinates
(1028,63841-1028,87410)(1028,86711-1028,99995)
(between 86711 and 87410).

I want to find such instances of jack and jill's that
fall in the same ranges and they should be in opposite
to each other. 

Truely, I always flunk and my mind gets blackedout
when I see these number ranges.  I do not know how to
write : check "if a range of numbers fall in the other
range of numbers" condition. 

tutors could any one help me please. 

thank u

srini



		
__________________________________ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com

From john at fouhy.net  Thu Sep 15 23:41:37 2005
From: john at fouhy.net (John Fouhy)
Date: Fri, 16 Sep 2005 09:41:37 +1200
Subject: [Tutor] Aschenputtel problem
In-Reply-To: <4329E7C0.2010901@tds.net>
References: <4329AB99.7070806@web.de> <dgco3v$tia$1@sea.gmane.org>
	<4329E7C0.2010901@tds.net>
Message-ID: <5e58f2e405091514412071a623@mail.gmail.com>

On 16/09/05, Kent Johnson <kent37 at tds.net> wrote:
> Alan Gauld wrote:
> > Bearing in mind that shorter is not necessarily better...
> >
> > [condition(i) and list1.append(i) or list2.append(i) for i in
> > original]
> 
> Hmm, no, this will always evaluate list2.append(i) because the value of list1.append(i) is None. You could use
> 
> [ (condition(i) and list1 or list2).append(i) for i in original ]

This will not work either, because initially, list1 will be [] which
is false.  So everything will end up in list2.

>>> list1, list2 = [], []
>>> [(i%2==1 and list1 or list2).append(i) for i in range(10)]
[None, None, None, None, None, None, None, None, None, None]
>>> list1, list2
([], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

You can get around this with a dodge..

>>> list1, list2 = [], []
>>> [(i%2 == 1 and [list1] or [list2])[0].append(i) for i in range(10)]
[None, None, None, None, None, None, None, None, None, None]
>>> list1, list2
([1, 3, 5, 7, 9], [0, 2, 4, 6, 8])

But I'm sure that using side-effects in a list comprehension is
prohibited by at least one major religion, so really, I would just
stick to a for loop :-)

-- 
John.

From wildcard2005 at comcast.net  Thu Sep 15 23:47:55 2005
From: wildcard2005 at comcast.net (Terry Kemmerer)
Date: Thu, 15 Sep 2005 14:47:55 -0700
Subject: [Tutor] Aschenputtel problem - Shorter is not better?
Message-ID: <1126820876.12333.99.camel@c-24-16-68-31.hsd1.wa.comcast.net>




"Bearing in mind that shorter is not necessarily better..."

Wouldn't shorter, as a rule of thumb, as in less language statements, mean fewer 
executions, and therefore faster?


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050915/17f3b106/attachment.htm

From alan.gauld at freenet.co.uk  Fri Sep 16 00:30:39 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Thu, 15 Sep 2005 23:30:39 +0100
Subject: [Tutor] Aschenputtel problem
References: <4329AB99.7070806@web.de> <dgco3v$tia$1@sea.gmane.org>
	<4329E7C0.2010901@tds.net>
Message-ID: <00c301c5ba45$1a1d3a40$0201a8c0@xp>

>> [condition(i) and list1.append(i) or list2.append(i) for i in 
>> original]
> 
> Hmm, no, this will always evaluate list2.append(i) because 
> the value of list1.append(i) is None. You could use
> 
> [ (condition(i) and list1 or list2).append(i) for i in original ]

Oops! Good point, which emphasises the point about shorter not 
necessarily being better!

My personal approach would be two separate comprehensions(*) which 
keeps the intent very clear and keeps it short at the expense 
of iterating the original list twice.

(*) Or you could use the filter funtion twice if you want to 
    make the intent even more explicit...

Alan G.

From dyoo at hkn.eecs.berkeley.edu  Fri Sep 16 00:38:43 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 15 Sep 2005 15:38:43 -0700 (PDT)
Subject: [Tutor] Please help with comparision in range of numbers
In-Reply-To: <20050915213941.79491.qmail@web31602.mail.mud.yahoo.com>
Message-ID: <Pine.LNX.4.44.0509151518450.22700-100000@hkn.eecs.berkeley.edu>



> 1427021_s_at	chr7:102786983-102794499	(+)
> 1452285_a_at	chr7:102786983-102794499	(+)
> 1445553_at	chr7:102848766-102910961	(-)
> 1420925_at	chr7:102863841-102887410	(+)
> 1450041_a_at	chr7:102863841-102887410	(+)
> 1447553_x_at	chr7:102899711-102899995	(-)
> 1418478_at	chr7:102991513-103023463	(-)
> 1452892_at	chr7:103132162-103291925	(-)
> 1430157_at	chr7:103292083-103297768	(+)

[some text cut]

> I want to find such instances of jack and jill's that fall in the same
> ranges and they should be in opposite to each other.


Hi Srinivas,


Let's break this down into two separate problems:

    1.  Finding Ranges that overlap.
    2.  Given two Ranges, see if they're in opposite directions.

I'm going to ignore problem 2 at the moment.  *grin*


If we don't care too much about efficiency, the following should help you
solve problem 1.

######
class Range(object):
    def __init__(self, low, high):
        assert low <= high
        self.low, self.high = low, high

    def is_overlapping(self, other):
        """Returns true if this range overlaps the other range.
        The exact boolean condition is copied from the
        classic textbook "Introduction to Algorithms, 2nd edition",
        section 14.3.
        """
        return (self.low <= other.high) and other.low <= self.high
######


For example:

######
>>> Range(1, 2).is_overlapping(Range(2, 3))
True
>>> Range(1, 2).is_overlapping(Range(3, 3))
False
>>> Range(1, 2).is_overlapping(Range(-2, 0))
False
>>> Range(1, 2).is_overlapping(Range(-42, 42))
True
######

So if you have sequence of Ranges like this, you can brute force and just
loop across all possible pairs, and do this is_overlapping() check.  You
may want to test this on a small sample dataset just to see that it works.

This approach, however, is slow, and gets slower as the dataset grows.
If we do care about efficiency, we have to do something a little smarter.

Interval trees or K-d Tree data structures are examples of data structures
that can help you do range-intersection queries much more quickly than a
brute-force approach.  There's an implementation of K-d trees in
biopython:

    http://biopython.org/docs/api/public/Bio.KDTree-module.html

so you may want to investigate this with the Biopython folks if speed is a
concern.  John Bentley wrote a nice survey article talking about these
range-searching algorithms here:

    http://portal.acm.org/citation.cfm?id=356797

although you might need an ACM account to get at the article.



> Truely, I always flunk and my mind gets blackedout when I see these
> number ranges.  I do not know how to write : check "if a range of
> numbers fall in the other range of numbers" condition.

Yeah, me too.  Check out the book reference in the code above: it helps to
clear things up about intervals and range checking.


From chris.arndt at web.de  Fri Sep 16 03:48:08 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Fri, 16 Sep 2005 02:48:08 +0100
Subject: [Tutor] Aschenputtel problem
In-Reply-To: <00c301c5ba45$1a1d3a40$0201a8c0@xp>
References: <4329AB99.7070806@web.de>
	<dgco3v$tia$1@sea.gmane.org>	<4329E7C0.2010901@tds.net>
	<00c301c5ba45$1a1d3a40$0201a8c0@xp>
Message-ID: <432A2458.1000805@web.de>

Alan G schrieb:
> My personal approach would be two separate comprehensions(*) which 
> keeps the intent very clear and keeps it short at the expense 
> of iterating the original list twice.

Of course this works only if condition(item) yields the same result each time
it is called with the same input (which should be the common case).

Also, iterating twice over the list could be expensive if the condition(item)
call takes comparatively long.

Chris

From tegmine at gmail.com  Fri Sep 16 06:23:42 2005
From: tegmine at gmail.com (Luis N)
Date: Thu, 15 Sep 2005 21:23:42 -0700
Subject: [Tutor] Boa-Constructor
In-Reply-To: <1126635134.9084.3.camel@c-24-16-68-31.hsd1.wa.comcast.net>
References: <1126559587.8796.12.camel@c-24-16-68-31.hsd1.wa.comcast.net>
	<77bfa81a0509130318192b7bd3@mail.gmail.com>
	<1126635134.9084.3.camel@c-24-16-68-31.hsd1.wa.comcast.net>
Message-ID: <77bfa81a05091521233a8f5167@mail.gmail.com>

 >  Luis,
>  
>  I was actually asking how usable Boa-Constructor is right now for project
> purposes, since I had "heard" it was kind of unstable and crashes a lot. Is
> that your experience with Boa-Constructor? Or was the information I found
> misleading?
>  
>  Thanks,
>  Terry 

I found Boa-constructor interesting/useful. Since this was sometime
ago, and wxPython has since gained a few version numbers, I can't
comment on its current stability. It was fine when I tried it, little
bloated though.

I'm a committed emacs user now.

Luis

From bgailer at gmail.com  Fri Sep 16 03:39:57 2005
From: bgailer at gmail.com (Bob Gailer)
Date: Thu, 15 Sep 2005 18:39:57 -0700
Subject: [Tutor] Aschenputtel problem
Message-ID: <23d7abd05091518397481bdb3@mail.gmail.com>

At 10:12 AM 9/15/2005, Christopher Arndt wrote:

Hi,

I wonder if there is a shorter form of the following idiom:

list1 = []
list2 = []
for item in original_list:
if condition(item):
list1.append(item)
else:
list2.append(item)


Consider (5 lines instead of 7):

lists = [[], []]
for item in original_list: 
lists[condition(item)].append(item)
list1 = lists[0]
list2 = lists[1]

This assumes condition() returns 0 or 1 (True)

or if you don't mind the result in sets (assumes unique elements):

set1 = set([x for x in original_list if cond(x)])
set2 = original_list - set1 

I can't send mail my usual way due to unknown problems. So am using gmail. 
Please relpy as always to bgailer at alum.rpi.edu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050915/cbc90026/attachment.html

From alan.gauld at freenet.co.uk  Fri Sep 16 09:32:28 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Fri, 16 Sep 2005 08:32:28 +0100
Subject: [Tutor] Aschenputtel problem - Shorter is not better?
References: <1126820876.12333.99.camel@c-24-16-68-31.hsd1.wa.comcast.net>
Message-ID: <00e501c5ba90$cb4bda10$0201a8c0@xp>

> "Bearing in mind that shorter is not necessarily better..."
>
> Wouldn't shorter, as a rule of thumb, as in less language 
> statements, mean fewer
> executions, and therefore faster?

Only in a very general sense. In practice a complex expression
(such as a list comprehension or a regular expression search)
can expand into a lot of assembler level steps and be bigger
than a multi line but simpler expression.

But even if it were faster, faster is not always better.

If you lose the ability to maintain the code easily or if the complex
single line introduces subtle bugs (like my untested one-liner did!)
then better to be slowly correct than rapidly wrong... :-)

Alan G. 


From pierre.barbier at cirad.fr  Fri Sep 16 11:30:07 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Fri, 16 Sep 2005 11:30:07 +0200
Subject: [Tutor] Aschenputtel problem
In-Reply-To: <4329AB99.7070806@web.de>
References: <4329AB99.7070806@web.de>
Message-ID: <432A909F.2040307@cirad.fr>

Well, in the specific case of numeric arrays, you can use Numeric or
numarray :

from Numeric import array, compress

ol = array(original_list)
selection = array([condition(i) for i in original_list)
list1 = compress(selection, ol)
list2 = compress(!selection, ol)

Even better, if condition can be expressed directly on the matrix itself
(which is pretty common with Numeric/numarray):

ol = array(original_list)
selection = condition(ol)
list1 = compress(selection, ol)
list2 = compress(!selection, ol)

Remember: if you have complex index operations on arrays of numbers,
Numeric (and even more numarray) contains a lot of very usefull
efficient functions.

Pierre

Christopher Arndt a ?crit :
> Hi,
> 
> I wonder if there is a shorter form of the following idiom:
> 
> list1 = []
> list2 = []
> for item in original_list:
>     if condition(item):
>         list1.append(item)
>     else:
>         list2.append(item)
> 
> (optional step:)
> 
> original_list[:] = list1
> 
> 
> I call this the "Aschenputtel" problem, because it is described by the famous
> quote from the fairy tale as told by the Grimm brothers:
> 
> "Die guten ins T?pfchen, die schlechten ins Kr?pfchen."
> 
> (The good ones in the pot, the bad ones in the crop)
> 
> Chris
> 
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68

From kent37 at tds.net  Fri Sep 16 13:58:41 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Sep 2005 07:58:41 -0400
Subject: [Tutor] Please help with comparision in range of numbers
In-Reply-To: <20050915213941.79491.qmail@web31602.mail.mud.yahoo.com>
References: <20050915213941.79491.qmail@web31602.mail.mud.yahoo.com>
Message-ID: <432AB371.20704@tds.net>

Srinivas Iyyer wrote:
> I want to find such instances of jack and jill's that
> fall in the same ranges and they should be in opposite
> to each other. 
> 
> Truely, I always flunk and my mind gets blackedout
> when I see these number ranges.  I do not know how to
> write : check "if a range of numbers fall in the other
> range of numbers" condition. 

You might be interested in the interval module available here:
http://members.cox.net/apoco/interval/

It implements Interval and IntervalSet. It seems to use a brute-force algorithm but at least it gives you a tested and packaged starting point.

Kent


From chris.arndt at web.de  Fri Sep 16 17:11:17 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Fri, 16 Sep 2005 16:11:17 +0100
Subject: [Tutor] Aschenputtel problem
In-Reply-To: <432A909F.2040307@cirad.fr>
References: <4329AB99.7070806@web.de> <432A909F.2040307@cirad.fr>
Message-ID: <432AE095.2030107@web.de>

Pierre Barbier de Reuille schrieb:
> Well, in the specific case of numeric arrays, you can use Numeric or
> numarray :
> 
> from Numeric import array, compress
> 
> ol = array(original_list)
> selection = array([condition(i) for i in original_list)
> list1 = compress(selection, ol)
> list2 = compress(!selection, ol)

This ! syntax isn't working for me (throws a syntax error). Is this defined by
Numeric somewhere?

This works (but see my upcoming post about benchmarking the different solutions):

selection = [condition(i) for i in original_list]
list1 = compress(selection, original_list)
list2 = compress([not x for x in selection], original_list)

Chris

From chris.arndt at web.de  Fri Sep 16 17:29:39 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Fri, 16 Sep 2005 16:29:39 +0100
Subject: [Tutor] Aschenputtel problem - Shorter is not better?
In-Reply-To: <1126820876.12333.99.camel@c-24-16-68-31.hsd1.wa.comcast.net>
References: <1126820876.12333.99.camel@c-24-16-68-31.hsd1.wa.comcast.net>
Message-ID: <432AE4E3.7060804@web.de>

Terry Kemmerer schrieb:
> 
> 
> "Bearing in mind that shorter is not necessarily better..."
> 
> Wouldn't shorter, as a rule of thumb, as in less language statements, mean fewer 
> executions, and therefore faster?

Well, see for yourself...

I wrote a little benchmarking script for different solutions to my problem. It
turns out, that the original "traditional for-loop" approach is not only the
most readable but also one of the fastest.

Here are my timings (Python 2.4, Athlon64 1.8 Ghz, Ubuntu Hoary) (see the
attached script for the functions names):

List length: 100, Function calls: 3 x 1000

cinderella1: (1) 0.188769, (2) 0.189790, (3) 0.188901
cinderella2: (1) 0.263702, (2) 0.254624, (3) 0.254050
cinderella3: (1) 0.430694, (2) 0.270807, (3) 0.265921
cinderella4: (1) 0.154761, (2) 0.142940, (3) 0.139610
cinderella5: (1) 0.145273, (2) 0.139491, (3) 0.133930
cinderella6: (1) 0.144191, (2) 0.139056, (3) 0.141840
cinderella7: (1) 0.737320, (2) 0.726961, (3) 0.732526

List length: 1000, Function calls: 3 x 1000

cinderella1: (1) 1.639245, (2) 0.975745, (3) 0.971775
cinderella2: (1) 1.337324, (2) 1.330888, (3) 1.319431
cinderella3: (1) 18.772992, (2) 18.764382, (3) 18.759283
cinderella4: (1) 1.140375, (2) 1.120827, (3) 1.119281
cinderella5: (1) 1.460923, (2) 1.444996, (3) 1.444842
cinderella6: (1) 1.481483, (2) 1.469315, (3) 1.478990
cinderella7: (1) 7.211108, (2) 7.208998, (3) 7.202029

"cinderella1" ist the traditional approach, "cinderella3" builds up a list of
positives and then checks that against the original list by using the "in"
operator. This scales very badly for longer lists, as you can see in the second
timing.

"cinderella7" ist the Numeric approach proposed by Pierre Barbier de Reuille.
It doesn't compare very well, probably because it has to iterate 3 times over
the original list and once more over the list of positives.

The solution using sets ("cinderella4") seems to do very well too, but has
several limitations:

- does not preserver order of elements
- elements must be unique
- only available from Python 2.3

I leave it as an axcercise to the reader to try how the different soltutions
behave when condition(item) is more expansive (i.e takes longer).

Chris
-------------- next part --------------
A non-text attachment was scrubbed...
Name: cinderella.py
Type: text/x-python
Size: 2677 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050916/55f26118/cinderella.py

From falcon3166 at hotmail.com  Fri Sep 16 18:48:26 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 16 Sep 2005 10:48:26 -0600
Subject: [Tutor] Do I have to include certain items in the setup.py file?
Message-ID: <BAY106-DAV212F6104BDBC905632E216C4910@phx.gbl>

Hey all,

I was curious about what I have to include in the setup.py file. Do I have to include such statements as "import random" if the code uses import random and the random functions in its code for example?

Hopefully this is not a beginner's question,
Nathan Pinno
For great sites go to: http://falcon3166.tripod.com
For great products go to: http://zoffee.tripod.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050916/acce7036/attachment.html

From pierre.barbier at cirad.fr  Fri Sep 16 19:17:22 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Fri, 16 Sep 2005 19:17:22 +0200
Subject: [Tutor] Aschenputtel problem - Shorter is not better?
In-Reply-To: <432AE4E3.7060804@web.de>
References: <1126820876.12333.99.camel@c-24-16-68-31.hsd1.wa.comcast.net>
	<432AE4E3.7060804@web.de>
Message-ID: <432AFE22.6090300@cirad.fr>

Well, I have some comments ^_^

First, about the function 6, it is exactly equivalent (and a little bit
quicker) to use:

===8<======8<======8<======8<======8<======8<======8<======8<======8<===
def cinderella6(original_list, condition):
    """Using while and list popping."""

    list1 = []
    i = 0
    try:
      while True:
        if not condition(original_list[i]):
          list1.append(original_list.pop(i))
        else:
          i += 1
    except IndexError:
      pass
    return original_list, list1
===8<======8<======8<======8<======8<======8<======8<======8<======8<===

That is, put the try block outside the loop ... however, if this method
is the quickest it is the only destructive one !

Then, you shouldn't time the creation of the list together with
algorithm. Thus the main loop should be:

===8<======8<======8<======8<======8<======8<======8<======8<======8<===
def test(list_length=100, num_func_calls=1000):
    """Profile different implementations of cinderella idiom."""

    global olist, rlist
    olist = range( list_length )
    rlist = array( olist )
    l = []
    for i in range(1,10):
        func = "cinderella%i" % i
        if i == 8:
          stmt = """%s(rlist, check)""" % (func,)
        else:
          stmt = """%s(olist, check)""" % (func,)
        timer = timeit.Timer(stmt,"from __main__ import %s, check,
array, compress, olist, rlist" % func)
        l.append(timer.repeat(3, int(num_func_calls)))
        print "%s: (1) %f, (2) %f, (3) %f" % (func, l[-1][0], l[-1][1],
l[-1][2])
===8<======8<======8<======8<======8<======8<======8<======8<======8<===

Well, I added the creation of a Numeric array ... as the function 8 is
supposed to work with it. So here are the corrected versions of the
functions 7 et 8 :

===8<======8<======8<======8<======8<======8<======8<======8<======8<===
def cinderella7(original_list, condition):
    """Using Numeric and array compression."""

    selection = array( [condition(i) for i in original_list] )
    list1 = compress(selection, original_list)
    list2 = compress(~selection, original_list)
    return list1, list2

def cinderella8(original_list, condition):
    """Using Numeric and array compression."""

    selection = condition( original_list )
    list1 = compress(selection, original_list)
    list2 = compress(~selection, original_list)
    return list1, list2
===8<======8<======8<======8<======8<======8<======8<======8<======8<===

In the end, Numeric rocks :) Solution 8 is even faster than solution 6 !

List length: 100, Function calls: 3 x 1000

cinderella1: (1) 0.228345, (2) 0.356115, (3) 0.229700
cinderella2: (1) 0.306550, (2) 0.308528, (3) 0.312639
cinderella3: (1) 0.469183, (2) 0.471858, (3) 0.474165
cinderella4: (1) 0.311316, (2) 0.327631, (3) 0.449626
cinderella5: (1) 0.309293, (2) 0.305037, (3) 0.293698
cinderella6: (1) 0.096513, (2) 0.095803, (3) 0.096810
cinderella7: (1) 0.661629, (2) 0.786803, (3) 0.673522
cinderella8: (1) 0.197300, (2) 0.198183, (3) 0.198790

List length: 1000, Function calls: 3 x 1000

cinderella1: (1) 2.248727, (2) 2.267243, (3) 2.301675
cinderella2: (1) 3.023581, (2) 3.046691, (3) 3.076899
cinderella3: (1) 29.806438, (2) 28.742620, (3) 31.848374
cinderella4: (1) 3.037407, (2) 3.162915, (3) 3.227520
cinderella5: (1) 4.260166, (2) 4.831273, (3) 3.991498
cinderella6: (1) 0.989976, (2) 1.346485, (3) 0.938494
cinderella7: (1) 5.095143, (2) 6.546663, (3) 6.203648
cinderella8: (1) 0.686484, (2) 0.686852, (3) 0.688778

List length: 10000, Function calls: 3 x 1000

cinderella6: (1) 8.399953, (2) 8.712989, (3) 8.998076
cinderella8: (1) 6.499856, (2) 6.388803, (3) 6.108556

Pierre

Christopher Arndt a ?crit :
> Terry Kemmerer schrieb:
> 
>>
>>"Bearing in mind that shorter is not necessarily better..."
>>
>>Wouldn't shorter, as a rule of thumb, as in less language statements, mean fewer 
>>executions, and therefore faster?
> 
> 
> Well, see for yourself...
> 
> I wrote a little benchmarking script for different solutions to my problem. It
> turns out, that the original "traditional for-loop" approach is not only the
> most readable but also one of the fastest.
> 
> Here are my timings (Python 2.4, Athlon64 1.8 Ghz, Ubuntu Hoary) (see the
> attached script for the functions names):
> 
> List length: 100, Function calls: 3 x 1000
> 
> cinderella1: (1) 0.188769, (2) 0.189790, (3) 0.188901
> cinderella2: (1) 0.263702, (2) 0.254624, (3) 0.254050
> cinderella3: (1) 0.430694, (2) 0.270807, (3) 0.265921
> cinderella4: (1) 0.154761, (2) 0.142940, (3) 0.139610
> cinderella5: (1) 0.145273, (2) 0.139491, (3) 0.133930
> cinderella6: (1) 0.144191, (2) 0.139056, (3) 0.141840
> cinderella7: (1) 0.737320, (2) 0.726961, (3) 0.732526
> 
> List length: 1000, Function calls: 3 x 1000
> 
> cinderella1: (1) 1.639245, (2) 0.975745, (3) 0.971775
> cinderella2: (1) 1.337324, (2) 1.330888, (3) 1.319431
> cinderella3: (1) 18.772992, (2) 18.764382, (3) 18.759283
> cinderella4: (1) 1.140375, (2) 1.120827, (3) 1.119281
> cinderella5: (1) 1.460923, (2) 1.444996, (3) 1.444842
> cinderella6: (1) 1.481483, (2) 1.469315, (3) 1.478990
> cinderella7: (1) 7.211108, (2) 7.208998, (3) 7.202029
> 
> "cinderella1" ist the traditional approach, "cinderella3" builds up a list of
> positives and then checks that against the original list by using the "in"
> operator. This scales very badly for longer lists, as you can see in the second
> timing.
> 
> "cinderella7" ist the Numeric approach proposed by Pierre Barbier de Reuille.
> It doesn't compare very well, probably because it has to iterate 3 times over
> the original list and once more over the list of positives.
> 
> The solution using sets ("cinderella4") seems to do very well too, but has
> several limitations:
> 
> - does not preserver order of elements
> - elements must be unique
> - only available from Python 2.3
> 
> I leave it as an axcercise to the reader to try how the different soltutions
> behave when condition(item) is more expansive (i.e takes longer).
> 
> Chris
> 
> 
-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68

From chris.arndt at web.de  Fri Sep 16 20:29:41 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Fri, 16 Sep 2005 19:29:41 +0100
Subject: [Tutor] Aschenputtel problem - Shorter is not better?
In-Reply-To: <432AFE22.6090300@cirad.fr>
References: <1126820876.12333.99.camel@c-24-16-68-31.hsd1.wa.comcast.net>	<432AE4E3.7060804@web.de>
	<432AFE22.6090300@cirad.fr>
Message-ID: <432B0F15.4000708@web.de>

Pierre Barbier de Reuille schrieb:
> Well, I have some comments ^_^

As should be always expected, when it comes to benchmarking ;-)

> First, about the function 6, it is exactly equivalent (and a little bit
> quicker) to use:
> [...]
> That is, put the try block outside the loop ... however, if this method
> is the quickest it is the only destructive one !

That's ok for my use case. Anyway, you can always copy the original list
beforehand:

list1 = original_list[:]

> Then, you shouldn't time the creation of the list together with
> algorithm. Thus the main loop should be:

It would affect all algorithms in the same way, but, yes, you're probably right.

> Well, I added the creation of a Numeric array ... as the function 8 is
> supposed to work with it.

Hmm, this might be considered cheating, since part of the algorithm is factored
out of the proper function, but if you're already working with Numeric arrays
it wouldn't make a difference.

> In the end, Numeric rocks :) Solution 8 is even faster than solution 6 !

So it seems. For the sake of minimal external requirements I'll stick to
solution 6, though.

You can speed up solution 4 (using sets) further (but not much) for Python 2.4
(but keeping compability with 2.3) if you do this:

try:
    set()
except NameError:
    from sets import Set as set

list1 = [x for x in original_list if condition(x)]
s = set(original_list)
list2 = list(s.difference(list1))

Chris

From 3dbernard at gmail.com  Fri Sep 16 21:21:03 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri, 16 Sep 2005 15:21:03 -0400
Subject: [Tutor] ElementTree: finding a tag with specific attribute
Message-ID: <61d0e2b405091612212f4ec2e3@mail.gmail.com>

Hello,

With ElementTree, can you search a tag under an Element by not only
specifying the tag label, but also some tag attribute values? That
would be in the case where I have several tags with the same label but
with various attribute values.

Right now I do a loop over every tag of the same label, then test the
attributes:

for oTag in oElement.findall( 'taglabel' ):
    if oTag.attrib[ 'value' ] == 'xx': do something

I'm looking for something a bit like BeautifulSoup, like:

oTag = oElement.find( 'taglabel', { 'value' : 'xx' } )


Btw in case you wonder, I don't use BeautifulSoup because somehow it
takes 20-30 seconds to parse a 2000-line xml file, and I don't know
why. ElementTree is proving very performing.


Thanks
Bernard

From bgailer at alum.rpi.edu  Thu Sep 15 20:47:42 2005
From: bgailer at alum.rpi.edu (bob)
Date: Thu, 15 Sep 2005 11:47:42 -0700
Subject: [Tutor] Aschenputtel problem
In-Reply-To: <4329AB99.7070806@web.de>
References: <4329AB99.7070806@web.de>
Message-ID: <6.1.2.0.0.20050915112459.0333ce98@mail.mric.net>

At 10:12 AM 9/15/2005, Christopher Arndt wrote:
>Hi,
>
>I wonder if there is a shorter form of the following idiom:
>
>list1 = []
>list2 = []
>for item in original_list:
>     if condition(item):
>         list1.append(item)
>     else:
>         list2.append(item)

Consider (5 lines instead of 7):

lists = [[], []]
for item in original_list:
     lists[condition(item)].append(item)
list1 = lists[0]
list2 = lists[1]

This assumes condition() returns 0 or 1 (True)

or if you don't mind the result in sets (assumes unique elements):

set1 = set([x for x in original_list if cond(x)])
set2 = original_list - set1 


From kent37 at tds.net  Fri Sep 16 21:44:42 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Sep 2005 15:44:42 -0400
Subject: [Tutor] ElementTree: finding a tag with specific attribute
In-Reply-To: <61d0e2b405091612212f4ec2e3@mail.gmail.com>
References: <61d0e2b405091612212f4ec2e3@mail.gmail.com>
Message-ID: <432B20AA.7090705@tds.net>

Bernard Lebel wrote:
> Hello,
> 
> With ElementTree, can you search a tag under an Element by not only
> specifying the tag label, but also some tag attribute values? That
> would be in the case where I have several tags with the same label but
> with various attribute values.
> 
> Right now I do a loop over every tag of the same label, then test the
> attributes:
> 
> for oTag in oElement.findall( 'taglabel' ):
>     if oTag.attrib[ 'value' ] == 'xx': do something

I think that is the best you can do. Or switch to something with full XPath support.

FLASH: I just found PDIS XPath which evaluates XPath expressions against ElementTree trees!
http://pdis.hiit.fi/pdis/download/
 
> I'm looking for something a bit like BeautifulSoup, like:
> 
> oTag = oElement.find( 'taglabel', { 'value' : 'xx' } )
> 
> 
> Btw in case you wonder, I don't use BeautifulSoup because somehow it
> takes 20-30 seconds to parse a 2000-line xml file, and I don't know
> why. ElementTree is proving very performing.

Would you send me privately a copy of your file and your code that reads it with BS? I'm curious why this takes so long.

Kent


From 3dbernard at gmail.com  Fri Sep 16 21:52:39 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri, 16 Sep 2005 15:52:39 -0400
Subject: [Tutor] ElementTree: finding a tag with specific attribute
In-Reply-To: <432B20AA.7090705@tds.net>
References: <61d0e2b405091612212f4ec2e3@mail.gmail.com>
	<432B20AA.7090705@tds.net>
Message-ID: <61d0e2b405091612523a127e3d@mail.gmail.com>

Thanks Kent, I'll check your suggestion out.

I have sent you the xml file.



Bernard



On 9/16/05, Kent Johnson <kent37 at tds.net> wrote:
> Bernard Lebel wrote:
> > Hello,
> >
> > With ElementTree, can you search a tag under an Element by not only
> > specifying the tag label, but also some tag attribute values? That
> > would be in the case where I have several tags with the same label but
> > with various attribute values.
> >
> > Right now I do a loop over every tag of the same label, then test the
> > attributes:
> >
> > for oTag in oElement.findall( 'taglabel' ):
> >     if oTag.attrib[ 'value' ] == 'xx': do something
> 
> I think that is the best you can do. Or switch to something with full XPath support.
> 
> FLASH: I just found PDIS XPath which evaluates XPath expressions against ElementTree trees!
> http://pdis.hiit.fi/pdis/download/
> 
> > I'm looking for something a bit like BeautifulSoup, like:
> >
> > oTag = oElement.find( 'taglabel', { 'value' : 'xx' } )
> >
> >
> > Btw in case you wonder, I don't use BeautifulSoup because somehow it
> > takes 20-30 seconds to parse a 2000-line xml file, and I don't know
> > why. ElementTree is proving very performing.
> 
> Would you send me privately a copy of your file and your code that reads it with BS? I'm curious why this takes so long.
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From dyoo at hkn.eecs.berkeley.edu  Fri Sep 16 22:12:07 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 16 Sep 2005 13:12:07 -0700 (PDT)
Subject: [Tutor] Do I have to include certain items in the setup.py file?
In-Reply-To: <BAY106-DAV212F6104BDBC905632E216C4910@phx.gbl>
Message-ID: <Pine.LNX.4.44.0509161308480.25552-100000@hkn.eecs.berkeley.edu>



On Fri, 16 Sep 2005, Nathan Pinno wrote:

> I was curious about what I have to include in the setup.py file. Do I
> have to include such statements as "import random" if the code uses
> import random and the random functions in its code for example?

Hi Nathan,

Each module is responsible for its own local imports.  So if setup.py
itself doesn't use random, even if it uses other modules where those other
modules use random, setup.py itself doesn't need to import random.

Does that help to clear things up?


From falcon3166 at hotmail.com  Fri Sep 16 22:15:37 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 16 Sep 2005 14:15:37 -0600
Subject: [Tutor] Do I have to include certain items in the setup.py file?
References: <Pine.LNX.4.44.0509161308480.25552-100000@hkn.eecs.berkeley.edu>
Message-ID: <BAY106-DAV2EBBECD197934F7EB8AC3C4910@phx.gbl>

It sure does. Thanks Danny. One final question: Is it possible to write one 
setup.py and use it for multiple Python programs?

Thanks,
Nathan Pinno
For great sites go to: http://falcon3166.tripod.com
For great products go to: http://zoffee.tripod.com
----- Original Message ----- 
From: "Danny Yoo" <dyoo at hkn.eecs.berkeley.edu>
To: "Nathan Pinno" <falcon3166 at hotmail.com>
Cc: "Tutor mailing list" <tutor at python.org>
Sent: Friday, September 16, 2005 2:12 PM
Subject: Re: [Tutor] Do I have to include certain items in the setup.py 
file?


>
>
> On Fri, 16 Sep 2005, Nathan Pinno wrote:
>
>> I was curious about what I have to include in the setup.py file. Do I
>> have to include such statements as "import random" if the code uses
>> import random and the random functions in its code for example?
>
> Hi Nathan,
>
> Each module is responsible for its own local imports.  So if setup.py
> itself doesn't use random, even if it uses other modules where those other
> modules use random, setup.py itself doesn't need to import random.
>
> Does that help to clear things up?
>
> 

From dashifen at dashifen.com  Fri Sep 16 23:42:15 2005
From: dashifen at dashifen.com (David Dashifen Kees)
Date: Fri, 16 Sep 2005 16:42:15 -0500
Subject: [Tutor] Multiple buttons, One callback
In-Reply-To: <Pine.LNX.4.44.0509161308480.25552-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509161308480.25552-100000@hkn.eecs.berkeley.edu>
Message-ID: <432B3C37.6050209@dashifen.com>

Greetings all:

First off, the necessary statistics:  Python 2.4 using Tkinter as a GUI 
manager.

Now, the problem:  I've got an interface that generates a number of 
buttons.  Each of these buttons performs the same basic task over 
different data based on which button is clicked.  In other languages, 
I've always been about to bind each button to one callback function 
which could then determine which button was clicked, and from that data 
grab the necessary data and perfrom the operations on that data.

So, in python this is what I did.  I made a class that inherits from the 
Tkinter.Toplevel class.  This class dynamically creates its interface 
which contains a series of rows.  On each row the following widgets 
appear in the following order: button, label, label, button button.  
Now, each of those buttons takes the information in the first label 
(maintained as a StringVar) and performs a similar operation upon it.  
I've been able to bind each button to the same callback function (that 
part's trivial) but what hasn't been trival is determining which button 
was clicked and, from this information, gathering the correct datum from 
the list of StringVars which make up the first label text.

In other languages, I've been able to set an id on the buttons that the 
callback function could access and that id would be the index within 
StringVar array to gather the data as well as a code to determine which 
button was clicked.  Thus, the buttons for one row could have the 
following ids:  0|0, 0|1, 0|2.  This would refer to take the datum 
string_vars[0] and perform operation 0, 1, or 2 upon it.  However, I 
cannot figure out how to create this behavior in python to date.

So, what do you think I need to do?  Is there an easier way?

Thanks all,
Dash Kees

From dyoo at hkn.eecs.berkeley.edu  Sat Sep 17 00:27:55 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 16 Sep 2005 15:27:55 -0700 (PDT)
Subject: [Tutor] Multiple buttons, One callback
In-Reply-To: <432B3C37.6050209@dashifen.com>
Message-ID: <Pine.LNX.4.44.0509161521330.1584-100000@hkn.eecs.berkeley.edu>



> I've been able to bind each button to the same callback function (that
> part's trivial) but what hasn't been trival is determining which button
> was clicked and, from this information, gathering the correct datum from
> the list of StringVars which make up the first label text.


Hi David,

It's possible to make dynamic callbacks.  For example:

######
>>> def some_function(x):
...     print "I see", x
...
>>> def make_callback(n):
...     def callback():
...         return some_function(n)
...     return callback
######


make_callback() is a function that returns a "thunk" callback.  That
returned thunk doesn't take an argument, so it's perfectly appropriate as
a button callback.

And yet, that callback can remember what was initially passed into
make_callback() --- it remembers the datum that we used to build the
thunk.  Here, take a look:

######
>>> callbacks = [make_callback(i) for i in range(5)]
>>> callbacks[0]
<function callback at 0x403a610c>
>>> callbacks[0]()
I see 0
>>> callbacks[1]
<function callback at 0x403a6bfc>
>>> callbacks[1]()
I see 1
######

Does this make sense?  Please free to ask questions about this.


Good luck!


From dyoo at hkn.eecs.berkeley.edu  Sat Sep 17 00:36:41 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 16 Sep 2005 15:36:41 -0700 (PDT)
Subject: [Tutor] Do I have to include certain items in the setup.py file?
In-Reply-To: <BAY106-DAV2EBBECD197934F7EB8AC3C4910@phx.gbl>
Message-ID: <Pine.LNX.4.44.0509161527580.1584-100000@hkn.eecs.berkeley.edu>



On Fri, 16 Sep 2005, Nathan Pinno wrote:

> It sure does. Thanks Danny. One final question: Is it possible to write
> one setup.py and use it for multiple Python programs?

Just to make sure, we are talking about the Distutils setup.py that's used
to build distributions of Python applications, right?

It might not be so useful to clone setup.py, since we'd probably want to
make changes for each program, just because we'd probably label our
programs with different names just to keep ourselves from getting
confused.

That is, technically, it's possible to call all our programs some generic
name like "program.py", and to keep all our programs in separate
subdirectories.  And in that way, the same 'setup.py' could work on
different applications.  But still, I don't see this being done very often
because people often like to use descriptive --- and varying --- names for
their programs.

In my own practice, I usually just write a setup.py from scratch (or copy
a template), and customize it to the particular application that I'm
packaging up.  Does this make sense?


Best of wishes!


From falcon3166 at hotmail.com  Sat Sep 17 00:37:56 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 16 Sep 2005 16:37:56 -0600
Subject: [Tutor] Do I have to include certain items in the setup.py file?
References: <Pine.LNX.4.44.0509161527580.1584-100000@hkn.eecs.berkeley.edu>
Message-ID: <BAY106-DAV157A29AAF6C7D889F31CF3C4910@phx.gbl>

It sure does! Thanks.
For great sites go to: http://falcon3166.tripod.com
For great products go to: http://zoffee.tripod.com
----- Original Message ----- 
From: "Danny Yoo" <dyoo at hkn.eecs.berkeley.edu>
To: "Nathan Pinno" <falcon3166 at hotmail.com>
Cc: "Tutor mailing list" <tutor at python.org>
Sent: Friday, September 16, 2005 4:36 PM
Subject: Re: [Tutor] Do I have to include certain items in the setup.py 
file?


>
>
> On Fri, 16 Sep 2005, Nathan Pinno wrote:
>
>> It sure does. Thanks Danny. One final question: Is it possible to write
>> one setup.py and use it for multiple Python programs?
>
> Just to make sure, we are talking about the Distutils setup.py that's used
> to build distributions of Python applications, right?
>
> It might not be so useful to clone setup.py, since we'd probably want to
> make changes for each program, just because we'd probably label our
> programs with different names just to keep ourselves from getting
> confused.
>
> That is, technically, it's possible to call all our programs some generic
> name like "program.py", and to keep all our programs in separate
> subdirectories.  And in that way, the same 'setup.py' could work on
> different applications.  But still, I don't see this being done very often
> because people often like to use descriptive --- and varying --- names for
> their programs.
>
> In my own practice, I usually just write a setup.py from scratch (or copy
> a template), and customize it to the particular application that I'm
> packaging up.  Does this make sense?
>
>
> Best of wishes!
>
> 

From keridee at jayco.net  Fri Sep 16 01:50:58 2005
From: keridee at jayco.net (Jacob S.)
Date: Thu, 15 Sep 2005 18:50:58 -0500
Subject: [Tutor] GETTING AN _.EXE VERSION OF _.PY program to run on
	amachine that does not have Python installed on it.
References: <00bd01c5b81e$b7e5d670$6601a8c0@Desk1>
Message-ID: <000001c5bb10$2df774b0$6401a8c0@JSLAPTOP>

Might I suggest that you use the built in min() and max() because they are probably faster.

Jacob
  ----- Original Message ----- 
  From: JackA 
  To: tutor at python.org 
  Sent: Monday, September 12, 2005 11:50 PM
  Subject: [Tutor] GETTING AN _.EXE VERSION OF _.PY program to run on amachine that does not have Python installed on it.


  I am attaching a word document copy of this EMail which might be easier to read and follow if your EMail window rearanges things to much.



  I would like thank Dax Reyes and John Fouhy for taking the trouble to respond to my attempt to create an     _.EXE     from a     Python program.



  The question now is; can the    PY2EXE    procedure make     PROG.EXE     ( Or a set of files. ) from      PROG.PY      that will allow      PROG.EXE      to run on a machine that does not have    Python    installed on it, and if so what has to be fixed and how?

  I have created        PROG.EXE       from      PROG.PY       , but it appears   NOT   to be portable in that when I try to run     PROG.EXE     on my wife's machine which does not have   Python   installed on it I get a " See the logfile PROG.EXE log for details".  The logfile has the following ;




  Traceback (most recent call last):

    File "PROG.PY", line 364, in ?

    File "PROG.PY", line 320, in Main

  EOFError: EOF when reading a line



  Lines 320 and 364 are shown below.  Line 364 is the last line of the program.  No line reference on the    EOFError    was given.

      filename=raw_input("Enter destination and filename as >  C:\Name.STR  <: ")                                                                                      # line 320 listed in traceback log.
  Main()                                                                        # line 360 listed in traceback log.




  The 6 lines of     PyToExe.PY     used to make     PROG.EXE      , is shown below starting with  ### in line #1.

  ###  PyToExe.PY = file name.    _.PY > _.EXE

  from distutils.core import setup
  import py2exe

  setup(windows=['PROG.PY'])

  The     DOS com line     command was :     PYTHON PyToExe.PY PY2EXE  .




  The program,     PROG.PY     has no errors and runs fine under Python24, as does PROG.EXE      on a Python equipped machine.  Actually I can delete    PROG.EXE    and double click the      PROG.PY     icon in the     Python24    folder and it runs fine. 

   

  I am running an XP machine with a 1.8 GHz CPU, 700 Meg of memory and 36 Gbyte of free space on disk.

  I am attaching       PROG.PY       in case anyone has any questions on it.

   

  At some point over the course of trying to run     PROG.EXE    it was indicated that      Python24.dll    was missing so it has been copied into the     DIST     folder where 

      PROG.EXE      is located as well as           WINDOWS\SYSTEM32\DRIVERS     ,           

          WINDOWS        and        WINDOWS\SYSTEM  .

  Jack Anema



------------------------------------------------------------------------------


  _______________________________________________
  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/20050915/9d578c7e/attachment.html

From keridee at jayco.net  Fri Sep 16 02:29:55 2005
From: keridee at jayco.net (Jacob S.)
Date: Thu, 15 Sep 2005 19:29:55 -0500
Subject: [Tutor] CREATING  A  PR.EXE  FROM  A  PR.PY
References: <001d01c5b1be$66134a50$6501a8c0@acerd3e20d0d7f>
Message-ID: <000101c5bb10$2fa65d30$6401a8c0@JSLAPTOP>

For some odd reason I love doing this...

1) Save this code and run it as is
2) Screen instructions *should* be intuitive enough
3) When entering file name, include extension (it uses the difference between py and pyw to know if it needs console)
4) When done, there should be two new folders in the directory with the file you made exe
    build is not needed for the execute
    Every file in dist is necessary for your exe (okay, well, maybe not *every* file)


##### setup.py ################
from distutils.core import setup
import py2exe
import os,sys

def selectdir():
    c2 = os.getcwd()
    while 1:
        old = c2
        print "Current directory is: %s" % c2
        current = raw_input("Enter new directory or 'stop' if dir okay. ")
        if current in ('stop','n','quit'):
            break
        elif current == '':
            c2 = default
        elif current == 'look':
            printlines(os.listdir(c2))
        elif current.startswith("chdir "):
            c2 = current[5:]
        else:
            c2 = os.path.join(c2,current)
        if not os.path.isdir(c2):
            n = raw_input("Directory does not exist. Create? ")
            if n == 'quit':
                raise SystemExit
            elif n == 'y':
                os.mkdir(c2)
            elif n == 'n':
                c2 = old
    os.chdir(c2)

zipfi = None

if len(sys.argv) == 1:
    sys.argv.append("py2exe")
##    sys.argv.append('--xref')

selectdir()
listed = []
listed2 = []
while 1:
    ask = raw_input('What is the file you want as an executable or \'stop\'? ')
    if ask in ['quit','stop','']:
        break
    else:
        if os.path.splitext(ask)[1] == '.pyw':
            listed2.append(ask)
        else:
            listed.append(ask)

setup(console = listed,
      windows = listed2,
      zipfile = zipfi)
#############################



Good luck,

Jacob Schmidt
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050915/e30a1052/attachment.htm

From keridee at jayco.net  Fri Sep 16 02:38:38 2005
From: keridee at jayco.net (Jacob S.)
Date: Thu, 15 Sep 2005 19:38:38 -0500
Subject: [Tutor] Where did those spaces come from?
References: <Pine.LNX.4.44.0509121845380.12147-100000@hkn.eecs.berkeley.edu>
Message-ID: <000501c5bb10$319d2420$6401a8c0@JSLAPTOP>

> As a file object, we can use the methods that files provide:
>
>    http://www.python.org/doc/lib/bltin-file-objects.html
>
> But the one we'll probably want is 'write()': the write() method of a file
> object lets us send content out, without any adulteration:
                                                                    ^^^^^^^^^^

Hey, Danny, um, maybe you meant alteration?  I don't think anyone is going 
as far cheating on their significant other to gain control over standard 
output.

;-)

Jacob

P.S.
    For those it may concern --  I know the correct term is adultery, but I 
had to bug him about something. :-) 


From keridee at jayco.net  Fri Sep 16 03:05:14 2005
From: keridee at jayco.net (Jacob S.)
Date: Thu, 15 Sep 2005 20:05:14 -0500
Subject: [Tutor] how to create a generic instance of an object?
References: <95FDCB82EFF3B9449865BF7D55FD2FF77BD74B@radmail.radical.ca>
Message-ID: <000601c5bb10$32792c40$6401a8c0@JSLAPTOP>

Two further suggestions.

1) Do you believe each class have to be in a seperate file? Is that habit 
from Perl?
    Try putting each class in one library file and then importing as 
needed/all into main script to be used
    as desired, maybe coexistent with the dictionary approach mentioned

2) How about a package? Except... that's kinda similar to the choice one...

Oh well, Danny's works -- 

Jacob


> I've got a base class "Asset", and currently have about 20 sub-classes
> (assetTypes) that will inherit from it, with more to follow, I'm sure.
> All of the assetTypes will have the same methods, but they'll be
> polymorphic; each assetType's methodA() will do something slightly
> different from it's sibling assetTypes.
>
> What I want to do is to pass in the assetType at runTime via an external
> script, create a new instance of it, and then run that instance's
> methods.  That way I won't have to have 20 or more " if assetType== "
> if/elif statements, and maintaining the script that creates new
> instances won't become a nightmare.
>
> And changing the base class' __init__ to contain another if/elif every
> time someone adds another assetType seems to be so wrong, I rejected
> that approach out of hand.  I want to design this thing so that the base
> class doesn't need to know about all the sub-classes.
>
> Perhaps I'm taking the wrong approach here with the Asset/AssetType
> base-class/sub-class organization; it's beginning to feel that way.
>
> I've tried something like this:
>
> <asset.py>
> class Asset: pass
>
> <foo.py>
> class Foo(Asset): pass
>
> <script.py>
> from asset import Asset
> from foo import Foo
>
> klass = 'Foo'
> o = klass()
>
> which gets me 'string not callable', which is kind of expected.
>
> On p.325 of the O'Reilly Learning Python (2nd ed.), there's an example
> of generic instance creation, but the values passed in are class
> objects, not strings...  I'm guessing that this works because it's all
> in the same module, so it knows that the things in the tuple iterated
> over in the foreach are classes.
>
> Any ideas?  I'm an old hand at perl (10+ years), but very new to Python,
> so please be patient.
>
> John Burk
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From keridee at jayco.net  Fri Sep 16 03:27:23 2005
From: keridee at jayco.net (Jacob S.)
Date: Thu, 15 Sep 2005 20:27:23 -0500
Subject: [Tutor] Importing modules/classes
Message-ID: <000701c5bb10$334778c0$6401a8c0@JSLAPTOP>

> You need to call the init method of the inherited class(es) from
> within your init. It's conventional to call the superclass
> constructor
> before doing your own initialisation so it should look like:
>
>    def __init__(self, num):
>        Thread.__init__(self)
>        print "__init__: Num = ", num
>
> There is a new technique for doing this in recent Python version
> (v2.2 onwards?) using the super keyword, but I've still to get
> my own head around it... :-)

super isn't a keyword, but a builtin function.
usage:

super(self).__init__()

It was mentioned on the list a couple of months ago, and as I gathered,
it didn't come out in favor of super() do to the fact that if a user-defined
class inherits from more than one class, super only calls one of the 
classes,
or something like that.  Perhaps it's better just to call them explicitly.

Jacob 


From keridee at jayco.net  Sat Sep 17 00:47:27 2005
From: keridee at jayco.net (Jacob S.)
Date: Fri, 16 Sep 2005 17:47:27 -0500
Subject: [Tutor] directory recursion
Message-ID: <002301c5bb10$c7f01cc0$6401a8c0@JSLAPTOP>

Okay, how about this?

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

import os
from fnmatch import fnmatch

def simplewalkgen(toplevel):
    """Yields full paths of all the text files in all the subdirectories"""
    for root,dirs,files in os.walk(toplevel):
        for x in files:
            ok = os.path.join(root,x)
            if fnmatch(ok,"*.txt"):
                yield ok

top = raw_input("What is the top level directory? ")

walker = simplewalkgen(top)
output = open("output.txt","w")

for fullpath in walker:
    f = os.path.basename(fullpath)
    input1 = open(fullpath,"r")
    for i in range(3):
        line = input1.readline()
    output.write(line)
    output.flush() ## Makes sure that it actually writes immediately?
    input1.close()
    print "Third line of %s written to output.txt successfully."%f
output.close()

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

Jacob Schmidt

----- Original Message ----- 
From: "Rob Andrews" <rob.andrews at gmail.com>
To: <tutor at python.org>
Sent: Monday, September 12, 2005 9:55 AM
Subject: Re: [Tutor] directory recursion


> Thanks! That did the trick after very modest head scratching.
> 
> -Rob
> 
> On 9/9/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>> >
>> > What's a nice, clean way to recursively scan through directories with
>> > an arbitrary number of subdirectories?
>> 
>> Hi Rob,
>> 
>> You may want to look at os.walk():
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From keridee at jayco.net  Sat Sep 17 00:48:46 2005
From: keridee at jayco.net (Jacob S.)
Date: Fri, 16 Sep 2005 17:48:46 -0500
Subject: [Tutor] hi
Message-ID: <003801c5bb10$f505b530$6401a8c0@JSLAPTOP>

If you would like to talk to me directly, (without the use of cluttering the 
list -- I mean, you can, they don't mind, but one-on-one is okay with me) I 
have very few things to do, and would be happy to help you out.  I have a 
tad of experience in python (about a years' worth of fiddling, actually) and 
am looking for something to do...

Ah, yes, and this invitation extends to everyone (Well... that is, of 
course, not for the honorary professionals like Kent, Danny, Alan, etc.)

My humblest offerings,
Jacob Schmidt

  ----- Original Message ----- 
  From: bobby arocha
  To: tutor at python.org
  Sent: Saturday, August 27, 2005 8:47 AM
  Subject: [Tutor] hi


  hello i am new to python very new as in my first time ever using it and no 
experience in programming at all and i woul dliek some help to understand 
how th eprogram works and how to use pythin to thelimits of its capabilitys 
and i woul dlike some help my name is bobby and i am serious about learning 
python so any help would be much apreciated
  thank u
  __________________________________________________
  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 keridee at jayco.net  Sat Sep 17 00:49:21 2005
From: keridee at jayco.net (Jacob S.)
Date: Fri, 16 Sep 2005 17:49:21 -0500
Subject: [Tutor] Website Retrieval Program
References: <1124901341.13491.4.camel@amdbert.oxbridgetechnology.local>
	<430CA592.70308@gmail.com>
Message-ID: <003b01c5bb10$f5923dc0$6401a8c0@JSLAPTOP>

> Daniel Watkins wrote:
>
>>I'm currently trying to write a script that will get all the files
>>necessary for a webpage to display correctly, followed by all the
>>intra-site pages and such forth, in order to try and retrieve one of the
>>many sites I have got jumbled up on my webspace. After starting the
>>writing, someone introduced me to wget, but I'm continuing this because
>>it seems like fun (and that statement is the first step on a slippery
>>slope :P).
>>
>>My script thus far reads:
>>"""
>>import re
>>import urllib
>>
>>source = urllib.urlopen("http://www.aehof.org.uk/real_index2.html")
>>next = re.findall('src=".*html"',source.read())
>>print next
>>"""
>>
>>This returns the following:
>>"['src="nothing_left.html"', 'src="testindex.html"',
>>'src="nothing_right.html"']"
>>
>>This is a good start (and it took me long enough! :P), but, ideally, the
>>re would strip out the 'src=' as well. Does anybody with more re-fu than
>>me know how I could do that?
>>
>>Incidentally, feel free to use that page as an example. In addition, I
>>am aware that this will need to be adjusted and expanded later on, but
>>it's a start.
>>
>>Thanks in advance,
>>Dan
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor

Orri wrote:
> Well, you don't necessarily need re-fu to do that:

Ah, but since he has already integrated re into the mix, perhaps it would be
simpler just to make the small re adaptation. Frankly, (gasp) I'm surprised
that
no one pointed it out.

import re
import urllib

source = urllib.urlopen("http://www.aehof.org.uk/real_index2.html")
next = re.findall('src=(".*html")',source.read())
print next

Notice the parentheses added in the pattern.
If you do not want the quotes in the final outcome, move the parentheses to
the other
side of the quotes in the pattern.

Jacob



> import re
> import urllib
>
> source = urllib.urlopen("http://www.aehof.org.uk/real_index2.html")
> next = [i[4:] for i in re.findall('src=".*html"',source.read())]
> print next
>
> gives you
>
> ['"nothing_left.html"', '"testindex.html"', '"nothing_right.html"']
>
> And if you wanted it to specifically take out "src=" only, I'm sure you
> could tailor it to do something with i[i.index(...):] instead.


From kent37 at tds.net  Sat Sep 17 00:48:57 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Sep 2005 18:48:57 -0400
Subject: [Tutor] ElementTree: finding a tag with specific attribute
In-Reply-To: <432B20AA.7090705@tds.net>
References: <61d0e2b405091612212f4ec2e3@mail.gmail.com>
	<432B20AA.7090705@tds.net>
Message-ID: <432B4BD9.40006@tds.net>

Kent Johnson wrote:
> Bernard Lebel wrote:
> 
>>Hello,
>>
>>With ElementTree, can you search a tag under an Element by not only
>>specifying the tag label, but also some tag attribute values? That
>>would be in the case where I have several tags with the same label but
>>with various attribute values.
> 
> FLASH: I just found PDIS XPath which evaluates XPath expressions against ElementTree trees!
> http://pdis.hiit.fi/pdis/download/

Here is a complete program that reads your file and uses pdis.xpath to dig out the value of a single parameter:

from elementtree import ElementTree
from pdis.xpath import compile

doc = ElementTree.parse('Camera_Root_bernard.xml')

path = compile('/root/sceneobject[@type="CameraRoot"]/localproperties/property[@name="Visibility"]/parameters/parameter[@scriptname="shdw"]')

node = path.evaluate(doc.getroot())[0]
print node
print node.text

>  
> 
>>I'm looking for something a bit like BeautifulSoup, like:
>>
>>oTag = oElement.find( 'taglabel', { 'value' : 'xx' } )
>>
>>
>>Btw in case you wonder, I don't use BeautifulSoup because somehow it
>>takes 20-30 seconds to parse a 2000-line xml file, and I don't know
>>why. ElementTree is proving very performing.
> 
> 
> Would you send me privately a copy of your file and your code that reads it with BS? I'm curious why this takes so long.

I took a bit of a look at this using the Python profiler. If anyone is interested, here is the main program to generate the profile results:

import BeautifulSoup, profile

sFile = r'Camera_Root_bernard.xml'

def reader():
    oFile = file( sFile, 'r' )
    oSoup = BeautifulSoup.BeautifulStoneSoup( oFile.read() )

profile.run('reader()', 'profile.out')


This creates a file called profile.out that can be analyzed with pstats.Stats:
 >>> from pstats import Stats
 >>> s=Stats('profile.out')
 >>> s.sort_stats('cum')
<pstats.Stats instance at 0x009BF918>
 >>> s.print_stats()

Here is an excerpt from the output. It doesn't work very well in email unfortunately. The most notable thing is the staggering number of times some functions are called. The first column (ncalls) is the total number of calls of a function. The second column (tottime) is the total time spent in the function, not counting the time spent in lower-level functions.

If you look at the list, for a while the functions are being called 777 times. This is probably the number of start tags in the document. But when you get to recursiveChildGenerator(), all of a sudden it is called 898655 times, over 1000 times for each call to _fetch()! This is a staggering number of calls, it is called 8 times for every character in the file!

I gave up trying to understand why this is happening, I would need to spend more time understanding the code...

Kent

Fri Sep 16 17:12:22 2005    profile.out

         9095825 function calls (9095048 primitive calls) in 80.402 CPU seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   80.402   80.402 profile:0(reader())
        1    0.000    0.000   80.398   80.398 <string>:1(?)
        1    0.002    0.002   80.397   80.397 F:\Tutor\bsTest\reader.py:5(reader)
        1    0.000    0.000   80.395   80.395 C:\Python24\lib\site-packages\BeautifulSoup.py:633(__init__)
        1    0.000    0.000   80.395   80.395 C:\Python24\lib\site-packages\BeautifulSoup.py:687(feed)
        1    0.000    0.000   80.381   80.381 C:\Python24\lib\sgmllib.py:86(feed)
        1    0.041    0.041   80.381   80.381 C:\Python24\lib\sgmllib.py:107(goahead)
      777    0.123    0.000   80.093    0.103 C:\Python24\lib\sgmllib.py:229(parse_starttag)
2331/1554    0.057    0.000   79.989    0.051 :0(getattr)
      777    0.013    0.000   79.844    0.103 C:\Python24\lib\sgmllib.py:304(finish_starttag)
      777    0.024    0.000   79.763    0.103 C:\Python24\lib\site-packages\BeautifulSoup.py:817(unknown_starttag)
      777    0.079    0.000   79.646    0.103 C:\Python24\lib\site-packages\BeautifulSoup.py:769(_smartPop)
     3108    0.051    0.000   79.575    0.026 C:\Python24\lib\site-packages\BeautifulSoup.py:676(__getattr__)
      777    0.019    0.000   79.496    0.102 C:\Python24\lib\site-packages\BeautifulSoup.py:348(__getattr__)
      777    0.010    0.000   79.467    0.102 C:\Python24\lib\site-packages\BeautifulSoup.py:467(first)
      777    0.014    0.000   79.456    0.102 C:\Python24\lib\site-packages\BeautifulSoup.py:477(fetch)
      777   10.923    0.014   79.443    0.102 C:\Python24\lib\site-packages\BeautifulSoup.py:168(_fetch)
   898655   21.556    0.000   38.801    0.000 C:\Python24\lib\site-packages\BeautifulSoup.py:525(recursiveChildGenerator)
   301476   10.316    0.000   23.791    0.000 C:\Python24\lib\site-packages\BeautifulSoup.py:233(_matches)
  2998523   14.816    0.000   14.816    0.000 :0(isinstance)
   602953    4.356    0.000    6.985    0.000 C:\Python24\lib\site-packages\BeautifulSoup.py:541(isList)
  1206683    5.852    0.000    5.852    0.000 :0(hasattr)
   905237    3.231    0.000    3.231    0.000 :0(len)
   601431    3.022    0.000    3.022    0.000 :0(range)
   599875    2.201    0.000    2.201    0.000 :0(pop)
   605655    2.153    0.000    2.153    0.000 :0(append)
   301476    1.080    0.000    1.080    0.000 :0(callable)


From dyoo at hkn.eecs.berkeley.edu  Sat Sep 17 00:54:15 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 16 Sep 2005 15:54:15 -0700 (PDT)
Subject: [Tutor] ElementTree: finding a tag with specific attribute
In-Reply-To: <432B4BD9.40006@tds.net>
Message-ID: <Pine.LNX.4.44.0509161551360.10169-100000@hkn.eecs.berkeley.edu>

> If you look at the list, for a while the functions are being called 777
> times. This is probably the number of start tags in the document. But
> when you get to recursiveChildGenerator(), all of a sudden it is called
> 898655 times, over 1000 times for each call to _fetch()! This is a
> staggering number of calls, it is called 8 times for every character in
> the file!

Hi Kent,

This sounds like a beautiful torture test for BeautifulSoup.

Kent, can you send me a copy of that test file too if that's ok?  I might
have some time to look into the performance problem.


From cpu.crazy at gmail.com  Sat Sep 17 01:09:02 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Fri, 16 Sep 2005 17:09:02 -0600
Subject: [Tutor] GetGarf
Message-ID: <432B508E.90503@gmail.com>

Ok... more probs with my GetGarf program...
First I acidently and permanently deleted all versions and now I've 
improved it but it won't download new images....
Here's the code (attached... sorry :-(   )
More Questions to come later.
Thanks,
Joe


From alan.gauld at freenet.co.uk  Sat Sep 17 01:31:35 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Sat, 17 Sep 2005 00:31:35 +0100
Subject: [Tutor] Multiple buttons, One callback
References: <Pine.LNX.4.44.0509161308480.25552-100000@hkn.eecs.berkeley.edu>
	<432B3C37.6050209@dashifen.com>
Message-ID: <001f01c5bb16$c7bf6110$0201a8c0@xp>

> I've always been about to bind each button to one callback function 
> which could then determine which button was clicked, and from that 
> data grab the necessary data and perfrom the operations on that 
> data.

There are several ways to do this.
The most direct is to use bind which passes an event object to the
callback. By interroghating the event you can determine its source.

The other way that i tend to use is:

def commonCallback(source):
    if source == 'A': doButtonA()
    elif source == 'B' : doButtonB()
    etc...

A = Button(parent, text='A', lambda id='A': commonCallback(id))
B = Button(parent, text='B', lambda id='B': commonCallback(id))

THat is create a common function that takes the source identifier
as a parameter. For each widget callback use a lambda to create
an anonymous handler that calls the comon function passing the
source id as an argument. The source Id is set up as a default
parameter value in the lambda definition.

HTH,

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


From cpu.crazy at gmail.com  Sat Sep 17 01:35:46 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Fri, 16 Sep 2005 17:35:46 -0600
Subject: [Tutor] IRC Client documentation
Message-ID: <432B56D2.7080901@gmail.com>

Hi,
    I've googled, checked out the Python Cookbook but still can't find 
anything usefull. I need to make python IRC client or find one written 
in python to start off with. DO you know of anything?
thanks,
    Joseph

From denise.hartley at gmail.com  Sat Sep 17 02:29:45 2005
From: denise.hartley at gmail.com (D. Hartley)
Date: Fri, 16 Sep 2005 17:29:45 -0700
Subject: [Tutor] More IDE's (was: Boa-Constructor)
In-Reply-To: <59CF9F456FAA9045B405C441EC916F3E02CE8639@MERC24.na.sas.com>
References: <59CF9F456FAA9045B405C441EC916F3E02CE8639@MERC24.na.sas.com>
Message-ID: <8daabe5605091617297b1b1540@mail.gmail.com>

I know how to use the code completion (hooray for me!) but so far,
most everything else that's going on in PyDev/Eclipse is a mystery to
me.  But I managed to get an interactive interpreter as an external
tool, so that's a lot of progress for me.

Technically I suppose this is OT, but did you guys that have used/are
using PyDev/Eclipse use any kind of tutorials for those other
functions? (Not sure if there even *are* any, besides the standard
documentation on PyDev's website)  Most of the things I've found on
eclipse are for much more advanced eyes than mine, it would seem.

I'd appreciate any pointers! :)

~Denise

On 9/14/05, George Flaherty <George.Flaherty at marketmax.com> wrote:
> Yeah, I have been using PyDev with Eclipse. It is pretty good, since with the latest version the debugger is working and they have include the ability to add additional paths in the PYTHONPATH variable.
> 
> I honestly would prefer to use Emacs, but I have not found any tool that provides code-completion with python. Until I have been using Eclipse (with Emacs running minimized :)
> 
> -g
> 
> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of D. Hartley
> Sent: Tuesday, September 13, 2005 10:27 PM
> To: Python tutor
> Subject: [Tutor] More IDE's (was: Boa-Constructor)
> 
> This thread made me wonder:
> 
> Is anyone out there using Eclipse and PyDev? (I started using Eclipse when I was toying around in Jython, and know others that are using it for C/C++, but I am curious if others have tried out PyDev and what they think).
> 
> ~Denise
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From falcon3166 at hotmail.com  Sat Sep 17 02:59:06 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 16 Sep 2005 18:59:06 -0600
Subject: [Tutor] Will the following code ever exit?
Message-ID: <BAY106-DAV9E33453314C82EE3EE66BC4900@phx.gbl>

Hey all,

Will the following code ever exit, or do I have to change something so that it will exit? It's a sample of what I'm currently working on.
import random

def add(a,b):
    answer = a+b
    guess = float(raw_input(a," + ",b," = "))

num1 = random.choice(range(1,10))
num2 = random.choice(range(1,10))

q = random.choice(range(15,31)
cq = 1
while cq >= q:
    add(num1,num2)
    if guess != answer:
        print "Incorrect! The correct answer is: ",answer
        incorrect += 1
        cq += 1
   elif guess == answer:
       print "Correct!"
       correct += 1
       cq += 1
else:
   print "Questions: ",q
   print "Correct: ",correct
   print "Percent Correct: ",(correct/q)*100

Thanks,
Nathan Pinno
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050916/4db65435/attachment.htm

From keridee at jayco.net  Sat Sep 17 03:18:54 2005
From: keridee at jayco.net (Jacob S.)
Date: Fri, 16 Sep 2005 20:18:54 -0500
Subject: [Tutor] threading problem in GUI
References: <431DAEEF.9090209@xit.net>
Message-ID: <071d01c5bb25$db1779a0$6401a8c0@JSLAPTOP>

> Hello there !
> i am having a problem with threading.
> OK, i have this GUI app that i am building with pygtk.
> there is a process (four actually, just working on getting one right now)
> that needs to run in the background.
> there is a button that starts the background function. But, it locks up
> the gui. it doesn't run in the background, it locks everything up. It
> still runs though.
> one of the things this background process is to do is updata a viewable
> area on the GUI. Now when run from a terminal, when i hit CTRL+C
> it stops the thread, but doesnt kill the GUI, and the TextView gets
> updated right then with everything it should have gotten before.
>
>
> def Serial1():
>            print 'running serial 1'
>            ser = serial.Serial('/dev/ttyS15', 2400, timeout=None)
>            loopy = 1
>            i = 1
>            while loopy < 5:
>                x_Now = strftime('%Y-%m-%d %H:%M:%S')
>                i = i + 1
>                a = ser.read(1)#read one byte
>                a = ord(a) # change byte to integer
>                if (a < 64 )or (a > 127):
>                    continue
>                b = ser.read(1)
>                b = ord(b)
>                if (b < 64 )or (b > 127):
>                    continue
>                c = ser.read(1)
>                c = ord(c)
>                if c < 92:
>                    continue
>                d = ser.read(1)
>                d = ord(d)
>                if d < 128:
>                    continue
>                Sensor_ID = (a & 63) + (b & 63) * 64 + (c & 1) * 4096
>                Status = (c & 62) / 2 + (d & 63) * 32
>                c = int(c)
>                d = int(d)
>                x_Now = strftime('%Y-%m-%d %H:%M:%S')
>                f = open('/home/piv/PivData/tmp/Serial/'+str(i), 'w')
>                Input1Data =
> str(Sensor_ID)+'\t'+str(Status)+'\t--------->\t'+x_Now+'\n'
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Okay, it's time for you to learn % formatting and fix this line.
Read this.

http://www.python.org/doc/2.4.1/lib/typesseq-strings.html#l2h-211

Okay, need help? Ask.
(I don't mean to be blunt, but that line is teetering on the edge of 
atrocious.)

>                Input1Iter = self.Input1Buffer.get_end_iter()
>                self.Input1Buffer.insert(Input1Iter,
> Input1Data)
>
> f.write(str(Sensor_ID)+'\n'+str(c)+'\n'+str(d)+'\n'+str(Status)+'\n'+x_Now)

Ah. The above line here should meet the same fate. It's atrocious too.

HTH,

Jacob


>                f.close()
>        thread.start_new(Serial1())
>
> the code may not be best form, i am still fairly new at this. so i am
> also open to
> any constructive critisism.


From falcon3166 at hotmail.com  Sat Sep 17 03:18:36 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 16 Sep 2005 19:18:36 -0600
Subject: [Tutor] Why won't it enter the quiz?
Message-ID: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>

Hi all,

I've got this program I've written that should give an addition quiz, except it never enters the quiz. How do I make it enter the quiz?

Here is the code:
import random

def add(a,b):
    answer = a+b
    guess = float(raw_input(a," + ",b," = "))

num1 = random.choice(range(1,10))
num2 = random.choice(range(1,10))

while 1:
    q = random.choice(range(15,31))
    cq = 1
    correct = 0
    while cq >= q:
        add(num1,num2)
        if guess != answer:
            print "Incorrect! The correct answer is: ",answer
            cq += 1
        elif guess == answer:
            print "Correct!"
            correct += 1
            cq += 1
    else:
        print "Questions: ",q
        print "Correct: ",correct
        print "Percent Correct: ",(cq/q)*100
        break

print "Goodbye."

It just prints out for an example:

Questions:  17
Correct:  0
Percent Correct:  0
Goodbye.

Thanks,
Nathan Pinno
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050916/6fb9ba65/attachment.html
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Pinno, Nathan Paul.vcf
Type: text/x-vcard
Size: 783 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050916/6fb9ba65/PinnoNathanPaul.vcf

From john at fouhy.net  Sat Sep 17 03:20:37 2005
From: john at fouhy.net (John Fouhy)
Date: Sat, 17 Sep 2005 13:20:37 +1200
Subject: [Tutor] Will the following code ever exit?
In-Reply-To: <BAY106-DAV9E33453314C82EE3EE66BC4900@phx.gbl>
References: <BAY106-DAV9E33453314C82EE3EE66BC4900@phx.gbl>
Message-ID: <5e58f2e405091618202e26b916@mail.gmail.com>

On 17/09/05, Nathan Pinno <falcon3166 at hotmail.com> wrote:
> def add(a,b): 
>     answer = a+b 
>     guess = float(raw_input(a," + ",b," = ")) 

Hi Nathan,

When you define a function, any variables you create in the function
are _local_ variables.  This means that they only exist within the
function, and when the function exits, python will forget about them.

As an example, consider the following code:

###
total = 13

def add(a, b):
    total = a + b

add(2, 4)
print total
###

The print statement at the end will print out 13, not 6.  The best way
to get output from a function is to use a return statement.  So, we
could change your add function to look something like this:

###
def add(a, b):
    answer = a+b
    guess = float(raw_input(a," + ",b," = "))
    return answer, guess
###

Then, you can use the function in your program like this:

###
answer, guess = add(num1, num2)
###

This will get the return values of the function and put it into
variables which you can access from the rest of your program.

Hope this helps!

-- 
John.

From falcon3166 at hotmail.com  Sat Sep 17 03:25:30 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 16 Sep 2005 19:25:30 -0600
Subject: [Tutor] Will the following code ever exit?
References: <BAY106-DAV9E33453314C82EE3EE66BC4900@phx.gbl>
	<5e58f2e405091618202e26b916@mail.gmail.com>
Message-ID: <BAY106-DAV568DFCA97A8BFE9A34BDCC4900@phx.gbl>

Thanks, but when I run the code, even after that change it always just 
prints the questions, correct questions(which is always 0), and percent 
right(always 0). How do I make it enter the quiz.
Thanks,
Nathan Pinno
----- Original Message ----- 
From: "John Fouhy" <john at fouhy.net>
To: "Nathan Pinno" <falcon3166 at hotmail.com>
Cc: <tutor at python.org>
Sent: Friday, September 16, 2005 7:20 PM
Subject: Re: [Tutor] Will the following code ever exit?


On 17/09/05, Nathan Pinno <falcon3166 at hotmail.com> wrote:
> def add(a,b):
>     answer = a+b
>     guess = float(raw_input(a," + ",b," = "))

Hi Nathan,

When you define a function, any variables you create in the function
are _local_ variables.  This means that they only exist within the
function, and when the function exits, python will forget about them.

As an example, consider the following code:

###
total = 13

def add(a, b):
    total = a + b

add(2, 4)
print total
###

The print statement at the end will print out 13, not 6.  The best way
to get output from a function is to use a return statement.  So, we
could change your add function to look something like this:

###
def add(a, b):
    answer = a+b
    guess = float(raw_input(a," + ",b," = "))
    return answer, guess
###

Then, you can use the function in your program like this:

###
answer, guess = add(num1, num2)
###

This will get the return values of the function and put it into
variables which you can access from the rest of your program.

Hope this helps!

-- 
John.

From kent37 at tds.net  Sat Sep 17 03:31:52 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Sep 2005 21:31:52 -0400
Subject: [Tutor] ElementTree: finding a tag with specific attribute
In-Reply-To: <Pine.LNX.4.44.0509161551360.10169-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509161551360.10169-100000@hkn.eecs.berkeley.edu>
Message-ID: <432B7208.5090405@tds.net>

Danny Yoo wrote:
>>If you look at the list, for a while the functions are being called 777
>>times. This is probably the number of start tags in the document. But
>>when you get to recursiveChildGenerator(), all of a sudden it is called
>>898655 times, over 1000 times for each call to _fetch()! This is a
>>staggering number of calls, it is called 8 times for every character in
>>the file!
> 
> 
> Hi Kent,
> 
> This sounds like a beautiful torture test for BeautifulSoup.
> 
> Kent, can you send me a copy of that test file too if that's ok?  I might
> have some time to look into the performance problem.

Bernard, would you send a copy to Danny? It's not my data so I'd rather not forward it.

Danny, the file is not particularly large or difficult, it has a simple structure and nests about six levels deep. Maybe there's some O(n^2) nastiness somewhere in BeautifulSoup.

Kent


From dyoo at hkn.eecs.berkeley.edu  Sat Sep 17 03:39:20 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 16 Sep 2005 18:39:20 -0700 (PDT)
Subject: [Tutor] Why won't it enter the quiz?
In-Reply-To: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>
Message-ID: <Pine.LNX.4.44.0509161832390.21356-100000@hkn.eecs.berkeley.edu>



> I've got this program I've written that should give an addition quiz,
> except it never enters the quiz. How do I make it enter the quiz?


Hi Nathan,


Let's look at a small snippet of the code.

>     q = random.choice(range(15,31))
>     cq = 1

What does 'q' stand for?  What does 'cq' stand for?

These aren't irrelevant questions, because you were doing fine with your
other variable names right up till then.

Your program isn't going to run any slower if you use longer variable
names.  *grin*  Until you get more experience, try using descriptive
names.  For myself, doing so usually jolts me into trying to make sure the
code reads well.


It also matters because I don't yet understand what the while's condition
is checking for:

>     while cq >= q:
            ^^^^^^^

Can you explain what this is trying to check?  I suspect that this
expression is "weird" in the sense that it doesn't check what you're
trying to check.


Best of wishes to you!


From falcon3166 at hotmail.com  Sat Sep 17 03:47:16 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 16 Sep 2005 19:47:16 -0600
Subject: [Tutor] Why won't it enter the quiz?
References: <Pine.LNX.4.44.0509161832390.21356-100000@hkn.eecs.berkeley.edu>
Message-ID: <BAY106-DAV1542CDFF1C03B5D5C3F41BC4900@phx.gbl>

cq is for "current question" and q is for "question"
therefore cq >= q should be correct most of the time
----- Original Message ----- 
From: "Danny Yoo" <dyoo at hkn.eecs.berkeley.edu>
To: "Nathan Pinno" <falcon3166 at hotmail.com>
Cc: <Tutor at python.org>
Sent: Friday, September 16, 2005 7:39 PM
Subject: Re: [Tutor] Why won't it enter the quiz?


>
>
>> I've got this program I've written that should give an addition quiz,
>> except it never enters the quiz. How do I make it enter the quiz?
>
>
> Hi Nathan,
>
>
> Let's look at a small snippet of the code.
>
>>     q = random.choice(range(15,31))
>>     cq = 1
>
> What does 'q' stand for?  What does 'cq' stand for?
>
> These aren't irrelevant questions, because you were doing fine with your
> other variable names right up till then.
>
> Your program isn't going to run any slower if you use longer variable
> names.  *grin*  Until you get more experience, try using descriptive
> names.  For myself, doing so usually jolts me into trying to make sure the
> code reads well.
>
>
> It also matters because I don't yet understand what the while's condition
> is checking for:
>
>>     while cq >= q:
>            ^^^^^^^
>
> Can you explain what this is trying to check?  I suspect that this
> expression is "weird" in the sense that it doesn't check what you're
> trying to check.
>
>
> Best of wishes to you!
>
> 

From byron at christianfreebies.com  Sat Sep 17 04:03:10 2005
From: byron at christianfreebies.com (Byron)
Date: Fri, 16 Sep 2005 19:03:10 -0700
Subject: [Tutor] Why won't it enter the quiz?
In-Reply-To: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>
References: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>
Message-ID: <432B795E.50804@christianfreebies.com>


Hi Nathan,

Wow, I have to give you some good credit -- you are quite the sneaky and 
innovative business guy.  You get the free tutors here to help write 
your programs and when they are finished, you sell them on your website 
for $20.00 each!  I bet more businesses wish they could do business the 
way you do!  Quite efficient, I must admit... <big grin>

Take care,

Brian
---


From 3dbernard at gmail.com  Sat Sep 17 04:13:54 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri, 16 Sep 2005 21:13:54 -0500
Subject: [Tutor] ElementTree: finding a tag with specific attribute
In-Reply-To: <432B7208.5090405@tds.net>
References: <Pine.LNX.4.44.0509161551360.10169-100000@hkn.eecs.berkeley.edu>
	<432B7208.5090405@tds.net>
Message-ID: <61d0e2b4050916191327911988@mail.gmail.com>

Kent, sorry to send you back your request, I won't access to file
until Monday, so either you send it to Danny, either Dannay waits
until Monday. I'm fine with you sending the file to Danny.

Guys let me know if Danny receives the file, I'll send it Monday if not.
And thanks for looking into this, glad to contribute to development :-)


Bernard



On 9/16/05, Kent Johnson <kent37 at tds.net> wrote:
> Danny Yoo wrote:
> >>If you look at the list, for a while the functions are being called 777
> >>times. This is probably the number of start tags in the document. But
> >>when you get to recursiveChildGenerator(), all of a sudden it is called
> >>898655 times, over 1000 times for each call to _fetch()! This is a
> >>staggering number of calls, it is called 8 times for every character in
> >>the file!
> >
> >
> > Hi Kent,
> >
> > This sounds like a beautiful torture test for BeautifulSoup.
> >
> > Kent, can you send me a copy of that test file too if that's ok?  I might
> > have some time to look into the performance problem.
> 
> Bernard, would you send a copy to Danny? It's not my data so I'd rather not forward it.
> 
> Danny, the file is not particularly large or difficult, it has a simple structure and nests about six levels deep. Maybe there's some O(n^2) nastiness somewhere in BeautifulSoup.
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From kent37 at tds.net  Sat Sep 17 04:21:16 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Sep 2005 22:21:16 -0400
Subject: [Tutor] ElementTree: finding a tag with specific attribute
In-Reply-To: <432B4BD9.40006@tds.net>
References: <61d0e2b405091612212f4ec2e3@mail.gmail.com>	<432B20AA.7090705@tds.net>
	<432B4BD9.40006@tds.net>
Message-ID: <432B7D9C.2020802@tds.net>

Kent Johnson wrote:
>>Bernard Lebel wrote:
>>>Btw in case you wonder, I don't use BeautifulSoup because somehow it
>>>takes 20-30 seconds to parse a 2000-line xml file, and I don't know
>>>why. ElementTree is proving very performing.
> 
> I took a bit of a look at this using the Python profiler. The most notable thing is the staggering number
> of times some functions are called. The first column (ncalls) is the
> total number of calls of a function. The second column (tottime) is
> the total time spent in the function, not counting the time spent in
> lower-level functions.
> 
> If you look at the list, for a while the functions are being called
> 777 times. This is probably the number of start tags in the document.
> But when you get to recursiveChildGenerator(), all of a sudden it is
> called 898655 times, over 1000 times for each call to _fetch()! This
> is a staggering number of calls, it is called 8 times for every
> character in the file!

I looked at this again and there is a bug in BS that causes this behaviour. It's kind of an interesting bug that is a side-effect of the way BS uses introspection to access child tags.

The problem begins at line 790:
        isResetNesting = self.RESET_NESTING_TAGS.has_key(name)

This looks innocent. The problem is that self.RESET_NESTING_TAGS is not defined. This forces a call to BeautifulStoneSoup.__getattr__() which calls Tag.__getattr__() and triggers a search for a child tag called RESET_NESTING_TAGS. I think the reason Bernard's file has such a hard time with this is because he has quite a few child tags under some of the tags. When each tag is created, the list of tags is iterated again.

Anyway I don't have time for a longer explanation right now. The fix is really simple - just add the line
    RESET_NESTING_TAGS = {}
after line 586.

I'll send a bug report to the author of BS.

Kent


From tutor.python.org at pooryorick.com  Sat Sep 17 04:52:51 2005
From: tutor.python.org at pooryorick.com (Nathan Coulter)
Date: Fri, 16 Sep 2005 22:52:51 -0400
Subject: [Tutor] Why won't it enter the quiz? (off topic)
In-Reply-To: <432B795E.50804@christianfreebies.com>
References: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>
	<432B795E.50804@christianfreebies.com>
Message-ID: <432B8503.7080508@pooryorick.com>

Byron wrote:
> Hi Nathan,
> 
> Wow, I have to give you some good credit -- you are quite the sneaky and 
> innovative business guy.  You get the free tutors here to help write 
> your programs and when they are finished, you sell them on your website 
> for $20.00 each!  I bet more businesses wish they could do business the 
> way you do!  Quite efficient, I must admit... <big grin>
> 

I'd bet that almost EVERYONE on this list is selling software with the skills they may have picked up here.  There's nothing wrong with that!  And any of Nathan's customer's that want to try to build it themselves are free to look here on the list to see exactly how he did it.  Kudos, Nathan!

Bye,
Poor Yorick

From kent37 at tds.net  Sat Sep 17 05:04:34 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Sep 2005 23:04:34 -0400
Subject: [Tutor] ElementTree: finding a tag with specific attribute
In-Reply-To: <432B7D9C.2020802@tds.net>
References: <61d0e2b405091612212f4ec2e3@mail.gmail.com>	<432B20AA.7090705@tds.net>	<432B4BD9.40006@tds.net>
	<432B7D9C.2020802@tds.net>
Message-ID: <432B87C2.5010502@tds.net>

One last note then I really have to go to bed...

There is a program to help browse the results of profiling a Python program. It's not fancy but it helps.
http://webpages.charter.net/erburley/pprofui.html

Kent


From falcon3166 at hotmail.com  Sat Sep 17 05:06:58 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 16 Sep 2005 21:06:58 -0600
Subject: [Tutor] Why won't it enter the quiz?
References: <mailman.1494.1126923682.508.tutor@python.org>
Message-ID: <BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>

Brian and all,

I am just asking for help - after all I write most each program myself, and 
just ask for help in debugging it whenever I cannot figure it out. If this 
is being sneaky, I apologize, and won't ask for help anymore.

I wanted help, or at least a hint, but instead, you laugh at me.

Oh well, guess I can't get help as a newbie...

I guess I should have erased my signature from these messages sooner rather 
than later, to prevent this e-mail.

Regards,
Nathan Pinno

> Date: Fri, 16 Sep 2005 19:03:10 -0700
> From: Byron <byron at christianfreebies.com>
> Subject: Re: [Tutor] Why won't it enter the quiz?
> To: Tutor at python.org
> Message-ID: <432B795E.50804 at christianfreebies.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
>
> Hi Nathan,
>
> Wow, I have to give you some good credit -- you are quite the sneaky and
> innovative business guy.  You get the free tutors here to help write
> your programs and when they are finished, you sell them on your website
> for $20.00 each!  I bet more businesses wish they could do business the
> way you do!  Quite efficient, I must admit... <big grin>
>
> Take care,
>
> Brian

From byron at christianfreebies.com  Sat Sep 17 05:21:48 2005
From: byron at christianfreebies.com (Byron)
Date: Fri, 16 Sep 2005 20:21:48 -0700
Subject: [Tutor] Why won't it enter the quiz? (off topic)
In-Reply-To: <432B8503.7080508@pooryorick.com>
References: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>	<432B795E.50804@christianfreebies.com>
	<432B8503.7080508@pooryorick.com>
Message-ID: <432B8BCC.7030101@christianfreebies.com>

Hi Nathan C,

No, I was not saying that he needed to stop.  However, I thought it was 
kind of funny / entertaining that the tutors here are helping to develop 
his code for free -- and then he gets to sell it online!  Quite the 
efficient business model there...  :-)

PS> No, (for the record only), there is a HUGE difference between 
selling "skills" and selling code that someone else wrote.  :-D

Brian
---


Nathan Coulter wrote:
> Byron wrote:
> 
>>Hi Nathan,
>>
>>Wow, I have to give you some good credit -- you are quite the sneaky and 
>>innovative business guy.  You get the free tutors here to help write 
>>your programs and when they are finished, you sell them on your website 
>>for $20.00 each!  I bet more businesses wish they could do business the 
>>way you do!  Quite efficient, I must admit... <big grin>
>>
> 
> I'd bet that almost EVERYONE on this list is selling software with the skills they may have picked up here.  There's nothing wrong with that!  And any of Nathan's customer's that want to try to build it themselves are free to look here on the list to see exactly how he did it.  Kudos, Nathan!
> 
> Bye,
> Poor Yorick
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



From byron at christianfreebies.com  Sat Sep 17 05:25:29 2005
From: byron at christianfreebies.com (Byron)
Date: Fri, 16 Sep 2005 20:25:29 -0700
Subject: [Tutor] Why won't it enter the quiz?
In-Reply-To: <BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
Message-ID: <432B8CA9.2000200@christianfreebies.com>

Nathan Pinno wrote:
> Brian and all,
> 
> I am just asking for help - after all I write most each program myself, 
> and just ask for help in debugging it whenever I cannot figure it out. 
> If this is being sneaky, I apologize, and won't ask for help anymore.


No, don't do that... Happy that you are asking questions!  I was humored 
by the idea that you have a GREAT business model there...  :-)  FREE 
Labor -- wow, should of thought of that one earlier...  <big grin>

Have a great weekend and hope you keep posting!

Brian
---




From tutor.python.org at pooryorick.com  Sat Sep 17 05:38:36 2005
From: tutor.python.org at pooryorick.com (Poor Yorick)
Date: Fri, 16 Sep 2005 23:38:36 -0400
Subject: [Tutor] Why won't it enter the quiz? (off topic)
In-Reply-To: <432B8BCC.7030101@christianfreebies.com>
References: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>	<432B795E.50804@christianfreebies.com>	<432B8503.7080508@pooryorick.com>
	<432B8BCC.7030101@christianfreebies.com>
Message-ID: <432B8FBC.7090304@pooryorick.com>

Byron wrote:
> Hi Nathan C,
> 
> PS> No, (for the record only), there is a HUGE difference between 
> selling "skills" and selling code that someone else wrote.  :-D
> 

Once again you're implying that there's something wrong with Nathan asking for help on this list.  Blow it out your hairdo...

Bye,
Poor Yorick

From singingxduck at gmail.com  Sat Sep 17 05:47:09 2005
From: singingxduck at gmail.com (Orri Ganel)
Date: Fri, 16 Sep 2005 23:47:09 -0400
Subject: [Tutor] Aschenputtel problem
In-Reply-To: <4329AB99.7070806@web.de>
References: <4329AB99.7070806@web.de>
Message-ID: <432B91BD.7070609@gmail.com>

Christopher Arndt wrote:

>Hi,
>
>I wonder if there is a shorter form of the following idiom:
>
>list1 = []
>list2 = []
>for item in original_list:
>    if condition(item):
>        list1.append(item)
>    else:
>        list2.append(item)
>
>(optional step:)
>
>original_list[:] = list1
>
>
>I call this the "Aschenputtel" problem, because it is described by the famous
>quote from the fairy tale as told by the Grimm brothers:
>
>"Die guten ins T?pfchen, die schlechten ins Kr?pfchen."
>
>(The good ones in the pot, the bad ones in the crop)
>
>Chris
>
>
>  
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>
Well, you there is a way to do it in one line, by having a list of list 
comprehensions:

 >>> olist = range(10)
 >>> list1, list2 = [[x for x in olist if not x % 2], [i for i in olist 
if i % 2]]
 >>>
 >>> list1
[0, 2, 4, 6, 8]
 >>> list2
[1, 3, 5, 7, 9]

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.


From falcon3166 at hotmail.com  Sat Sep 17 05:51:59 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 16 Sep 2005 21:51:59 -0600
Subject: [Tutor] Why won't it enter the quiz?
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
	<432B8CA9.2000200@christianfreebies.com>
Message-ID: <BAY106-DAV2DBE8A3F34F9C9B311318C4900@phx.gbl>

Thanks to hear that. I will keep posting, though no sales, so not a great 
business model. Any help with the original question?
Thanks,
Nathan Pinno
----- Original Message ----- 
From: "Byron" <byron at christianfreebies.com>
To: "Nathan Pinno" <falcon3166 at hotmail.com>; <Tutor at python.org>
Sent: Friday, September 16, 2005 9:25 PM
Subject: Re: [Tutor] Why won't it enter the quiz?


> Nathan Pinno wrote:
>> Brian and all,
>>
>> I am just asking for help - after all I write most each program myself, 
>> and just ask for help in debugging it whenever I cannot figure it out. If 
>> this is being sneaky, I apologize, and won't ask for help anymore.
>
>
> No, don't do that... Happy that you are asking questions!  I was humored 
> by the idea that you have a GREAT business model there...  :-)  FREE 
> Labor -- wow, should of thought of that one earlier...  <big grin>
>
> Have a great weekend and hope you keep posting!
>
> Brian
> ---
>
>
>
> 

From tvbare at socket.net  Sat Sep 17 06:07:26 2005
From: tvbare at socket.net (->Terry<-)
Date: Fri, 16 Sep 2005 23:07:26 -0500 (CDT)
Subject: [Tutor] More IDE's (was: Boa-Constructor)
In-Reply-To: <8daabe5605091617297b1b1540@mail.gmail.com>
References: <59CF9F456FAA9045B405C441EC916F3E02CE8639@MERC24.na.sas.com>
	<8daabe5605091617297b1b1540@mail.gmail.com>
Message-ID: <Pine.LNX.4.62.0509162236001.27574@elwood.hillbillyhaven.org>

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


Today (Sep 16, 2005) at 5:29pm, D. Hartley spoke these wise words:

- ->I know how to use the code completion (hooray for me!) but so far,
- ->most everything else that's going on in PyDev/Eclipse is a mystery to
- ->me.  But I managed to get an interactive interpreter as an external
- ->tool, so that's a lot of progress for me.
- ->
- ->Technically I suppose this is OT, but did you guys that have used/are
- ->using PyDev/Eclipse use any kind of tutorials for those other
- ->functions? (Not sure if there even *are* any, besides the standard
- ->documentation on PyDev's website)  Most of the things I've found on
- ->eclipse are for much more advanced eyes than mine, it would seem.
- ->
- ->I'd appreciate any pointers! :)
- ->
- ->~Denise

I too am having problems getting my head wrapped around Pydev/Eclipse.
The docs on Eclipse don't seem to be geared toward Pydev and the
FAQ on the Pydev site is rather sparse. At this point, I'm not even
sure the install went properly since I see error messages such as:

An internal error occurred during:"Pydev code completion:rebuilding modules"

among others I didn't take the time to copy down. For now I am back
to Gedit and an xterm. If you run across more documentation could you
please cc me as well?

Thanks,
- -- 
    Terry

     ,-~~-.___.     Terry Randall <tvbareATsocketDOTnet>
    / |  '     \    
   <   )        0    Linux Counter Project User# 98233
    \_/, ,-----'
       ====          //
      /  \-'~;    /~~~(0)
     /  __/~|   /      |   If only Snoopy had Slackware...
   =( ______| (________|

"He is your friend, your partner, your defender, your dog.
You are his life, his love, his leader. He will be yours,
faithful and true, to the last beat of his heart. You owe
it to him to be worthy of such devotion."    -- Unknown

         (Best viewed with a mono-spaced font.)

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.7 (GNU/Linux)

iD8DBQFDK5aDQvSnsfFzkV0RAv4YAJ4jPjR8z7X/afxscr+wt3eyeKcvnACeLfj9
TMyOGvnEYPqrZNQfQc67mBs=
=0pNZ
-----END PGP SIGNATURE-----


From byron at christianfreebies.com  Sat Sep 17 06:12:01 2005
From: byron at christianfreebies.com (Byron)
Date: Fri, 16 Sep 2005 21:12:01 -0700
Subject: [Tutor] Why won't it enter the quiz? (off topic)
In-Reply-To: <432B8FBC.7090304@pooryorick.com>
References: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>	<432B795E.50804@christianfreebies.com>	<432B8503.7080508@pooryorick.com>
	<432B8BCC.7030101@christianfreebies.com>
	<432B8FBC.7090304@pooryorick.com>
Message-ID: <432B9791.70303@christianfreebies.com>

Poor Yorick wrote:
> Once again you're implying that there's something wrong with Nathan 
> asking for help on this list.  Blow it out your hairdo...

No, I did not imply or state that at all.  In fact, I was answering your 
own statement in which you posted the following valid argument:


 > "I'd bet that almost EVERYONE on this list is selling software with
 > the __skills__ they may have picked up here."


Notice your beautiful keyword there -- "skills."  Yes, I agree with your 
statement 100%.  Not a problem at all.  However, anytime that one 
directly copies code from someone else, (at least within the United 
States), you run the risk of copyright violation and getting sued.

That's not an issue here, but in real life, one needs to be aware of 
this.  Not all people are as nice and wonderful as you will find in a 
teaching forum, such as this.

As a college-level teacher, it is important that an education be more 
than knowing how to write code -- it has to do with learning successful 
business practices too.  :-)  (Ones that will keep you out of the court 
room, at least!)

Brian
---


From cpu.crazy at gmail.com  Sat Sep 17 05:08:29 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Fri, 16 Sep 2005 21:08:29 -0600
Subject: [Tutor] GetGarf (sorry, this time with attachment)
Message-ID: <432B88AD.3050005@gmail.com>

Ooops Sorry, no attachment.

Ok... more probs with my GetGarf program...
First I acidently and permanently deleted all versions and now I've
improved it but it won't download new images....
Here's the code (attached... sorry :-(   )
More Questions to come later.
Thanks,
Joe
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: getgarf.py
Url: http://mail.python.org/pipermail/tutor/attachments/20050916/a4ca3ed9/getgarf.asc

From cpu.crazy at gmail.com  Sat Sep 17 06:21:02 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Fri, 16 Sep 2005 22:21:02 -0600
Subject: [Tutor] IRC Client documentation
In-Reply-To: <432B731D.3080101@pooryorick.com>
References: <432B56D2.7080901@gmail.com> <432B731D.3080101@pooryorick.com>
Message-ID: <432B99AE.2070608@gmail.com>

Poor Yorick wrote:

> Joseph Quigley wrote:
>
> You might want to look into Twisted at http://twistedmatrix.com/
>
> A quick google for "python twisted irc" turned up this:
>
> http://sourceforge.net/projects/pynfo/
>
Thanks, but as  I forgot to mention, I can't get the twisted 
dependencies because of some internet probs. However I found a search 
box on the Python Cookbook website and found a primitive IRC client... 
of which I have some problems (in another post).

Thanks again.. when  I can get twisted working I'll rewrite my IRC client.
Joe

From ismaelgf at adinet.com.uy  Sat Sep 17 06:30:00 2005
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Sat, 17 Sep 2005 01:30:00 -0300
Subject: [Tutor] GetGarf (sorry, this time with attachment)
In-Reply-To: <432B88AD.3050005@gmail.com>
References: <432B88AD.3050005@gmail.com>
Message-ID: <432B9BC8.1000506@adinet.com.uy>

Joseph Quigley wrote:

> Ok... more probs with my GetGarf program...
> First I acidently and permanently deleted all versions and now I've
> improved it but it won't download new images....
> Here's the code (attached... sorry :-(   )
> More Questions to come later.
> Thanks,
> Joe


Do you know about Dosage? It downloads lots of comics (around 500 - of 
course, you choose which ones). Among those, there's Garfield. It's 
"catchup" option will download past comics for you, and even generate 
RSS feeds and html pages if you wish to.

http://slipgate.za.net/dosage/

Ismael

From falcon3166 at hotmail.com  Sat Sep 17 06:30:17 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 16 Sep 2005 22:30:17 -0600
Subject: [Tutor] Why won't it enter the quiz? (off topic)
References: <mailman.1497.1126930332.508.tutor@python.org>
Message-ID: <BAY106-DAV2299CBA7C20DA16ED5C6C7C4900@phx.gbl>

Hey all,

It looks like I started another running debate, the last time I did this, it 
went forever it seemed.

Any hints or help on that original question?

For clarity, I'll ask it again:

Why won't it enter the quiz? Here is the code again:

{code}

import random

def add(a,b):
    answer = a+b
    guess = float(raw_input(a," + ",b," = "))
    return answer, guess

num1 = random.choice(range(1,10)) ### To limit the numbers chosen from 1-9
num2 = random.choice(range(1,10))

while 1:
    q = random.choice(range(15,31)) ### to choose the number of questions
    cq = 1 ### To find the current question
    correct = 0
    while cq >= q: ### To find whether or not to end the quiz.
        print cq
        answer, guess = add(num1,num2)
        if guess != answer:
            print "Incorrect! The correct answer is: ",answer
            cq += 1
        elif guess == answer:
            print "Correct!"
            correct += 1
            cq += 1
    else:
        print "Questions: ",q
        print "Correct: ",correct
        print "Percent Correct: ",(cq/q)*100
        break

print "Goodbye."

{/code}

Thanks for the help in advance,
Nathan Pinno
----- Original Message ----- 
> Date: Fri, 16 Sep 2005 22:52:51 -0400
> From: Nathan Coulter <tutor.python.org at pooryorick.com>
> Subject: Re: [Tutor] Why won't it enter the quiz? (off topic)
> Cc: Tutor at python.org
> Message-ID: <432B8503.7080508 at pooryorick.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Byron wrote:
>> Hi Nathan,
>>
>> Wow, I have to give you some good credit -- you are quite the sneaky and
>> innovative business guy.  You get the free tutors here to help write
>> your programs and when they are finished, you sell them on your website
>> for $20.00 each!  I bet more businesses wish they could do business the
>> way you do!  Quite efficient, I must admit... <big grin>
>>
>
> I'd bet that almost EVERYONE on this list is selling software with the 
> skills they may have picked up here.  There's nothing wrong with that! 
> And any of Nathan's customer's that want to try to build it themselves are 
> free to look here on the list to see exactly how he did it.  Kudos, 
> Nathan!
>
> Bye,
> Poor Yorick
>
>
> ------------------------------

From cpu.crazy at gmail.com  Sat Sep 17 06:35:15 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Fri, 16 Sep 2005 22:35:15 -0600
Subject: [Tutor] Getting rid of the newline in file
Message-ID: <432B9D03.3060709@gmail.com>

Hi. I'm using
f = file("foo", 'w')
fileContents = f.readlines()
print fileContents[0] + "Hi!"

and I get:

Foo
Hi!

How can I get rid of that new line? fileContents[1] has Bar.
I wrote the file using Joe (a *nix test editor) and for the new line I
pressed Enter to add Bar.
This is a pain as I don't want the newline.

Thanks,
    Joe
(No coincidence between my fav. text editor and my name!)




From bgailer at alum.rpi.edu  Sat Sep 17 06:40:30 2005
From: bgailer at alum.rpi.edu (bob)
Date: Fri, 16 Sep 2005 21:40:30 -0700
Subject: [Tutor] Why won't it enter the quiz? (off topic)
In-Reply-To: <BAY106-DAV2299CBA7C20DA16ED5C6C7C4900@phx.gbl>
References: <mailman.1497.1126930332.508.tutor@python.org>
	<BAY106-DAV2299CBA7C20DA16ED5C6C7C4900@phx.gbl>
Message-ID: <6.1.2.0.0.20050916214004.03564ae0@mail.mric.net>

At 09:30 PM 9/16/2005, Nathan Pinno wrote:
>Hey all,
>
>It looks like I started another running debate, the last time I did this, it
>went forever it seemed.
>
>Any hints or help on that original question?
>
>For clarity, I'll ask it again:
>
>Why won't it enter the quiz? Here is the code again:
>
>{code}
>
>import random
>
>def add(a,b):
>     answer = a+b
>     guess = float(raw_input(a," + ",b," = "))
>     return answer, guess
>
>num1 = random.choice(range(1,10)) ### To limit the numbers chosen from 1-9
>num2 = random.choice(range(1,10))
>
>while 1:
>     q = random.choice(range(15,31)) ### to choose the number of questions
>     cq = 1 ### To find the current question
>     correct = 0
>     while cq >= q: ### To find whether or not to end the quiz.

cq is never >= q

>         print cq
>         answer, guess = add(num1,num2)
>         if guess != answer:
>             print "Incorrect! The correct answer is: ",answer
>             cq += 1
>         elif guess == answer:
>             print "Correct!"
>             correct += 1
>             cq += 1
>     else:
>         print "Questions: ",q
>         print "Correct: ",correct
>         print "Percent Correct: ",(cq/q)*100
>         break
>
>print "Goodbye."
>
>{/code}
>
>Thanks for the help in advance,
>Nathan Pinno
>----- Original Message -----
> > Date: Fri, 16 Sep 2005 22:52:51 -0400
> > From: Nathan Coulter <tutor.python.org at pooryorick.com>
> > Subject: Re: [Tutor] Why won't it enter the quiz? (off topic)
> > Cc: Tutor at python.org
> > Message-ID: <432B8503.7080508 at pooryorick.com>
> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> >
> > Byron wrote:
> >> Hi Nathan,
> >>
> >> Wow, I have to give you some good credit -- you are quite the sneaky and
> >> innovative business guy.  You get the free tutors here to help write
> >> your programs and when they are finished, you sell them on your website
> >> for $20.00 each!  I bet more businesses wish they could do business the
> >> way you do!  Quite efficient, I must admit... <big grin>
> >>
> >
> > I'd bet that almost EVERYONE on this list is selling software with the
> > skills they may have picked up here.  There's nothing wrong with that!
> > And any of Nathan's customer's that want to try to build it themselves are
> > free to look here on the list to see exactly how he did it.  Kudos,
> > Nathan!
> >
> > Bye,
> > Poor Yorick
> >
> >
> > ------------------------------
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor


From falcon3166 at hotmail.com  Sat Sep 17 06:51:44 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 16 Sep 2005 22:51:44 -0600
Subject: [Tutor] How do fix this error?
Message-ID: <BAY106-DAV1447C20FE1D24748C4AD12C4900@phx.gbl>

I changed the code and got an error:
Here is the screenshot containing the error:

27

Traceback (most recent call last):
  File "D:\Python24\add_tutor.py", line 18, in -toplevel-
    answer, guess = add(num1,num2)
  File "D:\Python24\add_tutor.py", line 5, in add
    guess = float(raw_input(a," + ",b," = "))
TypeError: [raw_]input expected at most 1 arguments, got 4

Here is the updated code:
import random

def add(a,b):
    answer = a+b
    guess = float(raw_input(a," + ",b," = "))
    return answer, guess

num1 = random.choice(range(1,10)) ### To limit the numbers chosen from 1-9
num2 = random.choice(range(1,10))

q = random.choice(range(15,31)) ### to choose the number of questions
cq = 0 ### To find the current question
correct = 0
while 1:
    cq = cq + 1
    while cq >= q:
        print cq
        answer, guess = add(num1,num2)
        if guess != answer:
            print "Incorrect! The correct answer is: ",answer
        elif guess == answer:
            print "Correct!"
            correct += 1
print "Questions: ",q
print "Correct: ",correct
print "Percent right: ",(correct/q)*100
print "Goodbye."

How do I fix it so that it runs without anymore errors or problems?

Thanks for the help so far,
Nathan Pinno
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050916/050017ca/attachment.htm

From forestiero at qwest.net  Sat Sep 17 06:56:36 2005
From: forestiero at qwest.net (Dog Walker)
Date: Fri, 16 Sep 2005 21:56:36 -0700
Subject: [Tutor] Why won't it enter the quiz? (off topic)
In-Reply-To: <BAY106-DAV2299CBA7C20DA16ED5C6C7C4900@phx.gbl>
References: <mailman.1497.1126930332.508.tutor@python.org>
	<BAY106-DAV2299CBA7C20DA16ED5C6C7C4900@phx.gbl>
Message-ID: <200509162156.36368.forestiero@qwest.net>

On Friday 16 September 2005 21:30, Nathan Pinno wrote:
> Hey all,
> 
> It looks like I started another running debate, the last time I did this, it 
> went forever it seemed.
> 
> Any hints or help on that original question?

cq is equal to 1
15<=q<=31
cq cannot be >= q



From ismaelgf at adinet.com.uy  Sat Sep 17 07:12:56 2005
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Sat, 17 Sep 2005 02:12:56 -0300
Subject: [Tutor] OT - email & imaplib modules
In-Reply-To: <b6f3249e050907043444545284@mail.gmail.com>
References: <b6f3249e050907043444545284@mail.gmail.com>
Message-ID: <432BA5D8.40700@adinet.com.uy>

mailing list wrote:

>It's like Pythoncard, a layer of abstraction makes 90% of what you do
>easier, and the other 10% you can still do the manual way.
>
>I don't know, I'm also tempted to try and write those layers, if
>anyone would benefit from them. But yeah, would it be better or worse
>for people to not have to learn the niceties of RFC3501 formal syntax
>section to use imap?
>
I believe a layer of abstraction would do well. The commands you show 
are quite unintuitive, and if I were to use imap it would certainly 
require hours of googling. Also, when working in my programs I usually 
wrap in functions or even classes this kind of "hard" bits. Perhaps this 
is about getting a more pythonic feel to the libraries, like Pythoncard, 
Wax, ElementTree and so on, try to do.

Ismael

From tutor.python.org at pooryorick.com  Sat Sep 17 07:13:02 2005
From: tutor.python.org at pooryorick.com (Poor Yorick)
Date: Sat, 17 Sep 2005 01:13:02 -0400
Subject: [Tutor] How do fix this error?
In-Reply-To: <BAY106-DAV1447C20FE1D24748C4AD12C4900@phx.gbl>
References: <BAY106-DAV1447C20FE1D24748C4AD12C4900@phx.gbl>
Message-ID: <432BA5DE.6010204@pooryorick.com>

Nathan Pinno wrote:

>     guess = float(raw_input(a," + ",b," = "))
> TypeError: [raw_]input expected at most 1 arguments, got 4
>  

>     guess = float(raw_input(a," + ",b," = "))
>     return answer, guess
>  
hint:  how many arguments are you passing to raw_input here?

--
Poor Yorick

From ml.cyresse at gmail.com  Sat Sep 17 08:16:55 2005
From: ml.cyresse at gmail.com (mailing list)
Date: Sat, 17 Sep 2005 18:16:55 +1200
Subject: [Tutor] How do fix this error?
In-Reply-To: <432BA5DE.6010204@pooryorick.com>
References: <BAY106-DAV1447C20FE1D24748C4AD12C4900@phx.gbl>
	<432BA5DE.6010204@pooryorick.com>
Message-ID: <b6f3249e05091623166ddec50f@mail.gmail.com>

raw_input takes one argument.

While 

>>> x = 5
>>> b = 10
>>> print x, "+", b, "=", x+b 

will print 5 + 10 = 15, you could also have written it - 
>>>print str(x) + " + " + str(b) + " = " + str(x+b)

Now, if I have a function - 

def divByTen(number):
      return number/10

I can call it like so - 

>>>divByTen(100)
10

or

>>>divByTen(50+50)
10

As Python will resolve 50+50 first.

However, 

>>>divByTen(50,50)

will produce this error - 

TypeError: divByTen expected at most 1 arguments, got 2


See where I'm going with this?

One more thing, the comma only works for the print command. 
On 9/17/05, Poor Yorick <tutor.python.org at pooryorick.com> wrote:
> Nathan Pinno wrote:
> 
> >     guess = float(raw_input(a," + ",b," = "))
> > TypeError: [raw_]input expected at most 1 arguments, got 4
> >
> 
> >     guess = float(raw_input(a," + ",b," = "))
> >     return answer, guess
> >
> hint:  how many arguments are you passing to raw_input here?
> 
> --
> Poor Yorick
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From andreengels at gmail.com  Sat Sep 17 10:13:32 2005
From: andreengels at gmail.com (Andre Engels)
Date: Sat, 17 Sep 2005 10:13:32 +0200
Subject: [Tutor] Will the following code ever exit?
In-Reply-To: <BAY106-DAV568DFCA97A8BFE9A34BDCC4900@phx.gbl>
References: <BAY106-DAV9E33453314C82EE3EE66BC4900@phx.gbl>
	<5e58f2e405091618202e26b916@mail.gmail.com>
	<BAY106-DAV568DFCA97A8BFE9A34BDCC4900@phx.gbl>
Message-ID: <6faf39c9050917011340432d38@mail.gmail.com>

On 9/17/05, Nathan Pinno <falcon3166 at hotmail.com> wrote:
> Thanks, but when I run the code, even after that change it always just
> prints the questions, correct questions(which is always 0), and percent
> right(always 0). How do I make it enter the quiz.
> Thanks,
> Nathan Pinno

Your program has:

q = random.choice(range(15,31)
cq = 1
while cq >= q:

q has a value between 15 and 31, cq equals 1. 1 is not greater than or
equal to any number between 15 and 31, so cq >= q is always false. I
think you meant to write:

while q >= cq:

Andre Engels

From alan.gauld at freenet.co.uk  Sat Sep 17 10:50:15 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Sat, 17 Sep 2005 09:50:15 +0100
Subject: [Tutor] Will the following code ever exit?
References: <BAY106-DAV9E33453314C82EE3EE66BC4900@phx.gbl>
Message-ID: <006201c5bb64$d3950690$0201a8c0@xp>

Nathan,

> Will the following code ever exit, 

Yes, it will exit - with an error because it can never run.

def add(a,b):
    answer = a+b
    guess = float(raw_input(a," + ",b," = "))

You never return the answer so it dies when the function dies.

num1 = random.choice(range(1,10))
num2 = random.choice(range(1,10))

q = random.choice(range(15,31)
cq = 1
while cq >= q:

and cq is 1 and q is between 15,31 so cq will never be >= to q, 
the while loop will never execute.


    add(num1,num2)
    if guess != answer:

But if it did answer is not defined 9see comment above) 
so this will crash.

else:
   print "Questions: ",q
   print "Correct: ",correct

And if it gets this far correct is not defined so again 
we get an error.

You need to return answer from the function and define 
correct/incorrect. Then turn the while test into a <=

Then it might start to run although not necessarily correctly.

Alan G.


From alan.gauld at freenet.co.uk  Sat Sep 17 11:03:24 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Sat, 17 Sep 2005 10:03:24 +0100
Subject: [Tutor] Why won't it enter the quiz? (off topic)
References: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>	<432B795E.50804@christianfreebies.com>	<432B8503.7080508@pooryorick.com><432B8BCC.7030101@christianfreebies.com>
	<432B8FBC.7090304@pooryorick.com>
Message-ID: <00a501c5bb66$a96ae360$0201a8c0@xp>

>> PS> No, (for the record only), there is a HUGE difference between 
>> selling "skills" and selling code that someone else wrote.  :-D
>>
> Once again you're implying that there's something wrong with Nathan 
> asking for help on this list.  Blow it out your hairdo...

Technically there may be something wrong in that if he is
claiming copyright and selling for commerxcial gain rather
than selling it as open source  he has to prove that he
originated at least 75%(I think?) on his own. If he received
help for more than 25% he must publish the names of his
collaborators and give them their due share of the proceeds.

That's why selling code developed on the net in collaboration
via news groups and mailing lists is rarely done. It is nearly
always open source freeware. The legal minefield is potentially
horrible!

Using skills gained on such lists is fine, using code
jointly developed is a legal quagmire. However given the
nature of the code Nathan is producing and the prices
he's charging I doubt if we are going to be contesting
our share of his millions! It seems pretty harmless at
this level.

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


From alan.gauld at freenet.co.uk  Sat Sep 17 11:08:09 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Sat, 17 Sep 2005 10:08:09 +0100
Subject: [Tutor] Getting rid of the newline in file
References: <432B9D03.3060709@gmail.com>
Message-ID: <00bc01c5bb67$52e28650$0201a8c0@xp>

> f = file("foo", 'w')

Using 'w' will destroy the contents of the file, 
I assume you are really using 'r'?

> fileContents = f.readlines()

Each line will be terminated by a newline, you 
can use rstrip() to remove it:

> print fileContents[0].rstrip() + "Hi!"

HTH,

There is more on this topic in the file handling 
topic of my tutorial.

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

From alan.gauld at freenet.co.uk  Sat Sep 17 11:12:19 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Sat, 17 Sep 2005 10:12:19 +0100
Subject: [Tutor] How do fix this error?
References: <BAY106-DAV1447C20FE1D24748C4AD12C4900@phx.gbl>
Message-ID: <00ca01c5bb67$e81c6dd0$0201a8c0@xp>

Traceback (most recent call last):
  File "D:\Python24\add_tutor.py", line 18, in -toplevel-
    answer, guess = add(num1,num2)
  File "D:\Python24\add_tutor.py", line 5, in add
    guess = float(raw_input(a," + ",b," = "))
TypeError: [raw_]input expected at most 1 arguments, got 4

The error tells you what to do - give raw input 1 argument:

    guess = float(raw_input(a," + ",b," = "))

The commas separate the arguments. You need to create 
the prompt string first and then feed it to raw_input.

The string formatting operators may help here. 
See the Simple Sequences topic on my tutor for 
examples of string formatting.

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



From cpu.crazy at gmail.com  Sat Sep 17 16:52:50 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Sat, 17 Sep 2005 08:52:50 -0600
Subject: [Tutor] GetGarf (sorry, this time with attachment)
In-Reply-To: <mailman.1502.1126932711.508.tutor@python.org>
References: <mailman.1502.1126932711.508.tutor@python.org>
Message-ID: <432C2DC2.8070503@gmail.com>

Ismael wrote:

>Do you know about Dosage? It downloads lots of comics (around 500 - of 
>course, you choose which ones). Among those, there's Garfield. It's 
>"catchup" option will download past comics for you, and even generate 
>RSS feeds and html pages if you wish to.
>
>http://slipgate.za.net/dosage/
>
>Ismael
>
No I didn't.. is is free? If so then great! Just what I was looking for.


From cpu.crazy at gmail.com  Sat Sep 17 16:55:35 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Sat, 17 Sep 2005 08:55:35 -0600
Subject: [Tutor] Getting rid of the newline in file
In-Reply-To: <00bc01c5bb67$52e28650$0201a8c0@xp>
References: <432B9D03.3060709@gmail.com> <00bc01c5bb67$52e28650$0201a8c0@xp>
Message-ID: <432C2E67.5050404@gmail.com>

Alan G wrote:

>> f = file("foo", 'w')
>
>
> Using 'w' will destroy the contents of the file, I assume you are 
> really using 'r'?

Ah yes.. sorry.

>
> Each line will be terminated by a newline, you can use rstrip() to 
> remove it:
>
>> print fileContents[0].rstrip() + "Hi!"
>
Thanks a lot! This really helps.
Joseph



From tutor.python.org at pooryorick.com  Sat Sep 17 17:34:22 2005
From: tutor.python.org at pooryorick.com (Poor Yorick)
Date: Sat, 17 Sep 2005 11:34:22 -0400
Subject: [Tutor] Why won't it enter the quiz? (off topic)
In-Reply-To: <00a501c5bb66$a96ae360$0201a8c0@xp>
References: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>	<432B795E.50804@christianfreebies.com>	<432B8503.7080508@pooryorick.com><432B8BCC.7030101@christianfreebies.com>
	<432B8FBC.7090304@pooryorick.com>
	<00a501c5bb66$a96ae360$0201a8c0@xp>
Message-ID: <432C377E.3070009@pooryorick.com>

Alan G wrote:
 > 
> Technically there may be something wrong in that if he is
> claiming copyright and selling for commerxcial gain rather
> than selling it as open source  he has to prove that he

Then I recommend that Byron and anyone else interested in this stuff go browse http://www.benedict.com/ instead posting off-topic commentaries about people who turn to the list with questions.

Bye,
Poor Yorick

From jgschenz at yahoo.com  Sat Sep 17 18:44:05 2005
From: jgschenz at yahoo.com (J.Gabriel Schenz)
Date: Sat, 17 Sep 2005 11:44:05 -0500
Subject: [Tutor] Python Puzzles
In-Reply-To: <mailman.53.1126951210.19266.tutor@python.org>
References: <mailman.53.1126951210.19266.tutor@python.org>
Message-ID: <432C47D5.8080006@yahoo.com>

Hello all.

I recently returned home from overseas.  While I was overseas, I was not 
able to access the Internet very often, although I recall seeing at some 
point that there was a collection of Python puzzles that one could work 
on, and in order to move on to the next puzzle one had to solve the 
current puzzle.  Are these still out there some where?  I googled 
'Python puzzles' but did not see what I recall having seen before.  Now 
that I have the opportunity, I would like to get back into python, and 
this seems like an entertaining way to do so.

Thanks for the info.

Cheers,
Gabe


From py at virtual.demon.co.uk  Sat Sep 17 19:28:22 2005
From: py at virtual.demon.co.uk (Graeme)
Date: Sat, 17 Sep 2005 18:28:22 +0100
Subject: [Tutor] Python Puzzles
In-Reply-To: <432C47D5.8080006@yahoo.com>
References: <mailman.53.1126951210.19266.tutor@python.org>
	<432C47D5.8080006@yahoo.com>
Message-ID: <432C5236.7010403@virtual.demon.co.uk>

J.Gabriel Schenz wrote:
> there was a collection of Python puzzles that one could work 
> on, and in order to move on to the next puzzle one had to solve the 
> current puzzle.  Are these still out there some where?

You'll find the Python Challenge here - http://www.pythonchallenge.com/

Graeme

From falcon3166 at hotmail.com  Sat Sep 17 20:56:01 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Sat, 17 Sep 2005 12:56:01 -0600
Subject: [Tutor] Thank you all! was (Re:  How do fix this error?)
References: <BAY106-DAV1447C20FE1D24748C4AD12C4900@phx.gbl>
	<00ca01c5bb67$e81c6dd0$0201a8c0@xp>
Message-ID: <BAY106-DAV2461B98654D03632C07B6DC4900@phx.gbl>

Hey all,

I would like to thank everyone here and at Programmer's Heaven for all their help. Thanks again!

Gratefully,
Nathan Pinno
----- Original Message ----- 
From: "Alan G" <alan.gauld at freenet.co.uk>
To: "Nathan Pinno" <falcon3166 at hotmail.com>; <tutor at python.org>
Sent: Saturday, September 17, 2005 3:12 AM
Subject: Re: [Tutor] How do fix this error?


> Traceback (most recent call last):
>  File "D:\Python24\add_tutor.py", line 18, in -toplevel-
>    answer, guess = add(num1,num2)
>  File "D:\Python24\add_tutor.py", line 5, in add
>    guess = float(raw_input(a," + ",b," = "))
> TypeError: [raw_]input expected at most 1 arguments, got 4
> 
> The error tells you what to do - give raw input 1 argument:
> 
>    guess = float(raw_input(a," + ",b," = "))
> 
> The commas separate the arguments. You need to create 
> the prompt string first and then feed it to raw_input.
> 
> The string formatting operators may help here. 
> See the Simple Sequences topic on my tutor for 
> examples of string formatting.
> 
> Alan G
> Author of the Learn to Program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
> 
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050917/c41222b4/attachment.htm

From dyoo at hkn.eecs.berkeley.edu  Sat Sep 17 21:52:26 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 17 Sep 2005 12:52:26 -0700 (PDT)
Subject: [Tutor] Why won't it enter the quiz?
In-Reply-To: <BAY106-DAV1542CDFF1C03B5D5C3F41BC4900@phx.gbl>
Message-ID: <Pine.LNX.4.44.0509171250070.1905-100000@hkn.eecs.berkeley.edu>



On Fri, 16 Sep 2005, Nathan Pinno wrote:

> cq is for "current question" and q is for "question"
> therefore cq >= q should be correct most of the time

Are you sure?

Try specific values of current_question and question: don't just assume
that it'll work: try running through the numbers.

Remember, your initial conditions right before hitting the while loop are:

     question = random.choice(range(15,31))
     current_question = 1



From dyoo at hkn.eecs.berkeley.edu  Sat Sep 17 21:58:09 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 17 Sep 2005 12:58:09 -0700 (PDT)
Subject: [Tutor] Multiple buttons, One callback (fwd)
Message-ID: <Pine.LNX.4.44.0509171256530.1905-100000@hkn.eecs.berkeley.edu>

[Forwarding to tutor, just to keep the mailing list in the loop.  David,
try to use your email client's Reply-To-All feature next time, so that I
don't have to do this.  *grin*]

---------- Forwarded message ----------
Date: Sat, 17 Sep 2005 06:24:03 -0500
From: David Kees <dashifen at dashifen.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] Multiple buttons, One callback


Actually, that makes a lot of sense.  Feel free to get back to me at
your leisure, I'll be working on this problem some today so I might have
solved it by the time you respond, but if not then I'll probably need
some clarification.

So, just to see if I understand you, I can create a function that
creates the thunk callback and returns it.  This returned thunk callback
(is that a technical term or one of your own, by the way?) can then be
bound as the button's call back and will be able to remember the
parameters passed to the thunker -- the function creating the thunk
callbacks.

That's a great technique, one that I've not run into before.  Without
having applied it yet I can't be sure, but it certainly looks like it'll
do what I need it to.

Thanks,
Dash Kees

Danny Yoo wrote:

>
>
>>I've been able to bind each button to the same callback function (that
>>part's trivial) but what hasn't been trival is determining which button
>>was clicked and, from this information, gathering the correct datum from
>>the list of StringVars which make up the first label text.
>>
>>
>
>
>Hi David,
>
>It's possible to make dynamic callbacks.  For example:
>
>######
>
>
>>>>def some_function(x):
>>>>
>>>>
>...     print "I see", x
>...
>
>
>>>>def make_callback(n):
>>>>
>>>>
>...     def callback():
>...         return some_function(n)
>...     return callback
>######
>
>
>make_callback() is a function that returns a "thunk" callback.  That
>returned thunk doesn't take an argument, so it's perfectly appropriate as
>a button callback.
>
>And yet, that callback can remember what was initially passed into
>make_callback() --- it remembers the datum that we used to build the
>thunk.  Here, take a look:
>
>######
>
>
>>>>callbacks = [make_callback(i) for i in range(5)]
>>>>callbacks[0]
>>>>
>>>>
><function callback at 0x403a610c>
>
>
>>>>callbacks[0]()
>>>>
>>>>
>I see 0
>
>
>>>>callbacks[1]
>>>>
>>>>
><function callback at 0x403a6bfc>
>
>
>>>>callbacks[1]()
>>>>
>>>>
>I see 1
>######
>
>Does this make sense?  Please free to ask questions about this.
>
>
>Good luck!
>
>
>
>
>
>




From edhotchkiss at gmail.com  Sat Sep 17 21:59:54 2005
From: edhotchkiss at gmail.com (Ed Hotchkiss)
Date: Sat, 17 Sep 2005 15:59:54 -0400
Subject: [Tutor] MySQLdb error - PLEASE SAVE ME!
In-Reply-To: <d1bf1fa205091712503bb6f0bc@mail.gmail.com>
References: <d1bf1fa2050917124069a4ff61@mail.gmail.com>
	<d1bf1fa205091712503bb6f0bc@mail.gmail.com>
Message-ID: <d1bf1fa2050917125923cd617c@mail.gmail.com>

Ok. I am trying to read a csv file with three strings separated by commas.
I am trying to insert them into a MySQL DB online.
MySQLdb is installed, no problems.

I think that I am having some kind of error with my csv going into the
fields and being broken apart correctly. Can someone please help? I
attached the code below, it does work with that SQL server also if you
want to try and run it. Thanks in advance ..

-----

# Script to add links from a comma deliminated file to a MySQL database
# 9/16/05

import MySQLdb

conn=MySQLdb.connect( host="www.freesql.org <http://www.freesql.org>",
user="edhotchkiss",
port=3306,
passwd="test1",
db="links")

cursor = conn.cursor()
stmt = "DROP TABLE IF EXISTS links"
cursor.execute(stmt)
stmt = """CREATE TABLE links (
ID INT NOT NULL,
Name TEXT,
URL LONGTEXT,
Category LONGTEXT,
primary key (ID)
)"""
cursor.execute(stmt)


arr=[]
inp = open ("sites1.txt","r")
#read line into array
for line in inp.readlines():
links = map(str, line.split(","))
arr.append(links)
cursor.execute ("""
INSERT INTO links (Name, URL, category)
VALUES (%s, %s, %s)""" % tuple(links[0:3])
)
cursor.close()
conn.close()


--
edward hotchkiss
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050917/8fe6325e/attachment-0001.htm
-------------- next part --------------

# Script to add links from a comma deliminated file to a MySQL database
# 9/16/05

import MySQLdb

conn=MySQLdb.connect(	host="www.freesql.org",
			user="edhotchkiss",
			port=3306,
			passwd="test1",
	    		db="links")

cursor = conn.cursor()
stmt = "DROP TABLE IF EXISTS links"
cursor.execute(stmt)
stmt = """CREATE TABLE links (
    ID INT NOT NULL,
    Name TEXT,
    URL LONGTEXT,
    Category LONGTEXT,
    primary key (ID)
)"""
cursor.execute(stmt)


arr=[]
inp = open ("sites1.txt","r")
#read line into array
for line in inp.readlines():
    links = map(str, line.split(","))
    arr.append(links)
    cursor.execute ("""
	INSERT INTO links (Name, URL, category)
	    VALUES (%s, %s, %s)""" % tuple(links[0:3])
        )
cursor.close()
conn.close()








          

-------------- next part --------------
O'reilly Python Archive,http://python.oreilly.com/archive.html,python
Python Tutorials,http://www.awaretek.com/tutorials.html,python
MySQL Python,http://sourceforge.net/projects/mysql-python,python
Python Vaults of Parnassus,http://www.vex.net/parnassus/,python
PyCrypto,http://www.amk.ca/python/code/crypto,Python

From falcon3166 at hotmail.com  Sat Sep 17 22:06:06 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Sat, 17 Sep 2005 14:06:06 -0600
Subject: [Tutor] Why won't it enter the quiz?
References: <Pine.LNX.4.44.0509171250070.1905-100000@hkn.eecs.berkeley.edu>
Message-ID: <BAY106-DAV1421EAFD708B3036F26145C4900@phx.gbl>

I can see that I was wrong. I was tired, and I don't always think too smart. 
It should be cq <= q. :)
Nathan Pinno
----- Original Message ----- 
From: "Danny Yoo" <dyoo at hkn.eecs.berkeley.edu>
To: "Nathan Pinno" <falcon3166 at hotmail.com>
Cc: <Tutor at python.org>
Sent: Saturday, September 17, 2005 1:52 PM
Subject: Re: [Tutor] Why won't it enter the quiz?


>
>
> On Fri, 16 Sep 2005, Nathan Pinno wrote:
>
>> cq is for "current question" and q is for "question"
>> therefore cq >= q should be correct most of the time
>
> Are you sure?
>
> Try specific values of current_question and question: don't just assume
> that it'll work: try running through the numbers.
>
> Remember, your initial conditions right before hitting the while loop are:
>
>     question = random.choice(range(15,31))
>     current_question = 1
>
>
> 

From dyoo at hkn.eecs.berkeley.edu  Sat Sep 17 22:22:54 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 17 Sep 2005 13:22:54 -0700 (PDT)
Subject: [Tutor] Why won't it enter the quiz?
In-Reply-To: <BAY106-DAV1421EAFD708B3036F26145C4900@phx.gbl>
Message-ID: <Pine.LNX.4.44.0509171308530.1905-100000@hkn.eecs.berkeley.edu>



On Sat, 17 Sep 2005, Nathan Pinno wrote:

> I can see that I was wrong. I was tired, and I don't always think too
> smart.  It should be cq <= q. :)

Hi Nathan,


Yes.

Here are some general tips about debugging while loops.  If we have a
while loop:

    while some_condition:
        ...

and if we're not entering the loop at all, we should pay particular
attention to 'some_condition', because it's either backwards or checking
the wrong thing.

One technique that's often use is to "log" the variables used in a while
loop, at least temporarily while we're trying to figure out what's going
on in the code.  For example, we might want to do something like:

    print "About to enter the loop"
    print "cq ==", cq
    print "q ==", q
    print "cq <= q", cq <= q
    while cq <= q:
        ...

The idea is that we can temporarily make the program do a bit more than
what it should: we add some debugging scaffolding code.  Just as buildings
that are being constructed have supports to keep them up, we often write
additional log statements in our programs to give us debuggging
information.  It's a little cheezy sometimes, but it's surprisingly
effective.

A more rigorous way of adding this scaffold is to use an "assertion".  We
can talk about assertions if you'd like.


Symmetrically, if we have:

    while some_condition:
        ## body

and if we never get out of the while loop ever (infinite loop), we need to
look at some_condition, and ask ourselves: does anything in the body make
it possible for some_condition to be False?


I'm trying to point out that there are things that you can do to figure
out why programs don't work: those techniques are just as valuable ---
perhaps more so --- than actually writing the program.


Good luck!


From dyoo at hkn.eecs.berkeley.edu  Sat Sep 17 22:32:28 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 17 Sep 2005 13:32:28 -0700 (PDT)
Subject: [Tutor] MySQLdb error - PLEASE SAVE ME!
In-Reply-To: <d1bf1fa2050917125923cd617c@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509171303350.1905-100000@hkn.eecs.berkeley.edu>



On Sat, 17 Sep 2005, Ed Hotchkiss wrote:

> Ok. I am trying to read a csv file with three strings separated by
> commas. I am trying to insert them into a MySQL DB online. MySQLdb is
> installed, no problems.
>
> I think that I am having some kind of error with my csv going into the
> fields and being broken apart correctly.

Hi Ed,

Can you show us what error you're seeing?  Maybe it is related to the csv
splitting... Then again, maybe it isn't.  *grin*

If you have an error message, then it'll be good to show that to us on the
list, because then we can try to help you interpret the error message.
That way, next time you seem a similar error, you might have a better idea
what the system's trying to tell you.


Let's look at some of the code.

######
arr=[]
inp = open ("sites1.txt","r")
#read line into array
for line in inp.readlines():
    links = map(str, line.split(","))
    arr.append(links)
    cursor.execute ("""
        INSERT INTO links (Name, URL, category)
       VALUES (%s, %s, %s)""" % tuple(links[0:3])
    )
######

Ok, I see it.  I'll focus on the cursor execute() bug, but there's
possibly another one: if the sites1.txt file has lines that don't contain
two commas, then it won't be valid to try to process the data on an
incomplete line.  You may want to do a check to warn and skip such broken
lines.


Try to avoid doing direct string formatting when you're working with
databases: let the database do it for you.  cursor.execute() can take in
an additional tuple argument of values, which it'll use to fill in the
'%s' placeholders in the SQL.

So rather than:

    cursor.execute ("""
        INSERT INTO links (Name, URL, category)
       VALUES (%s, %s, %s)""" % tuple(links[0:3])
    )

Do this instead:

    cursor.execute ("""
        INSERT INTO links (Name, URL, category)
       VALUES (%s, %s, %s)""", tuple(links[0:3])
    )

The reason this is important is because SQL uses a different set of rules
for string quotation than Python, and it's really easy to mess it up.

This is one of those things that everyone gets mixed up about.  See the
thread on 'escape-quoting strings' here:

    http://mail.python.org/pipermail/tutor/2004-November/032943.html

and read that thread for more details on using cursor.execute() with that
second argument.


Best of wishes to you!


From kent37 at tds.net  Sat Sep 17 22:47:29 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 17 Sep 2005 16:47:29 -0400
Subject: [Tutor] Multiple buttons, One callback (fwd)
In-Reply-To: <Pine.LNX.4.44.0509171256530.1905-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509171256530.1905-100000@hkn.eecs.berkeley.edu>
Message-ID: <432C80E1.50109@tds.net>

Danny Yoo wrote:
>>make_callback() is a function that returns a "thunk" callback.  That
>>returned thunk doesn't take an argument, so it's perfectly appropriate as
>>a button callback.

Danny,

Can you explain the term 'thunk'? I'm not familiar with it and the definitions I can find don't make sense in this context.

Thanks,
Kent


From python at venix.com  Sat Sep 17 23:02:16 2005
From: python at venix.com (Python)
Date: Sat, 17 Sep 2005 17:02:16 -0400
Subject: [Tutor] MySQLdb error - PLEASE SAVE ME!
Message-ID: <1126990936.16852.117.camel@www.venix.com>

You should avoid sending the connection info to the list.  Google will
be making this widely available.  Pranksters *will* delete your tables.
Change your password!

Including the error info would help, but chances the following changes
will fix things:

stmt = """CREATE TABLE links (
    ID INT NOT NULL auto_increment,
                    ^^^^^^^^^^^^^^
    Name TEXT,
    URL LONGTEXT,
    Category LONGTEXT,
    primary key (ID)
)"""


for line in inp.readlines():
    #links = map(str, line.split(","))	# values are already strings
    links = line.split(",",2)	# limit to two splits i.e. only use first 2 commas
    arr.append(links)		# arr is not used ???
    cursor.execute ("""
        INSERT INTO links (Name, URL, category)
            VALUES (%s, %s, %s)""", links
        )

You are not supplying an ID value.  I assume that you want MySQL to fill
it in for you.  So you need to make ID an auto_increment field.

The cursor.execute is now getting *two* arguments, the sql and the
values for the insert.  Do not interpolate your values into the SQL
string.  Leave that to the MySQLdb module.  The %s in the VALUES serves
as a placeholder for the module and should not be used by you with the
Python string format (%) operator.  This should work so long as the name
and URL never contain commas.

-- 
Lloyd Kvam
Venix Corp


From edhotchkiss at gmail.com  Sat Sep 17 23:11:36 2005
From: edhotchkiss at gmail.com (Ed Hotchkiss)
Date: Sat, 17 Sep 2005 17:11:36 -0400
Subject: [Tutor] MySQLdb error - PLEASE SAVE ME!
In-Reply-To: <1126990936.16852.117.camel@www.venix.com>
References: <1126990936.16852.117.camel@www.venix.com>
Message-ID: <d1bf1fa2050917141132c42fb6@mail.gmail.com>

I got the mysql db just for this very purpose, that's it :P
Ok heres the error which I am getting now, I dont see why your new code 
shouldn't work, it makes sense to me ...
  >>> 
Traceback (most recent call last):
File "G:\Python\myCode\Links Database\addfromtext.py", line 30, in ?
cursor.execute ("""
File "C:\Python24\Lib\site-packages\MySQLdb\cursors.py", line 129, in 
execute
self.errorhandler(self, ProgrammingError, m.args[0])
File "C:\Python24\Lib\site-packages\MySQLdb\connections.py", line 33, in 
defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: not enough arguments for format string
>>> 
  heres the new code ...
   

# Script to add links from a comma deliminated file to a MySQL database
# 9/16/05

import MySQLdb

conn=MySQLdb.connect( host="www.freesql.org <http://www.freesql.org/>",
user="edhotchkiss",
port=3306,
passwd="test1",
db="links")

cursor = conn.cursor()
stmt = "DROP TABLE IF EXISTS links"
cursor.execute(stmt)
stmt = """CREATE TABLE links (
ID INT NOT NULL auto_increment,
Name TEXT,
URL LONGTEXT,
Category LONGTEXT,
primary key (ID)
)"""
cursor.execute(stmt)


inp = open ("sites.txt","r")
for line in inp.readlines():
#links = map(str, line.split(",")) # values are already strings
links = line.split(",",2) # limit to two splits i.e. only use first 2 commas
cursor.execute ("""
INSERT INTO links (Name, URL, category)
VALUES (%s, %s, %s)""", links
)

cursor.close()
conn.close()

   

   

 On 9/17/05, Python <python at venix.com> wrote: 
> 
> You should avoid sending the connection info to the list. Google will
> be making this widely available. Pranksters *will* delete your tables.
> Change your password!
> 
> Including the error info would help, but chances the following changes
> will fix things:
> 
> stmt = """CREATE TABLE links (
> ID INT NOT NULL auto_increment,
> ^^^^^^^^^^^^^^
> Name TEXT,
> URL LONGTEXT,
> Category LONGTEXT,
> primary key (ID)
> )"""
> 
> 
> for line in inp.readlines():
> #links = map(str, line.split(",")) # values are already strings
> links = line.split(",",2) # limit to two splits i.e. only use first 2 
> commas
> arr.append(links) # arr is not used ???
> cursor.execute ("""
> INSERT INTO links (Name, URL, category)
> VALUES (%s, %s, %s)""", links
> )
> 
> You are not supplying an ID value. I assume that you want MySQL to fill
> it in for you. So you need to make ID an auto_increment field.
> 
> The cursor.execute is now getting *two* arguments, the sql and the
> values for the insert. Do not interpolate your values into the SQL
> string. Leave that to the MySQLdb module. The %s in the VALUES serves
> as a placeholder for the module and should not be used by you with the
> Python string format (%) operator. This should work so long as the name
> and URL never contain commas.
> 
> --
> Lloyd Kvam
> Venix Corp
> 
> 


-- 
edward hotchkiss
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050917/7b09db36/attachment.htm

From ismaelgf at adinet.com.uy  Sat Sep 17 23:57:15 2005
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Sat, 17 Sep 2005 18:57:15 -0300
Subject: [Tutor] GetGarf (sorry, this time with attachment)
In-Reply-To: <432C2DC2.8070503@gmail.com>
References: <mailman.1502.1126932711.508.tutor@python.org>
	<432C2DC2.8070503@gmail.com>
Message-ID: <432C913B.20907@adinet.com.uy>

Joseph Quigley wrote:

>Ismael wrote:
>
>  
>
>>Do you know about Dosage? It downloads lots of comics (around 500 - of 
>>course, you choose which ones). Among those, there's Garfield. It's 
>>"catchup" option will download past comics for you, and even generate 
>>RSS feeds and html pages if you wish to.
>>
>>http://slipgate.za.net/dosage/
>>
>>Ismael
>>
>>    
>>
>No I didn't.. is is free? If so then great! Just what I was looking for.
>
>  
>
Free and written in Python :)

There's also dailystrips, phpGrabComics, ComicView, and a few more, I 
think. They all perform similiar tasks.

Ismael

From alan.gauld at freenet.co.uk  Sun Sep 18 00:26:12 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Sat, 17 Sep 2005 23:26:12 +0100
Subject: [Tutor] Why won't it enter the quiz? (off topic)
References: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>	<432B795E.50804@christianfreebies.com>	<432B8503.7080508@pooryorick.com><432B8BCC.7030101@christianfreebies.com><432B8FBC.7090304@pooryorick.com><00a501c5bb66$a96ae360$0201a8c0@xp>
	<432C377E.3070009@pooryorick.com>
Message-ID: <010801c5bbd6$cf8284c0$0201a8c0@xp>

>> Technically there may be something wrong in that if he is
>> claiming copyright and selling for commerxcial gain rather
> Then I recommend that Byron and anyone else interested in 
> this stuff go browse http://www.benedict.com/ 

Interesting site, thanks for pointing it out.

> instead posting off-topic commentaries about people who 
> turn to the list with questions.

Is it off topic on a newbie programming list to discuss the 
ramifications of trying to sell software? Learning to program 
is one thing. Trying to make a professional career out of 
it is another and requires additional knowledge. Any newbie 
about to embark on such a course should be made aware of 
the potential pitfalls. 

That's not to discourage said individual from the commercial 
venture nor from asking questions. I'd liken it to the stand 
we take on giving out homework answers, it's in the 
individual's own interests to maximise their own input.

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




From alan.gauld at freenet.co.uk  Sun Sep 18 00:31:15 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Sat, 17 Sep 2005 23:31:15 +0100
Subject: [Tutor] Multiple buttons, One callback (fwd)
References: <Pine.LNX.4.44.0509171256530.1905-100000@hkn.eecs.berkeley.edu>
Message-ID: <011a01c5bbd7$84422fa0$0201a8c0@xp>

> creates the thunk callback and returns it.  This returned thunk 
> callback
> (is that a technical term or one of your own, by the way?)

I'm not sure Danny is using it in the same way but
I first came across the term thunk in the Win32 API.
Microsoft used thunks to bridge between the new Win32 API
and the older 16 bit Win 3 API.

Why 'thunk' I do not know but the term seems to have stuck long
after everyone stopped using Win32 thunks...

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


From python at venix.com  Sun Sep 18 00:53:41 2005
From: python at venix.com (Python)
Date: Sat, 17 Sep 2005 18:53:41 -0400
Subject: [Tutor] MySQLdb error - PLEASE SAVE ME
Message-ID: <1126997621.16852.128.camel@www.venix.com>

> I dont see why your new code shouldn't work, it makes sense to me ...

Danny nailed this one.  He warned that your data could be short commas.
You have lines with fewer than two commas.  The INSERT is failing with:
	not enough arguments

Simple fix is to skip insert if len(links) != 3.

Note that we can't test without your data.  Generally, it is better to
keep the responsibility for testing in your hands and simply provide the
error info and the background context.

(Didn't mean to panic about the password, BUT I know folks who've
learned the hard way that Google sees a lot more than you might expect,
and pranksters really will drop your tables.)

-- 
Lloyd Kvam
Venix Corp


From carroll at tjc.com  Sun Sep 18 01:04:08 2005
From: carroll at tjc.com (Terry Carroll)
Date: Sat, 17 Sep 2005 16:04:08 -0700 (PDT)
Subject: [Tutor] MySQLdb error - PLEASE SAVE ME!
In-Reply-To: <d1bf1fa2050917125923cd617c@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509171603210.25287-100000@violet.rahul.net>

On Sat, 17 Sep 2005, Ed Hotchkiss wrote:

> I think that I am having some kind of error with my csv going into the
> fields and being broken apart correctly.

Ed, I'd suggest using the CSV module to parse out CSV files, rather than 
splitting it yourself.


From dyoo at hkn.eecs.berkeley.edu  Sun Sep 18 03:09:05 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 17 Sep 2005 18:09:05 -0700 (PDT)
Subject: [Tutor] Multiple buttons, One callback (fwd)
In-Reply-To: <Pine.LNX.4.44.0509171256530.1905-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0509171740550.15733-100000@hkn.eecs.berkeley.edu>


> So, just to see if I understand you, I can create a function that
> creates the thunk callback and returns it.  This returned thunk callback
> (is that a technical term or one of your own, by the way?) can then be
> bound as the button's call back and will be able to remember the
> parameters passed to the thunker -- the function creating the thunk
> callbacks.

Hi Dash,

Like most technical words, "thunk" is overloaded, and it has several
meanings, depending on who you're talking to.

I'm using the definition from the Lisp tradition: in the Lisp programming
language, a "thunk" is a function that doesn't take arguments.

    http://en.wikipedia.org/wiki/Thunk#Thunk_.28Lisp.29


(Confessional aside: I've been learning how to programming in the PLT
Scheme language recently, and I'm starting to absorb more and more of the
terminology into myself.  In the PLT documentation, they use the word
"thunk" all the time.  I apologize if this is making things confusing, but
I really have no control over this.  *grin*)


But anyway, going back to that example code,

######
>>> def make_msg_thunk(msg):
...     def thunk():
...         print msg
...     return thunk
...
>>> msg_callbacks = [make_msg_thunk(m)
...                  for m in ('hello', 'happy', 'world')]
>>>
>>> msg_callbacks
[<function thunk at 0x403a610c>, <function thunk at 0x403a6bc4>, <function
thunk at 0x403a6bfc>]
>>> msg_callbacks[0]()
hello
>>> msg_callbacks[1]()
happy
>>> msg_callbacks[2]()
world
######


We're taking advantage of a feature called "lexical scope": the thunk
function is physically nested and defined where it can see 'msg'.  By
taking advantage of this lexical scoping feature, we have a very
lightweight way of building custom callback functions.


Hope this helps!


From list at ohtogo.com  Sun Sep 18 16:18:08 2005
From: list at ohtogo.com (List)
Date: Sun, 18 Sep 2005 07:18:08 -0700
Subject: [Tutor] How do you organize code snippets?
Message-ID: <e2214c3f4fd0447fbfa5c8f8872e48e7@ohtogo.com>

The subject pretty much says it. I tend to clip and save snippets from various lists for later reference. I save each in a separate text file more or less named appropriately (or so I think at the time), but I've ended up with a mess of files in a snippets directory and I can't always remember what is what. Is there a better way of tracking code snippets? Is there a way of naming or organizing snippets that might help? (For example, file i/o snippets, text processing snippets, etc.)

 TIA,
 Trey

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

From cpu.crazy at gmail.com  Sun Sep 18 16:35:10 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Sun, 18 Sep 2005 08:35:10 -0600
Subject: [Tutor] IRC Client Trouble -- too many new lines
Message-ID: <432D7B1E.5080800@gmail.com>

Hi,
My IRC Client can't print the IRC server messages without a newline for 
each message in a giant list that I recieve...
here's my code:

import socket, string, sys

#some user data, change as per your taste
class Data:
    SERVER = 'irc.freenode.net'
    CHANNEL = "#python"
    NICKNAME = "Pythonatic"
    PORT = 6667
    #open a socket to handle the connection
    IRC = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#open a connection with the server
def Irc_Conn():
    print "Connecting to IRC server (%s)." % (Data.SERVER)
    try:
        Data.IRC.connect((Data.SERVER, Data.PORT))
    except socket.gaierror:
        print """Error: Name or service not known.

This could mean that you aren't connected to the internet or that
the server is down."""
        raise SystemExit

#simple function to send data through the socket
def Send_Data(command):
    Data.IRC.send(command + '\n')

#join the channel
def Join(channel):
    Send_Data("JOIN %s" % channel)

#send login data (customizable)
def Login(nickname, username='user', password = None, realname='You 
don\'t need2know', hostname='Slackware', servername='Intelnett'):
    Send_Data("USER %s %s %s %s" % (username, hostname, servername, 
realname))
    Send_Data("NICK " + NICKNAME)

Irc_Conn()
Login(Data.NICKNAME)
Join(Data.CHANNEL)

while (1):
    buffer = Data.IRC.recv(1024)
    msg = string.split(buffer)
    if msg[0] == "PING": #check if server have sent ping command
        Send_Data("PONG %s" % msg[1]) #answer with pong as per RFC 1459
    if msg[1] == 'PRIVMSG' and msg[2] == Data.NICKNAME:
        filetxt = open('%stmp' % (Data.configFileRead[8]), 'a+') #open 
an arbitrary file to store the messages
        nick_name = msg[0][:string.find(msg[0],"!")] #if a private 
message is sent to you catch it
        message = ' '.join(msg[3:])
        filetxt.write(string.lstrip(nick_name, ':') + ' -> ' + 
string.lstrip(message, ':') + '\n') #write to the file
        filetxt.flush() #don't wait for next message, write it now!
    if msg:
        msg_length = len(msg)
        print_msg = 0
        while True:
            if print_msg == msg_length:
                break
            else:
                print msg[print_msg]
                print_msg = print_msg + 1
                continue

Thanks,
Joe

From darnold992000 at yahoo.com  Sun Sep 18 17:17:39 2005
From: darnold992000 at yahoo.com (Don Arnold)
Date: Sun, 18 Sep 2005 08:17:39 -0700 (PDT)
Subject: [Tutor] Fwd: Re:  How do you organize code snippets?
Message-ID: <20050918151740.26624.qmail@web80905.mail.scd.yahoo.com>


Note: forwarded message attached.



		
__________________________________ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com
-------------- next part --------------
An embedded message was scrubbed...
From: Don Arnold <darnold992000 at yahoo.com>
Subject: Re: [Tutor] How do you organize code snippets?
Date: Sun, 18 Sep 2005 08:13:45 -0700 (PDT)
Size: 1449
Url: http://mail.python.org/pipermail/tutor/attachments/20050918/b1666742/attachment.mht

From marcink at ieee.org  Sun Sep 18 19:20:12 2005
From: marcink at ieee.org (Marcin Komorowski)
Date: Sun, 18 Sep 2005 13:20:12 -0400
Subject: [Tutor] Iterating over sorted dictionary keys in one line
Message-ID: <002101c5bc75$3ac2af00$6571a8c0@zobook>

I know that one of the ways to iterate over sorted dictionary keys is:
    keylist = dictionary.keys()
    keylist.sort()
    for key in keylist:
        ...

Is there a way to do this in a single line.  Something like this would be ideal:
    for key in dictionary.keys().soft():
        ...

But this gives me following error:
  Traceback (most recent call last):
    File "<interactive input>", line 1, in ?
  TypeError: iteration over non-sequence
I am guessing that this is because the sort method operates on a list in place and simply returns the 'None' value.  Is there a way to do this in Python?

Thanks,
Marcin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050918/70ea7f17/attachment.html

From tutor.python.org at pooryorick.com  Sun Sep 18 19:28:10 2005
From: tutor.python.org at pooryorick.com (Poor Yorick)
Date: Sun, 18 Sep 2005 13:28:10 -0400
Subject: [Tutor] How do you organize code snippets?
In-Reply-To: <e2214c3f4fd0447fbfa5c8f8872e48e7@ohtogo.com>
References: <e2214c3f4fd0447fbfa5c8f8872e48e7@ohtogo.com>
Message-ID: <432DA3AA.9020102@pooryorick.com>

List wrote:

> Is there a way of naming or organizing snippets that might help? (For 
> example, file i/o snippets, text processing snippets, etc.)
> 

If you really want to have fun, you can use LEO, http://webpages.charter.net/edreamleo/front.html to store your code snippets and generate files from them.  The fun part is that you can clone each node which may contain some code and move the clone to a different point in the hierarchy.  When you change your code in any of the clones, it gets changed in all of the clones.  At the most basic level, you can use LEO as on outliner, like Treepad.  If you decide to get more complicated, you can use LEO as a templating tool to generate your resulting .py files from your snippets.

--
Poor Yorick

From kent37 at tds.net  Sun Sep 18 19:30:04 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 18 Sep 2005 13:30:04 -0400
Subject: [Tutor] Iterating over sorted dictionary keys in one line
In-Reply-To: <002101c5bc75$3ac2af00$6571a8c0@zobook>
References: <002101c5bc75$3ac2af00$6571a8c0@zobook>
Message-ID: <432DA41C.9040602@tds.net>

Marcin Komorowski wrote:
> I know that one of the ways to iterate over sorted dictionary keys is:
>     keylist = dictionary.keys()
>     keylist.sort()
>     for key in keylist:
>         ...
>  
> Is there a way to do this in a single line.  Something like this would 
> be ideal:
>     for key in dictionary.keys().soft():

Python 2.4 adds the sorted() function which returns a sorted copy of a list. You can say
for key in sorted(dictionary.keys()):

and since iterating a dictionary is the same as iterating its keys you can shorten this to
for key in sorted(dictionary):

Kent


From Pawel_Kraszewski at wp.pl  Sun Sep 18 19:40:11 2005
From: Pawel_Kraszewski at wp.pl (Pawel Kraszewski)
Date: Sun, 18 Sep 2005 19:40:11 +0200
Subject: [Tutor] Iterating over sorted dictionary keys in one line
In-Reply-To: <002101c5bc75$3ac2af00$6571a8c0@zobook>
References: <002101c5bc75$3ac2af00$6571a8c0@zobook>
Message-ID: <200509181940.11496.Pawel_Kraszewski@wp.pl>

Dnia niedziela, 18 wrze?nia 2005 19:20, Marcin Komorowski napisa?:

> I know that one of the ways to iterate over sorted dictionary keys is:
>     keylist = dictionary.keys()
>     keylist.sort()
>     for key in keylist:
>         ...

Indeed, 'sort' sorts its argument in-place and returns 'none'. Bur Python 2.4+ 
has a new thing: 'sorted'. This leaves its argument intact and returns a 
sorted copy.

for mykey in sorted(dictionary.keys()):
	# things to do


See this:

Python 2.4.1 (#1, Jun 19 2005, 01:02:56)
[GCC 3.4.4 (Gentoo 3.4.4, ssp-3.4.4-1.0, pie-8.7.8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [4,3,2,1]
>>> print sorted(a) # "sorted" FUNCTION returns sorted list
[1, 2, 3, 4]
>>> a # and original list remains unchanged
[4, 3, 2, 1]
>>> print a.sort() # "sort" METHOD returns nothing
None
>>> a # instead it changes (sorts) its argument
[1, 2, 3, 4]
>>>



Best regards

-- 
 Pawel Kraszewski

From nephish at xit.net  Sun Sep 18 23:29:13 2005
From: nephish at xit.net (nephish)
Date: Sun, 18 Sep 2005 16:29:13 -0500
Subject: [Tutor] pychart and debian
Message-ID: <432DDC29.5020602@xit.net>

Hey there,
anyone have luck getting pychart installed on debian ?
there is no debian package for it (that i have found thus far)
and i need something that will allow me to place some
simple x, y plots on a chart in pygtk.

if any of you have a better solution, i am not completely sold out to
pychart. i know that there are others out there.

thanks
sk


From john at fouhy.net  Mon Sep 19 00:13:50 2005
From: john at fouhy.net (John Fouhy)
Date: Mon, 19 Sep 2005 10:13:50 +1200
Subject: [Tutor] Iterating over sorted dictionary keys in one line
In-Reply-To: <002101c5bc75$3ac2af00$6571a8c0@zobook>
References: <002101c5bc75$3ac2af00$6571a8c0@zobook>
Message-ID: <5e58f2e40509181513497eed51@mail.gmail.com>

On 19/09/05, Marcin Komorowski <marcink at ieee.org> wrote:
> Is there a way to do this in a single line.  Something like this would be
> ideal: 
>     for key in dictionary.keys().soft(): 

Hi Marcin,

Others have already answered you, but just to follow up:

There is a reason why lst.sort() returns None: When you call .sort()
on a list, you are changing the original list.  If you happened to
have a reference to that list somewhere else in your program, sorting
it could cause unexpected behaviour.  So, python deliberately prevents
you from being able to type "for item in lst.sort()" as a reminder
that there are side-effects that you need to be wary of.

On the other hand, the new sorted() function creates a sorted copy, so
it doesn't matter (but you should be aware of the extra memory
requirements if you have big lists).

-- 
John.

From bgailer at alum.rpi.edu  Mon Sep 19 00:33:43 2005
From: bgailer at alum.rpi.edu (bob)
Date: Sun, 18 Sep 2005 15:33:43 -0700
Subject: [Tutor] Iterating over sorted dictionary keys in one line
In-Reply-To: <432DA41C.9040602@tds.net>
References: <002101c5bc75$3ac2af00$6571a8c0@zobook> <432DA41C.9040602@tds.net>
Message-ID: <6.1.2.0.0.20050918152306.03507130@mail.mric.net>

At 10:30 AM 9/18/2005, Kent Johnson wrote:
>Marcin Komorowski wrote:
> > I know that one of the ways to iterate over sorted dictionary keys is:
> >     keylist = dictionary.keys()
> >     keylist.sort()
> >     for key in keylist:
> >         ...
> >
> > Is there a way to do this in a single line.  Something like this would
> > be ideal:
> >     for key in dictionary.keys().soft():
>
>Python 2.4 adds the sorted() function which returns a sorted copy of a 
>list. You can say
>for key in sorted(dictionary.keys()):

To be more precise - sorted() operates on any iterable and returns a list.

>and since iterating a dictionary is the same as iterating its keys you can 
>shorten this to
>for key in sorted(dictionary):
>
>Kent
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor


From edhotchkiss at gmail.com  Sun Sep 18 22:35:02 2005
From: edhotchkiss at gmail.com (Ed Hotchkiss)
Date: Sun, 18 Sep 2005 16:35:02 -0400
Subject: [Tutor] Best Encryption for Python Client/Server
Message-ID: <d1bf1fa20509181335391fa4b8@mail.gmail.com>

Let us say that I am trying to create a very small and simple private 
network/connection between several scripts on different machines, to 
communicate instructions/data/files etc. to each other over the net. Is SSL 
the best method? Any recommendations of something to get started with? 
Thanks in advance.

-- 
Edward hotchkiss
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050918/850bf405/attachment.html

From edhotchkiss at gmail.com  Sun Sep 18 23:53:40 2005
From: edhotchkiss at gmail.com (Ed Hotchkiss)
Date: Sun, 18 Sep 2005 17:53:40 -0400
Subject: [Tutor] tuples and mysqldb tables
Message-ID: <d1bf1fa205091814531008ca4@mail.gmail.com>

I have used fetchall() to insert the values from a table into a tuple. 
anywhere from 0 - ? many rows could be in this tuple, so it is a row within 
a row. How do I use a loops to iterate through the nested tuple, and assign 
the tuples integers and strings to variables, ugh :P
 The Tables data is like this: 
 
+---------------------------------------------------------------------------------------------------------------------+
| ID (INT) | Protocol (TEXT) | Name (LONGTEXT) Description (LONGTEXT) | 
+---------------------------------------------------------------------------------------------------------------------+
   
 import MySQLdb

import sys

 # find out what this ports function is ----

def grabPortInfo(port):

try:

conn=MySQLdb.connect( host="www.freesql.org <http://www.freesql.org>",

user="portnumbers",

port=3306,

passwd="*********",

db="portnumbers")

except MySQLdb.Error, e: 

print "Error %d: %s" % (e.args[0], e.args[1]) 

print "\n\n WTF!? - portnumbers MySQL DB didn't open"

sys.exit (1)

# ------------------

cursor = conn.cursor()

stmt = "SELECT * FROM portnumbers WHERE port=%i" %port

cursor.execute(stmt)

numrows = int(cursor.rowcount)

if numrows == 0:

print "port # not found in database"

elif numrows >= 1:

result = cursor.fetchall()

print len(result)

# break tuple into strings with output 

myPort = port

myProtocol = result[0|3]

myName = result[0|4]

myDescription = result[0|5]

print "PORT # | PROTOCOL | PORT NAME | PORT DESCRIPTION "

print myPort, myProtocol, myName, myDescription

cursor.close()

conn.close()

# end function -------------

 grabPortInfo(22)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050918/e4fc233b/attachment.htm

From dyoo at hkn.eecs.berkeley.edu  Mon Sep 19 01:11:03 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 18 Sep 2005 16:11:03 -0700 (PDT)
Subject: [Tutor] How do you organize code snippets?
In-Reply-To: <e2214c3f4fd0447fbfa5c8f8872e48e7@ohtogo.com>
Message-ID: <Pine.LNX.4.44.0509181604370.28898-100000@hkn.eecs.berkeley.edu>



On Sun, 18 Sep 2005, List wrote:

> The subject pretty much says it. I tend to clip and save snippets from
> various lists for later reference. I save each in a separate text file
> more or less named appropriately (or so I think at the time), but I've
> ended up with a mess of files in a snippets directory and I can't always
> remember what is what. Is there a better way of tracking code snippets?
> Is there a way of naming or organizing snippets that might help? (For
> example, file i/o snippets, text processing snippets, etc.)

Hi Trey,

The Python Cookbook tries to attack this problem,

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

and its approach to this has been to put such snippets in a central
database, and to use both categories and a search engine to maintain
order.

If you run across snippets that have come in handy for yourself, it might
be good to put them in the Cookbook.  Using a personal database
application is also practical, but if you can enter them into the Python
Cookbook as well, then others may find them of value.


Best of wishes to you!


From dyoo at hkn.eecs.berkeley.edu  Mon Sep 19 01:16:51 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 18 Sep 2005 16:16:51 -0700 (PDT)
Subject: [Tutor] pychart and debian
In-Reply-To: <432DDC29.5020602@xit.net>
Message-ID: <Pine.LNX.4.44.0509181611450.28898-100000@hkn.eecs.berkeley.edu>



On Sun, 18 Sep 2005, nephish wrote:

> anyone have luck getting pychart installed on debian ? there is no
> debian package for it (that i have found thus far) and i need something
> that will allow me to place some simple x, y plots on a chart in pygtk.

Hi sk,

Ah, found it.  It's in the 'testing' and 'unstable' branches in Debian:

    http://packages.qa.debian.org/p/python-pychart.html
    http://packages.debian.org/unstable/python/python2.3-pychart

If you're running 'stable', you may want to ask the Debian folks how easy
it is to grab it from 'testing' and install it.

If you install pychart from source, doing 'python setup.py install' should
be sufficient, as long as you have ghostscript installed on your system.


Best of wishes to you!


From dyoo at hkn.eecs.berkeley.edu  Mon Sep 19 01:32:38 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 18 Sep 2005 16:32:38 -0700 (PDT)
Subject: [Tutor] tuples and mysqldb tables
In-Reply-To: <d1bf1fa205091814531008ca4@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509181619550.28898-100000@hkn.eecs.berkeley.edu>



Hi Ed,


Let's look at one of your questions:

> How do I use a loops to iterate through the nested tuple

Let's separate this apart from the SQL stuff for the moment.  Are you
familiar with Python's for loop, and how it can work on sequences?  For
example:

######
>>> authors = ['fowler', 'lau', 'gamma', 'helm', 'johnson', 'vlissides']
>>> for a in authors:
...     print "hello", a
...
hello fowler
hello lau
hello gamma
hello helm
hello johnson
hello vlissides
######


Looping across a sequence works regardless of what the elements are, so
that means we can also do this iteration if the elements themselves are
lists:

######
>>> random_numbers = [[3, 1, 4], [1, 5, 9], [2, 6]]
>>> for row in random_numbers:
...     print row
...
[3, 1, 4]
[1, 5, 9]
[2, 6]
######


Does this help answer your question?


I'm getting a feeling that some of the questions you have actually don't
have anything to do with MySQLdb really; instead, it feels like your
questions are really about basic concepts.

Have you already gone through a tutorial like the ones linked from the
Beginner's Guide here?

    http://wiki.python.org/moin/BeginnersGuide

If not, you may want to go through one of them: it'll should help you in
the long run.  Feel free to ask questions here.


Good luck to you!


From dyoo at hkn.eecs.berkeley.edu  Mon Sep 19 01:39:15 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 18 Sep 2005 16:39:15 -0700 (PDT)
Subject: [Tutor] Best Encryption for Python Client/Server
In-Reply-To: <d1bf1fa20509181335391fa4b8@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509181633570.28898-100000@hkn.eecs.berkeley.edu>



On Sun, 18 Sep 2005, Ed Hotchkiss wrote:

> Let us say that I am trying to create a very small and simple private
> network/connection between several scripts on different machines, to
> communicate instructions/data/files etc. to each other over the net. Is
> SSL the best method? Any recommendations of something to get started
> with?  Thanks in advance.

Hi Ed,

David Mertz has written a series of 'Network programming with the Twisted
framework' articles that you might be interested in, especially Part 4:

    http://www-128.ibm.com/developerworks/linux/library/l-twist4.html

And even if you're not going to use Twisted, the resources at the bottom
of that tutorial refer to background on SSL, and should be useful as
background information.  I'm not really knowledgable in this area, so I'm
hoping that the others on Tutor will be able to point you toward other
secure programming resources.

Good luck to you!


From nephish at xit.net  Mon Sep 19 02:03:43 2005
From: nephish at xit.net (nephish)
Date: Sun, 18 Sep 2005 19:03:43 -0500
Subject: [Tutor] pychart and debian
In-Reply-To: <Pine.LNX.4.44.0509181611450.28898-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509181611450.28898-100000@hkn.eecs.berkeley.edu>
Message-ID: <432E005F.3050705@xit.net>

Danny Yoo wrote:

>On Sun, 18 Sep 2005, nephish wrote:
>
>  
>
>>anyone have luck getting pychart installed on debian ? there is no
>>debian package for it (that i have found thus far) and i need something
>>that will allow me to place some simple x, y plots on a chart in pygtk.
>>    
>>
>
>Hi sk,
>
>Ah, found it.  It's in the 'testing' and 'unstable' branches in Debian:
>
>    http://packages.qa.debian.org/p/python-pychart.html
>    http://packages.debian.org/unstable/python/python2.3-pychart
>
>If you're running 'stable', you may want to ask the Debian folks how easy
>it is to grab it from 'testing' and install it.
>
>If you install pychart from source, doing 'python setup.py install' should
>be sufficient, as long as you have ghostscript installed on your system.
>
>
>Best of wishes to you!
>
>
>  
>
ok, got the package installed, but it seems to not be working, or the 
examples are messed up.
here is the source

from pychart import *
theme.get_options()
data = [["Jan", 10], ["Feb", 22], ["Mar", 30]]

ar = area.T(x_coord = category_coord.T(data, 0),
            y_range = (0, None),
            x_axis = axis.X(label="Month"),
            y_axis = axis.Y(label="Value"))
ar.add_plot(bar_plot.T(data = data, label = "Something"))
ar.draw()

and here is what i get when i run it.

from: can't read /var/mail/pychart
./categbar.py: line 16: syntax error near unexpected token `data'
./categbar.py: line 16: `data = [["Jan", 10], ["Feb", 22], ["Mar", 30]]'
nephish at bitsbam:~$

what do you think may be wrong?
thanks for your help with the package by the way

-sk

From edhotchkiss at gmail.com  Mon Sep 19 02:41:35 2005
From: edhotchkiss at gmail.com (Ed Hotchkiss)
Date: Sun, 18 Sep 2005 20:41:35 -0400
Subject: [Tutor] tuples and mysqldb tables
In-Reply-To: <Pine.LNX.4.44.0509181619550.28898-100000@hkn.eecs.berkeley.edu>
References: <d1bf1fa205091814531008ca4@mail.gmail.com>
	<Pine.LNX.4.44.0509181619550.28898-100000@hkn.eecs.berkeley.edu>
Message-ID: <d1bf1fa205091817411e9d1011@mail.gmail.com>

I was cheap and I skimmed through "programming python" then jumped off a 
cliff and went right into it with a ripped parachute. I did a tutorial today 
and I solved the problem. I'm having a problem with threads and sockets now 
... I wrote a lot of code for this and it should work based on my 
understanding of threads and threading in python. For some reason, the 
following code does not scan a block of IP's like I had thought that it 
should. also, no more basic questions, i promise :P
 Any ideas? (where local host equals your ip or whomever ...)
   
class scanThread(threading.Thread):
def run(self):
try:
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ss.connect((ip, port_counter))
print "%s | %d OPEN" % (ip, port_counter)
ss.close()
except: pass
# end class -------------------


def scan(ip, begin, end):
for port_counter in range(begin, end):
while threading < MAX_THREADS:
scanThread().start()
# end function -------------------


scan("localhost", 0, 10000)


 On 9/18/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote: 
> 
> 
> 
> Hi Ed,
> 
> 
> Let's look at one of your questions:
> 
> > How do I use a loops to iterate through the nested tuple
> 
> Let's separate this apart from the SQL stuff for the moment. Are you
> familiar with Python's for loop, and how it can work on sequences? For
> example:
> 
> ######
> >>> authors = ['fowler', 'lau', 'gamma', 'helm', 'johnson', 'vlissides']
> >>> for a in authors:
> ... print "hello", a
> ...
> hello fowler
> hello lau
> hello gamma
> hello helm
> hello johnson
> hello vlissides
> ######
> 
> 
> Looping across a sequence works regardless of what the elements are, so
> that means we can also do this iteration if the elements themselves are
> lists:
> 
> ######
> >>> random_numbers = [[3, 1, 4], [1, 5, 9], [2, 6]]
> >>> for row in random_numbers:
> ... print row
> ...
> [3, 1, 4]
> [1, 5, 9]
> [2, 6]
> ######
> 
> 
> Does this help answer your question?
> 
> 
> I'm getting a feeling that some of the questions you have actually don't
> have anything to do with MySQLdb really; instead, it feels like your
> questions are really about basic concepts.
> 
> Have you already gone through a tutorial like the ones linked from the
> Beginner's Guide here?
> 
> http://wiki.python.org/moin/BeginnersGuide
> 
> If not, you may want to go through one of them: it'll should help you in
> the long run. Feel free to ask questions here.
> 
> 
> Good luck to you!
> 
> 


-- 
edward hotchkiss
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050918/268a8120/attachment.html

From dyoo at hkn.eecs.berkeley.edu  Mon Sep 19 04:48:25 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 18 Sep 2005 19:48:25 -0700 (PDT)
Subject: [Tutor] pychart and debian
In-Reply-To: <432E005F.3050705@xit.net>
Message-ID: <Pine.LNX.4.44.0509181941200.19397-100000@hkn.eecs.berkeley.edu>

> ok, got the package installed, but it seems to not be working, or the
> examples are messed up.
> here is the source
>
> from pychart import *
> theme.get_options()
> data = [["Jan", 10], ["Feb", 22], ["Mar", 30]]
>
> ar = area.T(x_coord = category_coord.T(data, 0),
>             y_range = (0, None),
>             x_axis = axis.X(label="Month"),
>             y_axis = axis.Y(label="Value"))
> ar.add_plot(bar_plot.T(data = data, label = "Something"))
> ar.draw()
>
> and here is what i get when i run it.
>
> from: can't read /var/mail/pychart
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Ah!  You're running into an issue with your Unix environment, not Python.

Unix doesn't care about file names: without any hints, it'll think that
your program is a mere shell script.  The error message above means that
'/bin/sh' is trying to interpret your program.  That is, it's trying to
run the Unix 'from' command!

http://www.freebsd.org/cgi/man.cgi?query=from&apropos=0&sektion=0&manpath=FreeBSD+5.4-RELEASE+and+Ports&format=html

And the subsequent error messages are pretty much '/bin/sh' error
messages.


To avoid this problem, try:

    $ python categbar.py

Alternatively, make sure the first line in your Python program contains
the "magic" line:

    #!/usr/bin/env python

to tell the Unix (or Linux) kernel that the program you're running is
meant to be run through Python.


From dyoo at hkn.eecs.berkeley.edu  Mon Sep 19 05:03:13 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 18 Sep 2005 20:03:13 -0700 (PDT)
Subject: [Tutor] tuples and mysqldb tables
In-Reply-To: <d1bf1fa205091817411e9d1011@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509181949160.19397-100000@hkn.eecs.berkeley.edu>



> def run(self):
>     try:
>         ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>         ss.connect((ip, port_counter))
>         print "%s | %d OPEN" % (ip, port_counter)
>         ss.close()
>     except: pass
              ^^^^

Hi Ed,

Yikes.  Don't do that.  *grin*

By "that", I mean setting the exception handler here to do nothing.
Exception handling shouldn't abused to silence errors like that, at least,
not wholesale like that.  At the very least, while we're debugging this,
import the 'traceback' module and at least give a heads up, like this:

    except:
        traceback.print_exc()

Once this is in place, expect to see errors.  I know what you meant to do:
you wanted to ignore network errors, so try to make the exception handler
a little more specific in the exceptions it's trying to silence.

The problem here is that the handler has been inadvertantely silencing a
legitimate NameError.  From casual inspection, it's not clear what
'port_counter' is.  I suspect you want to add that as part of the thread's
state, in which case consider adding it within your thread's __init__
method.


> def scan(ip, begin, end):
>     for port_counter in range(begin, end):
>         while threading < MAX_THREADS:
>         scanThread().start()
> # end function -------------------


Ok, I definitely suspect port_counter now as the culprit here.  Make sure
you create each thread with port_counter as a part of each thread's state.


[Aside: are you trying to a port scanner in the style that Jacob Matthews
wrote about here?

    http://www.kuro5hin.org/story/2004/3/17/93442/8657

Just curious.]



Good luck to you!


From nephish at xit.net  Mon Sep 19 05:44:54 2005
From: nephish at xit.net (nephish)
Date: Sun, 18 Sep 2005 22:44:54 -0500
Subject: [Tutor] pychart and debian
In-Reply-To: <Pine.LNX.4.44.0509181941200.19397-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509181941200.19397-100000@hkn.eecs.berkeley.edu>
Message-ID: <432E3436.8030105@xit.net>

Danny Yoo wrote:

>>ok, got the package installed, but it seems to not be working, or the
>>examples are messed up.
>>here is the source
>>
>>from pychart import *
>>theme.get_options()
>>data = [["Jan", 10], ["Feb", 22], ["Mar", 30]]
>>
>>ar = area.T(x_coord = category_coord.T(data, 0),
>>            y_range = (0, None),
>>            x_axis = axis.X(label="Month"),
>>            y_axis = axis.Y(label="Value"))
>>ar.add_plot(bar_plot.T(data = data, label = "Something"))
>>ar.draw()
>>
>>and here is what i get when i run it.
>>
>>from: can't read /var/mail/pychart
>>    
>>
>  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>
>Ah!  You're running into an issue with your Unix environment, not Python.
>
>Unix doesn't care about file names: without any hints, it'll think that
>your program is a mere shell script.  The error message above means that
>'/bin/sh' is trying to interpret your program.  That is, it's trying to
>run the Unix 'from' command!
>
>http://www.freebsd.org/cgi/man.cgi?query=from&apropos=0&sektion=0&manpath=FreeBSD+5.4-RELEASE+and+Ports&format=html
>
>And the subsequent error messages are pretty much '/bin/sh' error
>messages.
>
>
>To avoid this problem, try:
>
>    $ python categbar.py
>
>Alternatively, make sure the first line in your Python program contains
>the "magic" line:
>
>    #!/usr/bin/env python
>
>to tell the Unix (or Linux) kernel that the program you're running is
>meant to be run through Python.
>
>
>  
>
yup, the examples did not have the #!/usr/bin/python line.
i have been at python for about 5 months now. How did i miss this?

thanks
sk

From grouch at gmail.com  Mon Sep 19 06:43:47 2005
From: grouch at gmail.com (grouchy)
Date: Sun, 18 Sep 2005 23:43:47 -0500
Subject: [Tutor] Any suggestions for optimizing this code?
Message-ID: <e6443aa705091821434d9ee478@mail.gmail.com>

Hello again!

I've been playing with generating 1-D cellular automata, and this is the 
fastest solution I've come up with so far. 

In the makeArray() function below, I have a sliding window of three elements 
starting at row[-1,0,1] and going to row[-2,-1,0], so that it wraps around 
at either boundary. I use the results of 4*row[i-1] + row[i] + row[i+1] to 
convert the three bits to an integer, and fetch a result from rule[index]. 
The inner loop is simple, and executes a million times, so shaving any time 
off makes a big difference. 

The biggest speedup from things I tried came from making an empty matrix 
first, to put results into the next row by index, instead of creating new 
rows on the fly with append. And binding the result[row] and result[row+1] 
references before the loop. Those two things sped it up by a consistentt 
40%. Thanks to Python in a Nutshell!

Does anybody see a faster approach, or a way to optimize the inner loop on 
makeArray() further? With the current approach, the inner loop does the real 
work, as it steps over each cell one at a time.

For anybody not familiar with cellular automatas, there is a pretty java 
animation of how cells get calculated here: 
http://math.hws.edu/xJava/CA/CA.html

And this is what CAs they look like when you plot them, with 1s as black and 
0s as white, and some additional info: 
http://mathworld.wolfram.com/Rule30.html

I've just hardcoded rule 30 into this for testing. I make a blank matrix 
with makeMatrix(). Then makeArray(matrix) sets the middle element of the 
first row in the matrix to 1 to seed the CA, and loops through it two rows 
at a time, calculating the results of the first row, and putting them into 
the next row. 

Right now I get:

>>> timeArray(5)
Total time: 3.95693028

I am uneasy with the algorithm getting each element one at a time, throwing 
them away, and getting two that overlap in the next step of the window, but 
I couldn't come up with a more elegant solution. Also, it seems like a 
kludgey way to convert the 3 bits into a binary number, but it was the 
fastest way I stumbled on to.

w = 1000
h = 1000
rule = [0,1,1,1,1,0,0,0]

def makeMatrix(w,h):
result = [0]*h
for i in range(h):
result[i] = [0]*w
return result

def makeArray(matrix):
result = matrix 
result[0][w/2] = 1

for row in range(h-1):
last = result[row]
next = result[row+1]
for i in range(w-1):
next[i] = rule[4*last[i-1]+2*last[i]+last[i+1]]
next[i+1] = rule[4*last[i]+2*last[i+1]+last[0]]
return result

def timeArray(num):
import time
matrix = makeMatrix(w,h)
t1 = time.clock()
for i in range(num):
makeArray(matrix) 
t2 = time.clock()
print "Total time:", t2 - t1

timeArray(5)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050918/bcf358ac/attachment.htm

From john at fouhy.net  Mon Sep 19 06:55:58 2005
From: john at fouhy.net (John Fouhy)
Date: Mon, 19 Sep 2005 16:55:58 +1200
Subject: [Tutor] Any suggestions for optimizing this code?
In-Reply-To: <e6443aa705091821434d9ee478@mail.gmail.com>
References: <e6443aa705091821434d9ee478@mail.gmail.com>
Message-ID: <5e58f2e4050918215562dfcbce@mail.gmail.com>

On 19/09/05, grouchy <grouch at gmail.com> wrote:
> I've been playing with generating 1-D cellular automata, and this is the
> fastest solution I've come up with so far. 

I haven't dug deep into your code --- but, I wonder if the array
module might help?

-- 
John.

From grouch at gmail.com  Mon Sep 19 07:16:36 2005
From: grouch at gmail.com (grouchy)
Date: Mon, 19 Sep 2005 00:16:36 -0500
Subject: [Tutor] Any suggestions for optimizing this code?
In-Reply-To: <5e58f2e4050918215562dfcbce@mail.gmail.com>
References: <e6443aa705091821434d9ee478@mail.gmail.com>
	<5e58f2e4050918215562dfcbce@mail.gmail.com>
Message-ID: <e6443aa705091822162d89c6d@mail.gmail.com>

Hi John,

Thanks for that suggestion.

I tried replacing my matrix with a numpy array, and it was about 20% slower, 
but I just substituted one for the other, so that really isn't surprising. I 
didn't try with the built-in array, but I'm guessing that swapping out 
another container for lists would only have a chance of speeding it up by a 
constant amount, I think, since setting and getting list elements is O(1).

Having said that, I forgot arrays existed. I will take a look right now, and 
look at their methods, see if there is anything in there I can dig up to 
help above and beyond a new container.

I think, conceptually, I need to make the sliding window more efficient by 
not getting overlapping elements repeatedly, or maybe figuring out a way to 
skip the conversion from bits to integers. I tried storing as strings, and 
doing a join to get i.e. "110" and using that as a key to look up 1 or 0, 
but it was miserably slow :)

The ~15x speedup from psyco makes me think if there was a built-in function 
that could handle everything in one fell swoop with tight C code, that would 
probably speed it up a -lot-. But I haven't found anything like that for a 
sliding window type situation.


On 9/18/05, John Fouhy <john at fouhy.net> wrote:
> 
> On 19/09/05, grouchy <grouch at gmail.com> wrote:
> > I've been playing with generating 1-D cellular automata, and this is the
> > fastest solution I've come up with so far.
> 
> I haven't dug deep into your code --- but, I wonder if the array
> module might help?
> 
> --
> John.
> _______________________________________________
> 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/20050919/f99946e2/attachment.html

From kent37 at tds.net  Mon Sep 19 14:23:37 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Sep 2005 08:23:37 -0400
Subject: [Tutor] ElementTree: finding a tag with specific attribute
In-Reply-To: <432B7D9C.2020802@tds.net>
References: <61d0e2b405091612212f4ec2e3@mail.gmail.com>	<432B20AA.7090705@tds.net>	<432B4BD9.40006@tds.net>
	<432B7D9C.2020802@tds.net>
Message-ID: <432EADC9.1090604@tds.net>

Kent Johnson wrote:
> I looked at this again and there is a bug in BS that causes this
> behaviour. It's kind of an interesting bug that is a side-effect of
> the way BS uses introspection to access child tags.

There is a new release of BS that fixes this problem and one Danny found recently (broken fetch).
http://www.crummy.com/software/BeautifulSoup/index.html

Kent


From 3dbernard at gmail.com  Mon Sep 19 15:04:34 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon, 19 Sep 2005 09:04:34 -0400
Subject: [Tutor] ElementTree: finding a tag with specific attribute
In-Reply-To: <432EADC9.1090604@tds.net>
References: <61d0e2b405091612212f4ec2e3@mail.gmail.com>
	<432B20AA.7090705@tds.net> <432B4BD9.40006@tds.net>
	<432B7D9C.2020802@tds.net> <432EADC9.1090604@tds.net>
Message-ID: <61d0e2b405091906047561056@mail.gmail.com>

Thanks a lot everyone for this! Glad I could help debug BS!

Bernard



On 9/19/05, Kent Johnson <kent37 at tds.net> wrote:
> Kent Johnson wrote:
> > I looked at this again and there is a bug in BS that causes this
> > behaviour. It's kind of an interesting bug that is a side-effect of
> > the way BS uses introspection to access child tags.
> 
> There is a new release of BS that fixes this problem and one Danny found recently (broken fetch).
> http://www.crummy.com/software/BeautifulSoup/index.html
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From grouch at gmail.com  Mon Sep 19 16:00:59 2005
From: grouch at gmail.com (grouchy)
Date: Mon, 19 Sep 2005 09:00:59 -0500
Subject: [Tutor] ElementTree: finding a tag with specific attribute
In-Reply-To: <61d0e2b405091906047561056@mail.gmail.com>
References: <61d0e2b405091612212f4ec2e3@mail.gmail.com>
	<432B20AA.7090705@tds.net> <432B4BD9.40006@tds.net>
	<432B7D9C.2020802@tds.net> <432EADC9.1090604@tds.net>
	<61d0e2b405091906047561056@mail.gmail.com>
Message-ID: <e6443aa7050919070030fb9f14@mail.gmail.com>

Now I can replace my my Kent-and-Danny patched version :)

On 9/19/05, Bernard Lebel <3dbernard at gmail.com> wrote:
> 
> Thanks a lot everyone for this! Glad I could help debug BS!
> 
> Bernard
> 
> 
> 
> On 9/19/05, Kent Johnson <kent37 at tds.net> wrote:
> > Kent Johnson wrote:
> > > I looked at this again and there is a bug in BS that causes this
> > > behaviour. It's kind of an interesting bug that is a side-effect of
> > > the way BS uses introspection to access child tags.
> >
> > There is a new release of BS that fixes this problem and one Danny found 
> recently (broken fetch).
> > http://www.crummy.com/software/BeautifulSoup/index.html
> >
> > Kent
> >
> > _______________________________________________
> > 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050919/32c6520a/attachment.html

From cpu.crazy at gmail.com  Mon Sep 19 16:19:03 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Mon, 19 Sep 2005 08:19:03 -0600
Subject: [Tutor] IRC Client Trouble -- too many new lines
In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC0226A6F2@chbnt01.alpha.wd.govt.nz>
References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC0226A6F2@chbnt01.alpha.wd.govt.nz>
Message-ID: <432EC8D7.9010203@gmail.com>

An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050919/8ed00b85/attachment.htm

From 3dbernard at gmail.com  Mon Sep 19 16:55:00 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon, 19 Sep 2005 10:55:00 -0400
Subject: [Tutor] ElementTree: finding a tag with specific attribute
In-Reply-To: <432EADC9.1090604@tds.net>
References: <61d0e2b405091612212f4ec2e3@mail.gmail.com>
	<432B20AA.7090705@tds.net> <432B4BD9.40006@tds.net>
	<432B7D9C.2020802@tds.net> <432EADC9.1090604@tds.net>
Message-ID: <61d0e2b405091907555b6ba826@mail.gmail.com>

Well I have just retested BS with my XML file and now it's much, much
faster (I would say instantaneous).


Bernard



On 9/19/05, Kent Johnson <kent37 at tds.net> wrote:
> Kent Johnson wrote:
> > I looked at this again and there is a bug in BS that causes this
> > behaviour. It's kind of an interesting bug that is a side-effect of
> > the way BS uses introspection to access child tags.
> 
> There is a new release of BS that fixes this problem and one Danny found recently (broken fetch).
> http://www.crummy.com/software/BeautifulSoup/index.html
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From dyoo at hkn.eecs.berkeley.edu  Mon Sep 19 20:06:24 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 19 Sep 2005 11:06:24 -0700 (PDT)
Subject: [Tutor] tuples and mysqldb tables (fwd)
Message-ID: <Pine.LNX.4.44.0509191104500.31347-100000@hkn.eecs.berkeley.edu>

[Again forwarding to tutor.  Ed, please keep tutor at python.org in CC;
otherwise, your questions might lose themselves in my mailbox.  I don't
want to be a bottleneck in your learning.]

---------- Forwarded message ----------
Date: Mon, 19 Sep 2005 00:06:13 -0400
From: Ed Hotchkiss <edhotchkiss at gmail.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] tuples and mysqldb tables

Thanks for the debugging help :P - I've edited the error handling line, and
defined the port_counter above, but I am still not getting any output. I
have inserted print "scanned: ",port_counter,"\n"
into the thread, so that should at least print to screen each time the
thread is ran, regardless of the port being open or closed. Any ideas why
the thread itself though is not working?
A cleaner view of the code is here:
http://deadbeefbabe.org/paste/1672?_nevow_carryover_=1127102735.7127.0.0.10.809800804887
 Thanks again for the error handling help!

 On 9/18/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
>
> > def run(self):
> > try:
> > ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > ss.connect((ip, port_counter))
> > print "%s | %d OPEN" % (ip, port_counter)
> > ss.close()
> > except: pass
> ^^^^
>
> Hi Ed,
>
> Yikes. Don't do that. *grin*
>
> By "that", I mean setting the exception handler here to do nothing.
> Exception handling shouldn't abused to silence errors like that, at least,
> not wholesale like that. At the very least, while we're debugging this,
> import the 'traceback' module and at least give a heads up, like this:
>
> except:
> traceback.print_exc()
>
> Once this is in place, expect to see errors. I know what you meant to do:
> you wanted to ignore network errors, so try to make the exception handler
> a little more specific in the exceptions it's trying to silence.
>
> The problem here is that the handler has been inadvertantely silencing a
> legitimate NameError. From casual inspection, it's not clear what
> 'port_counter' is. I suspect you want to add that as part of the thread's
> state, in which case consider adding it within your thread's __init__
> method.
>
>
> > def scan(ip, begin, end):
> > for port_counter in range(begin, end):
> > while threading < MAX_THREADS:
> > scanThread().start()
> > # end function -------------------
>
>
> Ok, I definitely suspect port_counter now as the culprit here. Make sure
> you create each thread with port_counter as a part of each thread's state.
>
>
> [Aside: are you trying to a port scanner in the style that Jacob Matthews
> wrote about here?
>
> http://www.kuro5hin.org/story/2004/3/17/93442/8657
>
> Just curious.]
>
>
>
> Good luck to you!
>
>


-- 
edward hotchkiss


From George.Flaherty at marketmax.com  Mon Sep 19 20:21:40 2005
From: George.Flaherty at marketmax.com (George Flaherty)
Date: Mon, 19 Sep 2005 14:21:40 -0400
Subject: [Tutor] More IDE's (was: Boa-Constructor)
Message-ID: <59CF9F456FAA9045B405C441EC916F3E02DA6624@MERC24.na.sas.com>

Well, for starters.

1. PyDEV does not have any type of prespective. I use the java prespective or resources.

2. Check out this guide, granted it is a bit old(2003'ish) but it is still pretty good.
http://www-128.ibm.com/developerworks/opensource/library/os-ecant/

3. Terry, what do you mean by "other functions?" Are you talking about the ant/python extension libraries? 

4. Denise, regarding the code-completion as long as you have the libs within the PYTHONPATH you should be able to generate the code completion. Do you have some specific example of a library that is not working for you?

Cheers
-george


-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of ->Terry<-
Sent: Saturday, September 17, 2005 12:07 AM
To: D. Hartley
Cc: tutor at python.org
Subject: Re: [Tutor] More IDE's (was: Boa-Constructor)

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


Today (Sep 16, 2005) at 5:29pm, D. Hartley spoke these wise words:

- ->I know how to use the code completion (hooray for me!) but so far,
- ->most everything else that's going on in PyDev/Eclipse is a mystery to
- ->me.  But I managed to get an interactive interpreter as an external
- ->tool, so that's a lot of progress for me.
- ->
- ->Technically I suppose this is OT, but did you guys that have used/are
- ->using PyDev/Eclipse use any kind of tutorials for those other
- ->functions? (Not sure if there even *are* any, besides the standard
- ->documentation on PyDev's website)  Most of the things I've found on
- ->eclipse are for much more advanced eyes than mine, it would seem.
- ->
- ->I'd appreciate any pointers! :)
- ->
- ->~Denise

I too am having problems getting my head wrapped around Pydev/Eclipse.
The docs on Eclipse don't seem to be geared toward Pydev and the FAQ on the Pydev site is rather sparse. At this point, I'm not even sure the install went properly since I see error messages such as:

An internal error occurred during:"Pydev code completion:rebuilding modules"

among others I didn't take the time to copy down. For now I am back to Gedit and an xterm. If you run across more documentation could you please cc me as well?

Thanks,
- -- 
    Terry

     ,-~~-.___.     Terry Randall <tvbareATsocketDOTnet>
    / |  '     \    
   <   )        0    Linux Counter Project User# 98233
    \_/, ,-----'
       ====          //
      /  \-'~;    /~~~(0)
     /  __/~|   /      |   If only Snoopy had Slackware...
   =( ______| (________|

"He is your friend, your partner, your defender, your dog.
You are his life, his love, his leader. He will be yours, faithful and true, to the last beat of his heart. You owe
it to him to be worthy of such devotion."    -- Unknown

         (Best viewed with a mono-spaced font.)

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.7 (GNU/Linux)

iD8DBQFDK5aDQvSnsfFzkV0RAv4YAJ4jPjR8z7X/afxscr+wt3eyeKcvnACeLfj9
TMyOGvnEYPqrZNQfQc67mBs=
=0pNZ
-----END PGP SIGNATURE-----

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

From dyoo at hkn.eecs.berkeley.edu  Mon Sep 19 20:31:33 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 19 Sep 2005 11:31:33 -0700 (PDT)
Subject: [Tutor] tuples and mysqldb tables (fwd)
In-Reply-To: <Pine.LNX.4.44.0509191104500.31347-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0509191115080.31347-100000@hkn.eecs.berkeley.edu>



> Thanks for the debugging help :P - I've edited the error handling line, and
> defined the port_counter above, but I am still not getting any output. I
> have inserted print "scanned: ",port_counter,"\n"
> into the thread, so that should at least print to screen each time the
> thread is ran, regardless of the port being open or closed. Any ideas why
> the thread itself though is not working?
> A cleaner view of the code is here:
> http://deadbeefbabe.org/paste/1672?_nevow_carryover_=1127102735.7127.0.0.10.809800804887
>  Thanks again for the error handling help!

Hi Ed,

There are logically two possible areas where there might be a bug: there
might be a problem in the scanThread class, or there might be a problem in
scan.

Or there could be problems in both.  *grin*

You're still running into some fundamentally basic problems dealing with
variables and how variable scope works.  See:

    http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm

and go through the examples there: it should help clarify some of the
confusion you have about maintaining state in a class.

As it stands, there is nothing in the class definition that knows about
what 'ip' or 'port_counter' are: those two aren't parameters of the class
or its methods, nor are they instance variables.




> I have inserted print "scanned: ",port_counter,"\n" into the thread, so
> that should at least print to screen each time the thread is ran,
> regardless of the port being open or closed.

The direct implication here is that scanThread.run() itself is NOT being
executed.  So there's also a problem in scan() that prevents the threads
from getting started in the first place.  I don't understand what you're
trying to do with:

    while threading < MAX_THREADS:
        ...

since 'threading' is the 'threading' module.  Unfortunately, Python won't
treat this as a TypeError, even though it really should be treated as such
(what does it mean for a module to be "smaller" than something else?!)

And MAX_THREADS is undefined.

Are you getting any kind of error messages when you run your program?
I'm a bit confused, because there's so many opportunities here for Python
to tell you that there's a NameError here:  are you seeing those error
messages too?


From kent37 at tds.net  Mon Sep 19 20:35:48 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 19 Sep 2005 14:35:48 -0400
Subject: [Tutor] Port scanner (was: tuples and mysqldb tables)
In-Reply-To: <Pine.LNX.4.44.0509191104500.31347-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509191104500.31347-100000@hkn.eecs.berkeley.edu>
Message-ID: <432F0504.2070609@tds.net>

Danny Yoo wrote:
> [Again forwarding to tutor.  Ed, please keep tutor at python.org in CC;
> otherwise, your questions might lose themselves in my mailbox.  I don't
> want to be a bottleneck in your learning.]
> 
> ---------- Forwarded message ----------
> Date: Mon, 19 Sep 2005 00:06:13 -0400
> From: Ed Hotchkiss <edhotchkiss at gmail.com>
> To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] tuples and mysqldb tables
> 
> Thanks for the debugging help :P - I've edited the error handling line, and
> defined the port_counter above, but I am still not getting any output. I
> have inserted print "scanned: ",port_counter,"\n"
> into the thread, so that should at least print to screen each time the
> thread is ran, regardless of the port being open or closed. Any ideas why
> the thread itself though is not working?

Do you get an error message printed? If so, it's helpful if you copy and paste the exact traceback into your email.

> A cleaner view of the code is here:
> http://deadbeefbabe.org/paste/1672?_nevow_carryover_=1127102735.7127.0.0.10.809800804887

You still have not defined port_counter in the scope of class scanThread. As Danny suggests, you should pass this value to the scanThread constructor and save it as an instance variable, then use the saved value in scanThread.run().

You might want to try making a non-threaded version of this program first - maybe you could write a function that tests a single port. Once you have that working then you can learn how to call it in a new thread.

Kent

>  Thanks again for the error handling help!
> 
>  On 9/18/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
> 
>>
>>
>>>def run(self):
>>>try:
>>>ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>>ss.connect((ip, port_counter))
>>>print "%s | %d OPEN" % (ip, port_counter)
>>>ss.close()
>>>except: pass
>>
>>^^^^
>>
>>Hi Ed,
>>
>>Yikes. Don't do that. *grin*
>>
>>By "that", I mean setting the exception handler here to do nothing.
>>Exception handling shouldn't abused to silence errors like that, at least,
>>not wholesale like that. At the very least, while we're debugging this,
>>import the 'traceback' module and at least give a heads up, like this:
>>
>>except:
>>traceback.print_exc()
>>
>>Once this is in place, expect to see errors. I know what you meant to do:
>>you wanted to ignore network errors, so try to make the exception handler
>>a little more specific in the exceptions it's trying to silence.
>>
>>The problem here is that the handler has been inadvertantely silencing a
>>legitimate NameError. From casual inspection, it's not clear what
>>'port_counter' is. I suspect you want to add that as part of the thread's
>>state, in which case consider adding it within your thread's __init__
>>method.
>>
>>
>>
>>>def scan(ip, begin, end):
>>>for port_counter in range(begin, end):
>>>while threading < MAX_THREADS:
>>>scanThread().start()
>>># end function -------------------
>>
>>
>>Ok, I definitely suspect port_counter now as the culprit here. Make sure
>>you create each thread with port_counter as a part of each thread's state.
>>
>>
>>[Aside: are you trying to a port scanner in the style that Jacob Matthews
>>wrote about here?
>>
>>http://www.kuro5hin.org/story/2004/3/17/93442/8657
>>
>>Just curious.]
>>
>>
>>
>>Good luck to you!
>>
>>
> 
> 
> 


From edhotchkiss at gmail.com  Mon Sep 19 21:40:05 2005
From: edhotchkiss at gmail.com (Ed Hotchkiss)
Date: Mon, 19 Sep 2005 15:40:05 -0400
Subject: [Tutor] tuples and mysqldb tables (fwd)
In-Reply-To: <Pine.LNX.4.44.0509191115080.31347-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509191104500.31347-100000@hkn.eecs.berkeley.edu>
	<Pine.LNX.4.44.0509191115080.31347-100000@hkn.eecs.berkeley.edu>
Message-ID: <d1bf1fa20509191240d5b328a@mail.gmail.com>

Thanks for the link! It is EXACTLY what I have been looking for. When I used 
to use Flash a bit, and did some actionscript they had a similiar setup for 
OOP (Do all languages use OOP so similiarly?) which I never learned. I'm 
doing these examples, and now I'm going to try and rework the code from the 
beginning. Thanks again!
 -edward
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050919/a2874355/attachment.htm

From tvbare at socket.net  Mon Sep 19 22:08:11 2005
From: tvbare at socket.net (->Terry<-)
Date: Mon, 19 Sep 2005 15:08:11 -0500 (CDT)
Subject: [Tutor] More IDE's (was: Boa-Constructor)
In-Reply-To: <59CF9F456FAA9045B405C441EC916F3E02DA6624@MERC24.na.sas.com>
References: <59CF9F456FAA9045B405C441EC916F3E02DA6624@MERC24.na.sas.com>
Message-ID: <Pine.LNX.4.62.0509191502310.10681@elwood.hillbillyhaven.org>

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


Reply in-line.

Today (Sep 19, 2005) at 2:21pm, George Flaherty spoke these wise words:

- ->Well, for starters.
- ->
- ->1. PyDEV does not have any type of prespective. I use the java prespective or resources.
- ->
- ->2. Check out this guide, granted it is a bit old(2003'ish) but it is still pretty good.
- ->http://www-128.ibm.com/developerworks/opensource/library/os-ecant/

Thanks George, I'll check it out.

- ->3. Terry, what do you mean by "other functions?" Are you talking about the ant/python extension libraries? 

I believe you meant Denise.

- ->4. Denise, regarding the code-completion as long as you have the libs within the PYTHONPATH you should be able to generate the code completion. Do you have some specific example of a library that is not working for you?
- ->
- ->Cheers
- ->-george
- ->
- ->
- ->-----Original Message-----
- ->From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of ->Terry<-
- ->Sent: Saturday, September 17, 2005 12:07 AM
- ->To: D. Hartley
- ->Cc: tutor at python.org
- ->Subject: Re: [Tutor] More IDE's (was: Boa-Constructor)
- ->
- ->
- ->Today (Sep 16, 2005) at 5:29pm, D. Hartley spoke these wise words:
- ->
- ->->I know how to use the code completion (hooray for me!) but so far,
- ->->most everything else that's going on in PyDev/Eclipse is a mystery to
- ->->me.  But I managed to get an interactive interpreter as an external
- ->->tool, so that's a lot of progress for me.
- ->->
- ->->Technically I suppose this is OT, but did you guys that have used/are
- ->->using PyDev/Eclipse use any kind of tutorials for those other
- ->->functions? (Not sure if there even *are* any, besides the standard
- ->->documentation on PyDev's website)  Most of the things I've found on
- ->->eclipse are for much more advanced eyes than mine, it would seem.
- ->->
- ->->I'd appreciate any pointers! :)
- ->->
- ->->~Denise
- ->
- ->I too am having problems getting my head wrapped around Pydev/Eclipse.
- ->The docs on Eclipse don't seem to be geared toward Pydev and the FAQ on the Pydev site is rather sparse. At this point, I'm not even sure the install went properly since I see error messages such as:
- ->
- ->An internal error occurred during:"Pydev code completion:rebuilding modules"
- ->
- ->among others I didn't take the time to copy down. For now I am back to Gedit and an xterm. If you run across more documentation could you please cc me as well?
- ->
- ->Thanks,
- ->--
- ->    Terry

Cheers,
- -- 
    Terry

     ,-~~-.___.     Terry Randall <tvbareATsocketDOTnet>
    / |  '     \    
   <   )        0    Linux Counter Project User# 98233
    \_/, ,-----'
       ====          //
      /  \-'~;    /~~~(0)
     /  __/~|   /      |   If only Snoopy had Slackware...
   =( ______| (________|

"He is your friend, your partner, your defender, your dog.
You are his life, his love, his leader. He will be yours,
faithful and true, to the last beat of his heart. You owe
it to him to be worthy of such devotion."    -- Unknown

         (Best viewed with a mono-spaced font.)

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.7 (GNU/Linux)

iD8DBQFDLxquQvSnsfFzkV0RAsAoAKCEuQMWaFQTzL9b74VCSW5y0X9WogCeOR6/
NSSsxdyE/d8k/fUdHjBXkVA=
=rZMF
-----END PGP SIGNATURE-----


From dyoo at hkn.eecs.berkeley.edu  Mon Sep 19 22:35:32 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 19 Sep 2005 13:35:32 -0700 (PDT)
Subject: [Tutor] OOP fundamentals
In-Reply-To: <d1bf1fa20509191240d5b328a@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509191316581.12415-100000@hkn.eecs.berkeley.edu>



On Mon, 19 Sep 2005, Ed Hotchkiss wrote:

> Thanks for the link! It is EXACTLY what I have been looking for. When I
> used to use Flash a bit, and did some actionscript they had a similiar
> setup for OOP (Do all languages use OOP so similiarly?) which I never
> learned.

Hi Ed,


I believe that most things are fairly close among the languages that claim
to support OOP.  Just for comparison, let's see what this looks like in
some other languages.  For example, let's say we have a Person class:

### Python ###
class Person(object):
    def __init__(self, name):
        self.name = name
    def sayHello(self):
        print "hello, my name is", name

p = Person("ed")
p.sayHello()
##############

This creates a Person class, who extends the behavior of the base 'object'
class.  This class has a bit of state to remember what the respective
'name' is.  We also a method called 'sayHello' to make sure the person can
respond to a "sayHello" message.


Here's what things look like in Java:

/*** Java ***/
public class Person extends java.lang.Object {
    String name;
    public Person(String name) {
        this.name = name;
    }
    public void sayHello() {
        System.out.println("hello, my name is " + this.name);
    }

    static public void main(String[] args) {
        Person p = new Person("ed");
        p.sayHello();
    }
}
/************/


Pretty much the same thing: we define what things an instance of the class
needs to store in its personal state, and we also define a method that
instances can respond to.


Finally, just to make this idea concrete, let's switch to PLT Scheme:

;;; PLT Scheme ;;;
(require (lib "class.ss"))

(define person%
  (class object%
    (init-field name)
    (public say-hello!)
    (define (say-hello!)
      (printf "hello, my name is ~a~%" name))
    (super-new)))

(define p (new person% (name "ed")))
(send p say-hello!)
;;;;;;;;;;;;;;;;;;

Same thing, just more parentheses.  *grin*



Hope this helps!


From edhotchkiss at gmail.com  Mon Sep 19 23:01:30 2005
From: edhotchkiss at gmail.com (Ed Hotchkiss)
Date: Mon, 19 Sep 2005 17:01:30 -0400
Subject: [Tutor] OOP fundamentals
In-Reply-To: <Pine.LNX.4.44.0509191316581.12415-100000@hkn.eecs.berkeley.edu>
References: <d1bf1fa20509191240d5b328a@mail.gmail.com>
	<Pine.LNX.4.44.0509191316581.12415-100000@hkn.eecs.berkeley.edu>
Message-ID: <d1bf1fa2050919140120325ee1@mail.gmail.com>

Thanks Danny! Tommorrow I am off to get "Programming for Python, 2nd 
edition" and learn everything - all of it, before I even bother with 
Sockets. Afterall, I want python for EVERYTHING not just sockets and inet 
based scripts/applications. 
 I realized that I need to take a step back, make port scanner a class that 
does nothing but really help me learn classes, then insert threading, then 
once that works, insert the actual sockets into their respective class def 
etc ... Thanks again ...
 Next time I post, I'll have something either more abstract/theory question, 
or something that isn't quite so simple!
 Thanks again everyone thats been helping me out especially danny!

-edward
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050919/41d24153/attachment.htm

From kabads at gmail.com  Mon Sep 19 23:06:42 2005
From: kabads at gmail.com (Adam Cripps)
Date: Mon, 19 Sep 2005 22:06:42 +0100
Subject: [Tutor] Timer on CGI
Message-ID: <c7ff38550509191406687d20e8@mail.gmail.com>

Some of my pupils at school are working through simple mathematic
problems (multiplication tables) through my website. I basically show
some tables, they enter the results and then get feedback on how they
did.

I have two questions - and my guess is that one will be easier than the other. 

1. I want to store the results in a mySQL database - I've done this
kind of thing before using PHP - are there any good tutorial resources
for using mysql with python?

2. Today the children asked if they could be timed when they complete
the problem. Is there any way of knowing how long they spent
completing the task?

TIA
Adam
-- 
http://www.monkeez.org
PGP key: 0x7111B833

From adam.jtm30 at gmail.com  Mon Sep 19 23:24:32 2005
From: adam.jtm30 at gmail.com (Adam)
Date: Mon, 19 Sep 2005 23:24:32 +0200
Subject: [Tutor] Why won't it enter the quiz?
In-Reply-To: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>
References: <BAY106-DAV103DF2D336BE86AE53E93AC4900@phx.gbl>
Message-ID: <be4fbf920509191424326d0942@mail.gmail.com>

You're not returning the values of answer and guess so it jumps out of the 
while loop and does the else. Try this:

def add(a,b):
answer = a+b
guess = float(raw_input(a," + ",b," = "))
return answer, guess

answer, guess = add(num1,num2)
if guess != answer:

On 17/09/05, Nathan Pinno <falcon3166 at hotmail.com> wrote:
> 
> Hi all,
>  I've got this program I've written that should give an addition quiz, 
> except it never enters the quiz. How do I make it enter the quiz?
>  Here is the code:
> import random
>  def add(a,b):
> answer = a+b
> guess = float(raw_input(a," + ",b," = "))
>  num1 = random.choice(range(1,10))
> num2 = random.choice(range(1,10))
>  while 1:
> q = random.choice(range(15,31))
> cq = 1
> correct = 0
> while cq >= q:
> add(num1,num2)
> if guess != answer:
> print "Incorrect! The correct answer is: ",answer
> cq += 1
> elif guess == answer:
> print "Correct!"
> correct += 1
> cq += 1
> else:
> print "Questions: ",q
> print "Correct: ",correct
> print "Percent Correct: ",(cq/q)*100
> break
>  print "Goodbye."
>  It just prints out for an example:
>  Questions: 17
> Correct: 0
> Percent Correct: 0
> Goodbye.
>  Thanks,
> Nathan Pinno
> 
> _______________________________________________
> 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/20050919/08eeef2a/attachment.html

From chris.arndt at web.de  Mon Sep 19 23:29:55 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Mon, 19 Sep 2005 22:29:55 +0100
Subject: [Tutor] Timer on CGI
In-Reply-To: <c7ff38550509191406687d20e8@mail.gmail.com>
References: <c7ff38550509191406687d20e8@mail.gmail.com>
Message-ID: <432F2DD3.3090601@web.de>

Adam Cripps schrieb:
> Some of my pupils at school are working through simple mathematic
> problems (multiplication tables) through my website. I basically show
> some tables, they enter the results and then get feedback on how they
> did.
> 
> I have two questions - and my guess is that one will be easier than the other. 
> 
> 1. I want to store the results in a mySQL database - I've done this
> kind of thing before using PHP - are there any good tutorial resources
> for using mysql with python?

Don't know about that...

> 2. Today the children asked if they could be timed when they complete
> the problem. Is there any way of knowing how long they spent
> completing the task?

You'd have to use Cookies for that and (possibly) JavaScript for that.

The basic approach would be:

1) When they first request a task, send a session Cookie along with the page
and save it on the server side too.
2) provide a button on the page that says: "Start task". That button starts a
javascript timer.
3) Provide another Button that says "Finish / Send solution". This buttons
reads the timer value ans sends it along with the other request variables.
4) on the server read the request variables and the the cookie and match it to
the saved session ids, so you can determine which student this answer was for.

I hope I was able to convey the general idea. Please ask if you need to know more!

Chris

From dyoo at hkn.eecs.berkeley.edu  Mon Sep 19 23:33:01 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 19 Sep 2005 14:33:01 -0700 (PDT)
Subject: [Tutor] OOP fundamentals
In-Reply-To: <d1bf1fa2050919140120325ee1@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509191420000.12415-100000@hkn.eecs.berkeley.edu>



On Mon, 19 Sep 2005, Ed Hotchkiss wrote:

> Thanks Danny! Tommorrow I am off to get "Programming for Python, 2nd
> edition" and learn everything - all of it, before I even bother with
> Sockets.

Hi Ed,

I'd disrecommend Programming Python if you're a beginner.  Programming
Python is really more of an expedition over Python's features than a
tutorial.  Furthermore, it's a very thick and heavy book, and I have
something of a grudge against books that make me strain my wrists.  I
personally think that "Learning Python" will be a better fit for you.

I also have heard good things about Alan Gauld's "Learn to Program Using
Python", which is an expansion of the online tutorials you've been reading
into book form.  And I've heard that the author is pretty responsive.
*grin*

For more information, you can take a look at:

    http://wiki.python.org/moin/IntroductoryBooks

for book reviews of other introductory texts.


But finally, you may also want to look at:

    http://wiki.python.org/moin/BeginnersGuide/Programmers
    http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

You might be able to get pretty far from the online tutorials there.


Good luck!


From alan.gauld at btinternet.com  Mon Sep 19 23:52:11 2005
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Sep 2005 22:52:11 +0100
Subject: [Tutor] Timer on CGI
References: <c7ff38550509191406687d20e8@mail.gmail.com>
Message-ID: <dgnbt5$2aj$1@sea.gmane.org>

> 1. I want to store the results in a mySQL database - I've done 
> this
> kind of thing before using PHP - are there any good tutorial 
> resources
> for using mysql with python?

There is a generic DB API howto document and I have a database
topic in my tutor which uses SQLite but the basic principles
are identical you just load a different driver...

> 2. Today the children asked if they could be timed when they 
> complete
> the problem. Is there any way of knowing how long they spent
> completing the task?

You should be able to store the time of page display and 
submission
as hidden fields. Javascript might be the easiest way to do this
using the onLoad event. Then get the difference in times when 
they
hit submit and pass the elapsed time as a hidden field for the 
CGI
to pick up and display. Alternatively just pass the onLoad time
when submit is called and do the calculations at the CGI, but
then you get network transit and server queuing times added...

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




From Liam.Clarke-Hutchinson at business.govt.nz  Tue Sep 20 00:16:17 2005
From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson)
Date: Tue, 20 Sep 2005 10:16:17 +1200
Subject: [Tutor] IRC Client Trouble -- too many new lines
Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC0226A6F4@chbnt01.alpha.wd.govt.nz>

Hi Joseph, 

I'm unable to cc to the Python list from this address, so I'll try my
forwarding address.

>Example:
>this
>is 
>the
>type
>of 
>message
>I'm
>getting
>and
>as
>you
>can
>see
>,
>it's 
>really
>annoying!

You know that 'print' adds a newline?
You could either use - 

import sys
sys.stdout.write(msg[print_msg])

or, to simplify things -
I would recommend either - 

space = ' '
for item in msg:
	item.rstrip()

joinedMsg = space.join(msg)

or

nullString = ''
joinedMsg = nullString.join(msg)
noNewlinesMsg = joinedMsg.replace('\n', nullString)

Let me know how it goes. 

Regards, 

Liam Clarke-Hutchinson
________________________________________
From: Joseph Quigley [mailto:cpu.crazy at gmail.com] 
Sent: Tuesday, 20 September 2005 2:19 a.m.
To: Liam Clarke-Hutchinson; tutor at python.org
Subject: Re: [Tutor] IRC Client Trouble -- too many new lines

Hi,

Liam Clarke-Hutchinson wrote: 
Hi Joseph, 


  
while (1):
  	buffer = Data.IRC.recv(1024)
	msg = string.split(buffer)
    

Just a warning, the string module will be removed/deprecated come Py3K.
Better to use - 
buffer.split()
nick_name = msg[0][:msg[0].find("!")]
filetxt.write(nick_name.lstrip(':') + ' -> ' + message.lstrip(':') + '\n')
  
Ok. Thanks for the heads up.

As to your printing problem, I'm not sure if you're referring to - 
print msg[print_msg]
    

  
Oh, sorry. I'm refering to the print msg[print_msg]

And I'm not sure if you want it to print without an additional newline, or
with a newline. 
  
Well every word is on it's own new line (I get a huge message from the IRC
server) and I'd like a word wrap or something to fix that. 
#Incidentally, it's a bit simpler to maintain this kinda loop
#instead of a while loop.

for item in msg:
    item.rstrip() #Will strip whitespace (\t\r\n etc.) by default
    print item
  
Ah. Thanks

If you're wanting to print without the newline that print adds, why not do a
join like this one? message = ' '.join(msg[3:])

print ' '.join(msg) ?

  
Thanks again. This is proving very usefull.

What output you're expecting
  
I'm expecting a large amount of text without new lines for each word, and
possible word wrapping.

What output you're getting

  
Example:
this
is 
the
type
of 
message
I'm
getting
and
as
you
can
see
,
it's 
really
annoying!


PS Your code is interesting, I've never dealt with the IRC protocol
before,so it's good to see a demonstration of it.
I edited the code from a Python Cookbook recipe.

 I may toddle off and check
out that RFC.
  
Yes. Some people on a forum that I hang oput with suggested a chat room. A
freind of mine suggested IRC and python. He's doing the server and I'm doing
the client. I'm testing the client on freenode.. only thing I could think of
at the time.

A new monthly electronic newsletter covering all aspects of MED's work is now available.  Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism.  See http://news.business.govt.nz for more details.




http://www.govt.nz - connecting you to New Zealand central & local government services

Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer.

From edhotchkiss at gmail.com  Tue Sep 20 02:45:50 2005
From: edhotchkiss at gmail.com (Ed Hotchkiss)
Date: Mon, 19 Sep 2005 20:45:50 -0400
Subject: [Tutor] OOP fundamentals
In-Reply-To: <Pine.LNX.4.44.0509191420000.12415-100000@hkn.eecs.berkeley.edu>
References: <d1bf1fa2050919140120325ee1@mail.gmail.com>
	<Pine.LNX.4.44.0509191420000.12415-100000@hkn.eecs.berkeley.edu>
Message-ID: <d1bf1fa205091917454151ba57@mail.gmail.com>

Excellent, I'll be getting that book tomorrow! Thanks again, I'm doing a
tutorial as we speak!


 On 9/19/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
>
> On Mon, 19 Sep 2005, Ed Hotchkiss wrote:
>
> > Thanks Danny! Tommorrow I am off to get "Programming for Python, 2nd
> > edition" and learn everything - all of it, before I even bother with
> > Sockets.
>
> Hi Ed,
>
> I'd disrecommend Programming Python if you're a beginner. Programming
> Python is really more of an expedition over Python's features than a
> tutorial. Furthermore, it's a very thick and heavy book, and I have
> something of a grudge against books that make me strain my wrists. I
> personally think that "Learning Python" will be a better fit for you.
>
> I also have heard good things about Alan Gauld's "Learn to Program Using
> Python", which is an expansion of the online tutorials you've been reading
> into book form. And I've heard that the author is pretty responsive.
> *grin*
>
> For more information, you can take a look at:
>
> http://wiki.python.org/moin/IntroductoryBooks
>
> for book reviews of other introductory texts.
>
>
> But finally, you may also want to look at:
>
> http://wiki.python.org/moin/BeginnersGuide/Programmers
> http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
>
> You might be able to get pretty far from the online tutorials there.
>
>
> Good luck!
>
>


--
edward hotchkiss
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050919/e250da55/attachment.html

From grouch at gmail.com  Tue Sep 20 07:01:43 2005
From: grouch at gmail.com (grouchy)
Date: Tue, 20 Sep 2005 00:01:43 -0500
Subject: [Tutor] Any suggestions for optimizing this code?
In-Reply-To: <e6443aa705091822162d89c6d@mail.gmail.com>
References: <e6443aa705091821434d9ee478@mail.gmail.com>
	<5e58f2e4050918215562dfcbce@mail.gmail.com>
	<e6443aa705091822162d89c6d@mail.gmail.com>
Message-ID: <e6443aa7050919220143c80e56@mail.gmail.com>

Replying to myself, I got some speedups by replacing:

def makeArray1(matrix):
result = matrix
result[0][w/2] = 1
for row in range(h-1):
last = result[row]
next = result[row+1]
for i in range(w-1): 
next[i] = rule[4*last[i-1]+2*last[i]+last[i+1]]
next[i+1] = rule[4*last[i]+2*last[i+1]+last[0]]
return result

with this using Numerical Python:

def makeArray2(matrix):
result = matrix 
result[0,w/2] = 1
for n in range(h-1):
r = result[n]
r2 = result[n+1]
r2[1:-1] = choose(4*r[:-2]+2*r[1:-1]+r[2:],rule)
r2[0] = rule[4*r[-1]+2*r[0]+r[1]]
r2[-1] = rule[4*r[-2]+2*r[-1]+r[0]] 
return result


It finally clicked that instead of a sliding window, I could just add 4*row 
+ 2*row + row, each offset by one, and that would give the same results 
using Numpy as stepping through three elements at a time. It's not pretty 
looking, but it works. 

This is about 6x faster overall. The bottleneck is in choose, where each 
element gets looked up and replaced. I'm not sure how to do it any faster 
tho. Choose is much faster than a for loop, which is where the 6x speedup is 
really coming from. Numpy just adding and multiplying the row is more like 
20x faster than stepping through an element at time with a three element 
window :) 

As a sidenote that may be helpful to someone, makeArray1() is 22x faster 
using psyco, and 4x faster than the Numpy solution. Psyco doesn't speed up 
the Numpy calculations at all, which isn't surprsing, since it's mostly 
written in C. If you only use x86, that might be ok. Numpy is a lot more 
elegant of a solution it seems. 

I'm positive I could bring those closer together, if I could somehow not use 
a lookup table to convert binary numbers to integers and back to binary 
numbers.

Normally I wouldn't care a whit about optimisation, but number crunching 
through a million items and suddenly Numpy seemed pretty cool. I know this 
is the first time I understood the power of being able to perform a 
calculation on an entire array, and stacking slices. Multiplying and adding 
three rows is a lot faster than stepping through a single row three elements 
at a time.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050920/b6e14bc9/attachment.html

From kabads at gmail.com  Tue Sep 20 07:39:40 2005
From: kabads at gmail.com (Adam Cripps)
Date: Tue, 20 Sep 2005 06:39:40 +0100
Subject: [Tutor] Timer on CGI
In-Reply-To: <dgnbt5$2aj$1@sea.gmane.org>
References: <c7ff38550509191406687d20e8@mail.gmail.com>
	<dgnbt5$2aj$1@sea.gmane.org>
Message-ID: <c7ff38550509192239ddd78ac@mail.gmail.com>

On 9/19/05, Alan Gauld <alan.gauld at btinternet.com> wrote:
> > 1. I want to store the results in a mySQL database - I've done
> > this
> > kind of thing before using PHP - are there any good tutorial
> > resources
> > for using mysql with python?
> 
> There is a generic DB API howto document and I have a database
> topic in my tutor which uses SQLite but the basic principles
> are identical you just load a different driver...
> 
> > 2. Today the children asked if they could be timed when they
> > complete
> > the problem. Is there any way of knowing how long they spent
> > completing the task?
> 
> You should be able to store the time of page display and
> submission
> as hidden fields. Javascript might be the easiest way to do this
> using the onLoad event. Then get the difference in times when
> they
> hit submit and pass the elapsed time as a hidden field for the
> CGI
> to pick up and display. Alternatively just pass the onLoad time
> when submit is called and do the calculations at the CGI, but
> then you get network transit and server queuing times added...

Thanks to all for suggestions and link - will look at this and
probably come back for more help!

Adam

-- 
http://www.monkeez.org
PGP key: 0x7111B833

From janos.juhasz at VELUX.com  Tue Sep 20 08:26:46 2005
From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=)
Date: Tue, 20 Sep 2005 08:26:46 +0200
Subject: [Tutor] OOP fundamentals
In-Reply-To: <mailman.1757.1127165074.508.tutor@python.org>
Message-ID: <OF3F5468AD.51A7298B-ONC1257082.002187F4-C1257082.002368C9@velux.com>

Hi Ed,

last month I have found this beautifull sample about threads and sockets:
      http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642

It helped me to a lot to understand how these can be used together on an
OOP way.
It helped me much better, than any hypothetical OOP samples about cars and
wheels, those really usefull just for programming teachers who never made
any real programm, but has to tell something about why OOP is good to
learn.
It was so nice to read and understand a so clean code.
Probably it can help your understanding eighter.
The other place where I feel OOP very natural is using wxPython.

There is another recipe about portscanning with OOP and threading:
      http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286240


Yours sincerely,
______________________________
J?nos Juh?sz



> Message: 5
> Date: Mon, 19 Sep 2005 17:01:30 -0400
> From: Ed Hotchkiss <edhotchkiss at gmail.com>
> Subject: Re: [Tutor] OOP fundamentals
> To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
> Cc: Tutor <tutor at python.org>
> Message-ID: <d1bf1fa2050919140120325ee1 at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"

> Thanks Danny! Tommorrow I am off to get "Programming for Python, 2nd
> edition" and learn everything - all of it, before I even bother with
> Sockets. Afterall, I want python for EVERYTHING not just sockets and inet
> based scripts/applications.
> I realized that I need to take a step back, make port scanner a class
that
> does nothing but really help me learn classes, then insert threading,
then
> once that works, insert the actual sockets into their respective class
def
> etc ... Thanks again ...
> Next time I post, I'll have something either more abstract/theory
question,
> or something that isn't quite so simple!
> Thanks again everyone thats been helping me out especially danny!

> -edward
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL: http://mail.python.
> org/pipermail/tutor/attachments/20050919/41d24153/attachment.html


From edhotchkiss at gmail.com  Tue Sep 20 09:37:06 2005
From: edhotchkiss at gmail.com (Ed Hotchkiss)
Date: Tue, 20 Sep 2005 03:37:06 -0400
Subject: [Tutor] OOP fundamentals
In-Reply-To: <OF3F5468AD.51A7298B-ONC1257082.002187F4-C1257082.002368C9@velux.com>
References: <mailman.1757.1127165074.508.tutor@python.org>
	<OF3F5468AD.51A7298B-ONC1257082.002187F4-C1257082.002368C9@velux.com>
Message-ID: <d1bf1fa205092000377cfab9a7@mail.gmail.com>

I like that, I'm all over it like white on rice! Thanks.


 On 9/20/05, J?nos Juh?sz <janos.juhasz at velux.com> wrote:
>
> Hi Ed,
>
> last month I have found this beautifull sample about threads and sockets:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642
>
> It helped me to a lot to understand how these can be used together on an
> OOP way.
> It helped me much better, than any hypothetical OOP samples about cars and
> wheels, those really usefull just for programming teachers who never made
> any real programm, but has to tell something about why OOP is good to
> learn.
> It was so nice to read and understand a so clean code.
> Probably it can help your understanding eighter.
> The other place where I feel OOP very natural is using wxPython.
>
> There is another recipe about portscanning with OOP and threading:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286240
>
>
> Yours sincerely,
> ______________________________
> J?nos Juh?sz
>
>
>
> > Message: 5
> > Date: Mon, 19 Sep 2005 17:01:30 -0400
> > From: Ed Hotchkiss <edhotchkiss at gmail.com>
> > Subject: Re: [Tutor] OOP fundamentals
> > To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
> > Cc: Tutor <tutor at python.org>
> > Message-ID: <d1bf1fa2050919140120325ee1 at mail.gmail.com>
> > Content-Type: text/plain; charset="iso-8859-1"
>
> > Thanks Danny! Tommorrow I am off to get "Programming for Python, 2nd
> > edition" and learn everything - all of it, before I even bother with
> > Sockets. Afterall, I want python for EVERYTHING not just sockets and
> inet
> > based scripts/applications.
> > I realized that I need to take a step back, make port scanner a class
> that
> > does nothing but really help me learn classes, then insert threading,
> then
> > once that works, insert the actual sockets into their respective class
> def
> > etc ... Thanks again ...
> > Next time I post, I'll have something either more abstract/theory
> question,
> > or something that isn't quite so simple!
> > Thanks again everyone thats been helping me out especially danny!
>
> > -edward
> > -------------- next part --------------
> > An HTML attachment was scrubbed...
> > URL: http://mail.python.
> > org/pipermail/tutor/attachments/20050919/41d24153/attachment.html
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



--
edward hotchkiss
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050920/35205e19/attachment.html

From work at infomaniak.ch  Tue Sep 20 11:14:15 2005
From: work at infomaniak.ch (Cedric BRINER)
Date: Tue, 20 Sep 2005 11:14:15 +0200
Subject: [Tutor] IDEs
In-Reply-To: <1126711453.4624.3.camel@dhcp0320.acl.icnet.uk>
References: <mailman.1072.1126709746.508.tutor@python.org>
	<1126711453.4624.3.camel@dhcp0320.acl.icnet.uk>
Message-ID: <20050920091415.GA12501@obs.unige.ch>

what about eric3 ?
http://www.die-offenbachs.de/detlev/eric3.html

Ced.

-- 

Cedric BRINER
Geneva - Switzerland

From lists at janeden.org  Tue Sep 20 11:20:09 2005
From: lists at janeden.org (Jan Eden)
Date: Tue, 20 Sep 2005 11:20:09 +0200
Subject: [Tutor] List of class instances
Message-ID: <r02010500-1039-BDBC106229B711DABB2E000A959B4026@[10.149.23.208]>

Hi,

I'd like to form a list of class instances. The following does not work (TextfieldLong, Textarea, TextfieldShort etc being class names):

    fields = [
        TextfieldLong(name='title', label='Seitentitel', value=''),
        Textarea(name='content', label='Inhalt', value=''),
        ShortField(name='mother_id', label='MotherID', value=1)
    ]
    
Is there a way to create such a list?

Thanks in advance,

Jan
-- 
Any sufficiently advanced technology is indistinguishable from a Perl script. - Programming Perl

From lists at janeden.org  Tue Sep 20 11:39:02 2005
From: lists at janeden.org (Jan Eden)
Date: Tue, 20 Sep 2005 11:39:02 +0200
Subject: [Tutor] List of class instances
In-Reply-To: <r02010500-1039-BDBC106229B711DABB2E000A959B4026@[10.149.23.208]>
Message-ID: <r02010500-1039-6159F7FE29BA11DABB2E000A959B4026@[10.149.23.208]>

Hi,

Jan Eden wrote on 20.09.2005:

>Hi,
>
>I'd like to form a list of class instances. The following does not work 
>(TextfieldLong, Textarea, TextfieldShort etc being class names):
>
>    fields = [
>        TextfieldLong(name='title', label='Seitentitel', value=''),
>        Textarea(name='content', label='Inhalt', value=''),
>        ShortField(name='mother_id', label='MotherID', value=1)
>    ]
>    

Just found that it *does* work, but that I have to define the classes above the list assignment. Why is that? Why would Python not find the classes within the same file?

TIA,

Jan
-- 
Life's unfair - but root password helps!

From kent37 at tds.net  Tue Sep 20 11:59:45 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 20 Sep 2005 05:59:45 -0400
Subject: [Tutor] List of class instances
In-Reply-To: <r02010500-1039-6159F7FE29BA11DABB2E000A959B4026@[10.149.23.208]>
References: <r02010500-1039-6159F7FE29BA11DABB2E000A959B4026@[10.149.23.208]>
Message-ID: <432FDD91.7080705@tds.net>

Jan Eden wrote:
>>I'd like to form a list of class instances. The following does not work 
>>(TextfieldLong, Textarea, TextfieldShort etc being class names):
>>
>>   fields = [
>>       TextfieldLong(name='title', label='Seitentitel', value=''),
>>       Textarea(name='content', label='Inhalt', value=''),
>>       ShortField(name='mother_id', label='MotherID', value=1)
>>   ]
>>   
> 
> 
> Just found that it *does* work, but that I have to define the classes above the list assignment. Why is that? Why would Python not find the classes within the same file?

Class definitions are executable statements that bind the name of the class to a class object. Before the definition is executed the class is undefined, like any other assignment. For example you wouldn't expect this to work:

values = [x, y, z]
x=1
y=2
z=3

Your code suffers from the same problem. When you say
class foo:
  pass

this means, roughly,
foo = (the result of executing the class body)
and the name 'foo' is not defined until this executes.

Kent


From singingxduck at gmail.com  Tue Sep 20 12:32:01 2005
From: singingxduck at gmail.com (Orri Ganel)
Date: Tue, 20 Sep 2005 06:32:01 -0400
Subject: [Tutor] List of class instances
In-Reply-To: <r02010500-1039-6159F7FE29BA11DABB2E000A959B4026@[10.149.23.208]>
References: <r02010500-1039-6159F7FE29BA11DABB2E000A959B4026@[10.149.23.208]>
Message-ID: <432FE521.6040805@gmail.com>

As a side-note, unless you're okay with only being able to access those 
instance variables through the fields list (ie fields[0], fields[1], 
fields[2]), you may want to actually name them first.

Jan Eden wrote:

>Hi,
>
>Jan Eden wrote on 20.09.2005:
>
>  
>
>>Hi,
>>
>>I'd like to form a list of class instances. The following does not work 
>>(TextfieldLong, Textarea, TextfieldShort etc being class names):
>>
>>   fields = [
>>       TextfieldLong(name='title', label='Seitentitel', value=''),
>>       Textarea(name='content', label='Inhalt', value=''),
>>       ShortField(name='mother_id', label='MotherID', value=1)
>>   ]
>>   
>>    
>>
>
>Just found that it *does* work, but that I have to define the classes above the list assignment. Why is that? Why would Python not find the classes within the same file?
>
>TIA,
>
>Jan
>  
>


-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.


From lists at janeden.org  Tue Sep 20 12:58:08 2005
From: lists at janeden.org (Jan Eden)
Date: Tue, 20 Sep 2005 12:58:08 +0200
Subject: [Tutor] List of class instances
In-Reply-To: <432FE521.6040805@gmail.com>
Message-ID: <r02010500-1039-6E0049F029C511DABB2E000A959B4026@[10.149.23.208]>

Hi,

Orri Ganel wrote on 20.09.2005:

>As a side-note, unless you're okay with only being able to access
>those instance variables through the fields list (ie fields[0],
>fields[1], fields[2]), you may want to actually name them first.

Yes, I am fine with that - I actually prefer to have a sorted list instead of a dictionary. I'll always access them like

for field in fields:
    ...

Thanks,

Jan
-- 
I'd never join any club that would have the likes of me as a member. - Groucho Marx

From nephish at xit.net  Tue Sep 20 16:55:46 2005
From: nephish at xit.net (nephish)
Date: Tue, 20 Sep 2005 09:55:46 -0500
Subject: [Tutor] problem with matplot
Message-ID: <433022F2.5090704@xit.net>

hey there,
anyone have any luck getting up and running with matplot-lib on debian?
from the website, i followed the instructions to get it with apt. but 
something is messed up in the dependencies.

i get this
import pylab

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in -toplevel-
    import pylab
  File "/usr/lib/python2.3/site-packages/pylab.py", line 1, in -toplevel-
    from matplotlib.pylab import *
  File "/usr/lib/python2.3/site-packages/matplotlib/pylab.py", line 198, 
in -toplevel-
    from axes import Axes, PolarAxes
  File "/usr/lib/python2.3/site-packages/matplotlib/axes.py", line 13, 
in -toplevel-
    from artist import Artist, setp
  File "/usr/lib/python2.3/site-packages/matplotlib/artist.py", line 4, 
in -toplevel-
    from transforms import identity_transform
  File "/usr/lib/python2.3/site-packages/matplotlib/transforms.py", line 
189, in -toplevel-
    from _transforms import Value, Point, Interval, Bbox, Affine
  File "/usr/lib/python2.3/site-packages/matplotlib/_transforms.py", 
line 11, in -toplevel-
    from matplotlib._nc_transforms import *
ImportError: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.4' not found 
(required by /usr/lib/python2.3/site-packages/matplotlib/_nc_transforms.so)

i have already installed libstdc++6, and i dont really know what version 
GLIBCXX_3.4.4 means.

anyone have an idea?

thanks
shawn

From cpu.crazy at gmail.com  Tue Sep 20 06:06:22 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Mon, 19 Sep 2005 22:06:22 -0600
Subject: [Tutor] IRC Client Trouble -- too many new lines
In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC0226A6F4@chbnt01.alpha.wd.govt.nz>
References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC0226A6F4@chbnt01.alpha.wd.govt.nz>
Message-ID: <66ca60fc05091921065e32d595@mail.gmail.com>

I just found py-irclib on sf.net <http://sf.net> but can't make heads or 
tails... mind if you could interperet anything and send me the results?
Attached is irclib.
Thanks for your help so far.
Joseph
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050919/ca488903/attachment-0001.htm
-------------- next part --------------
A non-text attachment was scrubbed...
Name: irclib.py
Type: text/x-python
Size: 48911 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050919/ca488903/irclib-0001.py

From dyoo at hkn.eecs.berkeley.edu  Tue Sep 20 18:34:26 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 20 Sep 2005 09:34:26 -0700 (PDT)
Subject: [Tutor] problem with matplot
In-Reply-To: <433022F2.5090704@xit.net>
Message-ID: <Pine.LNX.4.44.0509200927390.10341-100000@hkn.eecs.berkeley.edu>



> anyone have any luck getting up and running with matplot-lib on debian?
> from the website, i followed the instructions to get it with apt. but
> something is messed up in the dependencies.

Check with the Debian folks about this one; the problem you're running
into looks really specific to the way Debian has packaged libstdc++6.
This topic isn't really one that folks on Tutor will necessarily have
competence in.  Instead, try the debian-python mailing list:

    http://lists.debian.org/debian-python/

I did try to Google what was going on, and there's a thread in:

http://lists.badopi.org/pipermail/comandob/Week-of-Mon-20050801/011594.html

Unfortunately, I'm not quite sure what they're saying, given that it's not
English.  *grin* But I suspect that someone intimate with the Debian
packaging system would know what was going on here.


From nephish at xit.net  Tue Sep 20 18:35:28 2005
From: nephish at xit.net (nephish)
Date: Tue, 20 Sep 2005 11:35:28 -0500
Subject: [Tutor] problem with matplot
In-Reply-To: <Pine.LNX.4.44.0509200927390.10341-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509200927390.10341-100000@hkn.eecs.berkeley.edu>
Message-ID: <43303A50.7020708@xit.net>

Danny Yoo wrote:

>  
>
>>anyone have any luck getting up and running with matplot-lib on debian?
>>from the website, i followed the instructions to get it with apt. but
>>something is messed up in the dependencies.
>>    
>>
>
>Check with the Debian folks about this one; the problem you're running
>into looks really specific to the way Debian has packaged libstdc++6.
>This topic isn't really one that folks on Tutor will necessarily have
>competence in.  Instead, try the debian-python mailing list:
>
>    http://lists.debian.org/debian-python/
>
>I did try to Google what was going on, and there's a thread in:
>
>http://lists.badopi.org/pipermail/comandob/Week-of-Mon-20050801/011594.html
>
>Unfortunately, I'm not quite sure what they're saying, given that it's not
>English.  *grin* But I suspect that someone intimate with the Debian
>packaging system would know what was going on here.
>
>
>  
>
thanks for the links, i will dig some more, i know this isnt really a 
python issue, but i thought that since debian is popular, matplot is 
most peoples recommendation for graphing, and it is for python.......
figgured i may not be the only one to run into this brick wall.
anyway, thanks for your time, maybe an upgrade to 'testing' will help 
for this package.
ok, thanks much.
shawn

From dyoo at hkn.eecs.berkeley.edu  Tue Sep 20 18:58:36 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 20 Sep 2005 09:58:36 -0700 (PDT)
Subject: [Tutor] problem with matplot
In-Reply-To: <43303A50.7020708@xit.net>
Message-ID: <Pine.LNX.4.44.0509200948590.18128-100000@hkn.eecs.berkeley.edu>

> >Check with the Debian folks about this one; the problem you're running
> >into looks really specific to the way Debian has packaged libstdc++6.
> >This topic isn't really one that folks on Tutor will necessarily have
> >competence in.  Instead, try the debian-python mailing list:
> >
> >    http://lists.debian.org/debian-python/
> >
> thanks for the links, i will dig some more, i know this isnt really a
> python issue, but i thought that since debian is popular, matplot is
> most peoples recommendation for graphing, and it is for python.......


True, but let's try to maintain the topical "Learn to program"  nature of
the mailing list.  I really want to try to avoid turning Tutor into the
"Help with installing package X on system Y" mailing list.  We'll try to
help out as best we can on such questions, of course, but this is probably
not the best place to ask this.

I guess I'm really trying to say: let's try to keep Tutor from turning
into comp.lang.python.  *grin*

>From the Google searches I've done so far, this problem really doesn't
look specific to Python, but basically to anything that links up with the
libstdc++ library on both Debian and Red Hat systems.  It's not exclusive
to Python, and since it's so far reaching, I have to assume that it's the
particular Linux distribution's faul... er, responsibility.


From nephish at xit.net  Tue Sep 20 19:12:48 2005
From: nephish at xit.net (nephish)
Date: Tue, 20 Sep 2005 12:12:48 -0500
Subject: [Tutor] problem with matplot
In-Reply-To: <Pine.LNX.4.44.0509200948590.18128-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509200948590.18128-100000@hkn.eecs.berkeley.edu>
Message-ID: <43304310.1060509@xit.net>

Danny Yoo wrote:

>>>Check with the Debian folks about this one; the problem you're running
>>>into looks really specific to the way Debian has packaged libstdc++6.
>>>This topic isn't really one that folks on Tutor will necessarily have
>>>competence in.  Instead, try the debian-python mailing list:
>>>
>>>   http://lists.debian.org/debian-python/
>>>
>>>      
>>>
>>thanks for the links, i will dig some more, i know this isnt really a
>>python issue, but i thought that since debian is popular, matplot is
>>most peoples recommendation for graphing, and it is for python.......
>>    
>>
>
>
>True, but let's try to maintain the topical "Learn to program"  nature of
>the mailing list.  I really want to try to avoid turning Tutor into the
>"Help with installing package X on system Y" mailing list.  We'll try to
>help out as best we can on such questions, of course, but this is probably
>not the best place to ask this.
>
>I guess I'm really trying to say: let's try to keep Tutor from turning
>into comp.lang.python.  *grin*
>
>>From the Google searches I've done so far, this problem really doesn't
>look specific to Python, but basically to anything that links up with the
>libstdc++ library on both Debian and Red Hat systems.  It's not exclusive
>to Python, and since it's so far reaching, I have to assume that it's the
>particular Linux distribution's faul... er, responsibility.
>
>
>  
>
he he he. yeah, i admit, i have been breezing over distrowatch.
sorry about the clutter. wont happen again. i don't know where i would
be without this list.
cheers,
sk

From mhansen at cso.atmel.com  Tue Sep 20 21:22:21 2005
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Tue, 20 Sep 2005 13:22:21 -0600
Subject: [Tutor] How do you organize code snippets?
In-Reply-To: <mailman.1620.1127083944.508.tutor@python.org>
References: <mailman.1620.1127083944.508.tutor@python.org>
Message-ID: <4330616D.3060006@cso.atmel.com>

> ------------------------------------------------------------------------
> 
> Subject:
> Re: [Tutor] How do you organize code snippets?
> From:
> Poor Yorick <tutor.python.org at pooryorick.com>
> Date:
> Sun, 18 Sep 2005 13:28:10 -0400
> 
> CC:
> tutor at python.org
> 
> 
> List wrote:
> 
>> Is there a way of naming or organizing snippets that might help? (For 
>> example, file i/o snippets, text processing snippets, etc.)
>>
> 
> If you really want to have fun, you can use LEO, 
> http://webpages.charter.net/edreamleo/front.html to store your code 
> snippets and generate files from them.  The fun part is that you can 
> clone each node which may contain some code and move the clone to a 
> different point in the hierarchy.  When you change your code in any of 
> the clones, it gets changed in all of the clones.  At the most basic 
> level, you can use LEO as on outliner, like Treepad.  If you decide to 
> get more complicated, you can use LEO as a templating tool to generate 
> your resulting .py files from your snippets.
> 
> -- 
> Poor Yorick

I'm facing a similar problem. I was hoping to find some sort of snippets plug-in 
for VIM, but haven't come across anything. I found a couple of open source 
snippet database programs for Windows. One kept crashing on my machine and the 
other was kind of klunky. LEO looks promising. I'm reading through the tutorial now.

Mike

From forestiero at qwest.net  Tue Sep 20 21:49:19 2005
From: forestiero at qwest.net (DogWalker)
Date: Tue, 20 Sep 2005 12:49:19 -0700
Subject: [Tutor] How do you organize code snippets?
In-Reply-To: <4330616D.3060006@cso.atmel.com>
References: <mailman.1620.1127083944.508.tutor@python.org>
	<4330616D.3060006@cso.atmel.com>
Message-ID: <20050920194414.22858.13234@linux.local>

"Mike Hansen" <mhansen at cso.atmel.com> said:

[...]

http://freshmeat.net/projects/pysnippet/

From billburns at pennswoods.net  Tue Sep 20 22:06:06 2005
From: billburns at pennswoods.net (Bill Burns)
Date: Tue, 20 Sep 2005 16:06:06 -0400
Subject: [Tutor] Threading in a for loop
Message-ID: <43306BAE.1070404@pennswoods.net>

I've got a few questions regarding Threading. I've never used threads
before and I want to make sure I'm doing it correctly ;-)

I have a GUI app and it processes Tiff files to PDF (or PostScript). The
GUI has a ListBox which the user populates with files to convert. You
click on a Button and the file conversion starts. When all the files
have been converted, the ListBox items (the files) are cleared.

Initially, you had no way of knowing what was going on until all the
files where cleared from the ListBox.

So I thought of creating threads in the 'for loop' and displaying the
name of each file in the statusBar of the GUI (as they are being
processed).

Here's my method which takes the files in the ListBox and sends them off
to my Convert() class (self.convert = Convert()).
<code>
def convertTiff2PDF(self):
     from time import time
     #Let's see how long this takes... I saw Kent do this on the
     #Python Tutor list before :-)
     start = time()
     #Grab a tuple which contains width & length
     sizes = self.getPaperSize()
     width = sizes[0]
     length = sizes[1]
     #Count the number of files in the ListBox
     fileCount = self.fileListBox.count()
     for index in range(fileCount):
         #Get each filename
         filenames = str(self.fileListBox.text(index))
         #Setup the worker thread and send the filenames in
         worker = WorkerThread(self, filenames)
         #Start threading
         worker.start()
         #Send each file to be converted
         self.convert.tiff2pdf(width, length, filenames)
     #We're done, so clear the ListBox
     self.fileListBox.clear()
     #Check the time again
     end = time()
     msg = '%s Files Processed in %0.3f Seconds.' % (fileCount,
(end-start))
     #Grab the statusBar and insert the message
     statusBar = self.statusBar()
     statusBar.message(msg, 0)
</code>

And here's what I'm doing in my Thread class:
<code>
class WorkerThread(Thread):
     """Thread class."""
     def __init__(self, parent, files):
         Thread.__init__(self)
         self.parent = parent
         self.files = files

     def run(self):
         statusBar = self.parent.statusBar()
         msg = 'Processing: %s, please wait.' % (self.files)
         statusBar.message(msg, 100)
         time.sleep(1)
</code>

Am I doing this threading properly? Is it 'OK' to start multiple threads
like this (in the for loop)? It's possible that a user could put 'many'
files into the ListBox, by 'many' I mean 100-200 files.

Thanks for your help.

Bill



From 3dbernard at gmail.com  Wed Sep 21 00:05:31 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Tue, 20 Sep 2005 18:05:31 -0400
Subject: [Tutor] Maths: getting degrees from radians (or am I wrong?)
Message-ID: <61d0e2b4050920150539e6b294@mail.gmail.com>

Hello,

I have this little math problem. I have this formula from wich I get a
dot product between two vectors.

cos(?) = A.B / |A|.|B| = -0.0634
So this would give me radians, right?

Then if I use

math.degrees( -0.0634 )

This gives me a value of -3.6325524211294193.

However I have a book in front of me who says I should get a value of
93.635 degrees. mmmmm

Btw, in the book, the equation is written

? = cos-1(-0.0634) = 93.635, where -1 is actually an exponent. Maybe
I'm just interpreting this wrong?



Thanks
Bernard

From kent37 at tds.net  Wed Sep 21 00:30:11 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 20 Sep 2005 18:30:11 -0400
Subject: [Tutor] Maths: getting degrees from radians (or am I wrong?)
In-Reply-To: <61d0e2b4050920150539e6b294@mail.gmail.com>
References: <61d0e2b4050920150539e6b294@mail.gmail.com>
Message-ID: <43308D73.3060109@tds.net>

Bernard Lebel wrote:
> Hello,
> 
> I have this little math problem. I have this formula from wich I get a
> dot product between two vectors.
> 
> cos(?) = A.B / |A|.|B| = -0.0634
> So this would give me radians, right?

No, it's the cosine of ?, which has no units (a cosine is a ratio of two lengths)

> 
> Then if I use
> 
> math.degrees( -0.0634 )
> 
> This gives me a value of -3.6325524211294193.
> 
> However I have a book in front of me who says I should get a value of
> 93.635 degrees. mmmmm
> 
> Btw, in the book, the equation is written
> 
> ? = cos-1(-0.0634) = 93.635, where -1 is actually an exponent. Maybe
> I'm just interpreting this wrong?

The -1 means inverse. You have cos(?) = -0.0634 - you want to find the angle whose cosine is -0.0634, i.e. (inverse cosine)(-0.0634). Another name for cos-1 is arccosine. In Python it is math.acos():
 >>> import math
 >>> math.acos(-0.0634)
1.6342388771557625
 >>> math.degrees(_)
93.634990377223801

Kent
> 
> 
> 
> Thanks
> Bernard
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From amonroe at columbus.rr.com  Wed Sep 21 00:51:27 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Tue, 20 Sep 2005 18:51:27 -0400
Subject: [Tutor] Maths: getting degrees from radians (or am I wrong?)
In-Reply-To: <43308D73.3060109@tds.net>
References: <61d0e2b4050920150539e6b294@mail.gmail.com>
	<43308D73.3060109@tds.net>
Message-ID: <111270358164.20050920185127@columbus.rr.com>

> Bernard Lebel wrote:

>  >>> import math
>  >>> math.acos(-0.0634)
> 1.6342388771557625
>  >>> math.degrees(_)  <--- in all my time on tutor
                             I have never noticed
                             this underscore trick
                             before
> 93.634990377223801

That's quite handy.

Alan


From john at fouhy.net  Wed Sep 21 01:09:26 2005
From: john at fouhy.net (John Fouhy)
Date: Wed, 21 Sep 2005 11:09:26 +1200
Subject: [Tutor] Maths: getting degrees from radians (or am I wrong?)
In-Reply-To: <111270358164.20050920185127@columbus.rr.com>
References: <61d0e2b4050920150539e6b294@mail.gmail.com>
	<43308D73.3060109@tds.net>
	<111270358164.20050920185127@columbus.rr.com>
Message-ID: <5e58f2e40509201609640f431a@mail.gmail.com>

On 21/09/05, R. Alan Monroe <amonroe at columbus.rr.com> wrote:
> >  >>> math.degrees(_)  <--- in all my time on tutor
>                              I have never noticed
>                              this underscore trick
>                              before

I'm not a big fan of it, actually.  It smells of Perl and those opaque
one-liners that make use of implicit functions implicitely setting
implicit variables...

-- 
John.

From com.pooryorick.lists at pooryorick.com  Wed Sep 21 01:45:06 2005
From: com.pooryorick.lists at pooryorick.com (Nathan Coulter)
Date: Tue, 20 Sep 2005 19:45:06 -0400
Subject: [Tutor] Maths: getting degrees from radians (or am I wrong?)
In-Reply-To: <5e58f2e40509201609640f431a@mail.gmail.com>
References: <61d0e2b4050920150539e6b294@mail.gmail.com>	<43308D73.3060109@tds.net>	<111270358164.20050920185127@columbus.rr.com>
	<5e58f2e40509201609640f431a@mail.gmail.com>
Message-ID: <43309F02.7060106@pooryorick.com>

John Fouhy wrote:
> On 21/09/05, R. Alan Monroe <amonroe at columbus.rr.com> wrote:
> 
>>> >>> math.degrees(_)  <--- in all my time on tutor
>>
>>                             I have never noticed
>>                             this underscore trick
>>                             before
> 
> 
> I'm not a big fan of it, actually.  It smells of Perl and those opaque
> one-liners that make use of implicit functions implicitely setting
> implicit variables...
> 

It also only works in *interactive* interpreters. -- Poor Yorick

From kent37 at tds.net  Wed Sep 21 04:05:33 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 20 Sep 2005 22:05:33 -0400
Subject: [Tutor] Maths: getting degrees from radians (or am I wrong?)
In-Reply-To: <5e58f2e40509201609640f431a@mail.gmail.com>
References: <61d0e2b4050920150539e6b294@mail.gmail.com>	<43308D73.3060109@tds.net>	<111270358164.20050920185127@columbus.rr.com>
	<5e58f2e40509201609640f431a@mail.gmail.com>
Message-ID: <4330BFED.6010209@tds.net>

John Fouhy wrote:
> On 21/09/05, R. Alan Monroe <amonroe at columbus.rr.com> wrote:
> 
>>> >>> math.degrees(_)  <--- in all my time on tutor
>>
>>                             I have never noticed
>>                             this underscore trick
>>                             before
> 
> 
> I'm not a big fan of it, actually.  It smells of Perl and those opaque
> one-liners that make use of implicit functions implicitely setting
> implicit variables...

I'm actually not much of a fan either - it's too easy to lose what I wanted by doing another step, then it's too late. And I usually don't use it on tutor because I think it is a bit obscure. This time I wondered if anyone would notice :-)

Kent


From carroll at tjc.com  Wed Sep 21 07:59:56 2005
From: carroll at tjc.com (Terry Carroll)
Date: Tue, 20 Sep 2005 22:59:56 -0700 (PDT)
Subject: [Tutor] Maths: getting degrees from radians (or am I wrong?)
In-Reply-To: <111270358164.20050920185127@columbus.rr.com>
Message-ID: <Pine.LNX.4.44.0509202257050.16968-100000@violet.rahul.net>

On Tue, 20 Sep 2005, R. Alan Monroe wrote:

> >  >>> math.degrees(_)  <--- in all my time on tutor
>                              I have never noticed
>                              this underscore trick
>                              before


That *is* cool.

I've usually done something like:

 >>> a+ 3*b +(5*ht/9) * 32
 9936254.2

Then use the up-arrow key to get

 >>> a+ 3*b +(5*ht/9) * 32

and edit it toL

 >>> x = a+ 3*b +(5*ht/9) * 32
 >>> foo(x)

The underscore's a nice stepsaver.  And limiting it to the interpreter 
avoids perlish abuse.


From singletoned at gmail.com  Wed Sep 21 15:00:20 2005
From: singletoned at gmail.com (Ed Singleton)
Date: Wed, 21 Sep 2005 14:00:20 +0100
Subject: [Tutor] Python Editors (particualrly Vim)
Message-ID: <34bb7f5b05092106005a1dcd49@mail.gmail.com>

I've been trying to decide which editor to use to edit Python (on
Windows mostly).

My wishlist of features would be:

- automatic code formatting (indentation etc)
- collapsible code (to collapse def's etc)
- automatic code coloring (that's easily changeable)
- auto-completion of namespaces
- easy to run scripts from the editor (a shortcut key to run them or something)

As I also do a lot of html, css and javascript it would be cool to
have an editor that could also handle them, in which case I would want
the same features for those languages, as well as the ability to write
macros, scripts, etc in python.

Having looked at loads of editors, I've ended up looking at emacs and vim.

Emacs seems too difficult with not enough support for using the mouse.

Vim seemed better, and I get the impression that it is possible to use
python to script the editor, but I can't find much information on
using vim as a python editor on windows.

My various questions are:

What other features should I be looking for?

What would be the best editor for a beginner to start using, with a
view to the long term?

Where can I find some authoritative information about setting emacs or
vim up as a fully featured python editor?

Thanks

Ed

From George.Flaherty at marketmax.com  Wed Sep 21 15:55:17 2005
From: George.Flaherty at marketmax.com (George Flaherty)
Date: Wed, 21 Sep 2005 09:55:17 -0400
Subject: [Tutor] Python Editors (particualrly Vim)
Message-ID: <59CF9F456FAA9045B405C441EC916F3E02DDFAB9@MERC24.na.sas.com>

 comments are inline.......

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Ed Singleton
Sent: Wednesday, September 21, 2005 9:00 AM
To: tutor at python.org
Subject: [Tutor] Python Editors (particualrly Vim)

I've been trying to decide which editor to use to edit Python (on Windows mostly).

My wishlist of features would be:

- automatic code formatting (indentation etc)

[george]: Emacs works great with this if you have python mode. Eclispe is the same.

- collapsible code (to collapse def's etc)

[george]: Eclipse is a little easier to perform this, but you can hide lines in Emacs as well. In emacs things are just a bit, "less visual" than eclipse.

- automatic code coloring (that's easily changeable)

[george]: Pretty much any editor will provide with this type of functionality.

- auto-completion of namespaces

[george]: Emacs does not (or I should say I have not found) any type of mode for code complete in python. There are rumors with improvements with CEDET(intellisense) for python, I haven't been able to use them. Eclipse with PyDEV works great, and if you are hardcore linux Eric3 will work too. Although you can run Eric3 on win32 there are a few extra steps needed to install. Also if you work in a commercial development shop, QT licensing for Eric3 might be an issue?

- easy to run scripts from the editor (a shortcut key to run them or something)

[george]: Emacs provides you a shell for which you can execute a script. You can extend lisp in Emacs as well, which is extremely flexible. I am not sure with eclipse regarding external scripts since I have just recently converted to eclipse from emacs(gasp!).I know you can call up python in interactive mode from eclipse, but I not sure how to call something like....myfoo.bat or myfoo.sh.
As with anything in eclipse....I am sure there has to be some type of plug-in or something for it.

As I also do a lot of html, css and javascript it would be cool to have an editor that could also handle them, in which case I would want the same features for those languages, as well as the ability to write macros, scripts, etc in python.

[george]: Lots of editors will support various mode. As for the code completion in javascipt and html I do not have an answer for those. 


Having looked at loads of editors, I've ended up looking at emacs and vim.

Emacs seems too difficult with not enough support for using the mouse.

[george]: Even though I am "some what" moving away from emacs, it is still a great editor. I am sure vim is good too, just my preference to use emacs. For mouse support....

Try including this in your .emacs file

(autoload 'mwheel-install "mwheel" "Enable wheely mouse")
(mwheel-install)


Vim seemed better, and I get the impression that it is possible to use python to script the editor, but I can't find much information on using vim as a python editor on windows.

[george]: I think that is fine, I do not have much experience with vim. I only use it about 5% out of the day, hopefully someone else could help you out.

My various questions are:

What other features should I be looking for?

[george]: I think you have them covered.... You might want to look at integrations with source control (cvs, svn, etc.) too. Also debuggers should be included as well.

What would be the best editor for a beginner to start using, with a view to the long term?

[george]: I think that is really user preference. Try them all out, you will most likely fall into which one fits your own needs.

Where can I find some authoritative information about setting emacs or vim up as a fully featured python editor?

[george]: check out sourceforge or freshmeat for add-ons and other modes.

[george]
Good luck
[/george]


Thanks

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

From 3dbernard at gmail.com  Wed Sep 21 16:05:38 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Wed, 21 Sep 2005 10:05:38 -0400
Subject: [Tutor] Maths: getting degrees from radians (or am I wrong?)
In-Reply-To: <43308D73.3060109@tds.net>
References: <61d0e2b4050920150539e6b294@mail.gmail.com>
	<43308D73.3060109@tds.net>
Message-ID: <61d0e2b4050921070521aac495@mail.gmail.com>

Okay thanks a lot everyone.

Bernard



On 9/20/05, Kent Johnson <kent37 at tds.net> wrote:
> Bernard Lebel wrote:
> > Hello,
> >
> > I have this little math problem. I have this formula from wich I get a
> > dot product between two vectors.
> >
> > cos(?) = A.B / |A|.|B| = -0.0634
> > So this would give me radians, right?
>
> No, it's the cosine of ?, which has no units (a cosine is a ratio of two lengths)
>
> >
> > Then if I use
> >
> > math.degrees( -0.0634 )
> >
> > This gives me a value of -3.6325524211294193.
> >
> > However I have a book in front of me who says I should get a value of
> > 93.635 degrees. mmmmm
> >
> > Btw, in the book, the equation is written
> >
> > ? = cos-1(-0.0634) = 93.635, where -1 is actually an exponent. Maybe
> > I'm just interpreting this wrong?
>
> The -1 means inverse. You have cos(?) = -0.0634 - you want to find the angle whose cosine is -0.0634, i.e. (inverse cosine)(-0.0634). Another name for cos-1 is arccosine. In Python it is math.acos():
>  >>> import math
>  >>> math.acos(-0.0634)
> 1.6342388771557625
>  >>> math.degrees(_)
> 93.634990377223801
>
> Kent
> >
> >
> >
> > Thanks
> > Bernard
> > _______________________________________________
> > 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
>

From jeffpeery at yahoo.com  Wed Sep 21 17:30:28 2005
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Wed, 21 Sep 2005 08:30:28 -0700 (PDT)
Subject: [Tutor] installation programs
In-Reply-To: <43312BF2.4070004@nglogic.com>
Message-ID: <20050921153029.89938.qmail@web30509.mail.mud.yahoo.com>


Hello, I want to create an installation program. Can anyone tell me what the best program would be to use... maybe inno setup or install shield? do these work with python programs? do they require programming in another language? thanks.

 

Jeff

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050921/85807c5a/attachment.htm

From ds-python-tutor at sidorof.com  Wed Sep 21 18:32:39 2005
From: ds-python-tutor at sidorof.com (DS)
Date: Wed, 21 Sep 2005 09:32:39 -0700
Subject: [Tutor] Error frameworks
Message-ID: <43318B27.6080900@sidorof.com>


Hi

Is there any particular standard or approach that I should use for an
error framework?  For example, suppose I have a set of functions that
call one another, and an error is triggered.  I want an error message to
be passed back to the user, so I could:

     1. have an error message passed back to each called function until
it bubbles up to a point to be passed back to the user in some
meaningful way.

     2. have a singleton error object updated.

     3.  ??

What do most people use?  Is there any url that you could point me to
that would help educate me on this point?

Thanks

ds



From kent37 at tds.net  Wed Sep 21 18:55:20 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Sep 2005 12:55:20 -0400
Subject: [Tutor] Error frameworks
In-Reply-To: <43318B27.6080900@sidorof.com>
References: <43318B27.6080900@sidorof.com>
Message-ID: <43319078.4070800@tds.net>

DS wrote:
> Hi
> 
> Is there any particular standard or approach that I should use for an
> error framework?  For example, suppose I have a set of functions that
> call one another, and an error is triggered.  I want an error message to
> be passed back to the user, so I could:

Raise an exception, either a built-in if one is appropriate, or one that you define.
http://docs.python.org/tut/node10.html tells you how
http://docs.python.org/lib/module-exceptions.html lists the built-in exceptions and what they mean

> 
>      1. have an error message passed back to each called function until
> it bubbles up to a point to be passed back to the user in some
> meaningful way.
> 
>      2. have a singleton error object updated.

Both these approaches have several drawbacks:
- Errors are easy to ignore or forget to handle
- Client code gets cluttered up with error-handling code

Kent
> 
>      3.  ??
> 
> What do most people use?  Is there any url that you could point me to
> that would help educate me on this point?
> 
> Thanks
> 
> ds
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From gsf at panix.com  Wed Sep 21 18:55:40 2005
From: gsf at panix.com (Gabriel Farrell)
Date: Wed, 21 Sep 2005 12:55:40 -0400
Subject: [Tutor] Python Editors (particualrly Vim)
In-Reply-To: <34bb7f5b05092106005a1dcd49@mail.gmail.com>
References: <34bb7f5b05092106005a1dcd49@mail.gmail.com>
Message-ID: <20050921165540.GA29780@panix.com>

Uh oh, looks like you're begging for an editor war. 

That said, I'm in the vim camp.  It can do everything you specified
for all of the languages you mention (well, I'm not sure about
collapsible code...web search...aha![1]).  After using it for four
years, I'm still learning new tricks (see, for example, this page I
found today on indentation[2]).

vim's extendable with python scripts, but a lot of what you need for
coding is already built in.  I find most of my info either in the help
manual that comes with it (:h) or at vim.org.

gsf

[1] http://www.dgp.toronto.edu/~mjmcguff/learn/vim/folding.txt
[2] http://www.vim.org/tips/tip.php?tip_id=83


On Wed, Sep 21, 2005 at 02:00:20PM +0100, Ed Singleton wrote:
> I've been trying to decide which editor to use to edit Python (on
> Windows mostly).
> 
> My wishlist of features would be:
> 
> - automatic code formatting (indentation etc)
> - collapsible code (to collapse def's etc)
> - automatic code coloring (that's easily changeable)
> - auto-completion of namespaces
> - easy to run scripts from the editor (a shortcut key to run them or something)
> 
> As I also do a lot of html, css and javascript it would be cool to
> have an editor that could also handle them, in which case I would want
> the same features for those languages, as well as the ability to write
> macros, scripts, etc in python.
> 
> Having looked at loads of editors, I've ended up looking at emacs and vim.
> 
> Emacs seems too difficult with not enough support for using the mouse.
> 
> Vim seemed better, and I get the impression that it is possible to use
> python to script the editor, but I can't find much information on
> using vim as a python editor on windows.
> 
> My various questions are:
> 
> What other features should I be looking for?
> 
> What would be the best editor for a beginner to start using, with a
> view to the long term?
> 
> Where can I find some authoritative information about setting emacs or
> vim up as a fully featured python editor?
> 
> Thanks
> 
> Ed
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From George.Flaherty at marketmax.com  Wed Sep 21 19:40:08 2005
From: George.Flaherty at marketmax.com (George Flaherty)
Date: Wed, 21 Sep 2005 13:40:08 -0400
Subject: [Tutor] Python Editors (particualrly Vim)
Message-ID: <59CF9F456FAA9045B405C441EC916F3E02DDFEA6@MERC24.na.sas.com>

No editor wars here...., my suggestion as I tried to state below is use what you like. Try'em all and take them for a test spin. Granted I might be slightly biased towards eclipse/emacs.....but that is just my world :)

Just out of curiosity, does vim have code completion for python? 

Cheers
-george


-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Gabriel Farrell
Sent: Wednesday, September 21, 2005 12:56 PM
To: tutor at python.org
Subject: Re: [Tutor] Python Editors (particualrly Vim)

Uh oh, looks like you're begging for an editor war. 

That said, I'm in the vim camp.  It can do everything you specified for all of the languages you mention (well, I'm not sure about collapsible code...web search...aha![1]).  After using it for four years, I'm still learning new tricks (see, for example, this page I found today on indentation[2]).

vim's extendable with python scripts, but a lot of what you need for coding is already built in.  I find most of my info either in the help manual that comes with it (:h) or at vim.org.

gsf

[1] http://www.dgp.toronto.edu/~mjmcguff/learn/vim/folding.txt
[2] http://www.vim.org/tips/tip.php?tip_id=83


On Wed, Sep 21, 2005 at 02:00:20PM +0100, Ed Singleton wrote:
> I've been trying to decide which editor to use to edit Python (on 
> Windows mostly).
> 
> My wishlist of features would be:
> 
> - automatic code formatting (indentation etc)
> - collapsible code (to collapse def's etc)
> - automatic code coloring (that's easily changeable)
> - auto-completion of namespaces
> - easy to run scripts from the editor (a shortcut key to run them or 
> something)
> 
> As I also do a lot of html, css and javascript it would be cool to 
> have an editor that could also handle them, in which case I would want 
> the same features for those languages, as well as the ability to write 
> macros, scripts, etc in python.
> 
> Having looked at loads of editors, I've ended up looking at emacs and vim.
> 
> Emacs seems too difficult with not enough support for using the mouse.
> 
> Vim seemed better, and I get the impression that it is possible to use 
> python to script the editor, but I can't find much information on 
> using vim as a python editor on windows.
> 
> My various questions are:
> 
> What other features should I be looking for?
> 
> What would be the best editor for a beginner to start using, with a 
> view to the long term?
> 
> Where can I find some authoritative information about setting emacs or 
> vim up as a fully featured python editor?
> 
> Thanks
> 
> Ed
> _______________________________________________
> 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

From grouch at gmail.com  Wed Sep 21 19:40:49 2005
From: grouch at gmail.com (grouchy)
Date: Wed, 21 Sep 2005 12:40:49 -0500
Subject: [Tutor] installation programs
In-Reply-To: <20050921153029.89938.qmail@web30509.mail.mud.yahoo.com>
References: <43312BF2.4070004@nglogic.com>
	<20050921153029.89938.qmail@web30509.mail.mud.yahoo.com>
Message-ID: <e6443aa705092110405185652f@mail.gmail.com>

Hi Jeff,

Most people seem to use a combination of py2exe, and either Inno Setup or
NSIS. InstallShield is commercial, and, well, you have to pay for it.

py2exe gives you the python interpreter, and all the libraries your program
needs in a tidy little package, so unless the computers you are installing
to have python and any external libraries you are using already installed,
you will need to use that, or something similar. It lets people just install
and run.

Inno Setup is easy if you don't need anything fancy, ie a simple install
made with it's wizard. Packaging things up with py2exe will likely be the
tricky part, at least if you start trimming it down manually, or run into
any snags. Otherwise it's a breeze. NSIS has a scripting language built in,
which does indeed entail learning another language(sorta). I haven't used
it, however, so there could be lots you can do without touching the
scripting bit.

py2exe: http://starship.python.net/crew/theller/py2exe/
NSIS: http://nsis.sourceforge.net/

Good luck!

On 9/21/05, Jeff Peery < jeffpeery at yahoo.com> wrote:
>
>  Hello, I want to create an installation program. Can anyone tell me what
> the best program would be to use... maybe inno setup or install shield? do
> these work with python programs? do they require programming in another
> language? thanks.
>
>  Jeff
>
>
> _______________________________________________
> 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/20050921/fd8a2369/attachment.htm

From shendric at uga.edu  Wed Sep 21 21:00:10 2005
From: shendric at uga.edu (Sean Q. Hendricks)
Date: Wed, 21 Sep 2005 12:00:10 -0700
Subject: [Tutor] Stopping a shell process started with system()
Message-ID: <4331ADBA.4000004@uga.edu>

Hi all,

I'm trying to write a simple front end for a commandline application 
(some of the people I'm working with get the shakes if they have to use 
the commandline) in Windows.  I was using os.system() to execute a 
command, and that works fine, but the only way I know to stop the 
external program is to hit CTRL-C.  On *nix, as I understand it, you 
could create a Popen3 class instance, which would have the pid as a 
property of the class, which can be used to call a kill on that pid to 
stop the program.  But, indications are that this is not available for 
Windows, so I'm wondering if there is a better option than os.system() 
or if there is just something I'm missing.  Any help would be 
appreciated.  I'm using Python 2.3 on Win 2k.

Sean

-- 
***Please note new email address: shendric at uga.edu***


From George.Flaherty at marketmax.com  Wed Sep 21 20:40:23 2005
From: George.Flaherty at marketmax.com (George Flaherty)
Date: Wed, 21 Sep 2005 14:40:23 -0400
Subject: [Tutor] FW:  Python Editors (particualrly Vim)
Message-ID: <59CF9F456FAA9045B405C441EC916F3E02DDFFFB@MERC24.na.sas.com>

forwarding.....

________________________________

From: Pujo Aji [mailto:ajikoe at gmail.com] 
Sent: Wednesday, September 21, 2005 2:39 PM
To: George Flaherty
Subject: Re: [Tutor] Python Editors (particualrly Vim)


I tried pydev, xemacs, komodo, vim, wingide, scite, drPython, pype, idle
Each has each own strength point. If I choose the three of them I will choose:
1. wingide (good intellisense, but you have to setup some preferences to suit your need)
2. komodo (has good colour choice)
3. scite (very simple)
 
All are great and I use all of the three.
 
You can only try one by one and decide which one is good for you.
 
Sincerely Yours,
pujo

 
On 9/21/05, George Flaherty <George.Flaherty at marketmax.com> wrote: 

	No editor wars here...., my suggestion as I tried to state below is use what you like. Try'em all and take them for a test spin. Granted I might be slightly biased towards eclipse/emacs.....but that is just my world :) 
	
	Just out of curiosity, does vim have code completion for python?
	
	Cheers
	-george
	
	
	-----Original Message-----
	From: tutor-bounces at python.org [mailto: tutor-bounces at python.org] On Behalf Of Gabriel Farrell
	Sent: Wednesday, September 21, 2005 12:56 PM
	To: tutor at python.org
	Subject: Re: [Tutor] Python Editors (particualrly Vim) 
	
	Uh oh, looks like you're begging for an editor war.
	
	That said, I'm in the vim camp.  It can do everything you specified for all of the languages you mention (well, I'm not sure about collapsible code...web search...aha![1]).  After using it for four years, I'm still learning new tricks (see, for example, this page I found today on indentation[2]). 
	
	vim's extendable with python scripts, but a lot of what you need for coding is already built in.  I find most of my info either in the help manual that comes with it (:h) or at vim.org .
	
	gsf
	
	[1] http://www.dgp.toronto.edu/~mjmcguff/learn/vim/folding.txt
	[2] http://www.vim.org/tips/tip.php?tip_id=83 
	
	
	On Wed, Sep 21, 2005 at 02:00:20PM +0100, Ed Singleton wrote:
	> I've been trying to decide which editor to use to edit Python (on
	> Windows mostly).
	>
	> My wishlist of features would be: 
	>
	> - automatic code formatting (indentation etc)
	> - collapsible code (to collapse def's etc)
	> - automatic code coloring (that's easily changeable)
	> - auto-completion of namespaces
	> - easy to run scripts from the editor (a shortcut key to run them or 
	> something)
	>
	> As I also do a lot of html, css and javascript it would be cool to
	> have an editor that could also handle them, in which case I would want
	> the same features for those languages, as well as the ability to write 
	> macros, scripts, etc in python.
	>
	> Having looked at loads of editors, I've ended up looking at emacs and vim.
	>
	> Emacs seems too difficult with not enough support for using the mouse.
	>
	> Vim seemed better, and I get the impression that it is possible to use
	> python to script the editor, but I can't find much information on
	> using vim as a python editor on windows.
	>
	> My various questions are: 
	>
	> What other features should I be looking for?
	>
	> What would be the best editor for a beginner to start using, with a
	> view to the long term?
	>
	> Where can I find some authoritative information about setting emacs or 
	> vim up as a fully featured python editor?
	>
	> Thanks
	>
	> Ed
	> _______________________________________________
	> Tutor maillist  -  Tutor at python.org 
	> http://mail.python.org/mailman/listinfo/tutor
	>
	_______________________________________________
	Tutor maillist  -   Tutor at python.org <mailto:Tutor at python.org> 
	http://mail.python.org/mailman/listinfo/tutor
	_______________________________________________
	Tutor maillist  -   Tutor at python.org <mailto: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/20050921/e03fa8c5/attachment.html

From kabads at gmail.com  Wed Sep 21 20:44:49 2005
From: kabads at gmail.com (Adam Cripps)
Date: Wed, 21 Sep 2005 19:44:49 +0100
Subject: [Tutor] cgi.FieldStorage to int
Message-ID: <c7ff385505092111445b6bbcc4@mail.gmail.com>

I'm trying to get a cgi.FieldStorage into an int.

The input is in numeric form, as it is provided by an <option>
drop-down box. However, when I try

timestable = int(form.getvalue('timestable'))

I get an error that the type is None - I guess this is because
FieldStorage is a class. However, I've trawled around trying to get
this field into an integer but without any luck.

Any pointers appreciated.
TIA
Adam
--
http://www.monkeez.org
PGP key: 0x7111B833

From kent37 at tds.net  Wed Sep 21 20:59:43 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Sep 2005 14:59:43 -0400
Subject: [Tutor] Error frameworks
In-Reply-To: <4331A639.2050805@sidorof.com>
References: <43318B27.6080900@sidorof.com> <43319078.4070800@tds.net>
	<4331A639.2050805@sidorof.com>
Message-ID: <4331AD9F.2020105@tds.net>

(Please reply to the tutor list, not to me privately)

DS wrote:
> Thanks for looking at my problem.  Let me try to explain what bothers me
> about raising an error:
> 
> Below is a brain-dead example of one function calling another which
> calls another.  If in function3 I raise an error, function2 properly
> catches an error, but function1 doesn't have a clue what went wrong. 
> However, if I want to have function provide the notification and/or
> handling of the error messages back to the user, then I must have a
> means of propagating that error back up the line.  In this example,
> since the error is given back as a string rather than a numeric, it
> still shows an error, but for general purposes this seems like a bad
> approach.  I've thought of having a tuple returned (answer, error) which
> would carry the message back to function 1, but that seems awkward as well.

Generally, you want to catch the exception at the level that knows what to do about it. Your function2() isn't handling the exception in any meaningful sense, it is just converting it to a magic return value. You might as well just use magic return values everywhere if you do this.

Even function1() seems like it is too low-level to handle the error since it is also just converting the error to a magic return.

For short, simple scripts you can often omit exception handling completely. Any raised exceptions will propagate to the interpreter which will print a stack trace and exit. This is very handy - you get to see exactly where the error occured and the details of the exception type and message. This style may also be appropriate for handling any fatal error even in a complex script.

For more complex scripts, for example a server or GUI app, or a script that processes many items, you probably don't want to exit the script on an error. In this case you might have a high-level exception handler that logs the exception and continues. For example here is a loop that processes a list of items, if there is an error processing an item a traceback is printed and the processing continues:

import traceback
def processLotsOfStuff(listOfStuff):
  for item in listOfStuff:
    try:
      processOneItem(item)
    except:
      print 'Error processing item', item
      traceback.print_exc()

Kent

> 
> Thanks for your help.
> 
> ds
> 
> *def* function1(value):
> 
>     /#   to simply this just calls the next function/
> 	*try*:
> 		value1 = function2(value)
> 		value1 += 1
> 	*except*:
> 		value1 = 'but what is the error?'
> 		
> 	*return* value1
> 
> *def* function2(value):
>     /#   to simply this just calls the next function/
> 	*try*:
> 		value2 = function3(value)
> 	*except*:
> 		value2 = 'error'
> 
> 	*return* value2
> 
> *def* function3(value):
>     /#   let's say real work is performed here/
> 	/#	the input has to be real number, for example/
> 	
> 	*if* value < 0:
> 		*raise* "this is bad, very bad"
> 	*else*:
> 		*return* value + 1
> 
> 
> 
> Kent Johnson wrote:
> 
> 
>>DS wrote:
>> 
>>
>>
>>>Hi
>>>
>>>Is there any particular standard or approach that I should use for an
>>>error framework?  For example, suppose I have a set of functions that
>>>call one another, and an error is triggered.  I want an error message to
>>>be passed back to the user, so I could:
>>>   
>>>
>>
>>Raise an exception, either a built-in if one is appropriate, or one that you define.
>>http://docs.python.org/tut/node10.html tells you how
>>http://docs.python.org/lib/module-exceptions.html lists the built-in exceptions and what they mean
>>
>> 
>>
>>
>>>    1. have an error message passed back to each called function until
>>>it bubbles up to a point to be passed back to the user in some
>>>meaningful way.
>>>
>>>    2. have a singleton error object updated.
>>>   
>>>
>>
>>Both these approaches have several drawbacks:
>>- Errors are easy to ignore or forget to handle
>>- Client code gets cluttered up with error-handling code
>>
>>Kent
>> 
>>
>>
>>>    3.  ??
>>>
>>>What do most people use?  Is there any url that you could point me to
>>>that would help educate me on this point?
>>>
>>>Thanks
>>>
>>>ds
>>>
>>>
>>>_______________________________________________
>>>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
>> 
>>
> 
> 
> 
> 


From kent37 at tds.net  Wed Sep 21 21:06:46 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Sep 2005 15:06:46 -0400
Subject: [Tutor] cgi.FieldStorage to int
In-Reply-To: <c7ff385505092111445b6bbcc4@mail.gmail.com>
References: <c7ff385505092111445b6bbcc4@mail.gmail.com>
Message-ID: <4331AF46.5010108@tds.net>

Adam Cripps wrote:
> I'm trying to get a cgi.FieldStorage into an int.
> 
> The input is in numeric form, as it is provided by an <option>
> drop-down box. However, when I try
> 
> timestable = int(form.getvalue('timestable'))
> 
> I get an error that the type is None - I guess this is because
> FieldStorage is a class. However, I've trawled around trying to get
> this field into an integer but without any luck.

My guess is that there is no 'timestable' parameter - are you sure you spelled it the same way in the form? Try adding 
import sys
print >>sys.stderr, form.keys()

to the form, I think this will print a list of available parameters to the console.

Kent


From kabads at gmail.com  Wed Sep 21 21:17:25 2005
From: kabads at gmail.com (Adam Cripps)
Date: Wed, 21 Sep 2005 20:17:25 +0100
Subject: [Tutor] cgi.FieldStorage to int
In-Reply-To: <4331AF46.5010108@tds.net>
References: <c7ff385505092111445b6bbcc4@mail.gmail.com>
	<4331AF46.5010108@tds.net>
Message-ID: <c7ff38550509211217614bf17b@mail.gmail.com>

On 9/21/05, Kent Johnson <kent37 at tds.net> wrote:
> Adam Cripps wrote:
> > I'm trying to get a cgi.FieldStorage into an int.
> >
> > The input is in numeric form, as it is provided by an <option>
> > drop-down box. However, when I try
> >
> > timestable = int(form.getvalue('timestable'))
> >
> > I get an error that the type is None - I guess this is because
> > FieldStorage is a class. However, I've trawled around trying to get
> > this field into an integer but without any luck.
>
> My guess is that there is no 'timestable' parameter - are you sure you spelled it the same way in the form? Try adding
> import sys
> print >>sys.stderr, form.keys()
>
> to the form, I think this will print a list of available parameters to the console.
>
> Kent
>

Great minds think alike, but alas I'm pretty sure it's not the issue -
I've already checked whether timestable existed with:

print "timestable is...", form.getvalue('timestable')

and it displays fine.

Adam

From kent37 at tds.net  Wed Sep 21 21:29:40 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Sep 2005 15:29:40 -0400
Subject: [Tutor] cgi.FieldStorage to int
In-Reply-To: <c7ff38550509211217614bf17b@mail.gmail.com>
References: <c7ff385505092111445b6bbcc4@mail.gmail.com>	<4331AF46.5010108@tds.net>
	<c7ff38550509211217614bf17b@mail.gmail.com>
Message-ID: <4331B4A4.2090000@tds.net>

Adam Cripps wrote:
> On 9/21/05, Kent Johnson <kent37 at tds.net> wrote:
> 
>>Adam Cripps wrote:
>>
>>>I'm trying to get a cgi.FieldStorage into an int.
>>>
>>>The input is in numeric form, as it is provided by an <option>
>>>drop-down box. However, when I try
>>>
>>>timestable = int(form.getvalue('timestable'))
>>>
>>>I get an error that the type is None - I guess this is because
>>>FieldStorage is a class. However, I've trawled around trying to get
>>>this field into an integer but without any luck.

Please post the exact error message including the stack trace. Also, what prints when you print form.getvalue('timestable')

Kent

>>
>>My guess is that there is no 'timestable' parameter - are you sure you spelled it the same way in the form? Try adding
>>import sys
>>print >>sys.stderr, form.keys()
>>
>>to the form, I think this will print a list of available parameters to the console.
>>
>>Kent
>>
> 
> 
> Great minds think alike, but alas I'm pretty sure it's not the issue -
> I've already checked whether timestable existed with:
> 
> print "timestable is...", form.getvalue('timestable')
> 
> and it displays fine.
> 
> Adam
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From genietdev0 at iol.ie  Wed Sep 21 21:35:21 2005
From: genietdev0 at iol.ie (Victor Reijs)
Date: Wed, 21 Sep 2005 20:35:21 +0100
Subject: [Tutor] dialog boxes for Windows
Message-ID: <4331B5F9.3080808@iol.ie>

Hello all of you,

I want to use yes/no-, text-, info-, checklist- dialog boxes in my image
manipulation program (on a Windows XP Pro system using python 2.2 and
2.3). What is the best way to do this?
Do peopel have some examples or links? I want to know which python 
modules are needed and where to get.

Thanks for your feedback.


All the best,


Victor





From tutor.python.org at pooryorick.com  Wed Sep 21 21:49:56 2005
From: tutor.python.org at pooryorick.com (Poor Yorick)
Date: Wed, 21 Sep 2005 15:49:56 -0400
Subject: [Tutor] Python, vim, indentation, and wrapped lines
Message-ID: <4331B964.8080405@pooryorick.com>

I use Vim as my primary Python code editor.  I've always wondered if 
there is a way to make wrapped lines take on the indentation of the 
previous line.  Of course I mean *in the display only*, since I don't 
want any newlines introduced.  This would also be handy for me when 
editing indented html/xml documents.  Anyone know how to do this in vim?

--
Poor Yorick

From kent37 at tds.net  Wed Sep 21 21:54:26 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 21 Sep 2005 15:54:26 -0400
Subject: [Tutor] dialog boxes for Windows
In-Reply-To: <4331B5F9.3080808@iol.ie>
References: <4331B5F9.3080808@iol.ie>
Message-ID: <4331BA72.80405@tds.net>

Victor Reijs wrote:
> Hello all of you,
> 
> I want to use yes/no-, text-, info-, checklist- dialog boxes in my image
> manipulation program (on a Windows XP Pro system using python 2.2 and
> 2.3). What is the best way to do this?

If your program does not have a GUI and you want to add some simple dialog boxes then EasyGUI might work for you:
http://www.ferg.org/easygui/

If your needs go beyond this then you will have to choose a GUI toolkit and learn to use it. The two most popular GUI toolkits for Python on Windows seem to be Tkinter (which is included with Python, see http://wiki.python.org/moin/TkInter for info) and wxPython (http://www.wxpython.org). Which is "better" is a matter of opinion. I think the general consensus is that Tkinter is easier to use for simple projects and wxPython has more variety of widgets and may be better for a complex GUI.

Kent

> Do peopel have some examples or links? I want to know which python 
> modules are needed and where to get.
> 
> Thanks for your feedback.
> 
> 
> All the best,
> 
> 
> Victor
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From ds-python-tutor at sidorof.com  Wed Sep 21 22:32:07 2005
From: ds-python-tutor at sidorof.com (DS)
Date: Wed, 21 Sep 2005 13:32:07 -0700
Subject: [Tutor] Error frameworks
Message-ID: <4331C347.6020008@sidorof.com>

>>(Please reply to the tutor list, not to me privately)

whoops

>>Generally, you want to catch the exception at the level that knows what to do about it. Your function2() isn't handling the exception in any meaningful sense, it is just converting it to a magic return value. You might as well just use magic return values everywhere if you do this.

>>Even function1() seems like it is too low-level to handle the error since it is also just converting the error to a magic return.

>>For short, simple scripts you can often omit exception handling completely. Any raised exceptions will propagate to the interpreter which will print a stack trace and exit. This is very handy - you get to see exactly where the error occured and the details of the exception type and message. This style may also be appropriate for handling any fatal error even in a complex script.

>>For more complex scripts, for example a server or GUI app, or a script that processes many items, you probably don't want to exit the script on an error. In this case you might have a high-level exception handler that logs the exception and continues. For example here is a loop that processes a list of items, if there is an error processing an item a traceback is printed and the processing continues:



I think you are correct that I haven't been letting my raised errors propagate high enough.  That helps.  Thanks very much.

ds




From kabads at gmail.com  Wed Sep 21 23:11:32 2005
From: kabads at gmail.com (Adam Cripps)
Date: Wed, 21 Sep 2005 22:11:32 +0100
Subject: [Tutor] cgi.FieldStorage to int
In-Reply-To: <4331B4A4.2090000@tds.net>
References: <c7ff385505092111445b6bbcc4@mail.gmail.com>
	<4331AF46.5010108@tds.net> <c7ff38550509211217614bf17b@mail.gmail.com>
	<4331B4A4.2090000@tds.net>
Message-ID: <c7ff3855050921141132644463@mail.gmail.com>

On 9/21/05, Kent Johnson <kent37 at tds.net> wrote:
> Adam Cripps wrote:
> > On 9/21/05, Kent Johnson <kent37 at tds.net> wrote:
> >
> >>Adam Cripps wrote:
> >>
> >>>I'm trying to get a cgi.FieldStorage into an int.
> >>>
> >>>The input is in numeric form, as it is provided by an <option>
> >>>drop-down box. However, when I try
> >>>
> >>>timestable = int(form.getvalue('timestable'))
> >>>
> >>>I get an error that the type is None - I guess this is because
> >>>FieldStorage is a class. However, I've trawled around trying to get
> >>>this field into an integer but without any luck.
>
> Please post the exact error message including the stack trace. Also, what prints when you print form.getvalue('timestable')
>
> Kent

Ok - thanks for the tipoff Kent - the problem is now solved. My
timestable was returning as a list, as it was being populated in a
loop (for each question in the times table). Once I moved it outside
of the loop, the int(form.getvalue('timestable') works fine.

Adam
--
http://www.monkeez.org
PGP key: 0x7111B833

From singletoned at gmail.com  Thu Sep 22 00:00:00 2005
From: singletoned at gmail.com (Ed Singleton)
Date: Wed, 21 Sep 2005 22:00:00 +0000
Subject: [Tutor] Python Editors (particualrly Vim)
In-Reply-To: <20050921165540.GA29780@panix.com>
References: <34bb7f5b05092106005a1dcd49@mail.gmail.com>
	<20050921165540.GA29780@panix.com>
Message-ID: <34bb7f5b0509211500d14ec63@mail.gmail.com>

I don't believe there's any kinds of wars on this mailing group.  :)

I found this Python Vim code completion thing in my searches today:
http://freshmeat.net/projects/pydiction/

Don't know how good it is, but it looks like it'd do the job.

Ed

On 21/09/05, Gabriel Farrell <gsf at panix.com> wrote:
> Uh oh, looks like you're begging for an editor war.
>
> That said, I'm in the vim camp.  It can do everything you specified
> for all of the languages you mention (well, I'm not sure about
> collapsible code...web search...aha![1]).  After using it for four
> years, I'm still learning new tricks (see, for example, this page I
> found today on indentation[2]).
>
> vim's extendable with python scripts, but a lot of what you need for
> coding is already built in.  I find most of my info either in the help
> manual that comes with it (:h) or at vim.org.
>
> gsf
>
> [1] http://www.dgp.toronto.edu/~mjmcguff/learn/vim/folding.txt
> [2] http://www.vim.org/tips/tip.php?tip_id=83
>
>
> On Wed, Sep 21, 2005 at 02:00:20PM +0100, Ed Singleton wrote:
> > I've been trying to decide which editor to use to edit Python (on
> > Windows mostly).
> >
> > My wishlist of features would be:
> >
> > - automatic code formatting (indentation etc)
> > - collapsible code (to collapse def's etc)
> > - automatic code coloring (that's easily changeable)
> > - auto-completion of namespaces
> > - easy to run scripts from the editor (a shortcut key to run them or something)
> >
> > As I also do a lot of html, css and javascript it would be cool to
> > have an editor that could also handle them, in which case I would want
> > the same features for those languages, as well as the ability to write
> > macros, scripts, etc in python.
> >
> > Having looked at loads of editors, I've ended up looking at emacs and vim.
> >
> > Emacs seems too difficult with not enough support for using the mouse.
> >
> > Vim seemed better, and I get the impression that it is possible to use
> > python to script the editor, but I can't find much information on
> > using vim as a python editor on windows.
> >
> > My various questions are:
> >
> > What other features should I be looking for?
> >
> > What would be the best editor for a beginner to start using, with a
> > view to the long term?
> >
> > Where can I find some authoritative information about setting emacs or
> > vim up as a fully featured python editor?
> >
> > Thanks
> >
> > Ed
> > _______________________________________________
> > 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
>

From bob.nienhuis at gmail.com  Thu Sep 22 00:36:01 2005
From: bob.nienhuis at gmail.com (Bob Nienhuis)
Date: Wed, 21 Sep 2005 15:36:01 -0700
Subject: [Tutor] Calling Modules in ActiveState 2.4
Message-ID: <45109da505092115361c4f4f70@mail.gmail.com>

Working my way through Alan Gauld's tutorial, and I am on the
section on modules.

When I call:
import sys
sys.exit()
I get a traceback error saying it needs more input

Same when I do:
import sys
print sys.path()

Both of these work if I do
sys.exit
or print sys.path without the parentheses.
Is this new behavior in Activstate 2.4, or do I need
to set an environment variable?

Bob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050921/306f5560/attachment.html

From damien.gouteux at gmail.com  Thu Sep 22 00:42:34 2005
From: damien.gouteux at gmail.com (Damien Gouteux)
Date: Thu, 22 Sep 2005 00:42:34 +0200
Subject: [Tutor] Calling Modules in ActiveState 2.4
In-Reply-To: <45109da505092115361c4f4f70@mail.gmail.com>
References: <45109da505092115361c4f4f70@mail.gmail.com>
Message-ID: <4331E1DA.5030907@gmail.com>

For exit:
You need to put an argument (more input) :
import sys
sys.exit(0)
The argument of exit is the return value of your script (0 = okay, other 
= problem).
sys.path is an attribute (of type list) of sys not a function.
So don't put () after path.
I hope it will help.
Damien.

Bob Nienhuis wrote:

> Working my way through Alan Gauld's tutorial, and I am on the
> section on modules.
>
> When I call:
> import sys
> sys.exit()
> I get a traceback error saying it needs more input
>
> Same when I do:
> import sys
> print sys.path()
>
> Both of these work if I do
> sys.exit
> or print sys.path without the parentheses.
> Is this new behavior in Activstate 2.4, or do I need
> to set an environment variable?
>
> Bob
>
>
>------------------------------------------------------------------------
>
>_______________________________________________
>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/20050922/531afb43/attachment-0001.htm

From dyoo at hkn.eecs.berkeley.edu  Thu Sep 22 01:21:25 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 21 Sep 2005 16:21:25 -0700 (PDT)
Subject: [Tutor] Calling Modules in ActiveState 2.4
In-Reply-To: <4331E1DA.5030907@gmail.com>
Message-ID: <Pine.LNX.4.44.0509211611001.9419-100000@hkn.eecs.berkeley.edu>


Hi Bob,


Bob, when you see these kinds of errors, please don't paraphrase the error
message.  You mentioned:

> > When I call:
> > import sys
> > sys.exit()
> > I get a traceback error saying it needs more input

Instead of putting the error in your own, just copy-and-paste the error.
Don't worry about verbosity here: we really like seeing good error
messages.  Honest!  *grin*

The reason this is important is because when things break, there could be
any number of reasons why.  We have to be able to know that the problems
we're seeing are the same problems that you're seeing: otherwise, we might
be "fixing" something that has nothing to do with your particular problem.

The code you have written works for me personally, so there must be
something context-sensitive going on here that I'm not seeing yet.
That's why, when we're debugging, we need to see the exact error message
that you're seeing too: it's just one of those valuable additional clues
that we use when figuring out what's going on.


Good luck to you!


From bob.nienhuis at gmail.com  Thu Sep 22 01:23:15 2005
From: bob.nienhuis at gmail.com (Bob Nienhuis)
Date: Wed, 21 Sep 2005 16:23:15 -0700
Subject: [Tutor] Calling Modules in ActiveState 2.4
In-Reply-To: <4331E1DA.5030907@gmail.com>
References: <45109da505092115361c4f4f70@mail.gmail.com>
	<4331E1DA.5030907@gmail.com>
Message-ID: <45109da50509211623382ff178@mail.gmail.com>

When I do:
import sys
sys.exit(0)
I get:
Traceback (most recent call last):
File "C:\Python24\Lib\site-packages\pythonwin\pywin\scintilla\bindings.py",
line 141, in fire
rc = apply(binding.handler, args)
File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\interact.py",
line 478, in ProcessEnterEvent
if self.interp.runsource(source, "<interactive input>"): # Need more input!
File "C:\Python24\lib\code.py", line 87, in runsource
self.runcode(code)
File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\interact.py",
line 257, in runcode
exec code in self.globals, self.locals
File "<interactive input>", line 1, in ?
SystemExit: 0

Bob

On 9/21/05, Damien Gouteux <damien.gouteux at gmail.com> wrote:
>
> For exit:
> You need to put an argument (more input) :
> import sys
> sys.exit(0)
> The argument of exit is the return value of your script (0 = okay, other =
> problem).
> sys.path is an attribute (of type list) of sys not a function.
> So don't put () after path.
> I hope it will help.
> Damien.
>
> Bob Nienhuis wrote:
>
> Working my way through Alan Gauld's tutorial, and I am on the
> section on modules.
>
> When I call:
> import sys
> sys.exit()
> I get a traceback error saying it needs more input
>
> Same when I do:
> import sys
> print sys.path()
>
> Both of these work if I do
> sys.exit
> or print sys.path without the parentheses.
> Is this new behavior in Activstate 2.4, or do I need
> to set an environment variable?
>
> Bob
>
>
> ------------------------------
>
> _______________________________________________
> 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/20050921/155f8cc7/attachment.html

From bob.nienhuis at gmail.com  Thu Sep 22 01:29:56 2005
From: bob.nienhuis at gmail.com (Bob Nienhuis)
Date: Wed, 21 Sep 2005 16:29:56 -0700
Subject: [Tutor] Calling Modules in ActiveState 2.4
In-Reply-To: <45109da50509211623382ff178@mail.gmail.com>
References: <45109da505092115361c4f4f70@mail.gmail.com>
	<4331E1DA.5030907@gmail.com>
	<45109da50509211623382ff178@mail.gmail.com>
Message-ID: <45109da5050921162950f2cd5e@mail.gmail.com>

Just tried again. Got:
>>> import sys
>>> sys.exit()
Firing event 'ProcessEnter' failed.
Traceback (most recent call last):
File "C:\Python24\Lib\site-packages\pythonwin\pywin\scintilla\bindings.py",
line 141, in fire
rc = apply(binding.handler, args)
File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\interact.py",
line 478, in ProcessEnterEvent
if self.interp.runsource(source, "<interactive input>"): # Need more input!
File "C:\Python24\lib\code.py", line 87, in runsource
self.runcode(code)
File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\interact.py",
line 257, in runcode
exec code in self.globals, self.locals
File "<interactive input>", line 1, in ?
SystemExit

sys.exit(0)
>>>

On 9/21/05, Bob Nienhuis <bob.nienhuis at gmail.com> wrote:
>
> When I do:
> import sys
> sys.exit(0)
> I get:
> Traceback (most recent call last):
> File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\scintilla\bindings.py", line
> 141, in fire
> rc = apply(binding.handler, args)
> File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\interact.py", line
> 478, in ProcessEnterEvent
> if self.interp.runsource(source, "<interactive input>"): # Need more
> input!
> File "C:\Python24\lib\code.py", line 87, in runsource
> self.runcode(code)
> File
> "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\interact.py", line
> 257, in runcode
> exec code in self.globals, self.locals
> File "<interactive input>", line 1, in ?
> SystemExit: 0
>
> Bob
>
> On 9/21/05, Damien Gouteux <damien.gouteux at gmail.com> wrote:
> >
> > For exit:
> > You need to put an argument (more input) :
> > import sys
> > sys.exit(0)
> > The argument of exit is the return value of your script (0 = okay, other
> > = problem).
> > sys.path is an attribute (of type list) of sys not a function.
> > So don't put () after path.
> > I hope it will help.
> > Damien.
> >
> > Bob Nienhuis wrote:
> >
> > Working my way through Alan Gauld's tutorial, and I am on the
> > section on modules.
> >
> > When I call:
> > import sys
> > sys.exit()
> > I get a traceback error saying it needs more input
> >
> > Same when I do:
> > import sys
> > print sys.path()
> >
> > Both of these work if I do
> > sys.exit
> > or print sys.path without the parentheses.
> > Is this new behavior in Activstate 2.4, or do I need
> > to set an environment variable?
> >
> > Bob
> >
> >
> > ------------------------------
> >
> > _______________________________________________
> > 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/20050921/bf251ea5/attachment.html

From dyoo at hkn.eecs.berkeley.edu  Thu Sep 22 01:45:08 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 21 Sep 2005 16:45:08 -0700 (PDT)
Subject: [Tutor] Calling Modules in ActiveState 2.4
In-Reply-To: <45109da50509211623382ff178@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509211636160.17648-100000@hkn.eecs.berkeley.edu>



On Wed, 21 Sep 2005, Bob Nienhuis wrote:

> When I do:
> import sys
> sys.exit(0)
> I get:
> Traceback (most recent call last):
> File "C:\Python24\Lib\site-packages\pythonwin\pywin\scintilla\bindings.py",
> line 141, in fire
> rc = apply(binding.handler, args)
> File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\interact.py",
> line 478, in ProcessEnterEvent
> if self.interp.runsource(source, "<interactive input>"): # Need more input!
> File "C:\Python24\lib\code.py", line 87, in runsource
> self.runcode(code)
> File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\interact.py",
> line 257, in runcode
> exec code in self.globals, self.locals
> File "<interactive input>", line 1, in ?
> SystemExit: 0


Ok, good, thanks for the error message: that clears up exactly what's
going on.  (Actually, that looks like a bug in PythonWin: it should handle
that particular situation a little bit more cleanly.)

Bob, what's happening is just the nature of the command you're executing:
sys.exit() is telling Python to exit.  But since the PythonWin text editor
itself depends on Python staying up, it rejects the exit command, as it
should!

Your interpretation that it was "asking for more input" wasn't accurate.
Instead, the error message is saying: "The user gave me this interactive
input command for me to run, but when I did, it raised an exception that I
don't know how to handle.  I'll spit out this debugging information for
something to inspect."


So try different module functions besides sys.exit().  I think things are
actually fine: you're just testing out a function that you shouldn't be
running on the PythonWin interactive prompt.

A different module you can play with is the 'math' module:

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



Good luck!


From falcon3166 at hotmail.com  Thu Sep 22 08:20:33 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Thu, 22 Sep 2005 00:20:33 -0600
Subject: [Tutor] Challenge [was Re:  Why won't it enter the quiz?]
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
	<432B8CA9.2000200@christianfreebies.com>
Message-ID: <BAY106-DAV159F309A389BF7EECD88A1C4970@phx.gbl>

I have a challenge for everyone on the tutor list. Take this serious, and 
don't think I'm asking it just because I am mad or something. I'm not, I 
just want to clear the air once and for all. Here is the challenge:

Choose any program that I am selling on my site, any one of them, and ask me 
for the code. I'll gladly send you a copy. Determine if I have copied most 
of it, or wrote most of it myself. Post your analysis to the group. If you 
determine that I have copied most of it, I'll remove it and post an apology. 
If not, you must admit that I wrote most of it myself. Fair enough?

Farewell for now,
Nathan Pinno.
----- Original Message ----- 
From: "Byron" <byron at christianfreebies.com>
To: "Nathan Pinno" <falcon3166 at hotmail.com>; <Tutor at python.org>
Sent: Friday, September 16, 2005 9:25 PM
Subject: Re: [Tutor] Why won't it enter the quiz?


> Nathan Pinno wrote:
>> Brian and all,
>>
>> I am just asking for help - after all I write most each program myself, 
>> and just ask for help in debugging it whenever I cannot figure it out. If 
>> this is being sneaky, I apologize, and won't ask for help anymore.
>
>
> No, don't do that... Happy that you are asking questions!  I was humored 
> by the idea that you have a GREAT business model there...  :-)  FREE 
> Labor -- wow, should of thought of that one earlier...  <big grin>
>
> Have a great weekend and hope you keep posting!
>
> Brian
> ---
>
>
>
> 

From matthew.williams at cancer.org.uk  Thu Sep 22 10:43:09 2005
From: matthew.williams at cancer.org.uk (Matt Williams)
Date: Thu, 22 Sep 2005 09:43:09 +0100
Subject: [Tutor] Python DB
Message-ID: <1127378589.5821.5.camel@localhost.localdomain>

Dear List,

I've been looking for a simple python based DB for a fairly simple app.
Only a single user, single access needed, but with a dynamic structure
(which needs to be extensible very easily).

Having googled and read some stuff, I seem to come down to a choice
between KirbyBase (very nice and simple, and has the advantages of text-
based files) or ZODB. I have a bit of an allergy to SQL, even if
mediated via SQLObject (which looks very nice)

These seem to be at the opposite end of the spectrum - so do others have
either comments on these options, or other suggestions.

Thanks,
Matt


From chris.arndt at web.de  Thu Sep 22 11:29:33 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Thu, 22 Sep 2005 10:29:33 +0100
Subject: [Tutor] Python DB
In-Reply-To: <1127378589.5821.5.camel@localhost.localdomain>
References: <1127378589.5821.5.camel@localhost.localdomain>
Message-ID: <4332797D.40403@web.de>

Matt Williams schrieb:
> These seem to be at the opposite end of the spectrum - so do others have
> either comments on these options, or other suggestions.

Well, I havn't use either yet, but I have some experience with SQL DBs.
>From what I read on the website, Kirby seems like a nice idea, if you really
need nothing more than table-structured data, made up of simple data types.

It only supports basic data types (int, float, string, boolean, date[time]) no
objects and it isn't even relational, i.e. you can't express references between
tables or columns and when querying for data, you can do so only from one table
at a time. This makes it very hard to normalize your data, because you would
have to handle all the relations between tables in your code. The nice thing
is, it writes flat text files, you can edit by hand or probably even import
into a spreadsheet application.

ZOBD, on the other hand, is a totally differnt beast. It doesn't store data in
tables, but stores (as the name says) objects, which might feel more natural to
use in your code. Note, that it is written partly in C and as such, might not
be so easy to deploy as a pure-python solution like Kirby.

Just my 2 centy, Chris

From dyoo at hkn.eecs.berkeley.edu  Thu Sep 22 11:41:32 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 22 Sep 2005 02:41:32 -0700 (PDT)
Subject: [Tutor] Python DB
In-Reply-To: <1127378589.5821.5.camel@localhost.localdomain>
Message-ID: <Pine.LNX.4.44.0509220237230.27385-100000@hkn.eecs.berkeley.edu>



On Thu, 22 Sep 2005, Matt Williams wrote:

> I've been looking for a simple python based DB for a fairly simple app.
> Only a single user, single access needed, but with a dynamic structure
> (which needs to be extensible very easily).

Hi Matt,

What kind of data are you trying to represent?  And how large will that
data be?

The reason I ask is because I'm going to lead with the silly question:
would something like the "shelve" module be sufficent?

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

I'm just making sure we can cross 'shelve' off as not viable for the
application.  But knowing why 'shelve' would be unsuitable will be helpful
in figuring out a good solution.  *grin*


From kent37 at tds.net  Thu Sep 22 12:00:49 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 22 Sep 2005 06:00:49 -0400
Subject: [Tutor] Python DB
In-Reply-To: <1127378589.5821.5.camel@localhost.localdomain>
References: <1127378589.5821.5.camel@localhost.localdomain>
Message-ID: <433280D1.4010300@tds.net>

Matt Williams wrote:
> Dear List,
> 
> I've been looking for a simple python based DB for a fairly simple app.
> Only a single user, single access needed, but with a dynamic structure
> (which needs to be extensible very easily).
> 
> Having googled and read some stuff, I seem to come down to a choice
> between KirbyBase (very nice and simple, and has the advantages of text-
> based files) or ZODB. I have a bit of an allergy to SQL, even if
> mediated via SQLObject (which looks very nice)

You should look at pysqlite, it's fairly lightweight.
http://initd.org/tracker/pysqlite

Kent


From Pawel_Kraszewski at wp.pl  Thu Sep 22 14:14:31 2005
From: Pawel_Kraszewski at wp.pl (Pawel Kraszewski)
Date: Thu, 22 Sep 2005 14:14:31 +0200
Subject: [Tutor] Python DB
In-Reply-To: <1127378589.5821.5.camel@localhost.localdomain>
References: <1127378589.5821.5.camel@localhost.localdomain>
Message-ID: <200509221414.31732.Pawel_Kraszewski@wp.pl>

Dnia czwartek, 22 wrze?nia 2005 10:43, Matt Williams napisa?:

> I've been looking for a simple python based DB for a fairly simple app.
> Only a single user, single access needed, but with a dynamic structure
> (which needs to be extensible very easily).

For pure Python implementation you might try SnakeSQL 
(http://www.pythonweb.org/projects/snakesql/):

---[CITE]---
SnakeSQL is a pure Python SQL database written to remove the dependence of the 
Python Web Modules on 3rd party drivers for non-Python databases like MySQL 
but designed to be a useful database in its own right.
The database supports the simplest possible subset of ANSI SQL 92 including 
NULLs (something other pure Python databases such as Gadfly do not currently 
support) as well as more advanced features such as foreign key constraints 
and simple joins.

The database is fully DB-API 2.0 compliant and is written in layers so that it 
can easily be extended to support different storage mechanisms. Currently 
implemented are a fast binary DBM driver (default) and a slower CSV file 
driver (handy for viewing table contents when designing and developing an 
application or database structure).
---[/CITE]---

If you don't need pure-Python,take a look at gadfly 
(http://gadfly.sourceforge.net)

If the data isn't too big, you may even try XML storage with DOM access (PyXML 
http://pyxml.sourceforge.net/)

HTH,
-- 
 Pawel Kraszewski

From work at infomaniak.ch  Thu Sep 22 14:25:22 2005
From: work at infomaniak.ch (Cedric BRINER)
Date: Thu, 22 Sep 2005 14:25:22 +0200
Subject: [Tutor] Python DB
In-Reply-To: <1127378589.5821.5.camel@localhost.localdomain>
References: <1127378589.5821.5.camel@localhost.localdomain>
Message-ID: <20050922122522.GG12501@obs.unige.ch>

I love sqlobject.org
it this a wrapper between many sql implementation (mysql, postgresql..) and python.

get a look.

Ced.

-- 

Cedric BRINER
Geneva - Switzerland

From edhotchkiss at gmail.com  Thu Sep 22 14:28:57 2005
From: edhotchkiss at gmail.com (Ed Hotchkiss)
Date: Thu, 22 Sep 2005 08:28:57 -0400
Subject: [Tutor] Python DB
In-Reply-To: <20050922122522.GG12501@obs.unige.ch>
References: <1127378589.5821.5.camel@localhost.localdomain>
	<20050922122522.GG12501@obs.unige.ch>
Message-ID: <d1bf1fa205092205282bb4b960@mail.gmail.com>

i like MySQLdb - although I said that you hate MySQL. FreeSQL.org has a nice
free MySQL server. I also have some example code if you would like from work
that I did last week ...
 -ed

 On 9/22/05, Cedric BRINER <work at infomaniak.ch> wrote:
>
> I love sqlobject.org <http://sqlobject.org>
> it this a wrapper between many sql implementation (mysql, postgresql..)
> and python.
>
> get a look.
>
> Ced.
>
> --
>
> Cedric BRINER
> Geneva - Switzerland
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



--
edward hotchkiss
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050922/2c99c9d2/attachment.htm

From singletoned at gmail.com  Thu Sep 22 14:54:49 2005
From: singletoned at gmail.com (Ed Singleton)
Date: Thu, 22 Sep 2005 13:54:49 +0100
Subject: [Tutor] Python Editors (particualrly Vim)
In-Reply-To: <34bb7f5b0509211500d14ec63@mail.gmail.com>
References: <34bb7f5b05092106005a1dcd49@mail.gmail.com>
	<20050921165540.GA29780@panix.com>
	<34bb7f5b0509211500d14ec63@mail.gmail.com>
Message-ID: <34bb7f5b0509220554689bd974@mail.gmail.com>

Okay, I've also found this:
http://cream.sourceforge.net/features.html

Which is amazing!  It's an easy-to-use mod for Vim.  It's modeless and
lots of other doubtless heretical things, but it includes an
outstanding auto-complete mode for text files!  Ctrl-Space auto
completes the word you're typing based on what you've already written
in the file.

I've also been trying SPE and that looks to be the most pleasing
editor so far.  It's also written in Python (AFAICT) which will
probably have benefits in the future.

Ed

On 21/09/05, Ed Singleton <singletoned at gmail.com> wrote:
> I don't believe there's any kinds of wars on this mailing group.  :)
>
> I found this Python Vim code completion thing in my searches today:
> http://freshmeat.net/projects/pydiction/
>
> Don't know how good it is, but it looks like it'd do the job.
>
> Ed
>
> On 21/09/05, Gabriel Farrell <gsf at panix.com> wrote:
> > Uh oh, looks like you're begging for an editor war.
> >
> > That said, I'm in the vim camp.  It can do everything you specified
> > for all of the languages you mention (well, I'm not sure about
> > collapsible code...web search...aha![1]).  After using it for four
> > years, I'm still learning new tricks (see, for example, this page I
> > found today on indentation[2]).
> >
> > vim's extendable with python scripts, but a lot of what you need for
> > coding is already built in.  I find most of my info either in the help
> > manual that comes with it (:h) or at vim.org.
> >
> > gsf
> >
> > [1] http://www.dgp.toronto.edu/~mjmcguff/learn/vim/folding.txt
> > [2] http://www.vim.org/tips/tip.php?tip_id=83
> >
> >
> > On Wed, Sep 21, 2005 at 02:00:20PM +0100, Ed Singleton wrote:
> > > I've been trying to decide which editor to use to edit Python (on
> > > Windows mostly).
> > >
> > > My wishlist of features would be:
> > >
> > > - automatic code formatting (indentation etc)
> > > - collapsible code (to collapse def's etc)
> > > - automatic code coloring (that's easily changeable)
> > > - auto-completion of namespaces
> > > - easy to run scripts from the editor (a shortcut key to run them or something)
> > >
> > > As I also do a lot of html, css and javascript it would be cool to
> > > have an editor that could also handle them, in which case I would want
> > > the same features for those languages, as well as the ability to write
> > > macros, scripts, etc in python.
> > >
> > > Having looked at loads of editors, I've ended up looking at emacs and vim.
> > >
> > > Emacs seems too difficult with not enough support for using the mouse.
> > >
> > > Vim seemed better, and I get the impression that it is possible to use
> > > python to script the editor, but I can't find much information on
> > > using vim as a python editor on windows.
> > >
> > > My various questions are:
> > >
> > > What other features should I be looking for?
> > >
> > > What would be the best editor for a beginner to start using, with a
> > > view to the long term?
> > >
> > > Where can I find some authoritative information about setting emacs or
> > > vim up as a fully featured python editor?
> > >
> > > Thanks
> > >
> > > Ed
> > > _______________________________________________
> > > 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
> >
>

From johan at accesstel.co.za  Thu Sep 22 15:05:19 2005
From: johan at accesstel.co.za (Johan Geldenhuys)
Date: Thu, 22 Sep 2005 15:05:19 +0200
Subject: [Tutor] Python Editors (particualrly Vim)
In-Reply-To: <34bb7f5b0509220554689bd974@mail.gmail.com>
References: <34bb7f5b05092106005a1dcd49@mail.gmail.com>
	<20050921165540.GA29780@panix.com>
	<34bb7f5b0509211500d14ec63@mail.gmail.com>
	<34bb7f5b0509220554689bd974@mail.gmail.com>
Message-ID: <1127394320.7081.23.camel@KMA.accesstel>

jedit is also good. I use that. The only thing is that you can't execute
the script from there. It is great for collapsing at indentions.
www.jedit.org

Johan
On Thu, 2005-09-22 at 13:54 +0100, Ed Singleton wrote:

> Okay, I've also found this:
> http://cream.sourceforge.net/features.html
> 
> Which is amazing!  It's an easy-to-use mod for Vim.  It's modeless and
> lots of other doubtless heretical things, but it includes an
> outstanding auto-complete mode for text files!  Ctrl-Space auto
> completes the word you're typing based on what you've already written
> in the file.
> 
> I've also been trying SPE and that looks to be the most pleasing
> editor so far.  It's also written in Python (AFAICT) which will
> probably have benefits in the future.
> 
> Ed
> 
> On 21/09/05, Ed Singleton <singletoned at gmail.com> wrote:
> > I don't believe there's any kinds of wars on this mailing group.  :)
> >
> > I found this Python Vim code completion thing in my searches today:
> > http://freshmeat.net/projects/pydiction/
> >
> > Don't know how good it is, but it looks like it'd do the job.
> >
> > Ed
> >
> > On 21/09/05, Gabriel Farrell <gsf at panix.com> wrote:
> > > Uh oh, looks like you're begging for an editor war.
> > >
> > > That said, I'm in the vim camp.  It can do everything you specified
> > > for all of the languages you mention (well, I'm not sure about
> > > collapsible code...web search...aha![1]).  After using it for four
> > > years, I'm still learning new tricks (see, for example, this page I
> > > found today on indentation[2]).
> > >
> > > vim's extendable with python scripts, but a lot of what you need for
> > > coding is already built in.  I find most of my info either in the help
> > > manual that comes with it (:h) or at vim.org.
> > >
> > > gsf
> > >
> > > [1] http://www.dgp.toronto.edu/~mjmcguff/learn/vim/folding.txt
> > > [2] http://www.vim.org/tips/tip.php?tip_id=83
> > >
> > >
> > > On Wed, Sep 21, 2005 at 02:00:20PM +0100, Ed Singleton wrote:
> > > > I've been trying to decide which editor to use to edit Python (on
> > > > Windows mostly).
> > > >
> > > > My wishlist of features would be:
> > > >
> > > > - automatic code formatting (indentation etc)
> > > > - collapsible code (to collapse def's etc)
> > > > - automatic code coloring (that's easily changeable)
> > > > - auto-completion of namespaces
> > > > - easy to run scripts from the editor (a shortcut key to run them or something)
> > > >
> > > > As I also do a lot of html, css and javascript it would be cool to
> > > > have an editor that could also handle them, in which case I would want
> > > > the same features for those languages, as well as the ability to write
> > > > macros, scripts, etc in python.
> > > >
> > > > Having looked at loads of editors, I've ended up looking at emacs and vim.
> > > >
> > > > Emacs seems too difficult with not enough support for using the mouse.
> > > >
> > > > Vim seemed better, and I get the impression that it is possible to use
> > > > python to script the editor, but I can't find much information on
> > > > using vim as a python editor on windows.
> > > >
> > > > My various questions are:
> > > >
> > > > What other features should I be looking for?
> > > >
> > > > What would be the best editor for a beginner to start using, with a
> > > > view to the long term?
> > > >
> > > > Where can I find some authoritative information about setting emacs or
> > > > vim up as a fully featured python editor?
> > > >
> > > > Thanks
> > > >
> > > > Ed
> > > > _______________________________________________
> > > > 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
> > >
> >
> _______________________________________________
> 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/20050922/fe192b13/attachment-0001.html

From nephish at xit.net  Thu Sep 22 15:08:01 2005
From: nephish at xit.net (nephish)
Date: Thu, 22 Sep 2005 08:08:01 -0500
Subject: [Tutor] time challange
Message-ID: <4332ACB1.9040605@xit.net>

Hey there,

i use mx.DateTime.RelativeDateTimeDiff to get the difference between 
date_x and date_y.
what i need to do divide this amount of time into 20 different times 
that spaced out between the date_x and the date_y.

so if the difference between date_x and date_y is 20 hours, i need 20 
DateTimes that are one hour apart from each other. If the difference is 
40 minutes, i need the 20 DateTimes to be spaced out 2 minutes from each 
other..

what would be a way to pull this off? i have looked at the docs for 
mxDateTime
http://www.egenix.com/files/python/mxDateTime.html
and there seems to be a divide operation, but i dont quite know what it 
is talking about
with the deltas.

anyone have a good start point?

thanks
shawn

From lists at janeden.org  Thu Sep 22 15:27:32 2005
From: lists at janeden.org (Jan Eden)
Date: Thu, 22 Sep 2005 15:27:32 +0200
Subject: [Tutor] Using superclass __init__ method
Message-ID: <r02010500-1039-A1EBCFB02B6C11DA9473000A959B4026@[10.149.23.208]>

Hi,

I just noticed that in the following environment:

class Base:
    def __init__(self):
        ...

class Child(Base):
    pass
    
the following statement:

child = Child()

would automatically execute the superclass __init__ method. This is exactly what I was looking for - but in the Cookbook, I found several suggestions on how to actively force the invocation of the superclass __init__.

Is this behvaiour documented?

Thanks,

Jan
-- 
There are 10 kinds of people:  those who understand binary, and those who don't

From matthew.williams at cancer.org.uk  Thu Sep 22 15:31:28 2005
From: matthew.williams at cancer.org.uk (Matt Williams)
Date: Thu, 22 Sep 2005 14:31:28 +0100
Subject: [Tutor] Python DB
In-Reply-To: <mailman.2153.1127394334.508.tutor@python.org>
References: <mailman.2153.1127394334.508.tutor@python.org>
Message-ID: <1127395888.5821.33.camel@localhost.localdomain>

Dear List,

Thanks for all the advice! Obviously, I'm still a bit torn, but some of
the ideas looked good.

In terms of spec, the DB can be fairly simple (single access, etc.).
Lower dependency on other libraries is good. Also, it needs to be cross-
platform.

The problem (I have) with SQL-type DB is that I cannot be sure ahead of
time of the exact data structure. The DB will be about patients, who
have diseases, and also have treatments.....Clearly, I can't specify now
the exact structure of the table. The advantage of SQL is that you can
(in general) do things like constrain types for fields, and give
enumerated options, which makes the data more consistent.

The thing I liked about KirbyBase was that it used text files. This is a
real advantage, as it means that I can access the data from other
application easily, and also makes it easier to back-up (can just copy a
few files). The same would seem to be true of the XML-based options. The
advantage of ZODB was that the "object" structure seemed to map well to
the concept of patients, with diseases, with treatments, etc. (and
Shelve would work at least as a trial implementation)

The final thing is that I needs to have a simple GUI frontend. The nice
thing about ZODB is that I could just map the eventhandlers to functions
on objects..

If people have more comments in the light of the bigger spec. above, I'd
still love to hear them...

Matt


From kent37 at tds.net  Thu Sep 22 15:40:48 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 22 Sep 2005 09:40:48 -0400
Subject: [Tutor] Using superclass __init__ method
In-Reply-To: <r02010500-1039-A1EBCFB02B6C11DA9473000A959B4026@[10.149.23.208]>
References: <r02010500-1039-A1EBCFB02B6C11DA9473000A959B4026@[10.149.23.208]>
Message-ID: <4332B460.4000201@tds.net>

Jan Eden wrote:
> Hi,
> 
> I just noticed that in the following environment:
> 
> class Base:
>     def __init__(self):
>         ...
> 
> class Child(Base):
>     pass
>     
> the following statement:
> 
> child = Child()
> 
> would automatically execute the superclass __init__ method. This is exactly what I was looking for - but in the Cookbook, I found several suggestions on how to actively force the invocation of the superclass __init__.
> 
> Is this behvaiour documented?

This is standard behavior for any class attribute - if it's not defined in the derived class, the base class is checked. It's not special for __init__.

I can't find a comprehensive reference for the way attribute lookup works - anyone else?

Kent


From cpu.crazy at gmail.com  Thu Sep 22 16:11:54 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Thu, 22 Sep 2005 08:11:54 -0600
Subject: [Tutor] How to install python on to a remote apache server
Message-ID: <4332BBAA.6070503@gmail.com>

Hi,
I'd like towrite some internet applications but I don't know how to test 
them unless I have python
on my server. However, It's running Apache 1.3.3 and it's a remote one 
(I'm in the Americas and it's in Europe) so I don't know how to access 
it. I also would like to know what platform of python to download. Is 
there a special server edition? Or do I just use a regular Linux edition?
Thanks,
Joe


From tutor.python.org at pooryorick.com  Thu Sep 22 16:18:13 2005
From: tutor.python.org at pooryorick.com (Poor Yorick)
Date: Thu, 22 Sep 2005 10:18:13 -0400
Subject: [Tutor] Python Editors (particualrly Vim)
In-Reply-To: <34bb7f5b0509220554689bd974@mail.gmail.com>
References: <34bb7f5b05092106005a1dcd49@mail.gmail.com>	<20050921165540.GA29780@panix.com>	<34bb7f5b0509211500d14ec63@mail.gmail.com>
	<34bb7f5b0509220554689bd974@mail.gmail.com>
Message-ID: <4332BD25.5040205@pooryorick.com>

Ed Singleton wrote:

>Okay, I've also found this:
>http://cream.sourceforge.net/features.html
>
>  
>
It seems to me that all the functionality listed here can easily be done 
in regular vim.  I would still recommend investing time in learning 
plain old vim or gvim.  The payoff for proficiency is high.

--
Poor Yorick

From paul1brian at gmail.com  Thu Sep 22 16:28:42 2005
From: paul1brian at gmail.com (paul brian)
Date: Thu, 22 Sep 2005 15:28:42 +0100
Subject: [Tutor] Using superclass __init__ method
In-Reply-To: <4332B460.4000201@tds.net>
References: <r02010500-1039-A1EBCFB02B6C11DA9473000A959B4026@10.149.23.208>
	<4332B460.4000201@tds.net>
Message-ID: <bbe9926e0509220728334f52b3@mail.gmail.com>

There are several areas this seems to touch upon, most of them well
covered by Guido himself in http://www.python.org/2.2/descrintro.html

firstly to call a super class' methods you get the subclass to refer
to the *superclass* then the method (note not to the superclass
instance)

from newstyle tutorial (comment mine):

    class B:
        def m(self):
            print "B here"

    class C(B):
        def m(self):
            print "C here"
            B.m(self)   #refer to the class definition not the
instance of C via self.


Secondly to run __init__ as you have described is normal behaviour
because the __call__ function that every new instance must go through
makes sure that __init__ is called, and as there is not one defined in
subclass it uses the one in superclass.

This should have the same effect, but is more controllable:

class Base:
   def __init__(self):
       print "hello"

class Child(Base):
   def __init__(self):
       Base.__init__(self)

produces::

>>> c = Child()
hello


This might also help make things clearer

class Base:
   def __init__(self):
       print "hello"

class Child(Base):
   def __init__(self):
       Base.__init__(self)

   def foo(self):
      print "foo"

c = Child()
b = Base()

x = Child()
x.foo()
Child.foo(x) #1
Child.foo(b) #2


The class defintion of Child is an object (since 2.2) and can be
called with parameters. at #1 we see foo printed out because we have
called the Child object method foo with an object of type Child (this
is essentially self)

Of course we can try passing in another object (#2) but it will barf.


This issue is frankly just muddy. Not because of bad design or poor
documentation but because it is a awkward subject.  Read the link
above - most of us mortals have had to read it several times. Things
also get a little more complex with __new__ but its all in there


However I have not found a really good explanation of the whole
instance creation thing - perhaps this list could make one?

--------------------------
Paul Brian
m. 07875 074 534
t. 0208 352 1741

From lists at janeden.org  Thu Sep 22 16:42:59 2005
From: lists at janeden.org (Jan Eden)
Date: Thu, 22 Sep 2005 16:42:59 +0200
Subject: [Tutor] Using superclass __init__ method
In-Reply-To: <4332B460.4000201@tds.net>
Message-ID: <r02010500-1039-2C7401122B7711DA9473000A959B4026@[10.149.23.208]>

Kent Johnson wrote on 22.09.2005:

>This is standard behavior for any class attribute - if it's not
>defined in the derived class, the base class is checked. It's not
>special for __init__.
>
>I can't find a comprehensive reference for the way attribute lookup
>works - anyone else?

Well, I did know that any attribute used explicitly with a class instance is looked up in the class, then the base class etc:

class Base:
    variable = 1
    
class Child(Base):
    pass

child = Child()
print child.variable
1

What I did not know was that the __init__ method behaves the same way - i.e. that Python looks for __init__ upon instantiation until it finds one.

Thanks,

Jan
-- 
A good programmer is someone who looks both ways before crossing a one-way street. - Doug Linder

From lists at janeden.org  Thu Sep 22 16:48:44 2005
From: lists at janeden.org (Jan Eden)
Date: Thu, 22 Sep 2005 16:48:44 +0200
Subject: [Tutor] Using superclass __init__ method
In-Reply-To: <bbe9926e0509220728334f52b3@mail.gmail.com>
Message-ID: <r02010500-1039-F9EE3F952B7711DA9473000A959B4026@[10.149.23.208]>

Hi,

paul brian wrote on 22.09.2005:

>
>class Base:
>   def __init__(self):
>       print "hello"
>
>class Child(Base):
>   def __init__(self):
>       Base.__init__(self)
>

This is how I did it so far. But in my program, I have 10 subclasses with identical __init__ methods, so I can simplify the setup a lot.

Thanks for your help,

Jan
-- 
Alcohol and calculus don't mix - PLEASE don't drink and derive.

From ramirez08063 at itc.nl  Thu Sep 22 16:50:24 2005
From: ramirez08063 at itc.nl (Jorge Ramirez)
Date: Thu, 22 Sep 2005 16:50:24 +0200
Subject: [Tutor] Simultaneous Adobe Reader
Message-ID: <36141C39871E4D4DAE92F79D1838543601B176CB@itcnt14.itc.nl>

Hello,
 
>From windows, using a python script how can I open Adobe Reader without
displaying a PDF document?  Furthermore, using a script is it possible
to run two Adobe Reader sessions simulatneously.  Thanks in advance.
 
Kind Regards,
JR
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050922/60408a61/attachment.html

From tim at johnsons-web.com  Thu Sep 22 17:33:22 2005
From: tim at johnsons-web.com (Tim Johnson)
Date: Thu, 22 Sep 2005 07:33:22 -0800
Subject: [Tutor] Python Editors (particualrly Vim)
In-Reply-To: <4332BD25.5040205@pooryorick.com>
References: <34bb7f5b05092106005a1dcd49@mail.gmail.com>
	<20050921165540.GA29780@panix.com>
	<34bb7f5b0509211500d14ec63@mail.gmail.com>
	<34bb7f5b0509220554689bd974@mail.gmail.com>
	<4332BD25.5040205@pooryorick.com>
Message-ID: <20050922153321.GB1811@johnsons-web.com>

* Poor Yorick <tutor.python.org at pooryorick.com> [050922 06:29]:
> Ed Singleton wrote:
> 
> >Okay, I've also found this:
> >http://cream.sourceforge.net/features.html
> >
> >  
> >
> It seems to me that all the functionality listed here can easily be done 
> in regular vim.  I would still recommend investing time in learning 
> plain old vim or gvim.  The payoff for proficiency is high.
 
  <grin> I'd be a poor war-fighter when it came to editors. Personally,
         I use all of vim, gvim, emacs and Xemacs and I work in a 
         multiple-language environment mainly on Linux.
         *but* if I were programming only in python and
         doing so on Windows, I'd probably use pythonwin.

         I've used it in the past and was very impressed,
         a real python IDE.
         MTCW
         tim

-- 
Tim Johnson <tim at johnsons-web.com>
      http://www.alaska-internet-solutions.com

From albertito_g at hotmail.com  Thu Sep 22 18:17:07 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Thu, 22 Sep 2005 16:17:07 +0000
Subject: [Tutor] USB Capture Image WebCAM
Message-ID: <BAY106-F150BCD67CD6913ED248B8989970@phx.gbl>

Hey Tutors

I want to make a program that looks like Conquer Cam

For those who doesn't know what is it its a program that captures images 
from your USB WebCAM and saves them to send via FTP.

Anyway, getting to the point I don't know how to get the video from the 
camara to watch it inside a GUI made in Python.

Is this possible?
How?

One step at the time..First I want to accomplish the online viewer of the 
camera and then talk about capturing the image

I'm using Python 2.3.4 over Windows XP Professional

Thanks in advanced

Alberto



From paul1brian at gmail.com  Thu Sep 22 18:35:46 2005
From: paul1brian at gmail.com (paul brian)
Date: Thu, 22 Sep 2005 17:35:46 +0100
Subject: [Tutor] time challange
In-Reply-To: <4332ACB1.9040605@xit.net>
References: <4332ACB1.9040605@xit.net>
Message-ID: <bbe9926e05092209357fd77ee4@mail.gmail.com>

You are fairly close

>>> t1 = today()
>>> t1
<DateTime object for '2005-09-22 00:00:00.00' at 11656e0>
>>> t2 = today() + RelativeDateTime(hours=20)
>>> t2
<DateTime object for '2005-09-22 20:00:00.00' at 1165760>
>>> t3 = t2 - t1
>>> t3.hours
20.0
>>> slice = t3/20
>>> slice
<DateTimeDelta object for '01:00:00.00' at 116cc50>

t3 is a "Delta" - that is an abstract representation
of time - it is not the 20 hours since midnight, just 20 hours
at any time in the universe.
slice is just 1/20th of that same abstract time. But because of the munificence
of Marc we can add that abstract hour to a real fixed time (ignoring
Einstein of course)

>>> t1 + slice
<DateTime object for '2005-09-22 01:00:00.00' at 11655e0>

And so that is a "real" datetime 1/20th of the way forward from t1

so a simple loop will get you your 20 evenly spaced time periods,
which is what i think you were asking for.

cheers



On 9/22/05, nephish <nephish at xit.net> wrote:
> Hey there,
>
> i use mx.DateTime.RelativeDateTimeDiff to get the difference between
> date_x and date_y.
> what i need to do divide this amount of time into 20 different times
> that spaced out between the date_x and the date_y.
>
> so if the difference between date_x and date_y is 20 hours, i need 20
> DateTimes that are one hour apart from each other. If the difference is
> 40 minutes, i need the 20 DateTimes to be spaced out 2 minutes from each
> other..
>
> what would be a way to pull this off? i have looked at the docs for
> mxDateTime
> http://www.egenix.com/files/python/mxDateTime.html
> and there seems to be a divide operation, but i dont quite know what it
> is talking about
> with the deltas.
>
> anyone have a good start point?
>
> thanks
> shawn
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


--
--------------------------
Paul Brian
m. 07875 074 534
t. 0208 352 1741

From paul1brian at gmail.com  Thu Sep 22 18:46:17 2005
From: paul1brian at gmail.com (paul brian)
Date: Thu, 22 Sep 2005 17:46:17 +0100
Subject: [Tutor] Python DB
In-Reply-To: <1127395888.5821.33.camel@localhost.localdomain>
References: <mailman.2153.1127394334.508.tutor@python.org>
	<1127395888.5821.33.camel@localhost.localdomain>
Message-ID: <bbe9926e050922094640e8dc5a@mail.gmail.com>

I would look quite seriously at SQLObject

It is a bit rough round the edges but given a class defintion, it then
creates the underlying SQL tables and handles the CRUD (create update
delete) for you.

I do not like this approach and prefer the other but equally nice
ability it has to look at a database and create appropriate classes,
which you can then use.
It is a class of Object Relational mapper, of which there are a few
Java production level ones but I do not know of any "real world" uses
of SQL Object. Perhaps others do.

Backups and access from other applications imply you want a fairly
serious admin load afterwarss - in which case I would think very
carefully before using anything other than a "real" RDBMS (Oracle,
MySQL, Postgres MSAccess even). Backups and synchronous access are
what they are designed to do.

However are you quite sure a normal db table will not suffice - I tend
to find that the underlying data structure is never as fluid as one
suspects.
Patient - disease - treatment sounds a fairly striaghtforward domain. 
Perhaps if you shared a few things that make you worried it will
change dramatically someone might be able to suggest workable
structures.

On 9/22/05, Matt Williams <matthew.williams at cancer.org.uk> wrote:
> Dear List,
>
> Thanks for all the advice! Obviously, I'm still a bit torn, but some of
> the ideas looked good.
>
> In terms of spec, the DB can be fairly simple (single access, etc.).
> Lower dependency on other libraries is good. Also, it needs to be cross-
> platform.
>
> The problem (I have) with SQL-type DB is that I cannot be sure ahead of
> time of the exact data structure. The DB will be about patients, who
> have diseases, and also have treatments.....Clearly, I can't specify now
> the exact structure of the table. The advantage of SQL is that you can
> (in general) do things like constrain types for fields, and give
> enumerated options, which makes the data more consistent.
>
> The thing I liked about KirbyBase was that it used text files. This is a
> real advantage, as it means that I can access the data from other
> application easily, and also makes it easier to back-up (can just copy a
> few files). The same would seem to be true of the XML-based options. The
> advantage of ZODB was that the "object" structure seemed to map well to
> the concept of patients, with diseases, with treatments, etc. (and
> Shelve would work at least as a trial implementation)
>
> The final thing is that I needs to have a simple GUI frontend. The nice
> thing about ZODB is that I could just map the eventhandlers to functions
> on objects..
>
> If people have more comments in the light of the bigger spec. above, I'd
> still love to hear them...
>
> Matt
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


--
--------------------------
Paul Brian
m. 07875 074 534
t. 0208 352 1741

From nephish at xit.net  Thu Sep 22 18:55:54 2005
From: nephish at xit.net (nephish)
Date: Thu, 22 Sep 2005 11:55:54 -0500
Subject: [Tutor] time challange
In-Reply-To: <bbe9926e05092209357fd77ee4@mail.gmail.com>
References: <4332ACB1.9040605@xit.net>
	<bbe9926e05092209357fd77ee4@mail.gmail.com>
Message-ID: <4332E21A.8010101@xit.net>

paul brian wrote:

>You are fairly close
>
>  
>
>>>>t1 = today()
>>>>t1
>>>>        
>>>>
><DateTime object for '2005-09-22 00:00:00.00' at 11656e0>
>  
>
>>>>t2 = today() + RelativeDateTime(hours=20)
>>>>t2
>>>>        
>>>>
><DateTime object for '2005-09-22 20:00:00.00' at 1165760>
>  
>
>>>>t3 = t2 - t1
>>>>t3.hours
>>>>        
>>>>
>20.0
>  
>
>>>>slice = t3/20
>>>>slice
>>>>        
>>>>
><DateTimeDelta object for '01:00:00.00' at 116cc50>
>
>t3 is a "Delta" - that is an abstract representation
>of time - it is not the 20 hours since midnight, just 20 hours
>at any time in the universe.
>slice is just 1/20th of that same abstract time. But because of the munificence
>of Marc we can add that abstract hour to a real fixed time (ignoring
>Einstein of course)
>
>  
>
>>>>t1 + slice
>>>>        
>>>>
><DateTime object for '2005-09-22 01:00:00.00' at 11655e0>
>
>And so that is a "real" datetime 1/20th of the way forward from t1
>
>so a simple loop will get you your 20 evenly spaced time periods,
>which is what i think you were asking for.
>
>cheers
>
>
>
>On 9/22/05, nephish <nephish at xit.net> wrote:
>  
>
>>Hey there,
>>
>>i use mx.DateTime.RelativeDateTimeDiff to get the difference between
>>date_x and date_y.
>>what i need to do divide this amount of time into 20 different times
>>that spaced out between the date_x and the date_y.
>>
>>so if the difference between date_x and date_y is 20 hours, i need 20
>>DateTimes that are one hour apart from each other. If the difference is
>>40 minutes, i need the 20 DateTimes to be spaced out 2 minutes from each
>>other..
>>
>>what would be a way to pull this off? i have looked at the docs for
>>mxDateTime
>>http://www.egenix.com/files/python/mxDateTime.html
>>and there seems to be a divide operation, but i dont quite know what it
>>is talking about
>>with the deltas.
>>
>>anyone have a good start point?
>>
>>thanks
>>shawn
>>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
>>    
>>
>
>
>--
>--------------------------
>Paul Brian
>m. 07875 074 534
>t. 0208 352 1741
>
>  
>
YES !
that is what i needed. This is great.
i think i understand your steps ok, but you lost me with the munificence
of Marc. i never got to take physics. All the same, thanks so much

shawn

From ramirez08063 at itc.nl  Thu Sep 22 15:30:40 2005
From: ramirez08063 at itc.nl (Jorge Ramirez)
Date: Thu, 22 Sep 2005 15:30:40 +0200
Subject: [Tutor] PDF
Message-ID: <36141C39871E4D4DAE92F79D1838543601B176C6@itcnt14.itc.nl>

Hello,
 
I would like to know how to open a pdf document using a python script.
 
thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050922/54e74b7f/attachment.htm

From dyoo at hkn.eecs.berkeley.edu  Thu Sep 22 20:38:16 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 22 Sep 2005 11:38:16 -0700 (PDT)
Subject: [Tutor] USB Capture Image WebCAM
In-Reply-To: <BAY106-F150BCD67CD6913ED248B8989970@phx.gbl>
Message-ID: <Pine.LNX.4.44.0509221137210.19556-100000@hkn.eecs.berkeley.edu>



On Thu, 22 Sep 2005, Alberto Troiano wrote:

> For those who doesn't know what is it its a program that captures images
> from your USB WebCAM and saves them to send via FTP.
>
> Anyway, getting to the point I don't know how to get the video from the
> camara to watch it inside a GUI made in Python.

You might be in luck; there's a project that provides USB Webcam access
for Windows:

    http://videocapture.sourceforge.net/

Good luck!


From dyoo at hkn.eecs.berkeley.edu  Thu Sep 22 20:55:21 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 22 Sep 2005 11:55:21 -0700 (PDT)
Subject: [Tutor] Python DB
In-Reply-To: <1127395888.5821.33.camel@localhost.localdomain>
Message-ID: <Pine.LNX.4.44.0509221138400.19556-100000@hkn.eecs.berkeley.edu>



On Thu, 22 Sep 2005, Matt Williams wrote:

> The problem (I have) with SQL-type DB is that I cannot be sure ahead of
> time of the exact data structure. The DB will be about patients, who
> have diseases, and also have treatments.....Clearly, I can't specify now
> the exact structure of the table. The advantage of SQL is that you can
> (in general) do things like constrain types for fields, and give
> enumerated options, which makes the data more consistent.

Hi Matt,

But another kind of advantage of SQL is that it can accomodate ad-hoc
queries.  That's a big one, since it means that if the requirements
change, the database can usually handle it efficiently.  Object databases
are tied to a particular structure and access pattern, so they may not be
so adaptable to different access patterns.

I'm also not quite seeing how an object database like ZODB will allow you
to escape planning about how to represent patients, diseases, and
treatement data.  And SQL databases may be more flexible to structural
change than you might expect.

SQLite is a lightweight database that you might want to consider:

    http://www.sqlite.org/
    http://initd.org/projects/pysqlite

and SQLite does have enough support for ALTER TABLE to let you change the
database structure as the problem statement solidifies:

    http://sqlite.org/faq.html#q13

Best of wishes to you!


From falcon3166 at hotmail.com  Thu Sep 22 20:57:50 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Thu, 22 Sep 2005 12:57:50 -0600
Subject: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
	<432B8CA9.2000200@christianfreebies.com>
	<BAY106-DAV159F309A389BF7EECD88A1C4970@phx.gbl>
	<be4fbf92050922042136464a41@mail.gmail.com>
Message-ID: <BAY106-DAV226752531F90F718C5F9F9C4970@phx.gbl>


http://zoffee.tripod.com/purchasecompprogs.htm is the URL.
  ----- Original Message ----- 
  From: Adam 
  To: Nathan Pinno 
  Sent: Thursday, September 22, 2005 5:21 AM
  Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]


  What's the URL?


  On 22/09/05, Nathan Pinno <falcon3166 at hotmail.com> wrote:
    I have a challenge for everyone on the tutor list. Take this serious, and
    don't think I'm asking it just because I am mad or something. I'm not, I
    just want to clear the air once and for all. Here is the challenge:

    Choose any program that I am selling on my site, any one of them, and ask me
    for the code. I'll gladly send you a copy. Determine if I have copied most
    of it, or wrote most of it myself. Post your analysis to the group. If you 
    determine that I have copied most of it, I'll remove it and post an apology.
    If not, you must admit that I wrote most of it myself. Fair enough?

    Farewell for now,
    Nathan Pinno.
    ----- Original Message ----- 
    From: "Byron" <byron at christianfreebies.com>
    To: "Nathan Pinno" <falcon3166 at hotmail.com>; < Tutor at python.org>
    Sent: Friday, September 16, 2005 9:25 PM
    Subject: Re: [Tutor] Why won't it enter the quiz?


    > Nathan Pinno wrote:
    >> Brian and all,
    >>
    >> I am just asking for help - after all I write most each program myself,
    >> and just ask for help in debugging it whenever I cannot figure it out. If
    >> this is being sneaky, I apologize, and won't ask for help anymore. 
    >
    >
    > No, don't do that... Happy that you are asking questions!  I was humored
    > by the idea that you have a GREAT business model there...  :-)  FREE
    > Labor -- wow, should of thought of that one earlier...  <big grin> 
    >
    > Have a great weekend and hope you keep posting!
    >
    > Brian
    > ---
    >
    >
    >
    >
    _______________________________________________
    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/20050922/3f5c558b/attachment.html

From project5 at redrival.net  Thu Sep 22 21:07:05 2005
From: project5 at redrival.net (Andrei)
Date: Thu, 22 Sep 2005 21:07:05 +0200
Subject: [Tutor] Python DB
In-Reply-To: <1127395888.5821.33.camel@localhost.localdomain>
References: <mailman.2153.1127394334.508.tutor@python.org>
	<1127395888.5821.33.camel@localhost.localdomain>
Message-ID: <dguvcr$d0a$1@sea.gmane.org>

> The problem (I have) with SQL-type DB is that I cannot be sure ahead of
> time of the exact data structure. The DB will be about patients, who
> have diseases, and also have treatments.....Clearly, I can't specify now
> the exact structure of the table. The advantage of SQL is that you can
> (in general) do things like constrain types for fields, and give
> enumerated options, which makes the data more consistent.

My experience:
- keeping in-memory: fast and easy as long as the amounts of data are 
*very* limited.
- kirby: I looked at it almost two years ago and it's nice, easy to use, 
but needs speedups for large amounts of data. At the time I tweaked some 
of the code and got very nice improvements (some of them are now in 
there I think).
- bsddb: very comfortable (just treat it like a dictionary), fast 
lookup, but searching in the values is slow. If you have thousands of 
records, you'll most likely need to employ some tricks to get fast 
responses when searching.
- sql (my experience is with SQLite): harder to work with (had some 
issues getting SQLObject to work with it, so I did it the very hard way 
by writing SQL statements), but insanely fast searches.

> The thing I liked about KirbyBase was that it used text files. This is a
> real advantage, as it means that I can access the data from other
> application easily, and also makes it easier to back-up (can just copy a
> few files). The same would seem to be true of the XML-based options. The

bsddb and sqlite also have single-file databases.

> The final thing is that I needs to have a simple GUI frontend. The nice
> thing about ZODB is that I could just map the eventhandlers to functions
> on objects..

sqlite has some viewers available (in my experience not quite reliable, 
but YMMV). bsddb can be inspected and manipulated easily in an 
interactive python session.

> If people have more comments in the light of the bigger spec. above, I'd
> still love to hear them...

I'd give bsddb a try if the application mainly involves looking up 
treatments/illnesses for a given patient (with the patient being the key 
in the database) or if the number of patients is quite low (hundreds). 
If however an important use is to do other types of searches too (e.g. 
find all patients with an age above X who use a drug Y) and you have a 
large database, some SQL DB would be better.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From chris.arndt at web.de  Thu Sep 22 22:03:49 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Thu, 22 Sep 2005 21:03:49 +0100
Subject: [Tutor] PDF
In-Reply-To: <36141C39871E4D4DAE92F79D1838543601B176C6@itcnt14.itc.nl>
References: <36141C39871E4D4DAE92F79D1838543601B176C6@itcnt14.itc.nl>
Message-ID: <43330E25.5080500@web.de>

Jorge Ramirez schrieb:
> 
> Hello,
>  
> I would like to know how to open a pdf document using a python script.

- What do you mean by "open"?
  - start a PDF viewer (e.g acrobar reader) from python?
  - or read in the file in Python and extract information from it?

- What platform are you on?
  - Windows
  - Linux/Unix
  - MAC OS

- What kind of PDFs do you have?
  - only Text
  - with images
  - or forms?
  - with encryption?
  - What versions of the PDF document format ?

You have to be a little more specific, please, if you want us to help you!

Chris

From albertito_g at hotmail.com  Thu Sep 22 22:24:56 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Thu, 22 Sep 2005 20:24:56 +0000
Subject: [Tutor] USB Capture Image WebCAM
In-Reply-To: <Pine.LNX.4.44.0509221137210.19556-100000@hkn.eecs.berkeley.edu>
Message-ID: <BAY106-F32B79194EF9C613F6E255B89970@phx.gbl>


Hey Danny

I have downloaded videoCapture but I can't make it run. This is the error I 
get when I try run the example on the Web Page

I want to be able to see the reproduction of the WebCAM inside a GUI of 
Python

I didn't find docs for this on the WEB. If somebody have some pointers I 
would appreciate a lot

Thanks in advanced

Alberto


>From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
>To: Alberto Troiano <albertito_g at hotmail.com>
>CC: tutor at python.org
>Subject: Re: [Tutor] USB Capture Image WebCAM
>Date: Thu, 22 Sep 2005 11:38:16 -0700 (PDT)
>
>
>
>On Thu, 22 Sep 2005, Alberto Troiano wrote:
>
> > For those who doesn't know what is it its a program that captures images
> > from your USB WebCAM and saves them to send via FTP.
> >
> > Anyway, getting to the point I don't know how to get the video from the
> > camara to watch it inside a GUI made in Python.
>
>You might be in luck; there's a project that provides USB Webcam access
>for Windows:
>
>     http://videocapture.sourceforge.net/
>
>Good luck!
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



From albertito_g at hotmail.com  Thu Sep 22 22:34:24 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Thu, 22 Sep 2005 20:34:24 +0000
Subject: [Tutor] FW: Re:  USB Capture Image WebCAM
Message-ID: <BAY106-F29C40A56E9A3E1E2FC8F9189970@phx.gbl>

Hey Danny

I have downloaded videoCapture but I can't make it run. This is the error I
get when I try run the example

Traceback (most recent call last):
  File "C:\Documents and Settings\Daron 
Malakian\Desktop\VideoCapture-0.9\Tools\webcam-uploader\webcam-uploader.py", 
line 130, in ?
    cam = VideoCapture.Device(devnum=devnum)
  File "C:\Python23\lib\VideoCapture.py", line 49, in __init__
    self.dev = vidcap.new_Dev(devnum, showVideoWindow)
Error: Capture Graph could not be created.


I want to be able to see the reproduction of the WebCAM inside a GUI of
Python

I didn't find docs for this on the WEB. If somebody have some pointers I
would appreciate a lot

Thanks in advanced

Alberto


> >From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
> >To: Alberto Troiano <albertito_g at hotmail.com>
> >CC: tutor at python.org
> >Subject: Re: [Tutor] USB Capture Image WebCAM
> >Date: Thu, 22 Sep 2005 11:38:16 -0700 (PDT)
> >
> >
> >
> >On Thu, 22 Sep 2005, Alberto Troiano wrote:
> >
> > > For those who doesn't know what is it its a program that captures 
>images
> > > from your USB WebCAM and saves them to send via FTP.
> > >
> > > Anyway, getting to the point I don't know how to get the video from 
>the
> > > camara to watch it inside a GUI made in Python.
> >
> >You might be in luck; there's a project that provides USB Webcam access
> >for Windows:
> >
> >     http://videocapture.sourceforge.net/
> >
> >Good luck!
> >
> >_______________________________________________
> >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



From wildcard2005 at comcast.net  Thu Sep 22 23:44:47 2005
From: wildcard2005 at comcast.net (Terry Kemmerer)
Date: Thu, 22 Sep 2005 14:44:47 -0700
Subject: [Tutor] Lost Color Lost Mind
Message-ID: <1127425487.11758.75.camel@c-24-16-68-31.hsd1.wa.comcast.net>

Just learning Python....

Running:

        Python 2.4.1 (#2, Aug 25 2005, 18:20:57) 
        [GCC 4.0.1 (4.0.1-2mdk for Mandriva Linux release 2006.0)] on
linux2

Concerning: IDLE

I tried several fonts, and finally changed the font on IDLE to courier
size 22 bold, so that it is easier for my old eyes to read, and while
the shell window still has color depicting the structure, the program
window is now displaying only in black. (I also forgot what font IDLE
originally was set on. A mind is such a terrible thing to loose...) 

Question:  How do I get color back in my programming window???   (It's
soooo pretty that way!)

Thanks!

Terry




-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050922/934cd330/attachment.html

From Goofball223 at wmconnect.com  Thu Sep 22 23:57:41 2005
From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com)
Date: Thu, 22 Sep 2005 17:57:41 EDT
Subject: [Tutor] where to insert?
Message-ID: <111.52fa7853.306482d5@wmconnect.com>

I would like to insert string.join(msgList,"") into the following program 
where do I insert it?

# numbers2text.py
#     A program to convert a sequence of ASCII numbers into
#         a string of text.

import string  # include string library for the split function.

def main():
    print "This program converts a sequence of ASCII numbers into"
    print "the string of text that it represents."
    print
    
    # Get the message to encode
    inString = raw_input("Please enter the ASCII-encoded message: ")

    # Loop through each substring and build ASCII message
    message = ""
    for numStr in string.split(inString):
        asciiNum = eval(numStr)           # convert digits to a number
        message = message + chr(asciiNum) # append character to message

    print "The decoded message is:", message

main()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050922/61716a2e/attachment.htm

From andrade1 at umbc.edu  Fri Sep 23 00:35:26 2005
From: andrade1 at umbc.edu (andrade1@umbc.edu)
Date: Thu, 22 Sep 2005 18:35:26 -0400 (EDT)
Subject: [Tutor] how to insert a string?
Message-ID: <1770.172.162.202.101.1127428526.squirrel@172.162.202.101>



Hello

I would like to insert a string into the following program to simplify the
program. Any suggestions on how I might do so?

# dateconvert2.py
#    Converts day month and year numbers into two date formats

import string

def main():
    # get the day month and year
    day, month, year = input("Please enter the day, month and year
numbers: ")

    date1 = str(month)+"/"+str(day)+"/"+str(year)

    months = ["January", "February", "March", "April",
              "May", "June", "July", "August",
              "September", "October", "November", "December"]
    monthStr = months[month-1]
    date2 = monthStr+" " + str(day) + ", " + str(year)

    print "The date is", date1, "or", date2

main()




From albertito_g at hotmail.com  Fri Sep 23 00:36:14 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Thu, 22 Sep 2005 22:36:14 +0000
Subject: [Tutor] FW: Re: USB Capture Image WebCAM
In-Reply-To: <Pine.LNX.4.44.0509221520070.31570-100000@hkn.eecs.berkeley.edu>
Message-ID: <BAY106-F11C9E0FD5136889D14107D89970@phx.gbl>

Hey Danny

Thanks for the reply and the tip...I will try to reach him/her.

In answer to your question, Conquer Cam is a buyable software. What it does 
is to show the WebCAM an captures Images every x time and sends it via FTP 
to any server.

But it doesn't works so fine, I think its because I cracked and didn't buy 
it *grin*
But I need like 200 licenses so it would be a little expensive. That's why 
I'm trying to make my own Python Gengis Cam *grin*

Thanks again

Alberto

>From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
>To: Alberto Troiano <albertito_g at hotmail.com>
>CC: Tutor <tutor at python.org>
>Subject: Re: [Tutor] FW: Re:  USB Capture Image WebCAM
>Date: Thu, 22 Sep 2005 15:29:07 -0700 (PDT)
>
>
> > I have downloaded videoCapture but I can't make it run. This is the 
>error I
> > get when I try run the example
> >
> > Traceback (most recent call last):
> >   File "C:\Documents and Settings\Daron
> > 
>Malakian\Desktop\VideoCapture-0.9\Tools\webcam-uploader\webcam-uploader.py",
> > line 130, in ?
> >     cam = VideoCapture.Device(devnum=devnum)
> >   File "C:\Python23\lib\VideoCapture.py", line 49, in __init__
> >     self.dev = vidcap.new_Dev(devnum, showVideoWindow)
> > Error: Capture Graph could not be created.
>
>Hi Alberto,
>
>You may want to talk with the developer of the VideoCapture module
>software.  I don't know what's going on here.  Testing this is also
>complicated because I don't have a webcam or Windows.
>
>
>Wait, let's back up a moment.  You mentioned earlier that:
>
> > > > > For those who doesn't know what is it its a program that captures
> > > > > images from your USB WebCAM and saves them to send via FTP.
>
>Does this mean then that you already have a program that saves webcam
>images to disk?
>
>
>If so, then if we know what graphical format they are, then perhaps we
>might be able to use PIL to convert them into a format that your favorite
>GUI toolkit can display.  PIL can talk with different graphical formats:
>
>     http://www.pythonware.com/products/pil/
>
>Tkinter integrates with this:
>
>     http://effbot.org/zone/tkinter-plot.htm
>
>And wxpython + PIL also appears to work:
>
>     http://wiki.wxpython.org/index.cgi/WorkingWithImages
>



From kent37 at tds.net  Fri Sep 23 00:36:17 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 22 Sep 2005 18:36:17 -0400
Subject: [Tutor] Threading in a for loop
In-Reply-To: <43306BAE.1070404@pennswoods.net>
References: <43306BAE.1070404@pennswoods.net>
Message-ID: <433331E1.3090009@tds.net>

Bill Burns wrote:
> I've got a few questions regarding Threading. I've never used threads
> before and I want to make sure I'm doing it correctly ;-)
> 
> I have a GUI app and it processes Tiff files to PDF (or PostScript). The
> GUI has a ListBox which the user populates with files to convert. You
> click on a Button and the file conversion starts. When all the files
> have been converted, the ListBox items (the files) are cleared.
> 
> Initially, you had no way of knowing what was going on until all the
> files where cleared from the ListBox.
> 
> So I thought of creating threads in the 'for loop' and displaying the
> name of each file in the statusBar of the GUI (as they are being
> processed).

You don't necessarily need threads for this. If you just want to provide feedback and don't care about the GUI being responsive, just do the processing in a loop, update the status bar and call root.update_idletasks() to allow the GUI to redraw. (Assuming you are using Tkinter.)

If you want the GUI to remain responsive so for example you can have a Cancel button, then I would make a single thread and process all the files in that thread. Don't sleep in the thread; call root.update() to give some time to event handling. Somehow you will have to notify the main thread that the worker thread is done.

The only reason I can think of to make a separate thread for each image is if the process is significantly I/O bound. My guess is that Tiff to PDF conversion is CPU-intensive and a single worker thread will be plenty.

More notes below...
 
> Here's my method which takes the files in the ListBox and sends them off
> to my Convert() class (self.convert = Convert()).
> <code>
> def convertTiff2PDF(self):
>      from time import time
>      #Let's see how long this takes... I saw Kent do this on the
>      #Python Tutor list before :-)
>      start = time()
>      #Grab a tuple which contains width & length
>      sizes = self.getPaperSize()
>      width = sizes[0]
>      length = sizes[1]
>      #Count the number of files in the ListBox
>      fileCount = self.fileListBox.count()
>      for index in range(fileCount):
>          #Get each filename
>          filenames = str(self.fileListBox.text(index))
>          #Setup the worker thread and send the filenames in
>          worker = WorkerThread(self, filenames)
>          #Start threading
>          worker.start()
>          #Send each file to be converted
>          self.convert.tiff2pdf(width, length, filenames)

The above line should be in the thread, not in the main loop - you are spawning threads that do nothing but update the status display - and they will compete for that.

>      #We're done, so clear the ListBox
>      self.fileListBox.clear()
>      #Check the time again
>      end = time()
>      msg = '%s Files Processed in %0.3f Seconds.' % (fileCount,
> (end-start))
>      #Grab the statusBar and insert the message
>      statusBar = self.statusBar()
>      statusBar.message(msg, 0)
> </code>
> 
> And here's what I'm doing in my Thread class:
> <code>
> class WorkerThread(Thread):
>      """Thread class."""
>      def __init__(self, parent, files):
>          Thread.__init__(self)
>          self.parent = parent
>          self.files = files
> 
>      def run(self):
>          statusBar = self.parent.statusBar()
>          msg = 'Processing: %s, please wait.' % (self.files)
>          statusBar.message(msg, 100)
>          time.sleep(1)
> </code>
> 
> Am I doing this threading properly? Is it 'OK' to start multiple threads
> like this (in the for loop)? It's possible that a user could put 'many'
> files into the ListBox, by 'many' I mean 100-200 files.

It's OK to have multiple threads but yours aren't doing any useful work.

I hope this helps get you on track, it's a bit brief.

Kent
> 
> Thanks for your help.
> 
> Bill
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From kim.d at tesco.net  Fri Sep 23 00:46:16 2005
From: kim.d at tesco.net (kim.d@tesco.net)
Date: Thu, 22 Sep 2005 22:46:16 +0000
Subject: [Tutor] Diamond Equivalent
Message-ID: <20050922224618.MEOL5796.aamta03-winn.mailhost.ntl.com@smtp.tesco.net>

I am coming to Python from Perl. Does Python have anything like the diamond 
operator found in Perl?


From dyoo at hkn.eecs.berkeley.edu  Fri Sep 23 00:29:07 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 22 Sep 2005 15:29:07 -0700 (PDT)
Subject: [Tutor] FW: Re:  USB Capture Image WebCAM
In-Reply-To: <BAY106-F29C40A56E9A3E1E2FC8F9189970@phx.gbl>
Message-ID: <Pine.LNX.4.44.0509221520070.31570-100000@hkn.eecs.berkeley.edu>


> I have downloaded videoCapture but I can't make it run. This is the error I
> get when I try run the example
>
> Traceback (most recent call last):
>   File "C:\Documents and Settings\Daron
> Malakian\Desktop\VideoCapture-0.9\Tools\webcam-uploader\webcam-uploader.py",
> line 130, in ?
>     cam = VideoCapture.Device(devnum=devnum)
>   File "C:\Python23\lib\VideoCapture.py", line 49, in __init__
>     self.dev = vidcap.new_Dev(devnum, showVideoWindow)
> Error: Capture Graph could not be created.

Hi Alberto,

You may want to talk with the developer of the VideoCapture module
software.  I don't know what's going on here.  Testing this is also
complicated because I don't have a webcam or Windows.


Wait, let's back up a moment.  You mentioned earlier that:

> > > > For those who doesn't know what is it its a program that captures
> > > > images from your USB WebCAM and saves them to send via FTP.

Does this mean then that you already have a program that saves webcam
images to disk?


If so, then if we know what graphical format they are, then perhaps we
might be able to use PIL to convert them into a format that your favorite
GUI toolkit can display.  PIL can talk with different graphical formats:

    http://www.pythonware.com/products/pil/

Tkinter integrates with this:

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

And wxpython + PIL also appears to work:

    http://wiki.wxpython.org/index.cgi/WorkingWithImages


From andrade1 at umbc.edu  Fri Sep 23 00:32:29 2005
From: andrade1 at umbc.edu (andrade1@umbc.edu)
Date: Thu, 22 Sep 2005 18:32:29 -0400 (EDT)
Subject: [Tutor] how to insert a string?
Message-ID: <1752.172.162.202.101.1127428349.squirrel@172.162.202.101>


Hello

I would like to insert a string into the following program to simplify the
program. Any suggestions on how I might do so?

# dateconvert2.py
#    Converts day month and year numbers into two date formats

import string

def main():
    # get the day month and year
    day, month, year = input("Please enter the day, month and year
numbers: ")

    date1 = str(month)+"/"+str(day)+"/"+str(year)

    months = ["January", "February", "March", "April",
              "May", "June", "July", "August",
              "September", "October", "November", "December"]
    monthStr = months[month-1]
    date2 = monthStr+" " + str(day) + ", " + str(year)

    print "The date is", date1, "or", date2

main()


From dyoo at hkn.eecs.berkeley.edu  Fri Sep 23 01:31:30 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 22 Sep 2005 16:31:30 -0700 (PDT)
Subject: [Tutor] Diamond Equivalent
In-Reply-To: <20050922224618.MEOL5796.aamta03-winn.mailhost.ntl.com@smtp.tesco.net>
Message-ID: <Pine.LNX.4.44.0509221627100.9056-100000@hkn.eecs.berkeley.edu>



On Thu, 22 Sep 2005 kim.d at tesco.net wrote:

> I am coming to Python from Perl. Does Python have anything like the
> diamond operator found in Perl?

Hi Kim,


According to 'perldoc perlop':

"""
       The null filehandle <> is special: it can be used to emulate the
       behavior of sed and awk.  Input from <> comes either from standard
       input, or from each file listed on the command line.  Here's how it
       works: the first time <> is evaluated, the @ARGV array is checked,
       and if it is empty, $ARGV[0] is set to "-", which when opened gives
       you standard input.  The @ARGV array is then processed as a list
       of filenames.
"""

Python includes a module called 'fileinput' that does sorta this:

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

If you have more questions, please feel free to ask.  Good luck to you!


From dyoo at hkn.eecs.berkeley.edu  Fri Sep 23 01:51:29 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 22 Sep 2005 16:51:29 -0700 (PDT)
Subject: [Tutor] how to insert a string?
In-Reply-To: <1770.172.162.202.101.1127428526.squirrel@172.162.202.101>
Message-ID: <Pine.LNX.4.44.0509221638200.9056-100000@hkn.eecs.berkeley.edu>



On Thu, 22 Sep 2005 andrade1 at umbc.edu wrote:

> I would like to insert a string into the following program to simplify
> the program. Any suggestions on how I might do so?

Hello,

It's a little unclear what you're asking when you mention "insert a
string": usually, inserting anything into a program makes it larger, and
consequently, slightly less simple.


Are you asking, instead, what techniques we can use to simplify the
program?  If so, one thing you may want to look at is the 'strftime'
function in the 'time' module.  For example:

######
>>> import time
>>> time.strftime("%B %d %Y")
'September 22 2005'
######

time.strftime() might not be perfect, since I think it only works on range
of dates starting from the Epoch (around 1970) to about the year 2038.
So if you need larger ranges than this, strftime probably won't be an
appropriate tool, although something like:

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

might be useful.



Anyway, let's take a quick at a line in your program.

>     date1 = str(month)+"/"+str(day)+"/"+str(year)

The construction of 'date1' can be slightly simplified if you use string
formatting:

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


For example:

######
>>> "%s went up the hill" % ("curious george")
'curious george went up the hill'
######



Best of wishes!


From dyoo at hkn.eecs.berkeley.edu  Fri Sep 23 02:05:03 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 22 Sep 2005 17:05:03 -0700 (PDT)
Subject: [Tutor] How to install python on to a remote apache server
In-Reply-To: <4332BBAA.6070503@gmail.com>
Message-ID: <Pine.LNX.4.44.0509221651470.9056-100000@hkn.eecs.berkeley.edu>



> I'd like to write some internet applications but I don't know how to
> test them unless I have python on my server. However, It's running
> Apache 1.3.3 and it's a remote one (I'm in the Americas and it's in
> Europe) so I don't know how to access it. I also would like to know what
> platform of python to download. Is there a special server edition? Or do
> I just use a regular Linux edition?

Hi Joseph,

Any version of Python should be fine: the higher, the better, just because
of the improvements to the Standard Library.  The work though will
probably be mostly on the Apache end of things.  You'll be better off
asking the Apache folks for help in setting up Python as a server
language.

For Apache 1.3, the documentation in:

    http://httpd.apache.org/docs/1.3/howto/cgi.html

will be useful for whoever needs to configure Apache on your remote
server.


For testing, you may want explore using Apache locally on your machine, or
you can even use CGIHTTPServer:

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


From darnold992000 at yahoo.com  Fri Sep 23 02:40:46 2005
From: darnold992000 at yahoo.com (Don Arnold)
Date: Thu, 22 Sep 2005 17:40:46 -0700 (PDT)
Subject: [Tutor] Lost Color Lost Mind
In-Reply-To: <1127425487.11758.75.camel@c-24-16-68-31.hsd1.wa.comcast.net>
Message-ID: <20050923004047.49970.qmail@web80908.mail.scd.yahoo.com>



--- Terry Kemmerer <wildcard2005 at comcast.net> wrote:

> Just learning Python....
> 
> Running:
> 
>         Python 2.4.1 (#2, Aug 25 2005, 18:20:57) 
>         [GCC 4.0.1 (4.0.1-2mdk for Mandriva Linux
> release 2006.0)] on
> linux2
> 
> Concerning: IDLE
> 
> I tried several fonts, and finally changed the font
> on IDLE to courier
> size 22 bold, so that it is easier for my old eyes
> to read, and while
> the shell window still has color depicting the
> structure, the program
> window is now displaying only in black. (I also
> forgot what font IDLE
> originally was set on. A mind is such a terrible
> thing to loose...) 
> 
> Question:  How do I get color back in my programming
> window???   (It's
> soooo pretty that way!)
> 
> Thanks!
> 
> Terry

Until you save the program window to a file with a
'.py' extension, IDLE doesn't realize it's Python
source code so it doesn't do any syntax highlighting.

HTH, 
Don


	
		
______________________________________________________ 
Yahoo! for Good 
Donate to the Hurricane Katrina relief effort. 
http://store.yahoo.com/redcross-donate3/ 


From tutor.python.org at pooryorick.com  Fri Sep 23 02:52:50 2005
From: tutor.python.org at pooryorick.com (Poor Yorick)
Date: Thu, 22 Sep 2005 20:52:50 -0400
Subject: [Tutor] FW: Re: USB Capture Image WebCAM
In-Reply-To: <BAY106-F11C9E0FD5136889D14107D89970@phx.gbl>
References: <BAY106-F11C9E0FD5136889D14107D89970@phx.gbl>
Message-ID: <433351E2.6020204@pooryorick.com>

Alberto Troiano wrote:

> 
> But it doesn't works so fine, I think its because I cracked and didn't buy 
> it *grin*
> But I need like 200 licenses so it would be a little expensive. That's why 
> I'm trying to make my own Python Gengis Cam *grin*
> 

You just admitted on a public forum to committing a crime.  Not wise, 
friend.

--
Poor Yorick

From wildcard2005 at comcast.net  Fri Sep 23 02:53:10 2005
From: wildcard2005 at comcast.net (Terry Kemmerer)
Date: Thu, 22 Sep 2005 17:53:10 -0700
Subject: [Tutor] Lost Color Lost Mind]
Message-ID: <1127436791.11758.166.camel@c-24-16-68-31.hsd1.wa.comcast.net>



> Just learning Python....
> 
> Running:
> 
>         Python 2.4.1 (#2, Aug 25 2005, 18:20:57) 
>         [GCC 4.0.1 (4.0.1-2mdk for Mandriva Linux
> release 2006.0)] on
> linux2
> 
> Concerning: IDLE
> 
> I tried several fonts, and finally changed the font
> on IDLE to courier
> size 22 bold, so that it is easier for my old eyes
> to read, and while
> the shell window still has color depicting the
> structure, the program
> window is now displaying only in black. (I also
> forgot what font IDLE
> originally was set on. A mind is such a terrible
> thing to loose...) 
> 
> Question:  How do I get color back in my programming
> window???   (It's
> soooo pretty that way!)
> 
> Thanks!
> 
> Terry

Until you save the program window to a file with a
'.py' extension, IDLE doesn't realize it's Python
source code so it doesn't do any syntax highlighting.

HTH, 
Don


Ha! Thanks Don!

I knew this was a dumb question. But, Tricky! Tricky! No wonder I 
couldn't find a combo of changes to revert things back. I kept looking 
at my test programs, and they were all in color because I always 
type the first word and SAVE to start a file! (a habit) I never noticed 
the difference. 
 
You just saved me a lot of confusion time wondering if I had broken something.
Terry 

	
		
______________________________________________________ 
Yahoo! for Good 
Donate to the Hurricane Katrina relief effort. 
http://store.yahoo.com/redcross-donate3/ 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050922/6d80fd64/attachment.html

From westside_indie at yahoo.com  Fri Sep 23 03:41:45 2005
From: westside_indie at yahoo.com (John Walton)
Date: Thu, 22 Sep 2005 18:41:45 -0700 (PDT)
Subject: [Tutor] words in networking I should probably know
Message-ID: <20050923014145.36973.qmail@web31009.mail.mud.yahoo.com>

Hello, again.  I'm back with my instant messenger
project.  My teacher has assigned us to write our
papers, excluding the procedure, results, and
conclusion.  One of my topics is going to be networks.
 Does anyone know a list of words relating to
networking/networks that I should know for this
project?  Not the definitions, but just the words; I
can look up the definitions on webopedia.  It would be
appreciated.  Thanks!
-John


		
__________________________________ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com

From falcon3166 at hotmail.com  Fri Sep 23 03:42:28 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Thu, 22 Sep 2005 19:42:28 -0600
Subject: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
	<432B8CA9.2000200@christianfreebies.com>
	<BAY106-DAV159F309A389BF7EECD88A1C4970@phx.gbl>
	<be4fbf92050922042136464a41@mail.gmail.com>
Message-ID: <BAY106-DAV12C80622184DA4A10D6CFBC4960@phx.gbl>

The URL is http://zoffee.tripod.com/purchasecomprogs.htm, and here is a third alternative: If the group says it is okay, I'll add them to the By: line as The Python Group, and I'll donate half of the sales to a charity of the group's choice.

Nathan Pinno
  ----- Original Message ----- 
  From: Adam 
  To: Nathan Pinno 
  Sent: Thursday, September 22, 2005 5:21 AM
  Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]


  What's the URL?


  On 22/09/05, Nathan Pinno <falcon3166 at hotmail.com> wrote:
    I have a challenge for everyone on the tutor list. Take this serious, and
    don't think I'm asking it just because I am mad or something. I'm not, I
    just want to clear the air once and for all. Here is the challenge:

    Choose any program that I am selling on my site, any one of them, and ask me
    for the code. I'll gladly send you a copy. Determine if I have copied most
    of it, or wrote most of it myself. Post your analysis to the group. If you 
    determine that I have copied most of it, I'll remove it and post an apology.
    If not, you must admit that I wrote most of it myself. Fair enough?

    Farewell for now,
    Nathan Pinno.
    ----- Original Message ----- 
    From: "Byron" <byron at christianfreebies.com>
    To: "Nathan Pinno" <falcon3166 at hotmail.com>; < Tutor at python.org>
    Sent: Friday, September 16, 2005 9:25 PM
    Subject: Re: [Tutor] Why won't it enter the quiz?


    > Nathan Pinno wrote:
    >> Brian and all,
    >>
    >> I am just asking for help - after all I write most each program myself,
    >> and just ask for help in debugging it whenever I cannot figure it out. If
    >> this is being sneaky, I apologize, and won't ask for help anymore. 
    >
    >
    > No, don't do that... Happy that you are asking questions!  I was humored
    > by the idea that you have a GREAT business model there...  :-)  FREE
    > Labor -- wow, should of thought of that one earlier...  <big grin> 
    >
    > Have a great weekend and hope you keep posting!
    >
    > Brian
    > ---
    >
    >
    >
    >
    _______________________________________________
    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/20050922/9dbf5a11/attachment-0001.htm

From kent37 at tds.net  Fri Sep 23 04:54:36 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 22 Sep 2005 22:54:36 -0400
Subject: [Tutor] Threading in a for loop
In-Reply-To: <433331E1.3090009@tds.net>
References: <43306BAE.1070404@pennswoods.net> <433331E1.3090009@tds.net>
Message-ID: <43336E6C.1060505@tds.net>

Here are some more resources for you.

This cookbook recipe is very similar to what you want to do, just customize workerThread1 to do the actual work. It shows how to use a Queue to communicate back to the GUI thread.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965

Here are a couple of thread pool recipes - these will be useful if you decide you need multiple threads.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/203871
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883

Threading is a complex subject and I don't have time and energy to do it justice right now. I hope these resources help.

Kent

Kent Johnson wrote:
> Bill Burns wrote:
> 
>>I've got a few questions regarding Threading. I've never used threads
>>before and I want to make sure I'm doing it correctly ;-)
>>
>>I have a GUI app and it processes Tiff files to PDF (or PostScript). The
>>GUI has a ListBox which the user populates with files to convert. You
>>click on a Button and the file conversion starts. When all the files
>>have been converted, the ListBox items (the files) are cleared.
>>
>>Initially, you had no way of knowing what was going on until all the
>>files where cleared from the ListBox.
>>
>>So I thought of creating threads in the 'for loop' and displaying the
>>name of each file in the statusBar of the GUI (as they are being
>>processed).
> 
> 
> You don't necessarily need threads for this. If you just want to provide feedback and don't care about the GUI being responsive, just do the processing in a loop, update the status bar and call root.update_idletasks() to allow the GUI to redraw. (Assuming you are using Tkinter.)
> 
> If you want the GUI to remain responsive so for example you can have a Cancel button, then I would make a single thread and process all the files in that thread. Don't sleep in the thread; call root.update() to give some time to event handling. Somehow you will have to notify the main thread that the worker thread is done.
> 
> The only reason I can think of to make a separate thread for each image is if the process is significantly I/O bound. My guess is that Tiff to PDF conversion is CPU-intensive and a single worker thread will be plenty.
> 
> More notes below...
>  
> 
>>Here's my method which takes the files in the ListBox and sends them off
>>to my Convert() class (self.convert = Convert()).
>><code>
>>def convertTiff2PDF(self):
>>     from time import time
>>     #Let's see how long this takes... I saw Kent do this on the
>>     #Python Tutor list before :-)
>>     start = time()
>>     #Grab a tuple which contains width & length
>>     sizes = self.getPaperSize()
>>     width = sizes[0]
>>     length = sizes[1]
>>     #Count the number of files in the ListBox
>>     fileCount = self.fileListBox.count()
>>     for index in range(fileCount):
>>         #Get each filename
>>         filenames = str(self.fileListBox.text(index))
>>         #Setup the worker thread and send the filenames in
>>         worker = WorkerThread(self, filenames)
>>         #Start threading
>>         worker.start()
>>         #Send each file to be converted
>>         self.convert.tiff2pdf(width, length, filenames)
> 
> 
> The above line should be in the thread, not in the main loop - you are spawning threads that do nothing but update the status display - and they will compete for that.
> 
> 
>>     #We're done, so clear the ListBox
>>     self.fileListBox.clear()
>>     #Check the time again
>>     end = time()
>>     msg = '%s Files Processed in %0.3f Seconds.' % (fileCount,
>>(end-start))
>>     #Grab the statusBar and insert the message
>>     statusBar = self.statusBar()
>>     statusBar.message(msg, 0)
>></code>
>>
>>And here's what I'm doing in my Thread class:
>><code>
>>class WorkerThread(Thread):
>>     """Thread class."""
>>     def __init__(self, parent, files):
>>         Thread.__init__(self)
>>         self.parent = parent
>>         self.files = files
>>
>>     def run(self):
>>         statusBar = self.parent.statusBar()
>>         msg = 'Processing: %s, please wait.' % (self.files)
>>         statusBar.message(msg, 100)
>>         time.sleep(1)
>></code>
>>
>>Am I doing this threading properly? Is it 'OK' to start multiple threads
>>like this (in the for loop)? It's possible that a user could put 'many'
>>files into the ListBox, by 'many' I mean 100-200 files.
> 
> 
> It's OK to have multiple threads but yours aren't doing any useful work.
> 
> I hope this helps get you on track, it's a bit brief.
> 
> Kent
> 
>>Thanks for your help.
>>
>>Bill
>>
>>
>>_______________________________________________
>>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
> 
> 


From bgailer at alum.rpi.edu  Fri Sep 23 06:08:14 2005
From: bgailer at alum.rpi.edu (bob)
Date: Thu, 22 Sep 2005 21:08:14 -0700
Subject: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
In-Reply-To: <BAY106-DAV12C80622184DA4A10D6CFBC4960@phx.gbl>
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
	<432B8CA9.2000200@christianfreebies.com>
	<BAY106-DAV159F309A389BF7EECD88A1C4970@phx.gbl>
	<be4fbf92050922042136464a41@mail.gmail.com>
	<BAY106-DAV12C80622184DA4A10D6CFBC4960@phx.gbl>
Message-ID: <6.1.2.0.0.20050922210541.02814178@mail.mric.net>

At 06:42 PM 9/22/2005, Nathan Pinno wrote:
>The URL is 
><http://zoffee.tripod.com/purchasecomprogs.htm>http://zoffee.tripod.com/purchasecomprogs.htm

[snip]

At your invitation I visited the site. I personally would not purchase 
anything listed there due to insufficient information. I don't know what 
I'm getting!

I suggest you dedicate a page to each program with at least one screenshot 
and explanation of what the program does. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050922/57a90236/attachment.html

From bgailer at alum.rpi.edu  Fri Sep 23 06:05:05 2005
From: bgailer at alum.rpi.edu (bob)
Date: Thu, 22 Sep 2005 21:05:05 -0700
Subject: [Tutor] Diamond Equivalent
In-Reply-To: <20050922224618.MEOL5796.aamta03-winn.mailhost.ntl.com@smtp
	.tesco.net>
References: <20050922224618.MEOL5796.aamta03-winn.mailhost.ntl.com@smtp.tesco.net>
Message-ID: <6.1.2.0.0.20050922210159.02813ee8@mail.mric.net>

At 03:46 PM 9/22/2005, kim.d at tesco.net wrote:
>I am coming to Python from Perl. Does Python have anything like the diamond
>operator found in Perl?

Some of us (who don't know Perl) might help you if you tell us what the 
diamond operator does. How could we get to first base with it? What are its 
facets? Does is have a heart counterpart? Ca it sing? 


From tutor.python.org at pooryorick.com  Fri Sep 23 06:42:31 2005
From: tutor.python.org at pooryorick.com (Poor Yorick)
Date: Fri, 23 Sep 2005 00:42:31 -0400
Subject: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
In-Reply-To: <6.1.2.0.0.20050922210541.02814178@mail.mric.net>
References: <mailman.1494.1126923682.508.tutor@python.org>	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>	<432B8CA9.2000200@christianfreebies.com>	<BAY106-DAV159F309A389BF7EECD88A1C4970@phx.gbl>	<be4fbf92050922042136464a41@mail.gmail.com>	<BAY106-DAV12C80622184DA4A10D6CFBC4960@phx.gbl>
	<6.1.2.0.0.20050922210541.02814178@mail.mric.net>
Message-ID: <433387B7.5070208@pooryorick.com>

bob wrote:
> At 06:42 PM 9/22/2005, Nathan Pinno wrote:
> 
>> The URL is http://zoffee.tripod.com/purchasecomprogs.htm
> 
> 
> [snip]
> 
> At your invitation I visited the site. I personally would not purchase 
> anything listed there due to insufficient information. I don't know what 
> I'm getting!
> 
> I suggest you dedicate a page to each program with at least one 
> screenshot and explanation of what the program does.

The shareware system would work best for these little programs. If it
were me, I would just use the honor system -- a pop-up window on program
startup that says "friendly reminder: This program costs $12.99. Have
you paid me for it or contributed to charity in my name yet? (yes/no)" 
Even though some (or even many, who knows?) people won't pay, it's worth 
the exposure. Another advantage is if people like what they download, 
they will come back and look for other things. In effect, your previous 
programs can advertise your newer programs.  Exposure is valuable.

--
Poor Yorick


From mi.janssen at gmail.com  Fri Sep 23 11:21:31 2005
From: mi.janssen at gmail.com (Michael Janssen)
Date: Fri, 23 Sep 2005 11:21:31 +0200
Subject: [Tutor] where to insert?
In-Reply-To: <111.52fa7853.306482d5@wmconnect.com>
References: <111.52fa7853.306482d5@wmconnect.com>
Message-ID: <1ff2dfbf05092302214d92e68b@mail.gmail.com>

On 9/22/05, Goofball223 at wmconnect.com <Goofball223 at wmconnect.com> wrote:

> I would like to insert string.join(msgList,"") into the following program where do I insert it?

do you want to build a temporary list and join its elements
afterwards? This can look like:

     # Loop through each substring and build ASCII message
     msgList = []
     for numStr in string.split(inString):
         asciiNum = int(numStr)           # convert digits to a number
         msgList.append(chr(asciiNum))
     # after completing the msgList, join it
     message = "".join(msgList)

Few notes: I have changed eval(numStr) into int(numStr) because int()
does everything you need here. eval() can do more but than just
converting digits into integers but this came at the cost of possible
unpredictable results. For example eval('1.23') is perfectly valid but
allowing floating point numbers wasn't your intention. int('1.23')
will fail with an exception wich is a good thing, because you can
catch the error and report the user back how to make better usage of
your programm. Other examples for unpredictable results with eval
invole eval('os.system("evilcommand")') or eval('range(2147483647)').
The latter would build a very large temporay list with numbers from 0
through 2147483646 which is likly to consume all of your machines
memory!

Second I'm using the "".join(msgList) (join as a string method)
instead of string.join(msgList, "") (join as a function of the string
modul), because it's slightly more readable and you mustn't remember
how string.join want to get its arguments.

Last not least: joining a list of strings instead of adding those
strings directly is a pattern used to avoid the problem that each
'alteration' of a string (as in 'message = message + chr(asciiNum)) is
in fact no alteration of the string but creates a new string every
time (because strings are immutable, i.e. can't be altered in place).
OTOH this problem doesn't seem to be such a big one ... In fact for
small strings and a small numer of them, the joining-a-list approach
can take more time. This is why I prefer to add strings directly and
only switch to an temporary list when I have really many strings or
when I gain some other advantages, when I e.g. want to join the
strings with a newline.


regards
Michael

From kim.d at tesco.net  Fri Sep 23 11:25:52 2005
From: kim.d at tesco.net (kim.d@tesco.net)
Date: Fri, 23 Sep 2005 9:25:52 +0000
Subject: [Tutor] Diamond Equivalent
Message-ID: <20050923092554.EUXD9247.aamta01-winn.mailhost.ntl.com@smtp.tesco.net>

>> I am coming to Python from Perl. Does Python have 
>>anything like the diamond operator found in Perl?


>Python includes a module called 'fileinput' that does sorta this:
>    http://www.python.org/doc/lib/module-fileinput.html
>If you have more questions, please feel free to ask.  
>Good luck to you!

Thanks, Danny. Is this module included with Python or will I have to download 
it? 


From kent37 at tds.net  Fri Sep 23 11:53:11 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 23 Sep 2005 05:53:11 -0400
Subject: [Tutor] Diamond Equivalent
In-Reply-To: <20050923092554.EUXD9247.aamta01-winn.mailhost.ntl.com@smtp.tesco.net>
References: <20050923092554.EUXD9247.aamta01-winn.mailhost.ntl.com@smtp.tesco.net>
Message-ID: <4333D087.9090702@tds.net>

kim.d at tesco.net wrote:
>>>I am coming to Python from Perl. Does Python have 
>>>anything like the diamond operator found in Perl?
> 
> 
> 
>>Python includes a module called 'fileinput' that does sorta this:
>>   http://www.python.org/doc/lib/module-fileinput.html
>>If you have more questions, please feel free to ask.  
>>Good luck to you!
> 
> 
> Thanks, Danny. Is this module included with Python or will I have to download 
> it? 

It is included as part of the standard library (as are all the modules in the doc Danny referenced).

Kent


From billburns at pennswoods.net  Fri Sep 23 12:18:02 2005
From: billburns at pennswoods.net (Bill Burns)
Date: Fri, 23 Sep 2005 06:18:02 -0400
Subject: [Tutor] Threading in a for loop
In-Reply-To: <43336E6C.1060505@tds.net>
References: <43306BAE.1070404@pennswoods.net> <433331E1.3090009@tds.net>
	<43336E6C.1060505@tds.net>
Message-ID: <4333D65A.7020600@pennswoods.net>

[Kent Johnson]
Here are some more resources for you.

This cookbook recipe is very similar to what you want to do, just 
customize workerThread1 to do the actual work. It shows how to use a 
Queue to communicate back to the GUI thread.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965

Here are a couple of thread pool recipes - these will be useful if you 
decide you need multiple threads.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/203871
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883

Kent,

Thank you for the tips and links. I'm using Pyqt and the top link above
has an example modified specifically for Pyqt, so that worked out nice!

As you stated, threading is complex (as I am now finding out), so I will
have to study these examples.

Thanks again!
Bill

From meesters at uni-mainz.de  Fri Sep 23 12:34:46 2005
From: meesters at uni-mainz.de (Christian Meesters)
Date: Fri, 23 Sep 2005 12:34:46 +0200
Subject: [Tutor] PyDoc problem
Message-ID: <9fa51d34fea032e19808297139c0cd6c@uni-mainz.de>

Hi,

PyDoc is working well, if invoked without flags on the modul in  
question. But when I use it with '-w' to produce html-output, I get an  
extremely long Traceback after a runtime of an hour or two. Here is a  
short part from it:

  Traceback (most recent call last):
  ? File "/usr/bin/pydoc", line 4, in ?
  ? ? pydoc.cli()
  ? File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/pydoc.py", line 2117, in cli
  ? ? writedoc(arg)
  ? File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/pydoc.py", line 1383, in writedoc
  ? ? page = html.page(describe(object), html.document(object, name))
  ? File  
"/Users/maxwell/Packages/SciPy_complete-0.3.2/build/lib.darwin-7.7.0- 
Power_Macintosh-2.3/scipy_base/ppimport.py", line 397, in  
_scipy_pydoc_Doc_document
  ? File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/pydoc.py", line 283, in document
  ? ? if inspect.ismodule(object): return self.docmodule(*args)
  <snip>
  ? File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/repr.py", line 49, in repr_list
  ? ? s = s + self.repr1(x[i], level-1)
  ? File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/pydoc.py", line 319, in repr1
  ? ? return self.escape(cram(stripid(repr(x)), self.maxother))
  ? File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/pydoc.py", line 111, in stripid
  ? ? if re.search(pattern, repr(Exception)):
  ? File  
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
python2.3/sre.py", line 137, in search
  ? ? return _compile(pattern, flags).search(string)
  RuntimeError: maximum recursion depth exceeded

What's going wrong? When I ask Pydoc to write html documentation for  
other modules there is no problem at all. It just works fine. And this  
traceback tell me nothing about my module, only about PyDoc. For it  
matters: I'm stuck with Python2.3 for compatibility reasons in this  
project and the module I'd like to see documented uses scipy and it is  
not really a small module anymore (about 1000 lines, including  
docstrings and comments).
Anybody an idea how I can force PyDoc to produce html output on this  
module?

TIA
Christian

From kim.d at tesco.net  Fri Sep 23 13:36:36 2005
From: kim.d at tesco.net (kim.d@tesco.net)
Date: Fri, 23 Sep 2005 11:36:36 +0000
Subject: [Tutor] Diamond Equivalent
Message-ID: <20050923113638.JKWS9247.aamta01-winn.mailhost.ntl.com@smtp.tesco.net>

>It is included as part of the standard 
>library (as are all the modules in the doc 
>Danny referenced).

Thanks, Kent.


From kim.d at tesco.net  Fri Sep 23 13:37:16 2005
From: kim.d at tesco.net (kim.d@tesco.net)
Date: Fri, 23 Sep 2005 11:37:16 +0000
Subject: [Tutor] Diamond Equivalent
Message-ID: <20050923113718.JLRO9247.aamta01-winn.mailhost.ntl.com@smtp.tesco.net>

bob wrote <<<Some of us (who don't know Perl) might help you if you tell us 
what the diamond operator does. How could we get to first base with it? What 
are its facets? Does is have a heart counterpart? Ca it sing?>>>

Sorry bob, that's what comes of posting my question last thing at night when 
finding the way upstairs is difficult enough.

In perl I can write this:

@array = <>;
print @array;

If I save that and call it from the command line, I can include the name of a 
file after the script name. It will read in the file, putting each line into an 
element of the array.

I know how to open a specific file using Python. I wanted to know how to give 
a Python script a file name in the command line, and have it open that file.

-kim


From kent37 at tds.net  Fri Sep 23 13:53:14 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 23 Sep 2005 07:53:14 -0400
Subject: [Tutor] PyDoc problem
In-Reply-To: <9fa51d34fea032e19808297139c0cd6c@uni-mainz.de>
References: <9fa51d34fea032e19808297139c0cd6c@uni-mainz.de>
Message-ID: <4333ECAA.8040700@tds.net>

Christian Meesters wrote:
> Hi,
> 
> PyDoc is working well, if invoked without flags on the modul in  
> question. But when I use it with '-w' to produce html-output, I get an  
> extremely long Traceback after a runtime of an hour or two. Here is a  
> short part from it:
> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ 
> python2.3/sre.py", line 137, in search
>       return _compile(pattern, flags).search(string)
>   RuntimeError: maximum recursion depth exceeded
> 
> What's going wrong? When I ask Pydoc to write html documentation for  
> other modules there is no problem at all. It just works fine. And this  
> traceback tell me nothing about my module, only about PyDoc. For it  
> matters: I'm stuck with Python2.3 for compatibility reasons in this  
> project and the module I'd like to see documented uses scipy and it is  
> not really a small module anymore (about 1000 lines, including  
> docstrings and comments).

Some re searches in Python 2.3 can cause stack overflow. It looks like you may be running in to that problem. It is fixed in Python 2.4; could you use 2.4 to run pydoc?

Here is the relevant section of the Python 2.4 release notes:
The re module is also no longer recursive, thanks to a massive amount of work by Gustavo Niemeyer. In a recursive regular expression engine, certain patterns result in a large amount of C stack space being consumed, and it was possible to overflow the stack. For example, if you matched a 30000-byte string of "a" characters against the expression (a|b)+, one stack frame was consumed per character. Python 2.3 tried to check for stack overflow and raise a RuntimeError exception, but certain patterns could sidestep the checking and if you were unlucky Python could segfault. Python 2.4's regular expression engine can match this pattern without problems.

Kent


From djennings3 at earthlink.net  Fri Sep 23 14:59:11 2005
From: djennings3 at earthlink.net (Don Jennings)
Date: Fri, 23 Sep 2005 08:59:11 -0400
Subject: [Tutor] thanks!
Message-ID: <D5DE822E-2C31-11DA-8B8F-0003930ACB16@earthlink.net>

Hi, everyone. Just a note of thanks to all of you who participate on 
the tutor list. I recently finished my first python CGI program, but I 
didn't have to post a lot of questions because most had been asked and 
answered already : >) For example, I wondered how to get unique file 
names for dynamic creation of web pages (answer: tempfile module). Keep 
up the great work.

Thanks again,
Don


From singletoned at gmail.com  Fri Sep 23 15:29:29 2005
From: singletoned at gmail.com (Ed Singleton)
Date: Fri, 23 Sep 2005 14:29:29 +0100
Subject: [Tutor] Remaking Vim in Python (was Python Editors)
Message-ID: <34bb7f5b05092306295748bd1b@mail.gmail.com>

I'd like a little advice on whether I'm being really stupid here.

Having researched editors and stuff, I've not quite found what I'm
looking for, though Vim comes close (except that it's extremely
difficult to work out what to do with it).

My instinct was to try and write a small program similar to vim, but
in Python.  The very basics should be quite easy.  If I start a system
that is very easily expandable then as and when I need further
functionality I can add it in.

html colourisation and auto-completion should be easy enough to add
using a html parser, but what about python?  Is there a python module
that can parse python code and is reasonably easy to use?  Also, css?

I know it would be ambitious to try and do this, but is it stupidly ambitious?

Ed

From meesters at uni-mainz.de  Fri Sep 23 15:41:58 2005
From: meesters at uni-mainz.de (Christian Meesters)
Date: Fri, 23 Sep 2005 15:41:58 +0200
Subject: [Tutor] PyDoc problem
In-Reply-To: <bbe9926e05092304182cdd2018@mail.gmail.com>
References: <9fa51d34fea032e19808297139c0cd6c@uni-mainz.de>
	<bbe9926e05092304182cdd2018@mail.gmail.com>
Message-ID: <299656923c9c4fd5bdcdbbe5d7d6beca@uni-mainz.de>

Hi Paul,

works great and within a seond, if I just uncomment the scipy imports. 
This was easy, but without your help I still would stare at my screen 
and think it's hopeless.

Thanks,
Christian
On 23 Sep 2005, at 13:18, paul brian wrote:

> THis sounds like a recursive import, which frankly should not happen
> but perhaps pydoc imports differently to the standard. Or it is trying
> to document the entire scipy framework, rather than just your module
>
> try firstly moving the module alone to directory foo and ensuring you
> are calling only that module
>
>> pydoc -w mymodule
>
> Perhaps also try uncommenting imports at the top of the file (ie #
> import scipy) to see if that helps.
>
>
>
> On 9/23/05, Christian Meesters <meesters at uni-mainz.de> wrote:
>> Hi,
>>
>> PyDoc is working well, if invoked without flags on the modul in
>> question. But when I use it with '-w' to produce html-output, I get an
>> extremely long Traceback after a runtime of an hour or two. Here is a
>> short part from it:
>>
>>  Traceback (most recent call last):
>>   File "/usr/bin/pydoc", line 4, in ?
>>   pydoc.cli()
>>   File
>> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
>> python2.3/pydoc.py", line 2117, in cli
>>   writedoc(arg)
>>   File
>> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
>> python2.3/pydoc.py", line 1383, in writedoc
>>   page = html.page(describe(object), html.document(object, name))
>>   File
>> "/Users/maxwell/Packages/SciPy_complete-0.3.2/build/lib.darwin-7.7.0-
>> Power_Macintosh-2.3/scipy_base/ppimport.py", line 397, in
>> _scipy_pydoc_Doc_document
>>   File
>> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
>> python2.3/pydoc.py", line 283, in document
>>   if inspect.ismodule(object): return self.docmodule(*args)
>>  <snip>
>>   File
>> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
>> python2.3/repr.py", line 49, in repr_list
>>   s = s + self.repr1(x[i], level-1)
>>   File
>> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
>> python2.3/pydoc.py", line 319, in repr1
>>   return self.escape(cram(stripid(repr(x)), self.maxother))
>>   File
>> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
>> python2.3/pydoc.py", line 111, in stripid
>>   if re.search(pattern, repr(Exception)):
>>   File
>> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
>> python2.3/sre.py", line 137, in search
>>   return _compile(pattern, flags).search(string)
>>  RuntimeError: maximum recursion depth exceeded
>>
>> What's going wrong? When I ask Pydoc to write html documentation for
>> other modules there is no problem at all. It just works fine. And this
>> traceback tell me nothing about my module, only about PyDoc. For it
>> matters: I'm stuck with Python2.3 for compatibility reasons in this
>> project and the module I'd like to see documented uses scipy and it is
>> not really a small module anymore (about 1000 lines, including
>> docstrings and comments).
>> Anybody an idea how I can force PyDoc to produce html output on this
>> module?
>>
>> TIA
>> Christian
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> --
> --------------------------
> Paul Brian
> m. 07875 074 534
> t. 0208 352 1741
>


From kent37 at tds.net  Fri Sep 23 15:52:10 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 23 Sep 2005 09:52:10 -0400
Subject: [Tutor] Remaking Vim in Python (was Python Editors)
In-Reply-To: <34bb7f5b05092306295748bd1b@mail.gmail.com>
References: <34bb7f5b05092306295748bd1b@mail.gmail.com>
Message-ID: <4334088A.6040101@tds.net>

Ed Singleton wrote:
> I'd like a little advice on whether I'm being really stupid here.
> 
> Having researched editors and stuff, I've not quite found what I'm
> looking for, though Vim comes close (except that it's extremely
> difficult to work out what to do with it).
> 
> My instinct was to try and write a small program similar to vim, but
> in Python.  The very basics should be quite easy.  If I start a system
> that is very easily expandable then as and when I need further
> functionality I can add it in.
> 
> I know it would be ambitious to try and do this, but is it stupidly ambitious?

You might consider starting from one of the existing editors written in Python, e.g. IDLE, eric3, spe, DrPython, scite and modifying it to suit. Writing an editor is a big project. OTOH most of these editors probably started out with some developer scratching an itch. So I'm not sure I would call it stupidly ambitious...

Kent


From albertito_g at hotmail.com  Fri Sep 23 16:27:55 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Fri, 23 Sep 2005 14:27:55 +0000
Subject: [Tutor] FW: Re: USB Capture Image WebCAM
In-Reply-To: <433351E2.6020204@pooryorick.com>
Message-ID: <BAY106-F27199A94F0A54FF87F79B389960@phx.gbl>

Hey all

If you noticed I also admitted that I don't want to crack it but I needed 
for testing
In fact if I wanted to crack 200 licenses I wouldn't be asking you guys for 
help on this program
By the way ....I bought 10 licenses from them so crime...I really don't 
think so

Let's see:

200 *10 $us = 2000 $us
My own prog = Free (well maybe a little of time)
I don't mean to crack the software and give it, I mean to make my own. 
That's why I posted.
And also I don't use cracked softwares..They always have some error when you 
crack it.

Sorry if I cause the wrong impression here. :)

Then again, I still can't make the code works...it keeps crashing with the 
same error I sent
I tried to contact Markus (the creator of VideoCapture) but without luck

Anyone who has tried it out or want to try it out?

Best Regards

Alberto


>From: Poor Yorick <tutor.python.org at pooryorick.com>
>To: tutor at python.org
>Subject: Re: [Tutor] FW: Re: USB Capture Image WebCAM
>Date: Thu, 22 Sep 2005 20:52:50 -0400
>
>Alberto Troiano wrote:
>
> >
> > But it doesn't works so fine, I think its because I cracked and didn't 
>buy
> > it *grin*
> > But I need like 200 licenses so it would be a little expensive. That's 
>why
> > I'm trying to make my own Python Gengis Cam *grin*
> >
>
>You just admitted on a public forum to committing a crime.  Not wise,
>friend.
>
>--
>Poor Yorick
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



From Goofball223 at wmconnect.com  Fri Sep 23 17:26:40 2005
From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com)
Date: Fri, 23 Sep 2005 11:26:40 EDT
Subject: [Tutor] simplifying with string-formatting operator
Message-ID: <1e8.43f9cd66.306578b0@wmconnect.com>

Hello

Does anyone have any idea on how i could simplify the following program by 
using strings?

# dateconvert2.py
#    Converts day month and year numbers into two date formats

import string

def main():
    # get the day month and year
    day, month, year = input("Please enter the day, month and year numbers: ")

    date1 = str(month)+"/"+str(day)+"/"+str(year)

    months = ["January", "February", "March", "April",
              "May", "June", "July", "August",
              "September", "October", "November", "December"]
    monthStr = months[month-1]
    date2 = monthStr+" " + str(day) + ", " + str(year)

    print "The date is", date1, "or", date2

main()

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050923/3c9c4559/attachment.htm

From paul1brian at gmail.com  Fri Sep 23 17:41:04 2005
From: paul1brian at gmail.com (paul brian)
Date: Fri, 23 Sep 2005 16:41:04 +0100
Subject: [Tutor] simplifying with string-formatting operator
In-Reply-To: <1e8.43f9cd66.306578b0@wmconnect.com>
References: <1e8.43f9cd66.306578b0@wmconnect.com>
Message-ID: <bbe9926e05092308417725c784@mail.gmail.com>

I would suggest you use the built in datetime modules or egenix mx.DateTime.

for example

>>> import datetime
>>> year = "05"; month="09";day="23"
>>> dateobj = datetime.date(int(year)+2000, int(month), int(day))
>>> dateobj.strftime("%A %B %y")
'Friday September 05'
>>>

obviously you need to look at how the incoming 2 digit strings are
checked and so on.

By the way the strftime("%A %B %y") tells python to print out the date
as %A which is locale weekday etc etc. with the %A or %B being
replaced in a similar way to %s in normal string formatting.

strftime is well documented in the time module docs.

cheers


On 9/23/05, Goofball223 at wmconnect.com <Goofball223 at wmconnect.com> wrote:
> Hello
>
> Does anyone have any idea on how i could simplify the following program by
> using strings?
>
> # dateconvert2.py
> #    Converts day month and year numbers into two date formats
>
> import string
>
> def main():
>    # get the day month and year
>    day, month, year = input("Please enter the day, month and year numbers:
> ")
>
>    date1 = str(month)+"/"+str(day)+"/"+str(year)
>
>    months = ["January", "February", "March", "April",
>              "May", "June", "July", "August",
>              "September", "October", "November", "December"]
>    monthStr = months[month-1]
>    date2 = monthStr+" " + str(day) + ", " + str(year)
>
>    print "The date is", date1, "or", date2
>
> main()
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


--
--------------------------
Paul Brian
m. 07875 074 534
t. 0208 352 1741

From ajikoe at gmail.com  Fri Sep 23 18:28:25 2005
From: ajikoe at gmail.com (Pujo Aji)
Date: Fri, 23 Sep 2005 18:28:25 +0200
Subject: [Tutor] simplifying with string-formatting operator
In-Reply-To: <1e8.43f9cd66.306578b0@wmconnect.com>
References: <1e8.43f9cd66.306578b0@wmconnect.com>
Message-ID: <cf5262d205092309282787878c@mail.gmail.com>

hello,
 you can use this model:

day, month, year = input("Please enter the day, month and year numbers: ")
date1 = '%s/%s/%s' % (month, day, year)

months = {1:"January", 2:"February", 3:"March", 4:"April",
5: "May", 6: "June", 7: "July", 8: "August",
9: "September", 10: "October", 11: "November", 12: "December"}

date2 = '%s %s, %s' % (months[int(day)], day, year)
print 'the date is %s or %s' % (date1, date2)
 cheers,
pujo

 On 9/23/05, Goofball223 at wmconnect.com <Goofball223 at wmconnect.com> wrote:
>
> Hello
>
> Does anyone have any idea on how i could simplify the following program by
> using strings?
>
> # dateconvert2.py
> # Converts day month and year numbers into two date formats
>
> import string
>
> def main():
> # get the day month and year
> day, month, year = input("Please enter the day, month and year numbers: ")
>
>
> date1 = str(month)+"/"+str(day)+"/"+str(year)
>
> months = ["January", "February", "March", "April",
> "May", "June", "July", "August",
> "September", "October", "November", "December"]
> monthStr = months[month-1]
> date2 = monthStr+" " + str(day) + ", " + str(year)
>
> print "The date is", date1, "or", date2
>
> main()
>
> _______________________________________________
> 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/20050923/9acdc7e5/attachment.htm

From hugonz-lists at h-lab.net  Fri Sep 23 18:32:06 2005
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Fri, 23 Sep 2005 11:32:06 -0500
Subject: [Tutor] FW: Re:  USB Capture Image WebCAM
In-Reply-To: <BAY106-F29C40A56E9A3E1E2FC8F9189970@phx.gbl>
References: <BAY106-F29C40A56E9A3E1E2FC8F9189970@phx.gbl>
Message-ID: <43342E06.8040105@h-lab.net>

Hi Alberto,

Sorry if I point out something obvious... from the page:

#
# The high-level module needs PIL to produce actual images from the 
pixel-data. PIL can be downloaded from PythonWare.

Do you have PIL installed? The fact that the image cannot be created 
just bit me...

Hugo

Alberto Troiano wrote:
> Hey Danny
> 
> I have downloaded videoCapture but I can't make it run. This is the error I
> get when I try run the example
> 
> Traceback (most recent call last):
>   File "C:\Documents and Settings\Daron 
> Malakian\Desktop\VideoCapture-0.9\Tools\webcam-uploader\webcam-uploader.py", 
> line 130, in ?
>     cam = VideoCapture.Device(devnum=devnum)
>   File "C:\Python23\lib\VideoCapture.py", line 49, in __init__
>     self.dev = vidcap.new_Dev(devnum, showVideoWindow)
> Error: Capture Graph could not be created.
> 
> 
> I want to be able to see the reproduction of the WebCAM inside a GUI of
> Python
> 
> I didn't find docs for this on the WEB. If somebody have some pointers I
> would appreciate a lot
> 
> Thanks in advanced
> 
> Alberto
> 
> 
> 
>>>From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
>>>To: Alberto Troiano <albertito_g at hotmail.com>
>>>CC: tutor at python.org
>>>Subject: Re: [Tutor] USB Capture Image WebCAM
>>>Date: Thu, 22 Sep 2005 11:38:16 -0700 (PDT)
>>>
>>>
>>>
>>>On Thu, 22 Sep 2005, Alberto Troiano wrote:
>>>
>>>
>>>>For those who doesn't know what is it its a program that captures 
>>
>>images
>>
>>>>from your USB WebCAM and saves them to send via FTP.
>>>>
>>>>Anyway, getting to the point I don't know how to get the video from 
>>
>>the
>>
>>>>camara to watch it inside a GUI made in Python.
>>>
>>>You might be in luck; there's a project that provides USB Webcam access
>>>for Windows:
>>>
>>>    http://videocapture.sourceforge.net/
>>>
>>>Good luck!
>>>
>>>_______________________________________________
>>>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
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From bgailer at alum.rpi.edu  Fri Sep 23 19:10:13 2005
From: bgailer at alum.rpi.edu (bob)
Date: Fri, 23 Sep 2005 10:10:13 -0700
Subject: [Tutor] Diamond Equivalent
In-Reply-To: <20050923113718.JLRO9247.aamta01-winn.mailhost.ntl.com@smtp
	.tesco.net>
References: <20050923113718.JLRO9247.aamta01-winn.mailhost.ntl.com@smtp.tesco.net>
Message-ID: <6.1.2.0.0.20050923100556.03528390@mail.mric.net>

At 04:37 AM 9/23/2005, kim.d at tesco.net wrote:
>[snip]
>In perl I can write this:
>
>@array = <>;
>print @array;
>
>If I save that and call it from the command line, I can include the name of a
>file after the script name. It will read in the file, putting each line 
>into an
>element of the array.
>
>I know how to open a specific file using Python. I wanted to know how to give
>a Python script a file name in the command line, and have it open that file.

So there are 2 parts to the question:

(1) how to retrieve command line arguments:

import sys
arg1 = sys.argv[1]

(2) how to read the lines of a file (whose path is in arg1) into an array

array = file(arg1).readlines()

That's all. Of course you don't need an intermediate variable; you can just:

import sys
array = file(sys.argv[1]).readlines()

and if you want to print the results:

print array 


From marcink at ieee.org  Fri Sep 23 19:48:59 2005
From: marcink at ieee.org (Marcin Komorowski)
Date: Fri, 23 Sep 2005 13:48:59 -0400
Subject: [Tutor] Remaking Vim in Python (was Python Editors)
References: <34bb7f5b05092306295748bd1b@mail.gmail.com>
	<4334088A.6040101@tds.net>
Message-ID: <037301c5c067$13f98010$6471a8c0@zobook>

Ed,
Before you dive into a full-fledged editor development project you might 
want to consider an existing extendible platform like Eclipse.  It is much 
more than just an editor, i.e. it is an advanced IDE platform.  The sweet 
thing is that it allows for developing plugins to add functionality.  I have 
not tried it, but someone already developed a vi input mode plugin for it.

Cheers,
Marcin
----- Original Message ----- 
From: "Kent Johnson" <kent37 at tds.net>
Cc: <tutor at python.org>
Sent: Friday, September 23, 2005 9:52 AM
Subject: Re: [Tutor] Remaking Vim in Python (was Python Editors)


> Ed Singleton wrote:
>> I'd like a little advice on whether I'm being really stupid here.
>>
>> Having researched editors and stuff, I've not quite found what I'm
>> looking for, though Vim comes close (except that it's extremely
>> difficult to work out what to do with it).
>>
>> My instinct was to try and write a small program similar to vim, but
>> in Python.  The very basics should be quite easy.  If I start a system
>> that is very easily expandable then as and when I need further
>> functionality I can add it in.
>>
>> I know it would be ambitious to try and do this, but is it stupidly 
>> ambitious?
>
> You might consider starting from one of the existing editors written in 
> Python, e.g. IDLE, eric3, spe, DrPython, scite and modifying it to suit. 
> Writing an editor is a big project. OTOH most of these editors probably 
> started out with some developer scratching an itch. So I'm not sure I 
> would call it stupidly ambitious...
>
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



From project5 at redrival.net  Fri Sep 23 20:14:37 2005
From: project5 at redrival.net (Andrei)
Date: Fri, 23 Sep 2005 20:14:37 +0200
Subject: [Tutor] Remaking Vim in Python (was Python Editors)
In-Reply-To: <34bb7f5b05092306295748bd1b@mail.gmail.com>
References: <34bb7f5b05092306295748bd1b@mail.gmail.com>
Message-ID: <dh1gmg$c6u$1@sea.gmane.org>

Ed Singleton wrote:
> My instinct was to try and write a small program similar to vim, but
> in Python.  The very basics should be quite easy.  If I start a system
> that is very easily expandable then as and when I need further
> functionality I can add it in.

I'd say it's better to either adapt an existing editor or write a new 
editor from scratch, but using an existing editor component. Under 
wxPython you could use the Scintilla control. This approach is much less 
time consuming than writing your own text editor control which will most 
likely end up either being less powerful than what you'd get for free if 
building on existing functionality. Text editors are more fiddly than 
you might expect, because they offer a lot of functionality people don't 
even notice is there until they come across one which lacks it. E.g. I 
avoid IDLE and Leo simply because I don't like their editing components.

You might even be interested in customizing Vim itself. I don't know 
what your goals are, but you could e.g. look at Cream 
(http://cream.sf.net) for a more user-friendly Vim.

> I know it would be ambitious to try and do this, but is it stupidly ambitious?

It's not stupidly ambitious, but odds are (simply based on the amount of 
editors out there and the features they have) that you'll end up with 
not much more than a slightly fancy notepad. This can of course still be 
a useful learning exercise, but if you want to have an editor in which 
to be productive, it's probably better to invest some time in learning 
to use one of the existing options. Whether it's Spe, Scite, Komodo, 
Vim, Emacs or whatever else suits you, is not very relevant.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From 3dbernard at gmail.com  Fri Sep 23 20:35:52 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri, 23 Sep 2005 14:35:52 -0400
Subject: [Tutor] Problem with BeautifulSoup
Message-ID: <61d0e2b405092311354fd2d76e@mail.gmail.com>

Hello,

I have this set of XML tags:


<parameter scriptname="posx"
fullname="Model.Camera_anim.kine.local.posx" type="Parameter"
sourceclassname="FCurve">
	<fcurve plotted="False">
	   <parameters>
		  <parameter scriptname="extrapolation">1</parameter>
		  <parameter scriptname="interpolation">3</parameter>
		  <parameter scriptname="highclamp">1.79769313486e+308</parameter>
		  <parameter scriptname="locked">False</parameter>
		  <parameter scriptname="lowclamp">-1.79769313486e+308</parameter>
		  <parameter scriptname="nokeyvalue">7.64880829803</parameter>
		  <parameter scriptname="si3dstyle">False</parameter>
		  <parameter scriptname="type">20</parameter>
	   </parameters>
	</fcurve>
</parameter>


This set of tags is nested deep few levels of tags. When I get the
fcurve tag, all I get is an empty tag. ie:


oXMLFcurve = oXMLParameter.fcurve
print str(oXMLFcurve)


Outputs:


<fcurve plotted="False">
</fcurve>


Normally it would print all the content of the tag, but it's not....
Any suggestion or pointer would be welcome!


Thanks
Bernard

From albertito_g at hotmail.com  Fri Sep 23 20:54:33 2005
From: albertito_g at hotmail.com (Alberto Troiano)
Date: Fri, 23 Sep 2005 18:54:33 +0000
Subject: [Tutor] FW: Re: USB Capture Image WebCAM
In-Reply-To: <43342E06.8040105@h-lab.net>
Message-ID: <BAY106-F24B3E444BF36925F08E2D189960@phx.gbl>

Hey Hugo

Yes...I have PIL 1.1.5 installed.
The weird thing about this is that the program gets one image and then show 
the error I sent
After that it doesn't load any more images and I have to unplug tha web cam 
and plug it again so I can get the software to work only one more time and 
so on

I will try it out in the computer I have at home...I'm thiking that maybe it 
is something on the machine...that's why I would like that somebody who had 
tried this app tell if this worked ok or maybe had the same problem I have

Thanks anyway Hugo

Alberto

>From: Hugo Gonz?lez Monteverde <hugonz-lists at h-lab.net>
>To: Alberto Troiano <albertito_g at hotmail.com>
>CC: tutor at python.org
>Subject: Re: [Tutor] FW: Re:  USB Capture Image WebCAM
>Date: Fri, 23 Sep 2005 11:32:06 -0500
>
>Hi Alberto,
>
>Sorry if I point out something obvious... from the page:
>
>#
># The high-level module needs PIL to produce actual images from the 
>pixel-data. PIL can be downloaded from PythonWare.
>
>Do you have PIL installed? The fact that the image cannot be created just 
>bit me...
>
>Hugo
>
>Alberto Troiano wrote:
>>Hey Danny
>>
>>I have downloaded videoCapture but I can't make it run. This is the error 
>>I
>>get when I try run the example
>>
>>Traceback (most recent call last):
>>   File "C:\Documents and Settings\Daron 
>>Malakian\Desktop\VideoCapture-0.9\Tools\webcam-uploader\webcam-uploader.py", 
>>line 130, in ?
>>     cam = VideoCapture.Device(devnum=devnum)
>>   File "C:\Python23\lib\VideoCapture.py", line 49, in __init__
>>     self.dev = vidcap.new_Dev(devnum, showVideoWindow)
>>Error: Capture Graph could not be created.
>>
>>
>>I want to be able to see the reproduction of the WebCAM inside a GUI of
>>Python
>>
>>I didn't find docs for this on the WEB. If somebody have some pointers I
>>would appreciate a lot
>>
>>Thanks in advanced
>>
>>Alberto
>>
>>
>>
>>>>From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
>>>>To: Alberto Troiano <albertito_g at hotmail.com>
>>>>CC: tutor at python.org
>>>>Subject: Re: [Tutor] USB Capture Image WebCAM
>>>>Date: Thu, 22 Sep 2005 11:38:16 -0700 (PDT)
>>>>
>>>>
>>>>
>>>>On Thu, 22 Sep 2005, Alberto Troiano wrote:
>>>>
>>>>
>>>>>For those who doesn't know what is it its a program that captures
>>>
>>>images
>>>
>>>>>from your USB WebCAM and saves them to send via FTP.
>>>>>
>>>>>Anyway, getting to the point I don't know how to get the video from
>>>
>>>the
>>>
>>>>>camara to watch it inside a GUI made in Python.
>>>>
>>>>You might be in luck; there's a project that provides USB Webcam access
>>>>for Windows:
>>>>
>>>>    http://videocapture.sourceforge.net/
>>>>
>>>>Good luck!
>>>>
>>>>_______________________________________________
>>>>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
>>
>>
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>



From grouch at gmail.com  Fri Sep 23 21:07:39 2005
From: grouch at gmail.com (grouchy)
Date: Fri, 23 Sep 2005 14:07:39 -0500
Subject: [Tutor] Problem with BeautifulSoup
In-Reply-To: <61d0e2b405092311354fd2d76e@mail.gmail.com>
References: <61d0e2b405092311354fd2d76e@mail.gmail.com>
Message-ID: <e6443aa7050923120758b6dbc3@mail.gmail.com>

Hi Bernard,
 Not much of an answer, but I printed out your snippet with prettify() to
see how it was being parsed, and either the XML is funny, or Beautiful Soup
is :)

>>> from BeautifulSoup import BeautifulStoneSoup as BSS
>>> soup = BSS(xml)
>>> print soup.prettify()

<parameter scriptname="posx" fullname="Model.Camera_anim.kine.local.posx"
type="Parameter" sourceclassname="FCurve">
<fcurve plotted="False">
<parameters>
</parameters>
</fcurve>
</parameter>
<parameter scriptname="extrapolation">1
</parameter>
<parameter scriptname="interpolation">3
</parameter>
<parameter scriptname="highclamp">1.79769313486e+308
</parameter>
<parameter scriptname="locked">False
</parameter>
<parameter scriptname="lowclamp">-1.79769313486e+308
</parameter>
<parameter scriptname="nokeyvalue">7.64880829803
</parameter>
<parameter scriptname="si3dstyle">False
</parameter>
<parameter scriptname="type">20
</parameter>?
>>>


 On 9/23/05, Bernard Lebel <3dbernard at gmail.com> wrote:
>
> Hello,
>
> I have this set of XML tags:
>
>
> <parameter scriptname="posx"
> fullname="Model.Camera_anim.kine.local.posx" type="Parameter"
> sourceclassname="FCurve">
> <fcurve plotted="False">
> <parameters>
> <parameter scriptname="extrapolation">1</parameter>
> <parameter scriptname="interpolation">3</parameter>
> <parameter scriptname="highclamp">1.79769313486e+308</parameter>
> <parameter scriptname="locked">False</parameter>
> <parameter scriptname="lowclamp">-1.79769313486e+308</parameter>
> <parameter scriptname="nokeyvalue">7.64880829803</parameter>
> <parameter scriptname="si3dstyle">False</parameter>
> <parameter scriptname="type">20</parameter>
> </parameters>
> </fcurve>
> </parameter>
>
>
> This set of tags is nested deep few levels of tags. When I get the
> fcurve tag, all I get is an empty tag. ie:
>
>
> oXMLFcurve = oXMLParameter.fcurve
> print str(oXMLFcurve)
>
>
> Outputs:
>
>
> <fcurve plotted="False">
> </fcurve>
>
>
> Normally it would print all the content of the tag, but it's not....
> Any suggestion or pointer would be welcome!
>
>
> Thanks
> Bernard
> _______________________________________________
> 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/20050923/f9eb6374/attachment.html

From zathras at thwackety.com  Fri Sep 23 21:15:03 2005
From: zathras at thwackety.com (Michael Sparks)
Date: Fri, 23 Sep 2005 20:15:03 +0100
Subject: [Tutor] Diamond Equivalent
In-Reply-To: <20050922224618.MEOL5796.aamta03-winn.mailhost.ntl.com@smtp.tesco.net>
References: <20050922224618.MEOL5796.aamta03-winn.mailhost.ntl.com@smtp.tesco.net>
Message-ID: <200509232015.03511.zathras@thwackety.com>

On Thursday 22 September 2005 23:46, kim.d at tesco.net wrote:
> I am coming to Python from Perl. Does Python have anything like the diamond
> operator found in Perl?

The correct answer is not really no, but you can manually perform the
same tasks. For those who don't know perl, <> is an incredibly useful
little operator that does some really wierd and wonderful things :-)

(That said, I don't think I'd like a magic operator like this in python :-)

If you want to do this:

@a = <>;

The equivalent is probably best expressed thus:

def diamond_array():
# Note, untested...
   import sys
   if len(sys.argv ==1):
      return sys.stdin.readlines()
   else:
      result = []
      for file in sys.argv[1:]:
         try:
            file = open(file)
            result.extend(file.readlines())
         except IOError:
            pass
      return result

a = diamond_array()


If however you want to do the equivalent of:

while ($line = <>) {
   ...
}

That mode of <> probably best equates to this:

for line in diamond_lines():
   ....

def diamond_lines():
# Note, untested...
   import sys
   if len(sys.argv ==1):
      for line in sys.stdin.xreadlines():
         yield line
   else:
      for file in sys.argv[1:]:
         try:
            file = open(file)
            for line in file.xreadlines():
                yield line
         except IOError:
            pass

As for this idiom:

while(1) {
   $line = <>;
   ...
}

That probably matches best to this:

diamond_iterator = diamond_lines() # same function as above
while 1:
    line = diamond_iterator.next()

Whereas this kind of trick:

$firstline = <>;
@remaining_lines = <>;

Would map to this: (using the functions above)

diamond_iterator  = diamond_lines() 
firstline = diamond_iterator.next()
remaining_lines = list(diamond_iterator.next())

Or to show a relatively common perl idiom:

$firstline, @remaining_lines= <>,<>;

Maps to:

diamond_iterator  = diamond_lines() 
firstline,remaining_lines = diamond_iterator.next(), list(diamond_iterator.next())

Best Regards,


Michael.



From 3dbernard at gmail.com  Fri Sep 23 21:15:14 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri, 23 Sep 2005 15:15:14 -0400
Subject: [Tutor] Problem with BeautifulSoup
In-Reply-To: <e6443aa7050923120758b6dbc3@mail.gmail.com>
References: <61d0e2b405092311354fd2d76e@mail.gmail.com>
	<e6443aa7050923120758b6dbc3@mail.gmail.com>
Message-ID: <61d0e2b405092312154bce6c53@mail.gmail.com>

Hi grouchy,

I seem to have found the problem. Somehow, it seems BeautifulSoup
doesn't like nested tags of the same name. For instance, I had this
tree:

<parameters>
   <parameter...>
      <fcurve>
         <parameters>
            <parameter...>
            </parameter>
         </parameters>
      </fcurve>
   </parameter>
</parameters>


Printing the entire tree in the command line shell showed some weird
rearrangements of the tree in these areas, where tags would show up in
different order, and there were a few black lines (there are none in
my xml file beyond the first tree tag). Chaing the second second of
<parameters><parameter> combination to
<fcurveparameters><fcurveparameter> seem to have solved the issue.

This sounds to me like a limitation..... oh well.


Thanks!
Bernard



On 9/23/05, grouchy <grouch at gmail.com> wrote:
> Hi Bernard,
>
> Not much of an answer, but I printed out your snippet with prettify() to see
> how it was being parsed, and either the XML is funny, or Beautiful Soup is
> :)
>
> >>> from BeautifulSoup import BeautifulStoneSoup as BSS
> >>> soup = BSS(xml)
> >>> print soup.prettify()
>
>  <parameter scriptname="posx"
> fullname="Model.Camera_anim.kine.local.posx"
> type="Parameter" sourceclassname="FCurve">
>   <fcurve plotted="False">
>    <parameters>
>    </parameters>
>   </fcurve>
>  </parameter>
>  <parameter scriptname="extrapolation">1
>  </parameter>
>  <parameter scriptname="interpolation">3
>  </parameter>
>  <parameter scriptname="highclamp">1.79769313486e+308
>  </parameter>
>  <parameter scriptname="locked">False
>  </parameter>
>  <parameter scriptname="lowclamp">- 1.79769313486e+308
>  </parameter>
>  <parameter scriptname="nokeyvalue">7.64880829803
>  </parameter>
>  <parameter scriptname="si3dstyle">False
>  </parameter>
>  <parameter scriptname="type">20
>  </parameter>?
> >>>
>
>
>
>
> On 9/23/05, Bernard Lebel <3dbernard at gmail.com> wrote:
> >
> > Hello,
> >
> > I have this set of XML tags:
> >
> >
> > <parameter scriptname="posx"
> > fullname=" Model.Camera_anim.kine.local.posx"
> type="Parameter"
> > sourceclassname="FCurve">
> >        <fcurve plotted="False">
> >           <parameters>
> >                  <parameter
> scriptname="extrapolation">1</parameter>
> >                  <parameter
> scriptname="interpolation">3</parameter>
> >                  <parameter
> scriptname="highclamp">1.79769313486e+308</parameter>
> >                  <parameter
> scriptname="locked">False</parameter>
> >                  <parameter
> scriptname="lowclamp">-1.79769313486e+308</parameter>
> >                  <parameter
> scriptname="nokeyvalue">7.64880829803</parameter>
> >                  <parameter
> scriptname="si3dstyle">False</parameter>
> >                  <parameter
> scriptname="type">20</parameter>
> >           </parameters>
> >        </fcurve>
> > </parameter>
> >
> >
> > This set of tags is nested deep few levels of tags. When I get the
> > fcurve tag, all I get is an empty tag. ie:
> >
> >
> > oXMLFcurve = oXMLParameter.fcurve
> > print str(oXMLFcurve)
> >
> >
> > Outputs:
> >
> >
> > <fcurve plotted="False">
> > </fcurve>
> >
> >
> > Normally it would print all the content of the tag, but it's not....
> > Any suggestion or pointer would be welcome!
> >
> >
> > Thanks
> > Bernard
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>

From TValone at DMV.CA.gov  Sat Sep 24 00:27:38 2005
From: TValone at DMV.CA.gov (Valone, Toren W.)
Date: Fri, 23 Sep 2005 15:27:38 -0700
Subject: [Tutor] Stupid newbie question
Message-ID: <5AE0A72A4C0AD711806A000255FC47DB09CC1911@dmv-ent-ex07.dmv.ca.gov>

I am trying to noodle thru classes with python and I built the following
class

import time

class startremail:
    def __init__(self):  
     remailfile = open('U:\Bounce20.txt', 'r')             #future
address/file from outlook
     resendfile = open('resend.txt', 'w')                  #currently these
files are in Python24
     EmailReport = open('erprt.txt', 'w')                  #Report of bad
emails etc
     fromaddr='Tvalone at dmv.ca.gov'                         #set fromadd to a
constant
     null_recepient_count = 0
     date_received = ""
     date_email_generated = ""
     Error_050 = ""
     Error_501 = ""
     Current_Date = time.ctime(time.time())
     month = Current_Date[4:8]
     day = Current_Date[8:10]
     print month

     def getday(self):
         return self.day
        
     def Read(self,line):
         line = remailfile.readline()                          #primer read 
         return line


I fire up IDLE and then do this 

from startremail import *
x = startremail()
print x.getday()
I get the following return

NameError: name 'getday' is not defined



From bill at celestial.net  Sat Sep 24 00:38:27 2005
From: bill at celestial.net (Bill Campbell)
Date: Fri, 23 Sep 2005 15:38:27 -0700
Subject: [Tutor] Stupid newbie question
In-Reply-To: <5AE0A72A4C0AD711806A000255FC47DB09CC1911@dmv-ent-ex07.dmv.ca.gov>
References: <5AE0A72A4C0AD711806A000255FC47DB09CC1911@dmv-ent-ex07.dmv.ca.gov>
Message-ID: <20050923223826.GA9883@alexis.mi.celestial.com>

On Fri, Sep 23, 2005, Valone, Toren W. wrote:
>I am trying to noodle thru classes with python and I built the following
>class
>
>import time
>
>class startremail:
>    def __init__(self):  
>     remailfile = open('U:\Bounce20.txt', 'r')             #future
>address/file from outlook
>     resendfile = open('resend.txt', 'w')                  #currently these
>files are in Python24
>     EmailReport = open('erprt.txt', 'w')                  #Report of bad
>emails etc
>     fromaddr='Tvalone at dmv.ca.gov'                         #set fromadd to a
>constant
>     null_recepient_count = 0
>     date_received = ""
>     date_email_generated = ""
>     Error_050 = ""
>     Error_501 = ""
>     Current_Date = time.ctime(time.time())
>     month = Current_Date[4:8]
>     day = Current_Date[8:10]
>     print month
>
>     def getday(self):
>         return self.day
>        
>     def Read(self,line):
>         line = remailfile.readline()                          #primer read 
>         return line
>
>
>I fire up IDLE and then do this 
>
>from startremail import *
>x = startremail()
>print x.getday()
>I get the following return
>
>NameError: name 'getday' is not defined

It appears that you're being bitten by my least-favorite ``feature''
of python, indentation errors.  The getday routine appears to be a
subroutine of __init__, not a method of the class.

BTW:  Not to start a religious war, I hated BEGIN/END blocks on
ALGOL too, but in those days my editor was an 026 keypunch or
worse, making paper tapes on a teletype for time sharing services.

Bill
--
INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
UUCP:               camco!bill  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676
URL: http://www.celestial.com/

``You know the one thing that's wrong with this country? Everyone gets a
chance to have their fair say.''
    -Bill Clinton, May 29, 1993, The White House

From dyoo at hkn.eecs.berkeley.edu  Sat Sep 24 00:41:04 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 23 Sep 2005 15:41:04 -0700 (PDT)
Subject: [Tutor] Stupid newbie question
In-Reply-To: <5AE0A72A4C0AD711806A000255FC47DB09CC1911@dmv-ent-ex07.dmv.ca.gov>
Message-ID: <Pine.LNX.4.44.0509231533270.30129-100000@hkn.eecs.berkeley.edu>



On Fri, 23 Sep 2005, Valone, Toren W. wrote:

> I am trying to noodle thru classes with python and I built the following
> class.

Hi Toren,

Ah.  Check your indentation: it appears that the definition of getday() is
within the body of the class initializer __init__().

What ends up happening is that getday() is no longer a method definition,
but an inner function definition.  Python makes it very easy to define
functions within functions, and what you have in effect is a function
definition within the __init__() method definition, which is probably not
what you want.

Tip: if possible, always use four spaces for your indentation to make this
error easier to see.  Don't skimp on this.  *grin*


Also note that Python's class system does not make using 'self' optional,
so when you're initializing the attributes of an instance in __init__:

    def __init__(self):
        remailfile = open('U:\Bounce20.txt', 'r')
        resendfile = open('resend.txt', 'w')
        EmailReport = open('erprt.txt', 'w')
        ...

you need to tell Python not to treat these as local variables assignments.

    def __init__(self):
        self.remailfile = open('U:\Bounce20.txt', 'r')
        self.resendfile = open('resend.txt', 'w')
        self.EmailReport = open('erprt.txt', 'w')
        ...


As a side note: escape the backslashes in your literal strings: otherwise,
you'll run into issues.  I'm assuming you're coming from a Java or C++
background, but if you need this point elaborated, please ask, and we'll
go into more detail.



If you have more questions, please feel free to ask.  Good luck!


From kim.d at tesco.net  Sat Sep 24 00:51:19 2005
From: kim.d at tesco.net (kim.d@tesco.net)
Date: Fri, 23 Sep 2005 22:51:19 +0000
Subject: [Tutor] Diamond Equivalent
Message-ID: <20050923225121.CGCS5796.aamta03-winn.mailhost.ntl.com@smtp.tesco.net>

Bob, Michael, my thanks to you both for answering my diamond operator 
question.

Bob, I tried the lines you suggested and they worked just the way I wanted 
them to. Thanks.

Michael, thanks for the user functions or subroutines: not sure what Python 
calls them. A lot of food for thought there. Much appreciated.


From falcon3166 at hotmail.com  Sat Sep 24 01:03:17 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 23 Sep 2005 17:03:17 -0600
Subject: [Tutor] Help with pi and the math module.
Message-ID: <BAY106-DAV2281819E5B74563EB28437C4960@phx.gbl>

Hi all,

I need help with pi and the math module. I had import math at the top of a program, but when it came to diameter*pi, it said that pi was not defined.

How do I use it correctly?

Thanks,
Nathan Pinno
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050923/e2fb84ff/attachment.htm

From dyoo at hkn.eecs.berkeley.edu  Sat Sep 24 01:21:50 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 23 Sep 2005 16:21:50 -0700 (PDT)
Subject: [Tutor] Help with pi and the math module.
In-Reply-To: <BAY106-DAV2281819E5B74563EB28437C4960@phx.gbl>
Message-ID: <Pine.LNX.4.44.0509231613070.7040-100000@hkn.eecs.berkeley.edu>



On Fri, 23 Sep 2005, Nathan Pinno wrote:

> I need help with pi and the math module. I had import math at the top of
> a program, but when it came to diameter*pi, it said that pi was not
> defined.


Hi Nathan,


Python's module import will not automatically pull all the names in a
module and dump them into our world: they'll be held within the module,
accessible but still boxed up.


Let's take another example, like the 'random' module:

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


If we're doing something like:

######
>>> import random
######

then to access the random() function that lives in the random module, we
say:

######
>>> random.random()
0.64082684341957585
######


If we just say 'random', we're talking about the random module, not the
random function:

######
>>> random
<module 'random' from '/usr/lib/python2.3/random.pyc'>
######

which itself does have a few things in its internals:

######
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'Random', 'SG_MAGICCONST', 'TWOPI',
'WichmannHill', '_BuiltinMethodType', '__all__', '__builtins__',
'__doc__', '__file__', '__name__', '_acos', '_cos', '_e', '_exp',
'_floor', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test',
'_test_generator', 'betavariate', 'choice', 'cunifvariate', 'expovariate',
'gammavariate', 'gauss', 'getstate', 'jumpahead', 'lognormvariate',
'normalvariate', 'paretovariate', 'randint', 'random', 'randrange',
'sample', 'seed', 'setstate', 'shuffle', 'stdgamma', 'uniform',
'vonmisesvariate', 'weibullvariate']
######


Does this clarify things for you?


For more information on this, see a tutorial like Alan Gauld's "How to
Program":

    http://www.freenetpages.co.uk/hp/alan.gauld/tutfunc.htm

or any of the other tutorials in:

    http://wiki.python.org/moin/BeginnersGuide/NonProgrammers


From negroup at gmail.com  Sat Sep 24 02:17:58 2005
From: negroup at gmail.com (Negroup -)
Date: Sat, 24 Sep 2005 02:17:58 +0200
Subject: [Tutor] Pattern to handle exceptions
Message-ID: <2fdabf190509231717494aeb6f@mail.gmail.com>

Hi all, I have a question about the following lines of code:

>>> class Foo:
...     bar = 'bar'
...
>>> # is it better this
>>> def te(attribute):
...     try:
...             print getattr(c, attribute)
...     except AttributeError:
...             return None
>>> #
>>> # or this?
>>> def h_a(attribute):
...     if hasattr(c, attribute):
...             return getattr(c, attribute)
...     else:
...             return None
...

Generally, to handle potentially erroneus situations, which pattern is
most correct to use?

TIA

From cpu.crazy at gmail.com  Sat Sep 24 04:01:55 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Fri, 23 Sep 2005 20:01:55 -0600
Subject: [Tutor] Binary 2 text & text 2 binary
Message-ID: <4334B393.6010005@gmail.com>

Hi I'm playing with a Binary to text & text to binary converter. I can't 
figure out how to replace the characters (first stage: text to binary).

I thought lists would be the best but I really don't know how to use 
them... here's my code:
#! /usr/bin/env python
A = "01000001"
B = "01000010"
C = "01000011"
D = "01000100"
E = "01000101"
F = "01000110"
G = "01000111"
H = "01001000"
I = "01001001"
J = "01001010"
K = "01001011"
L = "01001100"
M = "01001101"
N = "01001110"
O = "01001111"
P = "01010000"
Q = "01010001"
R = "01010010"
S = "01010011"
T = "01010100"
U = "01010101"
V = "01010110"
W = "01010111"
X = "01011000"
Y = "01011001"
Z = "01011010"

# Symbols
exclamationPoint = "0010 0001"
hash = "0010 0011"
dollar = "001 0100"
percent = "0010 0101"
_and = "0010 0110"
parentheses = "0010 1000"
closeParentheses = "0010 1001"
comma = "0010 1100"
dash = "0010 1101"
period = "0010 1110"
underline = "0101 1111"

# Numbers
zero = "00110000"
one = "00110001"
two = "00110010"
three = "00110011"
four = "00110100"
five = "00110101"
six = "00110110"
seven = "00110111"
eight = "00111000"
nine = "00111001"

ltra = "a"
ltrb = "b"
ltrc = "c"
while True:
    text = raw_input("Enter text: ")
    text = list(text)

Thanks,
    Joe


From amonroe at columbus.rr.com  Sat Sep 24 05:08:41 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Fri, 23 Sep 2005 23:08:41 -0400
Subject: [Tutor] Binary 2 text & text 2 binary
In-Reply-To: <4334B393.6010005@gmail.com>
References: <4334B393.6010005@gmail.com>
Message-ID: <135544991766.20050923230841@columbus.rr.com>


> I thought lists would be the best but I really don't know how to use
> them

They're easy. Just put stuff in square brackets with commas between.

mycoollist = [1,5,9,3,6,9,2,6]
mystringlist = ['a', 'u', 'e', 'b', 'd', 'h', 'q', 't']

Can you predict what this code will do?

print mycoollist[0]



Alan


From kent37 at tds.net  Sat Sep 24 05:20:21 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 23 Sep 2005 23:20:21 -0400
Subject: [Tutor] Pattern to handle exceptions
In-Reply-To: <2fdabf190509231717494aeb6f@mail.gmail.com>
References: <2fdabf190509231717494aeb6f@mail.gmail.com>
Message-ID: <4334C5F5.4050906@tds.net>

Negroup - wrote:
> Hi all, I have a question about the following lines of code:
> 
> 
>>>>class Foo:
> 
> ...     bar = 'bar'
> ...
> 
>>>># is it better this
>>>>def te(attribute):
> 
> ...     try:
> ...             print getattr(c, attribute)
> ...     except AttributeError:
> ...             return None
> 
>>>>#
>>>># or this?
>>>>def h_a(attribute):
> 
> ...     if hasattr(c, attribute):
> ...             return getattr(c, attribute)
> ...     else:
> ...             return None
> ...
> 
> Generally, to handle potentially erroneus situations, which pattern is
> most correct to use?

In the Python world, the first style is known as Easier to Ask Forgiveness than Permission (EAFP), the second style is Look Before You Leap (LBYL). In general EAFP is preferred - the idea is, if you want to know whether an object can do what you want, you just try it and if it doesn't work then clean up. It's not always that simple, for example if you want to do several operations and it would be messy to clean up if the last one failed, you may use LBYL. But the preference is for EAFP.

In this particular case, I would use the default argument form of getattr() and write it as
def da(attribute):
  return getattr(c, attribute, None)

Kent


From ml.cyresse at gmail.com  Sat Sep 24 08:50:26 2005
From: ml.cyresse at gmail.com (mailing list)
Date: Sat, 24 Sep 2005 18:50:26 +1200
Subject: [Tutor] Using new style classes and __slots__
Message-ID: <b6f3249e050923235059c73b@mail.gmail.com>

Hi all,

I'm just looking for a quick runthrough on the differences between new
style classes and the old ones, and how to use the new ones.

Also, how exactly do you use __slots__? I've got a 6000 object
collection, and apparently using __slots__ will save memory, but only
those attributes specified in __slots__ can be set, which suits my
project fine.

Is anyone able to point me in the right direction?

Much thanks,

Liam Clarke

From shitizb at yahoo.com  Sat Sep 24 10:11:58 2005
From: shitizb at yahoo.com (Shitiz Bansal)
Date: Sat, 24 Sep 2005 01:11:58 -0700 (PDT)
Subject: [Tutor] File mode r+
Message-ID: <20050924081159.16202.qmail@web53810.mail.yahoo.com>

Hi,
I want to update a textfile using the r+ file mode.
contents of file:

abcd
efgh
ijkl
mnop
qrst
uvwx
yx12

my scripts is:

file1=open("aa.txt",'r+')
file1.readline()
file1.readline()
file1.write("1234\n")
file1.close()

This should replace the third line with 1234.
However it does nothing.

Moreover the script:

file1=open("aa.txt",'r+')
file1.write("1234\n")
file1.close()

does replace the first line with 1234.

could anyone explain what is happening?

shitiz

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

From ajikoe at gmail.com  Sat Sep 24 10:42:13 2005
From: ajikoe at gmail.com (Pujo Aji)
Date: Sat, 24 Sep 2005 10:42:13 +0200
Subject: [Tutor] Binary 2 text & text 2 binary
In-Reply-To: <4334B393.6010005@gmail.com>
References: <4334B393.6010005@gmail.com>
Message-ID: <cf5262d205092401421589dfa6@mail.gmail.com>

If your symbol are specific it is better to use dictionary.
then if the user give an input you can take character by character and
translate into your binary.
This is the code textTobinary:
 mydic = {'A' : "01000001", 'B' : "01000010", 'C' : "01000011"}
strinput = 'ABBC'
result = [mydic[x] for x in strinput_process]
print result
 Cheers,
pujo

 On 9/24/05, Joseph Quigley <cpu.crazy at gmail.com> wrote:
>
> Hi I'm playing with a Binary to text & text to binary converter. I can't
> figure out how to replace the characters (first stage: text to binary).
>
> I thought lists would be the best but I really don't know how to use
> them... here's my code:
> #! /usr/bin/env python
> A = "01000001"
> B = "01000010"
> C = "01000011"
> D = "01000100"
> E = "01000101"
> F = "01000110"
> G = "01000111"
> H = "01001000"
> I = "01001001"
> J = "01001010"
> K = "01001011"
> L = "01001100"
> M = "01001101"
> N = "01001110"
> O = "01001111"
> P = "01010000"
> Q = "01010001"
> R = "01010010"
> S = "01010011"
> T = "01010100"
> U = "01010101"
> V = "01010110"
> W = "01010111"
> X = "01011000"
> Y = "01011001"
> Z = "01011010"
>
> # Symbols
> exclamationPoint = "0010 0001"
> hash = "0010 0011"
> dollar = "001 0100"
> percent = "0010 0101"
> _and = "0010 0110"
> parentheses = "0010 1000"
> closeParentheses = "0010 1001"
> comma = "0010 1100"
> dash = "0010 1101"
> period = "0010 1110"
> underline = "0101 1111"
>
> # Numbers
> zero = "00110000"
> one = "00110001"
> two = "00110010"
> three = "00110011"
> four = "00110100"
> five = "00110101"
> six = "00110110"
> seven = "00110111"
> eight = "00111000"
> nine = "00111001"
>
> ltra = "a"
> ltrb = "b"
> ltrc = "c"
> while True:
> text = raw_input("Enter text: ")
> text = list(text)
>
> Thanks,
> Joe
>
> _______________________________________________
> 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/20050924/2a0e5a51/attachment-0001.html

From ajikoe at gmail.com  Sat Sep 24 10:48:23 2005
From: ajikoe at gmail.com (Pujo Aji)
Date: Sat, 24 Sep 2005 10:48:23 +0200
Subject: [Tutor] Help with pi and the math module.
In-Reply-To: <BAY106-DAV2281819E5B74563EB28437C4960@phx.gbl>
References: <BAY106-DAV2281819E5B74563EB28437C4960@phx.gbl>
Message-ID: <cf5262d2050924014833aed68f@mail.gmail.com>

hi,
 if you use : import math
you can type: diameter * math.pi
 if you use from math import *
you can type: diameter * pi
 Cheers,
pujo

 On 9/24/05, Nathan Pinno <falcon3166 at hotmail.com> wrote:
>
> Hi all,
>  I need help with pi and the math module. I had import math at the top of
> a program, but when it came to diameter*pi, it said that pi was not defined.
>  How do I use it correctly?
>  Thanks,
> Nathan Pinno
>
> _______________________________________________
> 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/20050924/a788583b/attachment.htm

From tutor.python.org at pooryorick.com  Sat Sep 24 14:15:10 2005
From: tutor.python.org at pooryorick.com (Poor Yorick)
Date: Sat, 24 Sep 2005 08:15:10 -0400
Subject: [Tutor] Binary 2 text & text 2 binary
In-Reply-To: <cf5262d205092401421589dfa6@mail.gmail.com>
References: <4334B393.6010005@gmail.com>
	<cf5262d205092401421589dfa6@mail.gmail.com>
Message-ID: <4335434E.3040907@pooryorick.com>

Pujo Aji wrote:
> If your symbol are specific it is better to use dictionary.
> then if the user give an input you can take character by character and 
> translate into your binary.
> This is the code textTobinary:
>     mydic = {'A' : "01000001", 'B' : "01000010", 'C' : "01000011"}
>     strinput = 'ABBC'
>     result = [mydic[x] for x in strinput_process]
>     print result
>  

You might also want to look at "Number to String in Arbirtrary Base" recipe:

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

It uses a more innovative approach.

--
Poor Yorick


From kent37 at tds.net  Sat Sep 24 15:18:03 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 24 Sep 2005 09:18:03 -0400
Subject: [Tutor] Using new style classes and __slots__
In-Reply-To: <b6f3249e050923235059c73b@mail.gmail.com>
References: <b6f3249e050923235059c73b@mail.gmail.com>
Message-ID: <4335520B.4000009@tds.net>

mailing list wrote:
> Hi all,
> 
> I'm just looking for a quick runthrough on the differences between new
> style classes and the old ones, and how to use the new ones.
> 
> Also, how exactly do you use __slots__? I've got a 6000 object
> collection, and apparently using __slots__ will save memory, but only
> those attributes specified in __slots__ can be set, which suits my
> project fine.

All you have to do is define a __slots__ variable in your class. Its value is a list of attribute names. Then instances of your class will only be able to have the attributes named in __slots__:

 >>> class foo(object):
 ...   __slots__ = ['x', 'y']
 ...
 >>> f=foo()
 >>> f.x=1
 >>> f.y=2
 >>> f.z=3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'foo' object has no attribute 'z'

Take a look at
http://www.python.org/2.2.3/descrintro.html (search for __slots__)

Note to the list: Use of __slots__ is generally discouraged, but IIUC this is exactly the use case it was designed for so I think it is OK.

Kent


From ml.cyresse at gmail.com  Sat Sep 24 15:49:20 2005
From: ml.cyresse at gmail.com (mailing list)
Date: Sun, 25 Sep 2005 01:49:20 +1200
Subject: [Tutor] Using new style classes and __slots__
In-Reply-To: <4335520B.4000009@tds.net>
References: <b6f3249e050923235059c73b@mail.gmail.com>
	<4335520B.4000009@tds.net>
Message-ID: <b6f3249e05092406492c2ba0e9@mail.gmail.com>

Hi Kent,

>

>  >>> class foo(object):
>  ...   __slots__ = ['x', 'y']
>  ...
>  >>> f=foo()
>  >>> f.x=1
>  >>> f.y=2
>  >>> f.z=3
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: 'foo' object has no attribute 'z'
>
> Take a look at
> http://www.python.org/2.2.3/descrintro.html (search for __slots__)

Thanks for that. I was tearing my hair out trying to figure out why
despite the usage of __slots__ my instances still had a __dict__, and
then I saw the subclass of object, and sure enough... I'm guessing
that's how you get new style classes.

Quite like what I'm seeing, __slots__ and that property() thing will
allow me to remove all my __setattr__ and __getattr__ methods, which
tend to make things crawl a wee bit.

I was almost considering writing setters/getters to get around the
magic methods, but I grew to dislike them after having used Java, I
got annoyed at having to write setters/getters for every public
variable. Of course, I was using Notepad to write the Java programmes,
and then Eclipse helped me  realise why Java programmers value IDE's
so much, it's that automatic generation of set/gets...

> Note to the list: Use of __slots__ is generally discouraged, but IIUC this is exactly the >use case it was designed for so I think it is OK.

Throwing an error on adding a new attribute is just what I need as the
data I'm reading/writing has a very specific format; instead of using
__setattr__ and checking that the attribute already existed, I can
just let __slots__ do the work.

Out of curiosity, if you're using __slots__ with new style, you no
longer have __dict__. So, where does it stick data?

I was using 'self.__dict__["_created"] = False' to set a flag at the
start of __init__ to stop __setattr__ picking up the attributes being
set from parsed data (and running all my type checks, etc.),  but I
won't need that anymore. I could almost hug property(). :)

All in all, this has been an interesting tour around the inner
workings of a class in Python.
Give it another five years, I might be able to read one of those
metaclass explanations and understand it.


Regards,

Liam Clarke

PS Just for my edification, is there a builtin to determine how much
memory is allocated to an object?

From kent37 at tds.net  Sat Sep 24 16:20:42 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 24 Sep 2005 10:20:42 -0400
Subject: [Tutor] Using new style classes and __slots__
In-Reply-To: <b6f3249e05092406492c2ba0e9@mail.gmail.com>
References: <b6f3249e050923235059c73b@mail.gmail.com>	<4335520B.4000009@tds.net>
	<b6f3249e05092406492c2ba0e9@mail.gmail.com>
Message-ID: <433560BA.1060506@tds.net>

mailing list wrote:
> Hi Kent,
> 
> 
> 
>> >>> class foo(object):
>> ...   __slots__ = ['x', 'y']
>> ...
>> >>> f=foo()
>> >>> f.x=1
>> >>> f.y=2
>> >>> f.z=3
>>Traceback (most recent call last):
>>  File "<stdin>", line 1, in ?
>>AttributeError: 'foo' object has no attribute 'z'
>>
>>Take a look at
>>http://www.python.org/2.2.3/descrintro.html (search for __slots__)
> 
> 
> Thanks for that. I was tearing my hair out trying to figure out why
> despite the usage of __slots__ my instances still had a __dict__, and
> then I saw the subclass of object, and sure enough... I'm guessing
> that's how you get new style classes.

Yes, exactly. To be precise: A class is a new-style class if its metaclass is type 'type' or inherits from type. If you inherit from a new-style class, your class will have the same metaclass as the base class and thus be a new-style class. The simplest way to do this is to inherit from object.
 
> Quite like what I'm seeing, __slots__ and that property() thing will
> allow me to remove all my __setattr__ and __getattr__ methods, which
> tend to make things crawl a wee bit.

That's exactly what property() is for.
 
> I was almost considering writing setters/getters to get around the
> magic methods, but I grew to dislike them after having used Java, I
> got annoyed at having to write setters/getters for every public
> variable. Of course, I was using Notepad to write the Java programmes,
> and then Eclipse helped me  realise why Java programmers value IDE's
> so much, it's that automatic generation of set/gets...

One of the cool things about properties is that you can start with simple attributes and change them later to have behaviour without having to change the client code or use getters and setters all the time.
 
> Out of curiosity, if you're using __slots__ with new style, you no
> longer have __dict__. So, where does it stick data?

My understanding is that there are actually 'slots' allocated in the object to hold the references to the attribute data, kind of like a C struct. I'm not sure about this though.
 
> I was using 'self.__dict__["_created"] = False' to set a flag at the
> start of __init__ to stop __setattr__ picking up the attributes being
> set from parsed data (and running all my type checks, etc.),  but I
> won't need that anymore. I could almost hug property(). :)

You might want to learn more about the whole property mechanism then. property() is actually a bit of sugar over a deeper mechanism. Also there is an interesting idiom for creating properties using @apply (in Python 2.4) - look for Benji York's comment in this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698

> 
> All in all, this has been an interesting tour around the inner
> workings of a class in Python.
> Give it another five years, I might be able to read one of those
> metaclass explanations and understand it.

Me too!

Kent
> 
> 
> Regards,
> 
> Liam Clarke
> 
> PS Just for my edification, is there a builtin to determine how much
> memory is allocated to an object?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From luke.jordan at gmail.com  Sat Sep 24 17:11:34 2005
From: luke.jordan at gmail.com (Luke Jordan)
Date: Sat, 24 Sep 2005 10:11:34 -0500
Subject: [Tutor] Sum of List Elements
Message-ID: <ea0feb8005092408115367d273@mail.gmail.com>

Hi All,

I have spent an embarrassingly large amount of time trying to solve what on
its face seems like a simple problem.

I have a list of intergers, and I want to assign the sum of the intergers in
the list to a variable. There are only intergers in the list.

The best I have been able to do so far is to write a function that adds
list[0] and list[1], then list[1] and list [2], etc. Of course, this isn't
what I want.

I'd like to be able to sum a list of any size without having to type
list[0]+list[1]....

I am totally stumped.

:(

Luke

--
"Whether you're an honest man, or whether you're a thief, depends on whose
solicitor has given me my brief. " - Benjamin Franklin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050924/8e7f29ce/attachment.htm

From amonroe at columbus.rr.com  Sat Sep 24 17:16:00 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sat, 24 Sep 2005 11:16:00 -0400
Subject: [Tutor] Sum of List Elements
In-Reply-To: <ea0feb8005092408115367d273@mail.gmail.com>
References: <ea0feb8005092408115367d273@mail.gmail.com>
Message-ID: <147588630656.20050924111600@columbus.rr.com>

> Hi All,

> I have spent an embarrassingly large amount of time trying to solve what on
> its face seems like a simple problem.

> I have a list of intergers, and I want to assign the sum of the intergers in
> the list to a variable. There are only intergers in the list.

> The best I have been able to do so far is to write a function that adds
> list[0] and list[1], then list[1] and list [2], etc. Of course, this isn't
> what I want.

> I'd like to be able to sum a list of any size without having to type
> list[0]+list[1]....

total=0
for x in list:
    total += x


From cpu.crazy at gmail.com  Sat Sep 24 17:28:34 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Sat, 24 Sep 2005 09:28:34 -0600
Subject: [Tutor] Binary 2 text & text 2 binary
In-Reply-To: <mailman.2438.1127551335.508.tutor@python.org>
References: <mailman.2438.1127551335.508.tutor@python.org>
Message-ID: <433570A2.2040004@gmail.com>

Hi,

>From: "R. Alan Monroe" <amonroe at columbus.rr.com>
>
>They're easy. Just put stuff in square brackets with commas between.
>
>mycoollist = [1,5,9,3,6,9,2,6]
>mystringlist = ['a', 'u', 'e', 'b', 'd', 'h', 'q', 't']
>  
>
Ah sorry I forgot to say: I know how to print them but that's about it.

>Can you predict what this code will do?
>print mycoollist[0]
>  
>
yes. It will print (edited) [1, 2, 3 ,4 ........]
I'll rephrase myself again: I'd like to know where I can find tutorials
for slicing or some help from any of you. However keep on reading and I
think I'll have my answer :-)

>Message: 11
>Date: Sat, 24 Sep 2005 10:42:13 +0200
>From: Pujo Aji <ajikoe at gmail.com>
>
>If your symbol are specific it is better to use dictionary.
>  
>
Good Idea! Thanks....

>then if the user give an input you can take character by character and
>translate into your binary.
>This is the code textTobinary:
> mydic = {'A' : "01000001", 'B' : "01000010", 'C' : "01000011"}
>strinput = 'ABBC'
>result = [mydic[x] for x in strinput_process]
>print result
>
>  
>
This helps a lot, thank you!



From wkranec at gmail.com  Sat Sep 24 17:45:38 2005
From: wkranec at gmail.com (wkranec@gmail.com)
Date: Sat, 24 Sep 2005 11:45:38 -0400
Subject: [Tutor] Sum of List Elements
In-Reply-To: <147588630656.20050924111600@columbus.rr.com>
References: <ea0feb8005092408115367d273@mail.gmail.com>
	<147588630656.20050924111600@columbus.rr.com>
Message-ID: <32b77d5a0509240845586f3df2@mail.gmail.com>

how about sum()?

>>> sum(range(30))
435

-Bill

From grouch at gmail.com  Sat Sep 24 17:52:52 2005
From: grouch at gmail.com (grouchy)
Date: Sat, 24 Sep 2005 10:52:52 -0500
Subject: [Tutor] Sum of List Elements
In-Reply-To: <147588630656.20050924111600@columbus.rr.com>
References: <ea0feb8005092408115367d273@mail.gmail.com>
	<147588630656.20050924111600@columbus.rr.com>
Message-ID: <e6443aa70509240852615e4b71@mail.gmail.com>

Also, the built in function sum():

total = sum(list)

Which is probably the One Obvious Way since 2.3, if I had to guess.

On 9/24/05, R. Alan Monroe < amonroe at columbus.rr.com> wrote:
>
> > Hi All,
>
> > I have spent an embarrassingly large amount of time trying to solve what
> on
> > its face seems like a simple problem.
>
> > I have a list of intergers, and I want to assign the sum of the
> intergers in
> > the list to a variable. There are only intergers in the list.
>
> > The best I have been able to do so far is to write a function that adds
> > list[0] and list[1], then list[1] and list [2], etc. Of course, this
> isn't
> > what I want.
>
> > I'd like to be able to sum a list of any size without having to type
> > list[0]+list[1]....
>
> total=0
> for x in list:
> total += x
>
> _______________________________________________
> 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/20050924/44482405/attachment-0001.html

From bgailer at alum.rpi.edu  Sat Sep 24 18:03:59 2005
From: bgailer at alum.rpi.edu (bob)
Date: Sat, 24 Sep 2005 09:03:59 -0700
Subject: [Tutor] File mode r+
In-Reply-To: <20050924081159.16202.qmail@web53810.mail.yahoo.com>
References: <20050924081159.16202.qmail@web53810.mail.yahoo.com>
Message-ID: <6.1.2.0.0.20050924090231.0290e3d8@mail.mric.net>

At 01:11 AM 9/24/2005, Shitiz Bansal wrote:
>Hi,
>I want to update a textfile using the r+ file mode.
>contents of file:
>
>abcd
>efgh
>ijkl
>mnop
>qrst
>uvwx
>yx12
>
>my scripts is:
>
>file1=open("aa.txt",'r+')

Instead of readline, use skip to position the file to where you want to 
overwrite it.
file1.seek(10)

>file1.readline()
>file1.readline()
>file1.write("1234\n")
>file1.close()
>
>This should replace the third line with 1234.
>However it does nothing.
>
>Moreover the script:
>
>file1=open("aa.txt",'r+')
>file1.write("1234\n")
>file1.close()
>
>does replace the first line with 1234.
>
>could anyone explain what is happening?
>
>shitiz
>
>__________________________________________________
>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 grouch at gmail.com  Sat Sep 24 18:09:36 2005
From: grouch at gmail.com (grouchy)
Date: Sat, 24 Sep 2005 11:09:36 -0500
Subject: [Tutor] Stupid newbie question
In-Reply-To: <5AE0A72A4C0AD711806A000255FC47DB09CC1911@dmv-ent-ex07.dmv.ca.gov>
References: <5AE0A72A4C0AD711806A000255FC47DB09CC1911@dmv-ent-ex07.dmv.ca.gov>
Message-ID: <e6443aa705092409096e88083e@mail.gmail.com>

As long as you are using IDLE, why not let it handle indentation for you?
This could very well be a dumb question, and if it is, well, excuse me :)

On 9/23/05, Valone, Toren W. <TValone at dmv.ca.gov> wrote:
>
> I am trying to noodle thru classes with python and I built the following
> class
>
> import time
>
> class startremail:
> def __init__(self):
> remailfile = open('U:\Bounce20.txt', 'r') #future
> address/file from outlook
> resendfile = open('resend.txt', 'w') #currently these
> files are in Python24
> EmailReport = open('erprt.txt', 'w') #Report of bad
> emails etc
> fromaddr='Tvalone at dmv.ca.gov' #set fromadd to a
> constant
> null_recepient_count = 0
> date_received = ""
> date_email_generated = ""
> Error_050 = ""
> Error_501 = ""
> Current_Date = time.ctime(time.time())
> month = Current_Date[4:8]
> day = Current_Date[8:10]
> print month
>
> def getday(self):
> return self.day
>
> def Read(self,line):
> line = remailfile.readline() #primer read
> return line
>
>
> I fire up IDLE and then do this
>
> from startremail import *
> x = startremail()
> print x.getday()
> I get the following return
>
> NameError: name 'getday' is not defined
>
>
> _______________________________________________
> 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/20050924/22e24983/attachment.html

From bgailer at alum.rpi.edu  Sat Sep 24 18:31:12 2005
From: bgailer at alum.rpi.edu (bob)
Date: Sat, 24 Sep 2005 09:31:12 -0700
Subject: [Tutor] Sum of List Elements
In-Reply-To: <ea0feb8005092408115367d273@mail.gmail.com>
References: <ea0feb8005092408115367d273@mail.gmail.com>
Message-ID: <6.1.2.0.0.20050924090635.032a0f80@mail.mric.net>

At 08:11 AM 9/24/2005, Luke Jordan wrote:
>Hi All,
>
>I have spent an embarrassingly large amount of time trying to solve what 
>on its face seems like a simple problem.
>
>I have a list of intergers, and I want to assign the sum of the intergers 
>in the list to a variable. There are only intergers in the list.

In addition to the other solutions there is the (more generic?) use of the 
operator module and reduce function:

import operator
reduce(operator.add, (1,2,3))

Explore operator to see what other functions you can use.

Also there are the array handling modules such as numarray.

You can also define your own classes based on list and write methods to do 
these operations. 


From luke.jordan at gmail.com  Sat Sep 24 19:25:07 2005
From: luke.jordan at gmail.com (Luke Jordan)
Date: Sat, 24 Sep 2005 12:25:07 -0500
Subject: [Tutor] Sum of List Elements
In-Reply-To: <6.1.2.0.0.20050924090635.032a0f80@mail.mric.net>
References: <ea0feb8005092408115367d273@mail.gmail.com>
	<6.1.2.0.0.20050924090635.032a0f80@mail.mric.net>
Message-ID: <ea0feb8005092410257a95ecf4@mail.gmail.com>

Thanks for the help everyone, for answering a simple question and pointing
me toward more resources.

On 9/24/05, bob <bgailer at alum.rpi.edu> wrote:
>
> At 08:11 AM 9/24/2005, Luke Jordan wrote:
> >Hi All,
> >
> >I have spent an embarrassingly large amount of time trying to solve what
> >on its face seems like a simple problem.
> >
> >I have a list of intergers, and I want to assign the sum of the intergers
> >in the list to a variable. There are only intergers in the list.
>
> In addition to the other solutions there is the (more generic?) use of the
> operator module and reduce function:
>
> import operator
> reduce(operator.add, (1,2,3))
>
> Explore operator to see what other functions you can use.
>
> Also there are the array handling modules such as numarray.
>
> You can also define your own classes based on list and write methods to do
> these operations.
>
>


--
"Whether you're an honest man, or whether you're a thief, depends on whose
solicitor has given me my brief. " - Benjamin Franklin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050924/67e2c045/attachment.htm

From shitizb at yahoo.com  Sat Sep 24 22:44:31 2005
From: shitizb at yahoo.com (Shitiz Bansal)
Date: Sat, 24 Sep 2005 13:44:31 -0700 (PDT)
Subject: [Tutor] File mode r+
In-Reply-To: <6.1.2.0.0.20050924090231.0290e3d8@mail.mric.net>
Message-ID: <20050924204432.50375.qmail@web53806.mail.yahoo.com>


Hi,

How do i proceed if i am not sure about the number of characters in the fist two lines and want to write in the third line.is there a way to skip two lines and write on the third??

Also could anyone explain why the readline() did not work. according to what i understand it should.

 

shitiz


bob <bgailer at alum.rpi.edu> wrote:
At 01:11 AM 9/24/2005, Shitiz Bansal wrote:
>Hi,
>I want to update a textfile using the r+ file mode.
>contents of file:
>
>abcd
>efgh
>ijkl
>mnop
>qrst
>uvwx
>yx12
>
>my scripts is:
>
>file1=open("aa.txt",'r+')

>>Instead of readline, use skip to position the file to where you want to 
>>overwrite it.
>>file1.seek(10)


>file1.readline()
>file1.readline()
>file1.write("1234\n")
>file1.close()
>
>This should replace the third line with 1234.
>However it does nothing.
>
>Moreover the script:
>
>file1=open("aa.txt",'r+')
>file1.write("1234\n")
>file1.close()
>
>does replace the first line with 1234.
>
>could anyone explain what is happening?
>
>shitiz
>
>__________________________________________________
>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




		
---------------------------------
Yahoo! for Good
 Click here to donate to the Hurricane Katrina relief effort. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050924/3eb488e5/attachment.html

From ml.cyresse at gmail.com  Sat Sep 24 23:37:08 2005
From: ml.cyresse at gmail.com (Liam Clarke)
Date: Sun, 25 Sep 2005 09:37:08 +1200
Subject: [Tutor] Using new style classes and __slots__
In-Reply-To: <433560BA.1060506@tds.net>
References: <b6f3249e050923235059c73b@mail.gmail.com>
	<4335520B.4000009@tds.net> <b6f3249e05092406492c2ba0e9@mail.gmail.com>
	<433560BA.1060506@tds.net>
Message-ID: <b6f3249e05092414377a830052@mail.gmail.com>

Hi,


> You might want to learn more about the whole property mechanism then. property() is actually a bit of sugar over a deeper mechanism. Also there is an interesting idiom for creating properties using @apply (in Python 2.4) - look for Benji York's comment in this recipe:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698

Thanks Kent. Just looking at that above recipe, I'm not too sure how
the @ decorators work.
>From what I understand, it defines would turn apply() into a function
that returns the various get/sets?

Also found something interesting with property(), if it's called in
__init__ you get
>>> a.a
<property object at 0x011598C8>

whereas called outside __init__ it works normally.

This is a hassle for me because I'm a lazy typist, so I've been using
setattr() to pull attribute names out of a list. And the first
argument setattr() requires is an object, and self doesn't work
outside of a method, and using the class name leads to no attribute
being set.

Hmm, may have to learn even more about classes and their internals.

Regards,

Liam Clarke

From Goofball223 at wmconnect.com  Sun Sep 25 00:29:43 2005
From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com)
Date: Sat, 24 Sep 2005 18:29:43 EDT
Subject: [Tutor] (no subject)
Message-ID: <e0.1c8525c9.30672d57@wmconnect.com>

Hello

How would I get the following program to accept inputs of exam scores from 
0-100 with A being 100-90, B being 89-80, C being 79-70, D being 69-60, and F 
being everything less than 60?

import string

def main():


    scores = ["F", "D", "C", "B", "A"]
    g = input("Enter a score number (0-100): ")

    print "The score of your exam is", scores [g-0] + "."


main()   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050924/2a0ac1b6/attachment-0001.htm

From andrade1 at umbc.edu  Sun Sep 25 01:00:14 2005
From: andrade1 at umbc.edu (andrade1@umbc.edu)
Date: Sat, 24 Sep 2005 19:00:14 -0400 (EDT)
Subject: [Tutor] printing an acronym
Message-ID: <1936.172.170.62.199.1127602814.squirrel@172.170.62.199>

Hello

How could I get the following to print out an acronym for each phrase
entered such as if I entered random access memory it word print out RAM?

import string

def main():


    phrase = (raw_input("Please enter a phrase:"))

    acr1 = string.split(phrase)


    acr2 = string.capwords(phrase)


    acr3 = acr2[0]

    print"",acr3

main()


From amonroe at columbus.rr.com  Sun Sep 25 01:51:52 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sat, 24 Sep 2005 19:51:52 -0400
Subject: [Tutor] printing an acronym
In-Reply-To: <1936.172.170.62.199.1127602814.squirrel@172.170.62.199>
References: <1936.172.170.62.199.1127602814.squirrel@172.170.62.199>
Message-ID: <52619583013.20050924195152@columbus.rr.com>

> Hello

> How could I get the following to print out an acronym for each phrase
> entered such as if I entered random access memory it word print out RAM?

> import string

> def main():


>     phrase = (raw_input("Please enter a phrase:"))

>     acr1 = string.split(phrase)


>     acr2 = string.capwords(phrase)


>     acr3 = acr2[0]

>     print"",acr3

> main()

What does it currently print?

The typical way would be to use a for loop on acr1.

Alan


From bgailer at alum.rpi.edu  Sun Sep 25 03:30:15 2005
From: bgailer at alum.rpi.edu (bob)
Date: Sat, 24 Sep 2005 18:30:15 -0700
Subject: [Tutor] (no subject)
In-Reply-To: <e0.1c8525c9.30672d57@wmconnect.com>
References: <e0.1c8525c9.30672d57@wmconnect.com>
Message-ID: <6.1.2.0.0.20050924181400.03530100@mail.mric.net>

At 03:29 PM 9/24/2005, Goofball223 at wmconnect.com wrote:
>Hello
>
>How would I get the following program to accept inputs of exam scores from 
>0-100 with A being 100-90, B being 89-80, C being 79-70, D being 69-60, 
>and F being everything less than 60?

Many solutions are available. One could use an if statement:

if g >= 90: s = 'A'
elif g >= 80: s = 'B'
...
else: g = 'F'

although that can be hard to maintain.

Or associate the lower limit with the data and search using a loop:

scores = [("A",90), ("B",80), ("C".70), ("D",60),("F",0) ]
for letter, number in scores:
     if g >= number:break
print "The score of your exam is", letter

This separates the data from the program structure and becomes much easier 
to maintain / extend, apply to new situation.

If you are using a database then you could store these value pairs in a 
table and use SQL to retrieve the desired letter.

When the number ranges have a nice progression, you can reduce the number 
to an index:

print "The score of your exam is", "FFFFFEDCBAA"[g/10] # this is simpler 
code but harder to read/maintain.

Or - knowing that chr(65) = "A", chr(66) = "B" you could convert the number 
to be in the range 65..70 and use chr()

>import string

You do not refer to the string module, so there is no need to import it. 
Also be ware that it will eventually go away. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050924/1f6d1b80/attachment.htm

From ml.cyresse at gmail.com  Sun Sep 25 03:36:48 2005
From: ml.cyresse at gmail.com (Liam Clarke)
Date: Sun, 25 Sep 2005 13:36:48 +1200
Subject: [Tutor] Using new style classes and __slots__
In-Reply-To: <b6f3249e05092414377a830052@mail.gmail.com>
References: <b6f3249e050923235059c73b@mail.gmail.com>
	<4335520B.4000009@tds.net> <b6f3249e05092406492c2ba0e9@mail.gmail.com>
	<433560BA.1060506@tds.net> <b6f3249e05092414377a830052@mail.gmail.com>
Message-ID: <b6f3249e0509241836688199a8@mail.gmail.com>

Ooer,

Well, I got setattr() and property() working together nicely, but with
a weird side effect.

class Strange(object):
    def getA(um, self):
        print "What is", um
        return self.__a

    def setA(um, self, value):
        print um, "turns up here as well."
        self.__a = value

    def __init__(self):
        setattr(Strange, "a", property(self.getA, self.setA))
        self.a = 20

>>> c = Strange()
<__main__.Strange object at 0x01166290> turns up here as well.
>>> print c.a
What is <__main__.Strange object at 0x01166290>
20
>>> c
<__main__.Strange object at 0x01166290>

To my uneducated eye, it looks like it's passing self twice! Returning
um.__a works exactly the same as self.__a!

I'm getting the feelin I may need to venture into comp.lang.Python
with this sort of stuff.

Interesting.

Liam Clarke

On 9/25/05, Liam Clarke <ml.cyresse at gmail.com> wrote:
> Hi,
>
>
> > You might want to learn more about the whole property mechanism then. property() is actually a bit of sugar over a deeper mechanism. Also there is an interesting idiom for creating properties using @apply (in Python 2.4) - look for Benji York's comment in this recipe:
> > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698
>
> Thanks Kent. Just looking at that above recipe, I'm not too sure how
> the @ decorators work.
> From what I understand, it defines would turn apply() into a function
> that returns the various get/sets?
>
> Also found something interesting with property(), if it's called in
> __init__ you get
> >>> a.a
> <property object at 0x011598C8>
>
> whereas called outside __init__ it works normally.
>
> This is a hassle for me because I'm a lazy typist, so I've been using
> setattr() to pull attribute names out of a list. And the first
> argument setattr() requires is an object, and self doesn't work
> outside of a method, and using the class name leads to no attribute
> being set.
>
> Hmm, may have to learn even more about classes and their internals.
>
> Regards,
>
> Liam Clarke
>

From kent37 at tds.net  Sun Sep 25 04:00:42 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 24 Sep 2005 22:00:42 -0400
Subject: [Tutor] Using new style classes and __slots__
In-Reply-To: <b6f3249e05092414377a830052@mail.gmail.com>
References: <b6f3249e050923235059c73b@mail.gmail.com>	<4335520B.4000009@tds.net>
	<b6f3249e05092406492c2ba0e9@mail.gmail.com>	<433560BA.1060506@tds.net>
	<b6f3249e05092414377a830052@mail.gmail.com>
Message-ID: <433604CA.5090508@tds.net>

Liam Clarke wrote:
>>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698
> 
> 
> Thanks Kent. Just looking at that above recipe, I'm not too sure how
> the @ decorators work.
>>From what I understand, it defines would turn apply() into a function
> that returns the various get/sets?

OK, lets pick it apart a bit. Here is the recipe for defining a property:
class Example(object):
    @apply
    def myattr():
        doc = """This is the doc string."""

        def fget(self):
            return self._value

        def fset(self, value):
            self._value = value

        def fdel(self):
            del self._value

        return property(**locals())

Looking at myattr(), it defines the four attributes that make a property - doc, fget, fset and fdel. So at the end of myattr(), locals() is a dictionary containing these four attributes. Then it calls property() and passes it locals() as keyword arguments. So the last line is the same as return property(doc=doc, fget=fget, fset=fset, fdel=fdel) which creates a normal property.

OK, now what does the @apply do? Well, it's a decorator, and in general
@some_decorator
def myfunc():
  # etc

means the same thing as
def myfunc():
  # etc
myfunc = some_decorator(myfunc)

In other words the decorator is called with the function as an argument, and the return value of the function is bound to the name of the original function. So we have to know what apply(myattr) does. Actually, it just calls myattr(). So the net result is
myattr = myattr() i.e.
myattr = property(doc=doc, fget=fget, fset=fset, fdel=fdel)
which is what you would have done any way if you weren't trying to be so clever.

What does this recipe buy you? It puts the property function definitions into a separate namespace so they are not accessible as member functions, and it lets you reuse the names for them instead of having to invent new ones each time.
> 
> Also found something interesting with property(), if it's called in
> __init__ you get
> 
>>>>a.a
> 
> <property object at 0x011598C8>
> 
> whereas called outside __init__ it works normally.

Are you assigning the property to self or to the class? It might work if you assign to the class. But you will be recreating the properties for every instance.
> 
> This is a hassle for me because I'm a lazy typist, so I've been using
> setattr() to pull attribute names out of a list. And the first
> argument setattr() requires is an object, and self doesn't work
> outside of a method, and using the class name leads to no attribute
> being set.

I don't understand this at all, can you give an example?
> 
> Hmm, may have to learn even more about classes and their internals.

Yeah, it sounds like maybe a case for a metaclass.

Kent

> 
> Regards,
> 
> Liam Clarke
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From kent37 at tds.net  Sun Sep 25 04:15:37 2005
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 24 Sep 2005 22:15:37 -0400
Subject: [Tutor] Using new style classes and __slots__
In-Reply-To: <b6f3249e0509241836688199a8@mail.gmail.com>
References: <b6f3249e050923235059c73b@mail.gmail.com>	<4335520B.4000009@tds.net>
	<b6f3249e05092406492c2ba0e9@mail.gmail.com>	<433560BA.1060506@tds.net>
	<b6f3249e05092414377a830052@mail.gmail.com>
	<b6f3249e0509241836688199a8@mail.gmail.com>
Message-ID: <43360849.1090106@tds.net>

Your method signatures are off. Should be
def getA(self):
def setA(self, value)

So when you write self.a = 20 you are passing self as the um parameter. Actually I don't know why you don't get an exception for passing too many arguments?

And you don't need setattr, just write
Strange.a = property(...)

Oh wait, I get it - you are passing bound methods to property(). So um is bound to the instance when you access self.getA. Use Strange.getA instead of self.getA, then use the normal signatures.

But I don't get why you are doing this at all? What does it buy you over the standard form of

class Normal(object):
    def getA(self):
        return self.__a

    def setA(self, value):
        self.__a = value

    a = property(getA, setA)

    def __init__(self):
        self.a = 20

One more note below.

Kent

Liam Clarke wrote:
> Ooer,
> 
> Well, I got setattr() and property() working together nicely, but with
> a weird side effect.
> 
> class Strange(object):
>     def getA(um, self): 
>         print "What is", um
>         return self.__a
> 
>     def setA(um, self, value):
>         print um, "turns up here as well."
>         self.__a = value
> 
>     def __init__(self):
>         setattr(Strange, "a", property(self.getA, self.setA))
>         self.a = 20
> 
> 
>>>>c = Strange()
> 
> <__main__.Strange object at 0x01166290> turns up here as well.
> 
>>>>print c.a
> 
> What is <__main__.Strange object at 0x01166290>
> 20
> 
>>>>c
> 
> <__main__.Strange object at 0x01166290>
> 
> To my uneducated eye, it looks like it's passing self twice! Returning
> um.__a works exactly the same as self.__a!

It is passing self twice, because you are using a bound method as the property method rather than an unbound method.

> 
> I'm getting the feelin I may need to venture into comp.lang.Python
> with this sort of stuff.
> 
> Interesting.
> 
> Liam Clarke
> 
> On 9/25/05, Liam Clarke <ml.cyresse at gmail.com> wrote:
> 
>>Hi,
>>
>>
>>
>>>You might want to learn more about the whole property mechanism then. property() is actually a bit of sugar over a deeper mechanism. Also there is an interesting idiom for creating properties using @apply (in Python 2.4) - look for Benji York's comment in this recipe:
>>>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698
>>
>>Thanks Kent. Just looking at that above recipe, I'm not too sure how
>>the @ decorators work.
>>From what I understand, it defines would turn apply() into a function
>>that returns the various get/sets?
>>
>>Also found something interesting with property(), if it's called in
>>__init__ you get
>>
>>>>>a.a
>>
>><property object at 0x011598C8>
>>
>>whereas called outside __init__ it works normally.
>>
>>This is a hassle for me because I'm a lazy typist, so I've been using
>>setattr() to pull attribute names out of a list. And the first
>>argument setattr() requires is an object, and self doesn't work
>>outside of a method, and using the class name leads to no attribute
>>being set.
>>
>>Hmm, may have to learn even more about classes and their internals.
>>
>>Regards,
>>
>>Liam Clarke
>>
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From Goofball223 at wmconnect.com  Sun Sep 25 04:20:53 2005
From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com)
Date: Sat, 24 Sep 2005 22:20:53 EDT
Subject: [Tutor] creating strings
Message-ID: <110.52c0b74e.30676385@wmconnect.com>

Hello

How would I get the following program to accept inputs of exam scores from 
0-100 with A being 100-90, B being 89-80, C being 79-70, D being 69-60, and F 
being everything less than 60?

import string

def main():


   scores = ["F", "D", "C", "B", "A"]
   g = input("Enter a score number (0-100): ")

   print "The score of your exam is", scores [g-0] + "."


main()   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050924/536a9377/attachment.html

From ml.cyresse at gmail.com  Sun Sep 25 04:35:11 2005
From: ml.cyresse at gmail.com (Liam Clarke)
Date: Sun, 25 Sep 2005 14:35:11 +1200
Subject: [Tutor] (no subject)
In-Reply-To: <6.1.2.0.0.20050924181400.03530100@mail.mric.net>
References: <e0.1c8525c9.30672d57@wmconnect.com>
	<6.1.2.0.0.20050924181400.03530100@mail.mric.net>
Message-ID: <b6f3249e050924193546905a43@mail.gmail.com>

I'd also like to mention that input() is bad, as you can enter Python
statements and it'll execute them. For instance, entering "sys.exit()"
would cause your programme to try and call sys.exit(), which if the
sys module had been imported, would quit.

You can do far more malevolent things than that, of course.

Best to use

g = int(raw_input("Enter a score number (0-100): "))

Come Python 3.0, raw_input and input are to both get the boot, I
believe, in favour of sys.stdin.read()
On 9/25/05, bob <bgailer at alum.rpi.edu> wrote:
>  At 03:29 PM 9/24/2005, Goofball223 at wmconnect.com wrote:
>
> Hello
>
>  How would I get the following program to accept inputs of exam scores from
> 0-100 with A being 100-90, B being 89-80, C being 79-70, D being 69-60, and
> F being everything less than 60?
>  Many solutions are available. One could use an if statement:
>
>  if g >= 90: s = 'A'
>  elif g >= 80: s = 'B'
>  ...
>  else: g = 'F'
>
>  although that can be hard to maintain.
>
>  Or associate the lower limit with the data and search using a loop:
>
>  scores = [("A",90), ("B",80), ("C".70), ("D",60),("F",0) ]
>  for letter, number in scores:
>      if g >= number:break
>  print "The score of your exam is", letter
>
>  This separates the data from the program structure and becomes much easier
> to maintain / extend, apply to new situation.
>
>  If you are using a database then you could store these value pairs in a
> table and use SQL to retrieve the desired letter.
>
>  When the number ranges have a nice progression, you can reduce the number
> to an index:
>
>  print "The score of your exam is", "FFFFFEDCBAA"[g/10] # this is simpler
> code but harder to read/maintain.
>
>  Or - knowing that chr(65) = "A", chr(66) = "B" you could convert the number
> to be in the range 65..70 and use chr()
>
>
> import string
>  You do not refer to the string module, so there is no need to import it.
> Also be ware that it will eventually go away.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>

From Goofball223 at wmconnect.com  Sun Sep 25 05:50:24 2005
From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com)
Date: Sat, 24 Sep 2005 23:50:24 EDT
Subject: [Tutor] numbers from a name
Message-ID: <209.a26427e.30677880@wmconnect.com>

Hello

with the following program I would like it to be able to take a person's name 
 and then assign values to each letter and come up with a sum of all the 
letters in the name. for example if I entered bob. i would like the program to be 
able to print bob and then print the total of bob which would be 2 + 15 + 2 = 
18. 





import string

def main():
    value = (raw_input("Please enter your first name"))

     table = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5, 'f' : 6, 'g' : 7, 
'h' : 8, 'i' : 9, 'j' : 10, 'k' : 11, 'l' : 12, 'm' : 13, 'n' : 14, 'o' : 15, 
'p' : 16, 'q' : 17, 'r' : 18, 's' : 19, 't' : 20, 'u' :         21, 'v' : 22, 
'w' : 23, 'x' : 24, 'y' : 25, 'z' : 26}


     total = 0
     name = list(name)

     for string in name:
         total += table[string.lower()]
     print "The total of your name is:", total

main()

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050924/9fa01899/attachment.html

From zamb at saudi.net.sa  Sun Sep 25 06:59:12 2005
From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY)
Date: Sun, 25 Sep 2005 07:59:12 +0300
Subject: [Tutor] numbers from a name
In-Reply-To: <209.a26427e.30677880@wmconnect.com>
References: <209.a26427e.30677880@wmconnect.com>
Message-ID: <1127624352.7689.32.camel@localhost.localdomain>

On Sat, 2005-09-24 at 23:50 -0400, Goofball223 at wmconnect.com wrote:
> Hello
Hi Goofball...

>
> with the following program I would like it to be able to take a
> person's name  and then assign values to each letter and come up with
> a sum of all the letters in the name. for example if I entered bob. i
> would like the program to be able to print bob and then print the
> total of bob which would be 2 + 15 + 2 = 18.
>
It should be 19, not 18.

> import string 
You don't need the "string" module for something this simple.  Just
read.

> def main(): 
>    value = (raw_input("Please enter your first name"))
Why the parenthesis?  This is better:
    value = raw_input("Please enter your first name: ")

Also, after that you can convert the whole string to lower letters in
one step:
    value = value.lower()

A good resource for information about Python's built-ins and modules is
to start the Python shell and type "help(something)", where "something"
is what you want more info about.

In the above example, "raw_input" will return an object of type "str".
Type "help(str)" and see a lot of things you could do to/with "str"
objects!  (By the way, I found that "raw_input" returns "str" by typing
"help(raw_input) in Python! :) )

>     table = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5, 'f' : 6,
> 'g' : 7, 'h' : 8, 'i' : 9, 'j' : 10, 'k' : 11, 'l' : 12, 'm' : 13,
> 'n' : 14, 'o' : 15, 'p' : 16, 'q' : 17, 'r' : 18, 's' : 19, 't' : 20,
> 'u' :         21, 'v' : 22, 'w' : 23, 'x' : 24, 'y' : 25, 'z' : 26}
You could write a loop to create the "table" for you.  Though, It will
be slower than the above method and will consume more system resources.
But it will be much easier on you.   (A Real Programmer is a lazy one!:)
Just kidding!)

>
>     total = 0
>     name = list(name)
What's "name" for?  Also, "name" never used before!  Did you mean
"name=list(value)"?  But I don't see how's that going to help.
> 
>     for string in name:
>         total += table[string.lower()]
>     print "The total of your name is:", total 
"string" is the name of a module!  You can't use it here _if_ you
imported that module.  And as mentioned above, what's "name"?

Try this:
    for x in value:
        total += table[x]
    print "The total of your name is:", total

"x" will iterate for each item (in this case, letter) in "value" which
holds the lowered case input.  "table" have each letter assigned to a
number.  "table[x]" will look-up "table" and _return_ the _number_
assigned to the letter that is held in "x".

If you didn't understand this just ask here again and many well be glad
to help.


> main() 


Ziyad.


From Goofball223 at wmconnect.com  Sun Sep 25 07:06:04 2005
From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com)
Date: Sun, 25 Sep 2005 01:06:04 EDT
Subject: [Tutor] numbers from a name
Message-ID: <7a.7c6b4d18.30678a3c@wmconnect.com>

How could I change the program to accept something like: John Bob Zelle 
Python or Kip Rada?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050925/9bcd035c/attachment.htm

From dyoo at hkn.eecs.berkeley.edu  Sun Sep 25 08:47:10 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 24 Sep 2005 23:47:10 -0700 (PDT)
Subject: [Tutor] printing an acronym
In-Reply-To: <1936.172.170.62.199.1127602814.squirrel@172.170.62.199>
Message-ID: <Pine.LNX.4.44.0509242340490.18675-100000@hkn.eecs.berkeley.edu>



On Sat, 24 Sep 2005 andrade1 at umbc.edu wrote:

> How could I get the following to print out an acronym for each phrase
> entered such as if I entered random access memory it word print out RAM?


Hello,

Just out of curiosity, are you already familiar with Python's "lists"?

If so, then you might want to try the slightly easier problem of pulling
out acronyms out of a list of words.  Extracting an acronym out of a list
like:

    ["International", "Business", "Machines"]

    ==> "IBM"

is not too bad, and is one step toward doing the original problem on the
phrase "International Business Machines".


Tutorials like:

    http://www.freenetpages.co.uk/hp/alan.gauld/tutseq2.htm

and the other tutorials on:

    http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

should talk about lists.  Please feel free to ask questions here!


From dyoo at hkn.eecs.berkeley.edu  Sun Sep 25 08:56:39 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat, 24 Sep 2005 23:56:39 -0700 (PDT)
Subject: [Tutor] (no subject)
In-Reply-To: <e0.1c8525c9.30672d57@wmconnect.com>
Message-ID: <Pine.LNX.4.44.0509242350250.18675-100000@hkn.eecs.berkeley.edu>



On Sat, 24 Sep 2005 Goofball223 at wmconnect.com wrote:


> How would I get the following program to accept inputs of exam scores
> from 0-100 with A being 100-90, B being 89-80, C being 79-70, D being
> 69-60, and F being everything less than 60?

Hello,

Are you familiar with "if/elif/else"?  These "control-flow"  statements
should help you express the above grading idea fairly straightforwardly.

For experienced programmers, there is a module in the Standard Library
that does pretty much what you want.  I'll link to it below, but you
probably won't want to use it: learn to use if/elif/else first; I'd hate
to stunt your Python learning.  *grin*









Link for experienced programmers:

    http://www.python.org/doc/lib/bisect-example.html


From ml.cyresse at gmail.com  Sun Sep 25 10:34:12 2005
From: ml.cyresse at gmail.com (Liam Clarke)
Date: Sun, 25 Sep 2005 20:34:12 +1200
Subject: [Tutor] Using new style classes and __slots__
In-Reply-To: <43360849.1090106@tds.net>
References: <b6f3249e050923235059c73b@mail.gmail.com>
	<4335520B.4000009@tds.net> <b6f3249e05092406492c2ba0e9@mail.gmail.com>
	<433560BA.1060506@tds.net> <b6f3249e05092414377a830052@mail.gmail.com>
	<b6f3249e0509241836688199a8@mail.gmail.com> <43360849.1090106@tds.net>
Message-ID: <b6f3249e05092501347065d124@mail.gmail.com>

> Oh wait, I get it - you are passing bound methods to property(). So um is bound to the instance when you access self.getA. Use Strange.getA instead of self.getA, then use the normal signatures.

Ahh... I get it.

> But I don't get why you are doing this at all?

Because some of the objects I'm working with have 65 attributes, each
one needs to be typechecked and then passed down the line. As the
knowledge of the file structure I'm reading is not complete, as it
changes I'll have to update it. At the moment, what I'm doing is I
have a  docstring like so -
	"""
	Type: Track Item
	
	Tuple format:
		[0]   header_id (4string)
		[1]   header_length (int)
		[2]   total_length (int)             		<-- (Of child strings + header)
		[3]   num_of_strings (int)       		<-- (Above child strings)
		... ...
		[62] unknown (int)
		[63] unknown (int)
		[64] unknown (int)
		
		"""

and a struct string "4s6ih2c7i2h12iq2c3h10iq17i"

Now, as knowledge of the format changes, so does that tuple format and
struct string.
I have a convenience function which parses my docstring for each class
and creates a module dictionary of attribute name, type and length if
applicable. It can also create a struct string based on those types. I
can then call a generic set for all those attributes, which will pull
the type out of the dict and check it, and also acts as a repository
for attribute names.

If the file structure changes, I simply update my doc string, call my
convenience function, and my name:type dictionary is updated, as is my
struct string.

Alternatively, I can manually add header_id = property(..) and
manually update the struct string and the doc string when something
changes.

However, on reflection, I just figured out that it'll be simpler using
__setattr__ for this one, as I won't be able to get the attribute name
using property() unless I use a function factory to generate 127
functions and use func.__name__, when using __setattr__ and a
dictionary lookup is going to be much simpler.

But, it's good to know how to use property. I can think of a couple of
uses it for it. I wasn't thinking far enough ahead in this case, so
please forgive my emailed meanderings.

> It is passing self twice, because you are using a bound method as the property method
> rather than an unbound method.

Erk. That seems obvious in hindsight, like a cryptic crossword answer.
Once again, my lack of experience with this sorta stuff comes up.

I've never really dealt with indepth oo stuff before, so this has all
been a gigantic learning curve. Thanks for your help on this, Kent.

>> This is a hassle for me because I'm a lazy typist, so I've been using
>> setattr() to pull attribute names out of a list. And the first
>> argument setattr() requires is an object, and self doesn't work
>> outside of a method, and using the class name leads to no attribute
>> being set.

>I don't understand this at all, can you give an example?

Basically, I just found that outside methods, "self" gives a
NameError. The examples are all needless now, anyway.

Regards,

Liam Clarke

From big.gaz at dsl.pipex.com  Sun Sep 25 12:53:37 2005
From: big.gaz at dsl.pipex.com (Garry Rowberry)
Date: Sun, 25 Sep 2005 11:53:37 +0100
Subject: [Tutor] Error checking - very basic question
Message-ID: <20050925105338.6337BE000141@galaxy.systems.pipex.net>

I have a call which needs to reply 2.1 or 2.8 and report an error if not:


def ask_dau_version():
    """Determine the product issue of the DAU."""
    dau_version = None
    while dau_version not in ("2.8", "2.1"):
        dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please
enter only 2.1 or 2.8 ")
        print"\n\t\aError! - please enter only 2.1 or 2.8."
    else:
        print""
    return dau_version

I can see why it isn't working, the error message is in the wrong place, but
I can't see a simple way around it (wood for the trees)

Gaz


From zamb at saudi.net.sa  Sun Sep 25 13:04:28 2005
From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY)
Date: Sun, 25 Sep 2005 14:04:28 +0300
Subject: [Tutor] numbers from a name
In-Reply-To: <7a.7c6b4d18.30678a3c@wmconnect.com>
References: <7a.7c6b4d18.30678a3c@wmconnect.com>
Message-ID: <1127646268.8334.35.camel@localhost.localdomain>

On Sun, 2005-09-25 at 01:06 -0400, Goofball223 at wmconnect.com wrote:
> How could I change the program to accept something like: John Bob
> Zelle Python or Kip Rada? 
>
If it works for you with one word, all you need to make it accepts more
is to add the space character " " with a weight of zero to "table".
  >>>    table[' '] = 0

Alternatively, while creating the whole "table":
        table = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7,
        'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14,
        'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21,
        'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26, ' ': 0}

Likewise, you could add the ',' (also with a weight of 0) for names like
"Bob, Bob".

Ziyad.


From project5 at redrival.net  Sun Sep 25 13:05:35 2005
From: project5 at redrival.net (Andrei)
Date: Sun, 25 Sep 2005 13:05:35 +0200
Subject: [Tutor] Error checking - very basic question
In-Reply-To: <20050925105338.6337BE000141@galaxy.systems.pipex.net>
References: <20050925105338.6337BE000141@galaxy.systems.pipex.net>
Message-ID: <dh60a0$eqs$1@sea.gmane.org>

Garry Rowberry wrote:
> def ask_dau_version():
>     """Determine the product issue of the DAU."""
>     dau_version = None
>     while dau_version not in ("2.8", "2.1"):
>         dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please
> enter only 2.1 or 2.8 ")
>         print"\n\t\aError! - please enter only 2.1 or 2.8."
>     else:
>         print""
>     return dau_version
> 
> I can see why it isn't working, the error message is in the wrong place, but
> I can't see a simple way around it (wood for the trees)

How about using a "while True" loop that you break out of only when a 
correct value has been identified:

     while True:
         dau_version = raw_input('blabla')
         if dau_version in ("2.8", "2.1"):
             break
         else:
             print "Error"


-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.


From ml.cyresse at gmail.com  Sun Sep 25 13:09:43 2005
From: ml.cyresse at gmail.com (Liam Clarke)
Date: Sun, 25 Sep 2005 23:09:43 +1200
Subject: [Tutor] Error checking - very basic question
In-Reply-To: <20050925105338.6337BE000141@galaxy.systems.pipex.net>
References: <20050925105338.6337BE000141@galaxy.systems.pipex.net>
Message-ID: <b6f3249e05092504097cddad1b@mail.gmail.com>

Hi Garry,
     dau_version = None
     while dau_version not in ("2.8", "2.1"):
         dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please
                                                enter only 2.1 or 2.8 ")
         print"\n\t\aError! - please enter only 2.1 or 2.8."
     else:
         print""


I don't know what they else is meant to do, I take it that's when your
while loop exits.

Here's how your code will run -

dau_version = None
(while statement) is dau_version "2.8" or "2.1"? Nope.
dau_version = rawinput("Is...2.8")
print "Error! - please enter only 2.1 or 2.8"
is dau_version "2.8" or "2.1"? Yep - exit loop.

Try doing it like this -

while True:
     dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please\
                                           enter only 2.1 or 2.8 ")
     if dau_version in ("2.1", "2.8"):
           break
      print "Error! - please enter only 2.1 or 2.8"


What will happen is that your while loop will loop forever (as True is
always True).
However, if dau_version is "2.1" or "2.8", the break command will be
called, which exits out of the loop at that point.

So your loop looks like this now -

while True:
   get dau_version
   if dau_version is right, exit loop here.
   print error message

Regards,

Liam Clarke
On 9/25/05, Garry Rowberry <big.gaz at dsl.pipex.com> wrote:
> I have a call which needs to reply 2.1 or 2.8 and report an error if not:
>
>
> def ask_dau_version():
>     """Determine the product issue of the DAU."""
>     dau_version = None
>     while dau_version not in ("2.8", "2.1"):
>         dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please
> enter only 2.1 or 2.8 ")
>         print"\n\t\aError! - please enter only 2.1 or 2.8."
>     else:
>         print""
>     return dau_version
>
> I can see why it isn't working, the error message is in the wrong place, but
> I can't see a simple way around it (wood for the trees)
>
> Gaz
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From ajikoe at gmail.com  Sun Sep 25 13:11:41 2005
From: ajikoe at gmail.com (Pujo Aji)
Date: Sun, 25 Sep 2005 13:11:41 +0200
Subject: [Tutor] creating strings
In-Reply-To: <110.52c0b74e.30676385@wmconnect.com>
References: <110.52c0b74e.30676385@wmconnect.com>
Message-ID: <cf5262d20509250411342a6c9e@mail.gmail.com>

I will use simple function:
 def getscore(val):
if 90 < val <=100:
return 'A'
elif val >= 80:
return 'B'
elif val >= 70:
return 'C'
elif val >= 60:
return 'D'
else:
return 'F'

def main():
g = input('Enter score:')
print 'the score of the exam is %s' % (getscore(int(g)))

Cheers,
pujo
 On 9/25/05, Goofball223 at wmconnect.com <Goofball223 at wmconnect.com> wrote:
>
> Hello
>
> How would I get the following program to accept inputs of exam scores from
> 0-100 with A being 100-90, B being 89-80, C being 79-70, D being 69-60, and
> F being everything less than 60?
>
> import string
>
> def main():
>
>
> scores = ["F", "D", "C", "B", "A"]
> g = input("Enter a score number (0-100): ")
>
> print "The score of your exam is", scores [g-0] + "."
>
>
> main()
> _______________________________________________
> 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/20050925/6022a035/attachment.html

From project5 at redrival.net  Sun Sep 25 13:33:36 2005
From: project5 at redrival.net (Andrei)
Date: Sun, 25 Sep 2005 13:33:36 +0200
Subject: [Tutor] creating strings
In-Reply-To: <110.52c0b74e.30676385@wmconnect.com>
References: <110.52c0b74e.30676385@wmconnect.com>
Message-ID: <dh61ui$i5g$1@sea.gmane.org>

Goofball223 at wmconnect.com wrote:
> How would I get the following program to accept inputs of exam scores 
> from 0-100 with A being 100-90, B being 89-80, C being 79-70, D being 
> 69-60, and F being everything less than 60?
> 
> import string

There's no point in importing string.

> def main():
> 
>   scores = ["F", "D", "C", "B", "A"]
>   g = input("Enter a score number (0-100): ")
> 
>   print "The score of your exam is", scores [g-0] + "."
> main()

You could chain a bunch of if-statements.
   if g is between X1 and Y1: result is Z1
   else if g is between X2 and Y2: result is Z2
   else if ...

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])


From ml.cyresse at gmail.com  Sun Sep 25 13:52:01 2005
From: ml.cyresse at gmail.com (Liam Clarke)
Date: Sun, 25 Sep 2005 23:52:01 +1200
Subject: [Tutor] Error checking - very basic question
In-Reply-To: <20050925112724.D1D53E0000C9@galaxy.systems.pipex.net>
References: <b6f3249e05092504097cddad1b@mail.gmail.com>
	<20050925112724.D1D53E0000C9@galaxy.systems.pipex.net>
Message-ID: <b6f3249e05092504523b874c49@mail.gmail.com>

Hi Garry,

break is essential for while loops like that one. You'll see that
construct often enough in Python.

While 1 or While True followed by an if <condition> : break

Bit awkward, makes me miss the do - while construct.

continue is very useful in for loops.

Let's say I have a set of numbers, but I don't want to work with the
number 5. I have a phobia or something.

numbers = [1,2,3,4,5,6,7]

for number in numbers:
     if number == 5:
        continue
     print number

Continue will exit the loop at that point, but will continue with the
next value in numbers.
Try swapping break for continue.


On 9/25/05, Garry Rowberry <big.gaz at dsl.pipex.com> wrote:
> Thank you Liam,
>
> Works a treat, must look at the break and continue commands in more detail
>
> Regards
>
> Gaz
>
> -----Original Message-----
> From: Liam Clarke [mailto:ml.cyresse at gmail.com]
> Sent: Sunday, September 25, 2005 12:10 PM
> To: Garry Rowberry; Python Tutor Mailing List
> Subject: Re: [Tutor] Error checking - very basic question
>
> Hi Garry,
>      dau_version = None
>      while dau_version not in ("2.8", "2.1"):
>          dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8,
> please
>                                                 enter only 2.1 or 2.8 ")
>          print"\n\t\aError! - please enter only 2.1 or 2.8."
>      else:
>          print""
>
>
> I don't know what they else is meant to do, I take it that's when your
> while loop exits.
>
> Here's how your code will run -
>
> dau_version = None
> (while statement) is dau_version "2.8" or "2.1"? Nope.
> dau_version = rawinput("Is...2.8")
> print "Error! - please enter only 2.1 or 2.8"
> is dau_version "2.8" or "2.1"? Yep - exit loop.
>
> Try doing it like this -
>
> while True:
>      dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please\
>                                            enter only 2.1 or 2.8 ")
>      if dau_version in ("2.1", "2.8"):
>            break
>       print "Error! - please enter only 2.1 or 2.8"
>
>
> What will happen is that your while loop will loop forever (as True is
> always True).
> However, if dau_version is "2.1" or "2.8", the break command will be
> called, which exits out of the loop at that point.
>
> So your loop looks like this now -
>
> while True:
>    get dau_version
>    if dau_version is right, exit loop here.
>    print error message
>
> Regards,
>
> Liam Clarke
> On 9/25/05, Garry Rowberry <big.gaz at dsl.pipex.com> wrote:
> > I have a call which needs to reply 2.1 or 2.8 and report an error if not:
> >
> >
> > def ask_dau_version():
> >     """Determine the product issue of the DAU."""
> >     dau_version = None
> >     while dau_version not in ("2.8", "2.1"):
> >         dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8,
> please
> > enter only 2.1 or 2.8 ")
> >         print"\n\t\aError! - please enter only 2.1 or 2.8."
> >     else:
> >         print""
> >     return dau_version
> >
> > I can see why it isn't working, the error message is in the wrong place,
> but
> > I can't see a simple way around it (wood for the trees)
> >
> > Gaz
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>

From calvinkrishy at gmail.com  Sun Sep 25 15:25:48 2005
From: calvinkrishy at gmail.com (Krishna)
Date: Sun, 25 Sep 2005 18:55:48 +0530
Subject: [Tutor] Exception handling - syntaxerror?!
Message-ID: <e749d8a00509250625694906ff@mail.gmail.com>

When I try to run the following piece of code, I get a SyntaxError,
can someone help me out on this?

try:
... 	os.system("cls")
... except:
... 	print "Foo"
... print "Bar"
Traceback (  File "<interactive input>", line 5
    print "Bar"
        ^
SyntaxError: invalid syntax

What am I missing?

Thanks in advance,
Kris

From zamb at saudi.net.sa  Sun Sep 25 16:08:07 2005
From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY)
Date: Sun, 25 Sep 2005 17:08:07 +0300
Subject: [Tutor] Exception handling - syntaxerror?!
In-Reply-To: <e749d8a00509250625694906ff@mail.gmail.com>
References: <e749d8a00509250625694906ff@mail.gmail.com>
Message-ID: <1127657287.9375.5.camel@localhost.localdomain>

On Sun, 2005-09-25 at 18:55 +0530, Krishna wrote:
> When I try to run the following piece of code, I get a SyntaxError,
> can someone help me out on this?
> 
> try:
> ... 	os.system("cls")
> ... except:
> ... 	print "Foo"
> ... print "Bar"
> Traceback (  File "<interactive input>", line 5
>     print "Bar"
>         ^
> SyntaxError: invalid syntax
> 
> What am I missing?
> 
> Thanks in advance,
> Kris
What you're writing is this:
        try:
          os.system("cls")
            except:
              print "Foo"
            print "Bar"

Which is wrong!  Here's the correct way:
        try:
          os.system("cls")
        except:
          print "Foo"
        print "Bar"


Note the indentation for "try:" and "except:"?  They most be on the same
level.  This is how exception handling is done in Python.

By the way, the last "print" statement, I didn't know if you want it to
be printed all the time (like what I wrote it above) or just when
there's an exception.

Ziyad.


From calvinkrishy at gmail.com  Sun Sep 25 16:14:48 2005
From: calvinkrishy at gmail.com (Krishna)
Date: Sun, 25 Sep 2005 19:44:48 +0530
Subject: [Tutor] Exception handling - syntaxerror?!
In-Reply-To: <1127657287.9375.5.camel@localhost.localdomain>
References: <e749d8a00509250625694906ff@mail.gmail.com>
	<1127657287.9375.5.camel@localhost.localdomain>
Message-ID: <e749d8a005092507145139f54b@mail.gmail.com>

On 25/09/05, ZIYAD A. M. AL-BATLY <zamb at saudi.net.sa> wrote:
> On Sun, 2005-09-25 at 18:55 +0530, Krishna wrote:
> > When I try to run the following piece of code, I get a SyntaxError,
> > can someone help me out on this?
> >
> > try:
> > ...   os.system("cls")
> > ... except:
> > ...   print "Foo"
> > ... print "Bar"
> > Traceback (  File "<interactive input>", line 5
> >     print "Bar"
> >         ^
> > SyntaxError: invalid syntax
> >
> > What am I missing?
> >
> > Thanks in advance,
> > Kris
> What you're writing is this:
>         try:
>           os.system("cls")
>             except:
>               print "Foo"
>             print "Bar"
>
> Which is wrong!  Here's the correct way:
>         try:
>           os.system("cls")
>         except:
>           print "Foo"
>         print "Bar"
>
>
> Note the indentation for "try:" and "except:"?  They most be on the same
> level.  This is how exception handling is done in Python.
>
> By the way, the last "print" statement, I didn't know if you want it to
> be printed all the time (like what I wrote it above) or just when
> there's an exception.

Think the mail system screwed up the formatting! But am fairly sure
that I have indented it correctly in the console. Try and Except are
in the column. Any other hints?

BTW, I had just added the last print statement to see how try...except worked.

Thanks for the response.

-Kris

>
> Ziyad.
>
>

From marcink at ieee.org  Sun Sep 25 16:20:46 2005
From: marcink at ieee.org (Marcin Komorowski)
Date: Sun, 25 Sep 2005 10:20:46 -0400
Subject: [Tutor] 'print' without newline or space appended
Message-ID: <008201c5c1dc$52a29600$6671a8c0@zobook>

Hello,

This statement:
  for c in 'hello': print c
will generate following output:
  h
  e
  l
  l
  o
and by adding comma at the end of the print statement:
  for c in 'hello': print c,
we get this output:
  h e l l o
How do I output something using 'print' such that there is no new line or 
space appended at the end of the output.

....

Hehe... just answered my own question:
  import sys
  for c in 'hello' : sys.stdout.write(c)
Is this the way to do it or is there a more appropriate approach.

Thanks,
Marcin 



From amonroe at columbus.rr.com  Sun Sep 25 16:29:05 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sun, 25 Sep 2005 10:29:05 -0400
Subject: [Tutor] 'print' without newline or space appended
In-Reply-To: <008201c5c1dc$52a29600$6671a8c0@zobook>
References: <008201c5c1dc$52a29600$6671a8c0@zobook>
Message-ID: <127672216606.20050925102905@columbus.rr.com>

> Hello,

> This statement:
>   for c in 'hello': print c
> will generate following output:
>   h
>   e
>   l
>   l
>   o
> and by adding comma at the end of the print statement:
>   for c in 'hello': print c,
> we get this output:
>   h e l l o
> How do I output something using 'print' such that there is no new line or 
> space appended at the end of the output.

> ....

> Hehe... just answered my own question:
>   import sys
>   for c in 'hello' : sys.stdout.write(c)
> Is this the way to do it or is there a more appropriate approach.

Also

outstring = ''
for c in 'hello':
    outstring += c
print outstring


From zamb at saudi.net.sa  Sun Sep 25 17:05:14 2005
From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY)
Date: Sun, 25 Sep 2005 18:05:14 +0300
Subject: [Tutor] Exception handling - syntaxerror?!
In-Reply-To: <e749d8a005092507145139f54b@mail.gmail.com>
References: <e749d8a00509250625694906ff@mail.gmail.com>
	<1127657287.9375.5.camel@localhost.localdomain>
	<e749d8a005092507145139f54b@mail.gmail.com>
Message-ID: <1127660714.9687.10.camel@localhost.localdomain>

On Sun, 2005-09-25 at 19:44 +0530, Krishna wrote:
 <snip>
> Think the mail system screwed up the formatting! But am fairly sure
> that I have indented it correctly in the console. Try and Except are
> in the column. Any other hints?
Make sure you're not mixing "tabs" and "spaces".  A lot of editors uses
the ASCII "tab" character when hitting the Tab key, while other inserts
8 (or 4 on some cases) ASCII "space" character in that case.

If you're sure "try:" and "except:" are on the same column, then the
above advice is the only one I have for you.  Sorry.

> 
> BTW, I had just added the last print statement to see how try...except worked.
> 
> Thanks for the response.
You're welcome.

> 
> -Kris
> 
Ziyad.


From project5 at redrival.net  Sun Sep 25 17:28:12 2005
From: project5 at redrival.net (Andrei)
Date: Sun, 25 Sep 2005 17:28:12 +0200
Subject: [Tutor] Exception handling - syntaxerror?!
In-Reply-To: <e749d8a005092507145139f54b@mail.gmail.com>
References: <e749d8a00509250625694906ff@mail.gmail.com>	<1127657287.9375.5.camel@localhost.localdomain>
	<e749d8a005092507145139f54b@mail.gmail.com>
Message-ID: <dh6fme$gg8$1@sea.gmane.org>

> Think the mail system screwed up the formatting! But am fairly sure
> that I have indented it correctly in the console. Try and Except are
> in the column. Any other hints?

Yes :). Compare:

 >>> try:
...   os.system('cls')
... except:
...   print "Foo"
...
Foo
 >>> print "Bar"
Bar

With (what you had):

 >>> try:
...   os.system('cls')
... except:
...   print "Foo"
... print "Bar"
   File "<stdin>", line 5
     print "Bar"
         ^
SyntaxError: invalid syntax

Subtle, but important difference. You should terminate the try-except 
block (confirm with extra ENTER) before doing more stuff.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])


From lists at janeden.org  Sun Sep 25 19:47:38 2005
From: lists at janeden.org (Jan Eden)
Date: Sun, 25 Sep 2005 19:47:38 +0200
Subject: [Tutor] __getattr__ causes TypeError
Message-ID: <r02010500-1039-77293A9B2DEC11DA8EFB000A959B4026@[192.168.2.100]>

Hi,

I experienced a strange side effect using a custom __getattr__ method.

For a certain attribute, I'd like to return the value of another attribute if the former is not present. So I wrote:

def __getattr__(self, attrname):
    if attrname == 'own_type': return self.child_type
    else: AttributeError, attrname

But if I include this in my base class, I get a TypeError somewhere else:

  File "/Users/jan/Sites/janeden/cgi-bin/Pythonsite/Show.py", line 24, in Populate
   self.page_head = re.sub('%%author%%', self.first_name+' '+self.last_name, self.page_head)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

How can this possibly be related? I am clueless.

Best,

Jan
-- 
If all else fails read the instructions. - Donald Knuth

From lists at janeden.org  Sun Sep 25 19:51:18 2005
From: lists at janeden.org (Jan Eden)
Date: Sun, 25 Sep 2005 19:51:18 +0200
Subject: [Tutor] __getattr__ causes TypeError
In-Reply-To: <r02010500-1039-77293A9B2DEC11DA8EFB000A959B4026@[192.168.2.100]>
Message-ID: <r02010500-1039-FA5D4F762DEC11DA8EFB000A959B4026@[192.168.2.100]>

Sorry! Found the typo.

- Jan

Jan Eden wrote on 25.09.2005:

>Hi,
>
>I experienced a strange side effect using a custom __getattr__ method.
>
>For a certain attribute, I'd like to return the value of another attribute if 
>the former is not present. So I wrote:
>
>def __getattr__(self, attrname):
>    if attrname == 'own_type': return self.child_type
>    else: AttributeError, attrname
>
>But if I include this in my base class, I get a TypeError somewhere else:
>
>  File "/Users/jan/Sites/janeden/cgi-bin/Pythonsite/Show.py", line 24, in 
>Populate
>   self.page_head = re.sub('%%author%%', self.first_name+' '+self.last_name, 
>self.page_head)
>TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
>
>How can this possibly be related? I am clueless.
>
>Best,
>
>Jan
-- 
Any sufficiently advanced technology is indistinguishable from a Perl script. - Programming Perl

From marcink at ieee.org  Sun Sep 25 19:59:04 2005
From: marcink at ieee.org (Marcin Komorowski)
Date: Sun, 25 Sep 2005 13:59:04 -0400
Subject: [Tutor] 'print' without newline or space appended
References: <008201c5c1dc$52a29600$6671a8c0@zobook>
	<127672216606.20050925102905@columbus.rr.com>
Message-ID: <00d801c5c1fa$d1534fd0$6671a8c0@zobook>

Thanks,

This is the other 'work around'.  I take there is no way to tell 'print' to 
do it, correct?

Marcin

----- Original Message ----- 
From: "R. Alan Monroe" <amonroe at columbus.rr.com>
To: "python-tutor" <tutor at python.org>
Sent: Sunday, September 25, 2005 10:29 AM
Subject: Re: [Tutor] 'print' without newline or space appended


>> Hello,
>
>> This statement:
>>   for c in 'hello': print c
>> will generate following output:
>>   h
>>   e
>>   l
>>   l
>>   o
>> and by adding comma at the end of the print statement:
>>   for c in 'hello': print c,
>> we get this output:
>>   h e l l o
>> How do I output something using 'print' such that there is no new line or
>> space appended at the end of the output.
>
>> ....
>
>> Hehe... just answered my own question:
>>   import sys
>>   for c in 'hello' : sys.stdout.write(c)
>> Is this the way to do it or is there a more appropriate approach.
>
> Also
>
> outstring = ''
> for c in 'hello':
>    outstring += c
> print outstring
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



From Goofball223 at wmconnect.com  Mon Sep 26 01:25:13 2005
From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com)
Date: Sun, 25 Sep 2005 19:25:13 EDT
Subject: [Tutor] help getting acronym to print?
Message-ID: <1d7.45a8f5ef.30688bd9@wmconnect.com>

Hello

How could I get the following program to output UDP from the user entering 
user datagram protcol or IP if internet protocla was entered?

currently it only prints out on letter



import string

def main():


    phrase = (raw_input("Please enter a phrase:"))

    acr1 = string.split(phrase)
    print"",acr1 #only using print to see where I am

    acr2 = string.capwords(phrase)
    print"",acr2 #only using print to see where I am
    for phrase in string.split(phrase): 
     acronym = string.upper(phrase[0])
    
    print "", acronym
main()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050925/ed2771ba/attachment.htm

From hugonz-lists at h-lab.net  Mon Sep 26 01:48:46 2005
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Sun, 25 Sep 2005 17:48:46 -0600
Subject: [Tutor] help getting acronym to print?
In-Reply-To: <1d7.45a8f5ef.30688bd9@wmconnect.com>
References: <1d7.45a8f5ef.30688bd9@wmconnect.com>
Message-ID: <4337375D.5030304@h-lab.net>

Didn't go through everything, but why do you do:

 >    for phrase in string.split(phrase):
 >     acronym = string.upper(phrase[0])


you are iterating with the name of the list? bad juju

try something like

acronym = ""

for word in string.split(phrase):
     acronym = acronym + string.upper(word[0])

then the acronym variable will hold the initial letter to every word

Hugo


Goofball223 at wmconnect.com wrote:
> Hello
> 
> How could I get the following program to output UDP from the user 
> entering user datagram protcol or IP if internet protocla was entered?
> 
> currently it only prints out on letter
> 
> 
> 
> import string
> 
> def main():
> 
> 
>    phrase = (raw_input("Please enter a phrase:"))
> 
>    acr1 = string.split(phrase)
>    print"",acr1 #only using print to see where I am
> 
>    acr2 = string.capwords(phrase)
>    print"",acr2 #only using print to see where I am
>    for phrase in string.split(phrase):
>     acronym = string.upper(phrase[0])
>    
>    print "", acronym
> main()
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

From calvinkrishy at gmail.com  Mon Sep 26 07:20:14 2005
From: calvinkrishy at gmail.com (Krishna)
Date: Mon, 26 Sep 2005 10:50:14 +0530
Subject: [Tutor] Exception handling - syntaxerror?!
In-Reply-To: <dh6fme$gg8$1@sea.gmane.org>
References: <e749d8a00509250625694906ff@mail.gmail.com>
	<1127657287.9375.5.camel@localhost.localdomain>
	<e749d8a005092507145139f54b@mail.gmail.com>
	<dh6fme$gg8$1@sea.gmane.org>
Message-ID: <e749d8a005092522205e6fa703@mail.gmail.com>

On 25/09/05, Andrei <project5 at redrival.net> wrote:
> > Think the mail system screwed up the formatting! But am fairly sure
> > that I have indented it correctly in the console. Try and Except are
> > in the column. Any other hints?
>
> Yes :). Compare:
>
>  >>> try:
> ...   os.system('cls')
> ... except:
> ...   print "Foo"
> ...
> Foo
>  >>> print "Bar"
> Bar
>
> With (what you had):
>
>  >>> try:
> ...   os.system('cls')
> ... except:
> ...   print "Foo"
> ... print "Bar"
>    File "<stdin>", line 5
>      print "Bar"
>          ^
> SyntaxError: invalid syntax
>
> Subtle, but important difference. You should terminate the try-except
> block (confirm with extra ENTER) before doing more stuff.

When I have this piece of code in a function, it works fine. So is
this some limitation of directly working out off the console?

Seems the console supports complete code constructs only  I.e., I can
have one complete try...except block, a if block etc., but not a bunch
of constructs? Is my assumption correct?

Thanks.

>
> --
> Yours,
>
> Andrei

From paul1brian at gmail.com  Mon Sep 26 11:29:07 2005
From: paul1brian at gmail.com (paul brian)
Date: Mon, 26 Sep 2005 10:29:07 +0100
Subject: [Tutor] Help with pi and the math module.
In-Reply-To: <cf5262d2050924014833aed68f@mail.gmail.com>
References: <BAY106-DAV2281819E5B74563EB28437C4960@phx.gbl>
	<cf5262d2050924014833aed68f@mail.gmail.com>
Message-ID: <bbe9926e0509260229766e5fec@mail.gmail.com>

it might be a little clearer if you look at sys.modules


In the sys module is a useful dictionary called "modules"
This dictionary maps all the names of modules we import, to the objects
that are those modules.

for example (I am only importing pprint to make it easier to read)

>>> import sys, pprint
>>> pprint.pprint( sys.modules )
{'UserDict': <module 'UserDict' from 'C:\Python24\lib\UserDict.pyc'>,
 '__builtin__': <module '__builtin__' (built-in)>,
 '__main__': <module '__main__' (built-in)>,
 'copy_reg': <module 'copy_reg' from 'C:\Python24\lib\copy_reg.pyc'>,
 ...
 'sys': <module 'sys' (built-in)>,
 'types': <module 'types' from 'C:\Python24\lib\types.pyc'>,
 'warnings': <module 'warnings' from 'C:\Python24\lib\warnings.pyc'>,
 'zipimport': <module 'zipimport' (built-in)>}


So how does an import change this "namespace"?

Well, lets try one. I am going to choose the math module, becasue it has an
easy to spot constant in there called pi.

>>> import math
>>> pprint.pprint( sys.modules )
...
 'math': <module 'math' (built-in)>,
...

aha - that was not there earlier.

>>> import sys, pprint
>>> import math
>>> sys.modules['__main__'].__dict__['pi']
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 'pi'
>>> sys.modules['__main__'].__dict__['math']
<module 'math' (built-in)>
>>> math.pi
3.1415926535897931


So in the namespace of __main__ (where we run the interpreter) there
exists a module named 'math', and this module holds in its namespace a constant
called pi.

Now lets restart our python interepreter and try again

>>> import sys, pprint
>>> from math import *
>>> import sys, pprint
>>> pprint.pprint( sys.modules )
...
 'math': <module 'math' (built-in)>
...

There it is again. ?

Now if i have a look at the __main__ namespace (its __dict__)

>>> sys.modules['__main__'].__dict__['math']
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 'math'
>>> sys.modules['__main__'].__dict__['pi']
3.1415926535897931

math is not in the namespace, but pi is directly there.
Thats the difference between

import math which imports a module into the current namespace

and

from math import *
 which imports all the contents of math into the namespace

one last thing

>>> import random as offthewall
>>> pprint.pprint( sys.modules )
...
 'pprint': <module 'pprint' from 'C:\Python24\lib\pprint.pyc'>,
 'random': <module 'random' from 'C:\Python24\lib\random.pyc'>,
...
>>> random.randint(1,10)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'random' is not defined

Whoops - but it is clearly shown in the sys.modules. That is correct - because
we have imported the module (file) called random.  However when I am in
the __main__ namespace and do random.randint(1,10), Python tries to find
"random" in the __main__namespace.

>>> sys.modules['__main__'].__dict__['offthewall']
<module 'random' from 'C:\Python24\lib\random.pyc'>
>>> sys.modules['__main__'].__dict__['random']
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 'random'


We have imported the module random but with a name of offthewall
so

>>> offthewall.randint(1,10)
1
>>> offthewall.randint(1,10)
8

works fine.



On 9/24/05, Pujo Aji <ajikoe at gmail.com> wrote:
> hi,
>
> if you use : import math
> you can type: diameter * math.pi
>
> if you use from math import *
> you can type: diameter * pi
>
> Cheers,
> pujo
>
>
> On 9/24/05, Nathan Pinno <falcon3166 at hotmail.com> wrote:
> >
> >
> > Hi all,
> >
> > I need help with pi and the math module. I had import math at the top of a
> program, but when it came to diameter*pi, it said that pi was not defined.
> >
> > How do I use it correctly?
> >
> > Thanks,
> > Nathan Pinno
> > _______________________________________________
> > 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
>
>
>


--
--------------------------
Paul Brian
m. 07875 074 534
t. 0208 352 1741

From kent37 at tds.net  Mon Sep 26 12:09:07 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 26 Sep 2005 06:09:07 -0400
Subject: [Tutor] Problem with BeautifulSoup
In-Reply-To: <61d0e2b405092312154bce6c53@mail.gmail.com>
References: <61d0e2b405092311354fd2d76e@mail.gmail.com>	<e6443aa7050923120758b6dbc3@mail.gmail.com>
	<61d0e2b405092312154bce6c53@mail.gmail.com>
Message-ID: <4337C8C3.5020701@tds.net>

Bernard Lebel wrote:
> Hi grouchy,
> 
> I seem to have found the problem. Somehow, it seems BeautifulSoup
> doesn't like nested tags of the same name.

This seems to be a feature of BS. It seems a bit of a misfeature when applied to XML but anyway...you can configure BS with a set of tags which can be nested, then it will properly parse your data. Here is a short program that shows how:

xml = '''<parameter scriptname="posx">
    <fcurve plotted="False">
          <parameter scriptname="extrapolation">1</parameter>
    </fcurve>
</parameter>'''

import BeautifulSoup

class NestingParser(BeautifulSoup.BeautifulStoneSoup):
    NESTABLE_TAGS = BeautifulSoup.buildTagMap([], 'parameter')
    
soup = NestingParser(xml)
print soup.prettify()


Kent


From python at kapitalisten.no  Mon Sep 26 13:41:32 2005
From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=)
Date: Mon, 26 Sep 2005 13:41:32 +0200 (CEST)
Subject: [Tutor] wxPython problem
Message-ID: <38850.193.71.38.142.1127734892.squirrel@mail.sporck.net>

Hello.

I have been reading the
http://wiki.wxpython.org/index.cgi/Getting_20Started manual and are
running the program there. (Enclosed below).

When I run it, it works fine. But, when I run it again, I get the error
PyNoAppError: The wx.App object must be created first! I assume I have
killed the object and have to create it again. But how would I do that?
reload(MainWindow) does not work. Any suggestions?

Thanks in advance.


-----
import os
import wx
ID_ABOUT=101
ID_EXIT=110
class MainWindow(wx.Frame):
    def __init__(self,parent,id,title):
        wx.Frame.__init__(self,parent,wx.ID_ANY, title, size = ( 200,100),

                                        style=wx.DEFAULT_FRAME_STYLE|
                                        wx.NO_FULL_REPAINT_ON_RESIZE)
        self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
        self.CreateStatusBar() # A StatusBar in the bottom of the window
        # Setting up the menu.
        filemenu= wx.Menu()
        filemenu.Append(ID_ABOUT, "&About"," Information about this program")
        filemenu.AppendSeparator()
        filemenu.Append(ID_EXIT,"E&xit"," Terminate the program")
        # Creating the menubar.
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the
MenuBar
        self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.
        wx.EVT_MENU(self, ID_ABOUT, self.OnAbout) # attach the menu-event
ID_ABOUT to the
                                                           # method
self.OnAbout
        wx.EVT_MENU(self, ID_EXIT, self.OnExit)   # attach the menu-event
ID_EXIT to the
                                                           # method
self.OnExit
        self.Show(True)
    def OnAbout(self,e):
        d= wx.MessageDialog( self, " A sample editor \n"
                            " in wxPython","About Sample Editor", wx.OK)
                            # Create a message dialog box
        d.ShowModal() # Shows it
        d.Destroy() # finally destroy it when finished.
    def OnExit(self,e):
        self.Close(True)  # Close the frame.
app = wx.PySimpleApp()
frame = MainWindow(None, -1, "Sample editor")
app.MainLoop()

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


From challman at gmail.com  Mon Sep 26 13:56:32 2005
From: challman at gmail.com (Chris Hallman)
Date: Mon, 26 Sep 2005 07:56:32 -0400
Subject: [Tutor] script question
Message-ID: <9f68812f05092604563052918f@mail.gmail.com>

I needed a script that takes command line arguments, searches an ini file
for a match to the arguments and then executes a Windows executable. This is
my first script using python so I wanted to make sure I made the most of the
language. I took bits and pieces from different tutorials and examples
online. The script is executed in this manner:


python search_interface.py device interface interface_name "is down -
00:00:00 01/01/06"


Here is the script:

 import ConfigParser, string, sys
section = sys.argv[1]
port = sys.argv[3]
INI=ConfigParser.ConfigParser()
INI.read("interfaces.ini")
passwordentries=[p for p in INI.options(section)]
passwordlist=[INI.get(section, pw) for pw in passwordentries]
print passwordlist
for i in passwordlist:
if i == port:
os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] + " " +
sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])


I'd like to know if there is a more efficient way to do this and if there is
a way to have these functions performed with the least amount of time
possible (the ini file could grow quite large).



Thanks!!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050926/42fb29b6/attachment.htm

From kent37 at tds.net  Mon Sep 26 14:13:38 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 26 Sep 2005 08:13:38 -0400
Subject: [Tutor] script question
In-Reply-To: <9f68812f05092604563052918f@mail.gmail.com>
References: <9f68812f05092604563052918f@mail.gmail.com>
Message-ID: <4337E5F2.2050807@tds.net>

Chris Hallman wrote:
> The script is executed in this 
> manner:
> 
> python search_interface.py device interface interface_name "is down - 
> 00:00:00 01/01/06"
> 
> Here is the script:
> 
> import ConfigParser, string, sys
> section = sys.argv[1]
> port = sys.argv[3]
> INI=ConfigParser.ConfigParser()

Generally all caps names are used for constants, it would be more idiomatic to use ini.

> INI.read("interfaces.ini")
> passwordentries=[p for p in INI.options(section)]

This could just be 
passwordentries = INI.options(section), which is already a list. But even better, see below...

> passwordlist=[INI.get(section, pw) for pw in passwordentries]

The above two lines can be replaced with
passwordlist = [value for name, value in INI.items(section)]
which just accesses the section once.

Kent

> print passwordlist
> for i in passwordlist:
>     if i == port:
>         os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] + 
> " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])
> 
> 
> I'd like to know if there is a more efficient way to do this and if 
> there is a way to have these functions performed with the least amount 
> of time possible (the ini file could grow quite large).
> 
> 
> 
> Thanks!!
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From franz.steinhaeusler at gmx.at  Mon Sep 26 14:04:39 2005
From: franz.steinhaeusler at gmx.at (Franz Steinhäusler)
Date: Mon, 26 Sep 2005 14:04:39 +0200
Subject: [Tutor] wxPython problem
References: <38850.193.71.38.142.1127734892.squirrel@mail.sporck.net>
Message-ID: <nmofj195r4all4cp17aiuc2he0lpfub7ip@4ax.com>

On Mon, 26 Sep 2005 13:41:32 +0200 (CEST), ?yvind <python at kapitalisten.no> wrote:

>Hello.
>
>I have been reading the
>http://wiki.wxpython.org/index.cgi/Getting_20Started manual and are
>running the program there. (Enclosed below).
>
>When I run it, it works fine. But, when I run it again, I get the error
>PyNoAppError: The wx.App object must be created first! I assume I have
>killed the object and have to create it again. But how would I do that?
>reload(MainWindow) does not work. Any suggestions?
>
>Thanks in advance.


Hi,

Windows? Linux? wxPyVersion?

This sounds familiar to me, but I can't
remember exactly.

how do you run it?
in command prompt?
from a python shell (Idle, Pycrust)?

--
Franz Steinhaeusler


From python at kapitalisten.no  Mon Sep 26 14:32:53 2005
From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=)
Date: Mon, 26 Sep 2005 14:32:53 +0200 (CEST)
Subject: [Tutor] wxPython problem
Message-ID: <13974.193.71.38.142.1127737973.squirrel@mail.sporck.net>

Sorry... Forgot all about that.

Using WinXP, ActiveState Python 2.3 and wx-version 2.6.1.0.

I run it in ActiveStates Interactive Window, which is IDLE (I think).

Thanks in advance



<Hi,

<Windows? Linux? wxPyVersion?

<This sounds familiar to me, but I can't
<remember exactly.

<how do you run it?
<in command prompt?
<from a python shell (Idle, Pycrust)?

<--
<Franz Steinhaeusler

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


From chris.arndt at web.de  Mon Sep 26 14:56:25 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Mon, 26 Sep 2005 13:56:25 +0100
Subject: [Tutor] script question
In-Reply-To: <9f68812f05092604563052918f@mail.gmail.com>
References: <9f68812f05092604563052918f@mail.gmail.com>
Message-ID: <4337EFF9.6030604@web.de>

Chris Hallman schrieb:
> for i in passwordlist:
>     if i == port:
>         os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] +
> " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])

1) The last line can be also expressed as:

os.system(r"d:\tnd\bin\cawto.exe -cat NetNet %s" % (" ".join(sys.argv[1:5]),))

sys.argv is a list of strings (from which we're only using elements 1-4), which
you can concatenate with the join() method of strings. Then use the '%' string
operator to add it to the command string.

If your command line arguments might contain spaces, you should quote them like
this:

os.system(r"d:\tnd\bin\cawto.exe -cat NetNet %s" % (" ".join(['"%s"' % x for x
in sys.argv[1:5]]),))

You'll find more information about these methods and operators in the standard
library docs section 2.3.

2) I also used a raw string (r'') to avoid having to use double backslashes in
windows paths all the time.

3) Assuming that sys.argv[3] (port) will only match one password in
passwordlist, you can also shorten the for/if construction to:

if port in passwordlist:
    os.system(...)

because you're not actually using any of the information from the ini file in
your command line.

4) As to your question regarding efficiency of the script, unfortunately the
ConfigParser module parses the whole INI file unconditionally. You could look
for other third-party configuration file parsers that might do this more
efficiently, but I can not help you there. Start looking a the Cheese shop
(www.python.org/pypi)

Chris

From franz.steinhaeusler at gmx.at  Mon Sep 26 14:57:35 2005
From: franz.steinhaeusler at gmx.at (Franz Steinhäusler)
Date: Mon, 26 Sep 2005 14:57:35 +0200
Subject: [Tutor] wxPython problem
References: <13974.193.71.38.142.1127737973.squirrel@mail.sporck.net>
Message-ID: <dnrfj11uevtjkp9gpqtb6nl5rbtsj9fm83@4ax.com>

On Mon, 26 Sep 2005 14:32:53 +0200 (CEST), ?yvind <python at kapitalisten.no> wrote:

>Sorry... Forgot all about that.
>
>Using WinXP, ActiveState Python 2.3 and wx-version 2.6.1.0.
>
>I run it in ActiveStates Interactive Window, which is IDLE (I think).
>
>Thanks in advance
>
>

Aha, I thought something similar.

It is always a problem to run 2 different 
or competing GUI's the same time.

IDLE with wxPython or Active State Python (they
use the win32 extensions)

The best possibility is to use an IDE, which fits
to the GUI.

Pycrust as shell,
Editor and IDE's: DrPython, spe, Boa Constructor,...
or simply use SciTE as editor and with F5, you can
start your typed in Program and on the right you
have an output pane (With DrPython, you have these
possibilities and many more).

--
Franz Steinhaeusler


From falcon3166 at hotmail.com  Mon Sep 26 19:34:46 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Mon, 26 Sep 2005 11:34:46 -0600
Subject: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
	<432B8CA9.2000200@christianfreebies.com>
	<BAY106-DAV159F309A389BF7EECD88A1C4970@phx.gbl>
	<be4fbf92050922042136464a41@mail.gmail.com>
	<BAY106-DAV12C80622184DA4A10D6CFBC4960@phx.gbl>
	<6.1.2.0.0.20050922210541.02814178@mail.mric.net>
Message-ID: <BAY106-DAV92E734F3D5CD2E5A714D5C48B0@phx.gbl>

Bob,

I did what you suggested. Take another look, and tell me if you were a potential customer, would you purchase something?

Why not take the challenge? It's not like I'm asking much.

Nathan Pinno
  ----- Original Message ----- 
  From: bob 
  To: Nathan Pinno 
  Cc: tutor at python.org 
  Sent: Thursday, September 22, 2005 10:08 PM
  Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]


  At 06:42 PM 9/22/2005, Nathan Pinno wrote:

    The URL is http://zoffee.tripod.com/purchasecomprogs.htm

  [snip]

  At your invitation I visited the site. I personally would not purchase anything listed there due to insufficient information. I don't know what I'm getting!

  I suggest you dedicate a page to each program with at least one screenshot and explanation of what the program does. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050926/137d647c/attachment-0001.html

From project5 at redrival.net  Mon Sep 26 19:42:11 2005
From: project5 at redrival.net (Andrei)
Date: Mon, 26 Sep 2005 19:42:11 +0200
Subject: [Tutor] Exception handling - syntaxerror?!
In-Reply-To: <e749d8a005092522205e6fa703@mail.gmail.com>
References: <e749d8a00509250625694906ff@mail.gmail.com>	<1127657287.9375.5.camel@localhost.localdomain>	<e749d8a005092507145139f54b@mail.gmail.com>	<dh6fme$gg8$1@sea.gmane.org>
	<e749d8a005092522205e6fa703@mail.gmail.com>
Message-ID: <dh9btm$ikd$1@sea.gmane.org>

Krishna wrote:
> When I have this piece of code in a function, it works fine. So is
> this some limitation of directly working out off the console?

It is indeed valid Python (you don't have to have empty lines after 
try-except in a real Python program).

> Seems the console supports complete code constructs only  I.e., I can
> have one complete try...except block, a if block etc., but not a bunch
> of constructs? Is my assumption correct?

That seems to cover it, one compound statement per >>>. (You can chain 
several statements in one line by using ';', e.g. ">>> print 6; print 5" 
will work just fine.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])


From bgailer at alum.rpi.edu  Mon Sep 26 19:54:41 2005
From: bgailer at alum.rpi.edu (bob)
Date: Mon, 26 Sep 2005 10:54:41 -0700
Subject: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
In-Reply-To: <BAY106-DAV92E734F3D5CD2E5A714D5C48B0@phx.gbl>
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
	<432B8CA9.2000200@christianfreebies.com>
	<BAY106-DAV159F309A389BF7EECD88A1C4970@phx.gbl>
	<be4fbf92050922042136464a41@mail.gmail.com>
	<BAY106-DAV12C80622184DA4A10D6CFBC4960@phx.gbl>
	<6.1.2.0.0.20050922210541.02814178@mail.mric.net>
	<BAY106-DAV92E734F3D5CD2E5A714D5C48B0@phx.gbl>
Message-ID: <6.1.2.0.0.20050926105329.03561a00@mail.mric.net>

At 10:34 AM 9/26/2005, Nathan Pinno wrote:
>Bob,
>
>I did what you suggested. Take another look, and tell me if you were a 
>potential customer, would you purchase something?

  I tried 
<http://zoffee.tripod.com/purchasecomprogs.htm>http://zoffee.tripod.com/purchasecomprogs.htm 
I got "Sorry but the page ... is not here."
[]

Sorry, but the page or the file that you're looking for is not here.


>
>Why not take the challenge? It's not like I'm asking much.
>
>Nathan Pinno
>----- Original Message -----
>From: <mailto:bgailer at alum.rpi.edu>bob
>To: <mailto:falcon3166 at hotmail.com>Nathan Pinno
>Cc: <mailto:tutor at python.org>tutor at python.org
>Sent: Thursday, September 22, 2005 10:08 PM
>Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
>
>At 06:42 PM 9/22/2005, Nathan Pinno wrote:
>>The URL is 
>><http://zoffee.tripod.com/purchasecomprogs.htm>http://zoffee.tripod.com/purchasecomprogs.htm
>
>[snip]
>
>At your invitation I visited the site. I personally would not purchase 
>anything listed there due to insufficient information. I don't know what 
>I'm getting!
>
>I suggest you dedicate a page to each program with at least one screenshot 
>and explanation of what the program does.
>
>_______________________________________________
>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/20050926/3cddef7b/attachment.htm

From falcon3166 at hotmail.com  Mon Sep 26 19:56:49 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Mon, 26 Sep 2005 11:56:49 -0600
Subject: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
	<432B8CA9.2000200@christianfreebies.com>
	<BAY106-DAV159F309A389BF7EECD88A1C4970@phx.gbl>
	<be4fbf92050922042136464a41@mail.gmail.com>
	<BAY106-DAV12C80622184DA4A10D6CFBC4960@phx.gbl>
	<6.1.2.0.0.20050922210541.02814178@mail.mric.net>
	<BAY106-DAV92E734F3D5CD2E5A714D5C48B0@phx.gbl>
	<6.1.2.0.0.20050926105329.03561a00@mail.mric.net>
Message-ID: <BAY106-DAV13043F506FC9ABC94A169EC48B0@phx.gbl>

The actual URL is http://zoffee.tripod.com/purchasecompprogs.htm 
  ----- Original Message ----- 
  From: bob 
  To: Nathan Pinno 
  Cc: tutor at python.org 
  Sent: Monday, September 26, 2005 11:54 AM
  Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]


  At 10:34 AM 9/26/2005, Nathan Pinno wrote:

    Bob,
     
    I did what you suggested. Take another look, and tell me if you were a potential customer, would you purchase something?

   I tried http://zoffee.tripod.com/purchasecompprogs.htm I got "Sorry but the page ... is not here." 
   
  Sorry, but the page or the file that you're looking for is not here.




    Why not take the challenge? It's not like I'm asking much.
     
    Nathan Pinno

      ----- Original Message ----- 

      From: bob 

      To: Nathan Pinno 

      Cc: tutor at python.org 

      Sent: Thursday, September 22, 2005 10:08 PM

      Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]


      At 06:42 PM 9/22/2005, Nathan Pinno wrote:

        The URL is http://zoffee.tripod.com/purchasecomprogs.htm


      [snip]


      At your invitation I visited the site. I personally would not purchase anything listed there due to insufficient information. I don't know what I'm getting!


      I suggest you dedicate a page to each program with at least one screenshot and explanation of what the program does. 


    _______________________________________________
    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/20050926/94e6874b/attachment.html

From dyoo at hkn.eecs.berkeley.edu  Mon Sep 26 19:58:52 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 26 Sep 2005 10:58:52 -0700 (PDT)
Subject: [Tutor] printing an acronym (fwd)
Message-ID: <Pine.LNX.4.44.0509261058470.15723-100000@hkn.eecs.berkeley.edu>

Forwarding to tutor

---------- Forwarded message ----------
Date: Mon, 26 Sep 2005 08:32:02 -0500
From: Jason Massey <jason.massey at gmail.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] printing an acronym

Something like this:

def acro(a):
... 	b = a.split()
... 	c = ""
... 	for d in b:
... 		c+=d[0].upper()
... 	return c

other than the horrible variable naming, it works.

>>> acro('international business machines')
'IBM'

On 9/25/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
> On Sat, 24 Sep 2005 andrade1 at umbc.edu wrote:
>
> > How could I get the following to print out an acronym for each phrase
> > entered such as if I entered random access memory it word print out RAM?
>
>
> Hello,
>
> Just out of curiosity, are you already familiar with Python's "lists"?
>
> If so, then you might want to try the slightly easier problem of pulling
> out acronyms out of a list of words.  Extracting an acronym out of a list
> like:
>
>     ["International", "Business", "Machines"]
>
>     ==> "IBM"
>
> is not too bad, and is one step toward doing the original problem on the
> phrase "International Business Machines".
>
>
> Tutorials like:
>
>     http://www.freenetpages.co.uk/hp/alan.gauld/tutseq2.htm
>
> and the other tutorials on:
>
>     http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
>
> should talk about lists.  Please feel free to ask questions here!
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


From ajschmidt at fredericksburg.com  Mon Sep 26 20:10:54 2005
From: ajschmidt at fredericksburg.com (Allen John Schmidt, Jr.)
Date: Mon, 26 Sep 2005 14:10:54 -0400
Subject: [Tutor] printing an acronym (fwd)
In-Reply-To: <Pine.LNX.4.44.0509261058470.15723-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509261058470.15723-100000@hkn.eecs.berkeley.edu>
Message-ID: <433839AE.5030604@fredericksburg.com>

Or a shorter version,

a=lambda n: "".join([x[0].upper() for x in n.split()])

Then it is just:

>>> a('random access memory')
'RAM'





Danny Yoo wrote:

>Forwarding to tutor
>
>---------- Forwarded message ----------
>Date: Mon, 26 Sep 2005 08:32:02 -0500
>From: Jason Massey <jason.massey at gmail.com>
>To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
>Subject: Re: [Tutor] printing an acronym
>
>Something like this:
>
>def acro(a):
>... 	b = a.split()
>... 	c = ""
>... 	for d in b:
>... 		c+=d[0].upper()
>... 	return c
>
>other than the horrible variable naming, it works.
>
>  
>
>>>>acro('international business machines')
>>>>        
>>>>
>'IBM'
>
>On 9/25/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>  
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050926/abe7dfda/attachment.htm

From dyoo at hkn.eecs.berkeley.edu  Mon Sep 26 20:26:57 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 26 Sep 2005 11:26:57 -0700 (PDT)
Subject: [Tutor] help getting acronym to print?
In-Reply-To: <4337375D.5030304@h-lab.net>
Message-ID: <Pine.LNX.4.44.0509261116240.15723-100000@hkn.eecs.berkeley.edu>


> > How could I get the following program to output UDP from the user
> > entering user datagram protcol or IP if internet protocla was entered?

Wait a second.  This looks exactly like this question from just a day ago:

    http://mail.python.org/pipermail/tutor/2005-September/041639.html

The acronym question you are asking are pretty much a classic homework
exercise.  I was really hoping the others on the list would be more
careful about giving help, but the damage is done anyway.

If this is coincidence, it certainly looks bad anyway, since it shows
you're not doing much work in looking for answers.  If you are doing
homework, pleas don't ask the Tutor list to do it for you.  See:

    http://www.catb.org/~esr/faqs/smart-questions.html

Thanks.


From davholla2002 at yahoo.co.uk  Mon Sep 26 23:13:37 2005
From: davholla2002 at yahoo.co.uk (David Holland)
Date: Mon, 26 Sep 2005 22:13:37 +0100 (BST)
Subject: [Tutor] Tutor Digest, Vol 19, Issue 66
In-Reply-To: <mailman.2217.1127415482.508.tutor@python.org>
Message-ID: <20050926211337.62565.qmail@web25906.mail.ukl.yahoo.com>


--- tutor-request at python.org wrote:

> Send Tutor mailing list submissions to
> 	tutor at python.org
> 
> To subscribe or unsubscribe via the World Wide Web,
> visit
> 	http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body
> 'help' to
> 	tutor-request at python.org
> 
> You can reach the person managing the list at
> 	tutor-owner at python.org
> 
> When replying, please edit your Subject line so it
> is more specific
> than "Re: Contents of Tutor digest..."
> 
> 
> Today's Topics:
> 
>    1. USB Capture Image WebCAM (Alberto Troiano)
>    2. Re: time challange (paul brian)
>    3. Re: Python DB (paul brian)
>    4. Re: time challange (nephish)
>    5. PDF (Jorge Ramirez)
>    6. Re: USB Capture Image WebCAM (Danny Yoo)
>    7. Re: Python DB (Danny Yoo)
>    8. Re: Challenge [was Re: Why won't it enter the
> quiz?]
>       (Nathan Pinno)
> 
> 
>
----------------------------------------------------------------------
> 
> Message: 1
> Date: Thu, 22 Sep 2005 16:17:07 +0000
> From: "Alberto Troiano" <albertito_g at hotmail.com>
> Subject: [Tutor] USB Capture Image WebCAM
> To: tutor at python.org
> Message-ID:
> <BAY106-F150BCD67CD6913ED248B8989970 at phx.gbl>
> Content-Type: text/plain; charset=iso-8859-1;
> format=flowed
> 
> Hey Tutors
> 
> I want to make a program that looks like Conquer Cam
> 
> For those who doesn't know what is it its a program
> that captures images 
> from your USB WebCAM and saves them to send via FTP.
> 
> Anyway, getting to the point I don't know how to get
> the video from the 
> camara to watch it inside a GUI made in Python.
> 
> Is this possible?
> How?
> 
> One step at the time..First I want to accomplish the
> online viewer of the 
> camera and then talk about capturing the image
> 
> I'm using Python 2.3.4 over Windows XP Professional
> 
> Thanks in advanced
> 
> Alberto
> 
> 
> 
Have you thought about doing this on the light side ?
I know this is a bit late but no one else has
suggested it.  To be honest, if you are doing this for
security, Linux would be better for security
reasons.http://www.zoneminder.com/



	
	
		
___________________________________________________________ 
Does your mail provider give you access to messages sent to other POP email accounts, like your work account? 
Get Yahoo! Mail http://uk.mail.yahoo.com

From adam.jtm30 at gmail.com  Mon Sep 26 23:37:08 2005
From: adam.jtm30 at gmail.com (Adam)
Date: Mon, 26 Sep 2005 23:37:08 +0200
Subject: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
In-Reply-To: <BAY106-DAV13043F506FC9ABC94A169EC48B0@phx.gbl>
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
	<432B8CA9.2000200@christianfreebies.com>
	<BAY106-DAV159F309A389BF7EECD88A1C4970@phx.gbl>
	<be4fbf92050922042136464a41@mail.gmail.com>
	<BAY106-DAV12C80622184DA4A10D6CFBC4960@phx.gbl>
	<6.1.2.0.0.20050922210541.02814178@mail.mric.net>
	<BAY106-DAV92E734F3D5CD2E5A714D5C48B0@phx.gbl>
	<6.1.2.0.0.20050926105329.03561a00@mail.mric.net>
	<BAY106-DAV13043F506FC9ABC94A169EC48B0@phx.gbl>
Message-ID: <be4fbf9205092614376e97af4e@mail.gmail.com>

Can I have a look at the password program by any chance?



> 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/20050926/846173d9/attachment.html

From amonroe at columbus.rr.com  Mon Sep 26 23:51:24 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Mon, 26 Sep 2005 17:51:24 -0400
Subject: [Tutor] script question
In-Reply-To: <9f68812f05092604563052918f@mail.gmail.com>
References: <9f68812f05092604563052918f@mail.gmail.com>
Message-ID: <78785155253.20050926175124@columbus.rr.com>


> for i in passwordlist:
>   if i == port:
>     os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] + " " +
>        sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])

If you don't have duplicates in your list, a "break" after the
os.system line might help, because once you've found what you're
looking for you can skip the rest.


> I'd like to know if there is a more efficient way to do this and if there is
> a way to have these functions performed with the least amount of time
> possible (the ini file could grow quite large).

If you wanted to get tricky you could do things like sort the list and
do a binary search on it instead of a linear search.

Alan


From kent37 at tds.net  Tue Sep 27 00:54:57 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 26 Sep 2005 18:54:57 -0400
Subject: [Tutor] script question
In-Reply-To: <9f68812f05092604563052918f@mail.gmail.com>
References: <9f68812f05092604563052918f@mail.gmail.com>
Message-ID: <43387C41.20307@tds.net>

Chris Hallman wrote:
> Here is the script:
> 
> import ConfigParser, string, sys
> section = sys.argv[1]
> port = sys.argv[3]
> INI=ConfigParser.ConfigParser()
> INI.read("interfaces.ini")
> passwordentries=[p for p in INI.options(section)]
> passwordlist=[INI.get(section, pw) for pw in passwordentries]
> print passwordlist
> for i in passwordlist:
>     if i == port:
>         os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] + 
> " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])
> 
> 
> I'd like to know if there is a more efficient way to do this and if 
> there is a way to have these functions performed with the least amount 
> of time possible (the ini file could grow quite large).

*TEST FIRST* Don't optimize until you know it is too slow and you have a test case that you can time to see if your 'optimizations' are making it faster.

That said...
RawConfigParser should be faster than ConfigParser because it doesn't try to interpolate into the values.

RawConfigParser is built on Python dicts which are very fast, and the parsing is pretty simple so that should be fast too. It does copy sections before giving you the items so that could be a performance hit.

Since it appears that all you really need to know is if a particular section has a particular value, you might be able to write a simple line-by-line file scanner to figure it out. That might be faster than ConfigParser - you don't have to build the dicts, and you can stop when you find the section of interest.

BUT, again, try it first! Python is pretty fast for this kind of stuff. How many entries do you expect to have? How fast does it have to be?

Kent


From bgailer at alum.rpi.edu  Tue Sep 27 00:47:56 2005
From: bgailer at alum.rpi.edu (bob)
Date: Mon, 26 Sep 2005 15:47:56 -0700
Subject: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
In-Reply-To: <BAY106-DAV13043F506FC9ABC94A169EC48B0@phx.gbl>
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
	<432B8CA9.2000200@christianfreebies.com>
	<BAY106-DAV159F309A389BF7EECD88A1C4970@phx.gbl>
	<be4fbf92050922042136464a41@mail.gmail.com>
	<BAY106-DAV12C80622184DA4A10D6CFBC4960@phx.gbl>
	<6.1.2.0.0.20050922210541.02814178@mail.mric.net>
	<BAY106-DAV92E734F3D5CD2E5A714D5C48B0@phx.gbl>
	<6.1.2.0.0.20050926105329.03561a00@mail.mric.net>
	<BAY106-DAV13043F506FC9ABC94A169EC48B0@phx.gbl>
Message-ID: <6.1.2.0.0.20050926153531.035601e0@mail.mric.net>

At 10:56 AM 9/26/2005, Nathan Pinno wrote:
>The actual URL is 
><http://zoffee.tripod.com/purchasecompprogs.htm>http://zoffee.tripod.com/purchasecompprogs.htm 
>
>>I did what you suggested. Take another look, and tell me if you were a 
>>potential customer, would you purchase something?

No. For one thing I can (if I didn't already have one) buy a "real" 
calculator for $1.00. Also my WIndows op sys comes with a calculator with 
much more capabilities.

Also, seeing your screenshots leads me to suspect that the programs are 
character mode rather than providing a GUI.  This would be a turn off to 
most computer users.

One marketing clue - tell me how the program will benefit me. All I see is 
that it will take more work to do a calculation than using a "real" 
calculator. I think there is no benefit.

I say these things not to discourage you but to encourage you to find ways 
to give customers something they need/want and can't get some other way or 
as nice or as cheap or as fun or .... IOW if I'm to spend $10 I want some 
real benefit.

Think about why McDonald's is successful. Why people will spend $ for food 
that is not outstandingly good.

How do you find an equivalent benefit for software users?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050926/980f24c8/attachment.htm

From kent37 at tds.net  Tue Sep 27 04:03:47 2005
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 26 Sep 2005 22:03:47 -0400
Subject: [Tutor] script question
In-Reply-To: <43387C41.20307@tds.net>
References: <9f68812f05092604563052918f@mail.gmail.com>
	<43387C41.20307@tds.net>
Message-ID: <4338A883.7020001@tds.net>

Kent Johnson wrote:
> *TEST FIRST* Don't optimize until you know it is too slow and you
> have a test case that you can time to see if your 'optimizations' are
> making it faster.

Pardon my shouting :-)

Kent


From sanju_nic at yahoo.com  Tue Sep 27 06:51:27 2005
From: sanju_nic at yahoo.com (sanjay sinha)
Date: Mon, 26 Sep 2005 21:51:27 -0700 (PDT)
Subject: [Tutor] Tutor Digest, Vol 19, Issue 82
In-Reply-To: <mailman.2666.1127756098.508.tutor@python.org>
Message-ID: <20050927045127.48436.qmail@web60313.mail.yahoo.com>

Hi
I am sanju sinha just started python from the last one month . I have gone through all basic programming of with python and also use Tkinter for window . I want to know from you all experience person in python that weather i move to wx or tkinter is sufficient for GUI programming.
thank you
sanju

tutor-request at python.org wrote:
Send Tutor mailing list submissions to
tutor at python.org

To subscribe or unsubscribe via the World Wide Web, visit
http://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
tutor-request at python.org

You can reach the person managing the list at
tutor-owner at python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."


Today's Topics:

1. Re: Problem with BeautifulSoup (Kent Johnson)
2. wxPython problem (?yvind)
3. script question (Chris Hallman)
4. Re: script question (Kent Johnson)
5. Re: wxPython problem (Franz Steinh?usler)
6. Re: wxPython problem (?yvind)
7. Re: script question (Christopher Arndt)
8. Re: wxPython problem (Franz Steinh?usler)
9. Re: Challenge [was Re: Why won't it enter the quiz?]
(Nathan Pinno)


----------------------------------------------------------------------

Message: 1
Date: Mon, 26 Sep 2005 06:09:07 -0400
From: Kent Johnson 
Subject: Re: [Tutor] Problem with BeautifulSoup
Cc: Python Tutor list 
Message-ID: <4337C8C3.5020701 at tds.net>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Bernard Lebel wrote:
> Hi grouchy,
> 
> I seem to have found the problem. Somehow, it seems BeautifulSoup
> doesn't like nested tags of the same name.

This seems to be a feature of BS. It seems a bit of a misfeature when applied to XML but anyway...you can configure BS with a set of tags which can be nested, then it will properly parse your data. Here is a short program that shows how:

xml = '''



1



'''

import BeautifulSoup

class NestingParser(BeautifulSoup.BeautifulStoneSoup):
NESTABLE_TAGS = BeautifulSoup.buildTagMap([], 'parameter')

soup = NestingParser(xml)
print soup.prettify()


Kent



------------------------------

Message: 2
Date: Mon, 26 Sep 2005 13:41:32 +0200 (CEST)
From: ?yvind 

Subject: [Tutor] wxPython problem
To: tutor at python.org
Message-ID: <38850.193.71.38.142.1127734892.squirrel at mail.sporck.net>
Content-Type: text/plain;charset=iso-8859-1

Hello.

I have been reading the
http://wiki.wxpython.org/index.cgi/Getting_20Started manual and are
running the program there. (Enclosed below).

When I run it, it works fine. But, when I run it again, I get the error
PyNoAppError: The wx.App object must be created first! I assume I have
killed the object and have to create it again. But how would I do that?
reload(MainWindow) does not work. Any suggestions?

Thanks in advance.


-----
import os
import wx
ID_ABOUT=101
ID_EXIT=110
class MainWindow(wx.Frame):
def __init__(self,parent,id,title):
wx.Frame.__init__(self,parent,wx.ID_ANY, title, size = ( 200,100),

style=wx.DEFAULT_FRAME_STYLE|
wx.NO_FULL_REPAINT_ON_RESIZE)
self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
self.CreateStatusBar() # A StatusBar in the bottom of the window
# Setting up the menu.
filemenu= wx.Menu()
filemenu.Append(ID_ABOUT, "&About"," Information about this program")
filemenu.AppendSeparator()
filemenu.Append(ID_EXIT,"E&xit"," Terminate the program")
# Creating the menubar.
menuBar = wx.MenuBar()
menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the
MenuBar
self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content.
wx.EVT_MENU(self, ID_ABOUT, self.OnAbout) # attach the menu-event
ID_ABOUT to the
# method
self.OnAbout
wx.EVT_MENU(self, ID_EXIT, self.OnExit) # attach the menu-event
ID_EXIT to the
# method
self.OnExit
self.Show(True)
def OnAbout(self,e):
d= wx.MessageDialog( self, " A sample editor \n"
" in wxPython","About Sample Editor", wx.OK)
# Create a message dialog box
d.ShowModal() # Shows it
d.Destroy() # finally destroy it when finished.
def OnExit(self,e):
self.Close(True) # Close the frame.
app = wx.PySimpleApp()
frame = MainWindow(None, -1, "Sample editor")
app.MainLoop()

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



------------------------------

Message: 3
Date: Mon, 26 Sep 2005 07:56:32 -0400
From: Chris Hallman 
Subject: [Tutor] script question
To: tutor at python.org
Message-ID: <9f68812f05092604563052918f at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

I needed a script that takes command line arguments, searches an ini file
for a match to the arguments and then executes a Windows executable. This is
my first script using python so I wanted to make sure I made the most of the
language. I took bits and pieces from different tutorials and examples
online. The script is executed in this manner:


python search_interface.py device interface interface_name "is down -
00:00:00 01/01/06"


Here is the script:

import ConfigParser, string, sys
section = sys.argv[1]
port = sys.argv[3]
INI=ConfigParser.ConfigParser()
INI.read("interfaces.ini")
passwordentries=[p for p in INI.options(section)]
passwordlist=[INI.get(section, pw) for pw in passwordentries]
print passwordlist
for i in passwordlist:
if i == port:
os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] + " " +
sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])


I'd like to know if there is a more efficient way to do this and if there is
a way to have these functions performed with the least amount of time
possible (the ini file could grow quite large).



Thanks!!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050926/42fb29b6/attachment-0001.htm

------------------------------

Message: 4
Date: Mon, 26 Sep 2005 08:13:38 -0400
From: Kent Johnson 
Subject: Re: [Tutor] script question
Cc: tutor at python.org
Message-ID: <4337E5F2.2050807 at tds.net>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Chris Hallman wrote:
> The script is executed in this 
> manner:
> 
> python search_interface.py device interface interface_name "is down - 
> 00:00:00 01/01/06"
> 
> Here is the script:
> 
> import ConfigParser, string, sys
> section = sys.argv[1]
> port = sys.argv[3]
> INI=ConfigParser.ConfigParser()

Generally all caps names are used for constants, it would be more idiomatic to use ini.

> INI.read("interfaces.ini")
> passwordentries=[p for p in INI.options(section)]

This could just be 
passwordentries = INI.options(section), which is already a list. But even better, see below...

> passwordlist=[INI.get(section, pw) for pw in passwordentries]

The above two lines can be replaced with
passwordlist = [value for name, value in INI.items(section)]
which just accesses the section once.

Kent

> print passwordlist
> for i in passwordlist:
> if i == port:
> os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] + 
> " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])
> 
> 
> I'd like to know if there is a more efficient way to do this and if 
> there is a way to have these functions performed with the least amount 
> of time possible (the ini file could grow quite large).
> 
> 
> 
> Thanks!!
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



------------------------------

Message: 5
Date: Mon, 26 Sep 2005 14:04:39 +0200
From: Franz Steinh?usler 
Subject: Re: [Tutor] wxPython problem
To: tutor at python.org
Message-ID: 
Content-Type: text/plain; charset=ISO-8859-1

On Mon, 26 Sep 2005 13:41:32 +0200 (CEST), ?yvind 
wrote:

>Hello.
>
>I have been reading the
>http://wiki.wxpython.org/index.cgi/Getting_20Started manual and are
>running the program there. (Enclosed below).
>
>When I run it, it works fine. But, when I run it again, I get the error
>PyNoAppError: The wx.App object must be created first! I assume I have
>killed the object and have to create it again. But how would I do that?
>reload(MainWindow) does not work. Any suggestions?
>
>Thanks in advance.


Hi,

Windows? Linux? wxPyVersion?

This sounds familiar to me, but I can't
remember exactly.

how do you run it?
in command prompt?
from a python shell (Idle, Pycrust)?

--
Franz Steinhaeusler



------------------------------

Message: 6
Date: Mon, 26 Sep 2005 14:32:53 +0200 (CEST)
From: ?yvind 

Subject: Re: [Tutor] wxPython problem
To: tutor at python.org
Message-ID: <13974.193.71.38.142.1127737973.squirrel at mail.sporck.net>
Content-Type: text/plain;charset=iso-8859-1

Sorry... Forgot all about that.

Using WinXP, ActiveState Python 2.3 and wx-version 2.6.1.0.

I run it in ActiveStates Interactive Window, which is IDLE (I think).

Thanks in advance







<--

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



------------------------------

Message: 7
Date: Mon, 26 Sep 2005 13:56:25 +0100
From: Christopher Arndt 
Subject: Re: [Tutor] script question
To: Tutor at python.org
Message-ID: <4337EFF9.6030604 at web.de>
Content-Type: text/plain; charset=ISO-8859-1

Chris Hallman schrieb:
> for i in passwordlist:
> if i == port:
> os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] +
> " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])

1) The last line can be also expressed as:

os.system(r"d:\tnd\bin\cawto.exe -cat NetNet %s" % (" ".join(sys.argv[1:5]),))

sys.argv is a list of strings (from which we're only using elements 1-4), which
you can concatenate with the join() method of strings. Then use the '%' string
operator to add it to the command string.

If your command line arguments might contain spaces, you should quote them like
this:

os.system(r"d:\tnd\bin\cawto.exe -cat NetNet %s" % (" ".join(['"%s"' % x for x
in sys.argv[1:5]]),))

You'll find more information about these methods and operators in the standard
library docs section 2.3.

2) I also used a raw string (r'') to avoid having to use double backslashes in
windows paths all the time.

3) Assuming that sys.argv[3] (port) will only match one password in
passwordlist, you can also shorten the for/if construction to:

if port in passwordlist:
os.system(...)

because you're not actually using any of the information from the ini file in
your command line.

4) As to your question regarding efficiency of the script, unfortunately the
ConfigParser module parses the whole INI file unconditionally. You could look
for other third-party configuration file parsers that might do this more
efficiently, but I can not help you there. Start looking a the Cheese shop
(www.python.org/pypi)

Chris


------------------------------

Message: 8
Date: Mon, 26 Sep 2005 14:57:35 +0200
From: Franz Steinh?usler 
Subject: Re: [Tutor] wxPython problem
To: tutor at python.org
Message-ID: 
Content-Type: text/plain; charset=ISO-8859-1

On Mon, 26 Sep 2005 14:32:53 +0200 (CEST), ?yvind 
wrote:

>Sorry... Forgot all about that.
>
>Using WinXP, ActiveState Python 2.3 and wx-version 2.6.1.0.
>
>I run it in ActiveStates Interactive Window, which is IDLE (I think).
>
>Thanks in advance
>
>

Aha, I thought something similar.

It is always a problem to run 2 different 
or competing GUI's the same time.

IDLE with wxPython or Active State Python (they
use the win32 extensions)

The best possibility is to use an IDE, which fits
to the GUI.

Pycrust as shell,
Editor and IDE's: DrPython, spe, Boa Constructor,...
or simply use SciTE as editor and with F5, you can
start your typed in Program and on the right you
have an output pane (With DrPython, you have these
possibilities and many more).

--
Franz Steinhaeusler



------------------------------

Message: 9
Date: Mon, 26 Sep 2005 11:34:46 -0600
From: "Nathan Pinno" 
Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
To: "bob" 
Cc: tutor at python.org
Message-ID: 
Content-Type: text/plain; charset="iso-8859-1"

Bob,

I did what you suggested. Take another look, and tell me if you were a potential customer, would you purchase something?

Why not take the challenge? It's not like I'm asking much.

Nathan Pinno
----- Original Message ----- 
From: bob 
To: Nathan Pinno 
Cc: tutor at python.org 
Sent: Thursday, September 22, 2005 10:08 PM
Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]


At 06:42 PM 9/22/2005, Nathan Pinno wrote:

The URL is http://zoffee.tripod.com/purchasecomprogs.htm

[snip]

At your invitation I visited the site. I personally would not purchase anything listed there due to insufficient information. I don't know what I'm getting!

I suggest you dedicate a page to each program with at least one screenshot and explanation of what the program does. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050926/137d647c/attachment.html

------------------------------

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


End of Tutor Digest, Vol 19, Issue 82
*************************************

		
---------------------------------
Yahoo! for Good
 Click here to donate to the Hurricane Katrina relief effort. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050926/973c4c57/attachment.htm

From sanju_nic at yahoo.com  Tue Sep 27 06:51:52 2005
From: sanju_nic at yahoo.com (sanjay sinha)
Date: Mon, 26 Sep 2005 21:51:52 -0700 (PDT)
Subject: [Tutor] Tutor Digest, Vol 19, Issue 82
In-Reply-To: <mailman.2666.1127756098.508.tutor@python.org>
Message-ID: <20050927045152.28664.qmail@web60312.mail.yahoo.com>

Hi
I am sanju sinha just started python from the last one month . I have gone through all basic programming of with python and also use Tkinter for window . I want to know from you all experience person in python that weather i move to wx or tkinter is sufficient for GUI programming.
thank you
sanju

tutor-request at python.org wrote:
Send Tutor mailing list submissions to
tutor at python.org

To subscribe or unsubscribe via the World Wide Web, visit
http://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
tutor-request at python.org

You can reach the person managing the list at
tutor-owner at python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."


Today's Topics:

1. Re: Problem with BeautifulSoup (Kent Johnson)
2. wxPython problem (?yvind)
3. script question (Chris Hallman)
4. Re: script question (Kent Johnson)
5. Re: wxPython problem (Franz Steinh?usler)
6. Re: wxPython problem (?yvind)
7. Re: script question (Christopher Arndt)
8. Re: wxPython problem (Franz Steinh?usler)
9. Re: Challenge [was Re: Why won't it enter the quiz?]
(Nathan Pinno)


----------------------------------------------------------------------

Message: 1
Date: Mon, 26 Sep 2005 06:09:07 -0400
From: Kent Johnson 
Subject: Re: [Tutor] Problem with BeautifulSoup
Cc: Python Tutor list 
Message-ID: <4337C8C3.5020701 at tds.net>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Bernard Lebel wrote:
> Hi grouchy,
> 
> I seem to have found the problem. Somehow, it seems BeautifulSoup
> doesn't like nested tags of the same name.

This seems to be a feature of BS. It seems a bit of a misfeature when applied to XML but anyway...you can configure BS with a set of tags which can be nested, then it will properly parse your data. Here is a short program that shows how:

xml = '''



1



'''

import BeautifulSoup

class NestingParser(BeautifulSoup.BeautifulStoneSoup):
NESTABLE_TAGS = BeautifulSoup.buildTagMap([], 'parameter')

soup = NestingParser(xml)
print soup.prettify()


Kent



------------------------------

Message: 2
Date: Mon, 26 Sep 2005 13:41:32 +0200 (CEST)
From: ?yvind 

Subject: [Tutor] wxPython problem
To: tutor at python.org
Message-ID: <38850.193.71.38.142.1127734892.squirrel at mail.sporck.net>
Content-Type: text/plain;charset=iso-8859-1

Hello.

I have been reading the
http://wiki.wxpython.org/index.cgi/Getting_20Started manual and are
running the program there. (Enclosed below).

When I run it, it works fine. But, when I run it again, I get the error
PyNoAppError: The wx.App object must be created first! I assume I have
killed the object and have to create it again. But how would I do that?
reload(MainWindow) does not work. Any suggestions?

Thanks in advance.


-----
import os
import wx
ID_ABOUT=101
ID_EXIT=110
class MainWindow(wx.Frame):
def __init__(self,parent,id,title):
wx.Frame.__init__(self,parent,wx.ID_ANY, title, size = ( 200,100),

style=wx.DEFAULT_FRAME_STYLE|
wx.NO_FULL_REPAINT_ON_RESIZE)
self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
self.CreateStatusBar() # A StatusBar in the bottom of the window
# Setting up the menu.
filemenu= wx.Menu()
filemenu.Append(ID_ABOUT, "&About"," Information about this program")
filemenu.AppendSeparator()
filemenu.Append(ID_EXIT,"E&xit"," Terminate the program")
# Creating the menubar.
menuBar = wx.MenuBar()
menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the
MenuBar
self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content.
wx.EVT_MENU(self, ID_ABOUT, self.OnAbout) # attach the menu-event
ID_ABOUT to the
# method
self.OnAbout
wx.EVT_MENU(self, ID_EXIT, self.OnExit) # attach the menu-event
ID_EXIT to the
# method
self.OnExit
self.Show(True)
def OnAbout(self,e):
d= wx.MessageDialog( self, " A sample editor \n"
" in wxPython","About Sample Editor", wx.OK)
# Create a message dialog box
d.ShowModal() # Shows it
d.Destroy() # finally destroy it when finished.
def OnExit(self,e):
self.Close(True) # Close the frame.
app = wx.PySimpleApp()
frame = MainWindow(None, -1, "Sample editor")
app.MainLoop()

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



------------------------------

Message: 3
Date: Mon, 26 Sep 2005 07:56:32 -0400
From: Chris Hallman 
Subject: [Tutor] script question
To: tutor at python.org
Message-ID: <9f68812f05092604563052918f at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

I needed a script that takes command line arguments, searches an ini file
for a match to the arguments and then executes a Windows executable. This is
my first script using python so I wanted to make sure I made the most of the
language. I took bits and pieces from different tutorials and examples
online. The script is executed in this manner:


python search_interface.py device interface interface_name "is down -
00:00:00 01/01/06"


Here is the script:

import ConfigParser, string, sys
section = sys.argv[1]
port = sys.argv[3]
INI=ConfigParser.ConfigParser()
INI.read("interfaces.ini")
passwordentries=[p for p in INI.options(section)]
passwordlist=[INI.get(section, pw) for pw in passwordentries]
print passwordlist
for i in passwordlist:
if i == port:
os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] + " " +
sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])


I'd like to know if there is a more efficient way to do this and if there is
a way to have these functions performed with the least amount of time
possible (the ini file could grow quite large).



Thanks!!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050926/42fb29b6/attachment-0001.htm

------------------------------

Message: 4
Date: Mon, 26 Sep 2005 08:13:38 -0400
From: Kent Johnson 
Subject: Re: [Tutor] script question
Cc: tutor at python.org
Message-ID: <4337E5F2.2050807 at tds.net>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Chris Hallman wrote:
> The script is executed in this 
> manner:
> 
> python search_interface.py device interface interface_name "is down - 
> 00:00:00 01/01/06"
> 
> Here is the script:
> 
> import ConfigParser, string, sys
> section = sys.argv[1]
> port = sys.argv[3]
> INI=ConfigParser.ConfigParser()

Generally all caps names are used for constants, it would be more idiomatic to use ini.

> INI.read("interfaces.ini")
> passwordentries=[p for p in INI.options(section)]

This could just be 
passwordentries = INI.options(section), which is already a list. But even better, see below...

> passwordlist=[INI.get(section, pw) for pw in passwordentries]

The above two lines can be replaced with
passwordlist = [value for name, value in INI.items(section)]
which just accesses the section once.

Kent

> print passwordlist
> for i in passwordlist:
> if i == port:
> os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] + 
> " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])
> 
> 
> I'd like to know if there is a more efficient way to do this and if 
> there is a way to have these functions performed with the least amount 
> of time possible (the ini file could grow quite large).
> 
> 
> 
> Thanks!!
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



------------------------------

Message: 5
Date: Mon, 26 Sep 2005 14:04:39 +0200
From: Franz Steinh?usler 
Subject: Re: [Tutor] wxPython problem
To: tutor at python.org
Message-ID: 
Content-Type: text/plain; charset=ISO-8859-1

On Mon, 26 Sep 2005 13:41:32 +0200 (CEST), ?yvind 
wrote:

>Hello.
>
>I have been reading the
>http://wiki.wxpython.org/index.cgi/Getting_20Started manual and are
>running the program there. (Enclosed below).
>
>When I run it, it works fine. But, when I run it again, I get the error
>PyNoAppError: The wx.App object must be created first! I assume I have
>killed the object and have to create it again. But how would I do that?
>reload(MainWindow) does not work. Any suggestions?
>
>Thanks in advance.


Hi,

Windows? Linux? wxPyVersion?

This sounds familiar to me, but I can't
remember exactly.

how do you run it?
in command prompt?
from a python shell (Idle, Pycrust)?

--
Franz Steinhaeusler



------------------------------

Message: 6
Date: Mon, 26 Sep 2005 14:32:53 +0200 (CEST)
From: ?yvind 

Subject: Re: [Tutor] wxPython problem
To: tutor at python.org
Message-ID: <13974.193.71.38.142.1127737973.squirrel at mail.sporck.net>
Content-Type: text/plain;charset=iso-8859-1

Sorry... Forgot all about that.

Using WinXP, ActiveState Python 2.3 and wx-version 2.6.1.0.

I run it in ActiveStates Interactive Window, which is IDLE (I think).

Thanks in advance







<--

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



------------------------------

Message: 7
Date: Mon, 26 Sep 2005 13:56:25 +0100
From: Christopher Arndt 
Subject: Re: [Tutor] script question
To: Tutor at python.org
Message-ID: <4337EFF9.6030604 at web.de>
Content-Type: text/plain; charset=ISO-8859-1

Chris Hallman schrieb:
> for i in passwordlist:
> if i == port:
> os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] +
> " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])

1) The last line can be also expressed as:

os.system(r"d:\tnd\bin\cawto.exe -cat NetNet %s" % (" ".join(sys.argv[1:5]),))

sys.argv is a list of strings (from which we're only using elements 1-4), which
you can concatenate with the join() method of strings. Then use the '%' string
operator to add it to the command string.

If your command line arguments might contain spaces, you should quote them like
this:

os.system(r"d:\tnd\bin\cawto.exe -cat NetNet %s" % (" ".join(['"%s"' % x for x
in sys.argv[1:5]]),))

You'll find more information about these methods and operators in the standard
library docs section 2.3.

2) I also used a raw string (r'') to avoid having to use double backslashes in
windows paths all the time.

3) Assuming that sys.argv[3] (port) will only match one password in
passwordlist, you can also shorten the for/if construction to:

if port in passwordlist:
os.system(...)

because you're not actually using any of the information from the ini file in
your command line.

4) As to your question regarding efficiency of the script, unfortunately the
ConfigParser module parses the whole INI file unconditionally. You could look
for other third-party configuration file parsers that might do this more
efficiently, but I can not help you there. Start looking a the Cheese shop
(www.python.org/pypi)

Chris


------------------------------

Message: 8
Date: Mon, 26 Sep 2005 14:57:35 +0200
From: Franz Steinh?usler 
Subject: Re: [Tutor] wxPython problem
To: tutor at python.org
Message-ID: 
Content-Type: text/plain; charset=ISO-8859-1

On Mon, 26 Sep 2005 14:32:53 +0200 (CEST), ?yvind 
wrote:

>Sorry... Forgot all about that.
>
>Using WinXP, ActiveState Python 2.3 and wx-version 2.6.1.0.
>
>I run it in ActiveStates Interactive Window, which is IDLE (I think).
>
>Thanks in advance
>
>

Aha, I thought something similar.

It is always a problem to run 2 different 
or competing GUI's the same time.

IDLE with wxPython or Active State Python (they
use the win32 extensions)

The best possibility is to use an IDE, which fits
to the GUI.

Pycrust as shell,
Editor and IDE's: DrPython, spe, Boa Constructor,...
or simply use SciTE as editor and with F5, you can
start your typed in Program and on the right you
have an output pane (With DrPython, you have these
possibilities and many more).

--
Franz Steinhaeusler



------------------------------

Message: 9
Date: Mon, 26 Sep 2005 11:34:46 -0600
From: "Nathan Pinno" 
Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
To: "bob" 
Cc: tutor at python.org
Message-ID: 
Content-Type: text/plain; charset="iso-8859-1"

Bob,

I did what you suggested. Take another look, and tell me if you were a potential customer, would you purchase something?

Why not take the challenge? It's not like I'm asking much.

Nathan Pinno
----- Original Message ----- 
From: bob 
To: Nathan Pinno 
Cc: tutor at python.org 
Sent: Thursday, September 22, 2005 10:08 PM
Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]


At 06:42 PM 9/22/2005, Nathan Pinno wrote:

The URL is http://zoffee.tripod.com/purchasecomprogs.htm

[snip]

At your invitation I visited the site. I personally would not purchase anything listed there due to insufficient information. I don't know what I'm getting!

I suggest you dedicate a page to each program with at least one screenshot and explanation of what the program does. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050926/137d647c/attachment.html

------------------------------

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


End of Tutor Digest, Vol 19, Issue 82
*************************************


		
---------------------------------
Yahoo! for Good
 Click here to donate to the Hurricane Katrina relief effort. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050926/6769b0ba/attachment.html

From winglion1 at 163.com  Tue Sep 27 08:01:43 2005
From: winglion1 at 163.com (=?GB2312?B?zPrKrw==?=)
Date: Tue, 27 Sep 2005 14:01:43 +0800
Subject: [Tutor] encode question!
Message-ID: <20050927060236.4CEF51E4002@bag.python.org>

    I am trying to write a stript that extract jpg files
 from a html I had downloaded.I encounter a problem with
 a Big5 charset html file.Big5 used in Hongkong ans Taiwan.
    In this html file there's a jpg names "xvg_h%202.jpg"
in vi ,the tag of the image is <img src="...../xvg_h%25202.jpg>,
and as python read it out, it was "xvg_h%2525202.jpg".
As I try to test the size of this image,python report that 
file "xvg_h%2525202.jpg" don't  exists.
     I think %25 mean the char "%",the "%2525" was equal to 
the "%25" in html and "%" in the shell listed file name.
I had no idea about this encode! Is the html tag use big5 too?
Why '%' should be code as big5, I think it was a ASCII char before
today!
     So, how can I read this file name correctly!
    

¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡winglion1 at 163.com
¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡2005-09-27


From mwpippin at gmail.com  Tue Sep 27 05:39:47 2005
From: mwpippin at gmail.com (Mike Pippin)
Date: Mon, 26 Sep 2005 23:39:47 -0400
Subject: [Tutor] 2 questions......novice but not beginner
Message-ID: <c1967eb905092620397e2b4f95@mail.gmail.com>

Please HELP...........
 First....
I need to know how to allow the user to search their local drives and
directories in order to load a file...or if there are any pre-written
opensource functions that will also be well appreciated..
Second....
I need to know how to render graphics without the windowed enviroment.....I
know with pygame you can have a windowless enviroment but I need to be able
to have only the graphics i choose displayed on the screen without pygame
filling the rest of the screen with black if thats possible.
 ANY HELP WOULD BE GREATLY APPRECIATED.....thank you in advance to anyone
who can help me!!
 Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050926/5bdfeb91/attachment.htm

From dyoo at hkn.eecs.berkeley.edu  Tue Sep 27 08:58:26 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 26 Sep 2005 23:58:26 -0700 (PDT)
Subject: [Tutor] encode question!
In-Reply-To: <20050927060236.4CEF51E4002@bag.python.org>
Message-ID: <Pine.LNX.4.44.0509262317230.22667-100000@hkn.eecs.berkeley.edu>



On Tue, 27 Sep 2005, [GB2312] Ìúʯ wrote:

>     I am trying to write a stript that extract jpg files
>  from a html I had downloaded.I encounter a problem with
>  a Big5 charset html file.Big5 used in Hongkong ans Taiwan.
>     In this html file there's a jpg names "xvg_h%202.jpg" in vi ,the tag
> of the image is <img src="...../xvg_h%25202.jpg>, and as python read it
> out, it was "xvg_h%2525202.jpg". As I try to test the size of this
> image,python report that file "xvg_h%2525202.jpg" don't exists.

It'll help if you show us your program so far, and point us to an example
file in big5 format.

I do not suspect that an encoding issue's in play here; the file name you
are showing us looks regular enough that there may be some other issue.
There are any number of reasons why programs don't work: I'd rather remove
the ambgiuity by seeing real code.

Let's me check something quickly...

######
>>> import codecs
>>> from StringIO import StringIO
>>> sampleText = "xvg_h%202.jpg"
>>> sampleFile = StringIO(sampleText)
>>> translatedFile = codecs.EncodedFile(sampleFile, "big5")
>>> translatedFile.readline()
'xvg_h%202.jpg'
######

As far as I can tell, the filename that you're showing us, 'xvg_h%202.jpg'
doesn't have characters that trigger an alternative interpretation in
big5.  I'm unfamiliar enought with big5, though, that I could be mistaken.
Please point us to a sample text file with big5, and we can do more
realistic tests on this end.


Let me try another experiment with a big5-encoded file and a third-party
html parser called 'BeautifulSoup':

######
>>> import BeautifulSoup
>>> f = urllib.urlopen('http://chinese.yahoo.com')
>>> soup = BeautifulSoup.BeautifulSoup(f)
>>> images = soup('img')
>>> for img in images:
...     print img['src']
...
http://us.i1.yimg.com/us.yimg.com/i/b5/home/m6v1.gif
http://hk.yimg.com/i/search/mglass.gif
http://us.i1.yimg.com/us.yimg.com/i/hk/new2.gif
http://hk.yimg.com/i/icon/16/3.gif
http://us.i1.yimg.com/us.yimg.com/i/hk/spc.gif
http://hk.yimg.com/i/home/tabbt.gif
http://hk.yimg.com/i/home/tabp.gif
http://hk.yimg.com/i/home/tabp.gif
http://hk.yimg.com/i/home/tabp.gif
######

That looks sorta ok, although I know I'm completely ignoring big5 issues.
*grin*


Give us a file to work on, and we'll see what we can do to help you parse
it.  Good luck!


From zamb at saudi.net.sa  Tue Sep 27 09:08:05 2005
From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY)
Date: Tue, 27 Sep 2005 10:08:05 +0300
Subject: [Tutor] encode question!
In-Reply-To: <20050927060236.4CEF51E4002@bag.python.org>
References: <20050927060236.4CEF51E4002@bag.python.org>
Message-ID: <1127804885.16293.7.camel@localhost.localdomain>

On Tue, 2005-09-27 at 14:01 +0800, ?? wrote: 
>     I am trying to write a stript that extract jpg files
>  from a html I had downloaded.I encounter a problem with
>  a Big5 charset html file.Big5 used in Hongkong ans Taiwan.
>     In this html file there's a jpg names "xvg_h%202.jpg"
> in vi ,the tag of the image is <img src="...../xvg_h%25202.jpg>,
> and as python read it out, it was "xvg_h%2525202.jpg".
> As I try to test the size of this image,python report that 
> file "xvg_h%2525202.jpg" don't  exists.
>      I think %25 mean the char "%",the "%2525" was equal to 
> the "%25" in html and "%" in the shell listed file name.
> I had no idea about this encode! Is the html tag use big5 too?
> Why '%' should be code as big5, I think it was a ASCII char before
> today!
>      So, how can I read this file name correctly!
>     
> 
> ????????winglion1 at 163.com
> ??????????2005-09-27
> 
This has nothing to do with Big5 encoding!  This is how URL are sent in
HTTP requests.  As an example: a space letter " " become "%20".

In your example above your file name is probably named "xvg_h 2.jpg".
So, what's going on?  When you viewed the image in you browser (or the
application you used to download it, even if you were using Python
scrip) the request was something like:
        http://server.domain.tld/dir1/dir2/xvg_h%202.jpg
which translate to "xvg_h 2.jpg" which is right.  However, when you
saved the HTML file along with the image, the application interpreted
the "%20" as the character "percent sign" followed by the characters
"20".  It also encoded them as such (just like when sending HTTP
requests) and that resulted in "xvg_h%25202.jpg"!

How to fix this?  Use "unquote()" from the "urllib" module twice!

Here:
        >>> urllib.unquote(urllib.unquote('xvg_h%25202.jpg'))
        'xvg_h 2.jpg'

I hope this is the right explanation and that it will work for you.  If
anyone have a better opinion please don't be shy and help us all.
Ziyad.


From dyoo at hkn.eecs.berkeley.edu  Tue Sep 27 09:15:31 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 27 Sep 2005 00:15:31 -0700 (PDT)
Subject: [Tutor] 2 questions......novice but not beginner
In-Reply-To: <c1967eb905092620397e2b4f95@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509262358460.22667-100000@hkn.eecs.berkeley.edu>



On Mon, 26 Sep 2005, Mike Pippin wrote:

> I need to know how to allow the user to search their local drives and
> directories in order to load a file...or if there are any pre-written
> opensource functions that will also be well appreciated.. Second....

Hi Mike,

This is not completely obvious to do efficiently: that's what tools like
Google Desktop, Apple's Spotlight, and Microsoft's WinFS are trying to
enable.  If you can tell us what operating system you' re using, we might
be able to point you toward something.

If efficiency doesn't matter, you can brute force a search with os.walk:

    http://www.python.org/doc/lib/os-file-dir.html#l2h-1628

However, it's preferable not to use this as a general-purpose searching
utility, as it's very expensive to walk across a system's directory tree
structure like this: that's why using something OS specific might be a
good idea here.  If you're on Unix, you might even want to take advantage
of something like 'locate' or 'glimpse', which can maintain a quick
searchable index of your computer's files.

Can you limit the scope of the search somehow to a particular set of
directories, or do you have to search your whole hard drive?



> I need to know how to render graphics without the windowed
> enviroment.....I know with pygame you can have a windowless enviroment
> but I need to be able to have only the graphics i choose displayed on
> the screen without pygame filling the rest of the screen with black if
> thats possible.

Out of curiosity, why?  I don't know offhand how to do this, but the
pygame folks might: have you asked them yet?

Could you just capture the screen first, start up pygame, and then draw
the screen-captured image there?  That could provide an illusion of having
the game run on top of the desktop environment.  It's cheap, but it might
work.  *grin*


From lists at janeden.org  Tue Sep 27 12:02:31 2005
From: lists at janeden.org (Jan Eden)
Date: Tue, 27 Sep 2005 12:02:31 +0200
Subject: [Tutor] Simulating case statement
Message-ID: <r02010500-1039-D1E9DE1D2F3D11DAB3B4000A959B4026@[10.149.23.208]>

Hi,

I used to use an extended if...elif sequence to instantiate an object and call this object's display method afterwards:
####
if safe['type'] == pages:
    page = Show.Page(id=safe['id'], start=safe['start'] ...),
elif safe['type'] == pages:
    author = Show.Author(id=safe['id']...)
 ...

page.Display()
#### 

To improve readability, I changed this code to use a dictionary:

####
valid_types = dict(
    pages=Show.Page,
    authors=Show.Author,
    ...
)

page = valid_types[safe_parameters['type']](safe_parameters)
page.Display()
####

The problem is that the __init__ methods of the respective classes take a different number of parameters - this is why I pass the whole safe_parameters dictionary.

This has a number of drawbacks when instantiating an object in other situations because I cannot use a default for some parameters while passing some others.

So I'd like to do pass the parameters individually, based on the class. I know I would need to expand the valid_types dictionary to include the parameters - but how can I pass these one by one?

What I came up with is a monster (which does not work anyway):

valid_types = dict(
    pages=dict(klasse=Show.Page, parameters=dict(id=safe['id'], start=safe['start'] ...))
    authors=dict(klasse=Show.Author, ...)
    ...
)

page = valid_types[safe_parameters['type']]['klasse'](valid_types['parameters'])

page.Display()

How can I circumvent the if...elif sequence and have the parameters passed individually at the same time?

Thanks for any suggestions,

Jan
-- 
Common sense is what tells you that the world is flat.

From ml.cyresse at gmail.com  Tue Sep 27 12:39:39 2005
From: ml.cyresse at gmail.com (Liam Clarke)
Date: Tue, 27 Sep 2005 22:39:39 +1200
Subject: [Tutor] 2 questions......novice but not beginner
In-Reply-To: <c1967eb905092620397e2b4f95@mail.gmail.com>
References: <c1967eb905092620397e2b4f95@mail.gmail.com>
Message-ID: <b6f3249e0509270339730e1ebb@mail.gmail.com>

> I need to know how to render graphics without the windowed enviroment.....I
> know with pygame you can have a windowless enviroment but I need to be able
> to have only the graphics i choose displayed on the screen without pygame
> filling the rest of the screen with black if thats possible.

I believe to do this in Windows requires usage of the COM interface. I
know it's how
Konfabulator/ObjectDesktop etc. draw their widgets without little windows.

FWIW.

Liam Clarke

From amonroe at columbus.rr.com  Tue Sep 27 12:41:55 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Tue, 27 Sep 2005 06:41:55 -0400
Subject: [Tutor] 2 questions......novice but not beginner
In-Reply-To: <c1967eb905092620397e2b4f95@mail.gmail.com>
References: <c1967eb905092620397e2b4f95@mail.gmail.com>
Message-ID: <168831386140.20050927064155@columbus.rr.com>

> I need to know how to render graphics without the windowed enviroment.....I
> know with pygame you can have a windowless enviroment but I need to be able
> to have only the graphics i choose displayed on the screen without pygame
> filling the rest of the screen with black if thats possible.


Not sure if this is what you mean, but pygame can run within a normal
window (and you choose the size). It doesn't HAVE to be fullscreen. Is
that what you mean?


Alan


From adam.jtm30 at gmail.com  Tue Sep 27 13:31:27 2005
From: adam.jtm30 at gmail.com (Adam)
Date: Tue, 27 Sep 2005 12:31:27 +0100
Subject: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
In-Reply-To: <BAY106-DAV1268A8965F7C65D29A1F76C48A0@phx.gbl>
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV159F309A389BF7EECD88A1C4970@phx.gbl>
	<be4fbf92050922042136464a41@mail.gmail.com>
	<BAY106-DAV12C80622184DA4A10D6CFBC4960@phx.gbl>
	<6.1.2.0.0.20050922210541.02814178@mail.mric.net>
	<BAY106-DAV92E734F3D5CD2E5A714D5C48B0@phx.gbl>
	<6.1.2.0.0.20050926105329.03561a00@mail.mric.net>
	<BAY106-DAV13043F506FC9ABC94A169EC48B0@phx.gbl>
	<be4fbf9205092614376e97af4e@mail.gmail.com>
	<BAY106-DAV1268A8965F7C65D29A1F76C48A0@phx.gbl>
Message-ID: <be4fbf9205092704313ad1a187@mail.gmail.com>

Well Nathan you said you wanted an honest opinion so here goes. All the
program seems to do is create a clear text file that is world readable. I
personally wouldn't even use it if it was free because it would be a lot
easier to use a text editor. Now for improvements that would make it a
worthwhile program. Some sort of encryption would be good along with making
the file readable only to the owner where possible. Also for the majority of
users a GUI would probably be prefereable although I personally have no
problem with command line programs. Oh and don't put the main password in
the source code.

On 27/09/05, Nathan Pinno <falcon3166 at hotmail.com> wrote:
>
> No problem Adam. Glad you decided to take a look and see. Tell the group
> what your honest opinion is after looking at the file.
>
> ----- Original Message -----
> *From:* Adam <adam.jtm30 at gmail.com>
> *To:* Nathan Pinno <falcon3166 at hotmail.com>
> *Cc:* bob <bgailer at alum.rpi.edu> ; tutor at python.org
> *Sent:* Monday, September 26, 2005 3:37 PM
> *Subject:* Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
>
> Can I have a look at the password program by any chance?
>
>
>
> > 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/20050927/1f1f1a4d/attachment.htm

From adam.jtm30 at gmail.com  Tue Sep 27 13:49:00 2005
From: adam.jtm30 at gmail.com (Adam)
Date: Tue, 27 Sep 2005 12:49:00 +0100
Subject: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
In-Reply-To: <be4fbf9205092704313ad1a187@mail.gmail.com>
References: <mailman.1494.1126923682.508.tutor@python.org>
	<be4fbf92050922042136464a41@mail.gmail.com>
	<BAY106-DAV12C80622184DA4A10D6CFBC4960@phx.gbl>
	<6.1.2.0.0.20050922210541.02814178@mail.mric.net>
	<BAY106-DAV92E734F3D5CD2E5A714D5C48B0@phx.gbl>
	<6.1.2.0.0.20050926105329.03561a00@mail.mric.net>
	<BAY106-DAV13043F506FC9ABC94A169EC48B0@phx.gbl>
	<be4fbf9205092614376e97af4e@mail.gmail.com>
	<BAY106-DAV1268A8965F7C65D29A1F76C48A0@phx.gbl>
	<be4fbf9205092704313ad1a187@mail.gmail.com>
Message-ID: <be4fbf9205092704497ab9e379@mail.gmail.com>

There's one more problem as well Nathan. Most if not all of the programs you
have made have been made by other people as well albeit implemented slightly
differently and you could probably get a replacement for any of your
programs for free on sourceforge. If you want to make any serious money
you'll need something more original or just a lot better than the
competition.

On 27/09/05, Nathan Pinno <falcon3166 at hotmail.com> wrote:
> >
> > No problem Adam. Glad you decided to take a look and see. Tell the group
> > what your honest opinion is after looking at the file.
> >
> > ----- Original Message -----
> >  *From:* Adam <adam.jtm30 at gmail.com>
> > *To:* Nathan Pinno <falcon3166 at hotmail.com>
> > *Cc:* bob <bgailer at alum.rpi.edu> ; tutor at python.org
> > *Sent:* Monday, September 26, 2005 3:37 PM
> > *Subject:* Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
> >
> > Can I have a look at the password program by any chance?
> >
> >
> >
> > > 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/20050927/9837fea6/attachment.html

From kent37 at tds.net  Tue Sep 27 13:56:33 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Sep 2005 07:56:33 -0400
Subject: [Tutor] Simulating case statement
In-Reply-To: <r02010500-1039-D1E9DE1D2F3D11DAB3B4000A959B4026@[10.149.23.208]>
References: <r02010500-1039-D1E9DE1D2F3D11DAB3B4000A959B4026@[10.149.23.208]>
Message-ID: <43393371.9010109@tds.net>

Jan Eden wrote:
> Hi,
> 
> I used to use an extended if...elif sequence to instantiate an object and call this object's display method afterwards:
> ####
> if safe['type'] == pages:
>     page = Show.Page(id=safe['id'], start=safe['start'] ...),
> elif safe['type'] == pages:
>     author = Show.Author(id=safe['id']...)
>  ...
> 
> page.Display()
> #### 
> 
> To improve readability, I changed this code to use a dictionary:
> 
> ####
> valid_types = dict(
>     pages=Show.Page,
>     authors=Show.Author,
>     ...
> )
> 
> page = valid_types[safe_parameters['type']](safe_parameters)
> page.Display()
> ####
> 
> The problem is that the __init__ methods of the respective classes
> take a different number of parameters - this is why I pass the whole
> safe_parameters dictionary.

I think if you pass the dictionary as keyword arguments rather than as a single dict you will get what you want.
page = valid_types[safe_parameters['type']](**safe_parameters)

This syntax means, use safe_parameters to populate the keyword arguments of the function. Any parameters which are not in safe_parameters will be set to their default values, and in other calls you can set the parameters as you like. Here is a simple example:

 >>> def f1(id='123', value='abc', **kwds):
 ...   print 'id =', id
 ...   print 'value =', value
 ...
 >>> def f2(id='345', stuff='nonsense', **kwds):
 ...   print 'id =', id
 ...   print 'stuff =', stuff
 ...
 ...
 >>> params = dict(id=3, value='def')
 >>> f1(**params)
id = 3
value = def
 >>> f2(**params)
id = 3
stuff = nonsense
 >>> f1()
id = 123
value = abc
 >>> f1(value=34)
id = 123
value = 34

The **kwds parameter to the function is needed to allow the extra parameters in the passed dictionary. Otherwise you will get a TypeError:

 >>> def f3(id='345', stuff='nonsense'):
 ...   print 'id =', id
 ...   print 'stuff =', stuff
 ...
 >>> f3(**params)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: f3() got an unexpected keyword argument 'value'

Kent

> 
> This has a number of drawbacks when instantiating an object in other
> situations because I cannot use a default for some parameters while
> passing some others.
> 
> So I'd like to do pass the parameters individually, based on the
> class. I know I would need to expand the valid_types dictionary to
> include the parameters - but how can I pass these one by one?> 
> What I came up with is a monster (which does not work anyway):
> 
> valid_types = dict(
>     pages=dict(klasse=Show.Page, parameters=dict(id=safe['id'], start=safe['start'] ...))
>     authors=dict(klasse=Show.Author, ...)
>     ...
> )
> 
> page = valid_types[safe_parameters['type']]['klasse'](valid_types['parameters'])
> 
> page.Display()
> 
> How can I circumvent the if...elif sequence and have the parameters passed individually at the same time?
> 
> Thanks for any suggestions,
> 
> Jan


From lists at janeden.org  Tue Sep 27 14:13:58 2005
From: lists at janeden.org (Jan Eden)
Date: Tue, 27 Sep 2005 14:13:58 +0200
Subject: [Tutor] Simulating case statement
In-Reply-To: <43393371.9010109@tds.net>
Message-ID: <r02010500-1039-2F524DB22F5011DAB3B4000A959B4026@[10.149.23.208]>

Kent Johnson wrote on 27.09.2005:

>Jan Eden wrote:

>>The problem is that the __init__ methods of the respective classes
>>take a different number of parameters - this is why I pass the
>>whole safe_parameters dictionary.
>
>I think if you pass the dictionary as keyword arguments rather than
>as a single dict you will get what you want.

>page =
>valid_types[safe_parameters['type']](**safe_parameters)
>
>This syntax means, use safe_parameters to populate the keyword
>arguments of the function. Any parameters which are not in
>safe_parameters will be set to their default values, and in other
>calls you can set the parameters as you like. Here is a simple
>example:

I see. I did not know that I can use a formal parameter **param in calls - thought I could only do so in function definitions:

def func(**param):
    ...
    
 func(id=1, stuff='blah')
 
 Thanks for that!
 
 Jan
-- 
Mac OS X. Because making Unix user-friendly is easier than debugging Windows.

From winglion1 at 163.com  Tue Sep 27 14:19:30 2005
From: winglion1 at 163.com (=?utf-8?B?6ZOB55+z?=)
Date: Tue, 27 Sep 2005 20:19:30 +0800
Subject: [Tutor] =?utf-8?q?encode_question!?=
Message-ID: <20050927121950.55C671E40A0@bag.python.org>

tutor-request
     Thanks Ziyad.You answer is exactly the realson it is! I am missdirect
by the coding of the html. the %25 in the url is the '%' char in file name.
after  
    urllib.unquote('xvg_h%25202.jpg')
    'xvg_h%202.jpg'
That's the real filename I want!
thanks too, Danny Yoo!

>This has nothing to do with Big5 encoding!  This is how URL are sent in
>HTTP requests.  As an example: a space letter " " become "%20".
>
>In your example above your file name is probably named "xvg_h 2.jpg".
>So, what's going on?  When you viewed the image in you browser (or the
>application you used to download it, even if you were using Python
>scrip) the request was something like:
>        http://server.domain.tld/dir1/dir2/xvg_h%202.jpg
>which translate to "xvg_h 2.jpg" which is right.  However, when you
>saved the HTML file along with the image, the application interpreted
>the "%20" as the character "percent sign" followed by the characters
>"20".  It also encoded them as such (just like when sending HTTP
>requests) and that resulted in "xvg_h%25202.jpg"!
>
>How to fix this?  Use "unquote()" from the "urllib" module twice!
>
>Here:
>        >>> urllib.unquote(urllib.unquote('xvg_h%25202.jpg'))
>        'xvg_h 2.jpg'
>
>I hope this is the right explanation and that it will work for you.  If
>anyone have a better opinion please don't be shy and help us all.
>Ziyad.
>
>

????????winglion1 at 163.com
??????????2005-09-27


From matthew.williams at cancer.org.uk  Tue Sep 27 15:49:17 2005
From: matthew.williams at cancer.org.uk (Matt Williams)
Date: Tue, 27 Sep 2005 14:49:17 +0100
Subject: [Tutor] Linking with C programs
Message-ID: <1127828957.4592.23.camel@localhost.localdomain>

Dear List,

Could someone explain how, in very general terms, one would use python
to wrap some C libraries/ API. 

I ask because there are a few bits of C software that look quite
interesting, and I know that Python can be used to wrap the C - but how
does it work?

Thanks,

Matt


From taloner at gmail.com  Tue Sep 27 16:17:13 2005
From: taloner at gmail.com (the taloner)
Date: Tue, 27 Sep 2005 19:47:13 +0530
Subject: [Tutor] ICMP checksum
Message-ID: <696a3b1c05092707171bd66bec@mail.gmail.com>

Hi list,

I was just playing around with one of the examples given in Python
cook-book. This examples show you how to send data using ICMP packets.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439224

While running the script I encountered a problem which was with the
statement

icmp.set_icmp_cksum(0)

The error encountered was

Traceback (most recent call last):
File "icmpdata.py", line 38, in ?
icmp.set_icmp_chksum(0)
AttributeError: ICMP instance has no attribute 'set_icmp_chksum'


So I did the next logical thing, commented the line in code (which appears
twice). Script ran smoothly and I captured the traffic using tcpdump.
When the script sends first 54 bytes everything is good. When I send a
longer data string, and the script is forced to split the data over multiple
packets I start fasing a problem with checksum.

17:36:36.198543 IP (tos 0x0, ttl 255, id 16951, offset 0, flags [none],
length: 82) 192.168.3.37 <http://192.168.3.37> >
192.168.3.36<http://192.168.3.36>:
icmp 62: echo reply seq 0
0x0000: 0002 3fb9 17fe 000c 299c e8a5 0800 4500 ..?.....).....E.
0x0010: 0052 4237 0000 ff01 f1d9 c0a8 0325 c0a8 .RB7.........%..
0x0020: 0324 0000 bab9 0001 0000 6161 6161 6161 .$........aaaaaa
0x0030: 6161 6161 6161 6161 6161 6161 6161 6161 aaaaaaaaaaaaaaaa
0x0040: 6161 6161 6161 6161 6161 6161 6161 6161 aaaaaaaaaaaaaaaa
0x0050: 6161 6161 6161 6161 6161 6161 6161 6161 aaaaaaaaaaaaaaaa
17:36:37.198470 IP (tos 0x0, ttl 255, id 16952, offset 0, flags [none],
length: 82) 192.168.3.37 <http://192.168.3.37> >
192.168.3.36<http://192.168.3.36>:
icmp 62: echo reply seq 0 (wrong icmp cksum bab9 (->bab8)!)
0x0000: 0002 3fb9 17fe 000c 299c e8a5 0800 4500 ..?.....).....E.
0x0010: 0052 4238 0000 ff01 f1d8 c0a8 0325 c0a8 .RB8.........%..
0x0020: 0324 0000 bab9 0002 0000 6161 6161 6161 .$........aaaaaa
0x0030: 6161 6161 6161 6161 6161 6161 6161 6161 aaaaaaaaaaaaaaaa
0x0040: 6161 6161 6161 6161 6161 6161 6161 6161 aaaaaaaaaaaaaaaa
0x0050: 6161 6161 6161 6161 6161 6161 6161 6161 aaaaaaaaaaaaaaaa

Also as you can see that seq is not increasing as ideally it should have
been as directed by this line:

seq_id = seq_id + 1

Can someone give some light on these issues?

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050927/48657530/attachment.htm

From kent37 at tds.net  Tue Sep 27 16:37:51 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Sep 2005 10:37:51 -0400
Subject: [Tutor] ICMP checksum
In-Reply-To: <696a3b1c05092707171bd66bec@mail.gmail.com>
References: <696a3b1c05092707171bd66bec@mail.gmail.com>
Message-ID: <4339593F.9060105@tds.net>

the taloner wrote:
> Hi list,
> 
> I was just playing  around with one of the examples given in Python 
> cook-book. This examples show you how to send data using ICMP packets.
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439224
> 
> While running the script I encountered a problem which was with the 
> statement
> 
> icmp.set_icmp_cksum(0)
> 
> The error encountered was
> 
> Traceback (most recent call last):
>   File "icmpdata.py", line 38, in ?
>     icmp.set_icmp_chksum(0)
> AttributeError: ICMP instance has no attribute 'set_icmp_chksum'

This recipe uses a package called impacket which is available from
http://oss.coresecurity.com/projects/impacket.html

Looking at the implementation of ICMP in the latest release of ImpactPacket.py, the correct spelling of the method is 'set_icmp_cksum'

Kent

> 
> 
> So I did the next logical thing, commented the line in code (which 
> appears twice). Script ran smoothly and I captured the traffic using 
> tcpdump.
> When the script sends first 54 bytes everything is good. When I send a 
> longer data string, and the script is forced to split the data over 
> multiple packets I start fasing a problem with checksum.

That shouldn't be too surprising if you commented out the line that sets the checksum!

> 
> 17:36:36.198543 IP (tos 0x0, ttl 255, id 16951, offset 0, flags [none], 
> length: 82) 192.168.3.37 <http://192.168.3.37> > 192.168.3.36 
> <http://192.168.3.36>: icmp 62: echo reply seq 0
>         0x0000:  0002 3fb9 17fe 000c 299c e8a5 0800 4500  ..?.....).....E.
>         0x0010:  0052 4237 0000 ff01 f1d9 c0a8 0325 c0a8  .RB7.........%..
>         0x0020:  0324 0000 bab9 0001 0000 6161 6161 6161  .$........aaaaaa
>         0x0030:  6161 6161 6161 6161 6161 6161 6161 6161  aaaaaaaaaaaaaaaa
>         0x0040:  6161 6161 6161 6161 6161 6161 6161 6161  aaaaaaaaaaaaaaaa
>         0x0050:  6161 6161 6161 6161 6161 6161 6161 6161  aaaaaaaaaaaaaaaa
> 17:36:37.198470 IP (tos 0x0, ttl 255, id 16952, offset 0, flags [none], 
> length: 82) 192.168.3.37 <http://192.168.3.37> > 192.168.3.36 
> <http://192.168.3.36>: icmp 62: echo reply seq 0 (wrong icmp cksum bab9 
> (->bab8)!)
>         0x0000:  0002 3fb9 17fe 000c 299c e8a5 0800 4500  ..?.....).....E.
>         0x0010:  0052 4238 0000 ff01 f1d8 c0a8 0325 c0a8  .RB8.........%..
>         0x0020:  0324 0000 bab9 0002 0000 6161 6161 6161  .$........aaaaaa
>         0x0030:  6161 6161 6161 6161 6161 6161 6161 6161  aaaaaaaaaaaaaaaa
>         0x0040:  6161 6161 6161 6161 6161 6161 6161 6161  aaaaaaaaaaaaaaaa
>         0x0050:  6161 6161 6161 6161 6161 6161 6161 6161  aaaaaaaaaaaaaaaa
> 
> Also as you can see that seq is not increasing as ideally it should have 
> been as directed by this line:
> 
> seq_id = seq_id + 1
> 
> Can someone give some light on these issues?
> 
> Thanks
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From ewalker at micron.com  Tue Sep 27 16:41:31 2005
From: ewalker at micron.com (Eric Walker)
Date: Tue, 27 Sep 2005 08:41:31 -0600
Subject: [Tutor] Linking with C programs
In-Reply-To: <1127828957.4592.23.camel@localhost.localdomain>
References: <1127828957.4592.23.camel@localhost.localdomain>
Message-ID: <200509270841.31940.ewalker@micron.com>

There is a program called swig. this generates python interfaces to external 
C/C++ libraries. I never used it as I am a very new python programmer but I 
took the Mark Lutz class and he pushes it.

Python Newbie....


On Tuesday 27 September 2005 07:49 am, Matt Williams wrote:
> Dear List,
>
> Could someone explain how, in very general terms, one would use python
> to wrap some C libraries/ API.
>
> I ask because there are a few bits of C software that look quite
> interesting, and I know that Python can be used to wrap the C - but how
> does it work?
>
> Thanks,
>
> Matt
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Eric Walker
EDA/CAD Engineer

From lopoff at gmx.net  Tue Sep 27 16:56:01 2005
From: lopoff at gmx.net (lmac)
Date: Tue, 27 Sep 2005 16:56:01 +0200
Subject: [Tutor] find data in html file
Message-ID: <43395D81.1090006@gmx.net>

Hi there,
i have a base-question. If i want to read some kind of data out of a line
which i know the start-tag and the end-tag in an html-file how do i 
recognize
if it's more than one line ?

Example:

<td>Some text<a href>link</a>text ..... DATA ....</tr></td> etc.

I would use >text as the starting tag to localize the beginning of the DATA.
And then </tr> as the ending tag of the DATA. But if there is \n then 
there are more than
one line.

I hope i explained it well what i am going for. English is not my native 
language.

Thank you.


From taloner at gmail.com  Tue Sep 27 16:53:44 2005
From: taloner at gmail.com (the taloner)
Date: Tue, 27 Sep 2005 20:23:44 +0530
Subject: [Tutor] ICMP checksum
In-Reply-To: <4339593F.9060105@tds.net>
References: <696a3b1c05092707171bd66bec@mail.gmail.com>
	<4339593F.9060105@tds.net>
Message-ID: <696a3b1c0509270753df4e126@mail.gmail.com>

Thanks Kent,

It worked for the checksum.

Only thing that i am still confused with is the part where sequence numbers
are concerned. In the tcpdump o/p I still see seq as 0 over multiple
packets.

Regards

On 9/27/05, Kent Johnson <kent37 at tds.net> wrote:
>
> the taloner wrote:
> > Hi list,
> >
> > I was just playing around with one of the examples given in Python
> > cook-book. This examples show you how to send data using ICMP packets.
> > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439224
> >
> > While running the script I encountered a problem which was with the
> > statement
> >
> > icmp.set_icmp_cksum(0)
> >
> > The error encountered was
> >
> > Traceback (most recent call last):
> > File "icmpdata.py", line 38, in ?
> > icmp.set_icmp_chksum(0)
> > AttributeError: ICMP instance has no attribute 'set_icmp_chksum'
>
> This recipe uses a package called impacket which is available from
> http://oss.coresecurity.com/projects/impacket.html
>
> Looking at the implementation of ICMP in the latest release of
> ImpactPacket.py, the correct spelling of the method is 'set_icmp_cksum'
>
> Kent
>
> >
> >
> > So I did the next logical thing, commented the line in code (which
> > appears twice). Script ran smoothly and I captured the traffic using
> > tcpdump.
> > When the script sends first 54 bytes everything is good. When I send a
> > longer data string, and the script is forced to split the data over
> > multiple packets I start fasing a problem with checksum.
>
> That shouldn't be too surprising if you commented out the line that sets
> the checksum!
>
> >
> > 17:36:36.198543 IP (tos 0x0, ttl 255, id 16951, offset 0, flags [none],
> > length: 82) 192.168.3.37 <http://192.168.3.37> <http://192.168.3.37> >
> 192.168.3.36 <http://192.168.3.36>
> > <http://192.168.3.36>: icmp 62: echo reply seq 0
> > 0x0000: 0002 3fb9 17fe 000c 299c e8a5 0800 4500 ..?.....).....E.
> > 0x0010: 0052 4237 0000 ff01 f1d9 c0a8 0325 c0a8 .RB7.........%..
> > 0x0020: 0324 0000 bab9 0001 0000 6161 6161 6161 .$........aaaaaa
> > 0x0030: 6161 6161 6161 6161 6161 6161 6161 6161 aaaaaaaaaaaaaaaa
> > 0x0040: 6161 6161 6161 6161 6161 6161 6161 6161 aaaaaaaaaaaaaaaa
> > 0x0050: 6161 6161 6161 6161 6161 6161 6161 6161 aaaaaaaaaaaaaaaa
> > 17:36:37.198470 IP (tos 0x0, ttl 255, id 16952, offset 0, flags [none],
> > length: 82) 192.168.3.37 <http://192.168.3.37> <http://192.168.3.37> >
> 192.168.3.36 <http://192.168.3.36>
> > <http://192.168.3.36>: icmp 62: echo reply seq 0 (wrong icmp cksum bab9
> > (->bab8)!)
> > 0x0000: 0002 3fb9 17fe 000c 299c e8a5 0800 4500 ..?.....).....E.
> > 0x0010: 0052 4238 0000 ff01 f1d8 c0a8 0325 c0a8 .RB8.........%..
> > 0x0020: 0324 0000 bab9 0002 0000 6161 6161 6161 .$........aaaaaa
> > 0x0030: 6161 6161 6161 6161 6161 6161 6161 6161 aaaaaaaaaaaaaaaa
> > 0x0040: 6161 6161 6161 6161 6161 6161 6161 6161 aaaaaaaaaaaaaaaa
> > 0x0050: 6161 6161 6161 6161 6161 6161 6161 6161 aaaaaaaaaaaaaaaa
> >
> > Also as you can see that seq is not increasing as ideally it should have
> > been as directed by this line:
> >
> > seq_id = seq_id + 1
> >
> > Can someone give some light on these issues?
> >
> > Thanks
> >
> >
> > ------------------------------------------------------------------------
> >
> > _______________________________________________
> > 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050927/d1c4b984/attachment.htm

From jerl.simpso at gmail.com  Tue Sep 27 17:01:51 2005
From: jerl.simpso at gmail.com (Jerl Simpson)
Date: Tue, 27 Sep 2005 10:01:51 -0500
Subject: [Tutor] HTTP GET Request
Message-ID: <d94765f05092708016a6ed7b0@mail.gmail.com>

Hello,

I have been looking through some of the HTTP projects and haven't quite
found what I'm looking for.
Basicall, what I need is a stand alone CGI. Instead of the program passing
the data off to a CGI, I want it to parse and handle the request directly.

The part I'm having trouble with is actually getting the request and parsing
it.

Let's say I have a URI that looks like: ?var1=val1&var2=val2&...varn=valn

I'd like to find a way to get these into some datastructure so I can use
them to generate my output.

It seems like a simple thing, but as I'm new to python, I don't know where
to start.

Thank you for any help you can give.


Jerl
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050927/f40748b1/attachment.html

From gsf at panix.com  Tue Sep 27 17:30:59 2005
From: gsf at panix.com (Gabriel Farrell)
Date: Tue, 27 Sep 2005 11:30:59 -0400
Subject: [Tutor] Linking with C programs
In-Reply-To: <200509270841.31940.ewalker@micron.com>
References: <1127828957.4592.23.camel@localhost.localdomain>
	<200509270841.31940.ewalker@micron.com>
Message-ID: <20050927153059.GE29506@panix.com>

You can read some of what Guido has to say about Python and C at
http://python.org/doc/essays/omg-darpa-mcc-position.html
and see SWIG documentation (a few pertain to Python) at
http://www.swig.org/doc.html

gsf


On Tue, Sep 27, 2005 at 08:41:31AM -0600, Eric Walker wrote:
> There is a program called swig. this generates python interfaces to external 
> C/C++ libraries. I never used it as I am a very new python programmer but I 
> took the Mark Lutz class and he pushes it.
> 
> Python Newbie....
> 
> 
> On Tuesday 27 September 2005 07:49 am, Matt Williams wrote:
> > Dear List,
> >
> > Could someone explain how, in very general terms, one would use python
> > to wrap some C libraries/ API.
> >
> > I ask because there are a few bits of C software that look quite
> > interesting, and I know that Python can be used to wrap the C - but how
> > does it work?
> >
> > Thanks,
> >
> > Matt
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> 
> -- 
> Eric Walker
> EDA/CAD Engineer
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

From kent37 at tds.net  Tue Sep 27 17:51:02 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Sep 2005 11:51:02 -0400
Subject: [Tutor] Linking with C programs
In-Reply-To: <1127828957.4592.23.camel@localhost.localdomain>
References: <1127828957.4592.23.camel@localhost.localdomain>
Message-ID: <43396A66.3070207@tds.net>

Matt Williams wrote:
> Dear List,
> 
> Could someone explain how, in very general terms, one would use python
> to wrap some C libraries/ API. 

The "Extending and Embedding" document is the official doc:
http://docs.python.org/ext/ext.html

In addition to SWIG I have heard good things about SIP:
http://directory.fsf.org/devel/prog/cpp/Python-SIP.html

ctypes is another approach which lets you call C libraries directly from Python:
http://starship.python.net/crew/theller/ctypes/

Kent

> 
> I ask because there are a few bits of C software that look quite
> interesting, and I know that Python can be used to wrap the C - but how
> does it work?
> 
> Thanks,
> 
> Matt
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From paul1brian at gmail.com  Tue Sep 27 18:04:46 2005
From: paul1brian at gmail.com (paul brian)
Date: Tue, 27 Sep 2005 17:04:46 +0100
Subject: [Tutor] HTTP GET Request
In-Reply-To: <d94765f05092708016a6ed7b0@mail.gmail.com>
References: <d94765f05092708016a6ed7b0@mail.gmail.com>
Message-ID: <bbe9926e0509270904247e04ab@mail.gmail.com>

> Basicall, what I need is a stand alone CGI.  Instead of the program passing
> the data off to a CGI, I want it to parse and handle the request directly.

instead of which program ?

Http requests are served by a web server (ie Apache), which depending
on the type of request passes the request to wherever.

As such any HTTP request *must* be handled first by a web server, and
cgi scripts traditionally lived in cgi-bin directory on the server so
a URL would look like http://www.example.com/cgi-bin/myscript.py

I think you have 3 options

1. use the cgi module in python to create scripts like the one above.
    They will not be fast but it gives you a lowlevel access to the request
    However cgi was out of date about 8 years ago - it has some
serious    limitations mostly on speed/capacity.

2. use a system like mod_python. This is better than cgi for lots of reasons,
    mostly to do with speed. Here you also have access to the request 
 objects,   but there is a bit of a learning curve.

3. Zope - higher level than even mod_python and still more of a learning curve

(there is a multitude of python based cgi repalcements, Django,
webware and others spring to mind.  But there is no clear "winner"
amoungst the community)

I would recommend that you look at taking a weekend to install apache,
and play with both the cgi module and mod_python.  mod_python is
pretty good and fairly well documented, as well as being pretty low
level.

I think there is a lot to do here - perhaps if you tell us exactly
what you need we can point you at a solution. Some web hosters provide
mod_python or zope hosting and that might be a way to get up and
running faster.





On 9/27/05, Jerl Simpson <jerl.simpso at gmail.com> wrote:
> Hello,
>
> I have been looking through some of the HTTP projects and haven't quite
> found what I'm looking for.
> Basicall, what I need is a stand alone CGI.  Instead of the program passing
> the data off to a CGI, I want it to parse and handle the request directly.
>
> The part I'm having trouble with is actually getting the request and parsing
> it.
>
> Let's say I have a URI that looks like:
> ?var1=val1&var2=val2&...varn=valn
>
> I'd like to find a way to get these into some datastructure so I can use
> them to generate my output.
>
> It seems like a simple thing, but as I'm new to python, I don't know where
> to start.
>
> Thank you for any help you can give.
>
>
> Jerl
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


--
--------------------------
Paul Brian
m. 07875 074 534
t. 0208 352 1741

From kent37 at tds.net  Tue Sep 27 18:33:29 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Sep 2005 12:33:29 -0400
Subject: [Tutor] HTTP GET Request
In-Reply-To: <d94765f05092708016a6ed7b0@mail.gmail.com>
References: <d94765f05092708016a6ed7b0@mail.gmail.com>
Message-ID: <43397459.7020302@tds.net>

Jerl Simpson wrote:
> Hello,
> 
> I have been looking through some of the HTTP projects and haven't quite 
> found what I'm looking for.
> Basicall, what I need is a stand alone CGI.  Instead of the program 
> passing the data off to a CGI, I want it to parse and handle the request 
> directly.
> 
> The part I'm having trouble with is actually getting the request and 
> parsing it.

It sounds like you need to set up a web server. It also sounds like maybe you don't know that you need to set up a web server? You might want to take a look at CherryPy which is pretty easy to get started with. The third tutorial program shows how to get query parameters from the URL.
http://www.cherrypy.org

Kent

> 
> Let's say I have a URI that looks like:  ?var1=val1&var2=val2&...varn=valn
> 
> I'd like to find a way to get these into some datastructure so I can use 
> them to generate my output.
> 
> It seems like a simple thing, but as I'm new to python, I don't know 
> where to start.
> 
> Thank you for any help you can give.
> 
> 
> Jerl
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From cpu.crazy at gmail.com  Tue Sep 27 19:20:13 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Tue, 27 Sep 2005 11:20:13 -0600
Subject: [Tutor] Embedding
Message-ID: <43397F4D.1000604@gmail.com>

hi,
I'm working on a game with other friends who don't use python. However 
they'd like to use Java Python and C/C++. I was wondering if I could 
embedd C in a Python program in Jython and lastly in java (or the other 
way arround). My goal is: Can these for languages be used to make one 
program?
Thanks,
   Joe

From kent37 at tds.net  Tue Sep 27 19:42:14 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Sep 2005 13:42:14 -0400
Subject: [Tutor] Embedding
In-Reply-To: <43397F4D.1000604@gmail.com>
References: <43397F4D.1000604@gmail.com>
Message-ID: <43398476.1030800@tds.net>

Joseph Quigley wrote:
> hi,
> I'm working on a game with other friends who don't use python. However 
> they'd like to use Java Python and C/C++. I was wondering if I could 
> embedd C in a Python program in Jython and lastly in java (or the other 
> way arround). My goal is: Can these for languages be used to make one 
> program?

Not easily. You can embed C in Java with JNI. You can access the result from Jython. But the original requirement seems a bit weird - why Java and C in one program? ISTM you should pick Python/C or Jython/Java but not both. Can you say more about what you are trying to accomplish?

(By "Java Python" do you mean "Java AND Python" or "the Java version of Python" e.g. Jython?)

Kent


From darnold992000 at yahoo.com  Tue Sep 27 19:55:15 2005
From: darnold992000 at yahoo.com (Don Arnold)
Date: Tue, 27 Sep 2005 10:55:15 -0700 (PDT)
Subject: [Tutor] find data in html file
In-Reply-To: <43395D81.1090006@gmx.net>
Message-ID: <20050927175515.36072.qmail@web80909.mail.scd.yahoo.com>

--- lmac <lopoff at gmx.net> wrote:

> Hi there,
> i have a base-question. If i want to read some kind
> of data out of a line
> which i know the start-tag and the end-tag in an
> html-file how do i 
> recognize
> if it's more than one line ?
> 
> Example:
> 
> <td>Some text<a href>link</a>text ..... DATA
> ....</tr></td> etc.
> 
> I would use >text as the starting tag to localize
> the beginning of the DATA.
> And then </tr> as the ending tag of the DATA. But if
> there is \n then 
> there are more than
> one line.
> 
> I hope i explained it well what i am going for.
> English is not my native 
> language.
> 
> Thank you.
> 

As you've seen, normal string-handling methods aren't
very useful for parsing complicated (or even simple)
HTML documents. For parsing these, take a look at the
HTMLParser or htmllib modules.

HTH,
Don



		
__________________________________ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com

From kent37 at tds.net  Tue Sep 27 20:16:11 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Sep 2005 14:16:11 -0400
Subject: [Tutor] find data in html file
In-Reply-To: <43395D81.1090006@gmx.net>
References: <43395D81.1090006@gmx.net>
Message-ID: <43398C6B.7040008@tds.net>

lmac wrote:
> Hi there,
> i have a base-question. If i want to read some kind of data out of a line
> which i know the start-tag and the end-tag in an html-file how do i 
> recognize
> if it's more than one line ?
> 
> Example:
> 
> <td>Some text<a href>link</a>text ..... DATA ....</tr></td> etc.
> 
> I would use >text as the starting tag to localize the beginning of the DATA.
> And then </tr> as the ending tag of the DATA. But if there is \n then 
> there are more than
> one line.

Beautiful Soup is good for this.
http://www.crummy.com/software/BeautifulSoup/

Kent


From 3dbernard at gmail.com  Tue Sep 27 21:08:21 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Tue, 27 Sep 2005 15:08:21 -0400
Subject: [Tutor] Quick way to find the data type
Message-ID: <61d0e2b405092712087b5f8ff4@mail.gmail.com>

Hello,

Let say I have a string. The value of the string might be 'False',
'True', '3', '1.394', or whatever else. Is there a quick way to
convert this string into the appropriate data type other than with
try/except?


Thanks
Bernard

From jerl.simpso at gmail.com  Tue Sep 27 21:23:32 2005
From: jerl.simpso at gmail.com (Jerl Simpson)
Date: Tue, 27 Sep 2005 14:23:32 -0500
Subject: [Tutor] HTTP GET Request
In-Reply-To: <bbe9926e0509270904247e04ab@mail.gmail.com>
References: <d94765f05092708016a6ed7b0@mail.gmail.com>
	<bbe9926e0509270904247e04ab@mail.gmail.com>
Message-ID: <d94765f05092712232f709a7a@mail.gmail.com>

I don't think I explained my situation clearly enough.

Let me tell you what I'm doing.
First, I'm looking for an excuse to learn Python.

Second, I'm running a server that takes request from a remote server. This
request is an HTTP GET request. I used to have (lost the source) a C program
I wrote that functions as a web server.
It takes the request on port 80, parses the GET. From the GET I construct a
MySQL query and spit the results back out.

Now, the logical solution is to run Apache to handle the webserver aspect,
and have it hand off to a CGI to run the MySQL query and spit the results
back out to the requesting server. In this situation, I could have thousands
of requests per minute, and it bogs the server down. To much overhead when
Apache calls the CGI. I've tried using several different setups with Apache,
and C, Perl, and PHP CGIs.

I found it to be much faster if I wrote the webserver, and handle the MySQL
call within the same thread.

I was told by a friend of mine that Python is good for creating network
servers. So I thought I'd give it a try...instead of rewriting my C program
I wanted to take the opportunity to learn a bit of Python.

The only piece I don't have going the Python route is actually getting the
GET

On 9/27/05, paul brian <paul1brian at gmail.com> wrote:
>
> > Basicall, what I need is a stand alone CGI. Instead of the program
> passing
> > the data off to a CGI, I want it to parse and handle the request
> directly.
>
> instead of which program ?
>
> Http requests are served by a web server (ie Apache), which depending
> on the type of request passes the request to wherever.
>
> As such any HTTP request *must* be handled first by a web server, and
> cgi scripts traditionally lived in cgi-bin directory on the server so
> a URL would look like http://www.example.com/cgi-bin/myscript.py
>
> I think you have 3 options
>
> 1. use the cgi module in python to create scripts like the one above.
> They will not be fast but it gives you a lowlevel access to the request
> However cgi was out of date about 8 years ago - it has some
> serious limitations mostly on speed/capacity.
>
> 2. use a system like mod_python. This is better than cgi for lots of
> reasons,
> mostly to do with speed. Here you also have access to the request
> objects, but there is a bit of a learning curve.
>
> 3. Zope - higher level than even mod_python and still more of a learning
> curve
>
> (there is a multitude of python based cgi repalcements, Django,
> webware and others spring to mind. But there is no clear "winner"
> amoungst the community)
>
> I would recommend that you look at taking a weekend to install apache,
> and play with both the cgi module and mod_python. mod_python is
> pretty good and fairly well documented, as well as being pretty low
> level.
>
> I think there is a lot to do here - perhaps if you tell us exactly
> what you need we can point you at a solution. Some web hosters provide
> mod_python or zope hosting and that might be a way to get up and
> running faster.
>
>
>
>
>
> On 9/27/05, Jerl Simpson <jerl.simpso at gmail.com> wrote:
> > Hello,
> >
> > I have been looking through some of the HTTP projects and haven't quite
> > found what I'm looking for.
> > Basicall, what I need is a stand alone CGI. Instead of the program
> passing
> > the data off to a CGI, I want it to parse and handle the request
> directly.
> >
> > The part I'm having trouble with is actually getting the request and
> parsing
> > it.
> >
> > Let's say I have a URI that looks like:
> > ?var1=val1&var2=val2&...varn=valn
> >
> > I'd like to find a way to get these into some datastructure so I can use
> > them to generate my output.
> >
> > It seems like a simple thing, but as I'm new to python, I don't know
> where
> > to start.
> >
> > Thank you for any help you can give.
> >
> >
> > Jerl
> >
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> >
>
>
> --
> --------------------------
> Paul Brian
> m. 07875 074 534
> t. 0208 352 1741
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050927/2f43d19c/attachment.htm

From jerl.simpso at gmail.com  Tue Sep 27 21:25:02 2005
From: jerl.simpso at gmail.com (Jerl Simpson)
Date: Tue, 27 Sep 2005 14:25:02 -0500
Subject: [Tutor] HTTP GET Request
In-Reply-To: <d94765f05092712232f709a7a@mail.gmail.com>
References: <d94765f05092708016a6ed7b0@mail.gmail.com>
	<bbe9926e0509270904247e04ab@mail.gmail.com>
	<d94765f05092712232f709a7a@mail.gmail.com>
Message-ID: <d94765f05092712257c9981b7@mail.gmail.com>

Sorry, accidentally sent the last one before I was finished.
I was saying, I just lack getting the GET URI into a variable, and then
finding out the best way to parse it into it's components using Python.

Thanks again,

Jerl

On 9/27/05, Jerl Simpson <jerl.simpso at gmail.com> wrote:
>
> I don't think I explained my situation clearly enough.
>
> Let me tell you what I'm doing.
> First, I'm looking for an excuse to learn Python.
>
> Second, I'm running a server that takes request from a remote server. This
> request is an HTTP GET request. I used to have (lost the source) a C program
> I wrote that functions as a web server.
> It takes the request on port 80, parses the GET. From the GET I construct
> a MySQL query and spit the results back out.
>
> Now, the logical solution is to run Apache to handle the webserver aspect,
> and have it hand off to a CGI to run the MySQL query and spit the results
> back out to the requesting server. In this situation, I could have thousands
> of requests per minute, and it bogs the server down. To much overhead when
> Apache calls the CGI. I've tried using several different setups with Apache,
> and C, Perl, and PHP CGIs.
>
> I found it to be much faster if I wrote the webserver, and handle the
> MySQL call within the same thread.
>
> I was told by a friend of mine that Python is good for creating network
> servers. So I thought I'd give it a try...instead of rewriting my C program
> I wanted to take the opportunity to learn a bit of Python.
>
> The only piece I don't have going the Python route is actually getting the
> GET
>
> On 9/27/05, paul brian <paul1brian at gmail.com > wrote:
> >
> > > Basicall, what I need is a stand alone CGI. Instead of the program
> > passing
> > > the data off to a CGI, I want it to parse and handle the request
> > directly.
> >
> > instead of which program ?
> >
> > Http requests are served by a web server (ie Apache), which depending
> > on the type of request passes the request to wherever.
> >
> > As such any HTTP request *must* be handled first by a web server, and
> > cgi scripts traditionally lived in cgi-bin directory on the server so
> > a URL would look like http://www.example.com/cgi-bin/myscript.py
> >
> > I think you have 3 options
> >
> > 1. use the cgi module in python to create scripts like the one above.
> > They will not be fast but it gives you a lowlevel access to the request
> > However cgi was out of date about 8 years ago - it has some
> > serious limitations mostly on speed/capacity.
> >
> > 2. use a system like mod_python. This is better than cgi for lots of
> > reasons,
> > mostly to do with speed. Here you also have access to the request
> > objects, but there is a bit of a learning curve.
> >
> > 3. Zope - higher level than even mod_python and still more of a learning
> > curve
> >
> > (there is a multitude of python based cgi repalcements, Django,
> > webware and others spring to mind. But there is no clear "winner"
> > amoungst the community)
> >
> > I would recommend that you look at taking a weekend to install apache,
> > and play with both the cgi module and mod_python. mod_python is
> > pretty good and fairly well documented, as well as being pretty low
> > level.
> >
> > I think there is a lot to do here - perhaps if you tell us exactly
> > what you need we can point you at a solution. Some web hosters provide
> > mod_python or zope hosting and that might be a way to get up and
> > running faster.
> >
> >
> >
> >
> >
> > On 9/27/05, Jerl Simpson <jerl.simpso at gmail.com> wrote:
> > > Hello,
> > >
> > > I have been looking through some of the HTTP projects and haven't
> > quite
> > > found what I'm looking for.
> > > Basicall, what I need is a stand alone CGI. Instead of the program
> > passing
> > > the data off to a CGI, I want it to parse and handle the request
> > directly.
> > >
> > > The part I'm having trouble with is actually getting the request and
> > parsing
> > > it.
> > >
> > > Let's say I have a URI that looks like:
> > > ?var1=val1&var2=val2&...varn=valn
> > >
> > > I'd like to find a way to get these into some datastructure so I can
> > use
> > > them to generate my output.
> > >
> > > It seems like a simple thing, but as I'm new to python, I don't know
> > where
> > > to start.
> > >
> > > Thank you for any help you can give.
> > >
> > >
> > > Jerl
> > >
> > > _______________________________________________
> > > Tutor maillist - Tutor at python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > >
> > >
> >
> >
> > --
> > --------------------------
> > Paul Brian
> > m. 07875 074 534
> > t. 0208 352 1741
> >
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050927/0a25df2b/attachment.html

From kent37 at tds.net  Tue Sep 27 21:27:44 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Sep 2005 15:27:44 -0400
Subject: [Tutor] Quick way to find the data type
In-Reply-To: <61d0e2b405092712087b5f8ff4@mail.gmail.com>
References: <61d0e2b405092712087b5f8ff4@mail.gmail.com>
Message-ID: <43399D30.4070400@tds.net>

Bernard Lebel wrote:
> Hello,
> 
> Let say I have a string. The value of the string might be 'False',
> 'True', '3', '1.394', or whatever else. Is there a quick way to
> convert this string into the appropriate data type other than with
> try/except?

There is a nice solution here:
http://groups.google.com/group/comp.lang.python/msg/5ead7dae977ed990?hl=en&

It doesn't avoid the try/except but it wraps it up real pretty :-)

Kent


From mhansen at cso.atmel.com  Tue Sep 27 21:33:05 2005
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Tue, 27 Sep 2005 13:33:05 -0600
Subject: [Tutor] HTTP GET Request
In-Reply-To: <mailman.2828.1127848102.508.tutor@python.org>
References: <mailman.2828.1127848102.508.tutor@python.org>
Message-ID: <43399E71.2010807@cso.atmel.com>

> Subject:
> Re: [Tutor] HTTP GET Request
> From:
> paul brian <paul1brian at gmail.com>
> Date:
> Tue, 27 Sep 2005 17:04:46 +0100
> To:
> Jerl Simpson <jerl.simpso at gmail.com>
> 
> To:
> Jerl Simpson <jerl.simpso at gmail.com>
> CC:
> tutor at python.org
> 
> 
>>Basicall, what I need is a stand alone CGI.  Instead of the program passing
>>the data off to a CGI, I want it to parse and handle the request directly.
> 
> 
> instead of which program ?
> 
> Http requests are served by a web server (ie Apache), which depending
> on the type of request passes the request to wherever.
> 
> As such any HTTP request *must* be handled first by a web server, and
> cgi scripts traditionally lived in cgi-bin directory on the server so
> a URL would look like http://www.example.com/cgi-bin/myscript.py
> 
> I think you have 3 options
> 
> 1. use the cgi module in python to create scripts like the one above.
>     They will not be fast but it gives you a lowlevel access to the request
>     However cgi was out of date about 8 years ago - it has some
> serious    limitations mostly on speed/capacity.
> 

 From what others have told me, I wouldn't say that cgi is out of date. The 
couple of apps I've done perform just fine. Also, I'd recommend that every 
programmer do at least a little app using cgi to get a good understanding of the 
basics before jumping into alternative methods like mod_python or one of the 
million python web frameworks where things get more complex.

Mike

From chris.arndt at web.de  Tue Sep 27 21:39:29 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Tue, 27 Sep 2005 20:39:29 +0100
Subject: [Tutor] Quick way to find the data type
In-Reply-To: <61d0e2b405092712087b5f8ff4@mail.gmail.com>
References: <61d0e2b405092712087b5f8ff4@mail.gmail.com>
Message-ID: <43399FF1.5070605@web.de>

Bernard Lebel schrieb:
> Hello,
> 
> Let say I have a string. The value of the string might be 'False',
> 'True', '3', '1.394', or whatever else. Is there a quick way to
> convert this string into the appropriate data type other than with
> try/except?

A quick way, yes. But also secure? No.

>>> l = ['false', 'True', '3', '1.394']
>>> l = [eval(x) for x in l]
>>> print l
[False, True, 3, 1.3939999999999999]

but this fails when it encounters a string that eval can't handle, for example
'false'. Also eval will evaluate any valid Pythin expression in the string, so
you should use it only when you know *exactly* that the string can not contain
anything harmful. Which is rarely the case.

Chris

From zathras at thwackety.com  Tue Sep 27 22:02:31 2005
From: zathras at thwackety.com (Michael Sparks)
Date: Tue, 27 Sep 2005 21:02:31 +0100
Subject: [Tutor] Linking with C programs
In-Reply-To: <1127828957.4592.23.camel@localhost.localdomain>
References: <1127828957.4592.23.camel@localhost.localdomain>
Message-ID: <200509272102.32734.zathras@thwackety.com>

On Tuesday 27 September 2005 14:49, Matt Williams wrote:
> Could someone explain how, in very general terms, one would use python
> to wrap some C libraries/ API.
>
> I ask because there are a few bits of C software that look quite
> interesting, and I know that Python can be used to wrap the C - but how
> does it work?

Use Pyrex. If you don't care about produce bindings for languages other than 
python and you just want access to C based libraries, then pyrex is by far 
the most pleasant way I've found of wrapping C.

Essentially pyrex is a bridge language - half C and half python. It compiles 
down to pure C, but handles all the awkward parts of bridging the two for 
you. (like handling ref counts and similar.)

We've used this to wrap a few libraries so far and it's been a pleasant 
experience everytime. It has a couple of tutorials, that work, and even shows 
you how to use distutils (aka setup.py) to make it easy for others to build 
your bindings too.

   * http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
   * http://ldots.org/pyrex-guide/ - Michael Smith's guide to Pyrex - it's IMO
      brilliant and the examples work, and if you're used to C and used to
      python just feels _natural_ .

If you're after a couple of examples to work forward, you can download them
from:
    * http://sourceforge.net/projects/kamaelia

Specifically the vorbissimple and python-dirac downloads will hopefully get 
you started. (The vorbissimple example includes a small simple library 
written in C and show hand off of data from python to C and from C to python, 
as well as how to have a "context" variable in C that python doesn't need to 
understand the internal structure of. (Much like with a FILE structure you 
don't need to understand the FILE structure's internals, just how you pass it 
about)

Regards,


Michael.

From dyoo at hkn.eecs.berkeley.edu  Tue Sep 27 22:04:34 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 27 Sep 2005 13:04:34 -0700 (PDT)
Subject: [Tutor] Quick way to find the data type
In-Reply-To: <43399FF1.5070605@web.de>
Message-ID: <Pine.LNX.4.44.0509271252220.3143-100000@hkn.eecs.berkeley.edu>



> A quick way, yes. But also secure? No.
>
> >>> l = ['false', 'True', '3', '1.394']
> >>> l = [eval(x) for x in l]
> >>> print l
> [False, True, 3, 1.3939999999999999]
>
> but this fails when it encounters a string that eval can't handle, for
> example 'false'. Also eval will evaluate any valid Pythin expression in
> the string, so you should use it only when you know *exactly* that the
> string can not contain anything harmful. Which is rarely the case.

Yeah, I also strongly discourage eval() here: it's very dangerous.  And
even if its weren't dangerous, for the particular job of doing data
conversion from strings to values, it's still probably the wrong tool,
since it doesn't allow for any kind of customization.

We know eval() is both dangerous and uncustomizable, so that makes it all
the more worthwhile to avoid it like the plague.  *grin*  Don't use it for
data parsing and conversion.

Kent's link to Paul McGuire's solution sounds like a straightforward way
to do the string processing: it's controlled, and can be easily modified
to handle specialized literals like lowercased 'true' or 'false'.
"Lexers" are a more specialized class of tools for doing this sort of
thing, and there are several of them out there for Python.


From 3dbernard at gmail.com  Tue Sep 27 22:06:30 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Tue, 27 Sep 2005 16:06:30 -0400
Subject: [Tutor] Quick way to find the data type
In-Reply-To: <43399FF1.5070605@web.de>
References: <61d0e2b405092712087b5f8ff4@mail.gmail.com>
	<43399FF1.5070605@web.de>
Message-ID: <61d0e2b40509271306714eb932@mail.gmail.com>

Thanks a lot Chris.


Bernard



On 9/27/05, Christopher Arndt <chris.arndt at web.de> wrote:
> Bernard Lebel schrieb:
> > Hello,
> >
> > Let say I have a string. The value of the string might be 'False',
> > 'True', '3', '1.394', or whatever else. Is there a quick way to
> > convert this string into the appropriate data type other than with
> > try/except?
>
> A quick way, yes. But also secure? No.
>
> >>> l = ['false', 'True', '3', '1.394']
> >>> l = [eval(x) for x in l]
> >>> print l
> [False, True, 3, 1.3939999999999999]
>
> but this fails when it encounters a string that eval can't handle, for example
> 'false'. Also eval will evaluate any valid Pythin expression in the string, so
> you should use it only when you know *exactly* that the string can not contain
> anything harmful. Which is rarely the case.
>
> Chris
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From 3dbernard at gmail.com  Tue Sep 27 22:11:00 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Tue, 27 Sep 2005 16:11:00 -0400
Subject: [Tutor] Quick way to find the data type
In-Reply-To: <Pine.LNX.4.44.0509271252220.3143-100000@hkn.eecs.berkeley.edu>
References: <43399FF1.5070605@web.de>
	<Pine.LNX.4.44.0509271252220.3143-100000@hkn.eecs.berkeley.edu>
Message-ID: <61d0e2b405092713116a85bbb0@mail.gmail.com>

Well I understand all the security issues but unless I'm missing
something, I don't see anything wrong here.

This is in order to read some XML data and transfer its content to the
parameters of a 3D animation software. Since I wrote the XML writer, I
always know how the XML will be formatted. Also, the xml data is read
from disk, in predefined directories. Would the tree not conform to
what I expect the read would crash right away. Finally, the evaluation
of tag content is transposed to parameter values.

So far eval() seems to do a good job for my needs.... unless I'm
missing a piece?


Cheers
Bernard



On 9/27/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
> > A quick way, yes. But also secure? No.
> >
> > >>> l = ['false', 'True', '3', '1.394']
> > >>> l = [eval(x) for x in l]
> > >>> print l
> > [False, True, 3, 1.3939999999999999]
> >
> > but this fails when it encounters a string that eval can't handle, for
> > example 'false'. Also eval will evaluate any valid Pythin expression in
> > the string, so you should use it only when you know *exactly* that the
> > string can not contain anything harmful. Which is rarely the case.
>
> Yeah, I also strongly discourage eval() here: it's very dangerous.  And
> even if its weren't dangerous, for the particular job of doing data
> conversion from strings to values, it's still probably the wrong tool,
> since it doesn't allow for any kind of customization.
>
> We know eval() is both dangerous and uncustomizable, so that makes it all
> the more worthwhile to avoid it like the plague.  *grin*  Don't use it for
> data parsing and conversion.
>
> Kent's link to Paul McGuire's solution sounds like a straightforward way
> to do the string processing: it's controlled, and can be easily modified
> to handle specialized literals like lowercased 'true' or 'false'.
> "Lexers" are a more specialized class of tools for doing this sort of
> thing, and there are several of them out there for Python.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From kent37 at tds.net  Tue Sep 27 22:27:15 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Sep 2005 16:27:15 -0400
Subject: [Tutor] HTTP GET Request
In-Reply-To: <d94765f05092712257c9981b7@mail.gmail.com>
References: <d94765f05092708016a6ed7b0@mail.gmail.com>	<bbe9926e0509270904247e04ab@mail.gmail.com>	<d94765f05092712232f709a7a@mail.gmail.com>
	<d94765f05092712257c9981b7@mail.gmail.com>
Message-ID: <4339AB23.9050507@tds.net>

Jerl Simpson wrote:
>     The only piece I don't have going the Python route is actually
>     getting the GET

Which pieces do you have so far? If it is just Python, then you don't have all the pieces yet. If you already have a server, which one are you using?

> Sorry, accidentally sent the last one before I was finished.
> I was saying, I just lack getting the GET URI into a variable, and then 
> finding out the best way to parse it into it's components using Python.

The GET URI doesn't just magically appear - you need a webserver somewhere in the picture. If you have written a webserver in C you must know a bit about what is involved. It's not just getting a query parameter into a variable, somewhere you have to implement the HTTP protocol. 

There are many, many choices for how to do this in Python. Several have already been pointed out to you - 
Apache + Python CGI - simple way to get started
Apache + mod_python - runs Python in the same process as Apache, industrial-strength and faster than CGI
CherryPy - All-Python solution, fairly easy to get started with though for high-volume deployments it is recommended to run it behind Apache with mod_rewrite.

Here is a long list of other possibilities:
http://wiki.python.org/moin/WebProgramming

Maybe you should ask your friend what server he recommends?

Kent
> 
> Thanks again,
> 
> Jerl
> 
> On 9/27/05, *Jerl Simpson* <jerl.simpso at gmail.com 
> <mailto:jerl.simpso at gmail.com>> wrote:
> 
>     I don't think I explained my situation clearly enough.
> 
>     Let me tell you what I'm doing.
>     First, I'm looking for an excuse to learn Python.
> 
>     Second, I'm running a server that takes request from a remote
>     server.  This request is an HTTP GET request.  I used to have (lost
>     the source) a C program I wrote that functions as a web server.
>     It takes the request on port 80, parses the GET.  From the GET I
>     construct a MySQL query and spit the results back out.
> 
>     Now, the logical solution is to run Apache to handle the webserver
>     aspect, and have it hand off to a CGI to run the MySQL query and
>     spit the results back out to the requesting server.  In this
>     situation, I could have thousands of requests per minute, and it
>     bogs the server down.  To much overhead when Apache calls the CGI. 
>     I've tried using several different setups with Apache, and C, Perl,
>     and PHP CGIs. 
> 
>     I found it to be much faster if I wrote the webserver, and handle
>     the MySQL call within the same thread.
> 
>     I was told by a friend of mine that Python is good for creating
>     network servers.  So I thought I'd give it a try...instead of
>     rewriting my C program I wanted to take the opportunity to learn a
>     bit of Python.
> 
>     The only piece I don't have going the Python route is actually
>     getting the GET
> 
> 
>     On 9/27/05, *paul brian* < paul1brian at gmail.com
>     <mailto:paul1brian at gmail.com>> wrote:
> 
>>  Basicall, what I need is a stand alone CGI.  Instead of the
>         program passing
>>  the data off to a CGI, I want it to parse and handle the
>         request directly.
> 
>         instead of which program ?
> 
>         Http requests are served by a web server (ie Apache), which
>         depending
>         on the type of request passes the request to wherever.
> 
>         As such any HTTP request *must* be handled first by a web
>         server, and
>         cgi scripts traditionally lived in cgi-bin directory on the
>         server so
>         a URL would look like http://www.example.com/cgi-bin/myscript.py
> 
>         I think you have 3 options
> 
>         1. use the cgi module in python to create scripts like the one
>         above.
>             They will not be fast but it gives you a lowlevel access to
>         the request
>             However cgi was out of date about 8 years ago - it has some
>         serious    limitations mostly on speed/capacity.
> 
>         2. use a system like mod_python. This is better than cgi for
>         lots of reasons,
>             mostly to do with speed. Here you also have access to the
>         request
>         objects,   but there is a bit of a learning curve.
> 
>         3. Zope - higher level than even mod_python and still more of a
>         learning curve
> 
>         (there is a multitude of python based cgi repalcements, Django,
>         webware and others spring to mind.  But there is no clear "winner"
>         amoungst the community)
> 
>         I would recommend that you look at taking a weekend to install
>         apache,
>         and play with both the cgi module and mod_python.  mod_python is
>         pretty good and fairly well documented, as well as being pretty low
>         level.
> 
>         I think there is a lot to do here - perhaps if you tell us exactly
>         what you need we can point you at a solution. Some web hosters
>         provide
>         mod_python or zope hosting and that might be a way to get up and
>         running faster.
> 
> 
> 
> 
> 
>         On 9/27/05, Jerl Simpson <jerl.simpso at gmail.com
>         <mailto:jerl.simpso at gmail.com>> wrote:
>>  Hello,
>>
>>  I have been looking through some of the HTTP projects and
>         haven't quite
>>  found what I'm looking for.
>>  Basicall, what I need is a stand alone CGI.  Instead of the
>         program passing
>>  the data off to a CGI, I want it to parse and handle the
>         request directly.
>>
>>  The part I'm having trouble with is actually getting the
>         request and parsing
>>  it.
>>
>>  Let's say I have a URI that looks like:
>>  ?var1=val1&var2=val2&...varn=valn
>>
>>  I'd like to find a way to get these into some datastructure so
>         I can use
>>  them to generate my output.
>>
>>  It seems like a simple thing, but as I'm new to python, I
>         don't know where
>>  to start.
>>
>>  Thank you for any help you can give.
>>
>>
>>  Jerl
>>
>>  _______________________________________________
>>  Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>>  http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>
> 
> 
>         --
>         --------------------------
>         Paul Brian
>         m. 07875 074 534
>         t. 0208 352 1741
> 
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


From bgailer at alum.rpi.edu  Tue Sep 27 22:14:57 2005
From: bgailer at alum.rpi.edu (bob)
Date: Tue, 27 Sep 2005 13:14:57 -0700
Subject: [Tutor] Quick way to find the data type
In-Reply-To: <61d0e2b405092712087b5f8ff4@mail.gmail.com>
References: <61d0e2b405092712087b5f8ff4@mail.gmail.com>
Message-ID: <6.1.2.0.0.20050927131438.03443a70@mail.mric.net>

At 12:08 PM 9/27/2005, Bernard Lebel wrote:
>Hello,
>
>Let say I have a string. The value of the string might be 'False',
>'True', '3', '1.394', or whatever else. Is there a quick way to
>convert this string into the appropriate data type other than with
>try/except?

eval()? 


From project5 at redrival.net  Tue Sep 27 22:29:15 2005
From: project5 at redrival.net (Andrei)
Date: Tue, 27 Sep 2005 22:29:15 +0200
Subject: [Tutor] Tutor Digest, Vol 19, Issue 82
In-Reply-To: <20050927045127.48436.qmail@web60313.mail.yahoo.com>
References: <mailman.2666.1127756098.508.tutor@python.org>
	<20050927045127.48436.qmail@web60313.mail.yahoo.com>
Message-ID: <dhca2v$p40$1@sea.gmane.org>

sanjay sinha wrote:
> I am sanju sinha just started python from the last one month . I have 
> gone through all basic programming of with python and also use Tkinter 
> for window . I want to know from you all experience person in python 
> that weather i move to wx or tkinter is sufficient for GUI programming.

Tkinter is usable for GUI development and it's the default GUI toolkit 
in Python. wx is also usable. wx offers IMO better tools (visual GUI 
builders) and better looks, but your users will have to download both Py 
and wxPy to use it - unless you use Py2exe. Whether you should switch 
depends on whether you like Tkinter or not. I for one really dislike it 
and avoid programs written in it, but others seem to prefer Tkinter - 
it's very much a matter of taste.

In the future please don't include a full tutor digest in your message 
and mind the warning at the top of the digest:

'When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."'

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])


From cpu.crazy at gmail.com  Tue Sep 27 22:33:46 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Tue, 27 Sep 2005 14:33:46 -0600
Subject: [Tutor] Embedding
In-Reply-To: <mailman.2829.1127848102.508.tutor@python.org>
References: <mailman.2829.1127848102.508.tutor@python.org>
Message-ID: <4339ACAA.8040609@gmail.com>


>From: Kent Johnson <kent37 at tds.net>
>Subject: Re: [Tutor] Embedding
>  
>
>Not easily. You can embed C in Java with JNI.
>
Thanks, that just migh be perfect... or is there a program that will 
embedd Java into C/C++?

> You can access the result from Jython. But the original requirement seems a bit weird - why Java and C in one program? ISTM you should pick Python/C or Jython/Java but not both. Can you say more about what you are trying to accomplish?
>  
>
Well we are three programmers. I know python, another knows Java and the 
other C++. We are trying to figure out how to combine all three 
langauges to make a game.

>(By "Java Python" do you mean "Java AND Python"
>
Yes. Sorry forgot the comma

> or "the Java version of Python" e.g. Jython?)
>  
>
No.

Thanks.
Joe


From dyoo at hkn.eecs.berkeley.edu  Tue Sep 27 22:52:06 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 27 Sep 2005 13:52:06 -0700 (PDT)
Subject: [Tutor] Quick way to find the data type
In-Reply-To: <61d0e2b405092713116a85bbb0@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509271312460.10346-100000@hkn.eecs.berkeley.edu>



On Tue, 27 Sep 2005, Bernard Lebel wrote:

> Well I understand all the security issues but unless I'm missing
> something, I don't see anything wrong here.


Hi Bernard,

The other major problem with it, besides security, is that it can
introduce certain error messages that will look inscrutable unless you
take special precautions.

Assume for the moment that the file reads bad data:

######
>>> eval("3.1.4")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<string>", line 1
    3.1.4
       ^
SyntaxError: unexpected EOF while parsing
######

The issue here is to use the tools that are not only powerful, but easy to
debug.  Programs that use eval() are hard to debug because the dynamic
input to eval() because another possible source of errors.  Why should
your programs have SyntaxErrors, when they're not yours?  *grin*


Of course, you can then put try/except around the eval() to handle the
situation gracefully.  But if you're going to do that, you're already
halfway near the other solution, using try/except around the other
data-converter functions like int() and float().


> This is in order to read some XML data and transfer its content to the
> parameters of a 3D animation software. Since I wrote the XML writer, I
> always know how the XML will be formatted. Also, the xml data is read
> from disk, in predefined directories. Would the tree not conform to what
> I expect the read would crash right away. Finally, the evaluation of tag
> content is transposed to parameter values.
>
> So far eval() seems to do a good job for my needs.... unless I'm
> missing a piece?

It's most likely the wrong tool here.  And people HAVE been bitten by this
before:

    http://phpxmlrpc.sourceforge.net/#security

Different language, but same exact problem.  Those folks, too, though
using eval() was fine, because it was part of the internals, and bad data
would obviously never get into those internals.

They were wrong.  But it's wrong to say that they weren't careful enough
to control the flow of data: the real conceptual error was putting in
eval() in their program in the first place.  They finally woke up and
stripped it out, after getting exploited several times.


The assumptions you make, about controlling the input, and being the only
source of the xml output, sound fine.  But you're assuming that the
environment that your program will work in will be static.  Software often
ends up being applied in places that are ridiculous and unplanned-for,
like a network application.  It's best practice to avoid unneccessary
risk, and not to court it.  *grin*

The solution that Paul McGuire outlines is just as easy to use as eval(),
once you have it in a module.  And unlike eval(), there's no exploitation
risk at all.  So the argument should really be: why would we want to use
eval()?


From dyoo at hkn.eecs.berkeley.edu  Tue Sep 27 22:53:47 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 27 Sep 2005 13:53:47 -0700 (PDT)
Subject: [Tutor] Quick way to find the data type
In-Reply-To: <6.1.2.0.0.20050927131438.03443a70@mail.mric.net>
Message-ID: <Pine.LNX.4.44.0509271352290.10346-100000@hkn.eecs.berkeley.edu>



> >Let say I have a string. The value of the string might be 'False',
> >'True', '3', '1.394', or whatever else. Is there a quick way to convert
> >this string into the appropriate data type other than with try/except?
>
> eval()?

Gaaa, don't say that word!  *grin*

(Sorry, I know I'm sounding like a ranting maniac about this.  It's one of
my pet peeves.)


From 3dbernard at gmail.com  Tue Sep 27 23:26:06 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Tue, 27 Sep 2005 17:26:06 -0400
Subject: [Tutor] Quick way to find the data type
In-Reply-To: <Pine.LNX.4.44.0509271312460.10346-100000@hkn.eecs.berkeley.edu>
References: <61d0e2b405092713116a85bbb0@mail.gmail.com>
	<Pine.LNX.4.44.0509271312460.10346-100000@hkn.eecs.berkeley.edu>
Message-ID: <61d0e2b405092714264ca503fc@mail.gmail.com>

Fair enough Danny,
I made the changes. Thanks for the input.


Still, regarding this comment.....

On 9/27/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
> The assumptions you make, about controlling the input, and being the only
> source of the xml output, sound fine.  But you're assuming that the
> environment that your program will work in will be static.  Software often
> ends up being applied in places that are ridiculous and unplanned-for,
> like a network application.  It's best practice to avoid unneccessary
> risk, and not to court it.  *grin*

Well, the fact is I'm in charge of these things here, fortunately. My
job is to make sure nothing gets used the wrong way. :-)

Still, your points are valid and I have taken note of them :-)

Bernard

From kent37 at tds.net  Wed Sep 28 00:16:38 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Sep 2005 18:16:38 -0400
Subject: [Tutor] Embedding
In-Reply-To: <4339ACAA.8040609@gmail.com>
References: <mailman.2829.1127848102.508.tutor@python.org>
	<4339ACAA.8040609@gmail.com>
Message-ID: <4339C4C6.8050707@tds.net>

Joseph Quigley wrote:
>>From: Kent Johnson <kent37 at tds.net>
>>Subject: Re: [Tutor] Embedding 
>>
>>Not easily. You can embed C in Java with JNI.
>>
> Thanks, that just migh be perfect... or is there a program that will 
> embedd Java into C/C++?

Yes, that is supported by Sun. I'm not sure if it is part of JNI or something else. But I don't think that is a good solution to your problem.

I suppose you could have a core game engine written in C++ with Java or Python as an embedded scripting language. What kind of game do you have in mind?
> 
> Well we are three programmers. I know python, another knows Java and the 
> other C++. We are trying to figure out how to combine all three 
> langauges to make a game.

Sounds like a bit of a hash to me. Show them pygame and convince them to learn Python :-)

Kent


From zathras at thwackety.com  Wed Sep 28 00:53:29 2005
From: zathras at thwackety.com (Michael Sparks)
Date: Tue, 27 Sep 2005 23:53:29 +0100
Subject: [Tutor] Embedding
In-Reply-To: <4339C4C6.8050707@tds.net>
References: <mailman.2829.1127848102.508.tutor@python.org>
	<4339ACAA.8040609@gmail.com> <4339C4C6.8050707@tds.net>
Message-ID: <200509272353.30255.zathras@thwackety.com>

On Tuesday 27 September 2005 23:16, Kent Johnson wrote:
> Joseph Quigley wrote:...
> > Well we are three programmers. I know python, another knows Java and the
> > other C++. We are trying to figure out how to combine all three
> > langauges to make a game.
>
> Sounds like a bit of a hash to me. Show them pygame and convince them to
> learn Python :-)

If you tell them to drop the type declarations, braces {}, semicolons, and 
make their code a touch simpler, then they already (more or less) know python 
(At least that's the way I normally introduce people who know C/C++/Java to 
python).


Michael.


From shitizb at yahoo.com  Wed Sep 28 02:14:37 2005
From: shitizb at yahoo.com (Shitiz Bansal)
Date: Tue, 27 Sep 2005 17:14:37 -0700 (PDT)
Subject: [Tutor] File mode r+
In-Reply-To: <7e5ba9220509251600125f7aed@mail.gmail.com>
Message-ID: <20050928001437.40907.qmail@web53810.mail.yahoo.com>



--- "Michael P. Reilly" <arcege at gmail.com> wrote:

> On 9/24/05, Shitiz Bansal <shitizb at yahoo.com> wrote:
> >
> > Hi,
> >
> > How do i proceed if i am not sure about the number
> of characters in the
> > fist two lines and want to write in the third
> line.is <http://line.is>there a way to skip two
> lines and write on the third??
> >
> > Also could anyone explain why the readline() did
> not work. according to
> > what i understand it should.
> > *bob <bgailer at alum.rpi.edu>* wrote:
> >
> > At 01:11 AM 9/24/2005, Shitiz Bansal wrote:
> > >Hi,
> > >I want to update a textfile using the r+ file
> mode.
> > >contents of file:
> > >
> > >abcd
> > >efgh
> > >ijkl
> > >mnop
> > >qrst
> > >uvwx
> > >yx12
> > >
> > >my scripts is:
> > >
> > >file1=open("aa.txt",'r+')
> >
> > >>Instead of readline, use skip to position the
> file to where you want to
> > >>overwrite it.
> > >>file1.seek(10)
> >
> >
> > >file1.readline()
> > >file1.readline()
> > >file1.write("1234\n")
> > >file1.close()
> > >
> > >This should replace the third line with 1234.
> > >However it does nothing.
> > >
> > >Moreover the script:
> > >
> > >file1=open("aa.txt",'r+')
> > >file1.write("1234\n")
> > >file1.close()
> > >
> > >does replace the first line with 1234.
> > >
> > >could anyone explain what is happening?
> > >
> > >shitiz
> >
> > Hello Shitiz,
> 
> I'm not sure if it is true anymore, I haven't gotten
> to test it. But in the
> olden days of C and standard libraries and UNIX, you
> would open a file for
> reading and writing and before you could switch
> between read() and write()
> you would have to perform a seek(). Usually
> something like:
> file.readline() # read line 1
> file.readline() # read line 2
> file.seek(0, 1) # move 0 bytes from current position
> (no place)
> file.write("1234\n")
> file.close()
>  There may be one problem here. What you write will
> overwrite line 3.... or
> only part of line 3... or maybe all of line 3 and
> some of line 4. It is good
> to know how the file is structured before you write
> to it, in case you end
> up with unexpected data. If all your lines are four
> characters plus a
> newline, then you don't have to worry (most of us
> aren't that lucky).
> -Arcege
> --
> There's so many different worlds,
> So many different suns.
> And we have just one world,
> But we live in different ones.
> 



		
__________________________________ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com

From amonroe at columbus.rr.com  Wed Sep 28 02:33:07 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Tue, 27 Sep 2005 20:33:07 -0400
Subject: [Tutor] Embedding
In-Reply-To: <4339ACAA.8040609@gmail.com>
References: <mailman.2829.1127848102.508.tutor@python.org>
	<4339ACAA.8040609@gmail.com>
Message-ID: <124881258082.20050927203307@columbus.rr.com>

> Well we are three programmers. I know python, another knows Java and the
> other C++. We are trying to figure out how to combine all three 
> langauges to make a game.

I checked out this book from the local library:
MUD Game Programming by Ron Penton
http://www.amazon.com/exec/obidos/tg/detail/-/1592000908/qid=1127867592/sr=2-1/ref=pd_bbs_b_2_1/103-5133587-6168643?v=glance&s=books

It had a chapter on how to embed Python in a C++ program. Might be
worth a glance through.

Alan


From kent37 at tds.net  Wed Sep 28 03:47:24 2005
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 27 Sep 2005 21:47:24 -0400
Subject: [Tutor] Embedding
In-Reply-To: <200509272353.30255.zathras@thwackety.com>
References: <mailman.2829.1127848102.508.tutor@python.org>	<4339ACAA.8040609@gmail.com>
	<4339C4C6.8050707@tds.net>
	<200509272353.30255.zathras@thwackety.com>
Message-ID: <4339F62C.90001@tds.net>

Michael Sparks wrote:
> On Tuesday 27 September 2005 23:16, Kent Johnson wrote:
>>Sounds like a bit of a hash to me. Show them pygame and convince them to
>>learn Python :-)
> 
> If you tell them to drop the type declarations, braces {}, semicolons, and 
> make their code a touch simpler, then they already (more or less) know python 
> (At least that's the way I normally introduce people who know C/C++/Java to 
> python).

Yes, my experience with porting Java to Python is that the major activity is pressing 'delete' :-)

Kent


From djennings3 at earthlink.net  Wed Sep 28 04:13:30 2005
From: djennings3 at earthlink.net (Don Jennings)
Date: Tue, 27 Sep 2005 22:13:30 -0400
Subject: [Tutor] web development
Message-ID: <764A0C7E-2FC5-11DA-8B8F-0003930ACB16@earthlink.net>

Earlier this month, Kent posted that Jython and Velocity are a good way 
to develop dynamic web sites. After a little searching, it seems that 
there are quite a few options for web development in Python (perhaps 
too many?). So, rather than ask for recommendations of which one to 
use, what I would really like to know are how people decided to use any 
particular framework.

Thanks!
Don

P.S. As an aside, does anyone have any experience with django? (I 
really like the name since I am fond of django reinhardt, the jazz 
guitarist.)


From alan.gauld at btinternet.com  Wed Sep 28 09:23:18 2005
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 28 Sep 2005 08:23:18 +0100
Subject: [Tutor] Python Editors (particualrly Vim)
References: <59CF9F456FAA9045B405C441EC916F3E02DDFFFB@MERC24.na.sas.com>
Message-ID: <dhdgd1$h9e$1@sea.gmane.org>

> 3. scite (very simple)
>
>All are great and I use all of the three.

Just back from vacation or I would have had
a lot more to say! :-)

But I have to agree with scite as an option,
its very lightweight and fast and is basically
the editor portion opf Pythonwin(*). That means
you get all the editor features, but for many
languages.

But you lose the IDE Features - debugger integration,
some code completion, keyword suggestion etc.

Emacs can of course do all of the requested things
but you may have to invest a lot of configuration
time getting it just so.

THe other feature you may want to look for is
tags support (vim and emacs at least), ie the
ability to put the cursor on a fuinction name
and go to its definition with a single leap.
This is very good for exploring other peoples code!

(*)Scite was originally just a demostrator for
the Scintilla editor component for GUIs but it
has taken on a life of its own!

HTH,

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






From alan.gauld at btinternet.com  Wed Sep 28 09:33:38 2005
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 28 Sep 2005 08:33:38 +0100
Subject: [Tutor] Simultaneous Adobe Reader
References: <36141C39871E4D4DAE92F79D1838543601B176CB@itcnt14.itc.nl>
Message-ID: <dhdh0c$iqp$1@sea.gmane.org>

>From windows, using a python script how can I open
> Adobe Reader without displaying a PDF document?

Just start the reader executable with no arguments.

os.system(r"C:\Program Files\Adobe\Acrobat 
7.0\Reader\AcroRd32.exe")

Does it for me.

If you need to send commands etcto it you propbably need
to to use popen()/commands/subprocess depending on your
preferences and Python version.

> to run two Adobe Reader sessions simulatneously.

Yes of course but to communicate with them you will need
to store the pipes in different variables.

An alternative approach is to use the WSH COM objects,
but thats a whole new topic!


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




From alan.gauld at btinternet.com  Wed Sep 28 09:58:08 2005
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 28 Sep 2005 08:58:08 +0100
Subject: [Tutor] Stupid newbie question
References: <5AE0A72A4C0AD711806A000255FC47DB09CC1911@dmv-ent-ex07.dmv.ca.gov>
	<20050923223826.GA9883@alexis.mi.celestial.com>
Message-ID: <dhdiea$mo4$1@sea.gmane.org>

>>class startremail:
>>    def __init__(self):
>>     remailfile = open('U:\Bounce20.txt', 'r') 
>> #future
>>     def getday(self):
>>     def Read(self,line):

>>from startremail import *
>>x = startremail()
>>print x.getday()
>>I get the following return
>>
>>NameError: name 'getday' is not defined
>
> It appears that you're being bitten by my least-favorite 
> ``feature''
> of python, indentation errors.  The getday routine appears to 
> be a
> subroutine of __init__, not a method of the class.

Actually he is being bitten by *lack* of indentation.
Indentation would help here not hinder! Unless you mean
that Python should insist on a dertain minimum amouint
of indentation..

If you use >=3 chars for indentation this kind of error
rarely happens, its only when using absurdly low indentation
spaces that this occurs. Indentation is intended to prevent
this but if you try to avoid using it then you get bitten...

Admittedly if Python used block markers to close a block
(ala Ruby) then the parser would identify a missing block
marker or if the markers matched parse correctly. So I
suspect Bill is actually objecting to the lack of block
markers not the use of indentation! ;-)

Alan G. 




From singletoned at gmail.com  Wed Sep 28 10:25:53 2005
From: singletoned at gmail.com (Ed Singleton)
Date: Wed, 28 Sep 2005 09:25:53 +0100
Subject: [Tutor] find data in html file
In-Reply-To: <43395D81.1090006@gmx.net>
References: <43395D81.1090006@gmx.net>
Message-ID: <34bb7f5b0509280125208d435e@mail.gmail.com>

On 27/09/05, lmac <lopoff at gmx.net> wrote:
> Hi there,
> i have a base-question. If i want to read some kind of data out of a line
> which i know the start-tag and the end-tag in an html-file how do i
> recognize
> if it's more than one line ?
>
> Example:
>
> <td>Some text<a href>link</a>text ..... DATA ....</tr></td> etc.
>
> I would use >text as the starting tag to localize the beginning of the DATA.
> And then </tr> as the ending tag of the DATA. But if there is \n then
> there are more than
> one line.

Hopefully it's just a typo or something, but you appear to have your
ending </tr> and </td> tags the wrong way round.

You should be closing the cell before you close the row.

How do you want to get the data out?  This case is simple enough that
you could do a lazy (non-greedy) regex statement for it.  Something
like "<td>([\s|\S]+?)</td>" would do it.

Ed

From RPhillips at engineer.co.summit.oh.us  Wed Sep 28 12:56:00 2005
From: RPhillips at engineer.co.summit.oh.us (Ron Phillips)
Date: Wed, 28 Sep 2005 06:56:00 -0400
Subject: [Tutor] [tutor]web development
Message-ID: <s33a3e95.058@cosegw.cose.summitoh.net>

Well, I won't argue with anyone who chooses otherwise, but CherryPy
http://www.cherrypy.org/ is easy to use, lightweight, quick, and
pythonic. I write everything as plain old python, then webify it the
very last thing. 
 
It's also the basis of a new, promising framework called TurboGears
http://www.turbogears.org/, which Kevin Dangoor put together. He does a
"Wiki in 20 minutes" tutorial that's pretty impressive.
 
 
 
Ron Phillips
Programmer/Analyst
County of Summit Engineer
538 E. South St.
Akron, OH 44311
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050928/a96f226d/attachment.htm

From RPhillips at engineer.co.summit.oh.us  Wed Sep 28 13:44:15 2005
From: RPhillips at engineer.co.summit.oh.us (Ron Phillips)
Date: Wed, 28 Sep 2005 07:44:15 -0400
Subject: [Tutor] Prevent "Coder's Remorse"?
Message-ID: <s33a49e5.063@cosegw.cose.summitoh.net>

Maybe it's just me. I am always haunted by "coder's remorse" (the
certainty that there's a more compact, beautiful, fun, maintainable way
to code anything I finish.)
 
At any rate, I am currently working on a script to model an ordered
collection of geographic points, all of which must share the same
collection of attributes. So, a little collection might be:
 
pointList = [
{lat:40.123,lon:-81.456, 
    'attributes':{'msg':'example','beavers':34, 'distance':18.132}
},
{lat:40.12345,lon:-81.45678, 
    'attributes':{'msg':'','beavers':0, 'distance':0.0}
}
]
 
If I add an attribute of 'newAtt':'newVal' to
pointList[1]['attributes'], I want it to automatically add
'newAtt':'default' to
all the other member's 'attributes' dictionary. If I delete an
attribute, it should delete from all the member's dictionaries. The
attributes are limited to string, integer, and float values.
 
I can do this by brute force, but:

Is there an elegant approach that occurs to anyone? 
Is there a data structure that forces all members to have the same
keys? 
Is there an object structure that will let updates to one instance
affect all instances?
Am I even asking the right questions?

I suspect there's an elegant solution, but it's beyond me right now. If
not, fine; I'll happily go on with my ham-fisted approach.

Regards,




 
 

Ron Phillips
Programmer/Analyst
County of Summit Engineer
538 E. South St.
Akron, OH 44311

From kent37 at tds.net  Wed Sep 28 13:47:34 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 28 Sep 2005 07:47:34 -0400
Subject: [Tutor] web development
In-Reply-To: <764A0C7E-2FC5-11DA-8B8F-0003930ACB16@earthlink.net>
References: <764A0C7E-2FC5-11DA-8B8F-0003930ACB16@earthlink.net>
Message-ID: <433A82D6.1000906@tds.net>

Don Jennings wrote:
> what I would really like to know are how people decided to use any 
> particular framework.

Well I stumbled into Jython / Velocity over many years. My first web application was written in Java + servlets using the Jetty servlet engine. At first I didn't use any template engine and discovered the pain of manual HTML generation. Eventually I found Velocity and came to love it. At some point I learned Python and Jython and figured out that using Jython to write the servlet and Velocity for the view made for very agile web site development.

More recently I have completed a small project using CherryPy. My selection process for this was based on requirements and personal preference. I was writing a tool that would be distributed in my company so setup had to be easy. For this reason I wanted a framework that included a standalone webserver rather than requiring Apache. The tool could conceivably be distributed as a proprietary product so I avoided frameworks that are GPL licensed. These two requirements narrowed the field considerably. I also wanted XML-RPC support which is included with CherryPy. I have wanted to try it out so I gave it a go.

Kent


From challman at gmail.com  Wed Sep 28 14:35:35 2005
From: challman at gmail.com (Chris Hallman)
Date: Wed, 28 Sep 2005 08:35:35 -0400
Subject: [Tutor] script question
In-Reply-To: <4338A883.7020001@tds.net>
References: <9f68812f05092604563052918f@mail.gmail.com>
	<43387C41.20307@tds.net> <4338A883.7020001@tds.net>
Message-ID: <9f68812f050928053548024051@mail.gmail.com>

 Thanks for all the input!!! I really appreciate it. I need to post a
correction to my script. What I sent was an early version. I made a few
minor modifications:

import ConfigParser, string, sys, os
section = sys.argv[1]
interface = sys.argv[3]
INI=ConfigParser.ConfigParser()
INI.read("c:\utils\interfaces.ini")
interface_entries=[p for p in INI.options
(section)]
interface_list=[INI.get(section, pw) for pw in interface_entries]
for i in interface_list:
	if i == interface:
		os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet -n l17aesm1 forward
red held " +
sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])


I've researched what you all have suggested and I may need to switch to
reading the ini file line by line or using a different file parser. The ini
file is only 100 lines long now, but will likely grow to 500 line and maybe
to 4000 lines. To give you a better background of what I'm doing with this
script, it's running on a network management system that receives traps.
After some processing of the raw trap, messages get sent to this script for
further processing. These messages are for interface down traps from routers
and switches in our network. I use this script to mitigate the number of
interface down messages on our console. I need to do this because we do not
need to know when every port has gone down (i.e. user ports). This script
searches the ini file for a device name match. Once it has found a match and
if the interface matches as well, I need to message forwarded to the console
(the Windows command). If no matching device or interface is found, then the
script can just exit. - Show quoted text -


On 9/26/05, Kent Johnson <kent37 at tds.net> wrote:
>
> Kent Johnson wrote:
> > *TEST FIRST* Don't optimize until you know it is too slow and you
> > have a test case that you can time to see if your 'optimizations' are
> > making it faster.
>
> Pardon my shouting :-)
>
> 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/20050928/a02c95a9/attachment.html

From kent37 at tds.net  Wed Sep 28 14:50:43 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 28 Sep 2005 08:50:43 -0400
Subject: [Tutor] Prevent "Coder's Remorse"?
In-Reply-To: <s33a49e5.063@cosegw.cose.summitoh.net>
References: <s33a49e5.063@cosegw.cose.summitoh.net>
Message-ID: <433A91A3.2040806@tds.net>

Ron Phillips wrote:
> At any rate, I am currently working on a script to model an ordered
> collection of geographic points, all of which must share the same
> collection of attributes. So, a little collection might be:
>  
> pointList = [
> {lat:40.123,lon:-81.456, 
>     'attributes':{'msg':'example','beavers':34, 'distance':18.132}
> },
> {lat:40.12345,lon:-81.45678, 
>     'attributes':{'msg':'','beavers':0, 'distance':0.0}
> }
> ]
>  
> If I add an attribute of 'newAtt':'newVal' to
> pointList[1]['attributes'], I want it to automatically add
> 'newAtt':'default' to
> all the other member's 'attributes' dictionary. If I delete an
> attribute, it should delete from all the member's dictionaries. The
> attributes are limited to string, integer, and float values.
>  
> I can do this by brute force, but:
> 
> Is there an elegant approach that occurs to anyone? 
> Is there a data structure that forces all members to have the same
> keys? 
> Is there an object structure that will let updates to one instance
> affect all instances?
> Am I even asking the right questions?

I'm curious about why you want to do this, it is kind of a strange requirement. But anyway, here is a class that subclasses dict and presents the interface you want to client code. It doesn't actually update all instances when you add or delete a key; it keeps a list of valid keys in a class attribute and updates this list when you add or delete. Then when you access a key it checks the list of valid keys. If the key you want is not in the list, you get a KeyError - the instance dict is never checked. If the key you want is in the list but not in the instance, you get the default value.

I don't see any need to actually add default values to all the dicts. Conceivably to save memory you might want to actually delete values from all the dicts; to do this you could keep a list of all the existing dicts as another class attribute. I'm not sure you will save much though as the dict itself probably doesn't resize downward. A side effect of not deleting keys is that if you delete and then restore a key, instances that had that key before will magically restore their old value. This could be a bug or a feature depending on your requirements.

Finally, the set of valid keys is shared by all instances, so if you want to use this for two different types of things you will have to make subclasses and give each subclass its own _key attribute.

Requires Python 2.3 or greater

Kent

# CommonKeysDict.py
# Make it work with Python 2.3
try:
    set
except NameError:
    from sets import Set as set
    
class CommonKeysDict(dict):
    """Dictionary where all instances must have the same set of keys
       and with a default value for unknown keys.
       
       >>> d = CommonKeysDict()
       >>> d[0]
       Traceback (most recent call last):
         ...
       KeyError: 0
       
       >>> d[0] = 1
       >>> d[0]
       1
       
       A second instance will get the default value for keys that are in use:
       >>> d2 = CommonKeysDict()
       >>> d2[0]
       'default'
       
       The second instance can have its own values
       >>> d2[0] = 2
       >>> d2[0]
       2
       >>> d[0]
       1
       
       Deleting a key from any instance removes that key from the allowed set.
       Note that this doesn't actually delete the key from all instances, it just
       makes it inaccessible.
       
       >>> del d[0]
       >>> d2[0]
       Traceback (most recent call last):
         ...
       KeyError: 0
       
    """
    
    _keys = set()
    
    def __init__(self, **items):
        dict.__init__(self, **items)

    def __getitem__(self, key):
        if key not in self._keys:
            raise KeyError, key
        try: 
            return dict.__getitem__(self, key)
        except KeyError:
            return 'default'


    def __setitem__(self, key, value):
        self._keys.add(key)
        dict.__setitem__(self, key, value)
    
    
    def __delitem__(self, key):
        self._keys.remove(key)
        dict.__delitem__(self, key)
        
        
def _test():
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    _test()



From grouch at gmail.com  Wed Sep 28 15:34:44 2005
From: grouch at gmail.com (Andrew P)
Date: Wed, 28 Sep 2005 08:34:44 -0500
Subject: [Tutor] web development
In-Reply-To: <764A0C7E-2FC5-11DA-8B8F-0003930ACB16@earthlink.net>
References: <764A0C7E-2FC5-11DA-8B8F-0003930ACB16@earthlink.net>
Message-ID: <e6443aa70509280634766a93e6@mail.gmail.com>

I've used CherryPy on a couple of projects now. I use it with HTMLTemplate (
http://freespace.virgin.net/hamish.sanderson/htmltemplate.html) and
SQLObject (http://sqlobject.org/).

This has the advantage of being about as Pythonic as you can get, since
everything you manipulate is represented as an object. HTMLTemplate is
especially nice since it completely separates the html from your code. I
can, have, and do change the interface frequently with impunity, and vice
versa. Contrast this with something like inline PHP. It's also editable in
any old wsywig HTML editor. But you are free to choose whatever persistent
storage and templating system you like.

CherryPy is low level, and will force you to make decisions about what
templating you want to use, and what you want to use for a backend. But the
upside is, it feels no different than writing any other program. Just do
what you've always done, choose supporting packages you like, and it's off
to the races. It's even it's own webserver. So edit, run, edit run. Same as
always.

I can tell you why I didn't choose some others. Zope is a chunky,
labyrinth-like framework. My friend runs Plone, built with Zope, and it's
easily the most resource heavy thing running on my server. That just sent me
running. Webware uses some sort of JSP/ASP/PHP alike, which makes me cringe
in horror. HTML and code do not belong together in a big inline spaghetti
lovefest. IMHO :)

Twisted is an "asynchronous networking framework", and I haven't used it,
but actually looks fairly small, has it's own webserver, and a very very
nice looking templating system which has the same philosophy as
HTMLTemplate, but has some really cool feautures like livepage, which seems
to be the same thing as AJAX, a la google maps. I just haven't had a reason
to check it out, but it would be first on my list to check. It's more of a
kitchen sink approach, or general purpose if you prefer, but does seem cool.
So if you are looking for something like that, well. Build websites, write
chat programs!

OK. Enough early morning rambling :) Good luck choosing.


On 9/27/05, Don Jennings <djennings3 at earthlink.net> wrote:
>
> Earlier this month, Kent posted that Jython and Velocity are a good way
> to develop dynamic web sites. After a little searching, it seems that
> there are quite a few options for web development in Python (perhaps
> too many?). So, rather than ask for recommendations of which one to
> use, what I would really like to know are how people decided to use any
> particular framework.
>
> Thanks!
> Don
>
> P.S. As an aside, does anyone have any experience with django? (I
> really like the name since I am fond of django reinhardt, the jazz
> guitarist.)
>
> _______________________________________________
> 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/20050928/b2b4521c/attachment.htm

From RPhillips at engineer.co.summit.oh.us  Wed Sep 28 15:51:52 2005
From: RPhillips at engineer.co.summit.oh.us (Ron Phillips)
Date: Wed, 28 Sep 2005 09:51:52 -0400
Subject: [Tutor] Prevent "Coder's Remorse"?
Message-ID: <s33a67e2.037@cosegw.cose.summitoh.net>

 Kent Johnson wrote:
<snip>I'm curious about why you want to do this, it is kind of a
strange requirement.</snip> 

Yeah, that was bothering me, too. I was a little unsure if I'd even
defined the problem properly; that's what I meant by: "Am I even asking
the right questions?" 

I'll play around with the class a little and see if it helps me clarify
to myself what I am trying to do. I was kind of on the right path, but
I've never written much with __getitem__, __setitem__, etc. and it
wasn't going at all like I had in mind. I've found that when I patch and
patch and patch my code, it's usually because I am trying to do the
wrong thing altogether. And I wasn't using Class attributes properly,
either.

Thanks so much! Sorry for the vague question, but I really think the
class you made is close to what I needed.

Ron


From negroup at gmail.com  Wed Sep 28 16:16:20 2005
From: negroup at gmail.com (Negroup -)
Date: Wed, 28 Sep 2005 16:16:20 +0200
Subject: [Tutor] Reformatting a one (long) line xml file
Message-ID: <2fdabf1905092807165e304df9@mail.gmail.com>

Hi all, I have an xml file where the tags are all on the same line,
without any newline. This file is quite big and difficult to read. I'd
like to format it in a convenient way, using indentation and nesting.
How to pretty print my content?

I hope to have explained well enough my problem, differently let me know.

Thans a lot!

From alan.gauld at freenet.co.uk  Wed Sep 28 16:48:47 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Wed, 28 Sep 2005 15:48:47 +0100
Subject: [Tutor] Prevent "Coder's Remorse"?
References: <s33a49e5.063@cosegw.cose.summitoh.net>
Message-ID: <017901c5c43b$bb75a0d0$0201a8c0@xp>

> pointList = [
> {lat:40.123,lon:-81.456, 
>    'attributes':{'msg':'example','beavers':34, 'distance':18.132}
> },
> {lat:40.12345,lon:-81.45678, 
>    'attributes':{'msg':'','beavers':0, 'distance':0.0}
> }
> ]

THis sopunds like its crying out for a class

class Point:
   def __init__(self, lat, long, msg, beavers, distance):
      self.lat = lat
      self.long = long
      etc...
      

Pointlist = [Point(40.123,-81.456,'example',34,18.132),
             Point(40.12345,-81.4567,'',0,0.0)]

> If I add an attribute of 'newAtt':'newVal' to
> pointList[1]['attributes'], I want it to automatically add
> 'newAtt':'default' to all the other member's 'attributes' 
> dictionary. 

You could do that by calling a class method that updates all 
of the instances.

> If I delete an attribute, it should delete from all the 
> member's dictionaries. 

Likewise a class method could do this.

> attributes are limited to string, integer, and float values.

Doesn't really matter! :-)

> Is there an elegant approach that occurs to anyone? 
> Is there a data structure that forces all members to have the same
> keys? 

A class. Although in Python its always possible to add 
instance variables but you have to do it deliberately!
But at least a class will ensure that all the values 
that should be there are indeed present.

> Is there an object structure that will let updates to one instance
> affect all instances?

A class method is the traditional way of doing that. 
Get the init method to update a global (or class based) 
list of instances and write a del() method that removes 
itself.

Then a class method can iterate that instance list 
doing whatever it needs to do...

HTH,

Alan G.

From cpu.crazy at gmail.com  Wed Sep 28 16:44:42 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Wed, 28 Sep 2005 08:44:42 -0600
Subject: [Tutor] Embedding
In-Reply-To: <mailman.2871.1127873608.508.tutor@python.org>
References: <mailman.2871.1127873608.508.tutor@python.org>
Message-ID: <433AAC5A.2030208@gmail.com>

Hi,
Ok, I'll try to convince them to try python... but still, would it be 
best to just:
Program in C with Python and Java scripts
Program in Python with a little bit of C?

The game we're trying to make is a Super Mario type game (or super tux 
for you like linux games).
I suppose pygame would make it a breeze for video, sound and graphics!  
My only problem is I haven't done any games withy pygame at all and 
can't find any pygame tutorials (when I google).
Thanks,
  Joe


From grouch at gmail.com  Wed Sep 28 17:13:07 2005
From: grouch at gmail.com (Andrew P)
Date: Wed, 28 Sep 2005 10:13:07 -0500
Subject: [Tutor] script question
In-Reply-To: <9f68812f050928053548024051@mail.gmail.com>
References: <9f68812f05092604563052918f@mail.gmail.com>
	<43387C41.20307@tds.net> <4338A883.7020001@tds.net>
	<9f68812f050928053548024051@mail.gmail.com>
Message-ID: <e6443aa70509280813389cde9@mail.gmail.com>

Have you benchmarked it yet? 4000 lines isn't very many, even for an older
machine. Starting the Python interpreter usually takes most of the time with
simple scripts like this. Honestly, benchmark :)

You might find it easier to do::

interface_list = INI.items(section)
for i in interface_list:
if i[1] == interface:
...
the items method just returns the whole section in a list of tuples, so
don't have to build it yourself.

One last you may also want to consider is lowercasing any input, because
last I checked ConfigParser lowercases what it parses whether you want it to
or not :)

So if somebody searches for NetworkDevice10, ConfigParser will return it as
networkdevice10, and you won't get a match. That certainly bit me a couple
times.

Good luck.

On 9/28/05, Chris Hallman <challman at gmail.com> wrote:
>
> Thanks for all the input!!! I really appreciate it. I need to post a
> correction to my script. What I sent was an early version. I made a few
> minor modifications:
>
> import ConfigParser, string, sys, os
> section = sys.argv[1]
> interface = sys.argv[3]
> INI=ConfigParser.ConfigParser()
> INI.read("c:\utils\interfaces.ini")
> interface_entries=[p for p in INI.options(section)]
> interface_list=[INI.get(section, pw) for pw in interface_entries]
> for i in interface_list:
> 	if i == interface:
> 		os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet -n l17aesm1 forward red held " +
>
> sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])
>
>
> I've researched what you all have suggested and I may need to switch to
> reading the ini file line by line or using a different file parser. The ini
> file is only 100 lines long now, but will likely grow to 500 line and maybe
> to 4000 lines. To give you a better background of what I'm doing with this
> script, it's running on a network management system that receives traps.
> After some processing of the raw trap, messages get sent to this script for
> further processing. These messages are for interface down traps from routers
> and switches in our network. I use this script to mitigate the number of
> interface down messages on our console. I need to do this because we do not
> need to know when every port has gone down (i.e. user ports). This script
> searches the ini file for a device name match. Once it has found a match and
> if the interface matches as well, I need to message forwarded to the console
> (the Windows command). If no matching device or interface is found, then the
> script can just exit. - Show quoted text -
>
>
> On 9/26/05, Kent Johnson <kent37 at tds.net> wrote:
> >
> > Kent Johnson wrote:
> > > *TEST FIRST* Don't optimize until you know it is too slow and you
> > > have a test case that you can time to see if your 'optimizations' are
> > > making it faster.
> >
> > Pardon my shouting :-)
> >
> > Kent
> >
> > _______________________________________________
> > 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
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050928/6bfafe0a/attachment.html

From kent37 at tds.net  Wed Sep 28 17:37:56 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 28 Sep 2005 11:37:56 -0400
Subject: [Tutor] Embedding
In-Reply-To: <433AAC5A.2030208@gmail.com>
References: <mailman.2871.1127873608.508.tutor@python.org>
	<433AAC5A.2030208@gmail.com>
Message-ID: <433AB8D4.200@tds.net>

Joseph Quigley wrote:
> Hi,
> Ok, I'll try to convince them to try python... but still, would it be 
> best to just:
> Program in C with Python and Java scripts

This seems like a poor choice. Some commercial games have been written with the main game engine in C and Python used to script some game elements. My guess is that to have some game elements scripted in Python and some in C would be problematic. I guess you could program in C with Jython and Java scripts...

> Program in Python with a little bit of C?

That sounds more practical to me. Though I confess I haven't actually written any games this way, ISTM you could start with Python + Pygame and rewrite to C for performance as needed.

> 
> The game we're trying to make is a Super Mario type game (or super tux 
> for you like linux games).
> I suppose pygame would make it a breeze for video, sound and graphics!  
> My only problem is I haven't done any games withy pygame at all and 
> can't find any pygame tutorials (when I google).

Did you look on the pygame site?
http://pygame.org/tutorials.html

Also many of the sample games are open source:
http://pygame.org/projects/20

Search comp.lang.python for "game programming":
http://groups.google.com/group/comp.lang.python/search?hl=en&group=comp.lang.python&q=game+programming&qt_g=1&searchnow=Search+this+group

The rules page for the PyWeek Game Programming Challenge lists many other game programming resources. Also the submissions to this challenge are open source:
http://www.mechanicalcat.net/tech/PyWeek/1/rules.html/#entries-are-to-be-written-from-scratch

Kent


From mhansen at cso.atmel.com  Wed Sep 28 18:02:13 2005
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Wed, 28 Sep 2005 10:02:13 -0600
Subject: [Tutor] web development
In-Reply-To: <mailman.2870.1127873608.508.tutor@python.org>
References: <mailman.2870.1127873608.508.tutor@python.org>
Message-ID: <433ABE85.4020000@cso.atmel.com>

> Subject:
> [Tutor] web development
> From:
> Don Jennings <djennings3 at earthlink.net>
> Date:
> Tue, 27 Sep 2005 22:13:30 -0400
> To:
> tutor at python.org
> 
> To:
> tutor at python.org
> 
> 
> Earlier this month, Kent posted that Jython and Velocity are a good way 
> to develop dynamic web sites. After a little searching, it seems that 
> there are quite a few options for web development in Python (perhaps too 
> many?). So, rather than ask for recommendations of which one to use, 
> what I would really like to know are how people decided to use any 
> particular framework.
> 
> Thanks!
> Don
> 
> P.S. As an aside, does anyone have any experience with django? (I really 
> like the name since I am fond of django reinhardt, the jazz guitarist.)
> 

I've looked at a few of the web development frameworks for Python. I'm thinking 
I'm going with CherryPy on my next project. Reading the docs, it seems to click 
with me. Mapping URLs directly to python functions seems pretty simple and 
flexible. The POST and GET parameters just show up as arguments to your 
functions. You can even decide weather or not you want to expose the function or 
not. You can use any HTML templating toolkit you want with it. I'm still 
deciding on the templating toolkit to use.

Here's my take on some of the other frameworks....

Zope
It seems too big for my purposes. If your web apps are going to be high volume, 
Zope is probably the answer.

Quixote
It seems a little weird and complex to me. I may look at it again someday.

Django
Uses the MVC philosophy, and appears to build a directory structure to 
facilitate that philosophy. I'm not sure I want to go there yet in that you need 
to work its way and not your way. I've heard that it's very similar to Ruby on 
Rails.

Nevow
If I recall, it extracted woven from the Twisted Framework so that it could work 
on it's own. Kind of reminded me of Quixote.

There are many others that I passed on for various reasons.

For me, if it looked like a steep learning curve, then I thought I'd be better 
off with something else. I also wanted something that's been around for a 
while(stable) with a good size community to help if I got stuck. It had to be 
fairly easy to install and configure. I didn't want to spend all my time getting 
it up and running on a development server. Then having problems when it's time 
to install on a production server or other servers at different locations.

Mike

From chris.arndt at web.de  Wed Sep 28 19:19:07 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Wed, 28 Sep 2005 18:19:07 +0100
Subject: [Tutor] Reformatting a one (long) line xml file
In-Reply-To: <2fdabf1905092807165e304df9@mail.gmail.com>
References: <2fdabf1905092807165e304df9@mail.gmail.com>
Message-ID: <433AD08B.7030904@web.de>

Negroup - schrieb:
> Hi all, I have an xml file where the tags are all on the same line,
> without any newline. This file is quite big and difficult to read. I'd
> like to format it in a convenient way, using indentation and nesting.
> How to pretty print my content?

Untested:

import sys
from xml.dom import minidom
file = sys.argv[1]

doc = minidom.parse(file)
print doc.toprettyxml(indent=2)


See http://www.python.org/doc/current/lib/module-xml.dom.minidom.html for more
info.

HTH, Chris

From dyoo at hkn.eecs.berkeley.edu  Wed Sep 28 20:37:34 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 28 Sep 2005 11:37:34 -0700 (PDT)
Subject: [Tutor] Prevent "Coder's Remorse"?
In-Reply-To: <s33a49e5.063@cosegw.cose.summitoh.net>
Message-ID: <Pine.LNX.4.44.0509281125460.13372-100000@hkn.eecs.berkeley.edu>



On Wed, 28 Sep 2005, Ron Phillips wrote:

> Maybe it's just me. I am always haunted by "coder's remorse" (the
> certainty that there's a more compact, beautiful, fun, maintainable way
> to code anything I finish.)
>
>  At any rate, I am currently working on a script to model an ordered
> collection of geographic points, all of which must share the same
> collection of attributes. So, a little collection might be:
>
> pointList = [
> {lat:40.123,lon:-81.456,
>     'attributes':{'msg':'example','beavers':34, 'distance':18.132}
> },
> {lat:40.12345,lon:-81.45678,
>     'attributes':{'msg':'','beavers':0, 'distance':0.0}
> }
> ]

Hi Ron,

You may want to change the data structure.

Rather than have points all be peers, reorganize them so that there's some
kind of hierarchy: that'll help you directly represent the "sharing" of
attributes.  Explicitly:

#########################################################
class Point:
    def __init__(self, lat, lon, atts, parent=None):
        (self.lat, self.lon, self.atts, self.parent) = (
              lat, long, atts, parent)
    def lookup(self, name):
        if name in self.atts:
            return self.atts[name]
        if self.parent:
            return self.parent.lookup(name)
        raise KeyError
#########################################################


The idea here is that we impose some structure among the points.  We can
keep a central Point that has a set of child points within its satellite.

######
>>> centralPoint = Point(40, -81, {})
>>> satellitePoint = Point(40, -81, {}, centralPoint)
######


Once we formalize this hierarchical relationship --- satellitePoint's
"parent" is centralPoint --- then we can test out how attribute lookup and
sharing might work:

######
>>> satellitePoint = Point(40, -81, {}, centralPoint)
>>> centralPoint.atts['color'] = 'purple'
>>> satellitePoint.lookup('color')
'purple'
######


Does this make sense?


From RPhillips at engineer.co.summit.oh.us  Wed Sep 28 21:18:09 2005
From: RPhillips at engineer.co.summit.oh.us (Ron Phillips)
Date: Wed, 28 Sep 2005 15:18:09 -0400
Subject: [Tutor] Prevent "Coder's Remorse"?
Message-ID: <s33ab44e.039@cosegw.cose.summitoh.net>

Ok, I have three diverse answers from three of the tutors that I respect
most. 
 
Kent Johnson's approach: subclass dict and overloads the __getitem__ ,
__setitem__, and __delitem__ methods.
 
Alan G's idea:
 ". . .
Get the init method to update a global (or class based) 
list of instances and write a del() method that removes 
itself.
 
Then a class method can iterate that instance list 
doing whatever it needs to do..."

And Danny Yoo's hierarchical structure:

". . .
The idea here is that we impose some structure among the points.  We
can
keep a central Point that has a set of child points within its
satellite.

######
>>> centralPoint = Point(40, -81, {})
>>> satellitePoint = Point(40, -81, {}, centralPoint)
######

. . ."

Very clever ideas, as far as I can tell. I need to play with all three
of them so that I understand them thoroughly.  I think that once I do,
I'll be able to say I really understand OOP in Python! I believe that
any one of these approaches will do what I need, though, so maybe it
comes down to style.

Maybe I should explain why I thought I wanted this object. I am trying
to read, edit, and write shapefiles (actually, a shapefile is a
collection of 3-6 files having the same filename, but different
extensions. It's a legacy format that still gets a lot of use in
geography.)

One of the constituent files in a shapefile is a variant of Xbase,
which knows nothing  about NULL, so I have to provide some value in
every column for every record when I write them. I thought that having a
data structure that enforces a common set of "fields", the application
would be more robust when it's being edited. (Prevent me from deleting
an item for one record and not others, or adding a field to a record
without adding at least some default value to all the others.)

I just thought about it, but a CSV file has kind of the same problem.

Thanks, everyone; this will be a real education, however I go!

Ron

From adam.jtm30 at gmail.com  Wed Sep 28 22:23:28 2005
From: adam.jtm30 at gmail.com (Adam)
Date: Wed, 28 Sep 2005 22:23:28 +0200
Subject: [Tutor] Reformatting a one (long) line xml file
In-Reply-To: <2fdabf1905092807165e304df9@mail.gmail.com>
References: <2fdabf1905092807165e304df9@mail.gmail.com>
Message-ID: <be4fbf9205092813236b3921f0@mail.gmail.com>

BeautifulSoup <http://www.crummy.com/software/BeautifulSoup/> is a brilliant
module for this kind of thing. Just make an instance of a parser feed() in
the file with file.read() then .prettify()

On 28/09/05, Negroup - <negroup at gmail.com> wrote:
>
> Hi all, I have an xml file where the tags are all on the same line,
> without any newline. This file is quite big and difficult to read. I'd
> like to format it in a convenient way, using indentation and nesting.
> How to pretty print my content?
>
> I hope to have explained well enough my problem, differently let me know.
>
> Thans a lot!
> _______________________________________________
> 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/20050928/42e1ae28/attachment.htm

From tutor.python.org at pooryorick.com  Wed Sep 28 22:36:11 2005
From: tutor.python.org at pooryorick.com (Poor Yorick)
Date: Wed, 28 Sep 2005 16:36:11 -0400
Subject: [Tutor] Prevent "Coder's Remorse"?
In-Reply-To: <Pine.LNX.4.44.0509281125460.13372-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509281125460.13372-100000@hkn.eecs.berkeley.edu>
Message-ID: <433AFEBB.7090803@pooryorick.com>

Danny Yoo wrote:

>You may want to change the data structure.
>
>Rather than have points all be peers, reorganize them so that there's some
>kind of hierarchy: that'll help you directly represent the "sharing" of
>attributes.  Explicitly:
>
>#########################################################
>class Point:
>    def __init__(self, lat, lon, atts, parent=None):
>        (self.lat, self.lon, self.atts, self.parent) = (
>              lat, long, atts, parent)
>    def lookup(self, name):
>        if name in self.atts:
>            return self.atts[name]
>        if self.parent:
>            return self.parent.lookup(name)
>        raise KeyError
>#########################################################
>
>  
>

Many thanks Danny.  This example was an moment of epiphany for me, one
that will probably drastically influence me in the future.  I owe you
big time!

--
Poor Yorick


From jeffpeery at yahoo.com  Wed Sep 28 23:28:06 2005
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Wed, 28 Sep 2005 14:28:06 -0700 (PDT)
Subject: [Tutor] hiding a notebook page
Message-ID: <20050928212806.41929.qmail@web30505.mail.mud.yahoo.com>

hello, I'm using wxpython to write a windows app. I want to be able to hide a page in a notebook and I'm not sure how to do it. functionally its the same as doing:
 
notebook.Show(False)
 
but I want that to work for just one notebook page and not the whole notebook. I tried the wxpython list but didn't have much luck. any help would be much appreciated. thanks!
 
Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050928/02f1e567/attachment.html

From dubberlyr at msn.com  Wed Sep 28 22:41:36 2005
From: dubberlyr at msn.com (Rosalee Dubberly)
Date: Wed, 28 Sep 2005 13:41:36 -0700
Subject: [Tutor] Frustrated Beginner
Message-ID: <BAY107-F1858668B03E2A2A12A1686A48D0@phx.gbl>

I am trying to learn Python to use in my lesson plans. I am using Windows XP 
and the textbooks I am using are Beginning Python by WROX and Learning 
Pyhton by O'Reilly.

I am definning a range of words 0 to 55, if the number is divisible by 
3,7,11 with no remainder print eggs, else print spam. This works.

def firstpart():
   for n in range(0, 55):
      if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
          print 'eggs,',
      else:
          print 'spam,',
# Now I am trying to modify the function to replace eggs with toast and spam 
with jelly. I have spent days and nothing works. Can you send me in the 
right direction??
Rosa Dubberly
dubberlyr at msn.com

_________________________________________________________________
Don’t just search. Find. Check out the new MSN Search! 
http://search.msn.click-url.com/go/onm00200636ave/direct/01/


From amonroe at columbus.rr.com  Wed Sep 28 23:48:08 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Wed, 28 Sep 2005 17:48:08 -0400
Subject: [Tutor] Frustrated Beginner
In-Reply-To: <BAY107-F1858668B03E2A2A12A1686A48D0@phx.gbl>
References: <BAY107-F1858668B03E2A2A12A1686A48D0@phx.gbl>
Message-ID: <134957759154.20050928174808@columbus.rr.com>

> I am trying to learn Python to use in my lesson plans. I am using Windows XP 
> and the textbooks I am using are Beginning Python by WROX and Learning 
> Pyhton by O'Reilly.

> I am definning a range of words 0 to 55, if the number is divisible by 
> 3,7,11 with no remainder print eggs, else print spam. This works.

> def firstpart():
>    for n in range(0, 55):
>       if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
>           print 'eggs,',
>       else:
>           print 'spam,',
> # Now I am trying to modify the function to replace eggs with toast and spam 
> with jelly. I have spent days and nothing works. Can you send me in the 
> right direction??

It seems like you could just backspace the old words and type the new
words in their place. Unless I misundertand the purpose of the
program.

Alan


From bvande at po-box.mcgill.ca  Thu Sep 29 00:55:55 2005
From: bvande at po-box.mcgill.ca (Brian van den Broek)
Date: Wed, 28 Sep 2005 17:55:55 -0500
Subject: [Tutor] Frustrated Beginner
In-Reply-To: <BAY107-F1858668B03E2A2A12A1686A48D0@phx.gbl>
References: <BAY107-F1858668B03E2A2A12A1686A48D0@phx.gbl>
Message-ID: <433B1F7B.5000807@po-box.mcgill.ca>

Rosalee Dubberly said unto the world upon 2005-09-28 15:41:
> I am trying to learn Python to use in my lesson plans. I am using 
> Windows XP and the textbooks I am using are Beginning Python by WROX and 
> Learning Pyhton by O'Reilly.
> 
> I am definning a range of words 0 to 55, if the number is divisible by 
> 3,7,11 with no remainder print eggs, else print spam. This works.
> 
> def firstpart():
>   for n in range(0, 55):
>      if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
>          print 'eggs,',
>      else:
>          print 'spam,',
> # Now I am trying to modify the function to replace eggs with toast and 
> spam with jelly. I have spent days and nothing works. Can you send me in 
> the right direction??
> Rosa Dubberly
> dubberlyr at msn.com


Hi Rosa,

does this do the sort of thing you want?

 >>> def conditional_print(test_data, first_msg, second_msg):
	if test_data > 0:
		print first_msg
	else:
		print second_msg

		
 >>> conditional_print(5, "Positive!", "Non-positive!")
Positive!
 >>> conditional_print(-4, "Positive!", "Non-positive!")
Non-positive!
 >>> conditional_print(5, "Spam!", "Ham!")
Spam!
 >>> conditional_print("all strings are ", "greater than 0.", "less 
than o.")
greater than 0.
 >>>

Best,

Brian vdB


From ds-python-tutor at sidorof.com  Thu Sep 29 01:03:44 2005
From: ds-python-tutor at sidorof.com (DS)
Date: Wed, 28 Sep 2005 16:03:44 -0700
Subject: [Tutor] call a def/class by reference
Message-ID: <433B2150.7020904@sidorof.com>

Is it possible to call a function or class by reference, aside from
using an eval approach?

What I would like to do is have a loop that processes functions by:

    1.  gettting the input that consists of a function and its parameters,
    2.  determining if the function is on an approved function list,
    3.  executing the function
    4.  rinse, repeat.

I don't actually mind eval, but I would want to make sure I inspect
everything pretty thorougly before executing.

Thanks for any help you can give me.

ds

From adam.jtm30 at gmail.com  Thu Sep 29 01:13:08 2005
From: adam.jtm30 at gmail.com (Adam)
Date: Thu, 29 Sep 2005 01:13:08 +0200
Subject: [Tutor] call a def/class by reference
In-Reply-To: <433B2150.7020904@sidorof.com>
References: <433B2150.7020904@sidorof.com>
Message-ID: <be4fbf9205092816136c7f2db0@mail.gmail.com>

How about something like this

def foo(bar):
print bar

d = {"foo":foo}
s = "foo"
params = "bar"
try: d[s](params)
except: KeyError

Then you can just put the allowed functions into the dictionary.

On 29/09/05, DS <ds-python-tutor at sidorof.com> wrote:
>
> Is it possible to call a function or class by reference, aside from
> using an eval approach?
>
> What I would like to do is have a loop that processes functions by:
>
> 1. gettting the input that consists of a function and its parameters,
> 2. determining if the function is on an approved function list,
> 3. executing the function
> 4. rinse, repeat.
>
> I don't actually mind eval, but I would want to make sure I inspect
> everything pretty thorougly before executing.
>
> Thanks for any help you can give me.
>
> ds
> _______________________________________________
> 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/20050929/727ec11d/attachment-0001.htm

From ds-python-tutor at sidorof.com  Thu Sep 29 01:29:15 2005
From: ds-python-tutor at sidorof.com (DS)
Date: Wed, 28 Sep 2005 16:29:15 -0700
Subject: [Tutor] call a def/class by reference
In-Reply-To: <be4fbf9205092816136c7f2db0@mail.gmail.com>
References: <433B2150.7020904@sidorof.com>
	<be4fbf9205092816136c7f2db0@mail.gmail.com>
Message-ID: <433B274B.7090001@sidorof.com>

Thanks for answering my question.  What I'm hoping to avoid is an
explicit reference to any of the called functions within the program.  
By doing it that way, it would avoid a maintenance problem of having to
remember to put a reference for every new function in the calling program.

ds


Adam wrote:

> How about something like this
>
> def foo(bar):
>     print bar
>
> d = {"foo":foo}
> s = "foo"
> params = "bar"
> try: d[s](params)
> except: KeyError
>
> Then you can just put the allowed functions into the dictionary.
>
> On 29/09/05, *DS* <ds-python-tutor at sidorof.com
> <mailto:ds-python-tutor at sidorof.com>> wrote:
>
>     Is it possible to call a function or class by reference, aside from
>     using an eval approach?
>
>     What I would like to do is have a loop that processes functions by:
>
>         1.  gettting the input that consists of a function and its
>     parameters,
>         2.  determining if the function is on an approved function list,
>         3.  executing the function
>         4.  rinse, repeat.
>
>     I don't actually mind eval, but I would want to make sure I inspect
>     everything pretty thorougly before executing.
>
>     Thanks for any help you can give me.
>
>     ds
>     _______________________________________________
>     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 Goofball223 at wmconnect.com  Thu Sep 29 01:39:37 2005
From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com)
Date: Wed, 28 Sep 2005 19:39:37 EDT
Subject: [Tutor] help with running graphics program
Message-ID: <146.4d95667d.306c83b9@wmconnect.com>

Hello

I downloaded the graphics.py file and have it saved on my computer but 
everytime I run the following program I seem to keep getting an error.

from graphics import*

def main():
    win=GraphWin()
    shape = Circle(Point(50,50), 20)
    shape.setOutline("red")
    shape.setFill("red")
    shape.draw(win)
    for i in range(10):
        p = win.getMouse()
        c = shape.getCenter()
        dx = p.getX() - c.getX()
        dy = p.getY -c.getY()
        shape.move(dx,dy)
    win.close()
main()   


Traceback (most recent call last):
  File "C:/Python24/circle", line 1, in -toplevel-
    from graphics import*
ImportError: No module named graphics

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050928/8299fc2e/attachment.htm

From dubberlyr at msn.com  Thu Sep 29 00:39:39 2005
From: dubberlyr at msn.com (Rosalee Dubberly)
Date: Wed, 28 Sep 2005 15:39:39 -0700
Subject: [Tutor] Alan's responce  frustrated beginner
Message-ID: <BAY107-F27C65BD914801592051186A48D0@phx.gbl>

I want to save this file, import it and make the changes, eggs = toast, spam 
= jelly and change the values if needed.

def firstpart():
   for n in range(0, 55):
      if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
          print 'eggs,',
      else:
          print 'spam,',
Rosa Dubberly

_________________________________________________________________
On the road to retirement? Check out MSN Life Events for advice on how to 
get there! http://lifeevents.msn.com/category.aspx?cid=Retirement


From cpu.crazy at gmail.com  Thu Sep 29 01:51:10 2005
From: cpu.crazy at gmail.com (Joseph Quigley)
Date: Wed, 28 Sep 2005 17:51:10 -0600
Subject: [Tutor] More than one thing at a time?
Message-ID: <433B2C6E.5070501@gmail.com>

Hi, I've got a problem:
I've got a semi working IRC client. There's a function that is for 
receiving and one for sending. How can I have a loop where I can receive 
messages, yet still have a send prompt?
Thanks,
    Joe

From dyoo at hkn.eecs.berkeley.edu  Thu Sep 29 01:52:41 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 28 Sep 2005 16:52:41 -0700 (PDT)
Subject: [Tutor] call a def/class by reference
In-Reply-To: <433B274B.7090001@sidorof.com>
Message-ID: <Pine.LNX.4.44.0509281647480.25447-100000@hkn.eecs.berkeley.edu>



> Thanks for answering my question.  What I'm hoping to avoid is an
> explicit reference to any of the called functions within the program.
> By doing it that way, it would avoid a maintenance problem of having to
> remember to put a reference for every new function in the calling
> program.


In your list of requirements:

>    1.  gettting the input that consists of a function and its
>        parameters,
>    2.  determining if the function is on an approved function list,
>    3.  executing the function
>    4.  rinse, repeat.

the second one is probably the one that needs clarifying.

How do you know which functions should be callable? Adam's approach to
expressing that knowledge is to use a dictionary:

    d = {"foo" : foo}

And there are many other ways of doing this besides a hardcoded
dictionary.

Tell us more about what you mean for a function to be "approved", and we
should be able to suggest practical ways to do what you want.



From dyoo at hkn.eecs.berkeley.edu  Thu Sep 29 01:54:02 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 28 Sep 2005 16:54:02 -0700 (PDT)
Subject: [Tutor] help with running graphics program
In-Reply-To: <146.4d95667d.306c83b9@wmconnect.com>
Message-ID: <Pine.LNX.4.44.0509281653040.25447-100000@hkn.eecs.berkeley.edu>



On Wed, 28 Sep 2005 Goofball223 at wmconnect.com wrote:

> I downloaded the graphics.py file and have it saved on my computer but
> everytime I run the following program I seem to keep getting an error.

[some text cut]

> Traceback (most recent call last):
>   File "C:/Python24/circle", line 1, in -toplevel-
>     from graphics import*
> ImportError: No module named graphics


What directory did you download 'graphics.py' into?  Make sure that it
does have a .py suffix, and that it's in the same directory as your
'circle' program.


From Goofball223 at wmconnect.com  Thu Sep 29 01:54:03 2005
From: Goofball223 at wmconnect.com (Goofball223@wmconnect.com)
Date: Wed, 28 Sep 2005 19:54:03 EDT
Subject: [Tutor] drawing squares
Message-ID: <211.a2df4a2.306c871b@wmconnect.com>

Hello

How would I get the following program to draw squares instead of circles?


from graphics import*

def main():
    win=GraphWin()
    shape = Circle(Point(50,50), 20)
    shape.setOutline("red")
    shape.setFill("blue")
    shape.draw(win)
    for i in range(10):
        p = win.getMouse()
        c = shape.getCenter()
        dx = p.getX() - c.getX()
        dy = p.getY -c.getY()
        shape.move(dx,dy)
    win.close()
main() 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050928/88a504b6/attachment.html

From dyoo at hkn.eecs.berkeley.edu  Thu Sep 29 01:58:13 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 28 Sep 2005 16:58:13 -0700 (PDT)
Subject: [Tutor] Alan's responce  frustrated beginner
In-Reply-To: <BAY107-F27C65BD914801592051186A48D0@phx.gbl>
Message-ID: <Pine.LNX.4.44.0509281654140.25447-100000@hkn.eecs.berkeley.edu>



On Wed, 28 Sep 2005, Rosalee Dubberly wrote:

> I want to save this file, import it and make the changes, eggs = toast, spam
> = jelly and change the values if needed.
>
> def firstpart():
>    for n in range(0, 55):
>       if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
>           print 'eggs,',
>       else:
>           print 'spam,',


Hi Rosalee,

It sounds like you're still stuck trying to input programs into Python.
Are you using a "programming text editor"?  If not, then you may want to
look at:

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

That guide should help you get started.  Some of the notes there are a
little outdated since IDLE has been changed a bit since Python 2.1.  In
particular, "Run Script" is now "Run Module" in the Run menu.  But other
than that, that IDLE guide should be relevant.

Please free free to ask questions.  Good luck!


From dyoo at hkn.eecs.berkeley.edu  Thu Sep 29 02:07:08 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 28 Sep 2005 17:07:08 -0700 (PDT)
Subject: [Tutor] drawing squares
In-Reply-To: <211.a2df4a2.306c871b@wmconnect.com>
Message-ID: <Pine.LNX.4.44.0509281658240.25447-100000@hkn.eecs.berkeley.edu>



On Wed, 28 Sep 2005 Goofball223 at wmconnect.com wrote:

> How would I get the following program to draw squares instead of circles?

What have you tried so far?  What part of your program is the part
responsible for drawing circles?  What happens if you change that part?


To tell the blunt truth, the questions you've been asking so far have been
contentless and, frankly, uninteresting.  Although we do encourage people
to ask questions on Tutor, there is a flip side of this: you have to show
some initiative.  Please do enough to show that you're actually trying
something and doing something to understand things.

Otherwise, it really looks like you don't care about anything other than
getting a "right answer", and nothing demotivates a volunteer more than
being asked to do someone else's homework.  We're interested in helping
people understand how to solve problems, but we're really not interested
in doing your homework exercises.

"How to Ask Questions the Smart Way" talks about this some more:

    http://www.catb.org/~esr/faqs/smart-questions.html

Thanks.


From dyoo at hkn.eecs.berkeley.edu  Thu Sep 29 02:12:19 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 28 Sep 2005 17:12:19 -0700 (PDT)
Subject: [Tutor] call a def/class by reference (fwd)
Message-ID: <Pine.LNX.4.44.0509281712170.25447-100000@hkn.eecs.berkeley.edu>



---------- Forwarded message ----------
Date: Wed, 28 Sep 2005 17:11:07 -0700
From: DS <ds-python-tutor at sidorof.com>
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Subject: Re: [Tutor] call a def/class by reference

Danny Yoo wrote:

>
>
>>Thanks for answering my question.  What I'm hoping to avoid is an
>>explicit reference to any of the called functions within the program.
>>By doing it that way, it would avoid a maintenance problem of having to
>>remember to put a reference for every new function in the calling
>>program.
>>
>>
>
>
>In your list of requirements:
>
>
>
>>   1.  gettting the input that consists of a function and its
>>       parameters,
>>   2.  determining if the function is on an approved function list,
>>   3.  executing the function
>>   4.  rinse, repeat.
>>
>>
>
>the second one is probably the one that needs clarifying.
>
>How do you know which functions should be callable? Adam's approach to
>expressing that knowledge is to use a dictionary:
>
>    d = {"foo" : foo}
>
>And there are many other ways of doing this besides a hardcoded
>dictionary.
>
>Tell us more about what you mean for a function to be "approved", and we
>should be able to suggest practical ways to do what you want.
>
>
>
>
As far as an "approved" function, what I was imagining was something along
the lines of importing modules where all functions are callable such as

approvedlist = dir(mymodule)

which would give a list of names and then going from there.


From ds-python-tutor at sidorof.com  Thu Sep 29 02:17:40 2005
From: ds-python-tutor at sidorof.com (DS)
Date: Wed, 28 Sep 2005 17:17:40 -0700
Subject: [Tutor] call a def/class by reference
Message-ID: <433B32A4.9010302@sidorof.com>


Danny Yoo wrote:

>  
>
>>Thanks for answering my question.  What I'm hoping to avoid is an
>>explicit reference to any of the called functions within the program.
>>By doing it that way, it would avoid a maintenance problem of having to
>>remember to put a reference for every new function in the calling
>>program.
>>    
>>
>
>
>In your list of requirements:
>
>  
>
>>   1.  gettting the input that consists of a function and its
>>       parameters,
>>   2.  determining if the function is on an approved function list,
>>   3.  executing the function
>>   4.  rinse, repeat.
>>    
>>
>
>the second one is probably the one that needs clarifying.
>
>How do you know which functions should be callable? Adam's approach to
>expressing that knowledge is to use a dictionary:
>
>    d = {"foo" : foo}
>
>And there are many other ways of doing this besides a hardcoded
>dictionary.
>
>Tell us more about what you mean for a function to be "approved", and we
>should be able to suggest practical ways to do what you want.
>
>
>  
>
As far as an "approved" function, what I was imagining was something along
the lines of importing modules where all functions are callable such as

approvedlist = dir(mymodule)

which would give a list of names and then going from there.



From dyoo at hkn.eecs.berkeley.edu  Thu Sep 29 02:16:21 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 28 Sep 2005 17:16:21 -0700 (PDT)
Subject: [Tutor] drawing squares
In-Reply-To: <Pine.LNX.4.44.0509281658240.25447-100000@hkn.eecs.berkeley.edu>
Message-ID: <Pine.LNX.4.44.0509281713200.25447-100000@hkn.eecs.berkeley.edu>



> Otherwise, it really looks like you don't care about anything other than
> getting a "right answer", and nothing demotivates a volunteer more than
> being asked to do someone else's homework.  We're interested in helping
> people understand how to solve problems, but we're really not interested
> in doing your homework exercises.

And by homework exercise, I mean Discussion Exercise 3 of Python
Programming: An Introduction to Computer Science:

    http://www.fbeedle.com/python/99-6ch05.pdf

So please, please, don't just copy homework questions and submit them to
this Tutor list: we won't help you much if you do only that.


From magoldfish at gmail.com  Thu Sep 29 02:42:27 2005
From: magoldfish at gmail.com (Marcus Goldfish)
Date: Wed, 28 Sep 2005 20:42:27 -0400
Subject: [Tutor] stopping threads?
Message-ID: <5e183f3d05092817426a34e917@mail.gmail.com>

I'm a little confused about threading in Python. Here is a sample class I've
written for monitoring for events. Included in the comments are a couple of
questions, specifically:
  (1) can I use super() in the constructor, or is direct call to base class
preferred?
 (2) do I need to sleep in the run() method? If so, why? It seems to improve
my programs responsiveness
 (3) what happens after run() finishes-- does the thread die, get suspended,
go away? Should I try to force the thread into one of these states, and if
so how?
 Any help is appreciated!
Thanks,
Marcus
  class Monitor(threading.Thread):
 def __init__(self):
 threading.Thread.__init__(self) # would super() also work here? which is
preferred
 self.undetected = True # presumably, when the event occurs it sets this
attribute to False
  def run(self):
 print "looking for event"
 while self.undetected is True:
 time.sleep(0.1) # another minor point: why do I need to sleep here?
 self.processEvent()
 # what happens here-- does the thread die?
  def processEvent(self):
 print "yeah-- event detected"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050928/033aefd5/attachment.html

From 3dbernard at gmail.com  Thu Sep 29 02:48:35 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Wed, 28 Sep 2005 20:48:35 -0400
Subject: [Tutor] Flattening multi-dimentional list
Message-ID: <61d0e2b4050928174834f088d8@mail.gmail.com>

Hello,

I have this list wich is made of tuples. I wish I could "flatten" this
list, that is, to extract each element in the tuples and build a new
flat list with it. Is there any shortcut to do that or do I have to go
through some list comprehension-like procedure?

(I have looked at sets but I have to keep things ordered).


Thanks
Bernard

From dyoo at hkn.eecs.berkeley.edu  Thu Sep 29 03:01:22 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 28 Sep 2005 18:01:22 -0700 (PDT)
Subject: [Tutor] Flattening multi-dimentional list
In-Reply-To: <61d0e2b4050928174834f088d8@mail.gmail.com>
Message-ID: <Pine.LNX.4.44.0509281800500.12697-100000@hkn.eecs.berkeley.edu>



On Wed, 28 Sep 2005, Bernard Lebel wrote:

> I have this list wich is made of tuples. I wish I could "flatten" this
> list, that is, to extract each element in the tuples and build a new
> flat list with it. Is there any shortcut to do that or do I have to go
> through some list comprehension-like procedure?

Here you go:

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

Hope this helps!


From 3dbernard at gmail.com  Thu Sep 29 03:23:40 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Wed, 28 Sep 2005 21:23:40 -0400
Subject: [Tutor] Flattening multi-dimentional list
In-Reply-To: <Pine.LNX.4.44.0509281800500.12697-100000@hkn.eecs.berkeley.edu>
References: <61d0e2b4050928174834f088d8@mail.gmail.com>
	<Pine.LNX.4.44.0509281800500.12697-100000@hkn.eecs.berkeley.edu>
Message-ID: <61d0e2b4050928182326382f8f@mail.gmail.com>

Thanks a lot Danny.


Bernard



On 9/28/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
>
> On Wed, 28 Sep 2005, Bernard Lebel wrote:
>
> > I have this list wich is made of tuples. I wish I could "flatten" this
> > list, that is, to extract each element in the tuples and build a new
> > flat list with it. Is there any shortcut to do that or do I have to go
> > through some list comprehension-like procedure?
>
> Here you go:
>
>     http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363051
>
> Hope this helps!
>
>

From 3dbernard at gmail.com  Thu Sep 29 03:25:36 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Wed, 28 Sep 2005 21:25:36 -0400
Subject: [Tutor] Problem with BeautifulSoup
In-Reply-To: <4337C8C3.5020701@tds.net>
References: <61d0e2b405092311354fd2d76e@mail.gmail.com>
	<e6443aa7050923120758b6dbc3@mail.gmail.com>
	<61d0e2b405092312154bce6c53@mail.gmail.com> <4337C8C3.5020701@tds.net>
Message-ID: <61d0e2b4050928182566867988@mail.gmail.com>

Hi Kent,

Thanks a lot for that answer. I have had a look at the BS code, and I
have to admit I'm a bit at a loss: how would you add several nestable
tag names in that list?

I tried
NESTABLE_TAGS = BeautifulSoup.buildTagMap( [], 'parameter', 'parameters' )
for example, but I kept having these nesting issues. I fact I have a
whole bunch of tags that I need to make nestable....


Thanks
Bernard


On 9/26/05, Kent Johnson <kent37 at tds.net> wrote:
> Bernard Lebel wrote:
> > Hi grouchy,
> >
> > I seem to have found the problem. Somehow, it seems BeautifulSoup
> > doesn't like nested tags of the same name.
>
> This seems to be a feature of BS. It seems a bit of a misfeature when applied to XML but anyway...you can configure BS with a set of tags which can be nested, then it will properly parse your data. Here is a short program that shows how:
>
> xml = '''<parameter scriptname="posx">
>     <fcurve plotted="False">
>           <parameter scriptname="extrapolation">1</parameter>
>     </fcurve>
> </parameter>'''
>
> import BeautifulSoup
>
> class NestingParser(BeautifulSoup.BeautifulStoneSoup):
>     NESTABLE_TAGS = BeautifulSoup.buildTagMap([], 'parameter')
>
> soup = NestingParser(xml)
> print soup.prettify()
>
>
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From bgailer at alum.rpi.edu  Thu Sep 29 03:31:36 2005
From: bgailer at alum.rpi.edu (bob)
Date: Wed, 28 Sep 2005 18:31:36 -0700
Subject: [Tutor] call a def/class by reference
In-Reply-To: <433B274B.7090001@sidorof.com>
References: <433B2150.7020904@sidorof.com>
	<be4fbf9205092816136c7f2db0@mail.gmail.com>
	<433B274B.7090001@sidorof.com>
Message-ID: <6.1.2.0.0.20050928181702.033e23b0@mail.mric.net>

At 04:29 PM 9/28/2005, DS wrote:
>What I'm hoping to avoid is an
>explicit reference to any of the called functions within the program.
>By doing it that way, it would avoid a maintenance problem of having to
>remember to put a reference for every new function in the calling program.

Try this - a class in which you define all the functions. The __init__ 
method builds the dictionary.

 >>> class X:
...     funcs = {}
...     def y(self):
...             pass
...     def __init__(self):
...             for itemname in dir(self):
...                     if not itemname.startswith('__'):
...                             item = getattr(self, itemname)
...                             if callable(item):
...                                     self.funcs[itemname] = item
...
 >>> y = X()
 >>> y.funcs
{'y': <bound method x.y of <__main__.x instance at 0x01119828>>}
    


From kent37 at tds.net  Thu Sep 29 05:17:59 2005
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 28 Sep 2005 23:17:59 -0400
Subject: [Tutor] Flattening multi-dimentional list
In-Reply-To: <61d0e2b4050928174834f088d8@mail.gmail.com>
References: <61d0e2b4050928174834f088d8@mail.gmail.com>
Message-ID: <433B5CE7.2040908@tds.net>

Bernard Lebel wrote:
> Hello,
> 
> I have this list wich is made of tuples. I wish I could "flatten" this
> list, that is, to extract each element in the tuples and build a new
> flat list with it. Is there any shortcut to do that or do I have to go
> through some list comprehension-like procedure?

If the list is just nested one deep and every element is a tuple then a single list comprehension will do it:

 >>> l=[(1,2), (3,4)]
 >>> [ x for t in l for x in t ]
[1, 2, 3, 4]

Kent


From john at fouhy.net  Thu Sep 29 08:18:19 2005
From: john at fouhy.net (John Fouhy)
Date: Thu, 29 Sep 2005 18:18:19 +1200
Subject: [Tutor] stopping threads?
In-Reply-To: <5e183f3d05092817426a34e917@mail.gmail.com>
References: <5e183f3d05092817426a34e917@mail.gmail.com>
Message-ID: <5e58f2e405092823183e830e86@mail.gmail.com>

On 29/09/05, Marcus Goldfish <magoldfish at gmail.com> wrote:
> I'm a little confused about threading in Python.  Here is a sample class
> I've written for monitoring for events.  Included in the comments are a
> couple of questions, specifically:

Hi Marcus,

>    (1) can I use super() in the constructor, or is direct call to base class
> preferred?

You can use super() --- in fact, there are some circumstances where it
is prefered: if you have complicated inheritance, super() will do a
better job. Check out this article for details:
http://python.org/2.2.3/descrintro.html

>    (2) do I need to sleep in the run() method?  If so, why?  It seems to
> improve my programs responsiveness

Without a sleep(), you are doing what is called "busy waiting". 
Remember, you only have one processor which is only capable of doing
one thing at once.  Without a sleep() call, your program runs
something like this:

#################
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
----- context switch
do something else
run the user interface
----- context switch
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
check self.undetected
  True
...etc.
#################

But when a thread sleeps, python knows that it can do a context switch
immediately, because the thread isn't going to be using the processor.

#################
check self.undetected
 True
sleep
----- context switch
do something else
run the user interface
----- context switch
check self.undetected
 True
sleep
----- context switch
do something else
run the user interface
----- context switch
...etc
#################

Does that help explain?

>    (3) what happens after run() finishes-- does the thread die, get
> suspended, go away?  Should I try to force the thread into one of these
> states, and if so how?

>From the docs:

#################
isAlive()
    Return whether the thread is alive.

    Roughly, a thread is alive from the moment the start() method
returns until its run() method terminates.
#################

If you keep a reference to the object, then it will die, but not go
away.  If you don't keep a reference, I imagine it will be garbage
collected once it dies. (I can't quote you docs for that, though)

There's no easy way to tell a thread to stop.  A common technique is
to make the thread check a boolean every time it goes through its
look.

eg:

#################
def __init__(self, *etc):
 self.die = False

def run(self):
 while not self.die:
  # do stuff

def stop(self):
 self.die = True
#################

HTH!

--
John.

From pierre.barbier at cirad.fr  Thu Sep 29 08:27:42 2005
From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille)
Date: Thu, 29 Sep 2005 08:27:42 +0200
Subject: [Tutor] stopping threads?
In-Reply-To: <5e183f3d05092817426a34e917@mail.gmail.com>
References: <5e183f3d05092817426a34e917@mail.gmail.com>
Message-ID: <433B895E.3060406@cirad.fr>

Hello Marcus,

Marcus Goldfish a ?crit :
> I'm a little confused about threading in Python. Here is a sample class I've
> written for monitoring for events. Included in the comments are a couple of
> questions, specifically:
>   (1) can I use super() in the constructor, or is direct call to base class
> preferred?

IMO, it is better to explicitely call the base class ... I think it is
more readable. But I don't know if there is any drawback for any solution...

>  (2) do I need to sleep in the run() method? If so, why? It seems to improve
> my programs responsiveness

Yes, you need to sleep ! What you're doing is called "polling", you have
an infinite loop watching some state. If you don't wait, you'll use your
processor 100% for ... nothing ! Global responsiveness will decrease as
your program will always ask the OS for run-time ! Now, if you sleep,
you will test the state once, let other threads/process run and watch
some other time... 0.1 sec is quite a long time for processes and so
short for us ;) So if you need human-time responsiveness, you definitely
need this sleep. However, you may consider other way of
blocking/watching like using events or semaphors. So that your thread
will be blocked until someone releases it by sending the event or
releasing the semaphor.

>  (3) what happens after run() finishes-- does the thread die, get suspended,
> go away? Should I try to force the thread into one of these states, and if
> so how?

Yop ! after run() finishes, the thread dies. This is the normal way to
finish a thread ... just end its main function :)

>  Any help is appreciated!
> Thanks,
> Marcus
>   class Monitor(threading.Thread):
>  def __init__(self):
>  threading.Thread.__init__(self) # would super() also work here? which is
> preferred
>  self.undetected = True # presumably, when the event occurs it sets this
> attribute to False
>   def run(self):
>  print "looking for event"
>  while self.undetected is True:
>  time.sleep(0.1) # another minor point: why do I need to sleep here?
>  self.processEvent()
>  # what happens here-- does the thread die?
>   def processEvent(self):
>  print "yeah-- event detected"
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68

From negroup at gmail.com  Thu Sep 29 08:43:19 2005
From: negroup at gmail.com (Negroup -)
Date: Thu, 29 Sep 2005 08:43:19 +0200
Subject: [Tutor] Reformatting a one (long) line xml file
In-Reply-To: <433AD08B.7030904@web.de>
References: <2fdabf1905092807165e304df9@mail.gmail.com>
	<433AD08B.7030904@web.de>
Message-ID: <2fdabf19050928234362f0ed4f@mail.gmail.com>

2005/9/28, Christopher Arndt <chris.arndt at web.de>:
[cut]
>
> See http://www.python.org/doc/current/lib/module-xml.dom.minidom.html for more
> info.

Hi, this seems to be exactly what I was looking for!

import sys
from xml.dom import minidom

INDENT = ' ' * 4

file = sys.argv[1]

content = open(file).read()

pretty = minidom.parseString(content).toprettyxml(indent=INDENT).encode('utf-8')
beautiful = open('%s.pretty' % file, 'w')
beautiful.write(pretty)
beautiful.close()

I looked at BeautifulSoup, as Adam suggested. However it seems very
powerful and probably *too* powerful for my actual simple needings.
Anyway I will remember for the future.

> HTH, Chris

Thanks both of you!

From alan.gauld at freenet.co.uk  Thu Sep 29 09:22:00 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Thu, 29 Sep 2005 08:22:00 +0100
Subject: [Tutor] Alan's responce  frustrated beginner
References: <BAY107-F27C65BD914801592051186A48D0@phx.gbl>
Message-ID: <008001c5c4c6$7c28e230$0201a8c0@xp>


>I want to save this file, import it and make the changes, eggs = 
>toast, spam
> = jelly and change the values if needed.
>
> def firstpart():
>   for n in range(0, 55):
>      if n % 3 == 0 or n % 7 == 0 or n % 11 == 0:
>          print 'eggs,',
>      else:
>          print 'spam,',

There are two approaches:

1) Use module level variales for the messages:

#### module testval ####

passMessage = 'eggs'
failMessage = 'spam'

def firstpart():
   for n in range(55):
     if n %3 ..... :
       print passMessage
     else: print failMessage

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

####### clientcode ########

import testval

testVal.passMessage = 'Milk'
testVal.failMessage = 'Honey'

testval.firstpart()

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

2) Use function parameters

def firstpart(iterations, condition, passMsg, failMsg):
   for n in range(iterations):
     if condition:
       print passMsg
     else: print failMsg

firstpart(55,(n % 3 or n % 7 or n % 11), 'eggs','spam')
firstpart(55,(n % 3 or n % 7 or n % 11), 'Milk','Honey')

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

The second approach is probably best IMHO (whether you
parametereise the iterations and condition is optional,
it just makes the function as geeric as possible...)

HTH,

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


From alan.gauld at freenet.co.uk  Thu Sep 29 09:26:52 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Thu, 29 Sep 2005 08:26:52 +0100
Subject: [Tutor] Flattening multi-dimentional list
References: <61d0e2b4050928174834f088d8@mail.gmail.com>
Message-ID: <00a801c5c4c7$2a178e50$0201a8c0@xp>

> I have this list wich is made of tuples. I wish I could "flatten" 
> this list, that is, to extract each element in the tuples and 
> build a new flat list with it. 

Recursion is often used for this, there is an example 
function in my tutorial topic on recursion (using nested 
lists rather than tuples but it should work for either)

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

From ajikoe at gmail.com  Thu Sep 29 09:53:22 2005
From: ajikoe at gmail.com (Pujo Aji)
Date: Thu, 29 Sep 2005 09:53:22 +0200
Subject: [Tutor] Flattening multi-dimentional list
In-Reply-To: <61d0e2b4050928174834f088d8@mail.gmail.com>
References: <61d0e2b4050928174834f088d8@mail.gmail.com>
Message-ID: <cf5262d205092900533c14d3cb@mail.gmail.com>

Hi,
 Use this:

def _flatten(seq,myhasil):
  for isi in seq:
    if type(isi) != str:
      try:
        _flatten(isi,myhasil)
      except:
        myhasil.append(isi)
    else:
      myhasil.append(isi)

def flatten(seq):
  '''code to flatten tupple'''
  hasil = []
  _flatten(seq,hasil)
  return hasil

http://www.uselesspython.com/showcontent.php?author=38

Cheers,
pujo

 On 9/29/05, Bernard Lebel <3dbernard at gmail.com> wrote:
>
> Hello,
>
> I have this list wich is made of tuples. I wish I could "flatten" this
> list, that is, to extract each element in the tuples and build a new
> flat list with it. Is there any shortcut to do that or do I have to go
> through some list comprehension-like procedure?
>
> (I have looked at sets but I have to keep things ordered).
>
>
> Thanks
> Bernard
> _______________________________________________
> 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/20050929/53a3c53b/attachment.htm

From lists at janeden.org  Thu Sep 29 10:11:16 2005
From: lists at janeden.org (Jan Eden)
Date: Thu, 29 Sep 2005 10:11:16 +0200
Subject: [Tutor] New-style classes
Message-ID: <r02010500-1039-9CBD09AA30C011DA9B61000A959B4026@[10.149.23.208]>

Hi,

after updating a program to use new-style classes, I am a bit confused. My setup looks like this (simplified):

#Show.py

import Data

class Base(object):
    ...
    
class Page(Data.Page, Base):
    ...

class Author(Data.Author, Base):
...

#Data.py

class Base:
    ...

class Page(Base):
    ...

class Author(Base):
    ...

The module Show.py provides methods, Data.py provides data attributes. I use the property method in Data.Base for a certain attribute - but why does this work?

Data.Base has no base classes, so it is not based on a built-in type: How can it be a new-style class?

Thanks for any hints,

Jan
-- 
There are 10 kinds of people:  those who understand binary, and those who don't

From kent37 at tds.net  Thu Sep 29 11:49:42 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 29 Sep 2005 05:49:42 -0400
Subject: [Tutor] Prevent "Coder's Remorse"?
In-Reply-To: <433A91A3.2040806@tds.net>
References: <s33a49e5.063@cosegw.cose.summitoh.net> <433A91A3.2040806@tds.net>
Message-ID: <433BB8B6.5030708@tds.net>

Kent Johnson wrote:

> I'm curious about why you want to do this, it is kind of a strange
> requirement. But anyway, here is a class that subclasses dict and
> presents the interface you want to client code. It doesn't actually
> update all instances when you add or delete a key; it keeps a list of
> valid keys in a class attribute and updates this list when you add or
> delete. Then when you access a key it checks the list of valid keys.
> If the key you want is not in the list, you get a KeyError - the
> instance dict is never checked. If the key you want is in the list
> but not in the instance, you get the default value.

This class needs a little more work to correctly model a dictionary - its keys(), values(), items(), __contains__(), __iter__() and iteritems() methods at least need customization to work from the _keys attribute. One way to do this would be to inherit from UserDict.DictMixin; then only keys() would have to be defined.

Kent
 
> I don't see any need to actually add default values to all the dicts.
> Conceivably to save memory you might want to actually delete values
> from all the dicts; to do this you could keep a list of all the
> existing dicts as another class attribute. I'm not sure you will save
> much though as the dict itself probably doesn't resize downward. A
> side effect of not deleting keys is that if you delete and then
> restore a key, instances that had that key before will magically
> restore their old value. This could be a bug or a feature depending
> on your requirements.
> 
> Finally, the set of valid keys is shared by all instances, so if you
> want to use this for two different types of things you will have to
> make subclasses and give each subclass its own _key attribute.> 
> Requires Python 2.3 or greater
> 
> Kent
> 
> # CommonKeysDict.py
> # Make it work with Python 2.3
> try:
>     set
> except NameError:
>     from sets import Set as set
>     
> class CommonKeysDict(dict):
>     """Dictionary where all instances must have the same set of keys
>        and with a default value for unknown keys.
>        
>        >>> d = CommonKeysDict()
>        >>> d[0]
>        Traceback (most recent call last):
>          ...
>        KeyError: 0
>        
>        >>> d[0] = 1
>        >>> d[0]
>        1
>        
>        A second instance will get the default value for keys that are in use:
>        >>> d2 = CommonKeysDict()
>        >>> d2[0]
>        'default'
>        
>        The second instance can have its own values
>        >>> d2[0] = 2
>        >>> d2[0]
>        2
>        >>> d[0]
>        1
>        
>        Deleting a key from any instance removes that key from the allowed set.
>        Note that this doesn't actually delete the key from all instances, it just
>        makes it inaccessible.
>        
>        >>> del d[0]
>        >>> d2[0]
>        Traceback (most recent call last):
>          ...
>        KeyError: 0
>        
>     """
>     
>     _keys = set()
>     
>     def __init__(self, **items):
>         dict.__init__(self, **items)
> 
>     def __getitem__(self, key):
>         if key not in self._keys:
>             raise KeyError, key
>         try: 
>             return dict.__getitem__(self, key)
>         except KeyError:
>             return 'default'
> 
> 
>     def __setitem__(self, key, value):
>         self._keys.add(key)
>         dict.__setitem__(self, key, value)
>     
>     
>     def __delitem__(self, key):
>         self._keys.remove(key)
>         dict.__delitem__(self, key)
>         
>         
> def _test():
>     import doctest
>     doctest.testmod()
> 
> if __name__ == "__main__":
>     _test()
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From kent37 at tds.net  Thu Sep 29 11:54:39 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 29 Sep 2005 05:54:39 -0400
Subject: [Tutor] Prevent "Coder's Remorse"?
In-Reply-To: <s33ab44e.039@cosegw.cose.summitoh.net>
References: <s33ab44e.039@cosegw.cose.summitoh.net>
Message-ID: <433BB9DF.1080305@tds.net>

Ron Phillips wrote:
> Maybe I should explain why I thought I wanted this object. I am trying
> to read, edit, and write shapefiles (actually, a shapefile is a
> collection of 3-6 files having the same filename, but different
> extensions. It's a legacy format that still gets a lot of use in
> geography.)
> 
> One of the constituent files in a shapefile is a variant of Xbase,
> which knows nothing  about NULL, so I have to provide some value in
> every column for every record when I write them. I thought that having a
> data structure that enforces a common set of "fields", the application
> would be more robust when it's being edited. (Prevent me from deleting
> an item for one record and not others, or adding a field to a record
> without adding at least some default value to all the others.)
> 
> I just thought about it, but a CSV file has kind of the same problem.

I think I would try the same solution used by csv.DictWriter - use a writer object that has knowledge of the required fields and a default value. This assumes that at the time of writing you know what the required fields are, which seems reasonable but without knowing more about your app I can't be sure. Then the writer fills in the necessary default values as it writes the data.

Kent


From pjlists at gmail.com  Thu Sep 29 13:21:58 2005
From: pjlists at gmail.com (Peter Jessop)
Date: Thu, 29 Sep 2005 13:21:58 +0200
Subject: [Tutor] Generalising system processes
Message-ID: <7a8d5a0c05092904211474f0cb@mail.gmail.com>

Good day.

Is there a library in Python that generalises the display of processes
in the system.
I am looking for a consistent way of seeing processess, (a python
equivalent of ps(unix) or tasklist (windows).

I have googled but the only suggestion I have found was to install ps
on Windows.

Thanks

Peter Jessop

From kent37 at tds.net  Thu Sep 29 14:02:19 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 29 Sep 2005 08:02:19 -0400
Subject: [Tutor] New-style classes
In-Reply-To: <r02010500-1039-9CBD09AA30C011DA9B61000A959B4026@[10.149.23.208]>
References: <r02010500-1039-9CBD09AA30C011DA9B61000A959B4026@[10.149.23.208]>
Message-ID: <433BD7CB.4030202@tds.net>

Jan Eden wrote:
> Hi,
> 
> after updating a program to use new-style classes, I am a bit confused. My setup looks like this (simplified):
> 
> #Show.py
> 
> import Data
> 
> class Base(object):
>     ...
>     
> class Page(Data.Page, Base):
>     ...
> 
> class Author(Data.Author, Base):
> ...
> 
> #Data.py
> 
> class Base:
>     ...
> 
> class Page(Base):
>     ...
> 
> class Author(Base):
>     ...
> 
> The module Show.py provides methods, Data.py provides data
> attributes. I use the property method in Data.Base for a certain
> attribute - but why does this work?
> 
> Data.Base has no base classes, so it is not based on a built-in type:
> How can it be a new-style class?

Data.Base is not a new-style class, but the classes in Show are. And properties may appear to work in old-style classes. This document
http://www.python.org/2.2.3/descrintro.html#property
says,
Properties do not work for classic classes, but you don't get a clear error when you try this. Your get method will be called, so it appears to work, but upon attribute assignment, a classic class instance will simply set the value in its __dict__ without calling the property's set method, and after that, the property's get method won't be called either.

Here is an old-style class that defines a property:

 >>> class OldStyle:
 ...     def getA(self):
 ...         print "getA"
 ...         return self.__a
 ...     def setA(self, value):
 ...         print "setA"
 ...         self.__a = value
 ...     a = property(getA, setA)
 ...
 >>> o=OldStyle()

OldStyle.getA() is called the first time I access o.a:
 >>> o.a
getA
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in getA
AttributeError: OldStyle instance has no attribute '_OldStyle__a'

Setting a value for a wipes out the property, now it behaves like a normal attribute:
 >>> o.a = 3
 >>> o.a
3

A class that inherits from object and OldStyle is a new-style class and the property works as expected:
 >>> class NewStyle(object, OldStyle):
 ...   pass
 ...
 >>> n=NewStyle()
 >>> n.a
getA
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in getA
AttributeError: 'NewStyle' object has no attribute '_OldStyle__a'
 >>> n.a=3
setA
 >>> n.a
getA
3

Kent


From kent37 at tds.net  Thu Sep 29 14:03:26 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 29 Sep 2005 08:03:26 -0400
Subject: [Tutor] Problem with BeautifulSoup
In-Reply-To: <61d0e2b4050928182566867988@mail.gmail.com>
References: <61d0e2b405092311354fd2d76e@mail.gmail.com>	<e6443aa7050923120758b6dbc3@mail.gmail.com>	<61d0e2b405092312154bce6c53@mail.gmail.com>
	<4337C8C3.5020701@tds.net>
	<61d0e2b4050928182566867988@mail.gmail.com>
Message-ID: <433BD80E.7090003@tds.net>

(resending to the whole list)

Bernard Lebel wrote:
> Hi Kent,
> 
> Thanks a lot for that answer. I have had a look at the BS code, and I
> have to admit I'm a bit at a loss: how would you add several nestable
> tag names in that list?
> 
> I tried
> NESTABLE_TAGS = BeautifulSoup.buildTagMap( [], 'parameter', 'parameters' )
> for example, but I kept having these nesting issues. I fact I have a
> whole bunch of tags that I need to make nestable....

I think that's right but I confess I don't understand that part of the code too well either. Maybe an email to the author? or maybe it's time to try ElementTree (and pdis XPath?) again.

Kent

> 
> 
> Thanks
> Bernard
> 
> 
> On 9/26/05, Kent Johnson <kent37 at tds.net> wrote:
> 
>>Bernard Lebel wrote:
>>
>>>Hi grouchy,
>>>
>>>I seem to have found the problem. Somehow, it seems BeautifulSoup
>>>doesn't like nested tags of the same name.
>>
>>This seems to be a feature of BS. It seems a bit of a misfeature when applied to XML but anyway...you can configure BS with a set of tags which can be nested, then it will properly parse your data. Here is a short program that shows how:
>>
>>xml = '''<parameter scriptname="posx">
>>    <fcurve plotted="False">
>>          <parameter scriptname="extrapolation">1</parameter>
>>    </fcurve>
>></parameter>'''
>>
>>import BeautifulSoup
>>
>>class NestingParser(BeautifulSoup.BeautifulStoneSoup):
>>    NESTABLE_TAGS = BeautifulSoup.buildTagMap([], 'parameter')
>>
>>soup = NestingParser(xml)
>>print soup.prettify()
>>
>>
>>Kent
>>
>>_______________________________________________
>>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
> 
> 



From m.moghimi at gmail.com  Thu Sep 29 14:17:00 2005
From: m.moghimi at gmail.com (Mohammad Moghimi)
Date: Thu, 29 Sep 2005 15:47:00 +0330
Subject: [Tutor] Installing ActiveState Python vs2003
Message-ID: <d91bb71205092905176d20c8ad@mail.gmail.com>

Hi
When I tried to install activestate python(.net implementation of python) to
my visual studio 2003.
It gives me this error message:
----------------------------------------------------------------------------------------------------
The Visual Python Installer found an installation of Python 2.4,
but it also requires the win32 extensions.
----------------------------------------------------------------------------------------------------
what's the problem?
-- Mohammad
do you Python?!!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050929/82af7b03/attachment.htm

From lists at janeden.org  Thu Sep 29 15:00:52 2005
From: lists at janeden.org (Jan Eden)
Date: Thu, 29 Sep 2005 15:00:52 +0200
Subject: [Tutor] New-style classes
In-Reply-To: <433BD7CB.4030202@tds.net>
Message-ID: <r02010500-1039-10FE0EE630E911DA9B61000A959B4026@[10.149.23.208]>

Hi Kent,

Kent Johnson wrote on 29.09.2005:

>>Data.Base has no base classes, so it is not based on a built-in
>>type: How can it be a new-style class?
>
>Data.Base is not a new-style class, but the classes in Show are. And
>properties may appear to work in old-style classes. This document
>http://www.python.org/2.2.3/descrintro.html#property says,
>Properties do not work for classic classes, but you don't get a
>clear error when you try this. Your get method will be called, so it
>appears to work, but upon attribute assignment, a classic class
>instance will simply set the value in its __dict__ without calling
>the property's set method, and after that, the property's get method
>won't be called either.

Thanks for your quick reply. I read the document you mentioned before, that's why I was confused.

My actual code looks like this:

class Base:
    def GetOwnType(self):
        try: return self._own_type
        except: return self.child_type
    
    def SetOwnType(self, value):
        self._own_type = value
        
    own_type = property(GetOwnType, SetOwnType)

For some of the subclasses of Base, the attribute own_type is defined, the others should use child_type.

For both groups of subclasses, this works fine - if own_type has not been set somewhere else, self.child_type is returned when calling self.own_type.

When checking Data.Base.__mro__, I get an error, so it is not a new-style class by itself.

On the other hand, every time I use the own_type attribute, I do so via instances of new-style classes (Show.Page, Show.Author etc).

Could it be that the nature of these classes makes the code in Data.Base behave according to the new-style rules?

Thanks,

Jan
-- 
I'd never join any club that would have the likes of me as a member. - Groucho Marx

From amonroe at columbus.rr.com  Thu Sep 29 15:02:12 2005
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu, 29 Sep 2005 09:02:12 -0400
Subject: [Tutor] Generalising system processes
In-Reply-To: <7a8d5a0c05092904211474f0cb@mail.gmail.com>
References: <7a8d5a0c05092904211474f0cb@mail.gmail.com>
Message-ID: <1421012603326.20050929090212@columbus.rr.com>

> Is there a library in Python that generalises the display of processes
> in the system.
> I am looking for a consistent way of seeing processess, (a python
> equivalent of ps(unix) or tasklist (windows).

> I have googled but the only suggestion I have found was to install ps
> on Windows.

On Windows, you can probably use ctypes module to call
CreateToolhelp32Snapshot()

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/perfmon/base/createtoolhelp32snapshot.asp

I have not tried this in Python, though.

Alan


From 3dbernard at gmail.com  Thu Sep 29 15:07:36 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Thu, 29 Sep 2005 09:07:36 -0400
Subject: [Tutor] Flattening multi-dimentional list
In-Reply-To: <00a801c5c4c7$2a178e50$0201a8c0@xp>
References: <61d0e2b4050928174834f088d8@mail.gmail.com>
	<00a801c5c4c7$2a178e50$0201a8c0@xp>
Message-ID: <61d0e2b405092906072d02af44@mail.gmail.com>

Thanks for the examples and references everyone.

I should clarify though that I was simply looking for a *built-in*
feature rather than a function or a list-comprehension. I know these
last two works and I currently use a list comprehension.

# Example:
>>> flatten( [ 1, 3, 4, ('allo', 'bonjour', 'salut' ), 34, False,
False, ( 3, ) ]
[ 1, 3, 4, 'allo', 'bonjour', 'salut' , 34, False, False, 3 ]


Cheers!
Bernard

From kent37 at tds.net  Thu Sep 29 15:21:54 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 29 Sep 2005 09:21:54 -0400
Subject: [Tutor] New-style classes
In-Reply-To: <r02010500-1039-10FE0EE630E911DA9B61000A959B4026@[10.149.23.208]>
References: <r02010500-1039-10FE0EE630E911DA9B61000A959B4026@[10.149.23.208]>
Message-ID: <433BEA72.7060108@tds.net>

Jan Eden wrote:
> My actual code looks like this:
> 
> class Base:
>     def GetOwnType(self):
>         try: return self._own_type
>         except: return self.child_type
>     
>     def SetOwnType(self, value):
>         self._own_type = value
>         
>     own_type = property(GetOwnType, SetOwnType)
> 
> For some of the subclasses of Base, the attribute own_type is
> defined, the others should use child_type.
> 
> For both groups of subclasses, this works fine - if own_type has not
> been set somewhere else, self.child_type is returned when calling
> self.own_type.
> 
> When checking Data.Base.__mro__, I get an error, so it is not a
> new-style class by itself.
> 
> On the other hand, every time I use the own_type attribute, I do so
> via instances of new-style classes (Show.Page, Show.Author etc).

That is the key

> 
> Could it be that the nature of these classes makes the code in
> Data.Base behave according to the new-style rules?> 

Yes, I tried to show that in my example. Any class that has a new-style class as one of its base classes will be a new-style class. The attribute lookup is implemented in the metaclass.

For an instance of Data.Base, the metaclass (the class of its class) is types.ClassType, which implements old-style attribute access. So if you create a Data.Base directly the property access will be broken.

On the other hand if you create an instance of Show.Page, the meta class is type, which implements new-style attribute access and the properties will behave correctly.

You have to keep in mind, this is Python, everything is dynamic. When you define Data.Base you don't define its behaviour irrevocably. Attribute lookup happens at runtime and is affected by the current state of the object.

Kent

> Thanks,
> 
> Jan


From python at jayloden.com  Thu Sep 29 15:55:17 2005
From: python at jayloden.com (Jay Loden)
Date: Thu, 29 Sep 2005 09:55:17 -0400
Subject: [Tutor] Python equiv to PHP "include" ?
Message-ID: <200509290955.17763.python@jayloden.com>

I've not been able to find an answer to this conundrum anywhere: 

My current website is done in PHP with a setup something like this: 

::PHP TEMPLATE CODE::

include('file.htm')

::PHP TEMPLATE CODE::

This way, I can have PHP embedded in my htm files and it will be processed as 
part of the script. For example, I can have a form that's written in HTML and 
processed in PHP, then simply 'include("form.htm")' and I have a form with 
processing that's ALSO wrapped in my site template. 

I can't figure out how one would approach this in Python (i'm using 
mod_python). There's no equivalent to the "include" function from PHP. I 
can't use import because then Python would try to parse the HTML from the 
imported file. I've looked at stuff like cheetah and PSP, but neither of 
those actually answers the question, which is how can I include dynamic 
content including PHP code directly into an existing script. Even if I 
started using PSP, I still can't "include" a PSP page into the middle of 
another PSP page.

I'm definitely willing to consider any other solution for how I can make a 
form that processes its input but maintains my template code wrapped around 
it, so feel free to point out a "Pythonic" method. I just don't want to 
duplicate the template code, and I can't find a nice neat solution like what 
I've got in PHP.

-Jay

From kabads at gmail.com  Thu Sep 29 16:49:59 2005
From: kabads at gmail.com (Adam Cripps)
Date: Thu, 29 Sep 2005 15:49:59 +0100
Subject: [Tutor] Python equiv to PHP "include" ?
In-Reply-To: <200509290955.17763.python@jayloden.com>
References: <200509290955.17763.python@jayloden.com>
Message-ID: <c7ff385505092907496e0c52f5@mail.gmail.com>

On 9/29/05, Jay Loden <python at jayloden.com> wrote:
> I've not been able to find an answer to this conundrum anywhere:
>
> My current website is done in PHP with a setup something like this:
>
> ::PHP TEMPLATE CODE::
>
> include('file.htm')
>
> ::PHP TEMPLATE CODE::
>
> This way, I can have PHP embedded in my htm files and it will be processed as
> part of the script. For example, I can have a form that's written in HTML and
> processed in PHP, then simply 'include("form.htm")' and I have a form with
> processing that's ALSO wrapped in my site template.
>
> I can't figure out how one would approach this in Python (i'm using
> mod_python). There's no equivalent to the "include" function from PHP. I
> can't use import because then Python would try to parse the HTML from the
> imported file.

I thought PHP also parsed any html rendered through an included file?
Am I wrong here?
Adam
--
http://www.monkeez.org
PGP key: 0x7111B833

From ds-python-tutor at sidorof.com  Thu Sep 29 17:23:55 2005
From: ds-python-tutor at sidorof.com (DS)
Date: Thu, 29 Sep 2005 08:23:55 -0700
Subject: [Tutor] call a def/class by reference
In-Reply-To: <6.1.2.0.0.20050928181702.033e23b0@mail.mric.net>
References: <433B2150.7020904@sidorof.com>
	<be4fbf9205092816136c7f2db0@mail.gmail.com>
	<433B274B.7090001@sidorof.com>
	<6.1.2.0.0.20050928181702.033e23b0@mail.mric.net>
Message-ID: <433C070B.6010104@sidorof.com>

bob wrote:

> At 04:29 PM 9/28/2005, DS wrote:
>
>> What I'm hoping to avoid is an
>> explicit reference to any of the called functions within the program.
>> By doing it that way, it would avoid a maintenance problem of having to
>> remember to put a reference for every new function in the calling
>> program.
>
>
> Try this - a class in which you define all the functions. The __init__
> method builds the dictionary.
>
> >>> class X:
> ...     funcs = {}
> ...     def y(self):
> ...             pass
> ...     def __init__(self):
> ...             for itemname in dir(self):
> ...                     if not itemname.startswith('__'):
> ...                             item = getattr(self, itemname)
> ...                             if callable(item):
> ...                                     self.funcs[itemname] = item
> ...
> >>> y = X()
> >>> y.funcs
> {'y': <bound method x.y of <__main__.x instance at 0x01119828>>}
>   


Thanks bob, that's an interesting approach.  That would be one huge class.

ds

From chris.arndt at web.de  Thu Sep 29 17:22:18 2005
From: chris.arndt at web.de (Christopher Arndt)
Date: Thu, 29 Sep 2005 16:22:18 +0100
Subject: [Tutor] Python equiv to PHP "include" ?
In-Reply-To: <200509290955.17763.python@jayloden.com>
References: <200509290955.17763.python@jayloden.com>
Message-ID: <dhh0rb$3ls$1@sea.gmane.org>

Jay Loden schrieb:
> I can't figure out how one would approach this in Python (i'm using 
> mod_python). There's no equivalent to the "include" function from PHP. I 
> can't use import because then Python would try to parse the HTML from the 
> imported file. I've looked at stuff like cheetah and PSP, but neither of 
> those actually answers the question, which is how can I include dynamic 
> content including PHP code directly into an existing script. Even if I 
> started using PSP, I still can't "include" a PSP page into the middle of 
> another PSP page.

Python does not support mingling of Python code within HTML as PHP does out of
the box (because it is a general purpose programming language and wasn't
devised specifically for web development).  But there are several templating
modules that allow to embed Python code into other documents, like e.g. HTML.
You already mentioned Cheetah and PSP, another one I have used and found really
easy to work with, is EmPy.

With these, your script would basically be structured like the this: you have
your main CGI script, Servlet or whatever written in Python. There you import
the template module and use the functions it provides to load your HTML
template with embedded Python instructions and process it. Your main script
reads the output of the template processing and send it to standard out (which
is ultimately send to the browser).

For example (pseudo code)

-----> mytemplate.tpl <-----
<html>
<head>
    <title>@{htmlescpape(title)}</title>
</head>
<body>
    <h1>List of users:</h1>

<ul>
@{for user in users}
  <li>@{htmlescape(user)}</li>
@{end for}
</ul>

@{import time
now = time.asctime()
}
Generated at @{htmlescape(now)}
</body>
</html>
-----> end mytemplate.tpl <-----

-----> myscript.cgi <-----
import templatemodule

substitutions = dict(title="User list", users=('joe', 'bob', 'alice'))

output = template.process('mytemplate.tpl', substitutions)
print "Conten-type: text/html\n'
print output
-----> myscript.cgi <-----


Remember, this is pseudo code. There is no template module (to my knowledge)
that actually uses this exact syntax. But you should get the idea.

> I'm definitely willing to consider any other solution for how I can make a 
> form that processes its input but maintains my template code wrapped around 
> it, so feel free to point out a "Pythonic" method. I just don't want to 
> duplicate the template code, and I can't find a nice neat solution like what 
> I've got in PHP.

You just have to change your point of view. PHP *is* practically a template
language. The actual template processor is the Apache PHP module. In Python,
you can choose from several template modules available, each of which has it's
own syntax conventions and mechanisms.

Chris


From daniel at thewatkins.org.uk  Thu Sep 29 18:51:29 2005
From: daniel at thewatkins.org.uk (Daniel Watkins)
Date: Thu, 29 Sep 2005 17:51:29 +0100
Subject: [Tutor] FW:  Frustrated Beginner
In-Reply-To: <9AA4216B8A36B9429BB00C546DF6D27201B79B@schubert.OxbridgeTechnology.local>
References: <9AA4216B8A36B9429BB00C546DF6D27201B79B@schubert.OxbridgeTechnology.local>
Message-ID: <1128012689.21505.20.camel@amdbert.oxbridgetechnology.local>

Rosalee Dubberly wrote:
> ## Now I am trying to modify the function to replace eggs with toast
> and spam with jelly. I have spent days and nothing works. Can you send
> me in the right direction?? 

The obvious answer (that has already been mentioned) is to simply
replace the words in the actual program with their substitutes. However,
this is so obvious I sincerely hope that you don't mean this by the
question.

The right direction, as I understand it, would be to set the text to be
printed in a variable, which can then be passed to the function. This
will allow you to change the text to whatever you want easily, as well
as including the possibility for user input later.

An example is attached, so you can try to work it out yourself without
seeing it.

Dan
-------------- next part --------------
A non-text attachment was scrubbed...
Name: firstpart.py
Type: text/x-python
Size: 206 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20050929/2485787e/firstpart.py

From alan.gauld at freenet.co.uk  Thu Sep 29 19:51:20 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Thu, 29 Sep 2005 18:51:20 +0100
Subject: [Tutor] Python equiv to PHP "include" ?
References: <200509290955.17763.python@jayloden.com>
Message-ID: <004d01c5c51e$66ef80b0$0201a8c0@xp>

> My current website is done in PHP with a setup something like this:
>
> ::PHP TEMPLATE CODE::
>
> include('file.htm')
>
> ::PHP TEMPLATE CODE::
>
> This way, I can have PHP embedded in my htm files and it will be 
> processed as
> part of the script.

OK, But PHP uses server side scripting like JSP or ASP
whereas mod Python uses standard CGI style programming.
You have to turn your thinking inside out.

You write the code and print the HTML.

So to include some html file output in your program use
something like:

print open('foo.htm').read()

Of course foo.html has to be pure html (or client side
scripting) that goes straight to the browser.

> ...I have a form with
> processing that's ALSO wrapped in my site template.

If you want to import processing put that in a python
module and import that, keep the code and function separate
(always good practice!).

If you really want ASP sytyle processing you need to look
at another web server technology such as Zope, PSP or
similar server scripting solutions for Python.

> I can't figure out how one would approach this in Python (i'm using
> mod_python). There's no equivalent to the "include" function from 
> PHP.

Correct, the concept doesn't exist because you are working
with vanilla CGI rather than server scripting.

> can't use import because then Python would try to parse
> the HTML

But you can use import to pull in reusable python code.
Of course that's not quite the same since the python code
can't read values of the HTML fields etc. No problem for
the code in the current file but tricky if your form is
in the 'included' file...

> imported file. I've looked at stuff like cheetah and PSP,

> which is how can I include dynamic content including PHP code

Do you really mean you want a python script to include PHP code?
Thats something else again and I doubt if its possible.
I assumed your included file contained a mix of html and
python code?

> started using PSP, I still can't "include" a PSP page
> into the middle of another PSP page.

I thought you could do it using standard html SSI?

> I'm definitely willing to consider any other solution for how I can 
> make a
> form that processes its input but maintains my template code wrapped 
> around
> it, so feel free to point out a "Pythonic" method. I just don't want 
> to
> duplicate the template code, and I can't find a nice neat solution 
> like what
> I've got in PHP.

PHP comes from a very specific style of web programming.
Python tends to support vanilla CGI and to do PHP style coding you
need add-ins like PSP(the first suchj and therefore the most basic)
Either move up to a more powerful engine, like Zope, or adapt to CGI
style coding.

There are many web frameworks for Python but my needs are met
by CGI at one end and Zope at the other(once!) so I'm no expert.
CherryPy seems to be popular but I've no idea how it works...

HTH,

Alan g. 


From alan.gauld at freenet.co.uk  Thu Sep 29 19:52:23 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Thu, 29 Sep 2005 18:52:23 +0100
Subject: [Tutor] Python equiv to PHP "include" ?
References: <200509290955.17763.python@jayloden.com>
	<c7ff385505092907496e0c52f5@mail.gmail.com>
Message-ID: <005101c5c51e$8bdf38c0$0201a8c0@xp>

>> can't use import because then Python would try to parse the HTML 
>> from the
>> imported file.
>
> I thought PHP also parsed any html rendered through an included 
> file?

It does but PHP 'understands' HTML - or more specifically ignores it!

Alan G. 


From bgailer at alum.rpi.edu  Thu Sep 29 20:20:07 2005
From: bgailer at alum.rpi.edu (bob)
Date: Thu, 29 Sep 2005 11:20:07 -0700
Subject: [Tutor] call a def/class by reference
In-Reply-To: <433C070B.6010104@sidorof.com>
References: <433B2150.7020904@sidorof.com>
	<be4fbf9205092816136c7f2db0@mail.gmail.com>
	<433B274B.7090001@sidorof.com>
	<6.1.2.0.0.20050928181702.033e23b0@mail.mric.net>
	<433C070B.6010104@sidorof.com>
Message-ID: <6.1.2.0.0.20050929111557.03414e08@mail.mric.net>

At 08:23 AM 9/29/2005, DS wrote:
>bob wrote:
>
> > At 04:29 PM 9/28/2005, DS wrote:
> >
> >> What I'm hoping to avoid is an
> >> explicit reference to any of the called functions within the program.
> >> By doing it that way, it would avoid a maintenance problem of having to
> >> remember to put a reference for every new function in the calling
> >> program.
> >
> >
> > Try this - a class in which you define all the functions. The __init__
> > method builds the dictionary.
> >
> > >>> class X:
> > ...     funcs = {}
> > ...     def y(self):
> > ...             pass
> > ...     def __init__(self):
> > ...             for itemname in dir(self):
> > ...                     if not itemname.startswith('__'):
> > ...                             item = getattr(self, itemname)
> > ...                             if callable(item):
> > ...                                     self.funcs[itemname] = item
> > ...
> > >>> y = X()
> > >>> y.funcs
> > {'y': <bound method x.y of <__main__.x instance at 0x01119828>>}
> >
>
>
>Thanks bob, that's an interesting approach.  That would be one huge class.

Well if you have lots of functions you will have one *huge* module. The 
additional class stuff is minor.

Also note that you can accomplish a similar thing by defining the functions 
outside any class and then finding them in globals(). Having said that I 
like the class approach in that it becomes a container for the functions 
you want to expose and other functions defined outside the class will be 
ignored. 


From zathras at thwackety.com  Thu Sep 29 21:52:56 2005
From: zathras at thwackety.com (Michael Sparks)
Date: Thu, 29 Sep 2005 20:52:56 +0100
Subject: [Tutor] stopping threads?
In-Reply-To: <433B895E.3060406@cirad.fr>
References: <5e183f3d05092817426a34e917@mail.gmail.com>
	<433B895E.3060406@cirad.fr>
Message-ID: <200509292052.56973.zathras@thwackety.com>

On Thursday 29 September 2005 07:27, Pierre Barbier de Reuille wrote:
> IMO, it is better to explicitely call the base class ... I think it is
> more readable. But I don't know if there is any drawback for any
> solution...

A drawback of NOT using super is that you're potetially setting yourself you 
for a fall.

Consider the following code
----(Option 1)----
from hypothetical import SomeBaseClass

class myClass(SomeBaseClass):
    def __init__(self, ...):
        super(myClass, self).__init__(...)

----(Option 2)----
from hypothetical import SomeBaseClass

class myClass(SomeBaseClass):
    def __init__(self, ...):
        SomeBaseClass.__init__(self)


In the case of option 1, this will work, and have reliable, predictable 
behaviour even if the implementation of SomeBaseClass in the "hypothetical" 
library changes from something like:

    class SomeBaseClass(ActualBase):
       ...

To something like:

    class SomeBaseClass(ActualBase,mixin1, mixin2):
       ...


In Option 2, you run the risk of methods higher up the tree being run more 
than once. Obviously in your *own* code you can avoid this if you like, but 
as soon as you start using and inheriting from classes in other people's 
libraries you can't guarantee that you're not running that risk.

I posted an example about this via gmane's email to news gateway last
week, but it doesn't appear to have hit the archive (or the list :) for some
reason, so I've included the reply I gave illustrating what can go wrong if
you don't use super at the end.

Regards,


Michael.
---
Original post regarding super:
Subject: Re: Using superclass __init__ method

paul brian wrote:

> class Base:
>    def __init__(self):
>        print "hello"
> 
> class Child(Base):
>    def __init__(self):
>        Base.__init__(self)
> 
>    def foo(self):
>       print "foo"

I note this is using "old" style classes. However it's normal to recommend
that people use "new" style classes these days. (I only started using
python after they invented new style classes, hence the quotes around
new/old)

A more canonical example here is this:

class Base(object):
    def __init__(self):
        print "hello"

class Child(Base):
    def __init__(self):
        super(Child,self).__init__()
    def foo(self):
        print "foo"

Whilst this might an esoteric change, it's really to handle the fact that
python has multiple inheritance. Consider:

>>> class ChildOne(Base):
...     def __init__(self):
...         Base.__init__(self)
...         print "Hello from ChildOne"
...
>>> class ChildTwo(Base):
...     def __init__(self):
...         Base.__init__(self)
...         print "Hello from ChildTwo"
...
>>> class GrandChild(ChildOne,ChildTwo):
...     def __init__(self):
...         ChildOne.__init__(self)
...         ChildTwo.__init__(self)
...         print "Hello from GrandChild"
...
>>> GrandChild()
Hello from Base
Hello from ChildOne
Hello from Base
Hello from ChildTwo
Hello from GrandChild
<__main__.GrandChild instance at 0x40397f8c>


What you can see here is that the __init__ in Base was executed twice. This
may or may not be a problem with some things, but where people use classes
to "mixin" functionality it can be a real problem.

Consider the alternative using "super" instead: 

>>> class Base(object):
...     def __init__(self):
...         print "Hello from Base"
...
>>> class ChildOne(Base):
...     def __init__(self):
...         super(ChildOne,self).__init__()
...         print "Hello from ChildOne"
...
>>> class ChildTwo(Base):
...     def __init__(self):
...         super(ChildTwo,self).__init__()
...         print "Hello from ChildTwo"
...
>>> class GrandChild(ChildOne,ChildTwo):
...     def __init__(self):
...         super(GrandChild,self).__init__()
...         print "Hello from GrandChild"
...
>>> GrandChild()
Hello from Base
Hello from ChildTwo
Hello from ChildOne
Hello from GrandChild
<__main__.GrandChild object at 0x4039ccac>


Regards,


Michael

From ds-python-tutor at sidorof.com  Thu Sep 29 22:06:36 2005
From: ds-python-tutor at sidorof.com (DS)
Date: Thu, 29 Sep 2005 13:06:36 -0700
Subject: [Tutor] call a def/class by reference
In-Reply-To: <6.1.2.0.0.20050929111557.03414e08@mail.mric.net>
References: <433B2150.7020904@sidorof.com>
	<be4fbf9205092816136c7f2db0@mail.gmail.com>
	<433B274B.7090001@sidorof.com>
	<6.1.2.0.0.20050928181702.033e23b0@mail.mric.net>
	<433C070B.6010104@sidorof.com>
	<6.1.2.0.0.20050929111557.03414e08@mail.mric.net>
Message-ID: <433C494C.405@sidorof.com>

bob wrote:

> At 08:23 AM 9/29/2005, DS wrote:
>
>> bob wrote:
>>
>> > At 04:29 PM 9/28/2005, DS wrote:
>> >
>> >> What I'm hoping to avoid is an
>> >> explicit reference to any of the called functions within the program.
>> >> By doing it that way, it would avoid a maintenance problem of
>> having to
>> >> remember to put a reference for every new function in the calling
>> >> program.
>> >
>> >
>> > Try this - a class in which you define all the functions. The __init__
>> > method builds the dictionary.
>> >
>> > >>> class X:
>> > ...     funcs = {}
>> > ...     def y(self):
>> > ...             pass
>> > ...     def __init__(self):
>> > ...             for itemname in dir(self):
>> > ...                     if not itemname.startswith('__'):
>> > ...                             item = getattr(self, itemname)
>> > ...                             if callable(item):
>> > ...                                     self.funcs[itemname] = item
>> > ...
>> > >>> y = X()
>> > >>> y.funcs
>> > {'y': <bound method x.y of <__main__.x instance at 0x01119828>>}
>> >
>>
>>
>> Thanks bob, that's an interesting approach.  That would be one huge
>> class.
>
>
> Well if you have lots of functions you will have one *huge* module.
> The additional class stuff is minor.
>
I agree.  My first thought when I saw that was that it would be a memory
issue, but then as I sat and thought about it, it I couldn't really tell
if it was any different than a huge module.  One thing I don't have
experience with yet is the amount of memory taken when an instance of
the object is created.  For example, does it use substantially more
memory if there are a bunch of if, elif clauses (representing the unused
functions within the class)?  I'll monkey around with it and see what I get.

> Also note that you can accomplish a similar thing by defining the
> functions outside any class and then finding them in globals(). Having
> said that I like the class approach in that it becomes a container for
> the functions you want to expose and other functions defined outside
> the class will be ignored.

>From what I've read so far, globals are actively discouraged.  A class
seems like the best approach. 

I'm actually pretty surprised that there isn't a built-in facility with
Python for referencing functions like this.  In reading Python in a
Nutshell, prior to asking my questions here, I had thought that there
probably was, but I just wasn't grasping it.

Thanks.

ds





From dyoo at hkn.eecs.berkeley.edu  Thu Sep 29 22:40:54 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 29 Sep 2005 13:40:54 -0700 (PDT)
Subject: [Tutor] call a def/class by reference
In-Reply-To: <433C494C.405@sidorof.com>
Message-ID: <Pine.LNX.4.44.0509291333240.20475-100000@hkn.eecs.berkeley.edu>

> >From what I've read so far, globals are actively discouraged.  A class
> seems like the best approach.
>
> I'm actually pretty surprised that there isn't a built-in facility with
> Python for referencing functions like this.  In reading Python in a
> Nutshell, prior to asking my questions here, I had thought that there
> probably was, but I just wasn't grasping it.


Hi DS,


Modules can be thought of as containers for functions.  As a concrete
example, let's say we have a module named 'functions':

######
# in functions.py
def A(): print "A"

def B(): print "B"

def C(): print "C"
######


In other programs, this 'functions' module can be imported and dir()ed:

######
>>> import functions
>>> dir(functions)
['A', 'B', 'C', '__builtins__', '__doc__', '__file__', '__name__']
######


There are our attributes of the 'functions' module.  Those functions in
the module can also be called:

######
>>> getattr(functions, 'A')
<function A at 0x403a6ae4>
>>>
>>> getattr(functions, 'A')()
A
######


I'm not exactly sure if this is what you want, but this shows a simple way
to highlight a selection of functions, by using a module as the container.


Best of wishes!


From ds-python-tutor at sidorof.com  Thu Sep 29 23:14:29 2005
From: ds-python-tutor at sidorof.com (DS)
Date: Thu, 29 Sep 2005 14:14:29 -0700
Subject: [Tutor] call a def/class by reference
In-Reply-To: <Pine.LNX.4.44.0509291333240.20475-100000@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0509291333240.20475-100000@hkn.eecs.berkeley.edu>
Message-ID: <433C5935.70707@sidorof.com>

Danny Yoo wrote:

>>>From what I've read so far, globals are actively discouraged.  A class
>>seems like the best approach.
>>
>>I'm actually pretty surprised that there isn't a built-in facility with
>>Python for referencing functions like this.  In reading Python in a
>>Nutshell, prior to asking my questions here, I had thought that there
>>probably was, but I just wasn't grasping it.
>>    
>>
>
>
>Hi DS,
>
>
>Modules can be thought of as containers for functions.  As a concrete
>example, let's say we have a module named 'functions':
>
>######
># in functions.py
>def A(): print "A"
>
>def B(): print "B"
>
>def C(): print "C"
>######
>
>
>In other programs, this 'functions' module can be imported and dir()ed:
>
>######
>  
>
>>>>import functions
>>>>dir(functions)
>>>>        
>>>>
>['A', 'B', 'C', '__builtins__', '__doc__', '__file__', '__name__']
>######
>
>
>There are our attributes of the 'functions' module.  Those functions in
>the module can also be called:
>
>######
>  
>
>>>>getattr(functions, 'A')
>>>>        
>>>>
><function A at 0x403a6ae4>
>  
>
>>>>getattr(functions, 'A')()
>>>>        
>>>>
>A
>######
>
>
>I'm not exactly sure if this is what you want, but this shows a simple way
>to highlight a selection of functions, by using a module as the container.
>
>
>Best of wishes!
>
>  
>
Ok!!!   This is exactly it.  Thanks so much.  This provides the link
between a string that represents a function to the actual calling of
that function with getattr().  I was just reading up on the getattr()
because it was in used in Bob's answer, when your email came through.

Thanks so much to all of you that have answered my questions, including 
Liam.Clarke-Hutchinson, whom I didn't acknowledge directly with an
email.  I hope I'm not asking too many questions.  This is kind of a
departure for me.  Usually, I just bang my head against the wall till I
break through.  At some point I hope to get to a point where I can
provide answers for others who are just learning as well.

ds



From python at jayloden.com  Thu Sep 29 23:16:57 2005
From: python at jayloden.com (Jay Loden)
Date: Thu, 29 Sep 2005 17:16:57 -0400
Subject: [Tutor] Python equiv to PHP "include" ?
In-Reply-To: <004d01c5c51e$66ef80b0$0201a8c0@xp>
References: <200509290955.17763.python@jayloden.com>
	<004d01c5c51e$66ef80b0$0201a8c0@xp>
Message-ID: <200509291716.57780.python@jayloden.com>

Alan, thanks for your responses, they're quite helpful. I suspect the real 
problem I'm having is simply trying to switch modes of thinking to CGI style 
or mod_python style instead of the PHP style embedded code. 

The whole point of this exercise for me was to decide which language I prefer 
for web development and evaluate Python for web work. So far, I've found PHP 
much easier to work with and less "clunky" in terms of what I'm trying to do 
- but I believe that's very much a function of my thinking being rooted in 
the PHP style. 

If Im understanding this right...the Pythonic/CGI method for something like 
this is to import a template module of some kind, then call methods from that 
template to display the template, with other Python code in the middle that 
takes care of form processing? 

The solution I have now feels smoother, since all I do is put content 
into .htm files, then pull them into a template that's basically an html 
sandwich. This gives me capability to stick a <?php ?> section into the .htm 
file itself - for example a form with some dynamic content/variables - and 
then from a user perspective, all they see is a normal html page.  

From a server side, it's seeing one big PHP script that includes both template 
code and form code, but without me needing to write any templating code into 
the form itself - instead I just call the form into the template.  With 
Python, it seems like this kind of approach is impossible, and it also means 
that my form would probably have to have some kind of special extension, like 
"form.py" (so the handler knows what to do with it) instead of just being 
located at "form.htm" - am I following this all correctly? 

Does anyone know of any soup-to-nuts CGI programming examples online for 
Python that might make this clearer so I can bug the list less and just read 
some example code?

-Jay


From alan.gauld at freenet.co.uk  Thu Sep 29 23:26:19 2005
From: alan.gauld at freenet.co.uk (Alan G)
Date: Thu, 29 Sep 2005 22:26:19 +0100
Subject: [Tutor] call a def/class by reference
References: <433B2150.7020904@sidorof.com><be4fbf9205092816136c7f2db0@mail.gmail.com><433B274B.7090001@sidorof.com><6.1.2.0.0.20050928181702.033e23b0@mail.mric.net><433C070B.6010104@sidorof.com><6.1.2.0.0.20050929111557.03414e08@mail.mric.net>
	<433C494C.405@sidorof.com>
Message-ID: <007201c5c53c$6eddb3a0$0201a8c0@xp>

> I'm actually pretty surprised that there isn't a built-in facility 
> with
> Python for referencing functions like this.

I'm not. In fact its pretty unusual in any language to try to map
from function name to function directly. Dictionaries are the
universal solution for this, I can only think of a handful(4?)
languages that I've used (Out of 20 plus) that can do
string -> function mapping directly.

Its not usually a very useful thing to do - how would the
typical user know what the function names were? Either the
user has access to the code or the code presents the names
to the user(as strings) in which case a mapping has to
exist somewhere already.

I'm curious as to how you are addressing those issues?
Is this something that only developers will be using?
How will the user know what names are possible?

Alan G. 


From ds-python-tutor at sidorof.com  Fri Sep 30 00:12:27 2005
From: ds-python-tutor at sidorof.com (DS)
Date: Thu, 29 Sep 2005 15:12:27 -0700
Subject: [Tutor] call a def/class by reference
In-Reply-To: <007201c5c53c$6eddb3a0$0201a8c0@xp>
References: <433B2150.7020904@sidorof.com><be4fbf9205092816136c7f2db0@mail.gmail.com><433B274B.7090001@sidorof.com><6.1.2.0.0.20050928181702.033e23b0@mail.mric.net><433C070B.6010104@sidorof.com><6.1.2.0.0.20050929111557.03414e08@mail.mric.net>
	<433C494C.405@sidorof.com> <007201c5c53c$6eddb3a0$0201a8c0@xp>
Message-ID: <433C66CB.1000006@sidorof.com>

Alan G wrote:

>> I'm actually pretty surprised that there isn't a built-in facility with
>> Python for referencing functions like this.
>
>
> I'm not. In fact its pretty unusual in any language to try to map
> from function name to function directly. Dictionaries are the
> universal solution for this, I can only think of a handful(4?)
> languages that I've used (Out of 20 plus) that can do
> string -> function mapping directly.
>
> Its not usually a very useful thing to do - how would the
> typical user know what the function names were? Either the
> user has access to the code or the code presents the names
> to the user(as strings) in which case a mapping has to
> exist somewhere already.
>
> I'm curious as to how you are addressing those issues?
> Is this something that only developers will be using?
> How will the user know what names are possible?
>
> Alan G.


I am playing with building a facility that accepts equations or
expressions that are parsed and solved.  I hope to use this with genetic
algorithms that would create mostly useless expressions, but that over
time might become better.  If I was doing it for users building
expressions, I'd probably do a javascript kind of approach for
assembling expressions from lists.  Your point is well taken, because
I'm often awed at the amazing ly stupid errors that I make when I'm
typing. 

Rest assured, I don't know 20 languages, computer or otherwise.  I know
that I used some sort of thing like that in the 80's with Revelation, a
database/language derived from Pick.  (That one is probably a little
obscure, it may not be on your list of 20).  I also think you can do
that in Perl, but bear in mind I know less about Perl than I do Python.

ds

From zathras at thwackety.com  Fri Sep 30 00:58:33 2005
From: zathras at thwackety.com (Michael Sparks)
Date: Thu, 29 Sep 2005 23:58:33 +0100
Subject: [Tutor] call a def/class by reference
In-Reply-To: <007201c5c53c$6eddb3a0$0201a8c0@xp>
References: <433B2150.7020904@sidorof.com> <433C494C.405@sidorof.com>
	<007201c5c53c$6eddb3a0$0201a8c0@xp>
Message-ID: <200509292358.33829.zathras@thwackety.com>

On Thursday 29 September 2005 22:26, Alan G wrote:
> string -> function mapping directly.
>
> Its not usually a very useful thing to do

This is precisely how shared libraries under linux and IIRC DLLs in windows 
work. cf dlopen, dysym in C. 

> how would the typical user know what the function names were?

Under linux one can examine the names of functions in a library using "nm".

eg:
# nm libpython2.4.so|head -20
         U abort@@GLIBC_2.0
000dfea0 d abs_doc
0001fcf0 t abstract_get_bases
0001fe20 t abstract_issubclass
         U access@@GLIBC_2.0
000e9ba0 d acquire_doc
0008f970 t addcleanup
0001be40 t addclosure
000d2040 d add_doc
0009d7c0 t add_flag
0001b8f0 t addnfaarc
0001b870 t addnfastate
00059680 t add_subclass
00049de0 t adjust_tp_compare
000ea680 d alarm_doc
         U alarm@@GLIBC_2.0
000e9760 d allocate_doc
000e6280 d api_version_warning
0003a6f0 t app1
000cfc40 d append_doc

Obviously, ctypes does much the same thing. 

Compare and contrast:

try: 	 
    from ctypes import * 	 
    libc = cdll.LoadLibrary("/lib/libc.so.6") 	 
    sched_yield = libc.sched_yield
 except ImportError: 	 
    def sched_yield(): pass
 except AttributeError:
    def sched_yield(): pass

with ...

try:
   import functions as libc
   sched_yield = getattr(libc, "sched_yield")
                               # this is of course effectively equivalent to:
                               #   sched_yield = libc.sched_yield
except ImportError:
    def sched_yield(): pass
except AttributeError:
    def sched_yield(): pass

It's pretty much the same thing. I could see that this may have uses in 
systems that allow plugins.

Devils-advocate-ly , ;-)


Michael.


From dyoo at hkn.eecs.berkeley.edu  Fri Sep 30 01:05:18 2005
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu, 29 Sep 2005 16:05:18 -0700 (PDT)
Subject: [Tutor] call a def/class by reference
In-Reply-To: <433C5935.70707@sidorof.com>
Message-ID: <Pine.LNX.4.44.0509291603330.13988-100000@hkn.eecs.berkeley.edu>

> Thanks so much to all of you that have answered my questions, including
> Liam.Clarke-Hutchinson, whom I didn't acknowledge directly with an
> email.  I hope I'm not asking too many questions.

Hi ds,

You're doing perfectly fine.  *grin*  We got to see a lot of different
approaches to that class of problem, so I think it was very useful for
folks to see.


Best of wishes to you!


From keridee at jayco.net  Fri Sep 30 02:33:41 2005
From: keridee at jayco.net (Jacob S.)
Date: Thu, 29 Sep 2005 19:33:41 -0500
Subject: [Tutor] Why won't it enter the quiz? (off topic)
References: <mailman.1497.1126930332.508.tutor@python.org>
	<BAY106-DAV2299CBA7C20DA16ED5C6C7C4900@phx.gbl>
Message-ID: <043c01c5c556$b1e03f50$6601a8c0@JSLAPTOP>

Wow! What an argument...
A couple of comments on the code

> {code}
>
> import random
>
> def add(a,b):
>    answer = a+b
>    guess = float(raw_input(a," + ",b," = "))

This is easier IMHO, but the same
guess = float(raw_input("%s+%s="%(a,b)))

>    return answer, guess
>
> num1 = random.choice(range(1,10)) ### To limit the numbers chosen from 1-9
> num2 = random.choice(range(1,10))

Oh my.  Read the documentation on the random module.
Specifically random.randrange or even random.randint
Note: the difference between the two -- a <= result < b  as opposed to a <= 
result <= b

> while 1:
>    q = random.choice(range(15,31)) ### to choose the number of questions
>    cq = 1 ### To find the current question
>    correct = 0
>    while cq >= q: ### To find whether or not to end the quiz.

Of course, this has been corrected to   while cq <= q:

>        print cq
>        answer, guess = add(num1,num2)
>        if guess != answer:
>            print "Incorrect! The correct answer is: ",answer
>            cq += 1
>        elif guess == answer:
>            print "Correct!"
>            correct += 1
>            cq += 1
>    else:
>        print "Questions: ",q
>        print "Correct: ",correct
>        print "Percent Correct: ",(cq/q)*100

Okay, this is a problem -- Due to the integer division cq/q, Percent Correct 
will only display 0, ever

>        break
>
> print "Goodbye."

They probably won't see the stats because the program will execute the four 
print statements and immediately exit.  I suggest changing the last 
statement to

raw_input("Goodbye. Press enter to exit. ")

>
> {/code}
>

I have one more comment.  The code in the add function doesn't really seem 
to be that well grouped together ~ IOW, it seems like you defined a function 
just because you felt like you needed practice typing def something(args):

It seems much easier (in this case) to just leave the add() code in the 
actual main block. Does this make sense?

Oops.  I have two comments.  In add() (which I suggest removing) you define 
guess with float(...) whereas your answer is an integer.   (a+b)  So you may 
run into trouble with floating point precision.
For example. ~~Okay, I stand corrected, in my test, none (out of 0-100) gave 
me any trouble.

Hope this helps,
Jacob Schmidt 


From kent37 at tds.net  Fri Sep 30 03:10:31 2005
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 29 Sep 2005 21:10:31 -0400
Subject: [Tutor] Python equiv to PHP "include" ?
In-Reply-To: <200509291716.57780.python@jayloden.com>
References: <200509290955.17763.python@jayloden.com>	<004d01c5c51e$66ef80b0$0201a8c0@xp>
	<200509291716.57780.python@jayloden.com>
Message-ID: <433C9087.3020607@tds.net>

Jay Loden wrote:
> Alan, thanks for your responses, they're quite helpful. I suspect the real 
> problem I'm having is simply trying to switch modes of thinking to CGI style 
> or mod_python style instead of the PHP style embedded code. 

There are quite a few template engines for Python that allow embedding Python into the template. One of them is part of mod_python: http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html

Some others are Myghty and Spyce and the PSP component of WebWare:
http://www.myghty.org/
http://spyce.sourceforge.net/
http://www.webwareforpython.org/Webware/PSP/Docs/index.html

You might find that these have a familiar style.

Kent

> 
> The whole point of this exercise for me was to decide which language I prefer 
> for web development and evaluate Python for web work. So far, I've found PHP 
> much easier to work with and less "clunky" in terms of what I'm trying to do 
> - but I believe that's very much a function of my thinking being rooted in 
> the PHP style. 
> 
> If Im understanding this right...the Pythonic/CGI method for something like 
> this is to import a template module of some kind, then call methods from that 
> template to display the template, with other Python code in the middle that 
> takes care of form processing? 
> 
> The solution I have now feels smoother, since all I do is put content 
> into .htm files, then pull them into a template that's basically an html 
> sandwich. This gives me capability to stick a <?php ?> section into the .htm 
> file itself - for example a form with some dynamic content/variables - and 
> then from a user perspective, all they see is a normal html page.  
> 
>>From a server side, it's seeing one big PHP script that includes both template 
> code and form code, but without me needing to write any templating code into 
> the form itself - instead I just call the form into the template.  With 
> Python, it seems like this kind of approach is impossible, and it also means 
> that my form would probably have to have some kind of special extension, like 
> "form.py" (so the handler knows what to do with it) instead of just being 
> located at "form.htm" - am I following this all correctly? 
> 
> Does anyone know of any soup-to-nuts CGI programming examples online for 
> Python that might make this clearer so I can bug the list less and just read 
> some example code?
> 
> -Jay
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From keridee at jayco.net  Fri Sep 30 03:10:56 2005
From: keridee at jayco.net (Jacob S.)
Date: Thu, 29 Sep 2005 20:10:56 -0500
Subject: [Tutor] Quick way to find the data type
References: <61d0e2b405092713116a85bbb0@mail.gmail.com><Pine.LNX.4.44.0509271312460.10346-100000@hkn.eecs.berkeley.edu>
	<61d0e2b405092714264ca503fc@mail.gmail.com>
Message-ID: <052c01c5c55b$e79cb5b0$6601a8c0@JSLAPTOP>

I don't believe that eval() *would* work quite as intended either.

For example:

eval('a random string')
SyntaxError

and McGuire's method

othermethod('a random string')
'a random string'

Another example

eval('file')
<type 'file'>

othermethod('file')
'file'


That is, of course, if I understood the McGuire's method clearly. I didn't 
look very close. It might be that McGuire's method doesn't account for the 
second case either.

HTH,
Jacob


> Fair enough Danny,
> I made the changes. Thanks for the input.
>
>
> Still, regarding this comment.....
>
> On 9/27/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>> The assumptions you make, about controlling the input, and being the only
>> source of the xml output, sound fine.  But you're assuming that the
>> environment that your program will work in will be static.  Software 
>> often
>> ends up being applied in places that are ridiculous and unplanned-for,
>> like a network application.  It's best practice to avoid unneccessary
>> risk, and not to court it.  *grin*
>
> Well, the fact is I'm in charge of these things here, fortunately. My
> job is to make sure nothing gets used the wrong way. :-)
>
> Still, your points are valid and I have taken note of them :-)
>
> Bernard
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


From keridee at jayco.net  Fri Sep 30 03:42:03 2005
From: keridee at jayco.net (Jacob S.)
Date: Thu, 29 Sep 2005 20:42:03 -0500
Subject: [Tutor] script question
References: <9f68812f05092604563052918f@mail.gmail.com><43387C41.20307@tds.net>
	<4338A883.7020001@tds.net>
	<9f68812f050928053548024051@mail.gmail.com>
Message-ID: <05f101c5c560$535af790$6601a8c0@JSLAPTOP>

Why are you importing string?

1) You don't seem to use it anywhere
2) Use string methods instead

Jacob
  ----- Original Message ----- 
  From: Chris Hallman 
  To: tutor at python.org 
  Sent: Wednesday, September 28, 2005 7:35 AM
  Subject: Re: [Tutor] script question


  Thanks for all the input!!! I really appreciate it. I need to post a correction to my script. What I sent was an early version. I made a few minor modifications:


import ConfigParser, string, sys, ossection = sys.argv[1]interface = sys.argv[3]INI=ConfigParser.ConfigParser()INI.read("c:\utils\interfaces.ini")interface_entries=[p for p in INI.options
(section)]interface_list=[INI.get(section, pw) for pw in interface_entries]for i in interface_list:	if i == interface:		os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet -n l17aesm1 forward red held " + 
sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])
  I've researched what you all have suggested and I may need to switch to reading the ini file line by line or using a different file parser. The ini file is only 100 lines long now, but will likely grow to 500 line and maybe to 4000 lines. To give you a better background of what I'm doing with this script, it's running on a network management system that receives traps. After some processing of the raw trap, messages get sent to this script for further processing. These messages are for interface down traps from routers and switches in our network. I use this script to mitigate the number of interface down messages on our console. I need to do this because we do not need to know when every port has gone down (i.e. user ports). This script searches the ini file for a device name match. Once it has found a match and if the interface matches as well, I need to message forwarded to the console (the Windows command). If no matching device or interface is found, then the script can just exit. 
  - Show quoted text -



  On 9/26/05, Kent Johnson <kent37 at tds.net> wrote:
    Kent Johnson wrote:
    > *TEST FIRST* Don't optimize until you know it is too slow and you
    > have a test case that you can time to see if your 'optimizations' are
    > making it faster.

    Pardon my shouting :-) 

    Kent

    _______________________________________________
    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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050929/20a3266e/attachment.htm

From grouch at gmail.com  Fri Sep 30 07:14:27 2005
From: grouch at gmail.com (Andrew P)
Date: Fri, 30 Sep 2005 00:14:27 -0500
Subject: [Tutor] Book recommendations?
Message-ID: <e6443aa70509292214t7c3b6915m10a6d5d7eb27ce87@mail.gmail.com>

I was just thinking about Jon Bentley's Programming Pearls, and how much I
really liked it. Nothing has really changed since 1986, and all the pseudo
code translated nicely into Python. It was by far the most fun I've had
reading any book about programming. Especially solving problems he presented
before turning the page, or trying damned hard to!

Does anybody have any recommendations for other books on programming
practices in general? Any fun or philosophical reads on software
architecture/design?

I saw that Alan Gauld recommends Code Complete, and went ahead and ordered
that second hand :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050930/acec37e3/attachment.htm

From project5 at redrival.net  Fri Sep 30 08:19:43 2005
From: project5 at redrival.net (Andrei)
Date: Fri, 30 Sep 2005 06:19:43 +0000 (UTC)
Subject: [Tutor] Installing ActiveState Python vs2003
References: <d91bb71205092905176d20c8ad@mail.gmail.com>
Message-ID: <loom.20050930T081256-702@post.gmane.org>

Mohammad Moghimi <m.moghimi <at> gmail.com> writes:

> When I tried  to install activestate python(.net implementation of python) to
my visual studio 2003.
> It gives me this error message:
>
> The Visual Python Installer found an installation of Python 2.4, 
> but it also requires the win32 extensions.
>
> what's  the problem? -- Mohammaddo you Python?!!

It seems you need to install win32all
(http://starship.python.net/crew/mhammond/win32/). The ActiveState Python distro
(ActivePython) includes this as well. Note that ActivePython is not the same
thing as ActiveState Visual Python, which seems to be what you got - one is a
Python distro, the other is an extension of the VisualStudio IDE. Neither is a
.Net implementation of Python, IronPython is (http://www.ironpython.com/).

Yours,

Andrei


From alan.gauld at freenet.co.uk  Fri Sep 30 09:44:02 2005
From: alan.gauld at freenet.co.uk (alan.gauld@freenet.co.uk)
Date: Fri, 30 Sep 2005 08:44:02 +0100
Subject: [Tutor] call a def/class by reference
Message-ID: <380-2200595307442249@freenet.co.uk>

>>On Thursday 29 September 2005 22:26, Alan G wrote:
>>> string -> function mapping directly.
>>>
>>> Its not usually a very useful thing to do
>>
>This is precisely how shared libraries under linux and IIRC DLLs in
>windows work. cf dlopen, dysym in C. 

No, its completely different. These are not  done at the language 
level but are implemented in the OS using an explicit mapoping 
table built as part of the shared library creation process. That is 
the language builds a dictionary of the string-function mapping. 
It is not a feature of any of the languages used for building the 
libraries.

>using "nm".
>>
>>eg:
>># nm libpython2.4.so|head -20
>>         U abort@@GLIBC_2.0
>>000dfea0 d abs_doc
>>0001fcf0 t abstract_get_bases
>>0001fe20 t abstract_issubclass

Yres but those names are not typed in  as strings to call 
the functions rather they are uised by the programmer 
to access the functions through the library.

>>Obviously, ctypes does much the same thing. 

but again by using/building mapping tables, ctypes is written 
in C and Python neither of which provides a string-function 
mapping. And ctypes is not exactly a commmon application type! 

>>try: 	 
>>    from ctypes import * 	 
>>    libc = cdll.LoadLibrary("/lib/libc.so.6") 	 
>>    sched_yield = libc.sched_yield
>> except ImportError: 	 

>>try:
>>   import functions as libc
>>   sched_yield = getattr(libc, "sched_yield")
>>                               # this is of course effectively
>equivalent to:
>>                               #   sched_yield = libc.sched_yield

Yes, but getattr is simply looking up a dictionary which had 
to be built by ctypes to start with - which is what the OP didn't 
want to do... My argument was not that this was something 
you'd never want to do just that its not something normally 
supported by languages because its an unusual thing 
to do - developers are unusual people, they do unusual things :-)

And of course if you want to delve into the innards of Python 
you can pretty much do what was requested using the builtin 
dictyionary/module mechanisms, but its not a simple \
mechanism and not recommended for general applications use...


Alan G


From kent37 at tds.net  Fri Sep 30 11:48:26 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Sep 2005 05:48:26 -0400
Subject: [Tutor] script question
In-Reply-To: <9f68812f05092805343e834cb8@mail.gmail.com>
References: <9f68812f05092604563052918f@mail.gmail.com>	
	<43387C41.20307@tds.net> <4338A883.7020001@tds.net>
	<9f68812f05092805343e834cb8@mail.gmail.com>
Message-ID: <433D09EA.6020701@tds.net>

Chris Hallman wrote:
> 
> Thanks for all the input!!! I really appreciate it. I need to post a 
> correction to my script. What I sent was an early version. I made a few 
> minor modifications:

You don't seem to have incorporated any of the suggestions that you have received!

I doubt that a 4000-line ini file will be any problem at all.

Kent

> 
> import ConfigParser, string, sys, os
> section = sys.argv[1]
> interface = sys.argv[3]
> INI=ConfigParser.ConfigParser()
> INI.read("c:\utils\interfaces.ini")
> interface_entries=[p for p in INI.options
> (section)]
> interface_list=[INI.get(section, pw) for pw in interface_entries]
> for i in interface_list:
> 	if i == interface:
> 		os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet -n l17aesm1 forward red held " + 
> sys.argv[1] + " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])
> 
> 
> I've researched what you all have suggested and I may need to switch to 
> reading the ini file line by line or using a different file parser. The 
> ini file is only 100 lines long now, but will likely grow to 500 line 
> and maybe to 4000 lines. To give you a better background of what I'm 
> doing with this script, it's running on a network management system that 
> receives traps. After some processing of the raw trap, messages get sent 
> to this script for further processing. These messages are for interface 
> down traps from routers and switches in our network. I use this script 
> to mitigate the number of interface down messages on our console. I need 
> to do this because we do not need to know when every port has gone down 
> (i.e. user ports). This script searches the ini file for a device name 
> match. Once it has found a match and if the interface matches as well, I 
> need to message forwarded to the console (the Windows command). If no 
> matching device or interface is found, then the script can just exit.
> 
> 
> On 9/26/05, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> wrote:
> 
>     Kent Johnson wrote:
>      > *TEST FIRST* Don't optimize until you know it is too slow and you
>      > have a test case that you can time to see if your 'optimizations' are
>      > making it faster.
> 
>     Pardon my shouting :-)
> 
>     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 kent37 at tds.net  Fri Sep 30 11:57:51 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Sep 2005 05:57:51 -0400
Subject: [Tutor] Book recommendations?
In-Reply-To: <e6443aa70509292214t7c3b6915m10a6d5d7eb27ce87@mail.gmail.com>
References: <e6443aa70509292214t7c3b6915m10a6d5d7eb27ce87@mail.gmail.com>
Message-ID: <433D0C1F.1090709@tds.net>

Andrew P wrote:
> Does anybody have any recommendations for other books on programming 
> practices in general?  Any fun or philosophical reads on software 
> architecture/design?

Some of the highlights from my bookshelf:

Hunt & Thomas, The Pragmatic Programmer
http://pragmaticprogrammer.com/ppbook/index.shtml

(and the other books from  the Pragmatic Bookshelf)
http://pragmaticprogrammer.com/bookshelf/index.html

Martin, Agile Software Development
http://www.objectmentor.com/resources/bookstore/books/AgileSoftwareDevelopmentPPP

Fowler, Refactoring: Improving the Design of Existing Code
http://martinfowler.com/books.html#refactoring

Beck, Extreme Programming Explained
http://www.amazon.com/exec/obidos/ASIN/0201616416/ref%3Dnosim/armaties/102-7636110-6481700

Kent


From kent37 at tds.net  Fri Sep 30 13:57:38 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Sep 2005 07:57:38 -0400
Subject: [Tutor] Book recommendations?
In-Reply-To: <433D0C1F.1090709@tds.net>
References: <e6443aa70509292214t7c3b6915m10a6d5d7eb27ce87@mail.gmail.com>
	<433D0C1F.1090709@tds.net>
Message-ID: <433D2832.9080408@tds.net>

Kent Johnson wrote:
> Some of the highlights from my bookshelf:

How could I forget the Gang of Four? This is the book that started the Design Patterns movement.
Gamma, Helm, Johnson & Vlissides, Design Patterns
http://www.aw-bc.com/catalog/academic/product/0,1144,0201633612,00.html

> Beck, Extreme Programming Explained
> http://www.amazon.com/exec/obidos/ASIN/0201616416/ref%3Dnosim/armaties/102-7636110-6481700

The publisher's website for this book is
http://www.aw-bc.com/catalog/academic/product/0,1144,0321278658,00.html

and I see from that site that there is a second edition out which looks like it might be worth a read even if you have read the first. From a review at Bookpool:
This edition is a completely new version of the book. For example, there are new chapters on Taylorism, lean manufacturing, and the theory of constraints. There are many new ideas and XP is now explained more in terms of its values and principles than through strict adherence to twelve specific practices.

By the way bookpool.com is my favorite place to buy technical books, their prices are often lower than Amazon.com and shipping is reasonable and fast.

Kent


From lopoff at gmx.net  Fri Sep 30 14:44:21 2005
From: lopoff at gmx.net (lmac)
Date: Fri, 30 Sep 2005 14:44:21 +0200
Subject: [Tutor] find data in html file
Message-ID: <433D3325.8050402@gmx.net>

Date: Wed, 28 Sep 2005 09:25:53 +0100
From: Ed Singleton <singletoned at gmail.com>
Subject: Re: [Tutor] find data in html file
To: tutor at python.org
Message-ID: <34bb7f5b0509280125208d435e at mail.gmail.com>
Content-Type: text/plain; charset=ISO-8859-1

On 27/09/05, lmac <lopoff at gmx.net> wrote:

>> Hi there,
>> i have a base-question. If i want to read some kind of data out of a line
>> which i know the start-tag and the end-tag in an html-file how do i
>> recognize
>> if it's more than one line ?
>>
>> Example:
>>
>> <td>Some text<a href>link</a>text ..... DATA ....</tr></td> etc.
>>
>> I would use >text as the starting tag to localize the beginning of the DATA.
>> And then </tr> as the ending tag of the DATA. But if there is \n then
>> there are more than
>> one line.
>  
>

Hopefully it's just a typo or something, but you appear to have your
ending </tr> and </td> tags the wrong way round.

You should be closing the cell before you close the row.

How do you want to get the data out?  This case is simple enough that
you could do a lazy (non-greedy) regex statement for it.  Something
like "<td>([\s|\S]+?)</td>" would do it.

Ed

It's not this simple. The whole thing is that i try to use ebay.de for fetching websites
when i give an articlenumber. The downloading of the site for a specific article is no problem.
But to get the data like price,bidders,shipment etc without the official eBayAPI is hard.
Maybe anyone has a solution made ?

Thanks anyway. I tried the htmllib. This is a very good lib but i don't get it to work cos
there is no <tag> thing for the data i want to get. This is for html-tags. And to store data
in my own XML-files. (what i am goint to do when i get the data).






From john.ertl at fnmoc.navy.mil  Fri Sep 30 16:11:07 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Fri, 30 Sep 2005 07:11:07 -0700
Subject: [Tutor] Finding difference in two .gif
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C871@lanexc107p.fnmoc.navy.mil>

 
All,

I have two gif images that should be exactly the same...one static and the
other recreated from the same data. For months this has been working great
but yesterday the "new" image that I made was slightly different.  The image
size is 4 bytes different.  When I look at the image side by side I can not
see the difference.  I have very limited image manipulation software and I
was trying to isolate the image difference using PIL but all I get are black
images. I know nothing about how the imaging works so it could be as easy as
reseting the scale but I tried with no luck. 

Does anyone know how to isolate (hopefully small) image differences using
PIL?

Thank you,

John Ertl

Python 2.4, PIL 1.1.5
The simple code I have tried:

import Image
import ImageChops

file1 = Image.open("/home/PT04_RH.2005072300.gif")

file2 = Image.open("/home/PT04_RH.2005093000.gif")

#diffImage = ImageChops.difference(file1,file2)

diffImage = ImageChops.subtract(file1,file2)



diffImage.save("diffOut.gif")

From mhansen at cso.atmel.com  Fri Sep 30 16:17:24 2005
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Fri, 30 Sep 2005 08:17:24 -0600
Subject: [Tutor] Book recommendations?
In-Reply-To: <mailman.56.1128074423.2661.tutor@python.org>
References: <mailman.56.1128074423.2661.tutor@python.org>
Message-ID: <433D48F4.40100@cso.atmel.com>

> Subject:
> Re: [Tutor] Book recommendations?
> From:
> Kent Johnson <kent37 at tds.net>
> Date:
> Fri, 30 Sep 2005 05:57:51 -0400
> 
> CC:
> Python Tutor list <tutor at python.org>
> 
> 
> Andrew P wrote:
> 
>> Does anybody have any recommendations for other books on programming 
>> practices in general?  Any fun or philosophical reads on software 
>> architecture/design?
> 
> 
> Some of the highlights from my bookshelf:
> 
> Hunt & Thomas, The Pragmatic Programmer
> http://pragmaticprogrammer.com/ppbook/index.shtml
> 
> (and the other books from  the Pragmatic Bookshelf)
> http://pragmaticprogrammer.com/bookshelf/index.html
> 
> Martin, Agile Software Development
> http://www.objectmentor.com/resources/bookstore/books/AgileSoftwareDevelopmentPPP 
> 
> 
> Fowler, Refactoring: Improving the Design of Existing Code
> http://martinfowler.com/books.html#refactoring
> 
> Beck, Extreme Programming Explained
> http://www.amazon.com/exec/obidos/ASIN/0201616416/ref%3Dnosim/armaties/102-7636110-6481700 
> 
> 
> Kent

All of the above are great picks. I'd also recommend Joel On Software. It's a 
collection of his articles from his web site.

Mike

From kent37 at tds.net  Fri Sep 30 16:32:41 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Sep 2005 10:32:41 -0400
Subject: [Tutor] find data in html file
In-Reply-To: <433D3325.8050402@gmx.net>
References: <433D3325.8050402@gmx.net>
Message-ID: <433D4C89.8050906@tds.net>

lmac wrote:
> It's not this simple. The whole thing is that i try to use ebay.de for fetching websites
> when i give an articlenumber. The downloading of the site for a specific article is no problem.
> But to get the data like price,bidders,shipment etc without the official eBayAPI is hard.
> Maybe anyone has a solution made ?
> 
> Thanks anyway. I tried the htmllib. This is a very good lib but i don't get it to work cos
> there is no <tag> thing for the data i want to get. This is for html-tags. And to store data
> in my own XML-files. (what i am goint to do when i get the data).

You can try BeautifulSoup which is designed for screen-scraping:
http://www.crummy.com/software/BeautifulSoup/

But looking at the source for an eBay page it looks challenging. I wonder why you don't use the eBay API to get the information you want? It seems to be free for up to 10,000 requests a month and there is a python package to access it.

Kent


From paul1brian at gmail.com  Fri Sep 30 16:55:26 2005
From: paul1brian at gmail.com (paul brian)
Date: Fri, 30 Sep 2005 15:55:26 +0100
Subject: [Tutor] find data in html file
In-Reply-To: <bbe9926e0509300753p66876f0csba5378db895d3f25@mail.gmail.com>
References: <433D3325.8050402@gmx.net> <433D4C89.8050906@tds.net>
	<bbe9926e0509300753p66876f0csba5378db895d3f25@mail.gmail.com>
Message-ID: <bbe9926e0509300755g1e8aaef3r491e9c0d08896825@mail.gmail.com>

> But to get the data like price,bidders,shipment etc without the official
> eBayAPI is hard.
> Maybe anyone has a solution made ?

 Ebay specifically change around their HTML codes, tags and formatting
 (in quite a clever way) to stop people doing exactly what you are
 trying to do. I think it changes every month.

 Like people say, use the API - You need to become an "ebay developer"
 (signup) and can use your own code or the python-ebay thing for free
 in "the sandbox", but must pay $100 or so to have your code verified
 as "not likey to scrunch our servers" before they give you a key for
 the real world.

 Its a bit of a pain, so i just hacked turbo-ebay a while back and made
 do.  Worked quite well really.


--
--------------------------
Paul Brian
m. 07875 074 534
t. 0208 352 1741

From 3dbernard at gmail.com  Fri Sep 30 17:13:12 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri, 30 Sep 2005 11:13:12 -0400
Subject: [Tutor] Problem with BeautifulSoup
In-Reply-To: <433B5E7D.7060601@tds.net>
References: <61d0e2b405092311354fd2d76e@mail.gmail.com>
	<e6443aa7050923120758b6dbc3@mail.gmail.com>
	<61d0e2b405092312154bce6c53@mail.gmail.com> <4337C8C3.5020701@tds.net>
	<61d0e2b4050928182566867988@mail.gmail.com> <433B5E7D.7060601@tds.net>
Message-ID: <61d0e2b40509300813p710ad424k9aeb37de36d69140@mail.gmail.com>

Hi Kent,

Well I have decided to get this sorted once and for all. Not that I
don't like ElementTree, but the fack is that BeautifulSoup uses a near
identical syntax to the 3D application SDK's object model I'm using it
with, making interaction between the 3D and the XML extremely
transparent. Anyway, here is what I did.

I simply modified the BeautifulSoup class, and added my own nestable
tags to the list of NESTABLE_BLOCK_TAGS:

NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del']

became

NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del',
'sceneobject', 'parameters', 'parameter', 'shader']


Not super-elegant but it works. I wrote to the author but did not get an answer.


Thanks everyone!
Bernard



On 9/28/05, Kent Johnson <kent37 at tds.net> wrote:
> Bernard Lebel wrote:
> > Hi Kent,
> >
> > Thanks a lot for that answer. I have had a look at the BS code, and I
> > have to admit I'm a bit at a loss: how would you add several nestable
> > tag names in that list?
> >
> > I tried
> > NESTABLE_TAGS = BeautifulSoup.buildTagMap( [], 'parameter', 'parameters' )
> > for example, but I kept having these nesting issues. I fact I have a
> > whole bunch of tags that I need to make nestable....
>
> I think that's right but I confess I don't understand that part of the code too well either. Maybe an email to the author? or maybe it's time to try ElementTree (and pdis XPath?) again.
>
> Kent
>
> >
> >
> > Thanks
> > Bernard
> >
> >
> > On 9/26/05, Kent Johnson <kent37 at tds.net> wrote:
> >
> >>Bernard Lebel wrote:
> >>
> >>>Hi grouchy,
> >>>
> >>>I seem to have found the problem. Somehow, it seems BeautifulSoup
> >>>doesn't like nested tags of the same name.
> >>
> >>This seems to be a feature of BS. It seems a bit of a misfeature when applied to XML but anyway...you can configure BS with a set of tags which can be nested, then it will properly parse your data. Here is a short program that shows how:
> >>
> >>xml = '''<parameter scriptname="posx">
> >>    <fcurve plotted="False">
> >>          <parameter scriptname="extrapolation">1</parameter>
> >>    </fcurve>
> >></parameter>'''
> >>
> >>import BeautifulSoup
> >>
> >>class NestingParser(BeautifulSoup.BeautifulStoneSoup):
> >>    NESTABLE_TAGS = BeautifulSoup.buildTagMap([], 'parameter')
> >>
> >>soup = NestingParser(xml)
> >>print soup.prettify()
> >>
> >>
> >>Kent
> >>
> >>_______________________________________________
> >>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
> >
> >
>
>

From kent37 at tds.net  Fri Sep 30 17:32:29 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Sep 2005 11:32:29 -0400
Subject: [Tutor] Problem with BeautifulSoup
In-Reply-To: <61d0e2b40509300813p710ad424k9aeb37de36d69140@mail.gmail.com>
References: <61d0e2b405092311354fd2d76e@mail.gmail.com>	<e6443aa7050923120758b6dbc3@mail.gmail.com>	<61d0e2b405092312154bce6c53@mail.gmail.com>
	<4337C8C3.5020701@tds.net>	<61d0e2b4050928182566867988@mail.gmail.com>
	<433B5E7D.7060601@tds.net>
	<61d0e2b40509300813p710ad424k9aeb37de36d69140@mail.gmail.com>
Message-ID: <433D5A8D.2090803@tds.net>

Bernard Lebel wrote:
> Hi Kent,
> 
> Well I have decided to get this sorted once and for all. Not that I
> don't like ElementTree, but the fack is that BeautifulSoup uses a near
> identical syntax to the 3D application SDK's object model I'm using it
> with, making interaction between the 3D and the XML extremely
> transparent. Anyway, here is what I did.
> 
> I simply modified the BeautifulSoup class, and added my own nestable
> tags to the list of NESTABLE_BLOCK_TAGS:
> 
> NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del']
> 
> became
> 
> NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del',
> 'sceneobject', 'parameters', 'parameter', 'shader']

For your purposes I think you should be able to just do
class MyBeautifulSoup(BeautifulSoup.BeautifulStoneSoup):
    NESTABLE_BLOCK_TAGS = ['sceneobject', 'parameters', 'parameter', 'shader']

since presumably you don't need special handling for 'ol', 'ul', etc that BeautifulSoup has.

In any event there is no need to modify BS, better to make your own BSS subclass.

Kent


From grouch at gmail.com  Fri Sep 30 17:33:08 2005
From: grouch at gmail.com (Andrew P)
Date: Fri, 30 Sep 2005 10:33:08 -0500
Subject: [Tutor] Book recommendations?
In-Reply-To: <433D2832.9080408@tds.net>
References: <e6443aa70509292214t7c3b6915m10a6d5d7eb27ce87@mail.gmail.com>
	<433D0C1F.1090709@tds.net> <433D2832.9080408@tds.net>
Message-ID: <e6443aa70509300833y2fd391e8ud5401134f86830da@mail.gmail.com>

Thanks for the recommendations, Kent.

Kent wrote:

> How could I forget the Gang of Four? This is the book that started the
> Design Patterns movement.
> Gamma, Helm, Johnson & Vlissides, Design Patterns
> http://www.aw-bc.com/catalog/academic/product/0,1144,0201633612,00.html



I probably shouldn't forget this either. OOP is largely a mystery to me, and
it's hard/impossible to read anything about it without a reference to that
book.


Kent wrote:

By the way bookpool.com <http://bookpool.com> is my favorite place to buy
> technical books, their prices are often lower than Amazon.com<http://Amazon.com>and shipping is reasonable and fast.


Let me make my own quick recommendation for half.com <http://half.com>, and
alibris.com <http://alibris.com>. I like to look at those for any used
copies before ordering new. They are both listings from independent
booksellers around the country, with standardized shipping. I also have many
under-a-dollar books of the non-technical variety from both places on my
bookshelf.

I end up buying technical books new about half the time, since newer ones
hold so much value used. I'm not ecstatic about ordering from Amazon on the
best of days, so the recommendation is appreciated.

Thanks again,

Andrew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050930/7c6197e9/attachment-0001.htm

From grouch at gmail.com  Fri Sep 30 17:34:27 2005
From: grouch at gmail.com (Andrew P)
Date: Fri, 30 Sep 2005 10:34:27 -0500
Subject: [Tutor] Book recommendations?
In-Reply-To: <433D48F4.40100@cso.atmel.com>
References: <mailman.56.1128074423.2661.tutor@python.org>
	<433D48F4.40100@cso.atmel.com>
Message-ID: <e6443aa70509300834t2d9bf03ndbfc0c638d1c74f3@mail.gmail.com>

Thanks Mike. Many a google search has landed me on his site, and I always
end up reading more than what I landed on :)


All of the above are great picks. I'd also recommend Joel On Software. It's
> a
> collection of his articles from his web site.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050930/c5041eab/attachment.html

From 3dbernard at gmail.com  Fri Sep 30 17:40:19 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri, 30 Sep 2005 11:40:19 -0400
Subject: [Tutor] Problem with BeautifulSoup
In-Reply-To: <433D5A8D.2090803@tds.net>
References: <61d0e2b405092311354fd2d76e@mail.gmail.com>
	<e6443aa7050923120758b6dbc3@mail.gmail.com>
	<61d0e2b405092312154bce6c53@mail.gmail.com> <4337C8C3.5020701@tds.net>
	<61d0e2b4050928182566867988@mail.gmail.com> <433B5E7D.7060601@tds.net>
	<61d0e2b40509300813p710ad424k9aeb37de36d69140@mail.gmail.com>
	<433D5A8D.2090803@tds.net>
Message-ID: <61d0e2b40509300840k4a3568an8b99c7643d3ccc30@mail.gmail.com>

I know I should be doing that. But somehow it doesn't work (ie I keep
getting mangled XML tree).

Bernard



On 9/30/05, Kent Johnson <kent37 at tds.net> wrote:
> Bernard Lebel wrote:
> > Hi Kent,
> >
> > Well I have decided to get this sorted once and for all. Not that I
> > don't like ElementTree, but the fack is that BeautifulSoup uses a near
> > identical syntax to the 3D application SDK's object model I'm using it
> > with, making interaction between the 3D and the XML extremely
> > transparent. Anyway, here is what I did.
> >
> > I simply modified the BeautifulSoup class, and added my own nestable
> > tags to the list of NESTABLE_BLOCK_TAGS:
> >
> > NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del']
> >
> > became
> >
> > NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del',
> > 'sceneobject', 'parameters', 'parameter', 'shader']
>
> For your purposes I think you should be able to just do
> class MyBeautifulSoup(BeautifulSoup.BeautifulStoneSoup):
>     NESTABLE_BLOCK_TAGS = ['sceneobject', 'parameters', 'parameter', 'shader']
>
> since presumably you don't need special handling for 'ol', 'ul', etc that BeautifulSoup has.
>
> In any event there is no need to modify BS, better to make your own BSS subclass.
>
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From john.ertl at fnmoc.navy.mil  Fri Sep 30 17:50:52 2005
From: john.ertl at fnmoc.navy.mil (Ertl, John)
Date: Fri, 30 Sep 2005 08:50:52 -0700
Subject: [Tutor] Finding difference in two .gif
Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C873@lanexc107p.fnmoc.navy.mil>


All,

Well I found the answer...getbox() gave me the bounding box and then I could
just plot that portion of the two images.
 
Python 2.4, PIL 1.1.5
The simple code I have tried:

import Image
import ImageChops

file1 = Image.open("/home/PT04_RH.2005072300.gif")

file2 = Image.open("/home/PT04_RH.2005093000.gif")

            diffbox = ImageChops.difference(file1,file2).getbbox()
            diffImage = file1.crop(diffbox)

diffImage.save("diffOut.gif")
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor

From kent37 at tds.net  Fri Sep 30 17:50:53 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Sep 2005 11:50:53 -0400
Subject: [Tutor] Problem with BeautifulSoup
In-Reply-To: <61d0e2b40509300840k4a3568an8b99c7643d3ccc30@mail.gmail.com>
References: <61d0e2b405092311354fd2d76e@mail.gmail.com>	<e6443aa7050923120758b6dbc3@mail.gmail.com>	<61d0e2b405092312154bce6c53@mail.gmail.com>
	<4337C8C3.5020701@tds.net>	<61d0e2b4050928182566867988@mail.gmail.com>
	<433B5E7D.7060601@tds.net>	<61d0e2b40509300813p710ad424k9aeb37de36d69140@mail.gmail.com>	<433D5A8D.2090803@tds.net>
	<61d0e2b40509300840k4a3568an8b99c7643d3ccc30@mail.gmail.com>
Message-ID: <433D5EDD.3010806@tds.net>

Oh, what if you try

class MyBeautifulSoup(BeautifulSoup.BeautifulStoneSoup):
    NESTABLE_BLOCK_TAGS = ['sceneobject', 'parameters', 'parameter', 'shader']
    NESTABLE_TAGS = buildTagMap([], NESTABLE_BLOCK_TAGS)


Bernard Lebel wrote:
> I know I should be doing that. But somehow it doesn't work (ie I keep
> getting mangled XML tree).
> 
> Bernard
> 
> 
> 
> On 9/30/05, Kent Johnson <kent37 at tds.net> wrote:
> 
>>Bernard Lebel wrote:
>>
>>>Hi Kent,
>>>
>>>Well I have decided to get this sorted once and for all. Not that I
>>>don't like ElementTree, but the fack is that BeautifulSoup uses a near
>>>identical syntax to the 3D application SDK's object model I'm using it
>>>with, making interaction between the 3D and the XML extremely
>>>transparent. Anyway, here is what I did.
>>>
>>>I simply modified the BeautifulSoup class, and added my own nestable
>>>tags to the list of NESTABLE_BLOCK_TAGS:
>>>
>>>NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del']
>>>
>>>became
>>>
>>>NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del',
>>>'sceneobject', 'parameters', 'parameter', 'shader']
>>
>>For your purposes I think you should be able to just do
>>class MyBeautifulSoup(BeautifulSoup.BeautifulStoneSoup):
>>    NESTABLE_BLOCK_TAGS = ['sceneobject', 'parameters', 'parameter', 'shader']
>>
>>since presumably you don't need special handling for 'ol', 'ul', etc that BeautifulSoup has.
>>
>>In any event there is no need to modify BS, better to make your own BSS subclass.
>>
>>Kent
>>
>>_______________________________________________
>>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
> 
> 


From 3dbernard at gmail.com  Fri Sep 30 18:05:02 2005
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri, 30 Sep 2005 12:05:02 -0400
Subject: [Tutor] Problem with BeautifulSoup
In-Reply-To: <433D5EDD.3010806@tds.net>
References: <61d0e2b405092311354fd2d76e@mail.gmail.com>
	<e6443aa7050923120758b6dbc3@mail.gmail.com>
	<61d0e2b405092312154bce6c53@mail.gmail.com> <4337C8C3.5020701@tds.net>
	<61d0e2b4050928182566867988@mail.gmail.com> <433B5E7D.7060601@tds.net>
	<61d0e2b40509300813p710ad424k9aeb37de36d69140@mail.gmail.com>
	<433D5A8D.2090803@tds.net>
	<61d0e2b40509300840k4a3568an8b99c7643d3ccc30@mail.gmail.com>
	<433D5EDD.3010806@tds.net>
Message-ID: <61d0e2b40509300905l14bd526bp29b6554566fcaaab@mail.gmail.com>

Nice!


Thanks Kent
Bernard



On 9/30/05, Kent Johnson <kent37 at tds.net> wrote:
> Oh, what if you try
>
> class MyBeautifulSoup(BeautifulSoup.BeautifulStoneSoup):
>     NESTABLE_BLOCK_TAGS = ['sceneobject', 'parameters', 'parameter', 'shader']
>     NESTABLE_TAGS = buildTagMap([], NESTABLE_BLOCK_TAGS)
>
>
> Bernard Lebel wrote:
> > I know I should be doing that. But somehow it doesn't work (ie I keep
> > getting mangled XML tree).
> >
> > Bernard
> >
> >
> >
> > On 9/30/05, Kent Johnson <kent37 at tds.net> wrote:
> >
> >>Bernard Lebel wrote:
> >>
> >>>Hi Kent,
> >>>
> >>>Well I have decided to get this sorted once and for all. Not that I
> >>>don't like ElementTree, but the fack is that BeautifulSoup uses a near
> >>>identical syntax to the 3D application SDK's object model I'm using it
> >>>with, making interaction between the 3D and the XML extremely
> >>>transparent. Anyway, here is what I did.
> >>>
> >>>I simply modified the BeautifulSoup class, and added my own nestable
> >>>tags to the list of NESTABLE_BLOCK_TAGS:
> >>>
> >>>NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del']
> >>>
> >>>became
> >>>
> >>>NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del',
> >>>'sceneobject', 'parameters', 'parameter', 'shader']
> >>
> >>For your purposes I think you should be able to just do
> >>class MyBeautifulSoup(BeautifulSoup.BeautifulStoneSoup):
> >>    NESTABLE_BLOCK_TAGS = ['sceneobject', 'parameters', 'parameter', 'shader']
> >>
> >>since presumably you don't need special handling for 'ol', 'ul', etc that BeautifulSoup has.
> >>
> >>In any event there is no need to modify BS, better to make your own BSS subclass.
> >>
> >>Kent
> >>
> >>_______________________________________________
> >>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
> >
> >
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

From andrade1 at umbc.edu  Fri Sep 30 18:18:54 2005
From: andrade1 at umbc.edu (andrade1@umbc.edu)
Date: Fri, 30 Sep 2005 12:18:54 -0400 (EDT)
Subject: [Tutor] drawing a face
Message-ID: <2668.172.149.161.55.1128097134.squirrel@172.149.161.55>

Hello

I am trying to draw a basic face with eyes, nose, and a mouth. I keep
receiving the following error message:

>>>
Traceback (most recent call last):
  File "C:\Documents and Settings\Michele\Desktop\face", line 26, in ?
    main()
  File "C:\Documents and Settings\Michele\Desktop\face", line 10, in main
    leftEye = Cirlce(Point(285,210), 50)
NameError: global name 'Cirlce' is not defined

also I know i want an oval for the month but I only need half of one how
would i just get half of the oval?






from graphics import*

def main():
 win = GraphWin()
 shape = Circle(Point(300,200), 40)
 shape.setOutline("black")
 shape.setFill("orange")
 shape.draw(win)

 leftEye = Cirlce(Point(285,210), 50)
 leftEye.setFill("yellow")
 leftEye.setOutline("orange")
 rightEye = leftEye.clone()
 leftEye.draw(win)
 rightEye.draw(win)

        sidenose = Line(245, 265)
        botnose = Line(245,0)
        sidenose.draw(win)
        botnose.draw(win)

 win.getMouse()
 win.close()



main()



From gharper at medplus.com  Fri Sep 30 18:22:35 2005
From: gharper at medplus.com (Harper, Gina)
Date: Fri, 30 Sep 2005 12:22:35 -0400
Subject: [Tutor] drawing a face
Message-ID: <6DE1947A5F75F247852802839D05F83D335237@medexch2.medplus.com>

Looks like you misspelled circle...

-----Original Message-----
From: andrade1 at umbc.edu [mailto:andrade1 at umbc.edu] 
Sent: Friday, September 30, 2005 12:19 PM
To: tutor at python.org
Subject: [Tutor] drawing a face


Hello

I am trying to draw a basic face with eyes, nose, and a mouth. I keep
receiving the following error message:

>>>
Traceback (most recent call last):
  File "C:\Documents and Settings\Michele\Desktop\face", line 26, in ?
    main()
  File "C:\Documents and Settings\Michele\Desktop\face", line 10, in
main
    leftEye = Cirlce(Point(285,210), 50)
NameError: global name 'Cirlce' is not defined

also I know i want an oval for the month but I only need half of one how
would i just get half of the oval?






from graphics import*

def main():
 win = GraphWin()
 shape = Circle(Point(300,200), 40)
 shape.setOutline("black")
 shape.setFill("orange")
 shape.draw(win)

 leftEye = Cirlce(Point(285,210), 50)
 leftEye.setFill("yellow")
 leftEye.setOutline("orange")
 rightEye = leftEye.clone()
 leftEye.draw(win)
 rightEye.draw(win)

        sidenose = Line(245, 265)
        botnose = Line(245,0)
        sidenose.draw(win)
        botnose.draw(win)

 win.getMouse()
 win.close()



main()


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

From digitalsuicide at gmail.com  Fri Sep 30 18:21:26 2005
From: digitalsuicide at gmail.com (dataw0lf)
Date: Fri, 30 Sep 2005 10:21:26 -0600
Subject: [Tutor] drawing a face
In-Reply-To: <2668.172.149.161.55.1128097134.squirrel@172.149.161.55>
References: <2668.172.149.161.55.1128097134.squirrel@172.149.161.55>
Message-ID: <433D6606.3030508@gmail.com>

andrade1 at umbc.edu wrote:

> NameError: global name 'Cirlce' is not defined

Looks like you misspelled 'Circle'


-- 

Joshua Simpson -- dataw0lf.org
Lead Network Administrator/Engineer Aero-Graphics Inc.
jsimpson at aero-graphics.com

From kent37 at tds.net  Fri Sep 30 18:41:06 2005
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 30 Sep 2005 12:41:06 -0400
Subject: [Tutor] drawing a face
In-Reply-To: <2668.172.149.161.55.1128097134.squirrel@172.149.161.55>
References: <2668.172.149.161.55.1128097134.squirrel@172.149.161.55>
Message-ID: <433D6AA2.1030905@tds.net>

andrade1 at umbc.edu wrote:
> also I know i want an oval for the month but I only need half of one how
> would i just get half of the oval?

You are using John Zelle's graphics module, right? I don't think that module supports drawing part of an oval. As a work-around you could try drawing the whole oval, then draw a white rectangle that covers the half you don't want.

Good luck,
Kent

> 
> 
> 
> 
> 
> 
> from graphics import*
> 
> def main():
>  win = GraphWin()
>  shape = Circle(Point(300,200), 40)
>  shape.setOutline("black")
>  shape.setFill("orange")
>  shape.draw(win)
> 
>  leftEye = Cirlce(Point(285,210), 50)
>  leftEye.setFill("yellow")
>  leftEye.setOutline("orange")
>  rightEye = leftEye.clone()
>  leftEye.draw(win)
>  rightEye.draw(win)
> 
>         sidenose = Line(245, 265)
>         botnose = Line(245,0)
>         sidenose.draw(win)
>         botnose.draw(win)
> 
>  win.getMouse()
>  win.close()
> 
> 
> 
> main()
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


From falcon3166 at hotmail.com  Fri Sep 30 19:52:57 2005
From: falcon3166 at hotmail.com (Nathan Pinno)
Date: Fri, 30 Sep 2005 11:52:57 -0600
Subject: [Tutor] Challenge [was Re: Why won't it enter the quiz?]
References: <mailman.1494.1126923682.508.tutor@python.org>
	<BAY106-DAV83A982705E61EF29D5D9DC4900@phx.gbl>
	<432B8CA9.2000200@christianfreebies.com>
	<BAY106-DAV159F309A389BF7EECD88A1C4970@phx.gbl>
	<be4fbf92050922042136464a41@mail.gmail.com>
	<BAY106-DAV12C80622184DA4A10D6CFBC4960@phx.gbl>
	<6.1.2.0.0.20050922210541.02814178@mail.mric.net>
	<BAY106-DAV92E734F3D5CD2E5A714D5C48B0@phx.gbl>
	<6.1.2.0.0.20050926105329.03561a00@mail.mric.net>
	<BAY106-DAV13043F506FC9ABC94A169EC48B0@phx.gbl>
	<314b61150509301022v4e3c4466u968fb99eda4c7800@mail.gmail.com>
Message-ID: <BAY106-DAV17677E793291A73CD615FEC48F0@phx.gbl>

Lisa and all,

I got rid of that portion of my site. All that's there now is the e-book publishing part of my site.

Nathan Pinno
----- Original Message ----- 
  From: Lisa Fukui 
  To: Nathan Pinno 
  Sent: Friday, September 30, 2005 11:22 AM
  Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]


  Um, I clicked on your link, and it's still showing the error message:

  Sorry, but the page or the file that you're looking for is not here.
  ? Please check to see that you've entered the correct URL. 
  ? The owner of this site may have chosen to delete their membership.
  ? The site may have been removed due to a violation of Tripod's Terms of Service.
  ? The site may have been moved to a different URL.

  Is your website still around?


  On 9/26/05, Nathan Pinno <falcon3166 at hotmail.com> wrote:
    The actual URL is http://zoffee.tripod.com/purchasecompprogs.htm 
      ----- Original Message ----- 
      From: bob 
      To: Nathan Pinno 
      Cc: tutor at python.org 
      Sent: Monday, September 26, 2005 11:54 AM
      Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]


      At 10:34 AM 9/26/2005, Nathan Pinno wrote:

        Bob,
         
        I did what you suggested. Take another look, and tell me if you were a potential customer, would you purchase something?

       I tried http://zoffee.tripod.com/purchasecompprogs.htm I got "Sorry but the page ... is not here." 
       
      Sorry, but the page or the file that you're looking for is not here.




        Why not take the challenge? It's not like I'm asking much.
         
        Nathan Pinno

          ----- Original Message ----- 

          From: bob 

          To: Nathan Pinno 

          Cc: tutor at python.org 

          Sent: Thursday, September 22, 2005 10:08 PM

          Subject: Re: [Tutor] Challenge [was Re: Why won't it enter the quiz?]


          At 06:42 PM 9/22/2005, Nathan Pinno wrote:

            The URL is http://zoffee.tripod.com/purchasecomprogs.htm


          [snip]


          At your invitation I visited the site. I personally would not purchase anything listed there due to insufficient information. I don't know what I'm getting!


          I suggest you dedicate a page to each program with at least one screenshot and explanation of what the program does. 


        _______________________________________________
        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




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

From grouch at gmail.com  Fri Sep 30 20:15:58 2005
From: grouch at gmail.com (Andrew P)
Date: Fri, 30 Sep 2005 13:15:58 -0500
Subject: [Tutor] find data in html file
In-Reply-To: <bbe9926e0509300755g1e8aaef3r491e9c0d08896825@mail.gmail.com>
References: <433D3325.8050402@gmx.net> <433D4C89.8050906@tds.net>
	<bbe9926e0509300753p66876f0csba5378db895d3f25@mail.gmail.com>
	<bbe9926e0509300755g1e8aaef3r491e9c0d08896825@mail.gmail.com>
Message-ID: <e6443aa70509301115p1bab327lf63d42df62d858d4@mail.gmail.com>

It's free now to use the API. You just "self-certify" and get 10,000 calls a
month.

Imac, if you use the API, let me save you some trouble. REST is useless,
SOAP is overly complicated, which leaves XML over HTTP which is really quite
nice. I am not speaking generally, but talking about the ebay
implementatiosn before anybody beats me up :)

Besides, no Python tool I could find would parse that accursed WSDL file,
making SOAP a useless layer over the exact same request as XML over HTTP.

Personally tho, I just scrape what I want, for a variety of reasons. Number
one being when the API breaks, you are screwed. If your scrape breaks, it's
usually 5 minutes to suss out and fix. And breaking happens much, much less
often than you might think. It's a little more initial (monkey) work, since
you don't have a nicely formatted XML file coming back. But the same
principles apply. You need to choose a tool to parse stuctured data.
Elementtree + PDIS Xpath, or BeautifulSoup, either way you are making a tree
and extracting data from it :)

Don't worry if none of this makes sense right now. It's a bit of a learning
curve going down either road, but they are more parallel than not. Sign up
with ebay, get your developer tokens and all that jazz, download elementree
and start making some requests, and parsing what you get back with the tool
of your choice. If that suits your purposes, it is probably the easiest way.

On 9/30/05, paul brian <paul1brian at gmail.com> wrote:
>
> > But to get the data like price,bidders,shipment etc without the official
> > eBayAPI is hard.
> > Maybe anyone has a solution made ?
>
> Ebay specifically change around their HTML codes, tags and formatting
> (in quite a clever way) to stop people doing exactly what you are
> trying to do. I think it changes every month.
>
> Like people say, use the API - You need to become an "ebay developer"
> (signup) and can use your own code or the python-ebay thing for free
> in "the sandbox", but must pay $100 or so to have your code verified
> as "not likey to scrunch our servers" before they give you a key for
> the real world.
>
> Its a bit of a pain, so i just hacked turbo-ebay a while back and made
> do. Worked quite well really.
>
>
> --
> --------------------------
> Paul Brian
> m. 07875 074 534
> t. 0208 352 1741
> _______________________________________________
> 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/20050930/a9735002/attachment.html

From lopoff at gmx.net  Fri Sep 30 22:43:01 2005
From: lopoff at gmx.net (lmac)
Date: Fri, 30 Sep 2005 22:43:01 +0200
Subject: [Tutor] find data in html file
Message-ID: <433DA355.3000203@gmx.net>

>
>
>Message: 5
>Date: Fri, 30 Sep 2005 10:32:41 -0400
>From: Kent Johnson <kent37 at tds.net>
>Subject: Re: [Tutor] find data in html file
>Cc: tutor at python.org
>Message-ID: <433D4C89.8050906 at tds.net>
>Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
>lmac wrote:
>  
>
>>> It's not this simple. The whole thing is that i try to use ebay.de for fetching websites
>>> when i give an articlenumber. The downloading of the site for a specific article is no problem.
>>> But to get the data like price,bidders,shipment etc without the official eBayAPI is hard.
>>> Maybe anyone has a solution made ?
>>> 
>>> Thanks anyway. I tried the htmllib. This is a very good lib but i don't get it to work cos
>>> there is no <tag> thing for the data i want to get. This is for html-tags. And to store data
>>> in my own XML-files. (what i am goint to do when i get the data).
>>    
>>
>
>You can try BeautifulSoup which is designed for screen-scraping:
>http://www.crummy.com/software/BeautifulSoup/
>
>But looking at the source for an eBay page it looks challenging. I wonder why you don't use the eBay API to get the information you want? It seems to be free for up to 10,000 requests a month and there is a python package to access it.
>
>Kent
>
>
>
>------------------------------
>
>Message: 6
>Date: Fri, 30 Sep 2005 15:55:26 +0100
>From: paul brian <paul1brian at gmail.com>
>Subject: Re: [Tutor] find data in html file
>To: Python Tutor <tutor at python.org>
>Message-ID:
>	<bbe9926e0509300755g1e8aaef3r491e9c0d08896825 at mail.gmail.com>
>Content-Type: text/plain; charset=ISO-8859-1
>
>  
>
>>> But to get the data like price,bidders,shipment etc without the official
>>> eBayAPI is hard.
>>> Maybe anyone has a solution made ?
>>    
>>
>
> Ebay specifically change around their HTML codes, tags and formatting
> (in quite a clever way) to stop people doing exactly what you are
> trying to do. I think it changes every month.
>
> Like people say, use the API - You need to become an "ebay developer"
> (signup) and can use your own code or the python-ebay thing for free
> in "the sandbox", but must pay $100 or so to have your code verified
> as "not likey to scrunch our servers" before they give you a key for
> the real world.
>
> Its a bit of a pain, so i just hacked turbo-ebay a while back and made
> do.  Worked quite well really.
>
>
>--
>--------------------------
>Paul Brian
>m. 07875 074 534
>t. 0208 352 1741
>
>
>  
>
I look on it. (BeutifulSoup). At eBay i have now an DevAccount. But if read clearly it is
only the sandbox. Not the real eBay database, what means that i have not access to actual
ongoing auctions. Am i right ? 10.000 is more then enough. 
The other thing is i want to write this under Linux. I use only Linux for Internet surfing etc.
And the eBay-API is an windows-dll. Of cos pyEbay is working under Linux too.

Thanx for the tips. I think "Ich schmei? die Flinte ins Korn und mache alles manuell".

;-)




From shitizb at yahoo.com  Fri Sep 30 23:43:58 2005
From: shitizb at yahoo.com (Shitiz Bansal)
Date: Fri, 30 Sep 2005 14:43:58 -0700 (PDT)
Subject: [Tutor] File mode r+
In-Reply-To: <7e5ba9220509300904h5df2afc3u48d8e53b3f1f7bf3@mail.gmail.com>
Message-ID: <20050930214358.67746.qmail@web53802.mail.yahoo.com>

Hi,
Thats strange. Maybe me being on windows makes the
diference.
Here is the exact IDLE session to clarify:

    
IDLE 1.1      ==== No Subprocess ====
>>> 
>>> file1=open("aa.txt",'r+')
>>> file1.read()
'abcd\nefgh\nijkl\nmnop\nqrst\nuvwx\nyx12\n'
>>> file1.close()
>>> file1=open("aa.txt",'r+')
>>> file1.readline()
'abcd\n'
>>> file1.seek(0,1)
>>> file1.write("1234\b")
>>> file1.close()
>>> file1=open("aa.txt",'r+')
>>> file1.read()
'abcd\n1234\x08\nijkl\nmnop\nqrst\nuvwx\nyx12\n'
>>> 

I find this very very strange.

shitiz.

--- "Michael P. Reilly" <arcege at gmail.com> wrote:

> On 9/27/05, Shitiz Bansal <shitizb at yahoo.com> wrote:
> >
> > Hi,
> > thanx..it works fine. As for the structure of the
> > file...i decided to pad every line with extra
> spaces
> > to make the length of each line constant.That way
> i
> > can replace any line with another without being
> > bothered about the number of characters.
> > However my curiosity got better of me again...:D.
> > i tried to insert a /b character(i had a notion it
> > represents backspace) to see if it would work.
> > It inserted a bit of unicode in the file(Mind you,
> > inserted . Not replaced)
> > original file:
> >
> > 'abcd\nefgh\nijkl\nmnop\nqrst'
> >
> > code::
> > file1=open("aa.txt",'r+')
> > file1.readline()
> > file1.seek(0,1)
> > file1.write("1234\b")
> > file1.close()
> >
> > newfile:
> >
> > 'abcd\n1234\x08\nijkl\nmnop\nqrst'
> >
> > How does that come to pass?
> >
> >
> I didn't get what you got exactly. I got:
> 
> 'abcd\0121234\010ijkl\012mnop\012qrst'
> 
> \012 => \n and
> \010 => \b (\x08)
> 
> I'm not sure why you would have gotten '\x08\n' in
> the same sequence. Maybe
> you should look again. Incidently, when I try to
> print aa.txt, I get:
> abcd
> 123ijkl
> mnop
> qrst
> which is what I would expect.
> -Arcege
> --
> There's so many different worlds,
> So many different suns.
> And we have just one world,
> But we live in different ones.
> 



		
__________________________________ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com

From michaels at rd.bbc.co.uk  Fri Sep 30 23:51:07 2005
From: michaels at rd.bbc.co.uk (Michael Sparks)
Date: Fri, 30 Sep 2005 22:51:07 +0100
Subject: [Tutor] Request for newbies :-)
Message-ID: <200509302251.07797.michaels@rd.bbc.co.uk>

[ This /may/ be very "off-netiquette" for the tutor list. If it is, I
    apologise in advance.  ]
Hi,


One of the aims of the project I'm working on is that it aims to make writing
programs which are inherently (and potentially) highly parallel/concurrent
easy & safe to work with.

We've tested our hypothesis so far with a pre-university trainee who had very 
little programming experience before joining our team (a little bit of visual 
basic, some Access). During his time with us he learnt python during his 
first week, and did learnt our system in his second week.

In the remainder of his time with us he wrote a highly parallel program that 
simulated a digital TV decoder - using a shakespeare script as the data 
source, and doing things like scene detection, and displayed the script & 
characters using pygame (which was handled by other parts of the system.) 
That was a side project (20% style project if you like) whereas his main 
project he implemented during his short time with us was a system for going 
through an mpeg video, and sending snapshots every few seconds to a client 
running on a mobile phone (using python and our system). (An application of 
this could be browsing PVR content on a mobile).

We've since also had a vacation trainee (who's just completed 2 years of his 
course) join us, and in his 6 weeks with us he learnt python, our system, and 
despite no prior networking knowledge implemented a system for joining 
multicast islands together and adding in reliability on top. (A possible 
application of this is "broadcast" of news over the internet)

It's worth noting that the first trainee had very little experience of
programming, networks, mobiles and so on, and that the second had
no real knowledge of python, networks, concurrency, etc.

The approach we took for teaching the system was to get people to implement
a simple version of the core of the system itself. (After getting them to work 
through "How to think like a computer scientist" the week before).

This implementation was guied by a simple tutorial that is formulated as
a series of guided exercises (Standing, Walking, Talking, Conversing), with
a couple of interludes discussing the implications of the results of the
exercise.

As a result this is where I come to a request. If there is anyone out there 
who is willing to do the following tutorial/exercises, could they please do 
so at their own pace and when they've done them please get in touch?

    * http://kamaelia.sourceforge.net/MiniAxon/

If you want a holding hand, I'm often on #kamaelia on irc on freenode. In 
order to do the tutorial you need to understand the following concepts:
   * classes, methods, functions, if/elif/else, while, try..except, for..in..,
     generators (yield), lists, dictionaries, tuples. 

If you're not clear on generators, this might be a good way of understanding
what you can do with them :-)

Thanks in advance to anyone willing to give this a go, and to others for their 
patience regarding this message!

Best Regards,


Michael.
-- 
Michael Sparks, Senior R&D Engineer, Digital Media Group
Michael.Sparks at rd.bbc.co.uk, http://kamaelia.sourceforge.net/
British Broadcasting Corporation, Research and Development
Kingswood Warren, Surrey KT20 6NP

This e-mail may contain personal views which are not the views of the BBC.