From goodpotatoes at yahoo.com  Thu Apr  1 00:11:35 2010
From: goodpotatoes at yahoo.com (GoodPotatoes)
Date: Wed, 31 Mar 2010 15:11:35 -0700 (PDT)
Subject: [Tutor]  Open a WebPage with Forms Authentication
In-Reply-To: <t2r2b9003cf1003311333h445c0c34m1474b983d5f35f84@mail.gmail.com>
References: <t2r2b9003cf1003311333h445c0c34m1474b983d5f35f84@mail.gmail.com>
Message-ID: <891749.98302.qm@web51701.mail.re2.yahoo.com>

I would like to sign onto a web page, but am having a difficult time determine what parameters to pass in my sign in.  For a simple test, I am trying to parse text on a "friends" status page on twitter.  This is not via the API, but the web.

import urllib2, urllib, cookielib
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
cj = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
d={'authenticity_token':'8578471445acd12dec39b3353b71c88969f1505e', 'username_or_email':'user','password':'pswd123'}
params = urllib.urlencode(d)
opener.open('http://twitter.com/login', params)

if not 'id' in [cookie.name for cookie in cj]:
    raise ValueError, "Login failed"

#########   result
Traceback (most recent call last):
  File "<pyshell#12>", line 2, in <module>
    raise ValueError, "Login failed"
ValueError: Login failed

How can I tell what the page is asking for, and if I am passing the correct parameters?



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100331/d2daf6d7/attachment.html>

From bgailer at gmail.com  Thu Apr  1 00:15:19 2010
From: bgailer at gmail.com (bob gailer)
Date: Wed, 31 Mar 2010 18:15:19 -0400
Subject: [Tutor] what's wrong in my command?
In-Reply-To: <t2r2b9003cf1003311333h445c0c34m1474b983d5f35f84@mail.gmail.com>
References: <t2r2b9003cf1003311333h445c0c34m1474b983d5f35f84@mail.gmail.com>
Message-ID: <4BB3C977.60303@gmail.com>

On 3/31/2010 4:33 PM, Shurui Liu (Aaron Liu) wrote:
> # geek_translator3.py
>
> # Pickle
> import pickle
>
> # Open Dictionary
> geekfile = open('geekdictionary3.txt', 'r+')
> new_geeks = pickle.load(geekfile)
> geekterms = new_geeks.keys()
> geekterms.sort()
>
> # start
> choice = None
> while choice != "0":
>
>      print \
>      """
>      Geek Translator
>
>      0 - Quit
>      1 - Look Up a Geek Term
>      2 - Add a Geek Term
>      3 - Redefine a Geek Term
>      4 - Delete a Geek Term
>      5 - List of Terms
>      """
>
>      choice = raw_input("Choice: ")
>      print
>
>      # exit
>      if choice == "0":
>          print "Good-bye."
>
>      # get a definition
>      elif choice == "1":
>          term = raw_input("What term do you want me to translate?: ")
>          if term in new_geeks:
>              definition = new_geeks[term]
>              print "\n", term, "means", definition
>          else:
>              print "\nSorry, I don't know", term
>
>      # add a term-definition pair
>      elif choice == "2":
>          term = raw_input("What term do you want me to add?: ")
>          if term not in new_geeks:
>              definition = raw_input("\nWhat's the definition?: ")
>              new_geeks[term] = definition
>              geekterms.append(term)
>              geekterms.sort()
>              print "\n", term, "has been added."
>          else:
>              print "\nThat term already exists!  Try redefining it."
>      # redefine an existing term
>      elif choice == "3":
>          term = raw_input("What term do you want me to redefine?: ")
>          if term in new_geeks:
>              definition = raw_input("What's the new definition?: ")
>              new_geeks[term] = definition
>              print "\n", term, "has been redefined."
>          else:
>              print "\nThat term doesn't exist!  Try adding it."
>
>      # delete a term-definition pair
>      elif choice == "4":
>          term = raw_input("What term do you want me to delete?: ")
>          if term in new_geeks:
>              del new_geeks[term]
>              geekterms.remove(term)
>              print "\nOkay, I deleted", term
>          else:
>              print "\nI can't do that!", term, "doesn't exist in the dictionary."
>
>      # list of terms
>      elif choice == "5":
>          print geekterms
>
>      # some unknown choice
>      else:
>          print "\nSorry, but", choice, "isn't a valid choice."
> # geek speak link
> print "\tTo learn to speak geek visit"
> print "\n\t\thttp://www.youtube.com/watch?v=7BpsXZpAARk"
>
> # 133t speak links
> print "\n\n\tTo learn to 1337 speak visit"
> print "\n\t\thttp://linuxreviews.org/howtos/l33t/"
> print "\n\t\t\t\tor"
> print "\n\t\thttp://textozor.com/hacker-text/"
>
> # save dictionary
> pickle.dump(ldict, open('geekdictionary.txt', 'r+'))
>
> # close file
> geekfile.close()
>
> raw_input("\n\nPress the enter key to exit.")
>
>
>
>
>
> When I run it, the system gave me the feedback below:
> Traceback (most recent call last):
>    File "geek_translator3.py", line 4, in<module>
>      import pickle
>    File "/usr/local/lib/python2.5/pickle.py", line 13, in<module>
>
> AttributeError: 'module' object has no attribute 'dump'
>    

I suspect that file is not the one packaged with Python. Try renaming it 
and rerun the program.
> I don't understand, I don't write anything about pickle.py, why it mentioned?
> what's wrong with "import pickle"? I read many examples online whose
> has "import pickle", they all run very well.
> Thank you!
>
>    


-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From anand.shashwat at gmail.com  Thu Apr  1 00:16:24 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Thu, 1 Apr 2010 03:46:24 +0530
Subject: [Tutor] Open a WebPage with Forms Authentication
In-Reply-To: <891749.98302.qm@web51701.mail.re2.yahoo.com>
References: <t2r2b9003cf1003311333h445c0c34m1474b983d5f35f84@mail.gmail.com> 
	<891749.98302.qm@web51701.mail.re2.yahoo.com>
Message-ID: <s2hd4ab53de1003311516m820edaeds3cde3cef262a1492@mail.gmail.com>

may be you can try mechanize ?

On Thu, Apr 1, 2010 at 3:41 AM, GoodPotatoes <goodpotatoes at yahoo.com> wrote:

> I would like to sign onto a web page, but am having a difficult time
> determine what parameters to pass in my sign in.  For a simple test, I am
> trying to parse text on a "friends" status page on twitter.  This is not via
> the API, but the web.
>
> import urllib2, urllib, cookielib
> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
> cj = cookielib.LWPCookieJar()
> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
> urllib2.install_opener(opener)
> d={'authenticity_token':'8578471445acd12dec39b3353b71c88969f1505e',
> 'username_or_email':'user','password':'pswd123'}
> params = urllib.urlencode(d)
> opener.open('http://twitter.com/login', params)
>
> if not 'id' in [cookie.name for cookie in cj]:
>     raise ValueError, "Login failed"
>
> #########   result
> Traceback (most recent call last):
>   File "<pyshell#12>", line 2, in <module>
>     raise ValueError, "Login failed"
> ValueError: Login failed
>
> How can I tell what the page is asking for, and if I am passing the correct
> parameters?
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100401/fcd3b88c/attachment.html>

From steve at pearwood.info  Thu Apr  1 00:40:14 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 1 Apr 2010 09:40:14 +1100
Subject: [Tutor] Script Feedback
In-Reply-To: <262679b51003301654r983e843m61e06887e48cf6d@mail.gmail.com>
References: <262679b51003300727q3c6c6b65p4776880633a51384@mail.gmail.com>
	<20100330194134.6ac25d76@o>
	<262679b51003301654r983e843m61e06887e48cf6d@mail.gmail.com>
Message-ID: <201004010940.15199.steve@pearwood.info>

On Wed, 31 Mar 2010 10:54:34 am Damon Timm wrote:

> > Separate the underlying functionality from the application-level
> > code. These functions should NEVER print anything: they do all
> > communication through call-backs, or by returning a value, or
> > raising an exception.
>
> I tried to implement this, however, I am not sure how the 'callback'
> works ... is that just a function that a user would pass to *my*
> function that gets called at the end of the script?

Not necessarily at the end of the script.

You usually find callbacks used a lot in coding for graphical user 
interfaces (GUIs). For instance, the GUI framework might provide a 
Button class. The caller creates a new Button object, and provides a 
callback function which gets called automatically by the framework 
whenever the user clicks the button.

The built-in function map is very similar. map is more or less 
equivalent to the following:

def map(callback, sequence):
    result = []
    for item in sequence:
        result.append(callback(item))
    return result

except the real map is more efficient, and accepts multiple sequences. 
It's not common to describe the function argument to map as a callback, 
but that's essentially what it is. In this example, the callback 
function needs to be a function that takes a single arbitrary argument. 
The caller can pass any function they like, so long as it takes a 
single argument, and map promises to call that function with every item 
in the sequence.

There's nothing special about callbacks, except that they have to take 
the arguments which the library function promises to supply.


-- 
Steven D'Aprano

From davea at ieee.org  Thu Apr  1 11:45:52 2010
From: davea at ieee.org (Dave Angel)
Date: Thu, 01 Apr 2010 04:45:52 -0500
Subject: [Tutor] what's wrong in my command?
In-Reply-To: <t2r2b9003cf1003311333h445c0c34m1474b983d5f35f84@mail.gmail.com>
References: <t2r2b9003cf1003311333h445c0c34m1474b983d5f35f84@mail.gmail.com>
Message-ID: <4BB46B50.3080409@ieee.org>

Shurui Liu (Aaron Liu) wrote:
> # geek_translator3.py
>
> # Pickle
> import pickle
>
>   
This is where you told it to load import.py.   Normally, that just 
quietly loads the standard module included with your system.
> <snip, rest of source>
>
> When I run it, the system gave me the feedback below:
> Traceback (most recent call last):
>   File "geek_translator3.py", line 4, in <module>
>     import pickle
>   File "/usr/local/lib/python2.5/pickle.py", line 13, in <module>
>
> AttributeError: 'module' object has no attribute 'dump'
>
> I don't understand, I don't write anything about pickle.py, why it mentioned?
> what's wrong with "import pickle"? I read many examples online whose
> has "import pickle", they all run very well.
> Thank you!
>
>   
I don't have 2.5 any more, so I can't look at the same file you 
presumably have.  And line numbers will most likely be different in 
2.6.  In particular, there are lots of module comments at the beginning 
of my version of pickle.py.  You should take a look at yours, and see 
what's in line 13.   My guess it's a reference to the dump() function 
which may be defined in the same file.  Perhaps in 2.5 it was defined 
elsewhere.

Most common cause for something like this would be that pickle imports 
some module, and you have a module by that name in your current 
directory (or elsewhere on the sys.path).  So pickle gets an error after 
importing it, trying to use a global attribute that's not there.

Wild guess - do you have a file called marshal.py in your own code?

DaveA


From shurui91 at gmail.com  Thu Apr  1 18:31:00 2010
From: shurui91 at gmail.com (Shurui Liu (Aaron Liu))
Date: Thu, 1 Apr 2010 12:31:00 -0400
Subject: [Tutor] what's wrong in my command?
In-Reply-To: <4BB46B50.3080409@ieee.org>
References: <t2r2b9003cf1003311333h445c0c34m1474b983d5f35f84@mail.gmail.com>
	<4BB46B50.3080409@ieee.org>
Message-ID: <t2k2b9003cf1004010931u83a16d10h9fe7ff6fb553c7f3@mail.gmail.com>

OK, can you tell me import.py is empty or not? If it's not an empty
document, what's its content?

On Thu, Apr 1, 2010 at 5:45 AM, Dave Angel <davea at ieee.org> wrote:
> Shurui Liu (Aaron Liu) wrote:
>>
>> # geek_translator3.py
>>
>> # Pickle
>> import pickle
>>
>>
>
> This is where you told it to load import.py. ? Normally, that just quietly
> loads the standard module included with your system.
>>
>> <snip, rest of source>
>>
>> When I run it, the system gave me the feedback below:
>> Traceback (most recent call last):
>> ?File "geek_translator3.py", line 4, in <module>
>> ? ?import pickle
>> ?File "/usr/local/lib/python2.5/pickle.py", line 13, in <module>
>>
>> AttributeError: 'module' object has no attribute 'dump'
>>
>> I don't understand, I don't write anything about pickle.py, why it
>> mentioned?
>> what's wrong with "import pickle"? I read many examples online whose
>> has "import pickle", they all run very well.
>> Thank you!
>>
>>
>
> I don't have 2.5 any more, so I can't look at the same file you presumably
> have. ?And line numbers will most likely be different in 2.6. ?In
> particular, there are lots of module comments at the beginning of my version
> of pickle.py. ?You should take a look at yours, and see what's in line 13.
> My guess it's a reference to the dump() function which may be defined in the
> same file. ?Perhaps in 2.5 it was defined elsewhere.
>
> Most common cause for something like this would be that pickle imports some
> module, and you have a module by that name in your current directory (or
> elsewhere on the sys.path). ?So pickle gets an error after importing it,
> trying to use a global attribute that's not there.
>
> Wild guess - do you have a file called marshal.py in your own code?
>
> DaveA
>
>



-- 
Shurui Liu (Aaron Liu)
Computer Science & Engineering Technology
University of Toledo
419-508-1228

From alan.gauld at btinternet.com  Thu Apr  1 19:18:31 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 1 Apr 2010 18:18:31 +0100
Subject: [Tutor] what's wrong in my command?
References: <t2r2b9003cf1003311333h445c0c34m1474b983d5f35f84@mail.gmail.com><4BB46B50.3080409@ieee.org>
	<t2k2b9003cf1004010931u83a16d10h9fe7ff6fb553c7f3@mail.gmail.com>
Message-ID: <hp2khk$qth$1@dough.gmane.org>


"Shurui Liu (Aaron Liu)" <shurui91 at gmail.com> wrote


OK, can you tell me import.py is empty or not? If it's not an empty
document, what's its content?

On Thu, Apr 1, 2010 at 5:45 AM, Dave Angel <davea at ieee.org> wrote:
>> # Pickle
>> import pickle
> This is where you told it to load import.py. Normally, that just quietly
> loads the standard module included with your system.

Dave meant to say pickle.py

There is no import.py.

>> When I run it, the system gave me the feedback below:
>> Traceback (most recent call last):
>> File "geek_translator3.py", line 4, in <module>
>> import pickle
>> File "/usr/local/lib/python2.5/pickle.py", line 13, in <module>
>>
>> AttributeError: 'module' object has no attribute 'dump'

Did you by any chance create or edit a file called pickle.py in
the location indicated? It could be that you need to
reinstall to get the original pickle.py back.

>> I don't understand, I don't write anything about pickle.py, why it
>> mentioned?

You wrote about it when you did the import. Thats why it's mentioned.

>> what's wrong with "import pickle"? I read many examples online whose
>> has "import pickle", they all run very well.

What happens if you start a new Python interpreter session and type:

>>> import pickle

Does it work?

> Most common cause for something like this would be that pickle imports 
> some
> module, and you have a module by that name in your current directory (or
> elsewhere on the sys.path). So pickle gets an error after importing it,
> trying to use a global attribute that's not there.
>
> Wild guess - do you have a file called marshal.py in your own code?

And  tell us about this too...

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From davea at ieee.org  Thu Apr  1 20:46:08 2010
From: davea at ieee.org (Dave Angel)
Date: Thu, 01 Apr 2010 13:46:08 -0500
Subject: [Tutor] what's wrong in my command?
In-Reply-To: <t2k2b9003cf1004010931u83a16d10h9fe7ff6fb553c7f3@mail.gmail.com>
References: <t2r2b9003cf1003311333h445c0c34m1474b983d5f35f84@mail.gmail.com>	
	<4BB46B50.3080409@ieee.org>
	<t2k2b9003cf1004010931u83a16d10h9fe7ff6fb553c7f3@mail.gmail.com>
Message-ID: <4BB4E9F0.7050504@ieee.org>

Shurui Liu (Aaron Liu) wrote:
> OK, can you tell me import.py is empty or not? If it's not an empty
> document, what's its content?
>
>   
(Please don't top-post,  Add your comments after what you're quoting, or 
at the end)

That was a typo in my message.  I should have said  pickle.py,  not 
import.py.  When you import pickle, you're tell it to find and load 
pickle.py.  That's python source code, and it will generally import 
other modules.  I was suspecting module.py.  But you should start by 
looking at line 13 of pickle.py

> On Thu, Apr 1, 2010 at 5:45 AM, Dave Angel <davea at ieee.org> wrote:
>   
>> Shurui Liu (Aaron Liu) wrote:
>>     
>>> # geek_translator3.py
>>>
>>> # Pickle
>>> import pickle
>>>
>>>
>>>       
>> This is where you told it to load import.py.   Normally, that just quietly
>> loads the standard module included with your system.
>>     
>>> <snip, rest of source>
>>>
>>> When I run it, the system gave me the feedback below:
>>> Traceback (most recent call last):
>>>  File "geek_translator3.py", line 4, in <module>
>>>    import pickle
>>>  File "/usr/local/lib/python2.5/pickle.py", line 13, in <module>
>>>
>>> AttributeError: 'module' object has no attribute 'dump'
>>>
>>> I don't understand, I don't write anything about pickle.py, why it
>>> mentioned?
>>> what's wrong with "import pickle"? I read many examples online whose
>>> has "import pickle", they all run very well.
>>> Thank you!
>>>
>>>
>>>       
>> I don't have 2.5 any more, so I can't look at the same file you presumably
>> have.  And line numbers will most likely be different in 2.6.  In
>> particular, there are lots of module comments at the beginning of my version
>> of pickle.py.  You should take a look at yours, and see what's in line 13.
>> My guess it's a reference to the dump() function which may be defined in the
>> same file.  Perhaps in 2.5 it was defined elsewhere.
>>
>> Most common cause for something like this would be that pickle imports some
>> module, and you have a module by that name in your current directory (or
>> elsewhere on the sys.path).  So pickle gets an error after importing it,
>> trying to use a global attribute that's not there.
>>
>> Wild guess - do you have a file called marshal.py in your own code?
>>
>> DaveA
>>
>>
>>     
>
>
>
>   


From jojo.mwebaze at gmail.com  Thu Apr  1 23:34:53 2010
From: jojo.mwebaze at gmail.com (Jojo Mwebaze)
Date: Thu, 1 Apr 2010 23:34:53 +0200
Subject: [Tutor] os.fork | queue
Message-ID: <q2l3124be321004011434o34d80872s6fcee0a86b620a2@mail.gmail.com>

I am trying to implement parallel processing with os.fork.. However i want
to collect results from each process.. I thought i could use Queues, but i
cant seem to get it work. Threading, can not work for me, because of the way
some functions have been written -

Below is a copy of what i had written..

cheers

Jojo

---------------------------------
import os, time, Queue
import do_something


mylist1 = [item1, item2, item3 ......]
mylist2 = [item1,item2, item2 ......]

def child(x, y):
    return do_something(x,y)

def parent(myqueue):
    for x, y in zip (mylist1, mylist2):

         pid = os.fork()

         if pid !=0:
              print 'Process %d spwaned' %pid
         else:
             result = child(x, y)
             sys.exit(0)
         myqueue.put(result)
    return myqueue



myqueue = Queue.Queue(0)
data = parent(myqueue)

---------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100401/f46c36e6/attachment.html>

From jneiss at neisskids.org  Fri Apr  2 00:47:42 2010
From: jneiss at neisskids.org (jneiss at neisskids.org)
Date: Thu, 1 Apr 2010 15:47:42 -0700
Subject: [Tutor] Decoding MIME Attachments
Message-ID: <35231c7c1163ecf5891789fa7236684b.squirrel@www.neisskids.org>

 Hi, all;

 I am a longtime linux sysadmin that is fairly new to Python. I've got a
project for which Python seems to be perfect (or, at least, I've found a
way to integrate my learning :-)

 I receive log files via email from an outside vendor. We use Splunk to
generate reports based on these and other logs. At the moment, pulling
the emailed logs into Splunk is done by hand--open the email, save the
attachment, read the file in. I'd like to automate it, and procmail + a
script is the easiest way. I've found perl scripts that supposedly pull
MIME-encoded attachments, but not being a perl guy, I'm trying to use
Python instead.

 I have the following script--cobbled together from Internet searches, the
Python cookbook, and hand-written lines:

#! /usr/bin/env python

import email.Parser
import os, sys
def main(argv = sys.argv):
      if not sys.stdin.isatty():
              for m in sys.stdin.readlines():
                p = email.Parser.Parser()
                msg = p.parse(m)
                mailfile.close()
                partcounter = 1
                for part in msg.walk():
                        if part.get_content_maintype() == "multipart":
                                continue
                        name = part.get_param("name")
                        if name == None:
                                name = "part-%i" % partcounter
                        partcounter += 1
                        print "partcounter = %s" % partcounter
                        if name != "part-1":
                                outfile = open(name, "wb")
                                outfile.write(part.get_payload(decode=1))
                                outfile.close()
if __name__=="__main__":
        try:
                main(sys.argv)
        except KeyboardInterrupt:
                pass

 The gist is: read whatever's piped to the script (from procmail or on the
command line), walk through the data looking for the second MIME header,
and write that part (the file attachment) to disk.

 What actually happens is this:

[user at server scripts]# cat /tmp/mail.txt | ./mail_extract.py
Traceback (most recent call last):
  File "./mail_extract.py", line 32, in ?
    main(sys.argv)
  File "./mail_extract.py", line 12, in main
    msg = p.parse(mailfile)
  File "/usr/lib64/python2.4/email/Parser.py", line 65, in parse
    data = fp.read(8192)
AttributeError: 'str' object has no attribute 'read'
[user at server scripts]#

f I change the three lines starting with "def main" to:

def main():
     if len(sys.argv) != 2:
             print "Usage: %s filename" % os.path.basename(sys.argv[0])
             sys.exit(1)

and remove the last five lines (if...pass), changing the command line to
"./mail_extract.py /tmp/mail.txt", it works like a champ. As is, it errors
whether through procmail or directly from the command line.

 Any ideas? What am I doing wrong?

 I'm using Python 2.4.3 on Red Hat ES 5.3, if it matters.

 Thanks;
 Jason

--
 jason at neisskids.org
 gentoo linux, as if you cared
 nac mac feegle!



From waynejwerner at gmail.com  Fri Apr  2 03:10:35 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Thu, 1 Apr 2010 20:10:35 -0500
Subject: [Tutor] Decoding MIME Attachments
In-Reply-To: <35231c7c1163ecf5891789fa7236684b.squirrel@www.neisskids.org>
References: <35231c7c1163ecf5891789fa7236684b.squirrel@www.neisskids.org>
Message-ID: <m2n333efb451004011810v26a71be4q692743cda2f93c7c@mail.gmail.com>

On Thu, Apr 1, 2010 at 5:47 PM, <jneiss at neisskids.org> wrote:

>  Hi, all;
>
>  I am a longtime linux sysadmin that is fairly new to Python. I've got a
> project for which Python seems to be perfect (or, at least, I've found a
> way to integrate my learning :-)


Welcome to Python! I highly recommend this book by Noah Gift:
 http://www.amazon.com/Python-Unix-Linux-System-Administration/dp/0596515820

It seems like it's right up your alley!


>  I receive log files via email from an outside vendor. We use Splunk to
> generate reports based on these and other logs. At the moment, pulling
> the emailed logs into Splunk is done by hand--open the email, save the
> attachment, read the file in. I'd like to automate it, and procmail + a
> script is the easiest way. I've found perl scripts that supposedly pull
> MIME-encoded attachments, but not being a perl guy, I'm trying to use
> Python instead.
>
>  I have the following script--cobbled together from Internet searches, the
> Python cookbook, and hand-written lines:
>
> #! /usr/bin/env python
>
> import email.Parser
> import os, sys
> def main(argv = sys.argv):
>      if not sys.stdin.isatty():
>              for m in sys.stdin.readlines():
>                p = email.Parser.Parser()
>                msg = p.parse(m)
>

Here's basically where the problem is - m is a string. From the docs (I use
ipython - in the regular python prompt you'd say >>> help(p.parse):

In [3]: p.parse?
Type:           instancemethod
Base Class:     <type 'instancemethod'>
String Form:    <bound method Parser.parse of <email.parser.Parser instance
at 0x92ffa8c>>
Namespace:      Interactive
File:           /usr/lib/python2.6/email/parser.py
Definition:     p.parse(self, fp, headersonly=False)
Docstring:
    Create a message structure from the data in a file.

    Reads all the data from the file and returns the root of the message
    structure.  Optional headersonly is a flag specifying whether to stop
    parsing after reading the headers or not.  The default is False,
    meaning it parses the entire contents of the file.

So parse is looking for a file - the fp parameter.

> <snip>
>  Any ideas? What am I doing wrong?
>
>  I'm using Python 2.4.3 on Red Hat ES 5.3, if it matters.
>
>
See if you can figure it out from there - if you get further, and get stuck
again, let us know!

HTH,
Wayne

p.s. bonus points for posting the Traceback. A bit of explanation (read from
bottom to top)

 File "./mail_extract.py", line 32, in ?              <----- The main block
where it was called
   main(sys.argv)
 File "./mail_extract.py", line 12, in main         <-------- This is where
the next line was called
   msg = p.parse(mailfile)
 File "/usr/lib64/python2.4/email/Parser.py", line 65, in parse    <---
Tells you where the original error was (usually)
   data = fp.read(8192)
AttributeError: 'str' object has no attribute 'read'       <--------- Really
important, tells you what went wrong
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100401/e547c2d4/attachment.html>

From juryef at yahoo.com  Fri Apr  2 04:58:20 2010
From: juryef at yahoo.com (Judith Flores)
Date: Thu, 1 Apr 2010 19:58:20 -0700 (PDT)
Subject: [Tutor] Searching for time in a given string
Message-ID: <27451.74230.qm@web113808.mail.gq1.yahoo.com>

Hello,

   I was wondering if someone could provide me with the pattern syntax to find the time in a given string. The time usually appears as "14:28:32" (for example) within a string ("Sun Jan 23 14:28:32 1965"). How can I retrieve the time?


Thank you very much in advance for your help,

Judith


      


From metolone+gmane at gmail.com  Fri Apr  2 05:20:01 2010
From: metolone+gmane at gmail.com (Mark Tolonen)
Date: Thu, 1 Apr 2010 20:20:01 -0700
Subject: [Tutor] Searching for time in a given string
References: <27451.74230.qm@web113808.mail.gq1.yahoo.com>
Message-ID: <hp3np0$4h4$1@dough.gmane.org>


"Judith Flores" <juryef at yahoo.com> wrote in message 
news:27451.74230.qm at web113808.mail.gq1.yahoo.com...
> Hello,
>
>   I was wondering if someone could provide me with the pattern syntax to 
> find the time in a given string. The time usually appears as "14:28:32" 
> (for example) within a string ("Sun Jan 23 14:28:32 1965"). How can I 
> retrieve the time?

The built-in datetime module can parse this type of string:
(http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior)

PythonWin 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit 
(Intel)] on win32.
Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for 
further copyright information.
>>> s = "Sun Jan 23 14:28:32 1965"
>>> from datetime import datetime
>>> d=datetime.strptime(s,'%a %b %d %H:%M:%S %Y')
>>> d.hour
14
>>> d.minute
28
>>> d.second
32
>>> d.time()
datetime.time(14, 28, 32)
>>> d.date()
datetime.date(1965, 1, 23)
>>> d.ctime()
'Sat Jan 23 14:28:32 1965'

It also knows that date was really a Saturday :^)

-Mark




From doyennehoney at yahoo.com  Fri Apr  2 08:25:47 2010
From: doyennehoney at yahoo.com (adedoyin adegoke)
Date: Fri, 2 Apr 2010 07:25:47 +0100
Subject: [Tutor] Display in a text field using tkinter
Message-ID: <m2gcf7f1f3e1004012325k3bdfc413pa919e33145ebd766@mail.gmail.com>

from Tkinter import *
import MySQLdb

class Snoop(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        Label(self, text = "Database Name:").grid(row = 0, column = 0,
sticky = W)
        self.txt_box = Entry(self, text = "hool").grid(row = 0, column = 1,
sticky = W)
        Button(self, text = "Submit", command = self.connect_db).grid(row =
1, column = 1, sticky = W)
        Label(self, text = "Tables:").grid(row = 2, column = 0, sticky = W)

        Label(self, text = "Information:").grid(row = 2, column = 1, sticky
= W)
       # self.txt = Text(self, width = 40, height = 5, wrap = WORD).grid(row
= 3, column = 1, sticky = W)

    def connect_db(self):
        db= MySQLdb.connect(host="localhost", user="root" , passwd="")
        cursor = db.cursor()
        cursor.execute("show databases")

        self.favorite = StringVar()

        result = cursor.fetchall()
        i = 4
        for record in result:
            Radiobutton(self,
                     text = record,
                     variable = self.favorite,
                     value = record,
                     command = self.update_text
                     ).grid(row = i, column = 0, sticky = W)
            i+=1

        #print database
        #self.txt.delete(0.0, END)
        #self.get_db(database)
    def update_text(self):
        print self.favorite.get()
        trt = self.favorite.get()
        self.txt_box.insert(END,trt)



#db.close
root = Tk()
root.title("Snoop")
start = Snoop(root)

root.mainloop()



The above code will snoop and fetch all d available databases using tkinter.
When I select one of these databases, the name should be inserted in a text
field instead it throws the following error ;

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__
    return self.func(*args)
  File "/home/NetBeansProjects/python/src/Xsnoop.py", line 45, in
update_text
    self.txt_box.insert(END,trt)
AttributeError: 'NoneType' object has no attribute 'insert'


How can i correct this?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100402/a4b124ed/attachment-0001.html>

From alan.gauld at btinternet.com  Fri Apr  2 09:14:16 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 2 Apr 2010 08:14:16 +0100
Subject: [Tutor] Display in a text field using tkinter
References: <m2gcf7f1f3e1004012325k3bdfc413pa919e33145ebd766@mail.gmail.com>
Message-ID: <hp45gm$1oa$1@dough.gmane.org>


"adedoyin adegoke" <doyennehoney at yahoo.com> wrote >    def 
create_widgets(self):
>        Label(self, text = "Database Name:").grid(...
>        self.txt_box = Entry(self, text = "hool").grid(...

The grid(and pack etc)  method returns None.
You have to create the widgets then apply the layout manager on a separate 
line

       self.txt_box = Entry(self, text = "hool")
       self.txt_box.grid(....)

>
> Exception in Tkinter callback
>    self.txt_box.insert(END,trt)
> AttributeError: 'NoneType' object has no attribute 'insert'
>
> How can i correct this?

Don;t use grid() ion the same line as you create the widget.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From eire1130 at gmail.com  Fri Apr  2 15:26:36 2010
From: eire1130 at gmail.com (James Reynolds)
Date: Fri, 2 Apr 2010 09:26:36 -0400
Subject: [Tutor] Display in a text field using tkinter
In-Reply-To: <m2gcf7f1f3e1004012325k3bdfc413pa919e33145ebd766@mail.gmail.com>
References: <m2gcf7f1f3e1004012325k3bdfc413pa919e33145ebd766@mail.gmail.com>
Message-ID: <x2l98c3f7c51004020626m45a53246s6b5d320417ae4301@mail.gmail.com>

On Fri, Apr 2, 2010 at 2:25 AM, adedoyin adegoke <doyennehoney at yahoo.com>wrote:

> from Tkinter import *
> import MySQLdb
>
> class Snoop(Frame):
>     def __init__(self, master):
>         Frame.__init__(self, master)
>         self.grid()
>         self.create_widgets()
>
>     def create_widgets(self):
>         Label(self, text = "Database Name:").grid(row = 0, column = 0,
> sticky = W)
>         self.txt_box = Entry(self, text = "hool").grid(row = 0, column = 1,
> sticky = W)
>         Button(self, text = "Submit", command = self.connect_db).grid(row =
> 1, column = 1, sticky = W)
>         Label(self, text = "Tables:").grid(row = 2, column = 0, sticky = W)
>
>         Label(self, text = "Information:").grid(row = 2, column = 1, sticky
> = W)
>        # self.txt = Text(self, width = 40, height = 5, wrap =
> WORD).grid(row = 3, column = 1, sticky = W)
>
>     def connect_db(self):
>         db= MySQLdb.connect(host="localhost", user="root" , passwd="")
>         cursor = db.cursor()
>         cursor.execute("show databases")
>
>         self.favorite = StringVar()
>
>         result = cursor.fetchall()
>         i = 4
>         for record in result:
>             Radiobutton(self,
>                      text = record,
>                      variable = self.favorite,
>                      value = record,
>                      command = self.update_text
>                      ).grid(row = i, column = 0, sticky = W)
>             i+=1
>
>         #print database
>         #self.txt.delete(0.0, END)
>         #self.get_db(database)
>     def update_text(self):
>         print self.favorite.get()
>         trt = self.favorite.get()
>         self.txt_box.insert(END,trt)
>
>
>
> #db.close
> root = Tk()
> root.title("Snoop")
> start = Snoop(root)
>
> root.mainloop()
>
>
>
> The above code will snoop and fetch all d available databases using
> tkinter. When I select one of these databases, the name should be inserted
> in a text field instead it throws the following error ;
>
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__
>     return self.func(*args)
>   File "/home/NetBeansProjects/python/src/Xsnoop.py", line 45, in
> update_text
>     self.txt_box.insert(END,trt)
> AttributeError: 'NoneType' object has no attribute 'insert'
>
>
> How can i correct this?
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Is this line printing anything:

"print self.favorite.get()"?



I would try something like this:

Move this to the "__init__":

self.favorite = StringVar()


Change this:

self.txt_box = Entry(self, text = "hool").grid(row = 0, column = 1, sticky =
> W)


to this:


self.txt_box = Entry(self, text = self.name).grid(row = 0, column = 1,
> sticky = W)


in the "__init__" add two lines:


self.name = StringVar()
self.name.set("hool")

In update_text change this:

self.txt_box.insert(END,trt)


to this:

self.name.set(trt)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100402/10944d92/attachment.html>

From doyennehoney at yahoo.com  Sat Apr  3 10:05:41 2010
From: doyennehoney at yahoo.com (doyin adegoke)
Date: Sat, 3 Apr 2010 01:05:41 -0700 (PDT)
Subject: [Tutor] Display in a text field using tkinter
In-Reply-To: <x2l98c3f7c51004020626m45a53246s6b5d320417ae4301@mail.gmail.com>
References: <m2gcf7f1f3e1004012325k3bdfc413pa919e33145ebd766@mail.gmail.com>
	<x2l98c3f7c51004020626m45a53246s6b5d320417ae4301@mail.gmail.com>
Message-ID: <711523.85184.qm@web34504.mail.mud.yahoo.com>

Thanks
I made the changes and the error was still there

"print self.favorite.get()" prints the name of the selected database on the console




________________________________
From: James Reynolds <eire1130 at gmail.com>
To: adedoyin adegoke <doyennehoney at yahoo.com>
Cc: tutor at python.org
Sent: Fri, April 2, 2010 2:26:36 PM
Subject: Re: [Tutor] Display in a text field using tkinter




On Fri, Apr 2, 2010 at 2:25 AM, adedoyin adegoke <doyennehoney at yahoo.com> wrote:

from Tkinter import *
>import MySQLdb
>
>
>class Snoop(Frame):
>    def __init__(self, master):
>        Frame.__init__(self, master)
>        self.grid()
>>        self.create_widgets()
>
>
>    def create_widgets(self):
>        Label(self, text = "Database Name:").grid(row = 0, column = 0, sticky = W)
>        self.txt_box = Entry(self, text = "hool").grid(row = 0, column = 1, sticky = W)
>        Button(self, text = "Submit", command = self.connect_db).grid(row = 1, column = 1, sticky = W)
>        Label(self, text = "Tables:").grid(row = 2, column = 0, sticky = W)
>>
>       
>        Label(self, text = "Information:").grid(row = 2, column = 1, sticky = W)
>       # self.txt = Text(self, width = 40, height = 5, wrap = WORD).grid(row = 3, column = 1, sticky = W)
>       
>    def connect_db(self):
>        db= MySQLdb.connect(host="localhost", user="root" , passwd="")
>        cursor = db.cursor()
>        cursor.execute("show databases")
>
>
>        self.favorite = StringVar()
>
>
>        result = cursor.fetchall()
>        i = 4
>        for record in result:
>            Radiobutton(self,
>                     text = record,
>                     variable = self.favorite,
>                     value = record,
>                     command = self.update_text
>                     ).grid(row = i, column = 0, sticky = W)
>            i+=1
>        
>        #print database
>        #self.txt.delete(0.0, END)
>        #self.get_db(database)
>    def update_text(self):
>        print self.favorite.get()
>        trt = self.favorite.get()
>        self.txt_box.insert(END,trt)
>
>
>   
>
>
>#db.close
>root = Tk()
>root.title("Snoop")
>>
>start = Snoop(root)
>
>
>root.mainloop()
>
>
>
>
>
>
>The above code will snoop and fetch all d available databases using tkinter. When I select one of these databases, the name should be inserted in a text field instead it throws the following error ;
>
>
>Exception in Tkinter callback
>Traceback (most recent call last):
>  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__
>    return self.func(*args)
>  File "/home/NetBeansProjects/python/src/Xsnoop.py", line 45, in update_text
>    self.txt_box.insert(END,trt)
>AttributeError: 'NoneType' object has no attribute 'insert'
>   
>
>
>How can i correct this?
>
>
>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>To unsubscribe or change subscription options:
>http://mail.python.org/mailman/listinfo/tutor
>
>
Is this line printing anything:

>"print self.favorite.get()"?


I would try something like this:

Move this to the "__init__":

>self.favorite = StringVar()

Change this:

>self.txt_box = Entry(self, text = "hool").grid(row = 0, column = 1, sticky = W)

to this:


>self.txt_box = Entry(self, text = self.name).grid(row = 0, column = 1, sticky = W)

in the "__init__" add two lines:

 
self.name = StringVar()
self.name.set("hool")

In update_text change this:

>self.txt_box.insert(END,trt)

to this:

>self.name.set(trt)


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100403/6f76fb3d/attachment-0001.html>

From lie.1296 at gmail.com  Sat Apr  3 11:04:04 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sat, 03 Apr 2010 20:04:04 +1100
Subject: [Tutor] simple search and replace...
In-Reply-To: <340096.67805.qm@web86706.mail.ird.yahoo.com>
References: <n2lc7a040fa1003310820pbecf0ab7ufeb3a4b5a4d501e6@mail.gmail.com>	<hp02fo$ikn$1@dough.gmane.org>	<n2vc7a040fa1003311230jdac045e7t1260bda2d55dc23f@mail.gmail.com>
	<340096.67805.qm@web86706.mail.ird.yahoo.com>
Message-ID: <hp70bp$rmn$1@dough.gmane.org>

On 04/01/10 06:51, ALAN GAULD wrote:
> But if it's fixed patterns you can either do a replace()
> in a loop over your patterns:
> 
> for pat in ['PID','OBR',.....]
>     h7string = h7string.replace('\n'+pat, h7string)
> 
> Or even build a regex that does it all in one.
> (But the regex could get complex quickly!)

Or even write a "regex precompiler" that converts a list of items to
search into regex string (read: '|'.join(keywords)). That may be
necessary depending on the complexity of your queries and your
clash-handling scenario (what would you like to happen if your
replacement string contains another string in the keywords?).



From jdmccla at regence.com  Sat Apr  3 13:00:55 2010
From: jdmccla at regence.com (James D Mcclatchey)
Date: Sat, 3 Apr 2010 04:00:55 -0700
Subject: [Tutor] AUTO: James D Mcclatchey is out of the office. (returning
	04/09/2010)
Message-ID: <OF2F20B8D8.997CC43E-ON882576FA.003C8248-882576FA.003C8248@regence.com>



I am out of the office until 04/09/2010.

I will respond to your message when I return.


Note: This is an automated response to your message  "Tutor Digest, Vol 74,
Issue 6" sent on 4/3/10 1:05:50.

This is the only notification you will receive while this person is away.
*IMPORTANT NOTICE: This communication, including any attachment, contains information that may be confidential or privileged, and is intended solely for the entity or individual to whom it is addressed.  If you are not the intended recipient, you should delete this message and are hereby notified that any disclosure, copying, or distribution of this message is strictly prohibited.  Nothing in this email, including any attachment, is intended to be a legally binding signature.
*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100403/621c8021/attachment.html>

From rincewind668 at yahoo.com  Sat Apr  3 06:01:42 2010
From: rincewind668 at yahoo.com (kent morris)
Date: Fri, 2 Apr 2010 21:01:42 -0700 (PDT)
Subject: [Tutor] Using TAB in Python IDLE
Message-ID: <110349.60483.qm@web36204.mail.mud.yahoo.com>

I am just getting started programing in? python and am having a problem with the IDLE interface. When I type in an entry and hit the TAB key to enter a remark, I get a drop down menu of some kind, I don't know what this is for, I haven't gotten that far. All I want to do is TAB out to enter a comment. How do I turn this feature off? or work around it. I am using IDLE 3.1.2?





      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100402/3e747491/attachment.html>

From alan.gauld at btinternet.com  Sat Apr  3 14:08:20 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 3 Apr 2010 13:08:20 +0100
Subject: [Tutor] Display in a text field using tkinter
References: <m2gcf7f1f3e1004012325k3bdfc413pa919e33145ebd766@mail.gmail.com><x2l98c3f7c51004020626m45a53246s6b5d320417ae4301@mail.gmail.com>
	<711523.85184.qm@web34504.mail.mud.yahoo.com>
Message-ID: <hp7b43$njl$1@dough.gmane.org>


"doyin adegoke" <doyennehoney at yahoo.com> wrote

> I made the changes and the error was still there
>
> "print self.favorite.get()" prints the name of the selected database on 
> the console

The problem is that you are still calling grid when you create the widget.
grid() returns None so all your self.xxx attributes are set to None.

You must call grid after you create the widget.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From alan.gauld at btinternet.com  Sat Apr  3 14:12:47 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 3 Apr 2010 13:12:47 +0100
Subject: [Tutor] Using TAB in Python IDLE
References: <110349.60483.qm@web36204.mail.mud.yahoo.com>
Message-ID: <hp7bce$oc3$1@dough.gmane.org>


"kent morris" <rincewind668 at yahoo.com> wrote

> I am just getting started programing in python and am having
> a problem with the IDLE interface. When I type in an entry and
> hit the TAB key to enter a remark, I get a drop down menu of
> some kind, I don't know what this is for,

Neither do I from your description.

Can you tell us:

1) Which IDLE window are you using? The text editor or the
interactive prompt(>>>) aka Python Shell?

2) Can you cut n paste an example of where the "problem" occurs?
ie let us see *exactly* what you have typed.

3) Can you confirm that this happens when you type the TAB key?
I get various helpful things popping up in IDLE but none of them
use the TAB key.

> I haven't gotten that far. All I want to do is TAB out to enter a 
> comment.
> How do I turn this feature off or work around it. I am using IDLE 3.1.2?

I can use TAB to enter comments without any issues so we need
more detailed information.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From drwecki at gmail.com  Sun Apr  4 07:40:57 2010
From: drwecki at gmail.com (Brian Drwecki)
Date: Sun, 4 Apr 2010 00:40:57 -0500
Subject: [Tutor] Help with simple text book example that doesn't work!!!
Message-ID: <n2l15be17561004032240y9475550fl649271f123c74376@mail.gmail.com>

Hi all... I am working from the Learning Python 3rd edition published by
O'Reily... FYI I am trying to learn Python on my own (not for course credit
or anything).. I am a psychologist with very limited programming
experience.. I am anal, and this example code doesn't work.. I am using IDLE
to do everything (ni ni ni ni ni)

So here is the code the book give me..

while True:
    reply = raw_input('Enter text:')
    if reply == 'stop':
        break
    elif not reply.isdigit(  ):
        print 'Bad!' * 8
    else:
        print int(reply) ** 2
print 'Bye'


Idle gives me this error  SyntaxError: invalid syntax (it highlights the
word print in the print 'bye' line..

This bugs me!  I don't know why it's not working.. However, I know it is in
the print line... because When I get rid of print it does everything it is
supposed to do..it collects my input and provides feedback..

The print line is supposed to print 'Bye' when you type stop... The book
uses 2.5 I'm using 2.6, but I have no idea what is not working..Any hints?

All help is much appreciated!

Brian D
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100404/42f4cc19/attachment.html>

From steve at pearwood.info  Sun Apr  4 09:20:41 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 4 Apr 2010 18:20:41 +1100
Subject: [Tutor] Help with simple text book example that doesn't work!!!
In-Reply-To: <n2l15be17561004032240y9475550fl649271f123c74376@mail.gmail.com>
References: <n2l15be17561004032240y9475550fl649271f123c74376@mail.gmail.com>
Message-ID: <201004041720.42051.steve@pearwood.info>

On Sun, 4 Apr 2010 03:40:57 pm Brian Drwecki wrote:
> Hi all... I am working from the Learning Python 3rd edition published
> by O'Reily... FYI I am trying to learn Python on my own (not for
> course credit or anything).. I am a psychologist with very limited
> programming experience.. I am anal, and this example code doesn't
> work.. I am using IDLE to do everything (ni ni ni ni ni)
>
> So here is the code the book give me..
>
> while True:
>     reply = raw_input('Enter text:')
>     if reply == 'stop':
>         break
>     elif not reply.isdigit(  ):
>         print 'Bad!' * 8
>     else:
>         print int(reply) ** 2
> print 'Bye'
>
>
> Idle gives me this error  SyntaxError: invalid syntax (it highlights
> the word print in the print 'bye' line..

Please do an exact copy and paste of the error and post it, rather than 
paraphrasing the error.

In the meantime, a couple of guesses...

Are you sure you are using Python 2.6? If you are using 3.1, that would 
explain the failure. In Python 3, print stopped being a statement and 
became an ordinary function that requires parentheses.

In Python 2.6, one way to get that behaviour is with the special "from 
__future__ import" statement:

>>> from __future__ import print_function
>>> print "Hello world"
  File "<stdin>", line 1
    print "Hello world"
                      ^
SyntaxError: invalid syntax
>>> print("Hello world")
Hello world

Alternatively, sometimes if you have an error on one line, the 
interpreter doesn't see it until you get to the next, and then you get 
a SyntaxError on one line past the actual error.

E.g. if you forgot to close the bracket:

...
else:
    print int(reply ** 2
print 'Bye'

then you would (probably) get a SyntaxError on the line with the print.



-- 
Steven D'Aprano

From wescpy at gmail.com  Sun Apr  4 11:30:12 2010
From: wescpy at gmail.com (wesley chun)
Date: Sun, 4 Apr 2010 02:30:12 -0700
Subject: [Tutor] Help with simple text book example that doesn't work!!!
In-Reply-To: <201004041720.42051.steve@pearwood.info>
References: <n2l15be17561004032240y9475550fl649271f123c74376@mail.gmail.com>
	<201004041720.42051.steve@pearwood.info>
Message-ID: <t2x78b3a9581004040230i9a385012l766c23ed8d6efe3b@mail.gmail.com>

similarly, you get an error if:

"    print int(reply) ** 2
print 'Bye'"

... is all a single line and/or if you mixed spaces and TABs.

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

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

From neven.gorsic at gmail.com  Sun Apr  4 12:54:05 2010
From: neven.gorsic at gmail.com (=?UTF-8?B?TmV2ZW4gR29yxaFpxIc=?=)
Date: Sun, 4 Apr 2010 12:54:05 +0200
Subject: [Tutor] Menu data from file
Message-ID: <q2w8acd28da1004040354jb0284bdal9c61af6abff3154e@mail.gmail.com>

Hi!

I would like to import menu data from external txt file, but not as import
menudata.py, because then py2exe makes problems ...
I would like to preserve list structure like:

    (("File",
       ("&New\tCtrl+N", "Create new blank script", self.onNew),
       ("&Open\tCtrl+O", "Opens call script", self.onOpen),
       ("","",""),
       ("&Save\tCtrl+S", "Saves call script", self.onSave),
                  .  .  .

Thanks,

Neven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100404/3fd0ae07/attachment.html>

From drwecki at gmail.com  Sun Apr  4 15:15:20 2010
From: drwecki at gmail.com (Brian Drwecki)
Date: Sun, 4 Apr 2010 08:15:20 -0500
Subject: [Tutor] Help with simple text book example that doesn't work!!!
In-Reply-To: <201004041720.42051.steve@pearwood.info>
References: <n2l15be17561004032240y9475550fl649271f123c74376@mail.gmail.com>
	<201004041720.42051.steve@pearwood.info>
Message-ID: <k2j15be17561004040615qe414602w2a3bdd8a3c4594b@mail.gmail.com>

Python version


Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)]
on win32
Type "copyright", "credits" or "license()" for more information


As for the exact error code....here it is.

>>>
while True:
    reply = raw_input('Enter text:')
    if reply == 'stop':
        break
    elif not reply.isdigit(  ):
        print 'Bad!' * 8
    else:
        print int(reply) ** 2
print 'bye'
SyntaxError: invalid syntax  (note it highlights the print code)...

This works!!!
>>> print'bye'
bye
>>>



I tried adding parantheses around the print in the code and get the same
error


It only says SyntaxError:invalid syntax and it highlights the print word..



According to the book, this print should work, but it doesn't?   Any
thoughts? Does it work on your computer?



On Sun, Apr 4, 2010 at 2:20 AM, Steven D'Aprano <steve at pearwood.info> wrote:

> On Sun, 4 Apr 2010 03:40:57 pm Brian Drwecki wrote:
> > Hi all... I am working from the Learning Python 3rd edition published
> > by O'Reily... FYI I am trying to learn Python on my own (not for
> > course credit or anything).. I am a psychologist with very limited
> > programming experience.. I am anal, and this example code doesn't
> > work.. I am using IDLE to do everything (ni ni ni ni ni)
> >
> > So here is the code the book give me..
> >
> > while True:
> >     reply = raw_input('Enter text:')
> >     if reply == 'stop':
> >         break
> >     elif not reply.isdigit(  ):
> >         print 'Bad!' * 8
> >     else:
> >         print int(reply) ** 2
> > print 'Bye'
> >
> >
> > Idle gives me this error  SyntaxError: invalid syntax (it highlights
> > the word print in the print 'bye' line..
>
> Please do an exact copy and paste of the error and post it, rather than
> paraphrasing the error.
>
> In the meantime, a couple of guesses...
>
> Are you sure you are using Python 2.6? If you are using 3.1, that would
> explain the failure. In Python 3, print stopped being a statement and
> became an ordinary function that requires parentheses.
>
> In Python 2.6, one way to get that behaviour is with the special "from
> __future__ import" statement:
>
> >>> from __future__ import print_function
> >>> print "Hello world"
>  File "<stdin>", line 1
>    print "Hello world"
>                      ^
> SyntaxError: invalid syntax
> >>> print("Hello world")
> Hello world
>
> Alternatively, sometimes if you have an error on one line, the
> interpreter doesn't see it until you get to the next, and then you get
> a SyntaxError on one line past the actual error.
>
> E.g. if you forgot to close the bracket:
>
> ...
> else:
>    print int(reply ** 2
> print 'Bye'
>
> then you would (probably) get a SyntaxError on the line with the print.
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100404/f8732525/attachment.html>

From hugo.yoshi at gmail.com  Sun Apr  4 16:05:10 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sun, 4 Apr 2010 16:05:10 +0200
Subject: [Tutor] Help with simple text book example that doesn't work!!!
In-Reply-To: <k2j15be17561004040615qe414602w2a3bdd8a3c4594b@mail.gmail.com>
References: <n2l15be17561004032240y9475550fl649271f123c74376@mail.gmail.com> 
	<201004041720.42051.steve@pearwood.info>
	<k2j15be17561004040615qe414602w2a3bdd8a3c4594b@mail.gmail.com>
Message-ID: <n2o29179d161004040705g497f41b0j53c813b931cf9e04@mail.gmail.com>

On Sun, Apr 4, 2010 at 3:15 PM, Brian Drwecki <drwecki at gmail.com> wrote:
>
> As for the exact error code....here it is.
>
>>>>
> while True:
> ??? reply = raw_input('Enter text:')
> ??? if reply == 'stop':
> ??????? break
> ??? elif not reply.isdigit(? ):
> ??????? print 'Bad!' * 8
> ??? else:
> ??????? print int(reply) ** 2
> print 'bye'
> SyntaxError: invalid syntax? (note it highlights the print code)...
>
> This works!!!
>>>> print'bye'
> bye
>>>>
>

the interactive interpreter is a comparatively simple machine.
Notably, it expects you to type only a single statement at a time. It
may be a compound statement or a simple statement, but it must be only
one statement. Your code, at the top level consists of two statements,
a 'while' statement (which is compound) and a print statement. The
interpreter expects only a single statement, and complains when it
finds the second one:


In [2]: if True:
   ...:     print "inside statement one"
   ...: print "inside statement two"
------------------------------------------------------------
   File "<ipython console>", line 3
     print "inside statement two"
         ^
SyntaxError: invalid syntax

In [3]:

If you embed these two statements inside a single compound statement
(whether that is a loop, conditional, function, whatever) the
interpreter will stop complaining again, since the top-level statement
again consists of only a single statement:

In [8]: if True:
   ...:     if True:
   ...:         print "sub-statement one"
   ...:     print "sub-statement two"
   ...:
sub-statement one
sub-statement two
In [9]:

Note that when interpreting a python script, there is no such
limitation, and multiple top-level statements are perfectly fine.

I haven't read the source, but my guess is that when parsing python
source code, the parser uses a StatementList AST node as the root to
parse a list of statements, while the interactive interpreter doesn't
create this AST node. That's why it's limited to a single statement at
a time.

HTH,
Hugo

From alan.gauld at btinternet.com  Sun Apr  4 19:05:50 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 4 Apr 2010 18:05:50 +0100
Subject: [Tutor] Menu data from file
References: <q2w8acd28da1004040354jb0284bdal9c61af6abff3154e@mail.gmail.com>
Message-ID: <hpagtu$v8h$1@dough.gmane.org>


"Neven Gorsic" <neven.gorsic at gmail.com> wrote

> I would like to import menu data from external txt file, but not as 
> import
> menudata.py, because then py2exe makes problems ...
> I would like to preserve list structure like:

Yes that's a good idea.

>    (("File",
>       ("&New\tCtrl+N", "Create new blank script", self.onNew),
>       ("&Open\tCtrl+O", "Opens call script", self.onOpen),
>       ("","",""),
>       ("&Save\tCtrl+S", "Saves call script", self.onSave),
>                  .  .  .
>
> Thanks,

You're welcome.

Or do you have a problem with implementing it?
If so what? What did you try? What happened?
Oh, and it will help to tell us which GUI toolkit
you are using too?


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From shurui91 at gmail.com  Sun Apr  4 20:05:47 2010
From: shurui91 at gmail.com (Shurui Liu (Aaron Liu))
Date: Sun, 4 Apr 2010 14:05:47 -0400
Subject: [Tutor] constructor
Message-ID: <j2t2b9003cf1004041105z900fd5b2ld5688df802c05c79@mail.gmail.com>

I am studying about how to create a constructor in a Python program, I
don't really understand why the program print out "A new critter has
been born!" and "Hi.  I'm an instance of class Critter." twice. I
guess is because "crit1 = Critter()     crit2 = Critter()"  But I
don't understand how did computer understand the difference between
crit1 and crit2? cause both of them are equal to Critter(). Thank you!

# Constructor Critter
# Demonstrates constructors

class Critter(object):
    """A virtual pet"""
    def __init__(self):
        print "A new critter has been born!"

    def talk(self):
        print "\nHi.  I'm an instance of class Critter."

# main
crit1 = Critter()
crit2 = Critter()

crit1.talk()
crit2.talk()

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


-- 
Shurui Liu (Aaron Liu)
Computer Science & Engineering Technology
University of Toledo
419-508-1228

From shurui91 at gmail.com  Sun Apr  4 20:11:42 2010
From: shurui91 at gmail.com (Shurui Liu (Aaron Liu))
Date: Sun, 4 Apr 2010 14:11:42 -0400
Subject: [Tutor] constructor
In-Reply-To: <j2t2b9003cf1004041105z900fd5b2ld5688df802c05c79@mail.gmail.com>
References: <j2t2b9003cf1004041105z900fd5b2ld5688df802c05c79@mail.gmail.com>
Message-ID: <q2g2b9003cf1004041111jfd01f61ex7baa03d1a09aa81b@mail.gmail.com>

Sorry, let me specify. I think comptuter will print out those two
sentences like this:

A new critter has been born!

Hi.  I'm an instance of class Critter.
A new critter has been born!


Hi.  I'm an instance of class Critter.



But the result I got from computer is like this:
A new critter has been born!
A new critter has been born!

Hi.  I'm an instance of class Critter.

Hi.  I'm an instance of class Critter.


On Sun, Apr 4, 2010 at 2:05 PM, Shurui Liu (Aaron Liu)
<shurui91 at gmail.com> wrote:
> I am studying about how to create a constructor in a Python program, I
> don't really understand why the program print out "A new critter has
> been born!" and "Hi. ?I'm an instance of class Critter." twice. I
> guess is because "crit1 = Critter() ? ? crit2 = Critter()" ?But I
> don't understand how did computer understand the difference between
> crit1 and crit2? cause both of them are equal to Critter(). Thank you!
>
> # Constructor Critter
> # Demonstrates constructors
>
> class Critter(object):
> ? ?"""A virtual pet"""
> ? ?def __init__(self):
> ? ? ? ?print "A new critter has been born!"
>
> ? ?def talk(self):
> ? ? ? ?print "\nHi. ?I'm an instance of class Critter."
>
> # main
> crit1 = Critter()
> crit2 = Critter()
>
> crit1.talk()
> crit2.talk()
>
> raw_input("\n\nPress the enter key to exit.")
>
>
> --
> Shurui Liu (Aaron Liu)
> Computer Science & Engineering Technology
> University of Toledo
> 419-508-1228
>



-- 
Shurui Liu (Aaron Liu)
Computer Science & Engineering Technology
University of Toledo
419-508-1228

From lie.1296 at gmail.com  Sun Apr  4 20:27:00 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Mon, 05 Apr 2010 04:27:00 +1000
Subject: [Tutor] constructor
In-Reply-To: <q2g2b9003cf1004041111jfd01f61ex7baa03d1a09aa81b@mail.gmail.com>
References: <j2t2b9003cf1004041105z900fd5b2ld5688df802c05c79@mail.gmail.com>
	<q2g2b9003cf1004041111jfd01f61ex7baa03d1a09aa81b@mail.gmail.com>
Message-ID: <hpaln8$d51$1@dough.gmane.org>

On 04/05/10 04:11, Shurui Liu (Aaron Liu) wrote:

> But the result I got from computer is like this:
> A new critter has been born!
> A new critter has been born!
> 
> Hi.  I'm an instance of class Critter.
> 
> Hi.  I'm an instance of class Critter.

Because you tell it to do it in that order:

crit1 = Critter() # A new critter has been born
crit2 = Critter() # A new critter has been born
crit1.talk() # Hi.  I'm an instance of class Critter.
crit2.talk() # Hi.  I'm an instance of class Critter.



From emile at fenx.com  Sun Apr  4 20:37:36 2010
From: emile at fenx.com (Emile van Sebille)
Date: Sun, 04 Apr 2010 11:37:36 -0700
Subject: [Tutor] constructor
In-Reply-To: <q2g2b9003cf1004041111jfd01f61ex7baa03d1a09aa81b@mail.gmail.com>
References: <j2t2b9003cf1004041105z900fd5b2ld5688df802c05c79@mail.gmail.com>
	<q2g2b9003cf1004041111jfd01f61ex7baa03d1a09aa81b@mail.gmail.com>
Message-ID: <hpam9l$f5m$1@dough.gmane.org>

On 4/4/2010 11:11 AM Shurui Liu (Aaron Liu) said...
> Sorry, let me specify. I think comptuter will print out those two
> sentences like this:
>

It's a little more interesting as you move forward from here.  This is a 
small step...

class Critter(object):
     """A virtual pet"""
     def __init__(self,name):
         print "A new critter has been born!"
         self.name = name
     def talk(self):
         print "\nHi.  I'm %s, an instance of class Critter." % self.name


# main
crit1 = Critter('Polly')
crit2 = Critter('Spot')

crit1.talk()
crit2.talk()

HTH,

Emile


From galaxywatcher at gmail.com  Sun Apr  4 23:18:48 2010
From: galaxywatcher at gmail.com (TGW)
Date: Sun, 4 Apr 2010 17:18:48 -0400
Subject: [Tutor] Matching zipcode in address file
Message-ID: <EA75AA6A-400E-48D7-ACB7-F3569F7358F0@gmail.com>

I wrote a script that compares two text files (one zip code file, and  
one address file)  and tries to output records that match the  
zipcodes. Here is what I have so far:

#!/usr/bin/env python
# Find records that match zipcodes in zips.txt

def main():
     infile = open("/Users/tgw/NM_2010/NM_APR.txt", "r")
     outfile = open("zip_match_apr_2010.txt", "w")
     match_zips = open("zips.txt", "r")

     lines = [line for line in infile if line[149:154] in match_zips]  
# *** I think the problem is here ***

     outfile.write(''.join(lines))
     infile.close()
     outfile.close()
main()

I go the program functioning with
lines = [line for line in infile if line[149:154] not in match_zips]

But this matches records that do NOT match zipcodes. How do I get this  
running so that it matches zips?

Thanks

From alan.gauld at btinternet.com  Mon Apr  5 00:29:50 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Sun, 4 Apr 2010 22:29:50 +0000 (GMT)
Subject: [Tutor] Fw:  Menu data from file
In-Reply-To: <hpagtu$v8h$1@dough.gmane.org>
References: <q2w8acd28da1004040354jb0284bdal9c61af6abff3154e@mail.gmail.com>
	<hpagtu$v8h$1@dough.gmane.org>
Message-ID: <562203.58595.qm@web86703.mail.ird.yahoo.com>

forwarding to the list.

Please use Reply All when replying to the 
list otherwise it is only a reply to the 
original poster.

 Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/



>
>----- Forwarded Message ----
>From: Neven Gor?i? <neven.gorsic at gmail.com>
>To: Alan Gauld <alan.gauld at btinternet.com>
>Sent: Sunday, 4 April, 2010 22:39:41
>Subject: Re: [Tutor] Menu data from file
>
>I can not loop over each list item like:
>
>                    for eachMenuData in self.menuData():
>
>because when I read external txt file:
>
>                    f=open(listFile,'r')
>                    lines=f.readlines()
>>                    f.close()
>
>I get the list of file lines instead of list of external list (tuple) 
>elements.
>And if I join that in one string (or use read() instead of readlines()) loop
>goes through every character, again not getting tuple/list elements....
>
>Neven
>
>---------------------------------------
>
>
>
>On Sun, Apr 4, 2010 at 7:05 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>
>>>>"Neven Gorsic" <neven.gorsic at gmail.com> wrote
>>
>>
>>
>>>>>I would like to import menu data from external txt file, but not as import
>>>>>>menudata.py, because then py2exe makes problems ...
>>>>>>I would like to preserve list structure like:
>>>
>>
>>Yes that's a good idea.
>>
>>
>>
>>>>>   (("File",
>>>>>>      ("&New\tCtrl+N", "Create new blank script", self.onNew),
>>>>>>      ("&Open\tCtrl+O", "Opens call script", self.onOpen),
>>>>>>      ("","",""),
>>>>>>      ("&Save\tCtrl+S", "Saves call script", self.onSave),
>>>>>>                 .  .  .
>>>
>>>>>>Thanks,
>>>
>>
>>You're welcome.
>>
>>>>Or do you have a problem with implementing it?
>>>>If so what? What did you try? What happened?
>>>>Oh, and it will help to tell us which GUI toolkit
>>>>you are using too?
>>
>>
>>>>-- 
>>>>Alan Gauld
>>>>Author of the Learn to Program web site
>>http://www.alan-g.me.uk/ 
>>
>>>>_______________________________________________
>>>>Tutor maillist  -  Tutor at python.org
>>>>To unsubscribe or change subscription options:
>>http://mail.python.org/mailman/listinfo/tutor
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100404/6895b842/attachment.html>

From davea at ieee.org  Mon Apr  5 00:45:29 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 04 Apr 2010 18:45:29 -0400
Subject: [Tutor] constructor
In-Reply-To: <j2t2b9003cf1004041105z900fd5b2ld5688df802c05c79@mail.gmail.com>
References: <j2t2b9003cf1004041105z900fd5b2ld5688df802c05c79@mail.gmail.com>
Message-ID: <4BB91689.8000800@ieee.org>



Shurui Liu (Aaron Liu) wrote:
> I am studying about how to create a constructor in a Python program, I
> don't really understand why the program print out "A new critter has
> been born!" and "Hi.  I'm an instance of class Critter." twice. I
> guess is because "crit1 = Critter()     crit2 = Critter()"  But I
> don't understand how did computer understand the difference between
> crit1 and crit2? cause both of them are equal to Critter(). Thank you!
>
> # Constructor Critter
> # Demonstrates constructors
>
> class Critter(object):
>     """A virtual pet"""
>     def __init__(self):
>         print "A new critter has been born!"
>
>     def talk(self):
>         print "\nHi.  I'm an instance of class Critter."
>
> # main
> crit1 = Critter()
> crit2 = Critter()
>
> crit1.talk()
> crit2.talk()
>
> raw_input("\n\nPress the enter key to exit.")
>
>
>   
Critter is a class, not a function.  So the syntax
   crit1 = Critter()

is not calling a "Critter" function but constructing an instance of the 
Critter class.  You can tell that by doing something like
  print crit1
  print crit2

Notice that although both objects have the same type (or class), they 
have different ID values.

Since you supply an __init__() method in the class, that's called during 
construction of each object.  So you see that it executes twice.

Classes start to get interesting once you have instance attributes, so 
that each instance has its own "personality."  You can add attributes 
after the fact, or you can define them in __init__().  Simplest example 
could be:

crit1.name = "Spot"
crit2.name = "Fido"

Then you can do something like
  print crit1.name
  print crit2.name

and you'll see they really are different.

DaveA




From alan.gauld at btinternet.com  Mon Apr  5 00:46:50 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 4 Apr 2010 23:46:50 +0100
Subject: [Tutor] constructor
References: <j2t2b9003cf1004041105z900fd5b2ld5688df802c05c79@mail.gmail.com>
	<q2g2b9003cf1004041111jfd01f61ex7baa03d1a09aa81b@mail.gmail.com>
Message-ID: <hpb4ta$mo5$1@dough.gmane.org>

"Shurui Liu (Aaron Liu)" <shurui91 at gmail.com> wrote

> Sorry, let me specify. I think comptuter will print out those two
> sentences like this:
>
> A new critter has been born!
> Hi.  I'm an instance of class Critter.
> A new critter has been born!
> Hi.  I'm an instance of class Critter.

> class Critter(object):
> """A virtual pet"""
> def __init__(self):
> print "A new critter has been born!"

Here you are calling print inside the constructor (actually the 
initialiser)
method which gets called when you create a new object

> def talk(self):
> print "\nHi. I'm an instance of class Critter."

Here you are calling print inside a method that only gets executed
when explicitly called from the created object


> crit1 = Critter()
> crit2 = Critter()

Here you create two objects so the constructor method will be executed 
twice.
So you get the message

A new critter has been born!"

twice.

> crit1.talk()
> crit2.talk()

Then you call the talk method for each object so you get

Hi. I'm an instance of class Critter.

twice.

The __init__() method is nothing too special. It gets called
automatically when you create the object is all. You can think
of

crit = Critter()

as effectively being a call to Critter.__init__()

There is a little bit more to it that that but most of the time its
close enough.

You can read an alternative explanation in the OOP topic
of my tutorial...

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From alan.gauld at btinternet.com  Mon Apr  5 00:49:02 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 4 Apr 2010 23:49:02 +0100
Subject: [Tutor] Matching zipcode in address file
References: <EA75AA6A-400E-48D7-ACB7-F3569F7358F0@gmail.com>
Message-ID: <hpb51f$mvs$1@dough.gmane.org>


"TGW" <galaxywatcher at gmail.com> wrote

> I go the program functioning with
> lines = [line for line in infile if line[149:154] not in match_zips]
> 
> But this matches records that do NOT match zipcodes. How do I get this  
> running so that it matches zips?


Take out the word 'not' from the comprehension?

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Mon Apr  5 00:54:40 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 4 Apr 2010 23:54:40 +0100
Subject: [Tutor] Menu data from file
References: <q2w8acd28da1004040354jb0284bdal9c61af6abff3154e@mail.gmail.com><hpagtu$v8h$1@dough.gmane.org>
	<562203.58595.qm@web86703.mail.ird.yahoo.com>
Message-ID: <hpb5c1$nm2$1@dough.gmane.org>

>I can not loop over each list item like:
>
>                    for eachMenuData in self.menuData():
>
>because when I read external txt file:
>
>                    f=open(listFile,'r')
>                    lines=f.readlines()
>>                    f.close()
>
>I get the list of file lines instead of list of external list (tuple)
>elements.

Thats right you will need to parse the data to convert it into the format 
you want.
This is one reason you might find it easier to use XML for storing the data
and use a tool like ElementCTree to parse it.

Alternatively you could make your data file a Python module and import it

import menudata

for eachMenuData in menudata.menuData:

Or another option is to store the data as a tuple in a pickle or shelve 
file.
But they you need to create it from Python initially.

My personal favourite for this kind of application is the module approach.
Just edit the menu module when you want to modify the menu structure
and the import will see it as Python data.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From lie.1296 at gmail.com  Mon Apr  5 02:19:02 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Mon, 05 Apr 2010 10:19:02 +1000
Subject: [Tutor] Menu data from file
In-Reply-To: <hpb5c1$nm2$1@dough.gmane.org>
References: <q2w8acd28da1004040354jb0284bdal9c61af6abff3154e@mail.gmail.com><hpagtu$v8h$1@dough.gmane.org>	<562203.58595.qm@web86703.mail.ird.yahoo.com>
	<hpb5c1$nm2$1@dough.gmane.org>
Message-ID: <hpbabb$3ab$1@dough.gmane.org>

On 04/05/10 08:54, Alan Gauld wrote:
> Thats right you will need to parse the data to convert it into the
> format you want.
> This is one reason you might find it easier to use XML for storing the data
> and use a tool like ElementCTree to parse it.

s/ElementCTree/ElementTree/?


From bgailer at gmail.com  Mon Apr  5 02:24:52 2010
From: bgailer at gmail.com (bob gailer)
Date: Sun, 04 Apr 2010 20:24:52 -0400
Subject: [Tutor] Matching zipcode in address file
In-Reply-To: <EA75AA6A-400E-48D7-ACB7-F3569F7358F0@gmail.com>
References: <EA75AA6A-400E-48D7-ACB7-F3569F7358F0@gmail.com>
Message-ID: <4BB92DD4.20302@gmail.com>

On 4/4/2010 5:18 PM, TGW wrote:
> I wrote a script that compares two text files (one zip code file, and 
> one address file)  and tries to output records that match the 
> zipcodes. Here is what I have so far:
>
> #!/usr/bin/env python
> # Find records that match zipcodes in zips.txt
>
> def main():
>     infile = open("/Users/tgw/NM_2010/NM_APR.txt", "r")
>     outfile = open("zip_match_apr_2010.txt", "w")
>     match_zips = open("zips.txt", "r")
>
>     lines = [line for line in infile if line[149:154] in match_zips] # 
> *** I think the problem is here ***

Yep. You are right.

Try a very simple test case; see if you can figure out what's happening:

infile:
123
234
345

match_zips:
123
234
345

infile = open("infile")
match_zips = open("match_zips")
[line for line in infile if line in match_zips]

Now change infile:
123
244
345
and run the program again.

Interesting, no. Does that give you any insights?

>
>     outfile.write(''.join(lines))
>     infile.close()
>     outfile.close()
> main()
>
> I go the program functioning with
> lines = [line for line in infile if line[149:154] not in match_zips]
>
> But this matches records that do NOT match zipcodes. How do I get this 
> running so that it matches zips?
>
> Thanks

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From bgailer at gmail.com  Mon Apr  5 05:47:28 2010
From: bgailer at gmail.com (bob gailer)
Date: Sun, 04 Apr 2010 23:47:28 -0400
Subject: [Tutor] Matching zipcode in address file
In-Reply-To: <C66ED2F5-F1F6-4156-A184-ABBC58B81993@gmail.com>
References: <C66ED2F5-F1F6-4156-A184-ABBC58B81993@gmail.com>
Message-ID: <4BB95D50.7090301@gmail.com>

Please reply-all so a copy goes to the list.

On 4/4/2010 10:02 PM, TGW wrote:
>> >/  I wrote a script that compares two text files (one zip code file, and
>> />/  one address file)  and tries to output records that match the
>> />/  zipcodes. Here is what I have so far:
>> />/
>> />/  #!/usr/bin/env python
>> />/  # Find records that match zipcodes in zips.txt
>> />/
>> />/  def main():
>> />/      infile = open("/Users/tgw/NM_2010/NM_APR.txt", "r")
>> />/      outfile = open("zip_match_apr_2010.txt", "w")
>> />/      match_zips = open("zips.txt", "r")
>> />/
>> />/      lines = [line for line in infile if line[149:154] in match_zips] #
>> />/  *** I think the problem is here ***
>> /
>> Yep. You are right.
>>
>> Try a very simple test case; see if you can figure out what's happening:
>>
>> infile:
>> 123
>> 234
>> 345
>>
>> match_zips:
>> 123
>> 234
>> 345
>>
>> infile = open("infile")
>> match_zips = open("match_zips")
>> [line for line in infile if line in match_zips]
>>
>> Now change infile:
>> 123
>> 244
>> 345
>> and run the program again.
>>
>> Interesting, no. Does that give you any insights?
> I think I am just lost on this one. I have no new insights. What is the exact program that you want me to run?
> #!/usr/bin/env python
>
> infile = open("filex")
> match_zips = open("zippys")
> [line for line in infile if line in match_zips]
> print line
> I did what you said and I get '345' output both times.

Sorry - my mistake - try:

infile = open("filex")
match_zips = open("zippys")
result = [line for line in infile if line in match_zips]
print result



-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100404/5349b69f/attachment-0001.html>

From galaxywatcher at gmail.com  Mon Apr  5 06:56:23 2010
From: galaxywatcher at gmail.com (TGW)
Date: Mon, 5 Apr 2010 00:56:23 -0400
Subject: [Tutor] Matching zipcode in address file
In-Reply-To: <4BB95D50.7090301@gmail.com>
References: <C66ED2F5-F1F6-4156-A184-ABBC58B81993@gmail.com>
	<4BB95D50.7090301@gmail.com>
Message-ID: <A29F1213-A702-4454-91C6-23626864A224@gmail.com>


> Sorry - my mistake - try:
>
> infile = open("filex")
> match_zips = open("zippys")
> result = [line for line in infile if line in match_zips]
> print result
ok....Thanks...This should do it:

#!/usr/bin/env python

infile = open("filex")
zips = open("zippys")
match_zips = zips.readlines()
results = [line for line in infile if line in match_zips]
print results



From galaxywatcher at gmail.com  Mon Apr  5 07:15:35 2010
From: galaxywatcher at gmail.com (TGW)
Date: Mon, 5 Apr 2010 01:15:35 -0400
Subject: [Tutor] Matching zipcode in address file
In-Reply-To: <4BB95D50.7090301@gmail.com>
References: <C66ED2F5-F1F6-4156-A184-ABBC58B81993@gmail.com>
	<4BB95D50.7090301@gmail.com>
Message-ID: <C897F917-052C-4D33-9559-E18A33E2B4FA@gmail.com>

> Sorry - my mistake - try:
>
> infile = open("filex")
> match_zips = open("zippys")
> result = [line for line in infile if line in match_zips]
> print result
When I apply the readlines to the original file, It is taking a lot  
longer to process and the outfile still remains blank. Any suggestions?

#!/usr/bin/env python
# Find records that match zipcodes in zips.txt

import os
import sys

def main():
     infile = open("/Users/tgw/NM_2010/NM_APR.txt", "r")
     outfile = open("zip_match_apr_2010.txt", "w")
     zips = open("zips.txt", "r")
     match_zips = zips.readlines()
     lines = [ line for line in infile if line[149:154] in match_zips ]

     outfile.write(''.join(lines))
#    print line[149:154]
     print lines
     infile.close()
     outfile.close()
main()



From davea at ieee.org  Mon Apr  5 08:32:18 2010
From: davea at ieee.org (Dave Angel)
Date: Mon, 05 Apr 2010 02:32:18 -0400
Subject: [Tutor] Matching zipcode in address file
In-Reply-To: <hpb51f$mvs$1@dough.gmane.org>
References: <EA75AA6A-400E-48D7-ACB7-F3569F7358F0@gmail.com>
	<hpb51f$mvs$1@dough.gmane.org>
Message-ID: <4BB983F2.3030002@ieee.org>

Alan Gauld wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">
> "TGW" <galaxywatcher at gmail.com> wrote
>
>> I go the program functioning with
>> lines = [line for line in infile if line[149:154] not in match_zips]
>>
>> But this matches records that do NOT match zipcodes. How do I get 
>> this  running so that it matches zips?
>
>
> Take out the word 'not' from the comprehension?
>
That's one change.  But more fundamental is to change the file I/O.  
Since there's no seek() operation, the file continues wherever it left 
off the previous time.

I'd suggest reading the data from the match_zips into a list, and if the 
format isn't correct, doing some post-processing on it.  But there's no 
way to advise on that since we weren't given the format of either file.

zipdata = match_zips.readlines()
Then you can do an      if XXX in zipdata with assurance.

DaveA


From galaxywatcher at gmail.com  Mon Apr  5 08:51:47 2010
From: galaxywatcher at gmail.com (TGW)
Date: Mon, 5 Apr 2010 02:51:47 -0400
Subject: [Tutor] Matching zipcode in address file
In-Reply-To: <4BB983F2.3030002@ieee.org>
References: <EA75AA6A-400E-48D7-ACB7-F3569F7358F0@gmail.com>
	<hpb51f$mvs$1@dough.gmane.org> <4BB983F2.3030002@ieee.org>
Message-ID: <89583FAF-1EEA-484B-9145-20C034CBA6E6@gmail.com>

> I'd suggest reading the data from the match_zips into a list, and if  
> the format isn't correct, doing some post-processing on it.  But  
> there's no way to advise on that since we weren't given the format  
> of either file.
>
> zipdata = match_zips.readlines()
> Then you can do an      if XXX in zipdata with assurance.

Here is a simplified version of the program:
#!/usr/bin/env python

def main():
      infile = open("filex")
      outfile = open("results_testx", "w")
      zips = open("zippys")
      match_zips = zips.readlines()
      results = [line for line in infile if line[0:2] in match_zips]
      outfile.write(''.join(results))

      zips.close()
      infile.close()
      outfile.close()
main()

filex:
112332424
23423423423
34523423423
456234234234
234234234234
5672342342
67824242

zippys:
567
678
555

I want to output the lines in filex that match the the first 3 chars  
of zippys.

output:
5672342342
67824242

From alan.gauld at btinternet.com  Mon Apr  5 09:18:43 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 5 Apr 2010 07:18:43 +0000 (GMT)
Subject: [Tutor] Matching zipcode in address file
In-Reply-To: <5D62DA24-29DC-4A42-B5A8-0E7E1F736052@gmail.com>
References: <5D62DA24-29DC-4A42-B5A8-0E7E1F736052@gmail.com>
Message-ID: <648206.12699.qm@web86703.mail.ird.yahoo.com>

Please use Reply All whern responding to the list.

 

> lines = [line for line in infile if line[149:154] not in match_zips]
>
>Nope. I tried that. I actually modified your comprehension 
>that you provided about a month ago. 
>Works great for NOT matching, but can't figure out how to match. 
>Do you have another suggestion?def main():
>
>     infile = open("/Users/tgw/NM_2010/NM_APR.txt", "r")
>     outfile = open("zip_match_apr_2010.txt", "w")
>     match_zips = open("zips.txt", "r")
>
>You probably are best to read the zips file into a list, 
>stripping the newlines: 
>
>
>matchzips = [match.strip() for match in open('zips.txt')]
>
>then
>
>     lines = [line for line in infile if line[149:154] in match_zips] 
>Should work...
Either that or add a newline to the end of the slice.

HTH,

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100405/e8f12799/attachment.html>

From neven.gorsic at gmail.com  Mon Apr  5 09:39:32 2010
From: neven.gorsic at gmail.com (=?UTF-8?B?TmV2ZW4gR29yxaFpxIc=?=)
Date: Mon, 5 Apr 2010 09:39:32 +0200
Subject: [Tutor] Menu data from file
In-Reply-To: <hpbabb$3ab$1@dough.gmane.org>
References: <q2w8acd28da1004040354jb0284bdal9c61af6abff3154e@mail.gmail.com>
	<hpagtu$v8h$1@dough.gmane.org>
	<562203.58595.qm@web86703.mail.ird.yahoo.com>
	<hpb5c1$nm2$1@dough.gmane.org> <hpbabb$3ab$1@dough.gmane.org>
Message-ID: <t2h8acd28da1004050039q9f3d49diac6aefe1d467b0b6@mail.gmail.com>

Thank you for mentioning the possible options.
I already use option where I import .py module,
but I run into troubles when making executable with py2exe.

I suppose that XML approach is the most general method.
Can you recommend a good introduction text (not for experts :-))
and give more details about the tool ElementCTree.

Maybe it will be educational and interesting for other beginners too.

Thanks,

Neven

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

On Mon, Apr 5, 2010 at 2:19 AM, Lie Ryan <lie.1296 at gmail.com> wrote:

> On 04/05/10 08:54, Alan Gauld wrote:
> > Thats right you will need to parse the data to convert it into the
> > format you want.
> > This is one reason you might find it easier to use XML for storing the
> data
> > and use a tool like ElementCTree to parse it.
>
> s/ElementCTree/ElementTree/?
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100405/85f0c6e5/attachment.html>

From bgailer at gmail.com  Mon Apr  5 14:19:56 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 05 Apr 2010 08:19:56 -0400
Subject: [Tutor] Matching zipcode in address file
In-Reply-To: <C897F917-052C-4D33-9559-E18A33E2B4FA@gmail.com>
References: <C66ED2F5-F1F6-4156-A184-ABBC58B81993@gmail.com>
	<4BB95D50.7090301@gmail.com>
	<C897F917-052C-4D33-9559-E18A33E2B4FA@gmail.com>
Message-ID: <4BB9D56C.8020704@gmail.com>

On 4/5/2010 1:15 AM, TGW wrote:
>> Sorry - my mistake - try:
>>
>> infile = open("filex")
>> match_zips = open("zippys")
>> result = [line for line in infile if line in match_zips]
>> print result
> When I apply the readlines to the original file, It is taking a lot 
> longer to process and the outfile still remains blank. Any suggestions?

OK - you handled the problem regarding reading to end-of-file. Yes it 
takes a lot longer, because now you are actually iterating through 
match_zips for each line.

How large are these files? Consider creating a set from match_zips. As 
lists get longer, set membership test become faster than list membership 
test.

If the outfile is empty that means that line[149:154] is never in 
match_zips.

I suggest you take a look at match_zips. You will find a list of strings 
of length 6, which cannot match line[149:154], a string of length 5.

>
> #!/usr/bin/env python
> # Find records that match zipcodes in zips.txt
>
> import os
> import sys
>
> def main():
>     infile = open("/Users/tgw/NM_2010/NM_APR.txt", "r")
>     outfile = open("zip_match_apr_2010.txt", "w")
>     zips = open("zips.txt", "r")
>     match_zips = zips.readlines()
>     lines = [ line for line in infile if line[149:154] in match_zips ]
>
>     outfile.write(''.join(lines))
> #    print line[149:154]
>     print lines
>     infile.close()
>     outfile.close()
> main()
>
>
>


-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From lie.1296 at gmail.com  Mon Apr  5 16:03:39 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Tue, 06 Apr 2010 00:03:39 +1000
Subject: [Tutor] Menu data from file
In-Reply-To: <t2h8acd28da1004050039q9f3d49diac6aefe1d467b0b6@mail.gmail.com>
References: <q2w8acd28da1004040354jb0284bdal9c61af6abff3154e@mail.gmail.com>	<hpagtu$v8h$1@dough.gmane.org>	<562203.58595.qm@web86703.mail.ird.yahoo.com>	<hpb5c1$nm2$1@dough.gmane.org>
	<hpbabb$3ab$1@dough.gmane.org>
	<t2h8acd28da1004050039q9f3d49diac6aefe1d467b0b6@mail.gmail.com>
Message-ID: <hpcqlg$ptv$1@dough.gmane.org>

On 04/05/10 17:39, Neven Gor?i? wrote:
> Thank you for mentioning the possible options.
> I already use option where I import .py module,
> but I run into troubles when making executable with py2exe.

Maybe you should elaborate what problems you're experiencing with
py2exe? Probably we can solve that instead of developing workarounds.

Many popular UI toolkit provides an XML-based menu file.
Here is one for PyGTK:
http://www.pygtk.org/pygtk2tutorial/sec-UIManager.html

You should better use your GUI toolkit's version instead of writing your
own.

> I suppose that XML approach is the most general method.
> Can you recommend a good introduction text (not for experts :-))
> and give more details about the tool ElementCTree.
> 
> Maybe it will be educational and interesting for other beginners too.

ElementTree is quite simple, though I don't think there are many good
tutorials about it (at least I can't find one). In the simplest use
case, you just use xml.etree.ElementTree.parse("menu.xml") and you can
iterate the tree like so:

import xml.etree.cElementTree as Et
menuxml = """
<menubar>
  <menu title="File">
    <menuitem title="Open File..." action="open_file"/>
    <menu title="Recent Files">
      <menuitem title="placeholder_1" action="recent_1"/>
      <menuitem title="placeholder_2" action="recent_2"/>
      <menuitem title="placeholder_3" action="recent_3"/>
    </menu>
    <menuitem title="Exit My Program" action="quit"/>
  </menu>
  <menu title="Edit">
    <menuitem title="Copy" action="copy_clipboard"/>
    <menuitem title="Paste" action="paste_clipboard"/>
  </menu>
</menubar>
"""
# root = Et.parse("menu.xml")
root = Et.fromstring(menuxml)

def parse(menutk, element):
    for menu in mbar:
        if menu.tag == 'menu':
            # have submenus, recurse
            submenutk = add_menu(menutk)
            parse(submenutk, menu)
        elif emnu.tag == 'menuitem':
            add_menuitem(menutk, menuitem)

or something like that.


From vincent at vincentdavis.net  Mon Apr  5 19:08:54 2010
From: vincent at vincentdavis.net (Vincent Davis)
Date: Mon, 5 Apr 2010 11:08:54 -0600
Subject: [Tutor] New class, how return value of x in interactive shell
Message-ID: <j2v77e831101004051008p85b48e59z585b8f0a81e1c73d@mail.gmail.com>

I am working an a open source project and would like to add feature to a
class.
Current action:
in:    >>>b = BString.new('I am a BString object')
out:  >>>b
in:    >>><BString - Python:0x1044846c8 / R:0x105c86f50>
in:    >>>print(b)
out:  >>> 21-letter "BString" instance
               seq: I am a BString object

What I would like is to be able to
in   >>>b
out >>>21-letter "BString" instance
               seq: I am a BString object

I have 2 questions
1, how do I do this?
2, how does print know what to do?

I have a lot to learn so pointing me in the right direction or to
documentation is as useful as the correct code.

Thanks

  *Vincent Davis
720-301-3003 *
vincent at vincentdavis.net
 my blog <http://vincentdavis.net> |
LinkedIn<http://www.linkedin.com/in/vincentdavis>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100405/746f4422/attachment.html>

From waynejwerner at gmail.com  Mon Apr  5 19:24:03 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Mon, 5 Apr 2010 12:24:03 -0500
Subject: [Tutor] New class, how return value of x in interactive shell
In-Reply-To: <j2v77e831101004051008p85b48e59z585b8f0a81e1c73d@mail.gmail.com>
References: <j2v77e831101004051008p85b48e59z585b8f0a81e1c73d@mail.gmail.com>
Message-ID: <q2l333efb451004051024xdfc0b33at785b5413ec0c01e7@mail.gmail.com>

On Mon, Apr 5, 2010 at 12:08 PM, Vincent Davis <vincent at vincentdavis.net>wrote:

> I am working an a open source project and would like to add feature to a
> class.
> Current action:
> in:    >>>b = BString.new('I am a BString object')
> out:  >>>b
> in:    >>><BString - Python:0x1044846c8 / R:0x105c86f50>
> in:    >>>print(b)
> out:  >>> 21-letter "BString" instance
>                seq: I am a BString object
>
> What I would like is to be able to
> in   >>>b
> out >>>21-letter "BString" instance
>                seq: I am a BString object
>
> I have 2 questions
> 1, how do I do this?
> 2, how does print know what to do?
>
> I have a lot to learn so pointing me in the right direction or to
> documentation is as useful as the correct code.
>

Take a look at the repr and str methods:
 http://docs.python.org/reference/datamodel.html#basic-customization

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100405/d2159e54/attachment.html>

From royhink at gmail.com  Mon Apr  5 20:31:39 2010
From: royhink at gmail.com (Roy Hinkelman)
Date: Mon, 5 Apr 2010 11:31:39 -0700
Subject: [Tutor] Scraping gov site: site looking for Flash player
Message-ID: <t2gb934fcb1004051131r354ef28h9606851b7af167dd@mail.gmail.com>

Interesting.

I am using urllib2 to open some government pages, and they have some js
checking for Flash on my computer.

Is there a way to show them that I have flash? Or possibly another solution?

My code:
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent' : user_agent}
req = urllib2.Request(_URL, None, headers)
data = mechanize.urlopen(req)
_soup = B_S(data)

And what I get back from 'print _soup':
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head><title>Welcome to OurDocuments.gov</title>
<!-- Prevent caching in netscape. Very important because netscape tends to
mangle cached code -->
<meta http-equiv="expires" content="0" />
<meta http-equiv="Pragma" content="no-cache" />
<script language="JavaScript" type="text/javascript">

<!--

// moock fpi [f.lash p.layer i.nspector]

// version: 1.3.5

// written by colin moock

// code maintained at:
http://www.moock.org/webdesign/flash/detection/moockfpi/

// terms of use posted at: http://www.moock.org/terms/



//
=============================================================================

// These are the user defined globals.

// Modify the following variables to customize the inspection behaviour.



var requiredVersion = 6;   // Version the user needs to view site (max 6,
min 2)



var useRedirect = true;    // Flag indicating whether or not to load a
separate

                           // page based on detection results. Set to true
to

                           // load a separate page.



// Only set next three vars if useRedirect is true...which it is...

var flashPage = "/doc.php?flash=true&doc=2";     // The location of the
flash movie page

var noFlashPage = "/doc.php?flash=false&doc=2";  // Page displayed if the
user doesn't have the

                                      // plugin or we can't detect it.



var upgradePage = "/doc.php?flash=old&doc=2";  // Page displayed if we
detect an old plugin

//
=============================================================================



// *************

// Everything below this point is internal until after the BODY tag.

// Do not modify! Proceed to the BODY tag for further instructions.

// *************



// System globals

var flash2Installed = false;    // boolean. true if flash 2 is installed

var flash3Installed = false;    // boolean. true if flash 3 is installed

var flash4Installed = false;    // boolean. true if flash 4 is installed

var flash5Installed = false;    // boolean. true if flash 5 is installed

var flash6Installed = false;    // boolean. true if flash 6 is installed

var maxVersion = 6;             // highest version we can actually detect

var actualVersion = 0;          // will become the version the user really
has

var hasRightVersion = false;    // boolean. will become true if it's safe to
embed the flash movie in the page

var jsVersion = 1.0;            // the version of javascript supported



// -->

</script>
<script language="JavaScript1.1" type="text/javascript">

<!--



// Check the browser...we're looking for ie/win

var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
// true if we're on ie

var isWin = (navigator.appVersion.indexOf("Windows") != -1) ? true : false;
// true if we're on windows



// This is a js1.1 code block, so make note that js1.1 is supported.

jsVersion = 1.1;



// Write vbscript detection on ie win. IE on Windows doesn't support regular

// JavaScript plugins array detection.

if(isIE && isWin) {

  document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n');

  document.write('on error resume next \n');

  document.write('flash2Installed =
(IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.2"))) \n');

  document.write('flash3Installed =
(IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.3"))) \n');

  document.write('flash4Installed =
(IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.4"))) \n');

  document.write('flash5Installed =
(IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.5"))) \n');

  document.write('flash6Installed =
(IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.6"))) \n');

  document.write('</scr' + 'ipt\> \n'); // break up end tag so it doesn't
end our script

}

// -->

</script>
<script language="JavaScript" type="text/javascript">

<!--

// Next comes the standard javascript detection that uses the

// navigator.plugins array. We pack the detector into a function so it loads

// before we call it.



function detectFlash() {

  // If navigator.plugins exists...

  if (navigator.plugins) {

    // ...then check for flash 2 or flash 3+.

    if (navigator.plugins["Shockwave Flash 2.0"] ||
navigator.plugins["Shockwave Flash"]) {



      // Some version of Flash was found. Time to figure out which.



      // Set convenient references to flash 2 and the plugin description.

      var isVersion2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" :
"";

      var flashDescription = navigator.plugins["Shockwave Flash" +
isVersion2].description;



      // DEBUGGING: uncomment next line to see the actual description.

      // alert("Flash plugin description: " + flashDescription);



      // A flash plugin-description looks like this: Shockwave Flash 4.0 r5

      // We can get the major version by grabbing the character before the
period

      // note that we don't bother with minor version detection here (since
we don't need to, and it is best accomplished from within an actual Flash
movie anyway).

      var flashVersion =
parseInt(flashDescription.charAt(flashDescription.indexOf(".") - 1));



// wow this is old now.  to accomodate flash players 10 (!!) and higher,
following code was added.  d.cole. 3/2010

      var flashVersion2 =
parseInt(flashDescription.charAt(flashDescription.indexOf(".") - 2));



    // We found the version, now set appropriate version flags. Make sure

      // to use >= on the highest version so we don't prevent future version

      // users from entering the site.

      flash2Installed = flashVersion == 2;

      flash3Installed = flashVersion == 3;

      flash4Installed = flashVersion == 4;

      flash5Installed = flashVersion == 5;

      flash6Installed = flashVersion >= 6;

// wow this is old now.  to accomodate flash players 10 (!!) and higher,
following code was added.  d.cole. 3/2010

      flash6Installed = flashVersion2 >= 1;

}

  }



  // Loop through all versions we're checking, and

  // set actualVersion to highest detected version.

  for (var i = 2; i <= maxVersion; i++) {

    if (eval("flash" + i + "Installed") == true) {

        actualVersion = i;

    }

  }



  if (!actualVersion) {

      actualVersion = 0;

  }



  // If we're on webtv, the version supported is 2 (pre-summer2000,

  // or 3, post-summer2000). Note that we don't bother sniffing varieties

  // of webtv. You could if you were sadistic...

  if(navigator.userAgent.indexOf("WebTV") != -1) actualVersion = 3;



  // DEBUGGING: uncomment next line to display flash version

  //alert("version detected: " + actualVersion);



  // We're finished getting the version on all browsers that support
detection.

  // Time to take the appropriate action.



  // If the user has a new enough version...

  if (actualVersion >= requiredVersion) {

    // ...then we'll redirect them to the flash page, unless we've

    // been told not to redirect.

    if (useRedirect) {

      // Need javascript1.1 to do location.replace

      if(jsVersion > 1.0) {

        // It's safe to use replace(). Good...we won't break the back
button.

        window.location.replace(flashPage);

      } else {

        // JavaScript version is too old, so use .location to load the flash
page.

        window.location = flashPage;

      }

    }



    // If we got here, we didn't redirect. So we make a note that we should

    // write out the object/embed tags later.

    hasRightVersion = true;

  } else {

    // The user doesn't have a new enough version.

    // If the redirection option is on, load the appropriate alternate page.

    if (useRedirect) {

      // Do the same .replace() call only if js1.1+ is available.

      if(jsVersion > 1.0) {

        window.location.replace((actualVersion >= 2) ? upgradePage :
noFlashPage);

      } else {

        window.location = (actualVersion >= 2) ? upgradePage : noFlashPage;

      }

    }

  }

}



detectFlash();  // call our detector function now that it's safely loaded.



// -->

</script>
</head>
<body bgcolor="#FFFFFF" onload="detectFlash();">
<p>One moment please...</p>
<noscript>
<meta http-equiv="Refresh" content="4;URL=/doc.php?flash=false&amp;doc=2" />
</noscript>
</body>
</html>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100405/f9e42403/attachment-0001.html>

From vincent at vincentdavis.net  Mon Apr  5 21:03:27 2010
From: vincent at vincentdavis.net (Vincent Davis)
Date: Mon, 5 Apr 2010 13:03:27 -0600
Subject: [Tutor] New class, how return value of x in interactive shell
In-Reply-To: <q2l333efb451004051024xdfc0b33at785b5413ec0c01e7@mail.gmail.com>
References: <j2v77e831101004051008p85b48e59z585b8f0a81e1c73d@mail.gmail.com>
	<q2l333efb451004051024xdfc0b33at785b5413ec0c01e7@mail.gmail.com>
Message-ID: <r2j77e831101004051203v551d87e0xa9fba5792903932d@mail.gmail.com>

Take a look at the repr and str methods:
 http://docs.python.org/reference/datamodel.html#basic-customization

Ok so I am still a little confused, It seems that __str__ is used for print
and str()
byt what allows whats below. That is why does just entering the name of the
instance return print(b). I have tried a few combinations but not the right
one.
in   >>>b
out >>>21-letter "BString" instance
               seq: I am a BString object

*Vincent Davis
720-301-3003 *
vincent at vincentdavis.net
 my blog <http://vincentdavis.net> |
LinkedIn<http://www.linkedin.com/in/vincentdavis>


On Mon, Apr 5, 2010 at 11:24 AM, Wayne Werner <waynejwerner at gmail.com>wrote:

>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100405/366f64ab/attachment.html>

From alan.gauld at btinternet.com  Mon Apr  5 21:08:24 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Apr 2010 20:08:24 +0100
Subject: [Tutor] New class, how return value of x in interactive shell
References: <j2v77e831101004051008p85b48e59z585b8f0a81e1c73d@mail.gmail.com>
Message-ID: <hpdcfq$tib$1@dough.gmane.org>

"Vincent Davis" <vincent at vincentdavis.net> wrote 

>I am working an a open source project and would like to add feature to a
> class.
> Current action:
> in:    >>>b = BString.new('I am a BString object')

That' a very strange idiom in Python.
Can you show us the class definition?

> out:  >>>b
> in:    >>><BString - Python:0x1044846c8 / R:0x105c86f50>
> in:    >>>print(b)
> out:  >>> 21-letter "BString" instance
>               seq: I am a BString object
> 
> What I would like is to be able to
> in   >>>b
> out >>>21-letter "BString" instance
>               seq: I am a BString object
> 
> I have 2 questions
> 1, how do I do this?
> 2, how does print know what to do?

If you look at your class definition that should become obvious.
Are you sure this isn't a homework?


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From vincent at vincentdavis.net  Mon Apr  5 21:17:44 2010
From: vincent at vincentdavis.net (Vincent Davis)
Date: Mon, 5 Apr 2010 13:17:44 -0600
Subject: [Tutor] New class, how return value of x in interactive shell
In-Reply-To: <hpdcfq$tib$1@dough.gmane.org>
References: <j2v77e831101004051008p85b48e59z585b8f0a81e1c73d@mail.gmail.com>
	<hpdcfq$tib$1@dough.gmane.org>
Message-ID: <n2t77e831101004051217z58f904c6h235a4d2e6fdefa2e@mail.gmail.com>

>
> That' a very strange idiom in Python.
> Can you show us the class definition?


It's a bioconductor extension to rpy2
http://www.bitbucket.org/lgautier/rpy2-bioc-extensions/overview/
I am trying to learn R and at they same time more about python and R
bioconductor packages. So no it is not homework but I am trying to learn
something. I am sure the answer is obvious when you know it :)
Here is the class, although it is obviously part of something bigger, you
can checkout the full code at bitbuckit.org

class BString(XString):
    """ Biological string """

    _bstring_constructor = biostrings.BString

    @classmethod
    def new(cls, x):
        """ :param x: a (biological) string """
        res = cls(cls._bstring_constructor(conversion.py2ri(x)))
        _setExtractDelegators(res)
        return res

*Vincent Davis
720-301-3003 *
vincent at vincentdavis.net
 my blog <http://vincentdavis.net> |
LinkedIn<http://www.linkedin.com/in/vincentdavis>


On Mon, Apr 5, 2010 at 1:08 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> "Vincent Davis" <vincent at vincentdavis.net> wrote
>
>> I am working an a open source project and would like to add feature to a
>>
>> class.
>> Current action:
>> in:    >>>b = BString.new('I am a BString object')
>>
>
> That' a very strange idiom in Python.
> Can you show us the class definition?
>
>
>  out:  >>>b
>> in:    >>><BString - Python:0x1044846c8 / R:0x105c86f50>
>> in:    >>>print(b)
>> out:  >>> 21-letter "BString" instance
>>              seq: I am a BString object
>>
>> What I would like is to be able to
>> in   >>>b
>> out >>>21-letter "BString" instance
>>              seq: I am a BString object
>>
>> I have 2 questions
>> 1, how do I do this?
>> 2, how does print know what to do?
>>
>
> If you look at your class definition that should become obvious.
> Are you sure this isn't a homework?
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100405/381f2cd8/attachment.html>

From alan.gauld at btinternet.com  Mon Apr  5 22:00:40 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Apr 2010 21:00:40 +0100
Subject: [Tutor] New class, how return value of x in interactive shell
References: <j2v77e831101004051008p85b48e59z585b8f0a81e1c73d@mail.gmail.com><q2l333efb451004051024xdfc0b33at785b5413ec0c01e7@mail.gmail.com>
	<r2j77e831101004051203v551d87e0xa9fba5792903932d@mail.gmail.com>
Message-ID: <hpdfhp$992$1@dough.gmane.org>


"Vincent Davis" <vincent at vincentdavis.net> wrote

> Take a look at the repr and str methods:
> http://docs.python.org/reference/datamodel.html#basic-customization
>
> Ok so I am still a little confused, It seems that __str__ is used for 
> print
> and str()

That's right and repr() is used when evaluating the object, as at the >>> 
prompt.

So

>>> print b # calls b.__str__()

whereas

>>> b # calls b.__repr__()

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From alan.gauld at btinternet.com  Mon Apr  5 22:03:24 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Apr 2010 21:03:24 +0100
Subject: [Tutor] New class, how return value of x in interactive shell
References: <j2v77e831101004051008p85b48e59z585b8f0a81e1c73d@mail.gmail.com><hpdcfq$tib$1@dough.gmane.org>
	<n2t77e831101004051217z58f904c6h235a4d2e6fdefa2e@mail.gmail.com>
Message-ID: <hpdfmu$9s1$1@dough.gmane.org>

"Vincent Davis" <vincent at vincentdavis.net> wrote

> class BString(XString):
>    """ Biological string """
> 
>    _bstring_constructor = biostrings.BString
> 
>    @classmethod
>    def new(cls, x):
>        """ :param x: a (biological) string """
>        res = cls(cls._bstring_constructor(conversion.py2ri(x)))
>        _setExtractDelegators(res)
>        return res

OK, I see what they are doing but as far as I can tell this could be 
put in a __new__ method just as easily which would retain the 
usual instantiation style.

Any gurus out there able to explain why they have used an 
explicit new() class method rather than __new__()?

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From marcodrompre at gmail.com  Mon Apr  5 22:31:30 2010
From: marcodrompre at gmail.com (=?ISO-8859-1?Q?Marco_Rompr=E9?=)
Date: Mon, 5 Apr 2010 16:31:30 -0400
Subject: [Tutor] Simple bank account oriented object
In-Reply-To: <4BB3B2ED.2030305@gmail.com>
References: <l2j4bdcec5e1003301926nd20a7db1ge77485d72bcb88ef@mail.gmail.com>
	<houe7a$lf$1@dough.gmane.org>
	<k2l4bdcec5e1003310635w7f0c584fzea67cb11b9483e06@mail.gmail.com>
	<4BB3B2ED.2030305@gmail.com>
Message-ID: <s2o4bdcec5e1004051331q5fc37facq225bfc0fc6e49d04@mail.gmail.com>

Hi im doin a programmin course at university and in one on my exercise i
have to do that

I had to define a class CompteBancaire(CompteBancaire is bankaccount in
french), that would allow me to create objects Compte1, Compte2,etc.

     The following methods need to be defined
      - depot(somme)         would allow me to add cash to my account
balance
      - retrait(somme)        would allow me to withdraw some cash from my
account
      - ajouterInterest()      would allow me to add interest
      - affiche()                 would allow me to display the account
owner and his account balance

the retrait(somme) method is not supposed to let the account balance being
negative.



3.2

Create a sub-class to CompteBancaire and name it  CompteEtudiant. Each
CompteEtudiant (student account) should have a $1000CAD credit line. Write a
builder or constructor for this new class. Surcharge the retrait(somme)
method to make sure that the student can withdraw to their limit.
Test the class

Here's my code for now this is 3.1and 3.2 in the same code

Please help me i think im on the right track but i need some guidance in the
dark. lol

Thank you tutors


#Exercice 3,2 - Gestion d'un compte bancaire pour ?tudiant avec marge de
cr?dit disponible de 1000$CDN

class CompteBancaire:
    "d?finition d'un compte bancaire"

    def __init__(self,nom,solde,interet):       #Nous allons instancier et
initialiser les objets ? la classe
        self.nom, self.solde, self.interet = nom,solde,interet

    def depot(self,somme=0):                    #M?thode pour additionner
les d?p?ts au compte
        self.solde=self.solde+somme

    def retrait(self,somme=0):                  #M?thode pour soustraire les
retraits au compte
        if self.nom == 'Sandon':
            if self.solde-somme<0:
                print "Les fonds sont insuffisants. Essayez un autre montant
pour votre retrait!"
            else:
                self.solde=self.solde-somme

        elif self.nom =='?tudiant':             #V?rifie s'il s'agit d'un
compte ?tudiant
            if self.solde - somme < -self.margeCre:      # V?rifie si le
retrait d?passe la marge de cr?dit maximum
                print "D?sol?, votre retrait d?passe la marge de cr?dit
autoris?"
            else:                               # sinon d?uit le montant
retirer de la marge de cr?dit
                self.margeCre = self.solde - somme
                self.solde = 0

    def calculInteret(self,calculInteret=0):     #M?thode qui calcule les
int?r?ts et le solde r?siduel
        self.interet=self.solde*calculInteret/100
        self.solde=(self.solde*calculInteret/100)+self.solde

    def affiche_solde(self):                    #M?thode qui affiche le
solde et le montant d'int?r?t accumul?
        print "Le solde du compte bancaire de %s est de %d $CAD"
%(self.nom,self.solde)
        print "Vous avez r?colt? %d $CDN en int?r?t"%(self.interet)
#
######################
# cr?ation de la gestion d'un compte ?tudiant autorisant une marge de cr?dit
de (1 000$)

class CompteEtudiant(CompteBancaire):
    "d?finition du compte bancaire pour ?tudiant d?riv? du compte bancaire
standard"
    def __init__(self, nom='', solde=0, margeCre=0):
        CompteBancaire.__init__(self, nom='Nom', solde=0, interet=0)
        self.nom, self.solde, self.margeCre = nom, solde, margeCre

    def affiche_solde(self, somme=0):           #M?thode constructeur qui
red?fini la fonction affiche_solde pour le compte ?tudiant
        print "%s--Votre solde bancaire est de %d $CAD"
%(self.nom,self.solde)
        print "Le solde de votre marge de cr?dit est de %d $CAD"
%(self.margeCre)

##############################################################
#jeux d'essai avec des valeurs fictives
if __name__=='__main__':        #R?f?rence au corps principal du programme.
    compte1 = CompteBancaire('Sandon',800,0)    #Essai avec un solde de
800$, un retrait de 1200$ et des int?r?ts de 10%
    compte1.depot(0)
    compte1.retrait(1200)
    compte1.calculInteret(10)
    compte1.affiche_solde()
    compte2 = CompteEtudiant('?tudiant',800,1000)
    compte2.retrait(1100)
    compte2.affiche_solde()
############################################################


On Wed, Mar 31, 2010 at 4:39 PM, Lie Ryan <lie.1296 at gmail.com> wrote:

On 04/01/2010 12:35 AM, Marco Rompr? wrote:
> > what's wrong in this code??? if I want it to do what i describe in my
> > message.
>
> What happens when you run it? You did not even write that in your
> message. And please reply-all to the list.
>

When I run it,  it gives me this:

>>>
Les fonds sont insuffisants. Essayez un autre montant pour votre retrait!
(Try to witthdraw 1200 with a balance of 880$) This is good!
Le solde du compte bancaire de Sandon est de 880 $CAD (This is fine too)
Vous avez r?colt? 80 $CDN en int?r?t (This too)
?tudiant--Votre solde bancaire est de 0 $CAD (Trying to withdraw 1100$ with
a cash balance of 800 plus a credit line of 1000$)
Le solde de votre marge de cr?dit est de -300 $CAD (It would be supposed to
say that my credit line balance is 700= 1000-300 knowing that this 300 was
the amount missing from mu cash balance)

Would you please help me???

Ocram the newbie
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100405/051cc093/attachment-0001.html>

From grewal06 at gmail.com  Mon Apr  5 22:55:18 2010
From: grewal06 at gmail.com (Ravinder Singh)
Date: Mon, 5 Apr 2010 16:55:18 -0400
Subject: [Tutor] Need Maze traverse to move through start and find exit.
	replacing x on the path.
Message-ID: <r2z8cf54c3f1004051355hb87618cbk6fc36dd8930473a2@mail.gmail.com>

I do not know the code to move the traversal.
Maze = [ [ '#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#'
],\
         [ '#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#'
],\
         [ '#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#'
],\
         [ '.','.','.','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#'
],\
         [ '#','#','.','#','#','.','.','#','#','#','#','#','#','#','#','#','#','#','#','#'
],\
         [ '#','#','.','#','#','.','.','#','#','#','#','#','#','#','#','#','#','.','.','.'
],\
         [ '#','#','.','#','#','.','.','#','#','#','#','#','#','#','#','#','#','.','#','#'
],\
         [ '#','#','.','.','.','.','#','#','#','#','#','#','#','#','#','#','#','.','#','#'
],\
         [ '#','#','.','#','#','.','#','#','#','#','#','#','.','.','.','.','.','.','#','#'
],\
         [ '#','#','.','#','#','.','#','#','#','#','#','#','.','#','#','#','#','.','#','#'
],\
         [ '#','#','.','#','#','.','#','#','#','#','#','#','.','#','#','#','#','.','#','#'
],\
         [ '#','#','#','#','#','.','.','.','.','.','.','.','.','#','#','#','#','#','#','#'
],\
         [ '#','#','#','#','#','#','#','#','#','#','#','#','.','#','#','#','#','#','#','#'
],\
         [ '#','#','#','#','#','#','#','#','#','#','#','#','.','#','#','#','#','#','#','#'
],\
         [ '#','#','#','#','#','#','#','#','#','#','#','#','.','#','#','#','#','#','#','#'
],\
         [ '#','#','#','#','#','#','#','#'
,'#','#','#','#','.','#','#','#','#','#','#','#' ],\
         [ '#','#','#','#','#','#','#','#','#','#','#','#','.','#','#','#','#','#','#','#'
],\
         [ '#','#','#','#','#','#','#','#','#','#','#','#','.','#','#','#','#','#','#','#'
],\
         [ '#','#','#','#','#','#','#','#','#','#','#','#','.','#','#','#','#','#','#','#'
],\
         [ '#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#'
],\
]
x= "x"
Squares= 399
def PrintMaze():
    global Maze
    return "\n".join(' '.join(row) for row in Maze)

print(PrintMaze())

def MazeTraverse(Srow, col):
    Maze = []
    for i in range(Squares):
        Maze[4]= "x"
        return "\n".join(' '.join(row) for row in Maze)

print(MazeTraverse(60,61))

thanks

From neven.gorsic at gmail.com  Tue Apr  6 00:05:47 2010
From: neven.gorsic at gmail.com (=?UTF-8?B?TmV2ZW4gR29yxaFpxIc=?=)
Date: Tue, 6 Apr 2010 00:05:47 +0200
Subject: [Tutor] Menu data from file
In-Reply-To: <hpcqlg$ptv$1@dough.gmane.org>
References: <q2w8acd28da1004040354jb0284bdal9c61af6abff3154e@mail.gmail.com>
	<hpagtu$v8h$1@dough.gmane.org>
	<562203.58595.qm@web86703.mail.ird.yahoo.com>
	<hpb5c1$nm2$1@dough.gmane.org> <hpbabb$3ab$1@dough.gmane.org>
	<t2h8acd28da1004050039q9f3d49diac6aefe1d467b0b6@mail.gmail.com>
	<hpcqlg$ptv$1@dough.gmane.org>
Message-ID: <i2k8acd28da1004051505h5d55594at135d37c77489b7a4@mail.gmail.com>

OK, I will describe my "case".

I use menu date stored in list "shape" in file CMFlowData.py in the same
directory as my main program x.py. In the beginning of the program I have
command:

import CMFlowData

and everything works fine till I make executable with py2exe. There are no
error during "compilation" and exe are created in ...\dist directory. I copy
all my external files to that directory, together with CMFlowData.py file,
but when I run x.exe I get x.exe.log file with message:

Traceback (most recent call last):
  File "x.py", line 8, in <module>
ImportError: No module named CMFlowData
Traceback (most recent call last):
  File "x.py", line 8, in <module>
ImportError: No module named CMFlowData

All other files that I read from disk are created with relative paths and
work fine, except when I import
my own module.

Is there some procedure to "announce" my module to the Python or System?

That is all.

Neven

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

On Mon, Apr 5, 2010 at 4:03 PM, Lie Ryan <lie.1296 at gmail.com> wrote:

> On 04/05/10 17:39, Neven Gor?i? wrote:
> > Thank you for mentioning the possible options.
> > I already use option where I import .py module,
> > but I run into troubles when making executable with py2exe.
>
> Maybe you should elaborate what problems you're experiencing with
> py2exe? Probably we can solve that instead of developing workarounds.
>
> Many popular UI toolkit provides an XML-based menu file.
> Here is one for PyGTK:
> http://www.pygtk.org/pygtk2tutorial/sec-UIManager.html
>
> You should better use your GUI toolkit's version instead of writing your
> own.
>
> > I suppose that XML approach is the most general method.
> > Can you recommend a good introduction text (not for experts :-))
> > and give more details about the tool ElementCTree.
> >
> > Maybe it will be educational and interesting for other beginners too.
>
> ElementTree is quite simple, though I don't think there are many good
> tutorials about it (at least I can't find one). In the simplest use
> case, you just use xml.etree.ElementTree.parse("menu.xml") and you can
> iterate the tree like so:
>
> import xml.etree.cElementTree as Et
> menuxml = """
> <menubar>
>  <menu title="File">
>    <menuitem title="Open File..." action="open_file"/>
>    <menu title="Recent Files">
>      <menuitem title="placeholder_1" action="recent_1"/>
>      <menuitem title="placeholder_2" action="recent_2"/>
>      <menuitem title="placeholder_3" action="recent_3"/>
>    </menu>
>    <menuitem title="Exit My Program" action="quit"/>
>  </menu>
>  <menu title="Edit">
>    <menuitem title="Copy" action="copy_clipboard"/>
>    <menuitem title="Paste" action="paste_clipboard"/>
>  </menu>
> </menubar>
> """
> # root = Et.parse("menu.xml")
> root = Et.fromstring(menuxml)
>
> def parse(menutk, element):
>    for menu in mbar:
>        if menu.tag == 'menu':
>            # have submenus, recurse
>            submenutk = add_menu(menutk)
>            parse(submenutk, menu)
>        elif emnu.tag == 'menuitem':
>            add_menuitem(menutk, menuitem)
>
> or something like that.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100406/252aff82/attachment.html>

From alan.gauld at btinternet.com  Tue Apr  6 00:20:09 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Apr 2010 23:20:09 +0100
Subject: [Tutor] Simple bank account oriented object
References: <l2j4bdcec5e1003301926nd20a7db1ge77485d72bcb88ef@mail.gmail.com><houe7a$lf$1@dough.gmane.org><k2l4bdcec5e1003310635w7f0c584fzea67cb11b9483e06@mail.gmail.com><4BB3B2ED.2030305@gmail.com>
	<s2o4bdcec5e1004051331q5fc37facq225bfc0fc6e49d04@mail.gmail.com>
Message-ID: <hpdnnb$5j2$1@dough.gmane.org>

I don't speak French so I'm struggling a bit with the variable
names, however...

"Marco Rompr?" <marcodrompre at gmail.com> wrote in message

class CompteBancaire:
    def __init__(self,nom,solde,interet):       #Nous allons instancier et
        self.nom, self.solde, self.interet = nom,solde,interet

    def depot(self,somme=0):                    #M?thode pour additionner
        self.solde=self.solde+somme

    def retrait(self,somme=0):                  #M?thode pour soustraire 
les
        if self.nom == 'Sandon':
            if self.solde-somme<0:
                print "Les fonds sont insuffisants. Essayez un autre 
montant
            else:
                self.solde=self.solde-somme
        elif self.nom =='?tudiant':             #V?rifie s'il s'agit d'un
            if self.solde - somme < -self.margeCre:      # V?rifie si le
                print "D?sol?, votre retrait d?passe la marge de cr?dit
            else:                               # sinon d?uit le montant
                self.margeCre = self.solde - somme
                self.solde = 0

    def calculInteret(self,calculInteret=0):     #M?thode qui calcule les
        self.interet=self.solde*calculInteret/100
        self.solde=(self.solde*calculInteret/100)+self.solde

    def affiche_solde(self):                    #M?thode qui affiche le
        print "Le solde du compte bancaire de %s est de %d $CAD"
%(self.nom,self.solde)
        print "Vous avez r?colt? %d $CDN en int?r?t"%(self.interet)

class CompteEtudiant(CompteBancaire):
    "d?finition du compte bancaire pour ?tudiant d?riv? du compte bancaire
    def __init__(self, nom='', solde=0, margeCre=0):
        CompteBancaire.__init__(self, nom='Nom', solde=0, interet=0)
        self.nom, self.solde, self.margeCre = nom, solde, margeCre

    def affiche_solde(self, somme=0):           #M?thode constructeur qui
        print "%s--Votre solde bancaire est de %d $CAD"
%(self.nom,self.solde)
        print "Le solde de votre marge de cr?dit est de %d $CAD"
%(self.margeCre)

This second class does not seem to override any of the original
methods so does not modify the balance based on the "overdraft2 value.
This the status method prints out the balance based on a simple
calculation without taking the overdraft into account.

If you want to change that I think you will need to add override versions
of the withdrawal method to your subclass.

But I admit my understanding of the code is not deep, I didn't spend
enough time deciphering it for that...

Alan G.






When I run it,  it gives me this:

>>>
Les fonds sont insuffisants. Essayez un autre montant pour votre retrait!
(Try to witthdraw 1200 with a balance of 880$) This is good!
Le solde du compte bancaire de Sandon est de 880 $CAD (This is fine too)
Vous avez r?colt? 80 $CDN en int?r?t (This too)
?tudiant--Votre solde bancaire est de 0 $CAD (Trying to withdraw 1100$ with
a cash balance of 800 plus a credit line of 1000$)
Le solde de votre marge de cr?dit est de -300 $CAD (It would be supposed to
say that my credit line balance is 700= 1000-300 knowing that this 300 was
the amount missing from mu cash balance)



From shuying at gmail.com  Tue Apr  6 01:06:27 2010
From: shuying at gmail.com (Shu)
Date: Tue, 6 Apr 2010 09:06:27 +1000
Subject: [Tutor] Getting traceback info from C-API
Message-ID: <g2g75fa0c3a1004051606t9ebb1967id332e1d174ec716@mail.gmail.com>

Hi,

I have a CAPI extension module that is giving me MemoryError
exceptions from once in a while with no other information, so clearly
none of my exception handlers are catching it. Is there any way I can
traceback information for the extension module?

Thanks in advance,
.S

From steve at pearwood.info  Tue Apr  6 01:15:29 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 6 Apr 2010 10:15:29 +1100
Subject: [Tutor] Simple bank account oriented object
In-Reply-To: <s2o4bdcec5e1004051331q5fc37facq225bfc0fc6e49d04@mail.gmail.com>
References: <l2j4bdcec5e1003301926nd20a7db1ge77485d72bcb88ef@mail.gmail.com>
	<4BB3B2ED.2030305@gmail.com>
	<s2o4bdcec5e1004051331q5fc37facq225bfc0fc6e49d04@mail.gmail.com>
Message-ID: <201004060915.30697.steve@pearwood.info>

On Tue, 6 Apr 2010 06:31:30 am Marco Rompr? wrote:
> Hi im doin a programmin course at university and in one on my
> exercise i have to do that
>
> I had to define a class CompteBancaire(CompteBancaire is bankaccount
> in french), that would allow me to create objects Compte1,
> Compte2,etc.
[...]

I do not understand French, so if I have misunderstood something, please 
excuse me. My comments are added in between yours.


> #Exercice 3,2 - Gestion d'un compte bancaire pour ?tudiant avec marge
> de cr?dit disponible de 1000$CDN
>
> class CompteBancaire:
>     "d?finition d'un compte bancaire"

This docstring is not very useful. The reader already knows that you are 
defining a CompteBancaire. What else can you tell them? How about basic 
usage?

class CompteBancaire:
    """d?finition d'un compte bancaire

    Example: create a cheque account with $1000 balance.

    >>> compte = CompteBancaire('cheque', 1000)

    Deposit $100, then withdraw $80:

    >>> compte.depot(100)
    >>> compte.retrait(80)

    """


>     def __init__(self,nom,solde,interet):       #Nous allons
> instancier et initialiser les objets ? la classe
>         self.nom, self.solde, self.interet = nom,solde,interet

It is not clear to me whether interet (French for interest?) is meant to 
be a percentage rate, or an amount. I will assume it is an amount (how 
much interest the bank has paid you). Every new account will always 
start with interet = 0, so we should write this:

def __init__(self, nom, solde):
    self.nom, self.solde = nom, solde
    self.interet = 0

It is not clear to me what nom (name?) is for, but I have left it in.



>     def depot(self,somme=0):                    #M?thode pour
> additionner les d?p?ts au compte
>         self.solde=self.solde+somme

Do you need the default value for deposits? Will it ever be useful for 
the user to call compte.depot() without an amount?

I would think it would be more useful to add the default values to the 
initialiser __init__:

def __init__(self, nom='', solde=0):
    ...

and take it away from the depot and retrait methods:

def depot(self, somme):
    ...
def retrait(self,somme):
    ...


But this is just my opinion.


>     def retrait(self,somme=0):                  #M?thode pour
> soustraire les retraits au compte
>         if self.nom == 'Sandon':
>             if self.solde-somme<0:
>                 print "Les fonds sont insuffisants. Essayez un autre
> montant pour votre retrait!"
>             else:
>                 self.solde=self.solde-somme

This comment might be more advanced than you have learned. If so, you 
can safely ignore this part. If you have not learned about exceptions 
yet, you can safely ignore this.

When programming, you should separate the "back-end" from 
the "front-end". The back-end should report errors using exceptions, in 
a form which is useful to the programmer, and the front-end should 
catch those exceptions and print an error message in a form which is 
useful to the user.

So we should write:

def retrait(self, somme):
    if somme > self.solde:
        raise ValueError('fonds sont insuffisants')
    else:
        self.solde = self.solde - somme


>         elif self.nom =='?tudiant':             #V?rifie s'il s'agit
> d'un compte ?tudiant

This part is not good. The CompteBancaire class MUST NOT know anything 
about the CompteEtudiant subclass. Each class should only know about 
itself, and superclasses (parent classes).

So all the code dealing with the ?tudiant account must go inside the 
CompteEtudiant class, not the CompteBancaire.


>             if self.solde - somme < -self.margeCre:      # V?rifie si
> le retrait d?passe la marge de cr?dit maximum
>                 print "D?sol?, votre retrait d?passe la marge de
> cr?dit autoris?"
>             else:                               # sinon d?uit le
> montant retirer de la marge de cr?dit
>                 self.margeCre = self.solde - somme
>                 self.solde = 0


>     def calculInteret(self,calculInteret=0):     #M?thode qui calcule
> les int?r?ts et le solde r?siduel
>         self.interet=self.solde*calculInteret/100
>         self.solde=(self.solde*calculInteret/100)+self.solde

There is a small problem with Python here, depending on what version you 
are using. In older versions of Python, division is "integer division", 
so that:

1/2 -> 0
9/4 -> 2

and so forth. This will give you the wrong result for calculating 
interest. In newer versions of Python (version 3.0 and better) division 
is "true division":

1/2 -> 0.5
9/4 -> 2.5

The easiest way to make your code work correctly is to change 100 to 
100.0 (a float instead of an int) and then it will calculate as you 
expect in all versions.


>     def affiche_solde(self):                    #M?thode qui affiche
> le solde et le montant d'int?r?t accumul?
>         print "Le solde du compte bancaire de %s est de %d $CAD"
> %(self.nom,self.solde)
>         print "Vous avez r?colt? %d $CDN en int?r?t"%(self.interet)


Now we look at the ?tudiant account, and add the extra functionality.


> class CompteEtudiant(CompteBancaire):
>     "d?finition du compte bancaire pour ?tudiant d?riv? du compte
> bancaire standard"
>     def __init__(self, nom='', solde=0, margeCre=0):
>         CompteBancaire.__init__(self, nom='Nom', solde=0, interet=0)
>         self.nom, self.solde, self.margeCre = nom, solde, margeCre

The CompteEtudiant class can let the CompteBancaire do some of the work. 
This is called "inheritance" -- the subclass inherits code from the 
parent class.


def __init__(self, nom='', solde=0, margeCre=0):
    # Call the parent class method.
    CompteBancaire.__init__(self, nom, solde)
    # Do the extra work this class needs.
    self.margeCre = margeCre

Calling CompteBancaire.__init__ does everything the CompteBancaire 
understands. It sets nom, solde and interet, but not margeCre because 
CompteBancaire does not know anything about margeCre. Then the subclass 
sets margeCre itself.


>     def affiche_solde(self, somme=0):           #M?thode constructeur
> qui red?fini la fonction affiche_solde pour le compte ?tudiant
>         print "%s--Votre solde bancaire est de %d $CAD"
> %(self.nom,self.solde)
>         print "Le solde de votre marge de cr?dit est de %d $CAD"
> %(self.margeCre)


The CompteEtudiant should print the same information as the 
CompteBancaire class, plus extra. Again, inheritance makes it easy:

def affiche_solde(self):
    # Display everything the super class understands.
    CompteBancaire.affiche_soldeafficheself)
    # Display the parts that only the subclass understands.
    print "Le solde de votre marge de cr?dit est de %d $CAD" % 
(self.margeCre)


And one more method needs to be defined: we have to change the retrait 
method to allow negative balance, but only up to a maximum of margeCre.

def retrait(self, somme):
    if somme > self.solde + self.margeCre:
        raise ValueError('fonds sont insuffisants')
    else:
        self.solde = self.solde - somme



-- 
Steven D'Aprano

From transmogribenno at gmail.com  Tue Apr  6 01:38:55 2010
From: transmogribenno at gmail.com (Benno Lang)
Date: Tue, 6 Apr 2010 08:38:55 +0900
Subject: [Tutor] Scraping gov site: site looking for Flash player
In-Reply-To: <t2gb934fcb1004051131r354ef28h9606851b7af167dd@mail.gmail.com>
References: <t2gb934fcb1004051131r354ef28h9606851b7af167dd@mail.gmail.com>
Message-ID: <h2y9b00d1a91004051638v545f6795u8d2d0160d1e5a080@mail.gmail.com>

On 6 April 2010 03:31, Roy Hinkelman <royhink at gmail.com> wrote:
> I am using urllib2 to open some government pages, and they have some js
> checking for Flash on my computer.
> Is there a way to show them that I have flash? Or possibly another solution?

>From reading the JavaScript, you should fetch the URL
domain.tld/doc.php?flash=true&doc=2 instead of domain.tld/ as the
first URL.

> var flashPage = "/doc.php?flash=true&doc=2";     // The location of the
> flash movie page

This is the JS that specifies the desired redirect location. You could
open the original URL in a flash-capable browser to work out where to
go as well.

However, if the site is flash-based, you probably won't be able to get
any useful info from it.

HTH,
benno

From lie.1296 at gmail.com  Tue Apr  6 02:49:47 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Tue, 06 Apr 2010 10:49:47 +1000
Subject: [Tutor] Menu data from file
In-Reply-To: <i2k8acd28da1004051505h5d55594at135d37c77489b7a4@mail.gmail.com>
References: <q2w8acd28da1004040354jb0284bdal9c61af6abff3154e@mail.gmail.com>	<hpagtu$v8h$1@dough.gmane.org>	<562203.58595.qm@web86703.mail.ird.yahoo.com>	<hpb5c1$nm2$1@dough.gmane.org>
	<hpbabb$3ab$1@dough.gmane.org>	<t2h8acd28da1004050039q9f3d49diac6aefe1d467b0b6@mail.gmail.com>	<hpcqlg$ptv$1@dough.gmane.org>
	<i2k8acd28da1004051505h5d55594at135d37c77489b7a4@mail.gmail.com>
Message-ID: <hpe0h1$s48$1@dough.gmane.org>

On 04/06/10 08:05, Neven Gor?i? wrote:
> OK, I will describe my "case".
> 
> I use menu date stored in list "shape" in file CMFlowData.py in the same
> directory as my main program x.py. In the beginning of the program I
> have command:
> 
> import CMFlowData
> 
> and everything works fine till I make executable with py2exe. There are
> no error during "compilation" and exe are created in ...\dist directory.
> I copy all my external files to that directory, together with
> CMFlowData.py file, but when I run x.exe I get x.exe.log file with message:
> 
> Traceback (most recent call last):
>   File "x.py", line 8, in <module>
> ImportError: No module named CMFlowData
> Traceback (most recent call last):
>   File "x.py", line 8, in <module>
> ImportError: No module named CMFlowData
> 
> All other files that I read from disk are created with relative paths
> and work fine, except when I import
> my own module.
> 
> Is there some procedure to "announce" my module to the Python or System?

I've never used py2exe myself, but from what I can gather py2exe should
be able to collect the imported modules automatically. Did you follow
everything in the py2exe tutorial:
http://www.py2exe.org/index.cgi/Tutorial ? Are there any deviations of
the things you did from the tutorial?


From galaxywatcher at gmail.com  Tue Apr  6 03:35:56 2010
From: galaxywatcher at gmail.com (TGW)
Date: Mon, 5 Apr 2010 21:35:56 -0400
Subject: [Tutor] Matching zipcode in address file
In-Reply-To: <mailman.6860.1270492303.23597.tutor@python.org>
References: <mailman.6860.1270492303.23597.tutor@python.org>
Message-ID: <8538950C-156B-4056-96B0-1806C7068CA5@gmail.com>

> OK - you handled the problem regarding reading to end-of-file. Yes it
> takes a lot longer, because now you are actually iterating through
> match_zips for each line.
>
> How large are these files? Consider creating a set from match_zips. As
> lists get longer, set membership test become faster than list  
> membership
> test.
>
> If the outfile is empty that means that line[149:154] is never in
> match_zips.
>
> I suggest you take a look at match_zips. You will find a list of  
> strings
> of length 6, which cannot match line[149:154], a string of length 5.

I am still struggling with this....I have simplified the code, because  
I need to understand the principle.

#!/usr/bin/env python

import string

def main():
      infile = open("filex")
      outfile = open("results_testx", "w")
      zips = open("zippys", "r")
      match_zips = zips.readlines()
      lines = [line for line in infile if line[0:3] + '\n' in  
match_zips]
      outfile.write(''.join(lines))
      print line[0:3]
      zips.close()
      infile.close()
      outfile.close()
main()

filex:
112332424
23423423423
34523423423
456234234234
234234234234
5672342342
683824242

zippys:
123
123
234
345
456
567
678
555


I want to output records from filex whose first 3 characters match a  
record in zippys. Ouptut:
23423423423
34523423423
456234234234
234234234234
5672342342

I am not sure where I should put a '\n' or tweak something that I just  
cannot see.

Thanks

From galaxywatcher at gmail.com  Tue Apr  6 04:47:56 2010
From: galaxywatcher at gmail.com (TGW)
Date: Mon, 5 Apr 2010 22:47:56 -0400
Subject: [Tutor] Matching zipcode in address file
In-Reply-To: <mailman.6906.1270509347.23597.tutor@python.org>
References: <mailman.6906.1270509347.23597.tutor@python.org>
Message-ID: <5E4637CE-AFEA-40EE-8753-704FDA121939@gmail.com>

I got it. I was comparing '345' to '345\n'

Adding the '\n' to the slice did indeed do the trick.

#!/usr/bin/env python

import string

def main():
      infile = open("filex")
      outfile = open("results_testx", "w")
      zips = open("zippys", "r")
      match_zips = zips.readlines()
      lines = [line for line in infile if (line[0:3] + '\n')  in  
match_zips]
      outfile.write(''.join(lines))
#     print lines[0:2]
      zips.close()
      infile.close()
      outfile.close()
main()


From ranjand2005 at gmail.com  Tue Apr  6 08:16:19 2010
From: ranjand2005 at gmail.com (ranjan das)
Date: Tue, 6 Apr 2010 11:46:19 +0530
Subject: [Tutor] Extracting lines in a file
Message-ID: <u2u8e8e6fc01004052316ue028c3d8w89349ef260eae74a@mail.gmail.com>

Hi,


I am new to python, and specially to file handling.

I need to write a program which reads a unique string in a file and
corresponding to the unique string, extracts/reads the n-th line (from the
line in which the unique string occurs).

I say 'n-th line' as I seek a generalized way of doing it.

For instance lets say the unique string is "documentation" (and
"documentation" occurs more than once in the file). Now, on each instance
that the string "documentation" occurs in the file,  I want to read the 25th
line (from the line in which the string "documentation" occurs)

Is there a goto kind of function in python?

Kindly help
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100406/51f15e40/attachment.html>

From stefan_ml at behnel.de  Tue Apr  6 08:23:24 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Tue, 06 Apr 2010 08:23:24 +0200
Subject: [Tutor] Getting traceback info from C-API
In-Reply-To: <g2g75fa0c3a1004051606t9ebb1967id332e1d174ec716@mail.gmail.com>
References: <g2g75fa0c3a1004051606t9ebb1967id332e1d174ec716@mail.gmail.com>
Message-ID: <hpek0s$88r$1@dough.gmane.org>

Shu, 06.04.2010 01:06:
>  I have a CAPI extension module that is giving me MemoryError
> exceptions from once in a while with no other information

MemoryError is a bit special in that it usually only occurs when memory 
allocation fails, in which case raising a new exception object would likely 
also fail. So there is a pre-allocated MemoryError instance without any 
error text that can be raised in this case.


> so clearly
> none of my exception handlers are catching it. Is there any way I can
> traceback information for the extension module?

Is it a module that you have written yourself? In that case, you can 
manually add traceback information for each function in your code. There is 
a PyTraceBack_Here() function for that.

However, it might be easier to just rewrite your module in Cython, which 
will do this automatically for every function you write.

Stefan


From alan.gauld at btinternet.com  Tue Apr  6 09:45:26 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Apr 2010 08:45:26 +0100
Subject: [Tutor] Matching zipcode in address file
References: <mailman.6906.1270509347.23597.tutor@python.org>
	<5E4637CE-AFEA-40EE-8753-704FDA121939@gmail.com>
Message-ID: <hpeor8$m4c$1@dough.gmane.org>


"TGW" <galaxywatcher at gmail.com> wrote 
>I got it. I was comparing '345' to '345\n'
> 
> Adding the '\n' to the slice did indeed do the trick.

Yes, the problem is that the data in the file always has a \n at the end.
So you either have to rstrip() that off when you read it from the file 
or add a \n to your source data when comparing it with file data.

Personally I usually use strip() so that I'm working with 'clean' data
both for source and reference.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Tue Apr  6 09:54:37 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 6 Apr 2010 08:54:37 +0100
Subject: [Tutor] Extracting lines in a file
References: <u2u8e8e6fc01004052316ue028c3d8w89349ef260eae74a@mail.gmail.com>
Message-ID: <hpepcg$nqu$1@dough.gmane.org>


"ranjan das" <ranjand2005 at gmail.com> wrote

> For instance lets say the unique string is "documentation" (and
> "documentation" occurs more than once in the file). Now, on each instance
> that the string "documentation" occurs in the file,  I want to read the 
> 25th
> line (from the line in which the string "documentation" occurs)
>
> Is there a goto kind of function in python?

There is a seek() function but it would require the lines to be of
constant length. Its probably easier to just use a loop:

def file_jump(fileobj, n =1):
      for line in range(n):
            fileobj.readline()

That will move the file pointer forward n lines.

Note, if the jumps can overlap the original then you might want
to  use tell() before the jump to store the original location then
use seek() to go back. (eg if the trigger was in line 5 and the
jump was 7 lines but  the trigger also occured in line 10)

Pseudocode:

for line in file:
     if trigger in line:
         marker = file.tell()
         file_jump(file, jumps[trigger])
         process_file_data()
         file.seek(marker)   # go back to original position

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




From cwitts at compuscan.co.za  Tue Apr  6 10:13:04 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Tue, 06 Apr 2010 10:13:04 +0200
Subject: [Tutor] Extracting lines in a file
In-Reply-To: <hpepcg$nqu$1@dough.gmane.org>
References: <u2u8e8e6fc01004052316ue028c3d8w89349ef260eae74a@mail.gmail.com>
	<hpepcg$nqu$1@dough.gmane.org>
Message-ID: <4BBAED10.4000503@compuscan.co.za>

Alan Gauld wrote:
>
> "ranjan das" <ranjand2005 at gmail.com> wrote
>
>> For instance lets say the unique string is "documentation" (and
>> "documentation" occurs more than once in the file). Now, on each 
>> instance
>> that the string "documentation" occurs in the file,  I want to read 
>> the 25th
>> line (from the line in which the string "documentation" occurs)
>>
>> Is there a goto kind of function in python?
>
> There is a seek() function but it would require the lines to be of
> constant length. Its probably easier to just use a loop:
>
> def file_jump(fileobj, n =1):
>      for line in range(n):
>            fileobj.readline()
>
> That will move the file pointer forward n lines.
>
> Note, if the jumps can overlap the original then you might want
> to  use tell() before the jump to store the original location then
> use seek() to go back. (eg if the trigger was in line 5 and the
> jump was 7 lines but  the trigger also occured in line 10)
>
> Pseudocode:
>
> for line in file:
>     if trigger in line:
>         marker = file.tell()
>         file_jump(file, jumps[trigger])
>         process_file_data()
>         file.seek(marker)   # go back to original position
>
> HTH,
>
>

If you know the line numbers you can use the linecache module to get any 
line from any file for eg.

 >>> import linecache
 >>> linecache.getline('/etc/passwd', 4)
'sys:x:3:3:sys:/dev:/bin/sh\n'

If what you require is more complex than simply that then you might be 
better off doing line-for-line processing on the file.

-- 
Kind Regards,
Christian Witts



From davea at ieee.org  Tue Apr  6 11:26:44 2010
From: davea at ieee.org (Dave Angel)
Date: Tue, 06 Apr 2010 05:26:44 -0400
Subject: [Tutor] Extracting lines in a file
In-Reply-To: <u2u8e8e6fc01004052316ue028c3d8w89349ef260eae74a@mail.gmail.com>
References: <u2u8e8e6fc01004052316ue028c3d8w89349ef260eae74a@mail.gmail.com>
Message-ID: <4BBAFE54.1060507@ieee.org>

ranjan das wrote:
> Hi,
>
>
> I am new to python, and specially to file handling.
>
> I need to write a program which reads a unique string in a file and
> corresponding to the unique string, extracts/reads the n-th line (from the
> line in which the unique string occurs).
>
> I say 'n-th line' as I seek a generalized way of doing it.
>
> For instance lets say the unique string is "documentation" (and
> "documentation" occurs more than once in the file). Now, on each instance
> that the string "documentation" occurs in the file,  I want to read the 25th
> line (from the line in which the string "documentation" occurs)
>
> Is there a goto kind of function in python?
>
> Kindly help
>
>   
You can randomly access within an open file with the seek() function.  
However, if the lines are variable length, somebody would have to keep 
track of where each one begins, which is rather a pain.  Possibly worse, 
on Windows, if you've opened the file in text mode, you can't just count 
the characters you get, since 0d0a is converted to 0a before you get 
it.  You can still do it with a combination of seek() and tell(), however.

Three easier possibilities, if any of them applies:

1) If the lines are fixed in size, then just randomly access using 
seek() before the read.

2) If the file isn't terribly big, read it into a list with readlines(), 
and randomly access the list.

3) If the file is organized in "records" (groups of lines), then read 
and process a record at a time, rather than a line at a time.  A record 
might be 30 lines, and if you found something on the first line of the 
record, you want to modify the 26th line (that's your +25).  Anyway, 
it's possible to make a wrapper around file so that you can iterate 
through records, rather than lines.

HTH
DaveA


From bgailer at gmail.com  Tue Apr  6 15:11:46 2010
From: bgailer at gmail.com (bob gailer)
Date: Tue, 06 Apr 2010 09:11:46 -0400
Subject: [Tutor] Extracting lines in a file
In-Reply-To: <u2u8e8e6fc01004052316ue028c3d8w89349ef260eae74a@mail.gmail.com>
References: <u2u8e8e6fc01004052316ue028c3d8w89349ef260eae74a@mail.gmail.com>
Message-ID: <4BBB3312.8080603@gmail.com>

On 4/6/2010 2:16 AM, ranjan das wrote:
>
> Hi,
>
>
> I am new to python, and specially to file handling.
>
> I need to write a program which reads a unique string in a file and 
> corresponding to the unique string, extracts/reads the n-th line (from 
> the line in which the unique string occurs).
>
> I say 'n-th line' as I seek a generalized way of doing it.
>
> For instance lets say the unique string is "documentation" (and 
> "documentation" occurs more than once in the file). Now, on each 
> instance that the string "documentation" occurs in the file,  I want 
> to read the 25th line (from the line in which the string 
> "documentation" occurs)

> Is there a goto kind of function in python?

Others have offered linecache and seek.

The simplest generic solution is:

lines_to_be_read = []
for lineno, line in enumerate(open(filename)):
   if "documentation" in line:
     lines_to_be_read.append(lineno + 25)
   if lineno in lines_to_be_read:
     # process this line
     lines_to_be_read.pop(0)

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From anjalinairm at gmail.com  Tue Apr  6 17:17:21 2010
From: anjalinairm at gmail.com (anjali nair)
Date: Tue, 6 Apr 2010 20:47:21 +0530
Subject: [Tutor] create a wrapper for a C program
Message-ID: <s2he9119c11004060817r9dd89a7cy38e9ea32c3eccda3@mail.gmail.com>

Hi,,,

I am new to python. My doubt is related to wrapping a C program with a
python script.. I am running Netperf for Network Performance Benchmarking.
The code is written in C and has an associated Makefile. I thought of
writing a Python script which should be able to run Netperf with the
associated arguments on executing it. Do I need to go for SWIG? I tried
invoking by using subprocess, but that did not work.

Can somebody help?

Thanks
-- 
Anjali M
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100406/cd86ce85/attachment.html>

From emile at fenx.com  Wed Apr  7 00:04:39 2010
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 06 Apr 2010 15:04:39 -0700
Subject: [Tutor] create a wrapper for a C program
In-Reply-To: <s2he9119c11004060817r9dd89a7cy38e9ea32c3eccda3@mail.gmail.com>
References: <s2he9119c11004060817r9dd89a7cy38e9ea32c3eccda3@mail.gmail.com>
Message-ID: <hpgb5k$plu$1@dough.gmane.org>

On 4/6/2010 8:17 AM anjali nair said...
> Hi,,,
>
> I am new to python. My doubt is related to wrapping a C program with a
> python script.. I am running Netperf for Network Performance Benchmarking.
> The code is written in C and has an associated Makefile. I thought of
> writing a Python script which should be able to run Netperf with the
> associated arguments on executing it. Do I need to go for SWIG? I tried
> invoking by using subprocess, but that did not work.
>
> Can somebody help?


Looks like that's a command line tool -- you probably do want to use 
subprocess.  Show us what didn't work...

Emile


From stefan_ml at behnel.de  Wed Apr  7 08:09:47 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Wed, 07 Apr 2010 08:09:47 +0200
Subject: [Tutor] create a wrapper for a C program
In-Reply-To: <s2he9119c11004060817r9dd89a7cy38e9ea32c3eccda3@mail.gmail.com>
References: <s2he9119c11004060817r9dd89a7cy38e9ea32c3eccda3@mail.gmail.com>
Message-ID: <hph7jb$83r$1@dough.gmane.org>

anjali nair, 06.04.2010 17:17:
> I am new to python. My doubt is related to wrapping a C program with a
> python script.. I am running Netperf for Network Performance Benchmarking.
> The code is written in C and has an associated Makefile. I thought of
> writing a Python script which should be able to run Netperf with the
> associated arguments on executing it. Do I need to go for SWIG? I tried
> invoking by using subprocess, but that did not work.

"netperf" is a command line tool, so subprocess is the way to go. Note that 
"did not work" isn't a very complete problem description, so if you want 
advice on how to solve the problem at hand, please provide the code you 
tried and the exact error output that you got.

If you really want to write a C-level wrapper for the tool, you should 
first make sure that there is 1) an exported library that you can interface 
with, and either 2a) more functionality in the library than in the command 
line tool, or 2b) functionality in the library where you can benefit from 
very fast calling. If the major work happens inside of the tool, and it 
provides the functionality you need through its command line interface, 
writing a C-level wrapper for it is almost certainly not worth it.

BTW, SWIG isn't a particularly good way of writing a Python wrapper for a C 
program (unless you want to generate wrappers for some other languages at 
the same time).

Stefan


From dotancohen at gmail.com  Wed Apr  7 10:39:37 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Wed, 7 Apr 2010 11:39:37 +0300
Subject: [Tutor] Where to start, running interactive bash script in Qt GUI
Message-ID: <z2u880dece01004070139m6c29dc2bld377ad639d66b132@mail.gmail.com>

Hello all, new poster.

I have an interactive bash script that asks for a password, then
connects a remote machine via fuse with the supplied password. That's
fine for me, however, the wife needs an icon to click on, input a
password, and be on he way. I'd like to do that in Python with Qt. Is
there a way to wrap a bash script with Python for a GUI, ask for a
line of user input, then pass that to the bash script?

If there is a particular fine manual that I should be reading, I would
appreciate a link. I have been googling but found nothing relevant
that really helps. I am new to Python and have never used Qt. Thanks!

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il

?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?
?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-??-?-?
?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?
?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?
?-?-?-?-?-?-?

From computing.account at googlemail.com  Wed Apr  7 11:38:07 2010
From: computing.account at googlemail.com (AG)
Date: Wed, 07 Apr 2010 10:38:07 +0100
Subject: [Tutor] Introduction to modelling with Python
In-Reply-To: <201003281543.22999.eike.welk@gmx.net>
References: <4BAE2276.5050807@gmail.com> <201003281543.22999.eike.welk@gmx.net>
Message-ID: <4BBC527F.4040907@gmail.com>

Eike Welk wrote:
> On Saturday March 27 2010 16:21:26 AG wrote:
>   
>> I apologise in advance for the vagueness of this query, but I am looking
>> for a decent modern introduction to modelling using Python.
>> Specifically, I want something that is a good introduction (i.e. doesn't
>> expect one to already be a maths/ statistics or a programming guru) and
>> that has an ecology/ environmental science orientation. 
>>     
>
> You should look at the book "Python Scripting for Computational Science" by 
> Hans Petter Langtangen:
> http://www.amazon.com/Python-Scripting-Computational-Science-
> Engineering/dp/3540435085
> http://books.google.com/books?id=YEoiYr4H2A0C&printsec=frontcover&dq="Python+Scripting+for+Computational+Science"&source=bl&ots=ovp_JKREiY&sig=tJkigCLDqS6voOOjmL4xDxw0roM&hl=en&ei=OlWvS8PmE4r94Aa42vzgDw&sa=X&oi=book_result&ct=result&resnum=5&ved=0CBEQ6AEwBA#v=onepage&q=&f=false
>
> It is an introduction to the Python language, and to a big number of tools for 
> numerical computations. The book assumes that you have already some practice 
> in writing computer programs. 
>
> The book is not oriented towards ecology, the examples are from mechanical 
> engineering. 
>
> The book is however a bit dated, it's from 2004. Therefore many examples will 
> need to be slightly altered to work with the current versions of the libraries 
> that they use. 
>
>
>
> Alternatively you could ask your question on the Numpy/Scipy mailing lists. 
> These lists are frequented by scientists that use Python for their 
> computations.  
> http://www.scipy.org/Mailing_Lists
>
>
>
> Eike.
> _______________________________________________
>   

Eike

I just wanted to come back to you on the book recommendation you made 
"Python scripting for computational science" - I tracked down a cheapish 
copy of the 3rd edition from 2009 and flipping through it (it only 
arrived yesterday), it seems like it is going to be very useful.  
Certainly it draws a lot on numpy, goes into using Tcl for GUIs, and a 
number of recipes for scripting, regular expressions and so on ... lots 
to get my head around.  With respect to my original question then, 
equipped with this book you recommended, a book on differential 
equations, and one on an intro to environmental modelling, that should 
give me enough to work on for the time being.

So, just wanted to close the circle by letting you know that I took your 
recommendation, and it looks like it will pay off in time.

Thank you.

AG
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100407/3db7466e/attachment-0001.html>

From shurui91 at gmail.com  Wed Apr  7 12:56:27 2010
From: shurui91 at gmail.com (Shurui Liu (Aaron Liu))
Date: Wed, 7 Apr 2010 06:56:27 -0400
Subject: [Tutor] ask-why I cannot run it,
	and I am so confused about the traceback
Message-ID: <h2h2b9003cf1004070356z93d95595x5d52442c96718a8b@mail.gmail.com>

# Filename: classVolume.py
# Demonstrates multiple classes per program.

class Cube:
   """A class for cube shapes."""
   def __init__(self, side):
       self.side = side
   def calculateArea(self):
       return (self.side)**3.0

class Sphere:
   """A class for sphere shapes."""
   def __init__(self, radius1):
       self.radius1 = radius1
   def calculateArea(self):
       import math
       return (4/3)*(math.pi)*((self.radius1)**3.0)

class Cone:
   """A class for cone shapes."""
   def __init__(self, radius2, height):
       self.radius2 = radius2
       self.height = height
   def calculateArea(self):
       import math
       return (1/3.0)*(math.pi)*(self.height)*((self.radius2)**2)


# Create a list of volumes.
list = [Cube(1.1),Cube(1.2),Sphere(1.1),Sphere(1.2),Cone(1.1),Cone(1.2)]

# Print out the list contents.
for volume in list:
   print "The volume is: ", volume.calculateArea()
raw_input("\n\nPress the enter key to exit.")





Traceback (most recent call last):
 File "classVolume.py", line 30, in <module>
   list = [Cube(1.1),Cube(1.2),Sphere(1.1),Sphere(1.2),Cone(1.1),Cone(1.2)]
TypeError: __init__() takes exactly 3 arguments (2 given)


-- 
Shurui Liu (Aaron Liu)
Computer Science & Engineering Technology
University of Toledo
419-508-1228
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100407/50203d67/attachment.html>

From wesbrooks at gmail.com  Wed Apr  7 13:00:44 2010
From: wesbrooks at gmail.com (Wesley Brooks)
Date: Wed, 7 Apr 2010 12:00:44 +0100
Subject: [Tutor] ask-why I cannot run it,
	and I am so confused about the 	traceback
In-Reply-To: <h2h2b9003cf1004070356z93d95595x5d52442c96718a8b@mail.gmail.com>
References: <h2h2b9003cf1004070356z93d95595x5d52442c96718a8b@mail.gmail.com>
Message-ID: <q2leec9f8ee1004070400x774819caw6cd72f362c985045@mail.gmail.com>

Morning,

Your only supplying one argument to cone, when you need two: radius & height.

Cheers,

Wesley Brooks.

On 7 April 2010 11:56, Shurui Liu (Aaron Liu) <shurui91 at gmail.com> wrote:
> # Filename: classVolume.py
> # Demonstrates multiple classes per program.
>
> class Cube:
> ? ?"""A class for cube shapes."""
> ? ?def __init__(self, side):
> ? ? ? ?self.side = side
> ? ?def calculateArea(self):
> ? ? ? ?return (self.side)**3.0
>
> class Sphere:
> ? ?"""A class for sphere shapes."""
> ? ?def __init__(self, radius1):
> ? ? ? ?self.radius1 = radius1
> ? ?def calculateArea(self):
> ? ? ? ?import math
> ? ? ? ?return (4/3)*(math.pi)*((self.radius1)**3.0)
>
> class Cone:
> ? ?"""A class for cone shapes."""
> ? ?def __init__(self, radius2, height):
> ? ? ? ?self.radius2 = radius2
> ? ? ? ?self.height = height
> ? ?def calculateArea(self):
> ? ? ? ?import math
> ? ? ? ?return (1/3.0)*(math.pi)*(self.height)*((self.radius2)**2)
>
>
> # Create a list of volumes.
> list = [Cube(1.1),Cube(1.2),Sphere(1.1),Sphere(1.2),Cone(1.1),Cone(1.2)]
>
> # Print out the list contents.
> for volume in list:
> ? ?print "The volume is: ", volume.calculateArea()
> raw_input("\n\nPress the enter key to exit.")
>
>
>
>
>
> Traceback (most recent call last):
> ?File "classVolume.py", line 30, in <module>
> ? ?list = [Cube(1.1),Cube(1.2),Sphere(1.1),Sphere(1.2),Cone(1.1),Cone(1.2)]
> TypeError: __init__() takes exactly 3 arguments (2 given)
>
>
> --
> Shurui Liu (Aaron Liu)
> Computer Science & Engineering Technology
> University of Toledo
> 419-508-1228
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From martin at linux-ip.net  Wed Apr  7 13:02:31 2010
From: martin at linux-ip.net (Martin A. Brown)
Date: Wed, 7 Apr 2010 13:02:31 +0200
Subject: [Tutor] ask-why I cannot run it,
 and I am so confused about the traceback
In-Reply-To: <h2h2b9003cf1004070356z93d95595x5d52442c96718a8b@mail.gmail.com>
References: <h2h2b9003cf1004070356z93d95595x5d52442c96718a8b@mail.gmail.com>
Message-ID: <alpine.LNX.2.00.1004071300340.8718@octothorpe.wonderfrog.net>

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

Greetings,

 : class Cone:
 :    """A class for cone shapes."""
 :    def __init__(self, radius2, height):
 :        self.radius2 = radius2
 :        self.height = height
 :    def calculateArea(self):
 :        import math
 :        return (1/3.0)*(math.pi)*(self.height)*((self.radius2)**2)
 : 
 : 
 : # Create a list of volumes.
 : list = [Cube(1.1),Cube(1.2),Sphere(1.1),Sphere(1.2),Cone(1.1),Cone(1.2)]
 : 
 : # Print out the list contents.
 : for volume in list:
 :    print "The volume is: ", volume.calculateArea()
 : raw_input("\n\nPress the enter key to exit.")

 : Traceback (most recent call last):
 :  File "classVolume.py", line 30, in <module>
 :    list = [Cube(1.1),Cube(1.2),Sphere(1.1),Sphere(1.2),Cone(1.1),Cone(1.2)]
 : TypeError: __init__() takes exactly 3 arguments (2 given)

Look at your __init__ method for Cone().
Look at your invocation.

Each call to Cone only supplies a single argument.

  ... Cone(1.1),Cone(1.2) ...

- -Martin

- -- 
Martin A. Brown
http://linux-ip.net/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.9 (GNU/Linux)
Comment: pgf-0.72 (http://linux-ip.net/sw/pine-gpg-filter/)

iD8DBQFLvGZJHEoZD1iZ+YcRAikGAJ4gkDCl6ljej92QFx0VfYgh3jPUFACfUlWD
Yx6ZZiTTs6JIxulV+RcWucU=
=fhP5
-----END PGP SIGNATURE-----

From shurui91 at gmail.com  Wed Apr  7 14:12:37 2010
From: shurui91 at gmail.com (Shurui Liu (Aaron Liu))
Date: Wed, 7 Apr 2010 08:12:37 -0400
Subject: [Tutor] ask-why I cannot run it,
	and I am so confused about the 	traceback
In-Reply-To: <q2leec9f8ee1004070400x774819caw6cd72f362c985045@mail.gmail.com>
References: <h2h2b9003cf1004070356z93d95595x5d52442c96718a8b@mail.gmail.com>
	<q2leec9f8ee1004070400x774819caw6cd72f362c985045@mail.gmail.com>
Message-ID: <y2h2b9003cf1004070512le9776e0cwa9f6a8dbf1f2e89a@mail.gmail.com>

Yes, I found it. thanks!

On Wed, Apr 7, 2010 at 7:00 AM, Wesley Brooks <wesbrooks at gmail.com> wrote:

> Morning,
>
> Your only supplying one argument to cone, when you need two: radius &
> height.
>
> Cheers,
>
> Wesley Brooks.
>
> On 7 April 2010 11:56, Shurui Liu (Aaron Liu) <shurui91 at gmail.com> wrote:
> > # Filename: classVolume.py
> > # Demonstrates multiple classes per program.
> >
> > class Cube:
> >    """A class for cube shapes."""
> >    def __init__(self, side):
> >        self.side = side
> >    def calculateArea(self):
> >        return (self.side)**3.0
> >
> > class Sphere:
> >    """A class for sphere shapes."""
> >    def __init__(self, radius1):
> >        self.radius1 = radius1
> >    def calculateArea(self):
> >        import math
> >        return (4/3)*(math.pi)*((self.radius1)**3.0)
> >
> > class Cone:
> >    """A class for cone shapes."""
> >    def __init__(self, radius2, height):
> >        self.radius2 = radius2
> >        self.height = height
> >    def calculateArea(self):
> >        import math
> >        return (1/3.0)*(math.pi)*(self.height)*((self.radius2)**2)
> >
> >
> > # Create a list of volumes.
> > list = [Cube(1.1),Cube(1.2),Sphere(1.1),Sphere(1.2),Cone(1.1),Cone(1.2)]
> >
> > # Print out the list contents.
> > for volume in list:
> >    print "The volume is: ", volume.calculateArea()
> > raw_input("\n\nPress the enter key to exit.")
> >
> >
> >
> >
> >
> > Traceback (most recent call last):
> >  File "classVolume.py", line 30, in <module>
> >    list =
> [Cube(1.1),Cube(1.2),Sphere(1.1),Sphere(1.2),Cone(1.1),Cone(1.2)]
> > TypeError: __init__() takes exactly 3 arguments (2 given)
> >
> >
> > --
> > Shurui Liu (Aaron Liu)
> > Computer Science & Engineering Technology
> > University of Toledo
> > 419-508-1228
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
>



-- 
Shurui Liu (Aaron Liu)
Computer Science & Engineering Technology
University of Toledo
419-508-1228
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100407/19bb1ec5/attachment-0001.html>

From bgailer at gmail.com  Wed Apr  7 15:15:35 2010
From: bgailer at gmail.com (bob gailer)
Date: Wed, 07 Apr 2010 09:15:35 -0400
Subject: [Tutor] ask-why I cannot run it,
 and I am so confused about the traceback
In-Reply-To: <h2h2b9003cf1004070356z93d95595x5d52442c96718a8b@mail.gmail.com>
References: <h2h2b9003cf1004070356z93d95595x5d52442c96718a8b@mail.gmail.com>
Message-ID: <4BBC8577.5010408@gmail.com>

You have the solution. Good.

I beg you to avoid colored text. I find it hard to read.

Just use good old plain text. No fancy fonts, sizes, colors.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From matjaz88 at hotmail.com  Wed Apr  7 15:51:05 2010
From: matjaz88 at hotmail.com (Matjaz Pfefferer)
Date: Wed, 7 Apr 2010 15:51:05 +0200
Subject: [Tutor] ftp and python
Message-ID: <COL117-W567B9A7B0055973777C3AFC6170@phx.gbl>


Hi,

I'm Py newbie and I have some beginners problems with ftp 
handling.
What would be the easiest way to copy files from one ftp 
folder to another without downloading them to local system?
Are there
 any snippets for this task (I couldnt find example like this)

Thx 		 	   		  
_________________________________________________________________
Hotmail: Powerful Free email with security by Microsoft.
https://signup.live.com/signup.aspx?id=60969
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100407/dd441e7c/attachment.html>

From emailkgnow at gmail.com  Wed Apr  7 16:48:57 2010
From: emailkgnow at gmail.com (Khalid Al-Ghamdi)
Date: Wed, 7 Apr 2010 17:48:57 +0300
Subject: [Tutor] Django Book Recommendation
Message-ID: <p2udfac564f1004070748o14ac6590qf41ce4943e78204c@mail.gmail.com>

Hi everyone!

Do you have recommendations regrading good free books or websites to learn
django? I'm a beginner and know the basics of python.

thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100407/65e20c7d/attachment.html>

From zstumgoren at gmail.com  Wed Apr  7 17:12:49 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Wed, 7 Apr 2010 11:12:49 -0400
Subject: [Tutor] Django Book Recommendation
In-Reply-To: <p2udfac564f1004070748o14ac6590qf41ce4943e78204c@mail.gmail.com>
References: <p2udfac564f1004070748o14ac6590qf41ce4943e78204c@mail.gmail.com>
Message-ID: <t2gcadf44511004070812v59bde9b9g45e007d5b44e6ff8@mail.gmail.com>

There is lots of good information in the second edition of the
official Django Book (though it appears it's only a partially complete
Web preview):

  http://www.djangobook.com/en/2.0/

The Django google group is a great way to research specific questions
and get help:

  http://groups.google.com/group/django-users/

And though it's not free, I highly recommend the book Pro Django by
Marty Alchin. It deals with some pretty advanced concepts, but it's
the first resource I've found that really demonstrates how Django
works under the covers. You don't need to read it to use Django, but
it's an invaluable resource if you're trying to piece together the
moving parts behind the framework. And it's a great primer on more
advanced Python techniques like meta-programming.

HTH,
Serdar

On Wed, Apr 7, 2010 at 10:48 AM, Khalid Al-Ghamdi <emailkgnow at gmail.com> wrote:
> Hi everyone!
> Do you have?recommendations?regrading good free books or websites to learn
> django? I'm a beginner and know the basics of python.
> thanks
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From doyennehoney at yahoo.com  Wed Apr  7 17:30:36 2010
From: doyennehoney at yahoo.com (doyin adegoke)
Date: Wed, 7 Apr 2010 08:30:36 -0700 (PDT)
Subject: [Tutor] Display in a text field using tkinter
In-Reply-To: <g2x98c3f7c51004041335gb6cc4f70gf181e733e29e5b63@mail.gmail.com>
References: <m2gcf7f1f3e1004012325k3bdfc413pa919e33145ebd766@mail.gmail.com>
	<g2x98c3f7c51004041335gb6cc4f70gf181e733e29e5b63@mail.gmail.com>
Message-ID: <813267.14529.qm@web34507.mail.mud.yahoo.com>

Thanks guys I was able to resolve it by changing

self.txt_box = Entry(self, text = "hool").grid(row = 0, column = 1, sticky = W)

to

self.txt_box = Entry(self, text = "hool")
self.txt_box.grid(row = 0, column = 1, sticky = W)

and

 self.txt_box.insert(END,trt)

to

 self.txt_box.insert(0,trt)

but i added

 self.txt_box.delete(0, END)

before inserting






________________________________
From: James Reynolds <eire1130 at gmail.com>
To: adedoyin adegoke <doyennehoney at yahoo.com>
Sent: Sun, April 4, 2010 9:35:37 PM
Subject: Re: [Tutor] Display in a text field using tkinter

Did you try setting this (in the init):

self.create_widgets()

to something like this:

my_object = self.create_widgets()

?


On Fri, Apr 2, 2010 at 2:25 AM, adedoyin adegoke <doyennehoney at yahoo.com> wrote:

from Tkinter import *
>import MySQLdb
>
>
>class Snoop(Frame):
>    def __init__(self, master):
>        Frame.__init__(self, master)
>        self.grid()
>>        self.create_widgets()
>
>
>    def create_widgets(self):
>        Label(self, text = "Database Name:").grid(row = 0, column = 0, sticky = W)
>        self.txt_box = Entry(self, text = "hool").grid(row = 0, column = 1, sticky = W)
>        Button(self, text = "Submit", command = self.connect_db).grid(row = 1, column = 1, sticky = W)
>        Label(self, text = "Tables:").grid(row = 2, column = 0, sticky = W)
>>
>       
>        Label(self, text = "Information:").grid(row = 2, column = 1, sticky = W)
>       # self.txt = Text(self, width = 40, height = 5, wrap = WORD).grid(row = 3, column = 1, sticky = W)
>       
>    def connect_db(self):
>        db= MySQLdb.connect(host="localhost", user="root" , passwd="")
>        cursor = db.cursor()
>        cursor.execute("show databases")
>
>
>        self.favorite = StringVar()
>
>
>        result = cursor.fetchall()
>        i = 4
>        for record in result:
>            Radiobutton(self,
>                     text = record,
>                     variable = self.favorite,
>                     value = record,
>                     command = self.update_text
>                     ).grid(row = i, column = 0, sticky = W)
>            i+=1
>        
>        #print database
>        #self.txt.delete(0.0, END)
>        #self.get_db(database)
>    def update_text(self):
>        print self.favorite.get()
>        trt = self.favorite.get()
>        self.txt_box.insert(END,trt)
>
>
>   
>
>
>#db.close
>root = Tk()
>root.title("Snoop")
>>
>start = Snoop(root)
>
>
>root.mainloop()
>
>
>
>
>
>
>The above code will snoop and fetch all d available databases using tkinter. When I select one of these databases, the name should be inserted in a text field instead it throws the following error ;
>
>
>Exception in Tkinter callback
>Traceback (most recent call last):
>  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__
>    return self.func(*args)
>  File "/home/NetBeansProjects/python/src/Xsnoop.py", line 45, in update_text
>    self.txt_box.insert(END,trt)
>AttributeError: 'NoneType' object has no attribute 'insert'
>   
>
>
>How can i correct this?
>
>
>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>To unsubscribe or change subscription options:
>http://mail.python.org/mailman/listinfo/tutor
>
>



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100407/30a2b81d/attachment-0001.html>

From c.t.matsumoto at gmail.com  Wed Apr  7 18:14:23 2010
From: c.t.matsumoto at gmail.com (C.T. Matsumoto)
Date: Wed, 07 Apr 2010 18:14:23 +0200
Subject: [Tutor] Django Book Recommendation
In-Reply-To: <t2gcadf44511004070812v59bde9b9g45e007d5b44e6ff8@mail.gmail.com>
References: <p2udfac564f1004070748o14ac6590qf41ce4943e78204c@mail.gmail.com>
	<t2gcadf44511004070812v59bde9b9g45e007d5b44e6ff8@mail.gmail.com>
Message-ID: <4BBCAF5F.8020707@gmail.com>

If I can follow up with the 'not free' theme, I also think 'Practical 
Django Projects' by James Bennett is pretty good.

For really fast tutorials, look for screencasts too.

T

> And though it's not free, I highly recommend the book Pro Django by
> Marty Alchin.

From emile at fenx.com  Wed Apr  7 18:43:25 2010
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 07 Apr 2010 09:43:25 -0700
Subject: [Tutor] ftp and python
In-Reply-To: <COL117-W567B9A7B0055973777C3AFC6170@phx.gbl>
References: <COL117-W567B9A7B0055973777C3AFC6170@phx.gbl>
Message-ID: <hpicn6$kiv$1@dough.gmane.org>

On 4/7/2010 6:51 AM Matjaz Pfefferer said...
> I'm Py newbie and I have some beginners problems with ftp
> handling.
> What would be the easiest way to copy files from one ftp
> folder to another without downloading them to local system?

The easiest is of course command line access on the hosting system.  FTP 
is essentially a file transfer protocol designed and inteded to move 
data between systems.

If what you're asking for is essentially how to do a cp (or copy on 
win??) from a remote machine you may want to look at "scp - secure copy 
(remote file copy program)"

HTH,

Emile


From alan.gauld at btinternet.com  Wed Apr  7 20:23:08 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 7 Apr 2010 19:23:08 +0100
Subject: [Tutor] Where to start,
	running interactive bash script in Qt GUI
References: <z2u880dece01004070139m6c29dc2bld377ad639d66b132@mail.gmail.com>
Message-ID: <hpiij1$ec5$1@dough.gmane.org>


"Dotan Cohen" <dotancohen at gmail.com> wrote

> I have an interactive bash script that asks for a password, then
> connects a remote machine via fuse with the supplied password. 

> there a way to wrap a bash script with Python for a GUI, ask for a
> line of user input, then pass that to the bash script?

Rather than wrap the bash script I'd do the equivalent in Python.
Pop up a GUI window that captures the password then call fuse 
directly from Python via the subprocess module.

Rather than use Qt I'd use EasyGUI to just pop up an input box. 
It will be much easier.

http://easygui.sourceforge.net/

HTH,

Alan G.



From dotancohen at gmail.com  Wed Apr  7 20:44:12 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Wed, 7 Apr 2010 21:44:12 +0300
Subject: [Tutor] Where to start,
	running interactive bash script in Qt GUI
In-Reply-To: <hpiij1$ec5$1@dough.gmane.org>
References: <z2u880dece01004070139m6c29dc2bld377ad639d66b132@mail.gmail.com>
	<hpiij1$ec5$1@dough.gmane.org>
Message-ID: <m2z880dece01004071144wf0118877w7179339252a6e2a7@mail.gmail.com>

On 7 April 2010 21:23, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Dotan Cohen" <dotancohen at gmail.com> wrote
>
>> I have an interactive bash script that asks for a password, then
>> connects a remote machine via fuse with the supplied password.
>
>> there a way to wrap a bash script with Python for a GUI, ask for a
>> line of user input, then pass that to the bash script?
>
> Rather than wrap the bash script I'd do the equivalent in Python.
> Pop up a GUI window that captures the password then call fuse directly from
> Python via the subprocess module.
>

It is more than that, and calls many command-line functions such as
pdftools and imagemagic. I suppose that I could call them all from
Python, but it would be a mess. The bash is very straightforward for
working with command line tools.


> Rather than use Qt I'd use EasyGUI to just pop up an input box. It will be
> much easier.
>

I am hoping that this will be a stepping stone into bigger Qt
projects, as I am a motivated KDE user.


-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From fomcl at yahoo.com  Wed Apr  7 21:20:24 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Wed, 7 Apr 2010 12:20:24 -0700 (PDT)
Subject: [Tutor] ask-why I cannot run it,
	and I am so confused about the traceback
In-Reply-To: <4BBC8577.5010408@gmail.com>
Message-ID: <597244.40063.qm@web110701.mail.gq1.yahoo.com>

What's with Pythonistas and colours? http://www.mail-archive.com/python-list at python.org/msg231447.html ;-)))

Cheers!!

Albert-Jan



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

--- On Wed, 4/7/10, bob gailer <bgailer at gmail.com> wrote:

From: bob gailer <bgailer at gmail.com>
Subject: Re: [Tutor] ask-why I cannot run it, and I am so confused about the traceback
To: tutor at python.org
Date: Wednesday, April 7, 2010, 3:15 PM

You have the solution. Good.

I beg you to avoid colored text. I find it hard to read.

Just use good old plain text. No fancy fonts, sizes, colors.

-- Bob Gailer
919-636-4239
Chapel Hill NC

_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100407/2526fcac/attachment.html>

From wescpy at gmail.com  Wed Apr  7 21:46:12 2010
From: wescpy at gmail.com (wesley chun)
Date: Wed, 7 Apr 2010 12:46:12 -0700
Subject: [Tutor] Django Book Recommendation
In-Reply-To: <4BBCAF5F.8020707@gmail.com>
References: <p2udfac564f1004070748o14ac6590qf41ce4943e78204c@mail.gmail.com>
	<t2gcadf44511004070812v59bde9b9g45e007d5b44e6ff8@mail.gmail.com>
	<4BBCAF5F.8020707@gmail.com>
Message-ID: <x2t78b3a9581004071246l1737cc14wf68ee0bf5d200ff5@mail.gmail.com>

i worked on another well-received Django book with a pair of great
co-authors called "Python Web Development with Django", Addison Wesley
(2009).

rather than taking the existing Django docs, which are great BTW, and
expanding on them, we wanted to have a more comprehensive look at
Django development as a whole, starting with a strong intro to Python
and web services followed by taking on each major Django component
(model, template, view), then building 4 useful Django apps, all
focused on using different features of Django, then finally leading to
a high-level overview of more advanced features and useful appendices.

you can find out more from the amazon page as well as at the book's
homepage at: http://withdjango.com

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



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

From onyxtic at gmail.com  Wed Apr  7 22:07:08 2010
From: onyxtic at gmail.com (Evans Anyokwu)
Date: Wed, 7 Apr 2010 21:07:08 +0100
Subject: [Tutor] Django Book Recommendation
In-Reply-To: <x2t78b3a9581004071246l1737cc14wf68ee0bf5d200ff5@mail.gmail.com>
References: <p2udfac564f1004070748o14ac6590qf41ce4943e78204c@mail.gmail.com> 
	<t2gcadf44511004070812v59bde9b9g45e007d5b44e6ff8@mail.gmail.com> 
	<4BBCAF5F.8020707@gmail.com>
	<x2t78b3a9581004071246l1737cc14wf68ee0bf5d200ff5@mail.gmail.com>
Message-ID: <x2pc7e3e8811004071307ud944fec8n9f889fb5d945aa01@mail.gmail.com>

Nice book. I actually bought a copy of Python Web Development with Django
last month, and I can't recommend it enough.

On Wed, Apr 7, 2010 at 8:46 PM, wesley chun <wescpy at gmail.com> wrote:

> i worked on another well-received Django book with a pair of great
> co-authors called "Python Web Development with Django", Addison Wesley
> (2009).
>
> rather than taking the existing Django docs, which are great BTW, and
> expanding on them, we wanted to have a more comprehensive look at
> Django development as a whole, starting with a strong intro to Python
> and web services followed by taking on each major Django component
> (model, template, view), then building 4 useful Django apps, all
> focused on using different features of Django, then finally leading to
> a high-level overview of more advanced features and useful appendices.
>
> you can find out more from the amazon page as well as at the book's
> homepage at: http://withdjango.com
>
> cheers,
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
> "Python Fundamentals", Prentice Hall, (c)2009
>    http://corepython.com
>
>
>
> wesley.j.chun :: wescpy-at-gmail.com
> python training and technical consulting
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100407/1ee9174a/attachment-0001.html>

From steve at pearwood.info  Thu Apr  8 00:10:01 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 8 Apr 2010 08:10:01 +1000
Subject: [Tutor] ask-why I cannot run it,
	and I am so confused about the traceback
In-Reply-To: <4BBC8577.5010408@gmail.com>
References: <h2h2b9003cf1004070356z93d95595x5d52442c96718a8b@mail.gmail.com>
	<4BBC8577.5010408@gmail.com>
Message-ID: <201004080810.01969.steve@pearwood.info>

On Wed, 7 Apr 2010 11:15:35 pm bob gailer wrote:
> You have the solution. Good.
>
> I beg you to avoid colored text. I find it hard to read.
>
> Just use good old plain text. No fancy fonts, sizes, colors.

I don't see any of those. Can't you tell your mail client to ignore 
the "rich text" (HTML) attachment and just display the plain text?


-- 
Steven D'Aprano

From wescpy at gmail.com  Thu Apr  8 00:31:38 2010
From: wescpy at gmail.com (wesley chun)
Date: Wed, 7 Apr 2010 15:31:38 -0700
Subject: [Tutor] Django Book Recommendation
In-Reply-To: <x2pc7e3e8811004071307ud944fec8n9f889fb5d945aa01@mail.gmail.com>
References: <p2udfac564f1004070748o14ac6590qf41ce4943e78204c@mail.gmail.com>
	<t2gcadf44511004070812v59bde9b9g45e007d5b44e6ff8@mail.gmail.com>
	<4BBCAF5F.8020707@gmail.com>
	<x2t78b3a9581004071246l1737cc14wf68ee0bf5d200ff5@mail.gmail.com>
	<x2pc7e3e8811004071307ud944fec8n9f889fb5d945aa01@mail.gmail.com>
Message-ID: <w2l78b3a9581004071531x943f9d63s5cc4d9173ee68789@mail.gmail.com>

that's great!! we're always glad to hear about happy readers!

on a side note, if any of you out there are doing Django and Google
App Engine, there is some new information that i hadn't gotten a
chance to add to Appendix E yet. basically in that section, i describe
the use of the Helper but since then, there have been 2 more tools
that have come online. the 2nd is called the Patch, which was recently
replaced by django-nonrel and djangoappengine:
http://www.allbuttonspressed.com/

-wesley


On Wed, Apr 7, 2010 at 1:07 PM, Evans Anyokwu <onyxtic at gmail.com> wrote:
> Nice book. I actually bought a copy of Python Web Development with Django
> last month, and I can't recommend it enough.
>
> On Wed, Apr 7, 2010 at 8:46 PM, wesley chun <wescpy at gmail.com> wrote:
>>
>> i worked on another well-received Django book with a pair of great
>> co-authors called "Python Web Development with Django", Addison Wesley
>> (2009).
>>
>> rather than taking the existing Django docs, which are great BTW, and
>> expanding on them, we wanted to have a more comprehensive look at
>> Django development as a whole, starting with a strong intro to Python
>> and web services followed by taking on each major Django component
>> (model, template, view), then building 4 useful Django apps, all
>> focused on using different features of Django, then finally leading to
>> a high-level overview of more advanced features and useful appendices.
>>
>> you can find out more from the amazon page as well as at the book's
>> homepage at: http://withdjango.com
>>
>> cheers,
>> -- wesley
>> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
>> "Core Python Programming", Prentice Hall, (c)2007,2001
>> "Python Fundamentals", Prentice Hall, (c)2009
>> ? ?http://corepython.com
>>
>>
>>
>> wesley.j.chun :: wescpy-at-gmail.com
>> python training and technical consulting
>> cyberweb.consulting : silicon valley, ca
>> http://cyberwebconsulting.com
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>



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

"Python Web Development with Django", Addison Wesley, (c) 2009
    http://withdjango.com

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

From zstumgoren at gmail.com  Fri Apr  9 22:42:24 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Fri, 9 Apr 2010 16:42:24 -0400
Subject: [Tutor] accessing Postgres db results by column name
Message-ID: <y2ucadf44511004091342rdceebf93wfb4a4a6ea4626986@mail.gmail.com>

Hi folks,

Does anyone know if there's native support in psycopg2 for accessing rows in
a result-set by column name (rather than by index)?

I'd like to be able to do something like below:

cur.execute('select id, name from mytable')
data = cur.fetchall()
for row in data:
    print row['id'], row['name']

The functionality I have in mind is built into sqlite3:


http://docs.python.org/py3k/library/sqlite3.html#accessing-columns-by-name-instead-of-by-index

And there are a few Python recipes that let you mimic this behavior:


http://code.activestate.com/recipes/81252-using-dtuple-for-flexible-query-result-access/

http://code.activestate.com/recipes/52293-generate-field-name-to-column-number-dictionary/

But I'm wondering if any Postgres db adapters offer native support, similar
to sqlite3? I didn't notice it in a quick scan of the psycopg2 docs (
http://initd.org/psycopg/docs/), but perhaps the functionality is not
documented or someone knows of a different Postgres adapter that has this
capability?

As always, any pointers are greatly appreciated!

Regards,

Serdar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100409/1da836a5/attachment.html>

From zstumgoren at gmail.com  Fri Apr  9 23:08:08 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Fri, 9 Apr 2010 17:08:08 -0400
Subject: [Tutor] accessing Postgres db results by column name
In-Reply-To: <4BBF9538.9050706@gmail.com>
References: <y2ucadf44511004091342rdceebf93wfb4a4a6ea4626986@mail.gmail.com>
	<4BBF9538.9050706@gmail.com>
Message-ID: <h2rcadf44511004091408x1f8ad13fvecf697a282513921@mail.gmail.com>

> >>> class reg(object):
> ...     def __init__(self, cursor, registro):
> ...         for (attr, val) in zip((d[0] for d in cursor.description),
> registro) :
> ...             setattr(self, attr, val)
>
> >>> for row in cursor.fetchall() :
> ...     r = reg(cursor, row)
> ...     print r.CosCPrd, r.CosCAno, r.CosCMes, r.CosCImpSis, r.CosCUsr
>

WOW!!! That works beautifully! Many many thanks!

Regards,

Serdar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100409/58242b96/attachment.html>

From ricaraoz at gmail.com  Sat Apr 10 00:27:27 2010
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Fri, 09 Apr 2010 19:27:27 -0300
Subject: [Tutor] accessing Postgres db results by column name
In-Reply-To: <y2ucadf44511004091342rdceebf93wfb4a4a6ea4626986@mail.gmail.com>
References: <y2ucadf44511004091342rdceebf93wfb4a4a6ea4626986@mail.gmail.com>
Message-ID: <4BBFA9CF.9040209@gmail.com>

Serdar Tumgoren wrote:
> Hi folks,
>
> Does anyone know if there's native support in psycopg2 for accessing
> rows in a result-set by column name (rather than by index)?
>
> I'd like to be able to do something like below:
>
> cur.execute('select id, name from mytable')
> data = cur.fetchall()
> for row in data:
>     print row['id'], row['name']
>
> The functionality I have in mind is built into sqlite3:
>
>   
> http://docs.python.org/py3k/library/sqlite3.html#accessing-columns-by-name-instead-of-by-index
>
> And there are a few Python recipes that let you mimic this behavior:
>
>    
> http://code.activestate.com/recipes/81252-using-dtuple-for-flexible-query-result-access/
>    
> http://code.activestate.com/recipes/52293-generate-field-name-to-column-number-dictionary/
>
> But I'm wondering if any Postgres db adapters offer native support,
> similar to sqlite3? I didn't notice it in a quick scan of the psycopg2
> docs (http://initd.org/psycopg/docs/), but perhaps the functionality
> is not documented or someone knows of a different Postgres adapter
> that has this capability?
>
> As always, any pointers are greatly appreciated!

I do it in mssql, but I think it should be the same with psycopg (sorry
I didn't polish it but I'm finishing my day and no time) :

>>> class reg(object):
...     def __init__(self, cursor, registro):
...         for (attr, val) in zip((d[0] for d in cursor.description),
registro) :
...             setattr(self, attr, val)

>>> for row in cursor.fetchall() :
...     r = reg(cursor, row)
...     print r.CosCPrd, r.CosCAno, r.CosCMes, r.CosCImpSis, r.CosCUsr

HTH



From zstumgoren at gmail.com  Sat Apr 10 03:21:15 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Fri, 9 Apr 2010 21:21:15 -0400
Subject: [Tutor] accessing Postgres db results by column name
In-Reply-To: <4BBF9538.9050706@gmail.com>
References: <y2ucadf44511004091342rdceebf93wfb4a4a6ea4626986@mail.gmail.com>
	<4BBF9538.9050706@gmail.com>
Message-ID: <v2vcadf44511004091821m50e01419sdbcfbd32f3ecb733@mail.gmail.com>

Hey everyone,

Ricardo was nice enough to post his solution as a recipe on ActiveState. For
anyone interested in bookmarking it, here's the link:

http://code.activestate.com/recipes/577186-accessing-cursors-by-field-name/

Serdar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100409/8fdbc7b1/attachment.html>

From zhuchunml at gmail.com  Sat Apr 10 05:13:09 2010
From: zhuchunml at gmail.com (Joson)
Date: Sat, 10 Apr 2010 11:13:09 +0800
Subject: [Tutor]  Linux lib path
Message-ID: <h2zffa452951004092013n4ef1b2a4rd799231bd61fc852@mail.gmail.com>

Hi all,

How to append a path ("/var/myprog/src") to sys.path, but not in the dynamic
way like sys.path.apend(packpath), please?
I use debian os. and I'd tried to set the classpath in /etc/profile (export
CLASSPATH="..."), and the pythonpath too (export PYTHONPATH="..."). I found
it didn't work.

Best regards,

Joson
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100410/ff481597/attachment.html>

From mwalsh at mwalsh.org  Sat Apr 10 07:19:57 2010
From: mwalsh at mwalsh.org (Martin Walsh)
Date: Sat, 10 Apr 2010 00:19:57 -0500
Subject: [Tutor] accessing Postgres db results by column name
In-Reply-To: <v2vcadf44511004091821m50e01419sdbcfbd32f3ecb733@mail.gmail.com>
References: <y2ucadf44511004091342rdceebf93wfb4a4a6ea4626986@mail.gmail.com>	<4BBF9538.9050706@gmail.com>
	<v2vcadf44511004091821m50e01419sdbcfbd32f3ecb733@mail.gmail.com>
Message-ID: <4BC00A7D.7020808@mwalsh.org>

Serdar Tumgoren wrote:
> Hey everyone,
> 
> Ricardo was nice enough to post his solution as a recipe on ActiveState.
> For anyone interested in bookmarking it, here's the link:
> 
> http://code.activestate.com/recipes/577186-accessing-cursors-by-field-name/
> 
> Serdar
> 

I really like Ricardo's solution ... attribute access is a nice touch,
bookmarking it now.

FWIW, it would seem that psycopg2 also has a DictCursor (and
DictConnection).

http://initd.org/psycopg/docs/extras.html

HTH,
Marty



From alan.gauld at btinternet.com  Sat Apr 10 10:46:22 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 10 Apr 2010 09:46:22 +0100
Subject: [Tutor] Linux lib path
References: <h2zffa452951004092013n4ef1b2a4rd799231bd61fc852@mail.gmail.com>
Message-ID: <hppdt1$h4t$1@dough.gmane.org>


"Joson" <zhuchunml at gmail.com> wrote

> I use debian os. and I'd tried to set the classpath in /etc/profile 
> (export
> CLASSPATH="..."), and the pythonpath too (export PYTHONPATH="..."). I 
> found
> it didn't work.

So far as I know CLASSPATH is only used by Java.

PYTHONPATH should work...

Does it work in your local .profile?

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From cfuller at thinkingplanet.net  Sat Apr 10 10:53:22 2010
From: cfuller at thinkingplanet.net (Chris Fuller)
Date: Sat, 10 Apr 2010 03:53:22 -0500
Subject: [Tutor] Linux lib path
In-Reply-To: <h2zffa452951004092013n4ef1b2a4rd799231bd61fc852@mail.gmail.com>
References: <h2zffa452951004092013n4ef1b2a4rd799231bd61fc852@mail.gmail.com>
Message-ID: <201004100353.23109.cfuller@thinkingplanet.net>


I'm using Debian.  Used to be etch, but I did a double dist-upgrade recently.  
So, whatever the current testing release is.  My shell is zsh, but bash should 
work the same.

PYTHONPATH should have worked.  CLASSPATH is for Java.


Here's the documentation link you want: 
http://docs.python.org/install/index.html#inst-search-path
http://docs.python.org/library/site.html


Files that end in ".pth" are read by Python and the contents are added to 
sys.path.


0 % python            
Python 2.5.5 (r255:77872, Feb  1 2010, 19:53:42) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> '/home/cfuller/tmp' in sys.path
False

0 % export PYTHONPATH=/home/cfuller/tmp
0 % python
Python 2.5.5 (r255:77872, Feb  1 2010, 19:53:42) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> '/home/cfuller/tmp' in sys.path
True


What I prefer to do, rather than mucking around with environment variables 
(which isn't reliable, say if its called from a daemon, init script, or maybe 
a non-interactive shell, and probably other esoterica) is to use .pth files.  
These are just a listing of directories for Python to add to sys.path.  A lot 
of packages include some of their own, you should find some in site-packges.  
Used to be you had to put them there to get them loaded, but there is new per-
user support in Python 2.6 and 3k: http://www.python.org/dev/peps/pep-0370/.

0 % export PYTHONPATH=                 
0 % python            
Python 2.5.5 (r255:77872, Feb  1 2010, 19:53:42) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> '/home/cfuller/tmp' in sys.path


0 % mkdir -p ~/.local/lib/python2.6/site-packages
0 % echo /home/cfuller/tmp > ~/.local/lib/python2.6/site-packages/tmp.pth
0 % python2.6
Python 2.6.5 (r265:79063, Mar 18 2010, 23:38:15) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> '/home/cfuller/tmp' in sys.path
True



Cheers


On Friday 09 April 2010, Joson wrote:
> Hi all,
> 
> How to append a path ("/var/myprog/src") to sys.path, but not in the
>  dynamic way like sys.path.apend(packpath), please?
> I use debian os. and I'd tried to set the classpath in /etc/profile (export
> CLASSPATH="..."), and the pythonpath too (export PYTHONPATH="..."). I found
> it didn't work.
> 
> Best regards,
> 
> Joson
> 


From zstumgoren at gmail.com  Sat Apr 10 20:04:22 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Sat, 10 Apr 2010 14:04:22 -0400
Subject: [Tutor] accessing Postgres db results by column name
In-Reply-To: <4BC00A7D.7020808@mwalsh.org>
References: <y2ucadf44511004091342rdceebf93wfb4a4a6ea4626986@mail.gmail.com>
	<4BBF9538.9050706@gmail.com>
	<v2vcadf44511004091821m50e01419sdbcfbd32f3ecb733@mail.gmail.com>
	<4BC00A7D.7020808@mwalsh.org>
Message-ID: <h2ucadf44511004101104l84c687e8td9ad88335d0864d8@mail.gmail.com>

> I really like Ricardo's solution ... attribute access is a nice touch,
> bookmarking it now.
>
> FWIW, it would seem that psycopg2 also has a DictCursor (and
> DictConnection).
>
> http://initd.org/psycopg/docs/extras.html
>
>
> Ah, yes, there it is. Thank you. This list rocks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100410/000581d1/attachment.html>

From crp at cmc.net  Sun Apr 11 13:09:24 2010
From: crp at cmc.net (Ray Parrish)
Date: Sun, 11 Apr 2010 04:09:24 -0700
Subject: [Tutor] Speech recognition, and synthesis
Message-ID: <4BC1ADE4.7030002@cmc.net>

Hello,

Are there any Python libraries that deal with speech recognition, and 
speech synthesis?

If so, where are they available, and are there any open source versions?

Thanks for any help you can be.

Later, Ray Parrish

-- 
Linux dpkg Software Report script set..
http://www.rayslinks.com/LinuxdpkgSoftwareReport.html
Ray's Links, a variety of links to usefull things, and articles by Ray.
http://www.rayslinks.com
Writings of "The" Schizophrenic, what it's like to be a schizo, and other
things, including my poetry.
http://www.writingsoftheschizophrenic.com



From crp at cmc.net  Sun Apr 11 14:30:54 2010
From: crp at cmc.net (Ray Parrish)
Date: Sun, 11 Apr 2010 05:30:54 -0700
Subject: [Tutor] Declaring methods in modules.
Message-ID: <4BC1C0FE.9060203@cmc.net>

Hello,

I am working on some stuff, and I would like to be able to write a 
module which can be imported, and after it's been imported I would like 
to be able to access it's functions as methods.

In other words, if I do the import of module ISPdetector, I want to then 
be able to make calls like the following -

    ipAddress = "123.123.123.123"
    emails = ipAddress.GetEmailAddresses()

where GetEmailAddresses() is defined in module ISPdetector. Do I just 
wite that function in ISPdetector.py as a normally deffed function, or 
does it have to be part of a class within the module?

Thanks for any help you can be.

Later, Ray Parrish

-- 
Linux dpkg Software Report script set..
http://www.rayslinks.com/LinuxdpkgSoftwareReport.html
Ray's Links, a variety of links to usefull things, and articles by Ray.
http://www.rayslinks.com
Writings of "The" Schizophrenic, what it's like to be a schizo, and other
things, including my poetry.
http://www.writingsoftheschizophrenic.com



From patrick.just4fun at gmail.com  Sun Apr 11 14:43:02 2010
From: patrick.just4fun at gmail.com (Patrick Sabin)
Date: Sun, 11 Apr 2010 14:43:02 +0200
Subject: [Tutor] Declaring methods in modules.
In-Reply-To: <4BC1C0FE.9060203@cmc.net>
References: <4BC1C0FE.9060203@cmc.net>
Message-ID: <4BC1C3D6.9080902@gmail.com>

>    ipAddress = "123.123.123.123"
>    emails = ipAddress.GetEmailAddresses()

Not exactly sure, what you want, but maybe something like this?

class mystr(str):
     def GetEmailAddresses(self):
         return [str(self)]

ipAddress = mystr("123.123.123.123")
emails = ipAddress.GetEmailAddresses()

- Patrick

From alan.gauld at btinternet.com  Sun Apr 11 17:58:04 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 11 Apr 2010 16:58:04 +0100
Subject: [Tutor] Declaring methods in modules.
References: <4BC1C0FE.9060203@cmc.net>
Message-ID: <hpsrig$4n0$1@dough.gmane.org>


"Ray Parrish" <crp at cmc.net> wrote

> I am working on some stuff, and I would like to be able to write a module 
> which can be imported, and after it's been imported I would like to be 
> able to access it's functions as methods.

OK, Kind of...

> In other words, if I do the import of module ISPdetector, I want to then 
> be able to make calls like the following -
>
>    ipAddress = "123.123.123.123"
>    emails = ipAddress.GetEmailAddresses()

This won;t work since ipAddress is a string and you can't add methods to a 
builtin type.

But you could define a new special type of string class - an IPstring say - 
and
add methods to that. Put that definition in a module and you code becomes:

import ispdetector

ipAddress = ispdetector.IPstring("123.123.123.123")    # use module to 
access the class
emails = ipAddress.getEmailAddresses()         # use the locally created 
instance to access methods

> where GetEmailAddresses() is defined in module ISPdetector. Do I just 
> wite that function in ISPdetector.py as a normally deffed function, or 
> does it have to be part of a class within the module?

If you want to use it as a method it needs to be in a class. You could just 
write
it as a function that hass a string parameter in which case your code looks 
like:

import ispdetector

ipAddress = "123.123.123.123"
emails = ispdetector.getEmailAddresses(ipAddress)         # use the module 
and pass the strintg

Whether you need a class or not depends on what the restof your code is 
doing
and how data is being handled/stored etc. But we don;t have enough 
information
to be sure. My guess is that a class will be handy because you will likely 
need
several such methods all acting on common data - which is the definition of 
a class!

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From alan.gauld at btinternet.com  Sun Apr 11 18:00:20 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 11 Apr 2010 17:00:20 +0100
Subject: [Tutor] Speech recognition, and synthesis
References: <4BC1ADE4.7030002@cmc.net>
Message-ID: <hpsrmo$58o$1@dough.gmane.org>


"Ray Parrish" <crp at cmc.net> wrote

> Are there any Python libraries that deal with speech recognition, and 
> speech synthesis?

Yes.

> If so, where are they available, 

Google "python speech recognition synthesis"

There are several. I can't recommend any because I've 
never used them.

> and are there any open source versions?

Yes.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From steve at pearwood.info  Sun Apr 11 18:37:15 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 12 Apr 2010 02:37:15 +1000
Subject: [Tutor] Declaring methods in modules.
In-Reply-To: <4BC1C0FE.9060203@cmc.net>
References: <4BC1C0FE.9060203@cmc.net>
Message-ID: <201004120237.15911.steve@pearwood.info>

On Sun, 11 Apr 2010 10:30:54 pm Ray Parrish wrote:
> Hello,
>
> I am working on some stuff, and I would like to be able to write a
> module which can be imported, and after it's been imported I would
> like to be able to access it's functions as methods.
>
> In other words, if I do the import of module ISPdetector, I want to
> then be able to make calls like the following -
>
>     ipAddress = "123.123.123.123"
>     emails = ipAddress.GetEmailAddresses()

Can't be done -- in Python, built-in types like strings can't have new 
methods added to them, and thank goodness for that! The ability to 
monkey-patch builtins is more dangerous than useful. 

But you can subclass builtins, as Alan suggested:

# module ISPdetector
class MyString(string):
    def GetEmailAddresses(self):
        pass

# another module
import ISPdetector
ipAddress = ISPdetector.MyString("123.123.123.123")
emails = ipAddress.GetEmailAddresses()


But that is a strange API design. IP addresses aren't strings, they're 
integers, and although they are commonly written in quad-dotted form as 
a string, you don't want to treat them as strings. For example, 
something like ipAddress.replace('2', 'P') makes no sense.

Also, making GetEmailAddresses a method of an IP address implies that 
address *have* email addresses, which is nonsense. People have email 
addresses. Computer accounts have email addresses. Particular email 
*messages* come from an IP address, but IP addresses don't have email 
addresses. A better name would be ipaddress.find_email_from().

So I would suggest the best API is either to create an IP address class 
(or better still, don't re-invent the wheel, use one of the fine 
existing IP address modules already written), or write functions in the 
module and just call them:

import ISPdetector
ipAddress = "123.123.123.123"
emails = find_email_from(ipAddress)

Remember, in Python methods are just syntactic sugar for function calls. 
obj.method(arg) is just another way of spelling method(obj, arg).



-- 
Steven D'Aprano

From cfuller084 at thinkingplanet.net  Sun Apr 11 18:41:08 2010
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Sun, 11 Apr 2010 11:41:08 -0500
Subject: [Tutor] Declaring methods in modules.
In-Reply-To: <4BC1C0FE.9060203@cmc.net>
References: <4BC1C0FE.9060203@cmc.net>
Message-ID: <201004111141.09107.cfuller084@thinkingplanet.net>


This actually isn't so hard with classes (not instances of the class).  Just 
use setattr().  The first parameter of the function will be the instance, 
called "self" by convention.  This should work with both old and new style 
There's stuff in the new module for adding stuff to instances, but I haven't 
played around with it recently.  A little fiddling around in the interactive 
interpreter should clear up anything you're uncertain about, though.

Cheers


On Sunday 11 April 2010, Ray Parrish wrote:
> Hello,
> 
> I am working on some stuff, and I would like to be able to write a
> module which can be imported, and after it's been imported I would like
> to be able to access it's functions as methods.
> 
> In other words, if I do the import of module ISPdetector, I want to then
> be able to make calls like the following -
> 
>     ipAddress = "123.123.123.123"
>     emails = ipAddress.GetEmailAddresses()
> 
> where GetEmailAddresses() is defined in module ISPdetector. Do I just
> wite that function in ISPdetector.py as a normally deffed function, or
> does it have to be part of a class within the module?
> 
> Thanks for any help you can be.
> 
> Later, Ray Parrish
> 


From cfuller084 at thinkingplanet.net  Sun Apr 11 18:57:50 2010
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Sun, 11 Apr 2010 11:57:50 -0500
Subject: [Tutor] Declaring methods in modules.
In-Reply-To: <4BC1C0FE.9060203@cmc.net>
References: <4BC1C0FE.9060203@cmc.net>
Message-ID: <201004111157.50529.cfuller084@thinkingplanet.net>


Sorry, should have included a concrete example.  Although, as the others have 
said, I'm not sure how it helps with what you (seem) to want to do.

0 % cat bar.py
def the_answer(self):
   return 42
0 % cat foo.py
import bar

class A:
   pass


setattr(A, '__call__', bar.the_answer)

a=A()
print a()

class B(object):
   pass


setattr(B, '__call__', bar.the_answer)

b=B()
print b()

0 % python foo.py 
42
42


Cheers

From jdeltoro1973 at gmail.com  Mon Apr 12 07:12:59 2010
From: jdeltoro1973 at gmail.com (Juan Jose Del Toro)
Date: Mon, 12 Apr 2010 00:12:59 -0500
Subject: [Tutor] Sequences of letter
Message-ID: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>

Dear List;

I have embarked myself into learning Python, I have no programming
background other than some Shell scripts and modifying some programs in
Basic and PHP, but now I want to be able to program.

I have been reading Alan Gauld's Tutor which has been very useful and I've
also been watching Bucky Roberts (thenewboston) videos on youtube (I get
lost there quite often but have also been helpful).

So I started with an exercise to do sequences of letters, I wan to write a
program that could print out the suquence of letters from "aaa" all the way
to "zzz"  like this:
aaa
aab
aac
...
zzx
zzy
zzz

So far this is what I have:
letras =
["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","x","y","z"]
letra1 = 0
letra2 = 0
letra3 = 0
for i in letras:
    for j in letras:
        for k in letras:
            print letras[letra1]+letras[letra2]+letras[letra3]
            letra3=letra3+1
    letra2=letra2+1
letra1=letra1+1

It goes all the way to aaz and then it gives me this error
Traceback (most recent call last):
 File "/home/administrador/programacion/python/letras2.py", line 8, in
<module>
print letras[letra1]+letras[letra2]+letras[letra3]
IndexError: list index out of range
Script terminated.

Am I even in the right path?
I guess I should look over creating a function or something like that
because when I run it I can't even use my computer no memory left

-- 
?Saludos! / Greetings!
Juan Jos? Del Toro M.
jdeltoro1973 at gmail.com
Guadalajara, Jalisco MEXICO
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100412/7b4d5479/attachment.html>

From metolone+gmane at gmail.com  Mon Apr 12 08:19:54 2010
From: metolone+gmane at gmail.com (Mark Tolonen)
Date: Sun, 11 Apr 2010 23:19:54 -0700
Subject: [Tutor] Sequences of letter
References: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>
Message-ID: <hpue23$95s$1@dough.gmane.org>


"Juan Jose Del Toro" <jdeltoro1973 at gmail.com> wrote in message 
news:s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16 at mail.gmail.com...
Dear List;

I have embarked myself into learning Python, I have no programming
background other than some Shell scripts and modifying some programs in
Basic and PHP, but now I want to be able to program.

I have been reading Alan Gauld's Tutor which has been very useful and I've
also been watching Bucky Roberts (thenewboston) videos on youtube (I get
lost there quite often but have also been helpful).

So I started with an exercise to do sequences of letters, I wan to write a
program that could print out the suquence of letters from "aaa" all the way
to "zzz"  like this:
aaa
aab
aac
...
zzx
zzy
zzz

So far this is what I have:
letras =
["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","x","y","z"]
letra1 = 0
letra2 = 0
letra3 = 0
for i in letras:
    for j in letras:
        for k in letras:
            print letras[letra1]+letras[letra2]+letras[letra3]
            letra3=letra3+1
    letra2=letra2+1
letra1=letra1+1

It goes all the way to aaz and then it gives me this error
Traceback (most recent call last):
 File "/home/administrador/programacion/python/letras2.py", line 8, in
<module>
print letras[letra1]+letras[letra2]+letras[letra3]
IndexError: list index out of range
Script terminated.

Am I even in the right path?
I guess I should look over creating a function or something like that
because when I run it I can't even use my computer no memory left

-- 
?Saludos! / Greetings!
Juan Jos? Del Toro M.
jdeltoro1973 at gmail.com
Guadalajara, Jalisco MEXICO



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


> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

It's easier than you think.  Here's a hint:

>>> for i in 'abcd':
...  print i
...
a
b
c
d

What are the values of i,j,k in your loop?

-Mark



From patrick.just4fun at gmail.com  Mon Apr 12 08:38:36 2010
From: patrick.just4fun at gmail.com (Patrick Sabin)
Date: Mon, 12 Apr 2010 08:38:36 +0200
Subject: [Tutor] Sequences of letter
In-Reply-To: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>
References: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>
Message-ID: <4BC2BFEC.1030003@gmail.com>

> So far this is what I have:
> letras = 
> ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","x","y","z"]
> letra1 = 0
> letra2 = 0
> letra3 = 0
> for i in letras:
>     for j in letras:
>         for k in letras:
>             print letras[letra1]+letras[letra2]+letras[letra3]
>             letra3=letra3+1
>     letra2=letra2+1        
> letra1=letra1+1
> 
> It goes all the way to aaz and then it gives me this error
> Traceback (most recent call last):
>  File "/home/administrador/programacion/python/letras2.py", line 8, in 
> <module>
> print letras[letra1]+letras[letra2]+letras[letra3]
> IndexError: list index out of range

You should consider resetting the letra-variables before each loop (not 
before every loop).

- Patrick

From stefan_ml at behnel.de  Mon Apr 12 09:19:18 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Mon, 12 Apr 2010 09:19:18 +0200
Subject: [Tutor] Sequences of letter
In-Reply-To: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>
References: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>
Message-ID: <hpuhhm$i50$1@dough.gmane.org>

Juan Jose Del Toro, 12.04.2010 07:12:
> I wan to write a
> program that could print out the suquence of letters from "aaa" all the way
> to "zzz"  like this:
> aaa
> aab
> aac
> ...
> zzx
> zzy
> zzz
>
> So far this is what I have:
> letras =
> ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","x","y","z"]

See the 'string' module. Also, note that you do not need a list here, you 
can iterate over a simple string value as well.


> letra1 = 0
> letra2 = 0
> letra3 = 0
> for i in letras:
>      for j in letras:
>          for k in letras:
>              print letras[letra1]+letras[letra2]+letras[letra3]
>              letra3=letra3+1
>      letra2=letra2+1
> letra1=letra1+1

Note that the above is highly redundant. Try printing the values of i, j 
and k during the loop, you will see why.

Stefan


From alan.gauld at btinternet.com  Mon Apr 12 09:25:25 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 12 Apr 2010 08:25:25 +0100
Subject: [Tutor] Sequences of letter
References: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>
Message-ID: <hpuhta$jqc$1@dough.gmane.org>

"Juan Jose Del Toro" <jdeltoro1973 at gmail.com> wrote
> So far this is what I have:
> letras =
> ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","x","y","z"]

Because a string is a sequence of letters you could have saved
some typing by just doing:

letras = "abcdefghijklmnopqrstuvwxyz"


> letra1 = 0
> letra2 = 0
> letra3 = 0

You don't really need these. Remember that a 'for' loop in Python is
really a 'foreach' loop. It will pick out the items in the sequence
itself, you don't need to use an index in most cases.

> for i in letras:
>     for j in letras:
>         for k in letras:
>             print letras[letra1]+letras[letra2]+letras[letra3]

So this becomes:
   print i+j+k

>             letra3=letra3+1

However if you do insist on using indexes you will need to
reset the indexes to 0 at the end of each associated loop.

>     letra2=letra2+1
       letra3 = 0

> letra1=letra1+1
   letra2, letra3=0,0

> It goes all the way to aaz and then it gives me this error
> print letras[letra1]+letras[letra2]+letras[letra3]
> IndexError: list index out of range

Thats because you didn't reset the index to zero so letra3
was already at the end of letras and you tried to add one to
it again pushing it over the edge. This is the reason you
are best to use for loops without indexes, they handle all
that stuff for you.

> Am I even in the right path?

The basic idea is right, you just forgot to reset the
inner index. When debugging this kind of problem
try adding a print line to priont out the variables.
That might have helped you see what was going wrong.

But inthis case it would be better to just forget the indexes
and use the loop variables, i,j,k directly.

> I guess I should look over creating a function or something like that
> because when I run it I can't even use my computer no memory left

Thats shouldn't be a problem, it does not use that much menory!
Unless you have a very small (and old) computer :-)

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From denis.spir at gmail.com  Mon Apr 12 10:10:16 2010
From: denis.spir at gmail.com (spir =?UTF-8?B?4pij?=)
Date: Mon, 12 Apr 2010 10:10:16 +0200
Subject: [Tutor] Sequences of letter
In-Reply-To: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>
References: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>
Message-ID: <20100412101016.7e472e70@o>

On Mon, 12 Apr 2010 00:12:59 -0500
Juan Jose Del Toro <jdeltoro1973 at gmail.com> wrote:

> Dear List;
> 
> I have embarked myself into learning Python, I have no programming
> background other than some Shell scripts and modifying some programs in
> Basic and PHP, but now I want to be able to program.
> 
> I have been reading Alan Gauld's Tutor which has been very useful and I've
> also been watching Bucky Roberts (thenewboston) videos on youtube (I get
> lost there quite often but have also been helpful).
> 
> So I started with an exercise to do sequences of letters, I wan to write a
> program that could print out the suquence of letters from "aaa" all the way
> to "zzz"  like this:
> aaa
> aab
> aac
> ...
> zzx
> zzy
> zzz
> 
> So far this is what I have:
> letras =
> ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","x","y","z"]

cinqLetras = "abcde"
# No need to enumerate manually to get a list of letters:
print list(cinqLetras)
# ==> ['a', 'b', 'c', 'd', 'e']

> letra1 = 0
> letra2 = 0
> letra3 = 0
> for i in letras:
>     for j in letras:
>         for k in letras:
>             print letras[letra1]+letras[letra2]+letras[letra3]
>             letra3=letra3+1
>     letra2=letra2+1
> letra1=letra1+1

The items are *letters*, not indexes. Should be called l1,l2,l3 and "glued" directly.

> It goes all the way to aaz and then it gives me this error
> Traceback (most recent call last):
>  File "/home/administrador/programacion/python/letras2.py", line 8, in
> <module>
> print letras[letra1]+letras[letra2]+letras[letra3]
> IndexError: list index out of range
> Script terminated.
> 
> Am I even in the right path?
> I guess I should look over creating a function or something like that
> because when I run it I can't even use my computer no memory left


No need to use a list to traverse the string letter per letter:

def trioDeLetras(letras):
   for l1 in letras:
      for l2 in letras:
         for l3 in letras:
            # (the comma avoid one line per letter trio)
            print l1+l2+l3,

trioDeLetras(cinqLetras)
# ==>
'''\
aaa aab aac aad aae aba abb abc abd abe aca acb acc acd ace ada adb adc add ade aea aeb aec aed aee baa bab bac
bad bae bba bbb bbc bbd bbe bca bcb bcc bcd bce bda bdb bdc bdd bde bea beb bec bed bee caa cab cac cad cae cba
cbb cbc cbd cbe cca ccb ccc ccd cce cda cdb cdc cdd cde cea ceb cec ced cee daa dab dac dad dae dba dbb dbc dbd
dbe dca dcb dcc dcd dce dda ddb ddc ddd dde dea deb dec ded dee eaa eab eac ead eae eba ebb ebc ebd ebe eca ecb
ecc ecd ece eda edb edc edd ede eea eeb eec eed eee
''' 

Denis
________________________________

vit esse estrany ?

spir.wikidot.com

From yashwinkanchan at gmail.com  Mon Apr 12 15:48:35 2010
From: yashwinkanchan at gmail.com (Yashwin Kanchan)
Date: Mon, 12 Apr 2010 14:48:35 +0100
Subject: [Tutor] Sequences of letter
In-Reply-To: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>
References: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>
Message-ID: <m2ueae1591c1004120648r8ade561akb6a059cd1ec5cc16@mail.gmail.com>

Hi Juan

Hope you have got the correct picture now...

I just wanted to show you another way of doing the above thing in just 4
lines.

for i in range(65,91):
for j in range(65,91):
for k in range(65,91):
print chr(i)+chr(j)+chr(k),


On 12 April 2010 06:12, Juan Jose Del Toro <jdeltoro1973 at gmail.com> wrote:

> Dear List;
>
> I have embarked myself into learning Python, I have no programming
> background other than some Shell scripts and modifying some programs in
> Basic and PHP, but now I want to be able to program.
>
> I have been reading Alan Gauld's Tutor which has been very useful and I've
> also been watching Bucky Roberts (thenewboston) videos on youtube (I get
> lost there quite often but have also been helpful).
>
> So I started with an exercise to do sequences of letters, I wan to write a
> program that could print out the suquence of letters from "aaa" all the way
> to "zzz"  like this:
> aaa
> aab
> aac
> ...
> zzx
> zzy
> zzz
>
> So far this is what I have:
> letras =
> ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","x","y","z"]
> letra1 = 0
> letra2 = 0
> letra3 = 0
> for i in letras:
>     for j in letras:
>         for k in letras:
>             print letras[letra1]+letras[letra2]+letras[letra3]
>             letra3=letra3+1
>     letra2=letra2+1
> letra1=letra1+1
>
> It goes all the way to aaz and then it gives me this error
> Traceback (most recent call last):
>  File "/home/administrador/programacion/python/letras2.py", line 8, in
> <module>
> print letras[letra1]+letras[letra2]+letras[letra3]
> IndexError: list index out of range
> Script terminated.
>
> Am I even in the right path?
> I guess I should look over creating a function or something like that
> because when I run it I can't even use my computer no memory left
>
> --
> ?Saludos! / Greetings!
> Juan Jos? Del Toro M.
> jdeltoro1973 at gmail.com
> Guadalajara, Jalisco MEXICO
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100412/e6e82af8/attachment.html>

From dotancohen at gmail.com  Mon Apr 12 16:11:30 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Mon, 12 Apr 2010 17:11:30 +0300
Subject: [Tutor] Move all files to top-level directory
Message-ID: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>

I use this one-liner for moving photos nested a single folder deep
into the top-level folder:
find * -name "*.jpg" | awk  -F/ '{print "mv "$0,$1"-"$2}' | sh

I would like to expand this into an application that handles arbitrary
nesting and smart rename, so I figure that Python is the language that
I need. I have googled file handling in Python but I simply cannot get
something to replicate the current functionality of that lovely
one-liner. What fine manual should I be reading? I am not asking for
code, rather just a link to the right documentation.

Thanks.

-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From zstumgoren at gmail.com  Mon Apr 12 16:23:37 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Mon, 12 Apr 2010 10:23:37 -0400
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
Message-ID: <y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>

 What fine manual should I be reading? I am not asking for

> code, rather just a link to the right documentation.
>

You'll definitely want to explore the os module, part of Python's built-in
standard library.

http://docs.python.org/library/os.html
http://docs.python.org/library/os.html#files-and-directories

There are a bunch of recipes on ActiveState and elsewhere online that can
demonstrate how the os methods are used to work with files and directories.
Some googling for the various method names (eg. os.mkdir ) should turn them
up.

Best of luck,

Serdar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100412/4ea80c5b/attachment.html>

From dotancohen at gmail.com  Mon Apr 12 17:10:42 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Mon, 12 Apr 2010 18:10:42 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>
Message-ID: <i2k880dece01004120810m2cbd35ddy63e09b8008fde7d5@mail.gmail.com>

On 12 April 2010 17:23, Serdar Tumgoren <zstumgoren at gmail.com> wrote:
> ?What fine manual should I be reading? I am not asking for
>>
>> code, rather just a link to the right documentation.
>
> You'll definitely want to explore the os module, part of Python's built-in
> standard library.
>
> http://docs.python.org/library/os.html
> http://docs.python.org/library/os.html#files-and-directories
>

Thanks, going through there now...

I found these relevant functions:
os.listdir
os.rename
os.removedirs (this looks great, as it is recursive and nondestructive)


> There are a bunch of recipes on ActiveState and elsewhere online that can
> demonstrate how the os methods are used to work with files and directories.
> Some googling for the various method names (eg. os.mkdir ) should turn them
> up.
>

ActiveState looks like a great resource. Thanks!

-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

Please CC me if you want to be sure that I read your message. I do not
read all list mail.

From steve at pearwood.info  Mon Apr 12 18:06:47 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 13 Apr 2010 02:06:47 +1000
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
Message-ID: <201004130206.48216.steve@pearwood.info>

On Tue, 13 Apr 2010 12:11:30 am Dotan Cohen wrote:
> I use this one-liner for moving photos nested a single folder deep
> into the top-level folder:
> find * -name "*.jpg" | awk  -F/ '{print "mv "$0,$1"-"$2}' | sh
>
> I would like to expand this into an application that handles
> arbitrary nesting and smart rename, so I figure that Python is the
> language that I need. I have googled file handling in Python but I
> simply cannot get something to replicate the current functionality of
> that lovely one-liner. 

"Lovely"??? What on earth does it do? It's worse than Perl code!!!
*half a wink*


> What fine manual should I be reading? I am not 
> asking for code, rather just a link to the right documentation.

See the shell utilities module:

import shutil




-- 
Steven D'Aprano

From dotancohen at gmail.com  Mon Apr 12 18:13:59 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Mon, 12 Apr 2010 19:13:59 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <201004130206.48216.steve@pearwood.info>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<201004130206.48216.steve@pearwood.info>
Message-ID: <s2j880dece01004120913n3cc82c97p5ff2586aac55acbf@mail.gmail.com>

> "Lovely"??? What on earth does it do? It's worse than Perl code!!!
> *half a wink*
>

Like a good wife, it does what I need even if it is not pretty on the
eyes. _That_ is lovely!
(I can get away with that, I'm married to a redhead.)


> See the shell utilities module:
>
> import shutil
>

It overwrites files. I am playing with os.rename instead as the two
directories will always be on the same file system.

One thing that I am stuck with is os.walk for getting all the
subfolders' files. Now that at least I have discovered the _names_ of
the functions that I need I can google my out of this! I will write
back when I have a working solution, for the sake of the archives.
Thanks!


-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From dotancohen at gmail.com  Mon Apr 12 18:28:00 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Mon, 12 Apr 2010 19:28:00 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>
Message-ID: <j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com>

I'm really stuck here. I need move all files in subdirectories of cwd
to cwd. So that, for instance, if we are in ~/photos then this file:
~/photos/a/b/file with space.jpg
...will move to this location:
~/photos/file with space.jpg

This is what I've come up with:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
currentDir = os.getcwd()

files = os.walk(currentDir)
for f in files:
    os.rename(f, currentDir)


However, it fails like this:
$ ./moveUp.py
Traceback (most recent call last):
  File "./moveUp.py", line 8, in <module>
    os.rename(f, currentDir)
TypeError: coercing to Unicode: need string or buffer, tuple found

I can't google my way out of this one! The filenames on my test setup
are currently ascii, but this does need to be unicode-compatible as
the real filenames will have unicode non-ascii characters and even
spaces in the filenames!

What should I be reading now?

Thanks!


-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From davea at ieee.org  Mon Apr 12 18:46:39 2010
From: davea at ieee.org (Dave Angel)
Date: Mon, 12 Apr 2010 12:46:39 -0400
Subject: [Tutor] Sequences of letter
In-Reply-To: <m2ueae1591c1004120648r8ade561akb6a059cd1ec5cc16@mail.gmail.com>
References: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>
	<m2ueae1591c1004120648r8ade561akb6a059cd1ec5cc16@mail.gmail.com>
Message-ID: <4BC34E6F.5090007@ieee.org>

Or more readably:

from string import lowercase as letters
for c1 in letters:
     for c2 in letters:
         for c3 in letters:
                print c1+c2+c3


Yashwin Kanchan wrote:
> Hi Juan
>
> Hope you have got the correct picture now...
>
> I just wanted to show you another way of doing the above thing in just 4
> lines.
>
> for i in range(65,91):
> for j in range(65,91):
> for k in range(65,91):
> print chr(i)+chr(j)+chr(k),
>
>
> On 12 April 2010 06:12, Juan Jose Del Toro <jdeltoro1973 at gmail.com> wrote:
>
>   
>> Dear List;
>>
>> I have embarked myself into learning Python, I have no programming
>> background other than some Shell scripts and modifying some programs in
>> Basic and PHP, but now I want to be able to program.
>>
>> I have been reading Alan Gauld's Tutor which has been very useful and I've
>> also been watching Bucky Roberts (thenewboston) videos on youtube (I get
>> lost there quite often but have also been helpful).
>>
>> So I started with an exercise to do sequences of letters, I wan to write a
>> program that could print out the suquence of letters from "aaa" all the way
>> to "zzz"  like this:
>> aaa
>> aab
>> aac
>> ...
>> zzx
>> zzy
>> zzz
>>
>> So far this is what I have:
>> letras =
>> ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","x","y","z"]
>> letra1 = 0
>> letra2 = 0
>> letra3 = 0
>> for i in letras:
>>     for j in letras:
>>         for k in letras:
>>             print letras[letra1]+letras[letra2]+letras[letra3]
>>             letra3=letra3+1
>>     letra2=letra2+1
>> letra1=letra1+1
>>
>> It goes all the way to aaz and then it gives me this error
>> Traceback (most recent call last):
>>  File "/home/administrador/programacion/python/letras2.py", line 8, in
>> <module>
>> print letras[letra1]+letras[letra2]+letras[letra3]
>> IndexError: list index out of range
>> Script terminated.
>>
>> Am I even in the right path?
>> I guess I should look over creating a function or something like that
>> because when I run it I can't even use my computer no memory left
>>
>> --
>> ?Saludos! / Greetings!
>> Juan Jos? Del Toro M.
>> jdeltoro1973 at gmail.com
>> Guadalajara, Jalisco MEXICO
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>     
>
>   

From sander.sweers at gmail.com  Mon Apr 12 19:12:32 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 12 Apr 2010 19:12:32 +0200
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>
	<j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com>
Message-ID: <t2hb65fbb131004121012jcafb2ebcjd34820fdbc2b2c6b@mail.gmail.com>

On 12 April 2010 18:28, Dotan Cohen <dotancohen at gmail.com> wrote:
> However, it fails like this:
> $ ./moveUp.py
> Traceback (most recent call last):
> ?File "./moveUp.py", line 8, in <module>
> ? ?os.rename(f, currentDir)
> TypeError: coercing to Unicode: need string or buffer, tuple found

os.rename needs the oldname and the new name of the file. os.walk
returns a tuple with 3 values and it errors out.

Also os.getcwd returns the working dir so if you run it in the wrong
folder you will end up with a mess. In idle on my windows machine at
work this is what is gives me.

>>> os.getcwd()
'C:\\Python26'

So it is better to give the program the path you want it to look in
rather then relying on os.getcwd().

os.walk returns you a tuple with the following values:
(the root folder, the folders in the root, the files in the root folder).

You can use tuple unpacking to split each one in separate values for
your loop. Like:

for root, folder, files in os.walk('your path):
   #do stuff

It might be wise to only have this module print what it would do
instead of doing the actual move/rename so you can work out the bugs
first before it destroys your data.

Hope this helps.
Greets
Sander

From steve at pearwood.info  Mon Apr 12 19:22:40 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 13 Apr 2010 03:22:40 +1000
Subject: [Tutor] Sequences of letter
In-Reply-To: <4BC34E6F.5090007@ieee.org>
References: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com>
	<m2ueae1591c1004120648r8ade561akb6a059cd1ec5cc16@mail.gmail.com>
	<4BC34E6F.5090007@ieee.org>
Message-ID: <201004130322.40918.steve@pearwood.info>

On Tue, 13 Apr 2010 02:46:39 am Dave Angel wrote:
> Or more readably:
>
> from string import lowercase as letters
> for c1 in letters:
>      for c2 in letters:
>          for c3 in letters:
>                 print c1+c2+c3


Here's another solution, for those using Python 2.6 or better:


>>> import itertools
>>> for x in itertools.product('abc', 'abc', 'abc'):
...     print ''.join(x)
...
aaa
aab
aac
aba
abb
abc
[many more lines...]
ccc


If you don't like the repeated 'abc' in the call to product(), it can be 
written as itertools.product(*['ab']*3) instead.





-- 
Steven D'Aprano

From dotancohen at gmail.com  Mon Apr 12 19:25:40 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Mon, 12 Apr 2010 20:25:40 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <t2hb65fbb131004121012jcafb2ebcjd34820fdbc2b2c6b@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>
	<j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com>
	<t2hb65fbb131004121012jcafb2ebcjd34820fdbc2b2c6b@mail.gmail.com>
Message-ID: <i2v880dece01004121025uee0e3493x9aca6f452290732c@mail.gmail.com>

On 12 April 2010 20:12, Sander Sweers <sander.sweers at gmail.com> wrote:
> On 12 April 2010 18:28, Dotan Cohen <dotancohen at gmail.com> wrote:
>> However, it fails like this:
>> $ ./moveUp.py
>> Traceback (most recent call last):
>> ?File "./moveUp.py", line 8, in <module>
>> ? ?os.rename(f, currentDir)
>> TypeError: coercing to Unicode: need string or buffer, tuple found
>
> os.rename needs the oldname and the new name of the file. os.walk
> returns a tuple with 3 values and it errors out.
>

I see, thanks. So I was sending it four values apparently. I did not
understand the error message.

> Also os.getcwd returns the working dir so if you run it in the wrong
> folder you will end up with a mess. In idle on my windows machine at
> work this is what is gives me.
>
>>>> os.getcwd()
> 'C:\\Python26'
>
> So it is better to give the program the path you want it to look in
> rather then relying on os.getcwd().
>

I intend to use this in a Dolphin (KDE file manager) service menu
only. But I will try to be careful about that in the future. Running
the script in $HOME might be interesting!

Actually, I will add a check that cwd != $HOME || $HOME/.bin as those
are the only likely places it might run by accident. Or maybe I'll
wrap it in Qt and add a confirm button.


> os.walk returns you a tuple with the following values:
> (the root folder, the folders in the root, the files in the root folder).
>
> You can use tuple unpacking to split each one in separate values for
> your loop. Like:
>
> for root, folder, files in os.walk('your path):
> ? #do stuff
>

I did see that while googling, but did not understand it. Nice!


> It might be wise to only have this module print what it would do
> instead of doing the actual move/rename so you can work out the bugs
> first before it destroys your data.
>

I am testing on fake data, naturally.

Thanks!


-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

Please CC me if you want to be sure that I read your message. I do not
read all list mail.

From dotancohen at gmail.com  Mon Apr 12 20:21:09 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Mon, 12 Apr 2010 21:21:09 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <i2v880dece01004121025uee0e3493x9aca6f452290732c@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>
	<j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com>
	<t2hb65fbb131004121012jcafb2ebcjd34820fdbc2b2c6b@mail.gmail.com>
	<i2v880dece01004121025uee0e3493x9aca6f452290732c@mail.gmail.com>
Message-ID: <t2o880dece01004121121seaa71310rc07be3295a656a38@mail.gmail.com>

All right, I have gotten quite a bit closer, but Python is now
complaining about the directory not being empty:

?dcl:test$ cat moveUp.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
currentDir = os.getcwd()

filesList = os.walk(currentDir)
for root, folder, file in filesList:
    for f in file:
        toMove = root + "/" + f
        #print toMove
        os.rename(toMove, currentDir)

?dcl:test$ ./moveUp.py
Traceback (most recent call last):
  File "./moveUp.py", line 11, in <module>
    os.rename(toMove, currentDir)
OSError: [Errno 39] Directory not empty


I am aware that the directory is not empty, nor should it be! How can
I override this?

Thanks!

-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From waynejwerner at gmail.com  Mon Apr 12 20:53:27 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Mon, 12 Apr 2010 13:53:27 -0500
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <t2o880dece01004121121seaa71310rc07be3295a656a38@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com> 
	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com> 
	<j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com> 
	<t2hb65fbb131004121012jcafb2ebcjd34820fdbc2b2c6b@mail.gmail.com> 
	<i2v880dece01004121025uee0e3493x9aca6f452290732c@mail.gmail.com> 
	<t2o880dece01004121121seaa71310rc07be3295a656a38@mail.gmail.com>
Message-ID: <n2i333efb451004121153q3232adc1xf943b47ac0968630@mail.gmail.com>

On Mon, Apr 12, 2010 at 1:21 PM, Dotan Cohen <dotancohen at gmail.com> wrote:

> All right, I have gotten quite a bit closer, but Python is now
> complaining about the directory not being empty:
>
> ?dcl:test$ cat moveUp.py
> #!/usr/bin/python
> # -*- coding: utf-8 -*-
> import os
> currentDir = os.getcwd()
>
> filesList = os.walk(currentDir)
> for root, folder, file in filesList:
>    for f in file:
>        toMove = root + "/" + f
>        #print toMove
>        os.rename(toMove, currentDir)
>
> ?dcl:test$ ./moveUp.py
> Traceback (most recent call last):
>   File "./moveUp.py", line 11, in <module>
>    os.rename(toMove, currentDir)
> OSError: [Errno 39] Directory not empty
>
>
> I am aware that the directory is not empty, nor should it be! How can
> I override this?
>

from the docs:
os.rename(*src*, *dst*)?
<http://docs.python.org/library/os.html#os.rename>Rename
the file or directory *src* to *dst*. If *dst* is a directory,
OSError<http://docs.python.org/library/exceptions.html#exceptions.OSError>will
be raised. On Unix, if
*dst* exists and is a file, it will be replaced silently if the user has
permission. The operation may fail on some Unix flavors if *src* and
*dst*are on different filesystems. If successful, the renaming will be
an atomic
operation (this is a POSIX requirement). On Windows, if *dst* already
exists, OSError<http://docs.python.org/library/exceptions.html#exceptions.OSError>will
be raised even if it is a file; there may be no way to implement an
atomic rename when *dst* names an existing file. Availability: Unix,
Windows.It seems what you wan to do is os.rename(toMove, currentDir+f)

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100412/54734416/attachment.html>

From davea at ieee.org  Mon Apr 12 21:46:45 2010
From: davea at ieee.org (Dave Angel)
Date: Mon, 12 Apr 2010 15:46:45 -0400
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <i2v880dece01004121025uee0e3493x9aca6f452290732c@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>	<j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com>	<t2hb65fbb131004121012jcafb2ebcjd34820fdbc2b2c6b@mail.gmail.com>
	<i2v880dece01004121025uee0e3493x9aca6f452290732c@mail.gmail.com>
Message-ID: <4BC378A5.9060701@ieee.org>

Dotan Cohen wrote:
> On 12 April 2010 20:12, Sander Sweers <sander.sweers at gmail.com> wrote:
>   
>> On 12 April 2010 18:28, Dotan Cohen <dotancohen at gmail.com> wrote:
>>     
>>> However, it fails like this:
>>> $ ./moveUp.py
>>> Traceback (most recent call last):
>>>  File "./moveUp.py", line 8, in <module>
>>>    os.rename(f, currentDir)
>>> TypeError: coercing to Unicode: need string or buffer, tuple found
>>>       
>> os.rename needs the oldname and the new name of the file. os.walk
>> returns a tuple with 3 values and it errors out.
>>
>>     
>
> I see, thanks. So I was sending it four values apparently. I did not
> understand the error message.
>
>   
No, you're sending it two values:  a tuple, and a string.  It wants two 
strings.  Thus the error. If you had sent it four values, you'd have 
gotten a different error.
> <snip>
> Actually, I will add a check that cwd !=HOME || $HOME/.bin as those
> are the only likely places it might run by accident. Or maybe I'll
> wrap it in Qt and add a confirm button.
>
>
>   
>> os.walk returns you a tuple with the following values:
>> (the root folder, the folders in the root, the files in the root folder).
>>
>> You can use tuple unpacking to split each one in separate values for
>> your loop. Like:
>>
>> for root, folder, files in os.walk('your path):
>>   #do stuff
>>
>>     
>
> I did see that while googling, but did not understand it. Nice!
>
>
>   
Judging from your next message, you still don't understand it.
>> It might be wise to only have this module print what it would do
>> instead of doing the actual move/rename so you can work out the bugs
>> first before it destroys your data.
>>
>>     
>
> I am testing on fake data, naturally.
>
>   
Is your entire file system fake?  Perhaps you're running in a VM, and 
don't mind trashing it.

While debugging, you're much better off using prints than really moving 
files around.  You might be amazed how much damage a couple of minor 
bugs could cause.

DaveA


From zstumgoren at gmail.com  Mon Apr 12 22:01:04 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Mon, 12 Apr 2010 16:01:04 -0400
Subject: [Tutor] accessing Postgres db results by column name
In-Reply-To: <h2ucadf44511004101104l84c687e8td9ad88335d0864d8@mail.gmail.com>
References: <y2ucadf44511004091342rdceebf93wfb4a4a6ea4626986@mail.gmail.com>
	<4BBF9538.9050706@gmail.com>
	<v2vcadf44511004091821m50e01419sdbcfbd32f3ecb733@mail.gmail.com>
	<4BC00A7D.7020808@mwalsh.org>
	<h2ucadf44511004101104l84c687e8td9ad88335d0864d8@mail.gmail.com>
Message-ID: <l2scadf44511004121301w85b8055ana65d42cc097485b3@mail.gmail.com>

Hey folks,

Wanted to send along one more update about this topic. Steve Orr pointed out
in a comment on Ricardo's new recipe that there's yet another way to get
named attribute access to cursor results.

The secret sauce is namedtuple, "high performance" collection type.  This
appears to be the "canonical" approach these days:

http://code.activestate.com/recipes/500261/

The Python Docs have a nice little example of this approach, using both the
csv and sqlite3 modules:

http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields

And you can check out Steve's comment at the bottom of Ricardo's recipe:

http://code.activestate.com/recipes/577186-accessing-cursors-by-field-name/

Regards,

Serdar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100412/0132fc3d/attachment.html>

From zstumgoren at gmail.com  Mon Apr 12 22:04:39 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Mon, 12 Apr 2010 16:04:39 -0400
Subject: [Tutor] accessing Postgres db results by column name
In-Reply-To: <l2scadf44511004121301w85b8055ana65d42cc097485b3@mail.gmail.com>
References: <y2ucadf44511004091342rdceebf93wfb4a4a6ea4626986@mail.gmail.com>
	<4BBF9538.9050706@gmail.com>
	<v2vcadf44511004091821m50e01419sdbcfbd32f3ecb733@mail.gmail.com>
	<4BC00A7D.7020808@mwalsh.org>
	<h2ucadf44511004101104l84c687e8td9ad88335d0864d8@mail.gmail.com>
	<l2scadf44511004121301w85b8055ana65d42cc097485b3@mail.gmail.com>
Message-ID: <o2rcadf44511004121304h21eb2133k86ec4ea934d687a9@mail.gmail.com>

> Wanted to send along one more update about this topic. Steve Orr pointed
> out in a comment on Ricardo's new recipe that there's yet another way to get
> named attribute access to cursor results.
>

I should add the disclaimer that namedtuple is only available in Python 2.6+
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100412/590a2476/attachment.html>

From davea at ieee.org  Mon Apr 12 22:13:24 2010
From: davea at ieee.org (Dave Angel)
Date: Mon, 12 Apr 2010 16:13:24 -0400
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <t2o880dece01004121121seaa71310rc07be3295a656a38@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>	<j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com>	<t2hb65fbb131004121012jcafb2ebcjd34820fdbc2b2c6b@mail.gmail.com>	<i2v880dece01004121025uee0e3493x9aca6f452290732c@mail.gmail.com>
	<t2o880dece01004121121seaa71310rc07be3295a656a38@mail.gmail.com>
Message-ID: <4BC37EE4.4070304@ieee.org>



Dotan Cohen wrote:
> All right, I have gotten quite a bit closer, but Python is now
> complaining about the directory not being empty:
>
> ?dcl:test$ cat moveUp.py
> #!/usr/bin/python
> # -*- coding: utf-8 -*-
> import os
> currentDir =s.getcwd()
>
> filesList =s.walk(currentDir)
> for root, folder, file in filesList:
>   
Why is the print below commented out?
>     for f in file:
>         toMove =oot + "/" + f
>         #print toMove
>         os.rename(toMove, currentDir)
>
> ?dcl:test$ ./moveUp.py
> Traceback (most recent call last):
>   File "./moveUp.py", line 11, in <module>
>     os.rename(toMove, currentDir)
> OSError: [Errno 39] Directory not empty
>
>
> I am aware that the directory is not empty, nor should it be! How can
> I override this?
>
> Thanks!
>
>   
Have you looked at the value of "currentDir" ? Is it in a form that's 
acceptible to os.rename() ? And how about toMove? Perhaps it has two 
slashes in a row in it. When combining directory paths, it's generally 
safer to use

os.path.join()

Next, you make no check whether "root" is the same as "currentDir". So 
if there are any files already in the top-level directory, you're trying 
to rename them to themselves.

I would also point out that your variable names are very confusing. 
"file" is a list of files, so why isn't it plural? Likewise "folders."

DaveA



From sander.sweers at gmail.com  Mon Apr 12 23:27:15 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 12 Apr 2010 23:27:15 +0200
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <4BC37EE4.4070304@ieee.org>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>
	<j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com>
	<t2hb65fbb131004121012jcafb2ebcjd34820fdbc2b2c6b@mail.gmail.com>
	<i2v880dece01004121025uee0e3493x9aca6f452290732c@mail.gmail.com>
	<t2o880dece01004121121seaa71310rc07be3295a656a38@mail.gmail.com>
	<4BC37EE4.4070304@ieee.org>
Message-ID: <v2wb65fbb131004121427p748a3ffbq86cd3285bbbcc65e@mail.gmail.com>

On 12 April 2010 22:13, Dave Angel <davea at ieee.org> wrote:
> When combining directory paths, it's generally safer to use
>
> os.path.join()

As KDE/Dolphin runs on windows this is even more important as it will
sort out the directory separator (/ vs \) for you.

Some added reading on os.path can be found on Doug's excellent PyMOTW
[1]. Also check out the glob module [2].

Greets
Sander

[1] http://blog.doughellmann.com/2008/01/pymotw-ospath.html
[2] http://blog.doughellmann.com/2007/07/pymotw-glob.html

From alan.gauld at btinternet.com  Tue Apr 13 02:07:07 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Apr 2010 01:07:07 +0100
Subject: [Tutor] Sequences of letter
References: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com><m2ueae1591c1004120648r8ade561akb6a059cd1ec5cc16@mail.gmail.com><4BC34E6F.5090007@ieee.org>
	<201004130322.40918.steve@pearwood.info>
Message-ID: <hq0cji$f6j$1@dough.gmane.org>


"Steven D'Aprano" <steve at pearwood.info> wrote

>>>> import itertools
>>>> for x in itertools.product('abc', 'abc', 'abc'):
>
> If you don't like the repeated 'abc' in the call to product(), it can be
> written as itertools.product(*['ab']*3) instead.

Nope, I think the repeated string is much clearer, and thus better,
than the cryptogram thanks very much! :-)

But I like the itertools solution.
I really, really, need to spend some time playing with itertools.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From alan.gauld at btinternet.com  Tue Apr 13 02:13:48 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 13 Apr 2010 01:13:48 +0100
Subject: [Tutor] Move all files to top-level directory
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
Message-ID: <hq0d02$g2p$1@dough.gmane.org>


"Dotan Cohen" <dotancohen at gmail.com> wrote

>I use this one-liner for moving photos nested a single folder deep
> into the top-level folder:
> find * -name "*.jpg" | awk  -F/ '{print "mv "$0,$1"-"$2}' | sh

You could miss out the awk and use the exec option of find...

Or miss out the shell and use the system() function of awk.

> I need. I have googled file handling in Python but I simply cannot get
> something to replicate the current functionality of that lovely
> one-liner. What fine manual should I be reading? I am not asking for
> code, rather just a link to the right documentation.

You won't easily get a one liner to do the same in Python but you
can do the same things using the glob, subprocess, shutil, os and 
path modules. In particular look at the os.walk and the shutil.move 
functions.

In addition to the module documentation you will find examples and 
description of both in the Using the OS topic of my tutorial.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From roadierich at googlemail.com  Tue Apr 13 02:14:18 2010
From: roadierich at googlemail.com (Rich Lovely)
Date: Tue, 13 Apr 2010 01:14:18 +0100
Subject: [Tutor] Sequences of letter
In-Reply-To: <hq0cji$f6j$1@dough.gmane.org>
References: <s2i9b44710e1004112212zdf0b052fxe647ba6bb9671f16@mail.gmail.com> 
	<m2ueae1591c1004120648r8ade561akb6a059cd1ec5cc16@mail.gmail.com> 
	<4BC34E6F.5090007@ieee.org>
	<201004130322.40918.steve@pearwood.info> 
	<hq0cji$f6j$1@dough.gmane.org>
Message-ID: <l2nf0b4202b1004121714ufdb55e97i1592e11b481850d@mail.gmail.com>

On 13 April 2010 01:07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Steven D'Aprano" <steve at pearwood.info> wrote
>
>>>>> import itertools
>>>>> for x in itertools.product('abc', 'abc', 'abc'):
>>
>> If you don't like the repeated 'abc' in the call to product(), it can be
>> written as itertools.product(*['ab']*3) instead.
>
> Nope, I think the repeated string is much clearer, and thus better,
> than the cryptogram thanks very much! :-)
>
> But I like the itertools solution.
> I really, really, need to spend some time playing with itertools.
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

itertools.product() also has the repeat keyword argument:

for x in itertools.product('abc', 'abc', 'abc'):

is the same as

for x in itertools.product('abc', repeat=3):


-- 
Rich "Roadie Rich" Lovely

Just because you CAN do something, doesn't necessarily mean you SHOULD.
In fact, more often than not, you probably SHOULDN'T.  Especially if I
suggested it.

10 re-discover BASIC
20 ???
30 PRINT "Profit"
40 GOTO 10

From dotancohen at gmail.com  Tue Apr 13 09:14:46 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 13 Apr 2010 10:14:46 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <n2i333efb451004121153q3232adc1xf943b47ac0968630@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>
	<j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com>
	<t2hb65fbb131004121012jcafb2ebcjd34820fdbc2b2c6b@mail.gmail.com>
	<i2v880dece01004121025uee0e3493x9aca6f452290732c@mail.gmail.com>
	<t2o880dece01004121121seaa71310rc07be3295a656a38@mail.gmail.com>
	<n2i333efb451004121153q3232adc1xf943b47ac0968630@mail.gmail.com>
Message-ID: <x2o880dece01004130014n35ed5919z7bdebb65e7d7a9ee@mail.gmail.com>

> from the docs:
> os.rename(src, dst)?Rename the file or directory src to dst. If dst is a
> directory, OSError will be raised.

I did read that, thank you. That is why I asked how to override, as I
understood that Python was functioning exactly as intended.


> It seems what you wan to
> do is os.rename(toMove, currentDir+f)
>

Well, actually, that would be currentDir+"/"+f but you are correct! I
was thinking too much in terms of the unix mv command, which adds that
automatically. Thank you!


-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From dotancohen at gmail.com  Tue Apr 13 09:20:59 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 13 Apr 2010 10:20:59 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <4BC378A5.9060701@ieee.org>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>
	<j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com>
	<t2hb65fbb131004121012jcafb2ebcjd34820fdbc2b2c6b@mail.gmail.com>
	<i2v880dece01004121025uee0e3493x9aca6f452290732c@mail.gmail.com>
	<4BC378A5.9060701@ieee.org>
Message-ID: <i2s880dece01004130020ldc0d5372v9213cde286d04448@mail.gmail.com>

>> I see, thanks. So I was sending it four values apparently. I did not
>> understand the error message.
>
> No, you're sending it two values: ?a tuple, and a string. ?It wants two
> strings. ?Thus the error. If you had sent it four values, you'd have gotten
> a different error.

I see. For some reason I was thinking that the tuple was just three
strings. I've slept now and it is clear to me that this is not the
case!


>>> It might be wise to only have this module print what it would do
>>> instead of doing the actual move/rename so you can work out the bugs
>>> first before it destroys your data.
>>
>> I am testing on fake data, naturally.
>
> Is your entire file system fake? ?Perhaps you're running in a VM, and don't
> mind trashing it.
>
> While debugging, you're much better off using prints than really moving
> files around. ?You might be amazed how much damage a couple of minor bugs
> could cause.
>

I know that you are right. However, using prints would not have helped
me in my current case of not fully understanding the os.rename
function. I should probably develop as a different user, though, to
prevent "incidents". Thanks for the advice.

-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From dotancohen at gmail.com  Tue Apr 13 09:29:37 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 13 Apr 2010 10:29:37 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <4BC37EE4.4070304@ieee.org>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>
	<j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com>
	<t2hb65fbb131004121012jcafb2ebcjd34820fdbc2b2c6b@mail.gmail.com>
	<i2v880dece01004121025uee0e3493x9aca6f452290732c@mail.gmail.com>
	<t2o880dece01004121121seaa71310rc07be3295a656a38@mail.gmail.com>
	<4BC37EE4.4070304@ieee.org>
Message-ID: <z2n880dece01004130029uafd959pe35c09ea577cea77@mail.gmail.com>

> Why is the print below commented out?
>>
>> ? ?for f in file:
>> ? ? ? ?toMove =oot + "/" + f
>> ? ? ? ?#print toMove
>> ? ? ? ?os.rename(toMove, currentDir)
>>

I was testing, and it was not longer needed. It was returning what I
expected. Note that print can only be used to test that the value
matches what the dev expects, not to test that the value matches what
the function wants as we will soon see in the case of currentDir.


> Have you looked at the value of "currentDir" ? Is it in a form that's
> acceptible to os.rename() ?

No, but I though that it was. I had assumed that os.rename would
automatically add the filename as the unix command mv does. Yes, I
know what assumptions make out of me!


> And how about toMove? Perhaps it has two slashes
> in a row in it.

No, toMove was fine.


> When combining directory paths, it's generally safer to use
>
> os.path.join()
>

Thanks!


> Next, you make no check whether "root" is the same as "currentDir". So if
> there are any files already in the top-level directory, you're trying to
> rename them to themselves.
>

I have no problem with that. It is unnecessary, but not harmful at
this stage. But thank you for mentioning it, I will get to that.


> I would also point out that your variable names are very confusing. "file"
> is a list of files, so why isn't it plural? Likewise "folders."
>

Obfuscation! Just kidding, I did not realize that I would be
interacting with "file" as a list of files and not as an individual
file at the time I wrote that. I will revise the variable names, that
is good practice.

Thank you for your patience and advice. I am really enjoying Python
now that I am starting to get the hang of it. I do wish that the docs
had more usage examples but the help on this list and the volume of
information available through google mostly negates that. Thank you
very much.


-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From martin at linux-ip.net  Tue Apr 13 09:33:58 2010
From: martin at linux-ip.net (Martin A. Brown)
Date: Tue, 13 Apr 2010 09:33:58 +0200
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <hq0d02$g2p$1@dough.gmane.org>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<hq0d02$g2p$1@dough.gmane.org>
Message-ID: <alpine.LNX.2.00.1004130926070.19627@octothorpe.wonderfrog.net>

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

Hello,

 : I use this one-liner for moving photos nested a single folder deep
 : into the top-level folder:
 :
 : find * -name "*.jpg" | awk  -F/ '{print "mv "$0,$1"-"$2}' | sh

I would add a few different features to this 'find' to make it a bit 
more resistant to failure, although this sort of solution is always 
subject to the "somebody else is toying with my filesystem race 
condition".

  find "$srcdir" -depth -type f -print0 \
    | xargs --null --no-run-if-empty -- \
      mv --target-directory "$dstdir" --

The --target-directory option is only available in GNU mv (and cp), 
I believe.

I'll second the recommendation for 'shutil', although you can have 
some fun playing with recursion by building your tree flattener 
using os.walk(), os.path.split() and os.path.join().

- -Martin

- -- 
Martin A. Brown
http://linux-ip.net/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.9 (GNU/Linux)
Comment: pgf-0.72 (http://linux-ip.net/sw/pine-gpg-filter/)

iD8DBQFLxB5oHEoZD1iZ+YcRAvPUAKCmXcIhKVTUDx4IexWnAvnl64uQNACeOFf/
3tsR/sXGVe944dUMhxkPYkk=
=x0EG
-----END PGP SIGNATURE-----

From dotancohen at gmail.com  Tue Apr 13 09:59:38 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 13 Apr 2010 10:59:38 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
Message-ID: <h2s880dece01004130059ld0fa3a37sfe1a453529e8877a@mail.gmail.com>

All right, I've got it! This script will move all files of
subdirectories into cwd.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
currentDir = os.getcwd()
filesList = os.walk(currentDir)
for rootDirs, folders, files in filesList:
    for f in files:
        toMove      = os.path.join(rootDirs, f)
        newFilename = os.path.join(currentDir,f)
        os.rename(toMove, newFilename)

Now, features to add:
1) Smart rename: don't clobber existing files
2) Remove empty directories
3) Check that it works with spaces in filenames and directories
4) Check that it works with non-ascii UTF-8 characters in filenames
and directories
5) Confirmation button to prevent accidental runs in $HOME for instance.

Thank you to everyone who helped!

-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From zhuchunml at gmail.com  Tue Apr 13 10:18:34 2010
From: zhuchunml at gmail.com (Joson)
Date: Tue, 13 Apr 2010 16:18:34 +0800
Subject: [Tutor] Linux lib path
In-Reply-To: <q2qffa452951004130117z2a31cc37y4fabc5d276f3a02e@mail.gmail.com>
References: <h2zffa452951004092013n4ef1b2a4rd799231bd61fc852@mail.gmail.com>
	<201004100353.23109.cfuller@thinkingplanet.net>
	<q2qffa452951004130117z2a31cc37y4fabc5d276f3a02e@mail.gmail.com>
Message-ID: <n2uffa452951004130118v4f3c5cf7u65e5dccacf2c308e@mail.gmail.com>

Thanks.

2010/4/13 Joson <zhuchunml at gmail.com>

> thanks a lot. you've saved my life...
>
> 2010/4/10 Chris Fuller <cfuller at thinkingplanet.net>
>
>
>> I'm using Debian.  Used to be etch, but I did a double dist-upgrade
>> recently.
>> So, whatever the current testing release is.  My shell is zsh, but bash
>> should
>> work the same.
>>
>> PYTHONPATH should have worked.  CLASSPATH is for Java.
>>
>>
>> Here's the documentation link you want:
>> http://docs.python.org/install/index.html#inst-search-path
>> http://docs.python.org/library/site.html
>>
>>
>> Files that end in ".pth" are read by Python and the contents are added to
>> sys.path.
>>
>>
>> 0 % python
>> Python 2.5.5 (r255:77872, Feb  1 2010, 19:53:42)
>> [GCC 4.4.3] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>> >>> import sys
>> >>> '/home/cfuller/tmp' in sys.path
>> False
>>
>> 0 % export PYTHONPATH=/home/cfuller/tmp
>> 0 % python
>> Python 2.5.5 (r255:77872, Feb  1 2010, 19:53:42)
>> [GCC 4.4.3] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>> >>> import sys
>> >>> '/home/cfuller/tmp' in sys.path
>> True
>>
>>
>> What I prefer to do, rather than mucking around with environment variables
>> (which isn't reliable, say if its called from a daemon, init script, or
>> maybe
>> a non-interactive shell, and probably other esoterica) is to use .pth
>> files.
>> These are just a listing of directories for Python to add to sys.path.  A
>> lot
>> of packages include some of their own, you should find some in
>> site-packges.
>> Used to be you had to put them there to get them loaded, but there is new
>> per-
>> user support in Python 2.6 and 3k:
>> http://www.python.org/dev/peps/pep-0370/.
>>
>> 0 % export PYTHONPATH=
>> 0 % python
>> Python 2.5.5 (r255:77872, Feb  1 2010, 19:53:42)
>> [GCC 4.4.3] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>> >>> import sys
>> >>> '/home/cfuller/tmp' in sys.path
>>
>>
>> 0 % mkdir -p ~/.local/lib/python2.6/site-packages
>> 0 % echo /home/cfuller/tmp > ~/.local/lib/python2.6/site-packages/tmp.pth
>> 0 % python2.6
>> Python 2.6.5 (r265:79063, Mar 18 2010, 23:38:15)
>> [GCC 4.4.3] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>> >>> import sys
>> >>> '/home/cfuller/tmp' in sys.path
>> True
>>
>>
>>
>> Cheers
>>
>>
>> On Friday 09 April 2010, Joson wrote:
>> > Hi all,
>> >
>> > How to append a path ("/var/myprog/src") to sys.path, but not in the
>> >  dynamic way like sys.path.apend(packpath), please?
>> > I use debian os. and I'd tried to set the classpath in /etc/profile
>> (export
>> > CLASSPATH="..."), and the pythonpath too (export PYTHONPATH="..."). I
>> found
>> > it didn't work.
>> >
>> > Best regards,
>> >
>> > Joson
>> >
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100413/55d17c6c/attachment.html>

From dotancohen at gmail.com  Tue Apr 13 10:30:29 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 13 Apr 2010 11:30:29 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <v2wb65fbb131004121427p748a3ffbq86cd3285bbbcc65e@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<y2jcadf44511004120723jf422d013ib3b397ed5e4639be@mail.gmail.com>
	<j2i880dece01004120928p50cf6614qa7082dec89e53b0c@mail.gmail.com>
	<t2hb65fbb131004121012jcafb2ebcjd34820fdbc2b2c6b@mail.gmail.com>
	<i2v880dece01004121025uee0e3493x9aca6f452290732c@mail.gmail.com>
	<t2o880dece01004121121seaa71310rc07be3295a656a38@mail.gmail.com>
	<4BC37EE4.4070304@ieee.org>
	<v2wb65fbb131004121427p748a3ffbq86cd3285bbbcc65e@mail.gmail.com>
Message-ID: <k2k880dece01004130130jda2a69c4le953800bdc21e640@mail.gmail.com>

>> When combining directory paths, it's generally safer to use
>>
>> os.path.join()
>
> As KDE/Dolphin runs on windows this is even more important as it will
> sort out the directory separator (/ vs \) for you.
>

Added, thanks!

> Some added reading on os.path can be found on Doug's excellent PyMOTW
> [1]. Also check out the glob module [2].
>
> Greets
> Sander
>
> [1] http://blog.doughellmann.com/2008/01/pymotw-ospath.html
> [2] http://blog.doughellmann.com/2007/07/pymotw-glob.html
>

Oh, that is a great site! Any others that I should know about? Being
new to the Python community, I am as of yet unfamiliar with the
standard resources.

Thanks!

-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

Please CC me if you want to be sure that I read your message. I do not
read all list mail.

From dotancohen at gmail.com  Tue Apr 13 10:36:14 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 13 Apr 2010 11:36:14 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <hq0d02$g2p$1@dough.gmane.org>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<hq0d02$g2p$1@dough.gmane.org>
Message-ID: <l2p880dece01004130136m256fadf5q966e10584668d02d@mail.gmail.com>

>> I use this one-liner for moving photos nested a single folder deep
>> into the top-level folder:
>> find * -name "*.jpg" | awk ?-F/ '{print "mv "$0,$1"-"$2}' | sh
>
> You could miss out the awk and use the exec option of find...
>
> Or miss out the shell and use the system() function of awk.
>

The truth is that is not really my code, I modified it from something
that I found. I really want to code my own, and to understand what I
am doing. I'd rather use a real language for it, not a scripting
language as I want the knowledge to apply as generally as possible.


> You won't easily get a one liner to do the same in Python but you
> can do the same things using the glob, subprocess, shutil, os and path
> modules. In particular look at the os.walk and the shutil.move functions.
>

I am not looking for a one-liner. But thanks for clarifying.


> In addition to the module documentation you will find examples and
> description of both in the Using the OS topic of my tutorial.
>

I will read that. I did see your site once, I even bookmarked it. I
will go over it thoroughly! I actually have some comments about the
site, would you like them in private mail if you are interested?

Thanks!


-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From dotancohen at gmail.com  Tue Apr 13 10:39:09 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 13 Apr 2010 11:39:09 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <alpine.LNX.2.00.1004130926070.19627@octothorpe.wonderfrog.net>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<hq0d02$g2p$1@dough.gmane.org>
	<alpine.LNX.2.00.1004130926070.19627@octothorpe.wonderfrog.net>
Message-ID: <o2t880dece01004130139zb3d4a3f8o73aec13747da54b2@mail.gmail.com>

> I would add a few different features to this 'find' to make it a bit
> more resistant to failure, although this sort of solution is always
> subject to the "somebody else is toying with my filesystem race
> condition".
>
> ?find "$srcdir" -depth -type f -print0 \
> ? ?| xargs --null --no-run-if-empty -- \
> ? ? ?mv --target-directory "$dstdir" --
>
> The --target-directory option is only available in GNU mv (and cp),
> I believe.
>

I am trying to get into Python now, but I will go over that at a later
time to improve my shell scripting skills. Thanks. I do appreciate the
instruction.


> I'll second the recommendation for 'shutil', although you can have
> some fun playing with recursion by building your tree flattener
> using os.walk(), os.path.split() and os.path.join().
>

For certain values of "fun"! Actually, I did enjoy this exercise. I
learned a lot, and found some great resources. Python really is a fun
language.

-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From dotancohen at gmail.com  Tue Apr 13 11:31:54 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 13 Apr 2010 12:31:54 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <h2s880dece01004130059ld0fa3a37sfe1a453529e8877a@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<h2s880dece01004130059ld0fa3a37sfe1a453529e8877a@mail.gmail.com>
Message-ID: <g2r880dece01004130231kdcf25325wc36379b146617178@mail.gmail.com>

Here is the revised version:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
currentDir = os.getcwd()
i = 1
filesList = os.walk(currentDir)
for rootDirs, folders, files in filesList:
    for f in files:
        if (rootDirs!=currentDir):
            toMove      = os.path.join(rootDirs, f)
            print "--- "+str(i)
            print toMove
            newFilename = os.path.join(currentDir,f)
            renameNumber = 1
            while(os.path.exists(newFilename)):
                print "- "+newFilename
                newFilename = os.path.join(currentDir,f)+"_"+str(renameNumber)
                renameNumber = renameNumber+1
            print newFilename
            i=i+1
            os.rename(toMove, newFilename)

Now, features to add:
1) Remove empty directories. I think that os.removedirs will work here.
2) Prevent race conditions by performing the filename check during
write. For that I need to find a function that fails to write when the
file exists.
3) Confirmation button to prevent accidental runs in $HOME for
instance. Maybe add some other sanity checks. If anybody is still
reading, I would love to know what sanity checks would be wise to
perform.

Again, thanks to all who have helped.


-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From davea at ieee.org  Tue Apr 13 14:16:05 2010
From: davea at ieee.org (Dave Angel)
Date: Tue, 13 Apr 2010 08:16:05 -0400
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <g2r880dece01004130231kdcf25325wc36379b146617178@mail.gmail.com>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>	<h2s880dece01004130059ld0fa3a37sfe1a453529e8877a@mail.gmail.com>
	<g2r880dece01004130231kdcf25325wc36379b146617178@mail.gmail.com>
Message-ID: <4BC46085.5050308@ieee.org>

Dotan Cohen wrote:
> Here is the revised version:
>
> #!/usr/bin/python
> # -*- coding: utf-8 -*-
> import os
> currentDir = os.getcwd()
> i = 1
> filesList = os.walk(currentDir)
> for rootDirs, folders, files in filesList:
>   
Actual the first item in the tuple (returned by os.walk) is singular (a 
string), so I might call it rootDir.  Only the other two needed to be 
changed to plural to indicate that they were lists.
>     for f in files:
>         if (rootDirs!=currentDir):
>             toMove      = os.path.join(rootDirs, f)
>             print "--- "+str(i)
>             print toMove
>             newFilename = os.path.join(currentDir,f)
>             renameNumber = 1
>             while(os.path.exists(newFilename)):
>                 print "- "+newFilename
>                 newFilename = os.path.join(currentDir,f)+"_"+str(renameNumber)
>                 renameNumber = renameNumber+1
>             print newFilename
>             i=i+1
>             os.rename(toMove, newFilename)
>
> Now, features to add:
> 1) Remove empty directories. I think that os.removedirs will work here.
> 2) Prevent race conditions by performing the filename check during
> write. For that I need to find a function that fails to write when the
> file exists.
> 3) Confirmation button to prevent accidental runs in $HOME for
> instance. Maybe add some other sanity checks. If anybody is still
> reading, I would love to know what sanity checks would be wise to
> perform.
>
> Again, thanks to all who have helped.
>
>
>   
Note that it's not just race conditions that can cause collisions.  You 
might have the same name in two distinct subdirectories, so they'll end 
up in the same place.  Which one wins depends on the OS you're running, 
I believe.

DaveA

From dotancohen at gmail.com  Tue Apr 13 16:05:21 2010
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 13 Apr 2010 17:05:21 +0300
Subject: [Tutor] Move all files to top-level directory
In-Reply-To: <4BC46085.5050308@ieee.org>
References: <p2k880dece01004120711w76ce7dcer53fbb38cf772d782@mail.gmail.com>
	<h2s880dece01004130059ld0fa3a37sfe1a453529e8877a@mail.gmail.com>
	<g2r880dece01004130231kdcf25325wc36379b146617178@mail.gmail.com>
	<4BC46085.5050308@ieee.org>
Message-ID: <p2t880dece01004130705ha5dcc41es2b8ea1b760a7a3e6@mail.gmail.com>

> Actual the first item in the tuple (returned by os.walk) is singular (a
> string), so I might call it rootDir. ?Only the other two needed to be
> changed to plural to indicate that they were lists.

I did discover this, too. I wanted to finish with the code at hand
before I started experimenting with things.


> Note that it's not just race conditions that can cause collisions. ?You
> might have the same name in two distinct subdirectories, so they'll end up
> in the same place. ?Which one wins depends on the OS you're running, I
> believe.
>

The code checks for that, and assigns a different filename if the name
is already taken. See the renameNumber variable.

Thank you very much for your help.


-- 
Dotan Cohen

http://bido.com
http://what-is-what.com

From modulok at gmail.com  Tue Apr 13 16:52:21 2010
From: modulok at gmail.com (Modulok)
Date: Tue, 13 Apr 2010 08:52:21 -0600
Subject: [Tutor] Making pretty web pages from python code examples?
Message-ID: <t2m64c038661004130752wffabf551m5f31753b6efdfddd@mail.gmail.com>

Is there an easy way to get a docstring from a python file, without
first importing it?

Basically, I'm trying to read python code examples from files on disk
and generate pretty little web pages from them. I invision the
docstring appearing as the main text on the page, with the rest of the
code in HTML code or pre tags. That way I could just write up a bunch
of python samples, without having to do anything more but upload them.
Maybe something like this exists already? I don't know. I just figured
it would be pretty easy to write, but getting the docstrings without
trying to parse the files was a rut.

Thanks.
-Modulok-

From martin at linux-ip.net  Tue Apr 13 17:08:09 2010
From: martin at linux-ip.net (Martin A. Brown)
Date: Tue, 13 Apr 2010 17:08:09 +0200
Subject: [Tutor] Making pretty web pages from python code examples?
In-Reply-To: <t2m64c038661004130752wffabf551m5f31753b6efdfddd@mail.gmail.com>
References: <t2m64c038661004130752wffabf551m5f31753b6efdfddd@mail.gmail.com>
Message-ID: <alpine.LNX.2.00.1004131702580.19627@octothorpe.wonderfrog.net>

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

Hello,

 : Is there an easy way to get a docstring from a python file, 
 : without first importing it?
 : 
 : Basically, I'm trying to read python code examples from files on 
 : disk and generate pretty little web pages from them. I invision 
 : the docstring appearing as the main text on the page, with the 
 : rest of the code in HTML code or pre tags. That way I could just 
 : write up a bunch of python samples, without having to do anything 
 : more but upload them. Maybe something like this exists already? I 
 : don't know. I just figured it would be pretty easy to write, but 
 : getting the docstrings without trying to parse the files was a 
 : rut.

I think you may want sphinx [0] which is available in PyPI [1].

It understands reStrucTured text and adds a few Sphinx-specific 
directives/features for pulling the docstrings from your python 
modules.  Much easier than building your own.

Good luck,

- -Martin

 [0] http://sphinx.pocoo.org/
     http://sphinx.pocoo.org/contents.html
     http://pypi.python.org/pypi/Sphinx

- -- 
Martin A. Brown
http://linux-ip.net/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.9 (GNU/Linux)
Comment: pgf-0.72 (http://linux-ip.net/sw/pine-gpg-filter/)

iD8DBQFLxIjeHEoZD1iZ+YcRAmNbAJ4kteAHzm6b7sSkLFn1w4Tbk5z3YQCgqtnE
1BsohLC9e8FIL/hpwvnKBWs=
=wKJ5
-----END PGP SIGNATURE-----

From stefan_ml at behnel.de  Tue Apr 13 19:25:03 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Tue, 13 Apr 2010 19:25:03 +0200
Subject: [Tutor] Making pretty web pages from python code examples?
In-Reply-To: <t2m64c038661004130752wffabf551m5f31753b6efdfddd@mail.gmail.com>
References: <t2m64c038661004130752wffabf551m5f31753b6efdfddd@mail.gmail.com>
Message-ID: <hq29df$lkj$1@dough.gmane.org>

Modulok, 13.04.2010 16:52:
> ... generate pretty little web pages ...

Note that the 'pretty' bit usually doesn't reside in HTML but in CSS.

Stefan


From rayon at gtt.co.gy  Tue Apr 13 21:26:35 2010
From: rayon at gtt.co.gy (Rayon)
Date: Tue, 13 Apr 2010 15:26:35 -0400
Subject: [Tutor] cherrypy
Message-ID: <003901cadb3f$3b8b06b0$b2a11410$@gtt.co.gy>

I am running cherrypy server but I am having some trouble with sessions 

 

Where is my code 

 

from cherrypy.lib import sessions

sess = sessions.Session()

x = sess.id 

 

 

return x; 

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100413/a12db860/attachment.html>

From alan.gauld at btinternet.com  Wed Apr 14 01:44:57 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 14 Apr 2010 00:44:57 +0100
Subject: [Tutor] cherrypy
References: <003901cadb3f$3b8b06b0$b2a11410$@gtt.co.gy>
Message-ID: <hq2vm1$81q$1@dough.gmane.org>


"Rayon" <rayon at gtt.co.gy> wrote 

>I am running cherrypy server but I am having some trouble with sessions 

We need something a bit more specific.
What kind if "trouble"?

Does it execute but with the wrong result? (In what way wrong?)
Does it execute with errors? (please include error text)
Does it fail to execute?

> Where is my code 
> 
> from cherrypy.lib import sessions
> 
> sess = sessions.Session()
> x = sess.id 
> return x; 

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From modulok at gmail.com  Wed Apr 14 15:46:17 2010
From: modulok at gmail.com (Modulok)
Date: Wed, 14 Apr 2010 07:46:17 -0600
Subject: [Tutor] Making pretty web pages from python code examples?
In-Reply-To: <alpine.LNX.2.00.1004131702580.19627@octothorpe.wonderfrog.net>
References: <t2m64c038661004130752wffabf551m5f31753b6efdfddd@mail.gmail.com>
	<alpine.LNX.2.00.1004131702580.19627@octothorpe.wonderfrog.net>
Message-ID: <m2x64c038661004140646n39c4a74ds4c37511440654178@mail.gmail.com>

>  : Basically, I'm trying to read python code examples from files on
>  : disk and generate pretty little web pages from them.

> I think you may want sphinx [0] which is available in PyPI [1].
>
> It understands reStrucTured text and adds a few Sphinx-specific
> directives/features for pulling the docstrings from your python
> modules.  Much easier than building your own.

Thanks! Looks like just what I'm after.
-Modulok-

From dilipm79 at gmail.com  Wed Apr 14 17:27:43 2010
From: dilipm79 at gmail.com (Dilip M)
Date: Wed, 14 Apr 2010 20:57:43 +0530
Subject: [Tutor] How to deploy and upgrade python and its apps
In-Reply-To: <j2mc94f8e121004140206mf9b66857m9386494344f86e3a@mail.gmail.com>
References: <j2mc94f8e121004140206mf9b66857m9386494344f86e3a@mail.gmail.com>
Message-ID: <t2mc94f8e121004140827r9aad0d96tc9b83d5fa9cc3e79@mail.gmail.com>

Hi All,

I would like to understand how to deploy specific version of python and its
modules and apps in consistent manner.

Use case:

1- How to install specific version of python in my own path. (consider
?NFS, /opt/sw/bin and /opt/sw/lib). This particular share is mounted on all
dev machines.

2- How to develop application _using_ only the python and its libs installed in
?/opt/sw/bin and /opt/sw/lib.

3- Now once developed, my applications is dependent on python and its libs in
?/opt/sw/bin and /opt/sw/lib. Hence I want to keep it in sync on all machines
(ofcourse it is mounted). Giving me chance to rollback it necessary.

Here is what I am thinking of doing it. Please correct me and suggest
the better way!

1-

Install python in this location.

./configure --prefix=/opt/sw
make
make install

2-
setenv PYTHONPATH=/opt/sw/lib/python

3. Add whole /opt/sw to some dvcs (hg) and keep updating to stable revisions.


-- Dilip



-- 
Dilip

From dilipm79 at gmail.com  Wed Apr 14 11:06:51 2010
From: dilipm79 at gmail.com (Dilip M)
Date: Wed, 14 Apr 2010 14:36:51 +0530
Subject: [Tutor] How to deploy and upgrade python and its apps
Message-ID: <j2mc94f8e121004140206mf9b66857m9386494344f86e3a@mail.gmail.com>

Hi All,

I would like to understand how to deploy specific version of python and its
modules and apps in consistent manner.

Use case:

1- How to install specific version of python in my own path. (consider
  NFS, /opt/sw/bin and /opt/sw/lib). This particular share is mounted on all
dev machines.

2- How to develop application _using_ only the python and its libs installed in
  /opt/sw/bin and /opt/sw/lib.

3- Now once developed, my applications is dependent on python and its libs in
  /opt/sw/bin and /opt/sw/lib. Hence I want to keep it in sync on all machines
(ofcourse it is mounted). Giving me chance to rollback it necessary.

Here is what I am thinking of doing it. Please correct me and suggest
the better way!

1-

Install python in this location.

./configure --prefix=/opt/sw
make
make install

2-
setenv PYTHONPATH=/opt/sw/lib/python

3. Add whole /opt/sw to some dvcs (hg) and keep updating to stable revisions.


-- Dilip

From bludvigsen at gmail.com  Wed Apr 14 17:52:31 2010
From: bludvigsen at gmail.com (Bjorn Egil Ludvigsen)
Date: Wed, 14 Apr 2010 10:52:31 -0500
Subject: [Tutor] How to deploy and upgrade python and its apps
In-Reply-To: <t2mc94f8e121004140827r9aad0d96tc9b83d5fa9cc3e79@mail.gmail.com>
References: <j2mc94f8e121004140206mf9b66857m9386494344f86e3a@mail.gmail.com>
	<t2mc94f8e121004140827r9aad0d96tc9b83d5fa9cc3e79@mail.gmail.com>
Message-ID: <p2p5ec0fe121004140852l841bd86dn5c5829355558fb7f@mail.gmail.com>

Hi Dilip,

There is some good information about this in the book "Expert Python
Programming" by Tarek Ziade, and maybe you could look into
http://pypi.python.org/virtualenv, easy_install and zc.buildout.

Regards,
Bjorn

On Wed, Apr 14, 2010 at 10:27 AM, Dilip M <dilipm79 at gmail.com> wrote:

> Hi All,
>
> I would like to understand how to deploy specific version of python and its
> modules and apps in consistent manner.
>
> Use case:
>
> 1- How to install specific version of python in my own path. (consider
>  NFS, /opt/sw/bin and /opt/sw/lib). This particular share is mounted on all
> dev machines.
>
> 2- How to develop application _using_ only the python and its libs
> installed in
>  /opt/sw/bin and /opt/sw/lib.
>
> 3- Now once developed, my applications is dependent on python and its libs
> in
>  /opt/sw/bin and /opt/sw/lib. Hence I want to keep it in sync on all
> machines
> (ofcourse it is mounted). Giving me chance to rollback it necessary.
>
> Here is what I am thinking of doing it. Please correct me and suggest
> the better way!
>
> 1-
>
> Install python in this location.
>
> ./configure --prefix=/opt/sw
> make
> make install
>
> 2-
> setenv PYTHONPATH=/opt/sw/lib/python
>
> 3. Add whole /opt/sw to some dvcs (hg) and keep updating to stable
> revisions.
>
>
> -- Dilip
>
>
>
> --
> Dilip
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100414/b3eb6fe0/attachment.html>

From karper12345 at yahoo.com  Wed Apr 14 22:16:02 2010
From: karper12345 at yahoo.com (Karjer Jdfjdf)
Date: Wed, 14 Apr 2010 13:16:02 -0700 (PDT)
Subject: [Tutor] Problems with creating XML-documents
Message-ID: <915674.45955.qm@web44711.mail.sp1.yahoo.com>

I'm having problems with creating XML-documents, because I don't seem to write it to a document correctly. I have to write the document from a loop:

??? doc.write('<?xml version="1.0" encoding="iso-8859-1"?>\n')
??? ....
??? for instance in query:??? 
??????? if doc != None:
??????????? text = str('<record id="' + str(instance.id)+ '">\n' + \
?????????????????????? ' <date>' +? str(instance.datetime) + ' </date>\n' + \
?????????????????????? ' <order>'? + instance.order +? ' </order>\n' + \
?????????????????????? '</record>\n')
??????????? doc.write(text)

When I try to parse it, it keeps giving errors. So I tried to use an external library jaxml, but I don't know how to implement this in the loop because the output is written at the end (doc._output) and I overwrite my values. The code below is from the jaxml website

# an equivalent version using JAXML
import jaxml
doc = jaxml.XML_document()
doc.sometag(someattr=1).anothertag(jaxml="Nice")
doc.thirdone("Yo")
doc._output("sample.xml")

Can anybody point me in the rght direction or is there another library that I can use to create valid XML-documents?





      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100414/42ac7a61/attachment.html>

From bgailer at gmail.com  Wed Apr 14 23:12:42 2010
From: bgailer at gmail.com (bob gailer)
Date: Wed, 14 Apr 2010 17:12:42 -0400
Subject: [Tutor] Problems with creating XML-documents
In-Reply-To: <915674.45955.qm@web44711.mail.sp1.yahoo.com>
References: <915674.45955.qm@web44711.mail.sp1.yahoo.com>
Message-ID: <4BC62FCA.5080409@gmail.com>

On 4/14/2010 4:16 PM, Karjer Jdfjdf wrote:
> I'm having problems with creating XML-documents, because I don't seem 
> to write it to a document correctly. I have to write the document from 
> a loop:
>
>     doc.write('<?xml version="1.0" encoding="iso-8859-1"?>\n')
>     ....
>     for instance in query:
>         if doc != None:
>             text = str('<record id="' + str(instance.id)+ '">\n' + \
>                        ' <date>' +  str(instance.datetime) + ' 
> </date>\n' + \
>                        ' <order>'  + instance.order +  ' </order>\n' + \
>                        '</record>\n')
>             doc.write(text)
>
> When I try to parse it, it keeps giving errors.
>

I am frustrated with the lack of clarity and completeness. Please 
respect our time as volunteers by giving complete explicit informaion.

Show us the resultant file.

Tell us what parsing tool you are using.

Show us the exact errors.

[snip]

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100414/dba322c0/attachment-0001.html>

From alan.gauld at btinternet.com  Thu Apr 15 02:00:13 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 15 Apr 2010 01:00:13 +0100
Subject: [Tutor] Problems with creating XML-documents
References: <915674.45955.qm@web44711.mail.sp1.yahoo.com>
Message-ID: <hq5kum$9ev$1@dough.gmane.org>

"Karjer Jdfjdf" <karper12345 at yahoo.com> wrote

> I'm having problems with creating XML-documents, 
> because I don't seem to write it to a document correctly. 

Is that because you don't understand XML or because the 
output is not what you expect? How is the data being generated? 
Are you parsing an existing XML source or creating the XML 
from scratch? I'm not sure I understand your problem.

>      text = str('<record id="' + str(instance.id)+ '">\n' + \
' <date>' + str(instance.datetime) + ' </date>\n' + \
' <order>' + instance.order + ' </order>\n' + \
'</record>\n')

You can simplify this quite a lot. You almost certaionly don;t need 
the outer str() and you probably don;t need the \ characters either.

Also it might be easier to use a triple quoted string and format 
characters to insert the dasta values.

> When I try to parse it, it keeps giving errors. 

Why do you need to parse it if you are creating it?
Or is this after you read it back later? I don't understand the 
sequence of processing here.

> So I tried to use an external library jaxml, 

Did you try to use the standard library tools that come with Python, 
like elementTree or even sax?

I think we need a few more pointers to the root cause here.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From eike.welk at gmx.net  Thu Apr 15 03:17:09 2010
From: eike.welk at gmx.net (Eike Welk)
Date: Thu, 15 Apr 2010 03:17:09 +0200
Subject: [Tutor] Introduction to modelling with Python
In-Reply-To: <4BBC527F.4040907@gmail.com>
References: <4BAE2276.5050807@gmail.com> <201003281543.22999.eike.welk@gmx.net>
	<4BBC527F.4040907@gmail.com>
Message-ID: <201004150317.09898.eike.welk@gmx.net>

On Wednesday April 7 2010 11:38:07 AG wrote:

> 
> Eike
> 
> I just wanted to come back to you on the book recommendation you made
> "Python scripting for computational science" - I tracked down a cheapish
> copy of the 3rd edition from 2009 and flipping through it (it only
> arrived yesterday), it seems like it is going to be very useful.
> Certainly it draws a lot on numpy, goes into using Tcl for GUIs, and a
> number of recipes for scripting, regular expressions and so on ... lots
> to get my head around.  

"Python scripting for computational science" also contains a section about 
solving differential equations. It is in one of the chapters about additional 
libraries.

The book contains many Fortran examples. As an alternative to Fortran you 
should also look at Cython. This is a very fast, compiled companion language 
for Python. It produces *.so (*.dll) files that can be directly loaded into 
Python as modules. 
http://www.cython.org/

> With respect to my original question then,
> equipped with this book you recommended, a book on differential
> equations, and one on an intro to environmental modelling, that should
> give me enough to work on for the time being.

An other possible book for an inter library loan might be "Mathematical Models 
in Biology" from Leah Edelstein-Keshet. It contains many differential 
equations from different fields of biology. Additionally it contains a very 
good introduction how to write your own partial differential equations. 

It is not an ideal book for someone who wants to do numerical computations 
(like you), because the differential equations are solved symbolically with 
pen and paper. On the other hand: Why do numerical experiments, when you can 
find all possible solutions at once "just" with pen and paper. I believe 
however the real reason is, that the book was written before computers became 
cheap (1988).   

> 
> So, just wanted to close the circle by letting you know that I took your
> recommendation, and it looks like it will pay off in time.

Great!


Eike.

From karper12345 at yahoo.com  Thu Apr 15 08:03:33 2010
From: karper12345 at yahoo.com (Karjer Jdfjdf)
Date: Wed, 14 Apr 2010 23:03:33 -0700 (PDT)
Subject: [Tutor] Re Problems with creating XML-documents
Message-ID: <858489.96463.qm@web44716.mail.sp1.yahoo.com>

>> I'm having problems with creating XML-documents, 
>> because I don't seem to write it to a document correctly. 

>Is that because you don't understand XML or because the 
>output is not what you expect? How is the data being generated? 
>Are you parsing an existing XML source or creating the XML 
>from scratch? I'm not sure I understand your problem.

I know the theory of XML but have never used it really and
I'm a bit unsecure about it.

Basically I'm doing the following:

1. retrieve data from a database ( instance in q )
2. pass the data to an external java-program that requires file-input 
3. the java-program modifies the inputfile and creates an outputfile based on the inputfile
4. I read the outputfile and try to parse it.

1 to 3 are performed by a seperate program that creates the XML
4 is a program that tries to parse it (and then perform other
modifications using python)

When I try to parse the outputfile it creates different errors such as:
   * ExpatError: not well-formed (invalid token):

Basically it ususally has something to do with not-well-formed XML. 
Unfortunately the Java-program also alters the content on essential 
points such as inserting spaces in tags (e.g. id="value" to id = " value " ),
which makes it even harder. The Java is really a b&%$#!, but I have
no alternatives because it is custommade (but very poorly imho).

Sorry, I've nog been clear, but it's very difficult and frustrating for 
me to troubleshoot this properly because the Java-program is quite huge and 
takes a long time to load before doing it's actions and when running
also requires a lot of time. The minimum is about 10 minutes per run.

This means trying a few little things takes hours.
Because of the long load and processing time of the Java-program I'm forced
to store the output in a single file instead of processing it record by record.


Also each time I have to change something I have to modify functions in 
different libraries that perform specific functions. This probably means
that I've not done it the right way in the first place.



>>      text = str('<record id="' + str(instance.id)+ '">\n' + \
' <date>' + str(instance.datetime) + ' </date>\n' + \
' <order>' + instance.order + ' </order>\n' + \
'</record>\n')

>You can simplify this quite a lot. You almost certaionly don;t need 
>the outer str() and you probably don;t need the \ characters either.

I use a very simplified text-variable here. In reality I also include 
other fields which contain numeric values as well. I use the \ to
keep each XML-tag on a seperate line to keep the overview.


>Also it might be easier to use a triple quoted string and format 
>characters to insert the dasta values.

>> When I try to parse it, it keeps giving errors. 

>Why do you need to parse it if you are creating it?
>Or is this after you read it back later? I don't understand the 
>sequence of processing here.

>> So I tried to use an external library jaxml, 

>Did you try to use the standard library tools that come with Python, 
>like elementTree or even sax?

I've been trying to do this with minidom, but I'm not sure if this 
is the right solution because I'm pretty unaware of XML-writing/parsing

At the moment I'm tempted to do a line-by-line parse and trigger on
an identifier-string that identifies the end and start of a record. 
But that way I'll never learn XML.


>I think we need a few more pointers to the root cause here.




      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100414/2c3d4c2a/attachment.html>

From stefan_ml at behnel.de  Thu Apr 15 09:32:20 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Thu, 15 Apr 2010 09:32:20 +0200
Subject: [Tutor] Problems with creating XML-documents
In-Reply-To: <858489.96463.qm@web44716.mail.sp1.yahoo.com>
References: <858489.96463.qm@web44716.mail.sp1.yahoo.com>
Message-ID: <hq6fe4$bh2$1@dough.gmane.org>

Hi,

my main advice up-front: if you want good advice, give good details about 
the problem you face and enough background to let others understand what 
the real problem is and what your environmental constraints are.


Karjer Jdfjdf, 15.04.2010 08:03:
> I know the theory of XML but have never used it really and
> I'm a bit unsecure about it.

At least in Python, XML is trivial to use, as long as you use proper XML 
tools. It's a bit more tricky in Java, but there are some usable tools 
there, too. From what you write about the program, it's rather unlikely 
that is uses them, though.


> Basically I'm doing the following:
>
> 1. retrieve data from a database ( instance in q )
> 2. pass the data to an external java-program that requires file-input

XML input, I assume. So this is the part where you generate your XML output 
from database input. Fair enough.


> 3. the java-program modifies the inputfile and creates an outputfile based on the inputfile

Is this program outside of your control or do you have the sources?

Does it do anything really complex and tricky, or could it be reimplemented 
in a couple of lines in Python? The mere fact that a Java program "is huge 
and takes minutes to run" doesn't mean much in general. That's often just 
due to a bad design.


> 4. I read the outputfile and try to parse it.

Is the output file a newly created XML file or does the Java program do 
text processing on the input file?


> 1 to 3 are performed by a seperate program that creates the XML
> 4 is a program that tries to parse it (and then perform other
> modifications using python)
>
> When I try to parse the outputfile it creates different errors such as:
>     * ExpatError: not well-formed (invalid token):
>
> Basically it ususally has something to do with not-well-formed XML.

I.e. not XML at all.


> Unfortunately the Java-program also alters the content on essential
> points such as inserting spaces in tags (e.g. id="value" to id = " value " ),

Any XML parser will handle the whitespace around 'id' and '=' for you, but 
the fact that the program alters the content of an 'id' attribute seems 
rather frightening.


> The Java is really a b&%$#!, but I have
> no alternatives because it is custommade (but very poorly imho).

You should make sure it's really carved into stone. Could you give a hint 
about what the program actually does?


> This means trying a few little things takes hours.
> Because of the long load and processing time of the Java-program I'm forced
> to store the output in a single file instead of processing it record by record.

Maybe you could reduce the input file size for testing, or does it really 
take 10 Minutes to run a small file through it?


> Also each time I have to change something I have to modify functions in
> different libraries that perform specific functions. This probably means
> that I've not done it the right way in the first place.

Not sure I understand what you mean here.


>>>       text = str('<record id="' + str(instance.id)+ '">\n' + \
> '<date>' + str(instance.datetime) + '</date>\n' + \
> '<order>' + instance.order + '</order>\n' + \
> '</record>\n')
>
>> You can simplify this quite a lot. You almost certaionly don;t need
>> the outer str() and you probably don;t need the \ characters either.
>
> I use a very simplified text-variable here. In reality I also include
> other fields which contain numeric values as well. I use the \ to
> keep each XML-tag on a seperate line to keep the overview.

You should really use a proper tool to generate the XML. I never used jaxml 
myself, but I guess it would do the job at hand. If the file isn't too 
large (a couple of MB maybe), you can also go with cElementTree and just 
create the file in memory before writing it out.


>> Also it might be easier to use a triple quoted string and format
>> characters to insert the dasta values.

That's certainly good advice if you really want to take the "string output" 
road. Check the tutorial for '%' string formatting.


>> Did you try to use the standard library tools that come with Python,
>> like elementTree or even sax?
>
> I've been trying to do this with minidom, but I'm not sure if this
> is the right solution because I'm pretty unaware of XML-writing/parsing

If anything, use cElementTree instead.


> At the moment I'm tempted to do a line-by-line parse and trigger on
> an identifier-string that identifies the end and start of a record.
> But that way I'll never learn XML.

If the Java program really can't be forced into outputting XML, running an 
XML parser over the result is doomed to fail. XML is a very well specified 
format and a compliant XML parser is bound to reject anything that violates 
the spec.

Stefan


From lie.1296 at gmail.com  Thu Apr 15 09:57:03 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Thu, 15 Apr 2010 17:57:03 +1000
Subject: [Tutor] Re Problems with creating XML-documents
In-Reply-To: <858489.96463.qm@web44716.mail.sp1.yahoo.com>
References: <858489.96463.qm@web44716.mail.sp1.yahoo.com>
Message-ID: <hq6guu$h6a$1@dough.gmane.org>

On 04/15/10 16:03, Karjer Jdfjdf wrote:
> When I try to parse the outputfile it creates different errors such as:
>    * ExpatError: not well-formed (invalid token):

That error message is telling you that you're not parsing an XML file,
merely an XML-like file.

> Basically it ususally has something to do with not-well-formed XML. 
> Unfortunately the Java-program also alters the content on essential 
> points such as inserting spaces in tags (e.g. id="value" to id = " value " ),
> which makes it even harder. The Java is really a b&%$#!, but I have
> no alternatives because it is custommade (but very poorly imho).

The bug is in the program generating the XML, it is much easier to fix
it in Java side than trying to parse broken XML.

> Sorry, I've nog been clear, but it's very difficult and frustrating for 
> me to troubleshoot this properly because the Java-program is quite huge and *takes a long time to load before doing it's actions and when running
> also requires a lot of time. The minimum is about 10 minutes per run.

10 minutes per-run is instant compared to writing a parser for invalid
XML. And you can cut that 10 minutes short by using a smaller database
for testing purpose.

>>>/      text = str('<record id="' + str(instance.id)+ '">\n' + \
> /' <date>' + str(instance.datetime) + ' </date>\n' + \
> ' <order>' + instance.order + ' </order>\n' + \
> '</record>\n')
> 
>>You can simplify this quite a lot. You almost certaionly don;t need 
>>the outer str() and you probably don;t need
>   the \ characters either.
> 
> I use a very simplified text-variable here. In reality I also include 
> other fields which contain numeric values as well. I use the
>  \ to
> keep each XML-tag on a seperate line to keep the overview.

He means you can simplify it by using string interpolation:

text = '''
<record id="%s">
 <date>%s </date>
 <order>%s </order>
</record>
''' % (instance.id, instance.datetime, instance.order)

>>Also it might be easier to use a triple quoted string and format 
>>characters to insert the dasta values.
> 
>>>/ When I try to parse it, it keeps giving errors. 
> /
>>Why do you need to parse it if you are creating it?
>>Or is this after you read it back later? I don't understand the 
>>sequence of processing here.
> 
>>>/ So I tried to use an external library jaxml, 
> /
>>Did you try to use the standard library tools that come with Python, 
>>like elementTree or even sax?
> 
> I've been trying to do this with minidom, but I'm not sure if this 
> is the right solution because I'm pretty unaware of XML-writing/parsing
> 
> At the moment I'm 
>  tempted to do a line-by-line parse and trigger on
> an identifier-string that identifies the end and start of a record. 
> But that way I'll never learn XML.

Why bother writing an XML-like parser when you can fix the generating
program? And my recommendation, if you want to learn XML, learning to
write xHTML Strict first (with a plain text editor! not some
RealityWeaver or BackPage) is IMHO probably the easiest route
(especially if you already know some HTML).


From denis.spir at gmail.com  Thu Apr 15 13:37:02 2010
From: denis.spir at gmail.com (spir =?UTF-8?B?4pij?=)
Date: Thu, 15 Apr 2010 13:37:02 +0200
Subject: [Tutor] "value" ~ "data" ~ "object"
Message-ID: <20100415133702.78f1394b@o>

Hello,

I have been recently thinking at lexical distinctions around the notion of data. (--> eg for a starting point http://c2.com/cgi/wiki?WhatIsData) Not only but especially in Python. I ended up with the following questions:
Can one state "in Python value=data=object"?
Can one state "in Python speak value=data=object"?

What useful distinctions are or may be done, for instance in documentation?
What kind of difference in actual language semantics may such distinctions mirror?

Denis

PS: side-question on english:
I am annoyed by the fact that in english "data" is mainly used & understood as a collective (uncountable) noun. "datum" (singular) & "datas" (plural) seem to be considered weird. How to denote a single unit of data wothout using the phrase "piece of data"? Can one still use "datum" or "datas" (or "data" as plural) and be trivially understood by *anybody* (not only scientists)? Or else what word should one use?
-->  
Compare: german Datum/Daten http://de.wiktionary.org/wiki/Datum, french donn?e/donn?es http://fr.wiktionary.org/wiki/donn%C3%A9e, etc...
________________________________

vit esse estrany ?

spir.wikidot.com

From ncoghlan at gmail.com  Thu Apr 15 16:40:10 2010
From: ncoghlan at gmail.com (Nick Coghlan)
Date: Fri, 16 Apr 2010 00:40:10 +1000
Subject: [Tutor] [Python-ideas] "value" ~ "data" ~ "object"
In-Reply-To: <20100415133702.78f1394b@o>
References: <20100415133702.78f1394b@o>
Message-ID: <4BC7254A.9020304@gmail.com>

spir ? wrote:
> What useful distinctions are or may be done, for instance in documentation?

Python mainly considers:

object identity (x is y, determined by id())
object value (x == y, determined by the implementations of relevant
__eq__ methods)

For many objects, their value degenerates to being the same as their
identity (i.e. they compare equal only with themselves), but others have
for more useful comparisons defined (e.g. containers, numbers).

In addition to objects with their identities and values, there are
references to objects. These 'references' are the only things in Python
which aren't first class objects, since they reflect lookup entries in
some namespace or container, such as the mapping from names to pointers
in a class or module __dict__ or a function's locals, or the items
stored in a list or set.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------

From steve at pearwood.info  Fri Apr 16 03:02:42 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 16 Apr 2010 11:02:42 +1000
Subject: [Tutor] "value" ~ "data" ~ "object"
In-Reply-To: <20100415133702.78f1394b@o>
References: <20100415133702.78f1394b@o>
Message-ID: <201004161102.44301.steve@pearwood.info>

On Thu, 15 Apr 2010 09:37:02 pm spir ? wrote:
> Hello,
>
> I have been recently thinking at lexical distinctions around the
> notion of data. (--> eg for a starting point
> http://c2.com/cgi/wiki?WhatIsData) Not only but especially in Python.
> I ended up with the following questions: Can one state "in Python
> value=data=object"?
> Can one state "in Python speak value=data=object"?

I don't think so -- this is mistaking the map for the territory.

Objects are the concrete representation ("the map") in the memory of a 
computer of some data ("the territory"). The Python object 42 is not 
the integer 42, which is an abstract mathematical concept. The Python 
object my_list_of_countries is not an actual list of countries, it is a 
representation of a list containing representations of countries.

The dictionary definition of value generally describes it as a number, 
e.g. from WordNet: 

a numerical quantity measured or assigned or computed; "the value 
assigned was 16 milliseconds"

or Websters:

9. (Math.) Any particular quantitative determination; as, a function's 
value for some special value of its argument.

In modern terms, we extend this to other types of data: we might say the 
value of the variable A is the string 'elephant'.

So I would say things like:

a variable HAS a value;

the bit pattern 00001001 REPRESENTS the integer nine

an object REPRESENTS a value;

a name REFERS TO (points to, is bound to) an object;

and similar. To say that the (say) the variable x IS 9 is verbal short 
hand. Who has never pointed at a spot on the map and said "That's where 
we have to go"? We all treat the map as the territory sometimes.



> What useful distinctions are or may be done, for instance in
> documentation? What kind of difference in actual language semantics
> may such distinctions mirror?

I think that, 99% of the time, it is acceptable to treat the map as the 
territory and treat variables as BEING values. Just write the 
documentation in the most natural way:

class Elephant:
    def walk(self, direction):
        """Cause the elephant to walk in the direction given."""
        ...
    def _move_leg(self, leg):
        """Private method that operates the elephant's given leg."""
        ...


Trying to be pedantic about values, data and in-memory representations 
is rarely necessary.



> Denis
>
> PS: side-question on english:
> I am annoyed by the fact that in english "data" is mainly used &
> understood as a collective (uncountable) noun. "datum" (singular) &
> "datas" (plural) seem to be considered weird. 

"Datas" has never been the plural of data. Datum is the singular, data 
the plural.

Over the last few decades, data is slowly shifting to be an uncountable 
noun, like "water", "air" or "knowledge", and datum has become very 
old-fashioned. I would still expect most people would recognise it, or 
at least understand it from context.

Collective noun is incorrect. Collective nouns are things like "a FLOCK 
of geese", "a PILE of books", "a SET of spanners", or "a GROUP of 
people". The term you are thinking of is mass noun.

See:

http://en.wikipedia.org/wiki/Collective_noun
http://en.wikipedia.org/wiki/Mass_noun
http://en.wikipedia.org/wiki/Data


> How to denote a single 
> unit of data wothout using the phrase "piece of data"? 

You can still use datum, although it is becoming obsolete it is not gone 
yet. But if you treat data as uncountable, then like any uncountable 
noun you have to supply a unit or amount:

Item of data.
Element of data.
Great big lump of data.
42 bytes of data.





-- 
Steven D'Aprano

From timgoddardsemail at gmail.com  Fri Apr 16 04:03:52 2010
From: timgoddardsemail at gmail.com (Tim Goddard)
Date: Thu, 15 Apr 2010 21:03:52 -0500
Subject: [Tutor] Creating class instances through iteration
Message-ID: <o2zed76920d1004151903kbf2aed74m98d0680eae28ebdd@mail.gmail.com>

I came across a situation where what I thought I wanted to do was to create
a class that was spawned from data in a .csv file.  Where column 1 was the
name I wanted to use for each instance.  I had it all figured out and
working except for how to write a statement where the left hand side could
be a changing identifier.

All I could figure out was how to create the same instance 50 times albeit
in different ways.

For example each row would look like [name, value1, value2, value3], I
planned on passing the three values as a tuple

The code would simply be:

for row in csvimport:
    tuple = (row[1],row[2],row[3])
    instancename = Classname(tuple)

How could I create different instances inside an iteration loop for each row
?  Is it possible to change the name through modification of self attribute
(wait is self an attribute?)  Are cats sleeping with dogs here or what?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100415/6a1c89b3/attachment.html>

From denis.spir at gmail.com  Fri Apr 16 05:14:31 2010
From: denis.spir at gmail.com (spir =?UTF-8?B?4pij?=)
Date: Fri, 16 Apr 2010 05:14:31 +0200
Subject: [Tutor] Creating class instances through iteration
In-Reply-To: <o2zed76920d1004151903kbf2aed74m98d0680eae28ebdd@mail.gmail.com>
References: <o2zed76920d1004151903kbf2aed74m98d0680eae28ebdd@mail.gmail.com>
Message-ID: <20100416051431.43fd8d67@o>

On Thu, 15 Apr 2010 21:03:52 -0500
Tim Goddard <timgoddardsemail at gmail.com> wrote:

> I came across a situation where what I thought I wanted to do was to create
> a class that was spawned from data in a .csv file.  Where column 1 was the
> name I wanted to use for each instance.  I had it all figured out and
> working except for how to write a statement where the left hand side could
> be a changing identifier.
> 
> All I could figure out was how to create the same instance 50 times albeit
> in different ways.
> 
> For example each row would look like [name, value1, value2, value3], I
> planned on passing the three values as a tuple
> 
> The code would simply be:
> 
> for row in csvimport:
>     tuple = (row[1],row[2],row[3])
>     instancename = Classname(tuple)
> 
> How could I create different instances inside an iteration loop for each row
> ?

If I understand you properly, what you're trying to reinvent is a dict. For each row, use the name (which is data, too, right?) as key and the tuple oe whatever structure you like as value.
   thing[name] = tuple
An alternative, if you really want the names to be real var names, is to put all of that into an object as attributes, using the builtin func setattr:
   setattr(thing, name, tuple)

> Is it possible to change the name through modification of self attribute
> (wait is self an attribute?)

Don't understand why you want a class here.

> Are cats sleeping with dogs here or what?

???

Denis
________________________________

vit esse estrany ?

spir.wikidot.com

From crp at cmc.net  Fri Apr 16 06:06:04 2010
From: crp at cmc.net (Ray Parrish)
Date: Thu, 15 Apr 2010 21:06:04 -0700
Subject: [Tutor] Passing headers with httplib
Message-ID: <4BC7E22C.8010901@cmc.net>

Hello,

I am trying to figure out how to send cookie data with an httplib 
request command. Here is what the doc says -

request(      method, url[, body[, headers]])
    This will send a request to the server using the HTTP request method 
method and the selector url. If the body argument is present, it should 
be a string of data to send after the headers are finished. The header 
Content-Length is automatically set to the correct value. The headers 
argument should be a mapping of extra HTTP headers to send with the 
request.

My question is how do I formulate a "mapping" of a header for a few 
cookies? Here are the cookies I would like to send with the request -

TVGID=029690D849714243A9DDEA34652CA804; Provider=Broadcast; 
__qca=P0-547310088-1271379357584; 
LastGrid=fmt=0&srvid=20442&gridmins=120&gridyr=2010&gridmo=4&griddy=15&gridhr=20&chanrow=1&genre=0&favchan=false&magic=1269|9898&magictype=0&zip=&music=1&ppv=1&24hr=1&HDTVOnly=false; 
s_cc=true; s_sq=%5B%5BB%5D%5D; wtpgcnt=1; 
s_vi=[CS]v1|25E3DAD0050118C7-6000010E60004530[CE]; 
base_domain_4631b4ff1e53d450c3f9726dd45be7de=tvguide.com; 
rsi_ct=2010_4_15:6;

Thanks for any help you can be, Ray Parrish

-- 
Linux dpkg Software Report script set..
http://www.rayslinks.com/LinuxdpkgSoftwareReport.html
Ray's Links, a variety of links to usefull things, and articles by Ray.
http://www.rayslinks.com
Writings of "The" Schizophrenic, what it's like to be a schizo, and other
things, including my poetry.
http://www.writingsoftheschizophrenic.com



From steve at pearwood.info  Fri Apr 16 08:30:26 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 16 Apr 2010 16:30:26 +1000
Subject: [Tutor] Creating class instances through iteration
In-Reply-To: <o2zed76920d1004151903kbf2aed74m98d0680eae28ebdd@mail.gmail.com>
References: <o2zed76920d1004151903kbf2aed74m98d0680eae28ebdd@mail.gmail.com>
Message-ID: <201004161630.27566.steve@pearwood.info>

On Fri, 16 Apr 2010 12:03:52 pm Tim Goddard wrote:

> For example each row would look like [name, value1, value2, value3],
> I planned on passing the three values as a tuple
>
> The code would simply be:
>
> for row in csvimport:
>     tuple = (row[1],row[2],row[3])
>     instancename = Classname(tuple)
>
> How could I create different instances inside an iteration loop for
> each row ? 

Let me see if I have it right... you want a CSV file that looks 
something like this:

a,1,2,3
b,2,4,8
c,3,6,9


and you want to end up with:

a = Classname((1,2,4))
b = Classname((2,4,8))
c = Classname((3,6,9))


Correct?

That's the wrong question. It's easy to create new names, using eval 
(but beware of the security risks!). But the question you should be 
asking is, what on earth do I do with them once I've created them?

Later in your code, suppose you want to do something like this:

print c.some_method()


(say). But how do you know that c will exist? Maybe the CSV file doesn't 
have rows named a,b,c, but instead has x,y,z. Or a,b,d,e, or even 
fred,wilma,betty,barney. Since you don't know what the name of the 
variable will be, you can't refer to it in code. You then have to jump 
through all sorts of flaming hoops by writing code like this:

# Untested
list_of_names = []
for row in csvimport:
    list_of_names.append(row[0])
    tuple = (row[1],row[2],row[3])
    # WARNING -- the next line is DANGEROUS and has a HUGE security
    # hole which could cause data loss. Only use it on data you 
    # trust with your life.
    eval('%s = Classname(t)' % row[0], globals(), {'t': tuple})
# more code goes here
# ...
# much later
if 'c' in list_of_names:
    print c.some_method()
else:
    # Oh I don't know, just pick some random variable and hope it
    # is the right one...
    eval('print %s.some_method()' % list_of_names[0])


Whew! Ugly, insecure, slow, dangerous code.

Is there an alternative? Of course -- dictionaries.


objects = {}
for row in csvimport:
    tuple = (row[1],row[2],row[3])
    objects[row[0]) = Classname(tuple)
# more code goes here
# ...
# much later
try:
    print objects['c'].some_method()
except KeyError:
    # No name 'c' exists...
    ...


But more likely, you don't need to operate on a single object c, you 
need to operate on all of them. So what is the purpose of the names? 
Just drop the names, and work on a collection of objects:

objects = []
for row in csvimport:
    tuple = (row[0],row[1],row[2])
    objects.append(Classname(tuple))
# more code goes here
# ...
# much later
for obj in objects:
    print obj.some_method()


Hope this helps,




-- 
Steven D'Aprano

From cloudneozero at gmail.com  Fri Apr 16 08:50:58 2010
From: cloudneozero at gmail.com (Ark)
Date: Fri, 16 Apr 2010 01:50:58 -0500
Subject: [Tutor] Loop comparison
Message-ID: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>

Hi everyone.
A friend of mine suggested me to do the next experiment in python and Java.

It's a simple program to sum all the numbers from 0 to 1000000000.

result = i = 0
while i < 1000000000:
    result += i
    i += 1
print result

The time for this calculations was huge.  It took a long time to give
the result.  But, the corresponding program in Java takes less than 1
second to end.  And if in Java, we make a simple type check per cycle,
it does not take more than 10 seconds in the same machine.  I was not
expecting Python to be faster than Java, but it''s too slow.  Maybe
Java optimizes this case and Python doesn't.  Not sure about this.}

Thanks
ark

From stefan_ml at behnel.de  Fri Apr 16 09:38:23 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 16 Apr 2010 09:38:23 +0200
Subject: [Tutor] Loop comparison
In-Reply-To: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
Message-ID: <hq945f$9f9$1@dough.gmane.org>

Ark, 16.04.2010 08:50:
> A friend of mine suggested me to do the next experiment in python and Java.
>
> It's a simple program to sum all the numbers from 0 to 1000000000.
>
> result = i = 0
> while i<  1000000000:
>      result += i
>      i += 1
> print result

I hope you are aware that this is a) a very lousy benchmark and b) very 
unidiomatic Python code.


> The time for this calculations was huge.  It took a long time to give
> the result.  But, the corresponding program in Java takes less than 1
> second to end.  And if in Java, we make a simple type check per cycle,
> it does not take more than 10 seconds in the same machine.  I was not
> expecting Python to be faster than Java, but it''s too slow.  Maybe
> Java optimizes this case and Python doesn't.  Not sure about this.}

Exactly. A compiler for a statically compiled language can see that the 
above loop yields a constant result, so it can calculate the result in 
advance (or at least reduce the loop overhead for the calculation) instead 
of generating code for the loop as it stands.

The CPython runtime isn't particularly smart about arithmetic. You should 
first put the above loop into a function, which will speed it up 
considerably. Then, try the above code with psyco (a specialising JIT 
compiler). Or give PyPy a try, which should also be pretty good in this.

You can also try to run the code through Cython, which is (more or less) a 
Python compiler that supports static type annotations. You could write it 
like this (which is also a much more pythonic implementation):

     import cython

     @cython.locals(result=cython.longlong, i=cython.longlong)
     def add():
         result = 0
         for i in xrange(1000000000):
             result += i
         return result

     print add()

This runs in less than half a second on my machine, including the time to 
launch the CPython interpreter. I doubt that the JVM can even start up in 
that time.

Stefan


From cwitts at compuscan.co.za  Fri Apr 16 09:48:08 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Fri, 16 Apr 2010 09:48:08 +0200
Subject: [Tutor] Loop comparison
In-Reply-To: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
Message-ID: <4BC81638.90004@compuscan.co.za>

Ark wrote:
> Hi everyone.
> A friend of mine suggested me to do the next experiment in python and Java.
>
> It's a simple program to sum all the numbers from 0 to 1000000000.
>
> result = i = 0
> while i < 1000000000:
>     result += i
>     i += 1
> print result
>
> The time for this calculations was huge.  It took a long time to give
> the result.  But, the corresponding program in Java takes less than 1
> second to end.  And if in Java, we make a simple type check per cycle,
> it does not take more than 10 seconds in the same machine.  I was not
> expecting Python to be faster than Java, but it''s too slow.  Maybe
> Java optimizes this case and Python doesn't.  Not sure about this.}
>
> Thanks
> ark
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>   
Different methods and their relative benchmarks.  The last two functions 
are shortcuts for what you are trying to do, the last function 't5' 
corrects the mis-calculation 't4' has with odd numbers.
Remember, if you know a better way to do something you can always 
optimize yourself ;)

 >>> def t1(upper_bounds):
...   start = time.time()
...   total = sum((x for x in xrange(upper_bounds)))
...   end = time.time()
...   print 'Time taken: %s' % (end - start)
...   print total
...
 >>> t1(1000000000)
Time taken: 213.830082178
499999999500000000
 >>> def t2(upper_bounds):
...   total = 0
...   start = time.time()
...   for x in xrange(upper_bounds):
...     total += x
...   end = time.time()
...   print 'Time taken: %s' % (end - start)
...   print total
...
 >>> t2(1000000000)
Time taken: 171.760597944
499999999500000000
 >>> def t3(upper_bounds):
...   start = time.time()
...   total = sum(xrange(upper_bounds))
...   end = time.time()
...   print 'Time taken: %s' % (end - start)
...   print total
...
 >>> t3(1000000000)
Time taken: 133.12481904
499999999500000000
 >>> def t4(upper_bounds):
...   start = time.time()
...   mid = upper_bounds / 2
...   total = mid * upper_bounds - mid
...   end = time.time()
...   print 'Time taken: %s' % (end - start)
...   print total
...
 >>> t4(1000000000)
Time taken: 1.4066696167e-05
499999999500000000
 >>> def t5(upper_bounds):
...   start = time.time()
...   mid = upper_bounds / 2
...   if upper_bounds % 2:
...     total = mid * upper_bounds
...   else:
...     total = mid * upper_bounds - mid
...   end = time.time()
...   print 'Time taken: %s' % (end - start)
...   print total
...
 >>> t5(1000000000)
Time taken: 7.15255737305e-06
499999999500000000
 >>> t3(1999)
Time taken: 0.0038161277771
1997001
 >>> t4(1999)
Time taken: 3.09944152832e-06
1996002
 >>> t5(1999)
Time taken: 3.09944152832e-06
1997001

-- 
Kind Regards,
Christian Witts
Business Intelligence

C o m p u s c a n | Confidence in Credit

Telephone: +27 21 888 6000
National Cell Centre: 0861 51 41 31
Fax: +27 21 413 2424
E-mail: cwitts at compuscan.co.za

NOTE:  This e-mail (including attachments )is subject to the disclaimer published at: http://www.compuscan.co.za/live/content.php?Item_ID=494.
If you cannot access the disclaimer, request it from email.disclaimer at compuscan.co.za or 0861 514131.

National Credit Regulator Credit Bureau Registration No. NCRCB6 



From ppmeagher at gmail.com  Fri Apr 16 10:08:48 2010
From: ppmeagher at gmail.com (Peter Meagher)
Date: Fri, 16 Apr 2010 04:08:48 -0400
Subject: [Tutor] QUESTION REGARDING STATUS OF MY SUBSCRIPTION FW:
	Auto-response for your message to the "Tutor" mailing list
Message-ID: <001d01cadd3c$0c0b3dc0$2421b940$@com>

GREETINGS,

THIS EMAIL WOULD INDICATE THAT I AM ON THE SUBSCRIPTION
LIST.

HOWEVER, I GOT ANOTHER EMAIL, THAT CAME IN AT PRECISELY THE
SAME TIME AS THE ORIGINAL MESSAGE THAT I AM FORWARDING YOU.
THAT INDICATES THAT THERE WAS AN ISSUE ADDING ME TO THE
LIST. I'VE PASTED IT IN THE BLOCK OF TEXT BELOW, BUT ABOVE
THE EMAIL THAT I AM FORWARDING YOU.

THANK YOU FOR YOUR ATTENTION.
Peter Meagher



-------------------EMAIL INDICATING ISSUE PASTED BELOW

The results of your email command are provided below.
Attached is your original message.

- Results:
    Invalid confirmation string.  Note that confirmation
strings expire approximately 3 days after the initial
subscription request.  If your confirmation has expired,
please try to re-submit your original request or message.

- Unprocessed:
    RE: Your confirmation is required to join the Tutor
mailing list
    Thank you
    -----Original Message-----
    From: tutor-bounces+ppmeagher=gmail.com at python.org
    [mailto:tutor-bounces+ppmeagher=gmail.com at python.org] On
    Behalf Of
 
tutor-confirm+fe41d06d04b6e46925e0b5da4b2e115760b4f2bd at pytho
    n.org
    Sent: Friday, April 16, 2010 12:35 AM
    To: ppmeagher at gmail.com
    Subject: Your confirmation is required to join the Tutor
    mailing list
    Mailing list subscription confirmation notice for
mailing
    list Tutor
    We have received a request from 96.224.37.102 for
    subscription of your
    email address, "ppmeagher at gmail.com", to the
    tutor at python.org mailing
    list.  To confirm that you want to be added to this
mailing
    list,
    simply reply to this message, keeping the Subject:
header
    intact.  Or
    visit this web page:

- Ignored:
    
     
 
http://mail.python.org/mailman/confirm/tutor/fe41d06d04b6e46
    925e0b5da4b2e115760b4f2bd
    
    
    Or include the following line -- and only the following
line
    -- in a
    message to tutor-request at python.org:
    
        confirm fe41d06d04b6e46925e0b5da4b2e115760b4f2bd
    
    Note that simply sending a `reply' to this message
should
    work from
    most mail readers, since that usually leaves the
Subject:
    line in the
    right form (additional "Re:" text in the Subject: is
okay).
    
    If you do not wish to be subscribed to this list, please
    simply
    disregard this message.  If you think you are being
    maliciously
    subscribed to the list, or have any other questions,
send
    them to
    tutor-owner at python.org.
    

- Done.


-------------------END EMAIL INDICATING ISSUE PASTED ABOVE



-----Original Message-----
From: tutor-bounces+ppmeagher=gmail.com at python.org
[mailto:tutor-bounces+ppmeagher=gmail.com at python.org] On
Behalf Of tutor-bounces at python.org
Sent: Friday, April 16, 2010 1:34 AM
To: ppmeagher at gmail.com
Subject: Auto-response for your message to the "Tutor"
mailing list

Your message for tutor at python.org, the Python programming
tutor list,
has been received and is being delivered.  This automated
response is
sent to those of you new to the Tutor list, to point out a
few
resources that can help with answering your own questions,
or improve
the chances of getting a useful answer from the other
subscribers.

If your question is something akin to:

    "I've just heard about Python, and it sounds great!
Where can I
     find out more on how to program with Python?"

  or:

     "What's Python?"

please read section 1 below.

On the other hand, if your question is:
  
    "I've heard that Python is good for hacking -- I want to
know
more!"

  or

    "Can you teach me how to break into a computer with
Python?"

please read section 2 at the bottom of this email.

Section 1: ----------

The most comprehensive overview of python.org help resources
is at

  http://www.python.org/Help.html

The Python FAQ is available at

  http://www.python.org/doc/FAQ.html 

and it has answers to many questions that people ask,
possibly
including your question.  Another wealth of information and
experience
can be found via the python.org searches, at

  http://www.python.org/search/

There you'll find comprehensive, easy-to-use searches over
the
python.org web site and the Python newsgroup,
comp.lang.python.

Python has an online tutorial, available freely from

  http://www.python.org/doc/current/tutorial/index.html

Finally, when you do send email to the Tutor list, be as
clear as you
can about the problem, including, when relevant, details
like:

 - Precise error messages, including complete tracebacks    
 - The hardware platform (available in the Python sys module
as
sys.platform)
 - The python version (sys.version) 
 - The python search path (sys.path)

In general, be specific about what was going on connected
with the
problem or what specific concept you're having difficulties
with.  The
better the info you provide, the more likely the helpers
will be able
to glean the answer...

There's a HOWTO that shows how to ask "smart" questions to
technical
folks:

http://catb.org/~esr/faqs/smart-questions.html

Although it is provocative, it does have some good points,
and is an
interesting read.


Note that no one is paid to read the tutor list or provide
answers,
and most readers often have other work that demands their
attention.
Well-posed requests for help are usually answered fairly
promptly, but
occasionally a request slips by, so if you do not get a
response with
one or two working days (it's usually quicker than that),
please feel
free to send a followup, asking whether anyone is working on
your
question.

Anyway, your message is being delivered to the Tutor list as
this one
is being sent.  However, if your question was about as
detailed as
"Teach me how to program in Python", do not count on an
answer -- this
email contains all the information you need to start.  Come
back with
a more precise question, and we'll be glad to help.


Thanks!

Section 2: ----------

We periodically get requests which ask about hacking or
cracking or
breaking into computers.  If you haven't yet, go read Eric
Raymond's
article "How To Become a Hacker" at
  http://catb.org/esr/faqs/hacker-howto.html

If, after you've read that, you want help learning how to
hack the way
Eric defines the word, then come back to us (and read
Section 1
above).  If you want help learning how to crack, go look
elsewhere --
we're not interested in helping you do that.


From alan.gauld at btinternet.com  Fri Apr 16 10:09:23 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 16 Apr 2010 09:09:23 +0100
Subject: [Tutor] Loop comparison
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
Message-ID: <hq95vt$fnk$1@dough.gmane.org>


"Ark" <cloudneozero at gmail.com> wrote 

> It's a simple program to sum all the numbers from 0 to 1000000000.
> 
> result = i = 0
> while i < 1000000000:
>    result += i
>    i += 1
> print result
> 
> The time for this calculations was huge.  It took a long time to give
> the result.  But, the corresponding program in Java takes less than 1
> second to end.  

That's astonishing, it implies your PC is running at around 20GHz!
I want one! :-)

But Python will always be much slower for this kind of thing since Pythons 
integers are very different to Java ints (BTW did Java returtn an int or 
a float result?) Using something like psycho should yield a big improvement 
I suspect. Also some of the math libraries may have a native C summing 
function for large arrays. Even the built in sum() will be faster than a while 
loop:

result = sum(range(1000000000))

although it still took 10 minutes on my PC.

> And if in Java, we make a simple type check per cycle,
> it does not take more than 10 seconds in the same machine.  

That would be more like the kind of figure I'd expect.
Remember the time increases exponentialy. In my tests Python 
was sub 1s up to 10**7 then 10s for 10**8 and 600s for 10**9 )
Memory speed will play a big role here too since Pythons storage 
of large integers requires a lot of memory allocating/deallocating
compared to Java which uses native CPU integers

> I was not expecting Python to be faster than Java, but it''s too slow.  

For this kind of task yes. It was never designed for high speed 
number crunching. Thats why dedicated math modules have been 
written in C.

> Java optimizes this case and Python doesn't.  Not sure about this.}

The approaches are completely different. Java uses native ints, 
Python  uses arbitrarily long ints. Java's JVM will map closely 
to native CPU operations, Python is effectively calling functions.
This is almost a pathalogical case for comparing the two languages.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From stefan_ml at behnel.de  Fri Apr 16 10:25:54 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 16 Apr 2010 10:25:54 +0200
Subject: [Tutor] Loop comparison
In-Reply-To: <hq95vt$fnk$1@dough.gmane.org>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
	<hq95vt$fnk$1@dough.gmane.org>
Message-ID: <hq96uj$j45$1@dough.gmane.org>

Alan Gauld, 16.04.2010 10:09:
> Even the built in sum() will be faster than a while loop:
>
> result = sum(range(1000000000))
>
> although it still took 10 minutes on my PC.

Did you mean to say "minutes" or rather "seconds" here? And did you really 
mean to use "range" or rather "xrange" (or "range" in Py3)?

     sum(xrange(1000000000))

clearly runs in 12 seconds for me on Py2.6, whereas the same with "range" 
gives an error due to insufficient memory.

Stefan


From alan.gauld at btinternet.com  Fri Apr 16 10:29:40 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 16 Apr 2010 09:29:40 +0100
Subject: [Tutor] Loop comparison
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
	<hq945f$9f9$1@dough.gmane.org>
Message-ID: <hq975v$jtc$1@dough.gmane.org>

"Stefan Behnel" <stefan_ml at behnel.de> wrote 

>     import cython
> 
>     @cython.locals(result=cython.longlong, i=cython.longlong)
>     def add():
>         result = 0
>         for i in xrange(1000000000):
>             result += i
>         return result
> 
>     print add()
> 
> This runs in less than half a second on my machine, including the time to 
> launch the CPython interpreter. I doubt that the JVM can even start up in 
> that time.

I'm astonished at these results. What kind of C are you using. 
Even in assembler I'd expect the loop/sum to take at least 3s
on a quad core 3GHz box.

Or is cython doing the precalculation optimisations you mentioned?
And if so when does it do them? Because surely, at some stage, it 
still has to crank the numbers?

(We can of course do some fancy math to speed this particular 
sum up since the result for any power of ten has a common pattern, 
but I wouldn't expect the compiler optimiser to be that clever)


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From davea at ieee.org  Fri Apr 16 10:31:09 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 16 Apr 2010 04:31:09 -0400
Subject: [Tutor] Loop comparison
In-Reply-To: <4BC81638.90004@compuscan.co.za>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
	<4BC81638.90004@compuscan.co.za>
Message-ID: <4BC8204D.301@ieee.org>



Christian Witts wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Ark wrote:
>> Hi everyone.
>> A friend of mine suggested me to do the next experiment in python and 
>> Java.
>>
>> It's a simple program to sum all the numbers from 0 to 1000000000.
>>
>> result = i = 0
>> while i < 1000000000:
>>     result += i
>>     i += 1
>> print result
>>
>> The time for this calculations was huge.  It took a long time to give
>> the result.  But, the corresponding program in Java takes less than 1
>> second to end.  And if in Java, we make a simple type check per cycle,
>> it does not take more than 10 seconds in the same machine.  I was not
>> expecting Python to be faster than Java, but it''s too slow.  Maybe
>> Java optimizes this case and Python doesn't.  Not sure about this.}
>>
>> Thanks
>> ark
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>   
> Different methods and their relative benchmarks.  The last two 
> functions are shortcuts for what you are trying to do, the last 
> function 't5' corrects the mis-calculation 't4' has with odd numbers.
> Remember, if you know a better way to do something you can always 
> optimize yourself ;)
>
> >>> def t1(upper_bounds):
> ...   start = time.time()
> ...   total = sum((x for x in xrange(upper_bounds)))
> ...   end = time.time()
> ...   print 'Time taken: %s' % (end - start)
> ...   print total
> ...
> >>> t1(1000000000)
> Time taken: 213.830082178
> 499999999500000000
> >>> def t2(upper_bounds):
> ...   total = 0
> ...   start = time.time()
> ...   for x in xrange(upper_bounds):
> ...     total += x
> ...   end = time.time()
> ...   print 'Time taken: %s' % (end - start)
> ...   print total
> ...
> >>> t2(1000000000)
> Time taken: 171.760597944
> 499999999500000000
> >>> def t3(upper_bounds):
> ...   start = time.time()
> ...   total = sum(xrange(upper_bounds))
> ...   end = time.time()
> ...   print 'Time taken: %s' % (end - start)
> ...   print total
> ...
> >>> t3(1000000000)
> Time taken: 133.12481904
> 499999999500000000
> >>> def t4(upper_bounds):
> ...   start = time.time()
> ...   mid = upper_bounds / 2
> ...   total = mid * upper_bounds - mid
> ...   end = time.time()
> ...   print 'Time taken: %s' % (end - start)
> ...   print total
> ...
> >>> t4(1000000000)
> Time taken: 1.4066696167e-05
> 499999999500000000
> >>> def t5(upper_bounds):
> ...   start = time.time()
> ...   mid = upper_bounds / 2
> ...   if upper_bounds % 2:
> ...     total = mid * upper_bounds
> ...   else:
> ...     total = mid * upper_bounds - mid
> ...   end = time.time()
> ...   print 'Time taken: %s' % (end - start)
> ...   print total
> ...
> >>> t5(1000000000)
> Time taken: 7.15255737305e-06
> 499999999500000000
> >>> t3(1999)
> Time taken: 0.0038161277771
> 1997001
> >>> t4(1999)
> Time taken: 3.09944152832e-06
> 1996002
> >>> t5(1999)
> Time taken: 3.09944152832e-06
> 1997001
>
A simpler formula is simply
    upper_bounds * (upper_bounds-1) / 2

No check needed for even/odd.

DaveA

From stefan_ml at behnel.de  Fri Apr 16 10:35:26 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 16 Apr 2010 10:35:26 +0200
Subject: [Tutor] Loop comparison
In-Reply-To: <hq945f$9f9$1@dough.gmane.org>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
	<hq945f$9f9$1@dough.gmane.org>
Message-ID: <hq97gm$l51$1@dough.gmane.org>

Stefan Behnel, 16.04.2010 09:38:
> A compiler for a statically compiled language can see that the
> above loop yields a constant result, so it can calculate the result in
> advance (or at least reduce the loop overhead for the calculation)
> instead of generating code for the loop as it stands.

That reminds me of an optimisation anecdote I experienced during a talk I 
gave on Cython. I was showing how a couple of simple type annotations could 
be used to make Cython run arithmetic code a couple of hundred times faster 
than it runs in CPython. A tiny little change at the end brought the factor 
from about 200x to an increadible 18000x. That was still one order of 
magniture larger than the highest speedup I had seen from Cython up to 
then, so I was perplex at the time and had to take a deeper look.

It turned out that this was exactly the point where Cython had enough type 
annotations available to make the Python code turn completely into C code, 
so the C compiler noticed that the whole benchmark code didn't actually 
yield any result, optimised away the whole thing and just wrote out an 
empty module. A tremendous speedup, obviously...

Stefan


From cwitts at compuscan.co.za  Fri Apr 16 10:46:03 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Fri, 16 Apr 2010 10:46:03 +0200
Subject: [Tutor] Loop comparison
In-Reply-To: <hq975v$jtc$1@dough.gmane.org>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>	<hq945f$9f9$1@dough.gmane.org>
	<hq975v$jtc$1@dough.gmane.org>
Message-ID: <4BC823CB.9020509@compuscan.co.za>

Alan Gauld wrote:
> "Stefan Behnel" <stefan_ml at behnel.de> wrote
>>     import cython
>>
>>     @cython.locals(result=cython.longlong, i=cython.longlong)
>>     def add():
>>         result = 0
>>         for i in xrange(1000000000):
>>             result += i
>>         return result
>>
>>     print add()
>>
>> This runs in less than half a second on my machine, including the 
>> time to launch the CPython interpreter. I doubt that the JVM can even 
>> start up in that time.
>
> I'm astonished at these results. What kind of C are you using. Even in 
> assembler I'd expect the loop/sum to take at least 3s
> on a quad core 3GHz box.
>
> Or is cython doing the precalculation optimisations you mentioned?
> And if so when does it do them? Because surely, at some stage, it 
> still has to crank the numbers?
>
> (We can of course do some fancy math to speed this particular sum up 
> since the result for any power of ten has a common pattern, but I 
> wouldn't expect the compiler optimiser to be that clever)
>
>

The precalculation optimisations are taking place.  If you pass it an 
argument to use for the upper limit of the sequence the calculation time 
shoots up.

-- 
Kind Regards,
Christian Witts



From cwitts at compuscan.co.za  Fri Apr 16 10:49:05 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Fri, 16 Apr 2010 10:49:05 +0200
Subject: [Tutor] Loop comparison
In-Reply-To: <4BC8204D.301@ieee.org>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
	<4BC81638.90004@compuscan.co.za> <4BC8204D.301@ieee.org>
Message-ID: <4BC82481.5060004@compuscan.co.za>

Dave Angel wrote:
>
>
> Christian Witts wrote:
>> <div class="moz-text-flowed" style="font-family: -moz-fixed">Ark wrote:
>>> Hi everyone.
>>> A friend of mine suggested me to do the next experiment in python 
>>> and Java.
>>>
>>> It's a simple program to sum all the numbers from 0 to 1000000000.
>>>
>>> result = i = 0
>>> while i < 1000000000:
>>>     result += i
>>>     i += 1
>>> print result
>>>
>>> The time for this calculations was huge.  It took a long time to give
>>> the result.  But, the corresponding program in Java takes less than 1
>>> second to end.  And if in Java, we make a simple type check per cycle,
>>> it does not take more than 10 seconds in the same machine.  I was not
>>> expecting Python to be faster than Java, but it''s too slow.  Maybe
>>> Java optimizes this case and Python doesn't.  Not sure about this.}
>>>
>>> Thanks
>>> ark
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>   
>> Different methods and their relative benchmarks.  The last two 
>> functions are shortcuts for what you are trying to do, the last 
>> function 't5' corrects the mis-calculation 't4' has with odd numbers.
>> Remember, if you know a better way to do something you can always 
>> optimize yourself ;)
>>
>> >>> def t1(upper_bounds):
>> ...   start = time.time()
>> ...   total = sum((x for x in xrange(upper_bounds)))
>> ...   end = time.time()
>> ...   print 'Time taken: %s' % (end - start)
>> ...   print total
>> ...
>> >>> t1(1000000000)
>> Time taken: 213.830082178
>> 499999999500000000
>> >>> def t2(upper_bounds):
>> ...   total = 0
>> ...   start = time.time()
>> ...   for x in xrange(upper_bounds):
>> ...     total += x
>> ...   end = time.time()
>> ...   print 'Time taken: %s' % (end - start)
>> ...   print total
>> ...
>> >>> t2(1000000000)
>> Time taken: 171.760597944
>> 499999999500000000
>> >>> def t3(upper_bounds):
>> ...   start = time.time()
>> ...   total = sum(xrange(upper_bounds))
>> ...   end = time.time()
>> ...   print 'Time taken: %s' % (end - start)
>> ...   print total
>> ...
>> >>> t3(1000000000)
>> Time taken: 133.12481904
>> 499999999500000000
>> >>> def t4(upper_bounds):
>> ...   start = time.time()
>> ...   mid = upper_bounds / 2
>> ...   total = mid * upper_bounds - mid
>> ...   end = time.time()
>> ...   print 'Time taken: %s' % (end - start)
>> ...   print total
>> ...
>> >>> t4(1000000000)
>> Time taken: 1.4066696167e-05
>> 499999999500000000
>> >>> def t5(upper_bounds):
>> ...   start = time.time()
>> ...   mid = upper_bounds / 2
>> ...   if upper_bounds % 2:
>> ...     total = mid * upper_bounds
>> ...   else:
>> ...     total = mid * upper_bounds - mid
>> ...   end = time.time()
>> ...   print 'Time taken: %s' % (end - start)
>> ...   print total
>> ...
>> >>> t5(1000000000)
>> Time taken: 7.15255737305e-06
>> 499999999500000000
>> >>> t3(1999)
>> Time taken: 0.0038161277771
>> 1997001
>> >>> t4(1999)
>> Time taken: 3.09944152832e-06
>> 1996002
>> >>> t5(1999)
>> Time taken: 3.09944152832e-06
>> 1997001
>>
> A simpler formula is simply
>    upper_bounds * (upper_bounds-1) / 2
>
> No check needed for even/odd.
>
> DaveA
>
Ah yes, that is true. :)
Sometimes I feel I overlook the simplest of solutions.

-- 
Kind Regards,
Christian Witts



From davea at ieee.org  Fri Apr 16 10:45:11 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 16 Apr 2010 04:45:11 -0400
Subject: [Tutor] QUESTION REGARDING STATUS OF MY SUBSCRIPTION
 FW:	Auto-response for your message to the "Tutor" mailing list
In-Reply-To: <001d01cadd3c$0c0b3dc0$2421b940$@com>
References: <001d01cadd3c$0c0b3dc0$2421b940$@com>
Message-ID: <4BC82397.5060908@ieee.org>

Peter Meagher wrote:
> GREETINGS,
>
> THIS EMAIL WOULD INDICATE THAT I AM ON THE SUBSCRIPTION
> LIST.
>
> HOWEVER, I GOT ANOTHER EMAIL, THAT CAME IN AT PRECISELY THE
> SAME TIME AS THE ORIGINAL MESSAGE THAT I AM FORWARDING YOU.
> THAT INDICATES THAT THERE WAS AN ISSUE ADDING ME TO THE
> LIST. I'VE PASTED IT IN THE BLOCK OF TEXT BELOW, BUT ABOVE
> THE EMAIL THAT I AM FORWARDING YOU.
>
> THANK YOU FOR YOUR ATTENTION.
> Peter Meagher
>
> <snip>
> <snip>    
>     If you do not wish to be subscribed to this list, please
>     simply
>     disregard this message.  If you think you are being
>     maliciously
>     subscribed to the list, or have any other questions,
> send
>     them to
>     tutor-owner at python.org.
>     
>
>   
That explains where you go with subscription questions.  The address is 
NOT the same as the one used for posting on the list.  I suspect you 
didn't correctly reply to the original message.

Your other message is an independent point.  It has nothing to do with 
whether you're subscribed or not, but simply is an acknowledgement that 
you're a new poster to the list, and includes some suggestions.  In 
fact, I get that message sometimes, even though I was 3rd highest poster 
here last year.  It's perfectly legal to post without being a 
subscriber, as you could be browing the messages online.

BTW, all upper-case is considered shouting.  It makes a message much 
harder to read, and more likely to be ignored.

DaveA

From stefan_ml at behnel.de  Fri Apr 16 10:52:31 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 16 Apr 2010 10:52:31 +0200
Subject: [Tutor] Loop comparison
In-Reply-To: <hq975v$jtc$1@dough.gmane.org>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>	<hq945f$9f9$1@dough.gmane.org>
	<hq975v$jtc$1@dough.gmane.org>
Message-ID: <hq98gf$od7$1@dough.gmane.org>

Alan Gauld, 16.04.2010 10:29:
> "Stefan Behnel" wrote
>> import cython
>>
>> @cython.locals(result=cython.longlong, i=cython.longlong)
>> def add():
>>     result = 0
>>     for i in xrange(1000000000):
>>         result += i
>>     return result
>>
>> print add()
>>
>> This runs in less than half a second on my machine, including the time
>> to launch the CPython interpreter. I doubt that the JVM can even start
>> up in that time.
>
> I'm astonished at these results. What kind of C are you using. Even in
> assembler I'd expect the loop/sum to take at least 3s
> on a quad core 3GHz box.
 >
> Or is cython doing the precalculation optimisations you mentioned?

Nothing surprising in the C code:

   __pyx_v_result = 0;
   for (__pyx_t_1 = 0; __pyx_t_1 < 1000000000; __pyx_t_1+=1) {
     __pyx_v_i = __pyx_t_1;
     __pyx_v_result += __pyx_v_i;
   }


> And if so when does it do them? Because surely, at some stage, it still
> has to crank the numbers?

Cython does a bit of constant folding (which it can benefit from on 
internal optimisation decisions), but apart from that, the mantra is to 
just show the C compiler explicit C code that it can understand well, and 
let it do its job.


> (We can of course do some fancy math to speed this particular sum up
> since the result for any power of ten has a common pattern, but I
> wouldn't expect the compiler optimiser to be that clever)

In this particular case, the C compiler really stores the end result in the 
binary module, so I assume that it simply applies Little Gau? as an 
optimisation in combination with loop variable aliasing.

Stefan


From crp at cmc.net  Fri Apr 16 10:57:31 2010
From: crp at cmc.net (Ray Parrish)
Date: Fri, 16 Apr 2010 01:57:31 -0700
Subject: [Tutor] Passing headers with httplib
In-Reply-To: <4BC7E22C.8010901@cmc.net>
References: <4BC7E22C.8010901@cmc.net>
Message-ID: <4BC8267B.4010809@cmc.net>

Ray Parrish wrote:
> Hello,
>
> I am trying to figure out how to send cookie data with an httplib 
> request command. Here is what the doc says -
>
> request(      method, url[, body[, headers]])
>    This will send a request to the server using the HTTP request 
> method method and the selector url. If the body argument is present, 
> it should be a string of data to send after the headers are finished. 
> The header Content-Length is automatically set to the correct value. 
> The headers argument should be a mapping of extra HTTP headers to send 
> with the request.
>
> My question is how do I formulate a "mapping" of a header for a few 
> cookies? Here are the cookies I would like to send with the request -
>
> TVGID=029690D849714243A9DDEA34652CA804; Provider=Broadcast; 
> __qca=P0-547310088-1271379357584; 
> LastGrid=fmt=0&srvid=20442&gridmins=120&gridyr=2010&gridmo=4&griddy=15&gridhr=20&chanrow=1&genre=0&favchan=false&magic=1269|9898&magictype=0&zip=&music=1&ppv=1&24hr=1&HDTVOnly=false; 
> s_cc=true; s_sq=%5B%5BB%5D%5D; wtpgcnt=1; 
> s_vi=[CS]v1|25E3DAD0050118C7-6000010E60004530[CE]; 
> base_domain_4631b4ff1e53d450c3f9726dd45be7de=tvguide.com; 
> rsi_ct=2010_4_15:6;
>
> Thanks for any help you can be, Ray Parrish
OK,  I got it figured, but still no luck, passing the cookies didn't 
help me get at the search results I was trying to get. Here is the code 
for passing cookies -

connection = httplib.HTTPConnection("www.tvguide.com", port)
connection.putrequest("GET", "/listings/default.aspx?keyword=Star+Trek")
connection.putheader("Cookie", "TVGID=029690D849714243A9DDEA34652CA804; 
Provider=Broadcast; __qca=P0-547310088-1271379357584; 
LastGrid=fmt=0&srvid=20442&gridmins=120&gridyr=2010&gridmo=4&griddy=15&gridhr=20&chanrow=1&genre=0&favchan=false&magic=1269|9898&magictype=0&zip=&music=1&ppv=1&24hr=1&HDTVOnly=false; 
s_cc=true; s_sq=%5B%5BB%5D%5D; wtpgcnt=1; 
s_vi=[CS]v1|25E3DAD0050118C7-6000010E60004530[CE]; 
base_domain_4631b4ff1e53d450c3f9726dd45be7de=tvguide.com; 
rsi_ct=2010_4_15:8; 
rsi_segs=D04451_10006|D04451_10077|D04451_10089|D04451_10116; 
__utma=208178903.2088698592.1271379370.1271389872.1271398039.3; 
__utmc=208178903; 
__utmz=208178903.1271398041.3.3.utmccn=(referral)|utmcsr=tvguide.com|utmcct=/search/index.aspx|utmcmd=referral; 
zip=97424; ServiceID=20442; srvid=20442; ev1=star%20trek;")
connection.endheaders()
response = connection.getresponse()
headers = response.getheaders()
print headers
fileContents = response.read()

Later, Ray Parrish

-- 
Linux dpkg Software Report script set..
http://www.rayslinks.com/LinuxdpkgSoftwareReport.html
Ray's Links, a variety of links to usefull things, and articles by Ray.
http://www.rayslinks.com
Writings of "The" Schizophrenic, what it's like to be a schizo, and other
things, including my poetry.
http://www.writingsoftheschizophrenic.com



From alan.gauld at btinternet.com  Fri Apr 16 11:05:54 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Fri, 16 Apr 2010 09:05:54 +0000 (GMT)
Subject: [Tutor] Loop comparison
In-Reply-To: <4BC823CB.9020509@compuscan.co.za>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
	<hq945f$9f9$1@dough.gmane.org> <hq975v$jtc$1@dough.gmane.org>
	<4BC823CB.9020509@compuscan.co.za>
Message-ID: <571832.52910.qm@web86701.mail.ird.yahoo.com>



> The precalculation optimisations are 
> taking place.  If you pass it an argument to use for the upper limit of the 
> sequence the calculation time shoots up.

I'm still confused about when the addition takes place. 
Surely the compiler has to do the addition, so it should be slower?
I assume you have to run the posted code through cython
prior to running it in Python?

You can probably tell that I've never used Cython! :-)

Alan G.

From ppmeagher at gmail.com  Fri Apr 16 11:13:24 2010
From: ppmeagher at gmail.com (Peter Meagher)
Date: Fri, 16 Apr 2010 05:13:24 -0400
Subject: [Tutor] Python Examples of processing MS Outlook
Message-ID: <003001cadd45$128a5ce0$379f16a0$@com>

Greetings,

 

I'm doing a lot of email processing at the moment.  I put
together some basic code from within Outlook to open my
default inbox, filter email records based on text in the
Subject field, then parse the body, finally send the output
to a text file.  This is simple stuff but very useful.

 

I need to do more, however as a newbie with Python, I
figured I could both learn and produce at the same time.

 

Does anyone have references to simple MS Outlook 2007
processing code that I could vulture for my purposes?  (The
code that I adapted was from an old Office 2000 vba text, so
the version 2007 may not be that essential to my purposes)

 

After much searching, I found a reference to PyWebmail,
however it communicates directly to the webmail accounts, is
much more than I really need and I want to stay in the
Outlook environment for a number of reasons, particularly
its interface to Access.

 

Thank you.

Peter Meagher

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100416/f7bc3c41/attachment.html>

From steve at pearwood.info  Fri Apr 16 12:00:30 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 16 Apr 2010 20:00:30 +1000
Subject: [Tutor] Loop comparison
In-Reply-To: <hq975v$jtc$1@dough.gmane.org>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
	<hq945f$9f9$1@dough.gmane.org> <hq975v$jtc$1@dough.gmane.org>
Message-ID: <201004162000.31628.steve@pearwood.info>

On Fri, 16 Apr 2010 06:29:40 pm Alan Gauld wrote:
> "Stefan Behnel" <stefan_ml at behnel.de> wrote
>
> >     import cython
> >
> >     @cython.locals(result=cython.longlong, i=cython.longlong)
> >     def add():
> >         result = 0
> >         for i in xrange(1000000000):
> >             result += i
> >         return result
> >
> >     print add()
[...]
> Or is cython doing the precalculation optimisations you mentioned?
> And if so when does it do them? Because surely, at some stage, it
> still has to crank the numbers?
>
> (We can of course do some fancy math to speed this particular
> sum up since the result for any power of ten has a common pattern,
> but I wouldn't expect the compiler optimiser to be that clever)

No fancy maths needed, although I'd be amazed (in a good way) to learn 
that compiler compiler optimizers recognised this case! Are optimizing 
compilers really that clever these days?

The sum of 1,2,3,4,...,N is given by a simple formula: 1/2*N*(N+1). An 
anecdote about the great mathematician Carl Gauss is that while still a 
very young child in primary school, his teacher assigned the class the 
problem of adding the numbers 1 through 100 in order to keep them 
occupied for an hour or so. To his astonishment, Gauss gave him the 
answer within seconds. He reasoned like this:

sum =   1 +  2 +  3 +  4 + ... + 99 + 100
sum = 100 + 99 + 98 + 97 + ... +  2 +   1
2*sum = 101 + 101 + 101 + ... 101
      = 100*101

so sum = 1/2 * 100 * 101 = 5050

While it is uncertain whether this specific story is actually true, it 
is certain that Gauss was a child prodigy and a genius of the first 
degree.


-- 
Steven D'Aprano

From steve at pearwood.info  Fri Apr 16 12:02:50 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 16 Apr 2010 20:02:50 +1000
Subject: [Tutor] Loop comparison
In-Reply-To: <hq96uj$j45$1@dough.gmane.org>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
	<hq95vt$fnk$1@dough.gmane.org> <hq96uj$j45$1@dough.gmane.org>
Message-ID: <201004162002.50292.steve@pearwood.info>

On Fri, 16 Apr 2010 06:25:54 pm Stefan Behnel wrote:
> Alan Gauld, 16.04.2010 10:09:
> > Even the built in sum() will be faster than a while loop:
> >
> > result = sum(range(1000000000))
> >
> > although it still took 10 minutes on my PC.
>
> Did you mean to say "minutes" or rather "seconds" here? And did you
> really mean to use "range" or rather "xrange" (or "range" in Py3)?
>
>      sum(xrange(1000000000))
>
> clearly runs in 12 seconds for me on Py2.6, 

7 minutes for me in Python 2.5. The joys of low end hardware!

Are you sure you got the right number of zeroes?

> whereas the same with 
> "range" gives an error due to insufficient memory.

I'm not even going to try...




-- 
Steven D'Aprano

From stefan_ml at behnel.de  Fri Apr 16 13:03:02 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 16 Apr 2010 13:03:02 +0200
Subject: [Tutor] Loop comparison
In-Reply-To: <201004162000.31628.steve@pearwood.info>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>	<hq945f$9f9$1@dough.gmane.org>
	<hq975v$jtc$1@dough.gmane.org>
	<201004162000.31628.steve@pearwood.info>
Message-ID: <hq9g56$k82$1@dough.gmane.org>

Steven D'Aprano, 16.04.2010 12:00:
> On Fri, 16 Apr 2010 06:29:40 pm Alan Gauld wrote:
>> "Stefan Behnel"  wrote
>>
>>>      import cython
>>>
>>>      @cython.locals(result=cython.longlong, i=cython.longlong)
>>>      def add():
>>>          result = 0
>>>          for i in xrange(1000000000):
>>>              result += i
>>>          return result
>>>
>>>      print add()
> [...]
>> Or is cython doing the precalculation optimisations you mentioned?
>> And if so when does it do them? Because surely, at some stage, it
>> still has to crank the numbers?
>>
>> (We can of course do some fancy math to speed this particular
>> sum up since the result for any power of ten has a common pattern,
>> but I wouldn't expect the compiler optimiser to be that clever)
>
> No fancy maths needed, although I'd be amazed (in a good way) to learn
> that compiler compiler optimizers recognised this case! Are optimizing
> compilers really that clever these days?

If I was writing an optimising C compiler, I'd certainly put this in to 
show off in common benchmarks. ;-)

Stefan


From lie.1296 at gmail.com  Fri Apr 16 13:20:02 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Fri, 16 Apr 2010 21:20:02 +1000
Subject: [Tutor] Loop comparison
In-Reply-To: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
Message-ID: <hq9h7h$ojd$1@dough.gmane.org>

On 04/16/10 16:50, Ark wrote:
> Hi everyone.
> A friend of mine suggested me to do the next experiment in python and Java.
> 
> It's a simple program to sum all the numbers from 0 to 1000000000.
> 
> result = i = 0
> while i < 1000000000:
>     result += i
>     i += 1
> print result
> 

Are you sure you're not causing Java to overflow here? In Java,
Arithmetic Overflow do not cause an Exception, your int will simply wrap
to the negative side.


From davea at ieee.org  Fri Apr 16 15:37:03 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 16 Apr 2010 09:37:03 -0400
Subject: [Tutor] Loop comparison
In-Reply-To: <571832.52910.qm@web86701.mail.ird.yahoo.com>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>	<hq945f$9f9$1@dough.gmane.org>
	<hq975v$jtc$1@dough.gmane.org>	<4BC823CB.9020509@compuscan.co.za>
	<571832.52910.qm@web86701.mail.ird.yahoo.com>
Message-ID: <4BC867FF.9080006@ieee.org>

ALAN GAULD wrote:
>   
>> The precalculation optimisations are 
>> taking place.  If you pass it an argument to use for the upper limit of the 
>> sequence the calculation time shoots up.
>>     
>
> I'm still confused about when the addition takes place. 
> Surely the compiler has to do the addition, so it should be slower?
> I assume you have to run the posted code through cython
> prior to running it in Python?
>
> You can probably tell that I've never used Cython! :-)
>
> Alan G.
>
>   
I've never used Cython either, but I'd guess that it's the C compiler 
doing the extreme optimizing.  If all the code, including the loop 
parameters, are local, non-volatile, and known at compile time, the 
compile could do the arithmetic at compile time, and just store a result 
like    res = 42;

Or it could notice that there's no I/O done, so that the program has 
null effect.  And optimize the whole thing into a "sys.exit()"

I don't know if any compiler does that level of optimizing, but it's 
certainly a possibility.  And such optimizations might not be legitimate 
in stock Python (without type declarations and other assumptions), 
because of the possibility of other code changing the type of globals, 
or overriding various special functions.

DaveA


From alan.gauld at btinternet.com  Sat Apr 17 01:40:39 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Apr 2010 00:40:39 +0100
Subject: [Tutor] Loop comparison
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com><hq945f$9f9$1@dough.gmane.org>
	<hq975v$jtc$1@dough.gmane.org>
	<201004162000.31628.steve@pearwood.info>
Message-ID: <hqasi3$ten$1@dough.gmane.org>


"Steven D'Aprano" <steve at pearwood.info> wrote

>> (We can of course do some fancy math to speed this particular
>> sum up since the result for any power of ten has a common pattern,
>> but I wouldn't expect the compiler optimiser to be that clever)
> 
> No fancy maths needed, 

> The sum of 1,2,3,4,...,N is given by a simple formula: 1/2*N*(N+1). 

Depends how you define fancy... I count that as pretty fancy maths 
for a compiler optimiser to recognise! :-)

> anecdote about the great mathematician Carl Gauss 

I like it! I hadn't come across that one before.

Alan G.


From alan.gauld at btinternet.com  Sat Apr 17 01:47:46 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Apr 2010 00:47:46 +0100
Subject: [Tutor] Loop comparison
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com><hq95vt$fnk$1@dough.gmane.org>
	<hq96uj$j45$1@dough.gmane.org>
	<201004162002.50292.steve@pearwood.info>
Message-ID: <hqasvd$ug0$1@dough.gmane.org>

>> > result = sum(range(1000000000))
>> >
>> > although it still took 10 minutes on my PC.
>>
>> Did you mean to say "minutes" or rather "seconds" here? And did you
>> really mean to use "range" or rather "xrange" (or "range" in Py3)?

Yes, minutes and in Python 3.
And on a 2.8GHz 2 core CPU with 2G RAM

>>      sum(xrange(1000000000))
>>
>> clearly runs in 12 seconds for me on Py2.6, 

Well over a minute on 2.5 under Cygwin.
Dropping by an order of magnitude took it down to 17 secs
Which is exactly the same in Python 3...

Alan G.



From alan.gauld at btinternet.com  Sat Apr 17 01:51:07 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Apr 2010 00:51:07 +0100
Subject: [Tutor] Loop comparison
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>
	<hq9h7h$ojd$1@dough.gmane.org>
Message-ID: <hqat5m$v01$1@dough.gmane.org>

"Lie Ryan" <lie.1296 at gmail.com> wrote

>> A friend of mine suggested me to do the next experiment in python and Java.
>> It's a simple program to sum all the numbers from 0 to 1000000000.
>> 
>> result = i = 0
>> while i < 1000000000:
>>     result += i
>>     i += 1
>> print result
>> 
> 
> Are you sure you're not causing Java to overflow here? In Java,
> Arithmetic Overflow do not cause an Exception, your int will simply wrap
> to the negative side.

Thats why I asked if he got a float number back.
I never thought of it just wrapping, I assumed it would convert to floats.

Now that would be truly amusing.
If Java gives you the wrong answer much faster than Python 
gives the right one, which is best in that scenario?! :-)

Alan G.



From cloudneozero at gmail.com  Sat Apr 17 04:37:25 2010
From: cloudneozero at gmail.com (Ark)
Date: Fri, 16 Apr 2010 21:37:25 -0500
Subject: [Tutor] Loop comparison
In-Reply-To: <v2h9dd22c9c1004160848u5f1ae115h4993c029b798bda1@mail.gmail.com>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com> 
	<hq9h7h$ojd$1@dough.gmane.org>
	<v2h9dd22c9c1004160848u5f1ae115h4993c029b798bda1@mail.gmail.com>
Message-ID: <x2u9dd22c9c1004161937o498de5d6k4f6fd6b53596c402@mail.gmail.com>

Hi.
Thanks for everyone answers. ?It's true, hehe, it's not a ?benchmark
or anything like that. ?I hadn't taken into account compiler
optimizations, but I have learnt a lot in this thread.

About the Java code, Bigints are used.

ark

From alexandertelford at gmail.com  Fri Apr 16 11:19:59 2010
From: alexandertelford at gmail.com (Alexander Telford)
Date: Fri, 16 Apr 2010 10:19:59 +0100
Subject: [Tutor] Please sponsor me to run the Virgin London Marathon
Message-ID: <92f8e3398c8570954e2d869ee74e72a1@www.thekaraokenetwork.com>

Hi,

Next Sunday I am going to run the London Marathon to raise money for Treehouse: an educational charity for children with autism that is very close to
my heart.

Autism is a condition which my cousin James and hundreds of thousands of other people in the UK suffer from. It impairs their ability to communicate
and relate to the world in general. When James was very young, his parents (my uncle and aunt) and 3 other sets of parents set up Treehouse as a
specialist school for children with autism, as there was really nowhere else suitable around at the time. Since then, Treehouse has grown from a
school with 4 pupils, into a school with almost 100. Treehouse has also become a national autism charity, undertaking policy and parliamentary work
and research to ensure autism is a national priority. The charity supports parents to campaign locally and offers training and consultancy on autism
education.

Treehouse provides children with an education that is vitally important to them and their families. It gives people with autism from all over the UK
the chance to lead a better, more independent and more fulfilling life.

Please help me to raise money for this most worthy cause by visiting my sponsorship page: http://uk.virginmoneygiving.com/alexandertelford

Thank you for all your support! It really means a lot to me,

Alex


From stephen at xemacs.org  Sat Apr 17 07:55:01 2010
From: stephen at xemacs.org (Stephen J. Turnbull)
Date: Sat, 17 Apr 2010 14:55:01 +0900
Subject: [Tutor] [Python-ideas] "value" ~ "data" ~ "object"
In-Reply-To: <hqasaa$srh$1@dough.gmane.org>
References: <20100415133702.78f1394b@o> <hq80vp$h2h$1@dough.gmane.org>
	<hq9feq$i1c$1@dough.gmane.org> <hqasaa$srh$1@dough.gmane.org>
Message-ID: <87pr1yoc7e.fsf@uwakimon.sk.tsukuba.ac.jp>

Alan Gauld writes:

 > Ooh I was deliverately steering clear of the distinctions between data, 
 > information and knowledge! There lie religious wars! :-)

That's precisely why Guido says "don't say 'data' in this context."

It's not your choice to steer clear of those differences of
definition, it's your reader's, and she is not going to be aware that
it's necessary unless you explain.  You can't win here.


From davea at ieee.org  Sat Apr 17 10:47:55 2010
From: davea at ieee.org (Dave Angel)
Date: Sat, 17 Apr 2010 04:47:55 -0400
Subject: [Tutor] Loop comparison
In-Reply-To: <hqat5m$v01$1@dough.gmane.org>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>	<hq9h7h$ojd$1@dough.gmane.org>
	<hqat5m$v01$1@dough.gmane.org>
Message-ID: <4BC975BB.8010404@ieee.org>

Alan Gauld wrote:
> "Lie Ryan" <lie.1296 at gmail.com> wrote
>
>>> A friend of mine suggested me to do the next experiment in python 
>>> and Java.
>>> It's a simple program to sum all the numbers from 0 to 1000000000.
>>>
>>> result = i = 0
>>> while i < 1000000000:
>>>     result += i
>>>     i += 1
>>> print result
>>>
>>
>> Are you sure you're not causing Java to overflow here? In Java,
>> Arithmetic Overflow do not cause an Exception, your int will simply wrap
>> to the negative side.
>
> Thats why I asked if he got a float number back.
> I never thought of it just wrapping, I assumed it would convert to 
> floats.
>
> Now that would be truly amusing.
> If Java gives you the wrong answer much faster than Python gives the 
> right one, which is best in that scenario?! :-)
>
> Alan G.
>
It's been years, but I believe Java ints are 64 bits, on a 32bit 
implementation.  Just like Java strings are all unicode.

DaveA


From stefan_ml at behnel.de  Sat Apr 17 11:07:32 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sat, 17 Apr 2010 11:07:32 +0200
Subject: [Tutor] Loop comparison
In-Reply-To: <4BC975BB.8010404@ieee.org>
References: <n2u9dd22c9c1004152350hca3628f0s14e24b9e425f64ab@mail.gmail.com>	<hq9h7h$ojd$1@dough.gmane.org>	<hqat5m$v01$1@dough.gmane.org>
	<4BC975BB.8010404@ieee.org>
Message-ID: <hqbtol$7tm$1@dough.gmane.org>

Dave Angel, 17.04.2010 10:47:
> Alan Gauld wrote:
>> "Lie Ryan" wrote
>>
>>>> A friend of mine suggested me to do the next experiment in python
>>>> and Java.
>>>> It's a simple program to sum all the numbers from 0 to 1000000000.
>>>>
>>>> result = i = 0
>>>> while i < 1000000000:
>>>> result += i
>>>> i += 1
>>>> print result
>>>>
>>>
>>> Are you sure you're not causing Java to overflow here? In Java,
>>> Arithmetic Overflow do not cause an Exception, your int will simply wrap
>>> to the negative side.
>>
>> Thats why I asked if he got a float number back.
>> I never thought of it just wrapping, I assumed it would convert to
>> floats.
>
> It's been years, but I believe Java ints are 64 bits, on a 32bit
> implementation. Just like Java strings are all unicode.

Java has a 32bit 'int' and a 64bit 'long'.

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html

Both will work just fine for 'i', but 'result' requires a 64 bit long:

    >>> 1000000000 < 2**31
    True
    >>> 2**31 < 499999999500000000 < 2**63
    True

Stefan


From ppmeagher at gmail.com  Sat Apr 17 11:40:32 2010
From: ppmeagher at gmail.com (Peter Meagher)
Date: Sat, 17 Apr 2010 05:40:32 -0400
Subject: [Tutor] Can Anyone help with SMTP processiing
Message-ID: <000601cade12$079519b0$16bf4d10$@com>

Greetings,

 

I'm a newbie with Python. Passable with other languages e.g.
Basic, C++ and others.  

 

Not a programmer per se, just trying to get work done that
happens to require some programming skills and want to try
my hand with Python.

 

Email processing and parsing is the focus of my tasks at
present.

 

Therefore, to get started,  I tried the following code
copied and pasted from 

 

http://docs.python.org/library/smtplib.html

 

First time through, I got the prompts indicated in the code,
except when I entered the ctrl Z nothing happened.

 

The next time and subsequent times, thereafter I get the
following 2 pop up message windows:

 

 

IDLE Sub process Error

Socket error: No connection could be made because the target
machine actively refused it

 

Sub process Startup Error

IDLE's sub process didn't make connection. Either IDLE can't
start a sub process or personal firewall software is
blocking the connection

 

Code copied and pasted from
http://docs.python.org/library/smtplib.html  is:

 

----------------------------------BEGIN CODE

import smtplib

 

def prompt(prompt):

    return raw_input(prompt).strip()

 

fromaddr = prompt("From: ")

toaddrs  = prompt("To: ").split()

print "Enter message, end with ^D (Unix) or ^Z (Windows):"

 

# Add the From: and To: headers at the start!

msg = ("From: %s\r\nTo: %s\r\n\r\n"

       % (fromaddr, ", ".join(toaddrs)))

while 1:

    try:

        line = raw_input()

    except EOFError:

        break

    if not line:

        break

    msg = msg + line

 

print "Message length is " + repr(len(msg))

 

server = smtplib.SMTP('localhost')

server.set_debuglevel(1)

server.sendmail(fromaddr, toaddrs, msg)

server.quit()

---------------------------------END CODE

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100417/8c34c699/attachment-0001.html>

From alan.gauld at btinternet.com  Sat Apr 17 17:44:05 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Apr 2010 16:44:05 +0100
Subject: [Tutor] Can Anyone help with SMTP processiing
References: <000601cade12$079519b0$16bf4d10$@com>
Message-ID: <hqcl0i$e1f$1@dough.gmane.org>


"Peter Meagher" <ppmeagher at gmail.com> wrote

> I'm a newbie with Python. Passable with other languages e.g.
> Basic, C++ and others.  
> 
> Not a programmer per se, just trying to get work done that
> happens to require some programming skills and want to try
> my hand with Python.

Python is ideal for that.

> First time through, I got the prompts indicated in the code,
> except when I entered the ctrl Z nothing happened.
> 
> The next time and subsequent times, thereafter I get the
> following 2 pop up message windows:
> 
> IDLE Sub process Error
> 
> Socket error: No connection could be made because the target
> machine actively refused it
> 

> server = smtplib.SMTP('localhost')

My first question would be:
Does your local machine have an SMTP server running?
If it doesn't you won;t connect to it! You may need to use 
the SMTP server you use to send email

Also, I'd try something as long as this as a proper script 
rather than using IDLEs >>> prompt(if thats what you are doing.)
And then I'd run it from a DOS box to remove IDLE as a variable.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From damontimm at gmail.com  Sat Apr 17 17:57:28 2010
From: damontimm at gmail.com (Damon Timm)
Date: Sat, 17 Apr 2010 11:57:28 -0400
Subject: [Tutor] How to map different keys together ?
Message-ID: <m2n262679b51004170857m6883e0a5nb564d04c6bb07c60@mail.gmail.com>

Hello - I am writing a script that converts an entire music library
into a single desired output format.  The source music library has a
variety of music filetypes (flac, mp3, m4a, ogg, etc) and I am
attempting to use mutagen (a music file tagging module,
http://code.google.com/p/mutagen/) in order to handle the tagging.

I am struggling, on a theoretical level, on how to map the various
filetype's tag/key naming conventions.  I have already created my own
MusicFile objects to handle each filetype (with functions for
encoding/decoding) but I can't wrap my head around how to map the
tags.

Here is a relevant (I think) example from mutagen for three different
filetypes all with the same tags (but different keys identifying
them).

>>> flac.keys()
['album', 'disctotal', 'artist', 'title', 'tracktotal', 'genre',
'composer', 'date', 'tracknumber', 'discnumber']
>>> mp3.keys()
['TPOS', u'APIC:', 'TDRC', 'TIT2', 'TPE2', 'TPE1', 'TALB', 'TCON', 'TCOM']
>>> mp4.keys()
['\xa9alb', 'tmpo', '\xa9ART', '\xa9cmt', '\xa9too', 'cpil',
'----:com.apple.iTunes:iTunSMPB', '\xa9wrt', '\xa9nam', 'pgap',
'\xa9gen', 'covr', 'disk', '----:com.apple.iTunes:Encoding Params',
'----:com.apple.iTunes:iTunNORM']

And here is what I would need to do to find the song's TITLE text:

>>> flac['title']
[u'Christmas Waltz']
>>> mp3['TIT2'].text  #notice this one takes another additional step, as well, by specifying text !
[u'Christmas Waltz']
>>> mp4['\xa9nam']
[u"Christmas Waltz"]

In the end, after "the mapping", I would like to be able to do
something along these approaches:

[1] >>> target_file.tags = src_file.tags
[2] >>> target_file.set_tags(src_file.get_tags())

However, none of the keys match, so I need to somehow map them to a
central common source first ... and I am not sure about how to
approach this.  I know I could manually assign each key to a class
property (using the @property tag) ... but this seems tedious:

Any insight on where I can start with mapping all these together?

Thanks,
Damon

From damontimm at gmail.com  Sat Apr 17 17:57:28 2010
From: damontimm at gmail.com (Damon Timm)
Date: Sat, 17 Apr 2010 11:57:28 -0400
Subject: [Tutor] How to map different keys together ?
Message-ID: <m2n262679b51004170857m6883e0a5nb564d04c6bb07c60@mail.gmail.com>

Hello - I am writing a script that converts an entire music library
into a single desired output format.  The source music library has a
variety of music filetypes (flac, mp3, m4a, ogg, etc) and I am
attempting to use mutagen (a music file tagging module,
http://code.google.com/p/mutagen/) in order to handle the tagging.

I am struggling, on a theoretical level, on how to map the various
filetype's tag/key naming conventions.  I have already created my own
MusicFile objects to handle each filetype (with functions for
encoding/decoding) but I can't wrap my head around how to map the
tags.

Here is a relevant (I think) example from mutagen for three different
filetypes all with the same tags (but different keys identifying
them).

>>> flac.keys()
['album', 'disctotal', 'artist', 'title', 'tracktotal', 'genre',
'composer', 'date', 'tracknumber', 'discnumber']
>>> mp3.keys()
['TPOS', u'APIC:', 'TDRC', 'TIT2', 'TPE2', 'TPE1', 'TALB', 'TCON', 'TCOM']
>>> mp4.keys()
['\xa9alb', 'tmpo', '\xa9ART', '\xa9cmt', '\xa9too', 'cpil',
'----:com.apple.iTunes:iTunSMPB', '\xa9wrt', '\xa9nam', 'pgap',
'\xa9gen', 'covr', 'disk', '----:com.apple.iTunes:Encoding Params',
'----:com.apple.iTunes:iTunNORM']

And here is what I would need to do to find the song's TITLE text:

>>> flac['title']
[u'Christmas Waltz']
>>> mp3['TIT2'].text  #notice this one takes another additional step, as well, by specifying text !
[u'Christmas Waltz']
>>> mp4['\xa9nam']
[u"Christmas Waltz"]

In the end, after "the mapping", I would like to be able to do
something along these approaches:

[1] >>> target_file.tags = src_file.tags
[2] >>> target_file.set_tags(src_file.get_tags())

However, none of the keys match, so I need to somehow map them to a
central common source first ... and I am not sure about how to
approach this.  I know I could manually assign each key to a class
property (using the @property tag) ... but this seems tedious:

Any insight on where I can start with mapping all these together?

Thanks,
Damon

From alan.gauld at btinternet.com  Sat Apr 17 21:55:16 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 17 Apr 2010 20:55:16 +0100
Subject: [Tutor] How to map different keys together ?
References: <m2n262679b51004170857m6883e0a5nb564d04c6bb07c60@mail.gmail.com>
Message-ID: <hqd3ng$rei$1@dough.gmane.org>


"Damon Timm" <damontimm at gmail.com> wrote

> I am struggling, on a theoretical level, on how to map the various
> filetype's tag/key naming conventions.  I have already created my own
> MusicFile objects to handle each filetype (with functions for
> encoding/decoding) but I can't wrap my head around how to map the
> tags.

I'd define a mapping table per file type that maps from a standad
set of keys to the file specific tag.

Then define a class that works with the generic tags.
You can then eirther subclass per file type and use the file specific
mapping(a class variable) to translate internally or just create a function
that takes the file mapping as a parameter(maybe in the init() ) and sets
it up for the generic methods to use.

> And here is what I would need to do to find the song's TITLE text:
>
>>>> flac['title']
> [u'Christmas Waltz']
>>>> mp3['TIT2'].text  #notice this one takes another additional step, as well, 
>>>> by specifying text !
> [u'Christmas Waltz']
>>>> mp4['\xa9nam']
> [u"Christmas Waltz"]

So if the file is mp3 the generic

foo.setTag('title')

will inside the setTag method do

def setTag(self, tag, value)
       key = self.mapping[tag]   # get file specific tag
       fileData[key] = value       # and use it
       # or
       self.value = fileData[key]

> approach this.  I know I could manually assign each key to a class
> property (using the @property tag) ... but this seems tedious:

That would definitely be overklilll and not bvery flexible for adding new file 
types.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From matthew.carpenter.arevalo at googlemail.com  Sat Apr 17 22:04:47 2010
From: matthew.carpenter.arevalo at googlemail.com (Matthew Carpenter-Arevalo)
Date: Sat, 17 Apr 2010 13:04:47 -0700
Subject: [Tutor] Guess my number? Guess what's wrong!
Message-ID: <w2gde116e9b1004171304za860dc4aoa8b48ed7b9d42e3e@mail.gmail.com>

Hi Everyone,

I'm a beginner python programmer, and I've been working on
the perennial 'guess my number' example.

When I run this in my module, I get an infinite loop of 'higher' or 'lower.'
Can anyone see where I'm going wrong herE?

Thanks,

MCA


# Guess my number

# the computer picks a random number between 1 and 100
# the player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money

print "\tWelcome to 'Guess my number'!"
print "\nI'm think of a number between 1 and 100."
print "Try to guess it in as few attempts as possible. \n"

# set the initial values
# the number - represents the number the player has to guess
# raw_input = the player's first guess & converts it into an integer.
# tries = # of guesses so far.

import random

the_number = random.randrange(100) + 1
guess = int(raw_input("Take a guess: "))
tries = 1

# guessing loop
while (guess != the_number):
    if (guess > the_number):
        print "lower..."
    else:
        print "Higher..."

guess = int(raw_input("Take a guess: "))
tries += 1

print "You guessed it! The number was", the_number
print "and it only took you", tries, "tries!\n"

raw_input("\n\nPress the enter key to exit.")
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100417/d21f80e4/attachment.html>

From marc.tompkins at gmail.com  Sat Apr 17 22:25:23 2010
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sat, 17 Apr 2010 13:25:23 -0700
Subject: [Tutor] Guess my number? Guess what's wrong!
In-Reply-To: <w2gde116e9b1004171304za860dc4aoa8b48ed7b9d42e3e@mail.gmail.com>
References: <w2gde116e9b1004171304za860dc4aoa8b48ed7b9d42e3e@mail.gmail.com>
Message-ID: <u2h40af687b1004171325ne710e5fap721a5e8189b882bf@mail.gmail.com>

On Sat, Apr 17, 2010 at 1:04 PM, Matthew Carpenter-Arevalo <
matthew.carpenter.arevalo at googlemail.com> wrote:

> Hi Everyone,
>
> I'm a beginner python programmer, and I've been working on
> the perennial 'guess my number' example.
>
> When I run this in my module, I get an infinite loop of 'higher' or
> 'lower.' Can anyone see where I'm going wrong herE?
>
> I think you just have an indentation problem.  Take a look at your loop.




> Thanks,
>
> MCA
>
>
> # Guess my number
>
> # the computer picks a random number between 1 and 100
> # the player tries to guess it and the computer lets
> # the player know if the guess is too high, too low
> # or right on the money
>
> print "\tWelcome to 'Guess my number'!"
> print "\nI'm think of a number between 1 and 100."
> print "Try to guess it in as few attempts as possible. \n"
>
> # set the initial values
> # the number - represents the number the player has to guess
> # raw_input = the player's first guess & converts it into an integer.
> # tries = # of guesses so far.
>
> import random
>
> the_number = random.randrange(100) + 1
> guess = int(raw_input("Take a guess: "))
> tries = 1
>
> # guessing loop
> while (guess != the_number):
>     if (guess > the_number):
>         print "lower..."
>     else:
>         print "Higher..."
>
> guess = int(raw_input("Take a guess: "))
> tries += 1
>
> print "You guessed it! The number was", the_number
> print "and it only took you", tries, "tries!\n"
>
> raw_input("\n\nPress the enter key to exit.")
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100417/37633d03/attachment-0001.html>

From jf_byrnes at comcast.net  Sat Apr 17 22:32:20 2010
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Sat, 17 Apr 2010 15:32:20 -0500
Subject: [Tutor] Guess my number? Guess what's wrong!
In-Reply-To: <w2gde116e9b1004171304za860dc4aoa8b48ed7b9d42e3e@mail.gmail.com>
References: <w2gde116e9b1004171304za860dc4aoa8b48ed7b9d42e3e@mail.gmail.com>
Message-ID: <4BCA1AD4.5010001@comcast.net>

Matthew Carpenter-Arevalo wrote:
> Hi Everyone,
>
> I'm a beginner python programmer, and I've been working on
> the perennial 'guess my number' example.
>
> When I run this in my module, I get an infinite loop of 'higher' or 'lower.'
> Can anyone see where I'm going wrong herE?
>
> Thanks,
>
> MCA
>
>
> # Guess my number
>
> # the computer picks a random number between 1 and 100
> # the player tries to guess it and the computer lets
> # the player know if the guess is too high, too low
> # or right on the money
>
> print "\tWelcome to 'Guess my number'!"
> print "\nI'm think of a number between 1 and 100."
> print "Try to guess it in as few attempts as possible. \n"
>
> # set the initial values
> # the number - represents the number the player has to guess
> # raw_input = the player's first guess&  converts it into an integer.
> # tries = # of guesses so far.
>
> import random
>
> the_number = random.randrange(100) + 1
> guess = int(raw_input("Take a guess: "))
> tries = 1
>
> # guessing loop
> while (guess != the_number):
>      if (guess>  the_number):
>          print "lower..."
>      else:
>          print "Higher..."
>
> guess = int(raw_input("Take a guess: "))
> tries += 1

Move the above two lines to align with "else" so they become part of the 
while loop.

> print "You guessed it! The number was", the_number
> print "and it only took you", tries, "tries!\n"
>
> raw_input("\n\nPress the enter key to exit.")
>
Regards,  Jim

From damontimm at gmail.com  Sun Apr 18 19:42:46 2010
From: damontimm at gmail.com (Damon Timm)
Date: Sun, 18 Apr 2010 13:42:46 -0400
Subject: [Tutor] How to map different keys together ?
In-Reply-To: <hqd3ng$rei$1@dough.gmane.org>
References: <m2n262679b51004170857m6883e0a5nb564d04c6bb07c60@mail.gmail.com>
	<hqd3ng$rei$1@dough.gmane.org>
Message-ID: <t2m262679b51004181042u5dff8481i586264a0a40aea32@mail.gmail.com>

Hi Alan, et al - thanks for your response and your ideas.  I sat down
and did a little more coding so that I might tackle what I can and
bring back where I am having trouble.  I have implemented the basic
'tag_map' you suggested without a hitch using my own class and
getitem/setitem builtins.  Right now, if there is a one-to-one
correlation between my *generic* key (as a standard between my music
files) and the specific tag for the filetype, I am doing well.

However, everything is not so clear cut in the world of metatagging!
My first stumbling block is that M4A files store the track number and
track total in a single tuple ... but I need them as separate fields
(which is how some of the other formats do it).  This is going to be
one of many hurdles -- I need a way to accomplish more than a
one-to-one data map.

See my code, below, as well as some command line examples where I am
having trouble.  I feel there may be a way to pass functions through
my tag_map dictionary (maybe a lambda?!) but I can't get my head
around what approach is best (I can't think of any approach, right
now, actually).

Code follows. Thanks again.

class Tags(object):
    '''Wrapper class for a mutagen music file object.'''
    tag_map = {}

    def __init__(self, mutagen):
        self._mutagen = mutagen
        self.tags = {}

    def keys(self):
        '''Get list of generic tag keys in use'''
        keys = []
        for k in self.tag_map.keys():
            try:
                self._mutagen[self.tag_map[k]]
                keys.append(k)
            except KeyError:
                pass

        return keys

    def save(self):
        '''Save the mutagen changes.'''
        self._mutagen.save()

class MP4Tags(Tags):
    tag_map = {
    #   GENERIC         : SPECIFIC
        'title'         : '\xa9nam',
        'album'         : '\xa9alb',
        'artist'        : '\xa9ART',
        'albumartist'   : 'aART',
        'comment'       : '\xa9cmt',
        'compilation'   : 'cpil',
        'composer'      : '\xa9wrt',
        'genre'         : '\xa9gen',
        'discnumber'    : 'disk', # returns: (2,10) need lmbda or something ?!
        'disctotal'     : 'disk', # returns: (2,10) need lmbda or something ?!
        'year'          : '\xa9day',
        'tracknumber'   : 'trkn', # returns: (2,10) need lmbda or something ?!
        'tracktotal'    : 'trkn'  # returns: (2,10) need lmbda or something ?!

    }

    def __getitem__(self, key):
        try:
            return self._mutagen[self.tag_map[key]]
        except KeyError:
            pass

    def __setitem__(self, key, value):
        self._mutagen[self.tag_map[key]] = value

#EOF

**Here is how it works:

>>> import tagging
>>> from mutagen.mp4 import MP4
>>> mp4 = MP4('../tests/data/Compressed/M4A-256.m4a')
>>> mp4_tags = tagging.MP4Tags(mp4)
>>> mp4_tags['title']
[u'bob the builder']  # woo hoo! it works!
>>> mp4_tags['title'] = [u'I can change the title!']
>>> mp4_tags['title']
[u'I can change the title!']  # changing the titles works too
>>> mp4_tags['discnumber']
[(1, 1)]  # TODO - I need to return disk[0][0] ... not the tuple
>>> mp4_tags.save()

So, I need to modify how the data is shown to me as well as how I
would go about writing the data something like:

return_tag(disk): return disk[0][0]
save_tag(num): return [(%s, %s)] % ( num,
somehow_get_the_original_second_value_before_re_saving)

Thanks again and any advice or guidance about how to approach this is
greatly appreciated.

Damon



On Sat, Apr 17, 2010 at 3:55 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Damon Timm" <damontimm at gmail.com> wrote
>
>> I am struggling, on a theoretical level, on how to map the various
>> filetype's tag/key naming conventions. ?I have already created my own
>> MusicFile objects to handle each filetype (with functions for
>> encoding/decoding) but I can't wrap my head around how to map the
>> tags.
>
> I'd define a mapping table per file type that maps from a standad
> set of keys to the file specific tag.
>
> Then define a class that works with the generic tags.
> You can then eirther subclass per file type and use the file specific
> mapping(a class variable) to translate internally or just create a function
> that takes the file mapping as a parameter(maybe in the init() ) and sets
> it up for the generic methods to use.
>
>> And here is what I would need to do to find the song's TITLE text:
>>
>>>>> flac['title']
>>
>> [u'Christmas Waltz']
>>>>>
>>>>> mp3['TIT2'].text ?#notice this one takes another additional step, as
>>>>> well, by specifying text !
>>
>> [u'Christmas Waltz']
>>>>>
>>>>> mp4['\xa9nam']
>>
>> [u"Christmas Waltz"]
>
> So if the file is mp3 the generic
>
> foo.setTag('title')
>
> will inside the setTag method do
>
> def setTag(self, tag, value)
> ? ? ?key = self.mapping[tag] ? # get file specific tag
> ? ? ?fileData[key] = value ? ? ? # and use it
> ? ? ?# or
> ? ? ?self.value = fileData[key]
>
>> approach this. ?I know I could manually assign each key to a class
>> property (using the @property tag) ... but this seems tedious:
>
> That would definitely be overklilll and not bvery flexible for adding new
> file types.
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From denis.spir at gmail.com  Sun Apr 18 20:03:52 2010
From: denis.spir at gmail.com (spir =?UTF-8?B?4pij?=)
Date: Sun, 18 Apr 2010 20:03:52 +0200
Subject: [Tutor] How to map different keys together ?
In-Reply-To: <m2n262679b51004170857m6883e0a5nb564d04c6bb07c60@mail.gmail.com>
References: <m2n262679b51004170857m6883e0a5nb564d04c6bb07c60@mail.gmail.com>
Message-ID: <20100418200352.35f0d803@o>

On Sat, 17 Apr 2010 11:57:28 -0400
Damon Timm <damontimm at gmail.com> wrote:

> Hello - I am writing a script that converts an entire music library
> into a single desired output format.  The source music library has a
> variety of music filetypes (flac, mp3, m4a, ogg, etc) and I am
> attempting to use mutagen (a music file tagging module,
> http://code.google.com/p/mutagen/) in order to handle the tagging.
> 
> I am struggling, on a theoretical level, on how to map the various
> filetype's tag/key naming conventions.  I have already created my own
> MusicFile objects to handle each filetype (with functions for
> encoding/decoding) but I can't wrap my head around how to map the
> tags.
> 
> Here is a relevant (I think) example from mutagen for three different
> filetypes all with the same tags (but different keys identifying
> them).
> 
> >>> flac.keys()
> ['album', 'disctotal', 'artist', 'title', 'tracktotal', 'genre',
> 'composer', 'date', 'tracknumber', 'discnumber']
> >>> mp3.keys()
> ['TPOS', u'APIC:', 'TDRC', 'TIT2', 'TPE2', 'TPE1', 'TALB', 'TCON', 'TCOM']
> >>> mp4.keys()
> ['\xa9alb', 'tmpo', '\xa9ART', '\xa9cmt', '\xa9too', 'cpil',
> '----:com.apple.iTunes:iTunSMPB', '\xa9wrt', '\xa9nam', 'pgap',
> '\xa9gen', 'covr', 'disk', '----:com.apple.iTunes:Encoding Params',
> '----:com.apple.iTunes:iTunNORM']

Without the issue below with mp3, you could just do a triple (!) dict lookup. Using at best constants like TITLE to identify in a type-independant manner the field accessed, this could give:
   key = keys_per_type[FLAC][TITLE]
   title = album_data[key]
or in one go
   title = album_data[keys_per_type[FLAC][TITLE]]

> And here is what I would need to do to find the song's TITLE text:
> 
> >>> flac['title']
> [u'Christmas Waltz']
> >>> mp3['TIT2'].text  #notice this one takes another additional step, as well, by specifying text !

Yo, annoying!...

> [u'Christmas Waltz']
> >>> mp4['\xa9nam']
> [u"Christmas Waltz"]

... so maybe the best method is to write an access method per field, taking the type as param. Or a super access method taking both the type and field.

> In the end, after "the mapping", I would like to be able to do
> something along these approaches:
> 
> [1] >>> target_file.tags = src_file.tags
> [2] >>> target_file.set_tags(src_file.get_tags())

I would make an intermediate AlbumData type to handle the per-type mess, abstracting it for you as user.

album_data = AlbumData(src_file.tags)	# maybe type needed here
album_data.write(target_file)		# ditto?
or
target_file.write(album_data.format(type))
or something like that.

> However, none of the keys match, so I need to somehow map them to a
> central common source first ... and I am not sure about how to
> approach this.  I know I could manually assign each key to a class
> property (using the @property tag) ... but this seems tedious:

Not so sure it's more tedious. At least it's clear in serving code. (Just make sure there it is also clear on client code side.)

> Any insight on where I can start with mapping all these together?


> Thanks,
> Damon

Denis
________________________________

vit esse estrany ?

spir.wikidot.com

From denis.spir at gmail.com  Sun Apr 18 20:17:45 2010
From: denis.spir at gmail.com (spir =?UTF-8?B?4pij?=)
Date: Sun, 18 Apr 2010 20:17:45 +0200
Subject: [Tutor] How to map different keys together ?
In-Reply-To: <t2m262679b51004181042u5dff8481i586264a0a40aea32@mail.gmail.com>
References: <m2n262679b51004170857m6883e0a5nb564d04c6bb07c60@mail.gmail.com>
	<hqd3ng$rei$1@dough.gmane.org>
	<t2m262679b51004181042u5dff8481i586264a0a40aea32@mail.gmail.com>
Message-ID: <20100418201745.2eeb73c5@o>

On Sun, 18 Apr 2010 13:42:46 -0400
Damon Timm <damontimm at gmail.com> wrote:

> Hi Alan, et al - thanks for your response and your ideas.  I sat down
> and did a little more coding so that I might tackle what I can and
> bring back where I am having trouble.  I have implemented the basic
> 'tag_map' you suggested without a hitch using my own class and
> getitem/setitem builtins.  Right now, if there is a one-to-one
> correlation between my *generic* key (as a standard between my music
> files) and the specific tag for the filetype, I am doing well.
> 
> However, everything is not so clear cut in the world of metatagging!
> My first stumbling block is that M4A files store the track number and
> track total in a single tuple ... but I need them as separate fields
> (which is how some of the other formats do it).  This is going to be
> one of many hurdles -- I need a way to accomplish more than a
> one-to-one data map.
> 
> See my code, below, as well as some command line examples where I am
> having trouble.  I feel there may be a way to pass functions through
> my tag_map dictionary (maybe a lambda?!) but I can't get my head
> around what approach is best (I can't think of any approach, right
> now, actually).
> 
> Code follows. Thanks again.
> 
> class Tags(object):
>     '''Wrapper class for a mutagen music file object.'''
>     tag_map = {}
> 
>     def __init__(self, mutagen):
>         self._mutagen = mutagen
>         self.tags = {}
> 
>     def keys(self):
>         '''Get list of generic tag keys in use'''
>         keys = []
>         for k in self.tag_map.keys():
>             try:
>                 self._mutagen[self.tag_map[k]]
>                 keys.append(k)
>             except KeyError:
>                 pass
> 
>         return keys
> 
>     def save(self):
>         '''Save the mutagen changes.'''
>         self._mutagen.save()
> 
> class MP4Tags(Tags):
>     tag_map = {
>     #   GENERIC         : SPECIFIC
>         'title'         : '\xa9nam',
>         'album'         : '\xa9alb',
>         'artist'        : '\xa9ART',
>         'albumartist'   : 'aART',
>         'comment'       : '\xa9cmt',
>         'compilation'   : 'cpil',
>         'composer'      : '\xa9wrt',
>         'genre'         : '\xa9gen',
>         'discnumber'    : 'disk', # returns: (2,10) need lmbda or something ?!
>         'disctotal'     : 'disk', # returns: (2,10) need lmbda or something ?!
>         'year'          : '\xa9day',
>         'tracknumber'   : 'trkn', # returns: (2,10) need lmbda or something ?!
>         'tracktotal'    : 'trkn'  # returns: (2,10) need lmbda or something ?!
> 
>     }
> 
>     def __getitem__(self, key):
>         try:
>             return self._mutagen[self.tag_map[key]]
>         except KeyError:
>             pass
> 
>     def __setitem__(self, key, value):
>         self._mutagen[self.tag_map[key]] = value
> 
> #EOF

All of this is not only plain data, but constant! The case of non-exisitng tag for a given format is, as shown by your 'pass', not to be handled here. Using a class is not only averkill but (wrong in my opininon and) misleading.

Anyway it won't work since you need more than simple lookup in the case above, meaning some process must be done, and also the case of mp3 (iirc) titles shown in your first post.

> **Here is how it works:
> 
> >>> import tagging
> >>> from mutagen.mp4 import MP4
> >>> mp4 = MP4('../tests/data/Compressed/M4A-256.m4a')
> >>> mp4_tags = tagging.MP4Tags(mp4)
> >>> mp4_tags['title']
> [u'bob the builder']  # woo hoo! it works!
> >>> mp4_tags['title'] = [u'I can change the title!']
> >>> mp4_tags['title']
> [u'I can change the title!']  # changing the titles works too
> >>> mp4_tags['discnumber']
> [(1, 1)]  # TODO - I need to return disk[0][0] ... not the tuple
> >>> mp4_tags.save()
> 
> So, I need to modify how the data is shown to me as well as how I
> would go about writing the data something like:
> 
> return_tag(disk): return disk[0][0]
> save_tag(num): return [(%s, %s)] % ( num,
> somehow_get_the_original_second_value_before_re_saving)
> 
> Thanks again and any advice or guidance about how to approach this is
> greatly appreciated.
> 
> Damon




________________________________

vit esse estrany ?

spir.wikidot.com

From aidas at vineva.lt  Sun Apr 18 17:21:47 2010
From: aidas at vineva.lt (Aidas)
Date: Sun, 18 Apr 2010 18:21:47 +0300
Subject: [Tutor] Python root.
Message-ID: <4BCB238B.7090300@vineva.lt>

Hello.
In here http://mail.python.org/pipermail/tutor/2001-February/003385.html 
You had written how to ger root in python. The way is: "from math import 
sqrtprint sqrt( 49 )".

I noticed that if I write just "print sqrt(49)" I get nothing. So why I need to write "from math import sqrt" instead of write just "print sqrt( 49 )"?

P.S. Sorry about english-I'm lithuanian. :)


From alan.gauld at btinternet.com  Sun Apr 18 21:23:29 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Sun, 18 Apr 2010 19:23:29 +0000 (GMT)
Subject: [Tutor] How to map different keys together ?
In-Reply-To: <t2m262679b51004181042u5dff8481i586264a0a40aea32@mail.gmail.com>
References: <m2n262679b51004170857m6883e0a5nb564d04c6bb07c60@mail.gmail.com>
	<hqd3ng$rei$1@dough.gmane.org>
	<t2m262679b51004181042u5dff8481i586264a0a40aea32@mail.gmail.com>
Message-ID: <319117.98395.qm@web86707.mail.ird.yahoo.com>



> My first stumbling block is that M4A files store the track number and
> track total in a single tuple ... but I need them as separate fields
> one of many hurdles -- I need a way to accomplish more than a
> one-to-one data map.

In that case map to a function which can return the value.
Use lambdas for the trivial cases:

'Title': lambda : fileData['title']

For 1-1 maps:

'Artist' : lambda : fileData['ART']

For more complex maps:

'Track' : lambda : flieData['TRK'][0]
'Total' : lambda : fileData['TRK'][1]

And for more complex things define a function:

def complexMap(key):
      # do something here
      return result

'WeirdThing' : lambda : complex ('WeirdThing')


Then just call the funcyion when needed:

myDatya = map[key]()   # parens calls the function

> having trouble.  I feel there may be a way to pass functions through
> my tag_map dictionary (maybe a lambda?!) but I can't get my head
> around what approach is best 

Does what I've shown make sense?


 Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/



________________________________
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100418/2d577ced/attachment.html>

From waynejwerner at gmail.com  Sun Apr 18 22:15:58 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Sun, 18 Apr 2010 15:15:58 -0500
Subject: [Tutor] Python root.
In-Reply-To: <4BCB238B.7090300@vineva.lt>
References: <4BCB238B.7090300@vineva.lt>
Message-ID: <m2s333efb451004181315i65a4e8bcq5a5451e20f04875a@mail.gmail.com>

On Sun, Apr 18, 2010 at 10:21 AM, Aidas <aidas at vineva.lt> wrote:

> Hello.
> In here http://mail.python.org/pipermail/tutor/2001-February/003385.htmlYou had written how to ger root in python. The way is: "from math import
> sqrtprint sqrt( 49 )".
>
> I noticed that if I write just "print sqrt(49)" I get nothing. So why I
> need to write "from math import sqrt" instead of write just "print sqrt( 49
> )"?
>
> P.S. Sorry about english-I'm lithuanian. :)
>
>
>>> sqrt()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined

That traceback tells you what the error is and where the error is. The
NameError is the specific type of error, and it tells you why - sqrt is not
defined.

In order to call a function its name needs to be defined. When you type '>>>
from math import sqrt' then you are importing the function (or name) sqrt
from the math module.

Then you can use it:
>>> from math import sqrt
>>> print sqrt(49)
7.0


HTH,
Wayne



> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100418/639f4e51/attachment.html>

From davea at ieee.org  Sun Apr 18 23:08:25 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 18 Apr 2010 17:08:25 -0400
Subject: [Tutor] Python root.
In-Reply-To: <4BCB238B.7090300@vineva.lt>
References: <4BCB238B.7090300@vineva.lt>
Message-ID: <4BCB74C9.7060604@ieee.org>

Aidas wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Hello.
> In here 
> http://mail.python.org/pipermail/tutor/2001-February/003385.html You 
> had written how to ger root in python. The way is: "from math import 
> sqrtprint sqrt( 49 )".
>
> I noticed that if I write just "print sqrt(49)" I get nothing. 
I don't get "nothing," I get an error message.  In particular I get:

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined

> So why I need to write "from math import sqrt" instead of write just 
> "print sqrt( 49 )"?
>
> P.S. Sorry about english-I'm lithuanian. :)
>
As the message says, "sqrt" is not defined in the language.  It's 
included in one of the library modules.  Whenever you need code from an 
external module, whether that module is part of the standard Python 
library or something you wrote, or even a third-party library, you have 
to import it before you can use it.  The default method of importing is:

import math
print math.sqrt(49)

Where the prefix qualifer on sqrt means to run the sqrt() specifically 
from the math module.

When a single function from a particular library module is needed many 
times, it's frequently useful to use the alternate import form:

from math import sqrt

which does two things:

import math
sqrt = math.sqrt

The second line basically gives you an alias, or short name, for the 
function from that module.

HTH
DaveA


From neven.gorsic at gmail.com  Sun Apr 18 23:49:31 2010
From: neven.gorsic at gmail.com (=?UTF-8?B?TmV2ZW4gR29yxaFpxIc=?=)
Date: Sun, 18 Apr 2010 23:49:31 +0200
Subject: [Tutor] Raw string
Message-ID: <t2z8acd28da1004181449q52d02a28j31342f654778db4@mail.gmail.com>

Hi!

When I get file path from DirDialog, I get in a (path) variable.
Sometimes that string (path) contains special escape sequences, such as \x,
\r and so on.

             'C:\Python25\Programs\rating'

When I try to open that file (whose name contains escape sequences) it
doesn't work.

I know that raw string marker 'r' in front of string leaves char '\' as
character and not as start of escape sequences,
but I can not apply it to a variable name which contains file path.

Is there a function with same effect as raw string marker, as my problem
must be solved differently?

Can you help me?

Kind regards,

Neven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100418/1f7c6851/attachment.html>

From alan.gauld at btinternet.com  Mon Apr 19 00:19:02 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 18 Apr 2010 23:19:02 +0100
Subject: [Tutor] Python root.
References: <4BCB238B.7090300@vineva.lt>
Message-ID: <hqg0h4$jto$1@dough.gmane.org>


"Aidas" <aidas at vineva.lt> wrote

> You had written how to ger root in python. The way is: 
> from math import sqrt
> print sqrt( 49 )".
> 
> I noticed that if I write just "print sqrt(49)" I get nothing. 
> So why I need to write "from math import sqrt" 

Others have explained that you need to import the name sqrt from 
the math module because sqrt is not defined as a "built-in" Python 
function. But you can achieve the same thing using the pow() function, 
which is built in - pow(49,0.5) - or the exponentiation operator - 49 ** 0.5 
without using import...

You can read more about import and modules in the "Modules and 
Functions" topic of my tutorial and more detail still in the "Whats in a name?"
topic.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Mon Apr 19 00:46:15 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 18 Apr 2010 23:46:15 +0100
Subject: [Tutor] Raw string
References: <t2z8acd28da1004181449q52d02a28j31342f654778db4@mail.gmail.com>
Message-ID: <hqg245$nud$1@dough.gmane.org>


"Neven Gorsic" <neven.gorsic at gmail.com> wrote 

> When I get file path from DirDialog, I get in a (path) variable.
> Sometimes that string (path) contains special escape sequences, such as \x,
> \r and so on.
> 
>             'C:\Python25\Programs\rating'
> 
> When I try to open that file (whose name contains escape sequences) it
> doesn't work.

That sounds like a bug in DirDialog since I would expect it to return a 
properly constructed, platform specific path! Are you sure it doesn't?
What is the len() of the string? The above should return 27 not 24...

> I know that raw string marker 'r' in front of string leaves char '\' as
> character and not as start of escape sequences,
> but I can not apply it to a variable name which contains file path.

You can only apply it to literal strings not variables , regardless of 
what the variable points to.

> Is there a function with same effect as raw string marker, as my problem
> must be solved differently?

You might get some help from the os.path library functions. But to be 
honest I can't see anything obvious... You might have to resort to 
character by character replacement...

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From bgailer at gmail.com  Mon Apr 19 00:48:47 2010
From: bgailer at gmail.com (bob gailer)
Date: Sun, 18 Apr 2010 18:48:47 -0400
Subject: [Tutor] Raw string
In-Reply-To: <t2z8acd28da1004181449q52d02a28j31342f654778db4@mail.gmail.com>
References: <t2z8acd28da1004181449q52d02a28j31342f654778db4@mail.gmail.com>
Message-ID: <4BCB8C4F.6030304@gmail.com>

On 4/18/2010 5:49 PM, Neven Gor?i? wrote:
> Hi!
>
> When I get file path from DirDialog, I get in a (path) variable.
> Sometimes that string (path) contains special escape sequences, such 
> as \x, \r and so on.
>
>              'C:\Python25\Programs\rating'
>
> When I try to open that file (whose name contains escape sequences) it 
> doesn't work.

"It doesn't work" is too vague. Please show us a code snippet that 
includes obtaining the file path, attempt to open and what happens. Do 
you get a traceback (error message)? If so, please post it with the code.

Please also reply-all so a copy goes to the list.

>
> I know that raw string marker 'r' in front of string leaves char '\' 
> as character and not as start of escape sequences,
> but I can not apply it to a variable name which contains file path.
>
> Is there a function with same effect as raw string marker, as my 
> problem must be solved differently?
>
> Can you help me?
>
> Kind regards,
>
> Neven

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From cmcaine at googlemail.com  Mon Apr 19 00:53:03 2010
From: cmcaine at googlemail.com (C M Caine)
Date: Sun, 18 Apr 2010 23:53:03 +0100
Subject: [Tutor] List index usage: is there a more pythonesque way?
Message-ID: <q2nb98d9b671004181553g6ada64deo4e2e649dff327dd5@mail.gmail.com>

# Example data for forms and timetable:
forms = ["P7", "P8", "P9", "P10", "P11", "S7", "S8", "S9", "S10",
"S11", "IMA", "CAT", "FOR", "RLS", "EMPTY"]

timetable = ['CAT', 'P10', 'P8', 'EMPTY', 'EMPTY', 'EMPTY', 'S10',
'S8', 'IMA', 'EMPTY', 'S7', 'S10', 'P9', 'EMPTY', 'EMPTY', 'EMPTY',
'S7', 'EMPTY', 'EMPTY', 'RLS', 'FOR', 'EMPTY', 'EMPTY', 'EMPTY', 'S9',
'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY',
'EMPTY', 'EMPTY', 'S8', 'IMA', 'S11', 'P8', 'EMPTY', 'IMA', 'EMPTY',
'EMPTY', 'S11', 'S11', 'EMPTY', 'EMPTY', 'EMPTY', 'P7', 'S9', 'P11',
'P11', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY',
'EMPTY', 'EMPTY', 'P9', 'EMPTY', 'EMPTY', 'P8', 'FOR', 'S10', 'S11',
'S7', 'P7', 'EMPTY', 'EMPTY', 'IMA', 'EMPTY', 'S9', 'P10', 'P11',
'CAT', 'S8', 'P9', 'RLS']

def analyseTimetable():
        "Find number of and spaces between each form."
        numDict = {}
        spaceDict = {}
        adjustedSpaceDict = {}
        for form in forms:
            numDict[form], spaceDict['1st'+form], spaceDict['nth'+form] \
                           = 0,0,0
        for i in range(len(timetable)):
            numDict[timetable[i]] += 1
            if spaceDict['1st'+timetable[i]] == 0:
                spaceDict['nth'+timetable[i]] = i
            else:
                spaceDict['nth'+timetable[i]] = i
        for form in forms:
            adjustedSpaceDict[form] = spaceDict['nth'+form] - \
                                      spaceDict['1st'+form]
        return (numDict, adjustedSpaceDict)

# End example

This function works fine, but I think that using range(len(timetable))
is clumsy. On the other hand, I need the indexes to track the number
of spaces between instances of each form. Without using another loop
(so not using list.index), is there a way of getting the index of the
list entries?

Thanks in advance,
Colin Caine

From alan.gauld at btinternet.com  Mon Apr 19 01:09:04 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Apr 2010 00:09:04 +0100
Subject: [Tutor] List index usage: is there a more pythonesque way?
References: <q2nb98d9b671004181553g6ada64deo4e2e649dff327dd5@mail.gmail.com>
Message-ID: <hqg3eu$r4v$1@dough.gmane.org>


"C M Caine" <cmcaine at googlemail.com> wrote 


>        for i in range(len(timetable)):
>            numDict[timetable[i]] += 1
>            if spaceDict['1st'+timetable[i]] == 0:
>                spaceDict['nth'+timetable[i]] = i

for index, item in enumerate(timetable):
            numDict[item] += 1
            if spaceDict['1st'+item] == 0:
                spaceDict['nth'+item] = i
     
> This function works fine, but I think that using range(len(timetable))
> is clumsy. On the other hand, I need the indexes to track the number

enumerate() is your friend.


HTH,

Alan G


From steve at pearwood.info  Mon Apr 19 01:25:37 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 19 Apr 2010 09:25:37 +1000
Subject: [Tutor] Raw string
In-Reply-To: <t2z8acd28da1004181449q52d02a28j31342f654778db4@mail.gmail.com>
References: <t2z8acd28da1004181449q52d02a28j31342f654778db4@mail.gmail.com>
Message-ID: <201004190925.37634.steve@pearwood.info>

On Mon, 19 Apr 2010 07:49:31 am Neven Gor?i? wrote:
> Hi!
>
> When I get file path from DirDialog, I get in a (path) variable.
> Sometimes that string (path) contains special escape sequences, such
> as \x, \r and so on.
>
>              'C:\Python25\Programs\rating'

That creates a string containing a \r character, which is a carriage 
return.

You could write it as a raw string

r'C:\Python25\Programs\rating'

but that will fail if the string ends with a backslash. Or you could 
escape your backslashes:

'C:\\Python25\\Programs\\rating'

The best solution is to remember that Windows will accept either 
backslash or forward slash in paths, and so write:

'C:/Python25/Programs/rating'

Another solution is to construct the path programmatically, e.g.:

parts = ['C:', 'Python25', 'Programs', 'ratings']
path = '\\'.join(parts)

but frankly I would consider any solution except "use forward slashes" 
to be a waste of time -- CPU time *and* programmer time.


> When I try to open that file (whose name contains escape sequences)
> it doesn't work.

Only because the file doesn't exist. If you actually have a file called 
Programs\rating in the C:/Python25/ directory, you will open it.




-- 
Steven D'Aprano

From bgailer at gmail.com  Mon Apr 19 01:34:13 2010
From: bgailer at gmail.com (bob gailer)
Date: Sun, 18 Apr 2010 19:34:13 -0400
Subject: [Tutor] List index usage: is there a more pythonesque way?
In-Reply-To: <q2nb98d9b671004181553g6ada64deo4e2e649dff327dd5@mail.gmail.com>
References: <q2nb98d9b671004181553g6ada64deo4e2e649dff327dd5@mail.gmail.com>
Message-ID: <4BCB96F5.60903@gmail.com>

On 4/18/2010 6:53 PM, C M Caine wrote:
> # Example data for forms and timetable:
> forms = ["P7", "P8", "P9", "P10", "P11", "S7", "S8", "S9", "S10",
> "S11", "IMA", "CAT", "FOR", "RLS", "EMPTY"]
>
> timetable = ['CAT', 'P10', 'P8', 'EMPTY', 'EMPTY', 'EMPTY', 'S10',
> 'S8', 'IMA', 'EMPTY', 'S7', 'S10', 'P9', 'EMPTY', 'EMPTY', 'EMPTY',
> 'S7', 'EMPTY', 'EMPTY', 'RLS', 'FOR', 'EMPTY', 'EMPTY', 'EMPTY', 'S9',
> 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY',
> 'EMPTY', 'EMPTY', 'S8', 'IMA', 'S11', 'P8', 'EMPTY', 'IMA', 'EMPTY',
> 'EMPTY', 'S11', 'S11', 'EMPTY', 'EMPTY', 'EMPTY', 'P7', 'S9', 'P11',
> 'P11', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY',
> 'EMPTY', 'EMPTY', 'P9', 'EMPTY', 'EMPTY', 'P8', 'FOR', 'S10', 'S11',
> 'S7', 'P7', 'EMPTY', 'EMPTY', 'IMA', 'EMPTY', 'S9', 'P10', 'P11',
> 'CAT', 'S8', 'P9', 'RLS']
>
> def analyseTimetable():
>          "Find number of and spaces between each form."
>    

Consider using defaultdict in the collections module. The first time a 
key is referenced it is automatically added with a specified value.

         

import collections
          numDict = collections.defaultdict(0)
          spaceDict = collections.defaultdict(0)

>          adjustedSpaceDict = {}
>    

If you use enumerate then you can replace timetable[i] with key
>          for i, key in enumerate(timetable):
>              numDict[key] += 1
>    

Something is wrong in the following if statement, as both paths execute 
the same code.

>              if spaceDict['1st'+key] == 0:
>                  spaceDict['nth'+key] = i
>              else:
>                  spaceDict['nth'+key] = i
>          for form in forms:
>              adjustedSpaceDict[form] = spaceDict['nth'+form] - \
>                                        spaceDict['1st'+form]
>          return (numDict, adjustedSpaceDict)
>
> # End example
>
> This function works fine, but I think that using range(len(timetable))
> is clumsy. On the other hand, I need the indexes to track the number
> of spaces between instances of each form. Without using another loop
> (so not using list.index), is there a way of getting the index of the
> list entries?


-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From cmcaine at googlemail.com  Mon Apr 19 01:37:11 2010
From: cmcaine at googlemail.com (C M Caine)
Date: Mon, 19 Apr 2010 00:37:11 +0100
Subject: [Tutor] List index usage: is there a more pythonesque way?
In-Reply-To: <hqg3eu$r4v$1@dough.gmane.org>
References: <q2nb98d9b671004181553g6ada64deo4e2e649dff327dd5@mail.gmail.com> 
	<hqg3eu$r4v$1@dough.gmane.org>
Message-ID: <r2sb98d9b671004181637j3bebc8d9y748f5cdb8b1790e4@mail.gmail.com>

That's two new things I've learnt. I didn't realise that for loops
could be used like that (with more than one... key?).

Thanks, I'm changing my code even now!

On 19 April 2010 00:09, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "C M Caine" <cmcaine at googlemail.com> wrote
>
>> ? ? ? for i in range(len(timetable)):
>> ? ? ? ? ? numDict[timetable[i]] += 1
>> ? ? ? ? ? if spaceDict['1st'+timetable[i]] == 0:
>> ? ? ? ? ? ? ? spaceDict['nth'+timetable[i]] = i
>
> for index, item in enumerate(timetable):
> ? ? ? ? ? numDict[item] += 1
> ? ? ? ? ? if spaceDict['1st'+item] == 0:
> ? ? ? ? ? ? ? spaceDict['nth'+item] = i
>
>>
>> This function works fine, but I think that using range(len(timetable))
>> is clumsy. On the other hand, I need the indexes to track the number
>
> enumerate() is your friend.
>
>
> HTH,
>
> Alan G
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From steve at alchemy.com  Mon Apr 19 01:06:46 2010
From: steve at alchemy.com (Steve Willoughby)
Date: Sun, 18 Apr 2010 16:06:46 -0700
Subject: [Tutor] Raw string
In-Reply-To: <4BCB8C4F.6030304@gmail.com>
References: <t2z8acd28da1004181449q52d02a28j31342f654778db4@mail.gmail.com>
	<4BCB8C4F.6030304@gmail.com>
Message-ID: <20100418230646.GC3577@dragon.alchemy.com>

On Sun, Apr 18, 2010 at 06:48:47PM -0400, bob gailer wrote:
> On 4/18/2010 5:49 PM, Neven Gor??i?? wrote:
> >When I get file path from DirDialog, I get in a (path) variable.
> >Sometimes that string (path) contains special escape sequences, such 
> >as \x, \r and so on.

Since this is a tutorial list, it might be good to point out a few
distinctions at work here.  First of all, strings do not ever contain
escape sequences.  They simply contain characters.

So once a string is returned from DirDialog, it just contains characters.
For example, 'C:\Python25\Programs\rating', or in other words: C, colon,
backslash, P, y, t, and so forth.  I would imagine that handing that to
the open() function should work on a Windows platform just fine.  Handing
it to another function which may try to interpret the characters specially
might not, but as Bob Gailer pointed out,

> "It doesn't work" is too vague. Please show us a code snippet that 
> includes obtaining the file path, attempt to open and what happens. Do 
> you get a traceback (error message)? If so, please post it with the code.

However, you mentioned escape sequences and the 'r' marker.  These are not
things which are stored IN strings, but are part of the Python language as
tools to enable us to craete strings which  may have specific special 
characters in them.  So IN MY PROGRAM SOURCE CODE (ONLY) I could put a
bit of Python code like this:

          var = 'hello, world\n'

which contains the escape code \n which *in source code* tells Python
to create the string with a newline character where the \n was in the source.
There is not escape code in the string (which is referenced now by the name
var).  That string just contains the characters: h, e, l, l, o, comma, space,
w, o, r, l, d, newline.

If I used the "r" marker, that tells Python to avoid doing the above, so
the source code

          rawvar = r'hello, world\n'

would create the string: h, e, l, l, o, comma, space, w, o, r, l, d,
backslash, n.  But those, at this point (once that line of code was 
executed) are just characters in the string.


> >             'C:\Python25\Programs\rating'

If that were a line in a program as a string literal value, like
          filepath = 'C:\Python25\Programs\rating'

Then you'd have a problem, indeed.  That would need to use the 'r'
marker, or properly escape the backslashes:
          filepath = r'C:\Python25\Programs\rating'
          filepath = 'C:\\Python25\\Programs\\rating'

However, if the DirDialog returned a string value like:
              'C:\Python25\Programs\rating'

meaning the string C, colon, backslash, P, y, ..., then that's probably
exactly what it's supposed to do, and we'd need to see more code and/or
actual output to figure out what the real source of trouble might be.
          
> >I know that raw string marker 'r' in front of string leaves char '\' 
> >as character and not as start of escape sequences,
> >but I can not apply it to a variable name which contains file path.

I hope the explanation above helps you to understand why such appliction
is not only impossible, but wouldn't really even make sense to do.

> >Is there a function with same effect as raw string marker, as my 
> >problem must be solved differently?

If you mean to take a string which contained the same characters as
Python recognizes as escape sequences, like "backslash n" and turns them
into things like "newline", then yes, actually, there are several ways
Python can do that, but I'm almost certain that's not really your problem
here so I don't want to point you down the wrong path.

-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.

From damontimm at gmail.com  Mon Apr 19 01:43:49 2010
From: damontimm at gmail.com (Damon Timm)
Date: Sun, 18 Apr 2010 19:43:49 -0400
Subject: [Tutor] How to map different keys together ?
In-Reply-To: <319117.98395.qm@web86707.mail.ird.yahoo.com>
References: <m2n262679b51004170857m6883e0a5nb564d04c6bb07c60@mail.gmail.com>
	<hqd3ng$rei$1@dough.gmane.org>
	<t2m262679b51004181042u5dff8481i586264a0a40aea32@mail.gmail.com>
	<319117.98395.qm@web86707.mail.ird.yahoo.com>
Message-ID: <y2w262679b51004181643g2cf79e5en8a0f33edb2ddd94b@mail.gmail.com>

Thanks again for your input.  Comments below with working (yea!) code.

On Sun, Apr 18, 2010 at 3:23 PM, ALAN GAULD <alan.gauld at btinternet.com> wrote:
> Does what I've shown make sense?

Alan - I think I got my mind around it -- I had never used lambda
functions before, so this is new territory to me.  Thanks for the
examples and I think it has me in the right direction.  I included
updated code below, which is working.

2010/4/18 spir ? <denis.spir at gmail.com>:
> All of this is not only plain data, but constant! The case of non-exisitng tag for a given format is, as shown by your 'pass', not to be handled here. Using a class is not only averkill but (wrong in my opininon and) misleading.
>
> Anyway it won't work since you need more than simple lookup in the case above, meaning some process must be done, and also the case of mp3 (iirc) titles shown in your first post.

Denis - I thought that with all the extra functions that would be
needed, making a class would simplify it for the user (me, in this
case).  I actually have another class that this will be merged into
(maybe it will make more sense then) ... I was just setting up the Tag
classes so I didn't confuse everyone with all the other code ...

Again - I believe I am on the right track (even if it is overkill --
wink).  Here is what I updated and what is working:

class TagNotSupported(Exception):
    '''Raised when trying to use a tag that is not currently supported across
    filetypes.  Hopefully we cover enough so this does not happen!'''

def set_tag(mutagen, tag, value):
    mutagen[tag] = value

class Tags(object):
    '''Wrapper class for a mutagen music file object.'''
    _get_tags = {}
    _set_tags = {}

    def __init__(self, mutagen):
        '''Requires a loaded mutagen object to get us rolling'''
        self._mutagen = mutagen

    def keys(self):
        '''Get list of tag keys in the file.'''
        keys = []
        for key in self._get_tags.keys():
            try:
                self._get_tags[key](self._mutagen)
                keys.append(key)
            except KeyError:
                pass
        return keys

    def save(self):
        '''Save the mutagen changes.'''
        self._mutagen.save()

class MP4Tags(Tags):

    _get_tags = {
        'album'         : lambda x: x['\xa9alb'],
        'artist'        : lambda x: x['\xa9ART'],
        'albumartist'   : lambda x: x['aART'],
        'compilation'   : lambda x: x['cpil'],
        'composer'      : lambda x: x['\xa9wrt'],
        'description'   : lambda x: x['\xa9cmt'],
        'discnumber'    : lambda x: [str(x['disk'][0][0]).decode('utf-8')],
        'disctotal'     : lambda x: [str(x['disk'][0][1]).decode('utf-8')],
        'genre'         : lambda x: x['\xa9gen'],
        'title'         : lambda x: x['\xa9nam'],
        'tracknumber'   : lambda x: [str(x['trkn'][0][0]).decode('utf-8')],
        'tracktotal'    : lambda x: [str(x['trkn'][0][1]).decode('utf-8')],
        'date'          : lambda x: x['\xa9day'],
        }

    _set_tags = {
        'album'         : lambda x, v: set_tag(x._mutagen, '\xa9alb', v),
        'albumartist'   : lambda x, v: set_tag(x._mutagen, 'aART',    v),
        'artist'        : lambda x, v: set_tag(x._mutagen, '\xa9ART', v),
        'compilation'   : lambda x, v: set_tag(x._mutagen, 'cpil',    v),
        'composer'      : lambda x, v: set_tag(x._mutagen, '\xa9wrt', v),
        'description'   : lambda x, v: set_tag(x._mutagen, '\xa9cmt', v),
        'discnumber'    : lambda x, v: x.x_of_y('disk', 0, v),
        'disctotal'     : lambda x, v: x.x_of_y('disk', 1, v),
        'genre'         : lambda x, v: set_tag(x._mutagen, '\xa9gen', v),
        'title'         : lambda x, v: set_tag(x._mutagen, '\xa9nam', v),
        'tracknumber'   : lambda x, v: x.x_of_y('trkn', 0, v),
        'tracktotal'    : lambda x, v: x.x_of_y('trkn', 1, v),
        'date'          : lambda x, v: set_tag(x._mutagen, '\xa9day', v),
    }

    def __getitem__(self, key):
        try:
            return self._get_tags[key](self._mutagen)
        except KeyError:
            pass

    def __setitem__(self, key, value):
        try:
            self._set_tags[key](self, value)
        except KeyError:
            raise TagNotSupported('The tag "' + key + '" is not supported.')

    def x_of_y(self, key, index, value):
        '''Used to set our disc and track information.  MP4 stores everything
        in a tuple of (x,y).'''

        try: # if this value is not already set, we need defaults
            init_val = self._mutagen[key][0]
        except KeyError:
            init_val = (0,0)

        try: # mutagen often passes things in lists, eg [u'1']
            value = int(value)
        except TypeError:
            value = int(value[0])

        if not index: # if index == 0
            self._mutagen[key] = [(value, init_val[1])]
        else: # if index == 1
            self._mutagen[key] = [(init_val[0], value)]

Thanks again.

From cmcaine at googlemail.com  Mon Apr 19 02:00:18 2010
From: cmcaine at googlemail.com (C M Caine)
Date: Mon, 19 Apr 2010 01:00:18 +0100
Subject: [Tutor] List index usage: is there a more pythonesque way?
In-Reply-To: <4BCB96F5.60903@gmail.com>
References: <q2nb98d9b671004181553g6ada64deo4e2e649dff327dd5@mail.gmail.com> 
	<4BCB96F5.60903@gmail.com>
Message-ID: <w2xb98d9b671004181700k9d79e4cfyd7ced01435754c04@mail.gmail.com>

> Something is wrong in the following if statement, as both paths execute the
> same code.
>
>> ? ? ? ? ? ? if spaceDict['1st'+key] == 0:
>> ? ? ? ? ? ? ? ? spaceDict['nth'+key] = i
>> ? ? ? ? ? ? else:
>> ? ? ? ? ? ? ? ? spaceDict['nth'+key] = i
>> ? ? ? ? for form in forms:
>> ? ? ? ? ? ? adjustedSpaceDict[form] = spaceDict['nth'+form] - \
>> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? spaceDict['1st'+form]
>> ? ? ? ? return (numDict, adjustedSpaceDict)


Oh yeah, I think I pulled up an old version of the source file by
accident, I've fixed that bug already.
The correct code is:

# stuff...
 ? ? ? ? ? ? if spaceDict['1st'+key] == 0:
 ? ? ? ? ? ? ? ? spaceDict['1st'+key] = i
 ? ? ? ? ? ? else:
 ? ? ? ? ? ? ? ? spaceDict['nth'+key] = i
 ? ? ? ? for form in forms:
 ? ? ? ? ? ? adjustedSpaceDict[form] = spaceDict['nth'+form] - \
 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? spaceDict['1st'+form]
 ? ? ? ? return (numDict, adjustedSpaceDict)

I don't think I'll use defaultdict here, though thanks for pointing it
out to me, that's the first time I've heard of it; I'm trying to keep
the number of outside modules to a minimum as this is an assessed
piece of work.

Thanks, Bob.


On 19 April 2010 00:34, bob gailer <bgailer at gmail.com> wrote:
> On 4/18/2010 6:53 PM, C M Caine wrote:
>>
>> # Example data for forms and timetable:
>> forms = ["P7", "P8", "P9", "P10", "P11", "S7", "S8", "S9", "S10",
>> "S11", "IMA", "CAT", "FOR", "RLS", "EMPTY"]
>>
>> timetable = ['CAT', 'P10', 'P8', 'EMPTY', 'EMPTY', 'EMPTY', 'S10',
>> 'S8', 'IMA', 'EMPTY', 'S7', 'S10', 'P9', 'EMPTY', 'EMPTY', 'EMPTY',
>> 'S7', 'EMPTY', 'EMPTY', 'RLS', 'FOR', 'EMPTY', 'EMPTY', 'EMPTY', 'S9',
>> 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY',
>> 'EMPTY', 'EMPTY', 'S8', 'IMA', 'S11', 'P8', 'EMPTY', 'IMA', 'EMPTY',
>> 'EMPTY', 'S11', 'S11', 'EMPTY', 'EMPTY', 'EMPTY', 'P7', 'S9', 'P11',
>> 'P11', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY', 'EMPTY',
>> 'EMPTY', 'EMPTY', 'P9', 'EMPTY', 'EMPTY', 'P8', 'FOR', 'S10', 'S11',
>> 'S7', 'P7', 'EMPTY', 'EMPTY', 'IMA', 'EMPTY', 'S9', 'P10', 'P11',
>> 'CAT', 'S8', 'P9', 'RLS']
>>
>> def analyseTimetable():
>> ? ? ? ? "Find number of and spaces between each form."
>>
>
> Consider using defaultdict in the collections module. The first time a key
> is referenced it is automatically added with a specified value.
>
>
> import collections
> ? ? ? ? numDict = collections.defaultdict(0)
> ? ? ? ? spaceDict = collections.defaultdict(0)
>
>> ? ? ? ? adjustedSpaceDict = {}
>>
>
> If you use enumerate then you can replace timetable[i] with key
>>
>> ? ? ? ? for i, key in enumerate(timetable):
>> ? ? ? ? ? ? numDict[key] += 1
>>
>
> Something is wrong in the following if statement, as both paths execute the
> same code.
>
>> ? ? ? ? ? ? if spaceDict['1st'+key] == 0:
>> ? ? ? ? ? ? ? ? spaceDict['nth'+key] = i
>> ? ? ? ? ? ? else:
>> ? ? ? ? ? ? ? ? spaceDict['nth'+key] = i
>> ? ? ? ? for form in forms:
>> ? ? ? ? ? ? adjustedSpaceDict[form] = spaceDict['nth'+form] - \
>> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? spaceDict['1st'+form]
>> ? ? ? ? return (numDict, adjustedSpaceDict)
>>
>> # End example
>>
>> This function works fine, but I think that using range(len(timetable))
>> is clumsy. On the other hand, I need the indexes to track the number
>> of spaces between instances of each form. Without using another loop
>> (so not using list.index), is there a way of getting the index of the
>> list entries?
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at btinternet.com  Mon Apr 19 09:18:49 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 19 Apr 2010 07:18:49 +0000 (GMT)
Subject: [Tutor] List index usage: is there a more pythonesque way?
In-Reply-To: <r2sb98d9b671004181637j3bebc8d9y748f5cdb8b1790e4@mail.gmail.com>
References: <q2nb98d9b671004181553g6ada64deo4e2e649dff327dd5@mail.gmail.com>
	<hqg3eu$r4v$1@dough.gmane.org>
	<r2sb98d9b671004181637j3bebc8d9y748f5cdb8b1790e4@mail.gmail.com>
Message-ID: <460705.42881.qm@web86708.mail.ird.yahoo.com>

> That's two new things I've learnt. I didn't realise that for loops
> could be used like that (with more than one... key?).

Technically its still one key but enumerate returns a tuple 
of index and value and we use tuple unpacking to assign 
the values to the loop variables. That is we could write it like:

for tup in enumerate(sequence):
     index = tup[0]
     value = tup[1]
     # process stufff here
OR:
for tup in enumerate(sequence):
     index,value  = tup
     # process stufff here

Which becomes
for index, value in enumerate(sequence):
     # process stufff here

HTH,

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100419/145ae46b/attachment-0001.html>

From denis.spir at gmail.com  Mon Apr 19 09:26:06 2010
From: denis.spir at gmail.com (spir =?UTF-8?B?4pij?=)
Date: Mon, 19 Apr 2010 09:26:06 +0200
Subject: [Tutor] List index usage: is there a more pythonesque way?
In-Reply-To: <r2sb98d9b671004181637j3bebc8d9y748f5cdb8b1790e4@mail.gmail.com>
References: <q2nb98d9b671004181553g6ada64deo4e2e649dff327dd5@mail.gmail.com>
	<hqg3eu$r4v$1@dough.gmane.org>
	<r2sb98d9b671004181637j3bebc8d9y748f5cdb8b1790e4@mail.gmail.com>
Message-ID: <20100419092606.0c0e86a4@o>

On Mon, 19 Apr 2010 00:37:11 +0100
C M Caine <cmcaine at googlemail.com> wrote:

> That's two new things I've learnt. I didn't realise that for loops
> could be used like that (with more than one... key?).

Consider considering things differently: a for loop always iterates over items of a collection you indicate:

l = [1,2,3]
# item is list item		(implicit, it could be written items(l) or l.items())
for n in l: print n,
# item is (index,item) pair
for (i,n) in enumerate(l): print (i,n),
print

d = {'a':1, 'b':2, 'c':3}
# item is dict key		(implicit, it could be written d.keys())
for k in d: print k,
# item is dict value
for v in d.values(): print v,
# item is (key,value) pair
for (k,v) in d.items(): print (k,v),
print

(In the last case "items()" is maybe a bit confusing.)

Python lets you construct your own iterators on custom collections to iterate in a different way:
class NestedList(list):
	def __iter__(self):
		ll = list.__iter__(self)
		for l in ll:
			for item in l:
				yield item
ll = NestedList([[1,2,3], [9,8]])
for n in ll: print n,

Denis
________________________________

vit esse estrany ?

spir.wikidot.com

From cmcaine at googlemail.com  Mon Apr 19 13:59:40 2010
From: cmcaine at googlemail.com (C M Caine)
Date: Mon, 19 Apr 2010 12:59:40 +0100
Subject: [Tutor] List index usage: is there a more pythonesque way?
In-Reply-To: <20100419092606.0c0e86a4@o>
References: <q2nb98d9b671004181553g6ada64deo4e2e649dff327dd5@mail.gmail.com> 
	<hqg3eu$r4v$1@dough.gmane.org>
	<r2sb98d9b671004181637j3bebc8d9y748f5cdb8b1790e4@mail.gmail.com>
	<20100419092606.0c0e86a4@o>
Message-ID: <x2ob98d9b671004190459r8fd415e3m16f307cc4533e606@mail.gmail.com>

That's the first I've read of iterating through dictionaries, I'd
assumed it was impossible because they're unordered. Your explanation
for defining your own iterables is much easier to understand than the
one I read before as well.

Thanks again.

2010/4/19 spir ? <denis.spir at gmail.com>:
> On Mon, 19 Apr 2010 00:37:11 +0100
> C M Caine <cmcaine at googlemail.com> wrote:
>
>> That's two new things I've learnt. I didn't realise that for loops
>> could be used like that (with more than one... key?).
>
> Consider considering things differently: a for loop always iterates over items of a collection you indicate:
>
> l = [1,2,3]
> # item is list item ? ? ? ? ? ? (implicit, it could be written items(l) or l.items())
> for n in l: print n,
> # item is (index,item) pair
> for (i,n) in enumerate(l): print (i,n),
> print
>
> d = {'a':1, 'b':2, 'c':3}
> # item is dict key ? ? ? ? ? ? ?(implicit, it could be written d.keys())
> for k in d: print k,
> # item is dict value
> for v in d.values(): print v,
> # item is (key,value) pair
> for (k,v) in d.items(): print (k,v),
> print
>
> (In the last case "items()" is maybe a bit confusing.)
>
> Python lets you construct your own iterators on custom collections to iterate in a different way:
> class NestedList(list):
> ? ? ? ?def __iter__(self):
> ? ? ? ? ? ? ? ?ll = list.__iter__(self)
> ? ? ? ? ? ? ? ?for l in ll:
> ? ? ? ? ? ? ? ? ? ? ? ?for item in l:
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?yield item
> ll = NestedList([[1,2,3], [9,8]])
> for n in ll: print n,
>
> Denis
> ________________________________
>
> vit esse estrany ?
>
> spir.wikidot.com
>

From alan.gauld at btinternet.com  Mon Apr 19 16:23:00 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 19 Apr 2010 15:23:00 +0100
Subject: [Tutor] List index usage: is there a more pythonesque way?
References: <q2nb98d9b671004181553g6ada64deo4e2e649dff327dd5@mail.gmail.com>
	<hqg3eu$r4v$1@dough.gmane.org><r2sb98d9b671004181637j3bebc8d9y748f5cdb8b1790e4@mail.gmail.com><20100419092606.0c0e86a4@o>
	<x2ob98d9b671004190459r8fd415e3m16f307cc4533e606@mail.gmail.com>
Message-ID: <hqhp0j$otr$1@dough.gmane.org>


"C M Caine" <cmcaine at googlemail.com> wrote 

> That's the first I've read of iterating through dictionaries, I'd
> assumed it was impossible because they're unordered. 

Iteration doesn't require order, only to get each item once.
Even in very old Python versions you could iterate a dictionary 
via the keys() method. More recently you can do it directly - although 
the effect is the same. There is no guarantee of order only that 
you process every item once.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From waynejwerner at gmail.com  Mon Apr 19 16:58:24 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Mon, 19 Apr 2010 09:58:24 -0500
Subject: [Tutor] List index usage: is there a more pythonesque way?
In-Reply-To: <hqhp0j$otr$1@dough.gmane.org>
References: <q2nb98d9b671004181553g6ada64deo4e2e649dff327dd5@mail.gmail.com> 
	<hqg3eu$r4v$1@dough.gmane.org>
	<r2sb98d9b671004181637j3bebc8d9y748f5cdb8b1790e4@mail.gmail.com>
	<20100419092606.0c0e86a4@o>
	<x2ob98d9b671004190459r8fd415e3m16f307cc4533e606@mail.gmail.com>
	<hqhp0j$otr$1@dough.gmane.org>
Message-ID: <z2l333efb451004190758rb588ed55h633886a300e87928@mail.gmail.com>

On Mon, Apr 19, 2010 at 9:23 AM, Alan Gauld <alan.gauld at btinternet.com>wrote:

>
> "C M Caine" <cmcaine at googlemail.com> wrote
>
>> That's the first I've read of iterating through dictionaries, I'd
>>
>> assumed it was impossible because they're unordered.
>>
>
> Iteration doesn't require order, only to get each item once.
> Even in very old Python versions you could iterate a dictionary via the
> keys() method. More recently you can do it directly - although the effect is
> the same. There is no guarantee of order only that you process every item
> once.


And of course if you want to get the items sorted you can iterate over
sorted(mydict.keys()).

-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100419/9c1a55c0/attachment.html>

From cmcaine at googlemail.com  Mon Apr 19 18:08:22 2010
From: cmcaine at googlemail.com (C M Caine)
Date: Mon, 19 Apr 2010 17:08:22 +0100
Subject: [Tutor]  List index usage: is there a more pythonesque way?
In-Reply-To: <20100419151159.4970e1cd@o>
References: <q2nb98d9b671004181553g6ada64deo4e2e649dff327dd5@mail.gmail.com> 
	<hqg3eu$r4v$1@dough.gmane.org>
	<r2sb98d9b671004181637j3bebc8d9y748f5cdb8b1790e4@mail.gmail.com>
	<20100419092606.0c0e86a4@o>
	<x2ob98d9b671004190459r8fd415e3m16f307cc4533e606@mail.gmail.com>
	<20100419151159.4970e1cd@o>
Message-ID: <h2jb98d9b671004190908la99df03oeacace7c2524e0b1@mail.gmail.com>

Spir sent this solely to me by accident, I think.


---------- Forwarded message ----------
From: spir ? <denis.spir at gmail.com>
Date: 2010/4/19
Subject: Re: [Tutor] List index usage: is there a more pythonesque way?
To: cmcaine at googlemail.com


On Mon, 19 Apr 2010 12:59:40 +0100
C M Caine <cmcaine at googlemail.com> wrote:

> That's the first I've read of iterating through dictionaries, I'd
> assumed it was impossible because they're unordered.

Hem, actually "ordered" and "unordered" mean whether the order is
meaningful or not. There are at least 2 implicit orders for each
collection:
* There order in which they where put in.
* The order in which they iterated.
But these can be meaningless, in the sense of arbitrary, like the
alphabetic order. As an example, consider a 'friends' collections:
* If it's just a group of friends, then it's unordered and maps to a
set data structure in python (and computer science, and maths).
* If they are put in the collection eg by favor (best friend first or
last), then it's an ordered *sequence*, and maps to a list data
structure in python (and numerous other languages).
As a consequence, precisely because order is meaningful, another
difference is a sequence can hold several times the same item, while
it makes no sense for a set.

[The choice of the term "list" is imo rather misleading. Eg a shopping
list does not mean one must buy the items in order ;-)]


Denis
________________________________

vit esse estrany ?

spir.wikidot.com

From matthew.carpenter.arevalo at googlemail.com  Tue Apr 20 00:01:32 2010
From: matthew.carpenter.arevalo at googlemail.com (Matthew Carpenter-Arevalo)
Date: Mon, 19 Apr 2010 15:01:32 -0700
Subject: [Tutor] Guess my number? Guess what's wrong!
In-Reply-To: <4BCA1AD4.5010001@comcast.net>
References: <w2gde116e9b1004171304za860dc4aoa8b48ed7b9d42e3e@mail.gmail.com>
	<4BCA1AD4.5010001@comcast.net>
Message-ID: <k2xde116e9b1004191501u8f15da7duc1bee9c8ad0f7e1a@mail.gmail.com>

Thanks!


On Sat, Apr 17, 2010 at 1:32 PM, Jim Byrnes <jf_byrnes at comcast.net> wrote:

> Matthew Carpenter-Arevalo wrote:
>
>> Hi Everyone,
>>
>> I'm a beginner python programmer, and I've been working on
>> the perennial 'guess my number' example.
>>
>> When I run this in my module, I get an infinite loop of 'higher' or
>> 'lower.'
>> Can anyone see where I'm going wrong herE?
>>
>> Thanks,
>>
>> MCA
>>
>>
>> # Guess my number
>>
>> # the computer picks a random number between 1 and 100
>> # the player tries to guess it and the computer lets
>> # the player know if the guess is too high, too low
>> # or right on the money
>>
>> print "\tWelcome to 'Guess my number'!"
>> print "\nI'm think of a number between 1 and 100."
>> print "Try to guess it in as few attempts as possible. \n"
>>
>> # set the initial values
>> # the number - represents the number the player has to guess
>> # raw_input = the player's first guess&  converts it into an integer.
>> # tries = # of guesses so far.
>>
>> import random
>>
>> the_number = random.randrange(100) + 1
>> guess = int(raw_input("Take a guess: "))
>> tries = 1
>>
>> # guessing loop
>> while (guess != the_number):
>>     if (guess>  the_number):
>>         print "lower..."
>>     else:
>>         print "Higher..."
>>
>> guess = int(raw_input("Take a guess: "))
>> tries += 1
>>
>
> Move the above two lines to align with "else" so they become part of the
> while loop.
>
>
>  print "You guessed it! The number was", the_number
>> print "and it only took you", tries, "tries!\n"
>>
>> raw_input("\n\nPress the enter key to exit.")
>>
>>  Regards,  Jim
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100419/d0c20973/attachment-0001.html>

From oberoc at gmail.com  Tue Apr 20 04:25:39 2010
From: oberoc at gmail.com (Tino Dai)
Date: Mon, 19 Apr 2010 22:25:39 -0400
Subject: [Tutor] getting original pattern from regular expression object
Message-ID: <p2j2ac5d4851004191925xe2be3c01oaccb72cdd92f4390@mail.gmail.com>

If I have:

import re
a=re.compile('foo')

is there a way to get the original pattern of foo from the object a?

Thanks,
Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100419/f29b5a8f/attachment.html>

From roadierich at googlemail.com  Tue Apr 20 04:33:03 2010
From: roadierich at googlemail.com (Rich Lovely)
Date: Tue, 20 Apr 2010 03:33:03 +0100
Subject: [Tutor] getting original pattern from regular expression object
In-Reply-To: <p2j2ac5d4851004191925xe2be3c01oaccb72cdd92f4390@mail.gmail.com>
References: <p2j2ac5d4851004191925xe2be3c01oaccb72cdd92f4390@mail.gmail.com>
Message-ID: <x2jf0b4202b1004191933i88906a89vfc3c36b8b46b2b1c@mail.gmail.com>

On 20 April 2010 03:25, Tino Dai <oberoc at gmail.com> wrote:
> If I have:
>
> import re
> a=re.compile('foo')
>
> is there a way to get the original pattern of foo from the object a?
>
> Thanks,
> Tino
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

a.pattern:

>>> import re
>>> a = re.compile("foo")
>>> a.pattern
'foo'


-- 
Rich "Roadie Rich" Lovely

Just because you CAN do something, doesn't necessarily mean you SHOULD.
In fact, more often than not, you probably SHOULDN'T.  Especially if I
suggested it.

10 re-discover BASIC
20 ???
30 PRINT "Profit"
40 GOTO 10

From lowelltackett at yahoo.com  Tue Apr 20 18:58:06 2010
From: lowelltackett at yahoo.com (Lowell Tackett)
Date: Tue, 20 Apr 2010 09:58:06 -0700 (PDT)
Subject: [Tutor] the binary math "wall"
Message-ID: <482228.80558.qm@web110116.mail.gq1.yahoo.com>

I'm running headlong into the dilemma of binary math representation, with game-ending consequences, e.g.:

>>> 0.15
0.14999999999999999

Obviously, any attempts to manipulate this value, under the misguided assumption that it is truly "0.15" are ill-advised, with inevitable bad results.

the particular problem I'm attempting to corral is thus:

>>> math.modf(18.15)
(0.14999999999999858, 18.0)

with some intermediate scrunching, the above snippet morphs to:

>>> (math.modf(math.modf(18.15)[0]*100)[0])/.6
1.6666666666664298

The last line should be zero, and needs to be for me to continue this algorithm.

Any of Python's help-aids that I apply to sort things out, such as formatting (%), or modules like "decimal" do nothing more than "powder up" the display for visual consumption (turning it into a string).  The underlying float value remains "corrupted", and any attempt to continue with the math adapts and re-incorporates the corruption.

What I'm shooting for, by the way, is an algorithm that converts a deg/min/sec formatted number to decimal degrees.  It [mostly] worked, until I stumbled upon the peculiar cases of 15 minutes and/or 45 minutes, which exposed the flaw.

What to do?  I dunno.  I'm throwing up my hands, and appealing to the "Council".

(As an [unconnected] aside, I have submitted this query as best I know how, using plain text and the "Tutor at ..." address.  There is something that either I, or my yahoo.com mailer *or both* doesn't quite "get" about these mailings.  But, I simply do my best, following advice I've been offered via this forum.  Hope this --mostly-- works.)

>From the virtual desk of Lowell Tackett  



      

From rabidpoobear at gmail.com  Tue Apr 20 19:20:04 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 20 Apr 2010 12:20:04 -0500
Subject: [Tutor] the binary math "wall"
In-Reply-To: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
References: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
Message-ID: <i2udfeb4471004201020vc3c09506if59068570dc8fc11@mail.gmail.com>

On Tue, Apr 20, 2010 at 11:58 AM, Lowell Tackett
<lowelltackett at yahoo.com> wrote:
> I'm running headlong into the dilemma of binary math representation, with game-ending consequences, e.g.:
>
>>>> 0.15
> 0.14999999999999999
>
> Obviously, any attempts to manipulate this value, under the misguided assumption that it is truly "0.15" are ill-advised, with inevitable bad results.
>

Yes, floats are slightly inaccurate.
No, this usually doesn't cause problems.

You can use the decimal module if you want.
But I think your problem is that your math is wrong.
You are assuming that your float values are precise and they are not.
You must check ranges when dealing with float values, not for specific values.
I.E. you should never depend on a value being 1 in a float calculation,
instead your equations need to be robust enough to deal with values
very close to 1 as well.
If your equations cannot handle this, then coerce the value to 1.
if .9999999 < i < 1.00001:
    i = 1

And before you say "but that is just a hack", no, that is the nature
of floating-point values.  No one ever claimed that they were precise
or that you should depend on their values being precise.

If you really care so much, use the decimal module.
But you really just need to adapt your formulas from the ideal to the
reality, in which the values are not necessarily complete.

May I suggest another approach though?
Why even process these values as floats?

Consider this:
>>> a = 18.15
>>> a
18.149999999999999
>>> a = '18.15'
>>> degree, min = map(int, a.split('.'))
>>> degree
18
>>> min
15

Supposing you get your input as a string.
Basically the second you let your value end up stored as a float,
there's no turning back.  You need to get ahold of this value before
it becomes a float and deal with it in a different way.  The most
straightforward is to deal with the parts individually as integers.

Eventually you will develop a distrust for floats and you will
intrinsically know where and when you should / shouldn't use them ;)

Hope that helps,
-Luke

From malaclypse2 at gmail.com  Tue Apr 20 19:22:30 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Tue, 20 Apr 2010 13:22:30 -0400
Subject: [Tutor] the binary math "wall"
In-Reply-To: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
References: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
Message-ID: <z2n16651e81004201022u43c94b84nf977c9616572e3d3@mail.gmail.com>

On Tue, Apr 20, 2010 at 12:58 PM, Lowell Tackett
<lowelltackett at yahoo.com> wrote:
> Any of Python's help-aids that I apply to sort things out, such as formatting (%), or modules like "decimal" do nothing more than "powder up" the display for visual consumption (turning it into a string). ?The underlying float value remains "corrupted", and any attempt to continue with the math adapts and re-incorporates the corruption.

Using the decimal module does not convert anything to strings.  The
decimal module gives you floating point arithmetic with base 10 rather
than base 2.

You examples seem to work okay for me using decimals:

IDLE 2.6.4
>>> import decimal
>>> n = decimal.Decimal("18.15")

>>> n
Decimal('18.15')

>>> print n
18.15

>>> divmod(n, 1)
(Decimal('18'), Decimal('0.15'))

>>> divmod(divmod(n, 1)[1]*100, 1)[1]/decimal.Decimal("0.6")
Decimal('0.0')

If you need to avoid floating point calculations entirely, you might
try the fractions module (new in python 2.6):

>>> import fractions
>>> n = fractions.Fraction("18.15")

>>> n
Fraction(363, 20)

>>> print n
363/20

>>> divmod(divmod(n, 1)[1]*100, 1)[1]/fractions.Fraction("0.6")
Fraction(0, 1)

>>> print divmod(divmod(n, 1)[1]*100, 1)[1]/fractions.Fraction("0.6")
0

and if you need to convert to float at the end:

>>> float(divmod(divmod(n, 1)[1]*100, 1)[1]/fractions.Fraction("0.6"))
0.0
>>>

-- 
Jerry

From waynejwerner at gmail.com  Tue Apr 20 19:23:48 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Tue, 20 Apr 2010 12:23:48 -0500
Subject: [Tutor] the binary math "wall"
In-Reply-To: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
References: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
Message-ID: <i2k333efb451004201023jf468e413y4e39a0b795cd9bb7@mail.gmail.com>

On Tue, Apr 20, 2010 at 11:58 AM, Lowell Tackett <lowelltackett at yahoo.com>wrote:

> I'm running headlong into the dilemma of binary math representation, with
> game-ending consequences, e.g.:
>
> >>> 0.15
> 0.14999999999999999
>
> Obviously, any attempts to manipulate this value, under the misguided
> assumption that it is truly "0.15" are ill-advised, with inevitable bad
> results.
>
> the particular problem I'm attempting to corral is thus:
>
> >>> math.modf(18.15)
> (0.14999999999999858, 18.0)
>
> with some intermediate scrunching, the above snippet morphs to:
>
> >>> (math.modf(math.modf(18.15)[0]*100)[0])/.6
> 1.6666666666664298
>
> The last line should be zero, and needs to be for me to continue this
> algorithm.
>
> Any of Python's help-aids that I apply to sort things out, such as
> formatting (%), or modules like "decimal" do nothing more than "powder up"
> the display for visual consumption (turning it into a string).  The
> underlying float value remains "corrupted", and any attempt to continue with
> the math adapts and re-incorporates the corruption.
>

That is not precisely correct - modf first converts decimal to a float and
then applies the calculation. Try this instead:

def modf(mydecimal):
    num = decimal.Decimal('1.0')
    return (mydecimal%num, mydecimal//num)

On my machine this returns (with
In [18]: modf(d)
Out[18]: (Decimal('0.15'), Decimal('18'))

Which are easily converted.
In [30]: (modf(modf(d)[0]*100)[0])/decimal.Decimal('.6')
Out[30]: Decimal('0.0')

So your problem with decimal isn't that it lacks the precision you're
seeking - you're simply converting it to a float /before/ performing the
calculations, which makes turning it into a decimal in the first place
pretty much useless.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100420/293ee888/attachment.html>

From denis.spir at gmail.com  Tue Apr 20 19:41:35 2010
From: denis.spir at gmail.com (spir =?UTF-8?B?4pij?=)
Date: Tue, 20 Apr 2010 19:41:35 +0200
Subject: [Tutor] the binary math "wall"
In-Reply-To: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
References: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
Message-ID: <20100420194135.396aa360@o>

On Tue, 20 Apr 2010 09:58:06 -0700 (PDT)
Lowell Tackett <lowelltackett at yahoo.com> wrote:

> I'm running headlong into the dilemma of binary math representation, with game-ending consequences, e.g.:
> 
> >>> 0.15
> 0.14999999999999999
> [...]
> The last line should be zero, and needs to be for me to continue this algorithm.
> 
> Any of Python's help-aids that I apply to sort things out, such as formatting (%), or modules like "decimal" do nothing more than "powder up" the display for visual consumption (turning it into a string).  The underlying float value remains "corrupted",

You are wrong:

>>> from decimal import Decimal
>>> s  = "0.15"
>>> Decimal(s) == float(s)

This shows, maybe weirdly, that the decimal version != 0.14999999999999999 --since it is actually equal to 0.15. Decimals are *not* internally represented as binary values, but instead with groups of bits each coding a *decimal* digit; this is precisely the point. Else why do you think developpers would cope with such a problem?


Denis
________________________________

vit esse estrany ?

spir.wikidot.com

From lie.1296 at gmail.com  Tue Apr 20 19:50:01 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Wed, 21 Apr 2010 03:50:01 +1000
Subject: [Tutor] the binary math "wall"
In-Reply-To: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
References: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
Message-ID: <hqkpj4$h16$1@dough.gmane.org>

On 04/21/10 02:58, Lowell Tackett wrote:
> I'm running headlong into the dilemma of binary math representation, with game-ending consequences, e.g.:
> 

Never use float for representing numbers, use float to represent a
"magnitude", do not rely on the exact representation of the number itself.

If you need to control the representation of your number, either keep
the number as integers or string or use fixed-point arithmetic
(Decimal), depending on your use case.


From lowelltackett at yahoo.com  Tue Apr 20 20:20:47 2010
From: lowelltackett at yahoo.com (Lowell Tackett)
Date: Tue, 20 Apr 2010 11:20:47 -0700 (PDT)
Subject: [Tutor] the binary math "wall"
In-Reply-To: <i2udfeb4471004201020vc3c09506if59068570dc8fc11@mail.gmail.com>
Message-ID: <268266.81235.qm@web110108.mail.gq1.yahoo.com>


>From the virtual desk of Lowell Tackett  



--- On Tue, 4/20/10, Luke Paireepinart <rabidpoobear at gmail.com> wrote:

> From: Luke Paireepinart <rabidpoobear at gmail.com>
> Subject: Re: [Tutor] the binary math "wall"
> To: "Lowell Tackett" <lowelltackett at yahoo.com>
> Cc: "tutor" <Tutor at python.org>
> Date: Tuesday, April 20, 2010, 1:20 PM
> On Tue, Apr 20, 2010 at 11:58 AM,
> Lowell Tackett
> <lowelltackett at yahoo.com>
> wrote:
> > I'm running headlong into the dilemma of binary math
> representation, with game-ending consequences, e.g.:
> >
> >>>> 0.15
> > 0.14999999999999999
> >
> 
> Yes, floats are slightly inaccurate.
> 
> But I think your problem is that your math is wrong.
> You are assuming...
> If your equations cannot handle this, then coerce the value
> to 1.
> if .9999999 < i < 1.00001:
>     i = 1
> 
> And before you say "but that is just a hack", no, that is
> the nature...
> But you really just need to adapt...
> 
> May I suggest another approach though?
> 
> Consider this:
> >>> a = 18.15
> >>> a
> 18.149999999999999
> >>> a = '18.15'
> >>> degree, min = map(int, a.split('.'))
> >>> degree
> 18
> >>> min
> 15
> 
> Supposing you get your input as a string.
> Basically the second you let your value end up stored as a
> float,
> there's no turning back...
> 
> Eventually you will develop a distrust for floats...
> 
> Hope that helps,
> -Luke
> 

I was gonna go out jogging - and in a coupla hours check to see if anyone had tried to take this "on"; going out the door I decided to take a quick look.  Ahem...

These responses just "blow me away" on a couple of levels.  I'm choosing "Luke"'s offering as representative.  Within <minutes> some great folks had read, parsed, and re-structured my query.  My narrow focus yells out my inexperience...I was trying as hard as I could, with limited tools, to solve the issue.  That's fine.  But...the breadth and depth of the responses represent nothing short of a paradigm shift in my window into this world of "hacking".

Ya'll have insights of a scale unimagined in the confines of my "thinking box".  (Now, I gotta go out and jog just to clear my head!)  Then come back...and pull the blinds closed...and absorb; and come up for air in maybe a week or so.  And only then, be able to offer my thanks with an objective sense of how much I've been helped today...Wow!


      

From davea at ieee.org  Tue Apr 20 20:45:50 2010
From: davea at ieee.org (Dave Angel)
Date: Tue, 20 Apr 2010 14:45:50 -0400
Subject: [Tutor] the binary math "wall"
In-Reply-To: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
References: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
Message-ID: <4BCDF65E.7010800@ieee.org>

Lowell Tackett wrote:
> I'm running headlong into the dilemma of binary math representation, with game-ending consequences, e.g.:
>
>   
>>>> 0.15
>>>>         
> 0.14999999999999999
>
> Obviously, any attempts to manipulate this value, under the misguided assumption that it is truly "0.15" are ill-advised, with inevitable bad results.
>
> the particular problem I'm attempting to corral is thus:
>
>   
>>>> math.modf(18.15)
>>>>         
> (0.14999999999999858, 18.0)
>
> with some intermediate scrunching, the above snippet morphs to:
>
>   
>>>> (math.modf(math.modf(18.15)[0]*100)[0])/.6
>>>>         
> 1.6666666666664298
>
> The last line should be zero, and needs to be for me to continue this algorithm.
>
> Any of Python's help-aids that I apply to sort things out, such as formatting (%), or modules like "decimal" do nothing more than "powder up" the display for visual consumption (turning it into a string).  The underlying float value remains "corrupted", and any attempt to continue with the math adapts and re-incorporates the corruption.
>
> What I'm shooting for, by the way, is an algorithm that converts a deg/min/sec formatted number to decimal degrees.  It [mostly] worked, until I stumbled upon the peculiar cases of 15 minutes and/or 45 minutes, which exposed the flaw.
>
> What to do?  I dunno.  I'm throwing up my hands, and appealing to the "Council".
>
> (As an [unconnected] aside, I have submitted this query as best I know how, using plain text and the "Tutor at ..." address.  There is something that either I, or my yahoo.com mailer *or both* doesn't quite "get" about these mailings.  But, I simply do my best, following advice I've been offered via this forum.  Hope this --mostly-- works.)
>
> >From the virtual desk of Lowell Tackett  
>
>
>   
One of the cases you mention is 1.6666666    The decimal package won't 
help that at all.  What the decimal package does for you is two-fold:
    1) it means that what displays is exactly what's there
    2) it means that errors happen in the same places where someone 
doing it "by hand" will encounter.

But if you literally have to support arbitrary rational values 
(denominators other than 2 or 5), you would need to do fractions, either 
by explicitly keeping sets of ints, or by using a fractions library.  
And if you have to support arbitrary arithmetic, there's no answer other 
than hard analysis.

This is not a Python-specific problem.  Floating point has had such 
issues in every language I've dealt with since 1967, when I first 
learned Fortran.  If you compare two values, the simplest mechanism is
    abs(a-b) < delta

where you have to be clever about what small value to use for delta.

If all values are made up of  degrees/minutes/seconds, and seconds is a 
whole number, then store values as num-seconds, and do all arithmetic on 
those values.  Only convert them back to deg/min/sec upon output.

DaveA


From denis.spir at gmail.com  Tue Apr 20 21:38:26 2010
From: denis.spir at gmail.com (spir =?UTF-8?B?4pij?=)
Date: Tue, 20 Apr 2010 21:38:26 +0200
Subject: [Tutor] the binary math "wall"
In-Reply-To: <4BCDF65E.7010800@ieee.org>
References: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
	<4BCDF65E.7010800@ieee.org>
Message-ID: <20100420213826.751d7f48@o>

On Tue, 20 Apr 2010 14:45:50 -0400
Dave Angel <davea at ieee.org> wrote:

> If all values are made up of  degrees/minutes/seconds, and seconds is a 
> whole number, then store values as num-seconds, and do all arithmetic on 
> those values.  Only convert them back to deg/min/sec upon output.

This seems the most direct answer of the issue. If performance is not critical, I would even write a small Angle type with ? ' '' int attributes to get rid of (read: abstract away) all complexity once and for all.

Denis
________________________________

vit esse estrany ?

spir.wikidot.com

From Mike.Hansen at atmel.com  Wed Apr 21 00:11:33 2010
From: Mike.Hansen at atmel.com (Hansen, Mike)
Date: Tue, 20 Apr 2010 16:11:33 -0600
Subject: [Tutor] Python Examples of processing MS Outlook
In-Reply-To: <003001cadd45$128a5ce0$379f16a0$@com>
References: <003001cadd45$128a5ce0$379f16a0$@com>
Message-ID: <7941B2693F32294AAF16C26B679A258D10383F94@csomb01.corp.atmel.com>

 

> -----Original Message-----
> From: tutor-bounces+mike.hansen=atmel.com at python.org 
> [mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On 
> Behalf Of Peter Meagher
> Sent: Friday, April 16, 2010 3:13 AM
> To: tutor at python.org
> Subject: [Tutor] Python Examples of processing MS Outlook
> 
> Greetings,
> 
>  
> 
> I'm doing a lot of email processing at the moment.  I put 
> together some basic code from within Outlook to open my 
> default inbox, filter email records based on text in the 
> Subject field, then parse the body, finally send the output 
> to a text file.  This is simple stuff but very useful.
> 
>  
> 
> I need to do more, however as a newbie with Python, I figured 
> I could both learn and produce at the same time.
> 
>  
> 
> Does anyone have references to simple MS Outlook 2007 
> processing code that I could vulture for my purposes?  (The 
> code that I adapted was from an old Office 2000 vba text, so 
> the version 2007 may not be that essential to my purposes)
> 
>  
> 
> After much searching, I found a reference to PyWebmail, 
> however it communicates directly to the webmail accounts, is 
> much more than I really need and I want to stay in the 
> Outlook environment for a number of reasons, particularly its 
> interface to Access.
> 
>  
> 
> Thank you.
> 
> Peter Meagher
> 
> 

You probably need to look at Python COM. Another problem with Outlook is that it has some security that prevents other programs from controlling it in response to various virus attacks. I think there's a way around it.

Mike

From steve at pearwood.info  Wed Apr 21 01:39:30 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 21 Apr 2010 09:39:30 +1000
Subject: [Tutor] the binary math "wall"
In-Reply-To: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
References: <482228.80558.qm@web110116.mail.gq1.yahoo.com>
Message-ID: <201004210939.31224.steve@pearwood.info>

On Wed, 21 Apr 2010 02:58:06 am Lowell Tackett wrote:
> I'm running headlong into the dilemma of binary math representation, 
with game-ending consequences, e.g.:
> >>> 0.15
>
> 0.14999999999999999
>
> Obviously, any attempts to manipulate this value, under the misguided
> assumption that it is truly "0.15" are ill-advised, with inevitable
> bad results.

That really depends on what sort of manipulation you are doing.

>>> x = 0.15
>>> x
0.14999999999999999
>>> x*100 == 15
True

Seems pretty accurate to me.

However:

>>> 18.15*100 == 1815
False


The simplest, roughest way to fix these sorts of problems (at the risk 
of creating *other* problems!) is to hit them with a hammer:

>>> round(18.15*100) == 1815
True

[...]
> What I'm shooting for, by the way, is an algorithm that converts a
> deg/min/sec formatted number to decimal degrees.  It [mostly] worked,
> until I stumbled upon the peculiar cases of 15 minutes and/or 45
> minutes, which exposed the flaw.

I'm afraid that due to the nature of floating point, this is a hard 
problem. Even the professionals at Hewlett-Packard's scientific 
calculator division don't always get it right, and they are *extremely* 
careful:

http://www.hpmuseum.org/cgi-sys/cgiwrap/hpmuseum/archv018.cgi?read=132690

The best result I can suggest is, change the problem! Don't pass 
degrees-minutes-seconds around using a floating point value, but as a 
tuple with distinct (DEG, MIN, SEC) integer values. Or create a custom 
class.

But if you really need D.MMSS floats, then something like this should be 
a good start.:

def dms2deg(f):
    """Convert a floating point number formatted as D.MMSS 
    into degrees.
    """
    mmss, d = math.modf(f)
    assert d == int(f)
    if mmss >= 0.60:
        raise ValueError(
        'bad fractional part, expected < .60 but got %f' % mmss)
    mmss *= 100
    m = round(mmss)
    if m >= 60:
        raise ValueError('bad minutes, expected < 60 but got %d' % m)
    s = round((mmss - m)*100, 8)
    if not 0 <= s < 60.0:
        raise ValueError('bad seconds, expected < 60.0 but got %f' % s)
    return d + m/60.0 + s/3600.0


>>> dms2deg(18.15)
18.25
>>> dms2deg(18.1515)
18.254166666666666


which compares well to my HP-48GX:

18.15 HMS->

gives 18.25, and:

18.1515 HMS->

gives 18.2541666667.


Note though that this still fails with some valid input. I will leave 
fixing it as an exercise (or I might work on it later, time 
permitting).


-- 
Steven D'Aprano

From lowelltackett at yahoo.com  Wed Apr 21 04:11:24 2010
From: lowelltackett at yahoo.com (Lowell Tackett)
Date: Tue, 20 Apr 2010 19:11:24 -0700 (PDT)
Subject: [Tutor] the binary math "wall"
In-Reply-To: <201004210939.31224.steve@pearwood.info>
Message-ID: <776327.57413.qm@web110101.mail.gq1.yahoo.com>


>From the virtual desk of Lowell Tackett  



--- On Tue, 4/20/10, Steven D'Aprano <steve at pearwood.info> wrote:

> From: Steven D'Aprano <steve at pearwood.info>
> Subject: Re: [Tutor] the binary math "wall"
> To: tutor at python.org
> Date: Tuesday, April 20, 2010, 7:39 PM
> On Wed, 21 Apr 2010 02:58:06 am
> Lowell Tackett wrote:
> > I'm running headlong into the dilemma of binary math
> representation, 
> with game-ending consequences, e.g.:
> > >>> 0.15
> >
> > 0.14999999999999999
> >
> > Obviously, any attempts to manipulate this value,
> under the misguided
> > assumption that it is truly "0.15" are ill-advised,
> with inevitable
> > bad results.
> 
> That really depends on what sort of manipulation you are
> doing.
> 
> >>> x = 0.15
> >>> x
> 0.14999999999999999
> >>> x*100 == 15
> True
> 
> Seems pretty accurate to me.
> 
> However:
> 
> >>> 18.15*100 == 1815
> False
> 
> 
> The simplest, roughest way to fix these sorts of problems
> (at the risk 
> of creating *other* problems!) is to hit them with a
> hammer:
> 
> >>> round(18.15*100) == 1815
> True

Interestingly, this is the [above] result when I tried entered the same snippet:

Python 2.5.1 (r251:54863, Oct 14 2007, 12:51:35)
[GCC 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> round(18.15)*100 == 1815
False
>>>

But...I'm just offering that for its' curiosity value, not to contradict your comments or the case you are making.
> 
> [...]
> > What I'm shooting...is an algorithm
> that converts a
> > deg/min/sec formatted number to decimal degrees. 
> It [mostly] worked...which exposed the flaw.
> 
> I'm afraid that due to the nature of floating point, this
> is a hard 
> problem. Even the professionals at Hewlett-Packard's
> scientific 
> calculator division don't always get it right, and they are
> *extremely* 
> careful:
> 
> http://www.hpmuseum.org/cgi-sys/cgiwrap/hpmuseum/archv018.cgi?read=132690
> 

Interesting that you raise the *hallowed* 48GX as a standard.  I have one (of the two I own) sitting next to me here, and have been using it as the bar against which to compare my computer.  Using the HMS+/-/-> etc. functions, I get pretty darned accurate results.  (Wish I'd known in time that HP was gonna throw the "48's" down the drain-I would own a lot more than two of them!)

> The best result I can suggest is, change the problem! Don't
> pass 
> degrees-minutes-seconds around using a floating point
> value, but as a 
> tuple with distinct (DEG, MIN, SEC) integer values. Or
> create a custom 
> class.
> 
> But if you really need D.MMSS floats, then something like
> this should be 
> a good start.:
> 
> def dms2deg(f):
>     """Convert a floating point number formatted
> as D.MMSS 
>     into degrees.
>     """
>     mmss, d = math.modf(f)
>     assert d == int(f)
>     if mmss >= 0.60:
>         raise ValueError(
>         'bad fractional part, expected
> < .60 but got %f' % mmss)
>     mmss *= 100
>     m = round(mmss)
>     if m >= 60:
>         raise ValueError('bad minutes,
> expected < 60 but got %d' % m)
>     s = round((mmss - m)*100, 8)
>     if not 0 <= s < 60.0:
>         raise ValueError('bad seconds,
> expected < 60.0 but got %f' % s)
>     return d + m/60.0 + s/3600.0
> 
> 
> >>> dms2deg(18.15)
> 18.25
> >>> dms2deg(18.1515)
> 18.254166666666666
> 
> 
> which compares well to my HP-48GX:
> 
> 18.15 HMS->
> 
> gives 18.25, and:
> 
> 18.1515 HMS->
> 
> gives 18.2541666667.
> 
> 
> Note though that this still fails with some valid input. I
> will leave 
> fixing it as an exercise (or I might work on it later, time
> 
> permitting).
> 
> 
> -- 
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 

What you've provided with your comments is more of what I've received wholesale in this entire discourse--an incredible wealth of new insight and ways of looking at the problem.  Don't think you grasp how new I am at this, and how even what little I've tried to "pull off"-on my own-is way out at the edge of the "box" for me.  Someone wondered if performance was an issue that could effect my choices.  Well, no.  Basically, I want to manipulate [land] survey data - you know, coordinates and stuff - so the goal here is coding those things that will yield accurate number results.

I've been handed, in response, comments about the challenges going all the way back to the early days of Fortran, stuff I had no concept of.  This is all fantastic, and it's gonna take a long time for me to assimilate and absorb what has been offered.  Even your comment concerning creating a class--my reaction is "Oh, oh--classes?  What'da I do NOW?!"  But, I've been given a great deal to chew on, and the implications go way beyond the scope of my original query.

Did I get what I asked for when I posed my question?  I'd say so...about 10X!  Now I gotta go to work and gain some good knowledge out of this mountain of advice that's been piled on my desk!

Thanks, all...


      

From marcodrompre at gmail.com  Wed Apr 21 04:37:05 2010
From: marcodrompre at gmail.com (=?ISO-8859-1?Q?Marco_Rompr=E9?=)
Date: Tue, 20 Apr 2010 22:37:05 -0400
Subject: [Tutor] Need some info
Message-ID: <j2w4bdcec5e1004201937r6a52c05ejc95d60cee441add3@mail.gmail.com>

Hi! in my programming course at university, I need to create a python model
with 2 concepts in a one towards many relation  each of them  having 2-3
properties.

Also, I need to create an application with screens to add, modify, and
delete the data of the model.

Can someone know where I can find the information that would help me to
successfully complete my assignment????

Thank You!!!

--
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100420/c42c2d3f/attachment.html>

From waynejwerner at gmail.com  Wed Apr 21 04:44:53 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Tue, 20 Apr 2010 21:44:53 -0500
Subject: [Tutor] Need some info
In-Reply-To: <j2w4bdcec5e1004201937r6a52c05ejc95d60cee441add3@mail.gmail.com>
References: <j2w4bdcec5e1004201937r6a52c05ejc95d60cee441add3@mail.gmail.com>
Message-ID: <h2n333efb451004201944ud1f9526aza5f37f1b09c56f25@mail.gmail.com>

On Tue, Apr 20, 2010 at 9:37 PM, Marco Rompr? <marcodrompre at gmail.com>wrote:

> Hi! in my programming course at university, I need to create a python model
> with 2 concepts in a one towards many relation  each of them  having 2-3
> properties.
>
> Also, I need to create an application with screens to add, modify, and
> delete the data of the model.
>
> Can someone know where I can find the information that would help me to
> successfully complete my assignment????
>
>
Check with 1) Your professor/course materials 2) Documentation at python.org

And if all else fails, you can ask here if you post 1) Where you are so far
2) What you're doing that you think should work 3) What python tells you is
the problem, and any other sundry details.

Obviously we don't do homework here, but we're more than happy to help those
who get stuck on a problem.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100420/89b3c3e8/attachment.html>

From alan.gauld at btinternet.com  Wed Apr 21 09:25:36 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Apr 2010 08:25:36 +0100
Subject: [Tutor] Need some info
References: <j2w4bdcec5e1004201937r6a52c05ejc95d60cee441add3@mail.gmail.com>
Message-ID: <hqm9a1$9h6$1@dough.gmane.org>


"Marco Rompr?" <marcodrompre at gmail.com> wrote

> Hi! in my programming course at university, I need to create a python model
> with 2 concepts in a one towards many relation  each of them  having 2-3
> properties.

Are you allowed to use a relational database as part of the solution?
That would simplify things because managing relationships is pretty
much what they do... If you have to do it from scratch using Python
only then it a much more challenging task.

How much Python do you know?
How much of any programming language do you know?
How much about relational algebra do you know?

> Also, I need to create an application with screens to add, modify, and
> delete the data of the model.

This is the easy bit. Either using web or windows techniques.
Which OS are you using?

> Can someone know where I can find the information that would help me to
> successfully complete my assignment????

For the theory asp[ect Wikipedia is a good start.
For Python try both python.org and Activestate.com

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From rabidpoobear at gmail.com  Wed Apr 21 09:40:54 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 21 Apr 2010 02:40:54 -0500
Subject: [Tutor] Changing Default Install Path on Windows
Message-ID: <m2xdfeb4471004210040jaea3f3a7g75780de67b70a31c@mail.gmail.com>

Hi guys,
my first post to the list with a question rather than a response in a
few years, I think :)

(NOTE: I solved my question while writing this e-mail, I'm just
mailing this to the list for future users now)

I'm running Windows 7 64-bit.

I currently have 3 python installs.
First I installed the 64-bit version of Python 2.6 to C:\Python26,
then realized that it doesn't have as much lib support.
Then I installed the 32-bit version to C:\Python26x86
Everything worked fine after this (installs, etc. all went to the
proper site-packages.)

Then I installed Panda3D and normally it doesn't hijack your Python
install but I guess in this case I accidentally told it to become
default.

Now, when I try to run an installer, it finds the Panda3D Python first.

I'm getting really frustrated because I can't figure out why it's
finding the Panda3D Python.
I don't understand how the multiple version precedence works.


In my registry, HKLM / SOFTWARE / Python, all I have is PythonCore/2.6
and all references in here (PythonPath, InstallPath, etc. etc.) all
reference the FIRST python install (C:\Python26)

My PATH environment variable is:
C:\Users\rabidpoobear>echo %path%

C:\Program Files (x86)\PC Connectivity
Solution\;C:\Python26x86\Lib\site-packages\PyQt4\bin;C:\Program Files
(x86)\NVIDIA Corporation\PhysX\
Common;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program
Files\TortoiseSVN\bin;
C:\python26x86;C:\Program Files
(x86)\Graphviz2.26.3\bin;C:\jython2.5.1;C:\Panda3D-1.7.0\bin

the Panda3D bin directory does NOT contain a python.exe, it only
contains panda3d stuff.  The Panda3d python install is in
C:\Panda3D-1.7.0\python

I cannot find any references to the Panda3D python install ANYWHERE.

Yet anytime I try to run an installer, it tries to install there.  And
the stupid "helpful" python installers that auto-find the directory do
not let you change it.
They make the (faulty) assumption that they're correct.

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

I figured out the solution, I just did a Find on my entire registry
and found C:\Panda3D-1.7.0 in
HKLM\Software\Wow6432Node\Python\PythonCore\2.6\InstallPath .
After some investigation it seems that the special Wow6432Node has to
do with 64-bit versions of Windows running 32-bit versions of Python.

So the lesson we've learned today is that your 64-bit Python install
path should will be where it normally is
(HKLM\Software\Python\PythonCore\version\InstallPath)
but your 32-bit path will be in that special WowNode directory.

Hope that helps someone in the future,
-Luke

From denis.spir at gmail.com  Wed Apr 21 10:35:29 2010
From: denis.spir at gmail.com (spir =?UTF-8?B?4pij?=)
Date: Wed, 21 Apr 2010 10:35:29 +0200
Subject: [Tutor] the binary math "wall"
In-Reply-To: <776327.57413.qm@web110101.mail.gq1.yahoo.com>
References: <201004210939.31224.steve@pearwood.info>
	<776327.57413.qm@web110101.mail.gq1.yahoo.com>
Message-ID: <20100421103529.2baff09e@o>

On Tue, 20 Apr 2010 19:11:24 -0700 (PDT)
Lowell Tackett <lowelltackett at yahoo.com> wrote:

> > >>> round(18.15*100) == 1815  
> > True  
> 
> Interestingly, this is the [above] result when I tried entered the same snippet:
> 
> Python 2.5.1 (r251:54863, Oct 14 2007, 12:51:35)
> [GCC 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> round(18.15)*100 == 1815  
> False
> >>>  
> 
> But...I'm just offering that for its' curiosity value, not to contradict your comments or the case you are making.

hum hum hum...

Denis
________________________________

vit esse estrany ?

spir.wikidot.com

From davea at ieee.org  Wed Apr 21 12:46:31 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 21 Apr 2010 06:46:31 -0400
Subject: [Tutor] the binary math "wall"
In-Reply-To: <776327.57413.qm@web110101.mail.gq1.yahoo.com>
References: <776327.57413.qm@web110101.mail.gq1.yahoo.com>
Message-ID: <4BCED787.70207@ieee.org>



Lowell Tackett wrote:
> --- On Tue, 4/20/10, Steven D'Aprano <steve at pearwood.info> wrote:
>
>   
>> From: Steven D'Aprano <steve at pearwood.info>
>>     
>> <snip>
>>
>> The simplest, roughest way to fix these sorts of problems
>> (at the risk 
>> of creating *other* problems!) is to hit them with a
>> hammer:
>>
>>     
>>>>> round(18.15*100) == 1815
>>>>>           
>> True
>>     
>
> Interestingly, this is the [above] result when I tried entered the same snippet:
>
> Python 2.5.1 (r251:54863, Oct 14 2007, 12:51:35)
> [GCC 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>   
>>>> round(18.15)*100 == 1815
>>>>         
> False
>   
>
> <snip>
But you typed it differently than Steven.  He had   round(18.15*100), 
and you used round(18.15)*100

Very different.   His point boils down to comparing integers, and when 
you have dubious values, round them to an integer before comparing.  I 
have my doubts, since in this case it would lead to bigger sloppiness 
than necessary.

round(18.154 *100) == 1815

probably isn't what you'd want.

So let me ask again, are all angles a whole number of seconds?  Or can 
you make some assumption about how accurate they need to be when first 
input (like tenths of a second, or whatever)?  If so use an integer as 
follows:

val =  round((((degrees*60)+minutes)*60) + seconds)*10)

The 10 above is assuming that tenths of a second are your quantization.

HTH
DaveA


From stefan at lsd.co.za  Wed Apr 21 14:17:49 2010
From: stefan at lsd.co.za (Stefan Lesicnik)
Date: Wed, 21 Apr 2010 14:17:49 +0200 (SAST)
Subject: [Tutor] classes passing information
In-Reply-To: <838411876.2098.1271852153515.JavaMail.root@zimbra>
Message-ID: <62261639.2100.1271852269249.JavaMail.root@zimbra>

Hi Guys,

I'm slowly starting to understand classes coming from basic non oo scripting. I guess the problem comes in that you think you understand, and then look at code and its totally different and confusing. 

My question is maybe more generic with functions as opposed to classes, but i've been trying some pyGtk and I am unsure how i get values back from other classes.
Its something like, i have a program.py which has a class and methods.  One of those methods would be create a new dialog which is a class in dialog.py. So i can call that and pass it parameters. The question is, how do i get the result of that dialog back to the calling method?

Im not even sure if this makes sense. I guess im still struggling to understand how to pass parameters around to other methods, methods in other files, and get answers back.

Hope this makes somewhat sense.

Thanks

Stefan


From emile at fenx.com  Wed Apr 21 16:07:16 2010
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 21 Apr 2010 07:07:16 -0700
Subject: [Tutor] Python Examples of processing MS Outlook
In-Reply-To: <003001cadd45$128a5ce0$379f16a0$@com>
References: <003001cadd45$128a5ce0$379f16a0$@com>
Message-ID: <hqn0qd$38g$1@dough.gmane.org>

On 4/16/2010 2:13 AM Peter Meagher said...
> Does anyone have references to simple MS Outlook 2007
> processing code that I could vulture for my purposes?  (The
> code that I adapted was from an old Office 2000 vba text, so
> the version 2007 may not be that essential to my purposes)

You may what to dig into the spambayes code -- see 
http://spambayes.sourceforge.net/

Emile


From lowelltackett at yahoo.com  Wed Apr 21 17:37:35 2010
From: lowelltackett at yahoo.com (Lowell Tackett)
Date: Wed, 21 Apr 2010 08:37:35 -0700 (PDT)
Subject: [Tutor] the binary math "wall"
In-Reply-To: <4BCED787.70207@ieee.org>
Message-ID: <507758.69466.qm@web110105.mail.gq1.yahoo.com>


From the virtual desk of Lowell Tackett  



--- On Wed, 4/21/10, Dave Angel <davea at ieee.org> wrote:

> From: Dave Angel <davea at ieee.org>
> Subject: Re: [Tutor] the binary math "wall"
> To: "Lowell Tackett" <lowelltackett at yahoo.com>
> Cc: tutor at python.org, "Steven D'Aprano" <steve at pearwood.info>
> Date: Wednesday, April 21, 2010, 6:46 AM
> 
> 
> Lowell Tackett wrote:
> > --- On Tue, 4/20/10, Steven D'Aprano <steve at pearwood.info>
> wrote:
> > 
> >   
> >> From: Steven D'Aprano <steve at pearwood.info>
> >>     <snip>
> >> 
> >> The simplest, roughest way...hit them with a
> >> hammer:
> >>     
> >>>>> round(18.15*100) == 1815
> >>>>>       
>    
> >> True
> >>     
> > 
> > ...when I tried...:
> > 
> > Python 2.5.1 (r251:54863, Oct 14 2007, 12:51:35)
> > [GCC 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)] on linux2
> > Type "help", "copyright", "credits" or "license" for
> more information.
> >   
> >>>> round(18.15)*100 == 1815
> >>>>         
> > False
> >   
> > <snip>
> But you typed it differently than Steven.  He
> had   round(18.15*100), and you used
> round(18.15)*100

As soon as I'd posted my answer I realized this mistake.

> 
> Very different.   His point boils down to
> comparing integers, and when you have dubious values, round
> them to an integer before comparing.  I have my doubts,
> since in this case it would lead to bigger sloppiness than
> necessary.
> 
> round(18.154 *100) == 1815
> 
> probably isn't what you'd want.
> 
> So let me ask again, are all angles a whole number of
> seconds?  Or can you make some assumption about how
> accurate they need to be when first input (like tenths of a
> second, or whatever)?  If so use an integer as
> follows:
> 
> val =  round((((degrees*60)+minutes)*60) +
> seconds)*10)
> 
> The 10 above is assuming that tenths of a second are your
> quantization.
> 
> HTH
> DaveA
> 
> 

Recalling (from a brief foray into college Chem.) that a result could not be displayed with precision greater than the least precise component that bore [the result].  So, yes, I could accept my input as the arbitrator of accuracy.

A scenario:

Calculating the coordinates of a forward station from a given base station would require [perhaps] the bearing (an angle from north, say) and distance from hither to there.  Calculating the north coordinate would set up this relationship, e.g.:

cos(3? 22' 49.6") x 415.9207'(Hyp) = adjacent side(North)

My first requirement, and this is the struggle I (we) are now engaged in, is to convert my bearing angle (3? 22' 49.6") to decimal degrees, such that I can assign its' proper cosine value.  Now, I am multiplying these two very refined values (yes, the distance really is honed down to 10,000'ths of a foot-that's normal in surveying data); within the bowels of the computer's blackboard scratch-pad, I cannot allow errors to evolve and emerge.

Were I to accumulate many of these "legs" into perhaps a 15 mile traverse-accumulating little computer errors along the way-the end result could be catastrophically wrong.

(Recall that in the great India Survey in the 1800's, Waugh got the elevation of Mt. Everest wrong by almost 30' feet for just this exact same reason.)  In surveying, we have a saying, "Measure with a micrometer, mark with chalk, cut with an axe".  Accuracy [in math] is a sacred tenet.

So, I am setting my self very high standards of accuracy, simply because those are the standards imposed by the project I am adapting, and I can require nothing less of my finished project.


      


From emile at fenx.com  Wed Apr 21 18:11:53 2010
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 21 Apr 2010 09:11:53 -0700
Subject: [Tutor] the binary math "wall"
In-Reply-To: <507758.69466.qm@web110105.mail.gq1.yahoo.com>
References: <4BCED787.70207@ieee.org>
	<507758.69466.qm@web110105.mail.gq1.yahoo.com>
Message-ID: <hqn840$399$1@dough.gmane.org>

On 4/21/2010 8:37 AM Lowell Tackett said...
>
> So, I am setting my self very high standards of accuracy,
> simply because those are the standards imposed by the project
> I am adapting, and I can require nothing less of my finished project.

Then keep the source data in tenths (or 100ths or 1000ths) as whole 
numbers and only convert upon presentation and your calculations will 
always be accurate for the source measurements taken.

In accounting systems I've always keep dollar amounts in whole pennies 
for this same reason.

Emile




From bala.biophysics at gmail.com  Wed Apr 21 18:28:03 2010
From: bala.biophysics at gmail.com (Bala subramanian)
Date: Wed, 21 Apr 2010 18:28:03 +0200
Subject: [Tutor] set and sets.Set
Message-ID: <z2q288df32a1004210928i4144daf3vd8c1efe8c340ad9f@mail.gmail.com>

Friends,
Someone please write me the difference between creating set with set() and a
sets.Set().

>>> a=set([1,2,3])
>>> b=sets.Set([1,2,3])
>>> print a
set([1, 2, 3])
>>> print b
Set([1, 2, 3])

Thanks,
Bala
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100421/41537fdd/attachment.html>

From davea at ieee.org  Wed Apr 21 18:31:25 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 21 Apr 2010 12:31:25 -0400
Subject: [Tutor] the binary math "wall"
In-Reply-To: <507758.69466.qm@web110105.mail.gq1.yahoo.com>
References: <507758.69466.qm@web110105.mail.gq1.yahoo.com>
Message-ID: <4BCF285D.7040004@ieee.org>

Lowell Tackett wrote:
> From the virtual desk of Lowell Tackett  
>
>
>
> --- On Wed, 4/21/10, Dave Angel <davea at ieee.org> wrote:
>
>   
>> From: Dave Angel <davea at ieee.org>
>> Subject: Re: [Tutor] the binary math "wall"
>> To: "Lowell Tackett" <lowelltackett at yahoo.com>
>> Cc: tutor at python.org, "Steven D'Aprano" <steve at pearwood.info>
>> Date: Wednesday, April 21, 2010, 6:46 AM
>>
>>
>> Lowell Tackett wrote:
>>     
>>> --- On Tue, 4/20/10, Steven D'Aprano <steve at pearwood.info>
>>>       
>> wrote:
>>     
>>>   
>>>       
>>>> From: Steven D'Aprano <steve at pearwood.info>
>>>>     <snip>
>>>>
>>>> The simplest, roughest way...hit them with a
>>>> hammer:
>>>>     
>>>>         
>>>>>>> round(18.15*100) == 1815
>>>>>>>       
>>>>>>>               
>>    
>>     
>>>> True
>>>>     
>>>>         
>>> ...when I tried...:
>>>
>>> Python 2.5.1 (r251:54863, Oct 14 2007, 12:51:35)
>>> [GCC 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)] on linux2
>>> Type "help", "copyright", "credits" or "license" for
>>>       
>> more information.
>>     
>>>   
>>>       
>>>>>> round(18.15)*100 == 1815
>>>>>>         
>>>>>>             
>>> False
>>>   
>>> <snip>
>>>       
>> But you typed it differently than Steven.  He
>> had   round(18.15*100), and you used
>> round(18.15)*100
>>     
>
> As soon as I'd posted my answer I realized this mistake.
>
>   
>> Very different.   His point boils down to
>> comparing integers, and when you have dubious values, round
>> them to an integer before comparing.  I have my doubts,
>> since in this case it would lead to bigger sloppiness than
>> necessary.
>>
>> round(18.154 *100) == 1815
>>
>> probably isn't what you'd want.
>>
>> So let me ask again, are all angles a whole number of
>> seconds?  Or can you make some assumption about how
>> accurate they need to be when first input (like tenths of a
>> second, or whatever)?  If so use an integer as
>> follows:
>>
>> val =  round((((degrees*60)+minutes)*60) +
>> seconds)*10)
>>
>> The 10 above is assuming that tenths of a second are your
>> quantization.
>>
>> HTH
>> DaveA
>>
>>
>>     
>
> Recalling (from a brief foray into college Chem.) that a result could not be displayed with precision greater than the least precise component that bore [the result].  So, yes, I could accept my input as the arbitrator of accuracy.
>
> A scenario:
>
> Calculating the coordinates of a forward station from a given base station would require [perhaps] the bearing (an angle from north, say) and distance from hither to there.  Calculating the north coordinate would set up this relationship, e.g.:
>
> cos(3? 22' 49.6") x 415.9207'(Hyp) = adjacent side(North)
>
> My first requirement, and this is the struggle I (we) are now engaged in, is to convert my bearing angle (3? 22' 49.6") to decimal degrees, such that I can assign its' proper cosine value.  Now, I am multiplying these two very refined values (yes, the distance really is honed down to 10,000'ths of a foot-that's normal in surveying data); within the bowels of the computer's blackboard scratch-pad, I cannot allow errors to evolve and emerge.
>
> Were I to accumulate many of these "legs" into perhaps a 15 mile traverse-accumulating little computer errors along the way-the end result could be catastrophically wrong.
>
> (Recall that in the great India Survey in the 1800's, Waugh got the elevation of Mt. Everest wrong by almost 30' feet for just this exact same reason.)  In surveying, we have a saying, "Measure with a micrometer, mark with chalk, cut with an axe".  Accuracy [in math] is a sacred tenet.
>
> So, I am setting my self very high standards of accuracy, simply because those are the standards imposed by the project I am adapting, and I can require nothing less of my finished project.
>
>   
If you're trying to be accurate when calling cos, why are you using 
degrees?  The cosine function takes an angle in radians.  So what you 
need is a method to convert from deg/min/sec to radians.  And once you 
have to call trig, you can throw out all the other nonsense about 
getting exact values.  Trig functions don't take arbitrary number 
units.  They don't take decimals, and they don't take fractions.  They 
take double-precision floats.

Perhaps you don't realize the amount of this quantization error we've 
been talking about.  The double type is 64bits in size, and contains the 
equivalent of about 18 decimal digits of precision.  (Assuming common 
modern architectures, of course)


Your angle is specified to about 5 digits of precision, and the distance 
to 7.  So it would take a VERY large number of typical calculations for 
errors in the 18th place to accumulate far enough to affect those.

The real problem, and one that we can't solve for you, and neither can 
Python, is that it's easy to do calculations starting with 8 digits of 
accuracy, and the result be only useful to 3 or 4.  For example, simply 
subtract two very close numbers, and use the result as though it were 
meaningful.

I once had a real customer send us a letter asking about the math 
precision of a calculation he was doing.  I had written the math 
microcode of the machine he was using (from add and subtract, up to 
trigs and logs, I wrote it all).  So I analyzed his problem, pointed out 
his errors, and sent him away happy.

He was trying to calculate the difference between a perfectly flat 
machine table, and one that was leval at all points, following the 
curvature of the earth.  With a table of 200 feet, the distinction was a 
measurable one, and he was trying to calculate it.

His effective math was calculating the distance from the center of the 
earth to each end of the table, and subtracting.  So he was subtracting 
two very close numbers.  I did some simple geometry (using similar 
triangles), and showed him another way to do the calculation.

Anyway, in your case binary floating point is irrelevant.  You've got to 
do your own error analysis of every step in the calculation to 
understand how much you can trust the result.  And it's unlikely the 
"errors" in the math package will be the limiting factor.

DaveA


From bgailer at gmail.com  Wed Apr 21 18:38:46 2010
From: bgailer at gmail.com (bob gailer)
Date: Wed, 21 Apr 2010 12:38:46 -0400
Subject: [Tutor] set and sets.Set
In-Reply-To: <z2q288df32a1004210928i4144daf3vd8c1efe8c340ad9f@mail.gmail.com>
References: <z2q288df32a1004210928i4144daf3vd8c1efe8c340ad9f@mail.gmail.com>
Message-ID: <4BCF2A16.5030309@gmail.com>

On 4/21/2010 12:28 PM, Bala subramanian wrote:
> Friends,
> Someone please write me the difference between creating set with set() 
> and a sets.Set().

When sets were introduced to Python in version 2.3. they came as a 
separate "sets" module.

In version 2.6 built-in set/frozenset types replaced this module.

So either way is OK for now, but the sets module might go away in a 
newer version.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From lowelltackett at yahoo.com  Wed Apr 21 18:52:12 2010
From: lowelltackett at yahoo.com (Lowell Tackett)
Date: Wed, 21 Apr 2010 09:52:12 -0700 (PDT)
Subject: [Tutor] the binary math "wall"
In-Reply-To: <4BCF285D.7040004@ieee.org>
Message-ID: <909331.97678.qm@web110112.mail.gq1.yahoo.com>


>From the virtual desk of Lowell Tackett  



--- On Wed, 4/21/10, Dave Angel <davea at ieee.org> wrote:

> From: Dave Angel <davea at ieee.org>
> Subject: Re: [Tutor] the binary math "wall"
> To: "Lowell Tackett" <lowelltackett at yahoo.com>
> Cc: tutor at python.org, "Steven D'Aprano" <steve at pearwood.info>
> Date: Wednesday, April 21, 2010, 12:31 PM
> Lowell Tackett wrote:
> > From the virtual desk of Lowell Tackett  
> > 
> > 
*Whole buncha stuff snipped*
> 
> Anyway, in your case binary floating point is
> irrelevant.  You've got to do your own error analysis
> of every step in the calculation to understand how much you
> can trust the result.  And it's unlikely the "errors"
> in the math package will be the limiting factor.
> 
> DaveA
> 
> 

The sense of all this is beginning to emerge (perhaps).  Emile has just made a good point, simply convert all to whole values (using a subset algorithm that keeps track of the number of decimal "slips" that have accumulated-for later reconversion), crunch merrily away, and get good results.

Maybe that's valid, maybe not.  But I do know that this much is happening; I'm now beginning to quantify very novel and wide ranging ideas way outside "the box" I'd originally approached the challenge with.  That's the bigger value of this entire exercise, I think.  Naively thinking that the computer was benign and forgiving, I'd first opted for the most transparent and 'at hand' solutions...there was much to be learned.

I know a coupla things now...I'm gonna solve this dilemma, and largely with the help of all who've weighed in.   The solution may ultimately not be close to what has been suggested, but isn't that the fun of it all?

Secondly, there has accumulated [here] quite an array of novel (to me) thinking that I'm going to return to more and more as I tackle other, different projects, for the pedagogical value that will linger.


      


From alan.gauld at btinternet.com  Wed Apr 21 19:20:01 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 21 Apr 2010 18:20:01 +0100
Subject: [Tutor] classes passing information
References: <838411876.2098.1271852153515.JavaMail.root@zimbra>
	<62261639.2100.1271852269249.JavaMail.root@zimbra>
Message-ID: <hqnc4j$jgo$1@dough.gmane.org>


"Stefan Lesicnik" <stefan at lsd.co.za> wrote

Caveat: I know zilch about pyGtk.

> My question is maybe more generic with functions as opposed to classes,
> but i've been trying some pyGtk and I am unsure how i get values back
> from other classes.

They should be returned by the methods. So you just assign the method
result to a variable:

foo = someModule.SomeClass() # create an instance
bar = foo.someMethod()  # call a merthod and store the result.

> Its something like, i have a program.py which has a class and methods.
> One of those methods would be create a new dialog which is a class in
> dialog.py. So i can call that and pass it parameters.

import dialog

d = dialog.Dialog(foo, bar)

> The question is, how do i get the result of that dialog back to the calling 
> method?

The result being what? A reference to the new dialog object?
Or the button pressed by the user of the dialog?
For that I would need to know more about Gtk than I do.

> Im not even sure if this makes sense. I guess im still struggling to 
> understand
> how to pass parameters around to other methods, methods in other files,
> and get answers back.

It sounds like its the functions and parameter/value passing that you need help
with. The classes aspect is just an extra layer of fog.

Try my tutorial topic on Methods and Functions, see if that helps.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From ricaraoz at gmail.com  Wed Apr 21 19:24:14 2010
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Wed, 21 Apr 2010 14:24:14 -0300
Subject: [Tutor] the binary math "wall"
In-Reply-To: <909331.97678.qm@web110112.mail.gq1.yahoo.com>
References: <909331.97678.qm@web110112.mail.gq1.yahoo.com>
Message-ID: <4BCF34BE.1030609@gmail.com>

Lowell Tackett wrote:
> >From the virtual desk of Lowell Tackett  
>
>
>
> --- On Wed, 4/21/10, Dave Angel <davea at ieee.org> wrote:
>
>   
>> From: Dave Angel <davea at ieee.org>
>> Subject: Re: [Tutor] the binary math "wall"
>> To: "Lowell Tackett" <lowelltackett at yahoo.com>
>> Cc: tutor at python.org, "Steven D'Aprano" <steve at pearwood.info>
>> Date: Wednesday, April 21, 2010, 12:31 PM
>> Lowell Tackett wrote:
>>     
>>> From the virtual desk of Lowell Tackett  
>>>
>>>
>>>       
> *Whole buncha stuff snipped*
>   
>> Anyway, in your case binary floating point is
>> irrelevant.  You've got to do your own error analysis
>> of every step in the calculation to understand how much you
>> can trust the result.  And it's unlikely the "errors"
>> in the math package will be the limiting factor.
>>
>> DaveA
>>
>>
>>     
>
> The sense of all this is beginning to emerge (perhaps).  Emile has just made a good point, simply convert all to whole values (using a subset algorithm that keeps track of the number of decimal "slips" that have accumulated-for later reconversion), crunch merrily away, and get good results.
>
> Maybe that's valid, maybe not.  But I do know that this much is happening; I'm now beginning to quantify very novel and wide ranging ideas way outside "the box" I'd originally approached the challenge with.  That's the bigger value of this entire exercise, I think.  Naively thinking that the computer was benign and forgiving, I'd first opted for the most transparent and 'at hand' solutions...there was much to be learned.
>
> I know a coupla things now...I'm gonna solve this dilemma, and largely with the help of all who've weighed in.   The solution may ultimately not be close to what has been suggested, but isn't that the fun of it all?
>
> Secondly, there has accumulated [here] quite an array of novel (to me) thinking that I'm going to return to more and more as I tackle other, different projects, for the pedagogical value that will linger.
>   

Check python help docs for module decimal, there you have an example on
how to code a sin() and cos() functions with arbitrary precision
(depends on your context precision) using decimal values. Might be what
you are looking for (of course you would have to express your angles in
radians throughout all of your calculations and if needed convert at the
end.

HTH

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100421/36e39334/attachment.html>

From wescpy at gmail.com  Wed Apr 21 19:51:39 2010
From: wescpy at gmail.com (wesley chun)
Date: Wed, 21 Apr 2010 10:51:39 -0700
Subject: [Tutor] set and sets.Set
In-Reply-To: <4BCF2A16.5030309@gmail.com>
References: <z2q288df32a1004210928i4144daf3vd8c1efe8c340ad9f@mail.gmail.com>
	<4BCF2A16.5030309@gmail.com>
Message-ID: <t2g78b3a9581004211051sa71891dcl472c5f016770aded@mail.gmail.com>

> When sets were introduced to Python in version 2.3. they came as a separate "sets" module.
>
> In version 2.6 built-in set/frozenset types replaced this module.

2.4


> So either way is OK for now, but the sets module might go away in a newer version.

agreed

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Python Web Development with Django", Addison Wesley, (c) 2009
    http://withdjango.com

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

From mibaker88 at gmail.com  Wed Apr 21 20:15:28 2010
From: mibaker88 at gmail.com (Mike Baker)
Date: Wed, 21 Apr 2010 13:15:28 -0500
Subject: [Tutor] Remote access from Windows PC to a Linux box
In-Reply-To: <4BB34333.4040106@timgolden.me.uk>
References: <66563b0e1003300929x3b16a481g7dfaab688a80d9cc@mail.gmail.com>
	<4BB34333.4040106@timgolden.me.uk>
Message-ID: <q2l66563b0e1004211115wae86cb73i78d99320ae0f0f71@mail.gmail.com>

Thanks Tim,

Your subprocess examples got me started in the right direction.  I've moved
on to a slightly more advanced problem that I need help with.

I want to remotely start a Tshark packet capture session on one of our Linux
machines in the lab.  I want to start the session from my Windows machine
running Python 2.5.  The output capture file needs to be saved on the remote
Linux machine.

The example below nearly does what I want.  It starts Tshark via Putty, runs
for 10 seconds then writes the capture file (out.txt) to a remote Linux
machine.  The problem is that the putty session hangs open while Tshark is
running. So, I can't execute additional Python commands until the Tshark
capture finishes.

I've experimented with the Unix nohup command, but it does not seem to work
as expected with Tshark.  If you call my function below with
>>> test_subp(alt_cmd=1)
then the nohup command is added to the subprocess command list (along with a
trailing '&' to send the command to background).  This should work.  Using
this alternate command, out.txt gets created, but is always empty.


Here is my code:
**********************************************
def test_subp(alt_cmd=0):
    '''Establish a Putty connection with one of our Linux machines in the
lab.
    Send Tshark command to start a data collection session over Putty.
    '''
    PLINK = 'C:\\Progra~1\\putty\\plink'
    sess_name='LabComp1'
    if alt_cmd:
        '''This command does not work as expected.  The tshark output file
(out.txt)is created,
        but there is nothing in it '''
        CMD_LIST=[PLINK,sess_name,'/usr/bin/nohup','/usr/bin/sudo
/usr/sbin/tshark', '-a', 'duration:10', '-i',  'wlan0', '-T', 'text',
'-V','>', 'out.txt','&'];
    else:
        'This command works great, writing tshark output to out.txt on the
remote machine.'
        'Unfortunately, this command hangs the putty session until the
tshark capture ends'
        CMD_LIST=[PLINK,sess_name,'/usr/bin/sudo /usr/sbin/tshark', '-a',
'duration:10', '-i',  'wlan0', '-T', 'text', '-V','>', 'out.txt'];
    print "The command list you are sending to the subprocess is: \n", "\t",
CMD_LIST

    PIPE = subprocess.PIPE
    p = subprocess.Popen(CMD_LIST, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate ()
    print 'stdout = ', stdout
    print 'stderr = ', stderr
*********************************************************************

For both runs (atl_cmd=0 or alt_cmd=1), the stdout and stderr printouts at
the end of the script are empty.

Any suggestions would be appreciated.

Thanks,

    Mike
*******************************************************************************************************

On Wed, Mar 31, 2010 at 7:42 AM, Tim Golden <mail at timgolden.me.uk> wrote:

> On 30/03/2010 17:29, Mike Baker wrote:
>
>> I'm trying to connect to a Linux box from my Windows machine and execute a
>> series of commands
>>
>> I want a script to always
>> execute the same series of commands without having to do so manually.   I
>> also have code that will execute a single command like cat a file and
>> write
>> the ouput to a new file. However, when I try to use the communicate object
>> in subprocess, my window hangs.
>>
>
>
> This works for me:
>
> <code>
> import os, sys
> import subprocess
>
> PLINK = "plink"
> REMOTE_USER = "tgolden at web30.webfaction.com"
> PIPE = subprocess.PIPE
>
> p = subprocess.Popen ([PLINK, REMOTE_USER, "ls"], stdout=PIPE)
> stdout, stderr = p.communicate ()
> print "#1:", stdout.splitlines ()[0]
>
> with open ("out.txt", "w") as f:
>  p = subprocess.Popen ([PLINK, REMOTE_USER, "cat .bashrc"], stdout=f)
>  p.communicate ()
> print "#2:", open ("out.txt").read ().splitlines ()[0]
>
> p = subprocess.Popen ([PLINK, REMOTE_USER], stdin=PIPE, stdout=PIPE)
> stdout, stderr = p.communicate ("ls\nexit\n")
> print "#3", stdout
>
> p = subprocess.Popen ([PLINK, REMOTE_USER], stdin=PIPE, stdout=PIPE)
> p.stdin.write ("ls\nexit\n")
> stdout, stderr = p.communicate ()
> print "#4", stdout
>
> </code>
>
> A few things to note, none of which I believe to be germane to the
> issues you're experiencing:
>
> * You almost never need to use shell=True on a Windows call to subprocess.
>  If in doubt, don't use it.
>
> * Definitely better to pass the list-of-params style as the first param
>  of subprocess.Popen; it sorts out issues with embedded spaces etc.
>
> * The open ("...", "w") in your second example *may* be closing the
>  file immediately. I doubt it, since you'd expect Popen to hold a
>  reference, but I haven't checked the implementation.
>
> TJG
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100421/e358211b/attachment.html>

From yashwinkanchan at gmail.com  Wed Apr 21 21:45:12 2010
From: yashwinkanchan at gmail.com (Yashwin Kanchan)
Date: Wed, 21 Apr 2010 20:45:12 +0100
Subject: [Tutor] Remote access from Windows PC to a Linux box
In-Reply-To: <q2l66563b0e1004211115wae86cb73i78d99320ae0f0f71@mail.gmail.com>
References: <66563b0e1003300929x3b16a481g7dfaab688a80d9cc@mail.gmail.com>
	<4BB34333.4040106@timgolden.me.uk>
	<q2l66563b0e1004211115wae86cb73i78d99320ae0f0f71@mail.gmail.com>
Message-ID: <k2oeae1591c1004211245p7de2c924m17ad5c21f8f4db32@mail.gmail.com>

Hi Mike

have you tried running the tshark process in the background...

*CMD_LIST=[PLINK,sess_name,'/usr/bin/sudo /usr/sbin/tshark &', '-a',
'duration:10', '-i', 'wlan0', '-T', 'text', '-V','>', 'out.txt'];*

Or if you are using NOHUP try redirecting this way...

*CMD_LIST=[PLINK,sess_name,'/usr/bin/nohup','/usr/bin/sudo /usr/sbin/tshark >
out.txt 2> out.err < /dev/null ', '-a', 'duration:10', '-i', 'wlan0', '-T',
'text','&'];*

Regards
Yashwin Kanchan


On 21 April 2010 19:15, Mike Baker <mibaker88 at gmail.com> wrote:

> Thanks Tim,
>
> Your subprocess examples got me started in the right direction.  I've moved
> on to a slightly more advanced problem that I need help with.
>
> I want to remotely start a Tshark packet capture session on one of our
> Linux machines in the lab.  I want to start the session from my Windows
> machine running Python 2.5.  The output capture file needs to be saved on
> the remote Linux machine.
>
> The example below nearly does what I want.  It starts Tshark via Putty,
> runs for 10 seconds then writes the capture file (out.txt) to a remote Linux
> machine.  The problem is that the putty session hangs open while Tshark is
> running. So, I can't execute additional Python commands until the Tshark
> capture finishes.
>
> I've experimented with the Unix nohup command, but it does not seem to work
> as expected with Tshark.  If you call my function below with
> >>> test_subp(alt_cmd=1)
> then the nohup command is added to the subprocess command list (along
> with a trailing '&' to send the command to background).  This should work.
> Using this alternate command, out.txt gets created, but is always empty.
>
>
> Here is my code:
> **********************************************
> def test_subp(alt_cmd=0):
>     '''Establish a Putty connection with one of our Linux machines in the
> lab.
>     Send Tshark command to start a data collection session over Putty.
>     '''
>     PLINK = 'C:\\Progra~1\\putty\\plink'
>     sess_name='LabComp1'
>     if alt_cmd:
>         '''This command does not work as expected.  The tshark output file
> (out.txt)is created,
>         but there is nothing in it '''
>         CMD_LIST=[PLINK,sess_name,'/usr/bin/nohup','/usr/bin/sudo
> /usr/sbin/tshark', '-a', 'duration:10', '-i',  'wlan0', '-T', 'text',
> '-V','>', 'out.txt','&'];
>     else:
>         'This command works great, writing tshark output to out.txt on the
> remote machine.'
>         'Unfortunately, this command hangs the putty session until the
> tshark capture ends'
>         CMD_LIST=[PLINK,sess_name,'/usr/bin/sudo /usr/sbin/tshark', '-a',
> 'duration:10', '-i',  'wlan0', '-T', 'text', '-V','>', 'out.txt'];
>     print "The command list you are sending to the subprocess is: \n",
> "\t", CMD_LIST
>
>     PIPE = subprocess.PIPE
>     p = subprocess.Popen(CMD_LIST, stdout=PIPE, stderr=PIPE)
>     stdout, stderr = p.communicate ()
>     print 'stdout = ', stdout
>     print 'stderr = ', stderr
> *********************************************************************
>
> For both runs (atl_cmd=0 or alt_cmd=1), the stdout and stderr printouts at
> the end of the script are empty.
>
> Any suggestions would be appreciated.
>
> Thanks,
>
>     Mike
>
> *******************************************************************************************************
>
> On Wed, Mar 31, 2010 at 7:42 AM, Tim Golden <mail at timgolden.me.uk> wrote:
>
>> On 30/03/2010 17:29, Mike Baker wrote:
>>
>>> I'm trying to connect to a Linux box from my Windows machine and execute
>>> a
>>> series of commands
>>>
>>> I want a script to always
>>> execute the same series of commands without having to do so manually.   I
>>> also have code that will execute a single command like cat a file and
>>> write
>>> the ouput to a new file. However, when I try to use the communicate
>>> object
>>> in subprocess, my window hangs.
>>>
>>
>>
>> This works for me:
>>
>> <code>
>> import os, sys
>> import subprocess
>>
>> PLINK = "plink"
>> REMOTE_USER = "tgolden at web30.webfaction.com"
>> PIPE = subprocess.PIPE
>>
>> p = subprocess.Popen ([PLINK, REMOTE_USER, "ls"], stdout=PIPE)
>> stdout, stderr = p.communicate ()
>> print "#1:", stdout.splitlines ()[0]
>>
>> with open ("out.txt", "w") as f:
>>  p = subprocess.Popen ([PLINK, REMOTE_USER, "cat .bashrc"], stdout=f)
>>  p.communicate ()
>> print "#2:", open ("out.txt").read ().splitlines ()[0]
>>
>> p = subprocess.Popen ([PLINK, REMOTE_USER], stdin=PIPE, stdout=PIPE)
>> stdout, stderr = p.communicate ("ls\nexit\n")
>> print "#3", stdout
>>
>> p = subprocess.Popen ([PLINK, REMOTE_USER], stdin=PIPE, stdout=PIPE)
>> p.stdin.write ("ls\nexit\n")
>> stdout, stderr = p.communicate ()
>> print "#4", stdout
>>
>> </code>
>>
>> A few things to note, none of which I believe to be germane to the
>> issues you're experiencing:
>>
>> * You almost never need to use shell=True on a Windows call to subprocess.
>>  If in doubt, don't use it.
>>
>> * Definitely better to pass the list-of-params style as the first param
>>  of subprocess.Popen; it sorts out issues with embedded spaces etc.
>>
>> * The open ("...", "w") in your second example *may* be closing the
>>  file immediately. I doubt it, since you'd expect Popen to hold a
>>  reference, but I haven't checked the implementation.
>>
>> TJG
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100421/5ec70d8e/attachment-0001.html>

From mibaker88 at gmail.com  Wed Apr 21 22:32:22 2010
From: mibaker88 at gmail.com (Mike Baker)
Date: Wed, 21 Apr 2010 15:32:22 -0500
Subject: [Tutor] Remote access from Windows PC to a Linux box
In-Reply-To: <k2oeae1591c1004211245p7de2c924m17ad5c21f8f4db32@mail.gmail.com>
References: <66563b0e1003300929x3b16a481g7dfaab688a80d9cc@mail.gmail.com>
	<4BB34333.4040106@timgolden.me.uk>
	<q2l66563b0e1004211115wae86cb73i78d99320ae0f0f71@mail.gmail.com>
	<k2oeae1591c1004211245p7de2c924m17ad5c21f8f4db32@mail.gmail.com>
Message-ID: <n2w66563b0e1004211332qc0d3c5ffx383860cb87399794@mail.gmail.com>

Yashwin,

Thanks!  Your nohup redirection worked great!

  - Mike

On Wed, Apr 21, 2010 at 2:45 PM, Yashwin Kanchan
<yashwinkanchan at gmail.com>wrote:

> Hi Mike
>
> have you tried running the tshark process in the background...
>
> *CMD_LIST=[PLINK,sess_name,'/usr/bin/sudo /usr/sbin/tshark &', '-a',
> 'duration:10', '-i', 'wlan0', '-T', 'text', '-V','>', 'out.txt'];*
>
> Or if you are using NOHUP try redirecting this way...
>
> *CMD_LIST=[PLINK,sess_name,'/usr/bin/nohup','/usr/bin/sudo
> /usr/sbin/tshark > out.txt 2> out.err < /dev/null ', '-a', 'duration:10',
> '-i', 'wlan0', '-T', 'text','&'];*
>
> Regards
> Yashwin Kanchan
>
>
> On 21 April 2010 19:15, Mike Baker <mibaker88 at gmail.com> wrote:
>
>> Thanks Tim,
>>
>> Your subprocess examples got me started in the right direction.  I've
>> moved on to a slightly more advanced problem that I need help with.
>>
>> I want to remotely start a Tshark packet capture session on one of our
>> Linux machines in the lab.  I want to start the session from my Windows
>> machine running Python 2.5.  The output capture file needs to be saved on
>> the remote Linux machine.
>>
>> The example below nearly does what I want.  It starts Tshark via Putty,
>> runs for 10 seconds then writes the capture file (out.txt) to a remote Linux
>> machine.  The problem is that the putty session hangs open while Tshark is
>> running. So, I can't execute additional Python commands until the Tshark
>> capture finishes.
>>
>> I've experimented with the Unix nohup command, but it does not seem to
>> work as expected with Tshark.  If you call my function below with
>> >>> test_subp(alt_cmd=1)
>> then the nohup command is added to the subprocess command list (along
>> with a trailing '&' to send the command to background).  This should work.
>> Using this alternate command, out.txt gets created, but is always empty.
>>
>>
>> Here is my code:
>> **********************************************
>> def test_subp(alt_cmd=0):
>>     '''Establish a Putty connection with one of our Linux machines in the
>> lab.
>>     Send Tshark command to start a data collection session over Putty.
>>     '''
>>     PLINK = 'C:\\Progra~1\\putty\\plink'
>>     sess_name='LabComp1'
>>     if alt_cmd:
>>         '''This command does not work as expected.  The tshark output file
>> (out.txt)is created,
>>         but there is nothing in it '''
>>         CMD_LIST=[PLINK,sess_name,'/usr/bin/nohup','/usr/bin/sudo
>> /usr/sbin/tshark', '-a', 'duration:10', '-i',  'wlan0', '-T', 'text',
>> '-V','>', 'out.txt','&'];
>>     else:
>>         'This command works great, writing tshark output to out.txt on the
>> remote machine.'
>>         'Unfortunately, this command hangs the putty session until the
>> tshark capture ends'
>>         CMD_LIST=[PLINK,sess_name,'/usr/bin/sudo /usr/sbin/tshark', '-a',
>> 'duration:10', '-i',  'wlan0', '-T', 'text', '-V','>', 'out.txt'];
>>     print "The command list you are sending to the subprocess is: \n",
>> "\t", CMD_LIST
>>
>>     PIPE = subprocess.PIPE
>>     p = subprocess.Popen(CMD_LIST, stdout=PIPE, stderr=PIPE)
>>     stdout, stderr = p.communicate ()
>>     print 'stdout = ', stdout
>>     print 'stderr = ', stderr
>> *********************************************************************
>>
>> For both runs (atl_cmd=0 or alt_cmd=1), the stdout and stderr printouts at
>> the end of the script are empty.
>>
>> Any suggestions would be appreciated.
>>
>> Thanks,
>>
>>     Mike
>>
>> *******************************************************************************************************
>>
>>  On Wed, Mar 31, 2010 at 7:42 AM, Tim Golden <mail at timgolden.me.uk>wrote:
>>
>>> On 30/03/2010 17:29, Mike Baker wrote:
>>>
>>>> I'm trying to connect to a Linux box from my Windows machine and execute
>>>> a
>>>> series of commands
>>>>
>>>> I want a script to always
>>>> execute the same series of commands without having to do so manually.
>>>> I
>>>> also have code that will execute a single command like cat a file and
>>>> write
>>>> the ouput to a new file. However, when I try to use the communicate
>>>> object
>>>> in subprocess, my window hangs.
>>>>
>>>
>>>
>>> This works for me:
>>>
>>> <code>
>>> import os, sys
>>> import subprocess
>>>
>>> PLINK = "plink"
>>> REMOTE_USER = "tgolden at web30.webfaction.com"
>>> PIPE = subprocess.PIPE
>>>
>>> p = subprocess.Popen ([PLINK, REMOTE_USER, "ls"], stdout=PIPE)
>>> stdout, stderr = p.communicate ()
>>> print "#1:", stdout.splitlines ()[0]
>>>
>>> with open ("out.txt", "w") as f:
>>>  p = subprocess.Popen ([PLINK, REMOTE_USER, "cat .bashrc"], stdout=f)
>>>  p.communicate ()
>>> print "#2:", open ("out.txt").read ().splitlines ()[0]
>>>
>>> p = subprocess.Popen ([PLINK, REMOTE_USER], stdin=PIPE, stdout=PIPE)
>>> stdout, stderr = p.communicate ("ls\nexit\n")
>>> print "#3", stdout
>>>
>>> p = subprocess.Popen ([PLINK, REMOTE_USER], stdin=PIPE, stdout=PIPE)
>>> p.stdin.write ("ls\nexit\n")
>>> stdout, stderr = p.communicate ()
>>> print "#4", stdout
>>>
>>> </code>
>>>
>>> A few things to note, none of which I believe to be germane to the
>>> issues you're experiencing:
>>>
>>> * You almost never need to use shell=True on a Windows call to
>>> subprocess.
>>>  If in doubt, don't use it.
>>>
>>> * Definitely better to pass the list-of-params style as the first param
>>>  of subprocess.Popen; it sorts out issues with embedded spaces etc.
>>>
>>> * The open ("...", "w") in your second example *may* be closing the
>>>  file immediately. I doubt it, since you'd expect Popen to hold a
>>>  reference, but I haven't checked the implementation.
>>>
>>> TJG
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100421/79b0bd8a/attachment.html>

From steve at pearwood.info  Wed Apr 21 23:14:12 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 22 Apr 2010 07:14:12 +1000
Subject: [Tutor] set and sets.Set
In-Reply-To: <z2q288df32a1004210928i4144daf3vd8c1efe8c340ad9f@mail.gmail.com>
References: <z2q288df32a1004210928i4144daf3vd8c1efe8c340ad9f@mail.gmail.com>
Message-ID: <201004220714.12643.steve@pearwood.info>

On Thu, 22 Apr 2010 02:28:03 am Bala subramanian wrote:
> Friends,
> Someone please write me the difference between creating set with
> set() and a sets.Set().

The sets module, including sets.Set(), were first introduced in Python 
2.3 and is written in Python.

The built-in set object was introduced in Python 2.4 and is re-written 
in C for speed.

Functionally, they are identical. Speed-wise, the built-in version is 
much faster, so unless you need to support Python 2.3, always use the 
built-in set type.



-- 
Steven D'Aprano

From steve at pearwood.info  Wed Apr 21 23:48:08 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 22 Apr 2010 07:48:08 +1000
Subject: [Tutor] the binary math "wall"
In-Reply-To: <507758.69466.qm@web110105.mail.gq1.yahoo.com>
References: <507758.69466.qm@web110105.mail.gq1.yahoo.com>
Message-ID: <201004220748.08698.steve@pearwood.info>

On Thu, 22 Apr 2010 01:37:35 am Lowell Tackett wrote:

> Recalling (from a brief foray into college Chem.) that a result could
> not be displayed with precision greater than the least precise
> component that bore [the result].  So, yes, I could accept my input
> as the arbitrator of accuracy.

Unfortunately, you can't distinguish the number of supplied digits of 
accuracy from a float. Given as floats, all of the following are 
identical:

0.1
0.10000
0.099999999999999999
0.100000000000000001

as are these two:

0.099999999999999998
0.099999999999999985

Perhaps you should look at the Decimal class, not necessarily to use it, 
but to see what they do. For instance, you create a Decimal with a 
string, not a float:

>>> from decimal import Decimal
>>> Decimal('0.1')
Decimal("0.1")
>>> Decimal('0.10000')
Decimal("0.10000")

which allows you to distinguish the number of digits of precision.


> A scenario:
>
> Calculating the coordinates of a forward station from a given base
> station would require [perhaps] the bearing (an angle from north,
> say) and distance from hither to there.  Calculating the north
> coordinate would set up this relationship, e.g.:
>
> cos(3? 22' 49.6") x 415.9207'(Hyp) = adjacent side(North)
>
> My first requirement, and this is the struggle I (we) are now engaged
> in, is to convert my bearing angle (3? 22' 49.6") to decimal degrees,
> such that I can assign its' proper cosine value.

This is MUCH MUCH MUCH easier than trying to deal with DMS as a float. 
Your data already separates the parts for you, so it is just a matter 
of:

>>> d = 3 + 22/60.0 + 49.2/3600.0
>>> import math
>>> angle = math.radians(d)
>>> math.cos(angle)
0.9982601259166638

Then the only problem you have is whether or not the formula you are 
using is numerically stable, or whether it is subject to 
catastrophically growing errors.

I hope we're not frightening you off here. For nearly anything people 
are going to want to do, their input data will be in single-precision. 
One of the simplest things they can do to improve the accuracy of 
floating point calculations is to do their intermediate calculations in 
double-precision.

The good news is, Python floats are already in double-precision.

For most modern systems, single-precision floats have 24 binary digits 
of precision (approximately 6 decimal digits) and double-precision 
floats have 53 binary digits (15 decimal) of precision. More than 
sufficient for dealing with an angle measured to a tenth of a second.


Some resources for you to read:

http://en.wikipedia.org/wiki/Floating_point
http://www.cs.princeton.edu/introcs/91float/
http://www.cs.berkeley.edu/~wkahan/
http://docs.sun.com/source/806-3568/ncg_goldberg.html



> Were I to accumulate many of these "legs" into perhaps a 15 mile
> traverse-accumulating little computer errors along the way-the end
> result could be catastrophically wrong.

YES!!! 

And just by being aware of this potential problem, you are better off 
than 90% of programmers who are blithely unaware that floats are not 
real numbers.




-- 
Steven D'Aprano

From danny.yoo at gmail.com  Wed Apr 21 18:40:17 2010
From: danny.yoo at gmail.com (Danny Yoo)
Date: Wed, 21 Apr 2010 12:40:17 -0400
Subject: [Tutor] Fwd: python tutor needed
In-Reply-To: <fc2e430a5228.4bce13dd@students.wits.ac.za>
References: <fc2e430a5228.4bce13dd@students.wits.ac.za>
Message-ID: <v2jd06401781004210940vc8882fd3ubd3b06729f0887b2@mail.gmail.com>

Forwarding for Lumka:


---------- Forwarded message ----------
From: Lumka Msibi <Lumka.Msibi at students.wits.ac.za>
Date: Tue, Apr 20, 2010 at 2:51 PM
Subject: Fwd: python tutor needed
To: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>, "dany.yoo" <danny.yoo at gmail.com>


<html><p><font face = "verdana" size = "0.8" color = "navy">This
communication is intended for the addressee only. It is confidential.
If you have received this communication in error, please notify us
immediately and destroy the original message. You may not copy or
disseminate this communication without the permission of the
University. Only authorized signatories are competent to enter into
agreements on behalf of the University and recipients are thus advised
that the content of this message may not be legally binding on the
University and may contain the personal views and opinions of the
author, which are not necessarily the views and opinions of The
University of the Witwatersrand, Johannesburg. All agreements between
the University and outsiders are subject to South African Law unless
the University agrees in writing to the contrary.</font></p></html>

---------- Forwarded message ----------
From:?Lumka Msibi <Lumka.Msibi at students.wits.ac.za>
To:?Danny Yoo <dyoo at hkn.eecs.berkeley.edu>, "dany.yoo" <danny.yoo at gmail.com>
Date:?Tue, 20 Apr 2010 20:51:41 +0200
Subject:?Fwd: python tutor needed


---------- Forwarded message ----------
From:?Lumka Msibi <Lumka.Msibi at students.wits.ac.za>
To:?Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
Date:?Mon, 19 Apr 2010 16:25:19 +0200
Subject:?python tutor needed
Hi

Are there any python tutors in Johannesburg, South Africa? i really
need some tution before my exam in 2 weeks. please help.

thank you

From davea at ieee.org  Thu Apr 22 03:47:56 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 21 Apr 2010 21:47:56 -0400
Subject: [Tutor] the binary math "wall"
In-Reply-To: <201004220748.08698.steve@pearwood.info>
References: <507758.69466.qm@web110105.mail.gq1.yahoo.com>
	<201004220748.08698.steve@pearwood.info>
Message-ID: <4BCFAACC.10401@ieee.org>

Steven D'Aprano wrote:
> On Thu, 22 Apr 2010 01:37:35 am Lowell Tackett wrote:
>
> <snip>
>> Were I to accumulate many of these "legs" into perhaps a 15 mile
>> traverse-accumulating little computer errors along the way-the end
>> result could be catastrophically wrong.
>>     
>
> YES!!! 
>
> And just by being aware of this potential problem, you are better off 
> than 90% of programmers who are blithely unaware that floats are not 
> real numbers.
>
>
>   
Absolutely.  But "catastrophically wrong" has to be defined, and 
analyzed.  If each of these measurements is of 100 feet, measured to an 
accuracy of .0001 feet, and you add up the measurements in Python 
floats, you'll be adding 750 measurements, and your human error could 
accumulate to as much as .07 feet.

The same 750 floating point ads, each to 15 digits of quantization 
accuracy (thanks for the correction, it isn't 18) will give a maximum 
"computer error" of  maybe .000000001 feet.  The human error is much 
larger than the computer error.

No results can be counted on without some analysis of both sources of 
error.  Occasionally, the "computer error" will exceed the human, and 
that depends on the calculations you do on your measurements.

HTH,
DaveA

From billjordan121 at yahoo.com  Thu Apr 22 14:13:38 2010
From: billjordan121 at yahoo.com (Bill Jordan)
Date: Thu, 22 Apr 2010 05:13:38 -0700 (PDT)
Subject: [Tutor] number distribution
Message-ID: <173585.70626.qm@web114313.mail.gq1.yahoo.com>

Hey everbody,

If we have 100 apples, for example,?and we need to distrubte the 100 apples randomly in 10 boxes, how can we do this in python?

Cheers



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100422/cf94c333/attachment.html>

From hugo.yoshi at gmail.com  Thu Apr 22 18:53:35 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Thu, 22 Apr 2010 18:53:35 +0200
Subject: [Tutor] number distribution
In-Reply-To: <173585.70626.qm@web114313.mail.gq1.yahoo.com>
References: <173585.70626.qm@web114313.mail.gq1.yahoo.com>
Message-ID: <j2p29179d161004220953m268a36bdic2e299cb5bc79876@mail.gmail.com>

I suggest you take a look at the random module. There should be
something in there that suits your needs.

On Thu, Apr 22, 2010 at 2:13 PM, Bill Jordan <billjordan121 at yahoo.com> wrote:
> Hey everbody,
>
> If we have 100 apples, for example,?and we need to distrubte the 100 apples
> randomly in 10 boxes, how can we do this in python?
>
> Cheers
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From alan.gauld at btinternet.com  Thu Apr 22 18:56:08 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 22 Apr 2010 17:56:08 +0100
Subject: [Tutor] number distribution
References: <173585.70626.qm@web114313.mail.gq1.yahoo.com>
Message-ID: <hqpv3r$mnf$1@dough.gmane.org>

"Bill Jordan" <billjordan121 at yahoo.com> wrote 

> If we have 100 apples, for example, and we need to distrubte 
> the 100 apples randomly in 10 boxes, how can we do this in python?

This sounds like homework, and we don't do homework for you.

But if you'd like to tell us your ideas, or even better show us whatever 
code you have tried to work, we can offer comments and ideas.

In the meantime try looking at the documentation for the "random" 
module.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From garry.willgoose at newcastle.edu.au  Fri Apr 23 02:34:02 2010
From: garry.willgoose at newcastle.edu.au (Garry Willgoose)
Date: Fri, 23 Apr 2010 10:34:02 +1000
Subject: [Tutor] sys.path and the path order
Message-ID: <C7D9B164-F931-42ED-84D9-37AE31BAAC46@newcastle.edu.au>

My question is so simple I'm surprised I can't find an answer  
somewhere. I'm interested if I can rely on the order of the  
directories in the sys.path list. When I'm running a file from the  
comand line like

python tellusim.py

The string in entry sys.path[0] appears to be the full path to the  
location of the file I'm running in this case tellusim ... i.e. it  
looks like '/Volumes/scone2/codes/tellusim0006'. This is good because  
for my code I need to create a search path for modules that is  
relative to the location of this file irrespective of the location I'm  
in when I invoke the script file (i.e. I could be in /Volumes/scone2  
and invoke it by 'python codes/tellusim0006/tellusim.py').

The question is can I rely on entry [0] in sys.path always being the  
directory in which the original file resides (& across linux, OSX and  
Windows)? If not what is the reliable way of getting that information?







From steve at pearwood.info  Fri Apr 23 05:42:43 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 23 Apr 2010 13:42:43 +1000
Subject: [Tutor] sys.path and the path order
In-Reply-To: <C7D9B164-F931-42ED-84D9-37AE31BAAC46@newcastle.edu.au>
References: <C7D9B164-F931-42ED-84D9-37AE31BAAC46@newcastle.edu.au>
Message-ID: <201004231342.44670.steve@pearwood.info>

On Fri, 23 Apr 2010 10:34:02 am Garry Willgoose wrote:
> My question is so simple I'm surprised I can't find an answer
> somewhere. 

Did you read the Fine Manual?


> I'm interested if I can rely on the order of the 
> directories in the sys.path list.
[...] 
> The question is can I rely on entry [0] in sys.path always being the
> directory in which the original file resides (& across linux, OSX and
> Windows)? 


The documentation says:

sys.path

A list of strings that specifies the search path for modules. 
Initialized from the environment variable PYTHONPATH, plus an 
installation-dependent default.

As initialized upon program startup, the first item of this list, 
path[0], is the directory containing the script that was used to invoke 
the Python interpreter. If the script directory is not available (e.g. 
if the interpreter is invoked interactively or if the script is read 
from standard input), path[0] is the empty string, which directs Python 
to search modules in the current directory first. Notice that the 
script directory is inserted before the entries inserted as a result of 
PYTHONPATH.

http://docs.python.org/library/sys.html#sys.path

So the answer to your question is, Yes.


-- 
Steven D'Aprano

From smokefloat at gmail.com  Fri Apr 23 07:11:36 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 23 Apr 2010 01:11:36 -0400
Subject: [Tutor] Class Inheritance
Message-ID: <v2p2d00d7fe1004222211x265187cdj322d0df2c198974b@mail.gmail.com>

Hello List!

While experimenting with Tkinter(python2.6), when from Tkinter import*
is used I came across the following error:
************
C:\Users\ascent>c:\python26/Script3.py
Traceback (most recent call last):
  File "C:\python26\Script3.py", line 1, in <module>
    from Tkinter import *
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 44, in <module>
    from turtle import *
  File "C:\Python26\lib\lib-tk\turtle.py", line 374, in <module>
    class ScrolledCanvas(Tkinter.Frame):
AttributeError: 'module' object has no attribute 'Frame'

*************

Which stems from the below in turtle.py:

class ScrolledCanvas(TK.Frame)

I know that ScrolledCanvas is trying to use class TK.Frame as it's base
class to build from, and the class Frame is what is trying to be called
from the Tkinter module.

So I tried to alter the turtle.py. When I try to just 'from Tkinter
import *, such as:

from Tkinter import *
class ScrolledCanvas(Tkinter.Frame):

I get:
*****************
C:\Users\ascent>c:\python26/Script3.py
Traceback (most recent call last):
  File "C:\python26\Script3.py", line 1, in <module>
    from Tkinter import *
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 44, in <module>
    from turtle import *
  File "C:\Python26\lib\lib-tk\turtle.py", line 373, in <module>
    class ScrolledCanvas(Tkinter.Frame):
NameError: name 'Tkinter' is not defined
*******************


I know pretty much what is going on there. But when I try to use:

import Tkinter
from Tkinter import *
class ScrolledCanvas(Tkinter.Frame):

It takes me back to the first error. Which means
in both instances both directly called by me, and
when called from the original turtle.py call,
it's not finding the Frame class.

>From the docs (9.5. Inheritance) it states:

"The name BaseClassName must be defined in a
scope containing the derived class definition.
In place of a base class name, other arbitrary
expressions are also allowed. This can be useful,
for example, when the base class is defined in another module:

class DerivedClassName(modname.BaseClassName)
"


So why does the above, from turtle.py, a standard module,
not allow this, or is their something
the module writer got wrong, or more likely, that I'm not
understanding about what it's doing?

As a sidenote, I ended up removing the from turtle import *
line from Tkinter which resolved the problem(the example I was using
didn't have a canvas, and I'm pretty sure Tkinter was defaulting
to the ScrolledCanvas).


TIA,
David

From steve at pearwood.info  Fri Apr 23 07:51:22 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 23 Apr 2010 15:51:22 +1000
Subject: [Tutor] Class Inheritance
In-Reply-To: <v2p2d00d7fe1004222211x265187cdj322d0df2c198974b@mail.gmail.com>
References: <v2p2d00d7fe1004222211x265187cdj322d0df2c198974b@mail.gmail.com>
Message-ID: <201004231551.23114.steve@pearwood.info>

On Fri, 23 Apr 2010 03:11:36 pm David Hutto wrote:
> Hello List!
>
> While experimenting with Tkinter(python2.6), when from Tkinter
> import* is used I came across the following error:
> ************
> C:\Users\ascent>c:\python26/Script3.py
> Traceback (most recent call last):
>   File "C:\python26\Script3.py", line 1, in <module>
>     from Tkinter import *
>   File "C:\Python26\lib\lib-tk\Tkinter.py", line 44, in <module>
>     from turtle import *
>   File "C:\Python26\lib\lib-tk\turtle.py", line 374, in <module>
>     class ScrolledCanvas(Tkinter.Frame):
> AttributeError: 'module' object has no attribute 'Frame'

Something is screwy there. I believe you have broken your installation 
by making changes to files without having any understanding of what you 
are doing.

The turtle module does this:

import Tkinter as TK

so that line should be "class ScrolledCanvas(TK.Frame)", and in fact 
that's what I find when I go and look at the source code:

class ScrolledCanvas(TK.Frame):

The line number is different too. How many breakages have you introduced 
to the library?


> Which stems from the below in turtle.py:
>
> class ScrolledCanvas(TK.Frame)

Note the difference between Tkinter.Frame and TK.Frame.


> I know that ScrolledCanvas is trying to use class TK.Frame as it's
> base class to build from, and the class Frame is what is trying to be
> called from the Tkinter module.
>
> So I tried to alter the turtle.py. 

Please don't try to "fix" library files when you don't understand what 
they are doing. Confine your experiments to your own code, so that when 
things break, you know that the cause is in your code, not some random 
change you have done to the library.



> When I try to just 'from Tkinter 
> import *, such as:
>
> from Tkinter import *
> class ScrolledCanvas(Tkinter.Frame):

That won't work, because there is no Tkinter defined.

One wrong way to do it is:

from Tkinter import *
class ScrolledCanvas(Frame):

but that risks stomping over the top of other variables with great big 
hob-nailed boots. Better to avoid import *, and do this:

import Tkinter
class ScrolledCanvas(Tkinter.Frame):

but that's still a silly thing to do, because the turtle module has 
already imported Tkinter. The right way is to leave the module alone, 
it was working before you changed it:

import Tkinter as TK

class ScrolledCanvas(TK.Frame):


> I get:
> *****************
> C:\Users\ascent>c:\python26/Script3.py
> Traceback (most recent call last):
>   File "C:\python26\Script3.py", line 1, in <module>
>     from Tkinter import *
>   File "C:\Python26\lib\lib-tk\Tkinter.py", line 44, in <module>
>     from turtle import *
>   File "C:\Python26\lib\lib-tk\turtle.py", line 373, in <module>
>     class ScrolledCanvas(Tkinter.Frame):
> NameError: name 'Tkinter' is not defined

Now you have two errors. 

(1) You have introduced a circular import dependency, where turtle tries 
to import Tkinter which tries to import Tkinter which tries to import 
turtle...

(2) You have no Tkinter object, since you import it's contents, not the 
module itself.


> I know pretty much what is going on there. 

I doubt it, or else you wouldn't have done what you did.

> But when I try to use: 
>
> import Tkinter
> from Tkinter import *

Why would you do that when turtle has already imported Tkinter under the 
name TK?

> class ScrolledCanvas(Tkinter.Frame):
>
> It takes me back to the first error. Which means
> in both instances both directly called by me, and
> when called from the original turtle.py call,
> it's not finding the Frame class.

I suspect you've broken it. I recommend you re-install the Tkinter 
library, including turtle.py, in order to get it back to a known 
working state.



> >From the docs (9.5. Inheritance) it states:
>
> "The name BaseClassName must be defined in a
> scope containing the derived class definition.
> In place of a base class name, other arbitrary
> expressions are also allowed. This can be useful,
> for example, when the base class is defined in another module:
>
> class DerivedClassName(modname.BaseClassName)
> "
>
>
> So why does the above, from turtle.py, a standard module,
> not allow this, or is their something
> the module writer got wrong, or more likely, that I'm not
> understanding about what it's doing?

I don't have this problem with an unmodified version of turtle and 
Tkinter in Python 2.6. I get:

>>> import turtle
>>> turtle.TK.Frame
<class Tkinter.Frame at 0x00BC2F60>
>>> turtle.ScrolledCanvas
<class turtle.ScrolledCanvas at 0x00F71720>


> As a sidenote, I ended up removing the from turtle import *
> line from Tkinter which resolved the problem(the example I was using
> didn't have a canvas, and I'm pretty sure Tkinter was defaulting
> to the ScrolledCanvas).

I should say so! Tkinter doesn't have a "from turtle import *" line, as 
that would set up a circular import dependency. No wonder you have had 
problems, making random changes to libraries without understanding 
them.




-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Fri Apr 23 09:42:51 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 23 Apr 2010 08:42:51 +0100
Subject: [Tutor] Class Inheritance
References: <v2p2d00d7fe1004222211x265187cdj322d0df2c198974b@mail.gmail.com>
Message-ID: <hqrj2f$tkr$1@dough.gmane.org>

"David Hutto" <smokefloat at gmail.com> wrote 

> While experimenting with Tkinter(python2.6), when from Tkinter import*
> is used I came across the following error:
> ************
>  File "C:\Python26\lib\lib-tk\Tkinter.py", line 44, in <module>
>    from turtle import *

Huh? Why is Tkinter.py importing from turtle?
It doesn't in my Python 2.5 version.

>  File "C:\Python26\lib\lib-tk\turtle.py", line 374, in <module>
>    class ScrolledCanvas(Tkinter.Frame):
> AttributeError: 'module' object has no attribute 'Frame'

Which is also odd since turtle.py imports Tkinter as TK 
so why would it be referring to Tkinter? Something is 
broken in your standard modules!

> Which stems from the below in turtle.py:
> 
> class ScrolledCanvas(TK.Frame)
> 
> I know that ScrolledCanvas is trying to use class TK.Frame as it's base
> class to build from, and the class Frame is what is trying to be called
> from the Tkinter module.

Yes, TK is an alias for Tkinter. So why is your error showing 
Tkinter when the module imports it as TK?

> So I tried to alter the turtle.py. When I try to just 'from Tkinter
> import *, such as:

Don't ever modify the standard modules! There lies chaos. 
If you want to try changing something make a copy and work 
on that. Then you know you can go back to something that 
has been tested and proven to work.

> from Tkinter import *
> class ScrolledCanvas(Tkinter.Frame):
> 
> I get:
> *****************
>    class ScrolledCanvas(Tkinter.Frame):
> NameError: name 'Tkinter' is not defined

Thats right, when you import * you import all the names 
inside the module but not the module itself. So any references 
to the module will generate this error.

> I know pretty much what is going on there. But when I try to use:
> 
> import Tkinter
> from Tkinter import *

Don't mix these two styles. It is very common for modules to 
contain objects of the same name as the module so the second 
import often hides the module name. And if you do it the other 
way round the module name hides the internal object. 
Its just confusing. Use one or the other and preferrably don't 
use import * except for experimenting at the >>> prompt.

> class ScrolledCanvas(Tkinter.Frame):
> 
> It takes me back to the first error. Which means
> in both instances both directly called by me, and
> when called from the original turtle.py call,
> it's not finding the Frame class.

Because by messing about with the imports you have confused 
things to the point where Python doesn't know where to look for it.
Go back to the standard modules and work with them as-is. 
They work.

> for example, when the base class is defined in another module:
> 
> class DerivedClassName(modname.BaseClassName)
> "
> 
> 
> So why does the above, from turtle.py, a standard module,
> not allow this, 

It does and in its original form

import Tkinter as TK
...
class ScrolledCanvas(TK.Frame)

It works just fine!

> the module writer got wrong, or more likely, that I'm not
> understanding about what it's doing?

You don't understand how Python module imports and namespaces 
work. Try reading the "Modules and Function" topic in my tutorial 
followed by "Whats in a name"?

> As a sidenote, I ended up removing the from turtle import *
> line from Tkinter which resolved the problem(the example I was using
> didn't have a canvas, and I'm pretty sure Tkinter was defaulting
> to the ScrolledCanvas).

How did it get there in the first place? Did you add it?
Why would Tkinter import turtle? turtle is built using Tkinter 
not the other way around. Do not change the standard library 
modules - they work just fine as they are. And because they 
are used by other modules beeaking one is likely to cause 
an avalanche effect. 

If you really think you can improve on them make a copy 
with a new name and change it.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From davea at ieee.org  Fri Apr 23 10:23:30 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 23 Apr 2010 04:23:30 -0400
Subject: [Tutor] sys.path and the path order
In-Reply-To: <C7D9B164-F931-42ED-84D9-37AE31BAAC46@newcastle.edu.au>
References: <C7D9B164-F931-42ED-84D9-37AE31BAAC46@newcastle.edu.au>
Message-ID: <4BD15902.2050104@ieee.org>

Garry Willgoose wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">My 
> question is so simple I'm surprised I can't find an answer somewhere. 
> I'm interested if I can rely on the order of the directories in the 
> sys.path list. When I'm running a file from the comand line like
>
> python tellusim.py
>
> The string in entry sys.path[0] appears to be the full path to the 
> location of the file I'm running in this case tellusim ... i.e. it 
> looks like '/Volumes/scone2/codes/tellusim0006'. This is good because 
> for my code I need to create a search path for modules that is 
> relative to the location of this file irrespective of the location I'm 
> in when I invoke the script file (i.e. I could be in /Volumes/scone2 
> and invoke it by 'python codes/tellusim0006/tellusim.py').
>
> The question is can I rely on entry [0] in sys.path always being the 
> directory in which the original file resides (& across linux, OSX and 
> Windows)? If not what is the reliable way of getting that information?
>
As Steven says, that's how it's documented.

There is another way, one that I like better.  Each module, including 
the startup script, has an attribute called __file__, which is the path 
to the source file of that module.

Then I'd use os.path.abspath(), and os.path.dirname() to turn that into 
an absolute path to the directory.

The only exception I know of to __file__ usefulness is modules that are 
loaded from zip files.  I don't know if the initial script can come from 
a zip file, but if it does, the question changes.

DaveA


From steve at pearwood.info  Fri Apr 23 11:49:19 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 23 Apr 2010 19:49:19 +1000
Subject: [Tutor] Class Inheritance
In-Reply-To: <x2g2d00d7fe1004222354w1f7ee7ddn59fcf7b8aeaa8aad@mail.gmail.com>
References: <v2p2d00d7fe1004222211x265187cdj322d0df2c198974b@mail.gmail.com>
	<201004231551.23114.steve@pearwood.info>
	<x2g2d00d7fe1004222354w1f7ee7ddn59fcf7b8aeaa8aad@mail.gmail.com>
Message-ID: <201004231949.19488.steve@pearwood.info>

On Fri, 23 Apr 2010 04:54:11 pm David Hutto wrote:
[...]
> > Something is screwy there. I believe you have broken your
> > installation by making changes to files without having any
> > understanding of what you are doing.
>
> My original post was incorrect: the first error should be:
>
> C:\Users\ascent>c:\python26/Script3.py
> Traceback (most recent call last):
>   File "C:\python26\Script3.py", line 1, in <module>
>     from Tkinter import *
>   File "C:\Python26\lib\lib-tk\Tkinter.py", line 44, in
>     from turtle import *
>   File "C:\Python26\lib\lib-tk\turtle.py", line 374, in
>     class ScrolledCanvas(TK.Frame):
> AttributeError: 'module' object has no attribute 'Frame'

For anyone else reading this, this is a good example of why retyping 
error messages is a bad, bad idea. That just wastes everybody's time, 
and sends us on wild-goose chases trying to diagnose problems that 
didn't actually occur.



> > Please don't try to "fix" library files when you don't understand
> > what they are doing. Confine your experiments to your own code, so
> > that when things break, you know that the cause is in your code,
> > not some random change you have done to the library.
>
> I know this, but I reinstall regularly, so evereything is 'pristine'.

You know it but continue to do it anyway?

If you want to experiment with library modules, make a copy of them into 
your home directory, with a different name, and experiment to your 
heart's desire. That gives you all the benefits of experimentation with 
none of the disadvantages.

When you mangle a standard library module, then post long complicated 
posts suggesting that the Python development team don't understand 
their own language, you waste our time as well as yours. If you want to 
waste your time, go right ahead, but don't send us on wild goose chases 
with nonsense about the turtle module not allowing inheritance when the 
breakage was due to your tinkering.

Next time you do something like this, be up front about it. Tell us 
right from the beginning that you've been editing the modules, so we 
don't have to spend our time discovering this for ourselves. If you 
had, this conversation would have taken a completely different turn.


> If I get an error, I don't wait for mailing list responses, I usually
> try to analyze, from what I've learned so far, what's wrong  and
> figure out why on my own

All that is good practice. What's not good practice is making random 
changes to complicated libraries.

A good exercise in programming discipline is to try to reproduce the 
fault in the smallest amount of code possible. When asking for help, 
you'll often be asked to do this, because when asking for volunteers to 
spend their time solving your problems for free, it is only fair that 
you reduce the amount of effort needed as much as possible. As an 
exercise, I've reproduced your error in minimal form:



>>> import mytkinter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mytkinter.py", line 1, in <module>
    from myturtle import *
  File "myturtle.py", line 3, in <module>
    class ScrolledCanvas(TK.Frame):
AttributeError: 'module' object has no attribute 'Frame'


and here's the minimal implementation:


# mytinkinter.py
from myturtle import *
class Frame:
    pass


# myturtle.py
import mytkinter as TK
class ScrolledCanvas(TK.Frame):
    pass



> P.S. I bet you've been waiting since you got your first condescending
> response to a similar question, to lay it on someone about touching
> the Almighty Library.
>
> Way to keep up the cycle.

Don't try to psychoanalyse people you've never met, you aren't any good 
at it.




-- 
Steven D'Aprano

From bermanrl at cfl.rr.com  Fri Apr 23 16:05:37 2010
From: bermanrl at cfl.rr.com (Robert Berman)
Date: Fri, 23 Apr 2010 10:05:37 -0400
Subject: [Tutor] Binary search question
Message-ID: <003301cae2ee$0cbb5d60$26321820$@rr.com>

Hi,

Given a list, list1 having 100,000 non repeating, sorted integers ,  which of
the following methods is fastest to find an item fully understanding the item
may or may not be in the list: The binary search method which is the standard
search for such a small sample size, or the more python type statement is
<value> in list1?

What I am really trying to ascertain is how expensive or how efficient is  'is
<value> in list1'.

Thanks for your input

Robert Berman

What you don't see with your eyes, don't invent with your mouth.



From cwitts at compuscan.co.za  Fri Apr 23 16:17:50 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Fri, 23 Apr 2010 16:17:50 +0200
Subject: [Tutor] Binary search question
In-Reply-To: <003301cae2ee$0cbb5d60$26321820$@rr.com>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>
Message-ID: <4BD1AC0E.20105@compuscan.co.za>

Robert Berman wrote:
> Hi,
>
> Given a list, list1 having 100,000 non repeating, sorted integers ,  which of
> the following methods is fastest to find an item fully understanding the item
> may or may not be in the list: The binary search method which is the standard
> search for such a small sample size, or the more python type statement is
> <value> in list1?
>
> What I am really trying to ascertain is how expensive or how efficient is  'is
> <value> in list1'.
>
> Thanks for your input
>
> Robert Berman
>
> What you don't see with your eyes, don't invent with your mouth.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>   

Bisect and search.
If the list is sorted you easily know what the first and last element 
is.  Bisect the list, check that value, if it's higher than your target 
then bisect the bottom half of the list and check that and then it's a 
matter of rinse & repeat.

You'll be suprised how few bisections you will need to do in order to 
find your data.

-- 
Kind Regards,
Christian Witts



From hugo.yoshi at gmail.com  Fri Apr 23 17:00:36 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Fri, 23 Apr 2010 17:00:36 +0200
Subject: [Tutor] Binary search question
In-Reply-To: <003301cae2ee$0cbb5d60$26321820$@rr.com>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>
Message-ID: <v2t29179d161004230800q84269ac6t1df26943ce0ef501@mail.gmail.com>

On Fri, Apr 23, 2010 at 4:05 PM, Robert Berman <bermanrl at cfl.rr.com> wrote:
> Hi,
>
> Given a list, list1 having 100,000 non repeating, sorted integers , ?which of
> the following methods is fastest to find an item fully understanding the item
> may or may not be in the list: The binary search method which is the standard
> search for such a small sample size, or the more python type statement is
> <value> in list1?
>
> What I am really trying to ascertain is how expensive or how efficient is ?'is
> <value> in list1'.
>

Because the 'in' operator can't make any assumptions about the order
of the sequence (it has to work on unsorted data as well), it has to
check every item, which makes it O(n) time in the size of the
iterator.

A binary search requires data to be sorted, but works in O(log n), so
It will always be faster than a naive linear search like the in
operator performs.

HTH,
Hugo

From emile at fenx.com  Fri Apr 23 17:29:01 2010
From: emile at fenx.com (Emile van Sebille)
Date: Fri, 23 Apr 2010 08:29:01 -0700
Subject: [Tutor] Binary search question
In-Reply-To: <003301cae2ee$0cbb5d60$26321820$@rr.com>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>
Message-ID: <hqsebc$91i$1@dough.gmane.org>

On 4/23/2010 7:05 AM Robert Berman said...
> Hi,
>
> Given a list, list1 having 100,000 non repeating, sorted integers ,  which of
> the following methods is fastest to find an item fully understanding the item
> may or may not be in the list: The binary search method which is the standard
> search for such a small sample size, or the more python type statement is
> <value>  in list1?
>
> What I am really trying to ascertain is how expensive or how efficient is  'is
> <value>  in list1'.


It's expensive enough that for a list this size I'd convert it to a dict 
and use in on that.  eg,

a = range(100000)
d = dict(zip(a,a))

55555 in d


Emile


From hugo.yoshi at gmail.com  Fri Apr 23 18:40:53 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Fri, 23 Apr 2010 18:40:53 +0200
Subject: [Tutor] Binary search question
In-Reply-To: <hqsebc$91i$1@dough.gmane.org>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>
	<hqsebc$91i$1@dough.gmane.org>
Message-ID: <h2u29179d161004230940qa64ca901ucea26e86a203c5b6@mail.gmail.com>

On Fri, Apr 23, 2010 at 5:29 PM, Emile van Sebille <emile at fenx.com> wrote:
>
>
> It's expensive enough that for a list this size I'd convert it to a dict and
> use in on that. ?eg,
>
> a = range(100000)
> d = dict(zip(a,a))
>
> 55555 in d
>

you will want to nuance that statement just a little. If you're going
to perform just a few key lookups, the process of creating the dict
will negate any performance advantage. With many key lookups it will
be a win, of course, because O(1) lookup saves you a lot over O(n).

Here's some timings of different methods:

$ python prof.py
starting timing...
timing list: [7.5448801517486572, 6.4503600597381592, 6.1473228931427002]
timing bisect: [0.012073993682861328, 0.011871099472045898,
0.011121988296508789]
timing frozenset (one lookup): [9.3203139305114746,
15.974851131439209, 10.923642873764038]
timing dict (one lookup)": [32.903657913208008, 38.234655857086182,
42.381407976150513]
timing frozenset (many lookups): [0.0022511482238769531,
0.0021729469299316406, 0.0021619796752929688]
timing dict (many lookups): [0.0048539638519287109,
0.0043039321899414062, 0.0047240257263183594]

each one times 10.000 lookups of the number 55555 into a sorted list
(range(10000)), using different methods:

* list: use the 'in' operator on the list
* bisect: use the bisection algorithm from the std lib.
* frozenset: create a frozenset from the list and use that for lookup.
* dict: create a dict from the list and use that for lookup.

The frozenset and dict methods are done in two differen ways: creating
it once and using it for all lookups, and creating a new one for every
lookup (simulating the case where you only need to do a single lookup
into the list)

conclusions:
* if you only need to do one lookup into the list, use bisect if you
can. It's the better algorithm. Your second-best option is the 'in'
operator. creating a dict or frozenset is too expensive.
* when you're going to do many lookups on a list, creating a frozenset
from it is the fastest option. It's cheaper to create than a
dictionary, and lookups are O(1).

caveats:
* timings apply to a sorted list. if your list is unsorted and you
only need a single lookup, the simple lookup may be better than a
sort/bisect. for multiple lookups, frozenset will likely still be the
fastest method.
* the number chosen to look up is not present in the list,
guarantueeing worst case performace for list.__contains__. Timings
will be different for a number present in the list (when looking up
the first element, performace should be very good indeed). However,
you should always account for the worst case IMHO

for the curious, the timing script I used is up here:
http://gist.github.com/376767

HTH,
Hugo

From bermanrl at cfl.rr.com  Fri Apr 23 19:23:55 2010
From: bermanrl at cfl.rr.com (Robert Berman)
Date: Fri, 23 Apr 2010 13:23:55 -0400
Subject: [Tutor] Binary search question
Message-ID: <000001cae309$c088ebd0$419ac370$@rr.com>

Thank you all for your ideas and suggestions. The detailed explanations were
most useful.

 

Robert Berman

 

What you don't see with your eyes, don't invent with your mouth.

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100423/5b476c11/attachment.html>

From alan.gauld at btinternet.com  Fri Apr 23 23:07:11 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 23 Apr 2010 22:07:11 +0100
Subject: [Tutor] Binary search question
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>
	<v2t29179d161004230800q84269ac6t1df26943ce0ef501@mail.gmail.com>
Message-ID: <hqt26j$noc$1@dough.gmane.org>


"Hugo Arts" <hugo.yoshi at gmail.com> wrote
> A binary search requires data to be sorted, but works in O(log n), so
> It will always be faster than a naive linear search like the in
> operator performs.

Being picky but 'in' could be faster if the item searched for happens 
to be very near the front of the list. "Always" is a strong word :-)

But in general terms you are, of course, quite right, a linear search 
is slower than a chop for sorted data.

Alan G


From alan.gauld at btinternet.com  Fri Apr 23 23:21:13 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 23 Apr 2010 22:21:13 +0100
Subject: [Tutor] Binary search question
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>
	<hqsebc$91i$1@dough.gmane.org>
Message-ID: <hqt30t$qhe$1@dough.gmane.org>


"Emile van Sebille" <emile at fenx.com> wrote 

> It's expensive enough that for a list this size I'd convert it to a dict 
> and use in on that.  eg,
> 
> a = range(100000)
> d = dict(zip(a,a))
> 

Surely that would depend on how often you do the search? 
If its a one off occurence I'd expect the overhead of zipping 
and converting to a dict would outweight the savings?

If the search was inside a loop however then I'd definitely 
agree. Although I'd opt for a set rather than a dict...

Another option would be to use the bisect module on a 
sorted version of the list.

if x in L

is like

L2 = sorted(L)
if L2[bisect.bisect_left(x)] == x      # untested! Might need bisect_right()...
But only testing and timing would tell which was faster.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From emile at fenx.com  Fri Apr 23 23:33:31 2010
From: emile at fenx.com (Emile van Sebille)
Date: Fri, 23 Apr 2010 14:33:31 -0700
Subject: [Tutor] Binary search question
In-Reply-To: <hqt30t$qhe$1@dough.gmane.org>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>	<hqsebc$91i$1@dough.gmane.org>
	<hqt30t$qhe$1@dough.gmane.org>
Message-ID: <hqt3mq$sub$1@dough.gmane.org>

On 4/23/2010 2:21 PM Alan Gauld said...
>
> "Emile van Sebille" <emile at fenx.com> wrote
>> It's expensive enough that for a list this size I'd convert it to a
>> dict and use in on that. eg,
>>
>> a = range(100000)
>> d = dict(zip(a,a))
>>
>
> Surely that would depend on how often you do the search? If its a one
> off occurence I'd expect the overhead of zipping and converting to a
> dict would outweight the savings?

Oh sure, but in practical terms, if it's a one-off situation who cares 
which you us?  For a one-off I'd just use in and not be concerned.

>
> If the search was inside a loop however then I'd definitely agree.
> Although I'd opt for a set rather than a dict...

Old habits...

Emile


From hugo.yoshi at gmail.com  Fri Apr 23 23:55:21 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Fri, 23 Apr 2010 23:55:21 +0200
Subject: [Tutor] Binary search question
In-Reply-To: <hqt3mq$sub$1@dough.gmane.org>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>
	<hqsebc$91i$1@dough.gmane.org> 
	<hqt30t$qhe$1@dough.gmane.org> <hqt3mq$sub$1@dough.gmane.org>
Message-ID: <m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com>

On Fri, Apr 23, 2010 at 11:33 PM, Emile van Sebille <emile at fenx.com> wrote:
> On 4/23/2010 2:21 PM Alan Gauld said...
>>
>> "Emile van Sebille" <emile at fenx.com> wrote
>>>
>>> It's expensive enough that for a list this size I'd convert it to a
>>> dict and use in on that. eg,
>>>
>>> a = range(100000)
>>> d = dict(zip(a,a))
>>>
>>
>> Surely that would depend on how often you do the search? If its a one
>> off occurence I'd expect the overhead of zipping and converting to a
>> dict would outweight the savings?
>
> Oh sure, but in practical terms, if it's a one-off situation who cares which
> you us? ?For a one-off I'd just use in and not be concerned.
>

I guess Alan missed my second e-mail with the micro benchmarks, but
that nuances my first answer quite a bit, and makes all the points he
is making. That does not make him less correct, of course. set (I used
frozenset, but either way) is faster than dict, and in a one-off
you're best off using bisect.

For completeness sake, on a 10000 item list, using the in operator
takes *in the worst case* around 7 seconds. bisect, again in the worst
case, takes only around 0.01 seconds (that's on a Core 2 Duo T5300 @
1.7 GHZ, 2 GB RAM). That's quite a savings. those 7 seconds can easily
be 99% of the execution time of a typical script. So for sufficiently
large data set it can definitely pay off to be concerned, even with a
one-off

Of course, profiling will immediately catch that kind of performance
bottleneck. So even if you care about performance, you can start off
using 'in' and easily optimize later with bisect or a set, the whole
"don't do it yet" thing and all.

Hugo

From marcodrompre at gmail.com  Sat Apr 24 00:32:42 2010
From: marcodrompre at gmail.com (=?ISO-8859-1?Q?Marco_Rompr=E9?=)
Date: Fri, 23 Apr 2010 18:32:42 -0400
Subject: [Tutor] Would you please help me understand my error
Message-ID: <j2n4bdcec5e1004231532r69f0e687g8727b6176630f176@mail.gmail.com>

Its supposed to be a object magasin (shop in french) with some golf items in
it


 class Magasin:
    """
    Le concept magasin pour la gestion d'inventaire des items de golf.
    """
    def __init__(self, nom ="", items =[] ):
        self.nom = nom
        self.items = items

    def set_nom(self, nom):
        self.nom = nom

    nom = property(None, set_nom)

    def set_items(self, items):
        self.items = items

    items = property(None, set_items)

    def __str__(self):
        return self.nom

class Item:
    """
    Le concept item pour la gestion d'inventaire des items de golf.
    """
    def __init__(self, nom ="", prix =""):
        self.nom = nom
        self.prix = prix

    def set_nom(self, nom):
        self.nom = nom

    nom = property(None, set_nom)

    def set_prix(self, prix):
        self.prix = prix

    prix = property(None, set_prix)

    def __str__(self):
        return self.nom

class Modele:
    """
    La definition d'un modele avec les magasins.
    """
    def __init__(self, magasins =[]):
        self.magasins = magasins

    def set_magasins(self, magasins):
        self.magasins = magasins

    magasins = property(None, set_magasins)

    def vide(self):
        if self.magasins == []:
            return True
        else:
            return False

    def initialiser(self):
        magasin01 = Magasin ("Swing de golf")

        item01 = Item ("Ensemble de fers Titleist")
        item01.set_prix("999.99")

        item02 = Item ("Ensemble de fers Callaway")

        items = [item01, item02]
        magasin01.set_items(items)

    def afficher(self):
        print("")
        print("Magasins")
        for magasin in self.magasins:
            print("")
            print(magasin)
            for tache in magasin.items:
                print(item)
        self.set_magasins([magasin01])



if __name__ == '__main__':
    modele = Modele()
    #modele.charger()
    if modele.vide():
        modele.initialiser()
    modele.afficher()

My error is:

Magasins

Traceback (most recent call last):
  File "F:\School\University\Session 4\Programmation SIO\Golftmodele.py",
line 102, in <module>
    modele.afficher()
  File "F:\School\University\Session 4\Programmation SIO\Golftmodele.py",
line 93, in afficher
    self.set_magasins([magasin01])
NameError: global name 'magasin01' is not defined

Thank you
-- 
Marc-O. Rompr?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100423/c237d14e/attachment.html>

From ricaraoz at gmail.com  Sat Apr 24 00:32:42 2010
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Fri, 23 Apr 2010 19:32:42 -0300
Subject: [Tutor] Binary search question
In-Reply-To: <m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>	<hqsebc$91i$1@dough.gmane.org>
	<hqt30t$qhe$1@dough.gmane.org> <hqt3mq$sub$1@dough.gmane.org>
	<m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com>
Message-ID: <4BD2200A.6000504@gmail.com>

Hugo Arts wrote:
> On Fri, Apr 23, 2010 at 11:33 PM, Emile van Sebille <emile at fenx.com> wrote:
>   
>> On 4/23/2010 2:21 PM Alan Gauld said...
>>     
>>> "Emile van Sebille" <emile at fenx.com> wrote
>>>       
>>>> It's expensive enough that for a list this size I'd convert it to a
>>>> dict and use in on that. eg,
>>>>
>>>> a = range(100000)
>>>> d = dict(zip(a,a))
>>>>
>>>>         
>>> Surely that would depend on how often you do the search? If its a one
>>> off occurence I'd expect the overhead of zipping and converting to a
>>> dict would outweight the savings?
>>>       
>> Oh sure, but in practical terms, if it's a one-off situation who cares which
>> you us?  For a one-off I'd just use in and not be concerned.
>>
>>     
>
> I guess Alan missed my second e-mail with the micro benchmarks, but
> that nuances my first answer quite a bit, and makes all the points he
> is making. That does not make him less correct, of course. set (I used
> frozenset, but either way) is faster than dict, and in a one-off
> you're best off using bisect.
>
> For completeness sake, on a 10000 item list, using the in operator
> takes *in the worst case* around 7 seconds. bisect, again in the worst
> case, takes only around 0.01 seconds (that's on a Core 2 Duo T5300 @
> 1.7 GHZ, 2 GB RAM). That's quite a savings. those 7 seconds can easily
> be 99% of the execution time of a typical script. So for sufficiently
> large data set it can definitely pay off to be concerned, even with a
> one-off
>
> Of course, profiling will immediately catch that kind of performance
> bottleneck. So even if you care about performance, you can start off
> using 'in' and easily optimize later with bisect or a set, the whole
> "don't do it yet" thing and all.
>
> Hugo
> _______________________________________________
>   

In the same vein of completeness sake, and since this is the *tutor*
list, we should stress that the 'right' approach is to use 'in' whatever
the case. And only if the system is too slow and profiling shows that
'in' is the culprit should we seek for alternatives.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100423/fe8d4f0a/attachment-0001.html>

From emile at fenx.com  Sat Apr 24 00:44:35 2010
From: emile at fenx.com (Emile van Sebille)
Date: Fri, 23 Apr 2010 15:44:35 -0700
Subject: [Tutor] Binary search question
In-Reply-To: <m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>	<hqsebc$91i$1@dough.gmane.org>
	<hqt30t$qhe$1@dough.gmane.org> <hqt3mq$sub$1@dough.gmane.org>
	<m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com>
Message-ID: <hqt7s0$a3b$1@dough.gmane.org>

On 4/23/2010 2:55 PM Hugo Arts said...
> For completeness sake, on a 10000 item list, using the in operator
> takes *in the worst case* around 7 seconds.

:)

Well on my system checking for the last element of a 100k item list 
returns true almost upon hitting the enter key.  Surely 7 seconds for a 
list 1/10th the size is a typo?

Anyway, I think we're all on the same page.

Nice benchmarks, btw.

Regards,

Emile


From james at uplinkzero.com  Sat Apr 24 00:41:04 2010
From: james at uplinkzero.com (James Chapman)
Date: Fri, 23 Apr 2010 23:41:04 +0100
Subject: [Tutor] smtplib help required
Message-ID: <1272062464.4bd22200aa350@webmail.uplinkzero.com>

Hi there gurus and everyone else. This is my first post to this group,
and I'm turning here because I'm stumped and search engines are not
helping.

I've used smtplib for a few things already and while wanting to use
it again today, I'm having weird things happen.

Basically, my code looks like this:

----------------
#!/usr/bin/env python

import smtplib

pass

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

and when I run it, I get this:
----------------
srv1:~/python# ./email.py?
Traceback (most recent call last):
??File "./email.py", line 3, in 
?? ?import smtplib
??File "/usr/local/lib/python2.6/smtplib.py", line 46, in 
?? ?import email.utils
ImportError: No module named utils

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

And I can also confirm that email.utils exists
----------------
srv1:~/python# file /usr/local/lib/python2.6/email/utils.py
/usr/local/lib/python2.6/email/utils.py: ASCII Java program text
----------------

So can anyone steer me in the right direction?
Oh, this first happened with the Debian distro release Python2.5, I
then downloaded and compiled 2.6.5 and it's still happening. I'm very
lost and would appreciate any help on the matter.

--
James

?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100423/a6f91643/attachment.html>

From bermanrl at cfl.rr.com  Sat Apr 24 00:59:55 2010
From: bermanrl at cfl.rr.com (Robert Berman)
Date: Fri, 23 Apr 2010 18:59:55 -0400
Subject: [Tutor] Binary search question
In-Reply-To: <m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>	<hqsebc$91i$1@dough.gmane.org>
	<hqt30t$qhe$1@dough.gmane.org> <hqt3mq$sub$1@dough.gmane.org>
	<m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com>
Message-ID: <002001cae338$b10d8f10$1328ad30$@rr.com>


> -----Original Message-----
> From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor-
> bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Hugo Arts
> Sent: Friday, April 23, 2010 5:55 PM
> To: Emile van Sebille
> Cc: tutor at python.org
> Subject: Re: [Tutor] Binary search question
> 
>
>>>>>>>>>>>>>>>>>BIG SNIP	

> Of course, profiling will immediately catch that kind of performance
> bottleneck. So even if you care about performance, you can start off
> using 'in' and easily optimize later with bisect or a set, the whole
> "don't do it yet" thing and all.
> 
> Hugo

This sounds very much like the school of thought that equates optimal
efficiency with the developers level of comfort < not confidence>. So that I
might be willing to live with an occasional 7 second search time for the
general ease of using <value> in list. Knowing of course that eventually a
programmer who is concerned with that potential 7 second lag time will opt for
either a dictionary lookup or a bisected search.


Robert Berman

What you don't see with your eyes, don't invent with your mouth.

> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From ricaraoz at gmail.com  Sat Apr 24 01:02:47 2010
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Fri, 23 Apr 2010 20:02:47 -0300
Subject: [Tutor] Would you please help me understand my error
In-Reply-To: <j2n4bdcec5e1004231532r69f0e687g8727b6176630f176@mail.gmail.com>
References: <j2n4bdcec5e1004231532r69f0e687g8727b6176630f176@mail.gmail.com>
Message-ID: <4BD22717.4070905@gmail.com>

Marco Rompr? wrote:
> Its supposed to be a object magasin (shop in french) with some golf
> items in it
>
>
>  class Magasin:
>     """
>     Le concept magasin pour la gestion d'inventaire des items de golf.
>     """
>     def __init__(self, nom ="", items =[] ):
>         self.nom = nom
>         self.items = items
>
>     def set_nom(self, nom):
>         self.nom = nom
>
>     nom = property(None, set_nom)
>
>     def set_items(self, items):
>         self.items = items
>
>     items = property(None, set_items)
>
>     def __str__(self):
>         return self.nom
>
> class Item:
>     """
>     Le concept item pour la gestion d'inventaire des items de golf.
>     """
>     def __init__(self, nom ="", prix =""):
>         self.nom = nom
>         self.prix = prix
>
>     def set_nom(self, nom):
>         self.nom = nom
>
>     nom = property(None, set_nom)
>
>     def set_prix(self, prix):
>         self.prix = prix
>
>     prix = property(None, set_prix)
>
>     def __str__(self):
>         return self.nom
>
> class Modele:
>     """
>     La definition d'un modele avec les magasins.
>     """
>     def __init__(self, magasins =[]):
>         self.magasins = magasins
>
>     def set_magasins(self, magasins):
>         self.magasins = magasins
>
>     magasins = property(None, set_magasins)
>
>     def vide(self):
>         if self.magasins == []:
>             return True
>         else:
>             return False
>
>     def initialiser(self):
>         magasin01 = Magasin ("Swing de golf")
>
>         item01 = Item ("Ensemble de fers Titleist")
>         item01.set_prix("999.99")
>        
>         item02 = Item ("Ensemble de fers Callaway")
>
>         items = [item01, item02]
>         magasin01.set_items(items)
>
>     def afficher(self):
>         print("")
>         print("Magasins")
>         for magasin in self.magasins:
>             print("")
>             print(magasin)
>             for tache in magasin.items:
>                 print(item)
>         self.set_magasins([magasin01])
>
>
>
> if __name__ == '__main__':     
>     modele = Modele()
>     #modele.charger()
>     if modele.vide():
>         modele.initialiser()
>     modele.afficher()
>
> My error is:
>
> Magasins
>
> Traceback (most recent call last):
>   File "F:\School\University\Session 4\Programmation
> SIO\Golftmodele.py", line 102, in <module>
>     modele.afficher()
>   File "F:\School\University\Session 4\Programmation
> SIO\Golftmodele.py", line 93, in afficher
>     self.set_magasins([magasin01])
> NameError: global name 'magasin01' is not defined
>
> Thank you
> -- 
> Marc-O. Rompr?

Bien,
    for starters please get rid of all those set_ methods. They are
doing nothing, it's not pythonic. Just assign the value straight away.
e.g.: from """ item01.set_prix("999.99") """  to """ item01.prix =
"999.99" """
BTW, why do you use prix as a character? Shouldn't it be a number? Check
the decimal module.
Your error comes from the fact that magasin01 only exists inside
initialiser(), it is local to this method, so afficher() can't reference it.
Note : notice the """ print(tache) """ correction. The code is untested
and probably compliant with 2.5 and not 3.x

 from decimal import Decimal
 class Magasin:
    """
    Le concept magasin pour la gestion d'inventaire des items de golf.
    """
    def __init__(self, nom ="", items =[] ):
        self.nom = nom
        self.items = items

    def __str__(self):
        return self.nom

class Item:
    """
    Le concept item pour la gestion d'inventaire des items de golf.
    """
    def __init__(self, nom ="", prix =None):
        self.nom = nom
        self.prix = prix

    def __str__(self):
        return self.nom

class Modele:
    """
    La definition d'un modele avec les magasins.
    """
    def __init__(self, magasins =[]):
        self.magasins = magasins

    def vide(self):
        return not self.magasins     # Though I can't see why you would
want this method. Just ask for the property and done

    def initialiser(self):
        items = [Item ("Ensemble de fers Titleist", Decimal("999.99")),
                     Item ("Ensemble de fers Callaway")]
        self.magasin = Magasin ("Swing de golf", items)

    def afficher(self):
        print("")
        print("Magasins")
        for magasin in self.magasins:
            print("")
            print(magasin)
            for tache in magasin.items:
                print(tache)



if __name__ == '__main__':     
    modele = Modele()
    #modele.charger()
    if modele.vide():
        modele.initialiser()
    modele.afficher()


From bermanrl at cfl.rr.com  Sat Apr 24 01:11:21 2010
From: bermanrl at cfl.rr.com (Robert Berman)
Date: Fri, 23 Apr 2010 19:11:21 -0400
Subject: [Tutor] Binary search question
In-Reply-To: <4BD2200A.6000504@gmail.com>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>	<hqsebc$91i$1@dough.gmane.org>	<hqt30t$qhe$1@dough.gmane.org>
	<hqt3mq$sub$1@dough.gmane.org>	<m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com>
	<4BD2200A.6000504@gmail.com>
Message-ID: <002101cae33a$4a09b940$de1d2bc0$@rr.com>

From: tutor-bounces+bermanrl=cfl.rr.com at python.org
[mailto:tutor-bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Ricardo
Ar?oz
Sent: Friday, April 23, 2010 6:33 PM
To: Hugo Arts
Cc: tutor at python.org; Emile van Sebille
Subject: Re: [Tutor] Binary search question

Hugo Arts wrote: 
On Fri, Apr 23, 2010 at 11:33 PM, Emile van Sebille <emile at fenx.com> wrote:
  
On 4/23/2010 2:21 PM Alan Gauld said...
    
"Emile van Sebille" <emile at fenx.com> wrote
      
It's expensive enough that for a list this size I'd convert it to a
dict and use in on that. eg,

a = range(100000)
d = dict(zip(a,a))

        
Surely that would depend on how often you do the search? If it's a one
off occurrence I'd expect the overhead of zipping and converting to a
dict would outweigh the savings?
      
Oh sure, but in practical terms, if it's a one-off situation who cares which
you us? ?For a one-off I'd just use in and not be concerned.

    

I guess Alan missed my second e-mail with the micro benchmarks, but
that nuances my first answer quite a bit, and makes all the points he
is making. That does not make him less correct, of course. set (I used
frozenset, but either way) is faster than dict, and in a one-off
you're best off using bisect.

For completeness sake, on a 10000 item list, using the in operator
takes *in the worst case* around 7 seconds. bisect, again in the worst
case, takes only around 0.01 seconds (that's on a Core 2 Duo T5300 @
1.7 GHZ, 2 GB RAM). That's quite a savings. those 7 seconds can easily
be 99% of the execution time of a typical script. So for sufficiently
large data set it can definitely pay off to be concerned, even with a
one-off

Of course, profiling will immediately catch that kind of performance
bottleneck. So even if you care about performance, you can start off
using 'in' and easily optimize later with bisect or a set, the whole
"don't do it yet" thing and all.

Hugo
_______________________________________________
  

In the same vein of completeness sake, and since this is the *tutor* list, we
should stress that the 'right' approach is to use 'in' whatever the case. And
only if the system is too slow and profiling shows that 'in' is the culprit
should we seek for alternatives.

Wow. I feel I have just been b
h slapped across the face. I think Hugo?s test
results pretty much confirmed ?in? is not the way to go although it is one of
the methods I am trying even though my tendency, since the number of elements
is always less than 1,000,000, is to use the dictionary approach. 
But, even though my years of experience using Python is less than 4 I would be
reluctant to use ?in? just based on what I have been reading from those who
took the time to answer my post. Just my $0.02 worth.

Robert Berman

What you don't see with your eyes, don't invent with your mouth.




From steve at pearwood.info  Sat Apr 24 01:19:53 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Apr 2010 09:19:53 +1000
Subject: [Tutor] Binary search question
In-Reply-To: <hqt30t$qhe$1@dough.gmane.org>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>
	<hqsebc$91i$1@dough.gmane.org> <hqt30t$qhe$1@dough.gmane.org>
Message-ID: <201004240919.54592.steve@pearwood.info>

On Sat, 24 Apr 2010 07:21:13 am Alan Gauld wrote:
> "Emile van Sebille" <emile at fenx.com> wrote
>
> > It's expensive enough that for a list this size I'd convert it to a
> > dict and use in on that.  eg,
> >
> > a = range(100000)
> > d = dict(zip(a,a))
>
> Surely that would depend on how often you do the search?
> If its a one off occurence I'd expect the overhead of zipping
> and converting to a dict would outweight the savings?

It absolutely has to, because zipping it has to iterate over the entire 
list, then calling dict has to iterate over the entire zipped version. 
That's iterating over the entire list *twice* before you even START 
doing a search!

In Python 3.x, zip is a lazy iterator so that will reduce the excess 
iterations from twice to once, but for a one-off test it entirely 
negates the point of converting.


> If the search was inside a loop however then I'd definitely
> agree. Although I'd opt for a set rather than a dict...

Yes, there's no point in making a dict {a:a} just for membership testing 
when you can just use a set.


> Another option would be to use the bisect module on a
> sorted version of the list.

But keep in mind that unless the list is HUGE, or your Python version 
includes the C version of bisect, a linear search using in may end up 
being faster than a slow pure-Python version of bisect.

Also, bisect on its own doesn't do membership testing:

>>> data = range(0,100,2)
>>> 7 in data
False
>>> bisect.bisect(data, 7)
4

So you have to weigh up the extra complication needed versus the 
optimization.

Another strategy is to move items closer to the front of the list each 
time they are accessed, so that commonly used items eventually bubble 
up to the front of the list and searches for them are fast.

And finally, if the list is very large, and your searches tend to be 
clustered, it becomes wasteful to do a fresh binary search each time 
you look something up. (E.g. consider looking up these three words in 
the dictionary, one after the other: "caravan", "cat", "cap".) In this 
case, a good strategy is sometimes called "hunt and search". The 
algorithm is something like this:

Each search takes a second argument, i, the place to start searching 
from. This will usually be the place the previous search ended at.

First you *hunt* for the item: try to bracket the item you want between 
i and i+1, then i and i+2, then i and i+4, i+8, and so forth, doubling 
the size of the bracket each time. (This assumes that the value at 
index i was too small. If it were too large, you hunt in the opposite 
direction, with i-1 to i, i-2 to i, etc.)

Once you have bracketed the item you are searching for, you *search* for 
it within those limits, using binary search or even a linear search. If 
your searches are clustered, most of the hunt phases will be short and 
even linear search will be fast, rather than doing a binary search over 
the full list each time.



-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Sat Apr 24 01:31:58 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Apr 2010 00:31:58 +0100
Subject: [Tutor] Binary search question
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>	<hqsebc$91i$1@dough.gmane.org>	<hqt30t$qhe$1@dough.gmane.org><hqt3mq$sub$1@dough.gmane.org>	<m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com><4BD2200A.6000504@gmail.com>
	<002101cae33a$4a09b940$de1d2bc0$@rr.com>
Message-ID: <hqtam2$i06$1@dough.gmane.org>


"Robert Berman" <bermanrl at cfl.rr.com> wrote

> But, even though my years of experience using Python is less than 4 I would be
> reluctant to use 'in' just based on what I have been reading from those who
> took the time to answer my post. Just my $0.02 worth.

It depends, if you are transmitting the data across a slow network then it might
take 10 minutes to do that. So who cares if the in search takes 10 seconds?
And its by far the easiest and most readable solution. OTOH if your whole
program takes 1 second apart from the search then you probably do want to
optimise things.

As always use the simplest solution and only if it really needs to go faster
then optimise it.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From malaclypse2 at gmail.com  Sat Apr 24 01:39:37 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Fri, 23 Apr 2010 19:39:37 -0400
Subject: [Tutor] smtplib help required
In-Reply-To: <1272062464.4bd22200aa350@webmail.uplinkzero.com>
References: <1272062464.4bd22200aa350@webmail.uplinkzero.com>
Message-ID: <x2i16651e81004231639s1005b94h65f1ca8500aa4c99@mail.gmail.com>

On Fri, Apr 23, 2010 at 6:41 PM, James Chapman <james at uplinkzero.com> wrote:
> Hi there gurus and everyone else. This is my first post to this group, and
> I'm turning here because I'm stumped and search engines are not helping.
> I've used smtplib for a few things already and while wanting to use it again
> today, I'm having weird things happen.
<snip>
> ----------------
> srv1:~/python# ./email.py
> Traceback (most recent call last):
> ??File "./email.py", line 3, in <module>
> ?? ?import smtplib
> ??File "/usr/local/lib/python2.6/smtplib.py", line 46, in <module>
> ?? ?import email.utils
> ImportError: No module named utils
> ----------------

You've named your script email.py, which is shadowing the email
package from the standard library.

-- 
Jerry

From alan.gauld at btinternet.com  Sat Apr 24 01:41:05 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Apr 2010 00:41:05 +0100
Subject: [Tutor] Binary search question
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>	<hqsebc$91i$1@dough.gmane.org><hqt30t$qhe$1@dough.gmane.org>
	<hqt3mq$sub$1@dough.gmane.org><m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com>
	<hqt7s0$a3b$1@dough.gmane.org>
Message-ID: <hqtb76$jaj$1@dough.gmane.org>

"Emile van Sebille" <emile at fenx.com> wrote

>> For completeness sake, on a 10000 item list, using the in operator
>> takes *in the worst case* around 7 seconds.
> Well on my system checking for the last element of a 100k item list 
> returns true almost upon hitting the enter key.  Surely 7 seconds for a 
> list 1/10th the size is a typo?

Interestingly on my PC with Python 3.1:

>>> data = list(range(10000000))
>>> 9999999 in data
True
>>> -5 in data
False

takes an apparently constant, sub second time.
And the same test on Python 2.5 under cygwin is the same.
Now integers will be easier to deal with than strings but:

>>> data = [str(x) for x in range(100000)]
>>> '9999' in data
True
>>> "-5" in data
False
>>> 

Produces the same results.

And even at 10000000 entries, the list creation slowed right 
down - about 10 seconds, but the searches even for "-5" were 
still around a second.

So 'in' looks pretty effective to me!

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




From alan.gauld at btinternet.com  Sat Apr 24 01:51:35 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Apr 2010 00:51:35 +0100
Subject: [Tutor] smtplib help required
References: <1272062464.4bd22200aa350@webmail.uplinkzero.com>
Message-ID: <hqtbqs$knu$1@dough.gmane.org>


"James Chapman" <james at uplinkzero.com> wrote

> import smtplib

> and when I run it, I get this:
> import email.utils
> ImportError: No module named utils


> And I can also confirm that email.utils exists

Definitely looks like a fault in the install/configure setup.

Is there an __init__.py file in the emails folder?

But I'd definitely try a delete and reinstall.

Alan G



From james at uplinkzero.com  Sat Apr 24 01:52:21 2010
From: james at uplinkzero.com (James Chapman)
Date: Sat, 24 Apr 2010 00:52:21 +0100
Subject: [Tutor] smtplib help required
Message-ID: <1272066741.4bd232b5117d5@webmail.uplinkzero.com>

D'Oh!

Of course!?
I feel like a right pillock now.

Cheers for that though.

--
James

At Saturday, 24-04-2010 on 0:39 Jerry Hill wrote:

On Fri, Apr 23, 2010 at 6:41 PM, James Chapman  wrote:
> Hi there gurus and everyone else. This is my first post to this
group, and
> I'm turning here because I'm stumped and search engines are not
helping.
> I've used smtplib for a few things already and while wanting to use
it again
> today, I'm having weird things happen.

> ----------------
> srv1:~/python# ./email.py
> Traceback (most recent call last):
> ??File "./email.py", line 3, in 
> ?? ?import smtplib
> ??File "/usr/local/lib/python2.6/smtplib.py", line 46, in 
> ?? ?import email.utils
> ImportError: No module named utils
> ----------------

You've named your script email.py, which is shadowing the email
package from the standard library.

-- 
Jerry
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100424/8ffb9cbe/attachment-0001.html>

From steve at pearwood.info  Sat Apr 24 02:37:15 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Apr 2010 10:37:15 +1000
Subject: [Tutor] Binary search question
In-Reply-To: <002101cae33a$4a09b940$de1d2bc0$@rr.com>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>
	<4BD2200A.6000504@gmail.com>
	<002101cae33a$4a09b940$de1d2bc0$@rr.com>
Message-ID: <201004241037.15952.steve@pearwood.info>

On Sat, 24 Apr 2010 09:11:21 am Robert Berman wrote:
> Wow. I feel I have just been b?h slapped across the face.

There's no need to be so sensitive.

> I think 
> Hugo?s test results pretty much confirmed ?in? is not the way to go

If that is the *only* thing you have learned from this email thread, 
then you have failed to understand what folks are trying to say. 
Whether that is your failure or our failure is another question :)

The most important thing is that the right solution depends on what your 
data is and what you intend doing with it.

If your data is unordered, and all you do is membership testing, then 
using the `in` operator with a set is the right solution. Membership 
testing of sets is (approximately) O(1), which is much better than 
O(log N) for binary search and MUCH better than O(N) for linear search.

If you need a list, and you have the opportunity to control the format 
of your data, then you can keep the data in a list *and* a set, 
carefully keeping the two in sync. A class is probably good for that. 
Use the list for list-like things, and the set for membership testing, 
and that gives you the best of both worlds.

If your data is sorted, then binary search may be the right approach. 
But if your list is small enough, then the extra overhead of binary 
search will actually make it *slower* than a linear search.

If your data needs to be unsorted (say, you have to store it in the 
order it is delivered to you) then binary search is *not* suitable. In 
the worst case, you may have no choice but a linear search: copying the 
list into a fresh set each time is wasteful, or the list might include 
objects which are mutable and can't go into sets or dicts. Fortunately, 
Python lists are written in C and so even a linear search using `in` is 
pretty fast.

But probably the best advice given is, don't worry about optimizing your 
code until you *know* it needs optimizing. Good advice for searching a 
list with ten million items is *at best* pointless for searching a ten 
item list, and at worst actually harmful. It's hard to predict where 
bottlenecks are at the best of times, and particularly hard for people 
used to languages like C or Java. Text books that give optimization 
advice are often counter-productive when it comes to Python code. For 
instance, they will often assume that comparisons are cheap and moving 
data is relatively expensive, which is true for low-level languages 
like C. But for Python it's the other way around, comparisons are 
relatively expensive and moving data relatively cheap.

I've actually seen somebody do something like this in the name 
of "efficiency":

def issorted(alist):
    """Helper function returning true if alist is already sorted"""
    if len(alist) == 0:
        return True
    x = alist[0]
    flag = True
    for item in alist:
        if item < x:
            flag = False
            break
        x = item
    return flag

def bin_search(alist, what):
    if not issorted(alist):
        # make a copy of the list and work with that
        alist = alist[:]  # Careful! Don't change the original!
        alist.sort()
    i = bisect.bisect(alist, what)
    if i == 0:
        return False
    else:
        return alist[i-1] == what


If you think carefully about what this is doing, it is hilarious! For 
beginners who don't quite see, consider what happens if you give it a 
sorted list. First it walks the entire list, to determine whether it is 
sorted, which takes N steps. Then it does a binary search, which is 
O(log N). Since the time is dominated by the O(N) test for sortedness, 
it would be quicker to just do a linear search.

If the list is unsorted, first it walks some fraction of the list to 
discover the fact, then it does a O(N) copy, plus an O(N*log N) sort, 
before the binary search. And it does this *every single time*. Total, 
utter fail.

True confession time: the person who wrote this ridiculous piece of code 
was... me. My reasoning was that binary search was much faster than 
linear search, so it was worth sorting the list to get that advantage. 
Then I realised that I couldn't just sort the list, because other parts 
of the code might rely on it being unsorted, hence I had to make a copy 
first. Then I reasoned that I didn't need to copy it if it were already 
sorted.

For the record, here's some timing benchmarks to see how badly it turned 
out:

>>> from random import shuffle
>>> data1 = range(10000)
>>> data2 = range(10000)
>>> shuffle(data2)
>>>
>>> setup = """from __main__ import data1, data2, bin_search"""
>>> from timeit import Timer
>>> t1 = Timer("457 in data1", setup)
>>> t2 = Timer("457 in data2", setup)
>>> t3 = Timer("bin_search(data1, 457)", setup)
>>> t4 = Timer("bin_search(data2, 457)", setup)
>>>
>>> for t in (t1, t2, t3, t4):
...     print min(t.repeat(number=1000))
...
0.0346097946167
0.461233854294
3.04955101013
5.70547604561

For comparison, here's the timing on a plain binary search:



There, I have now exposed my secret shame to the whole world. Please 
don't hate me.

*wink*



-- 
Steven D'Aprano

From steve at pearwood.info  Sat Apr 24 02:50:07 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Apr 2010 10:50:07 +1000
Subject: [Tutor] Class Inheritance
In-Reply-To: <q2h2d00d7fe1004230822he9fedd2bi27c00a0b43ba4742@mail.gmail.com>
References: <v2p2d00d7fe1004222211x265187cdj322d0df2c198974b@mail.gmail.com>
	<201004231949.19488.steve@pearwood.info>
	<q2h2d00d7fe1004230822he9fedd2bi27c00a0b43ba4742@mail.gmail.com>
Message-ID: <201004241050.07906.steve@pearwood.info>

On Sat, 24 Apr 2010 01:22:54 am David Hutto wrote:
> I'm new, I touched the Holy lib, and
> didn't check to reset the original Tkinter directory before posting.
> Won't happen again.

I'm sorry we got off on the wrong foot, you caught me at a time when I 
was frustrated about other things, and after spending 30 minutes 
wasting my time trying to reproduce the errors you were getting, I 
snapped at you.

It's nothing about the library being "Holy", that's an asinine thing to 
say. It's a software package, not a piece of the One True Cross. But 
you wouldn't randomly plug and unplug parts in your car engine, and 
then complain that "Perhaps I've misunderstood something, but it seems 
to me that the Ford Fiesta doesn't have a working internal combustion 
engine."

You've got the right idea about learning by experimentation, but there's 
a right way and a wrong way to do it, and the way you've chosen is 
actively harmful to *you*, as well as wasting the time of those who 
volunteer to give help. How many hours did you waste because you 
thought that Python's implementation of inheritance was buggy, due to 
changes you introduced?

Even if it were only *one minute*, it would be too long because it is 
completely, 100% unnecessary. Keep the standard library as it is 
supplied. If you want to modify a module to see what happens, make a 
copy of it and put it in your home directory with another name, and 
make the changes there.

I applaud the fact that you are actively trying to solve problems before 
asking for help. I'm not being sarcastic or condescending when I say 
this is fantastic. But I am saying that your practice of *how* you try 
to solve problems yourself is actually counterproductive, making a rod 
for your own back, by introducing bugs into code that wasn't buggy in 
the first place. Learning to code is hard enough when you can trust the 
library to be (mostly) bug free, don't make it any harder!



-- 
Steven D'Aprano

From marcodrompre at gmail.com  Sat Apr 24 03:10:22 2010
From: marcodrompre at gmail.com (=?ISO-8859-1?Q?Marco_Rompr=E9?=)
Date: Fri, 23 Apr 2010 21:10:22 -0400
Subject: [Tutor] Would you please help me understand my error
In-Reply-To: <4BD22717.4070905@gmail.com>
References: <j2n4bdcec5e1004231532r69f0e687g8727b6176630f176@mail.gmail.com>
	<4BD22717.4070905@gmail.com>
Message-ID: <p2k4bdcec5e1004231810w790adc6aq76321cf8838d730b@mail.gmail.com>

Bien,

>    for starters please get rid of all those set_ methods. They are
> doing nothing, it's not pythonic. Just assign the value straight away.
> e.g.: from """ item01.set_prix("999.99") """  to """ item01.prix =

"999.99" """
>

    Our teacher showed us this method and in our exercise we had to copy the
teacher's code and modify the data to fit our concept

    But thks I found my error but what did you say about th decimal module
    we have to keep in mind that my exercise is for an introductory course
in python I am not good, I am  trying to learn at my best.

Here's my new code( can you please tell me if it is okay)

class Magasin:
    """
    Le concept magasin pour la gestion d'inventaire des items de golf.
    """
    def __init__(self, nom ="", items =[] ):
        self.nom = nom
        self.items = items

    def set_nom(self, nom):
        self.nom = nom

    nom = property(None, set_nom)

    def set_items(self, items):
        self.items = items

    items = property(None, set_items)

    def __str__(self):
        return self.nom

class Item:
    """
    Le concept item pour la gestion d'inventaire des items de golf.
    """
    def __init__(self, nom ="", prix =""):
        self.nom = nom
        self.prix = prix

    def set_nom(self, nom):
        self.nom = nom

    nom = property(None, set_nom)

    def set_prix(self, prix):
        self.prix = prix

    prix = property(None, set_prix)

    def __str__(self):
        return self.nom

class Modele:
    """
    La definition d'un modele avec les magasins.
    """
    def __init__(self, magasins =[]):
        self.magasins = magasins

    def set_magasins(self, magasins):
        self.magasins = magasins

    magasins = property(None, set_magasins)


    def sauvegarder(self,nom_fichier):
        modele_fichier = open(nom_fichier, 'w')
        for magasin in self.magasins:
            modele_fichier.write("===MAGASIN==="  + "\n")
            modele_fichier.write("nom : " + magasin.nom + "\n")
            modele_fichier.write("items : " + "\n")
            for item in magasin.items:
                modele_fichier.write("    ---ITEM---"  + "\n")
                modele_fichier.write("    nom : " + item.nom + "\n")
                modele_fichier.write("    prix : " + item.prix + "\n")
                modele_fichier.write("    ---FIN ITEM---"  + "\n")
            modele_fichier.write("===FIN MAGASIN==="  + "\n")
        modele_fichier.close()

    def charger(self, nom_fichier):
        magasins = []
        try:
            modele_fichier = open(nom_fichier, 'r')
        except IOError:
            print("Le fichier " + nom_fichier + " n'existe pas.")
        else:
            fin_fichier = False
            while not fin_fichier:
                ligne = modele_fichier.readline()
                if ligne == "":
                    self.set_magasins(magasins)
                    modele_fichier.close()
                    fin_fichier = True
                    break
                magasin = Magasin()
                items = []
                fin_magasin = False
                while not fin_magasin:
                    ligne = modele_fichier.readline().strip()
                    if ligne.startswith("===FIN MAGASIN==="):
                        magasin.set_items(items)
                        magasins.append(magasin)
                        fin_magasin = True
                    elif ligne.startswith("nom"):
                        nom = ligne.split(':')[1]
                        magasin.set_nom(nom.strip())
                    elif ligne.startswith("---ITEM---"):
                        item = Item()
                        fin_item = False
                        while not fin_item:
                            ligne = modele_fichier.readline().strip()
                            if ligne.startswith("nom"):
                                nom = ligne.split(':')[1]
                                item.set_nom(nom.strip())
                            elif ligne.startswith("prix"):
                                prix = ligne.split(':')[1]
                                item.set_prix(prix.strip())
                            elif ligne.startswith("---FIN ITEM---"):
                                items.append(item)
                                fin_item = True




    def vide(self):
        if self.magasins == []:
            return True
        else:
            return False

    def initialiser(self, nom_fichier):
        magasin01 = Magasin ("Swing de golf")

        item01 = Item ("Ensemble de fers Titleist")
        item01.set_prix("999.99")

        item02 = Item ("Ensemble de fers Callaway")

        items = [item01, item02]
        magasin01.set_items(items)

        self.set_magasins([magasin01])

        self.sauvegarder(nom_fichier)

    def afficher(self):
        print("")
        print("Magasins")
        for magasin in self.magasins:
            print("")
            print(magasin)
            for item in magasin.items:
                print(item)


if __name__ == '__main__':
    modele = Modele()
    nom_fichier = "magasinmodele.txt"
    modele.charger(nom_fichier)
    if modele.vide():
        modele.initialiser(nom_fichier)
    modele.afficher()




> BTW, why do you use prix as a character? Shouldn't it be a number? Check
> the decimal module.
> Your error comes from the fact that magasin01 only exists inside
> initialiser(), it is local to this method, so afficher() can't reference
> it.
> Note : notice the """ print(tache) """ correction. The code is untested
> and probably compliant with 2.5 and not 3.x
>
>  from decimal import Decimal
>
> Thank You in advance


-- 
Marc-O. Rompr?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100423/3ac29f83/attachment-0001.html>

From steve at pearwood.info  Sat Apr 24 04:04:42 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Apr 2010 12:04:42 +1000
Subject: [Tutor] Binary search question
In-Reply-To: <hqtb76$jaj$1@dough.gmane.org>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>
	<hqt7s0$a3b$1@dough.gmane.org> <hqtb76$jaj$1@dough.gmane.org>
Message-ID: <201004241204.44005.steve@pearwood.info>

On Sat, 24 Apr 2010 09:41:05 am Alan Gauld wrote:
> "Emile van Sebille" <emile at fenx.com> wrote
>
> >> For completeness sake, on a 10000 item list, using the in operator
> >> takes *in the worst case* around 7 seconds.
> >
> > Well on my system checking for the last element of a 100k item list
> > returns true almost upon hitting the enter key.  Surely 7 seconds
> > for a list 1/10th the size is a typo?
>
> Interestingly on my PC with Python 3.1:
> >>> data = list(range(10000000))
> >>> 9999999 in data
>
> True
>
> >>> -5 in data
>
> False
>
> takes an apparently constant, sub second time.

With respect Alan, timing operations by eye is pretty lame, what did you 
do, count your heartbeats? :)

Python makes it so easy to do accurate timings quickly. At least as 
accurate as they can be on a multi-tasking operating system that can 
preemptively swap processes in and out of memory as needed.

I would expect that the difference between searching for 9999999 and -5 
would be insignificant, because in both cases you have to walk the 
entire list. And sure enough, both take about half a second on my PC:


>>> setup = "data = list(range(10000000))"
>>> from timeit import Timer
>>> min(Timer("9999999 in data", setup).repeat(number=100))/100
0.5429409599304199
>>> min(Timer("-5 in data", setup).repeat(number=100))/100
0.4803972291946411

I wouldn't treat the difference between 0.54 and 0.48 as significant in 
this case. I have about a dozen other applications running, including 
at least fifty pages open in web browsers, and I continued actively 
working while the timing code was running, which is a big No-No if you 
want accurate results.

In any case, if you search for something else, the speed is quite 
different:

>>> min(Timer("5 in data", setup).repeat(number=100))/100
4.291534423828125e-07


[...]
> So 'in' looks pretty effective to me!

It is, at least for built-in lists. O(N) might not be amazingly fast, 
but it is usually fast enough. It's O(N**2) operations that you want to 
watch out for!

It is tempting to speed hours optimizing code to save twenty 
milliseconds on a program that takes 200,000 milliseconds to run, but 
there are better ways to spend your time as a programmer. Hence the 
usual advice that premature optimization is the root of all evil. First 
make it work, and then only if it's not fast enough, make it work 
faster.

Of course, none of this is meant to say you shouldn't plan ahead and 
choose the best data structure for the job!


-- 
Steven D'Aprano

From steve at pearwood.info  Sat Apr 24 04:11:07 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Apr 2010 12:11:07 +1000
Subject: [Tutor] Binary search question
In-Reply-To: <201004241037.15952.steve@pearwood.info>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>
	<002101cae33a$4a09b940$de1d2bc0$@rr.com>
	<201004241037.15952.steve@pearwood.info>
Message-ID: <201004241211.07755.steve@pearwood.info>

On Sat, 24 Apr 2010 10:37:15 am Steven D'Aprano wrote:
> For the record, here's some timing benchmarks to see how badly it
> turned out:
[...]
> 0.0346097946167
> 0.461233854294
> 3.04955101013
> 5.70547604561
>
> For comparison, here's the timing on a plain binary search:

Oops, I hit send too soon and forgot the timing. Here it is:

0.0034401416778564453

So about 10 times faster than a linear search on 10,000 items. Not to be 
sneezed at, but unless the time taken by your program is dominated by 
the searches, I probably wouldn't bother with the extra complexity.



-- 
Steven D'Aprano

From zhuchunml at gmail.com  Sat Apr 24 04:27:12 2010
From: zhuchunml at gmail.com (Joson)
Date: Sat, 24 Apr 2010 10:27:12 +0800
Subject: [Tutor]  self.attribute and import attribute
Message-ID: <u2tffa452951004231927o1732c068n68dddfafaa9408f4@mail.gmail.com>

Hi all,
I have a problem about variables efficiency.
As below, I import f from config.py, Then f is appended to app1.py global
variables.
In class App, there're two ways to use this variable. One is "self.file =f",
then use self.file; the other is using "f" directory. Which way is high
efficient?

config.py:
f = file("test.txt")


app1.py:
from config import *

class App:
    def __init__(self):
        self.file = Attr1

    def run(self):
        self.file.write("...")
        # f.write("...")

Regards.
Joson
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100424/2e684f53/attachment.html>

From marcodrompre at gmail.com  Sat Apr 24 05:07:11 2010
From: marcodrompre at gmail.com (=?ISO-8859-1?Q?Marco_Rompr=E9?=)
Date: Fri, 23 Apr 2010 23:07:11 -0400
Subject: [Tutor] Hi everybody stuck on some error need help please thank
	you!!
Message-ID: <y2z4bdcec5e1004232007ncf5fe451ta6ab88aff4f53293@mail.gmail.com>

Hi everybody, I would appreciate your help on this one
In this program I want to create 2 concepts each with 2 or 3 properties
My first concept is magasin(shop in french) and my shop has 3 attributes:
nom(name in french), items and ville (city in french)
the second one is items and its 2 attributes are nom(name in french) and
prix (price in french)
I want to be able to show a modele with the name of my magasins (stores) and
the city theyre located in, what are the names of the items i have in each
magasin and their prices.

Here's my code:

class Magasin:
    """
    Le concept magasin pour la gestion d'inventaire des items de golf.
    """
    def __init__(self, nom ="", items =[], ville="" ):
        self.nom = nom
        self.items = items
        self.vile = ville

    def set_nom(self, nom):
        self.nom = nom

    nom = property(None, set_nom)

    def set_items(self, items):
        self.items = items

    items = property(None, set_items)

    def set_ville(self, ville):
        self.ville = ville

    items = property(None, set_ville)

    def __str__(self):
        return self.nom

class Item:
    """
    Le concept item pour la gestion d'inventaire des items de golf.
    """
    def __init__(self, nom ="", prix = 100):
        self.nom = nom
        self.prix = prix

    def set_nom(self, nom):
        self.nom = nom

    nom = property(None, set_nom)

    def set_prix(self, prix):
        self.prix = prix

    prix = property(None, set_prix)

    def __str__(self):
        return self.nom

class Modele:
    """
    La definition d'un modele avec les magasins.
    """
    def __init__(self, nom_fichier, magasins =[]):
        self.nom_fichier = nom_fichier
        self.magasins = magasins

    def set_nom_fichier(self, nom_fichier):
        self.nom_fichier = nom_fichier

    nom_fichier = property(None, set_nom_fichier)

    def set_magasins(self, magasins):
        self.magasins = magasins

    magasins = property(None, set_magasins)

    def sauvegarder(self):
        modele_fichier = open(self.nom_fichier, 'w')
        for magasin in self.magasins:
            modele_fichier.write("===MAGASIN==="  + "\n")
            modele_fichier.write("nom : " + magasin.nom + "\n")
            modele_fichier.write("items : " + "\n")
            for item in magasin.items:
                modele_fichier.write("    ---ITEM---"  + "\n")
                modele_fichier.write("    nom : " + item.nom + "\n")
                modele_fichier.write("    prix : " + item.prix + "\n")
                modele_fichier.write("    ---FIN ITEM---"  + "\n")
            modele_fichier.write("===FIN MAGASIN==="  + "\n")
        modele_fichier.close()

    def charger(self):
        magasins = []
        try:
            modele_fichier = open(self.nom_fichier, 'r')
        except IOError:
            print("Le fichier " + self.nom_fichier + " n'existe pas.")
        else:
            fin_fichier = False
            while not fin_fichier:
                ligne = modele_fichier.readline()
                if ligne == "":
                    self.set_magasins(magasins)
                    modele_fichier.close()
                    fin_fichier = True
                    break
                magasin = Magasin()
                items = []
                fin_magasin = False
                while not fin_magasin:
                    ligne = modele_fichier.readline().strip()
                    if ligne.startswith("===FIN MAGASIN==="):
                        magasin.set_items(items)
                        magasins.append(magasin)
                        fin_magasin = True
                    elif ligne.startswith("nom"):
                        nom = ligne.split(':')[1]
                        magasin.set_nom(nom.strip())
                    elif ligne.startswith("---ITEM---"):
                        item = Item()
                        fin_item = False
                        while not fin_item:
                            ligne = modele_fichier.readline().strip()
                            if ligne.startswith("nom"):
                                nom = ligne.split(':')[1]
                                item.set_nom(nom.strip())
                            elif ligne.startswith("prix"):
                                prix = ligne.split(':')[1]
                                item.set_prix(float())
                            elif ligne.startswith("---FIN ITEM---"):
                                items.append(item)
                                fin_item = True

    def vide(self):
        if self.magasins == []:
            return True
        else:
            return False

    def initialiser(self):

        magasin01 = Magasin ("Swing de golf")

        magasin02 = Magasin ("Golftown")

        magasin03 = Magasin ("PointGolf")


        item01 = Item ("Ensemble de fers Titleist")
        item01.set_prix("1099.99")

        item02 = Item ("Ensemble de fers Callaway")
        item02.set_prix("1299.99")

        item03 = Item ("Ensemble de fers Taylormade Burner Graphite")
        item03.set_prix("2499.99")

        item04 = Item ("Ensemble de fers Cobra")
        item04.set_prix("999.99")

        item05 = Item ("Ensemble de fers Ping")
        item06.set_prix("1399.99")

        item06 = Item ("Ensemble de fers Ben Hogan")
        item06.set_prix("1199.99")

        items = [item01, item02, item03, item04, item05, item06]
        magasin01.set_items(items)

        self.set_magasins([magasin01])

        self.sauvegarder()

    def afficher(self):
        print("")
        print("Magasins")
        for magasin in self.magasins:
            print("")
            print(magasin)
            for item in magasin.items:
                print(item)


if __name__ == '__main__':
    modele = Modele()
    nom_fichier = "magasinmodele.txt"
    modele.charger(nom_fichier)
    if modele.vide():
        modele.initialiser(nom_fichier)
    modele.afficher()

And here's my error :

Traceback (most recent call last):
  File "F:\School\University\Session 4\Programmation
SIO\magasingolfmodele.py", line 187, in <module>
    modele = Modele()
TypeError: __init__() takes at least 2 arguments (1 given)


Thank You!!!

-- 
Marc-O. Rompr?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100423/571c2a90/attachment-0001.html>

From steve at pearwood.info  Sat Apr 24 05:10:00 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Apr 2010 13:10:00 +1000
Subject: [Tutor] self.attribute and import attribute
In-Reply-To: <u2tffa452951004231927o1732c068n68dddfafaa9408f4@mail.gmail.com>
References: <u2tffa452951004231927o1732c068n68dddfafaa9408f4@mail.gmail.com>
Message-ID: <201004241310.01348.steve@pearwood.info>

On Sat, 24 Apr 2010 12:27:12 pm Joson wrote:
> Hi all,
> I have a problem about variables efficiency.

99% of the time, you waste more of your time than you save by worrying 
about tiny efficiencies. Saving 1 minute in a program that runs for 3 
minutes is worthwhile. Saving 0.0002 seconds in a program that runs for 
0.03 seconds is not.


> As below, I import f from config.py, Then f is appended to app1.py
> global variables.

You should avoid using global variables whenever possible. They are a 
bad idea for many reasons. Just a few reasons:

They lead to excessive coupling between objects and functions.

For anything except tiny scripts, they make code harder to read, write 
and understand.

They make maintenance of the code much more difficult.

They make testing much more difficult.


> In class App, there're two ways to use this variable. One is
> "self.file =f", then use self.file; the other is using "f" directory.

Will you ever have more than one file? Then using f directly is a bad 
idea.



> Which way is high efficient?
>
> config.py:
> f = file("test.txt")

Surely there is a better name than "f" for a configuration file.



> app1.py:
> from config import *

Using import * is generally (but not always) a mistake. It makes 
debugging more difficult and leads to hard-to-find bugs. It is usually 
recommended that you write 

import config 

and then later refer to

config.f



> class App:
>     def __init__(self):
>         self.file = Attr1

Where is Attr1 defined? This code currently fails.


>     def run(self):
>         self.file.write("...")
>         # f.write("...")

The second line forces you into only ever having a single file.

The first method lets you have different files, so you could do 
something like this:

app1 = App()
app2 = App()
app1.file = file("my first file.txt", "w")
app2.file = file("my first file.txt", "w")

app2.run()
app1.run()


without each instance destroying the other instance's file.


Also, note that you keep the file open for long periods of time. This is 
generally a bad idea. If your application crashes, or the power goes 
out, the chances are very good that the data will never be written to 
disk and you will lose the data you thought you wrote to the file! It 
is best to do this:

    def run(self):
        self.file.write("...")
        self.file.flush()

Also, under some operating systems (Windows?), while the file is open, 
no other process can read from it, so backup programmers can't copy the 
file. So it is often better not to keep the file open for very long, 
but do something like this:

    def run(self):
        f = open(self.filename, 'a')
        f.write("...")
        f.close()


Even better, if you are running Python 2.6 or higher:

    def run(self):
        with open(self.filename, 'a') as f:
            f.write("...")

and the file will be automatically closed safely even if an error 
occurs!

(In Python 2.5, you can also do this if you run

from __future__ import with_statement

at the very top of your program.)




-- 
Steven D'Aprano

From steve at pearwood.info  Sat Apr 24 05:22:28 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Apr 2010 13:22:28 +1000
Subject: [Tutor] Hi everybody stuck on some error need help please thank
	you!!
In-Reply-To: <y2z4bdcec5e1004232007ncf5fe451ta6ab88aff4f53293@mail.gmail.com>
References: <y2z4bdcec5e1004232007ncf5fe451ta6ab88aff4f53293@mail.gmail.com>
Message-ID: <201004241322.28917.steve@pearwood.info>

On Sat, 24 Apr 2010 01:07:11 pm Marco Rompr? wrote:

> Here's my code:
[...]
> class Modele:
>     """
>     La definition d'un modele avec les magasins.
>     """
>     def __init__(self, nom_fichier, magasins =[]):
>         self.nom_fichier = nom_fichier
>         self.magasins = magasins
[...]
> if __name__ == '__main__':
>     modele = Modele()
>     nom_fichier = "magasinmodele.txt"
>     modele.charger(nom_fichier)
>     if modele.vide():
>         modele.initialiser(nom_fichier)
>     modele.afficher()
>
> And here's my error :
>
> Traceback (most recent call last):
>   File "F:\School\University\Session 4\Programmation
> SIO\magasingolfmodele.py", line 187, in <module>
>     modele = Modele()
> TypeError: __init__() takes at least 2 arguments (1 given)


You define Modele to require a nom_fichier argument, but then you try to 
call it with no nom_fuchier.


Also, I see that you do this:

def __init__(self, nom_fichier, magasins =[]):

You probably shouldn't do this -- it doesn't do what you probably think 
it does.

You probably think that what happens is that if you call 
Modele(nom_fichier), the magasins attribute will be set to an empty 
list. But that's not what happens.

Default values in Python are defined when the method is created, not 
when it is run. Watch this example:

>>> class Test:
...     def __init__(self, x=[]):
...             self.x = x
...
>>> a = Test()
>>> a.x
[]
>>> b = Test()
>>> b.x
[]
>>>
>>> a.x.append("Surprise!")
>>> b.x
['Surprise!']


How does this happen? Because every instance shares the same default 
list. When you append to it, all the other instances see the same 
change.

You don't notice this with default values that are strings or numbers, 
because you can't modify them, only replace them:

>>> x = y = 2  # Make two variables that point to the same value.
>>> x is y  # Make sure they are identical, not just equal.
True
>>> x = 3  # Make x point to something else.
>>> x is y  # And no longer identical.
False
>>>
>>> x = y = []  # Make two variables that point to the same thing.
>>> x is y
True
>>> x.append('something')  # Modify that list in place.
>>> x is y  # Still identical.
True
>>> y
['something']


If this is the behaviour you want, then you don't need to do anything. 
Otherwise you need to move the creation of the empty list inside the 
method:

    def __init__(self, nom_fichier, magasins=None):
        if magasins is None:
            magasins = []
        self.nom_fichier = nom_fichier
        self.magasins = magasins



-- 
Steven D'Aprano

From marcodrompre at gmail.com  Sat Apr 24 05:33:46 2010
From: marcodrompre at gmail.com (=?ISO-8859-1?Q?Marco_Rompr=E9?=)
Date: Fri, 23 Apr 2010 23:33:46 -0400
Subject: [Tutor] Hi everybody stuck on some error need help please thank
	you!!
In-Reply-To: <201004241322.28917.steve@pearwood.info>
References: <y2z4bdcec5e1004232007ncf5fe451ta6ab88aff4f53293@mail.gmail.com>
	<201004241322.28917.steve@pearwood.info>
Message-ID: <s2s4bdcec5e1004232033jd85cedcekd85a2add98f75514@mail.gmail.com>

I tried to enter model = Modele (nom_fichier) but it still does not work.
And for the list I don't understand very well, Do you know where I can pay
someone to help with my programming.
Because I feel to annoy tutors with my basic stuff

On Fri, Apr 23, 2010 at 11:22 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> On Sat, 24 Apr 2010 01:07:11 pm Marco Rompr? wrote:
>
> > Here's my code:
> [...]
> > class Modele:
> >     """
> >     La definition d'un modele avec les magasins.
> >     """
> >     def __init__(self, nom_fichier, magasins =[]):
> >         self.nom_fichier = nom_fichier
> >         self.magasins = magasins
> [...]
> > if __name__ == '__main__':
> >     modele = Modele()
> >     nom_fichier = "magasinmodele.txt"
> >     modele.charger(nom_fichier)
> >     if modele.vide():
> >         modele.initialiser(nom_fichier)
> >     modele.afficher()
> >
> > And here's my error :
> >
> > Traceback (most recent call last):
> >   File "F:\School\University\Session 4\Programmation
> > SIO\magasingolfmodele.py", line 187, in <module>
> >     modele = Modele()
> > TypeError: __init__() takes at least 2 arguments (1 given)
>
>
> You define Modele to require a nom_fichier argument, but then you try to
> call it with no nom_fuchier.
>
>
> Also, I see that you do this:
>
> def __init__(self, nom_fichier, magasins =[]):
>
> You probably shouldn't do this -- it doesn't do what you probably think
> it does.
>
> You probably think that what happens is that if you call
> Modele(nom_fichier), the magasins attribute will be set to an empty
> list. But that's not what happens.
>
> Default values in Python are defined when the method is created, not
> when it is run. Watch this example:
>
> >>> class Test:
> ...     def __init__(self, x=[]):
> ...             self.x = x
> ...
> >>> a = Test()
> >>> a.x
> []
> >>> b = Test()
> >>> b.x
> []
> >>>
> >>> a.x.append("Surprise!")
> >>> b.x
> ['Surprise!']
>
>
> How does this happen? Because every instance shares the same default
> list. When you append to it, all the other instances see the same
> change.
>
> You don't notice this with default values that are strings or numbers,
> because you can't modify them, only replace them:
>
> >>> x = y = 2  # Make two variables that point to the same value.
> >>> x is y  # Make sure they are identical, not just equal.
> True
> >>> x = 3  # Make x point to something else.
> >>> x is y  # And no longer identical.
> False
> >>>
> >>> x = y = []  # Make two variables that point to the same thing.
> >>> x is y
> True
> >>> x.append('something')  # Modify that list in place.
> >>> x is y  # Still identical.
> True
> >>> y
> ['something']
>
>
> If this is the behaviour you want, then you don't need to do anything.
> Otherwise you need to move the creation of the empty list inside the
> method:
>
>    def __init__(self, nom_fichier, magasins=None):
>        if magasins is None:
>             magasins = []
>        self.nom_fichier = nom_fichier
>        self.magasins = magasins
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Marc-O. Rompr?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100423/3fc6fb1f/attachment.html>

From steve at pearwood.info  Sat Apr 24 07:01:45 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Apr 2010 15:01:45 +1000
Subject: [Tutor] Hi everybody stuck on some error need help please thank
	you!!
In-Reply-To: <s2s4bdcec5e1004232033jd85cedcekd85a2add98f75514@mail.gmail.com>
References: <y2z4bdcec5e1004232007ncf5fe451ta6ab88aff4f53293@mail.gmail.com>
	<201004241322.28917.steve@pearwood.info>
	<s2s4bdcec5e1004232033jd85cedcekd85a2add98f75514@mail.gmail.com>
Message-ID: <201004241501.46172.steve@pearwood.info>

On Sat, 24 Apr 2010 01:33:46 pm Marco Rompr? wrote:
> I tried to enter model = Modele (nom_fichier) but it still does not
> work. 

What does "still does not work" mean?

Please copy and paste the error you get.



> And for the list I don't understand very well, 


Open an interactive session and do some experiments.

>>> a = []  # One empty list.
>>> b = []  # A different empty list. 
>>> a.append(1)  # Appends to the first list.
>>> print a, b
[1] []
>>>
>>> a = []  # An empty list.
>>> b = a  # The SAME empty list.
>>> a.append(1)
>>> print a, b
[1] [1]


When you have a default value like magasins=[], it is like the second, 
not the first.



-- 
Steven D'Aprano

From mnshtb at gmail.com  Sat Apr 24 07:13:13 2010
From: mnshtb at gmail.com (Michael Scharf)
Date: Sat, 24 Apr 2010 01:13:13 -0400
Subject: [Tutor] NLTK needs YAML?
Message-ID: <j2n388161951004232213v288643f7u577cf62c7c5074c6@mail.gmail.com>

Dear Friends,

I'm new to the list, and new to Python.  The last time I've tried
anything like the below was 20 years ago on a NeXT machine, and I had
no clue what I was doing then, either.

I've gotten IDLE up and have done some hello worlding.

I am now trying to get the NLTK working on my new iMac running OS X
10.6.3.  The Python version I have up is 2.6.5.  (There may be a
slightly older pre-install with faulty IDLE lingering somewhere on the
machine.)

I've installed Macports, and through it I installed NLTK by saying

$ sudo port install nltk

which worked.

But when, in a Python session, I try to

>>> import nltk
Traceback (most recent call last):
??File "<stdin>", line 1, in <module>
ImportError: No module named nltk

is what I get.

Macports says if that happens that I should

$ cd /tmp/nltk-installer

which works.  And that I should then

$ sudo python setup.py install

Traceback (most recent call last):
  File "setup.py", line 13, in <module>
    import nltk
  File "/private/tmp/nltk-installer/nltk/__init__.py", line 92, in <module>
    from yamltags import *
  File "/private/tmp/nltk-installer/nltk/yamltags.py", line 1, in <module>
    import yaml
ImportError: No module named yaml

So I did this:

$ port search yaml

And got:

libyaml @0.1.3 (devel)
    A YAML Parser.

p5-data-phrasebook-loader-yaml @0.09 (perl)
    Abstract your queries ... with YAML!

p5-test-yaml-meta @0.15 (perl)
    Validation of the META.yml file in a distribution.

p5-test-yaml-valid @0.04 (perl)
    Test for valid YAML

p5-yaml @0.68 (perl)
    YAML loader/dumper module

p5-yaml-libyaml @0.32 (perl)
    Perl YAML Serialization using XS and libyaml

p5-yaml-syck @0.99 (perl)
    A fast, lightweight YAML loader and dumper

p5-yaml-tiny @1.41 (perl)
    Read/Write YAML files with as little code as possible

py-yaml @3.05 (python, devel)
    YAML 1.1 parser and emitter for Python

py25-yaml @3.08 (python, devel)
    YAML 1.1 parser and emitter for Python

py26-yaml @3.08 (python, devel)
    YAML 1.1 parser and emitter for Python

rb-bee @0.5.1 (ruby, devel)
    Bee is a build tool running YAML files

syck @0.55 (textproc, devel)
    An extension for reading and writing YAML

yaml-mode.el @0.0.3 (editors)
    An emacs major mode for editing yaml files.

Found 14 ports.

So I then did:

$ sudo port install py26-yaml
--->  Computing dependencies for py26-yaml
--->  Cleaning py26-yaml

closed and re-opened the terminal, and tried it all again.

But I still get the same

ImportError: No module named yaml

So my question is: do I really not have what I need here?  Or is it a
question of  something not finding something that's there?  Maybe I'm
using the wrong name somewhere?  Or??

Many thanks,
Mike S.

From ricaraoz at gmail.com  Sat Apr 24 07:19:10 2010
From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=)
Date: Sat, 24 Apr 2010 02:19:10 -0300
Subject: [Tutor] =?iso-8859-1?q?About_property=28=29__-_For_Marco_Rompr=E9?=
Message-ID: <4BD27F4E.7070201@gmail.com>

Hi Marco (and everybody),
    in another thread you showed your code and made extensive use of
property(). Wrongful use I might say.
Let's see an example:
>>> class C(object):
...     def __init__(self): self._x = None
...     def getx(self): return self._x - 10
...     def setx(self, value): self._x = -value
...     def delx(self): del self._x
...     x = property(getx, setx, delx, "I'm the 'x' property.")
...    
>>> c = C()
>>> c.x = 23
>>> c.x
-33

as you can see you don't call setx() or getx() directly, you just
operate straight with x and setx() or getx() get automatically called
(c.x is given -value, that is -23 on setx(), and then we subtract 10 to
-23 giving -33).
What's more, you don't use property() nor setters and getters to do """
self._x = value """ that makes no sense, in that case you would use just
x and get done with it. You usually use c.x = 22 and if you have the
need of a setter or getter to process x before setting or getting *then*
you start using the setters and getters.


From smokefloat at gmail.com  Sat Apr 24 07:41:04 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 24 Apr 2010 01:41:04 -0400
Subject: [Tutor] Class Inheritance, Beat it into the Ground
Message-ID: <g2n2d00d7fe1004232241xdbb35fe0q24ef460cf5179dd0@mail.gmail.com>

In previous post I asked about  turtle module importing from tkinter.
But what I don't understand is why does Tkinter default it's casnvas
to ScrolledCanvas in turtle.py, and then as a 'metaclass' for
ScrolledCanvas in turtle it calls TK.Frame, which could have
been set as a default within Tkinter itself?

From steve at pearwood.info  Sat Apr 24 08:18:55 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 24 Apr 2010 16:18:55 +1000
Subject: [Tutor] Class Inheritance, Beat it into the Ground
In-Reply-To: <g2n2d00d7fe1004232241xdbb35fe0q24ef460cf5179dd0@mail.gmail.com>
References: <g2n2d00d7fe1004232241xdbb35fe0q24ef460cf5179dd0@mail.gmail.com>
Message-ID: <201004241618.56177.steve@pearwood.info>

On Sat, 24 Apr 2010 03:41:04 pm David Hutto wrote:
> In previous post I asked about  turtle module importing from tkinter.
> But what I don't understand is why does Tkinter default it's casnvas
> to ScrolledCanvas in turtle.py, and then as a 'metaclass' for
> ScrolledCanvas in turtle it calls TK.Frame, which could have
> been set as a default within Tkinter itself?


Tkinter doesn't know anything about turtle. turtle is an independent 
module which is built on top of Tkinter.

>>> Tkinter.turtle

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    Tkinter.turtle
AttributeError: 'module' object has no attribute 'turtle'

Yes, Tkinter could have had a ScrolledCanvas. It could have had lots of 
things, you have to draw the line somewhere otherwise you end up with 
one giant module that does *everything*:

>>> import UniversalModuleWithEverything  # takes a few hours to load
>>> UniversalModuleWithEverything. \
... Klingon_Wordprocessor_With_Graphics_Imbedded_Spreadsheet().run() 

*wink*

Tkinter doesn't do anything in turtle. turtle wants a ScrolledCanvas, 
and since Tkinter doesn't have one, it creates it. It uses Tkinter's 
Frame object as the base class (not a metaclass, metaclasses are an 
advanced technique which are very different). That way the 
ScrolledCanvas class inherits behaviour from Frame.



-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Sat Apr 24 10:48:20 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Apr 2010 09:48:20 +0100
Subject: [Tutor] Binary search question
References: <003301cae2ee$0cbb5d60$26321820$@rr.com><hqt7s0$a3b$1@dough.gmane.org>
	<hqtb76$jaj$1@dough.gmane.org>
	<201004241204.44005.steve@pearwood.info>
Message-ID: <hqub99$tjs$1@dough.gmane.org>


"Steven D'Aprano" <steve at pearwood.info> wrote

>> Interestingly on my PC with Python 3.1:
>> >>> data = list(range(10000000))
>> >>> 9999999 in data
>>
>> takes an apparently constant, sub second time.
>
> With respect Alan, timing operations by eye is pretty lame, what did you
> do, count your heartbeats? :)

Sure, but I was surprised at the previous post claiming 7 seconds.
I just wanted to show that 'in' should not be discarded too quickly,
its "good enough" for the vast majority of cases even with big data
sets.

> I would expect that the difference between searching for 9999999 and -5
> would be insignificant, because in both cases you have to walk the
> entire list. And sure enough, both take about half a second on my PC:

Yes, I did try other values too, but by the "heartbeat test" (you should patent 
it! :-)
they were all 'constant' time.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From alan.gauld at btinternet.com  Sat Apr 24 10:56:51 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Apr 2010 09:56:51 +0100
Subject: [Tutor] Class Inheritance, Beat it into the Ground
References: <g2n2d00d7fe1004232241xdbb35fe0q24ef460cf5179dd0@mail.gmail.com>
Message-ID: <hqubp8$us1$1@dough.gmane.org>

"David Hutto" <smokefloat at gmail.com> wrote

> In previous post I asked about  turtle module importing from tkinter.
> But what I don't understand is why does Tkinter default it's casnvas
> to ScrolledCanvas in turtle.py, 

Tkinter doesn't. The author of the turtle module - which is not part of 
Tkinter but simply uses it - chose to use a Scrolled Canvas. Presumably 
because he wanted a canvas that scrollled!

> and then as a 'metaclass' for ScrolledCanvas in turtle it calls TK.Frame, 

Its not a meta-class its a super class - the two concepts are completely 
different and you don't want to be thinking about meta classes for a 
long time yet!

> which could have been set as a default within Tkinter itself?

No it couldn't because turtle.py didn't exist when Tkinter was created.
And even if it did you couldn't guarantee that everyone would want it that 
way. Tkinter is a generic UI framework that can be used in many 
applications. It should not be defined to suit any single application.

You appear to be struggling with the concept of module use and 
dependencies. You should be trying to create a tree structure of 
dependencies with no circular loops. turtle depends on Tkinter but 
Tkinter does not depend on turtle. And your code can depend on 
Tkinter, turtle or both. But neither module should know anything 
about your code.

Inheritance is a mechanism for taking an existing class and 
specialising it for your specific application. So turtle specialised 
Frame to produce a ScrolledCanvas which it uses to display the 
turtle.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Sat Apr 24 11:00:05 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 24 Apr 2010 10:00:05 +0100
Subject: [Tutor] Class Inheritance, Beat it into the Ground
References: <g2n2d00d7fe1004232241xdbb35fe0q24ef460cf5179dd0@mail.gmail.com>
	<201004241618.56177.steve@pearwood.info>
Message-ID: <hqubva$vhm$1@dough.gmane.org>

"Steven D'Aprano" <steve at pearwood.info> wrote

> Yes, Tkinter could have had a ScrolledCanvas. It could have had lots of
> things, you have to draw the line somewhere otherwise you end up with
> one giant module that does *everything*:

And for completeness there are a number of add-on modules in the standard
library that provide many of these extra widgets. Tix and the turtle module are
two examples. The standard dialogs etc are also in separate modules.

And there are several other add-on moduiles not in the standard library that
you can download that extend Tkinter even further.

This is all designed so you only need to use the bits you actually need.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From davea at ieee.org  Sat Apr 24 11:44:35 2010
From: davea at ieee.org (Dave Angel)
Date: Sat, 24 Apr 2010 05:44:35 -0400
Subject: [Tutor] Hi everybody stuck on some error need help please thank
 you!!
In-Reply-To: <s2s4bdcec5e1004232033jd85cedcekd85a2add98f75514@mail.gmail.com>
References: <y2z4bdcec5e1004232007ncf5fe451ta6ab88aff4f53293@mail.gmail.com>	<201004241322.28917.steve@pearwood.info>
	<s2s4bdcec5e1004232033jd85cedcekd85a2add98f75514@mail.gmail.com>
Message-ID: <4BD2BD83.7030007@ieee.org>

(Don't top-post.  Either put your remarks immediately after the part 
they reference, or at the end of the message.  Otherwise, everything's 
thoroughly out of order.)

Marco Rompr? wrote:
> I tried to enter model = Modele (nom_fichier) but it still does not work.
>   
You didn't define the global nom_fichier till after that line.  In 
general, while you're learning, please avoid using the same names for 
global values, class attributes, instance attributes, function parameter 
names, and local variables.   The rules for what a name means changes 
depending on where the name is used.
> <snip>
> On Fri, Apr 23, 2010 at 11:22 PM, Steven D'Aprano <steve at pearwood.info>wrote:
>
>   
>> On Sat, 24 Apr 2010 01:07:11 pm Marco Rompr? wrote:
>>
>>     
>>> Here's my code:
>>>       
>> [...]
>>     
>>> class Modele:
>>>     """
>>>     La definition d'un modele avec les magasins.
>>>     """
>>>     def __init__(self, nom_fichier, magasins =[]):
>>>         self.nom_fichier = nom_fichier
>>>         self.magasins = magasins
>>>       
>> [...]
>>     
>>> if __name__ == '__main__':
>>>     modele = Modele()
>>>       
This is where you got the error, because there's a required argument, 
for parameter nom_fichier.  So you could use
        modele = Modele("thefile.txt")
>>>     nom_fichier = "magasinmodele.txt"
>>>       
I'd call this something else, like  g_nom_fichier.  While you're 
learning, you don't want to get confused between the multiple names that 
look the same.
>>>     modele.charger(nom_fichier)
>>>     if modele.vide():
>>>         modele.initialiser(nom_fichier)
>>>     modele.afficher()
>>>
>>> And here's my error :
>>>
>>> Traceback (most recent call last):
>>>   File "F:\School\University\Session 4\Programmation
>>> SIO\magasingolfmodele.py", line 187, in <module>
>>>     modele = Modele()
>>> TypeError: __init__() takes at least 2 arguments (1 given)
>>>       
>> You define Modele to require a nom_fichier argument, but then you try to
>> call it with no nom_fuchier.
>> <snip>
>>     


From bermanrl at cfl.rr.com  Sat Apr 24 15:39:33 2010
From: bermanrl at cfl.rr.com (Robert Berman)
Date: Sat, 24 Apr 2010 09:39:33 -0400
Subject: [Tutor] Binary search question
In-Reply-To: <hqtb76$jaj$1@dough.gmane.org>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>	<hqsebc$91i$1@dough.gmane.org><hqt30t$qhe$1@dough.gmane.org>	<hqt3mq$sub$1@dough.gmane.org><m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com>	<hqt7s0$a3b$1@dough.gmane.org>
	<hqtb76$jaj$1@dough.gmane.org>
Message-ID: <004b01cae3b3$92f0dbb0$b8d29310$@rr.com>

> -----Original Message-----
> From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor-
> bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Alan Gauld
> Sent: Friday, April 23, 2010 7:41 PM
> To: tutor at python.org
> Subject: Re: [Tutor] Binary search question
> 
> "Emile van Sebille" <emile at fenx.com> wrote
> 
> >    BIG SNIP
> 
> And even at 10000000 entries, the list creation slowed right
> down - about 10 seconds, but the searches even for "-5" were
> still around a second.
> 
> So 'in' looks pretty effective to me!
> 
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/


Now that is most impressive.


Robert Berman

What you don't see with your eyes, don't invent with your mouth.




From hugo.yoshi at gmail.com  Sat Apr 24 16:36:55 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sat, 24 Apr 2010 16:36:55 +0200
Subject: [Tutor] Binary search question
In-Reply-To: <hqub99$tjs$1@dough.gmane.org>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>
	<hqt7s0$a3b$1@dough.gmane.org> 
	<hqtb76$jaj$1@dough.gmane.org> <201004241204.44005.steve@pearwood.info>
	<hqub99$tjs$1@dough.gmane.org>
Message-ID: <h2n29179d161004240736y1f08e050wc52992181808482a@mail.gmail.com>

On Sat, Apr 24, 2010 at 10:48 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Steven D'Aprano" <steve at pearwood.info> wrote
>
>>> Interestingly on my PC with Python 3.1:
>>> >>> data = list(range(10000000))
>>> >>> 9999999 in data
>>>
>>> takes an apparently constant, sub second time.
>>
>> With respect Alan, timing operations by eye is pretty lame, what did you
>> do, count your heartbeats? :)
>
> Sure, but I was surprised at the previous post claiming 7 seconds.
> I just wanted to show that 'in' should not be discarded too quickly,
> its "good enough" for the vast majority of cases even with big data
> sets.
>

With regard to my previous post claiming a 7 second time, that was a
mistake on my part. I (conveniently ;-) forgot that the I ran a timing
of 10.000 lookups, not a single one. So yeah, my bad. 'in' actually
seems plenty fast for all but the most gargantuan data sets, and if
you're performing 10k lookups, building a set/frozenset is an
optimization that might be worth looking into (to phrase it
carefully).

So looking at my benchmarks again, it seems like the complexity bisect
adds is only very rarely worth the speedup (in fact, I start getting
memory errors before bisect makes enough of a difference to be worth
it).

Hugo

From lie.1296 at gmail.com  Sat Apr 24 18:21:15 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 25 Apr 2010 02:21:15 +1000
Subject: [Tutor] Binary search question
In-Reply-To: <004b01cae3b3$92f0dbb0$b8d29310$@rr.com>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>	<hqsebc$91i$1@dough.gmane.org><hqt30t$qhe$1@dough.gmane.org>	<hqt3mq$sub$1@dough.gmane.org><m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com>	<hqt7s0$a3b$1@dough.gmane.org>	<hqtb76$jaj$1@dough.gmane.org>
	<004b01cae3b3$92f0dbb0$b8d29310$@rr.com>
Message-ID: <hqv5sr$b6h$1@dough.gmane.org>

On 04/24/10 23:39, Robert Berman wrote:
>> -----Original Message-----
>> From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor-
>> bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Alan Gauld
>> Sent: Friday, April 23, 2010 7:41 PM
>> To: tutor at python.org
>> Subject: Re: [Tutor] Binary search question
>>
>> "Emile van Sebille" <emile at fenx.com> wrote
>>
>>>    BIG SNIP
>>
>> And even at 10000000 entries, the list creation slowed right
>> down - about 10 seconds, but the searches even for "-5" were
>> still around a second.
>>
>> So 'in' looks pretty effective to me!
> 
> Now that is most impressive.
> 

But that is with the assumption that comparison is very cheap. If you're
searching inside an object with more complex comparison, say, 0.01
second per comparison, then with a list of 10 000 000 items, with 'in'
you will need on *average* 5 000 000 comparisons which is 50 000 seconds
compared to *worst-case* 24 comparisons with bisect which is 0.24 seconds.

Now, I say that's 208333 times difference, most impressive indeed.


From kbailey at howlermonkey.net  Sun Apr 25 05:00:50 2010
From: kbailey at howlermonkey.net (Kirk Z Bailey)
Date: Sat, 24 Apr 2010 23:00:50 -0400
Subject: [Tutor] sqrt?
Message-ID: <4BD3B062.7010009@howlermonkey.net>

ok gang, My desktop runs 2.5, and for my college algebra I needed to do 
som quadratic equation work. This involves squareroots. So I fired uop 
the interactive idle and imported math. I then tried to play with sqrt.

Nothing.

Importing math does not import a sqrt function.

Now riddle me this: if string.foo makes it do a function FOO on a 
string, whyfore and howcome does math.sqrt not do square roots on a 
simple number like 4???

I am now officiciously pissed.

Help?

-- 
end

Very Truly yours,
                 - Kirk Bailey,
                   Largo Florida

                       kniht   
                      +-----+  
                      | BOX |  
                      +-----+  
                       think   


From walterwefft at googlemail.com  Sun Apr 25 06:09:42 2010
From: walterwefft at googlemail.com (Walter Wefft)
Date: Sun, 25 Apr 2010 05:09:42 +0100
Subject: [Tutor] sqrt?
In-Reply-To: <4BD3B062.7010009@howlermonkey.net>
References: <4BD3B062.7010009@howlermonkey.net>
Message-ID: <hr0fa7$s69$1@dough.gmane.org>

Kirk Z Bailey wrote:
> ok gang, My desktop runs 2.5, and for my college algebra I needed to do 
> som quadratic equation work. This involves squareroots. So I fired uop 
> the interactive idle and imported math. I then tried to play with sqrt.
> 
> Nothing.
> 
> Importing math does not import a sqrt function.
> 
> Now riddle me this: if string.foo makes it do a function FOO on a 
> string, whyfore and howcome does math.sqrt not do square roots on a 
> simple number like 4???
> 

Show us the code that you wrote.

> I am now officiciously pissed.
> 

?It?s not that I?m so smart,
it?s just that I stay with problems longer.?
Albert Einstein


From steve at pearwood.info  Sun Apr 25 06:00:16 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 25 Apr 2010 14:00:16 +1000
Subject: [Tutor] sqrt?
In-Reply-To: <4BD3B062.7010009@howlermonkey.net>
References: <4BD3B062.7010009@howlermonkey.net>
Message-ID: <201004251400.16684.steve@pearwood.info>

On Sun, 25 Apr 2010 01:00:50 pm Kirk Z Bailey wrote:
> ok gang, My desktop runs 2.5, and for my college algebra I needed to
> do som quadratic equation work. This involves squareroots. So I fired
> uop the interactive idle and imported math. I then tried to play with
> sqrt.
>
> Nothing.
>
> Importing math does not import a sqrt function.

It works for me.


[steve at sylar ~]$ python
Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.sqrt(4)
2.0
>>> math.sqrt(12.5)
3.5355339059327378



> Now riddle me this: if string.foo makes it do a function FOO on a
> string, whyfore and howcome does math.sqrt not do square roots on a
> simple number like 4???
>
> I am now officiciously pissed.

Perhaps you should drink less alcohol before posting then.

*wink*


(For those in the US, in British and Australian English, to be "pissed" 
is to be drunk. Being angry is "pissed off".)




-- 
Steven D'Aprano

From emile at fenx.com  Sun Apr 25 10:09:22 2010
From: emile at fenx.com (Emile van Sebille)
Date: Sun, 25 Apr 2010 01:09:22 -0700
Subject: [Tutor] sqrt?
In-Reply-To: <201004251400.16684.steve@pearwood.info>
References: <4BD3B062.7010009@howlermonkey.net>
	<201004251400.16684.steve@pearwood.info>
Message-ID: <hr0tef$sea$1@dough.gmane.org>

On 4/24/2010 9:00 PM Steven D'Aprano said...
> On Sun, 25 Apr 2010 01:00:50 pm Kirk Z Bailey wrote:
>> Importing math does not import a sqrt function.
>
Hmm... mine's there, but hey, it's easy to roll your own:

ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec  5 2008, 13:58:38) [MSC v.1500 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> def sqrt(x): return x**.5
...
 >>> sqrt(4)
2.0
 >>> sqrt(12)
3.4641016151377544


Emile



From alan.gauld at btinternet.com  Sun Apr 25 15:25:21 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 25 Apr 2010 14:25:21 +0100
Subject: [Tutor] sqrt?
References: <4BD3B062.7010009@howlermonkey.net>
Message-ID: <hr1fso$fli$1@dough.gmane.org>


"Kirk Z Bailey" <kbailey at howlermonkey.net> wrote 

> som quadratic equation work. This involves squareroots. So I fired uop 
> the interactive idle and imported math. I then tried to play with sqrt.
> 
> Nothing.
> 
> Importing math does not import a sqrt function.

So what error do you get? Please post it.

Did you try dir(math) to see the list of names? Does it include sqrt?
If the list is not as you expect have you perhaps inadvertantly created 
a file called math.py that it is importing instead?

> Now riddle me this: if string.foo makes it do a function FOO on a 
> string, whyfore and howcome does math.sqrt not do square roots on a 
> simple number like 4???

It does on my system.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From dillyg23 at gmail.com  Sun Apr 25 15:34:56 2010
From: dillyg23 at gmail.com (Sharon)
Date: Sun, 25 Apr 2010 14:34:56 +0100
Subject: [Tutor] Which Designer
Message-ID: <4BD44500.9060802@gmail.com>

Hi,
I am a newbie to python but would like to use a designer for 
simplicity.  Which would be the easiest to use:

WxGlade
Qt 4 Designer
Glade Interface Designer (Gtk)

At this point in time I would be looking at the simplest for a newbie 
until my programming skills in Python improve.  Appreciate a few 
opinions on this.

Regards

Sharon

From eire1130 at gmail.com  Sun Apr 25 16:29:19 2010
From: eire1130 at gmail.com (eire1130 at gmail.com)
Date: Sun, 25 Apr 2010 14:29:19 +0000
Subject: [Tutor] Which Designer
In-Reply-To: <4BD44500.9060802@gmail.com>
References: <4BD44500.9060802@gmail.com>
Message-ID: <882128129-1272205759-cardhu_decombobulator_blackberry.rim.net-1676725854-@bda2340.bisx.prod.on.blackberry>







Sent from my Verizon Wireless BlackBerry

-----Original Message-----
From: Sharon <dillyg23 at gmail.com>
Date: Sun, 25 Apr 2010 14:34:56 
To: Tutor Python<tutor at python.org>
Subject: [Tutor] Which Designer

Hi,
I am a newbie to python but would like to use a designer for 
simplicity.  Which would be the easiest to use:

WxGlade
Qt 4 Designer
Glade Interface Designer (Gtk)

At this point in time I would be looking at the simplest for a newbie 
until my programming skills in Python improve.  Appreciate a few 
opinions on this.

Regards

Sharon
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


From hugo.yoshi at gmail.com  Sun Apr 25 16:38:55 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sun, 25 Apr 2010 16:38:55 +0200
Subject: [Tutor] sqrt?
In-Reply-To: <4BD3B062.7010009@howlermonkey.net>
References: <4BD3B062.7010009@howlermonkey.net>
Message-ID: <s2i29179d161004250738od3e72375xa2cb32a9e304b398@mail.gmail.com>

On Sun, Apr 25, 2010 at 5:00 AM, Kirk Z Bailey <kbailey at howlermonkey.net> wrote:
> ok gang, My desktop runs 2.5, and for my college algebra I needed to do som
> quadratic equation work. This involves squareroots. So I fired uop the
> interactive idle and imported math. I then tried to play with sqrt.
>
> Nothing.
>
> Importing math does not import a sqrt function.
>

I know it seems like the members of this list work magic sometimes,
but contrary to popular belief we don't actually have the power to
remotely see what is happening on someone's computer. Furthermore, we
are all busy people and we don't have time to guess at what your
problem may be, so until we get some more information, most people
will just assume that you're doing it wrong.

> Now riddle me this: if string.foo makes it do a function FOO on a string,
> whyfore and howcome does math.sqrt not do square roots on a simple number
> like 4???

It does. How did you come to the conclusion that it doesn't? What did
you try? did you read help(math)? help(math.sqrt)? did you google
something like "python sqrt?" Is the math file you're importing the
one you think you're importing?

>
> I am now officiciously pissed.
>
> Help?

We can't properly help you with the information you are providing us.
Asking good questions is not hard, really, and the more you help us
the more likely we are to help you. I recommend everyone posting on
any mailing list to read Eric S. Raymond's guide to asking smart
questions: http://catb.org/~esr/faqs/smart-questions.html

Yours truly,
Hugo Arts

(please excuse the rant)

From hugo.yoshi at gmail.com  Sun Apr 25 17:33:43 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sun, 25 Apr 2010 17:33:43 +0200
Subject: [Tutor]  sqrt?
In-Reply-To: <4BD45554.5040003@howlermonkey.net>
References: <4BD3B062.7010009@howlermonkey.net>
	<s2i29179d161004250738od3e72375xa2cb32a9e304b398@mail.gmail.com>
	<4BD45554.5040003@howlermonkey.net>
Message-ID: <j2p29179d161004250833h5229b05dnba65faa5434f59a9@mail.gmail.com>

Forwarding for the benefit of the list. There I go again, ranting for
nothing ;-)

Hugo

---------- Forwarded message ----------
From: Kirk Z Bailey <kbailey at howlermonkey.net>
Date: Sun, Apr 25, 2010 at 4:44 PM
Subject: Re: [Tutor] sqrt?
To: Hugo Arts <hugo.yoshi at gmail.com>


I have solved the problem;? the . key has keybounce and needs
cleaning. Going back and deleting one solves it. Sorry to bother the
list

From lowelltackett at yahoo.com  Sun Apr 25 20:10:17 2010
From: lowelltackett at yahoo.com (Lowell Tackett)
Date: Sun, 25 Apr 2010 11:10:17 -0700 (PDT)
Subject: [Tutor] the binary math "wall"
In-Reply-To: <201004210939.31224.steve@pearwood.info>
Message-ID: <578160.86870.qm@web110104.mail.gq1.yahoo.com>


>From the virtual desk of Lowell Tackett  



--- On Tue, 4/20/10, Steven D'Aprano <steve at pearwood.info> wrote:

> From: Steven D'Aprano <steve at pearwood.info>
> Subject: Re: [Tutor] the binary math "wall"
> To: tutor at python.org
> Date: Tuesday, April 20, 2010, 7:39 PM
> On Wed, 21 Apr 2010 02:58:06 am
> Lowell Tackett wrote:
> > I'm running headlong into the dilemma of binary math
> representation, 
> with game-ending consequences, e.g.:
> > >>> 0.15

> But if you really need D.MMSS floats, then something like
> this should be 
> a good start.:
> 
> def dms2deg(f):
>     """Convert a floating point number formatted
> as D.MMSS 
>     into degrees.
>     """
>     mmss, d = math.modf(f)
>     assert d == int(f)
>     if mmss >= 0.60:
>         raise ValueError(
>         'bad fractional part, expected
> < .60 but got %f' % mmss)
>     mmss *= 100
>     m = round(mmss)
>     if m >= 60:
>         raise ValueError('bad minutes,
> expected < 60 but got %d' % m)
>     s = round((mmss - m)*100, 8)
>     if not 0 <= s < 60.0:
>         raise ValueError('bad seconds,
> expected < 60.0 but got %f' % s)
>     return d + m/60.0 + s/3600.0
> 
> 
> >>> dms2deg(18.15)
> 18.25
> >>> dms2deg(18.1515)
> 18.254166666666666
> 
> 

Haven't gone away...I'm having a blast dissecting (parsing[?]-is that the right word?) your script snippet!  Got a big pot of coffee fueling the effort.

> 
> Note though that this still fails with some valid input. I
> will leave 
> fixing it as an exercise (or I might work on it later, time
> 
> permitting).

Got the hint...I'm gonna pick up this challenge.  This effort is taking me in endless tangents (all productive)-I'll be back sometime [soon] with my efforts and results.  Thanks for your [own] time and effort.

> 
> 
> -- 
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 


      


From bgailer at gmail.com  Sun Apr 25 21:52:10 2010
From: bgailer at gmail.com (bob gailer)
Date: Sun, 25 Apr 2010 15:52:10 -0400
Subject: [Tutor] sqrt?
In-Reply-To: <4BD3B062.7010009@howlermonkey.net>
References: <4BD3B062.7010009@howlermonkey.net>
Message-ID: <4BD49D6A.1000406@gmail.com>

On 4/24/2010 11:00 PM, Kirk Z Bailey wrote:
> ok gang, My desktop runs 2.5, and for my college algebra I needed to 
> do som quadratic equation work. This involves squareroots. So I fired 
> uop the interactive idle and imported math. I then tried to play with 
> sqrt.
>
> Nothing.

As Hugo pointed out - asking good questions is important. That includes 
being really specific. "play" and "nothing" are not specific. We can 
guess - we might even be right - but that is costly for all of us in time.

Python rarely gives "nothing".

You usually get some result (perhaps you don't agree with it) or some 
error (traceback). Sometimes there is no visible result, as the case 
with import.

So if I were willing to spend some time guessing I'd guess that you did 
and got something like:

 >>> import math
 >>> sqrt
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined
 >>>

Please either confirm or alter the above. IOW show us what you entered 
and what you got.

Did you read the Python Manual's explanation of import?

>
> Importing math does not import a sqrt function.

Not under that name, as a global variable. It did create a global name 
math. Math has attributes, one of which is sqrt.

>
> Now riddle me this: if string.foo makes it do a function FOO on a string

Wow - so many assumptions, errors and generalities. Where would I even 
begin?

> , whyfore and howcome does math.sqrt not do square roots on a simple 
> number like 4???

O but it does, as others have pointed out
 >>> math.sqrt(4)
2.0

>
> I am now officiciously pissed.
>
> Help?
>


-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From sli1que at yahoo.com  Sun Apr 25 22:22:46 2010
From: sli1que at yahoo.com (Eric Walker)
Date: Sun, 25 Apr 2010 13:22:46 -0700 (PDT)
Subject: [Tutor] sqrt?
In-Reply-To: <4BD49D6A.1000406@gmail.com>
References: <4BD3B062.7010009@howlermonkey.net> <4BD49D6A.1000406@gmail.com>
Message-ID: <272541.71566.qm@web65402.mail.ac4.yahoo.com>




________________________________
From: bob gailer <bgailer at gmail.com>
To: tutor at python.org
Sent: Sun, April 25, 2010 12:52:10 PM
Subject: Re: [Tutor] sqrt?

On 4/24/2010 11:00 PM, Kirk Z Bailey wrote:
> ok gang, My desktop runs 2.5, and for my college algebra I needed to do som quadratic equation work. This involves squareroots. So I fired uop the interactive idle and imported math. I then tried to play with sqrt.
> 
> Nothing.

As Hugo pointed out - asking good questions is important. That includes being really specific. "play" and "nothing" are not specific. We can guess - we might even be right - but that is costly for all of us in time.

Python rarely gives "nothing".

You usually get some result (perhaps you don't agree with it) or some error (traceback). Sometimes there is no visible result, as the case with import.

So if I were willing to spend some time guessing I'd guess that you did and got something like:

>>> import math
>>> sqrt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined
>>>

Please either confirm or alter the above. IOW show us what you entered and what you got.

Did you read the Python Manual's explanation of import?

> 
> Importing math does not import a sqrt function.

Not under that name, as a global variable. It did create a global name math. Math has attributes, one of which is sqrt.

> 
> Now riddle me this: if string.foo makes it do a function FOO on a string

Wow - so many assumptions, errors and generalities. Where would I even begin?

> , whyfore and howcome does math.sqrt not do square roots on a simple number like 4???

O but it does, as others have pointed out
>>> math.sqrt(4)
2.0

> 
> I am now officiciously pissed.
> 
> Help?
> 

I am a newbie but after typing "import math"
you can do a dir(math) to get the available first level methods available to you.
>>> import math
>>> dir(math)
['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']


Eric

_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100425/b3adc7e5/attachment.html>

From davea at ieee.org  Sun Apr 25 23:10:02 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 25 Apr 2010 17:10:02 -0400
Subject: [Tutor] Binary search question
In-Reply-To: <hqv5sr$b6h$1@dough.gmane.org>
References: <003301cae2ee$0cbb5d60$26321820$@rr.com>	<hqsebc$91i$1@dough.gmane.org><hqt30t$qhe$1@dough.gmane.org>	<hqt3mq$sub$1@dough.gmane.org><m2m29179d161004231455xc2723763j5e6cd23c4033133d@mail.gmail.com>	<hqt7s0$a3b$1@dough.gmane.org>	<hqtb76$jaj$1@dough.gmane.org>	<004b01cae3b3$92f0dbb0$b8d29310$@rr.com>
	<hqv5sr$b6h$1@dough.gmane.org>
Message-ID: <4BD4AFAA.5020801@ieee.org>

Lie Ryan wrote:
> On 04/24/10 23:39, Robert Berman wrote:
>   
>>> -----Original Message-----
>>> From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor-
>>> bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Alan Gauld
>>> Sent: Friday, April 23, 2010 7:41 PM
>>> To: tutor at python.org
>>> Subject: Re: [Tutor] Binary search question
>>>
>>> "Emile van Sebille" <emile at fenx.com> wrote
>>>
>>>       
>>>>    BIG SNIP
>>>>         
>>> And even at 10000000 entries, the list creation slowed right
>>> down - about 10 seconds, but the searches even for "-5" were
>>> still around a second.
>>>
>>> So 'in' looks pretty effective to me!
>>>       
>> Now that is most impressive.
>>
>>     
>
> But that is with the assumption that comparison is very cheap. If you're
> searching inside an object with more complex comparison, say, 0.01
> second per comparison, then with a list of 10 000 000 items, with 'in'
> you will need on *average* 5 000 000 comparisons which is 50 000 seconds
> compared to *worst-case* 24 comparisons with bisect which is 0.24 seconds.
>
> Now, I say that's 208333 times difference, most impressive indeed.
>
>
>   

The ratio doesn't change with a slow comparison, only the magnitude.

And if you have ten million objects that are complex enough to take .01 
secs per comparison, chances are it took a day or two to load them up 
into your list.  Most likely you won't be using a list anyway, but a 
database, so you don't have to reload them each time you start the program.


It's easy to come up with situations in which each of these solutions is 
better than the other.

DaveA

From alan.gauld at btinternet.com  Mon Apr 26 01:38:15 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Apr 2010 00:38:15 +0100
Subject: [Tutor] Which Designer
References: <4BD44500.9060802@gmail.com>
Message-ID: <hr2jpv$300$1@dough.gmane.org>


"Sharon" <dillyg23 at gmail.com> wrote

> I am a newbie to python but would like to use a designer for 
> simplicity.  Which would be the easiest to use:
> 
> WxGlade
> Qt 4 Designer
> Glade Interface Designer (Gtk)


These are all GUI builders so I assume you want to write GUIs?
If so which GUI toolkit are you intending to use because the 
GUI builders all tend to be specific to one particular tookit, 
which limits your options. Choose your toolkit and the GUI 
builder is chosen for you...

> At this point in time I would be looking at the simplest for a newbie 
> until my programming skills in Python improve.  Appreciate a few 
> opinions on this.

The simplest toolkit or the simplest tool?
Picking the simplest tool may leave you writing code for a 
complex toolkit? OPne of the simplest GUI tookits is the 
standard Tkinter that comes with Python. But the tools for 
building GUIs for Tkinter are not great! But toolkits like 
Gtk and Qt have better tools but tend to be much more 
complex than Tkinter (more powerful too of course - it tends 
to be the case in programming that power and complexity 
are closely linked!)

Maybe you should stick to simple programming first 
and worry about the GUI stuff later? Or are you already 
comfortable with command line/console  programs and
its only the GUI stuff that is new?

To really help we need to know more.


HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From dillyg23 at gmail.com  Mon Apr 26 02:48:24 2010
From: dillyg23 at gmail.com (Sharon)
Date: Mon, 26 Apr 2010 01:48:24 +0100
Subject: [Tutor] Which Designer
In-Reply-To: <hr2jpv$300$1@dough.gmane.org>
References: <4BD44500.9060802@gmail.com> <hr2jpv$300$1@dough.gmane.org>
Message-ID: <4BD4E2D8.70802@gmail.com>

I think you are probably right. The only other sort of programming I did 
before I started on python was really 'VBA' and everything was done with 
GUI. I think that is what was in my mind. I have started using Tkinter 
and it isn't so bad. I just like the idea of having the visual side of 
actually seeing the buttons and whistles on the form ready. I have 
looked at QT, GTK and wxGlade but it is all more complicated than 
'visual basic' and not at all rad like. So, for now I'll stick with my 
book and use Tkinter to get to grips with binding the widgets to the 
event handlers.

Thank you for your advice,

Sharon

Alan Gauld wrote:
>
> "Sharon" <dillyg23 at gmail.com> wrote
>
>> I am a newbie to python but would like to use a designer for 
>> simplicity. Which would be the easiest to use:
>>
>> WxGlade
>> Qt 4 Designer
>> Glade Interface Designer (Gtk)
>
>
> These are all GUI builders so I assume you want to write GUIs?
> If so which GUI toolkit are you intending to use because the GUI 
> builders all tend to be specific to one particular tookit, which 
> limits your options. Choose your toolkit and the GUI builder is chosen 
> for you...
>
>> At this point in time I would be looking at the simplest for a newbie 
>> until my programming skills in Python improve. Appreciate a few 
>> opinions on this.
>
> The simplest toolkit or the simplest tool?
> Picking the simplest tool may leave you writing code for a complex 
> toolkit? OPne of the simplest GUI tookits is the standard Tkinter that 
> comes with Python. But the tools for building GUIs for Tkinter are not 
> great! But toolkits like Gtk and Qt have better tools but tend to be 
> much more complex than Tkinter (more powerful too of course - it tends 
> to be the case in programming that power and complexity are closely 
> linked!)
>
> Maybe you should stick to simple programming first and worry about the 
> GUI stuff later? Or are you already comfortable with command 
> line/console programs and
> its only the GUI stuff that is new?
>
> To really help we need to know more.
>
>
> HTH,
>


From steve at alchemy.com  Mon Apr 26 03:31:30 2010
From: steve at alchemy.com (Steve Willoughby)
Date: Sun, 25 Apr 2010 18:31:30 -0700
Subject: [Tutor] Which Designer
In-Reply-To: <4BD4E2D8.70802@gmail.com>
References: <4BD44500.9060802@gmail.com> <hr2jpv$300$1@dough.gmane.org>
	<4BD4E2D8.70802@gmail.com>
Message-ID: <20100426013130.GA80914@dragon.alchemy.com>

On Mon, Apr 26, 2010 at 01:48:24AM +0100, Sharon wrote:
> I think you are probably right. The only other sort of programming I did 
> before I started on python was really 'VBA' and everything was done with 
> GUI. I think that is what was in my mind. I have started using Tkinter 
> and it isn't so bad. I just like the idea of having the visual side of 

Tkinter is really not a bad way to quickly hack together a GUI application
which will run on pretty much anything.  In my experience, I started with
more primitive toolkits for X and they were a real pain until I discovered
Tcl/Tk, which was truly wonderful to move to.

However, there are some real disadvantages to Tk(inter) as well, chiefly
that it is a least-common denominator which does a passable job of running
GUIs but they don't look consistent with the native look of Windows or OS/X
or whatever.  And there is a lot of missing functionality.

I'm getting into wxPython at the moment, and I have to say it's at least
worth a look.  It's also available for every platform (but doesn't come
with Python), and is far more complete, and just about as easy to use
as Tk, but looks a lot more polished.

There are other toolkits with their advocates as well, of course, but if
someone were just starting out with Python GUI programming, I'd recommend
looking around at your options before starting with Tk.

-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.

From evosweet at hotmail.com  Mon Apr 26 03:56:06 2010
From: evosweet at hotmail.com (Rayon)
Date: Sun, 25 Apr 2010 21:56:06 -0400
Subject: [Tutor] module import problems
Message-ID: <SNT143-ds9ED73D595C50E7E05A470C3040@phx.gbl>

I have a module with the name _table 
in the same directory I have another by the name of _module

I would like to import _table into _module

can someone tall me how. 

from tables.report_db_engine import *











-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100425/54cf240a/attachment.html>

From bgailer at gmail.com  Mon Apr 26 04:25:53 2010
From: bgailer at gmail.com (bob gailer)
Date: Sun, 25 Apr 2010 22:25:53 -0400
Subject: [Tutor] module import problems
In-Reply-To: <SNT143-ds9ED73D595C50E7E05A470C3040@phx.gbl>
References: <SNT143-ds9ED73D595C50E7E05A470C3040@phx.gbl>
Message-ID: <4BD4F9B1.10600@gmail.com>

On 4/25/2010 9:56 PM, Rayon wrote:
> I have a module with the name _table
> in the same directory I have another by the name of _module
> I would like to import _table into _module

What exactly does that mean?

The import statement, when executed,  imports a module into the module 
containing the import statement.

And what is the purpose of the following line?
> from tables.report_db_engine import *
>

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100425/0a26534f/attachment.html>

From steve at pearwood.info  Mon Apr 26 05:09:51 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 26 Apr 2010 13:09:51 +1000
Subject: [Tutor] module import problems
In-Reply-To: <SNT143-ds9ED73D595C50E7E05A470C3040@phx.gbl>
References: <SNT143-ds9ED73D595C50E7E05A470C3040@phx.gbl>
Message-ID: <201004261309.52320.steve@pearwood.info>

On Mon, 26 Apr 2010 11:56:06 am Rayon wrote:
> I have a module with the name _table
> in the same directory I have another by the name of _module
>
> I would like to import _table into _module
>
> can someone tall me how.

At the beginning of the _module module (what a name! yuck! don't you 
have a more descriptive name you can use?), put this line:

import _table


Then whenever you need something from _table, you write something like 
this:

print _table.my_function("something")


> from tables.report_db_engine import *

Two comments:

What is "tables"? Is that the same as _table?

Generally you shouldn't use the "from module import *" form. You should 
consider it advanced usage, or at least discouraged.



-- 
Steven D'Aprano

From evosweet at hotmail.com  Mon Apr 26 09:47:44 2010
From: evosweet at hotmail.com (Rayon)
Date: Mon, 26 Apr 2010 03:47:44 -0400
Subject: [Tutor] module import problems
In-Reply-To: <4BD4F9B1.10600@gmail.com>
References: <SNT143-ds9ED73D595C50E7E05A470C3040@phx.gbl>
	<4BD4F9B1.10600@gmail.com>
Message-ID: <SNT143-ds49AFB5BFEA3515CCD26E4C3040@phx.gbl>

I have a project folder  report_db in that project folder I have to  packages 
_modules and _ tables

report_db   \
                    _tables 
                    _modules 
  I want to import some functions from _tables  to _modules so I can use them in  a function in _modules.

  


From: bob gailer 
Sent: Sunday, April 25, 2010 10:25 PM
To: tutor at python.org 
Subject: Re: [Tutor] module import problems


On 4/25/2010 9:56 PM, Rayon wrote: 
  I have a module with the name _table 
  in the same directory I have another by the name of _module

  I would like to import _table into _module

What exactly does that mean?

The import statement, when executed,  imports a module into the module containing the import statement.

And what is the purpose of the following line?


  from tables.report_db_engine import *




-- 
Bob Gailer
919-636-4239
Chapel Hill NC

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


_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100426/0f1aa8cf/attachment.html>

From alan.gauld at btinternet.com  Mon Apr 26 10:09:59 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Apr 2010 09:09:59 +0100
Subject: [Tutor] Which Designer
References: <4BD44500.9060802@gmail.com>
	<hr2jpv$300$1@dough.gmane.org><4BD4E2D8.70802@gmail.com>
	<20100426013130.GA80914@dragon.alchemy.com>
Message-ID: <hr3hpf$e5q$1@dough.gmane.org>


"Steve Willoughby" <steve at alchemy.com> wrote

> However, there are some real disadvantages to Tk(inter) as well, chiefly
> that it is a least-common denominator which does a passable job of running
> GUIs but they don't look consistent with the native look of Windows or OS/X

The new themed widgets in Tk have changed that, they are built on the
native widgets and look just like any other GUI. Available in Tkinter from
Python 2.7 and 3.1

> or whatever.  And there is a lot of missing functionality.

This is still true although Tix addresses the biggest gaps - but is
sadly lacking documentation - you have to use the Tcl/Tk docs :-(
(I keep intending to do a write up on Tix but other things get in the way!)

And there are other bolt-ons too such as PMW.

> I'm getting into wxPython at the moment, and I have to say it's at least
> worth a look.  It's also available for every platform (but doesn't come
> with Python), and is far more complete, and just about as easy to use
> as Tk, but looks a lot more polished.

wxPython is definielt more powerful and in particular has support
for things like printing and drag n drop which are missing fromTk.

> There are other toolkits with their advocates as well, of course, but if
> someone were just starting out with Python GUI programming, I'd recommend
> looking around at your options before starting with Tk.

I'd still advocate Tk because
a) It comes with Python so is standard
b) It is also the standard GUI in Ruby, Perl and Tcl so once learned is 
oportable
c) It is best documented with many books etc featuring it
d) It is easy to learn the basic GUI principles that are valid in any Framework
    (a bit like learning Python is good becauise it helps you learn other 
languages)

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From evosweet at hotmail.com  Mon Apr 26 11:48:14 2010
From: evosweet at hotmail.com (Rayon)
Date: Mon, 26 Apr 2010 05:48:14 -0400
Subject: [Tutor] module import problems
In-Reply-To: <SNT143-ds49AFB5BFEA3515CCD26E4C3040@phx.gbl>
References: <SNT143-ds9ED73D595C50E7E05A470C3040@phx.gbl><4BD4F9B1.10600@gmail.com>
	<SNT143-ds49AFB5BFEA3515CCD26E4C3040@phx.gbl>
Message-ID: <SNT143-ds7744A75B90F2C954D87CCC3040@phx.gbl>

my bad it was a simple error I was calling it form the wrong module thanks


From: Rayon 
Sent: Monday, April 26, 2010 3:47 AM
To: bob gailer ; tutor at python.org 
Subject: Re: [Tutor] module import problems


I have a project folder  report_db in that project folder I have to  packages 
_modules and _ tables

report_db   \
                    _tables 
                    _modules 
  I want to import some functions from _tables  to _modules so I can use them in  a function in _modules.

  


From: bob gailer 
Sent: Sunday, April 25, 2010 10:25 PM
To: tutor at python.org 
Subject: Re: [Tutor] module import problems


On 4/25/2010 9:56 PM, Rayon wrote: 
  I have a module with the name _table 
  in the same directory I have another by the name of _module

  I would like to import _table into _module

What exactly does that mean?

The import statement, when executed,  imports a module into the module containing the import statement.

And what is the purpose of the following line?


  from tables.report_db_engine import *




-- 
Bob Gailer
919-636-4239
Chapel Hill NC

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


_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



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


_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100426/e6368f9d/attachment-0001.html>

From humphreybutau at vodamail.co.za  Mon Apr 26 12:18:45 2010
From: humphreybutau at vodamail.co.za (Humphrey)
Date: Mon, 26 Apr 2010 12:18:45 +0200 (SAST)
Subject: [Tutor] Programming pic chips with python
Message-ID: <26697822.1272277126364.JavaMail.27716278846>

hi there

I am new to python and i want to ask if python can be used in electronics like for programming programmable chips like the PIC16F series. I want to used it specifically in power conversion systems like Sine wave inverters and uninterpretable power supply systems

kindest regards 

Humphrey Butau
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100426/99320fcb/attachment.html>

From steve at alchemy.com  Mon Apr 26 17:23:04 2010
From: steve at alchemy.com (Steve Willoughby)
Date: Mon, 26 Apr 2010 08:23:04 -0700
Subject: [Tutor] Programming pic chips with python
In-Reply-To: <26697822.1272277126364.JavaMail.27716278846>
References: <26697822.1272277126364.JavaMail.27716278846>
Message-ID: <20100426152304.GA22947@dragon.alchemy.com>

On Mon, Apr 26, 2010 at 12:18:45PM +0200, Humphrey wrote:
> I am new to python and i want to ask if python can be used in electronics like for programming programmable chips like the PIC16F series. I want to used it specifically in power conversion systems like Sine wave inverters and uninterpretable power supply systems

In theory, any language could be used for something like this, but
generally speaking embedded systems like PICs (and I'd say particularly
for the PIC16 series which have very tiny memory storage), it may be
too much to expect the chip to carry a Python runtime inside it.  It
is an interesting idea, though, to either think of some sort of
tiny interpreter or a native code compiler.  

For really time-critical or memory-restrained applications, though,
which is typically the arena in which PICs and similar microcontrollers
exist, people usually program "closer to the bare metal" in assembly
or C.

You may be interested in looking at xwisp, though, as a related topic.
That is a PIC programmer (i.e., software to manage the transfer of
programs into the chip itself) written in Python.


-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.

From mhw at doctors.org.uk  Mon Apr 26 15:00:24 2010
From: mhw at doctors.org.uk (Matthew Williams)
Date: Mon, 26 Apr 2010 14:00:24 +0100
Subject: [Tutor] Problem iterating over csv.DictReader
Message-ID: <web-24331172@be1.doctors.org.uk>

Dear All,

I have noticed this odd behaviour in the CSV DictReader 
Class, and at a loss to understand/ get around it.

The aim is to read in a CSV file, and then iterate over 
the lines. The problem (seems) to be that once you have 
iterated over it once, you can't do it again.

I don't know if this is me (and it may well be) but it 
seems to be a recurrent issue, and means that a 
csv.DictReader doesn't behave in the same way as a normal 
dict object.

Code to confirm/ replicate below.

What I'm looking for is a way to explicity reset the 
iterator, to tell it to go back to the beginning.

Any ideas (or pointing out I am a moron) very welcome.

Matt


Python 2.6.3 (r253:75183, Oct 11 2009, 18:26:07)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu4)] on linux2

import csv
fname = "insert your csv file here.csv"
inr = csv.DictReader(open(fname, 'r'), delimiter = ',', 
quotechar = '"')

for r in inr:
     print r

<Get your rows here>

for r in inr:
     print r


Nothing.....

If I reload the file, I can solve the issue



From alan.gauld at btinternet.com  Mon Apr 26 17:35:42 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Apr 2010 16:35:42 +0100
Subject: [Tutor] Programming pic chips with python
References: <31010.7519886971$1272277602@news.gmane.org>
Message-ID: <hr4bt6$ms7$1@dough.gmane.org>


"Humphrey" <humphreybutau at vodamail.co.za> wrote

> I am new to python and i want to ask if python can be used in electronics 
> like for programming programmable chips like the PIC16F series. 

It depends on your chip development environment.
If the programmer connects to a PC (via serial or USB for example) 
then usually there will be standard Windows libraries that expose 
an API onto the chip. In that case you can use the ctypes module 
in Python to communicate with the programmer.


If the programmer is standalone it will be much harder, 
maybe impossible. And if it is a bespoke platform using 
a standard OS(eg Linux) then its likely possible to get the 
Python source to build on the platform and use it, but how 
much use it would be will dpened on how the programmer 
makes itself available in an API.

It will take a fair bit of in depth research to find out exactly 
what will work in your case.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From zstumgoren at gmail.com  Mon Apr 26 17:57:09 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Mon, 26 Apr 2010 11:57:09 -0400
Subject: [Tutor] Problem iterating over csv.DictReader
In-Reply-To: <web-24331172@be1.doctors.org.uk>
References: <web-24331172@be1.doctors.org.uk>
Message-ID: <m2ucadf44511004260857u925b54dcpcc458d837867fcce@mail.gmail.com>

> I have noticed this odd behaviour in the CSV DictReader Class, and at a
> loss to understand/ get around it.
>
> The aim is to read in a CSV file, and then iterate over the lines. The
> problem (seems) to be that once you have iterated over it once, you can't do
> it again.
>
> This is expected behavior. See below from the Python docs:

http://docs.python.org/glossary.html#term-iterator
http://docs.python.org/library/stdtypes.html#typeiter

If you'd like to make multiple passes over the lines from your CSV, store
them in a variable when you first read them in and then loop over that
variable instead.

One approach (though it may not be the best if you're dealing with huge
quantities of data):

reader = csv.DictReader(open(fname, 'r'), delimiter = ',', quotechar = '"')
data = [row for row in reader]
# now you can make multiple passes over the dictionaries stored in "data"


> I don't know if this is me (and it may well be) but it seems to be a
> recurrent issue, and means that a csv.DictReader doesn't behave in the same
> way as a normal dict object.
>

Correct. It's not supposed to behave like a normal dict. It behaves like a
reader object. See the python docs:

"Create an object which operates like a regular reader but maps the
information read into a dict whose keys are given by the optional *
fieldnames* parameter."
http://docs.python.org/library/csv.html#reader-objects

HTH,
Serdar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100426/00875050/attachment.html>

From norman at khine.net  Mon Apr 26 18:45:09 2010
From: norman at khine.net (Norman Khine)
Date: Mon, 26 Apr 2010 18:45:09 +0200
Subject: [Tutor] what is wrong with this code?
Message-ID: <x2i9c2c8ffb1004260945jaa8ebd30z8691047d782c04b1@mail.gmail.com>

hello, i have a list of tables i want to drop:

user_tables = ['notification', 'userNotification', 'product_comments',
'product_donation_paypalTransaction', 'product_donation',
'productList_recommended', 'productList_user_assoc',
'profile_values']

drop_user_tables = """DROP TABLE IF EXISTS db2.%s"""

try:
    cursor.execute(drop_user_tables, (x for x in user_tables))


thanks

From zstumgoren at gmail.com  Mon Apr 26 19:18:54 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Mon, 26 Apr 2010 13:18:54 -0400
Subject: [Tutor] what is wrong with this code?
In-Reply-To: <x2i9c2c8ffb1004260945jaa8ebd30z8691047d782c04b1@mail.gmail.com>
References: <x2i9c2c8ffb1004260945jaa8ebd30z8691047d782c04b1@mail.gmail.com>
Message-ID: <n2icadf44511004261018nf5d304b9t67af926ff2e169fc@mail.gmail.com>

> user_tables = ['notification', 'userNotification', 'product_comments',
> 'product_donation_paypalTransaction', 'product_donation',
> 'productList_recommended', 'productList_user_assoc',
> 'profile_values']
>
> drop_user_tables = """DROP TABLE IF EXISTS db2.%s"""
>
> try:
>    cursor.execute(drop_user_tables, (x for x in user_tables))
>

Norman,
It looks like what you're after is the cursor's "executemany" method, which
is supported by many common database adapters that comply with DB-API2.0.

If you're using sqlite3, there are more details here:

    http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.executemany

In your code, you seem to be trying to loop over the values in the
user_tables list. I haven't tested this, but instead try simply passing the
list of user_tables to executemany:

    cursor.executemany(drop_user_tables, user_tables)

If the above doesn't work or is not available with your database adapter,
how about just using a simple loop?

for table in user_tables:
    cursor.execute(drop_user_tables, (table,))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100426/e5f08bdf/attachment-0001.html>

From norman at khine.net  Mon Apr 26 19:45:13 2010
From: norman at khine.net (Norman Khine)
Date: Mon, 26 Apr 2010 19:45:13 +0200
Subject: [Tutor] what is wrong with this code?
In-Reply-To: <n2icadf44511004261018nf5d304b9t67af926ff2e169fc@mail.gmail.com>
References: <x2i9c2c8ffb1004260945jaa8ebd30z8691047d782c04b1@mail.gmail.com>
	<n2icadf44511004261018nf5d304b9t67af926ff2e169fc@mail.gmail.com>
Message-ID: <o2g9c2c8ffb1004261045mf4d58e3nae2caad7ab088720@mail.gmail.com>

thanks for the reply.

On Mon, Apr 26, 2010 at 7:18 PM, Serdar Tumgoren <zstumgoren at gmail.com> wrote:
>
>> user_tables = ['notification', 'userNotification', 'product_comments',
>> 'product_donation_paypalTransaction', 'product_donation',
>> 'productList_recommended', 'productList_user_assoc',
>> 'profile_values']
>>
>> drop_user_tables = """DROP TABLE IF EXISTS db2.%s"""
>>
>> try:
>> ? ?cursor.execute(drop_user_tables, (x for x in user_tables))
>
> Norman,
> It looks like what you're after is the cursor's "executemany" method, which
> is supported by many common database adapters that comply with DB-API2.0.
>
> If you're using sqlite3, there are more details here:
>
> ? ? http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.executemany
>
> In your code, you seem to be trying to loop over the values in the
> user_tables list. I haven't tested this, but instead try simply passing the
> list of user_tables to executemany:
>
> ? ? cursor.executemany(drop_user_tables, user_tables)

i am using MySQLdb, to make changes to a database.
>
> If the above doesn't work or is not available with your database adapter,
> how about just using a simple loop?
>
> for table in user_tables:
> ? ? cursor.execute(drop_user_tables, (table,))

both ways, i got this error:

$ py upgrade.py
Error (1064, "You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near ''notification'' at line 1")
aqoon:ookoodoo khinester$ py upgrade.py
Error (1064, "You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near ''notification'' at line 1")

but my query, is fine:

drop_user_tables = """DROP TABLE IF EXISTS db2.%s"""


>
>
>

From norman at khine.net  Mon Apr 26 19:53:17 2010
From: norman at khine.net (Norman Khine)
Date: Mon, 26 Apr 2010 19:53:17 +0200
Subject: [Tutor] what is wrong with this code?
In-Reply-To: <o2g9c2c8ffb1004261045mf4d58e3nae2caad7ab088720@mail.gmail.com>
References: <x2i9c2c8ffb1004260945jaa8ebd30z8691047d782c04b1@mail.gmail.com>
	<n2icadf44511004261018nf5d304b9t67af926ff2e169fc@mail.gmail.com>
	<o2g9c2c8ffb1004261045mf4d58e3nae2caad7ab088720@mail.gmail.com>
Message-ID: <l2y9c2c8ffb1004261053nd110e0b7xb7dd634dbd58c181@mail.gmail.com>

On Mon, Apr 26, 2010 at 7:45 PM, Norman Khine <norman at khine.net> wrote:
> thanks for the reply.
>
> On Mon, Apr 26, 2010 at 7:18 PM, Serdar Tumgoren <zstumgoren at gmail.com> wrote:
>>
>>> user_tables = ['notification', 'userNotification', 'product_comments',
>>> 'product_donation_paypalTransaction', 'product_donation',
>>> 'productList_recommended', 'productList_user_assoc',
>>> 'profile_values']
>>>
>>> drop_user_tables = """DROP TABLE IF EXISTS db2.%s"""
>>>
>>> try:
>>> ? ?cursor.execute(drop_user_tables, (x for x in user_tables))
>>
>> Norman,
>> It looks like what you're after is the cursor's "executemany" method, which
>> is supported by many common database adapters that comply with DB-API2.0.
>>
>> If you're using sqlite3, there are more details here:
>>
>> ? ? http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.executemany
>>
>> In your code, you seem to be trying to loop over the values in the
>> user_tables list. I haven't tested this, but instead try simply passing the
>> list of user_tables to executemany:
>>
>> ? ? cursor.executemany(drop_user_tables, user_tables)
>
> i am using MySQLdb, to make changes to a database.
>>
>> If the above doesn't work or is not available with your database adapter,
>> how about just using a simple loop?
>>
>> for table in user_tables:
>> ? ? cursor.execute(drop_user_tables, (table,))
>
> both ways, i got this error:
>
> $ py upgrade.py
> Error (1064, "You have an error in your SQL syntax; check the manual
> that corresponds to your MySQL server version for the right syntax to
> use near ''notification'' at line 1")
> aqoon:ookoodoo khinester$ py upgrade.py
> Error (1064, "You have an error in your SQL syntax; check the manual
> that corresponds to your MySQL server version for the right syntax to
> use near ''notification'' at line 1")
>
> but my query, is fine:
>
> drop_user_tables = """DROP TABLE IF EXISTS db2.%s"""

ok this worked,

cursor.execute(drop_user_tables % ",".join(user_tables))

it seems that DROP TABLE (and other DDL statements) don't technically
take SQL parameters.

>
>
>>
>>
>>
>

From sander.sweers at gmail.com  Mon Apr 26 19:59:00 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 26 Apr 2010 19:59:00 +0200
Subject: [Tutor] Problem iterating over csv.DictReader
In-Reply-To: <web-24331172@be1.doctors.org.uk>
References: <web-24331172@be1.doctors.org.uk>
Message-ID: <t2hb65fbb131004261059w31ca30cfk4ea10b8f46dcf5e1@mail.gmail.com>

On 26 April 2010 15:00, Matthew Williams <mhw at doctors.org.uk> wrote:
> What I'm looking for is a way to explicity reset the iterator, to tell it to
> go back to the beginning.

You will need to use the seek method on the fileobject.

f = open('insert your csv file here.csv', 'rb') #Note the b in 'rb'

#Do your processing

f.seek(0)

#Do some more

Greets
Sander

From steve at alchemy.com  Mon Apr 26 19:58:35 2010
From: steve at alchemy.com (Steve Willoughby)
Date: Mon, 26 Apr 2010 10:58:35 -0700
Subject: [Tutor] what is wrong with this code?
In-Reply-To: <l2y9c2c8ffb1004261053nd110e0b7xb7dd634dbd58c181@mail.gmail.com>
References: <x2i9c2c8ffb1004260945jaa8ebd30z8691047d782c04b1@mail.gmail.com>
	<n2icadf44511004261018nf5d304b9t67af926ff2e169fc@mail.gmail.com>
	<o2g9c2c8ffb1004261045mf4d58e3nae2caad7ab088720@mail.gmail.com>
	<l2y9c2c8ffb1004261053nd110e0b7xb7dd634dbd58c181@mail.gmail.com>
Message-ID: <20100426175835.GB31272@dragon.alchemy.com>

On Mon, Apr 26, 2010 at 07:53:17PM +0200, Norman Khine wrote:
> ok this worked,
> 
> cursor.execute(drop_user_tables % ",".join(user_tables))
> 
> it seems that DROP TABLE (and other DDL statements) don't technically
> take SQL parameters.


That's correct.  The point of using %s as a placeholder for an SQL
value (not to be confused with %s in string formatting with the % operator
in Python), is to prevent them from being confused with SQL *statement*
code but made into proper values (strings, integers, and so forth).

But the names of tables, fields, etc., are NOT values, they are part
of the SQL syntax and you have to build them as part of the string
itself.
-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.

From cmcaine at googlemail.com  Mon Apr 26 21:38:17 2010
From: cmcaine at googlemail.com (C M Caine)
Date: Mon, 26 Apr 2010 20:38:17 +0100
Subject: [Tutor] For loop breaking string methods
Message-ID: <p2ib98d9b671004261238hf96a7342kfe3e316746da4ea5@mail.gmail.com>

Why does this not work:
>>> L = [' foo ','bar ']
>>> for i in L:
    i = i.strip()


>>> L
[' foo ', 'bar ']
>>> # note the leading whitespace that has not been removed.

But this does:
>>> L = [i.strip() for i in L]
>>> L
['foo', 'bar']

What other strange behaviour should I expect from for loops?

Thanks,
Colin Caine
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100426/1d8fd1e5/attachment.html>

From bgailer at gmail.com  Mon Apr 26 22:06:32 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 26 Apr 2010 16:06:32 -0400
Subject: [Tutor] For loop breaking string methods
In-Reply-To: <p2ib98d9b671004261238hf96a7342kfe3e316746da4ea5@mail.gmail.com>
References: <p2ib98d9b671004261238hf96a7342kfe3e316746da4ea5@mail.gmail.com>
Message-ID: <4BD5F248.30709@gmail.com>

On 4/26/2010 3:38 PM, C M Caine wrote:
> Why does this not work:

By "work" you mean "do what I want it to do".

> >>> L = [' foo ','bar ']
> >>> for i in L:
>     i = i.strip()

This creates a new local variable named i. It does not affect L. This 
has nothing to do with loops nor is it strange behavior - it is expected 
behavior.

Consider the loopless equivalent:

 >>> i = L[0]
 >>> i = i.strip()
 >>> L
[' foo ', 'bar ']

>
>
> >>> L
> [' foo ', 'bar ']
> >>> # note the leading whitespace that has not been removed.
>
> But this does:
> >>> L = [i.strip() for i in L]
> >>> L
> ['foo', 'bar']
>
> What other strange behaviour should I expect from for loops?
>

None - loops do not have "strange" behaviors.
Perhaps "unexpected" but that is a result of not understanding an aspect 
of the language.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From cmcaine at googlemail.com  Mon Apr 26 22:58:15 2010
From: cmcaine at googlemail.com (C M Caine)
Date: Mon, 26 Apr 2010 21:58:15 +0100
Subject: [Tutor] For loop breaking string methods
In-Reply-To: <4BD5F248.30709@gmail.com>
References: <p2ib98d9b671004261238hf96a7342kfe3e316746da4ea5@mail.gmail.com> 
	<4BD5F248.30709@gmail.com>
Message-ID: <h2wb98d9b671004261358g3b12dc55q3a1366f59f143176@mail.gmail.com>

Thank you for the clarification, bob.

For any future readers of this thread I include this link[1] to effbot's
guide on lists, which I probably should have already read.

My intention now is to modify list contents in the following fashion:

for index, value in enumerate(L):
    L[0] = some_func(value)

Is this the standard method?

[1]: http://effbot.org/zone/python-list.htm

Colin Caine
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100426/64ca8ffa/attachment-0001.html>

From sander.sweers at gmail.com  Mon Apr 26 22:59:15 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 26 Apr 2010 22:59:15 +0200
Subject: [Tutor] For loop breaking string methods
In-Reply-To: <p2ib98d9b671004261238hf96a7342kfe3e316746da4ea5@mail.gmail.com>
References: <p2ib98d9b671004261238hf96a7342kfe3e316746da4ea5@mail.gmail.com>
Message-ID: <r2ob65fbb131004261359m41f6aa88za5eb5b2cc00e6b23@mail.gmail.com>

On 26 April 2010 21:38, C M Caine <cmcaine at googlemail.com> wrote:
> Why does this not work:
>>>> L = [' foo ','bar ']
>>>> for i in L:
> ??? i = i.strip()

str.strip() _returns_ a *new* string and leaves the original string
alone. The reason being that string are immutable so can not be
changed.

>>> s1 = ' foo '
>>> s1[1]
'f'
>>> s1[1] = 'g'

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    s1[1] = 'g'
TypeError: 'str' object does not support item assignment

However lists are mutable and can be changed in place.

>>> l = [' foo ','bar ']
>>> l[0] = ' boo '
>>> l
[' boo ', 'bar ']
>>> l[1] = 'far '
>>> l
[' boo ', 'far ']


> But this does:
>>>> L = [i.strip() for i in L]
>>>> L
> ['foo', 'bar']

What you do here is create a *new* list object and assign it to
variable L. The new list is created with *new* string objects returned
by str.strip().

Putting the 2 together you could do something like below but I would
use a list comprehension like you did above:

>>> l = [' foo ','bar ']
>>> for x in range(len(l)):
	l[x] = l[x].strip()
	
>>> l
['foo', 'bar']
>>>

> What other strange behaviour should I expect from for loops?

You should read up on immutable data types like strings and tuples.
Start with [1].

Greets
Sander

[1] http://docs.python.org/reference/datamodel.html

From alan.gauld at btinternet.com  Tue Apr 27 00:45:58 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 26 Apr 2010 23:45:58 +0100
Subject: [Tutor] For loop breaking string methods
References: <p2ib98d9b671004261238hf96a7342kfe3e316746da4ea5@mail.gmail.com>
	<4BD5F248.30709@gmail.com>
	<h2wb98d9b671004261358g3b12dc55q3a1366f59f143176@mail.gmail.com>
Message-ID: <hr553u$qq2$1@dough.gmane.org>


"C M Caine" <cmcaine at googlemail.com> wrote 

> My intention now is to modify list contents in the following fashion:
> 
> for index, value in enumerate(L):
>    L[0] = some_func(value)

I think you mean:
      L[index] = some_func(value)

> Is this the standard method?

Or use a List copmprehension.

L = [some_func(value) for value in L]

I'd say nowadays that the comprehension was most common.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From cmcaine at googlemail.com  Tue Apr 27 01:39:13 2010
From: cmcaine at googlemail.com (C M Caine)
Date: Tue, 27 Apr 2010 00:39:13 +0100
Subject: [Tutor] For loop breaking string methods
In-Reply-To: <r2ob65fbb131004261359m41f6aa88za5eb5b2cc00e6b23@mail.gmail.com>
References: <p2ib98d9b671004261238hf96a7342kfe3e316746da4ea5@mail.gmail.com> 
	<r2ob65fbb131004261359m41f6aa88za5eb5b2cc00e6b23@mail.gmail.com>
Message-ID: <m2lb98d9b671004261639lcc1c10bfnfddea06dcd383434@mail.gmail.com>

>> What other strange behaviour should I expect from for loops?
>
> You should read up on immutable data types like strings and tuples.
> Start with [1].
>
> Greets
> Sander
>
> [1] http://docs.python.org/reference/datamodel.html
>

Thank you kindly for your reply, I'll be sure to read up on it.

Colin

From cmcaine at googlemail.com  Tue Apr 27 01:40:40 2010
From: cmcaine at googlemail.com (C M Caine)
Date: Tue, 27 Apr 2010 00:40:40 +0100
Subject: [Tutor] For loop breaking string methods
In-Reply-To: <hr553u$qq2$1@dough.gmane.org>
References: <p2ib98d9b671004261238hf96a7342kfe3e316746da4ea5@mail.gmail.com> 
	<4BD5F248.30709@gmail.com>
	<h2wb98d9b671004261358g3b12dc55q3a1366f59f143176@mail.gmail.com>
	<hr553u$qq2$1@dough.gmane.org>
Message-ID: <l2nb98d9b671004261640q838cdfdewf43b3876041cabed@mail.gmail.com>

On 26 April 2010 23:45, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "C M Caine" <cmcaine at googlemail.com> wrote
>>
>> My intention now is to modify list contents in the following fashion:
>>
>> for index, value in enumerate(L):
>> ? L[0] = some_func(value)
>
> I think you mean:
> ? ? L[index] = some_func(value)

Yes, I do

>> Is this the standard method?
>
> Or use a List copmprehension.
>
> L = [some_func(value) for value in L]
>
> I'd say nowadays that the comprehension was most common.
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/

Thanks, I can see why the comprehensions are more popular.

Colin

From davea at ieee.org  Tue Apr 27 04:19:48 2010
From: davea at ieee.org (Dave Angel)
Date: Mon, 26 Apr 2010 22:19:48 -0400
Subject: [Tutor] For loop breaking string methods
In-Reply-To: <h2wb98d9b671004261358g3b12dc55q3a1366f59f143176@mail.gmail.com>
References: <p2ib98d9b671004261238hf96a7342kfe3e316746da4ea5@mail.gmail.com>
	<4BD5F248.30709@gmail.com>
	<h2wb98d9b671004261358g3b12dc55q3a1366f59f143176@mail.gmail.com>
Message-ID: <4BD649C4.5040301@ieee.org>

C M Caine wrote:
> Thank you for the clarification, bob.
>
> For any future readers of this thread I include this link[1] to effbot's
> guide on lists, which I probably should have already read.
>
> My intention now is to modify list contents in the following fashion:
>
> for index, value in enumerate(L):
>     L[0] = some_func(value)
>
> Is this the standard method?
>
> [1]: http://effbot.org/zone/python-list.htm
>
> Colin Caine
>
>   
Almost.   You should have said

    L[index] = some_func(value)

The way you had it, it would only replace the zeroth item of the list.

Note also that if you insert or delete from the list while you're 
looping, you can get undefined results.  That's one reason it's common 
to build a new loop, and just assign it back when done.  Example would 
be the list comprehension you showed earlier.

DaveA


From mhw at doctors.net.uk  Tue Apr 27 10:42:43 2010
From: mhw at doctors.net.uk (mhw at doctors.net.uk)
Date: Tue, 27 Apr 2010 08:42:43 +0000
Subject: [Tutor] Multipane windows using curses
Message-ID: <1045253198-1272357796-cardhu_decombobulator_blackberry.rim.net-467439581-@bda188.bisx.produk.on.blackberry>

Dear All,

I am looking for some advice about a design decision. I want to write a curses-based editor (for OWL ontologies). This should then be usable via ssh, etc. Ontology files may be large, and quite complex. Current editors (e.g. Protege) have multiple tabs to cope with this.

The simplest option would seem to be to have a single appliction, running through a single terminal. However, the data is often complex, and so it would be nice to have multiple terminals showing different bits of the ontologies at the same time. However, doing this with multiple instances of the app would be difficult, as each window would have to load the whole ontolog, etc.

My next thought was then to run a simple server that loads the data file and returns bits of it. Then one could open multiple ssh terminals, and each could run a client to allow one to view the data. However, this is obviously more complex.

Am I missing something simpler?

Thanks,

Matt
Sent from my BlackBerry? wireless device

From lie.1296 at gmail.com  Tue Apr 27 11:15:02 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Tue, 27 Apr 2010 19:15:02 +1000
Subject: [Tutor] For loop breaking string methods
In-Reply-To: <4BD649C4.5040301@ieee.org>
References: <p2ib98d9b671004261238hf96a7342kfe3e316746da4ea5@mail.gmail.com>	<4BD5F248.30709@gmail.com>	<h2wb98d9b671004261358g3b12dc55q3a1366f59f143176@mail.gmail.com>
	<4BD649C4.5040301@ieee.org>
Message-ID: <hr6a1m$16m$1@dough.gmane.org>

On 04/27/10 12:19, Dave Angel wrote:
> Note also that if you insert or delete from the list while you're
> looping, you can get undefined results.  That's one reason it's common
> to build a new loop, and just assign it back when done.  Example would
> be the list comprehension you showed earlier.


I have to add to Dave's statement, if you "modify the list's content"
while looping there is no undefined behavior; you get undefined behavior
if you "modify the list's structure".

Operations that modify a list's structure includes insertion, delete,
append, etc; those operations which can modify the len() of list.

Modifying the content, however, is perfectly safe.

However, even when just modifying list's content, I personally still
prefer list/generator comprehension. They're fast and simple.


From bgailer at gmail.com  Tue Apr 27 16:10:27 2010
From: bgailer at gmail.com (bob gailer)
Date: Tue, 27 Apr 2010 10:10:27 -0400
Subject: [Tutor] For loop breaking string methods
In-Reply-To: <4BD649C4.5040301@ieee.org>
References: <p2ib98d9b671004261238hf96a7342kfe3e316746da4ea5@mail.gmail.com>
	<4BD5F248.30709@gmail.com>
	<h2wb98d9b671004261358g3b12dc55q3a1366f59f143176@mail.gmail.com>
	<4BD649C4.5040301@ieee.org>
Message-ID: <4BD6F053.3080100@gmail.com>

On 4/26/2010 10:19 PM, Dave Angel wrote:
>
> Note also that if you insert or delete from the list while you're 
> looping, you can get undefined results.
>

The results are not undefined. They m,ight be unexpected, but that is 
due to an invalid assumption.

The behavior is explained in section 7.3 of The Python Language 
Reference. Note especially:

"""

There is a subtlety when the sequence is being modified by the loop 
(this can only occur for mutable sequences, i.e. lists). An internal 
counter is used to keep track of which item is used next, and this is 
incremented on each iteration. When this counter has reached the length 
of the sequence the loop terminates. This means that if the suite 
deletes the current (or a previous) item from the sequence, the next 
item will be skipped (since it gets the index of the current item which 
has already been treated). Likewise, if the suite inserts an item in the 
sequence before the current item, the current item will be treated again 
the next time through the loop. This can lead to nasty bugs that can be 
avoided by making a temporary copy using a slice of the whole sequence, 
e.g.,

for  x  in  a[:]:
     if  x  <  0:  a.remove(x)
"""


-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From cmcaine at googlemail.com  Tue Apr 27 23:24:48 2010
From: cmcaine at googlemail.com (C M Caine)
Date: Tue, 27 Apr 2010 22:24:48 +0100
Subject: [Tutor] Modify inherited methods
Message-ID: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>

I'm writing a class that inherits the inbuilt dict class and want some
of my own code to run at initialisation, on the other hand, I still
want the original dict.__init__ function to run. Can I ask the class
to run the original __init__ and then my own function at
initialisation automatically? If so, how?

Regards,
Colin Caine

From steve at pearwood.info  Wed Apr 28 00:08:12 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 28 Apr 2010 08:08:12 +1000
Subject: [Tutor] Modify inherited methods
In-Reply-To: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>
Message-ID: <201004280808.14083.steve@pearwood.info>

On Wed, 28 Apr 2010 07:24:48 am C M Caine wrote:
> I'm writing a class that inherits the inbuilt dict class and want
> some of my own code to run at initialisation, on the other hand, I
> still want the original dict.__init__ function to run. Can I ask the
> class to run the original __init__ and then my own function at
> initialisation automatically? If so, how?

This is the general technique for calling the superclass' method:

class MyDict(dict):
    def __init__(self, *args, **kwargs):
        # Call the superclass method.
        dict.__init__(self, *args, **kwargs)
        # Perform my own initialisation code.
        print "Calling my init code..."


For advanced usage, replace the call to dict.__init__ with a call to 
super:

        super(MyDict, self).__init__(*args, **kwargs)

And for guru-level mastery, replace to call to dict.__init__ with ... 
nothing at all, because dict.__init__ doesn't do anything.

Some people argue that you must call dict.__init__ even though it 
doesn't do anything. Their reasoning is, some day its behaviour might 
change, and if you don't call it in your subclass, then your class may 
break. This is true, as far as it goes, but what they say is that if 
the behaviour of dict.__init__ changes, and you *do* call it, your 
class may still break. (This is why dict is unlikely to change any time 
soon.)




-- 
Steven D'Aprano

From steve at pearwood.info  Wed Apr 28 02:09:31 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 28 Apr 2010 10:09:31 +1000
Subject: [Tutor] Modify inherited methods
In-Reply-To: <201004280808.14083.steve@pearwood.info>
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>
	<201004280808.14083.steve@pearwood.info>
Message-ID: <201004281009.31934.steve@pearwood.info>

On Wed, 28 Apr 2010 08:08:12 am Steven D'Aprano wrote:

> Some people argue that you must call dict.__init__ even though it
> doesn't do anything. Their reasoning is, some day its behaviour might
> change, and if you don't call it in your subclass, then your class
> may break. This is true, as far as it goes, but what they say is that
> if the behaviour of dict.__init__ changes, and you *do* call it, your
> class may still break. (This is why dict is unlikely to change any
> time soon.)

Oops, left out a word. I meant to say "what they *don't* say is...".



-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Wed Apr 28 02:32:16 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 28 Apr 2010 01:32:16 +0100
Subject: [Tutor] Modify inherited methods
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>
	<201004280808.14083.steve@pearwood.info>
Message-ID: <hr7vmh$fku$1@dough.gmane.org>


"Steven D'Aprano" <steve at pearwood.info> wrote
> On Wed, 28 Apr 2010 07:24:48 am C M Caine wrote:
>> I'm writing a class that inherits the inbuilt dict class and want
>> some of my own code to run at initialisation, on the other hand, I
>> still want the original dict.__init__ function to run. ...

> This is the general technique for calling the superclass' method:
> 
> class MyDict(dict):
>    def __init__(self, *args, **kwargs):
>        # Call the superclass method.
>        dict.__init__(self, *args, **kwargs)
>        # Perform my own initialisation code.
>        print "Calling my init code..."

And just to be clear that applies to any method not just __init__
Also you can do your intialisation before or after or both.
eg.

def __init__(....)
     # do local pre processing(optional)
     super(....).__init__(...)
     #  do local post processing(optional)

> Some people argue that you must call dict.__init__ even though it 
> doesn't do anything. Their reasoning is, some day its behaviour might 
> change, and if you don't call it in your subclass, then your class may 
> break. 

I tend to argue for calling even if its a null call. Mainly because you 
sometimes don't know what the superclass does or doesn't do 
(eg you might not have access to the source) so its safer to call 
it...

> the behaviour of dict.__init__ changes, and you *do* call it, your 
> class may still break. 

... and if it breaks you at least have access to your own code to fix it...

But if you do have access to the superclass source then you can 
make an informed decision. In general I'm too lazy to go looking 
for it and just put the super call in :-)

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From marcodrompre at gmail.com  Wed Apr 28 04:35:14 2010
From: marcodrompre at gmail.com (=?ISO-8859-1?Q?Marco_Rompr=E9?=)
Date: Tue, 27 Apr 2010 22:35:14 -0400
Subject: [Tutor] How can I display my float as a string???
Message-ID: <s2r4bdcec5e1004271935q8b99e5bdkacffe3706270baca@mail.gmail.com>

Here is my code, I need to display my float value as a string.

item.set_prix str(float(prix))

Thank You
-- 
Marc-O. Rompr?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100427/32975ad0/attachment.html>

From marcodrompre at gmail.com  Wed Apr 28 05:12:17 2010
From: marcodrompre at gmail.com (=?ISO-8859-1?Q?Marco_Rompr=E9?=)
Date: Tue, 27 Apr 2010 23:12:17 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <p2i4bdcec5e1004272004ya53a0157s7970fe45e88281c0@mail.gmail.com>
References: <p2i4bdcec5e1004272004ya53a0157s7970fe45e88281c0@mail.gmail.com>
Message-ID: <q2l4bdcec5e1004272012tb1d9c2ebl6b41a6572597a711@mail.gmail.com>

Oups my posting was too big!!!

On Tue, Apr 27, 2010 at 11:04 PM, Marco Rompr? <marcodrompre at gmail.com>wrote:

> Why is none of my items button works???? In this, I have two files and in
> my second file I imported all the function of the first one
>
> Here is my codes and my error code  for the two files please help me:
> Traceback (most recent call last):
>
>
>   File "F:\School\University\Session 4\Programmation
> SIO\magasingolfvues.py", line 426, in <module>
>     app = App(racine, "magasinmodele.txt")
>   File "F:\School\University\Session 4\Programmation
> SIO\magasingolfvues.py", line 23, in __init__
>     ItemsFrame(contexte, item)
> NameError: global name 'item' is not defined
> >>>
>
>
>  1st fil called magasingolfmodele.py:
>
> # -*- coding: utf-8 -*-
> #
> # magasingolfmodele.py
> #
> # Magasin de golf --< Items de golf
> # Magasin de golf (nom, items, ville)
> # Items de golf(nom, prix)
> #
> # naming standards: http://www.python.org/dev/peps/pep-0008/
> #
>
>
> class Magasin:
>     """
>     Le concept magasin pour la gestion d'inventaire des items de golf.
>     """
>     def __init__(self, nom ="", items =[], ville="" ):
>         self.nom = nom
>         self.items = items
>         self.ville = ville
>
>     def set_nom(self, nom):
>         self.nom = nom
>
>     nom = property(None, set_nom)
>
>     def set_items(self, items):
>         self.items = items
>
>     items = property(None, set_items)
>
>     def set_ville(self, ville):
>         self.ville = ville
>
>     ville = property(None, set_ville)
>
>     def __str__(self):
>         return self.nom
>
> class Item:
>     """
>     Le concept item pour la gestion d'inventaire des items de golf.
>     """
>     def __init__(self, nom ="", prix = 100):
>         self.nom = nom
>         self.prix = prix
>
>
>     def set_nom(self, nom):
>         self.nom = nom
>
>     nom = property(None, set_nom)
>
>     def set_prix(self, prix):
>         self.prix = prix
>
>     prix = property(None, set_prix)
>
>     def __str__(self):
>         return self.nom
>
>
>
>     def initialiser(self):
>
>
>         item01 = Item ("Ensemble de fers Titleist")
>         item01.set_prix("1099.99")
>
>         item02 = Item ("Ensemble de fers Callaway")
>         item02.set_prix("1299.99")
>
>         item03 = Item ("Ensemble de fers Taylormade Burner Graphite")
>         item03.set_prix("2499.99")
>
>         item04 = Item ("Ensemble de fers Cobra")
>         item04.set_prix("999.99")
>
>         item05 = Item ("Ensemble de fers Ping")
>         item05.set_prix("1399.99")
>
>         item06 = Item ("Ensemble de fers Ben Hogan")
>         item06.set_prix("1199.99")
>
>         items = [item01, item02, item03, item04, item05, item06]
>         magasin01.set_items(items)
>
>         items = [item01, item03, item04, item06]
>         magasin02.set_items(items)
>
>         items = [item01, item02, item03, item05]
>         magasin03.set_items(items)
>
>         magasins = [magasin01,
>                     magasin02,
>                     magasin03]
>
>         self.set_magasins(magasins)
>
>         self.sauvegarder()
>
>     def afficher(self):
>         print("")
>         print("Magasins")
>         for magasin in self.magasins:
>             print("")
>             print(magasin)
>             print("")
>             for item in magasin.items:
>                 print(item)
>                 for prix in item.prix:
>                     print(prix)
>
>
> if __name__ == '__main__':
>     modele = Modele("magasinmodele.txt")
>     modele.charger()
>     if modele.vide():
>         modele.initialiser()
>     modele.afficher()
>
>
> Here's the code of my second file:
>
> # -*- coding: utf-8 -*-
> #
> # magasingolfvues.py
> #
> # naming standards: http://www.python.org/dev/peps/pep-0008/
> #
>
> from Tkinter import *
>
> from magasingolfmodele import *
>
> class App:
>     """
>     Application illustrant le concept d'un magasin de golf et des items
> qu'il vend.
>     """
>     def __init__(self, contexte, nom_fichier):
>         self.contexte = contexte
>         self.modele = Modele(nom_fichier)
>         self.modele.charger()
>         if self.modele.vide():
>             self.modele.initialiser()
>         MagasinsFrame(self)
>         ItemsFrame(contexte, item)
>
>
> class ItemsFrame(Toplevel):
>     """
>     Liste des items.
>     """
>     def __init__(self, contexte, items):
>         Toplevel.__init__(self, contexte)
>         self.contexte = contexte
>         self.items = items
>
>         self.title("Gestion des items de golf")
>         titre = Label(self, text = "B?tons de golf disponibles (nom)")
>         titre.pack()
>
>         self.liste = Listbox(self)
>         for items in self.items:
>             self.liste.insert(END, items)
>         self.liste.pack()
>
>         self.afficher_item_bouton = Button(
>             self, text = "Item", fg = "blue", command = self.afficher_item
>             )
>         self.afficher_item_bouton.pack(side = LEFT)
>
>         self.ajouter_item_bouton = Button(
>             self, text = "Ajouter", fg = "blue", command =
> self.ajouter_item
>             )
>         self.ajouter_item_bouton.pack(side=LEFT)
>
>         self.afficher_item_bouton = Button(
>             self, text = "Modifier", fg = "blue", command =
> self.modifier_item
>             )
>         self.afficher_item_bouton.pack(side = LEFT)
>
>         self.supprimer_facture_bouton = Button(
>             self, text = "Supprimer", fg = "red", command =
> self.supprimer_item
>             )
>         self.supprimer_facture_bouton.pack(side=LEFT)
>
>         self.afficher_nom_bouton = Button(
>             self, text = "Nom", fg = "blue", command = self.afficher_nom
>             )
>         self.afficher_nom_bouton.pack(side = LEFT)
>
>         self.afficher_prix_bouton = Button(
>             self, text = "Prix", fg = "blue", command = self.afficher_prix
>             )
>         self.afficher_prix_bouton.pack(side = LEFT)
>
>         sortir_bouton = Button(
>             self, text = "Sortir", fg = "red", command = self.quit
>             )
>         sortir_bouton.pack(side = LEFT)
>
>
>     def afficher_item(self):
>         items = self.liste.curselection()
>         items = [self.app.modele.items[int(item)] for item in items]
>         if (items != []):
>             items = items[0]
>             itemsFrame = ItemsFrame(self, item)
>
>     def ajouter_item(self):
>         itemAjouterFrame = ItemAjouterFrame(self, self.app.modele.items)
>
>     def modifier_item(self):
>         items = self.liste.curselection()
>         items = [self.app.modele.items[int(item)] for item in items]
>         if (items != []):
>             item = items[0]
>             ItemModifierFrame(self, items)
>
>     def supprimer_item(self):
>         items = self.liste.curselection()
>         items = [self.app.modele.items[int(item)] for item in items]
>         if (items != []):
>             items = items[0]
>             self.app.modele.items.remove(items)
>             self.app.modele.sauvegarder()
>             item = items[0]
>             self.liste_supprimer(item)
>
>     def afficher_nom(self):
>         items = self.liste.curselection()
>         items = [self.app.modele.items[int(item)] for item in items]
>         if (items != []):
>             items = magasins[0]
>             itemsFrame = ItemsFrame(self, magasin.items.nom)
>
>     def afficher_prix(self):
>         items = self.liste.curselection()
>         items = [self.app.modele.items[int(item)] for item in items]
>         if (items != []):
>             items = magasins[0]
>             itemsFrame = ItemsFrame(self, magasin.items.prix)
>
>     def liste_ajouter(self, items):
>         self.liste.insert(END, items)
>
>     def liste_modifier(self, item, items):
>         self.liste.delete(item)
>         self.liste.insert(item, items)
>
>     def liste_supprimer(self, item):
>         self.liste.delete(item)
>
> class ItemFrame(Toplevel):
>     """
>     Un certain item de golf.
>     """
>     def __init__(self, contexte, item):
>         Toplevel.__init__(self, contexte)
>
>         self.title("Item")
>
>         nom_etiquette = Label(self, text = "Nom l'item : " + item.nom, bg =
> "white", fg= "red")
>         nom_etiquette.pack()
>
>         nom_etiquette = Label(self, text = "Nom de la ville : " +
> items.prix, bg = "white", fg= "blue")
>         nom_etiquette.pack()
>
>         sortir_bouton = Button(
>             self, text = "Sortir", fg = "red", command = self.quit
>             )
>         sortir_bouton.pack(side = LEFT)
>
> class ItemAjouterFrame(Toplevel):
>     """
>     Ajouter un item.
>     """
>     def __init__(self, contexte, magasins):
>         Toplevel.__init__(self, contexte)
>         self.contexte = contexte
>         self.items = items
>
>
>         self.title("Ajouter")
>         titre = Label(self, text = "Item")
>         titre.pack()
>
>         nom_etiquette = Label(self, text = "Nom", bg = "white")
>         nom_etiquette.pack()
>         self.nom_entree = Entry(self)
>         self.nom_entree.pack()
>
>         self.ajouter_item_bouton = Button(
>             self, text = "Ajouter", command = self.ajouter_item
>             )
>         self.ajouter_item_bouton.pack(side=LEFT)
>
>         sortir_bouton = Button(
>             self, text = "Sortir", fg = "blue", command = self.quit
>             )
>         sortir_bouton.pack(side=LEFT)
>
>     def ajouter_item(self):
>         nom = self.nom_entree.get()
>         if nom.strip() == "":
>             nom = "?"
>         item = Item(nom)
>         self.item.append(item)
>         self.contexte.app.modele.sauvegarder()
>         self.contexte.liste_ajouter(items)
>
> class ItemModifierFrame(Toplevel):
>     """
>     Modifier un item dans la liste d'items.
>     """
>     def __init__(self, contexte, magasin):
>         Toplevel.__init__(self, contexte)
>         self.contexte = contexte
>         self.items = items
>
>         self.title("Modifer")
>         titre = Label(self, text = "Item de golf")
>         titre.pack()
>
>         nom_etiquette = Label(self, text = "nom", bg = "white")
>         nom_etiquette.pack()
>         self.nom_entree = Entry(self)
>         self.nom_entree.insert(0, self.magasin.items.nom)
>         self.nom_entree.pack()
>         nom_etiquette = Label(self, text = "prix", bg = "white")
>         nom_etiquette.pack()
>         self.nom_entree = Entry(self)
>         self.nom_entree.insert(0, self.magasin.items.prix)
>         self.nom_entree.pack()
>
>         self.modifier_item_bouton = Button(
>             self, text = "Modifier", command = self.modifier_magasin
>             )
>         self.modifier_item_bouton.pack(side=LEFT)
>
>         sortir_bouton = Button(
>             self, text = "Sortir", fg = "blue", command = self.quit
>             )
>         sortir_bouton.pack(side = LEFT)
>
>     def modifier_item(self):
>         nom = self.nom_entree.get()
>         if nom.strip() == "":
>             nom = "?"
>             self.nom_entree.insert(0, nom)
>         self.item.set_nom(nom)
>         self.contexte.app.modele.sauvegarder()
>         items = self.contexte.liste.curselection()
>         item = items[0]
>         self.contexte.liste_modifier(item, self.items)
>
>
> if __name__ == '__main__':
>     racine = Tk()
>     app = App(racine, "magasinmodele.txt")
>     racine.mainloop()
>     racine.destroy()
>
> Thank You for your help!!!
>
>
>
> --
> Marc-O. Rompr?
>
>


-- 
Marc-O. Rompr?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100427/ecf94400/attachment-0001.html>

From lie.1296 at gmail.com  Wed Apr 28 05:30:29 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Wed, 28 Apr 2010 13:30:29 +1000
Subject: [Tutor] How can I display my float as a string???
In-Reply-To: <s2r4bdcec5e1004271935q8b99e5bdkacffe3706270baca@mail.gmail.com>
References: <s2r4bdcec5e1004271935q8b99e5bdkacffe3706270baca@mail.gmail.com>
Message-ID: <hr8a7k$9p1$1@dough.gmane.org>

On 04/28/10 12:35, Marco Rompr? wrote:
> Here is my code, I need to display my float value as a string.
> 
> item.set_prix str(float(prix))

print prix


From rabidpoobear at gmail.com  Wed Apr 28 06:06:08 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Tue, 27 Apr 2010 23:06:08 -0500
Subject: [Tutor] (no subject)
In-Reply-To: <q2l4bdcec5e1004272012tb1d9c2ebl6b41a6572597a711@mail.gmail.com>
References: <p2i4bdcec5e1004272004ya53a0157s7970fe45e88281c0@mail.gmail.com> 
	<q2l4bdcec5e1004272012tb1d9c2ebl6b41a6572597a711@mail.gmail.com>
Message-ID: <z2jdfeb4471004272106oda0a2634r56f669470a1c552f@mail.gmail.com>

On Tue, Apr 27, 2010 at 10:12 PM, Marco Rompr? <marcodrompre at gmail.com> wrote:
> Oups my posting was too big!!!
>
> On Tue, Apr 27, 2010 at 11:04 PM, Marco Rompr? <marcodrompre at gmail.com>
> wrote:
>>
>> Why is none of my items button works???? In this, I have two files and in
>> my second file I imported all the function of the first one
>>
>> Here is my codes and my error code? for the two files please help me:
>> Traceback (most recent call last):
>>
>>
>> ? File "F:\School\University\Session 4\Programmation
>> SIO\magasingolfvues.py", line 426, in <module>
>> ??? app = App(racine, "magasinmodele.txt")
>> ? File "F:\School\University\Session 4\Programmation
>> SIO\magasingolfvues.py", line 23, in __init__
>> ??? ItemsFrame(contexte, item)
>> NameError: global name 'item' is not defined
>> >>>
>>
>>[snip lots of code]


You're not going to get a very good reply with a post like this.
First of all, it's homework, so we aren't going to give you answers
(not that we would anyway).
Secondly, if you have a problem, you need to clearly specify what the
problem is, and clearly outline what you did to try to solve it, and
why you think that didn't work, and some general indication that you
are trying things.
We're not here to just give people answers, we're here to help you
when you get stuck learning on your own.
It's much more rewarding in the end, trust me.

Also why do you think the problem you're having is your "items button
[doesn't] work" when it's pretty clear from the traceback that your
code crashes due to trying to access a variable that doesn't exist?

-Luke

From mhw at doctors.net.uk  Wed Apr 28 08:27:37 2010
From: mhw at doctors.net.uk (mhw at doctors.net.uk)
Date: Wed, 28 Apr 2010 06:27:37 +0000
Subject: [Tutor] Using Regex to produce text
Message-ID: <631639478-1272436089-cardhu_decombobulator_blackberry.rim.net-645033092-@bda188.bisx.produk.on.blackberry>

Dear All,

Quick question:

Is there an way of using the regex patterns to produce text, instead of matching it?

E.g.:
pat = re.compile("ab?d")
pat.getListofPossibleText()

Thanks,

Matt


Sent from my BlackBerry? wireless device

From rabidpoobear at gmail.com  Wed Apr 28 08:51:43 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 28 Apr 2010 01:51:43 -0500
Subject: [Tutor] Using Regex to produce text
In-Reply-To: <631639478-1272436089-cardhu_decombobulator_blackberry.rim.net-645033092-@bda188.bisx.produk.on.blackberry>
References: <631639478-1272436089-cardhu_decombobulator_blackberry.rim.net-645033092-@bda188.bisx.produk.on.blackberry>
Message-ID: <u2idfeb4471004272351qd4973ddci1a93fff005b3a4a9@mail.gmail.com>

On Wed, Apr 28, 2010 at 1:27 AM,  <mhw at doctors.net.uk> wrote:
> Dear All,
>
> Quick question:
>
> Is there an way of using the regex patterns to produce text, instead of matching it?
>
> E.g.:
> pat = re.compile("ab?d")
> pat.getListofPossibleText()
>

There's no end to the length of many patterns so this would be fairly pointless.
For example, what would getListofPossibleText do for the pattern ".*" ?

I think the better question is: what are you trying to do?
Or perhaps: Why do you think you need to solve your problem this way?

-Luke

From walterwefft at googlemail.com  Wed Apr 28 08:53:06 2010
From: walterwefft at googlemail.com (Walter Wefft)
Date: Wed, 28 Apr 2010 07:53:06 +0100
Subject: [Tutor] Modify inherited methods
In-Reply-To: <201004280808.14083.steve@pearwood.info>
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>
	<201004280808.14083.steve@pearwood.info>
Message-ID: <hr8m0i$82m$1@dough.gmane.org>

Steven D'Aprano wrote:
 > And for guru-level mastery, replace to call to dict.__init__ with ... 
nothing at all, because dict.__init__ doesn't do anything.
 >
 >
 >

(Sorry, should have sent to list).

I don't understand this - it must do something:

class MyDict1(dict):

    def __init__(self, *args, **kw):
        pass

class MyDict2(dict):

    def __init__(self, *args, **kw):
        dict.__init__(self, *args, **kw)


d = MyDict1(y=2)
print d
{}

d = MyDict2(y=2)
print d
{'y': 2}

d = MyDict1({'x': 3})
print d
{}

d = MyDict2({'x': 3})
print d
{'x': 3}

Behaviour is different depending on whether you call the superclass 
__init__ or not.

?



From alan.gauld at btinternet.com  Wed Apr 28 09:09:42 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 28 Apr 2010 08:09:42 +0100
Subject: [Tutor] (no subject)
References: <p2i4bdcec5e1004272004ya53a0157s7970fe45e88281c0@mail.gmail.com>
	<q2l4bdcec5e1004272012tb1d9c2ebl6b41a6572597a711@mail.gmail.com>
Message-ID: <hr8mvn$br2$1@dough.gmane.org>


"Marco Rompr?" <marcodrompre at gmail.com> wrote

> Oups my posting was too big!!!

In general it is better to popst long listings (over 100 lines say)
to a web site such as pastebin. That will ensure they are readable
and will not fill up peoples mailboxes unnecessarily.

However, even better is to reproduce your error in a small sample
program so we do not have to read all of your code!

> Why is none of my items button works???? In this, I have two files and in
> my second file I imported all the function of the first one

I can't speak for all of them but the first one I looked at had an error,
very similar to that suggested by your error message.

>         self.afficher_item_bouton = Button(
>                             self, text = "Modifier", fg = "blue", command =
>                             self.modifier_item
>             )
>         self.afficher_item_bouton.pack(side = LEFT)

>     def afficher_item(self):
>         items = self.liste.curselection()
>         items = [self.app.modele.items[int(item)] for item in items]
>         if (items != []):
>             items = items[0]
>             itemsFrame = ItemsFrame(self, item)
>

In this code the method assigns a value to items, then reassigns items to a 
modified list.
If the list is not empty it reassigns items to the first element. It then 
creates a new variable.
passing a variable item which does bot exist in the method so shouldbe defined 
globally.
But your error message suggests it is not. I suspect the items[0] assignment 
should be
to item? Or maybe to self.item?

> Here is my codes and my error code  for the two files please help me:
> Traceback (most recent call last):
>
>
>   File "F:\School\University\Session 4\Programmation
> SIO\magasingolfvues.py", line 426, in <module>
>     app = App(racine, "magasinmodele.txt")
>   File "F:\School\University\Session 4\Programmation
> SIO\magasingolfvues.py", line 23, in __init__
>     ItemsFrame(contexte, item)
> NameError: global name 'item' is not defined
> >>>


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



From denis.spir at gmail.com  Wed Apr 28 10:45:16 2010
From: denis.spir at gmail.com (spir =?UTF-8?B?4pij?=)
Date: Wed, 28 Apr 2010 10:45:16 +0200
Subject: [Tutor] Modify inherited methods
In-Reply-To: <hr8m0i$82m$1@dough.gmane.org>
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>
	<201004280808.14083.steve@pearwood.info>
	<hr8m0i$82m$1@dough.gmane.org>
Message-ID: <20100428104516.62eb93b5@o>

On Wed, 28 Apr 2010 07:53:06 +0100
Walter Wefft <walterwefft at googlemail.com> wrote:

> Steven D'Aprano wrote:
>  > And for guru-level mastery, replace to call to dict.__init__ with ... 
> nothing at all, because dict.__init__ doesn't do anything.
>  >
>  >
>  >
> 
> (Sorry, should have sent to list).
> 
> I don't understand this - it must do something:
> 
> class MyDict1(dict):
> 
>     def __init__(self, *args, **kw):
>         pass
> 
> class MyDict2(dict):
> 
>     def __init__(self, *args, **kw):
>         dict.__init__(self, *args, **kw)
> 
> 
> d = MyDict1(y=2)
> print d
> {}
> 
> d = MyDict2(y=2)
> print d
> {'y': 2}
> 
> d = MyDict1({'x': 3})
> print d
> {}
> 
> d = MyDict2({'x': 3})
> print d
> {'x': 3}
> 
> Behaviour is different depending on whether you call the superclass 
> __init__ or not.
> 
> ?

Hem... this is a rather obscure point (I personly have it wrong each time I need to subtype builtin types). Maybe you find some enlightenment in the following code:

===============================
class MyDict0(dict):
    pass
class MyDict1(dict):
    def __init__(self, *args, **kw):
        pass
class MyDict2(dict):
    def __init__(self, *args, **kw):
        dict.__init__(self, *args, **kw)
===============================

d0 = MyDict0(a=1) ; d1 = MyDict1(a=1) ; d2 = MyDict2(a=1)
print d0,d1,d2 # ==> {'a': 1} {} {'a': 1}

In case you do not define any custom __init__ *at all*, dict will transparently feed an instance of your type with provided entries, if any. If you define one, and don't feed the collection yourself, you need to call dict's __init__ to do it for you.
This behaviour allows having custom params at init:

===============================
class MyDict(dict):
    def __init__(self, name="", **entries):
        self.name = name
        dict.__init__(self, **entries)
    def __str__(self):
        return "%s:%s" %(self.name,dict.__str__(self))
d = MyDict(name="XYZ", a=1,b=2,c=3)
print d	# ==> XYZ:{'a': 1, 'c': 3, 'b': 2}
===============================

But all this does not apply to "atomic" builtin types such as int:

===============================
class MyInt0(int):
    pass

class MyInt1(int):
    def __init__(self, *args):
        pass

class MyInt2(int):
    def __init__(self, *args):
        int.__init__(self, *args)

i0 = MyInt0(1) ; i1 = MyInt1(1) ; i2 = MyInt2(1)
print i0,i1,i2	# ==> 1 1 1
===============================

This runs by me with a message from the compiler: "DeprecationWarning: object.__init__() takes no parameters" (about the call to int.__init__).
I would like to understand the implementation and the reason for this difference.
This means one cannot customize the initialisation of a subtype of int like is done above for a subtype of dict:

===============================
class MyInt(int):
    def __init__(self, value=0, name=""):
        self.name = name
        int.__init__(self, value)
    def __str__(self):
        return "%s:%s" %(self.name,int.__str__(self))
#~ i = MyInt(name="XYZ", value=3)
i = MyInt(3, "XYZ")
print i	# ==> TypeError: an integer is required
===============================

(Keyword parameters will also be rejected.) This is due to the implicit execution of the builtin constructor, which requires definite parameters (here a value and possibly a base).
More info on this topic welcome :-)

Denis
________________________________

vit esse estrany ?

spir.wikidot.com

From walterwefft at googlemail.com  Wed Apr 28 12:20:34 2010
From: walterwefft at googlemail.com (Walter Wefft)
Date: Wed, 28 Apr 2010 11:20:34 +0100
Subject: [Tutor] Modify inherited methods
In-Reply-To: <20100428104516.62eb93b5@o>
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>	<201004280808.14083.steve@pearwood.info>	<hr8m0i$82m$1@dough.gmane.org>
	<20100428104516.62eb93b5@o>
Message-ID: <hr925j$j7a$1@dough.gmane.org>

spir ? wrote:
> On Wed, 28 Apr 2010 07:53:06 +0100
> Walter Wefft <walterwefft at googlemail.com> wrote:
> 
>> Steven D'Aprano wrote:
>>  > And for guru-level mastery, replace to call to dict.__init__ with ... 
>> nothing at all, because dict.__init__ doesn't do anything.
>>  >
>>  >
>>  >
>>
>> (Sorry, should have sent to list).
>>
>> I don't understand this - it must do something:
>>
>> class MyDict1(dict):
>>
>>     def __init__(self, *args, **kw):
>>         pass
>>
>> class MyDict2(dict):
>>
>>     def __init__(self, *args, **kw):
>>         dict.__init__(self, *args, **kw)
>>
>>
>> d = MyDict1(y=2)
>> print d
>> {}
>>
>> d = MyDict2(y=2)
>> print d
>> {'y': 2}
>>
>> d = MyDict1({'x': 3})
>> print d
>> {}
>>
>> d = MyDict2({'x': 3})
>> print d
>> {'x': 3}
>>
>> Behaviour is different depending on whether you call the superclass 
>> __init__ or not.
>>
>> ?
> 
> Hem... this is a rather obscure point (I personly have it wrong each time I need to subtype builtin types). Maybe you find some enlightenment in the following code:
> 
> ===============================
> class MyDict0(dict):
>     pass
> class MyDict1(dict):
>     def __init__(self, *args, **kw):
>         pass
> class MyDict2(dict):
>     def __init__(self, *args, **kw):
>         dict.__init__(self, *args, **kw)
> ===============================
> 
> d0 = MyDict0(a=1) ; d1 = MyDict1(a=1) ; d2 = MyDict2(a=1)
> print d0,d1,d2 # ==> {'a': 1} {} {'a': 1}
> 

You reiterate my point. To say that dict.__init__ can be omitted in a 
subclass's __init__ with no effect, is not a correct statement.


From steve at pearwood.info  Wed Apr 28 13:04:30 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 28 Apr 2010 21:04:30 +1000
Subject: [Tutor] Modify inherited methods
In-Reply-To: <hr8m0i$82m$1@dough.gmane.org>
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>
	<201004280808.14083.steve@pearwood.info>
	<hr8m0i$82m$1@dough.gmane.org>
Message-ID: <201004282104.31213.steve@pearwood.info>

On Wed, 28 Apr 2010 04:53:06 pm Walter Wefft wrote:
> Steven D'Aprano wrote:
>  > And for guru-level mastery, replace to call to dict.__init__ with
>  > ...
>
> nothing at all, because dict.__init__ doesn't do anything.
[...]
> Behaviour is different depending on whether you call the superclass
> __init__ or not.
>
> ?

Fascinating... it seems that you are correct. Just goes to show, you can 
be programming in Python for well over a decade and still learn 
something new.

Believe it or not, I did test the behaviour before posting, but 
obviously my tests were faulty!


-- 
Steven D'Aprano

From mhw at doctors.net.uk  Wed Apr 28 17:32:38 2010
From: mhw at doctors.net.uk (mhw at doctors.net.uk)
Date: Wed, 28 Apr 2010 15:32:38 +0000
Subject: [Tutor] Using Regex to produce text
Message-ID: <51342422-1272468791-cardhu_decombobulator_blackberry.rim.net-2069735896-@bda188.bisx.produk.on.blackberry>

While some patterns are infinite, other's aren't (e.g. The example I gave). 

Using a subset of Regex syntax to produce a set of strings has the advantage of using a well understood and documented form, and if you could hook into the existing API, at minimal coding effort.

In addition, it allows a nice symmetry between search and production of resource names.

E.g.

Source some data (containing resources)
Label res 1 to res n using re.pattern(p1) 
Add this data to the larger data lump

.... do some stuff...

Find the data items you had again:
DataGroup1 = AllData.search(re.pattern(p1))

I suspect it's not that easy, as I don't think we can get to the internals of the regex FSM. However, I thought it would be worth asking.

Matt
Etc.


------Original Message------
From: Luke Paireepinart
To: mhw at doctors.net.uk
Cc: Python tutor
Subject: Re: [Tutor] Using Regex to produce text
Sent: 28 Apr 2010 07:51

On Wed, Apr 28, 2010 at 1:27 AM,  <mhw at doctors.net.uk> wrote:
> Dear All,
>
> Quick question:
>
> Is there an way of using the regex patterns to produce text, instead of matching it?
>
> E.g.:
> pat = re.compile("ab?d")
> pat.getListofPossibleText()
>

There's no end to the length of many patterns so this would be fairly pointless.
For example, what would getListofPossibleText do for the pattern ".*" ?

I think the better question is: what are you trying to do?
Or perhaps: Why do you think you need to solve your problem this way?

-Luke


Sent from my BlackBerry? wireless device

From emile at fenx.com  Wed Apr 28 17:56:30 2010
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 28 Apr 2010 08:56:30 -0700
Subject: [Tutor] Modify inherited methods
In-Reply-To: <hr925j$j7a$1@dough.gmane.org>
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>	<201004280808.14083.steve@pearwood.info>	<hr8m0i$82m$1@dough.gmane.org>	<20100428104516.62eb93b5@o>
	<hr925j$j7a$1@dough.gmane.org>
Message-ID: <hr9lu4$4hl$1@dough.gmane.org>

On 4/28/2010 3:20 AM Walter Wefft said...
> spir ? wrote:
>> On Wed, 28 Apr 2010 07:53:06 +0100
>> Walter Wefft <walterwefft at googlemail.com> wrote:
<snip>
>> ===============================
>> class MyDict0(dict):
>> pass
>> class MyDict1(dict):
>> def __init__(self, *args, **kw):
>> pass
>> class MyDict2(dict):
>> def __init__(self, *args, **kw):
>> dict.__init__(self, *args, **kw)
>> ===============================
>>
>> d0 = MyDict0(a=1) ; d1 = MyDict1(a=1) ; d2 = MyDict2(a=1)
>> print d0,d1,d2 # ==> {'a': 1} {} {'a': 1}
>>
>
> You reiterate my point. To say that dict.__init__ can be omitted in a
> subclass's __init__ with no effect, is not a correct statement.
>

It wasn't the omitted case that exhibits the difference.  When 
sub-classing, any methods omitted defer to the parent's version so the 
init from the dict parent happened.

Emile


From walterwefft at googlemail.com  Wed Apr 28 18:32:56 2010
From: walterwefft at googlemail.com (Walter Wefft)
Date: Wed, 28 Apr 2010 17:32:56 +0100
Subject: [Tutor] Modify inherited methods
In-Reply-To: <hr9lu4$4hl$1@dough.gmane.org>
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>	<201004280808.14083.steve@pearwood.info>	<hr8m0i$82m$1@dough.gmane.org>	<20100428104516.62eb93b5@o>	<hr925j$j7a$1@dough.gmane.org>
	<hr9lu4$4hl$1@dough.gmane.org>
Message-ID: <hr9nvp$cv5$1@dough.gmane.org>

Emile van Sebille wrote:
> On 4/28/2010 3:20 AM Walter Wefft said...
>> spir ? wrote:
>>> On Wed, 28 Apr 2010 07:53:06 +0100
>>> Walter Wefft <walterwefft at googlemail.com> wrote:
> <snip>
>>> ===============================
>>> class MyDict0(dict):
>>> pass
>>> class MyDict1(dict):
>>> def __init__(self, *args, **kw):
>>> pass
>>> class MyDict2(dict):
>>> def __init__(self, *args, **kw):
>>> dict.__init__(self, *args, **kw)
>>> ===============================
>>>
>>> d0 = MyDict0(a=1) ; d1 = MyDict1(a=1) ; d2 = MyDict2(a=1)
>>> print d0,d1,d2 # ==> {'a': 1} {} {'a': 1}
>>>
>>
>> You reiterate my point. To say that dict.__init__ can be omitted in a
>> subclass's __init__ with no effect, is not a correct statement.
>>
> 
> It wasn't the omitted case that exhibits the difference.  When 
> sub-classing, any methods omitted defer to the parent's version so the 
> init from the dict parent happened.
> 

"omitted in a subclass's __init__", ie. a *call* to the superclass's method


From emile at fenx.com  Wed Apr 28 19:36:22 2010
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 28 Apr 2010 10:36:22 -0700
Subject: [Tutor] Modify inherited methods
In-Reply-To: <hr9nvp$cv5$1@dough.gmane.org>
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>	<201004280808.14083.steve@pearwood.info>	<hr8m0i$82m$1@dough.gmane.org>	<20100428104516.62eb93b5@o>	<hr925j$j7a$1@dough.gmane.org>	<hr9lu4$4hl$1@dough.gmane.org>
	<hr9nvp$cv5$1@dough.gmane.org>
Message-ID: <hr9rp9$s8q$1@dough.gmane.org>

On 4/28/2010 9:32 AM Walter Wefft said...
> Emile van Sebille wrote:
>> On 4/28/2010 3:20 AM Walter Wefft said...
>>> You reiterate my point. To say that dict.__init__ can be omitted in a
>>> subclass's __init__ with no effect, is not a correct statement.
>>>
>>
>> It wasn't the omitted case that exhibits the difference. When
>> sub-classing, any methods omitted defer to the parent's version so the
>> init from the dict parent happened.
>>
>
> "omitted in a subclass's __init__", ie. a *call* to the superclass's method


You're right.  Failure to read on my part.  Sorry.

Emile


From eike.welk at gmx.net  Wed Apr 28 20:09:19 2010
From: eike.welk at gmx.net (Eike Welk)
Date: Wed, 28 Apr 2010 20:09:19 +0200
Subject: [Tutor] Modify inherited methods
In-Reply-To: <201004282104.31213.steve@pearwood.info>
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>
	<hr8m0i$82m$1@dough.gmane.org>
	<201004282104.31213.steve@pearwood.info>
Message-ID: <201004282009.19781.eike.welk@gmx.net>

On Wednesday April 28 2010 13:04:30 Steven D'Aprano wrote:
> On Wed, 28 Apr 2010 04:53:06 pm Walter Wefft wrote:
> > Steven D'Aprano wrote:
> >  > And for guru-level mastery, replace to call to dict.__init__ with
> >  > ...
> >
> > nothing at all, because dict.__init__ doesn't do anything.
> 
> [...]
> 
> > Behaviour is different depending on whether you call the superclass
> > __init__ or not.
> >
> > ?
> 
> Fascinating... it seems that you are correct. Just goes to show, you can
> be programming in Python for well over a decade and still learn
> something new.

You probably thought of tuple, where __init__ really does nothing. Tuple 
instances are created by __new__.


Eike.

From cmcaine at googlemail.com  Wed Apr 28 20:57:27 2010
From: cmcaine at googlemail.com (C M Caine)
Date: Wed, 28 Apr 2010 19:57:27 +0100
Subject: [Tutor] Modify inherited methods
In-Reply-To: <201004282009.19781.eike.welk@gmx.net>
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com> 
	<hr8m0i$82m$1@dough.gmane.org>
	<201004282104.31213.steve@pearwood.info> 
	<201004282009.19781.eike.welk@gmx.net>
Message-ID: <l2kb98d9b671004281157na4611631l4d4bd1e74e0d3cf4@mail.gmail.com>

Thank you all. One tangentially related question: what does (self,
*args, **kwargs) actually mean? How does one reference variables given
to a function that accepts these inputs?

Colin

From asmosis.asterix at gmail.com  Wed Apr 28 21:06:22 2010
From: asmosis.asterix at gmail.com (Daniel)
Date: Wed, 28 Apr 2010 22:06:22 +0300
Subject: [Tutor] Python beginner having troubles understanding word lists
	and character lists
Message-ID: <y2n3162f4ea1004281206x8b33c389v383d4e4d3824b128@mail.gmail.com>

Hello, I'm a beginner programmer, trying to learn python. I'm currently
reading The programming Historian,
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
I stumbled into lists of words and lists of characters. I have no
explications in that book for those two and I didn't found some explications
on the web. Could you point me to a link or something where I can read about
them? I don't seem to understand why they are used.
thank you so much!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100428/06880e4a/attachment.html>

From rabidpoobear at gmail.com  Wed Apr 28 21:19:43 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Wed, 28 Apr 2010 14:19:43 -0500
Subject: [Tutor] Python beginner having troubles understanding word
	lists and character lists
In-Reply-To: <y2n3162f4ea1004281206x8b33c389v383d4e4d3824b128@mail.gmail.com>
References: <y2n3162f4ea1004281206x8b33c389v383d4e4d3824b128@mail.gmail.com>
Message-ID: <n2rdfeb4471004281219rf7d149ecq77673f0a9373f599@mail.gmail.com>

On Wed, Apr 28, 2010 at 2:06 PM, Daniel <asmosis.asterix at gmail.com> wrote:
> Hello, I'm a beginner programmer, trying to learn python. I'm currently
> reading The programming
> Historian,http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
> I stumbled into lists of words and lists of characters. I have no
> explications in that book for those two and I didn't found some explications
> on the web. Could you point me to a link or something where I can read about
> them? I don't seem to understand why they are used.
> thank you so much!
>

Daniel,
I'm not too clear on what you're talking about.
What part is confusing you exactly?
Could you provide a code example?
Thanks,
-Luke

From lie.1296 at gmail.com  Wed Apr 28 22:36:18 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Thu, 29 Apr 2010 06:36:18 +1000
Subject: [Tutor] Using Regex to produce text
In-Reply-To: <51342422-1272468791-cardhu_decombobulator_blackberry.rim.net-2069735896-@bda188.bisx.produk.on.blackberry>
References: <51342422-1272468791-cardhu_decombobulator_blackberry.rim.net-2069735896-@bda188.bisx.produk.on.blackberry>
Message-ID: <hra6b4$96b$1@dough.gmane.org>

On 04/29/10 01:32, mhw at doctors.net.uk wrote:
> While some patterns are infinite, other's aren't (e.g. The example I gave). 

How should the regex engine know about that?

> Using a subset of Regex syntax to produce a set of strings has the 
> advantage of using a well understood and documented form, and if you
> could hook into the existing API, at minimal coding effort.

> In addition, it allows a nice symmetry between search and production of resource names.

String generation is generally simpler than string parsing. If the
pattern of the string you're generating is so complex that you need a
regex-powered name generator, it will probably be impossible to parse
that. Use string interpolation/formatting instead: '%s_%0s.txt' % (name,
num)

> I suspect it's not that easy, as I don't think we can get to the internals of
> the regex FSM. However, I thought it would be worth asking.

The problem is how you would define the "universe" set of characters. If
you had a '.', would you want alphanumeric only, all printable
characters, all ASCII (0-127) characters, all byte (0-255) character,
all Unicode characters? It's too ambiguous and if you say to follow what
regex is doing, then regex just happen to not be choosing the most
convenient default for pattern generators.


From eike.welk at gmx.net  Wed Apr 28 22:51:00 2010
From: eike.welk at gmx.net (Eike Welk)
Date: Wed, 28 Apr 2010 22:51:00 +0200
Subject: [Tutor] Modify inherited methods
In-Reply-To: <l2kb98d9b671004281157na4611631l4d4bd1e74e0d3cf4@mail.gmail.com>
References: <w2ub98d9b671004271424k283891b9jf1bf3e99deb42ccb@mail.gmail.com>
	<201004282009.19781.eike.welk@gmx.net>
	<l2kb98d9b671004281157na4611631l4d4bd1e74e0d3cf4@mail.gmail.com>
Message-ID: <201004282251.01021.eike.welk@gmx.net>

On Wednesday April 28 2010 20:57:27 C M Caine wrote:
> Thank you all. One tangentially related question: what does (self,
> *args, **kwargs) actually mean? How does one reference variables given
> to a function that accepts these inputs?

*args is a tuple containing the positional arguments; 
**kwargs is a dictionary which contains the keyword arguments. 

The stars before the variable names are the special syntax to handle arbitrary 
function arguments; you can use any variable names you want. You can use the 
syntax in a function call and in a function definition.

Here's an example session with Ipython:

In [5]: def foo(*args, **kwargs):
   ...:     print "args: ", args
   ...:     print "kwargs: ", kwargs
   ...:
   ...:

In [6]: foo(1, 2, 3)
args:  (1, 2, 3)
kwargs:  {}

In [7]: foo(1, 2, 3, a=4, b=5)
args:  (1, 2, 3)
kwargs:  {'a': 4, 'b': 5}

In [8]: foo( *(10, 11), **{"p":20, "q":21})
args:  (10, 11)
kwargs:  {'q': 21, 'p': 20}


Eike.

From malaclypse2 at gmail.com  Wed Apr 28 22:55:15 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Wed, 28 Apr 2010 16:55:15 -0400
Subject: [Tutor] Using Regex to produce text
In-Reply-To: <631639478-1272436089-cardhu_decombobulator_blackberry.rim.net-645033092-@bda188.bisx.produk.on.blackberry>
References: <631639478-1272436089-cardhu_decombobulator_blackberry.rim.net-645033092-@bda188.bisx.produk.on.blackberry>
Message-ID: <o2j16651e81004281355sdc875d65p72a85a7dbae93220@mail.gmail.com>

On Wed, Apr 28, 2010 at 2:27 AM,  <mhw at doctors.net.uk> wrote:
> Is there an way of using the regex patterns to produce text, instead of matching it?

There have been some previous discussions about generating all of the
possible matches for a given regular expressions.  I believe these are
the first messages in a couple of recent threads on python-list:

http://mail.python.org/pipermail/python-list/2010-February/1235120.html
http://mail.python.org/pipermail/python-list/2010-March/1240605.html

There's at least one sample implementation using the pyparsing library here:
http://pyparsing.wikispaces.com/file/view/invRegex.py

This message appears to have another implementation, sent to the list
as attachments:
http://mail.python.org/pipermail/python-list/2010-April/1240687.html

I haven't tried any of them myself, but they may be useful to you if
you really need to go down this road.

-- 
Jerry

From steve at pearwood.info  Thu Apr 29 01:16:56 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 29 Apr 2010 09:16:56 +1000
Subject: [Tutor] Using Regex to produce text
In-Reply-To: <hra6b4$96b$1@dough.gmane.org>
References: <51342422-1272468791-cardhu_decombobulator_blackberry.rim.net-2069735896-@bda188.bisx.produk.on.blackberry>
	<hra6b4$96b$1@dough.gmane.org>
Message-ID: <201004290916.57767.steve@pearwood.info>

On Thu, 29 Apr 2010 06:36:18 am Lie Ryan wrote:
> On 04/29/10 01:32, mhw at doctors.net.uk wrote:
> > While some patterns are infinite, other's aren't (e.g. The example
> > I gave).
>
> How should the regex engine know about that?

The regex engine itself doesn't run in reverse, so it can't know this 
and doesn't need to. However, it is possible to write a reverse regex 
engine which does run in reverse, in which case it is up to the 
programmer who creates it to encode that knowledge in the engine.


> > Using a subset of Regex syntax to produce a set of strings has the
> > advantage of using a well understood and documented form, and if
> > you could hook into the existing API, at minimal coding effort.
> >
> > In addition, it allows a nice symmetry between search and
> > production of resource names.
>
> String generation is generally simpler than string parsing. If the
> pattern of the string you're generating is so complex that you need a
> regex-powered name generator, it will probably be impossible to parse
> that. 

What? That makes no sense. That's like saying "I have here a formula for 
generating a series of numbers which is so complicated that it is 
impossible to write a formula for it". Since the string was generated 
from a regex, it will be parsable by *exactly* the same regex.


> Use string interpolation/formatting instead: '%s_%0s.txt' % 
> (name, num)

All this does is delay the work. You still have to generate all possible 
names and nums. Since you haven't defined what they are meant to be, 
it's impossible to do so.


> > I suspect it's not that easy, as I don't think we can get to the
> > internals of the regex FSM. However, I thought it would be worth
> > asking.
>
> The problem is how you would define the "universe" set of characters.

The same way the regex engine does.


> If you had a '.', would you want alphanumeric only, all printable
> characters, all ASCII (0-127) characters, all byte (0-255) character,
> all Unicode characters? 

The regex engine defines . as meaning "any character except newline, or 
any character including newline if the dotall flag is given". The regex 
engine operates on byte strings unless you give it the unicode flag. 
Given that the original poster wants to stick to regex syntax rather 
than learn a different syntax with different definitions, then the 
universal set of characters is well defined.

Here is a generator which should do the job:

# Untested.
def gen_dot(dotall_flag=False, unicode_flag=False):
    """Iterate over the sequence of strings which matches ."""
    if not unicode_flag:
        all_chars = [chr(i) for i in range(256)]
        if not dotall_flag:
            all_chars.remove('\n')
        for c in all_chars:
            yield c
    else:
        # There are a *lot* of unicode characters, but I don't know
        # how many. Take the coward's way out.
        raise NotImplementedError('left as an exercise for the reader')




> It's too ambiguous and if you say to follow 
> what regex is doing, then regex just happen to not be choosing the
> most convenient default for pattern generators.

Whether regex rules are the most convenient, or whether learning yet 
another complicated, terse language is better, is not the question.



-- 
Steven D'Aprano

From thepond at hughes.net  Wed Apr 28 21:22:56 2010
From: thepond at hughes.net (Eric Meigs)
Date: Wed, 28 Apr 2010 14:22:56 -0500
Subject: [Tutor] date problems
Message-ID: <4BD88B10.6060106@hughes.net>

I want to create a program to tell me when I am supposed to do things.
I have a text file with dates like  4-4-2010' as well as other data. I 
want to read in this date into my code and then compare it with 
'date.today()'
example 'if /variable/ >= today:'
I don't see how to read in a string and get it into a format for comparison.

I can do all of the other code.

Eric
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100428/afc99942/attachment.html>

From alan.gauld at btinternet.com  Thu Apr 29 01:31:31 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Apr 2010 00:31:31 +0100
Subject: [Tutor] date problems
References: <4BD88B10.6060106@hughes.net>
Message-ID: <hraggl$blf$1@dough.gmane.org>


"Eric Meigs" <thepond at hughes.net> wrote 

> I don't see how to read in a string and get it into a format for comparison.

Have you loked at the time and datetime modules?
They should do all you need.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Thu Apr 29 01:38:40 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Apr 2010 00:38:40 +0100
Subject: [Tutor] Python beginner having troubles understanding word
	listsand character lists
References: <y2n3162f4ea1004281206x8b33c389v383d4e4d3824b128@mail.gmail.com>
Message-ID: <hragu2$clr$1@dough.gmane.org>


"Daniel" <asmosis.asterix at gmail.com> wrote 

> I stumbled into lists of words and lists of characters. I have no
> explications in that book for those two and I didn't found some explications
> on the web. 

aListOfWords = ['one','word','or','many']
aListOfCharacters = ['a','s','d','f']

aStringOfCharacters = 'asdf'
aWord = aStringOfCharacters

Now what part do you not understand?

> Could you point me to a link or something where I can read about
> them? I don't seem to understand why they are used.

You use a list of words any time you want to process multiple words. 
For example a spelling checker may break a document into a list 
of words and compare each word to a reference list of correctly 
spelled words.

A list of characters is rarely used in Python since you can use 
a string in almost every case. 

You will find some more information in the "Raw Materials" topic 
of my tutorial.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From steve at pearwood.info  Thu Apr 29 01:56:04 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 29 Apr 2010 09:56:04 +1000
Subject: [Tutor] Python beginner having troubles understanding word
	lists and character lists
In-Reply-To: <y2n3162f4ea1004281206x8b33c389v383d4e4d3824b128@mail.gmail.com>
References: <y2n3162f4ea1004281206x8b33c389v383d4e4d3824b128@mail.gmail.com>
Message-ID: <201004290956.05916.steve@pearwood.info>

On Thu, 29 Apr 2010 05:06:22 am Daniel wrote:
> Hello, I'm a beginner programmer, trying to learn python. I'm
> currently reading The programming Historian,
> http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
> I stumbled into lists of words and lists of characters. I have no
> explications in that book for those two and I didn't found some
> explications on the web. Could you point me to a link or something
> where I can read about them? I don't seem to understand why they are
> used.
> thank you so much!

Hi Daniel,

Is English your first language? I ask because "list of words" is 
ordinary English, and the meaning in Python is hardly different.

In English, a list of words is a collection of words. There is no 
official way of writing a list in English. Here are three examples:

    red blue yellow green

    milk
    money
    mud
    monkeys
    moose

    king, queen, emperor, peasant, duke, serf


In Python, a word is just a string with no spaces inside it:

    "word"
    "not a word"

and a list can be created with square brackets and commas:

    ["red", "blue", "yellow", "green"]


Characters are single letters, digits or punctuation marks:

    a e i o u 2 4 6 8 . ? $ %

In Python, characters are just strings, and you can put them in a list:

    ["a", "e", "i", "o", "u", "2", "4", "6", "8", ".", "?", "$", "%"]


Hope this helps you.



-- 
Steven D'Aprano

From aclark at aclark.net  Thu Apr 29 01:59:08 2010
From: aclark at aclark.net (Alex Clark)
Date: Wed, 28 Apr 2010 23:59:08 +0000 (UTC)
Subject: [Tutor] date problems
References: <4BD88B10.6060106@hughes.net>
Message-ID: <slrnhthiuc.6uu.aclark@aclark.aclark.net>

On 2010-04-28, Eric Meigs <thepond at hughes.net> wrote:
> This is a multi-part message in MIME format.
> --===============0277013919==
> Content-Type: multipart/alternative;
> 	boundary="------------060806000801070600050409"
>
> This is a multi-part message in MIME format.
> --------------060806000801070600050409
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> Content-Transfer-Encoding: 7bit
>
> I want to create a program to tell me when I am supposed to do things.
> I have a text file with dates like  4-4-2010' as well as other data. I 
> want to read in this date into my code and then compare it with 
> 'date.today()'
> example 'if /variable/ >= today:'
> I don't see how to read in a string and get it into a format for comparison.

So you have two questions here, one "how to read in a string" and two "get it 
into a format for comparison"?

It seems to me you could do something like this:

    from datetime import datetime

    input = open('dates.txt','rb')
    list = input.read()
    dates = list.split()[0] # chars before the first whitespace 
    items = list.split()[-1] # everything after the first whitespace

    if datetime.now().strftime('%m-%d-%Y') == dates:
        print 'Do %s today!' % items

(from http://github.com/aclark4life/Python-Tutor/blob/master/eric-meigs.py)

> I can do all of the other code.
>
> Eric
>
> --------------060806000801070600050409
> Content-Type: text/html; charset=ISO-8859-1
> Content-Transfer-Encoding: 7bit
>
><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
><html>
><head>
>
><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
></head>
><body bgcolor="#ffffff" text="#000000">
><font size="-1"><font face="Arial">I want to create a program to tell
> me when I am supposed to do things.<br>
> I have a text file with dates like&nbsp; 4-4-2010' as well as other data. I
> want to read in this date into my code and then compare it with
> 'date.today()' <br>
> example 'if <i>variable</i> &gt;= today:' <br>
> I don't see how to read in a string and get it into a format for
> comparison.<br>
><br>
> I can do all of the other code.<br>
><br>
> Eric<br>
></font></font>
></body>
></html>
>
> --------------060806000801070600050409--
>
> --===============0277013919==
> Content-Type: text/plain; charset="us-ascii"
> MIME-Version: 1.0
> Content-Transfer-Encoding: 7bit
> Content-Disposition: inline
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> --===============0277013919==--
>


-- 
Alex Clark ? http://aclark.net
Author of Plone 3.3 Site Administration ? http://aclark.net/plone-site-admin


From dillyg23 at gmail.com  Thu Apr 29 11:05:17 2010
From: dillyg23 at gmail.com (Sharon)
Date: Thu, 29 Apr 2010 10:05:17 +0100
Subject: [Tutor] [Fwd: Re:  Which Designer]
Message-ID: <4BD94BCD.5010902@gmail.com>

Thank you both for your help and insight.  It has given me room for thought.

Much appeciated,

Sharon

-------- Original Message --------
Subject: 	Re: [Tutor] Which Designer
Date: 	Mon, 26 Apr 2010 09:09:59 +0100
From: 	Alan Gauld <alan.gauld at btinternet.com>
To: 	tutor at python.org
References: 	<4BD44500.9060802 at gmail.com> 
<hr2jpv$300$1 at dough.gmane.org><4BD4E2D8.70802 at gmail.com> 
<20100426013130.GA80914 at dragon.alchemy.com>



"Steve Willoughby" <steve at alchemy.com> wrote

> However, there are some real disadvantages to Tk(inter) as well, chiefly
> that it is a least-common denominator which does a passable job of running
> GUIs but they don't look consistent with the native look of Windows or OS/X

The new themed widgets in Tk have changed that, they are built on the
native widgets and look just like any other GUI. Available in Tkinter from
Python 2.7 and 3.1

> or whatever.  And there is a lot of missing functionality.

This is still true although Tix addresses the biggest gaps - but is
sadly lacking documentation - you have to use the Tcl/Tk docs :-(
(I keep intending to do a write up on Tix but other things get in the way!)

And there are other bolt-ons too such as PMW.

> I'm getting into wxPython at the moment, and I have to say it's at least
> worth a look.  It's also available for every platform (but doesn't come
> with Python), and is far more complete, and just about as easy to use
> as Tk, but looks a lot more polished.

wxPython is definielt more powerful and in particular has support
for things like printing and drag n drop which are missing fromTk.

> There are other toolkits with their advocates as well, of course, but if
> someone were just starting out with Python GUI programming, I'd recommend
> looking around at your options before starting with Tk.

I'd still advocate Tk because
a) It comes with Python so is standard
b) It is also the standard GUI in Ruby, Perl and Tcl so once learned is 
oportable
c) It is best documented with many books etc featuring it
d) It is easy to learn the basic GUI principles that are valid in any Framework
   (a bit like learning Python is good becauise it helps you learn other 
languages)

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 


_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


From kpkirton at gmail.com  Thu Apr 29 12:06:30 2010
From: kpkirton at gmail.com (Kevin Kirton)
Date: Thu, 29 Apr 2010 20:06:30 +1000
Subject: [Tutor] Any
Message-ID: <p2u47e5e0951004290306q8250c071ma70b29bd0db0c36f@mail.gmail.com>

Hi all,

I was just wondering if anyone here can recommend any freeware program
that has been written in python and for which the source code is
available.

Basically I just want to see a program that does something relatively
simple and straightforward, but something that is "real world," I mean
something that people actually use, hopefully something that comes
with it's own installer and GUI.

I'd like to try out using the program as an ordinary user and then I
want to look at the source code to see how it's been achieved.

Any ideas or suggestions?

Kevin Kirton
Australia

From cwitts at compuscan.co.za  Thu Apr 29 12:23:36 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Thu, 29 Apr 2010 12:23:36 +0200
Subject: [Tutor] Any
In-Reply-To: <p2u47e5e0951004290306q8250c071ma70b29bd0db0c36f@mail.gmail.com>
References: <p2u47e5e0951004290306q8250c071ma70b29bd0db0c36f@mail.gmail.com>
Message-ID: <4BD95E28.3080007@compuscan.co.za>

Kevin Kirton wrote:
> Hi all,
>
> I was just wondering if anyone here can recommend any freeware program
> that has been written in python and for which the source code is
> available.
>
> Basically I just want to see a program that does something relatively
> simple and straightforward, but something that is "real world," I mean
> something that people actually use, hopefully something that comes
> with it's own installer and GUI.
>
> I'd like to try out using the program as an ordinary user and then I
> want to look at the source code to see how it's been achieved.
>
> Any ideas or suggestions?
>
> Kevin Kirton
> Australia
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>   

Maybe look through projects at Freshmeat [1].

[1] http://freshmeat.net/tags/python

-- 
Kind Regards,
Christian Witts



From alan.gauld at btinternet.com  Thu Apr 29 14:04:20 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 29 Apr 2010 13:04:20 +0100
Subject: [Tutor] Any
References: <p2u47e5e0951004290306q8250c071ma70b29bd0db0c36f@mail.gmail.com>
Message-ID: <hrbsk7$d9v$1@dough.gmane.org>


"Kevin Kirton" <kpkirton at gmail.com> wrote 

> I was just wondering if anyone here can recommend any freeware program
> that has been written in python and for which the source code is
> available.

IDLE? 
The IDE that comes with Python ias wtten in Python and the 
source comes as part of the standard library.

But if thats not enough try both sourceforge and the PyGame web sites.
On sourceforge search for projects using python... DIA is one that springs 
to mind(a Visio type drawing program)

PyGame has lots of Python games you can download, several with source.

> Basically I just want to see a program that does something relatively
> simple and straightforward, but something that is "real world," I mean
> something that people actually use, hopefully something that comes
> with it's own installer and GUI.

You can use the python install tools or drive them with something 
higher level like Wize(?) or Installshield (or the free InstallMaker for 
Windows that I used to use... I don't know if its still extant however!)

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From kpkirton at gmail.com  Thu Apr 29 14:16:32 2010
From: kpkirton at gmail.com (Kevin Kirton)
Date: Thu, 29 Apr 2010 22:16:32 +1000
Subject: [Tutor] Any
In-Reply-To: <4BD95E28.3080007@compuscan.co.za>
References: <p2u47e5e0951004290306q8250c071ma70b29bd0db0c36f@mail.gmail.com>
	<4BD95E28.3080007@compuscan.co.za>
Message-ID: <r2j47e5e0951004290516q1a90ebfem1246701081573932@mail.gmail.com>

Christian Witts wrote:

> Maybe look through projects at Freshmeat [1].
>
> [1] http://freshmeat.net/tags/python

That's exactly what I was looking for. I've already selected a few
small programs and now I plan on installing them, seeing how they
operate from a user's perspective, then I'll take a look at the source
code and see what I can work out.

Thanks very much.

From denis.spir at gmail.com  Thu Apr 29 14:40:41 2010
From: denis.spir at gmail.com (spir =?UTF-8?B?4pij?=)
Date: Thu, 29 Apr 2010 14:40:41 +0200
Subject: [Tutor] Any
In-Reply-To: <hrbsk7$d9v$1@dough.gmane.org>
References: <p2u47e5e0951004290306q8250c071ma70b29bd0db0c36f@mail.gmail.com>
	<hrbsk7$d9v$1@dough.gmane.org>
Message-ID: <20100429144041.1a232ef7@o>

On Thu, 29 Apr 2010 13:04:20 +0100
"Alan Gauld" <alan.gauld at btinternet.com> wrote:

> IDLE? 
> The IDE that comes with Python ias wtten in Python and the 
> source comes as part of the standard library.

There's also a free software programming editor --editra, I guess-- written in and mainly for python. (But I would not recommend it for first tweaks, because it is great code but highly abstract.)

Denis
________________________________

vit esse estrany ?

spir.wikidot.com

From kpkirton at gmail.com  Thu Apr 29 14:49:49 2010
From: kpkirton at gmail.com (Kevin Kirton)
Date: Thu, 29 Apr 2010 22:49:49 +1000
Subject: [Tutor] Any
In-Reply-To: <hrbsk7$d9v$1@dough.gmane.org>
References: <p2u47e5e0951004290306q8250c071ma70b29bd0db0c36f@mail.gmail.com>
	<hrbsk7$d9v$1@dough.gmane.org>
Message-ID: <s2u47e5e0951004290549y5d5379f3wb4ffbf3d331c1ec6@mail.gmail.com>

Alan Gauld wrote:

> But if thats not enough try both sourceforge and the PyGame web sites.
> On sourceforge search for projects using python... DIA is one that springs
> to mind(a Visio type drawing program)
>
> PyGame has lots of Python games you can download, several with source.

PyGame looks promising (very distracting too). DIA in itself looks
quite useful and interesting, so I might learn that as a user then see
if I can look through its code.

Thanks for your help.

From steve at pearwood.info  Thu Apr 29 15:31:53 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 29 Apr 2010 23:31:53 +1000
Subject: [Tutor] Any
In-Reply-To: <p2u47e5e0951004290306q8250c071ma70b29bd0db0c36f@mail.gmail.com>
References: <p2u47e5e0951004290306q8250c071ma70b29bd0db0c36f@mail.gmail.com>
Message-ID: <201004292331.55052.steve@pearwood.info>

On Thu, 29 Apr 2010 08:06:30 pm Kevin Kirton wrote:
> Hi all,
>
> I was just wondering if anyone here can recommend any freeware
> program that has been written in python and for which the source code
> is available.

The Red Hat Package Manager (rpm) is written in Python.

The original BitTorrent application was written in Python.

The Roundup and Trac bug-trackers are both written in Python, as are the 
version-control systems Bazaar and Mercurial.

So are Mailman and Plone.

Most of these are fairly big applications though. Not huge, but big.

The Reddit website is written in Python, as is the EVE Online massive 
multiplayer game, although I doubt the source code for them are 
available.


> Basically I just want to see a program that does something relatively
> simple and straightforward, but something that is "real world," I
> mean something that people actually use, hopefully something that
> comes with it's own installer and GUI.

Unfortunately, these days all the "cool kids" are programming web apps 
rather than desktop applications. So it's a bit hard to find 
interesting, useful desktop applications. However, you can check out 
Pygame, PythonCard and Dabo:

http://www.pygame.org/news.html
http://pythoncard.sourceforge.net/
http://dabodev.com/

Pygame is a framework for, well, programming games in Python.

Pythoncard is a desktop application based on Apple's much-loved and 
never forgotten Hypercard (may it rest in peace!).

And Dabo is based on Visual FoxPro.



-- 
Steven D'Aprano

From SERKOS at avalon.ru  Thu Apr 29 17:17:01 2010
From: SERKOS at avalon.ru (=?koi8-r?B?68/T1MnLz9cg88XSx8XKIO7Jy8/MwcXXyd7=?=)
Date: Thu, 29 Apr 2010 19:17:01 +0400
Subject: [Tutor] How to get ipRouteTable from Cisco router?
Message-ID: <A2D4DE2854C7E444A15711412A98E1A95A273E15@legolas.avalon.ru>

Hello! 

I want to get route tables from Cisco routers in the network. What i 
have: 

import re 

from pysnmp.entity.rfc3413.oneliner import cmdgen 

s = r'(%s)' % ('(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.)\ 
{3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)') 
pattern = re.compile(s) 
file = 'routers.txt' 
s = open(file).read() 
i = 0 
router_list = [] 
while True: 
    match = pattern.search(s, i) 
    if match: 
        router_list.append(match.group(1)) 
        i = match.end() + 1 
    else: 
        break 

class router: 
    def __init__(self, who): 
        self.name = who 

    routetable = {} 

router1 = router(router_list[0]) 

cmdGen = cmdgen.CommandGenerator() 
errorIndication, errorStatus, errorIndex, varBindTable = 
cmdGen.nextCmd( 
    cmdgen.CommunityData('test-agent', public, 0), 
    cmdgen.UdpTransportTarget((router1.name, 161)), 
    (1,3,6,1,2,1,4,21,1,1)) 

if errorIndication: 
        print errorIndication 
else: 
    if errorStatus: 
            print '%s at %s\n' % 
(errorStatus.prettyPrint(),varBindTable[-1][int(errorIndex)-1]) 
    else: 
        for varBindTableRow in varBindTable: 
            for oid, val in varBindTableRow: 
                 print varBindTableRow 

Result: 

Code: Select all 
[(ObjectName('1.3.6.1.2.1.4.21.1.1.0.0.0.0'), IpAddress('0.0.0.0'))] 
[(ObjectName('1.3.6.1.2.1.4.21.1.1.10.9.0.0'), IpAddress('10.9.0.0'))] 
[(ObjectName('1.3.6.1.2.1.4.21.1.1.192.168.1.0'), 
IpAddress('192.168.1.0'))] 

How can i get IpAddress values from this list and put they in the 
dictionary? Or may be there is much better solution?

From iamroot at ajilan.pair.com  Thu Apr 29 18:11:16 2010
From: iamroot at ajilan.pair.com (iamroot at ajilan.pair.com)
Date: Thu, 29 Apr 2010 12:11:16 -0400 (EDT)
Subject: [Tutor] Any
In-Reply-To: <201004292331.55052.steve@pearwood.info>
Message-ID: <20100429161116.66268.qmail@ajilan.pair.com>

> 
> The Reddit website is written in Python, as is the EVE Online massive 
> multiplayer game, although I doubt the source code for them are 
> available.
>                                                    
Actually, Reddit has made it's source available and has included a HOWTO install Reddit on your webserver. There is a Google Group reddit-dev for
this purpose, as well.

See http://code.reddit.com for more...they actually use Trac for that site. ;).

--
Brie


From SERKOS at avalon.ru  Thu Apr 29 20:30:25 2010
From: SERKOS at avalon.ru (=?koi8-r?B?68/T1MnLz9cg88XSx8XKIO7Jy8/MwcXXyd7=?=)
Date: Thu, 29 Apr 2010 22:30:25 +0400
Subject: [Tutor] How to get ipRouteTable from Cisco router?
In-Reply-To: <m2j333efb451004290922mb8afd87cob31fcc1c54e705f@mail.gmail.com>
References: <A2D4DE2854C7E444A15711412A98E1A95A273E15@legolas.avalon.ru>,
	<m2j333efb451004290922mb8afd87cob31fcc1c54e705f@mail.gmail.com>
Message-ID: <A2D4DE2854C7E444A15711412A98E1A95A273E18@legolas.avalon.ru>

Hello!

I want to get route tables from Cisco routers in the network. What i
have:
<snip>
   else:
       for varBindTableRow in varBindTable:
           for oid, val in varBindTableRow:
                print varBindTableRow
 <snip>

Result:

Code: Select all
[(ObjectName('1.3.6.1.2.1.4.21.1.1.0.0.0.0'), IpAddress('0.0.0.0'))]
[(ObjectName('1.3.6.1.2.1.4.21.1.1.10.9.0.0'), IpAddress('10.9.0.0'))]
[(ObjectName('1.3.6.1.2.1.4.21.1.1.192.168.1.0'),
IpAddress('192.168.1.0'))]

How can i get IpAddress values from this list and put they in the
dictionary? Or may be there is much better solution?

My guess, from looking at what you have there, str(varBindTableRow[1]) should get your IP address in a string format. In any case the varBindTableRow[1] will contain the IpAddress object(?) that is displayed in the lists.

HTH,
Wayne


Results are: 

1. print str(varBindTableRow[1])

IndexError: list index out of range

2. print str(varBindTableRow[0][1])

??

3. but for ipRouteIfIndex, i have

print str(varBindTableRow[0][1])

0
0
1

So, it works for IfIndex, RouteType, but not for Dest, Mask and NextHop as they return ip.

Thanks indeed.


From shurui91 at gmail.com  Thu Apr 29 22:23:44 2010
From: shurui91 at gmail.com (Shurui Liu (Aaron Liu))
Date: Thu, 29 Apr 2010 16:23:44 -0400
Subject: [Tutor] blackjack game
Message-ID: <l2z2b9003cf1004291323rfed86ce1gf26bc6630224e8bf@mail.gmail.com>

# Blackjack
# From 1 to 7 players compete against a dealer

import cards, games

class BJ_Card(cards.Card):
    """ A Blackjack Card. """
    ACE_VALUE = 1

    def get_value(self):
        if self.is_face_up:
            value = BJ_Card.RANKS.index(self.rank) + 1
            if value > 10:
                value = 10
        else:
            value = None
        return value

    value = property(get_value)


class BJ_Deck(cards.Deck):
    """ A Blackjack Deck. """
    def populate(self):
        for suit in BJ_Card.SUITS:
            for rank in BJ_Card.RANKS:
                self.cards.append(BJ_Card(rank, suit))


class BJ_Hand(cards.Hand):
    """ A Blackjack Hand. """
    def __init__(self, name):
        super(BJ_Hand, self).__init__()
        self.name = name

    def __str__(self):
        rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
        if self.total:
            rep += "(" + str(self.total) + ")"
        return rep

    def get_total(self):
        # if a card in the hand has value of None, then total is None
        for card in self.cards:
            if not card.value:
                return None

        # add up card values, treat each Ace as 1
        total = 0
        for card in self.cards:
              total += card.value

        # determine if hand contains an Ace
        contains_ace = False
        for card in self.cards:
            if card.value == BJ_Card.ACE_VALUE:
                contains_ace = True

        # if hand contains Ace and total is low enough, treat Ace as 11
        if contains_ace and total <= 11:
            # add only 10 since we've already added 1 for the Ace
            total += 10

        return total

    total = property(get_total)

    def is_busted(self):
        return self.total > 21


class BJ_Player(BJ_Hand):
    """ A Blackjack Player. """
    def is_hitting(self):
        response = games.ask_yes_no("\n" + self.name + ", do you want
a hit? (Y/N): ")
        return response == "y"

    def bust(self):
        print self.name, "busts."
        self.lose()

    def lose(self):
        print self.name, "loses."

    def win(self):
        print self.name, "wins."

    def push(self):
        print self.name, "pushes."


class BJ_Dealer(BJ_Hand):
    """ A Blackjack Dealer. """
    def is_hitting(self):
        return self.total < 17

    def bust(self):
        print self.name, "busts."

    def flip_first_card(self):
        first_card = self.cards[0]
        first_card.flip()


class BJ_Game(object):
    """ A Blackjack Game. """
    def __init__(self, names):
        self.players = []
        for name in names:
            player = BJ_Player(name)
            self.players.append(player)

        self.dealer = BJ_Dealer("Dealer")

        self.deck = BJ_Deck()
        self.deck.populate()
        self.deck.shuffle()

    def get_still_playing(self):
        remaining = []
        for player in self.players:
            if not player.is_busted():
                remaining.append(player)
        return remaining

    # list of players still playing (not busted) this round
    still_playing = property(get_still_playing)

    def __additional_cards(self, player):
        while not player.is_busted() and player.is_hitting():
            self.deck.deal([player])
            print player
            if player.is_busted():
                player.bust()

    def play(self):
        # deal initial 2 cards to everyone
        self.deck.deal(self.players + [self.dealer], per_hand = 2)
        self.dealer.flip_first_card()    # hide dealer's first card
        for player in self.players:
            print player
        print self.dealer

        # deal additional cards to players
        for player in self.players:
            self.__additional_cards(player)

        self.dealer.flip_first_card()    # reveal dealer's first

        if not self.still_playing:
            # since all players have busted, just show the dealer's hand
            print self.dealer
        else:
            # deal additional cards to dealer
            print self.dealer
            self.__additional_cards(self.dealer)

            if self.dealer.is_busted():
                # everyone still playing wins
                for player in self.still_playing:
                    player.win()
            else:
                # compare each player still playing to dealer
                for player in self.still_playing:
                    if player.total > self.dealer.total:
                        player.win()
                    elif player.total < self.dealer.total:
                        player.lose()
                    else:
                        player.push()

        # remove everyone's cards
        for player in self.players:
            player.clear()
        self.dealer.clear()


def main():
    print "\t\tWelcome to Blackjack!\n"

    names = []
    number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8)
    for i in range(number):
        name = raw_input("Enter player name: ")
        names.append(name)
    print

    game = BJ_Game(names)

    again = None
    while again != "n":
        game.play()
        again = games.ask_yes_no("\nDo you want to play again?: ")


main()
raw_input("\n\nPress the enter key to exit.")




Here is the code of this game. I want to change some part of them.
1. Since I don't know what part of code is "responsible" for the
number of cards, so I don't know how to add a "card number check"
attribute, I mean, to check the number of card is more enough for next
time play no matter how many players there are, if cards are not more
enough, print out a notice and stop the program;
2. I am not sure if I can let the winner get all of the cards and
print out what cards the winner has when the game finished.

Thank you!

-- 
Shurui Liu (Aaron Liu)
Computer Science & Engineering Technology
University of Toledo
419-508-1228

From lie.1296 at gmail.com  Thu Apr 29 23:16:28 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Fri, 30 Apr 2010 07:16:28 +1000
Subject: [Tutor] blackjack game
In-Reply-To: <l2z2b9003cf1004291323rfed86ce1gf26bc6630224e8bf@mail.gmail.com>
References: <l2z2b9003cf1004291323rfed86ce1gf26bc6630224e8bf@mail.gmail.com>
Message-ID: <hrct2b$gk6$1@dough.gmane.org>

On 04/30/10 06:23, Shurui Liu (Aaron Liu) wrote:
> # Blackjack
> # From 1 to 7 players compete against a dealer
<snip code>
> 
> 
> Here is the code of this game. I want to change some part of them.
> 1. Since I don't know what part of code is "responsible" for the
> number of cards, so I don't know how to add a "card number check"
> attribute, I mean, to check the number of card is more enough for next
> time play no matter how many players there are, if cards are not more
> enough, print out a notice and stop the program;

The BJ_Game is responsible in querying the Deck if it has enough cards
for the round. BJ_Game will calculate the number of players and asks if
ask BJ_Deck if it can support that much player. Be careful when
calculating number of cards since in blackjack using one deck it is
possible to split one's hand into four (btw, why is BJ_Player inheriting
BJ_Deck? that would make splitting impossible; a player has a hand but
it is not a hand :-)

> 2. I am not sure if I can let the winner get all of the cards and
> print out what cards the winner has when the game finished.

that depends on the house rule, I think, some games requires all player
can see everyone else's card while other games keeps everyone's hand closed.


From alan.gauld at btinternet.com  Fri Apr 30 01:43:32 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 30 Apr 2010 00:43:32 +0100
Subject: [Tutor] Any
References: <p2u47e5e0951004290306q8250c071ma70b29bd0db0c36f@mail.gmail.com>
	<201004292331.55052.steve@pearwood.info>
Message-ID: <hrd5j8$c0b$1@dough.gmane.org>


"Steven D'Aprano" <steve at pearwood.info> wrote

> Pythoncard is a desktop application based on Apple's much-loved and 
> never forgotten Hypercard (may it rest in peace!).
> 
> And Dabo is based on Visual FoxPro.

Just a caveat:

Both of these are really development tools rather than applications in 
the normal sense - although they are applications for developers of 
course! But they are much closer to Visual Studio than to MS Word...

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




From alan.gauld at btinternet.com  Fri Apr 30 01:49:15 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 30 Apr 2010 00:49:15 +0100
Subject: [Tutor] blackjack game
References: <l2z2b9003cf1004291323rfed86ce1gf26bc6630224e8bf@mail.gmail.com>
Message-ID: <hrd5tv$cr0$1@dough.gmane.org>


"Shurui Liu (Aaron Liu)" <shurui91 at gmail.com> wrote

Your sig says you are studying Comp Sci and engineering.

You have posted the code for what is really a very, very, small program.
In the real world you will be expected to read and understand much
bigger programs than this - think about 1000+ files and half a million
lines of code.... (That was my first post uni' project - in C)

You apparently want us to read this code and interpret it for you?

Please try reading it and figuring out how it works first, then if you
have sections you want help with, come back and ask specific
questions. Don't expect us to do something you are not willing
to at least make a start on...

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


># Blackjack
> # From 1 to 7 players compete against a dealer
>
> import cards, games
>
> class BJ_Card(cards.Card):
>    """ A Blackjack Card. """
>    ACE_VALUE = 1
>
>    def get_value(self):
>        if self.is_face_up:
>            value = BJ_Card.RANKS.index(self.rank) + 1
>            if value > 10:
>                value = 10
>        else:
>            value = None
>        return value
>
>    value = property(get_value)
>
>
> class BJ_Deck(cards.Deck):
>    """ A Blackjack Deck. """
>    def populate(self):
>        for suit in BJ_Card.SUITS:
>            for rank in BJ_Card.RANKS:
>                self.cards.append(BJ_Card(rank, suit))
>
>
> class BJ_Hand(cards.Hand):
>    """ A Blackjack Hand. """
>    def __init__(self, name):
>        super(BJ_Hand, self).__init__()
>        self.name = name
>
>    def __str__(self):
>        rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
>        if self.total:
>            rep += "(" + str(self.total) + ")"
>        return rep
>
>    def get_total(self):
>        # if a card in the hand has value of None, then total is None
>        for card in self.cards:
>            if not card.value:
>                return None
>
>        # add up card values, treat each Ace as 1
>        total = 0
>        for card in self.cards:
>              total += card.value
>
>        # determine if hand contains an Ace
>        contains_ace = False
>        for card in self.cards:
>            if card.value == BJ_Card.ACE_VALUE:
>                contains_ace = True
>
>        # if hand contains Ace and total is low enough, treat Ace as 11
>        if contains_ace and total <= 11:
>            # add only 10 since we've already added 1 for the Ace
>            total += 10
>
>        return total
>
>    total = property(get_total)
>
>    def is_busted(self):
>        return self.total > 21
>
>
> class BJ_Player(BJ_Hand):
>    """ A Blackjack Player. """
>    def is_hitting(self):
>        response = games.ask_yes_no("\n" + self.name + ", do you want
> a hit? (Y/N): ")
>        return response == "y"
>
>    def bust(self):
>        print self.name, "busts."
>        self.lose()
>
>    def lose(self):
>        print self.name, "loses."
>
>    def win(self):
>        print self.name, "wins."
>
>    def push(self):
>        print self.name, "pushes."
>
>
> class BJ_Dealer(BJ_Hand):
>    """ A Blackjack Dealer. """
>    def is_hitting(self):
>        return self.total < 17
>
>    def bust(self):
>        print self.name, "busts."
>
>    def flip_first_card(self):
>        first_card = self.cards[0]
>        first_card.flip()
>
>
> class BJ_Game(object):
>    """ A Blackjack Game. """
>    def __init__(self, names):
>        self.players = []
>        for name in names:
>            player = BJ_Player(name)
>            self.players.append(player)
>
>        self.dealer = BJ_Dealer("Dealer")
>
>        self.deck = BJ_Deck()
>        self.deck.populate()
>        self.deck.shuffle()
>
>    def get_still_playing(self):
>        remaining = []
>        for player in self.players:
>            if not player.is_busted():
>                remaining.append(player)
>        return remaining
>
>    # list of players still playing (not busted) this round
>    still_playing = property(get_still_playing)
>
>    def __additional_cards(self, player):
>        while not player.is_busted() and player.is_hitting():
>            self.deck.deal([player])
>            print player
>            if player.is_busted():
>                player.bust()
>
>    def play(self):
>        # deal initial 2 cards to everyone
>        self.deck.deal(self.players + [self.dealer], per_hand = 2)
>        self.dealer.flip_first_card()    # hide dealer's first card
>        for player in self.players:
>            print player
>        print self.dealer
>
>        # deal additional cards to players
>        for player in self.players:
>            self.__additional_cards(player)
>
>        self.dealer.flip_first_card()    # reveal dealer's first
>
>        if not self.still_playing:
>            # since all players have busted, just show the dealer's hand
>            print self.dealer
>        else:
>            # deal additional cards to dealer
>            print self.dealer
>            self.__additional_cards(self.dealer)
>
>            if self.dealer.is_busted():
>                # everyone still playing wins
>                for player in self.still_playing:
>                    player.win()
>            else:
>                # compare each player still playing to dealer
>                for player in self.still_playing:
>                    if player.total > self.dealer.total:
>                        player.win()
>                    elif player.total < self.dealer.total:
>                        player.lose()
>                    else:
>                        player.push()
>
>        # remove everyone's cards
>        for player in self.players:
>            player.clear()
>        self.dealer.clear()
>
>
> def main():
>    print "\t\tWelcome to Blackjack!\n"
>
>    names = []
>    number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8)
>    for i in range(number):
>        name = raw_input("Enter player name: ")
>        names.append(name)
>    print
>
>    game = BJ_Game(names)
>
>    again = None
>    while again != "n":
>        game.play()
>        again = games.ask_yes_no("\nDo you want to play again?: ")
>
>
> main()
> raw_input("\n\nPress the enter key to exit.")
>
>
>
>
> Here is the code of this game. I want to change some part of them.
> 1. Since I don't know what part of code is "responsible" for the
> number of cards, so I don't know how to add a "card number check"
> attribute, I mean, to check the number of card is more enough for next
> time play no matter how many players there are, if cards are not more
> enough, print out a notice and stop the program;
> 2. I am not sure if I can let the winner get all of the cards and
> print out what cards the winner has when the game finished.
>
> Thank you!
>
> -- 
> Shurui Liu (Aaron Liu)
> Computer Science & Engineering Technology
> University of Toledo
> 419-508-1228
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 



From steve at pearwood.info  Fri Apr 30 03:35:18 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 30 Apr 2010 11:35:18 +1000
Subject: [Tutor] blackjack game
In-Reply-To: <l2z2b9003cf1004291323rfed86ce1gf26bc6630224e8bf@mail.gmail.com>
References: <l2z2b9003cf1004291323rfed86ce1gf26bc6630224e8bf@mail.gmail.com>
Message-ID: <201004301135.19338.steve@pearwood.info>

On Fri, 30 Apr 2010 06:23:44 am Shurui Liu (Aaron Liu) wrote:

> Here is the code of this game. I want to change some part of them.
> 1. Since I don't know what part of code is "responsible" for the
> number of cards, so I don't know how to add a "card number check"
> attribute, I mean, to check the number of card is more enough for
> next time play no matter how many players there are, if cards are not
> more enough, print out a notice and stop the program;

In real life, cards are dealt from a deck, and if the deck does not have 
enough cards, something will happen -- usually the dealer will start a 
new, shuffled, deck. Does your code have a deck?

> 2. I am not sure if I can let the winner get all of the cards and
> print out what cards the winner has when the game finished.

That's a question about blackjack, not Python. Since I don't play 
blackjack, I don't know.



-- 
Steven D'Aprano

From crp at cmc.net  Fri Apr 30 07:44:59 2010
From: crp at cmc.net (Ray Parrish)
Date: Thu, 29 Apr 2010 22:44:59 -0700
Subject: [Tutor] Boa Constructor list control
Message-ID: <4BDA6E5B.4090708@cmc.net>

Hello,

I am just learning how to use Boa Constructor to make GUI apps, and am 
having some problem with understanding the list control.

The list control has a property called columns, but I cannot figure out 
how to add columns, and specify names for them.

When I click the column property a small window opens up with it's title 
set to col1 something with the word "Name" in a label on it. Subsequent 
clicks on the column properry of the list control just brings this 
little window up again.

I cannot change the text in the label of that small window to the name I 
want for a column, and I cannot figure out how to add more columns to 
the list control.

When the small column window is selected no properties show for it in 
the Inspector window.

Can anyone tell me how to use this control? I tried using the Boa 
Constructor help menu, and it led me to a very brief description of the 
list control, with no details on what it's properties were even.

Thanks, Ray Parrish

-- 
Linux dpkg Software Report script set..
http://www.rayslinks.com/LinuxdpkgSoftwareReport.html
Ray's Links, a variety of links to usefull things, and articles by Ray.
http://www.rayslinks.com
Writings of "The" Schizophrenic, what it's like to be a schizo, and other
things, including my poetry.
http://www.writingsoftheschizophrenic.com



From crp at cmc.net  Fri Apr 30 08:07:47 2010
From: crp at cmc.net (Ray Parrish)
Date: Thu, 29 Apr 2010 23:07:47 -0700
Subject: [Tutor] Boa Constructor list control
In-Reply-To: <4BDA6E5B.4090708@cmc.net>
References: <4BDA6E5B.4090708@cmc.net>
Message-ID: <4BDA73B3.9080304@cmc.net>

Ray Parrish wrote:
> Hello,
>
> I am just learning how to use Boa Constructor to make GUI apps, and am 
> having some problem with understanding the list control.
>
> The list control has a property called columns, but I cannot figure 
> out how to add columns, and specify names for them.
>
> When I click the column property a small window opens up with it's 
> title set to col1 something with the word "Name" in a label on it. 
> Subsequent clicks on the column properry of the list control just 
> brings this little window up again.
>
> I cannot change the text in the label of that small window to the name 
> I want for a column, and I cannot figure out how to add more columns 
> to the list control.
>
> When the small column window is selected no properties show for it in 
> the Inspector window.
>
> Can anyone tell me how to use this control? I tried using the Boa 
> Constructor help menu, and it led me to a very brief description of 
> the list control, with no details on what it's properties were even.
>
> Thanks, Ray Parrish
>
OK, I've discovered the collection editor, and now know how to use it, 
but when I click the new button in the collection editor for a list 
control, it pops up an error message stating that the list needs to be 
created with the wx.LC_REPORT flag, and I have no idea how to accomplish 
that.

Could someone please enlighten me?

Thanks, Ray Parrish

-- 
Linux dpkg Software Report script set..
http://www.rayslinks.com/LinuxdpkgSoftwareReport.html
Ray's Links, a variety of links to usefull things, and articles by Ray.
http://www.rayslinks.com
Writings of "The" Schizophrenic, what it's like to be a schizo, and other
things, including my poetry.
http://www.writingsoftheschizophrenic.com



From marc.tompkins at gmail.com  Fri Apr 30 08:29:29 2010
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 29 Apr 2010 23:29:29 -0700
Subject: [Tutor] Boa Constructor list control
In-Reply-To: <4BDA73B3.9080304@cmc.net>
References: <4BDA6E5B.4090708@cmc.net> <4BDA73B3.9080304@cmc.net>
Message-ID: <x2z40af687b1004292329za3300a1en1e9d923518d653be@mail.gmail.com>

On Thu, Apr 29, 2010 at 11:07 PM, Ray Parrish <crp at cmc.net> wrote:

> OK, I've discovered the collection editor, and now know how to use it, but
> when I click the new button in the collection editor for a list control, it
> pops up an error message stating that the list needs to be created with the
> wx.LC_REPORT flag, and I have no idea how to accomplish that.
>
> Could someone please enlighten me?
>
> Ray --

I hate to say it ('cause I always hate it when I get an answer like this
myself), but you're asking on the wrong list: this isn't exactly a Python
question, it's either a BoaConstructor or a wxPython question.

Python itself is not a graphics language, but you can integrate various
graphics packages with Python to write GUI programs.  (One package, called
tkInter, ships with Python.)  WX is a popular cross-platform graphics
package written in C; wxPython is the Python translation/wrapping of wx.
Boa Constructor, in turn, is a rapid development tool for automatically
generating wxPython code.

The message you're reporting might be a bug in BoaConstructor (not too
likely), or a problem with how BoaConstructor is installed on your machine,
or...

Anyway, the first place I'd try would be the wxpython-users mailing list:
wxpython-users at lists.wxwidgets.org
http://lists.wxwidgets.org/mailman/listinfo/wxpython-users

I use wxPython myself, and I do know how to create a list with the
wx.LC_REPORT flag, but I don't think that's actually going to help you right
now - you need to talk to somebody who uses BoaConstructor.  (I'm an SPE man
myself.)

Hope that helps -

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100429/9b4ecfcd/attachment.html>

From dillyg23 at gmail.com  Fri Apr 30 23:30:44 2010
From: dillyg23 at gmail.com (Sharon)
Date: Fri, 30 Apr 2010 22:30:44 +0100
Subject: [Tutor] [Fwd: Re:  Which Designer]
Message-ID: <4BDB4C04.6070004@gmail.com>

Thankyou for your advice and I will strive to do this.
Sharon

-------- Original Message --------
Subject: 	Re: [Tutor] Which Designer
Date: 	Mon, 26 Apr 2010 13:37:15 -0300
From: 	Ricardo Ar?oz <ricaraoz at gmail.com>
Reply-To: 	raraoz at bigfoot.com
To: 	Sharon <dillyg23 at gmail.com>
References: 	<4BD44500.9060802 at gmail.com> <hr2jpv$300$1 at dough.gmane.org> 
<4BD4E2D8.70802 at gmail.com>



Sharon wrote:
> I think you are probably right. The only other sort of programming I
> did before I started on python was really 'VBA' and everything was
> done with GUI. I think that is what was in my mind. I have started
> using Tkinter and it isn't so bad. I just like the idea of having the
> visual side of actually seeing the buttons and whistles on the form
> ready. I have looked at QT, GTK and wxGlade but it is all more
> complicated than 'visual basic' and not at all rad like. So, for now
> I'll stick with my book and use Tkinter to get to grips with binding
> the widgets to the event handlers.
So maybe a bit of advice. Get your app together as a set of functions
and/or classes (your business layer) that called appropriately will
deliver all the functionality you need. Then whether you call those
functions from a console app, Tkinter, Wxpython, web app, or even a test
suite, will make no difference at all and porting them will be real
easy. Buttons should have no code but a call to a function in your
business layer, grids when instantiated or updated should call a
function in your business layer that should provide the appropriate data
set, etc.