Re: [Tutor] Mainframe Technology (was: aBSOLUTE BEGINNER) (OT)

2007-10-18 Thread Carroll, Barry
 -Original Message-
 Date: Thu, 18 Oct 2007 10:53:22 +0100
 From: Alan Gauld [EMAIL PROTECTED]
 Subject: Re: [Tutor] aBSOLUTE BEGINNER
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; format=flowed; charset=iso-8859-1;
   reply-type=original
 
 bhaaluu [EMAIL PROTECTED] wrote
 
  What does that mean... mainframe technology?
 
 I'll take a guess at what it means.
 A true mainframe is usually one of (or a clone of) IBM
 or ICLmainframe hardware running an OS like OS/390. It is
 primarily used for large volume data crunching and the
 applications use text only screens such as 3270 terminals
 running LU6.2 protocol. LU6.2 is somewhat like CGI
 on the web(*). A user is presented with a form which they
 fill in and submit as a job to the mainframe. The job
 executes and presents the results in the shape of
 another form. The coordination between transactions
 is managed by a system such as IBM's CICS.
 
 (*)I've often thought a mainframe wouldmake the ultimate
 web server, but sadly I'll never find out as web apps are
 usually considered far too trivial to waste a mainframe on...
 
 For the programmer or 'operator'(sys admin) the system
 involves a lot of small executables (programs) each
 wrapped up as a job in a script written in JCL
 (Job Control Language) which will define how much
 memory should be allocated, when the job should start,
 when it should terminate (regardless of whether it has
 finished), its schedulling priority, and so on.
 
 Any scripting in the python sense tends to be done
 using REXX, but it still needs to be wrapped in JCL.
 Everything is a job on a mainframe.
 
 Mainframe people tend to regard Unix boxes in the
 same way Unix guys regard PCs - little more than
 grown up toys. Mainframes hardly ever fail, they run
 the world's top businesses. But they are expensive,
 they are used for data centric rathger than user-centric
 applications and so many people working on them
 find them a tad dull, or boring... I know I spent a very
 instructive year wotking on a mainframe project.
 I'm glad I did it, I learned a lot about writing super
 reliable programs , but I don't want to do another
 one - ever!
 
 Now I may be assuming too much but I'm guerssing
 that's what the OP is referring to.
 
  Python is anything but boring! I doubt we can help you!
 
 Well, Python is much more fun than either REXX or JCL so
 learning Python may well bring some light relief.
 
 Alan G.
 
 --

Greetings:

An interesting side note:

IBM's mainframes are now constructed out of massively pararallel arrays
of MPUs.  In other words, all that number crunching is done by hundreds
or thousands of souped up PCs, all connected together and stuffed into a
single box.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] Need Some Help

2007-08-22 Thread Carroll, Barry

 -Original Message-
 Date: Wed, 22 Aug 2007 02:23:25 -0700
 From: chinni [EMAIL PROTECTED]
 Subject: [Tutor] Need Some Help
 To: tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 Hi All,
 
 I am new to python.i need some help about python.i want to learn
python so
 plz guide me from where can i start.so,that i can learn and under
stand
 quickly.
 
 --
 Best Regards,
 M.Srikanth Kumar,
 -- next part --
 An HTML attachment was scrubbed...
 URL:

http://mail.python.org/pipermail/tutor/attachments/20070822/a0813e4e/att
ac
 hment-0001.htm
 
 --
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 
 
 End of Tutor Digest, Vol 42, Issue 74
 *

Welcome to Python.

the best introduction to Python I've seen is this one:

Learning to Program
by Alan Gauld
http://www.freenetpages.co.uk/hp/alan.gauld/

It is freely available online and is clear and easy to understand.  Even
better, the author is a regular contributor on this forum. You can ask
questions here and get answers direct form here.  

There are also a number of other Python experts here, all of whom are
happy to assist as they can.  (I'm not one of the experts.  Just a
moderately good programmer who likes and uses Python regularly,)

HTH


Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

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


Re: [Tutor] Question re Tutor List Etiquette

2007-08-14 Thread Carroll, Barry
 Date: Tue, 14 Aug 2007 12:33:16 -0700
 From: Dick Moores [EMAIL PROTECTED]
 Subject: Re: [Tutor] Question re Tutor List Etiquette
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii; format=flowed
 
 At 11:56 AM 8/14/2007, Kent Johnson wrote:
 Dick Moores wrote:
   When sending a reply to a post, to the list, should we also
address
   the reply to the author of the post to which we are replying?
   (There's gotta be an easier way to say that..) If we do so, then
the
   author gets a duplicate of our reply.
 
 This is configurable for each subscriber. Go to the tutor web page at
 http://mail.python.org/mailman/listinfo/tutor
 
 Enter your subscription email at the bottom where it says, To
 unsubscribe from Tutor, get a password reminder, or change your
 subscription options enter your subscription email address:
 
 Set Avoid duplicate copies of messages? to Yes.
 
 Great!
 
   Ten years ago or so I managed a Majordomo list, and I recall that
it
   was possible for the list manager to configure the list to include
a
   Reply-To header. If this would be possible for the admins to do
   with Tutor -- to include a Reply-To: tutor@python.org header in
the
   posts sent out by the list, it would enable us to address a reply
   only to the list by hitting the Reply button.
 
 Surely you have been reading the list long enough to know that this
 comes up every three months as a topic!
 
 No, you can't assume that because I'm a long-term subscriber that I
 have always faithfully read the list. If I had, I'd be much better at
 Python than I am!
 
   It's not going to change. I'm
 not going to discuss it (and I hope no one else will either). Search
the
 archives if you want to see previous discussions.
 
 Well, I don't see that it's all that bad that I brought it up again.
 The newcomers undoubtedly will benefit from your advice, as I did. Or
 does the new welcome message mention how to avoid duplicate copies of
 messages? If not, it should.
 
 Dick
 
 
 
 --
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 
 
 End of Tutor Digest, Vol 42, Issue 50
 *

Greetings:

I receive these messages as a digest, not individual e-mails.  So for me
the list is the sender.  To reply to an author, I have to Fwd: and and
copy the address manually.  Since I almost never need to do that,  it
isn't a problem.  Also, it keeps my my inbox uncluttered: half a dozen
e-mails a day instead of scores.  On the other hand, the compilation
delay means that by the time I see a new question, it's nearly always
been answered three times already.  So y'all seldom get the benefit of
my superior Pythonic advice.  =8^)

FWIW,  it's nice to see this topic addressed for once without the usual
accompanying flamage.  I agree with Dick that this info should be added
to the FAQ.  Keep the frustration level down by providing the options up
front.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed




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


Re: [Tutor] Design Pattern + Wxpython

2007-08-02 Thread Carroll, Barry
 -Original Message-
 Message: 4
 Date: Wed, 1 Aug 2007 19:01:36 +0400
 From: Pradeep Kumar [EMAIL PROTECTED]
 Subject: [Tutor] Design Pattern + Wxpython
 To: tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 I am new to this and wants to do a project for Autoparts industry
 (Trading)
 with backend SQL Server 2000.
 
 1. Which Design Pattern is suitable for me.
 
 Pradeep~~
 -- next part --
 An HTML attachment was scrubbed...
 URL:

http://mail.python.org/pipermail/tutor/attachments/20070801/4c91c9a0/att
ac
 hment-0001.html
 
 --
 
 Message: 5
 Date: Wed, 01 Aug 2007 21:03:08 -0400
 From: Kent Johnson [EMAIL PROTECTED]
 Subject: Re: [Tutor] Design Pattern + Wxpython
 To: Pradeep Kumar [EMAIL PROTECTED]
 Cc: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1; format=flowed
 
 Pradeep Kumar wrote:
  I am new to this and wants to do a project for Autoparts industry
  (Trading) with backend SQL Server 2000.
 
  1. Which Design Pattern is suitable for me.
 
 This one clearly applies:
 http://catb.org/~esr/faqs/smart-questions.html
 
 Kent
 
 
 --
Ouch!

True and appropriate, but ouch all the same. ;-)

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] Invoking Python from Vim

2007-06-08 Thread Carroll, Barry

 -Original Message-
 Date: Fri, 8 Jun 2007 00:19:39 +0100
 From: Alan Gauld [EMAIL PROTECTED]
 Subject: Re: [Tutor] Invoking Python from Vim
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; format=flowed; charset=iso-8859-1;
   reply-type=original
 
 
 Matt Smith [EMAIL PROTECTED] wrote
 
  Do any Vim users have a better way of running a Python program while
  it
  is being edited in Vim?
 
 My personal preference is to have 3 windows open:
 
 1) gvim for editing the files
 2) a console for running the files using command recall to do so
 3) a console running a python shell prompt
 (actually nowadays I'm using a a PyCrust shell)
 
 And I alt-tab between the windows.
 
 This way I can experiment in PyCrust, copy the resultant experiments
 into gvim and run the program, keeping the error messages etc
 visible without sacrificing gvim window space.
 
 The downside is the alt-tab required to switch to the right window
 and an up-arrow press to recall the python command to re-execute
 each time.
 
 Alan G.
 
My setup is similar to Alan's:

* Windows XP 
* Python Enthought Edition
* Iron Python shell for experimenting/prototyping
* GviM for editing
* Standard Command prompt window for execution

It isn't a sophisticated, integrated solution, but it works quite
well.  Sometimes the simple ideas are the best.  Remember this famous
exchange:

 Devil:   Take the easy path. I brought you a suite of applications

   that all work together.
 Dilbert: That's unnatural!!!  Be gone!!!

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed
 

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


Re: [Tutor] leave tutorial

2007-06-01 Thread Carroll, Barry

 -Original Message-
 Date: Wed, 30 May 2007 14:50:25 -0500
 From: Grant Hagstrom [EMAIL PROTECTED]
 Subject: Re: [Tutor] leave tutorial
 To: Kriti Satija [EMAIL PROTECTED]
 Cc: Tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 Nobody leaves the tutorial.
 
 http://mail.python.org/mailman/listinfo/tutor
 (at the bottom of the page)
 
 On 5/30/07, Kriti Satija [EMAIL PROTECTED] wrote:
 
  i want to leave the tutorial
snip

'relax,' said the night man,
'We are programmed to receive.
 You can checkout any time you like,
 But you can never leave!'
(Hotel California: Don Henley, Glenn Frey and Don Felder; 1977)

Off-topic, I know, but I couldn't resist.  Sorry.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

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


Re: [Tutor] range()-like function for dealing with floats...?

2007-03-30 Thread Carroll, Barry
 -Original Message-
 Date: Fri, 30 Mar 2007 14:47:26 +0530
 From: Joydeep Mitra [EMAIL PROTECTED]
 Subject: [Tutor] range()-like function for dealing with floats...?
 To: tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 Hi all,
 I need to generate a sequence of real numbers that are evenly spaced.
I
 have
 used loops for this purpose until now, but it gets kinna messy when
you
 gotta do it a number of times in a program.
 The range function, as per my knowledge, accepts parameters and return
 values only as integers.
 Is there a function in python, which performs the task of the range()
 function with floats?
 
 Joy
Joy:

Try entering python range float at your personal favorite search
engine.  I tried it on Google.  Here is the first entry returned:

ASPN : Python Cookbook : frange(), a range function with float
...
Sadly missing in the Python standard library, this function
allows 
to use ranges, just as the built-in function range(), but with 
float arguments. ...
aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66472 
- 32k - Cached - Similar pages 

There were lots of others.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] range()-like function for dealing with floats...?

2007-03-30 Thread Carroll, Barry
 -Original Message-
 Date: Fri, 30 Mar 2007 19:28:51 +0200
 From: Andreas Kostyrka [EMAIL PROTECTED]
 Subject: Re: [Tutor] range()-like function for dealing with floats...?
 To: Carroll, Barry [EMAIL PROTECTED]
 Cc: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii
 
 * Carroll, Barry [EMAIL PROTECTED] [070330 19:15]:
  Try entering python range float at your personal favorite search
  engine.  I tried it on Google.  Here is the first entry returned:
 
  ASPN : Python Cookbook : frange(), a range function with float
  ...
  Sadly missing in the Python standard library, this function
  allows
  to use ranges, just as the built-in function range(), but with
  float arguments. ...
  aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66472
  - 32k - Cached - Similar pages
 
  There were lots of others.
 
 Just don't forget that floats are not evenly spaced. The hole between
 possible floats gets bigger the more you move away from zero.
 
 On my IA32 Linux laptop I get:
 
  (1e+16) + 1 == (1e+16)
 True
  (1e+16) + 10 == (1e+16)
 False
 
 So a frange(1e+16, (1e+16) + 1000, 1) won't work, or at best will
 result something else than what you thought it would.
 
 That's probably the reason why frange is not part of the standard
 library: It's not possible to define it sensible for all float ranges,
 and floats have many properties that make them fiendish. Typically,
 programming courses just ignore the problematic aspects (at best one
 learns that floats should not be used to represent money), one usually
 has to take a course on Numerics to get the details.
 
 Andreas
 
Andreas is right, of course.  In fact, the URL I referenced above
includes a discussion of the contributor's function and ways of
mitigating (NOT eliminating) the round-off problem.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] Making table

2007-03-21 Thread Carroll, Barry
 -Original Message-
 Date: Tue, 20 Mar 2007 22:53:15 +0100
 From: J?nos Juh?sz [EMAIL PROTECTED]
 Subject: Re: [Tutor] Making table
 To: tutor@python.org
 Message-ID:
   OF6CDC76A3.A1E29388-ONC12572A4.0077642D-
 [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-2
 
 Dear Barry,
 
 Using a formatting string of %10.4f, these would be rendered as:
 
'  253.'
'   77.6000
'9.0300'
'0.0210'
 
 This formatting gives the impression that all values but the last
are
 more precise than they truly are.  A scientist or statistician would
 prefer to see something like this:
 
'254.'
' 77.6   '
'  9.03  '
'  0.0210'
 
 Does numpy or some other math package have that capability?
 
 You can use advanced regexp, called lookaround, lookbehind for this
 purpose.
 
 ###
 
 import re
 
 l = (253., 77.6, 9.03, .0210, 1000, 100.1230)
 ending_zero = re.compile('0(?=0*$)') # zero followed with only zeros
 
 for f in l:
 print re.sub(ending_zero, ' ', ('%10.4f' % f))
 
 ###
 
 
 
 
 Yours sincerely,
 __
 J?nos Juh?sz

Thanks, J?nos.  Your solution works in almost all cases.  It breaks down
when one or more trailing zeros are significant: 0.0210 should print
unchanged, since the final 0 is significant.  

Still this is a big step forward.  It shouldn't be too hard to add the
additional logic.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] Making table

2007-03-19 Thread Carroll, Barry
 -Original Message-
 Date: Mon, 19 Mar 2007 11:53:06 -0400
 From: Kent Johnson [EMAIL PROTECTED]
 Subject: Re: [Tutor] Making table
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1; format=flowed
 
 Dave Kuhlman wrote:
  Try ljust and rjust.  They are string functions/methods and are
  described here: http://docs.python.org/lib/string-methods.html
 
  Something like the following might work for you:
 
  In [1]: value = 3.45678
  In [2]: (%0.3f % value).rjust(10)
  Out[2]: ' 3.457'
 
 Most string formatting conversions allow you to specify a width
 directly. For example,
 In [61]: value = 3.45678
 In [63]: %10.3f % value
 Out[63]: ' 3.457'
 
 Kent
 
What if one wished to align the values in each column at the decimal
point?  Is there a simple means to do this in Python, or would one need
to write a new function?

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] Making table

2007-03-19 Thread Carroll, Barry
 -Original Message-
 From: Kent Johnson [mailto:[EMAIL PROTECTED]
 Sent: Monday, March 19, 2007 12:59 PM
 To: Carroll, Barry
 Cc: tutor@python.org
 Subject: Re: [Tutor] Making table
 
 Carroll, Barry wrote:
  -Original Message-
  Date: Mon, 19 Mar 2007 11:53:06 -0400
  From: Kent Johnson [EMAIL PROTECTED]
 
  Most string formatting conversions allow you to specify a width
  directly. For example,
  In [61]: value = 3.45678
  In [63]: %10.3f % value
  Out[63]: ' 3.457'
 
  Kent
 
  What if one wished to align the values in each column at the decimal
  point?  Is there a simple means to do this in Python, or would one
need
  to write a new function?
 
 If you specify the number of digits after the decimal point, that
number
 of digits will always be given, so columns will line up:
 In [86]: '%10.3f' % 1.2
 Out[86]: ' 1.200'
 In [87]: '%10.3f' % 1.23456
 Out[87]: ' 1.235'
 
 If you want something fancier I think you will have to do it yourself.
 
 Kent
Kent:

Thanks for your response.  That method is certainly good enough for
general use.  What about a case where the user needs to keep track of
significant digits? As an example, assume that the following values
(pulled arbitrarily from my head, I admit) are accurate to three
significant digits:

253.
77.6
9.03
.0210

Using a formatting string of %10.4f, these would be rendered as:

'  253.'
'   77.6000
'9.0300'
'0.0210'

This formatting gives the impression that all values but the last are
more precise than they truly are.  A scientist or statistician would
prefer to see something like this:

'254.'
' 77.6   '
'  9.03  '
'  0.0210'

Does numpy or some other math package have that capability?

Thanks again.
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] forth

2007-03-02 Thread Carroll, Barry
 -Original Message-
 Date: Fri, 02 Mar 2007 14:54:04 -0800
 From: Bob Gailer [EMAIL PROTECTED]
 Subject: Re: [Tutor] forth
 To: Hilton Garcia Fernandes [EMAIL PROTECTED]
 Cc: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1; format=flowed
 
 Hilton Garcia Fernandes wrote:
  in python:
 
  print Hello world!
 
  21 bytes.
 
 True, but the forth program is (as I read it) more equivalent to:
 
 def helloWorld():
 print Hello World!
 
 although is says 'resulting in a [sic] executable. Not sure what that
 means, unless the obvious - an .exe file which when run displays
Hello
 World!. In that case 263 bytes is remarkable.
  all the best,
  hilton
 
  Em Sexta 02 Mar?o 2007 16:48, Kirk Bailey escreveu:
 
  Hello world
 
  : helloWorld .Hello World!;
 
  that's it.
 
  HelloWorld is now part of the language. Now if your language
instance
  lets you compile it down, it will include all functions to create
that
  function, and leave all others out, resulting in a executable. Mine
 came
  in at 263 bytes.
 
  Microsoft C came in at 47 K.
 
  to add 2+ 2:
 
  2
  2
  +
  .
 
  As it uses Reverse Polish Notation and is stack oriented, doing
math is
  rather intresting, different, and novel. It's a novel language.
VERY
  good for controllers giving you maximum program in a small device
such
  as your usuall PIC chip. Really SHINES in this venue.
 
  Here's a link to wikipedia:
  http://en.wikipedia.org/wiki/Forth_(programming_language)
 
  But this is python list, so enough of comparitive languages.
 
 
 
 --
 Bob Gailer
 510-978-4454

Okay.  Here's my Hello World script.

CONSOLE
J:\ dir helloworld.py
 Volume in drive J is EUGSRV340
 Volume Serial Number is 0435-C18F

 Directory of J:\

03/02/2007  03:20 PM43 helloworld.py
   1 File(s) 43 bytes
   0 Dir(s)  23,540,051,968 bytes free

J:\ type helloworld.py
#!/usr/bin/python2.3
print Hello World

J:\ helloworld.py
Hello World

J:\ 
/CONSOLE

This script will run on a Windows XP box with the Python interpreter
installed.  At 43 bytes, it's not too bad.  Running on a box without
Python is a different story.  I can make a .exe file using py2exe:

CONSOLE
J:\ type setup.py
# setup.py
from distutils.core import setup
import py2exe

setup(
zipfile=None, # append zip-archive to the executable.
options = {py2exe: {compressed: 1,
  optimize: 2,
  ascii: 1,   # to make a smaller executable,
# don't include the encodings
  packages: [xml.sax.drivers,
   xml.sax.drivers2,],
 }
  },
console=[helloworld.py]
)


J:\ python setup.py py2exe

py2exe output snipped

J:\ cd dist

J:\dist dir *.exe
 Volume in drive J is EUGSRV340
 Volume Serial Number is 0435-C18F

 Directory of J:\dist

03/02/2007  03:39 PM   493,826 helloworld.exe
05/11/2005  07:03 PM16,384 w9xpopen.exe
   2 File(s)510,210 bytes
   0 Dir(s)  23,504,711,680 bytes free

J:\dist helloworld
Hello World

J:\dist 
/CONSOLE

I'm a novice at py2exe.  There are probably ways to tweak the setup file
to make the .exe file smaller.  

I wonder if Kirk's 263 byte Forth program is self-contained?

Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] python problem

2007-03-01 Thread Carroll, Barry
 -Original Message-
 Date: Thu, 1 Mar 2007 10:54:36 -0500
 From: Kent Johnson [EMAIL PROTECTED]
 Subject: Re: [Tutor] python problem
 To: Purcell,  Brittany Nicole [EMAIL PROTECTED],
   tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1
 
 
  From: Purcell,  Brittany Nicole [EMAIL PROTECTED]
  Date: 2007/03/01 Thu AM 01:40:45 EST
  To: tutor@python.org
  Subject: [Tutor] python problem
 
  I have no idea how to even begin to program something like this and
  what I need to do is:
  To complete the skeleton by replacing ellipsis (in this case
vertical)
  with a  solution. The number of dot indicates the number of lines of
  the solution, and fill in the following dots:
 
 This looks like homework to me. We won't do your homework for you. We
will
 answer questions and help you when you have trouble but you have to
try.
 
 What have you learned so far in class? How might you apply that to
these
 exercises?
 
 Kent
 
snip
 
Hello, Brittany.

I agree with Kent, et al: I'm not doing to do the work for you.  That
doesn't do you any good and besides, we all have our own work to do.
But, just saying, go do it yourself isn't very good tutoring, IMHO.
So, here are a couple of hints, and a method (algorithm for you
theoretical CS types) that will help you get better results from the
folks on this mailing list.

1. Consider the following (here come the hints):
* All of these exercises deal with string manipulation.
* In Python, a string is a type of sequence.
* Pieces of a Python sequence can be accessed using
indices 
  (singular: index) and slices.
2. Read what your text (and class notes, if you have them) has
to 
   say on these topics.  
3. Fire up your Python interpreter and try out some of the
examples
   you found in 2.  
4. Make up some examples of your own and try them out.
5. Try solving one or more of your exercises using what you've
learned
   from 1. - 4.  
6. If your solution doesn't work, send another e-mail here,
including 
   your code and any output and error messages you get, asking
for 
   suggestions, explanations, etc.  

This really is a great place to get help, once you've made an honest
effort to help yourself.  

Good luck.

Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] Replying to the tutor-list

2007-02-16 Thread Carroll, Barry
Greetings:

I just thought I'd throw my own hat into the ring.  I'm trying out my
new, asbestos-free, flame-retardant underwear.  ;^)

 -Original Message-
 Date: Fri, 16 Feb 2007 08:14:29 -0500
 From: Michael P. Reilly [EMAIL PROTECTED]
 Subject: Re: [Tutor] Replying to the tutor-list
 To: ALAN GAULD [EMAIL PROTECTED]
 Cc: Tutor tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 On 2/16/07, ALAN GAULD [EMAIL PROTECTED] wrote:
 
   However, the standard behavior at the time was that
   replies went back to the mailing list, not to the original sender.
 
  But the mailing list was the original sender so it was all
wonderfully
  consistent. Reply  goes to sender only, which happens
  to be the list server...
 
  Ah, the good ol' days :-)
 
  Alan g.
 
  Alan,
 
 The issue is not what the mailing list does, but what the user expects
and
 should do.  

I agree.  However, it seems to me that the expectation in this case is
divided into two contradictory positions.  (The division seems pretty
even to me, but that's not necessarily a critical point.)

 Listserv was the first mailing list system from 23 years ago.
 The users expected, as standard behavior, that replies would go to the
 mailing list, not to the original sender.  You had made a claim that
more
 than 10 years ago (when listserv was still in use) that the standard
 behavior was that mailing lists was that users would reply to the
original
 sender.  I'm just offering up one, very well-known example to refute
that.

Again, I agree.  That is an excellent counter-example.  To me, it
demonstrates that this division of expectation existed from the
beginning of the technology.  
 
 Myself, I'm not a person who cares how the mailing list goes.  I'll
adapt.
 But it does irk me when standards are applied because of
 misunderstandings
 of applications.  For example, the usual convention is that people
attach
 their comments below the respondent's.  At my work, they have tried to
 convince me that the standard is to put it above simply because
Outlook
 does that.

Don't get me started on that.  I just got out of a minor fire fight on
another forum over that one. :^(

 When making arguments, please make the arguments on a technical basis,
not
 on this was how it has been done in the past.  

I would agree with this, too, if this were a technical issue.  But it's
not.  Read on.  

 If that was the case, then
 all the stuff you get in your mailbox isn't spam since spam related
only
 to cross-posting on newsgroups (anyone remember the Spam Wars?).
However,
 the general collective has decided to expand the standard definition.
 
 Times change, standards can evolve. Sometimes not for the better.
Make an
 argument for keeping the standards how they should be technically,
not
 historically.
 

While I agree that appeals to historical authority aren't very helpful
in cases like this, assertions of technical superiority are equally
unproductive.  Again, IMHO, this not a technical issue.  Ring vs. bus
vs. star network topology is a technical issue.  This is an issue of
convenience, which is intensely personal.  The rightness or wrongness of
either position is subjective (purely so, I believe) and technical
discussion does not clarify.  That's why discussions like this so often
turn into religious wars (as this one nearly did a few posts back).  

There is a technical issue that relates, however.  Some posters have
touched on it.  Modern mail and news software should be flexible enough
to accommodate the user's preference in this regard.  A few are,
apparently.  Most are not.  Why not?  What should be done about it?  Who
has a Python implementation that makes the default Reply to: behavior
configurable?  Which is the most flexible?  How can it be improved?
These are questions that benefit from technical discussion.  I'd like to
see more posts on these topics, and less on whose personal preference is
correct.

-Arcege
 --
 There's so many different worlds,
 So many different suns.
 And we have just one world,
 But we live in different ones.
 --
 

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

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


[Tutor] Picking Nits in Learning to Program

2007-02-16 Thread Carroll, Barry
Alan:

This is arguably a minor detail, and not directly related to Python but, hey, 
I'm a programmer.  Minor details are my stock in trade.  So here goes.  

In Learning to Program, look at The Raw Materials, Real Numbers.  The 
first sentence, These are fractions is technically incorrect, but incomplete. 
 While it's true that fractions (i.e. rational numbers) are real numbers, there 
are far more real numbers that cannot be expressed as a ratio of two integers.  
Hence the name Irrational Numbers.  The square root of two is the prime 
example. (Sorry, can't do the math symbol in Plain Text.)  

You might say something like, Fractions are examples of real numbers.  

I know, I know.  Strictly speaking, integers are real numbers, too.  But let's 
not quibble. 8^)

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed


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


[Tutor] Property Question (Was: RE: Overloading assignment operator)

2007-02-08 Thread Carroll, Barry
 -Original Message-
 From: Tony Cappellini [mailto:[EMAIL PROTECTED]
 Sent: Thursday, February 08, 2007 5:41 PM
 To: Carroll, Barry
 Subject: re:Overloading assignment operator
 
 Hello Barry
 
 I'm trying to understand you post
 
 my question is, should this line
 
 result = property(get_result, set_result)
 
 actually be
 
 self.result = property(get_result, set_result)
 
 if result is an instance variable?
 
 Or did you intend it to be a class variable?
 
 Properties always confused me.
 
 
 thanks
 
 Overloading assignment operator
 Carroll, Barry Barry.Carroll at psc.com
 Wed Jan 24 00:32:34 CET 2007
 
 Hello, Achim,
 
 * ...here is where
 * properties become useful.  you can create a getter, setter, and even
a
 * deleter and doc string if you want. here's how you use it... add the
 * following to your class:
 
 * def get_result(self):
 * return self.__result
 *
 * def set_result (self, expression):
 * self.__result = expression
 *
 * result = property(get_result, set_ result, doc='result of
operations')
 *
 * -
 *
 
 I have tested this using the admittedly simple-minded code snipped
 below.
 
 
 @BCARROLL[Python]|3 class Aclass:
  |. def __init__(self):
  |. __result = None
  |. def get_result(self):
  |. return self.__result
  |. def set_result (self, result):
  |. self.__result = result
  |. result = property(get_result, set_result,
 doc='result of expression')
  |.
 @BCARROLL[Python]|5 a = Aclass()
 @BCARROLL[Python]|7 a.result = 2*3
 @BCARROLL[Python]|8 a.result
  8 6
 @BCARROLL[Python]|9 a.result = 25.0 * 5.25
 @BCARROLL[Python]|10 a.result
  10 131.25
 @BCARROLL[Python]|11
Hello, Tony:

First off, it's always a good idea to respond to the mailing list
instead of directly to an individual.  Everyone benefits from the
information instead of just one person.  Besides, if I make a mistake
(something I fo depressingly often) someone else on the list can correct
it so you get the right info.

Anyway, to your question: result vs self.result.  Look at the
interpreter session snippet above.  The assignment to result is inside
the class definition, so it is an attribute of Aclass.  At this point
Aclass.result is indeed a class variable.  Or, perhaps more correctly,
a class property.  

However, when a is set to Aclass(), an instance of Aclass is created
and given the name a.  a.result is therefore an instance variable.
I never use the class variable Aclass.result.  

Does that help any?

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] converting tab-delimited text files to csv

2007-01-29 Thread Carroll, Barry
 -Original Message-
 Date: Fri, 26 Jan 2007 22:40:24 -0500
 From: Kent Johnson [EMAIL PROTECTED]
 Subject: Re: [Tutor] converting tab-delimited text files to csv
 To: Luke Paireepinart [EMAIL PROTECTED]
 Cc: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=windows-1252; format=flowed
 
 Luke Paireepinart wrote:
  csv is comma-separated values, right?
  you should be able to just do a string replace of tabs - commas on
each
  line in the new file...
  or is the csv format more complicated than that?
 
 Yes, it is more complicated than that because the data itself may
 contain commas.
 
 Kent


Greetings:

It's useful to recall that the Python CSV module was written to handle
Microsoft's implementation of the format.  According to Wikipedia

(http://en.wikipedia.org/wiki/Comma-separated_values)

there is no formal specification. The article includes these two links:

http://tools.ietf.org/html/rfc4180
http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm

Here's another link that I've found useful:

http://object-craft.com.au/projects/csv/

HTH.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] Telepathic Python (was: Division doesn't work)

2007-01-18 Thread Carroll, Barry
 -Original Message-
 Date: Thu, 18 Jan 2007 14:16:07 +0100
 From: Zara [EMAIL PROTECTED]
 Subject: Re: [Tutor] Division doesn't work
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii
 
 On Thu, 18 Jan 2007 13:09:48 +0100, Geoframer [EMAIL PROTECTED]
 wrote:
 
 You assign s as an integer... it should be a float to get the right
 result...
 ...
 
 
 Yes, that is the wordt defect of Python: its inability to read
 programmer mind and detect the rteal programmer intentions.
 
 
 Zara
Hi, Zara.

All programming languages seem to share that drawback, as do all
computing machines.  They always do exactly what we tell them to do,
instead of what we want to do.  Drat!

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] python dictionaries

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

http://mail.python.org/pipermail/tutor/attachments/20070106/df0a537b/att
ac
 hment.htm

Think of it this way:

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

How can you use your dictionary to emulate that?

Good luck.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] Accessing the name of a Function

2006-12-13 Thread Carroll, Barry
Greetings:

Andreas and Kent helped me solve my problem.  We are writing a keyword
driven framework for embedded SW testing.  The framework supports scores
of keywords, built-in and user-defined.  We are still writing the
framework, so none of the functions for manipulating the target device
has been written, although the keywords are defined.  As a result, he
framework's output log is full of keyword not found errors, which mask
real errors in framework operation.  

To get rid of these 'pseudo errors' I wanted a stub handler that would
output an information message, with the name of the function and its
arguments.  Using the sys._getframe method and the inspect.getargvalues
methods, I was able to write a single routine that will handle any
function signature.  Here is the result:

A sample keyword triggered function:
##
import sys
from actioncommon import handlestub

def doaction_dbopen(ctrl, proc, schemafile, configfile,
dataset=default):
'''A, Config, DB, Open, schemafile, configfile, dataset=default

Open the testbench data base. 
Where:
schemafile (str) - the xml schema file for the product to be
tested; 
configfile (str) - the configuration file for the product to be 
   tested; 
dataset(str) - optional configuration data set to activate.

   defaults to default
Example:
A, Config, DB, Open, master.xml, test.tex, current
'''
# TODO: replace stub handler with action logic.
handlestub(ctrl, proc, sys._getframe())
return True
##

The stub handler:
##
from inspect import getargvalues

def handlestub(ctrl, proc, thestubframe):
Identifies actions that are defined but not yet implemented.

themsg = Execuiting %s (implementation pending) with arguments:  %
\
 thestubframe.f_code.co_name
(theargnames, trash1, trash2,
thelocalsdict)=getargvalues(thestubframe)
# The first two arguments are internal to the application: do not 
  display.
if len(theargnames) = 2:
themsg += None
else:
for theargname in theargnames[2:]:
themsg += %s=%s   % (theargname,
thelocalsdict[theargname])ctrl.log.logaction(ctrl.log.INFO, themsg)
##

The resulting log output:
##
INFO Execuiting doaction_dbopen (implementation pending) with
arguments: schemafile=USBIBM.XML  configfile=USBIBM.TEX
dataset=usbimbstart
##

Thanks to Andreas and Kent for their help
 
Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


 -Original Message-
 From: Kent Johnson [mailto:[EMAIL PROTECTED]
 Sent: Wednesday, December 13, 2006 2:55 AM
 To: Carroll, Barry
 Cc: tutor@python.org
 Subject: Re: [Tutor] Accessing the name of a Function
 
 Carroll, Barry wrote:
  Andreas:
 
  You're right, that is kind of messy and somewhat limited.  In the
  present case, however, it is the function's defined name that I
want, so
  this would work okay.
 
  I'm guessing that there is a way to determine the number and names
of
  the arguments to the function as well.  I'll go look at the sys
module
  and see what I can find.
 
 Look at the inspect module, specifically getargspec() and
getargvalues().
 
 Kent
 

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


Re: [Tutor] Accessing the name of a Function

2006-12-13 Thread Carroll, Barry
 -Original Message-
 From: Kent Johnson [mailto:[EMAIL PROTECTED]
 Sent: Wednesday, December 13, 2006 3:42 PM
 To: Carroll, Barry
 Cc: tutor@python.org
 Subject: Re: [Tutor] Accessing the name of a Function
 
skip
 
 You could also do this very simply and cleanly with a decorator,
 assuming Python = 2.4. This example is pretty much what you want:
 http://wiki.python.org/moin/PythonDecoratorLibrary#head-
 d4ce77c6d6e75aad25baf982f6fec0ff4b3653f4
 
 In your approach, you can call _getframe() in handlestub, see for
example
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062
 
 Kent
 
 
skip


Right again, Kent. Due to the constraints of the target test system,
this application has to stay at Python 2.3, at least for now.  But using
_getframe(1) to get the caller's stack frame does simplify the stub
handler call considerably, from 

handlestub(ctrl, proc, sys._getframe())
to
handlestub()

The handler now looks like this:

##
def handlestub():
Identifies actions that are defined but not yet implemented.

# Get the calling function's stack frame.  
thestubframe = sys._getframe(1)
themsg = Execuiting %s (implementation pending) with arguments:  %
\
 thestubframe.f_code.co_name
(theargnames, trash1, trash2, thelocalsdict) = \
 getargvalues(thestubframe)
# The first two arguments are internal to the application: do not 
#display.
if len(theargnames) = 2:
themsg += None
else:
for theargname in theargnames[2:]:
themsg += %s=%s   % (theargname,
thelocalsdict[theargname])
ctrl = thelocalsdict[ctrl]
ctrl.log.logaction(ctrl.log.INFO, themsg)
##

Thanks again.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


[Tutor] Accessing the name of a Function

2006-12-12 Thread Carroll, Barry
Greetings:

 

Is it possible, from inside a stand-alone function (not a member of a
class), to access the string representation of the function's name?  If
so, how?

 

Regards,

 

Barry

[EMAIL PROTECTED]

541-302-1107



We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

 

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


Re: [Tutor] Accessing the name of a Function

2006-12-12 Thread Carroll, Barry
Andreas:

You're right, that is kind of messy and somewhat limited.  In the
present case, however, it is the function's defined name that I want, so
this would work okay.  

I'm guessing that there is a way to determine the number and names of
the arguments to the function as well.  I'll go look at the sys module
and see what I can find.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

 -Original Message-
 From: Andreas Kostyrka [mailto:[EMAIL PROTECTED]
 Sent: Tuesday, December 12, 2006 4:05 PM
 To: Carroll, Barry
 Cc: tutor@python.org
 Subject: Re: [Tutor] Accessing the name of a Function
 
 * Carroll, Barry [EMAIL PROTECTED] [061212 23:54]:
 Greetings:
 
 
 
 Is it possible, from inside a stand-alone function (not a member
of a
 class), to access the string representation of the function's
name?
 If
 so, how?
 Probably, but it's dirty like help (sys._getframe would be your ticket
 into this), but you ask on the tutor mailing list, so you'll probably
 don't want this:
 
 def func(x):
  return 2 * x
 
 gunc = func
 del func
 
 print gunc(10)
 
 The best you can hope to derive is func here, but as you can see,
 functions are only objects that can be assigned freely.
 
 (Spoiler: it's sys._getframe(0).f_code.co_name, but it will always
 only know the name the function was defined under. No way to know how
 it was named when it was called. So it's not worth much.)
 
 Andreas
 
 
 
 Regards,
 
 
 
 Barry
 
 [EMAIL PROTECTED]
 
 541-302-1107
 
 
 
 We who cut mere stones must always be envisioning cathedrals.
 
 --Quarry worker's creed
 
 
 
  References
 
 Visible links
 1. mailto:[EMAIL PROTECTED]
 
  ___
  Tutor maillist  -  Tutor@python.org
  http://mail.python.org/mailman/listinfo/tutor
 


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


Re: [Tutor] How to generate permutations of a given string

2006-11-28 Thread Carroll, Barry
Dick, et al:

 -Original Message-
 Date: Tue, 28 Nov 2006 12:57:51 -0800
 From: Dick Moores [EMAIL PROTECTED]
 Subject: Re: [Tutor] How to generate permutations of a given string
 To: Python Tutor List tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii; format=flowed
 
 At 02:49 PM 11/27/2006, John Fouhy wrote:
 On 28/11/06, Carroll, Barry [EMAIL PROTECTED] wrote:
   I'm not sure these qualify as simple, but they work.  This was
one
 of
   my very first projects in Python, so it may be more complicated
than
   necessary.
 
 This is an alternative approach:
 http://mail.python.org/pipermail/tutor/2005-May/038059.html
 
 However, this is not what someone looking for an anagram algorithm
 would find useful, it seems to me.
 
 Barry Carroll offering does the job, if the last line is revised as
 shown below:
 
 def permute(word):
  
  By Barry Carrol [EMAIL PROTECTED]
  on Tutor list, revised (last line) by me.
  
  retList=[]
  if len(word) == 1:
  # There is only one possible permutation
  retList.append(word)
  else:
  # Return a list of all permutations using all
characters
  for pos in range(len(word)):
  # Get the permutations of the rest of the
word
 
 permuteList=permute(word[0:pos]+word[pos+1:len(word)])
  # Now, tack the first char onto each word in
the
 list
  # and add it to the output
  for item in permuteList:
  retList.append(word[pos]+item)
  #return retList
  return list(set(retList)) # make elements of retList unique
 
 (The line in the code in Barry's post,
 permuteList=permute2(word[0:pos]+word[pos+1:len(word)]), was
 corrected to permuteList=permute(word[0:pos]+word[pos+1:len(word)])
 in an email from him to me.)
 (i.e., permute2 changed to permute)
 
 Dick Moores
In the intrest of reusability, I would recommend leaving permute as it
is and calling it from another function:

#
 def permuteset(word):
 return list(set(permute(word)))

 permute(121)
 ['121', '112', '211', '211', '112', '121']

 permuteset(121)
 ['121', '211', '112']
#

If you're sure you will never want to use the permute function in any
other way, then it doesn't matter, of course.  Otherwise, it's nice to
have the original function intact, in case you ever want a list of all
the combinations that ARE duplicates, for example ;*)

FWIW.

Regards,

Barry

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


Re: [Tutor] How to generate permutations of a given string

2006-11-27 Thread Carroll, Barry
Hello, Asrarahmed

 -Original Message-
 Date: Mon, 27 Nov 2006 12:06:54 +
 From: Asrarahmed Kadri [EMAIL PROTECTED]
 Subject: [Tutor] How to generate permutations of a given string
 To: tutor-python tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 Hello folks,
 
 
 Can someone help me with a simple algorithm to generate permutations
of a
 given string:
 
 Input string: 'abc'
 
 Output:---  ['abc','acb','bac','bca','cab','cba']
 
 Thanks.
 Regards,
 Asrarahmed Kadri
 -
 To HIM you shall return.

I'm not sure these qualify as simple, but they work.  This was one of
my very first projects in Python, so it may be more complicated than
necessary.  

##
def permute (word):

Accepts a string. 
Returns a list of all permutations of the string using all
characters.  

retList=[]
if len(word) == 1:
# There is only one possible permutation
retList.append(word)
else:
# Return a list of all permutations using all characters
for pos in range(len(word)):
# Get the permutations of the rest of the word 
permuteList=permute2(word[0:pos]+word[pos+1:len(word)])
# Now, tack the first char onto each word in the list
# and add it to the output
for item in permuteList:
retList.append(word[pos]+item)
return retList
##

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] Ruby Code Blocks vs. Python Lambdas

2006-11-07 Thread Carroll, Barry
 -Original Message-
 Date: Tue, 07 Nov 2006 12:20:16 +0100
 From: Andreas Kostyrka [EMAIL PROTECTED]
 Subject: Re: [Tutor] Ruby Code Blocks vs. Python Lambdas
 To: Alan Gauld [EMAIL PROTECTED]
 Cc: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii
 
 Am Dienstag, den 07.11.2006, 09:56 + schrieb Alan Gauld:
  Carroll, Barry [EMAIL PROTECTED] wrote
 
   Thank you for this post.  I was in a discussion of Ruby vs. Python
   at
   lunch today.  The consensus was that Python was much better than
   Ruby in
   all ways.
 
 That's bullshit. Python and Ruby are quite comparable.
 
snip

Aw.  And here I thought we had just decided that such language was
unnecessary and unappreciated on this list.  Why not just say, I
disagree, and avoid all the unpleasantness.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] Ruby Code Blocks vs. Python Lambdas

2006-11-07 Thread Carroll, Barry
Hello again.

 -Original Message-
 Date: Tue, 7 Nov 2006 09:56:42 -
 From: Alan Gauld [EMAIL PROTECTED]
 Subject: Re: [Tutor] Ruby Code Blocks vs. Python Lambdas
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; format=flowed; charset=iso-8859-1;
   reply-type=original
 
 Carroll, Barry [EMAIL PROTECTED] wrote
 
snip

  The consensus was that Python was much better than Ruby in
  all ways.
 
 That's a little hard on Ruby. There are many good features and several
 of them are arguably improvements on Python. 

snip
 

In case anybody's interested, I wasn't giving my own opinion on Ruby; I
don't know enough to have an opinion on Ruby.  Sadly I don't have time
at present to study the language right now.  That's one reason why I'm
enjoying this discussion.  

  I have struggled considerably with lambdas since taking up Python.
  I'm
  still not really comfortable using them in production code.  I agree
  that Ruby's style is more intuitive and easier to use.  I wonder if
  a
  future version of Python could adopt this style.
 
 I think it would be difficult without adding block delimiters to
 the language, and most of the common symbols already
 have a role ([],(),{}, |, etc).

I think a solution could be found if the desire for the capability was
there (e.g. , ``, ...). 
 
 Also Guido prefers explicit definition of functions to
 anonymous ones - explicit is better than implicit is
 one of Pythons principles after all.

Correct indeed.  But lambda functions ARE anonymous.  

Python supports the creation of anonymous functions (i.e. 
functions that are not bound to a name) at runtime, using 
a construct called lambda. 
http://www.secnetix.de/~olli/Python/lambda_functions.hawk

So that principle has already been bent.  Since code blocks are more
flexible and more intuitive than lambdas, why not add them to the tool
box?  To quote some more principles:

* Beautiful is better than ugly. 
* Readability counts. 
* ... practicality beats purity.

 
 Alan G.
 

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


[Tutor] (OT) Flame wars (was: Amazing power of Regular Expressions...)

2006-11-06 Thread Carroll, Barry
Greetings, all:

 -Original Message-
 Date: Mon, 6 Nov 2006 10:32:32 +
 From: Michael Sparks [EMAIL PROTECTED]
 Subject: Re: [Tutor] Amazing power of Regular Expressions...
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain;  charset=iso-8859-1
 
 On Monday 06 November 2006 01:08, Alan Gauld wrote:
  While using a dictionary is probably overkill, so is a rage.
 
 No, in this case it's absolutely the right choice.
 
  A simple string holding all characters and an 'in' test would
probably
  be both easier to read and faster.
 
 I'm stunned you think this. It's precisely this sort of naivete that
 baffles
 me with regard to regales.
 
  Which kind of illustrates the point of the thread I think! :-)
 
 Actually, no, it doesn't.
 
snip
 
 I'm serious, if you think ^[0-9A-Za-z_.-]*$ is unclear and complex, go
 away
 and relearn regales.
 
 Michael.
 

With the final sentence above, this thread has ceased to be an
intellectual discussion and become a religious argument.  Until then, I
was enjoying an informative discussion by knowledgeable people on a
topic of considerable interest.  Now I'm upset by the implications of
the statement and embarrassed on behalf of the writer.

When a person his so convinced of his/her rightness that they feel
justified in insulting those in opposition, that person has substituted
flaming for advocacy.  They have also, in my opinion, seriously weakened
their position on the subject.  Why would someone resort to such an
attack if they were, in fact, correct?  

I am disappointed to see such behavior on this list, and I hope it's
occurrence will continue to be vanishingly small.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] Why is this only catching one occurance?

2006-10-27 Thread Carroll, Barry
Chris:

See below.  


 -Original Message-
 Message: 7
 Date: Fri, 27 Oct 2006 12:20:51 -0700
 From: Chris Hengge [EMAIL PROTECTED]
 Subject: Re: [Tutor] Why is this only catching one occurance?
 To: Bob Gailer [EMAIL PROTECTED]
 Cc: Tutor tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 I've tried to use your example:
 for unWantedItem in directoryList[,,-1]:
 
 but I get an error:
 for unWantedItem in directoryList[,,-1]:
  ^
 SyntaxError: invalid syntax
 
SNIP

The problem is the commas.  Python uses colons to describe slices.  Try
this instead:

 for unWantedItem in directoryList[::-1]:

I think that will work for you.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

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


[Tutor] (OT) Non-Python discussions (Was: I am terribly confused about generators ...)

2006-10-27 Thread Carroll, Barry
Greetings:

I agree completely with David.  There are plenty of places to discuss
controvercial topics.  Let's not do it here, where it will only disrupt,
and possibly ruin, an exceptionally useful teaching and learning
channel.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


 -Original Message-
 Message: 1
 Date: Fri, 27 Oct 2006 10:41:51 -0600
 From: David Heiser [EMAIL PROTECTED]
 Subject: Re: [Tutor] I am terribly confused about generators and
   iterators.. Help me
 To: pythontutor tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii
 
 May I invite EVERYONE to NOT introduce political or religious elements
 into these discussions. It has no place here and can destroy this
 excellent discussion group. I've seen it happen.
 
 PLEASE take it elsewhere.
 
 -Original Message-
 From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
 Behalf Of Bob Gailer
 Sent: Friday, October 27, 2006 10:11 AM
 To: Asrarahmed Kadri
 Cc: pythontutor
 Subject: Re: [Tutor] I am terribly confused about generators and
 iterators.. Help me
 
 Asrarahmed Kadri wrote:
 
  Hi Folks,
 
snip
  To HIM you shall return.
 I am glad that this thought brings you some comfort or stimulation. I
 used to believe something similar, and all it did was bring me fear
 guilt and shame.
 
 --
 Bob Gailer
 510-978-4454
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor


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


Re: [Tutor] VIM Python

2006-10-11 Thread Carroll, Barry
I'm a Vim user, too.  I usually have three windows open: IPython to try
out snippets of code, ViM to edit the target program, and a command
shell to execute the module/run the self tests.  A while back I asked
the ViM mailing list (vim@vim.org) if there was a way to open a shell
window from within ViM.  Here is the response I got:  

** Vim can be compiled with Python support; the output of the :version

** command will then show either +python or +python/dyn

** With such a version of Vim, you can execute individual Python
commands, 
** inline Python documents in Vim scripts, or full-fledged Python
scripts. 
** Also, Python commands called from Vim may access Vim buffers,
windows, 
** variables, etc., giving you access to the power of both Vim and
Python 
** in a single script. Of course, 'T Aint No Such Thing As A Free Lunch:

** such a script is more powerful but less portable, since it can only
be 
** run on a machine where both Vim and Python are installed.

** See :help python for details of how to use the Python interface.

I read the suggested help pages, but I haven't had the nerve to try out
the interface yet.  When I do, I'll post my findings here.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

 -Original Message-
 Date: Wed, 11 Oct 2006 21:40:56 +0100
 Subject: [Tutor] VIM  Python
 To: tutor@python.org
 
  I use VIM to write my Python programs. I usually have a shell open
  to run
  pyflakes on the file I just edited. Is there a way to run pyflakes
  from
  within VIM and have it display the errors in another buffer?

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


Re: [Tutor] Question about startswith() and endswith() in 2.5

2006-09-25 Thread Carroll, Barry

 -Original Message-
 Date: Mon, 25 Sep 2006 02:59:45 -0700
 From: Dick Moores [EMAIL PROTECTED]
 Subject: [Tutor] Question about startswith() and endswith() in 2.5
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii; format=flowed
 
 http://www.python.org/doc/lib/string-methods.html has
 =
 startswith( prefix[, start[, end]])
 Return True if string starts with the prefix, otherwise return False.
 prefix can also be a tuple of suffixes to look for. With optional
 start, test string beginning at that position. With optional end,
 stop comparing string at that position.
 
 Changed in version 2.5: Accept tuples as prefix.
 ==
 
 and
 
 
 endswith( suffix[, start[, end]])
 Return True if the string ends with the specified suffix, otherwise
 return False. suffix can also be a tuple of suffixes to look for.
 With optional start, test beginning at that position. With optional
 end, stop comparing at that position.
 
 Changed in version 2.5: Accept tuples as suffix.
 ==
 
 Through experimentation I now see a use for a tuple in which start
 and end are indexes (as with the startswith() and endswith() of
2.4.3):
 
   s = qwerty
  
   s.startswith(er,2,3)
 False
  
   s.startswith(er,2,4)
 True
  
 
 but
   s.startswith(er,q,ty)
 
 Traceback (most recent call last):
File pyshell#55, line 1, in module
  s.startswith(er,q,ty)
 TypeError: slice indices must be integers or None or have an __index__
 method
 
 On http://docs.python.org/whatsnew/other-lang.html I found
 
 ==
 The startswith() and endswith() methods of string types now accept
 tuples of strings to check for.
 
 
 def is_image_file (filename):
  return filename.endswith(('.gif', '.jpg', '.tiff'))
 
 
 
 This is the only example I've been able to find in the documentation
 that uses the new tuple of strings, and I don't understand it. The
 function is_image_file() will return filenames ending in '.gif', but
 what do '.jpg' (as start) and '.tiff' (as end) do? What kind of
 data(?) would this function be applied to? A Python list of filenames?
 
 Thanks,
 
 Dick Moores
 

Hello, Dick.

Let's compare your final startswith method and the endswith method in
is_image_file:


s.startswith(er,q,ty)
filename.endswith(('.gif', '.jpg', '.tiff'))


Notice that, while startswith has THREE parameters, endswith has only
ONE.  ('.gif', '.jpg', '.tiff') is a tuple, and the interpreter sees it
as a single parameter.  In other words your method is passing the
following parameters: 

prefix = er
start = q
end = ty

while the example method is passing:

suffix = ('.gif', '.jpg', '.tiff')
start = None
end = None

Does that make sense?

Good luck.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


[Tutor] Overloading the assignment operator in a class

2006-09-20 Thread Carroll, Barry
Greetings:

I have a class that implements a die (singular or dice).  Here is the class 
definition:


class Die(object):
Implements a gaming die.

Attributes:
n:  the number of sides
Must correspond to the number of sides on a physical die.
value:  The die face currently facing up. Guaranteed to be in the
range 1 = value = n.  

Methods:
init:   instantiate a die
roll:   roll the die; set and return the new value
set:set the die's value to an arbitrary, in range, value
__repr__   
__lt__
__le__
__eq__
__ne__
__gt__
__ge__
__cmp__
   

def __init__(self, nsides = 6, firstval = 'r'):
create a die

usage:  x = die(n, firstval) - an 'n'-sided die with
value='firstval'
Arguments:
nsides: the number of sides
valid:  3,   4,  5,  6,  7,  8,  10, 12, 
14, 16, 20, 24, 30, 50, 100
default:6
Must correspond to the number of sides on a physical die.
Using an invalid value causes an exception.
firstval:   the die's initial value; 
valid:  'r' - random value between 1 and n
 n  - specified value; must be between 1 and n
  Using an invalid value causes an 
  exception.
default:'r'


validn = (3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 30, 50, 100)
if nsides not in validn:
errmsg = No die has %s sides.  Valid values are: %s. 
raise ValueError(errmsg % (nsides, validn))
self.n = nsides

if firstval == 'r':
self.value = randint(1, self.n)
elif isinstance(firstval, int):
if 1 = firstval = self.n:
   self.value =  firstval
else:
errmsg = %s is not between 1 and %s.  
raise ValueError (errmsg % (firstval, self.n))
else:
errmsg = %s is invalid.  Valid entries are '%s'  \
 or an integer between 1 and %s. 
raise ValueError(errmsg % (firstval, 'r', self.n))

def roll(self):
roll the die; set and return the new value
self.value = randint(1, self.n)
return self.value

def set(self, newval):
set the die's new value IF between 1 and n; 
else raise exception


if isinstance(newval, int):
if 1 = newval = self.n:
   self.value =  newval
else:
errmsg = %s is not between 1 and %s.  
raise ValueError (errmsg % (newval, self.n))
else:
errmsg = %s is invalid.  Valid entries are '  \
 integers between 1 and %s. 
raise ValueError(errmsg % (newval, self.n))

# special methods
def __cast(self, other):
if isinstance(other, Die): return other.value
else: return other
def __repr__(self): return repr(self.value)
def __lt__(self, other): return self.value   self.__cast(other)
def __le__(self, other): return self.value = self.__cast(other)
def __eq__(self, other): return self.value == self.__cast(other)
def __ne__(self, other): return self.value != self.__cast(other)
def __gt__(self, other): return self.value   self.__cast(other)
def __ge__(self, other): return self.value = self.__cast(other)
def __cmp__(self, other): return cmp(self.value, self.__cast(other))


This all seems to work okay.  

I want the assignment operator ('=') to call the set method transparently on 
Die instances, as in this fictitious example:

###
@BCARROLL[Python]|2 mydie = Die(6,3)
@BCARROLL[Python]|3 mydie.n
 3 6
@BCARROLL[Python]|4 mydie.value
 4 3
@BCARROLL[Python]|5 mydie
 5 3
@BCARROLL[Python]|6 mydie = 5
@BCARROLL[Python]|7 mydie
 7 5
@BCARROLL[Python]|8 mydie.value
  8 5
@BCARROLL[Python]|9
###

Above, the statement mydie = 5 resets mydie.value and preserves mydie as a 
Die instance.  The actual (undesired) behavior rebinds the mydie to the int 
object, and the Die instance is lost:


@BCARROLL[Python]|2 mydie = Die(6,3)
@BCARROLL[Python]|3 mydie.n
 3 6
@BCARROLL[Python]|4 mydie.value
 4 3
@BCARROLL[Python]|5 mydie
 5 3
@BCARROLL[Python]|6 mydie = 5
@BCARROLL[Python]|7 mydie
 7 5
@BCARROLL[Python]|8 mydie.value
---
exceptions.AttributeError Traceback (most recent call last)

\\psc.pscnet.com\shares\home\bgcarroll\My Documents\My 
Projects\study\Python\console

AttributeError: 'int' object has no attribute 'value'
@BCARROLL[Python]|9


How do I 

[Tutor] Where to post a Python Program

2006-09-05 Thread Carroll, Barry








Greetings:



I have written a console version of the dice game Yahtzee).
I would like to post it for comment. It is too long to post here and I dont
have a web site. Is there some place where I can post my code and get
feedback about it?



Regards,



Barry

[EMAIL PROTECTED]

541-302-1107



We who cut mere stones must always be
envisioning cathedrals.

Quarry worker's creed








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


Re: [Tutor] Big wad of Python tutorials

2006-08-21 Thread Carroll, Barry
 -Original Message-
 Date: Mon, 21 Aug 2006 13:52:45 -0700 (PDT)
 From: Terry Carroll [EMAIL PROTECTED]
 Subject: [Tutor] Big wad of Python tutorials
 To: tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: TEXT/PLAIN; charset=US-ASCII
 
 
 This page, consisting of links to a few hundred topically sorted
Python
 tutorials, was mentioned on Digg recently.  I thought I'd pass on the
URL:
 
 http://www.awaretek.com/tutorials.html
 
 Many of the URLs will be familiar to some on this list, but many more
are
 new, certainly at least to me.
 
Thanks, Terry.  That link looks like a great resource.  I think I'll
start with the GUI sections.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] Tutor Digest, Vol 30, Issue 68

2006-08-21 Thread Carroll, Barry
Hello, Marcus

 Date: Mon, 21 Aug 2006 16:50:37 -0400
 From: Marcus Goldfish [EMAIL PROTECTED]
 Subject: [Tutor] custom container subclassing list-- slices are
   lists!?
 To: Tutor tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 Hi,
 
 I'd like to sublcass the built-in list type to create my own
container.
 How
 can I make slices of the list be of type myclass-- currently they are
 lists.  Example:
 
  class MyFoo(list):
def __init__(self, inlist):
   self = inlist[:]
  me = MyFoo(range(10))

I'll start with a side question: did you check the contents of me?  When
I did this (using the IPython shell running on Python 2.3) I got the
following:

**
@BCARROLL[Python]|1 class MyFoo(list):
 |. def __init__(self, inlist):
 |. self = inlist[:]
 |.
@BCARROLL[Python]|2 me = MyFoo(range(10))
@BCARROLL[Python]|3 me
 3 []
**

The identifier me did not get the list you wanted
([0,1,2,3,4,5,6,7,8,9]).  I don't know why.  Perhaps one of the more
experienced people on the list knows.

  type(me)
 class '__main__.MyFoo'

This worked okay: the empty list is of type class MyFoo

 
  type(me[0:3])
 type 'list'

So far, you have only defined one special method for your class:
__init__.  All the other operations available for instances of your
class come from the base class list.  And the slicing operator for the
list class returns ... you guessed it ... a list.  In order to return an
instance or your class, you must override the slicing operator in your
class definition.  

Doing this correctly is not simple.  The slicing operator is implemented
by three special methods (__getitem__, __setitem__ and __delitem__),
each of which takes a slice OBJECT as a parameter.  Overriding these
three methods is pretty advanced Python.  Python in a Nutshell, 2nd
Edition (my Python bible) says, 

... It's best to avoid this complication by simply not defining

the slice-specific special methods in your classes; however, 
you may need to override these methods if your class subclasses 
list or tuple and you want to provide special functionality when

an instance of your class is sliced with just one colon. ...
[Section 5.2.2.4, Container Slicing]

So, the question to ask yourself is, Do I require special functionality
when slicing a MyFoo object?.  If not, then don't worry that the
slice's type is different than that of the original instance.

If the answer is yes, however, you can try subclassing UserList.  Module
UserList was written back when built-in types like list could not be
subclassed.  It uses the now deprecated special methods __getslice__,
__setslice__ and __delslice__, and it is no longer entirely complete or
correct.  But it still works pretty well.  And, it also overrides many
other operators that apply to lists.  (Read about it in Python Library
Reference Section 3.8 and UserList.py.)

Using this module, your code would look like this:

**
@BCARROLL[Python]|1 from UserList import UserList
@BCARROLL[Python]|2 class MyFoo(UserList):
 |. def __init__(self, inlist):
 |. UserList.__init__(self, inlist)
 |.
@BCARROLL[Python]|3 me = MyFoo(range(10))
@BCARROLL[Python]|4 me
 4 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
**

Note that this construction handles the range method correctly.

**
@BCARROLL[Python]|5 type(me)
 5 type 'instance'
@BCARROLL[Python]|6 isinstance(me, MyFoo)
 6 True
**

Note here that the type method doesn't show me to be an instance of
MyFoo, but that isinstance does.  

**
@BCARROLL[Python]|7 me[0:3]
 7 [0, 1, 2]
@BCARROLL[Python]|8 type(me[0:3])
 8 type 'instance'
@BCARROLL[Python]|9 isinstance(me[0:3], MyFoo)
 9 True 
**

And finally, the slice is in fact an instance of MyFoo.

 All help appreciated!

Sorry for being so long-winded.  I hope this helps.  
 
 Thanks,
 Marcus

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] Python on network problems

2006-08-15 Thread Carroll, Barry
Hello, Diana,

I have had a little experience with networking problems.  Here's my take
on your situation.  

Regards,
 

 Date: Tue, 15 Aug 2006 11:19:35 +1000
 From: Diana Hawksworth [EMAIL PROTECTED]
 Subject: Re: [Tutor] Python on network problems
 To: Alan Gauld [EMAIL PROTECTED]
 Cc: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain
 
snip
 
 We are running Windows XP.  The students log in to a network server
that
 allows them access to their user accounts as well as various group
 folders.  We have 4 rooms full of computers - but Python is installed
on
 each workstation in this room only ie, it is active in this room
only.
 It is not on the network and no other computer rooms have access to
it.
 The students in this room save their Python files to a networked
user
 account - as they do with all their other files.
 

From your description, I gather that a single computer provides
authentication service and file service to the entire network.  Is this
correct?  If so, that machine is a single point of failure in your
network.  If it hangs for any reason, the entire network goes away.  

 Two failures have occurred.
 
 The first has been intermittent and to individual students only at
rare
 times.  A student will attempt to start IDLE - and nothing will
happen.
 Sometimes, changing that student's log in user name will solve the
 problem, and he then has access to Python again.
 

I don't haven't used IDLE that much, so Alan's ideas are more reliable
than mine here:

 That could be a local machine/user setup issue.
 Given the various issues with IDLE and firewalls I might
 look at the firewall settings on the Python PCs and make
 sure IDLE is happy with them.

 The 2nd is more pervasive, and that is, whenever I have the class
working
 with Python - the entire school network becomes inoperable, and the
system
 administrator needs to reboot it again. Because we have been working
on
 Python each time this has happened, Python is being blamed for the
system
 failure. Inoperable - no one is able to open any files in any program,
 save any work they have been working on, open files - or even log in
if
 they haven't already. The whole system is  frozen, from the office
to
 every other computer in the school.

 Now I am inclined to think it is not a Python problem at all.  Python
is
 locally and individually installed on computers in this room only.  It
has
 no network access at all  - apart from files being saved in networked
user
 accounts.
 

 The only slight possibility is if any of the students are
 writing code that accesses a networked folder, to open
 a file say, and is causing some high volume network traffic. 

I think Alan is right here, too, and here's why. (Python internals
gurus, please correct any bad assumptions in the following.)  Lab #4 is
full of users running Python programs.  The interpreter is running on
each local machine, but the program (and data) files are all stored on
the lone network file server.  Since Python programs are executed by the
interpreter, they access file storage more heavily that compiled
programs do.  So, every time any of the (15, 20, 25?) computers in the
Python lab needs a file, or needs to save a file, it sends a request to
that one computer.  The potential bottleneck is obvious.  

I think the network server's capacity is being exceeded in some way.
When this happens, instead of degrading service gracefully (e.g.
rejecting a request and instructing the client to try again later) the
server is getting lost somehow and hanging, causing the failure modes
you describe.  

Here are some areas for your network administrator to investigate:

   * maximum number of concurrent disk access requests, 
   * maximum number of open files,
   * file server disk usage,
   * file server disk fragmentation,
   * server processor utilization, 
   * network bandwidth utilization,
   * other limits imposed by the networking software or the 
 server's hardware.

 What I would like to know is if anyone else has had a similar problem
-
 and it has been proven that Python is the cause?  If so - how was the
 problem solved?
 

The best solution (IMHO) is also the most expensive: add a redundant
server to your network.  This would eliminate the single point of
failure weakness and reduce the load per server.  Also, is one server
should hang or fail for any other reason, the duplicate server can keep
the network running while the failed machine is rebooted, repaired, etc.


If possible, I would recommend using a Unix clone as your server's OS
instead of Windows.  Even Linux, which is available free of charge,
provides a more stable platform for a network server than does Windows.
This is relatively easy, especially if your network is based on TCP/IP.
Many Windows intranets use Unix/Linux servers.  The biggest obstacle, in
many cases, is the learning curve required of the network administrator.


 Be grateful for any advice - and hope I have made the situation

Re: [Tutor] syntax error

2006-07-31 Thread Carroll, Barry
Hello Chris,

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

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

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

HTH.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] Tutor Digest, Vol 29, Issue 66

2006-07-26 Thread Carroll, Barry
Greetings:

 -Original Message-
 Date: Wed, 26 Jul 2006 10:11:28 +0100
 From: Alan Gauld [EMAIL PROTECTED]
 Subject: Re: [Tutor] loops to assign variables
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 
snip
 
 John CORRY [EMAIL PROTECTED] wrote
 
  For example, I have 30 textentry boxes numbered from entry20 to
  entry50.
  I have used the following code to assign the entryboxes to a local
  name.
 
  text20 = self.wTree.get_widget(entry20)
  text21 = self.wTree.get_widget(entry21)
 
 This is not a resonse to Johns original request but a general
 comment on variable naming. It seems quite common in GUI
 work for folks to use this style of entryN, buttonM etc.
 
 But its not very programmer friendly! We wouldn't normally
 call our variables var1, var2 etc it makes the intent of the code
 much harder to comprehend. So we choose meaningful variable
 names like width, height, name, location etc.
 
snip

I agree with Alan here.  Unless the numbers reflect some property of the
object being modeled (room numbers in a hotel, airline flight numbers,
TV channels, etc), they should not be used in the widget name.  

My $0.02.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] confused by linked queue

2006-07-26 Thread Carroll, Barry
Danny, et al:


 -Original Message-
 Date: Tue, 25 Jul 2006 15:43:34 -0700 (PDT)
 From: Danny Yoo [EMAIL PROTECTED]
 Subject: Re: [Tutor] confused by linked queue
 To: Christopher Spears [EMAIL PROTECTED]
 Cc: Tutor tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed
 
  One of my problems in conecptualizing this is that I thought a
linked
  queue was just a linked list.  Is a linked queue a linked list?
There
  seems to be a subtle difference...
 
 Hi Chris,
 
 I think you mean to ask:
 
  Is a queue a linked list?
 
 
 Here's another particular possible queue class that does something
 similar, but with Python's regular lists rather than a linked list:
 
 ##
 class ArrayQueue:
  def __init__(self):
  self.elements = []
 
  def isEmpty(self):
  return len(self.elements) == 0
 
  def insert(self, elt):
  self.elements.append(elt)
 
  def remove(self):
  return self.elements.pop(0)
 ##
 
 This works on a different principle than the linked list queue, but it
 does the same stuff.  The main idea is that a queue can be anything,
as
 long as it supports three operations:
 
  * isEmpty
  * insert
  * remove
 
snip

Isn't there a fourth operation needed?

* isFull  

Even in Python (where the underlying data structure can grow on the fly,
there is a physical upper limit: the size of the heap or stack.  This
condition needs to be handled gracefully. 

Regards,

Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] IDE for Python

2006-07-25 Thread Carroll, Barry
Raj:

I prefer ViM as well.  I have tried several IDEs: Idle, SlickEdit,
Eclipse/PyDev, Stani's Python Editor (SPE).  None of them manages
multiple editing windows as well as ViM, and that is the feature I use
most.  

In a typical editing session I will have six or more editing windows
open, accessing perhaps three different files.  ViM handles all this
effortlessly.  It allows me to have many windows open at once, each one
in the position and of the size that best matches my need at the moment.
Resizing, opening and closing windows, displaying a new file in an
existing window, chancing focus from one window to another.  ViM handles
these tasks far better than any of the IDEs I have tried.   

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

 -Original Message-
 Date: Tue, 25 Jul 2006 10:51:54 -0600
 From: Mike Hansen [EMAIL PROTECTED]
 Subject: Re: [Tutor] IDE for Python
 To: tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii
 
 
 
 
 
 
   From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED]
 On Behalf Of Basavaraj SP.
   Sent: Tuesday, July 25, 2006 9:05 AM
   To: tutor@python.org
   Subject: [Tutor] IDE for Python
 
 
 
   Dear All,
 
   I am new to Python.
 
   I want to know which IDE I should use for programming.
 
   If so from where can I get it?
 
   Thanks in advance.
 
   - Raj
 
 I personally use VIM. The closest thing to an IDE I've used is Komodo.
 You might check out these links.
 
 http://pyfaq.infogami.com/tutor-whats-the-best-editor-ide-for-python
 
 Mike
 http://users.adelphia.net/~mahansen/programming/editorides.html

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


Re: [Tutor] How do you implement a config file?

2006-07-17 Thread Carroll, Barry
Tracy:

 Date: Sat, 15 Jul 2006 22:44:43 -0700 (PDT)
 From: Danny Yoo [EMAIL PROTECTED]
 Subject: Re: [Tutor] How do you implement a config file?
 To: Tracy R Reed [EMAIL PROTECTED]
 Cc: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed
 
 
 
  I am writing a small python application that needs a few variables
to be
  end user configurable. Right now I just have the variables right up
  front where the user can tweak them in the program code and a big
  commented line that says Nothing editable past this point. But I
would
  like to be able to break this out into a separate config file. There
are
  two ways I see to do this:
 
 Hi Tracy,
 
 [config parser approach cut]
 
  I don't see any good way to do that either without actually making
my
  config file a module and calling it config.py instead of
  application.config.
 
 This second approach --- using a module as a configuration file --- is
the
 programmer-friendly one.  *grin* If you can get away with this, it's
 probably the simplest to implement.  It also seems to be the approach
that
 most Python programs use, bar more sophisticated approaches like XML
or
 some other structured data format.
 
 We had some discussion about this earlier the last few weeks (and
months!
 Someone should put this on the FAQ!), and the concensus seems to be
that
 ConfigParser is a bit limiting:
 

http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/3116794
  http://mail.python.org/pipermail/tutor/2006-June/047557.html

I like to implement config data as a Python dictionary.  Doing so makes
things almost trivial. To use your example:

In config.py

configdata = {
  foo: ['bar','baz','bah']
  .
  .
  .
}


In application.py

from config import configdata
.
.
.
foo = configdata[foo]


The drawback, of course, is that the application's administrator must
understand enough Python to fill in a dictionary.  As Danny says, if you
can get away with that caveat, the dictionary approach is easy to
implement.  

Another method is to store your config data in XML format.  This is a
little more complex to implement, but has a couple of advantages. First,
since XML is a pretty widely accepted standard, is reasonable to expect
the application's administrator to know it.  Second, you can name the
config file whatever you want: application.config works just fine
(although you might want to add XML to the file name somewhere).

Again, from your example:

In appXML.config:

[configdata]
  [foo]
bar
baz
bah
  [/foo]
  .
  .
  .
[/configdata]


I haven't used XML for this purpose (yet), so I can't help you with the
Python XML parser, but you can get more information on the WEB:

  http://pyxml.sourceforge.net/topics/

HTH.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] Python Programming Books

2006-07-14 Thread Carroll, Barry
Greetings:

Like Matthew, I have a been programming for several years, mostly in
C-like languages and various assembly languages.  I started using Python
about two years ago. Learning Python is my text book; Python in a
Nutshell is my language reference.  Both are excellent.  I use one or
both nearly every day.  I haven't used the Python Cookbook much.  

For those learning to program with Python as their language, I recommend
Alan Gauld's online guide Learning to Program:

 http://www.freenetpages.co.uk/hp/alan.gauld/

It is well written and easy to follow.  For those who like to read hard
copy, you can download a pdf version of the guide

 http://www.freenetpages.co.uk/hp/alan.gauld/tutor.pdf

and print it out.  

Best of luck.  

Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


 --
 Date: Fri, 14 Jul 2006 10:11:19 +0100
 From: Matthew Webber [EMAIL PROTECTED]
 Subject: Re: [Tutor] Python Programming Books
 To: 'Grady Henry' [EMAIL PROTECTED], tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii
 
 It depends a lot on what your prior programming experience in other
 languages is.
 
 I have a large amount of prior programming experience, and I found
 Learning
 Python very good. The Python Cookbook (Martelli et. al., also
O'Reilly)
 is very useful for learning the idioms.
 
 
 -Original Message-
 From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
Behalf
 Of Grady Henry
 Sent: 14 July 2006 06:20
 To: tutor@python.org
 Subject: [Tutor] Python Programming Books
 
 I have three books on Python programming, Learning Python by
O'Reilly,
 Beginning Python by Hetland, and Python in a Nutshell by O'Reilly.
 Are
 these good (recommended) books?  Any others that might be recommended?
 

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


Re: [Tutor] Unit testing

2006-06-26 Thread Carroll, Barry


Regards,
 
Tino:

I agree with Kent on this.  As much as possible, a unit test should test
what it is supposed to do.  

 Date: Mon, 26 Jun 2006 15:50:36 -0400
 From: Tino Dai [EMAIL PROTECTED]
 Subject: Re: [Tutor] Unit testing
 To: Kent Johnson [EMAIL PROTECTED], tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
  I often write unit tests that do this. In my opinion it is simple
and
  straightforward and effective. Some purists will insist that a unit
test
  shouldn't write the file system or touch a database or use any other
  external resource, but I think that is silly - if the job of a bit
of
 code
  is to write a file or interact with the database, then the simplest
way
 to
  test it is to check the file or database. As long as the tests run
fast
  enough it's OK. (For me, a unit test on a single module should
ideally
 run
  in well under a second.)
 
  Alternately you can use StringIO or other substitutes for files in
your
  tests. But somewhere in your test system you probably want to make
sure
 the
  actual file is there on disk, whether it is in a unit test or
acceptance
  test.
 
 
 Ok, that leads me to my next question.  Currently, I have a class that
I
 want to unit test, but it contains a semaphore from another class.
Now, I
 could make the semaphore a global variable, or I bring in the other
class.
 One violates good programming principles and the other violates the
unit
 testing principles. Is there another way?
 
 -Tino
 -- next part --
 An HTML attachment was scrubbed...
 URL:

http://mail.python.org/pipermail/tutor/attachments/20060626/bf127497/att
ac
 hment.html
 
 --

I think the same principle applies here.  The code you are testing
involves a semaphore.  By all means, include the other class and test
the semaphore.  

I'm not familiar with the 'unit testing principles' that would forbid
your doing this.  Even if I were, principles are to be followed when
they make sense.  When it makes better sense to violate a principle,
then violate it. 

Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

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


[Tutor] Machine Vs. Human Parsing (Was: XML: Expletive Deleted) (Way OT!)

2006-06-16 Thread Carroll, Barry
Greetings:

 -Original Message-
 Date: Fri, 16 Jun 2006 00:05:41 +0100
 From: Alan Gauld [EMAIL PROTECTED]
 Subject: Re: [Tutor] XML: Expletive Deleted (OT)
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 
 Just picked this up after being out for most of the week...
 
 Carroll, Barry [EMAIL PROTECTED] wrote in message
 
  One reason to for choosing a human-readable format is the desire to
  visually confirm the correctness of the stored data and format.
 
 Thats a very dangerous asumption, how do you detect unprintable
 characters, tabs instead of spaces, trailing spaces on a line etc etc.
 Whole text representations are helpful you should never rely on the
 human eye to validate a data file.
 
  can be invaluable when troubleshooting a bug involving stored data.
  If
  there is a tool between the user and the data, one must then rely
  upon
  the correctness of the tool to determine the correctness of the
  data.
 
 Or the correctness of the eye. I know which one i prefer - a tested
 tool.
 The human eye is not a dta parser, but it flatters to deceive by being
 nearly good enough.
 
  In a case like this, nothing beats the evidence of one's eyes, IMHO.
 
 Almost anything beats the human eye IME :-)
 Actually if you must use eyes do so on a hex dump of the file, that
 is usually reliable enough if you can read hex...
 
snip
 
 Alan g.

If I gave the impression that the human eye is the only useful means of
examining and verifying stored data, I apologize.  I indented to say
that the human eye, and the brain that goes with it, is an invaluable
tool in evaluating data.  I stand by that statement.  

The most sophisticated tool is only as good as the developer(s) who made
it.  Since software is ultimately written by humans, it is fallible.  It
contains mistakes, gaps, holes, imperfections.  When the tool gives bad,
or erroneous, or incomplete results, what do you do?  You look at the
data.  

A case in point.  I used to test audio subsystems on PC motherboards.
The codec vendor released a new version of their chip with new driver
software.  Suddenly our tests began to fail.  The vendor insisted their
HW and SW were correct.  The test owner insisted his SW was correct.
Somebody was mistaken.  

I used an audio editing program to display the waveform of the data in
the capture buffer.  The first several hundred samples were not a
waveform, but apparently random noise.  I now knew why the test is
failing, but why was there noise in the buffer? It wasn't there before.
The  editing SW was no help there.  So I switched tools, and displayed
the capture buffer with simple file dump program.  The first 2K of the
buffer was filled with text!

The story goes on, but that's enough to illustrate my point.  Neither
the audio driver, nor the test SW, nor the editing tool could show the
real problem.  All of them were 'tested tools', but when presented with
data they were not designed to handle, they produced incorrect or
incomplete results.  I could cite other examples from other disciplines,
but this one suffices:  no SW tool should be relied upon to be correct
in all cases.  

I trust my eyes to see things tools can't, not because they can detect
nonprintable characters in a HEX dump (I can read HEX dumps, and binary
when necessary, but I usually just print out '\t', '[SP]', etc) but
because they are not bound by anyone else's rules as to what is correct
and incorrect.  The programmer's two most valuable tools are her/his
eyes and brain.  They are always useful, sometimes indispensable.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] XML: Expletive Deleted (OT)

2006-06-12 Thread Carroll, Barry
Alan, Ralph, et al:

This is a little off-topic, I guess, being not directly related to
Python.  Oh, well.  Here are a couple of personal opinions and a
question about XML.

 -Original Message-
 Date: Sun, 11 Jun 2006 08:55:17 +0100
 From: Alan Gauld [EMAIL PROTECTED]
 Subject: Re: [Tutor] Expletive Deleted
 To: Ralph H. Stoos Jr. [EMAIL PROTECTED],
Tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; format=flowed; charset=iso-8859-1;
   reply-type=original
 
  I think XML is a tool that allows non-programmers to look at
  structured
  data and have it a in human readable form that gives us a chance of
  understanding that structure.
 
 Thats not a great reason to choose a file format IMHO.
 Tools can be written to display data in a readable format.
 For example SQL can be used to view the data in a database.
 File formats should be designed to store data, compactly
 and with easy access.

One reason to for choosing a human-readable format is the desire to
visually confirm the correctness of the stored data and format.  This
can be invaluable when troubleshooting a bug involving stored data.  If
there is a tool between the user and the data, one must then rely upon
the correctness of the tool to determine the correctness of the data.
In a case like this, nothing beats the evidence of one's eyes, IMHO.  

In their book, The Pragmatic Programmer: From Journeyman to Master
(Addison Wesley Professional), Andrew Hunt and David Thomas give another
reason for storing data in human readable form:

The problem with most binary formats is that the context necessary 
to understand the data is separate from the data itself. You are 
artificially divorcing the data from its meaning. The data may 
as well be encrypted; it is absolutely meaningless without the 
application logic to parse it. With plain text, however, you can 
achieve a self-describing data stream that is independent of the 
application that created it.

Tip 20

Keep Knowledge in Plain Text

  The other strength that I can see is this:  Once data is in this
  format,
  and a tool has been written to parse it,  data can be added to the
  structure (more elements) and the original tool will not be broken
  by
  this.  Whatever it is parsed for is found and the extra is ignored.
 
 But this is a very real plus point for XML.
 And this IMHO is the biggest single reason for using it, if you have
 data where the very structure itself is changing yet the same file
 has to be readable by old and new clients then XML is a good choice.

No argument there.  

  Without a doubt, the overhead XML adds over say, something as simple
  as
  CSV is considerable, and XML would appear to be rather more hard to
  work
  with in things like Python and PERL.
 
 Considerable is an understatement, its literally up to 10 or 20 times
 more space and that means bandwidth and CPU resource to
 process it.
 
 Using XML as a storage medium - a file - is not too bad, you suck
 it up, process it and foirget the file. MY big gripe is that people
 are
 inceasingly trying to use XML as the payload in comms systems,
 sending XML messages around. This is crazy! The extra cost of the
 network and hardware needed to process that kind of architecture
 is usually far higher than the minimal savings it gives in developer
 time.
 [As an example I recently had to uplift the bandwidth of the
 intranet pipe in one of our buildings from 4Mb to a full ATM pipe
 of 34Mb just to accomodate a system 'upgrade' that now used XML.
 That raised the network operations cost of that one building
 from $10k per year to over $100k! - The software upgrade by
 contrast was only a one-off cost of $10K]

This is an example of the resource balancing act that computer people
have been faced with since the beginning.  The most scarce/expensive
resource dictates the program's/system's design.  In Alan's example high
speed bandwidth is the limiting resource.  A data transmission method
that fails to minimize use of that resource is therefore a bad solution.


Python itself is a result of this balancing act.  Interpreted languages
like Basic were invented to overcome the disadvantages of writing of
programs in machine-readable, human-unfriendly formats.  Compiled
languages like C were invented to overcome the slow execution speed of
interpreted programs.  As processor speeds increased and execution times
dropped , interpreted languages like Python once again became viable for
large scale programs.  

  So, I think XML has it's place but I will not fault anyone for
  trying to
  make it easier to get code to work.
 
 Absolutely agree with that. Just be careful how you use it and
 think of the real cost impact you may be having if its your choice.
 Your customers will thank you.

So here's my off-topic question: Ajax is being touted as the 'best-known
method' (BKM) for making dynamic browser-based applications, and XML is
the BKM for 

[Tutor] Python related mags

2006-06-12 Thread Carroll, Barry


Hello, Andrew:

 -Original Message-
 Date: Mon, 12 Jun 2006 07:53:05 -0400
 From: Andrew Robert [EMAIL PROTECTED]
 Subject: [Tutor] Python related mags
 To: Python Tutor tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1
 
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1
 
 Hi everyone,
 
 Does anyone know of any Python related magazines available that would
be
 worth subscribing to?
 
 Ideally, a free one, but I would not object to a reasonably priced one
 either.
 
 I was able to find pyzine located at www.pyzine.com but it appears to
be
   defunct.

Dr. Dobbs puts out a weekly Python related e-zine that be useful to you.
I couldn't find the URL, but I get a link to it every week in the
Python-announce-list:

http://mail.python.org/mailman/listinfo/python-announce-list.  

HTH.  

Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] Trouble with os.path.isfile

2006-06-05 Thread Carroll, Barry
Carlos:

Thank you for your response.  

It turns out that Python and os.path.isfile() are working as expected.
A permissions conflict on my Linux-based system caused the isfile
function to return false for all the entries in the directory.  The web
server is running as user apache.  The files were owned by user iip.  I
don't have all the details worked out yet, but it appears that adding
apache to iip's group list resolves the conflict.  

It would be nice if the library entries for os.path.is* (where * is one
of {file, dir, link, mount) mentioned this restriction.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

 -Original Message-
 Date: Fri, 2 Jun 2006 23:28:21 -0700
 From: Carlos Daniel Ruvalcaba Valenzuela [EMAIL PROTECTED]
 Subject: Re: [Tutor] Trouble with os.path.isfile
 To: tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=WINDOWS-1252; format=flowed
 
 From: Carlos Daniel Ruvalcaba Valenzuela [EMAIL PROTECTED]
 Date: Jun 2, 2006 11:10 PM
 Subject: Re: [Tutor] Trouble with os.path.isfile
 To: Carroll, Barry [EMAIL PROTECTED]
 
 
 Here is the problem IMO:
 
 I did some modifications to your code (very minimal on ifs) and it
worked:
 
 import os
 
 def lstdirsnfiles(tdir):
 flst = os.listdir(tdir)
 flst.sort()
 
 fnames = []
 dnames = ['.', '..']
 
 for name in flst:
 absfn = os.path.join(tdir, name)
 
 if os.path.isdir(absfn):
 dnames.append(name)
 
 if os.path.isfile(absfn):
  fnames.append(name)
 return (dnames, fnames)
 
 (dirs, files) = lstdirsnfiles('/home/clsdaniel')
 
 It returns correctly all directories and files.
 
 Regards
 Carlos Daniel Ruvalcaba Valenzuela
snip


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


[Tutor] [Off topic] Is Zero Positive (was: Not Really Questions)

2006-06-05 Thread Carroll, Barry
Greetings:

 -Original Message-
 Date: Sun, 04 Jun 2006 18:43:25 -0700
 From: Yi Qiang [EMAIL PROTECTED]
 Subject: Re: [Tutor] Not Really Questions
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1
 
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1
 
 Alan Gauld wrote, On 06/04/2006 04:01 PM:
  Hi John,
 
  I'll pitch in although I've read most of the other answers
  too so I'll be adding to them mostly.
 
  The first one is lists... I can't for the life of me understand why
  a list
  starts at zero. In everything else in life other than programming
 
  Not quite. In math zero is usually the starting point, its generally
  viewed as a positive number(although it is obviously neither
positive
  or negative) and proofs and definitions usually start by
consideriung
  zero - or at least defining whether zero is in or out of scope.
 That is just not true. A number is positive if and only if it is
 strictly greater than 0 by definition.  Zero is not considered
positive
 in mathematics.  In fact, the set of positive integers, Z+, is the set
 {1,2,3,}.
 - --
 Yi Qiang ([EMAIL PROTECTED])
 Web: http://www.yiqiang.net
 Tel: (206) 661-8469
 PGP: 0xB515564B

[Somewhat off topic]
Strictly speaking, Yi Qiang is correct, of course. The set Z+ (which BTW
is identical with the set of natural numbers, N), does not include 0.  0
is neither positive nor negative. However, the set of non-negative
numbers does include 0, as does the set of non-positive numbers.  The
former set, {0, 1, 2, ...}, is the one associated with lists, arrays,
etc, as it is possible to have 0 or more elements in a list, while it is
not possible to have less than 0 elements.  

[Back on topic]
Like John, I find the half-open range concept to be 'unnatural'.  When
waiting for checkout at the market, I don't think of myself as being
'zeroth' in line; I'm either 'first' or 'next' in line.  

For me, it's a matter of context.  When programming, it helps remind
myself that I'm not in the 'natural' universe where 'natural numbers'
are the rule.  I'm in the computer's mathematical universe, where
'zeroth' in line is perfectly natural.  =8^)

HTH
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


Re: [Tutor] implementing config files

2006-06-02 Thread Carroll, Barry
Carlos:

Where does one find the objxml module?  I have looked on python.org and
Google and can't find it.  

Thanks in advance,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

 -Original Message-
 Date: Thu, 1 Jun 2006 23:36:27 -0700
 From: Carlos Daniel Ruvalcaba Valenzuela [EMAIL PROTECTED]
 Subject: Re: [Tutor] implementing config files
 To: Tracy R Reed [EMAIL PROTECTED]
 Cc: tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 Your could try to use XML files to store configuration files, I
 already coded something like that, using expat parser and loading the
 XML contents to objects and attributes, this is a sample code of how
 works my module:
 
 Lets supouse we have this file config.xml with the following contents:
 ?xml version=1.0 encoding=ISO-8859-1?
 config
 connection
 serverMySQL/server
 hostlocalhost/host
 port21/port
 userusername/user
 passwd/passwd
 /connection
 /config
 
 and in our code:
 
 from objxml import *
 
 fd = file('config.xml', 'r')
 p = XMLParser(fd)
 
 root = p.Root
 port = str(root.connection.port)
 user = str(root.connection.username)
 
 All nodes are objects, converting them to strings gets you the
 content, you can also access the atributes as normal object
 attributes.
 
 This code can be useful for what you want, take a look.
 
 Regards
 Carlos Daniel Ruvalcaba Valenzuela
 
 
 On 6/1/06, Tracy R Reed [EMAIL PROTECTED] wrote:
  Hello all!
 
  I am writing some code to implement a bunch of passive checks for
the
  nagios network monitoring system. 
snip
 
  --
  Tracy R Reed  http://ultraviolet.org
  A: Because we read from top to bottom, left to right
  Q: Why should I start my reply below the quoted text

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


[Tutor] Trouble with os.path.isfile

2006-06-02 Thread Carroll, Barry








Greetings:



One of the functions of my test system web server program is
to allow the user to view the contents of the image file directories and select
files to load onto the hardware. Obviously, a central part of this
function is to identify and display the names of directories and files in a specified
directory. I havent been able to find any canned code or cookbook
entries that do this, so Im making one from scratch. Here is the helper
function that gets and returns the directory and file names:





def lstdirsnfiles(tdir):

 flst = os.listdir(tdir)

 flst.sort()

 fnames = []

 dnames = ['.', '..']

 for name in flst:

 absfn =
os.path.join(tdir, name)

 if
os.path.isdir(absfn):


dnames.append(name)

 elif os.path.isfile(absfn):


fnames.append(name)

 return dnames, fnames 





The root of the image file directory tree is /home/iip/images.
When lstdirsnfiles is run with tdir set appropriately, the lists returned
contain no additional information: dnames = ['.', '..'] and fnames = [].
I added some tracing statements to see what was happening inside the
function:





def lstdirsnfiles(tdir):

 global DEBUG, dbgfname

 DEBUG = True

 

 flst = os.listdir(tdir)

 flst.sort()

 fnames = []

 dnames = ['.', '..']

 

 if DEBUG:

 dbgf =
open(dbgfname,mode=a)

 dbgf.write(\n+str
(time.localtime())+\n)


dbgf.write(Entering lstdirsnfiles\n)


dbgf.write(The directory = %s\n % tdir)


dbgf.write(The file list = %s\n % flst)



 for name in flst:

 absfn =
os.path.join(tdir, name)

 

 if DEBUG:


dbgf.write(File path = %s, isfile = %s\n % 

 
(absfn, os.path.isfile(absfn)))



 if
os.path.isdir(absfn):


dnames.append(name)

 elif
os.path.isfile(absfn):


fnames.append(name)

 

 if DEBUG:


dbgf.write(dnames = %s\n % dnames)


dbgf.write(fnames = %s\n % fnames)

 dbgf.close()

 DEBUG = False

 

 return dnames, fnames





The log vile received the following:



(2006, 6, 2, 15, 23, 4, 4, 153, 1)

Entering lstdirsnfiles

The directory = /home/iip/images

The file list = ['test1.bmp', 'test2.bmp', 'test3.bmp',
'test4.bmp', 'test5.bmp', 'test6.bmp']

File path = /home/iip/images/test1.bmp, isfile = False

File path = /home/iip/images/test2.bmp, isfile = False

File path = /home/iip/images/test3.bmp, isfile = False

File path = /home/iip/images/test4.bmp, isfile = False

File path = /home/iip/images/test5.bmp, isfile = False

File path = /home/iip/images/test6.bmp, isfile = False

dnames = ['.', '..']

fnames = []





So there are entries in the directory, but the function doesnt
recognize them as files. 



Finally, I opened the interpreter and tried doing this, as
nearly as possible, interactively. I got this:





 import os

 tdir = '/home/iip/images'

 os.listdir(tdir)

['test4.bmp', 'test3.bmp', 'test2.bmp', 'test1.bmp',
'test5.bmp', 'test6.bmp']

 flst = os.listdir(tdir)

 flst.sort()

 flst

['test1.bmp', 'test2.bmp', 'test3.bmp', 'test4.bmp',
'test5.bmp', 'test6.bmp']

 for name in flst:

... absfn = os.path.join(tdir,name)

... print absfn, is,

... if not os.path.isfile(absfn):

... print
NOT,

... print a file

...

/home/iip/images/test1.bmp is a file

/home/iip/images/test2.bmp is a file

/home/iip/images/test3.bmp is a file

/home/iip/images/test4.bmp is a file

/home/iip/images/test5.bmp is a file

/home/iip/images/test6.bmp is a file





As you can see, the interpreter correctly identifies the
strings in the list as names of files, but my function does not. I cant
see anything wrong with the logic in the function. Can any or you see the
problem Im missing?



As always, thanks in advance for your help.



Barry

[EMAIL PROTECTED]

541-302-1107



We who cut mere stones must always be
envisioning cathedrals.

Quarry worker's creed








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


Re: [Tutor] selecting and ordering file names on a remote machine

2006-05-12 Thread Carroll, Barry
Kent:

snip
 
  Essentially, page must do the following:
 
 1. present the files in the directory to the user as some sort
of list from which multiple names can be selected,
 2. present the selected file names in the order in which they
were selected,
 3. allow the user to add additional names, remove existing names
and change their order at will.
 
 
snip
 
 Sounds like a good time to learn some AJAX. Something like this?
 http://wiki.script.aculo.us/scriptaculous/show/SortableListsDemo
 
 To do this on a web page you need to use JavaScript, not Python. It's
 not too hard to write the classic list-on-the-left, move left button,
 move right button, list-on-the-right. But these days you can do much
 fancier stuff such as the link above.
 
 Kent


Yes, something like that would be great.  I've been reading an AJAX text
for awhile.  I guess now's a good time to start applying it.  =8^)
Thank you for the tips.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


[Tutor] selecting and ordering file names on a remote machine

2006-05-11 Thread Carroll, Barry
Greetings:

I'm adding a new page to our test system's browser based UI.  This page 
implements the process of sending one more barcode 'images' to the system for 
decoding by the unit under test.  Each 'image' is in a file in a known 
directory on the test system.  The file(s) to be presented, and the order of 
their presentation, are selected by the user via the web page.  There are other 
fields on the page, including a button to start the presentation, but I know 
how to implement those features.  It's the selecting and ordering of the files 
I find challenging.  

Essentially, page must do the following:

   1. present the files in the directory to the user as some sort 
  of list from which multiple names can be selected, 
   2. present the selected file names in the order in which they 
  were selected,
   3. allow the user to add additional names, remove existing names
  and change their order at will.

I've seen dialog boxes in GUI based programs that do this sort of things. Is 
there a widget or recipe extant that does this on a web page?  I've looked in 
the Python Cookbook and the recipe pages on aspn.activestate.com.  I didn't 
see anything promising.  Any ideas?  

My site is currently hand-built: no web application framework in use.  But, if 
there is a lightweight framework out there that has this functionality I'd be 
happy to use it, if it doesn't take months to install, configure and become 
proficient in.  

As always, thanks for your help.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed


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


Re: [Tutor] Books

2006-05-03 Thread Carroll, Barry
Greetings, John,

For my money, that book is:

Learning Python, 2nd Edition 
By David Ascher, Mark Lutz 
Publisher: O'Reilly 
Pub Date: December 2003 
ISBN: 0-596-00281-5 
Pages: 620

$25.19 new, 18.47 used (+ shipping)
From amazon.com

I taught myself Python with this book, and I still use it nearly every
day.  

BTW, there are several excellent tutorials for free online, but you
asked about books :^)

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


 -Original Message-
 Date: Wed, 03 May 2006 17:57:37 +1000
 From: John Connors [EMAIL PROTECTED]
 Subject: [Tutor] Books
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; format=flowed
 
 G'day,
 
 I know this is a difficult question to answer because it's probably
more a
 matter of personal taste than anything else.
 
 I'm retired so money has to be watched fairly carefully and books are
kind
 of expensive down here in Australia but the Mrs has said I can lash
out on
 a
 book for my birthday. So I was wondering (bearing in mimd that I'm
only 2
 or
 3 steps above total beginner), what is the one book on python that I
 shouldn't be without?
 
 John
 
 _
 realestate.com.au: the biggest address in property
 http://ninemsn.realestate.com.au
 
 
 
 --
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 
 
 End of Tutor Digest, Vol 27, Issue 4
 


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


Re: [Tutor] looking to hire a tutor

2006-04-24 Thread Carroll, Barry
Hello, Meenakshi,

 -Original Message-
 Date: Fri, 21 Apr 2006 19:44:57 -0700 (PDT)
 From: [EMAIL PROTECTED]
 Subject: [Tutor] looking to hire a tutor
 To: tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain;charset=iso-8859-1
 
 
   Hi,
 I apologize if this has been covered before.
 I am a postdoctoral research scientist learning Python programming.  I
 would like to hire a tutor who can spend 1-2 hours a week with me
going
 overand critiquing my programming.  I have looked for online Python
 programming classes (not free tutorials), which offer structure and
 feedback for a reasonable price.  To my surprise, I havent been very
 successful.
Working with online free tutorials hasnt been an ideal approach,
partly
 because I dont get feedback and partly because they dont completely
 meet my requirements.
 
  How would I go about hiring a python tutor who:
 
 Spends time critiquing my code and providing detailed feedback.
 Cares about good programming practices and is able to provide cogent
 explanations of programming principles.
 Can instruct me in the finer points of breaking a programming problem
down
 into constituent parts.
 Is well versed in Python.  It would be great (but not necessary) if
he/she
 were also familiar with data mining practices.
 
  I would be willing to pay 20-30$ an hour (or more depending on
instructor
 qualifications).
 
How do I go about doing this?  Any suggestions?
 
   Thanks
 Meenakshi 

I agree with the others that this list is an excellent place to learn
both Python and best programming practices.  However, the more personal,
one-on-one approach can be very useful.  

Have you checked the resources available there?  I'm thinking
particularly of the Computer Science department and the Student
Placement Service (or whatever they are called on your campus).  Most
placement services have a student employment service (web page, bulletin
board, etc) where students in need of part-time work can find job
listings.  Likewise, many computer science departments have a job board
or web page that does the same thing.  I'd be very surprised if UCLA
doesn't have something similar.

Good luck.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] locations

2006-04-21 Thread Carroll, Barry
Hi, Linda,

 -Original Message-
 I have a question. in the LIST M=
 [[1,1,1,1],
 [0,1,1,1],
 [1,1,0,1],
 [1,1,1,1]]
 If treat them as the locations of 16 points, I want to generate
another
 list
 N to hold the corresponding value for each point to its nearest 0.
 For example:
 the nearest 0 point to M[0][0] is M[1][0], so N[0][0]=1;
 M[0][1]'s nearest 0 is also at M[1][0], so N[0][1]=2;
 but N[0][3]=3 because 0 at M[2][2] is much nearer;
 N[1][0]=0 because the distance to itself is 0;
 N should be
 [[1,2,2,3],
 [0,1,1,2],
 [1,1,0,1],
 [2,2,1,2]]
 I am really very new to Python and have no idea how to write the code.
 Thanks!
 Linda

Basically, what you need to do is compare the coordinates of each cell
in N with the coordinates of each cell in M WHICH CONTAINS A 0.  Here is
my solution:

1. create the list N
   a. same structure as M
   b. set each cell to a huge integer value (will be replaced later)
2. make a third list, C, containing the coordinates of the 0 cells
in M 
3. walk the list N
   a. compare each cell's coordinates with each coordinate pair in C
  1. calculate the distance between the two coordinate pairs
   b. assign the smallest value obtained from 3.a. to this cell in
N.

Here are some code fragments to get you started.

To, create the coordinate list (C), walk the list M, looking for 0s:

C = []
for i in xrange(len(M)):
for j in xrange(len(M[i])):
if M[i][j] == 0:
C.append((i,j))

(This could probably be rewritten as a list comprehension, but I'm not
very good at them yet.)  =8^(

To find the distance between the coordinate pairs:

dist = abs(C[k][0] - i) + abs(C[k][1] - j)


To check for a minimum distance:

if dist  N[i][j]:
N[i][j] = dist


Does this give you enough information to write your solution?  If not,
just post more questions.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


[Tutor] FW: Splitting a number into even- and odd- numbered digits

2006-04-20 Thread Carroll, Barry
Greetings:

First of all, thanks to those who contributed suggestions.  

Unfortunately, my description was incomplete.
 
 I am writing a function that accepts a string of decimal digits,
 calculates a checksum and returns it as a single character string.
 The first step in the calculation is to split the input into two
strings:
 the even- and odd- numbered digits, respectively.  The least
significant
 digit is defined as odd.
 
I forgot to include two important requirements:

1. the length of the input string is arbitrary,
2. the order of the digits must be maintained.

I could not find a way to include these requirements in a single, simple
expression.  I decided to make an explicit test for string length, which
simplified matters. I came up with this:


 def odd_even(x):
... if len(x) % 2 == 1:
... return x[::2], x[1::2]
... else:
... return x[1::2], x[::2]

 odd_even('987654321')
('97531', '8642')

 odd_even('98765432')
('8642', '9753')
 


which is an improvement, I think, on my original.  
 
 
  s = '987654321'
  odd = ''
  for c in s[::-2]:
 ... odd = c + odd
 ...
  s = s[:-1]
  even = ''
  for c in s[::-2]:
 ... even = c + even
 ...
  odd
 '97531'
  even
 '8642'
 
 
Thanks again.  This is the most useful list I've ever found.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] Splitting a number into even- and odd- numbered digits

2006-04-20 Thread Carroll, Barry
Greetings:

First of all, thanks to those who contributed suggestions.  

Unfortunately, my description was incomplete.
 
 I am writing a function that accepts a string of decimal digits,
 calculates a checksum and returns it as a single character string.
 The first step in the calculation is to split the input into two
strings:
 the even- and odd- numbered digits, respectively.  The least
significant
 digit is defined as odd.
 
I forgot to include two important requirements:

1. the length of the input string is arbitrary,
2. the order of the digits must be maintained.

I could not find a way to include these requirements in a single, simple
expression.  I decided to make an explicit test for string length, which
simplified matters. I came up with this:


 def odd_even(x):
... if len(x) % 2 == 1:
... return x[::2], x[1::2]
... else:
... return x[1::2], x[::2]

 odd_even('987654321')
('97531', '8642')

 odd_even('98765432')
('8642', '9753')
 


which is an improvement, I think, on my original.  
 
 
  s = '987654321'
  odd = ''
  for c in s[::-2]:
 ... odd = c + odd
 ...
  s = s[:-1]
  even = ''
  for c in s[::-2]:
 ... even = c + even
 ...
  odd
 '97531'
  even
 '8642'
 
 
Thanks again.  This is the most useful list I've ever found.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] Splitting a number into even- and odd- numbered digits

2006-04-20 Thread Carroll, Barry
Greetings:

Unfortunately, my problem description was incomplete.  I forgot to
include two important requirements:

1. the length of the input string is arbitrary,
2. the order of the digits must be maintained.

I could not find a way to include these requirements in a single, simple
expression.  I decided to make an explicit test for string length, which
simplified matters. I came up with this:


 def odd_even(x):
... if len(x) % 2 == 1:
... return x[::2], x[1::2]
... else:
... return x[1::2], x[::2]

 odd_even('987654321')
('97531', '8642')

 odd_even('98765432')
('8642', '9753')
 


which is an improvement, I think, on my original.  
 
Thanks to those who provided suggestions.  This is the most useful list
I've ever found.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


[Tutor] Splitting a number into even- and odd- numbered digits

2006-04-19 Thread Carroll, Barry
Greetings:

I am writing a function that accepts a string of decimal digits, calculates a 
checksum and returns it as a single character string.  
The first step in the calculation is to split the input into two strings: the 
even- and odd- numbered digits, respectively.  The least significant digit is 
defined as odd.  

The following code fragment does the job but seems sort of brutish and 
inelegant to me:


 s = '987654321'
 odd = ''
 for c in s[::-2]:
... odd = c + odd
... 
 s = s[:-1]
 even = ''
 for c in s[::-2]:
... even = c + even
... 
 odd
'97531'
 even
'8642'


Is there a better (i.e. more Pythonic) way to do this?  

Thanks in advance for all your help.

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed


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


Re: [Tutor] Tutor Digest, Vol 26, Issue 55

2006-04-17 Thread Carroll, Barry
Payal:

 -Original Message-
 Date: Mon, 17 Apr 2006 13:24:31 -0400
 From: Payal Rathod [EMAIL PROTECTED]
 Subject: Re: [Tutor] functions in Python
 To: Steve Nelson [EMAIL PROTECTED]
 Cc: Python\[Tutor\] tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii
 
 On Mon, Apr 17, 2006 at 05:42:05PM +0100, Steve Nelson wrote:
  When you define a function, you are writing a block of code which
you
  can ask to perform a task.  The task may be simple, and not require
  any additional information, or it may be more complex and need
  information.
 
 What is the difference between,
 
  def f(x):
 ... return x
 ...
  f(4)
 4
 
  def f(x):
 ... print x
 ...
  f(4)
 4
 
 Both give same results. So, why return statement is needed?
 With warm regards,
 -Payal

Let's use your two functions named and see what we can do with them.  In
order to use both function definitions in the same interactive session,
I will name the first 'f1' and the second 'f2'.  


 def f1(x):
... return x
... 
 def f2(x): 
... print x
... 


Okay so far?  

Now, let's use each of these functions in a simple computation.  To
start, we'll just add two integers (called literals in programming
jargon),  


 4 + 4
8


The '+' operator takes two integers, adds them together and gives back
(returns) the result.  (Actually, the '+' operator can do more than
this, but this is enough for this example.)  

Now, we'll do the same calculation using f1 instead of the literals.   


 f1(4) + f1(4)
8


This worked as expected:  f1 sent back (returned) the value we gave it
(the argument 4) and the '+' operator did the addition.  
Questions?

Now, let's do the same calcuation once more, using f2 this time.


 f2(4) + f2(4)
4
4
Traceback (most recent call last):
  File input, line 1, in ?
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType' 


This time the operation failed. The f2 function did what we wrote it to
do: it printed the argument to the Standard Output device (also called
STDOUT), the interactive shell window in this case.  But, as the error
message indicates, it also RETURNED a value: in this case None, which
has the type NoneType.  The '+' operator then tried to add the two None
values together and failed.  

The examples above show that, although the output of f1 and f2 look the
same, it is actually different.  The 'f2' function displays its argument
for humans to read.  The 'f1' function makes the argument available for
other code to use.  That is the purpose of the 'return' statement: to
make the results of the function available to other code.  

It is important to remember that, in Python, EVERY function returns a
value.  If a 'return' statement is included in the function, the value
the result of the expression associated with the statement (in your
example, 4).  If no 'return' statement is included, the function returns
None.  

I hope this makes sense to you.  If not, keep asking questions.  

Best Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


Re: [Tutor] failing to learn python

2006-04-13 Thread Carroll, Barry
Greetings:

The discussion surrounding this topic (by Payal, Kent, Alan and others)
has been very interesting.  It illustrates the fact that software
engineering remains very much a craft. As with all crafts, is heavily
influenced by the preferences (style if you will) of the individual
artisan.  There are very few 'right or wrong' answers here.  

The tool that works well and feels comfortable when used is the one that
should be used.  When a new tool comes along, try it out.  If it makes
the work easier or faster, or the product better, then use it.  If not,
forget it.  The product is the goal, not the tool.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


 -Original Message-

snip

  For me, I don't know those specialized tools and I have chosen not
to
  learn them because I don't often need their capabilities and Python
can
 do
  what they do.
 
 I must admit I use a myriad of tools, including several text editors.
 Its one of the few areas where I disagree with Hunt  Thomas
 in the Pragmatic Programmer, they advocate choosing one editor
 and using it exclusively, I use emacs, vim, xedit and even ed on
 a daily basis (OK ed only once a month or so!) But I also use
 awk and sed weekly.

snip



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


Re: [Tutor] failing to learn python

2006-04-13 Thread Carroll, Barry
Alan:

As always, you make excellent points.  Actually, there isn't much on
which we disagree here, I think.  I did not mean that other engineering
disciplines necessarily employ less craftsmanship than does software.
On the contrary, excellent craftsmanship can be found in all branches of
engineering.  

One example will suffice: automotive engineering.  Manufacturer _
[insert your favorite here] produces vehicles which are among the most
finely crafted objects in the world.  On the other hand, __ [again,
take your pick) makes cars that exhibit horrible craftsmanship.  Both
are the products of automotive engineering, but the differences in
reliability, safety, performance and economy, not to mention beauty,
individuality and 'fine-ness' (a great term, IMHO), are obvious.

I could cite examples from any other discipline, though I might have to
spend some time in research; I'm a programmer, not an engineering
historian.  =8^)  

Anyway, my point was that no programming language is best in all cases
or for all people.  The preference of the engineer (craftsman, if you
will) matters.  

Best Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


 -Original Message-
 From: Alan Gauld [mailto:[EMAIL PROTECTED]
 Sent: Thursday, April 13, 2006 2:46 PM
 To: Carroll, Barry; tutor@python.org
 Subject: Re: [Tutor] failing to learn python
 
  has been very interesting.  It illustrates the fact that software
  engineering remains very much a craft. As with all crafts, is
heavily
  influenced by the preferences (style if you will) of the individual
  artisan.  There are very few 'right or wrong' answers here.
 
 Oops, you hit a hot button there. :-)
 
 RANT
 I don't think the multitude of styles or tools is any different to any
 other engineering discipline and certainly doesn't indicate any more
 craft status than the fact that different electrical engineers have
 different
 preferences of AVO meter type (analogue, digital, electronic, magnetic
 etc - and most use several). Choosing the right tool for the job is
just
 as much part of the skill of the engineer as much as the artisan.
 
 Where there may be a difference is that the engineer may specify the
 tools (and definitely the materials) during the design process, the
 artisan may choose the tools and materials in an ad-hoc manner
 as the work progresses. The engineer's goals are consistency and
 economy whereas the artisans goals are quality(*) and individuality.
 
 (*)Engineers strive for quality too, but a pre-determined measure
 of quality not the abstract concept of 'fine-ness' that craftsmen
 generally
 aim for.
 
 Software engineering, when practiced as engineering, is very little
 different to other branches of engineering, unfortunately it is, for
 various reasons, not often practiced as an engineering discipline
 but as a craft. But the SE label is applied regardless! As in other
 engineering disciplines it will take a large disaster with huge loss
 of human life(*) due to badly designed software to force the industry
 to adopt the kind of rigour demanded in other fields. It is entirely
 possible now, it's just not practiced!
 
 (*)And even then only when that loss of life is accompanied by
 correspondingly large insurance claims - or is that too cynical?
 We'll find out fairly soon I'm sure...
 
 /RANT
 
 Alan G.
 


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


[Tutor] Unittest not running all test cases

2006-04-07 Thread Carroll, Barry
Greetings:

I'm not certain this is the right forum for this question.  If not, please 
point me to the correct one.  

I am using the unittest module to test a package our team is writing.  I 
presently have three modules of test cases and a top level module to run the 
entire suite.  The hierarchy looks like this:

testsymgen  top level
testsymc39  61 test cases
testsym2544 test cases
testsymc93  0 test cases (so far)

testsymgen is a very simple file.  Here it is:


import unittest
from testsymc39 import *
from testsym25 import *
from testsymc93 import *


if __name__=='__main__':
unittest.main( )


Each of the sub-modules runs correctly, but when I run testsymgen, only 99 test 
cases are executed.  Can anyone tell me why this should happen.  Is there some 
sort of limit on the number of test cases that can be run in a batch?

Thanks in advance for your help.

Regards,

Barry



Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed


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


Re: [Tutor] Unittest not running all test cases

2006-04-07 Thread Carroll, Barry
Kent:

I just rechecked my class names, and there are no duplicates.  I was
careful to preface all of the classes in testsymc39 with 'C39...', and
used 'S25...' in testsym25.  Likewise, the classes in each module have
names that describe the type of data being tested, so names are unique
within each module as well.  

Is there a maximum length for class names?  Some of my class names are
pretty long, and only differ in the last few characters.  I'd be
surprised if that were the case in Python, but I'm short on other ideas.


Thanks for your help.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


 -Original Message-
 Date: Fri, 07 Apr 2006 15:42:15 -0400
 From: Kent Johnson [EMAIL PROTECTED]
 Subject: Re: [Tutor] Unittest not running all test cases
 Cc: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1; format=flowed
 

snip

 
 I don't think there is a limit like this. I wonder, do you have any
name
 collisions? For example if testsymc39 and testsym25 both contain class
 TestSym then only the second one will run because it will shadow the
 name from the first module.
 
 If this is the case you need a more sophisticated way of accumulating
 tests. You might want to look into using nose or one of the other
 test-discovery frameworks listed here:

http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy#UnitTestingTools
 
 Kent

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


Re: [Tutor] Unittest not running all test cases

2006-04-07 Thread Carroll, Barry
Kent:

 -Original Message-
 From: Kent Johnson [mailto:[EMAIL PROTECTED]
 Sent: Friday, April 07, 2006 3:59 PM
 To: Carroll, Barry
 Subject: Re: [Tutor] Unittest not running all test cases
 
 Carroll, Barry wrote:
  Kent:
 
  I just rechecked my class names, and there are no duplicates.  I was
  careful to preface all of the classes in testsymc39 with 'C39...',
and
  used 'S25...' in testsym25.  Likewise, the classes in each module
have
  names that describe the type of data being tested, so names are
unique
  within each module as well.
 
  Is there a maximum length for class names?  Some of my class names
are
  pretty long, and only differ in the last few characters.  I'd be
  surprised if that were the case in Python, but I'm short on other
ideas.
 
 I don't know of any limits on class names. They are just strings in
 dictionaries after all.
 
 Try running your tests in verbose mode, you should at least be able to
 figure out which ones aren't running. Try
 
  unittest.main(argv=['', '-v'])
 
 Kent
 

I tried your suggestion.  Lo and behold, all the test cases ran! So I
tried the terse mode again.  All the test cases STILL ran!  So the
problem has vanished without a trace.  Or a good reason.  

Having a problem just disappear like that bothers me almost more than
the original problem.  (It's also a little embarrassing.) =8^(  

Anyway, thanks for your help.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

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


Re: [Tutor] Logical Operators

2006-04-06 Thread Carroll, Barry
Greetings, Kaushal:

There are two topics to understand here:

   1. what TRUE and FALSE mean in Python, and
   2. how Python evaluates X and Y.

The tutorial Instant Python by Magnus Lie Hetland has good, short
descriptions of these two topics, so I'll borrow from it.  You can find
the document at:

   http://www.hetland.org/python/instant-python.php

1. All values in Python can be used as logic values. Some of the
more 
empty ones, like [], 0,  and None represent logical falsity,

while most other values (like [0], 1 or Hello, world)
represent 
logical truth.

In your examples, 5 and 1 are both considered 'TRUE', while 0, of
course, is considered FALSE.  

2. Now, logical expressions like a and b are evaluated like this: 
First, check if a is true. If it is not, then simply return it.
If 
it is, then simply return b (which will represent the truth
value 
of the expression.) The corresponding logic for a or b is: If a
is 
true, then return it. If it isn't, then return b.

Python evaluates your example expressions like this:

   a. Get the first sub-expression.x
  Get the value of x.  5
  Is 5 a TRUE value?Yes
  Since the operator is and, get the 
 second sub-expression.1
  Is 1 a TRUE value?Yes
  Return it.   1

   b. Get the first sub-expression.y
  Get the value of y.  0
  Is 0 a TRUE value? No
  Since the operator is and, 
 STOP and return the sub-expression.   0

Does this help?  Try this: change the 'and' operator in your examples to
'or'.  What would the return value be now?

   5 or 1=???

   0 or 1=???

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

 -Original Message-
 Date: Thu, 6 Apr 2006 16:06:11 +0530
 From: Kaushal Shriyan [EMAIL PROTECTED]
 Subject: [Tutor] Logical Operators
 To: tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1
 
 Hi
 
 I am referring to http://www.ibiblio.org/obp/thinkCSpy/chap04.htm
 about Logical operators
 
 I didnot understood
 
   x = 5
   x and 1
 1
   y = 0
   y and 1
 0
 
 How 5 and 1 means 1 and 0 and 1 means 0
 
 Thanks
 
 Regards
 
 Kaushal

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


Re: [Tutor] setdefault method

2006-03-28 Thread Carroll, Barry
Terry and Kent:

Thanks for your timely replies. I agree: its creator could have chosen a
more intuitive name for setdefault.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


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


[Tutor] setdefault method

2006-03-27 Thread Carroll, Barry
Greetings:

What is the purpose of the dictionary method setdefault(k[, x])?

For example assume the following dictionary:

 colors = {'green':(0,255,0), 'red':(255,0,0), 'blue':(0,0,255), 
 'white':(255,255,255), 'black':(0,0,0)}


Now, execute the statement:

 colors.setdefault('black')
(0, 0, 0)


I would expect that future references to colors, with no argument or a null 
argument, would return the value of colors['black'], e.g.:

 colors[]
(0, 0, 0)
 colors
(0, 0, 0)


or some similar syntax.  This is not the case, however. The actual behavior is:

 colors
{'blue': (0, 0, 255), 'black': (0, 0, 0), 'white': (255, 255, 255), 'green': 
(0, 255, 0), 'red': (255, 0, 0)}
 colors[]
  File input, line 1
colors[]
   ^
SyntaxError: invalid syntax


So, what then is the proper use of setdefault()?  And, if d.setdefault does not 
actually assign a default value for d, is there a way to do this?

As always, thanks in advance for your responses.  
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed


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


[Tutor] Data Type with Dictionary and List Behavior

2006-03-27 Thread Carroll, Barry
Greetings:

I have a function that computes the checksum of an integer, including or 
excluding digits in the computation based on the content of a mask string.  For 
example, 

cksum(123456789, '***...***')

will do its computation on 123789, masking out the three non-significant 
digits.  

My question concerns assigning the value of the mask string.  The class that 
defines the function also pre-defines several masks, say '*', 
'***...***', and '..***'.  The masks have names: 'all', 'first-last', 
'last'. Of these, 'all' is the most commonly used.  The user may select one of 
these masks, or may supply their own, arbitrary value. Further, the user can 
choose to add their value to the group of pre-defines, and reuse that value 
later in the session.  (The user-defined mask is not saved between sessions; no 
permanent storage is required.)

So far, this structure looks like a dictionary.  However, the user also wants 
to access the group of pre-defined masks as if they were elements of a list: 

 masks[0] returns '*' 
 masks[1] returns '***...***'

and so on.  To make matters even more complex, if the user does not specify a 
mask to use, the function should use the mask employed in the previous 
invocation, defaulting to masks[0] if this is the first invocation.  Finally, 
the user can set a mask as 'default', which essentially marks a mask as 'last 
used' without invoking the function.  

Is there a derived type or data structure in existence that implements these 
capabilities (in descending order of importance?

1. Access by name (dict)
2. Access by position (list)
3. Addition of new items  (dict, list)
4. Set a 'last used' item (??)
5. Set a 'default' item   (dict???)

Thanks in advance for your help.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed


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


Re: [Tutor] (no subject)

2006-03-02 Thread Carroll, Barry
Jacob,

What, exactly, do you mean by 'hack'?  The free dictionary wiktionary 

 http://en.wiktionary.org/wiki

gives the following definitions

hack
Verb
to hack (third-person singular simple present hacks, present participle
hacking, simple past hacked, past participle hacked)

1. To cough noisily. 
  This cold is awful. I can't stop hacking. 
2. To chop or cut down in a rough manner. 
  They hacked the brush down and made their way through the jungle. 
3. To withstand or put up with a difficult situation. 
  Can you hack it out here with no electricity or running water? 
4. To play hackeysack. 
5. to accomplish a difficult programming task. 
  She can hack like no one else and make the program work as
expected. 
6. To work with on an intimately technical level. 
  I'm currently hacking distributed garbage collection. 
7. To make a quick code change to patch a computer program. 
  I hacked in a fix for this bug, but we'll still have to do a real 
  fix later.. 
8. To gain unauthorized access to a computer system (e.g. website) by 
   manipulating code. (Widely called crack) 
9. to hack into; to gain illegal access to a computer network; a crack

   in computer parlance.

I'm going to guess that you aren't referring to any of the first four
definitions, so I'll bypass those.  

If your interest is in definition 5, 6, or 7, the short answer is, you
learn by doing.  Find a problem you want to solve, make a stab (hack, if
you will) at solving it using Python, and post questions here.  There
are many skilled people here who will be more than happy to help.  

If you're talking about definitions 8 or 9, you've come to the wrong
place.  No one here is interested in helping people break the law or
steal someone else's intellectual property.  

Go to 
   
http://catb.org/esr/faqs/hacker-howto.html#MS_hater

and read Eric's excellent essay on hacking.  If you're still interested,
come on back and we'll help you get started.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


 --
 
 Message: 3
 Date: Wed, 1 Mar 2006 18:36:26 -0600
 From: Jacob Simonovich [EMAIL PROTECTED]
 Subject: [Tutor] (no subject)
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 I want to learn how to hack but don't know where to start.  I have
been
 searching all over the internet to try to find things out but none of
the
 websites have helped me.  I would like to know the tools needed and
just a
 step by step process on how to do it using widows xp home edition.
 -- next part --
 An HTML attachment was scrubbed...
 URL:

http://mail.python.org/pipermail/tutor/attachments/20060301/680c01c3/att
ac
 hment.htm
 
 --


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


Re: [Tutor] nutshell review

2006-02-10 Thread Carroll, Barry
Greetings:

I have been programming in Python for about a year.  We use Python 2.3;
we haven't migrated to 2.4 because the Real-time OS we use in our test
systems doesn't yet support it.  I have the four O'Reilly 'standards' as
well (Nutshell, Learning, Cookbook, and Programming).  I use
Nutshell and Learning the most by far.  When I'm looking for a
detailed example of some implementation I will look through Cookbook
or Programming, but when I need to look up usage or syntax, or remind
myself how some feature works, I go to Nutshell first and then
Learning I use them both nearly every day.  I find that Nutshell
supports 2.3 very well.  Don't know about 2.4.  

Another book I have just found that may turn out useful is Python
Programming Patterns  by Thomas W. Christopher, published by Prentice
Hall PTR.  From the reviews I've read, It isn't really a 'design
patterns' book in the usual sense, but it contains good demonstrations
of applying Python to solve real problems.  I don't know for myself yet,
as I just ordered it yesterday.  We'll see.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

Never trust anything that can think for itself 
if you can't see where it keeps its brain 
JK Rowling
 
 -Original Message-
 --
 
 Message: 10
 Date: Fri, 10 Feb 2006 02:18:20 +
 From: nephish [EMAIL PROTECTED]
 Subject: [Tutor] nutshell review
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain
 
 lo there,
 i know this comes up from time to time. i am considering buying
'python
 in a nutshell'. All the reviews i have read for it are very good. But
it
 only covers up to python 2.2. i use 2.3 at work, and tinker with 2.4
at
 home. As good a reference as it is, is it too dated to be that good
 still ? i have 'Learning Python' and 'Programming Python'. Learning is
 awesome for me, Programming is a bit over my head.
   any suggestions?


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


[Tutor] Iterating over a string: index and value

2006-02-10 Thread Carroll, Barry








I seem to recall reading somewhere that it is possible to concurrently
generate the index and value of a strings characters in a single for
statement. Is this true or did imagine it?



Here is the scenario:



Given an ASCII string of arbitrary length and content, generate
a sequence of tuples whose elements are: 

 the index of each character in the string,
and 

 data based on the ordinal value of the
character in the ASCII collating sequence. 



The brute force way to do this is 





tuplseq = ()

for idx in mystr:

 char = mystr[idx]

 ordval = ord(char)

 data = "">

 tuplseq.append(idx, data)





Is there a way to generate the character (or its ord value)
along with the index? E.g.:





tuplseq = ()

for idx ordval in X:

 tuplseq.append(idx, process(ordval))





Where X is some construct using mystr.



BTW, this is for internal software for our test group.




Thanks in advance for your help. 



Barry

[EMAIL PROTECTED]

541-302-1107



Never trust anything that can think for itself 

if you can't see where it keeps its brain 

JK Rowling










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


Re: [Tutor] Iterating over a string: index and value

2006-02-10 Thread Carroll, Barry
Adam,

That is super!  Just what I was looking for.  Thanks!

And whaddya know?  There it is in the Python 2.3 Library reference, section 2.1!

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

Never trust anything that can think for itself 
if you can't see where it keeps its brain 
JK Rowling
 

From: Adam [mailto:[EMAIL PROTECTED] 
Sent: Friday, February 10, 2006 1:42 PM
To: Carroll, Barry
Cc: tutor@python.org
Subject: Re: [Tutor] Iterating over a string: index and value

Here's a list comprehension which does it:
 print [(i, ord(v)) for i, v in enumerate(abcdefg)]
[(0, 97), (1, 98), (2, 99), (3, 100), (4, 101), (5, 102), (6, 103)]

and a for loop:

 for i, v in enumerate(abcdefg):
... tuplseq.append((i, ord(v)))
...
 tuplseq
[(0, 97), (1, 98), (2, 99), (3, 100), (4, 101), (5, 102), (6, 103)]

how's that?

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


[Tutor] More Doubt with classes

2006-01-24 Thread Carroll, Barry
Greetings:

I took Edgar's script and added some more people.  Here is the script as
I ran it.  


class Person:
'''Represents a person.'''
population = 0

def __init__(self, name):
'''Initializes the person's data.'''
self.name = name
print '(Initializing %s)' % self.name

# When this person is created, he/she
# adds to the population
Person.population += 1

def __del__(self):
'''I am dying.'''
print '%s says bye.' % self.name
Person.population -= 1

if Person.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' % Person.population


def sayHi(self):
'''Greeting by the person.
Really, that's all it does.'''
print 'Hi, my name is %s.' % self.name

def howMany(self):
'''Prints the current population.'''
print self.name + ' says: ',
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' % Person.population

swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()

kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()

butch = Person('Butch Cassidy')
butch.sayHi()
butch.howMany()

gerald = Person('Gerald McBoingBoing')
gerald.sayHi()
gerald.howMany()

tony = Person('Tony Danza')
tony.sayHi()
tony.howMany()

swaroop.howMany()
kalam.howMany()
butch.howMany()
gerald.howMany()
tony.howMany()


When I ran it on my system (Windows XP Professional), I got an error as
the script was cleaning up.  Here is the output.  


(Initializing Swaroop)
Hi, my name is Swaroop.
Swaroop says:  I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
Abdul Kalam says:  We have 2 persons here.
(Initializing Butch Cassidy)
Hi, my name is Butch Cassidy.
Butch Cassidy says:  We have 3 persons here.
(Initializing Gerald McBoingBoing)
Hi, my name is Gerald McBoingBoing.
Gerald McBoingBoing says:  We have 4 persons here.
(Initializing Tony Danza)
Hi, my name is Tony Danza.
Tony Danza says:  We have 5 persons here.
Swaroop says:  We have 5 persons here.
Abdul Kalam says:  We have 5 persons here.
Butch Cassidy says:  We have 5 persons here.
Gerald McBoingBoing says:  We have 5 persons here.
Tony Danza says:  We have 5 persons here.
Butch Cassidy says bye.
There are still 4 people left.
Abdul Kalam says bye.
There are still 3 people left.
Gerald McBoingBoing says bye.
There are still 2 people left.
Swaroop says bye.
There are still 1 people left.
Tony Danza says bye.
Exception exceptions.AttributeError: 'NoneType' object has no attribute
'population' in bound method Person.__del__ of __main__.Person
instance at 0x00909BC0 ignored


Surprisingly, when I comment out the statements referencing the 'tony'
instance, the error goes away.


(Initializing Swaroop)
Hi, my name is Swaroop.
Swaroop says:  I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
Abdul Kalam says:  We have 2 persons here.
(Initializing Butch Cassidy)
Hi, my name is Butch Cassidy.
Butch Cassidy says:  We have 3 persons here.
(Initializing Gerald McBoingBoing)
Hi, my name is Gerald McBoingBoing.
Gerald McBoingBoing says:  We have 4 persons here.
Swaroop says:  We have 4 persons here.
Abdul Kalam says:  We have 4 persons here.
Butch Cassidy says:  We have 4 persons here.
Gerald McBoingBoing says:  We have 4 persons here.
Butch Cassidy says bye.
There are still 3 people left.
Abdul Kalam says bye.
There are still 2 people left.
Gerald McBoingBoing says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.


I can't figure out what the difference is.  Does anyone have an idea?  

Regards,
 
Barry

PS Sorry for the long post.  I didn't want to leave anything out that
might contain a clue.
BGC
 
 -Original Message-
 Date: Fri, 20 Jan 2006 20:20:29 -0600
 From: Edgar Antonio Rodr?guez Velazco
[EMAIL PROTECTED]
 Subject: [Tutor] Doubt with classes
 To: tutor@python.org
 Message-ID:
   [EMAIL PROTECTED]
 Content-Type: text/plain; charset=iso-8859-1
 
 Hi everybody,
 I've been reading the chapter of classes of Byte of Python by Swaroop.
 There's an example with classes (11.4) that is below:
 
 #
 snip 
 ##
 
 I have runned the script in both Linux and Windows and got the same
 result.
 Could you explain me what's wrong with this???
 
 --
 Edgar A. Rodriguez
 -- next part --
 An HTML attachment was scrubbed...
 URL:

http://mail.python.org/pipermail/tutor/attachments/20060120/c527657b/att
ac
 hment.htm


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


[Tutor] Scope Problem with Files

2005-12-14 Thread Carroll, Barry
Greetings:

I am implementing a (crude but useful) debug facility in my test system client 
software.  Basically, I test the value of a global Boolean. It True, I write 
pertinent data to a text file.  I want to do this in multiple functions in a 
module.  Rather than open and close the file each time I write, I want to open 
the file once at the start of process and close it at the end.  Here are 
excerpts from the module.  

##
import socket
import struct
import time

# initialize the debug flag
DEBUG = True
. . .

dbgf = None # File object and path for saving debug output
dbgfname = debug.txt

def snd_cmd(sock,cmd):

. . .

while remainlen  0:
if remainlen  MTU:
pktstp = pktstrt + MTU
else:
pktstp = pktlen
pktflags |= EOD

pkthdr = struct.pack('@2BH',pktflags,seq,pktlen)
sndpkt = pkthdr+cmd[pktstrt:pktstp]

if DEBUG:
dbgf.write(command:  + cmd + \n)
dbgf.write(flags: 0x%X, seq: %u, len: %u\n % (pktflags, seq, 
pktlen))

sock.sendto(sndpkt,addr)

pktstrt += MTU
remainlen -= MTU
pktflags = pktflags  ~SOD
seq = (seq + 1) % 256

. . .

def recv_resp(sock):
response = ''
try:
response = sock.recv(MTU)
except socket.timeout:
errtupl = (ERROR, 'Server did not respond')
return (errtupl, response)

. . .

if DEBUG:
dbgf.write(response:  + response + \n)
dbgf.write(flags: 0x%X, seq: %u, len: %u\n % (flags, retseq, dlen))

. . .

return (errtupl, response)

def do_cmd(cmd):

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(timetowait)
retriesleft = retries
if DEBUG:
dbgf = open(dbgfname,mode=a)
dbgf.write(\n+str(time.localtime())+\n)

while retriesleft  0:
snd_cmd(sock, cmd)
recvtupl = recv_resp(sock)
if recvtupl[0][0] != ERROR:
break
retriesleft -= 1

if DEBUG:
dbgf.close()

sock.close( )
return recvtupl
##

When I run this code, I get the following error message:


A problem occurred in a Python script. Here is the sequence of function calls 
leading up to the error, in the order they occurred.
/var/www/cgi-bin/pagen.py  
   76 # function.  Check the returned error code for success.  
   77 cmdtosnd = state['s']['getcmd']
   *78 (errorcode, errorstr), platformstate['itype']['curstate'] = 
do_cmd(cmdtosnd)
   79 if errorcode == 0:
   80 cmdtosnd = state['t']['getcmd']

. . .

/var/www/cgi-bin/Client.py in do_cmd(cmd='cmd') 
  160 
  161 while retriesleft  0:
  *162 snd_cmd(sock, cmd)
  163 recvtupl = recv_resp(sock)
  164 if recvtupl[0][0] != IIPSRVERROR:
 
global snd_cmd = function snd_cmd, sock = socket._socketobject object, cmd 
= 'cmd' 


 /var/www/cgi-bin/Client.py in snd_cmd(sock=socket._socketobject object, 
cmd='cmd') 
   65 
   66 if DEBUG:
   *67 dbgf.write(command:  + cmd + \n)
   69 
 
global dbgf = None, dbgf.write undefined, cmd = 'cmd' 


AttributeError: 'NoneType' object has no attribute 'write' 
  args = ('NoneType' object has no attribute 'write',)


dbgf is declared at the top of the module.  It is opened and closed in do_cmd.  
I attempt to write to it in snd_cmd and recv_resp, both of which are called by 
do_cmd.  Since dbgf is global to all of these functions, I expected its value 
(the open file object) to persist.  I don't understand why it didn't.  I expect 
I have misunderstood Python's scoping rules.  Can someone enlighten me?

Thanks and enjoy the holidays.  

BGC

Never trust anything that can think for itself 
if you can't see where it keeps its brain 
JK Rowling
 


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


Re: [Tutor] Scope Problem with Files

2005-12-14 Thread Carroll, Barry
Thanks, Bob.  I figured it was something simple.  

BGC


Never trust anything that can think for itself 
if you can't see where it keeps its brain 
JK Rowling
 
snip

 
  sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  sock.settimeout(timetowait)
  retriesleft = retries
  if DEBUG:
  dbgf = open(dbgfname,mode=a)
 
 dbgf is a local variable. If you want to reassign to the global you
must
 add
 global dbgf
 to the function
 
  dbgf.write(\n+str(time.localtime())+\n)
 


snip



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


Re: [Tutor] Newbie question

2005-11-22 Thread Carroll, Barry
Hello, Erik,

Welcome to the maillist.  

From your description, is sounds like you are attempting to run the
scripts by double clicking on them from Windows Explorer, or from the
Run dialog on the Start menu.  Both these methods open a command window
in a new process, run the script, then terminate the process as soon as
the script ends.  

Try opening a command window manually, changing to the directory where
the script resides, and running the program from there.  That way the
window will remain after the script has finished, and you can see the
results.  

One way to get to a command prompt window is to use the XP start menu:

 Start-All Programs-Accessories-Command Prompt

HTH

BGC

==
 Date: Tue, 22 Nov 2005 08:03:08 -0600
 From: Douglass, Erik [EMAIL PROTECTED]
 Subject: [Tutor] Newbie question
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii
 
 I am trying to follow some online first timer tutorials, and I am
 writing the practice scripts in notepad (only w32 at work :-()..   I
 save the script with a .py extension, and when I run it it opens for a
 brief moment in a command prompt then closes before I even have a
chance
 to see what it says.  This may seem trivial, but Python also happens
to
 be my first language so this is all new to me.Using Python 2.4.2
 
 
 
 Thanks for any help.
 
 
 
 Erik
 

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


[Tutor] File extension for CGI scripts written in Python

2005-11-11 Thread Carroll, Barry
Greetings:

I am writing the first of the handler routines for my test system web
interface.  They will be Common Gateway Interface (CGI) scripts written in
Python.  In the literature I have studied, I have seen the extensions .cgi
and .py applied to such files.  Is one preferred over the other, or is it a
matter of personal preference?

As always, thanks for taking the time to respond.  

Barry


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


Re: [Tutor] Namespace Problem

2005-11-07 Thread Carroll, Barry
Bob:

Yes I did mean 'import' and yes there is more to the function.  Here is the
entire program.  


import socket
import struct

# data packet flags
ABC = 1
DEF = 2
GHI = 4
JKL = 8
seq = 0

buf = 8192 # This is the max_packet_size defined in the SocketServer module
addr = ('localhost', 12345) # Host and port used by the server

def do_stuff(in_str):
hdr = struct.pack('@2BH',ABC|DEF,seq,len(in_str))
newstr = hdr+in_str
if(sock.sendto(newstr,addr)):
response = sock.recv(buf)
flags, retseq, dlen = struct.unpack('@2BH', response[:4])
print flags: 0x%X, retseq: %u, dlen: %u % (flags, retseq, dlen)
response = response[4:]
rsphdr=eval(response[:response.find(')')+1])
response = response[response.find(')')+2:]
resptupl = (rsphdr, response)
seq += 1
return resptupl

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

def_msg = ===Enter message to send to server===;
print \n,def_msg

# Send messages
while (1):
data = raw_input(' ')
if not data:
break
else:
print Sending message ',data,'
ret_data = do_stuff(data)
print Got back: , ret_data

sock.close( )


Here is a trace of program execution.  


===Enter message to send to server===
 send some data
Sending message ' send some data '
Traceback (most recent call last):
  File ./bgctest.py, line 40, in ?
ret_data = do_stuff(data)
  File ./bgctest.py, line 15, in do_stuff
hdr = struct.pack('@2BH',ABC|DEF,seq,len(in_str))
UnboundLocalError: local variable 'seq' referenced before
assignment

I can't figure it out.  

Barry

 -Original Message-
 From: bob [mailto:[EMAIL PROTECTED]
 Sent: Friday, November 04, 2005 6:32 PM
 To: Carroll, Barry; 'tutor@python.org'
 Cc: Carroll, Barry
 Subject: Re: [Tutor] Namespace Problem
 
 At 05:47 PM 11/4/2005, Carroll, Barry wrote:
 I have a function that makes use of several global variables:
 
 ##
 Include struct
 
 Did you mean import?
 
 ABC = 1
 DEF = 2
 xyz = 0
 def do_stuff(in_str):
  hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str))
  newstr = hdr+in_str
 
 Works find for me. Is there anything else you are not showing us?
 
snip


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


Re: [Tutor] Namespace Problem

2005-11-07 Thread Carroll, Barry
Kent:

Thank you for the explanation.  This is a subtlety of Python that has
tripped me up before.  

Barry

 Date: Mon, 07 Nov 2005 16:26:39 -0500
 From: Kent Johnson [EMAIL PROTECTED]
 Subject: Re: [Tutor] Namespace Problem
 Cc: 'tutor@python.org' tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1; format=flowed
 

snip

  seq += 1
 
 The above statement binds a value to the name 'seq'. If a name is bound
 anywhere within a block,  the compiler treats it as a local name and it
 will not be looked up in the global namespace. When the struct.pack() line
 is executed, seq is not bound in the local namespace and you get an error.
 The solution is to include 'global seq' in do_stuff(); this tells the
 compiler that seq should always be treated as a global name even though it
 is bound in the current block.
 
 This a little bit subtle because you are using seq += 1. Still this is
 binding a new value to seq and you need to declare it global.
 
 Kent
 

snip


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


[Tutor] Namespace Problem

2005-11-04 Thread Carroll, Barry
I have a function that makes use of several global variables:

##
Include struct

ABC = 1
DEF = 2

xyz = 0
# Other variables 

def do_stuff(in_str):
hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str))
newstr = hdr+in_str

# rest of code snipped
##

When I run the program containing this code I get this error:


Traceback (most recent call last):
  File sample.py, line 43, in ?
ret_data = do_stuff(data)
  File sample.py, line 17, in do_stuff
hdr = struct.pack('@2BH', ABC|DEF,xyz,len(in_str))
UnboundLocalError: local variable 'xyz' referenced before assignment


The error goes away if I include a 'global' statement at the top of the
function:

##
def do_stuff(in_str):
global xyz
hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str))
##

Why does the interpreter choke on xyz and not on ABC or DEF?

Barry

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


Re: [Tutor] File IO

2005-11-03 Thread Carroll, Barry
Mike:

I see two issues here:

First, do you really want to apply your field selection logic to ALL the
lines in each file?  It seems to me that the first five lines of the file
are header information that you want to ignore.  If so, and if all the files
have the same format, you can use a loop to throw away the first five lines
of the input and start collecting your data on line #6. Another possibility
would be to check each line and throw it away if fields[1] cannot be
converted into a number.  

Second, your current logic is assembling the data from each line into a
string.  Is that what you want?  I'm guessing you want to extract the three
fields into a three element list.  If so, you need to turn the three strings
(fields[1], fields[2] and fields[3]) back into list elements.  Do this by
placing them in square brackets separated by commas:

 data = [fields[1], fields[2], fields[7]]



 --
 Date: Thu, 3 Nov 2005 22:10:02 - (GMT)
 From: Mike Haft [EMAIL PROTECTED]
 Subject: Re: [Tutor] File IO
 To: bob [EMAIL PROTECTED]
 Cc: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain;charset=iso-8859-1
 
 I did that and got this:
 
 Here goes
 Enter filename:
 Name:LAU73M.MET
 Line too short Monthly Weather Data, LAU73M.MET, converted from:
 
 Line too short BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR
 01/01/1973-31/12/1973
 
 Line too short
 **
 
 ['DEWPCALCULATEDHUMID', 'RAINAVTEMPEVAPW', '22.50.311.9', '16.11.818.1',
 '16.44.836.8', '19.55.945.5', '36.113.283.0', '36.016.9105.7',
 '37.718.298.6', '29.318.297.9', '27.014.858.7', '57.67.631.3',
 '23.43.919.1', '14.00.712.5']
 might work
 
 Its worth pointing out that there are more than eight fields in my actual
 files, I'm using a shorter version just to test stuff on. Actual fields
 are:
 
 MONTHRAIN  AVTEMP S10RAD  SUNWIND   EVAPW
 EVAPG   EVAPS   HUMID VAPDEWP
 
 There are 13 so I'll have a play with that for the moment.
 
 Thanks for the help
 
 Mike
 
 
  At 01:34 PM 11/3/2005, Michael Haft wrote:
 Hello,
   I tried the following code:
 
 def readSOMNETM(inputName):
  input = open(inputName, r)
  result = []
  for line in input:
  fields = line.split()
 
 # add this; it will show you what line(s) have less than 8
  fields
 if len(fields)  8:
 print Line too short, line
 continue
 
  data = fields[1] + fields[2] + fields[7]
  result.append(data)
  input.close()

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


Re: [Tutor] Tutorials on the web

2005-11-02 Thread Carroll, Barry
Johan:

The link is helpful indeed.  In five minutes I found six tutorials I want to
check out for my current project.  Thank you.  

Barry

 Message: 5
 Date: Wed, 02 Nov 2005 11:02:45 +0200
 From: Johan Geldenhuys [EMAIL PROTECTED]
 Subject: [Tutor] Tutorials on the web
 To: Tutor tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=ISO-8859-1; format=flowed
 
 Here is a link to a range of tutorials:
 http://www.awaretek.com/tutorials.html
 
 Maybe this wil help some people to know where to find a good tutorial
 ona specific subject.
 
 Johan

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


Re: [Tutor] Talking to UDPServer

2005-11-01 Thread Carroll, Barry








Johan, et al:



Yes, that is exactly what I want. I
need to write a program that communicates with an existing server, using the
UDP protocol. This is my first time writing such a program, and I need
help getting started. 



Thanks again. 



Barry













From: Johan Geldenhuys [mailto:[EMAIL PROTECTED] 
Sent: Monday, October 31, 2005
5:35 PM
To: Carroll, Barry
Cc: 'tutor@python.org'
Subject: Re: [Tutor] Talking to
UDPServer





Maybe you could tel us if you already have the server
listening on the socket that you expec connections on? If, yes, do you want an
example of how a client connects to that socket?

Johan

Carroll, Barry wrote: 

Greetings:



I am writing a browser-based interface to a server
program which extends SocketServer.UDPServer. The program listens on a
well-known socket, receiving commands, verifying them and using their content
to drive our test hardware, returning status to the client. The current
client interface is a command line interface that allows the user to type in a
command and sends it to the server, receives the status response and displays
it for the user. My job is to duplicate the client functionality in a set
of web pages. 



My problem is that, while I can find documentation on
UDPServer, I cannot find anything on how a remote client talks to the
server. How is this done in Python? Can someone point me to a
how-to, tutorial or the like? 



Thanks in advance.



Barry











___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor 






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


Re: [Tutor] while/if/elif/else loops

2005-11-01 Thread Carroll, Barry
Greetings:

I tried running first just the expression, then the statement.  Here are the
results:

 tosses = 1000
 tosses
False
 while tosses = 1000:
  File stdin, line 1
while tosses = 1000:
 ^
SyntaxError: invalid syntax


Coming from the C/C++ world as I do,  I was a little surprised by the error.
C accepts the assignment expression and uses the result as the while
condition, so that the loop never executes.  Nice to see that Python avoids
that trap.

Regards,

Barry

 Date: Mon, 31 Oct 2005 22:10:34 -0500
 From: R. Alan Monroe [EMAIL PROTECTED]
 Subject: Re: [Tutor] while/if/elif/else loops
 To: tutor@python.org
 Message-ID: [EMAIL PROTECTED]
 Content-Type: text/plain; charset=us-ascii
 
 
  while tosses = 1000:
 
 I didn't run the program, but this immediately caught my eye as
 looking kind of suspect. Was it a typo? Most programs usually
 have a need for comparisons of equal, or greater/less, but it's really
 rare to need both combined in one statement...
 
 Also if you really _do_ want to check two things being equal, don't
 forget to use double equal ( == ).
 
 Alan
 

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


Re: [Tutor] Talking to UDPServer

2005-11-01 Thread Carroll, Barry
Kent, Johan:

Thank you.  These examples will be a great help.  I also found some links
via Google (I always forget that resource for some reason).  I have enough
to go forward, now.  

Barry


 -Original Message-
 From: Johan Geldenhuys [mailto:[EMAIL PROTECTED]
 Sent: Tuesday, November 01, 2005 11:39 AM
 To: Kent Johnson
 Cc: Carroll, Barry; 'tutor@python.org'
 Subject: Re: [Tutor] Talking to UDPServer
 
 I've done some network programming mostly with TCP and I don't think
 that the way the client connects to the server is a lot different (if
 any), The only difference is when you must decide the protcol family.
 socket.SOCK_DGRAM will be for UDP and socket.SOCK_STREAM will be for
 TCP. After this, the client can connect the same way.
 
 Here is a simpler sample than the one Kent gave:
 
 
 from socket import *
 
 HOST = 'localhost'
 PORT = 3001
 BUFSIZ = 1024
 ADDR = (HOST, PORT)
 
 tcpCliSock = socket(AF_INET, SOCK_STREAM) # change here for UDP
 tcpCliSock.connect(ADDR)
 
 while 1:
 data = raw_input('') # Enter text to be transmitted to the server.
 if not data: break
 tcpClisock.send(data)
 data = tcpCliSock.recv(BUFSIZ)
 if not data: break
 print data
 
 tcpCliSock.close()
 
 HTH,
 
 Johan
 
 
 Kent Johnson wrote:
 
  Carroll, Barry wrote:
 
  Yes, that is exactly what I want.  I need to write a program that
  communicates with an existing server, using the UDP protocol.  This
  is my first time writing such a program, and I need help getting
  started.
 
 
  Here is an example from Python Network Programming, by John Goerzen.
  It opens a UDP port, sends a message, then echoes any received text to
  the console. There is no higher-level support built in to Python, you
  just open a datagram socket and push data out. Google for Python udp
  for more examples.
 
  Kent
 
  #!/usr/bin/env python
  # UDP Example - Chapter 2
 
  import socket, sys, time
 
  host = sys.argv[1]
  textport = sys.argv[2]
 
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  try:
 port = int(textport)
  except ValueError:
 # That didn't work.  Look it up instread.
 port = socket.getservbyname(textport, 'udp')
 
  s.connect((host, port))
  print Enter data to transmit: 
  data = sys.stdin.readline().strip()
  s.sendall(data)
  s.shutdown(1)
  print Looking for replies; press Ctrl-C or Ctrl-Break to stop.
  while 1:
 buf = s.recv(2048)
 if not len(buf):
 break
 print Received: %s % buf
 
 

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


[Tutor] Talking to UDPServer

2005-10-31 Thread Carroll, Barry








Greetings:



I am writing a browser-based interface to a server program
which extends SocketServer.UDPServer. The program listens on a well-known
socket, receiving commands, verifying them and using their content to drive our
test hardware, returning status to the client. The current client
interface is a command line interface that allows the user to type in a command
and sends it to the server, receives the status response and displays it for
the user. My job is to duplicate the client functionality in a set of web
pages. 



My problem is that, while I can find documentation on
UDPServer, I cannot find anything on how a remote client talks to the
server. How is this done in Python? Can someone point me to a
how-to, tutorial or the like? 



Thanks in advance.



Barry












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


[Tutor] Recursion and List Comprehensions

2005-10-28 Thread Carroll, Barry








Greetings:



I'm trying to improve my programming and Python
skills. To that end I have implemented a word jumble program as a
recursive function: given a string of arbitrary length, return a list of
all permutations of the string each character exactly once. In other
words:



 permute('t') = ['t'],


 permute('te') = ['te',
'et'], 

 permute('tes') = ['tes',
'tse', 'ets', 'est', 'ste', 'set'],


 etc. 



Here is my first try, the brute force method:



def permute1 (word):

 retList=[]

 if len(word) ==
1:


# There is only one possible permutation


retList.append(word)

 else:


# Return a list of all permutations using all characters


for pos in range(len(word)):


# First isolate the char that goes in the first spot


firstChar=word[pos]


# Then assemble the rest of the word


restWord=word[0:pos]+word[pos+1:len(word)]


# Get the permutations of the rest of the word 

 restList=permute1(restWord)


# Now, tack the first char onto each word in the list


for item in restList:


newWord=firstChar+item


# and add it to the output


retList.append(newWord)

 return retList



My second version combines statements to remove intermediate
variables: 



def permute2 (word):

 retList=[]

 if len(word) ==
1:


# There is only one possible permutation


retList.append(word)

 else:


# Return a list of all permutations using all characters


for pos in range(len(word)):


# Get the
permutations of the rest of the word 


permuteList=permute2(word[0:pos]+word[pos+1:len(word)])


# Now, tack the first char onto each word in the list


# and add it to the output


for item in permuteList:


retList.append(word[pos]+item)

 return retList



I'm told that I can collapse the logic further by
using a list comprehension, something like:



def permute3 (word):

 retList=[]

 if len(word) ==
1:


# There is only one possible permutation


retList.append(word)

 else:


# Return a list of all permutations using all characters


retlist = [a list comprehension that calls permute3]

 return retList



Unfortunately, I don't understand how list
comprehensions work and how to implement them. Can someone point me in
the right direction, please. 



Thanks in advance for your help. I'm learning a
lot by following this list.



Barry








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


Re: [Tutor] Recursion and List Comprehensions

2005-10-28 Thread Carroll, Barry
Alan et al:

After reading the topic you recommended I tried rewriting my permute
function as follows: 

##
def permute3 (word):
if len(word) == 1:
# There is only one possible permutation
retList=[word]
else:
# Return a list of all permutations using all characters
for pos in range(len(word)):
# Get the permutations of the rest of the word, 
# tack the first char onto each word in the list
# and add it to the output
retList=[word[pos]+item for item in permute3(word[0:pos]+
word[pos+1:])]
return retList
##

The list comprehension looks correct to my eyes.  However, when I run the
function I always get back a one element list.  For example


 permute.permute3('test')
['tset']


By contrast my previous version returns the correct output:


 permute.permute2('test')
['test', 'tets', 'tset', 'tste', 'ttes', 'ttse', 'etst', 'etts', 'estt',
'estt', 'etts', 'etst', 'stet', 'stte', 'sett', 'sett', 'stte', 'stet',
'ttes', 'ttse', 'tets', 'test', 'tste', 'tset']



Note that permute3 returns the last element of the list returned by
permute2.  This is true in general:  permute3 always returns the last
element generated by permute2.  

I think there is a problem with the assignment (retList= ...), but the
append operator (retList+= ...) causes this error:


 permute.permute3('tests')
Traceback (most recent call last):
  File stdin, line 1, in ?
  File permute.py, line 50, in permute3
retList+=[word[pos]+item for item in
permute3(word[0:pos]+word[pos+1:len(word)])]
UnboundLocalError: local variable 'retList' referenced before assignment


Ideas, anyone?  

Thanks again.  

Barry

-Original Message-
From: Alan Gauld [mailto:[EMAIL PROTECTED] 
Sent: Friday, October 28, 2005 3:01 PM
To: Carroll, Barry; tutor@python.org
Subject: Re: [Tutor] Recursion and List Comprehensions

def permute3 (word):
retList=[]
if len(word) == 1:
# There is only one possible permutation
retList.append(word)
else:
# Return a list of all permutations using all characters
retlist = [a list comprehension that calls permute3]

retlist += [ word[0] + item , item  for item in permute3(word[1:]) ]

return retList

 Unfortunately, I don't understand how list comprehensions work and how to
 implement them.  Can someone point me in the right direction, please.

Take a look in the functional programming topic of my tutor for an
explanation of comprehensions. The code above is untested but
should be close I think. It tries to produce a list of each item in the
permutation list plus the same item with the first char added.
However one point to consider is whether order matters.

Take 'te' as your word
t, te, e

is what the above gives but you could argue that 'et' is also a permutation,
if so, my comprehension doesn't give that. And its quite hard to generate
(ie I can't think of an easy way! :-)

HTH,

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



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


[Tutor] Code Readability (was: Recursion and List Comprehensions)

2005-10-28 Thread Carroll, Barry
Kent Johnson [EMAIL PROTECTED] wrote:

snip

PS Don't get too crazy about eliminating intermediate variables, they can
make the code more readable.

Kent

I agree.  When writing for keeps (i.e. production code) I prefer clarity and
ease of maintenance over 'elegance' or 'trickiness'.  This exercise is
intended, in part, to sharpen my understanding of Python idioms.  If I can
write highly idiomatic code that works,  chances are better that I will be
able to decipher it when I come across it elsewhere.  

Barry


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


Re: [Tutor] Recursion and List Comprehensions

2005-10-28 Thread Carroll, Barry
Greetings:

Andrei gave me the answer I needed:
snip
Let's fix that by extending the list instead:

   retList.extend([word[pos] + item for item in permuteList])

snip

The extend method solved the problem.  

Barry

-Original Message-
From: Carroll, Barry 
Sent: Friday, October 28, 2005 5:49 PM
To: 'Alan Gauld'; Carroll, Barry; tutor@python.org
Subject: RE: [Tutor] Recursion and List Comprehensions

Alan et al:

After reading the topic you recommended I tried rewriting my permute
function as follows: 


snip


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


Re: [Tutor] Recursion and List Comprehensions

2005-10-28 Thread Carroll, Barry


Andrei:

Date: Sat, 29 Oct 2005 01:13:45 +0200
From: Andrei [EMAIL PROTECTED]
Subject: Re: [Tutor] Recursion and List Comprehensions
To: tutor@python.org
Message-ID: [EMAIL PROTECTED]
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

snip

There's nothing magic about writing a list comprehension - they're just 
an inside-out way of writing a for-loop :).

snip

That was just what I needed.  Your description was clear and easy to follow.


4 lines of perfectly readable code have become 4 lines of perfectly 
unreadable list comprehension. Any reader interested in understanding 
this will have to perform the exact opposite set of operations to go 
back to the original code.

snip

I couldn't agree more.  This was a learning exercise for me.  In a real
program (one that I or someone else would have to maintain a year or so from
now) I would have stopped with the first version, with all the loops and
intermediate variables left in.  

Thanks for your help.  I really enjoy this list.  

Barry


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