From cspears2002 at yahoo.com Tue Aug 1 00:29:13 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 31 Jul 2006 15:29:13 -0700 (PDT) Subject: [Tutor] syntax error Message-ID: <20060731222913.40214.qmail@web51615.mail.yahoo.com> My brain has gone squishy. I am combining a linked list with a priority queue. This is the last exercise out of How To Think Like A Computer Scientist (Chapter 19). class Node: def __init__(self, cargo=None, next=None): self.cargo = cargo self.next = next def __str__(self): return str(self.cargo) class ImprovedQueue: def __init__(self): self.length = 0 self.head = None self.last = None def isEmpty(self): return (self.length == 0) def insert(self, cargo): node = Node(cargo) node.next = None if self.length == 0: # if list is empty, the new node is head and last self.head = self.last = node elif node.cargo > self.head.cargo: node.next = self.head self.head = node else node.cargo <= self.head.cargo: self.last.next = node self.last = node self.length = self.length + 1 def remove(self): cargo = self.head.cargo self.head = self.head.next self.length = self.length - 1 if self.length == 0: self.last = None return cargo Here is the error message: >>> from linkedPriorityQueue import * Traceback (most recent call last): File "", line 1, in ? File "linkedPriorityQueue.py", line 27 else node.cargo <= self.head.cargo: ^ SyntaxError: invalid syntax I am not sure what this means. Everything is spelled correctly. -Chris From john at fouhy.net Tue Aug 1 00:34:59 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 1 Aug 2006 10:34:59 +1200 Subject: [Tutor] syntax error In-Reply-To: <20060731222913.40214.qmail@web51615.mail.yahoo.com> References: <20060731222913.40214.qmail@web51615.mail.yahoo.com> Message-ID: <5e58f2e40607311534q4a60581coe04469fede08f1fa@mail.gmail.com> On 01/08/06, Christopher Spears wrote: > Traceback (most recent call last): > File "", line 1, in ? > File "linkedPriorityQueue.py", line 27 > else node.cargo <= self.head.cargo: > ^ > SyntaxError: invalid syntax > > I am not sure what this means. Everything is spelled > correctly. An 'else' clause doesn't take a condition. The general shape of an if statement is: if [condition]: do something elif [another condition]: do something else else: do other things The 'else' clause is the catchall for anything that doesn't match one of the preceding conditions, so it doesn't have its own condition. What I often like to do is to use a comment to indicate what is true in the 'else' branch. eg: else: # node.cargo <= self.head.cargo self.last.next = node self.last = node HTH! -- John. From alan.gauld at freenet.co.uk Tue Aug 1 00:43:11 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 31 Jul 2006 23:43:11 +0100 Subject: [Tutor] syntax error References: <20060731222913.40214.qmail@web51615.mail.yahoo.com> Message-ID: <000e01c6b4f2$b44a95b0$0201a8c0@XPpro> > My brain has gone squishy. :-) I know the feeling... > Here is the error message: >>>> from linkedPriorityQueue import * > Traceback (most recent call last): > File "", line 1, in ? > File "linkedPriorityQueue.py", line 27 > else node.cargo <= self.head.cargo: > ^ > SyntaxError: invalid syntax else: or elif condition: but not else condition: HTH, Alan G. From Barry.Carroll at psc.com Tue Aug 1 00:58:32 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 31 Jul 2006 15:58:32 -0700 Subject: [Tutor] syntax error Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36EF@eugsrv400.psc.pscnet.com> Hello Chris, > -----Original Message----- > Date: Mon, 31 Jul 2006 15:29:13 -0700 (PDT) > From: Christopher Spears > Subject: [Tutor] syntax error > To: tutor at python.org > Message-ID: <20060731222913.40214.qmail at web51615.mail.yahoo.com> > Content-Type: text/plain; charset=iso-8859-1 > > My brain has gone squishy. I am combining a linked > list with a priority queue. This is the last exercise > out of How To Think Like A Computer Scientist (Chapter > 19). > <> > > def insert(self, cargo): > node = Node(cargo) > node.next = None > if self.length == 0: > # if list is empty, the new node is head and last > self.head = self.last = node > elif node.cargo > self.head.cargo: > node.next = self.head > self.head = node > else node.cargo <= self.head.cargo: > self.last.next = node > self.last = node > self.length = self.length + 1 > <> > > Here is the error message: > >>> from linkedPriorityQueue import * > Traceback (most recent call last): > File "", line 1, in ? > File "linkedPriorityQueue.py", line 27 > else node.cargo <= self.head.cargo: > ^ > SyntaxError: invalid syntax > > I am not sure what this means. Everything is spelled > correctly. > > -Chris > The syntax error occurs just after the "else". Unlike "if" and "elif", "else" does not take an expression. It covers any cases left over after the "if" clause and all of the "elif" clauses have been tried and failed. The expression "node.cargo <= self.head.cargo" is therefore logically unnecessary. Python (and all other programming languages I know of) enforces this by making it illegal to put an expression in an "else" clause. I don't have access to "How To Think Like A Computer Scientist", so I can't point you to the section that discusses this, but I'm sure it's in there somewhere. Look in the index for "else clause", "if-elif-else statement" or some entry like that. HTH. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From justin.mailinglists at gmail.com Tue Aug 1 05:03:12 2006 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Tue, 1 Aug 2006 11:03:12 +0800 Subject: [Tutor] question about headers and smtplib Message-ID: <3c6718980607312003w7ba84d31q74c5f4b51b7aaee8@mail.gmail.com> When I first started with Python, I used MimeWriter to create E-mails. Then some mail servers rejected my E-mails. Some research (google) indicated (to me) that I needed a MIME-Version header. (Can't recall now if I also needed a Content-Type header.) Anyway, more research (Python docs) indicated that I should use the email package instead. I have been doing so since and have not had reports of anymore rejected E-mails. Hope this helps. >>> import email >>> from email.MIMENonMultipart import MIMENonMultipart >>> from email.Utils import formataddr >>> format_addresses = lambda pairs: ', '.join([formataddr(pair) for pair in pairs]) >>> msg = MIMENonMultipart('text', 'plain', charset='us-ascii') >>> msg.set_payload('Foo Bar') >>> msg.add_header('From', formataddr(('Justin', 'a at b.com'))) >>> msg.add_header('To', format_addresses([('Justin', 'a at b.com'), ('You', 'c at e.com')])) >>> print msg.as_string() Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 From: Justin To: Justin , You Foo Bar >>> From noufal at nibrahim.net.in Tue Aug 1 07:52:35 2006 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Tue, 1 Aug 2006 11:22:35 +0530 (IST) Subject: [Tutor] Debugging multithreaded programs in python Message-ID: <26963.61.16.169.181.1154411555.squirrel@members.hcoop.net> Greetings all, A friend here is trying to debug a rather badly written python program which spawns off lots of threads here and there. Are there any frameworks that I can reccommend that would ease his pain? On a more general note, it seems rather strange that I can't quickly google and find a debugger for multithreaded python programs. Python's "batteries included" philosophy has always been very useful to me. I've always managed to find what I need without any hassles. This is the first exception. Any insights? Are there any decent ways to debug a multi threaded program which make a debugger redundant? Peace. -- -NI From kent37 at tds.net Tue Aug 1 12:19:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 01 Aug 2006 06:19:22 -0400 Subject: [Tutor] Debugging multithreaded programs in python In-Reply-To: <26963.61.16.169.181.1154411555.squirrel@members.hcoop.net> References: <26963.61.16.169.181.1154411555.squirrel@members.hcoop.net> Message-ID: <44CF2AAA.9010300@tds.net> Noufal Ibrahim wrote: > Greetings all, > A friend here is trying to debug a rather badly written python program > which spawns off lots of threads here and there. Are there any > frameworks that I can reccommend that would ease his pain? > winpdb claims to debug multi-threaded programs. I have found it useful for single-threaded programs, haven't tried it for m-t. http://www.digitalpeers.com/pythondebugger/ Debugging m-t programs can be very hard. Placing a breakpoint can change the timing so a bug doesn't appear, or ruin a critical response time. Print statements can help. You say the program is badly written, if it uses more threads than needed maybe the first step is to get rid of some of them. You could also look for subsystems that could be tested independently, perhaps using unittest. Kent From nephish at gmail.com Tue Aug 1 21:29:13 2006 From: nephish at gmail.com (shawn bright) Date: Tue, 1 Aug 2006 15:29:13 -0400 Subject: [Tutor] question about headers and smtplib In-Reply-To: <3c6718980607312003w7ba84d31q74c5f4b51b7aaee8@mail.gmail.com> References: <3c6718980607312003w7ba84d31q74c5f4b51b7aaee8@mail.gmail.com> Message-ID: <384c93600608011229x4a8703efu89fc7311d1f2cb64@mail.gmail.com> OK, this worked, please disregard my last. The online docs at python.orgtold me the answer to that one. Between their example and yours, i am able to make it work. thanks a whole bunch ! shawn On 7/31/06, Justin Ezequiel wrote: > > When I first started with Python, I used MimeWriter to create E-mails. > > Then some mail servers rejected my E-mails. > > Some research (google) indicated (to me) that I needed a MIME-Version > header. > (Can't recall now if I also needed a Content-Type header.) > > Anyway, more research (Python docs) indicated that I should use the > email package instead. > I have been doing so since and have not had reports of anymore rejected > E-mails. > > Hope this helps. > > >>> import email > >>> from email.MIMENonMultipart import MIMENonMultipart > >>> from email.Utils import formataddr > >>> format_addresses = lambda pairs: ', '.join([formataddr(pair) for > pair in pairs]) > >>> msg = MIMENonMultipart('text', 'plain', charset='us-ascii') > >>> msg.set_payload('Foo Bar') > >>> msg.add_header('From', formataddr(('Justin', 'a at b.com'))) > >>> msg.add_header('To', format_addresses([('Justin', 'a at b.com'), > ('You', 'c at e.com')])) > >>> print msg.as_string() > Content-Type: text/plain; charset="us-ascii" > MIME-Version: 1.0 > From: Justin > To: Justin , You > > Foo Bar > >>> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060801/76e51ec3/attachment.html From cspears2002 at yahoo.com Wed Aug 2 00:27:29 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 1 Aug 2006 15:27:29 -0700 (PDT) Subject: [Tutor] When am I ever going to use this? Message-ID: <20060801222729.62964.qmail@web51605.mail.yahoo.com> I've been working through a tutorial: http://www.ibiblio.org/obp/thinkCSpy/index.htm. Lately, I have been learning about abstract data types (linked lists, stacks, queues, trees, etc.). While I do enjoy the challenge of creating these objects, I am not sure what they are used for. From jordangreenberg at gmail.com Wed Aug 2 01:13:15 2006 From: jordangreenberg at gmail.com (Jordan Greenberg) Date: Tue, 01 Aug 2006 19:13:15 -0400 Subject: [Tutor] When am I ever going to use this? In-Reply-To: <20060801222729.62964.qmail@web51605.mail.yahoo.com> References: <20060801222729.62964.qmail@web51605.mail.yahoo.com> Message-ID: <44CFE00B.2050005@gmail.com> Christopher Spears wrote: > I've been working through a tutorial: > http://www.ibiblio.org/obp/thinkCSpy/index.htm. > Lately, I have been learning about abstract data types > (linked lists, stacks, queues, trees, etc.). While I > do enjoy the challenge of creating these objects, I am > not sure what they are used for. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > They all have many uses. Priority Queues are used frequently in operating systems for process scheduling, etc. Trees are fantastic for most any searching application. Linked lists can be used for general purpose storage (since unlike arrays, their size is not fixed.) Learning data structures is really the one thing i wouldn't recommend python for, just because the job is usually done for you. Why implement a linked list, when we already have lists? Then Queues and Stacks are trivial to implement once you've got lists. If you're interested in learning more about data structures and their uses, this looks like a good reference: http://www.brpreiss.com/books/opus7/ -Jordan Greenberg From dyoo at hkn.eecs.berkeley.edu Wed Aug 2 05:19:37 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 1 Aug 2006 20:19:37 -0700 (PDT) Subject: [Tutor] When am I ever going to use this? In-Reply-To: <20060801222729.62964.qmail@web51605.mail.yahoo.com> References: <20060801222729.62964.qmail@web51605.mail.yahoo.com> Message-ID: On Tue, 1 Aug 2006, Christopher Spears wrote: > I've been working through a tutorial: > http://www.ibiblio.org/obp/thinkCSpy/index.htm. Lately, I have been > learning about abstract data types (linked lists, stacks, queues, trees, > etc.). While I do enjoy the challenge of creating these objects, I am > not sure what they are used for. Hi Chris, Let say that we are trying to write a navigator program, one that helps plan road trips. One portion of the input to this program would be a map of the roads. For example: map = [('a', 'b'), ('a', 'c'), ('c', 'f'), ('b', 'd'), ('d', 'e'), ('d', 'f')] might represent the following street map: a ------ b | | | | c d ------ e \ | \ | ----- f where 'a', 'b', 'c', 'd', 'e', and 'f' are points of interest. (I'm oversimplifying, but I hope you don't mind!) A simple question we might ask this system is: how far is it from point 'a' to point 'f'? We'd like to ask the system: distance('a', 'f', map) and be able to get 2, since there's a hop from 'a' to 'c', and from 'c' to 'f'. This problem is ripe to be attacked with an algorithm called "breadth-first search", and breadth-first search typically is implemented by keeping a queue of places. We can talk about this in more detail if you'd like. http://en.wikipedia.org/wiki/Breadth-first_search This is a long hand-wavy example for a short explanation: queues and and other data structures are "background" support tools: they themselves aren't so interesting, but they're the tools that a programmer often will reach for when working on non-string related problems. If you remember Starcraft: there was a four-level queue of movement commands that you could set up by holding "shift" while navigating your forces. You could also "queue" up production orders in factories. Same data structure. *grin* Best of wishes! From marc_a_poulin at yahoo.com Wed Aug 2 05:58:40 2006 From: marc_a_poulin at yahoo.com (Marc Poulin) Date: Tue, 1 Aug 2006 20:58:40 -0700 (PDT) Subject: [Tutor] When am I ever going to use this? In-Reply-To: <20060801222729.62964.qmail@web51605.mail.yahoo.com> Message-ID: <20060802035840.14836.qmail@web34114.mail.mud.yahoo.com> --- Christopher Spears wrote: > I've been working through a tutorial: > http://www.ibiblio.org/obp/thinkCSpy/index.htm. > Lately, I have been learning about abstract data > types > (linked lists, stacks, queues, trees, etc.). While > I > do enjoy the challenge of creating these objects, I > am > not sure what they are used for. > You probably use a linked list every day and don't even know it. Do you ever hit the "Back" button on your web browser to return to previous pages? The browser keeps a list of the pages you've visited, all linked together, so you can move backwards and forwards through the list. Here is a great resource for learning about different kinds of data structures: http://www.nist.gov/dads Regards, Marc __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From arcege at gmail.com Wed Aug 2 15:45:35 2006 From: arcege at gmail.com (Michael P. Reilly) Date: Wed, 2 Aug 2006 09:45:35 -0400 Subject: [Tutor] When am I ever going to use this? In-Reply-To: <20060801222729.62964.qmail@web51605.mail.yahoo.com> References: <20060801222729.62964.qmail@web51605.mail.yahoo.com> Message-ID: <7e5ba9220608020645t1d4d555ao9be367162d483ef6@mail.gmail.com> On 8/1/06, Christopher Spears wrote: > > I've been working through a tutorial: > http://www.ibiblio.org/obp/thinkCSpy/index.htm. > Lately, I have been learning about abstract data types > (linked lists, stacks, queues, trees, etc.). While I > do enjoy the challenge of creating these objects, I am > not sure what they are used for. > Queues and linked lists are also used extensively inside operating systems. Process lists are a large collections of queues organized in multiple queues implemented as linked lists and stored in one array. File systems store files by accessing data blocks through linked "blocks" (not quite the same as your linked node structure) and access to the disks and the network are through queues. Trees are used less often, but still very useful. The directory structure (folders and files) on your disk are trees, the program to search your email may use a tree. Stacks are often used for network protocols and program execution (every time you call a function, you are pushing something onto a stack). How about real life uses for these structures. Queues are one of the most natural structures from social life brought into computer science. Insects, banks, highways, birds, even the lunch line in grade school used queues. Stacks are the next, with stacks of books, papers, etc. Trees are used for people's genealogies. And you might used a linked list in a treasure hunt or for footnotes and bibliographies. Even post-it notes are a form of mental linked list. I hope this helps your understanding. -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060802/b9d27cd0/attachment.html From RPhillips at engineer.co.summit.oh.us Wed Aug 2 19:33:34 2006 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Wed, 02 Aug 2006 13:33:34 -0400 Subject: [Tutor] Update BLOB with odbc Message-ID: <44D0A9BD.0345.0006.0@engineer.co.summit.oh.us> It must be easier than I am making it. -------------------- sql = "UPDATE sa2.outfalls SET photo_content = %s WHERE pppoint_id ='"+record[0].strip()+"';" newsql = sql%pstuff print newsql[:150] cursor.execute(newsql) ______________ the print newsql[:150] => "UPDATE sa2.outfalls SET photo_content = ????*EExif . . . " and I get this error: TypeError: argument 1 must be string without null bytes, not str which sounds reasonable, but I don't know how to fix it. Is there some escape thing that I'm missing? Ron From anilmrn at yahoo.com Wed Aug 2 21:22:19 2006 From: anilmrn at yahoo.com (anil maran) Date: Wed, 2 Aug 2006 12:22:19 -0700 (PDT) Subject: [Tutor] latin-1 to unicode in python Message-ID: <20060802192219.30038.qmail@web55901.mail.re3.yahoo.com> Unicode? im getting this error: invalid byte sequence for encoding "UTF8": 0x92 since the db is not handling latin-1 and is set to use UTF8 how do i handle this thanks a lot --------------------------------- Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1?/min. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060802/fc538d18/attachment.htm From kent37 at tds.net Wed Aug 2 21:30:26 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 02 Aug 2006 15:30:26 -0400 Subject: [Tutor] latin-1 to unicode in python In-Reply-To: <20060802192219.30038.qmail@web55901.mail.re3.yahoo.com> References: <20060802192219.30038.qmail@web55901.mail.re3.yahoo.com> Message-ID: <44D0FD52.70305@tds.net> anil maran wrote: > Unicode? > im getting this error: > invalid byte sequence for encoding "UTF8": 0x92 > > since the db is not handling latin-1 and is set to use UTF8 how do i > handle this If you have a latin-1 string and you want utf-8, convert it to Unicode and then to utf-8 using decode() and encode(): In [1]: s='\x92' In [3]: s.decode('latin-1').encode('utf-8') Out[3]: '\xc2\x92' Kent From alan.gauld at freenet.co.uk Wed Aug 2 22:01:46 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 2 Aug 2006 21:01:46 +0100 Subject: [Tutor] When am I ever going to use this? References: <20060801222729.62964.qmail@web51605.mail.yahoo.com> Message-ID: <002201c6b66e$7c5ac8a0$0201a8c0@XPpro> > Lately, I have been learning about abstract data types > (linked lists, stacks, queues, trees, etc.). While I > do enjoy the challenge of creating these objects, I am > not sure what they are used for. To be honest, with the possible exception of trees, not very often! Most of these data types are taught for historic reasons. Older programminng languages like assembler, C, BASIC, Fortran, Pascal typically only had arrays(and often only single dimensioned arrays) for collecting data, and arrays were either fixed size or had to be explicitly resized in blocks of storage. Thus a whole science grew up in Computing about how to represent data more abstractly using arrays as the underpinnings. For example a linked list could be built using 2 identical arrays. One held the data and the other held the index of the next item, like this: index intList next 0 42 1 1 27 2 2 66 -1 <-- where -1 indicates end of list... which was equivalent to a list: 42,27,66 Now we can insert a member between 42 and 27 by adding an item at index 3 then modifying the next value for 42 to be 3 and setting the next value at 3 to be 1 - like this: index intList next 0 42 3 1 27 2 2 66 -1 <-- where -1 indicates end of list... 3 99 1 All very convoluted but produced the illusion of a python like list in a language without lists. But if the language has lists built in, which almost all modern languages do, there is no real need for most of this. You can add features like priorities and auto sorting etc etc, but this is almost trivial in modern languages whereas in old languages it was a lot of work. And if the language suuppors a dictionary type ijn addition to lists, and if it can store data of moxed types, then you can implement almost any abstract data collection easily. But the concepts of abstract data types are still taught to an increasingly bewildered audience... In practice, the average Python programmer can easily simulate or replace all of the classic data structures with built in types (with the possible exception of trees) or by using a relational database - the use of which wasn't possible in the 60's, 70's and early 80's because they hadn't been invented yet! Now implementing an RDBMS as part of a solution is so trivial that there's rarely need to worry about bulding trees etc for fast searches. That may be a slightly controversial view but it reflects my personal experience of programming with Python (and Ruby, Tcl, Smalltalk etc)! Of course if you ever have to use one of the older languages then the data structure stuff instantly applies again. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Aug 2 22:30:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 02 Aug 2006 16:30:31 -0400 Subject: [Tutor] latin-1 to unicode in python In-Reply-To: <20060802202149.93344.qmail@web55901.mail.re3.yahoo.com> References: <20060802202149.93344.qmail@web55901.mail.re3.yahoo.com> Message-ID: <44D10B67.3060401@tds.net> anil maran wrote: > In [1]: s='\x92' > > In [3]: s.decode('latin-1').encode('utf-8') > > > Out[3]: '\xc2\x92' > > is this some kind of python shell, pls clarify Yes, it's IPython. http://ipython.scipy.org/ Kent > > */Kent Johnson /* wrote: > > anil maran wrote: > > Unicode? > > im getting this error: > > invalid byte sequence for encoding "UTF8": 0x92 > > > > since the db is not handling latin-1 and is set to use UTF8 how > do i > > handle this > > If you have a latin-1 string and you want utf-8, convert it to > Unicode > and then to utf-8 using decode() and encode(): > > In [1]: s='\x92' > > In [3]: s.decode('latin-1').encode('utf-8') > Out[3]: '\xc2\x92' > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > From kent37 at tds.net Wed Aug 2 22:39:31 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 02 Aug 2006 16:39:31 -0400 Subject: [Tutor] latin-1 to unicode in python In-Reply-To: <20060802202100.46710.qmail@web55905.mail.re3.yahoo.com> References: <20060802202100.46710.qmail@web55905.mail.re3.yahoo.com> Message-ID: <44D10D83.7050307@tds.net> anil maran wrote: > how to determine > wat encoding it is in > for eg i m might not know it is in latin-1 This is hard. It is better by far to know what encoding your data is in. There is no way to determine for sure what encoding it is by looking at the data. The best you can do is rule out some encodings, and make a best guess. Here is one way: http://chardet.feedparser.org/ You can also try to decode the text using different encodings and use the first one that works. This is risky because latin-1 will always work. Finally, a non-Python method - MS Word is pretty good about guessing the encodings of text files. Kent PS Please reply on list > > */Kent Johnson /* wrote: > > anil maran wrote: > > Unicode? > > im getting this error: > > invalid byte sequence for encoding "UTF8": 0x92 > > > > since the db is not handling latin-1 and is set to use UTF8 how > do i > > handle this > > If you have a latin-1 string and you want utf-8, convert it to > Unicode > and then to utf-8 using decode() and encode(): > > In [1]: s='\x92' > > In [3]: s.decode('latin-1').encode('utf-8') > Out[3]: '\xc2\x92' > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------------------------------------------------ > How low will we go? Check out Yahoo! Messenger?s low PC-to-Phone call > rates. > From kent37 at tds.net Wed Aug 2 22:54:54 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 02 Aug 2006 16:54:54 -0400 Subject: [Tutor] latin-1 to unicode in python In-Reply-To: <20060802204725.54244.qmail@web55907.mail.re3.yahoo.com> References: <20060802204725.54244.qmail@web55907.mail.re3.yahoo.com> Message-ID: <44D1111E.8000509@tds.net> anil maran wrote: > 'ascii' codec can't encode character u'\x96' in position 213: ordinal > not in range(128) > > now i m getting this error Please show your code and the traceback and reply on list, not to me personally. Kent > > */Kent Johnson /* wrote: > > anil maran wrote: > > Unicode? > > im getting this error: > > invalid byte sequence for encoding "UTF8": 0x92 > > > > since the db is not handling latin-1 and is set to use UTF8 how > do i > > handle this > > If you have a latin-1 string and you want utf-8, convert it to > Unicode > and then to utf-8 using decode() and encode(): > > In [1]: s='\x92' > > In [3]: s.decode('latin-1').encode('utf-8') > Out[3]: '\xc2\x92' > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------------------------------------------------ > Do you Yahoo!? > Get on board. You're invited > > to try the new Yahoo! Mail Beta. From dkuhlman at rexx.com Wed Aug 2 23:43:33 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 2 Aug 2006 14:43:33 -0700 Subject: [Tutor] Notes on namespaces, scopes, etc In-Reply-To: References: <20060727155200.GA94348@cutter.rexx.com> <44C8EDF4.5020809@tds.net> <20060728204526.GB11905@cutter.rexx.com> Message-ID: <20060802214333.GA2067@cutter.rexx.com> On Fri, Jul 28, 2006 at 02:36:08PM -0700, Danny Yoo wrote: > > If there were really such a thing as nested scopes/namespaces, we would > > have a function that would give us access to them, similar to the way > > that locals() and globals() give us access to the local and global > > namespace. > > It would be _convenient_ to have such a function for inspection, but it's > not a requirement. > > Here's a function that shows lexical scope in action: > > ########################## > >>> def pair(x, y): > ... def f(b): > ... if b: return x > ... return y > ... return f > ... > >>> p = pair(3, 4) > >>> p(True) > 3 > >>> p(False) > 4 > ########################## I believe that I've incorporated most, if not all, of the suggestions from those on the list, except for Danny's suggestion (above) about closures. To paraphrase "The Treasure of the Sierra Madre": "Closures? Closures? We don't got to show you no stinking closures." After all, these notes on notes and bindings were intended to beginners, not computer science students. But, I did add a link to an explanation of closures. I've also added a collection of links to related material at the end of these notes. Hopefully, if my explanation is confusing, Alan's explanation or the standard docs will pull them through. The document itself is still here: http://www.rexx.com/~dkuhlman/python_comments.html#namespaces And, thanks again for all the help. Off topic -- For those of you who need the quote: "Badges? We ain't got no badges. We don't need no badges. I don't have to show you any stinking badges!" --Gold Hat, as played by Alfonso Bedoya "The Treasure of the Sierra Madre" (1948) Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From cspears2002 at yahoo.com Thu Aug 3 00:42:10 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 2 Aug 2006 15:42:10 -0700 (PDT) Subject: [Tutor] os.walk() Message-ID: <20060802224210.67474.qmail@web51606.mail.yahoo.com> I'm creating a function that traverses a directory tree and prints out paths to files: #!/usr/bin/python import os, os.path, glob def traverse(base = '.'): for root,dirs,files in os.walk(base): for name in files: path = os.path.join(root, name) print path Sample output: ./gui_screenshot.jpeg ./find_items.pyc ./find_items.py ./os ./LearningToProgram/loggablebankaccount.py ./LearningToProgram/BankAccounts.pyc ./LearningToProgram/KeysApp.py ./LearningToProgram/Message.py ./LearningToProgram/Message.pyc ./LearningToProgram/a.txt ./LearningToProgram/b.txt I'm glad that the function works smoothly. I'm just wondering how os.walk works. Shouldn't I have to write a statement like this: path = os.path.join(root, dirs, name) From alan.gauld at freenet.co.uk Thu Aug 3 01:58:46 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 3 Aug 2006 00:58:46 +0100 Subject: [Tutor] Notes on namespaces, scopes, etc References: <20060727155200.GA94348@cutter.rexx.com> <44C8EDF4.5020809@tds.net><20060728204526.GB11905@cutter.rexx.com> <20060802214333.GA2067@cutter.rexx.com> Message-ID: <002b01c6b68f$982507a0$0201a8c0@XPpro> Looks good Dave. Alan G. From kyrath at cox.net Thu Aug 3 03:16:34 2006 From: kyrath at cox.net (Rob) Date: Wed, 2 Aug 2006 21:16:34 -0400 Subject: [Tutor] smtp error from cgi script Message-ID: <002201c6b69a$7622aa80$0701a8c0@kasil> Hi, can someone help me interpret the error output below? I can't tell whether this is a coding error, or a configuration error, in which case, it would be up to my host provider. For privacy reasons, I have changed the actual email addresses to name at domain1.net and name at domain2.net. The first was the recipient and the second was the sender. Thanks in advance. -- Rob SMTPRecipientsRefused Python 2.3.5: /usr/bin/python Wed Aug 2 20:17:33 2006 A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. 62 63 server = smtplib.SMTP(mailserver) 64 failed = server.sendmail(From, To, text) 65 server.quit() 66 if failed: failed undefined, server = , server.sendmail = >, From = 'name at domain2.net', To = 'name at domain1.net', text = 'From: name at domain2.net\nTo: name at domain1.net\nDa... 1 1 \n----------------------------------------\n' /usr/lib/python2.3/smtplib.py in sendmail(self=, from_addr='name at domain2.net', to_addrs=['name at domain1.net'], msg='From: name at domain2.net\nTo: name at domain1.net\nDa... 1 1 \n----------------------------------------\n', mail_options=[], rcpt_options=[]) 685 # the server refused all our recipients 686 self.rset() 687 raise SMTPRecipientsRefused(senderrs) 688 (code,resp) = self.data(msg) 689 if code != 250: global SMTPRecipientsRefused = , senderrs = {'name at domain1.net': (550, 'authentication required')} SMTPRecipientsRefused: {'name at domain1.net': (550, 'authentication required')} args = ({'name at domain1.net': (550, 'authentication required')},) recipients = {'name at domain1.net': (550, 'authentication required')} -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060802/667cfc18/attachment.htm From cspears2002 at yahoo.com Thu Aug 3 06:14:23 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 2 Aug 2006 21:14:23 -0700 (PDT) Subject: [Tutor] critique my script! Message-ID: <20060803041423.84422.qmail@web51615.mail.yahoo.com> I created a function that takes a pattern and a base path and then uses os.walk and glob to traverse directories starting from the base path and place files that match the glob pattern in a dictionary. #!/usr/bin/python import os, os.path, glob def glob_files(pattern, base = '.'): path_list = [] abs_base = os.path.abspath(base) path_list.append(abs_base) for root,dirs,files in os.walk(abs_base): for name in dirs: path = os.path.join(root, name) #print path path_list.append(path) globbed = {} cwd = os.getcwd() for p in path_list: os.chdir(p) matched_files = glob.glob(pattern) if matched_files != []: globbed[p] = matched_files os.chdir(abs_base) os.chdir(cwd) return globbed Tell me what you think. This script would probably have been easier to write with reqular expressions, but I was determined to use glob. From anilmrn at yahoo.com Thu Aug 3 08:56:11 2006 From: anilmrn at yahoo.com (anil maran) Date: Wed, 2 Aug 2006 23:56:11 -0700 (PDT) Subject: [Tutor] how do i get datetime object or time object from updated in rss Message-ID: <20060803065611.10588.qmail@web55913.mail.re3.yahoo.com> How do i convert this string to datetime object Fri, 21 Apr 2006 03:02:17 +0000 Previously I'd been using mxDateTime (which does everything but requires a C extension) to parse e-mail style dates (i.e. the ones used in RSS and changes.xml) but it looks like they're handled by the standard library. http://blogs.law.harvard.edu/tech/rss mx.DateTime.DateTimeFrom(d['entries'][1].updated) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/mx/DateTime/DateTime.py", line 226, in DateTimeFrom value = float(arg) ValueError: invalid literal for float(): Fri, 21 Apr 2006 03:02:17 +0000 __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060802/af77942a/attachment.htm From ewald.ertl at hartter.com Thu Aug 3 09:14:18 2006 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Thu, 03 Aug 2006 09:14:18 +0200 Subject: [Tutor] smtp error from cgi script In-Reply-To: <002201c6b69a$7622aa80$0701a8c0@kasil> References: <002201c6b69a$7622aa80$0701a8c0@kasil> Message-ID: <44D1A24A.2050504@hartter.com> Hi Rob, Rob wrote: > Hi, can someone help me interpret the error output below? > > I can't tell whether this is a coding error, or a configuration error, > in which case, it would be up to my host provider. > > For privacy reasons, I have changed the actual email addresses to > name at domain1.net and name at domain2.net > . The first was the recipient and the second > was the sender. > > Thanks in advance. > -- Rob > > > SMTPRecipientsRefused > Python 2.3.5: /usr/bin/python > Wed Aug 2 20:17:33 2006 > > A problem occurred in a Python script. Here is the sequence of function > calls leading up to the error, in the order they occurred. > > > 62 > 63 server = smtplib.SMTP(mailserver) > 64 failed = server.sendmail(From, To, text) > 65 server.quit() > 66 if failed: > failed undefined, server = , server.sendmail = > >, From = > 'name at domain2.net' , > To = 'name at domain1.net' , text = 'From: > name at domain2.net\nTo : name at domain1.net\nDa > ... 1 1 > \n----------------------------------------\n' > > > /usr/lib/python2.3/smtplib.py > in sendmail(self=, from_addr='name at domain2.net' > , to_addrs=['name at domain1.net'], > msg='From: name at domain2.net\nTo : > name at domain1.net\nDa ... > 1 1 \n----------------------------------------\n', mail_options=[], > rcpt_options=[]) > 685 # the server refused all our recipients > 686 self.rset() > 687 raise SMTPRecipientsRefused(senderrs) > 688 (code,resp) = self.data(msg) > 689 if code != 250: > global SMTPRecipientsRefused = , > senderrs = {'name at domain1.net' : (550, > 'authentication required')} > > SMTPRecipientsRefused: {'name at domain1.net' : > (550, 'authentication required')} > args = ({'name at domain1.net' : (550, > 'authentication required')},) > recipients = {'name at domain1.net' : > (550, 'authentication required')} > I've not worked with smtplib, but the error (550, 'authentication required'), suggests to me, that you have to login into the mail-Server, otherwise the server would not accept emails. Looking into the doc for smtplib, the Class SMTP has method for that: login(self, user, password) Log in on an SMTP server that requires authentication. The arguments are: - user: The user name to authenticate with. - password: The password for the authentication. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. This method will return normally if the authentication was successful. This method may raise the following exceptions: SMTPHeloError The server didn't reply properly to the helo greeting. SMTPAuthenticationError The server didn't accept the username/ password combination. SMTPException No suitable authentication method was found. HTH Ewald From alan.gauld at btinternet.com Thu Aug 3 11:49:52 2006 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Aug 2006 10:49:52 +0100 Subject: [Tutor] os.walk() References: <20060802224210.67474.qmail@web51606.mail.yahoo.com> Message-ID: "Christopher Spears" wrote> for root,dirs,files in os.walk(base): > for name in files: > path = os.path.join(root, name) > print path > > Sample output: > > ./gui_screenshot.jpeg > ./find_items.pyc > ./find_items.py > ./os > ./LearningToProgram/loggablebankaccount.py > I'm glad that the function works smoothly. I'm just > wondering how os.walk works. Shouldn't I have to > write a statement like this: > > path = os.path.join(root, dirs, name) > No, the dirs value holds a list of folders, the files value holds a list of files. Thus if you wanted to print out all the sub folders in the root you would print root+dirs But you want files not folders so you correctly use print root+files root holds the full path to the current point in the tree. (And os.walk is a good example of a program using a tree data structure! ;-) Alan G. From alan.gauld at freenet.co.uk Thu Aug 3 12:40:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 3 Aug 2006 11:40:03 +0100 Subject: [Tutor] critique my script! References: <20060803041423.84422.qmail@web51615.mail.yahoo.com> Message-ID: <000e01c6b6e9$2e5119e0$0201a8c0@XPpro> >I created a function that takes a pattern and a base > path and then uses os.walk and glob to traverse > directories starting from the base path and place > files that match the glob pattern in a dictionary. I'm not sure why you are traversing the paths a second time. Why not just apply glob within the os.walk traversal? After all you are putting the path into the path list, then iterating over that list later, why not just apply glob the first time around? > #!/usr/bin/python > > import os, os.path, glob > > def glob_files(pattern, base = '.'): > path_list = [] > abs_base = os.path.abspath(base) > path_list.append(abs_base) > for root,dirs,files in os.walk(abs_base): > for name in dirs: > path = os.path.join(root, name) > #print path > path_list.append(path) > globbed = {} > cwd = os.getcwd() > for p in path_list: > os.chdir(p) > matched_files = glob.glob(pattern) > if matched_files != []: > globbed[p] = matched_files > os.chdir(abs_base) > os.chdir(cwd) > return globbed Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Aug 3 13:09:25 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Aug 2006 07:09:25 -0400 Subject: [Tutor] Notes on namespaces, scopes, etc In-Reply-To: <20060802214333.GA2067@cutter.rexx.com> References: <20060727155200.GA94348@cutter.rexx.com> <44C8EDF4.5020809@tds.net> <20060728204526.GB11905@cutter.rexx.com> <20060802214333.GA2067@cutter.rexx.com> Message-ID: <44D1D965.60008@tds.net> Dave Kuhlman wrote: > I believe that I've incorporated most, if not all, of the > suggestions from those on the list, except for Danny's suggestion > (above) about closures. > > The document itself is still here: > > http://www.rexx.com/~dkuhlman/python_comments.html#namespaces Very nice. Just a few notes: - When you talk about the hierarchy of namespace lookup, you might just mention nested scopes and refer to the PEP for more info, instead of omitting it completely. - In the section "Accessing namespace dictionaries" you write, "Note that for lexically/statically nested scopes (for example, a function defined inside a function), it seems that globals() and locals() still give access to all items in the accessible namespaces, /but/ do not give dictionary style access to all visible scopes." globals() and locals() give access to items in the global and local namespaces, not all accessible namespaces. As was noted in the emails, variables in nested scopes are not included in locals() and globals(). I think that's what you're trying to say but it isn't clear. - PEP 227 is definitely the present, not the future. Nested scopes have been available since Python 2.1. Kent From kent37 at tds.net Thu Aug 3 13:20:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Aug 2006 07:20:20 -0400 Subject: [Tutor] critique my script! In-Reply-To: <000e01c6b6e9$2e5119e0$0201a8c0@XPpro> References: <20060803041423.84422.qmail@web51615.mail.yahoo.com> <000e01c6b6e9$2e5119e0$0201a8c0@XPpro> Message-ID: <44D1DBF4.3010805@tds.net> Alan Gauld wrote: >> I created a function that takes a pattern and a base >> path and then uses os.walk and glob to traverse >> directories starting from the base path and place >> files that match the glob pattern in a dictionary. >> > > I'm not sure why you are traversing the paths a second time. > Why not just apply glob within the os.walk traversal? > After all you are putting the path into the path list, then > iterating over that list later, why not just apply glob the > first time around? Alternately you could use fnmatch.fnmatch() to filter the list of files received from os.walk(). Then you wouldn't be using glob() but fnmatch() is the file-name-matching part of glob(). A list comprehension would be good for this: matchedFiles = [ f for f in files if fnmatch(f, pattern) ] I think your whole program can be written in about six lines, but I'll let you puzzle it a bit rather than showing you. Kent From ml.cyresse at gmail.com Thu Aug 3 13:44:45 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Thu, 3 Aug 2006 23:44:45 +1200 Subject: [Tutor] Binary fractions, recommendations? Message-ID: Hi all, I was recently playing with the problem of implementing the floor() functionality, modulo being specifically mentioned in the briefing... so, after grokking that x = a - (a % b) would do it (i.e. for a = 5.5 and b = 1, you'd get x =5) I felt very pleased... ...until I saw the definiton of modulo. Which would be... def my_mod(x, y): return x - (y*math.floor(x/y)) Ack. My floor() relies on modulo which relies on... floor. So after some Googling, I find a page which indicates that the trick seems to be bit operations - http://www.diycalculator.com/popup-m-round.shtml Problem is; I can't bitshift on floats, so can't test. Can't bitshift on floats in C either. Does anyone know how I could work on a binary representation of a float? Any language at all, I'm desperate... Regards, Liam Clarke From rabidpoobear at gmail.com Thu Aug 3 15:34:03 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 03 Aug 2006 08:34:03 -0500 Subject: [Tutor] Binary fractions, recommendations? In-Reply-To: References: Message-ID: <44D1FB4B.4010309@gmail.com> Liam Clarke wrote: > Hi all, > > I was recently playing with the problem of implementing the floor() > functionality, modulo being specifically mentioned in the briefing. > > you could convert the float to a string, split on the decimal point, and convert the left-hand side back to an integer :) or you could just convert the float to an integer. From jgcox39 at highstream.net Thu Aug 3 20:12:28 2006 From: jgcox39 at highstream.net (Joe Cox) Date: Thu, 3 Aug 2006 11:12:28 -0700 Subject: [Tutor] Listbox selection Message-ID: I am still having a problem getting my listbox's binded to the radiobuttons. I am getting closer. ###Assign each Radiobutton with its own listbox values, show one selected button and one listbox### from Tkinter import * root = Tk() var = StringVar() var.set('a') { 'Aluminum' : ['Wrought', 'Die cast'], 'Steel' : ['Low Carbon', 'Medium-high carbon','Alloy'] } def radio_command(): if var.get() == 'a': # button with value 'a' selected listbox.insert('a') #here I am trying to put the string starting with 'Steel' in the listbox elif var.get() == 'b': # button with value 'b' selected listbox.insert('b') #here I am trying to put the string starting with 'Aluminum' in the listbox radio_a = Radiobutton(root,text="Steel", variable=var, value='a', command=radio_command).pack() radio_b = Radiobutton(root,text="Aluminum", variable=var, value='b', command=radio_command).pack() radio_c = Radiobutton(root,text="Cast Iron", variable=var, value='c', command=radio_command).pack() radio_d = Radiobutton(root,text="Nickel", variable=var, value='d', command=radio_command).pack() radio_e = Radiobutton(root,text="Titaniuim", variable=var, value='e', command=radio_command).pack() listbox = Listbox(root) for item in (): listbox.insert(END, item) listbox.pack(side=LEFT, fill=BOTH) root.mainloop() Joe Cox 513-293-4830 From cspears2002 at yahoo.com Thu Aug 3 17:33:46 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 3 Aug 2006 08:33:46 -0700 (PDT) Subject: [Tutor] critique my script! In-Reply-To: <000e01c6b6e9$2e5119e0$0201a8c0@XPpro> Message-ID: <20060803153346.17327.qmail@web51614.mail.yahoo.com> I didn't know I could place the glob in the os.walk traversal. Could you give me an example of how to do this? --- Alan Gauld wrote: > >I created a function that takes a pattern and a > base > > path and then uses os.walk and glob to traverse > > directories starting from the base path and place > > files that match the glob pattern in a dictionary. > > I'm not sure why you are traversing the paths a > second time. > Why not just apply glob within the os.walk > traversal? > After all you are putting the path into the path > list, then > iterating over that list later, why not just apply > glob the > first time around? > > > #!/usr/bin/python > > > > import os, os.path, glob > > > > def glob_files(pattern, base = '.'): > > path_list = [] > > abs_base = os.path.abspath(base) > > path_list.append(abs_base) > > for root,dirs,files in os.walk(abs_base): > > for name in dirs: > > path = os.path.join(root, name) > > #print path > > path_list.append(path) > > globbed = {} > > cwd = os.getcwd() > > for p in path_list: > > os.chdir(p) > > matched_files = glob.glob(pattern) > > if matched_files != []: > > globbed[p] = matched_files > > os.chdir(abs_base) > > os.chdir(cwd) > > return globbed > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "I generally know what I'm doing." -Buster Keaton From kent37 at tds.net Thu Aug 3 19:09:08 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Aug 2006 13:09:08 -0400 Subject: [Tutor] Binary fractions, recommendations? In-Reply-To: References: Message-ID: <44D22DB4.8060507@tds.net> Liam Clarke wrote: > Problem is; I can't bitshift on floats, so can't test. Can't bitshift > on floats in C either. Does anyone know how I could work on a binary > representation of a float? Any language at all, I'm desperate... In C you can certainly get access to the binary representation of a float as bytes. My C is really rusty but something like float x = 1.3; char* p = &x; will give you a pointer to the binary representation of x. You can do something similar with the struct module in Python; struct.pack() will give you a byte string containing the representation of a float. Kent From arbaro at gmail.com Thu Aug 3 19:28:42 2006 From: arbaro at gmail.com (arbaro arbaro) Date: Thu, 3 Aug 2006 19:28:42 +0200 Subject: [Tutor] regular expression Message-ID: <802dc1e0608031028h7cf4e84oe2454214c6399efa@mail.gmail.com> Hello, I'm trying to mount an usb device from python under linux. To do so, I read the kernel log /proc/kmsg and watch for something like: "<6> /dev/scsi/host3/bus0/target0/lun0/:<7>usb-storage: device scan complete" When I compile a regular expression like: "r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')" It is found. But I don't want the <\d+>\s or '<6> ' in front of the path, so I tried: "r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')" But this way the usb device path it is not found. So what i'm trying to do is: - find the usb device path from the kernel log with the regular expression. - Determine the start and end positions of the match (and add /disc or /part1 to the match). - And use that to mount the usb stick on /mnt/usb -> mount -t auto match /mnt/usb If anyone can see what i'm doing wrong, please tell me, because I don't understand it anymore. Thanks. Below is the code: # \d+ = 1 or more digits # \s = an empty space import re def findusbdevice(): ''' Returns path of usb device ''' # I did a 'cat /proc/kmsg /log/kmsg' to be able to read the kernel message. # Somehow I can't read /proc/kmsg directly. kmsg = open('/log/kmsg', 'r') r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+') #r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+') for line in kmsg: if 'usb-storage' in line and r.match(line): print 'Success', line -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060803/f505e592/attachment.html From jeffpeery at yahoo.com Thu Aug 3 19:38:22 2006 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu, 3 Aug 2006 10:38:22 -0700 (PDT) Subject: [Tutor] python processing of web html forms Message-ID: <20060803173822.3453.qmail@web30508.mail.mud.yahoo.com> Hello, I want to use python to process information input into a HTML form on my website. how is this typically performed? I saw cherrypy and also quixote for web python stuff... I have no experience with python on the web. Thanks. jeff --------------------------------- Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1?/min. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060803/f8990b3e/attachment-0001.html From kent37 at tds.net Thu Aug 3 19:46:55 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Aug 2006 13:46:55 -0400 Subject: [Tutor] regular expression In-Reply-To: <802dc1e0608031028h7cf4e84oe2454214c6399efa@mail.gmail.com> References: <802dc1e0608031028h7cf4e84oe2454214c6399efa@mail.gmail.com> Message-ID: <44D2368F.10706@tds.net> arbaro arbaro wrote: > Hello, > > I'm trying to mount an usb device from python under linux. > To do so, I read the kernel log /proc/kmsg and watch for something like: > "<6> /dev/scsi/host3/bus0/target0/lun0/:<7>usb-storage: device scan > complete" > > When I compile a regular expression like: > "r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')" You should use raw strings for regular expressions that contain \ characters. > It is found. But I don't want the <\d+>\s or '<6> ' in front of the > path, so I tried: > "r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')" > But this way the usb device path it is not found. You are using re.match(), which just looks for a match at the start of the string. Try using re.search() instead. http://docs.python.org/lib/matching-searching.html Kent > > So what i'm trying to do is: > - find the usb device path from the kernel log with the regular > expression. > - Determine the start and end positions of the match (and add /disc or > /part1 to the match). > - And use that to mount the usb stick on /mnt/usb -> mount -t auto > match /mnt/usb > > If anyone can see what i'm doing wrong, please tell me, because I > don't understand it anymore. > Thanks. > > Below is the code: > > # \d+ = 1 or more digits > # \s = an empty space > > import re > > def findusbdevice(): > ''' Returns path of usb device ''' > # I did a 'cat /proc/kmsg /log/kmsg' to be able to read the kernel > message. > # Somehow I can't read /proc/kmsg directly. > kmsg = open('/log/kmsg', 'r') > r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+') > #r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+') > for line in kmsg: > if 'usb-storage' in line and r.match(line): > print 'Success', line > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Thu Aug 3 19:48:33 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 3 Aug 2006 18:48:33 +0100 Subject: [Tutor] critique my script! References: <20060803153346.17327.qmail@web51614.mail.yahoo.com> Message-ID: <000301c6b725$0a453ae0$0201a8c0@XPpro> >I didn't know I could place the glob in the os.walk > traversal. Could you give me an example of how to do > this? I'm not sure why you see a problem. A simplified form of your code is like this: for root,dirs,files in os.walk(abs_base): for name in dirs: path = os.path.join(root, name) path_list.append(path) So you create the path list here for p in path_list: os.chdir(p) matched_files = glob.glob(pattern) then you iterate over it applying glob. Why not combine the lops like: for root,dirs,files in os.walk(abs_base): for name in dirs: path = os.path.join(root, name) os.chdir(path) matched_files = glob.glob(pattern) Doesn't that do the same thing - or am I missing something? Alan G. > --- Alan Gauld wrote: > >> >I created a function that takes a pattern and a >> base >> > path and then uses os.walk and glob to traverse >> > directories starting from the base path and place >> > files that match the glob pattern in a dictionary. >> >> I'm not sure why you are traversing the paths a >> second time. >> Why not just apply glob within the os.walk >> traversal? >> After all you are putting the path into the path >> list, then >> iterating over that list later, why not just apply >> glob the >> first time around? >> >> > #!/usr/bin/python >> > >> > import os, os.path, glob >> > >> > def glob_files(pattern, base = '.'): >> > path_list = [] >> > abs_base = os.path.abspath(base) >> > path_list.append(abs_base) >> > for root,dirs,files in os.walk(abs_base): >> > for name in dirs: >> > path = os.path.join(root, name) >> > #print path >> > path_list.append(path) >> > globbed = {} >> > cwd = os.getcwd() >> > for p in path_list: >> > os.chdir(p) >> > matched_files = glob.glob(pattern) >> > if matched_files != []: >> > globbed[p] = matched_files >> > os.chdir(abs_base) >> > os.chdir(cwd) >> > return globbed >> >> Alan Gauld >> Author of the Learn to Program web site >> http://www.freenetpages.co.uk/hp/alan.gauld >> > > > "I'm the last person to pretend that I'm a radio. I'd rather go out > and be a color television set." > -David Bowie > > "Who dares wins" > -British military motto > > "I generally know what I'm doing." > -Buster Keaton From Mike.Hansen at atmel.com Thu Aug 3 20:07:40 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 3 Aug 2006 12:07:40 -0600 Subject: [Tutor] python processing of web html forms Message-ID: <57B026980605A64F9B23484C5659E32E254E64@poccso.US.ad.atmel.com> ______________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Jeff Peery Sent: Thursday, August 03, 2006 11:38 AM To: tutor at python.org Subject: [Tutor] python processing of web html forms Hello, I want to use python to process information input into a HTML form on my website. how is this typically performed? I saw cherrypy and also quixote for web python stuff... I have no experience with python on the web. Thanks. jeff ________________________________ You might want to take a look at the cgi module. Devshed has an article on getting started with it. http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/ IMO, I think if you want to do web stuff, you should learn the basics first(cgi), then move on to cherrypy, quixote, django, turbo gears... Mike From K.Weinert at gmx.net Thu Aug 3 21:35:57 2006 From: K.Weinert at gmx.net (K.Weinert at gmx.net) Date: Thu, 03 Aug 2006 21:35:57 +0200 Subject: [Tutor] File like object for Windows registry Message-ID: <20060803193557.259320@gmx.net> Hello! My app should run on debian and windows platforms. For storing the configuration data, I use the ConfigParser module. What I find difficult is to determine a place for my configuration file. On debian, it is simply os.path.join(os.path.expanduser("~")),"myconfig") but what am I supposed to do on Windows? I think a clean solution would be to create a file-like object that reads and writes to the registry, is it? Kind regards, Karsten. -- "Feel free" ? 10 GB Mailbox, 100 FreeSMS/Monat ... Jetzt GMX TopMail testen: http://www.gmx.net/de/go/topmail From lkvam at venix.com Thu Aug 3 20:07:52 2006 From: lkvam at venix.com (Lloyd Kvam) Date: Thu, 03 Aug 2006 14:07:52 -0400 Subject: [Tutor] python processing of web html forms In-Reply-To: <20060803173822.3453.qmail@web30508.mail.mud.yahoo.com> References: <20060803173822.3453.qmail@web30508.mail.mud.yahoo.com> Message-ID: <1154628472.28304.569.camel@www.venix.com> On Thu, 2006-08-03 at 10:38 -0700, Jeff Peery wrote: > Hello, I want to use python to process information input into a HTML > form on my website. how is this typically performed? I saw cherrypy > and also quixote for web python stuff... I have no experience with > python on the web. Thanks. TurboGears provides a very nice tutorial. http://www.turbogears.org/docs/wiki20/ That should help get you started. > > jeff > > > > ______________________________________________________________________ > Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great > rates starting at 1?/min. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 From arbaro at gmail.com Thu Aug 3 22:16:38 2006 From: arbaro at gmail.com (arbaro arbaro) Date: Thu, 3 Aug 2006 22:16:38 +0200 Subject: [Tutor] regular expression In-Reply-To: <802dc1e0608031028h7cf4e84oe2454214c6399efa@mail.gmail.com> References: <802dc1e0608031028h7cf4e84oe2454214c6399efa@mail.gmail.com> Message-ID: <802dc1e0608031316n7c48f462n5f1bb847603b9f5f@mail.gmail.com> Hello, Im just answering my own email, since I just found out what my error was. >From a regular expression howto: http://www.amk.ca/python/howto/regex/regex.html The match() function only checks if the RE matches at the beginning of the string while search() will scan forward through the string for a match. It's important to keep this distinction in mind. Remember, match() will only report a successful match which will start at 0; if the match wouldn't start at zero, match() will not report it. That was exactly my problem. Replacing r.match(line) for r.search(line) solved it. Sorry for having bothered you prematurely. On 8/3/06, arbaro arbaro wrote: > > Hello, > > I'm trying to mount an usb device from python under linux. > To do so, I read the kernel log /proc/kmsg and watch for something like: > "<6> /dev/scsi/host3/bus0/target0/lun0/:<7>usb-storage: device scan complete" > > When I compile a regular expression like: > "r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')" > It is found. But I don't want the <\d+>\s or '<6> ' in front of the path, so I tried: > "r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+')" > But this way the usb device path it is not found. > > So what i'm trying to do is: > - find the usb device path from the kernel log with the regular expression. > - Determine the start and end positions of the match (and add /disc or /part1 to the match). > - And use that to mount the usb stick on /mnt/usb -> mount -t auto match /mnt/usb > > If anyone can see what i'm doing wrong, please tell me, because I don't understand it anymore. > Thanks. > > Below is the code: > > # \d+ = 1 or more digits > # \s = an empty space > > import re > > def findusbdevice(): > ''' Returns path of usb device ''' > # I did a 'cat /proc/kmsg /log/kmsg' to be able to read the kernel message. > # Somehow I can't read /proc/kmsg directly. > kmsg = open('/log/kmsg', 'r') > r = re.compile('/dev/scsi/host\d+/bus\d+/target\d+/lun\d+') > #r = re.compile('<\d+>\s/dev/scsi/host\d+/bus\d+/target\d+/lun\d+') > for line in kmsg: > if 'usb-storage' in line and r.match(line): > print 'Success', line > From h.finucane at gmail.com Thu Aug 3 22:37:13 2006 From: h.finucane at gmail.com (Henry Finucane) Date: Thu, 3 Aug 2006 13:37:13 -0700 Subject: [Tutor] File like object for Windows registry In-Reply-To: <20060803193557.259320@gmx.net> References: <20060803193557.259320@gmx.net> Message-ID: On 8/3/06, K.Weinert at gmx.net wrote: > Hello! > > My app should run on debian and windows platforms. For storing the configuration data, I use the ConfigParser module. > > What I find difficult is to determine a place for my configuration file. On debian, it is simply > > os.path.join(os.path.expanduser("~")),"myconfig") > > but what am I supposed to do on Windows? I think a clean solution would be to create a file-like object that reads and writes to the registry, is it? You might be able to do that, I don't know much about win32 programming, but I believe a better solution is to use the built-in windows variables. %APPDATA% is where you should store user-specific application data (and even Microsoft is starting to store XML configuration files there), and it's an easy variable to get. >>> import os >>> os.environ["APPDATA"] 'C:\\Documents and Settings\\UserName\\Application Data' That should function just fine as a home directory replacement. > Kind regards, > Karsten. > -- > > > "Feel free" ? 10 GB Mailbox, 100 FreeSMS/Monat ... > Jetzt GMX TopMail testen: http://www.gmx.net/de/go/topmail > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- --H.F. My penguin is bigger than yours, mister... From andre.roberge at gmail.com Thu Aug 3 22:42:41 2006 From: andre.roberge at gmail.com (Andre Roberge) Date: Thu, 3 Aug 2006 17:42:41 -0300 Subject: [Tutor] File like object for Windows registry In-Reply-To: References: <20060803193557.259320@gmx.net> Message-ID: <7528bcdd0608031342l9a38186je120f0a569f9eabe@mail.gmail.com> On 8/3/06, Henry Finucane wrote: > On 8/3/06, K.Weinert at gmx.net wrote: > > Hello! > > > > My app should run on debian and windows platforms. For storing the configuration data, I use the ConfigParser module. > > > > What I find difficult is to determine a place for my configuration file. On debian, it is simply > > > > os.path.join(os.path.expanduser("~")),"myconfig") This works on Windows as well. I just tried it :-) > > > > but what am I supposed to do on Windows? I think a clean solution would be to create a file-like object that reads and writes to the registry, is it? Messing with the registry is (imo) a bad idea. > > You might be able to do that, I don't know much about win32 > programming, but I believe a better solution is to use the built-in > windows variables. %APPDATA% is where you should store user-specific > application data (and even Microsoft is starting to store XML > configuration files there), and it's an easy variable to get. > > >>> import os > >>> os.environ["APPDATA"] > 'C:\\Documents and Settings\\UserName\\Application Data' > > That should function just fine as a home directory replacement. > ... Andr? From h.finucane at gmail.com Thu Aug 3 22:54:40 2006 From: h.finucane at gmail.com (Henry Finucane) Date: Thu, 3 Aug 2006 13:54:40 -0700 Subject: [Tutor] File like object for Windows registry In-Reply-To: <7528bcdd0608031342l9a38186je120f0a569f9eabe@mail.gmail.com> References: <20060803193557.259320@gmx.net> <7528bcdd0608031342l9a38186je120f0a569f9eabe@mail.gmail.com> Message-ID: On 8/3/06, Andre Roberge wrote: > On 8/3/06, Henry Finucane wrote: > > On 8/3/06, K.Weinert at gmx.net wrote: > > > Hello! > > > > > > My app should run on debian and windows platforms. For storing the configuration data, I use the ConfigParser module. > > > > > > What I find difficult is to determine a place for my configuration file. On debian, it is simply > > > > > > os.path.join(os.path.expanduser("~")),"myconfig") > > This works on Windows as well. I just tried it :-) Doh. Always try the simple stuff first :P. > > > > > > but what am I supposed to do on Windows? I think a clean solution would be to create a file-like object that reads and writes to the registry, is it? > > Messing with the registry is (imo) a bad idea. > > > > > You might be able to do that, I don't know much about win32 > > programming, but I believe a better solution is to use the built-in > > windows variables. %APPDATA% is where you should store user-specific > > application data (and even Microsoft is starting to store XML > > configuration files there), and it's an easy variable to get. > > > > >>> import os > > >>> os.environ["APPDATA"] > > 'C:\\Documents and Settings\\UserName\\Application Data' > > > > That should function just fine as a home directory replacement. > > > ... > > Andr? > -- --H.F. My penguin is bigger than yours, mister... From alan.gauld at freenet.co.uk Thu Aug 3 23:37:33 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 3 Aug 2006 22:37:33 +0100 Subject: [Tutor] File like object for Windows registry References: <20060803193557.259320@gmx.net> Message-ID: <002901c6b745$080d17a0$0201a8c0@XPpro> > My app should run on debian and windows platforms. Hard lines :-( > For storing the configuration data, I use the ConfigParser module. > What I find difficult is to determine a place for my configuration > file. Config parser basically produces an .in file. The rules that Windows uses to locate .ini files vary according to Windows version. If you can assume you only have to deal with Win2K and XP then things are a bit easier since there is a recommended location and indeed users have the concept of a home directory - even the $HOME environment variable works. However traditionally ini files were stored in one of 1) the Windows directory (%WINDIR%) or 2) the application home directory. 3) The C:\ root directory - but this is now strongly discouraged If you want to have application level ini files as well as per user configurations those are still the preferred locations for the global files. Between Windows 95 and Windows 2000 the Registry was being pushed as the best place for config data but as Registry performance and corruption problems increase .ini files are coming back into favour. To summarise. If you want to just have a per user config file just store it in the users data folder. If you also have a global ini file then I recommend putting it in the app install folder. If the app is cross platform I'd advise keeping well clear of the registry, but if you must use it I'd favour using the WSH objects rather than the Win32 API calls to access the Registry - although it does add another dependency to the app. HTH, Alan G. From cspears2002 at yahoo.com Fri Aug 4 00:37:49 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 3 Aug 2006 15:37:49 -0700 (PDT) Subject: [Tutor] critique my script! In-Reply-To: <000301c6b725$0a453ae0$0201a8c0@XPpro> Message-ID: <20060803223749.30495.qmail@web51602.mail.yahoo.com> I rewrote my code with Alan's suggestions in mind. #!/usr/bin/python import os, os.path, glob def glob_files(pattern, base_path = '.'): abs_base = os.path.abspath(base_path) #path_list = [] #path_list.append(abs_base) globbed_dict = {} cwd = os.getcwd() for root,dirs,files in os.walk(abs_base): for name in dirs: path = os.path.join(root, name) print path os.chdir(path) matched_files = glob.glob(pattern) #print matched_files if matched_files != []: globbed_dict[path] = matched_files os.chdir(abs_base) os.chdir(cwd) return globbed_dict if __name__ == "__main__": base_path = raw_input("Enter a base path: ") pattern = raw_input("Enter a glob pattern: ") str(base_path) str(pattern) globbed_dict = glob_files(pattern, base_path) print globbed_dict However, the code still doesn't do exactly what I want. $ ./~/chris_python 126> ./find_items_01.py Enter a base path: ./LearningToProgram Enter a glob pattern: *.pyc {} Under the LearningToProgram directory is a test directory that doesn't contain any .pyc files, so the script's returned value is correct. However, .pyc files exist in the LearningToProgram directory, and I would like to put those files in the dictionary too. Is there an elegant way to accomplish this? From alan.gauld at freenet.co.uk Fri Aug 4 01:26:41 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 4 Aug 2006 00:26:41 +0100 Subject: [Tutor] critique my script! References: <20060803223749.30495.qmail@web51602.mail.yahoo.com> Message-ID: <000301c6b754$46e386d0$0201a8c0@XPpro> > Under the LearningToProgram directory is a test > directory that doesn't contain any .pyc files, so the > script's returned value is correct. However, .pyc > files exist in the LearningToProgram directory, and I > would like to put those files in the dictionary too. > Is there an elegant way to accomplish this? You just need to apply glob at the root level before starting to walk the tree. Because your inner loop looks at the dirs list you only glob the subdirectories, you need to glob the top level one too. Alan G. From python at venix.com Fri Aug 4 01:49:42 2006 From: python at venix.com (Python) Date: Thu, 03 Aug 2006 19:49:42 -0400 Subject: [Tutor] critique my script! In-Reply-To: <20060803223749.30495.qmail@web51602.mail.yahoo.com> References: <20060803223749.30495.qmail@web51602.mail.yahoo.com> Message-ID: <1154648982.28304.622.camel@www.venix.com> (Sorry about accidental posting before I had finished editing.) On Thu, 2006-08-03 at 15:37 -0700, Christopher Spears wrote: > I rewrote my code with Alan's suggestions in mind. > > #!/usr/bin/python > > import os, os.path, glob > > def glob_files(pattern, base_path = '.'): > abs_base = os.path.abspath(base_path) > #path_list = [] > #path_list.append(abs_base) > globbed_dict = {} > cwd = os.getcwd() > for root,dirs,files in os.walk(abs_base): > for name in dirs: > path = os.path.join(root, name) > print path > os.chdir(path) > matched_files = glob.glob(pattern) > #print matched_files > if matched_files != []: > globbed_dict[path] = matched_files > os.chdir(abs_base) > os.chdir(cwd) > return globbed_dict > > if __name__ == "__main__": > base_path = raw_input("Enter a base path: ") > pattern = raw_input("Enter a glob pattern: ") > > str(base_path) > str(pattern) > > globbed_dict = glob_files(pattern, base_path) > > print globbed_dict > > However, the code still doesn't do exactly what I > want. > > $ ./~/chris_python 126> ./find_items_01.py > Enter a base path: ./LearningToProgram > Enter a glob pattern: *.pyc > {} > > Under the LearningToProgram directory is a test > directory that doesn't contain any .pyc files, so the > script's returned value is correct. However, .pyc > files exist in the LearningToProgram directory, and I > would like to put those files in the dictionary too. > Is there an elegant way to accomplish this? I won't answer for elegance, but you glob the dirs, but do not glob root. Now all of your code is knotted together pretty tightly, so it's hard to make the change. Suppose we have: def dirs(abs_base): # (corrected from earlier accidental posting) yield abs_base for root,dirs,files in os.walk(abs_base): for name in dirs: yield os.path.join(root, name) def globfiles(path,pattern): os.chdir(pattern) return glob.glob(pattern) for path in dirs(abs_base): matched_files = globfiles(path, pattern) if matched_files: globbed_dict[path] = matched_files Hopefully that's a step in the right direction. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From python at venix.com Fri Aug 4 01:31:47 2006 From: python at venix.com (Python) Date: Thu, 03 Aug 2006 19:31:47 -0400 Subject: [Tutor] critique my script! In-Reply-To: <20060803223749.30495.qmail@web51602.mail.yahoo.com> References: <20060803223749.30495.qmail@web51602.mail.yahoo.com> Message-ID: <1154647907.28304.608.camel@www.venix.com> On Thu, 2006-08-03 at 15:37 -0700, Christopher Spears wrote: > I rewrote my code with Alan's suggestions in mind. > > #!/usr/bin/python > > import os, os.path, glob > > def glob_files(pattern, base_path = '.'): > abs_base = os.path.abspath(base_path) > #path_list = [] > #path_list.append(abs_base) > globbed_dict = {} > cwd = os.getcwd() > for root,dirs,files in os.walk(abs_base): > for name in dirs: > path = os.path.join(root, name) > print path > os.chdir(path) > matched_files = glob.glob(pattern) > #print matched_files > if matched_files != []: > globbed_dict[path] = matched_files > os.chdir(abs_base) > os.chdir(cwd) > return globbed_dict > > if __name__ == "__main__": > base_path = raw_input("Enter a base path: ") > pattern = raw_input("Enter a glob pattern: ") > > str(base_path) > str(pattern) > > globbed_dict = glob_files(pattern, base_path) > > print globbed_dict > > However, the code still doesn't do exactly what I > want. > > $ ./~/chris_python 126> ./find_items_01.py > Enter a base path: ./LearningToProgram > Enter a glob pattern: *.pyc > {} > > Under the LearningToProgram directory is a test > directory that doesn't contain any .pyc files, so the > script's returned value is correct. However, .pyc > files exist in the LearningToProgram directory, and I > would like to put those files in the dictionary too. > Is there an elegant way to accomplish this? I won't answer for elegance, but you glob the dirs, but do not glob root. Now all of your code is knotted together pretty tightly, so it's hard to make the change. Suppose we have: def dirs(abs_base): for root,dirs,files in os.walk(abs_base): yield root for name in dirs: yield os.path.join(root, name) def globdir(path,pattern): > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From python at venix.com Fri Aug 4 01:53:06 2006 From: python at venix.com (Python) Date: Thu, 03 Aug 2006 19:53:06 -0400 Subject: [Tutor] critique my script! In-Reply-To: <20060803223749.30495.qmail@web51602.mail.yahoo.com> References: <20060803223749.30495.qmail@web51602.mail.yahoo.com> Message-ID: <1154649186.28304.626.camel@www.venix.com> On Thu, 2006-08-03 at 15:37 -0700, Christopher Spears wrote: (in the os.walk processing) > os.chdir(path) > matched_files = glob.glob(pattern) >From the os.walk documentation Note: If you pass a relative pathname, don't change the current working directory between resumptions of walk(). walk() never changes the current directory, and assumes that its caller doesn't either. Just making sure no one blindly copies this code without understanding that an absolute path is essential. -- Lloyd Kvam Venix Corp From python at venix.com Fri Aug 4 01:56:48 2006 From: python at venix.com (Python) Date: Thu, 03 Aug 2006 19:56:48 -0400 Subject: [Tutor] critique my script! In-Reply-To: <000301c6b754$46e386d0$0201a8c0@XPpro> References: <20060803223749.30495.qmail@web51602.mail.yahoo.com> <000301c6b754$46e386d0$0201a8c0@XPpro> Message-ID: <1154649408.28304.629.camel@www.venix.com> On Fri, 2006-08-04 at 00:26 +0100, Alan Gauld wrote: > > Under the LearningToProgram directory is a test > > directory that doesn't contain any .pyc files, so the > > script's returned value is correct. However, .pyc > > files exist in the LearningToProgram directory, and I > > would like to put those files in the dictionary too. > > Is there an elegant way to accomplish this? > > You just need to apply glob at the root level before starting > to walk the tree. Because your inner loop looks at the dirs > list you only glob the subdirectories, you need to glob the > top level one too. Which of course is all I suggested except with more shuffling than necessary. > > Alan G. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From ml.cyresse at gmail.com Fri Aug 4 04:38:05 2006 From: ml.cyresse at gmail.com (Liam Clarke) Date: Fri, 4 Aug 2006 14:38:05 +1200 Subject: [Tutor] Binary fractions, recommendations? In-Reply-To: <44D22DB4.8060507@tds.net> References: <44D22DB4.8060507@tds.net> Message-ID: Hmmm, and then I could use struct to swing it back... so, I'll be using string slices to model bitshifting then. Always found it quite strange that working mathematically with binary is so hard in programming languages. Even in Scheme, which will happily play with imaginary numbers. Regards, Liam On 8/4/06, Kent Johnson wrote: > Liam Clarke wrote: > > Problem is; I can't bitshift on floats, so can't test. Can't bitshift > > on floats in C either. Does anyone know how I could work on a binary > > representation of a float? Any language at all, I'm desperate... > > In C you can certainly get access to the binary representation of a > float as bytes. My C is really rusty but something like > float x = 1.3; > char* p = &x; > > will give you a pointer to the binary representation of x. You can do > something similar with the struct module in Python; struct.pack() will > give you a byte string containing the representation of a float. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Aug 4 04:39:10 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Aug 2006 22:39:10 -0400 Subject: [Tutor] critique my script! In-Reply-To: <20060803223749.30495.qmail@web51602.mail.yahoo.com> References: <20060803223749.30495.qmail@web51602.mail.yahoo.com> Message-ID: <44D2B34E.2020808@tds.net> Christopher Spears wrote: > I rewrote my code with Alan's suggestions in mind. > > #!/usr/bin/python > > import os, os.path, glob > > def glob_files(pattern, base_path = '.'): > abs_base = os.path.abspath(base_path) > #path_list = [] > #path_list.append(abs_base) > globbed_dict = {} > cwd = os.getcwd() > for root,dirs,files in os.walk(abs_base): > for name in dirs: > path = os.path.join(root, name) > print path > os.chdir(path) > matched_files = glob.glob(pattern) > #print matched_files > if matched_files != []: > globbed_dict[path] = matched_files > os.chdir(abs_base) > os.chdir(cwd) > return globbed_dict > > if __name__ == "__main__": > base_path = raw_input("Enter a base path: ") > pattern = raw_input("Enter a glob pattern: ") > > str(base_path) > str(pattern) > > globbed_dict = glob_files(pattern, base_path) > > print globbed_dict > > However, the code still doesn't do exactly what I > want. > > $ ./~/chris_python 126> ./find_items_01.py > Enter a base path: ./LearningToProgram > Enter a glob pattern: *.pyc > {} > > Under the LearningToProgram directory is a test > directory that doesn't contain any .pyc files, so the > script's returned value is correct. However, .pyc > files exist in the LearningToProgram directory, and I > would like to put those files in the dictionary too. > Is there an elegant way to accomplish this? The base_path directory will never appear in the dirs list from os.walk(). It will be returned as the root directory however. You could modify your program to glob the root directory instead of the list of dirs. Or use fnmatch.fnmatch() or fnmatch.filter(), which I still think is a better solution if you aren't married to glob(): import os, fnmatch def glob_files(pattern, base_path = '.'): abs_base = os.path.abspath(base_path) globbed_dict = {} for root,dirs,files in os.walk(abs_base): matched_files = [ os.path.join(root, name) for name in fnmatch.filter(files, pattern) ] if matched_files: # Note: no need to compare to [] globbed_dict[root] = matched_files return globbed_dict Kent From cspears2002 at yahoo.com Fri Aug 4 06:03:25 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 3 Aug 2006 21:03:25 -0700 (PDT) Subject: [Tutor] critique my script again! Message-ID: <20060804040325.64157.qmail@web51604.mail.yahoo.com> Here is the complete script with documentation: #!/usr/bin/python #This script prompts the user for a path and a glob pattern. #The script firsts looks in the directory denoted by the path #for a matching file. If a match is found, the path and file are added #to a dictionary as a key and value. This process is repeated for all #directories underneath the base directory. Finally, the directories and #their corresponding files are formatted and printed to the screen. #Next step: rework script as GUI using PyGTK. #Created by Chris Spears 7/3/06. #Thanks to tutor at python.org. import os, os.path, glob def create_dict(path, globbed_dict): os.chdir(path) matched_files = glob.glob(pattern) if matched_files != []: globbed_dict[path] = matched_files return globbed_dict def glob_files(pattern, base_path = '.'): abs_base = os.path.abspath(base_path) globbed_dict = {} cwd = os.getcwd() #Check the root directory first globbed_dict = create_dict(abs_base, globbed_dict) #Check other directories for root,dirs,files in os.walk(abs_base): for name in dirs: path = os.path.join(root, name) globbed_dict = create_dict(path, globbed_dict) os.chdir(abs_base) #Make sure the script returns to the user's original directory. os.chdir(cwd) return globbed_dict def print_dict(globbed_dict): paths = globbed_dict.keys() paths.sort() for p in paths: print p,": " file_list = globbed_dict[p] for f in file_list: print "\t",f if __name__ == "__main__": base_path = raw_input("Enter a base path: ") pattern = raw_input("Enter a glob pattern: ") str(base_path) str(pattern) globbed_dict = glob_files(pattern, base_path) print_dict(globbed_dict) From alan.gauld at freenet.co.uk Fri Aug 4 09:30:59 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 4 Aug 2006 08:30:59 +0100 Subject: [Tutor] Binary fractions, recommendations? References: <44D22DB4.8060507@tds.net> Message-ID: <002d01c6b797$ef21eb00$0201a8c0@XPpro> > Always found it quite strange that working mathematically with > binary > is so hard in programming languages. Even in Scheme, which will > happily play with imaginary numbers. I'm not clear on what you want to do. You are working mathematically with binary all the time, in fact that's the reason we get weird results sometimes because its really binary and not decimal that we are manipulating. Working in binary is the default behaviour. >> > Problem is; I can't bitshift on floats, so can't test. Can't >> > bitshift >> > on floats in C either. Nor even in Assembler. And that is because a float is really stored in IEEE representation not in binary. You can bitshift the binary bits but it doesn't do what you expect in that it doesn't multiply or divide the number by powers of 2. But the same is true of decimal numbers represented in compacted reperesentations, you need to convert to a normal number first. > Does anyone know how I could work on a binary > representation of a float? Any language at all, Its the same in all languages; you need to convert the IEE format to a binary format. The simplest way will likely be a string but you can use two integers too. Maybe writing a class? - In fact maybe a class exists if you Google for it... But why? What will be the advantage in having a binary format float? And given the huge amount of memory such a beast vwill consume (the reason we don't store them like that in the first place) will the advantage outweigh the cost? >> In C you can certainly get access to the binary representation of a >> float as bytes. My C is really rusty but something like >> float x = 1.3; >> char* p = &x; That doesn't give you a binary representation of the number just access to the bytes of the IEEE representation. bit shifting that would be pretty pointless IMHO. >> something similar with the struct module in Python; > struct.pack() will give you a byte string containing the > representation of a float. If its only the IEEE representation you want to bit shift then this will be fine. But I'd be really interested in why anyone would want to do that? Alan G. From kent37 at tds.net Fri Aug 4 12:43:22 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Aug 2006 06:43:22 -0400 Subject: [Tutor] critique my script again! In-Reply-To: <20060804040325.64157.qmail@web51604.mail.yahoo.com> References: <20060804040325.64157.qmail@web51604.mail.yahoo.com> Message-ID: <44D324CA.4070307@tds.net> Christopher Spears wrote: > import os, os.path, glob > > def create_dict(path, globbed_dict): > os.chdir(path) > matched_files = glob.glob(pattern) > if matched_files != []: > globbed_dict[path] = matched_files > return globbed_dict > As written create_dict() has the side-effect of changing the working dir, which you correct for in the caller. A better design would be to save and restore the correct dir in create_dict() so callers don't have to know that it has changed. > def glob_files(pattern, base_path = '.'): > abs_base = os.path.abspath(base_path) > globbed_dict = {} > cwd = os.getcwd() > #Check the root directory first > globbed_dict = create_dict(abs_base, globbed_dict) > #Check other directories > for root,dirs,files in os.walk(abs_base): > for name in dirs: > path = os.path.join(root, name) > globbed_dict = create_dict(path, globbed_dict) > os.chdir(abs_base) > #Make sure the script returns to the user's original > directory. > os.chdir(cwd) > return globbed_dict > Rather than special-casing abs_base with its own call to create_dict, I would have the os.walk() loop act on root instead of dirs: for root,dirs,files in os.walk(abs_base): globbed_dict = create_dict(root, globbed_dict) > > def print_dict(globbed_dict): > paths = globbed_dict.keys() > paths.sort() > for p in paths: > Could be written more succinctly as for p in sorted(globbed_dict.keys()): Kent > print p,": " > file_list = globbed_dict[p] > for f in file_list: > print "\t",f > > > if __name__ == "__main__": > base_path = raw_input("Enter a base path: ") > pattern = raw_input("Enter a glob pattern: ") > > str(base_path) > str(pattern) > > globbed_dict = glob_files(pattern, base_path) > > print_dict(globbed_dict) > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kent37 at tds.net Fri Aug 4 12:58:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Aug 2006 06:58:06 -0400 Subject: [Tutor] Binary fractions, recommendations? In-Reply-To: <002d01c6b797$ef21eb00$0201a8c0@XPpro> References: <44D22DB4.8060507@tds.net> <002d01c6b797$ef21eb00$0201a8c0@XPpro> Message-ID: <44D3283E.6030003@tds.net> Alan Gauld wrote: > Does anyone know how I could work on a binary >> representation of a float? Any language at all, >> >>> In C you can certainly get access to the binary representation of a >>> float as bytes. My C is really rusty but something like >>> float x = 1.3; >>> char* p = &x; >>> > > That doesn't give you a binary representation of the > number just access to the bytes of the IEEE representation. > bit shifting that would be pretty pointless IMHO. > I guess it depends on what the OP means by "binary representation of a float". The request is ambiguous. I interpret it as, access to the actual bits of the representation, which the above code will give. Another interpretation is, an ASCII representation of the bits of the number, which seems to be what you mean. Kent From klappnase at freenet.de Fri Aug 4 14:01:23 2006 From: klappnase at freenet.de (Michael Lange) Date: Fri, 04 Aug 2006 12:01:23 -0000 Subject: [Tutor] Listbox selection In-Reply-To: References: Message-ID: <20060210140136.46b7259c.klappnase@freenet.de> Hi Joe, On Thu, 3 Aug 2006 11:12:28 -0700 "Joe Cox" wrote: > I am still having a problem getting my listbox's binded to the radiobuttons. > I am getting closer. > > ###Assign each Radiobutton with its own listbox values, show one selected > button and one listbox### > > > > from Tkinter import * > > root = Tk() > > var = StringVar() > var.set('a') > > { 'Aluminum' : ['Wrought', 'Die cast'], > 'Steel' : ['Low Carbon', 'Medium-high carbon','Alloy'] } > Didn't you want to keep a reference to the dictionary? > > def radio_command(): > if var.get() == 'a': > # button with value 'a' selected > listbox.insert('a') #here I am trying to put the string starting > with 'Steel' in the listbox > elif var.get() == 'b': > # button with value 'b' selected > listbox.insert('b') #here I am trying to put the string starting > with 'Aluminum' in the listbox > > > > radio_a = Radiobutton(root,text="Steel", variable=var, value='a', > command=radio_command).pack() Are you aware that pack() returns None, so you actually assign None to all your radio_* variables; if you want to keep access to the widgets you need to do: radio_a = Radiobutton() radio_a.pack() > radio_b = Radiobutton(root,text="Aluminum", variable=var, value='b', > command=radio_command).pack() > radio_c = Radiobutton(root,text="Cast Iron", variable=var, value='c', > command=radio_command).pack() > radio_d = Radiobutton(root,text="Nickel", variable=var, value='d', > command=radio_command).pack() > radio_e = Radiobutton(root,text="Titaniuim", variable=var, value='e', > command=radio_command).pack() > > > listbox = Listbox(root) > for item in (): > listbox.insert(END, item) The last two lines don't really seem to have much sense, if you want an empty Listbox, just don't insert anything. > listbox.pack(side=LEFT, fill=BOTH) > > root.mainloop() > I am not sure what your question is here, maybe you want to try something like (untested): var = StringVar() var.set('Steel') listbox = Listbox(root) listbox.pack(side=LEFT, fill=BOTH) metals = {'Aluminum' : ['Wrought', 'Die cast'], 'Steel' : ['Low Carbon', 'Medium-high carbon','Alloy'] } def radio_command(): listbox.delete(0, 'end') for m in metals[var.get()]: listbox.insert('end', m) for metal in metals.keys(): # assuming that you don't need to keep references to all buttons Radiobutton(root, text=metal, variable=var, value=metal, command=radio_command).pack() # fill the listbox with initial values radio_command() I hope this helps Michael From matthew.williams at cancer.org.uk Fri Aug 4 14:58:23 2006 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Fri, 04 Aug 2006 13:58:23 +0100 Subject: [Tutor] (*args, **kwargs) Message-ID: <44D3446F.5060902@cancer.org.uk> Dear All, I have learnt to do bits of python, but one of the things I cannot get my head around is the *args, **kwargs syntax. I have tried reading stuff on the web, and I have a copy of the python cookbook (which uses it as a recipe early on) but I still don't understand it. Please could someone explain _very_ slowly? Apologies for the gross stupidity, Matt -- http://acl.icnet.uk/~mw http://adhominem.blogsome.com/ +44 (0)7834 899570 From rabidpoobear at gmail.com Fri Aug 4 15:23:38 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 04 Aug 2006 08:23:38 -0500 Subject: [Tutor] Listbox selection In-Reply-To: <20060210140136.46b7259c.klappnase@freenet.de> References: <20060210140136.46b7259c.klappnase@freenet.de> Message-ID: <44D34A5A.2040706@gmail.com> Michael Lange wrote: > Hi Joe, > [snip post] Fix your date/time please Michael. I don't think it's been February 10th for quite some time :) From jordangreenberg at gmail.com Fri Aug 4 18:38:54 2006 From: jordangreenberg at gmail.com (Jordan Greenberg) Date: Fri, 04 Aug 2006 12:38:54 -0400 Subject: [Tutor] (*args, **kwargs) In-Reply-To: <44D3446F.5060902@cancer.org.uk> References: <44D3446F.5060902@cancer.org.uk> Message-ID: <44D3781E.40204@gmail.com> Matt Williams wrote: > Dear All, > > I have learnt to do bits of python, but one of the things I cannot get > my head around is the *args, **kwargs syntax. > > I have tried reading stuff on the web, and I have a copy of the python > cookbook (which uses it as a recipe early on) but I still don't > understand it. > > Please could someone explain _very_ slowly? > > Apologies for the gross stupidity, > > Matt Basically, *args and **kwargs allows you to collect arguments. Normally, you'd do something like: *args collects any arguments (other then the positional ones) into a list, and **kwargs collects arguments into a dictionary. In [6]: def foo(a, b, c): ...: print a, b, c ...: In [7]: foo(1, 2, 3) 1 2 3 but, say you wanted to make it so it could accept any number of arguments, you could use *args like so: In [4]: def foo(*args): ...: print args ...: for each in args: ...: print each ...: In [5]: foo(1, 2, 3, 4) (1, 2, 3, 4) 1 2 3 4 Notice how all the parameters i passed to foo are collected in the list args. **kwargs collects arguments of the form key=value into a dictionary, like so: In [15]: def foo(**kwargs): ....: print kwargs ....: In [16]: foo(name="Jordan", email="jordangreenberg at gmail.com") {'name': 'Jordan', 'email': 'jordangreenberg at gmail.com'} Your functions can then use the list/dictionary as normal. You can also use these in conjunction with normal positional parameters: In [27]: def foo(a, b, c, *args, **kwargs): ....: print "Positional arguments:" ....: print a, b, c ....: print "Non-positional argument list:" ....: print args ....: for each in args: ....: print each ....: print "Keyword argument list:" ....: print kwargs ....: for key in kwargs.keys(): ....: print "Key: ", key ....: print "Data: ", kwargs[key] ....: In [28]: foo(1, "monkey", 7.5, 10, 11, 12, name="jordan", email="jordangreenberg at gmail.com") Positional arguments: 1 monkey 7.5 Non-positional argument list: (10, 11, 12) 10 11 12 Keyword argument list: {'name': 'jordan', 'email': 'jordangreenberg at gmail.com'} Key: name Data: jordan Key: email Data: jordangreenberg at gmail.com So, to summarize, *args and **kwargs are basically there so you can build your functions so that they can accept a variable number of arguments. We had a thread about this not terribly long ago too, and Kent Johnson had a great explanation (as per usual) so I expect he'll be along shortly with either a link to that thread or a better explanation then mine! Anyway, I hope this helps! -Jordan Greenberg From dyoo at hkn.eecs.berkeley.edu Fri Aug 4 18:40:18 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 4 Aug 2006 09:40:18 -0700 (PDT) Subject: [Tutor] Multiple buttons, One callback (fwd) Message-ID: Hi everyone, Can someone help with Michael's question? Unfortunately, I can't answer it at the moment. Here it is below. (I've stripped off the image attachment.) ---------- Forwarded message ---------- Date: Fri, 4 Aug 2006 09:32:48 -0700 (PDT) From: Michael Cochez To: dyoo at hkn.eecs.berkeley.edu Subject: Multiple buttons, One callback Hi Danny, I've just been reading your reply on this subject at http://mail.python.org/pipermail/tutor/2005-September/041358.html about a year ago. I need something like this but also something more: I'm making an app with an interface that is going to look like in the added image. The "=" buttons are there to copy the contents of the previous lines to the current line. To make the buttons tried a lot of things but the problem is: the number of buttons is always different (one less as the number of day) so it can be none or 20 or something else. So i putted the creation in a for loop. But now the real problem: every button must have its own callback(because the linenumber is different) So my question is: how can I give each button its 'own' callback while only having one (the callbacks are all the same but with another value of linenumber. I added a piece of the code to show what i mean. michaelcochez, PS:excuse me if my English isn't comprehensive, I'm not a native English speaker (I speak Dutch at home) __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- A non-text attachment was scrubbed... Name: Buttons.py Type: text/x-python-script Size: 803 bytes Desc: 2612874683-Buttons.py Url : http://mail.python.org/pipermail/tutor/attachments/20060804/916ceb88/attachment.bin From matthew.williams at cancer.org.uk Fri Aug 4 18:49:12 2006 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Fri, 04 Aug 2006 17:49:12 +0100 Subject: [Tutor] (*args, **kwargs) In-Reply-To: <20060804143807.96438.qmail@web55615.mail.re4.yahoo.com> References: <20060804143807.96438.qmail@web55615.mail.re4.yahoo.com> Message-ID: <44D37A88.1080109@cancer.org.uk> Dear Etienne & Carlos, Thanks so much for that - much clearer! I guess the next question is _how_ do you use it intelligently? I'm interested because I'm trying to put stuff into a db using sqlobject. Obviously one way would be: class MyClass: def __init__(self,**kw) self.property1 = self.kw['property1'] self.property2 = self.kw['property2'] etc.... Does anyone know of an example of this ? Thanks, Matt From anilmrn at yahoo.com Fri Aug 4 19:19:43 2006 From: anilmrn at yahoo.com (anil maran) Date: Fri, 4 Aug 2006 10:19:43 -0700 (PDT) Subject: [Tutor] hi Message-ID: <20060804171943.48837.qmail@web55913.mail.re3.yahoo.com> i have a textbox in a webform i save it in postgres in postgres, it has several newlines and it is properly displayed when i redisplay using cheetah it just displays in a single line and looks ugly is there a simple way to replace newlines with
thanks --------------------------------- Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1?/min. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060804/256be4b5/attachment.html From anilmrn at yahoo.com Fri Aug 4 20:46:36 2006 From: anilmrn at yahoo.com (anil maran) Date: Fri, 4 Aug 2006 11:46:36 -0700 (PDT) Subject: [Tutor] python unicode - help Message-ID: <20060804184636.91744.qmail@web55904.mail.re3.yahoo.com> postgres takes utf8 and ie has different encodings, sometimes western, sometimes utf8 when someone submits data to the form with different, there is an error, how do we determine the encoding, automatically convert to utf8 and then feed to postgres thanks a lot --------------------------------- See the all-new, redesigned Yahoo.com. Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060804/27a04222/attachment.htm From K.Weinert at gmx.net Fri Aug 4 21:05:19 2006 From: K.Weinert at gmx.net (K.Weinert at gmx.net) Date: Fri, 04 Aug 2006 21:05:19 +0200 Subject: [Tutor] Config file directory (was: File like object for Windows registry) Message-ID: <20060804190519.59480@gmx.net> Hello again! Thanks a lot for the helpful hints! I was not aware that expanduser does also work on windows since I am on WinMe... My current approach is this: import platform, os.path def _detect_filepath(): op_sys= platform.system() op_rel= platform.release() if op_sys=="Windows": if op_rel in ["XP"]: return os.path.expanduser("~") else: return os.path.dirname(__file__) # store in package directory elif op_sys=="Linux": return os.path.expanduser("~") else: raise "Unsupported operating system." What do you think? If someone with a win2000 system could tell me the return value of platform.release(), that would be nice. Kind regards, Karsten. ----- Original Message ----- Hello! My app should run on debian and windows platforms. For storing the configuration data, I use the ConfigParser module. What I find difficult is to determine a place for my configuration file. On debian, it is simply os.path.join(os.path.expanduser("~")),"myconfig") but what am I supposed to do on Windows? I think a clean solution would be to create a file-like object that reads and writes to the registry, is it? Kind regards, Karsten. -- Echte DSL-Flatrate dauerhaft f?r 0,- Euro*. Nur noch kurze Zeit! "Feel free" mit GMX DSL: http://www.gmx.net/de/go/dsl From granted14 at yahoo.com Fri Aug 4 16:38:07 2006 From: granted14 at yahoo.com (Etienne Robillard) Date: Fri, 4 Aug 2006 10:38:07 -0400 (EDT) Subject: [Tutor] (*args, **kwargs) In-Reply-To: <44D3446F.5060902@cancer.org.uk> Message-ID: <20060804143807.96438.qmail@web55615.mail.re4.yahoo.com> --- Matt Williams wrote: > Dear All, > > I have learnt to do bits of python, but one of the > things I cannot get > my head around is the *args, **kwargs syntax. > I have tried reading stuff on the web, and I have a > copy of the python > cookbook (which uses it as a recipe early on) but I > still don't > understand it. > > Please could someone explain _very_ slowly? Here's how I've learned it so far: First, there's a convention for 'passing lists as arguments', which is simply to use 'kw' (I prefer that one) or 'kwargs' with a '*' in front of them. But first you need to initialize your data structure properly, thus: kw = {} # a empty dictionnary Then you may want to add stuff inside that kw object: kw['foo'] = "bar" Now consider the following data structure: class Foo: def __init__(self, **kw): # do something with kw objects here. pass Then here's how to pass the whole kw object as a argument list: Foo(**kw) HTH, Etienne > Apologies for the gross stupidity, P.S - There's no such thing here, sorry. :-) > Matt > > > -- > http://acl.icnet.uk/~mw > http://adhominem.blogsome.com/ > +44 (0)7834 899570 -- Etienne Robillard JID: incidah AT njs.netlab.cz YMS/MSN: granted14 AT yahoo.com TEL: +1 514.962.7703 URL: http://www.assembla.com/wiki/show/stn-portfolio/ __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From anilmrn at yahoo.com Fri Aug 4 22:29:42 2006 From: anilmrn at yahoo.com (anil maran) Date: Fri, 4 Aug 2006 13:29:42 -0700 (PDT) Subject: [Tutor] how to use Message-ID: <20060804202942.49301.qmail@web55909.mail.re3.yahoo.com> list comprehensions to return a dictionary thanks a lot --------------------------------- See the all-new, redesigned Yahoo.com. Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060804/977ecbc0/attachment.html From anilmrn at yahoo.com Fri Aug 4 22:32:50 2006 From: anilmrn at yahoo.com (anil maran) Date: Fri, 4 Aug 2006 13:32:50 -0700 (PDT) Subject: [Tutor] can some one explain Message-ID: <20060804203250.49054.qmail@web55908.mail.re3.yahoo.com> decorators and why uses them makes it faster than if then else blocks because of decorators using hash structures i dont understand this please help me --------------------------------- Do you Yahoo!? Next-gen email? Have it all with the all-new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060804/70b87be0/attachment.htm From klappnase at freenet.de Fri Aug 4 23:30:43 2006 From: klappnase at freenet.de (Michael Lange) Date: Fri, 4 Aug 2006 23:30:43 +0200 Subject: [Tutor] Multiple buttons, One callback (fwd) In-Reply-To: References: Message-ID: <20060804233043.69d05361.klappnase@freenet.de> > ---------- Forwarded message ---------- > Date: Fri, 4 Aug 2006 09:32:48 -0700 (PDT) > From: Michael Cochez > To: dyoo at hkn.eecs.berkeley.edu > Subject: Multiple buttons, One callback > > Hi Danny, > I've just been reading your reply on this subject at > http://mail.python.org/pipermail/tutor/2005-September/041358.html > about a year ago. > I need something like this but also something more: > I'm making an app with an interface that is going to > look like in the added image. The "=" buttons are > there to copy the contents of the previous lines to > the current line. > To make the buttons tried a lot of things but the > problem is: the number of buttons is always different > (one less as the number of day) so it can be none or > 20 or something else. So i putted the creation in a > for loop. > But now the real problem: every button must have its > own callback(because the linenumber is different) So > my question is: how can I give each button its 'own' > callback while only having one (the callbacks are all > the same but with another value of linenumber. I added > a piece of the code to show what i mean. I would use a lambda for this, like: def makeidentical(linenumber): print "the linenumber is: %d" % (linenumber) for day in datelist: a=datelist.index(day) if a>0:#on every line exept the first identicalbutton=Button(frame2,text="=",command=lambda : makeidentical(a)) identicalbutton.grid(row=a+2,column=3,sticky=W) frame2widgets.append(identicalbutton) I hope this helps Michael From kent37 at tds.net Sat Aug 5 00:53:11 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Aug 2006 18:53:11 -0400 Subject: [Tutor] hi In-Reply-To: <20060804171943.48837.qmail@web55913.mail.re3.yahoo.com> References: <20060804171943.48837.qmail@web55913.mail.re3.yahoo.com> Message-ID: <44D3CFD7.4080401@tds.net> anil maran wrote: > i have a textbox in a webform > i save it in postgres > in postgres, it has several newlines and it is properly displayed > when i redisplay using cheetah > it just displays in a single line and looks ugly > > is there a simple way to replace newlines with
s.replace('\n', '
') Kent From kent37 at tds.net Sat Aug 5 00:55:27 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Aug 2006 18:55:27 -0400 Subject: [Tutor] python unicode - help In-Reply-To: <20060804184636.91744.qmail@web55904.mail.re3.yahoo.com> References: <20060804184636.91744.qmail@web55904.mail.re3.yahoo.com> Message-ID: <44D3D05F.90604@tds.net> anil maran wrote: > postgres takes utf8 > and ie has different encodings, sometimes western, sometimes utf8 > when someone submits data to the form with different, there is an > error, how do we determine the encoding, automatically convert to utf8 > and then feed to postgres Generally a browser will return form data in the same encoding as the form itself. Set the encoding of the form to utf8 using a meta tag and the browser will return utf8 to you. The meta tag looks like this and goes in the section of your form: Kent From kent37 at tds.net Sat Aug 5 00:56:20 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Aug 2006 18:56:20 -0400 Subject: [Tutor] how to use In-Reply-To: <20060804202942.49301.qmail@web55909.mail.re3.yahoo.com> References: <20060804202942.49301.qmail@web55909.mail.re3.yahoo.com> Message-ID: <44D3D094.3000005@tds.net> anil maran wrote: > list comprehensions to return a dictionary A list comprehension creates a list. Can you explain why you want this? Kent From kent37 at tds.net Sat Aug 5 00:57:29 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Aug 2006 18:57:29 -0400 Subject: [Tutor] can some one explain In-Reply-To: <20060804203250.49054.qmail@web55908.mail.re3.yahoo.com> References: <20060804203250.49054.qmail@web55908.mail.re3.yahoo.com> Message-ID: <44D3D0D9.10507@tds.net> anil maran wrote: > decorators and why uses them makes it faster than if then else blocks > because of decorators using hash structures Do you mean dictionaries rather than decorators? I'm not sure what you are talking about. Kent From kent37 at tds.net Sat Aug 5 01:00:48 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Aug 2006 19:00:48 -0400 Subject: [Tutor] Multiple buttons, One callback (fwd) In-Reply-To: <20060804233043.69d05361.klappnase@freenet.de> References: <20060804233043.69d05361.klappnase@freenet.de> Message-ID: <44D3D1A0.7090304@tds.net> Michael Lange wrote: >> ---------- Forwarded message ---------- >> Date: Fri, 4 Aug 2006 09:32:48 -0700 (PDT) >> From: Michael Cochez >> To: dyoo at hkn.eecs.berkeley.edu >> Subject: Multiple buttons, One callback >> >> Hi Danny, >> I've just been reading your reply on this subject at >> http://mail.python.org/pipermail/tutor/2005-September/041358.html >> about a year ago. >> I need something like this but also something more: >> I'm making an app with an interface that is going to >> look like in the added image. The "=" buttons are >> there to copy the contents of the previous lines to >> the current line. >> To make the buttons tried a lot of things but the >> problem is: the number of buttons is always different >> (one less as the number of day) so it can be none or >> 20 or something else. So i putted the creation in a >> for loop. >> But now the real problem: every button must have its >> own callback(because the linenumber is different) So >> my question is: how can I give each button its 'own' >> callback while only having one (the callbacks are all >> the same but with another value of linenumber. I added >> a piece of the code to show what i mean. >> > > I would use a lambda for this, like: > > > def makeidentical(linenumber): > > print "the linenumber is: %d" % (linenumber) > > > for day in datelist: > > a=datelist.index(day) > > if a>0:#on every line exept the first > > identicalbutton=Button(frame2,text="=",command=lambda : makeidentical(a)) > You have to bind the current value of a in the lambda, otherwise all the callbacks will use the final value of a. One way to do this is with a default argument to the lambda: identicalbutton=Button(frame2,text="=",command=lambda a=a : makeidentical(a)) Another way is with a separate function such as make_callback in the original post. Kent > > From ag at adamgomaa.com Fri Aug 4 19:05:46 2006 From: ag at adamgomaa.com (Adam Gomaa) Date: Fri, 04 Aug 2006 13:05:46 -0400 Subject: [Tutor] IDLE Crashing Message-ID: <44D37E6A.7030409@adamgomaa.com> I'm having trouble with this script. When I run it, it crashes IDLE... which is no fun. :( I'm running Ubuntu 6.06 w/ python 2.4 When I say crash, I mean really _crash_. IDLE stop responding, and I have to killall idle && killall python2.4 before I can restart it (cause python2.4 keeps the TCP port open, I'm assuming) A few notes: list.txt is a text file with 99 lines, each with three letters on it. In ./retrieves, I have 99 files of style [xyz].1.txt. (in addition to list.txt) These are retrieved HTML pages that have the HTML stripped (the actual script is part of a series of scripts to download and format my school's course catalog) It seems to crash on the final iteration of the second for loop, no matter what file it's on at that point (which I've changed by changing x&y in 'for each in filelist[x:y]:' to diffrent values), so I don't think it has anything to do with the actual files it's accessing. ----- #2006 Adam Gomaa, Public Domain listfiles=open('retrieves/list.txt','r') fileread=listfiles.read() ##reads list.txt and assings to fileread filelist=[] filelist=fileread.splitlines() ##each filelist word is 3-letter combo listfiles.close() count,count2=0,0 ##for debugging textstringlist=[] goodlist1=[] for each in filelist[:-50]: ##filelist[x:y] always crashes for any value of x,y print count ##for debugging count=count+1 textfileread=open('retrieves/%s.1.txt' % each,'r') textstring=textfileread.read() textfileread.close() each=each.upper() textstringlist=textstring.split(each)##if I comment out from here... for each2 in textstringlist[:]: #changing to textstringlist[3:-3] still results in crash count2=count2+1 print count2,'is count2' ##this gets quite high, into thousands, before stopping on the final iteration (and crashing) if 'Prerequisites' in each2: goodlist1.append(each2)##to here, it doesn't crash print goodlist1 ------ Anyone have an insight? If someone would like me to I can tar the 99 files & list.txt and post a link. Thanks, From rabidpoobear at gmail.com Sat Aug 5 08:52:51 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 05 Aug 2006 01:52:51 -0500 Subject: [Tutor] IDLE Crashing In-Reply-To: <44D37E6A.7030409@adamgomaa.com> References: <44D37E6A.7030409@adamgomaa.com> Message-ID: <44D44043.7070603@gmail.com> Hi Adam. Adam Gomaa wrote: > I'm having trouble with this script. When I run it, it crashes IDLE... > which is no fun. :( > > I'm running Ubuntu 6.06 w/ python 2.4 > > When I say crash, I mean really _crash_. IDLE stop responding, and I > have to killall idle && killall python2.4 before I can restart it (cause > python2.4 keeps the TCP port open, I'm assuming) > > A few notes: > list.txt is a text file with 99 lines, each with three letters on it. > In ./retrieves, I have 99 files of style [xyz].1.txt. (in addition to > list.txt) These are retrieved HTML pages that have the HTML stripped > (the actual script is part of a series of scripts to download and format > my school's course catalog) > It seems to crash on the final iteration of the second for loop, no > matter what file it's on at that point (which I've changed by changing > x&y in 'for each in filelist[x:y]:' to diffrent values), so I don't > think it has anything to do with the actual files it's accessing. > > ----- > #2006 Adam Gomaa, Public Domain > listfiles=open('retrieves/list.txt','r') > fileread=listfiles.read() ##reads list.txt and assings to fileread > filelist=[] > filelist=fileread.splitlines() ##each filelist word is 3-letter combo > listfiles.close() > count,count2=0,0 ##for debugging > textstringlist=[] > goodlist1=[] > for each in filelist[:-50]: ##filelist[x:y] always crashes for any value > of x,y > print count ##for debugging > count=count+1 > textfileread=open('retrieves/%s.1.txt' % each,'r') > textstring=textfileread.read() > textfileread.close() > each=each.upper() > textstringlist=textstring.split(each)##if I comment out from here... > Did you really mean to split the string on every occurrence of 'each' and not on each newline? > for each2 in textstringlist[:]: #changing to textstringlist[3:-3] > still results in crash > count2=count2+1 > print count2,'is count2' ##this gets quite high, into thousands, > before stopping on the final iteration (and crashing) > if 'Prerequisites' in each2: > goodlist1.append(each2)##to here, it doesn't crash > print goodlist1 > ------ > > Anyone have an insight? > If someone would like me to I can tar the 99 files & list.txt and post a > link. > I can't tell what's wrong without looking at your input files and a more detailed explanation of what you're trying to do. If someone else comes along with help, that's great, but if not, I'll download the tar and see what I can do. > Thanks, > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From jon.papageorgiou at wachovia.com Sat Aug 5 12:05:36 2006 From: jon.papageorgiou at wachovia.com (jon.papageorgiou at wachovia.com) Date: Sat, 5 Aug 2006 06:05:36 -0400 Subject: [Tutor] Jon Papageorgiou is out of the office. Message-ID: I will be Out of the Office Start Date: 8/4/2006. End Date: 8/12/2006. If you are in need of immediate support: Don?t call the Help Desk The Help Desk (590-9000) consultants are not trained to provide Command Center support. While they might attempt to assist you with your problem, the results could compromise the system and require extra repair work for the CC Support group. So who do you call? What do you do now? PICCT vs. RAPS2 When deciding on which application to use, think of it this way. PICCT is your local mechanic shop and RAPS2 is the nearest car dealership. If you have a problem or break with current hardware/software that you use, please open a PICCT ticket by following the steps below. If you are looking for something new, a new workstation or application, please use the RAPS2 request system. Problem/Issue Support (PICCT) A problem issue is an issue that deals with current software/hardware already installed on your workstation. For Normal Issues Please Follow this Procedure: All issues must have a PICCT ticket created. All tickets must be transferred to the "ts-prdsvs-ndso-cmd center support" group. You must include an accurate description of the problem in the ticket. For example, "The pc station is experiencing problems" is not an accurate description. You must make sure your contact info is correct. ***If you are not the location specified in the PICCT ticket contact info, please include where you are currently sitting in the "Brief Description" field. Any incorrect information will lead to a delay in service. Also, please include any pertinent information such as PC name. The more infomation we have the sooner we can fix your problem. For Urgent Issues requiring an "Immediate Response", Please Follow this Procedure: Page the On-Call Support Person via http://esm.wachovia.net/ListOncall.asp Include the Ticket Number Include ?Issue:? - Brief description of the issue (first text line of email) Include ?Contact:? - Person to contact (second text line of email) Include ?Contact #:?- Phone # of person to contact, no 800 numbers (third text line of email) ***Please don?t contact support individuals directly when reporting support related issues. ***Please send all support related correspondence to the ?Command Center Infrastructure Support? Notes ID ***Although we Support the Command Center 7/24/365 we are not staffed 7/24/365, so please be patient for response. New Request for Work (RAPS2) This is a request for new software/hardware that you currently do not have but need, such as workstation or software installs and any changes that are not related to a problem issue. These types of requests would not be problem related but new requests for work. CCIS will provide you with support on these issues. Don?t use Remedy/Capture/PICCT/SM&A Work Request System for ?New Work Requests?. Instead please use the new corporate standard, RAPS2, located @ http://raps2.wachovia.net/raps2 Here are some steps that you might find to be helpful: 1. Go to the website above, and click on "Submit a New Request" 2. Select the plus sign (+) next to "Enterprise System Management (ESM)". 3. Select the green "Command Center Support Team Request". 4. Enter your employee ID # 5. Fill out all the fields with an aqua background. Enter your contact information. (For the Services Requested drop-down list, select "Command Center Support") 6. Click "next" 7. You can add other information if you want, or just click on "Finish!" If you have questions or concerns, please feel free to call us @ 704-427-8179 or email us. ?Command Center Infrastructure Support? Notes ID If your email is not concerning support, I will respond to your message when I return. From kent37 at tds.net Sat Aug 5 13:56:04 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 05 Aug 2006 07:56:04 -0400 Subject: [Tutor] IDLE Crashing In-Reply-To: <44D37E6A.7030409@adamgomaa.com> References: <44D37E6A.7030409@adamgomaa.com> Message-ID: <44D48754.5020804@tds.net> Adam Gomaa wrote: > I'm having trouble with this script. When I run it, it crashes IDLE... > which is no fun. :( > > I'm running Ubuntu 6.06 w/ python 2.4 > > When I say crash, I mean really _crash_. IDLE stop responding, and I > have to killall idle && killall python2.4 before I can restart it (cause > python2.4 keeps the TCP port open, I'm assuming) > > A few notes: > list.txt is a text file with 99 lines, each with three letters on it. > In ./retrieves, I have 99 files of style [xyz].1.txt. (in addition to > list.txt) These are retrieved HTML pages that have the HTML stripped > (the actual script is part of a series of scripts to download and format > my school's course catalog) > It seems to crash on the final iteration of the second for loop, no > matter what file it's on at that point (which I've changed by changing > x&y in 'for each in filelist[x:y]:' to diffrent values), so I don't > think it has anything to do with the actual files it's accessing. > It looks like for some reason there is a problem with printing goodlist1. I can't think of why that would happen. (At first I thought, maybe there are special chars in the data, but printing a list prints the repr() of the list elements, so any special chars should be escaped. I also suspected the length of goodlist1 but it sounds like you have tried with a smaller subset of the data.) A couple of things you could try. If you put these prints before "print goodlist1" it will confirm that you do exit the last loop. # get some idea how much data is in goodlist print len(goodlist1) print len(repr(goodlist1)) Try running your program from the command line instead of inside IDLE. Posting the tar file sounds like a good idea. Kent > ----- > #2006 Adam Gomaa, Public Domain > listfiles=open('retrieves/list.txt','r') > fileread=listfiles.read() ##reads list.txt and assings to fileread > filelist=[] > filelist=fileread.splitlines() ##each filelist word is 3-letter combo > listfiles.close() > count,count2=0,0 ##for debugging > textstringlist=[] > goodlist1=[] > for each in filelist[:-50]: ##filelist[x:y] always crashes for any value > of x,y > print count ##for debugging > count=count+1 > textfileread=open('retrieves/%s.1.txt' % each,'r') > textstring=textfileread.read() > textfileread.close() > each=each.upper() > textstringlist=textstring.split(each)##if I comment out from here... > for each2 in textstringlist[:]: #changing to textstringlist[3:-3] > still results in crash > count2=count2+1 > print count2,'is count2' ##this gets quite high, into thousands, > before stopping on the final iteration (and crashing) > if 'Prerequisites' in each2: > goodlist1.append(each2)##to here, it doesn't crash > print goodlist1 > ------ > > Anyone have an insight? > If someone would like me to I can tar the 99 files & list.txt and post a > link. > Thanks, > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From meiermic at ee.ethz.ch Sat Aug 5 14:08:04 2006 From: meiermic at ee.ethz.ch (Michael Meier) Date: Sat, 05 Aug 2006 14:08:04 +0200 Subject: [Tutor] IDLE Crashing Message-ID: <44D48A24.7040102@ee.ethz.ch> I'm also having trouble when running IDLE under Debian 3.1 (Kernel 2.6.12). I often run into the same problem (IDLE not responding with the only solution to killall idle) as Adam Gomaa just after starting up IDLE and typing in some characters. E.g. I'm starting up IDLE and typing in "import soc" when IDLE suddenly stops responding. This happens while I'm typing and _not_ when executing a line or a bunch of code. This phenomenon is not reproducable, it just happens from time to time. Unfortunately it happens rather often which does not amuse me ;) Does anyone experience the same problem as I? Is there a common solution to Adams and my problems? Thanks, Michael Meier P.S. I'm new to this list... I think its a very interesting and friendly place to be :) From anilmrn at yahoo.com Sat Aug 5 14:55:08 2006 From: anilmrn at yahoo.com (anil maran) Date: Sat, 5 Aug 2006 05:55:08 -0700 (PDT) Subject: [Tutor] how to use In-Reply-To: <44D48232.5000507@tds.net> Message-ID: <20060805125508.96687.qmail@web55907.mail.re3.yahoo.com> the program has several groups i hav a table with titles and contents are in different table content_table each title -> is title_id in content_table so every time i display a group, i have to select title and then select all messagesw with title_id now the problem is, I have to display more than one group in a single page in cheetah, so after displaying the title, i have to now choose the message to display since i have a list of [] of messages i need to index into them so i thought i will make them return a dictionary indexed with URL which is unique thanks > anil maran wrote: > > list comprehensions to return a dictionary > > A list comprehension creates a list. Can you explain why you want > this? > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor --------------------------------- Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060805/08b435be/attachment.html From anilmrn at yahoo.com Sat Aug 5 14:58:27 2006 From: anilmrn at yahoo.com (anil maran) Date: Sat, 5 Aug 2006 05:58:27 -0700 (PDT) Subject: [Tutor] Generic functions In-Reply-To: <20060804203250.49054.qmail@web55908.mail.re3.yahoo.com> Message-ID: <20060805125827.55285.qmail@web55915.mail.re3.yahoo.com> i have a hard time understanding, why these are a better idea than if then else structures . Here is the page, that is not clear thanks a lot First Try at Generic FunctionsWiki:First Try at G??? Edit Goto Help. First Try at Generic Functions ... However, I have long meant to use his generic functions, as I think they seem pretty ... blog.ianbicking.org/first-try-at-generic-functions.html - 41k - Cached - Similar pages Python Buzz Forum - First Try at Generic FunctionsFirst Try at Generic Functions, Posted: Nov 1, 2005 2:42 AM ... Original Post: First Try at Generic Functions Feed Title: Ian Bicking ... www.artima.com/forums/flat.jsp?forum=122&thread=134755 - 17k -Cached - Similar pages """Why are generic functions better than this technique?""" Your technique will not affect any modules that used from jsonify import jsonify to obtain the function, because they won't see your replacement version. Your technique degrades performance linearly with the number of types added, while generic functions use a dispatch tree that uses hash tables, binary search, or other lookup techniques as appropriate. The dispatch tree is automatically balanced to test the most discriminating criteria first. So, adding a new type in the JSON example has virtually no effect on performance of the jsonify() function, versus one extra function-call of overhead added by your approach for each new type. Your technique can only add tests at the highest precedence level, which means that if there's any overlap in conditions between what you are adding, and what exists, you will need to code a more complex "if" rule, and you will need to know what other existing rules overlap. (Which means that only linear extension is possible, and that some tests will be repeated unnecessarily.) Your technique cannot take advantage of any overlap in the conditions being tested. For example, the various isinstance() calls in your version repeatedly walk the object's class' __mro__ to see if it contains the target classes. The generic function, however, will do this walk once, no matter how many types are registered, and then call the correct function. Your code is buggy; it should return jsonify_orig(obj). :) In other words, generic functions are far superior to monkeypatching for creating an extensible operation, which is why the Python standard library uses a simple form of them for things like copying and pickling. However, the RuleDispatch generic function implementation supports automating the registration process and lookup tables for simple functions (using @dispatch.on) and allows for building dispatch trees on arbitrary computations with full generic functions (using @dispatch.generic). --------------------------------- Groups are talking. We´re listening. Check out the handy changes to Yahoo! Groups. --------------------------------- Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060805/0c9a26a3/attachment.htm From kent37 at tds.net Sat Aug 5 15:04:05 2006 From: kent37 at tds.net (Kent Johnson) Date: Sat, 05 Aug 2006 09:04:05 -0400 Subject: [Tutor] how to use In-Reply-To: <20060805125508.96687.qmail@web55907.mail.re3.yahoo.com> References: <20060805125508.96687.qmail@web55907.mail.re3.yahoo.com> Message-ID: <44D49745.2030308@tds.net> I still don't understand what you are trying to do. Can you post a short example of the data you have and the dictionary you would like to create from it? Kent anil maran wrote: > the program has several groups > i hav a table with titles > and contents are in different table content_table > > each title -> is title_id in content_table > > so every time i display a group, i have to select title and then > select all messagesw with title_id > > now the problem is, I have to display more than one group in a single > page in cheetah, > > so after displaying the title, i have to now choose the message to > display > > since i have a list of [] of messages > > i need to index into them > so i thought i will make them return a dictionary indexed with URL > which is unique > > thanks > > > anil maran wrote: > > > list comprehensions to return a dictionary > > > > A list comprehension creates a list. Can you explain why you want > > this? > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > ------------------------------------------------------------------------ > Yahoo! Messenger with Voice. Make PC-to-Phone Calls > > to the US (and 30+ countries) for 2?/min or less. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ismaelgf at adinet.com.uy Sat Aug 5 19:25:18 2006 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sat, 05 Aug 2006 14:25:18 -0300 Subject: [Tutor] IDLE Crashing In-Reply-To: <44D48754.5020804@tds.net> References: <44D37E6A.7030409@adamgomaa.com> <44D48754.5020804@tds.net> Message-ID: <44D4D47E.20209@adinet.com.uy> Kent Johnson escribi?: > Adam Gomaa wrote: > >> I'm having trouble with this script. When I run it, it crashes IDLE... >> which is no fun. :( >> >> I'm running Ubuntu 6.06 w/ python 2.4 >> >> When I say crash, I mean really _crash_. IDLE stop responding, and I >> have to killall idle && killall python2.4 before I can restart it (cause >> python2.4 keeps the TCP port open, I'm assuming) >> >> A few notes: >> list.txt is a text file with 99 lines, each with three letters on it. >> In ./retrieves, I have 99 files of style [xyz].1.txt. (in addition to >> list.txt) These are retrieved HTML pages that have the HTML stripped >> (the actual script is part of a series of scripts to download and format >> my school's course catalog) >> It seems to crash on the final iteration of the second for loop, no >> matter what file it's on at that point (which I've changed by changing >> x&y in 'for each in filelist[x:y]:' to diffrent values), so I don't >> think it has anything to do with the actual files it's accessing. >> >> > It looks like for some reason there is a problem with printing > goodlist1. I can't think of why that would happen. (At first I thought, > maybe there are special chars in the data, but printing a list prints > the repr() of the list elements, so any special chars should be escaped. > I also suspected the length of goodlist1 but it sounds like you have > tried with a smaller subset of the data.) > IDLE becomes **very** unresponsive when printing long lists/strings. Great doses of patience and a good processor usually let you live through (Idle uses 100%, you have to take out of view the long text to make it become responsive again). At least, this happens on Windows (maybe other platforms don't have this problem?). I get this a lot when working with long HTML. There must be something wrong in the way IDLE prints long strings... Ismael From ag at adamgomaa.com Sat Aug 5 20:13:10 2006 From: ag at adamgomaa.com (Adam Gomaa) Date: Sat, 05 Aug 2006 14:13:10 -0400 Subject: [Tutor] IDLE Crashing In-Reply-To: <44D4D47E.20209@adinet.com.uy> References: <44D37E6A.7030409@adamgomaa.com> <44D48754.5020804@tds.net> <44D4D47E.20209@adinet.com.uy> Message-ID: <44D4DFB6.70802@adamgomaa.com> > IDLE becomes **very** unresponsive when printing long lists/strings. > Great doses of patience and a good processor usually let you live > through (Idle uses 100%, you have to take out of view the long text to > make it become responsive again). At least, this happens on Windows > (maybe other platforms don't have this problem?). I get this a lot when > working with long HTML. > There must be something wrong in the way IDLE prints long strings... > > Ismael > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Yes, as it turns out this was the issue. I entered the script line-by-line, and it finished the loops just fine- but at the 'print goodlist1' line, it froze. (it has to print about 1300 entries) I'm rewriting the script so it writes the list to an external file within the loop, so I won't have to deal with such huge lists inside idle. Thanks for everyone's help! Adam From josipl2000 at yahoo.com Sat Aug 5 19:11:48 2006 From: josipl2000 at yahoo.com (josip) Date: Sat, 5 Aug 2006 10:11:48 -0700 (PDT) Subject: [Tutor] forum Message-ID: <20060805171148.15741.qmail@web60819.mail.yahoo.com> look at this www.python-forum.org --------------------------------- Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1?/min. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060805/1a9805f0/attachment.html From john at fouhy.net Sun Aug 6 01:20:29 2006 From: john at fouhy.net (John Fouhy) Date: Sun, 6 Aug 2006 11:20:29 +1200 Subject: [Tutor] (*args, **kwargs) In-Reply-To: <44D37A88.1080109@cancer.org.uk> References: <20060804143807.96438.qmail@web55615.mail.re4.yahoo.com> <44D37A88.1080109@cancer.org.uk> Message-ID: <5e58f2e40608051620m53f76603xd9c634f651fdd563@mail.gmail.com> On 05/08/06, Matt Williams wrote: > I guess the next question is _how_ do you use it intelligently? I'm > interested because I'm trying to put stuff into a db using sqlobject. One common place to use it is when you are dealing with inheritance. For example, suppose I'm writing a Tkinter program, and I want to make my own GUI component. I might write: class MyCustomFrame(Tkinter.Frame): def __init__(self, parent, foo, bar, baz=None, **kw): Tkinter.Frame.__init__(self, parent, **kw) # do something with foo, bar, baz; etc. The reason for doing this is that Tkinter objects support all kinds of keyword arguments, and this lets me support them in my custom code without having to explicitely list them all. Of course, I could also set/override some of the Tkinter keyword arguments. eg, I could make a frame with a pink background like this: class PinkFrame(Tkinter.Frame): def __init__(self, parent, **kw): kw['background'] = 'pink' # line 2 Tkinter.Frame.__init__(self, parent, **kw) (note that I can't skip line 2, and replace line 3 with "Tkinter.Frame.__init__(self, parent, background='pink', **kw)" because if kw already contains a value for background, python will get confused and throw an exception..) > class MyClass: > > def __init__(self,**kw) > self.property1 = self.kw['property1'] > self.property2 = self.kw['property2'] > etc.... > > Does anyone know of an example of this ? I'm not sure there's much value in using **kw if you know exactly what keyword arguments you're expecting. Although you can be a bit fancy, eg: def __init__(self, **kw): for key in **kw: setattr(self, key, kw[key]) But you run the risk of writing obscure code that's hard to follow.. If you were implementing the range() function, you would use *args. Perhaps something like this: def range(*args): if len(args) == 1: return _range(0, args[0], 1) elif len(args) == 2: return _range(args[0], args[1], 1) else: return _range(args[0], args[1], args[2]) # could replace this with: return _range(*args) def _range(start, stop, step): # etc HTH! -- John. From john at fouhy.net Sun Aug 6 01:22:32 2006 From: john at fouhy.net (John Fouhy) Date: Sun, 6 Aug 2006 11:22:32 +1200 Subject: [Tutor] how to use In-Reply-To: <20060804202942.49301.qmail@web55909.mail.re3.yahoo.com> References: <20060804202942.49301.qmail@web55909.mail.re3.yahoo.com> Message-ID: <5e58f2e40608051622q1181fffle548ce30d86fffe3@mail.gmail.com> On 05/08/06, anil maran wrote: > list comprehensions to return a dictionary Well, hyou can use the dict function. eg: dict((x, x**x) for x in range(10)) -- John. From brian at daviesinc.com Sun Aug 6 02:22:06 2006 From: brian at daviesinc.com (Brian Gustin) Date: Sat, 05 Aug 2006 20:22:06 -0400 Subject: [Tutor] forum In-Reply-To: <20060805171148.15741.qmail@web60819.mail.yahoo.com> References: <20060805171148.15741.qmail@web60819.mail.yahoo.com> Message-ID: <44D5362E.8080301@daviesinc.com> Signed up, but it never send me the confirmation email (yes, I used a valid email address) . It's been 2 hours, and still no email. How the HECK does one contact the forum admin to ask them to activate my account? I signed up with support at phplogix.com Grrr.. I really hate forums that have admins that dont post contact information or provide some way to contact them when there's a registration issue. :( josip wrote: > look at this > www.python-forum.org > > ------------------------------------------------------------------------ > Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great > rates starting at 1?/min. !DSPAM:44d500e691801941725006! > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > !DSPAM:44d500e691801941725006! > From gwhjr at cox.net Sun Aug 6 03:44:26 2006 From: gwhjr at cox.net (Grady Henry) Date: Sat, 5 Aug 2006 18:44:26 -0700 Subject: [Tutor] This will run on Outlook but not Outlook Express Message-ID: <000701c6b8f9$d9d329e0$8b4a6244@valued61da873e> The following script will run on Microsoft Outlook but not on Outlook Express: from win32com.client import Dispatch s=Dispatch("Mapi.Session") s.Logon() newMsg = s.Outbox.Messages.Add("Hi from Python", "Hello") recip = newMsg.Recipients.Add("Greg Hart", "SMTP:gwhjr at rock.com") newMsg.Send() s.DeliverNow() I was wondering if I could write a script that would run on both Outlook and Outlook Express. Can anybody help? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060805/7fcdb528/attachment.htm From anilmrn at yahoo.com Sun Aug 6 08:48:39 2006 From: anilmrn at yahoo.com (anil maran) Date: Sat, 5 Aug 2006 23:48:39 -0700 (PDT) Subject: [Tutor] help regarding forms... Message-ID: <20060806064839.11558.qmail@web55902.mail.re3.yahoo.com>
i did by mistake and i got an empty page http://localhost/newtodo?category= can one of you guys explain what this is and tell me if this can be usefully used like http://groups.google.com/group/webpy/post?_done=%2Fgroup%2Fwebpy%3F&_... and if Yes how to use this http://localhost/newtodo?category= http://localhost/todo?category="health"&length=10 and how to do the class todo: def GET and class newtodo: def POST: thanks a lot --------------------------------- Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060805/4073090d/attachment.html From anilmrn at yahoo.com Sun Aug 6 08:53:22 2006 From: anilmrn at yahoo.com (anil maran) Date: Sat, 5 Aug 2006 23:53:22 -0700 (PDT) Subject: [Tutor] how to use In-Reply-To: <44D49745.2030308@tds.net> Message-ID: <20060806065322.55820.qmail@web55907.mail.re3.yahoo.com> TABLE RSS TITLES: Greg Reinacker's Weblog and it s url The Design of Software and its url Paul Graham Wingedpig.com - Mark Fletcher's Blog Aaron Swartz: The Weblog BusinessWeek Online -- New Tech in Asia TABLE 2 has all the feedposts for eg., Simple Tips for Longer Living --> What is going on here? --> Nutrition Basics --> I Love the University --> On Losing Weight Digg reddit Where's the Outrage? Around the Corner in a Cafe with Power. What Drives Bloggers? Paul Graham Eats Breakfast (Director's Cut) Being Copied one in bold is pg, rsest is aaron, when i get out contents of blog by select and query sql statements they return lists indexed by numbers and hence it is difficult to map to the original title - i have to do monkeypatching so i want a dictionary indexed by the url http://paulgraham.infogami.com/blog/atom.xml and another element indexed by http://www.aaronsw.com/weblog/index.xml thanks Kent Johnson wrote: I still don't understand what you are trying to do. Can you post a short example of the data you have and the dictionary you would like to create from it? Kent anil maran wrote: > the program has several groups > i hav a table with titles > and contents are in different table content_table > > each title -> is title_id in content_table > > so every time i display a group, i have to select title and then > select all messagesw with title_id > > now the problem is, I have to display more than one group in a single > page in cheetah, > > so after displaying the title, i have to now choose the message to > display > > since i have a list of [] of messages > > i need to index into them > so i thought i will make them return a dictionary indexed with URL > which is unique > > thanks > > > anil maran wrote: > > > list comprehensions to return a dictionary > > > > A list comprehension creates a list. Can you explain why you want > > this? > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > ------------------------------------------------------------------------ > Yahoo! Messenger with Voice. Make PC-to-Phone Calls > > to the US (and 30+ countries) for 2???/min or less. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Do you Yahoo!? Next-gen email? Have it all with the all-new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060805/43bf50d4/attachment.htm From anilmrn at yahoo.com Sun Aug 6 08:54:34 2006 From: anilmrn at yahoo.com (anil maran) Date: Sat, 5 Aug 2006 23:54:34 -0700 (PDT) Subject: [Tutor] how to use In-Reply-To: <5e58f2e40608051622q1181fffle548ce30d86fffe3@mail.gmail.com> Message-ID: <20060806065434.48463.qmail@web55912.mail.re3.yahoo.com> what does x**x) do? 2nd) what is the key for the dictionary, i assume x is the value of the dictionary John Fouhy wrote: On 05/08/06, anil maran wrote: > list comprehensions to return a dictionary Well, hyou can use the dict function. eg: dict((x, x**x) for x in range(10)) -- John. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Groups are talking. We´re listening. Check out the handy changes to Yahoo! Groups. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060805/ad385238/attachment.html From anilmrn at yahoo.com Sun Aug 6 09:58:07 2006 From: anilmrn at yahoo.com (anil maran) Date: Sun, 6 Aug 2006 00:58:07 -0700 (PDT) Subject: [Tutor] error, i m unable to find the error for past 1week, this doesnt work, please help me out Message-ID: <20060806075807.41593.qmail@web55905.mail.re3.yahoo.com> You can override the web.internalerror function to have it to do other interesting things. For example, I have infogami send me an email with the full debugerror traceback whenever there's a crash: olderror = web.internalerror def error(): olderror() import sys, traceback tb = sys.exc_info() text = """From: the bugman To: the bugfixer Subject: bug: %s: %s (%s) Content-Type: multipart/mixed; boundary="----here----" ------here---- Content-Type: text/plain Content-Disposition: inline %s %s ------here---- Content-Type: text/html; name="bug.html" Content-Disposition: attachment; filename="bug.html" """ % (tb[0], tb[1], web.ctx.path, web.ctx.method+' '+web.ctx.home+web.ctx.f ullpath, ''.join(traceback.format_exception(*tb)), text += str(web.djangoerror()) utils.send('... at example.com', '... at example.com', text) web.internalerror = error --------------------------------- Yahoo! Music Unlimited - Access over 1 million songs.Try it free. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060806/c9079525/attachment.htm From anilmrn at yahoo.com Sun Aug 6 10:00:55 2006 From: anilmrn at yahoo.com (anil maran) Date: Sun, 6 Aug 2006 01:00:55 -0700 (PDT) Subject: [Tutor] can you explain string replacement syntax and comma separated statements Message-ID: <20060806080055.3019.qmail@web55901.mail.re3.yahoo.com> text = """From: the bugman To: the bugfixer Subject: bug: %s: %s (%s) Content-Type: multipart/mixed; boundary="----here----" ------here---- Content-Type: text/plain Content-Disposition: inline %s %s ------here---- Content-Type: text/html; name="bug.html" Content-Disposition: attachment; filename="bug.html" """ % (tb[0], tb[1], web.ctx.path, web.ctx.method+' '+web.ctx.home+web.ctx.f ullpath, ''.join(traceback.format_exception(*tb)), text += str(web.djangoerror()) --------------------------------- Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060806/7a85df7a/attachment.html From alan.gauld at freenet.co.uk Sun Aug 6 10:00:48 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 6 Aug 2006 09:00:48 +0100 Subject: [Tutor] This will run on Outlook but not Outlook Express References: <000701c6b8f9$d9d329e0$8b4a6244@valued61da873e> Message-ID: <002801c6b92e$6e5c3a50$0201a8c0@XPpro> > from win32com.client import Dispatch > s=Dispatch("Mapi.Session") I don't think Outlook express uses MAPI. MAPI is a strictly Microsoft protocol and only used in Outlook and a few other clients that try to talk to Exchange servers. Outlook Express is a much more conventional mailtool that talks POP/SMTP (and maybe IMAP?) > I was wondering if I could write a script that would run on > both Outlook and Outlook Express. Trying to use a COM object model for that will be extemely difficult. I'd look at using the standard email tools with Python since both Outlook and OE talk standard internet mail protocols. Alan G. From rfquerin at gmail.com Sun Aug 6 15:52:13 2006 From: rfquerin at gmail.com (Richard Querin) Date: Sun, 6 Aug 2006 09:52:13 -0400 Subject: [Tutor] Raw files and jpeg thumbnail extraction Message-ID: <7d81675b0608060652y2982cd99n6bda808f394e0e24@mail.gmail.com> I am interested in extracting jpeg thumbnails that are stored in my camera's Canon .CR2 raw files. Does anybody know of any python libraries with this kind of functionality? Is dcraw the only way to implement this functionality? I'm writing a simple gui to selectively process raw files into jpegs, but I really would like to pick the photos based on thumbnails. I read somewhere that most digital camera raw files contain jpeg thumbnails that would be much quicker to load than doing an on-the-fly conversion just to get the thumbnails. Can anybody point me in a good direction on this? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060806/bdbd32b1/attachment.htm From alan.gauld at freenet.co.uk Sun Aug 6 17:31:41 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 6 Aug 2006 16:31:41 +0100 Subject: [Tutor] how to use References: <20060806065434.48463.qmail@web55912.mail.re3.yahoo.com> Message-ID: <003201c6b96d$6ae368a0$0201a8c0@XPpro> Hi Anil, Are you reading a tutorial? Most of the questions you are asking should be covered in any standard tutorial. > what does > > x**x) do? Its equivalent to pow(x,x) ie raises x to the power x. > 2nd) what is the key for the dictionary, i assume x is the value of > the dictionary > dict((x, x**x) for x in range(10)) x is the key and x**x is the value. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Aug 6 17:42:19 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 6 Aug 2006 16:42:19 +0100 Subject: [Tutor] can you explain string replacement syntax and commaseparated statements References: <20060806080055.3019.qmail@web55901.mail.re3.yahoo.com> Message-ID: <005001c6b96e$e6fab910$0201a8c0@XPpro> > can you explain string replacement syntax and commaseparated > statements string substitution replaces the 5 %s comvbinations with the 5 values after the % sign A simplied example is: s = "hello %s, welcome to %s" % ('world','python') Your example just uses triple quotes to allow the string to wrap and has more substitutions. The 5 values are also less direct but all yield strings eventually! The comma separated assignment looks like a mistake to me! A simplified form looks like: s = "Hello", s += "world" Which yields a syntax error. Are you sure its not a semi-colon, in which case it just combines the two instructions on a single line. If so its very bad coding style IMHO but is legal. HTH, Alan G. > text = """From: the bugman > To: the bugfixer > Subject: bug: %s: %s (%s) > Content-Type: multipart/mixed; boundary="----here----" > > ------here---- > Content-Type: text/plain > Content-Disposition: inline > > %s > > %s > > ------here---- > Content-Type: text/html; name="bug.html" > Content-Disposition: attachment; filename="bug.html" > > """ % (tb[0], tb[1], web.ctx.path, web.ctx.method+' > '+web.ctx.home+web.ctx.f > ullpath, > ''.join(traceback.format_exception(*tb)), > text += str(web.djangoerror()) > > > > > --------------------------------- > Do you Yahoo!? > Everyone is raving about the all-new Yahoo! Mail Beta. From dyoo at hkn.eecs.berkeley.edu Sun Aug 6 22:17:44 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 6 Aug 2006 13:17:44 -0700 (PDT) Subject: [Tutor] help regarding forms... In-Reply-To: <20060806064839.11558.qmail@web55902.mail.re3.yahoo.com> References: <20060806064839.11558.qmail@web55902.mail.re3.yahoo.com> Message-ID: On Sat, 5 Aug 2006, anil maran wrote: > http://localhost/newtodo?category= > > can one of you guys explain what this is Hi Anil, Are you taking some kind of internet web-development class? You seem to be asking a lot of web-development questions. In the absence of context, I'm not sure what to do other than to point you to the standard RFC on Uniform Resource Locators: http://www.faqs.org/rfcs/rfc1738.html and see if that addresses your question. > class todo: > def GET > > and > class newtodo: > def POST: Have you looked at any Python CGI tutorials yet? http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/ From dyoo at hkn.eecs.berkeley.edu Sun Aug 6 22:27:38 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 6 Aug 2006 13:27:38 -0700 (PDT) Subject: [Tutor] can you explain string replacement syntax and comma separated statements In-Reply-To: <20060806080055.3019.qmail@web55901.mail.re3.yahoo.com> References: <20060806080055.3019.qmail@web55901.mail.re3.yahoo.com> Message-ID: On Sun, 6 Aug 2006, anil maran wrote: > text = """From: the bugman > To: the bugfixer > Subject: bug: %s: %s (%s) > Content-Type: multipart/mixed; boundary="----here----" [text example cut] Hi Anil, Anil, take a look at: http://www.python.org/doc/lib/typesseq-strings.html Does this address your question? On a high-level view of your questions so far: Are you running into problems because you can't find the documentation? Or is the issue that the documentation is unclear? From bob.nienhuis at gmail.com Sun Aug 6 23:56:29 2006 From: bob.nienhuis at gmail.com (Bob Nienhuis) Date: Sun, 6 Aug 2006 14:56:29 -0700 Subject: [Tutor] Community documentation framework? Message-ID: <45109da50608061456v67580f30oc42d1d18453f1226@mail.gmail.com> Have you had the experience of finding a nifty bit of code on the web, trying it out, and then discovering that technique only worked in version X.YY, or requires module Z that is no longer available? Well perhaps we can address this situation. I would like to see an online system that facilitates the collaborative production, cataloging and updating of community documentation. See an article, "Rethinking Community Documentation" by Andy Oram < http://www.onlamp.com/pub/a/onlamp/2006/07/06/rethinking-community-documentation.html >. Features I would like to see: A Wikipedia-like capacity for community update-ability/modifiability of documentation submissions. Database for cataloging available packages, modules, FAQs, How-Tos tutorials, cookbook code fragments etc. Should have capacity for developers to add and others to add to their contributions. Oram suggests a rating system for submissions so users can assess the quality of submissions, and point to parts that need modification or clarification.. Might use TurboGears, Django AJAX or other web framework? I think main Python documentation is great, but there is a lot of stuff out there that isn't documented so well, or needs updating. This project is intended to adress that need. What would you like to see? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060806/a4225c50/attachment.html From Hans.Dushanthakumar at navman.com Mon Aug 7 01:27:35 2006 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Mon, 7 Aug 2006 11:27:35 +1200 Subject: [Tutor] Python for basic web-testing Message-ID: <6054E9239B849044B9544941B2F8DDD9994A80@bnt-nav-akl-exh.navman.bnt.local> Hi, How do I use python for basic web-tasks like inputting data or clicking buttons on web-pages. For eg, how do I enter my username and password and click on the "OK" button on the yahoo mail page? I had a look at the webbrowser module documentation (http://www.python.org/doc/current/lib/module-webbrowser.html), but it doesnt seem to support clicking buttons or sending data. Thanks, Hans -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060807/7a3374fe/attachment.html From python-tutor at v.igoro.us Mon Aug 7 01:44:39 2006 From: python-tutor at v.igoro.us (Dustin J. Mitchell) Date: Sun, 06 Aug 2006 18:44:39 -0500 Subject: [Tutor] Python for basic web-testing In-Reply-To: <6054E9239B849044B9544941B2F8DDD9994A80@bnt-nav-akl-exh.navman.bnt.local> References: <6054E9239B849044B9544941B2F8DDD9994A80@bnt-nav-akl-exh.navman.bnt.local> Message-ID: <44D67EE7.1040207@v.igoro.us> Hans Dushanthakumar wrote: > Hi, > How do I use python for basic web-tasks like inputting data or > clicking buttons on web-pages. For eg, how do I enter my username and > password and click on the "OK" button on the yahoo mail page? > I had a look at the webbrowser module documentation > (http://www.python.org/doc/current/lib/module-webbrowser.html), but it > doesnt seem to support clicking buttons or sending data. All the stuff you need is right here: http://wwwsearch.sourceforge.net/ Specifically, the clicking buttons part is in ClientForm. Dustin From jordangreenberg at gmail.com Mon Aug 7 01:45:18 2006 From: jordangreenberg at gmail.com (Jordan Greenberg) Date: Sun, 06 Aug 2006 19:45:18 -0400 Subject: [Tutor] Python for basic web-testing In-Reply-To: <6054E9239B849044B9544941B2F8DDD9994A80@bnt-nav-akl-exh.navman.bnt.local> References: <6054E9239B849044B9544941B2F8DDD9994A80@bnt-nav-akl-exh.navman.bnt.local> Message-ID: <44D67F0E.3090600@gmail.com> Hans Dushanthakumar wrote: > Hi, > How do I use python for basic web-tasks like inputting data or > clicking buttons on web-pages. For eg, how do I enter my username and > password and click on the "OK" button on the yahoo mail page? > I had a look at the webbrowser module documentation > (http://www.python.org/doc/current/lib/module-webbrowser.html), but it > doesnt seem to support clicking buttons or sending data. > Thanks, > Hans > Hi Hans, I'm sure its possible, though i haven't a clue how you'd go about doing it. If its just for testing and you don't need it integrated with python, you might want to check out Greasemonkey (http://greasemonkey.mozdev.org/) or Chickenfoot (http://groups.csail.mit.edu/uid/chickenfoot/) which make those kinds of tasks absurdly easy. From Hans.Dushanthakumar at navman.com Mon Aug 7 02:19:21 2006 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Mon, 7 Aug 2006 12:19:21 +1200 Subject: [Tutor] Python for basic web-testing Message-ID: <6054E9239B849044B9544941B2F8DDD9994A81@bnt-nav-akl-exh.navman.bnt.local> Have been doing some googling myself..The Selenium tool looks good. It appears to be a record-and-play extension to the firefox browser...Anyone have any experience with the Selnium Remote Control? I'm having difficulty installing it. Cheers Hans -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Dustin J. Mitchell Sent: Monday, 7 August 2006 11:45 a.m. To: tutor at python.org Subject: Re: [Tutor] Python for basic web-testing Hans Dushanthakumar wrote: > Hi, > How do I use python for basic web-tasks like inputting data or > clicking buttons on web-pages. For eg, how do I enter my username and > password and click on the "OK" button on the yahoo mail page? > I had a look at the webbrowser module documentation > (http://www.python.org/doc/current/lib/module-webbrowser.html), but it > doesnt seem to support clicking buttons or sending data. All the stuff you need is right here: http://wwwsearch.sourceforge.net/ Specifically, the clicking buttons part is in ClientForm. Dustin _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From nephish at gmail.com Mon Aug 7 06:21:59 2006 From: nephish at gmail.com (shawn bright) Date: Sun, 6 Aug 2006 23:21:59 -0500 Subject: [Tutor] quick OO pointer Message-ID: <384c93600608062121l3b20c685ld9e06eb9f0478b28@mail.gmail.com> Hello there, a while back i wrote a module called DbConnector.py that allowed me to run different types of SQL queries. Cool enough. i did it mostly to handle the open and close of a db connection so i wouldn't have to worry about 'too many connection' errors. it makes a connection, runs a query, then closes the connection. The reason i write this, is that i know how the module works to make a connection 'object' now, i have a few functions in some scripts that i would like to reuse across the board. But, they dont really fit the "object" thing, i dont thing. Basically, i have a bunch of functions that do different things and i would like one script to hold them all. do i need to define a class for this, or can you import a function from another script ? like if i have def write_something_to_log(logfile, something) f = open(logfile, 'a') f.write('%s\n' % something) f.close() return 'success' and i wanted to use this same function in about four different scripts, do i need a class ? Do i need to just create a script full of common functions that i can access ? and if so, how ? usually in the tutorials i read, they deal with OO and classes. Most commonly a class called Person. Then person has different attributes. But these functions are just bits of code that i want to reuse what is the cleanest way to do something like this ? thanks sk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060806/74ccaee9/attachment.htm From jordangreenberg at gmail.com Mon Aug 7 09:07:23 2006 From: jordangreenberg at gmail.com (Jordan Greenberg) Date: Mon, 07 Aug 2006 03:07:23 -0400 Subject: [Tutor] quick OO pointer In-Reply-To: <384c93600608062121l3b20c685ld9e06eb9f0478b28@mail.gmail.com> References: <384c93600608062121l3b20c685ld9e06eb9f0478b28@mail.gmail.com> Message-ID: <44D6E6AB.5010402@gmail.com> shawn bright wrote: > Hello there, > > a while back i wrote a module called DbConnector.py that allowed me to run > different types of SQL queries. Cool enough. > i did it mostly to handle the open and close of a db connection so i > wouldn't have to worry about 'too many connection' errors. > it makes a connection, runs a query, then closes the connection. > The reason i write this, is that i know how the module works to make a > connection 'object' > now, i have a few functions in some scripts that i would like to reuse > across the board. But, they dont really fit the "object" thing, i dont > thing. Basically, i have a bunch of functions that do different things > and i > would like one script to hold them all. > do i need to define a class for this, or can you import a function from > another script ? > > like if i have > > def write_something_to_log(logfile, something) > f = open(logfile, 'a') > f.write('%s\n' % something) > f.close() > return 'success' > > and i wanted to use this same function in about four different scripts, > do i > need a class ? Do i need to just create a script full of common functions > that i can access ? and if so, how ? > usually in the tutorials i read, they deal with OO and classes. Most > commonly a class called Person. Then person has different attributes. But > these functions are just bits of code that i want to reuse > what is the cleanest way to do something like this ? > > thanks > > sk If your function write_something_to_log is in file myfunctions.py you can just do: from myfunctions import write_something_to_log and then use write_something_to_log() just like it was defined in that file. Example: #file: test1.py def spam(): print "Spam, eggs, and toast" #file: myscript.py from test1 import spam spam() #prints "Spam, eggs, and toast" Hope this helps! -Jordan Greenberg From janos.juhasz at VELUX.com Mon Aug 7 10:11:06 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 7 Aug 2006 10:11:06 +0200 Subject: [Tutor] os.system() with NO_WAIT In-Reply-To: Message-ID: Dear Guys, I have a small script that is running on a terminal server's client session. ####### import os import time import glob def send(): print 'I am checking %s' % time.ctime() if len(glob.glob(r'U:\ediout\DESADV\*.doc')) > 0: os.system('vedicom.exe') if __name__ == '__main__': os.chdir(r'U:\vedicom\DESADV\\') while 1: send() time.sleep(30) ####### As you can see, it is just start a windows program from a folder, when there are files in that folder. My problem comes when the network connection is broken. In that case, this program wait a user interaction to push a button. When the connection come back, it is just waiting to push the button and we are missing to send the EDI documents. Have you got any idea how I can strart this windows GUI program with not waiting its return. Yours sincerely, ______________________________ J?nos Juh?sz VELUX Magyarorsz?g Fert?di ?p?t?komponens Kft. IT Department Malom K?z 1, H-9431 Fert?d Telephone direct: +36 99 537 939 Telephone office: +36 99 537 920 Office fax: +36 99 537 921 Telephone mobile: +36 30 682 6331 @ janos.juhasz at VELUX.com www www.VELUX.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060807/530d068c/attachment.htm From reddazz at gmail.com Mon Aug 7 13:14:43 2006 From: reddazz at gmail.com (William Mhlanga) Date: Mon, 7 Aug 2006 12:14:43 +0100 Subject: [Tutor] Invoking bash from python Message-ID: I'd like to write an app that helps a user install a program on Linux after fetching it from a remote site. The program is packaged as a bin file and when run from bash, the user has to agree to a licence agreement by entering "y" or "n" and enter a path for installation. It seems like I need to find a way for my program to invoke bash so that the user can enter the input required. So far, I've figured out that I can use urllib to fetch the file and the commands module to execute some system commands. Any ideas on how I can envoke bash and pass on the users input to bash. Thanks for your input. Will -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060807/393cbd46/attachment.html From reddazz at gmail.com Mon Aug 7 13:26:40 2006 From: reddazz at gmail.com (William Mhlanga) Date: Mon, 7 Aug 2006 12:26:40 +0100 Subject: [Tutor] Invoking bash from python In-Reply-To: References: Message-ID: I think I found a solution to my problem and thats to use the os module ( os.system function). I'm still open to any suggestions you may have. --Will On 8/7/06, William Mhlanga wrote: > > I'd like to write an app that helps a user install a program on Linux > after fetching it from a remote site. The program is packaged as a bin file > and when run from bash, the user has to agree to a licence agreement by > entering "y" or "n" and enter a path for installation. It seems like I need > to find a way for my program to invoke bash so that the user can enter the > input required. So far, I've figured out that I can use urllib to fetch the > file and the commands module to execute some system commands. Any ideas on > how I can envoke bash and pass on the users input to bash. > > Thanks for your input. > > Will > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060807/92d3b69d/attachment.htm From alan.gauld at freenet.co.uk Mon Aug 7 14:12:22 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 7 Aug 2006 13:12:22 +0100 Subject: [Tutor] quick OO pointer References: <384c93600608062121l3b20c685ld9e06eb9f0478b28@mail.gmail.com> Message-ID: <001201c6ba1a$bdc7ecf0$0201a8c0@XPpro> > now, i have a few functions in some scripts that i would like to > reuse > across the board. But, they dont really fit the "object" thing, i > dont > thing. Basically, i have a bunch of functions that do different > things and i > would like one script to hold them all. You can put normal functions in a module and reuse them sure. If they operate on the same kinds of data then a class would be more appropriate but otherwise functions are fine. Its probably good to try to group them into families if possible. And you definitely want to use Functional Programming principles to maximise reuse. By that I mean: 1) No use of global variables 2) Pass everything in by parameters 3) Use default values to minimise the number of values the user sets 4) pass multiple values back in tuples where appropriate 5) make sure that the same set of input values always returns the same value - no hidden state Consider a number of smaller modules with related functionns too. Its tempting to just create a module called mystuff or similar that holds everything, but you then wind up with every project depending on mystuiff and small changes affect lots of code. Better to have small modules with only a few functions that can be imported as needed. Grouping the functions around the kind of data they manipulate is a good start - but that brings us back to objects again :-) > def write_something_to_log(logfile, something) > f = open(logfile, 'a') > f.write('%s\n' % something) > f.close() > return 'success' > > and i wanted to use this same function in about four different > scripts, do i > need a class ? Do i need to just create a script full of common > functions > that i can access ? and if so, how ? ############## # file: mylogger.py def write_something_to_log(logfile, something) f = open(logfile, 'a') f.write('%s\n' % something) f.close() return 'success' ###################### ############# # file myprog.py import mylogger mylogger.write_something('logfile.txt', 'hello world') ############## As simple as that! Just make sure the module file is where it can be found by import... More on creating modules in my tutorial topic on "Functions & Modules". Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From nephish at gmail.com Mon Aug 7 14:45:39 2006 From: nephish at gmail.com (shawn bright) Date: Mon, 7 Aug 2006 07:45:39 -0500 Subject: [Tutor] quick OO pointer In-Reply-To: <001201c6ba1a$bdc7ecf0$0201a8c0@XPpro> References: <384c93600608062121l3b20c685ld9e06eb9f0478b28@mail.gmail.com> <001201c6ba1a$bdc7ecf0$0201a8c0@XPpro> Message-ID: <384c93600608070545i53c9cf28r8a0e405289fc06ac@mail.gmail.com> Way cool, thanks a lot. I have one more small question. If my script that needs to call a function from another module, and the module itself both require, say, the string module.... do i need to import it in both? If i just import string on my original script, will the module know what to do with it? and if so, is that good practice ? thanks again shawn On 8/7/06, Alan Gauld wrote: > > > now, i have a few functions in some scripts that i would like to > > reuse > > across the board. But, they dont really fit the "object" thing, i > > dont > > thing. Basically, i have a bunch of functions that do different > > things and i > > would like one script to hold them all. > > You can put normal functions in a module and reuse them sure. > If they operate on the same kinds of data then a class would be > more appropriate but otherwise functions are fine. > > Its probably good to try to group them into families if possible. > And you definitely want to use Functional Programming principles > to maximise reuse. By that I mean: > 1) No use of global variables > 2) Pass everything in by parameters > 3) Use default values to minimise the number of values the user sets > 4) pass multiple values back in tuples where appropriate > 5) make sure that the same set of input values always > returns the same value - no hidden state > > Consider a number of smaller modules with related functionns too. > Its tempting to just create a module called mystuff or similar that > holds everything, but you then wind up with every project > depending on mystuiff and small changes affect lots of code. > Better to have small modules with only a few functions that can > be imported as needed. Grouping the functions around the kind > of data they manipulate is a good start - but that brings us back > to objects again :-) > > > > def write_something_to_log(logfile, something) > > f = open(logfile, 'a') > > f.write('%s\n' % something) > > f.close() > > return 'success' > > > > and i wanted to use this same function in about four different > > scripts, do i > > need a class ? Do i need to just create a script full of common > > functions > > that i can access ? and if so, how ? > > ############## > # file: mylogger.py > def write_something_to_log(logfile, something) > f = open(logfile, 'a') > f.write('%s\n' % something) > f.close() > return 'success' > ###################### > > ############# > # file myprog.py > import mylogger > > mylogger.write_something('logfile.txt', 'hello world') > ############## > > As simple as that! > Just make sure the module file is where it can be found by import... > > More on creating modules in my tutorial topic on "Functions & > Modules". > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060807/5e2d93cc/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Aug 7 16:53:04 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 7 Aug 2006 07:53:04 -0700 (PDT) Subject: [Tutor] help regarding forms... (fwd) Message-ID: ---------- Forwarded message ---------- Date: Mon, 7 Aug 2006 00:28:50 -0700 (PDT) From: anil maran To: Danny Yoo Subject: Re: [Tutor] help regarding forms... dear danny yoo thanks a lot for replying can you explain post methods and actions i wasnt able to find out how it works thanks a lot sincerely anil Danny Yoo wrote: On Sat, 5 Aug 2006, anil maran wrote: > http://localhost/newtodo?category= > > can one of you guys explain what this is Hi Anil, Are you taking some kind of internet web-development class? You seem to be asking a lot of web-development questions. In the absence of context, I'm not sure what to do other than to point you to the standard RFC on Uniform Resource Locators: http://www.faqs.org/rfcs/rfc1738.html and see if that addresses your question. > class todo: > def GET > > and > class newtodo: > def POST: Have you looked at any Python CGI tutorials yet? http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/ __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Mon Aug 7 16:53:06 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 7 Aug 2006 07:53:06 -0700 (PDT) Subject: [Tutor] can you explain string replacement syntax and comma separated statements (fwd) Message-ID: ---------- Forwarded message ---------- Date: Mon, 7 Aug 2006 00:33:08 -0700 (PDT) From: anil maran To: Danny Yoo Subject: Re: [Tutor] can you explain string replacement syntax and comma separated statements Dear danny yoo The help page doesnt take about multiline string replacement and this example doesnt work for me - it gives an error on text+ line Please help me out thanks a lot Anil olderror = web.internalerror def error(): olderror() import sys, traceback tb = sys.exc_info() text = """From: the bugman To: the bugfixer Subject: bug: %s: %s (%s) Content-Type: multipart/mixed; boundary="----here----" ------here---- Content-Type: text/plain Content-Disposition: inline %s %s ------here---- Content-Type: text/html; name="bug.html" Content-Disposition: attachment; filename="bug.html" """ % (tb[0], tb[1], web.ctx.path, web.ctx.method+' '+web.ctx.home+web.ctx.f ullpath, ''.join(traceback.format_exception(*tb)), text += str(web.djangoerror()) utils.send('... at example.com', '... at example.com', text) web.internalerror = error Danny Yoo wrote: On Sun, 6 Aug 2006, anil maran wrote: > text = """From: the bugman > To: the bugfixer > Subject: bug: %s: %s (%s) > Content-Type: multipart/mixed; boundary="----here----" [text example cut] Hi Anil, Anil, take a look at: http://www.python.org/doc/lib/typesseq-strings.html Does this address your question? On a high-level view of your questions so far: Are you running into problems because you can't find the documentation? Or is the issue that the documentation is unclear? --------------------------------- Do you Yahoo!? Next-gen email? Have it all with the all-new Yahoo! Mail Beta. From alan.gauld at freenet.co.uk Mon Aug 7 19:22:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 7 Aug 2006 18:22:51 +0100 Subject: [Tutor] quick OO pointer References: <384c93600608062121l3b20c685ld9e06eb9f0478b28@mail.gmail.com> <001201c6ba1a$bdc7ecf0$0201a8c0@XPpro> <384c93600608070545i53c9cf28r8a0e405289fc06ac@mail.gmail.com> Message-ID: <000b01c6ba46$1cb37d80$0201a8c0@XPpro> > If my script that needs to call a function from another module, and > the > module itself both require, say, the string module.... do i need to > import > it in both? Yes, importing just makes the name visible in the module where it is imported. So if you import your module the stuff that it imported is not visible. But you really need to look at all the options around importing because there are several options: import mymodule import mymodule as anothername from my module import myfunc from mymodule import * The last technique is frowned upon except in special cases. But you should really read about all the options to understand exactly what each does for you. > If i just import string on my original script, will the module > know what to do with it? Not sure what you mean. The module does nothing with it. Its up to you to write code that uses it. It will be available inside the module after the import and you can access its functions in turn by prefixing them. Think of it a bit like a bit containment graph where each node in the graph can refer to any other node. Where you get cycles then you can get problems so you should try to avoid those situations. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pythontut at pusspaws.net Mon Aug 7 20:10:27 2006 From: pythontut at pusspaws.net (dave s) Date: Mon, 7 Aug 2006 18:10:27 +0000 Subject: [Tutor] creating a method name on the fly Message-ID: <200608071810.28043.pythontut@pusspaws.net> I need to scan a long list of QT tickboxes in a dialog. I need to execute pseudo code something like ... list = ['error_button', 'print_button' ... etc ] for key in list: button= list[key] print button, self.button.isChecked() where self.button.isChecked() becomes self.error_button.isChecked() ... self.print_button.isChecked() .... etc etc Can anyone tell me how to do this ? I have looked at apply but with no luck Thanks Dave From dyoo at hkn.eecs.berkeley.edu Mon Aug 7 20:19:06 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 7 Aug 2006 11:19:06 -0700 (PDT) Subject: [Tutor] help regarding forms... (fwd) In-Reply-To: References: Message-ID: > can you explain post methods and actions i wasnt able to find out how it > works Hi Anil, Please do not email me directly. I don't have much time these days to help on Tutor. It is better to send replies back to the Tutor list, so that others there can continue helping you. Also, apologies for my slightly curt tone; I'm getting much busier these days, and I simply don't have the time for in-depth replies. Have you looked at: http://hoohoo.ncsa.uiuc.edu/cgi/forms.html GET and POST are particular ways that web browsers send data to the web server. They differ in the particulars in how they send that data, but conceptually, they do the same sort of thing in sending a "request" off to the server. There is already a module in Python to handle some of the ugly details of the CGI protocol; from the point of the CGI program, you shouldn't have to worry about POST or GET unless you really want to be concerned about it. See the 'cgi' module for some details: http://www.python.org/doc/lib/module-cgi.html From dyoo at hkn.eecs.berkeley.edu Mon Aug 7 20:23:51 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 7 Aug 2006 11:23:51 -0700 (PDT) Subject: [Tutor] can you explain string replacement syntax and comma separated statements (fwd) In-Reply-To: References: Message-ID: > The help page doesnt take about multiline string replacement and this > example doesnt work for me Hi Anil, Please be more specific and as informative as you can; we can't look over your shoulder, and the only information we see is what you send us. When you say, "This example doesn't work for me; it gives an error", don't just tell us this, but show us what you have done. Show us what example you have typed in, and what the literal error message is. From metaperl at gmail.com Mon Aug 7 20:25:00 2006 From: metaperl at gmail.com (Terrence Brannon) Date: Mon, 7 Aug 2006 14:25:00 -0400 Subject: [Tutor] help regarding forms... (fwd) In-Reply-To: References: Message-ID: On 8/7/06, Danny Yoo wrote: > > > Hi Anil, > > Please do not email me directly. this list is setup to send to the poster by default. I made the mistake of doing such a thing earlier myself. I know this is a huge item of contention, but do people favor having the default be to send replies to the list? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060807/e2c535cd/attachment.html From python at venix.com Mon Aug 7 20:36:44 2006 From: python at venix.com (Python) Date: Mon, 07 Aug 2006 14:36:44 -0400 Subject: [Tutor] creating a method name on the fly In-Reply-To: <200608071810.28043.pythontut@pusspaws.net> References: <200608071810.28043.pythontut@pusspaws.net> Message-ID: <1154975804.28304.835.camel@www.venix.com> On Mon, 2006-08-07 at 18:10 +0000, dave s wrote: > I need to scan a long list of QT tickboxes in a dialog. I need to execute > pseudo code something like ... > > > list = ['error_button', 'print_button' ... etc ] > for key in list: > button= list[key] > print button, self.button.isChecked() > > list = ['error_button', 'print_button' ... etc ] for key in list: button= getattr(self, key) print button, button.isChecked() You can't use a string directly in an object reference, so self.key and self.button will not work. You want to use the value in the string to look up an attribute. The getattr function supports that ability. (See also setattr and hasattr). key will be bound to each of the button attribute names in turn. The getattr call returns the button object. NOTE: you no longer need to specify self. Then simply use the button object. > > where self.button.isChecked() becomes self.error_button.isChecked() ... > self.print_button.isChecked() .... etc etc > > Can anyone tell me how to do this ? I have looked at apply but with no luck > > Thanks > > Dave > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From mahesh.akarapu at gmail.com Mon Aug 7 20:41:11 2006 From: mahesh.akarapu at gmail.com (Mahesh) Date: Tue, 8 Aug 2006 00:11:11 +0530 Subject: [Tutor] Beginner's question Message-ID: Hi All, To start with, please forgive me if this question is already answered. I am totally new to Python. I heard about Python some 3 years back, but did not give importance to it. I am hearing a lot about Python again recently. I was wondering what Python is good for and how will it help me, since I am already comfortable with C. Could someone tell me how Python is useful and why is it a good language to learn apart from C. Also please point me to a good starting point for learning Python. Thanks Mahesh From alan.gauld at freenet.co.uk Mon Aug 7 20:50:24 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 7 Aug 2006 19:50:24 +0100 Subject: [Tutor] Invoking bash from python References: Message-ID: <001e01c6ba52$581fc700$0201a8c0@XPpro> > required. So far, I've figured out that I can use urllib to fetch > the file > and the commands module to execute some system commands. > Any ideas on how Ican envoke bash and pass on the users input to > bash. Look at the Subprocess module and the Popen class. Check the examples of how tyo simulate the now deprecated popen functions. Basically they allow you to execute an external program and control the stdin/stdout streams from your program. You can also read some introductory stuff with examples on my tutor site under the OS topic. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Aug 7 20:51:31 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 7 Aug 2006 19:51:31 +0100 Subject: [Tutor] Invoking bash from python References: Message-ID: <002a01c6ba52$7fb96960$0201a8c0@XPpro> >I think I found a solution to my problem and thats to use the os >module ( > os.system function). I'm still open to any suggestions you may have. os system() will just run the bash program. Not too much avanytage. If you want to control the program from Python you need the popen functions - or the new Subprocess module. Alan G. > > --Will > > On 8/7/06, William Mhlanga wrote: >> >> I'd like to write an app that helps a user install a program on >> Linux >> after fetching it from a remote site. The program is packaged as a >> bin file >> and when run from bash, the user has to agree to a licence >> agreement by >> entering "y" or "n" and enter a path for installation. It seems >> like I need >> to find a way for my program to invoke bash so that the user can >> enter the >> input required. So far, I've figured out that I can use urllib to >> fetch the >> file and the commands module to execute some system commands. Any >> ideas on >> how I can envoke bash and pass on the users input to bash. >> >> Thanks for your input. >> >> Will >> > From rabidpoobear at gmail.com Mon Aug 7 20:53:26 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 07 Aug 2006 13:53:26 -0500 Subject: [Tutor] help regarding forms... (fwd) In-Reply-To: References: Message-ID: <44D78C26.3090409@gmail.com> Terrence Brannon wrote: > > > On 8/7/06, *Danny Yoo* > wrote: > > > Hi Anil, > > Please do not email me directly. > > > this list is setup to send to the poster by default. I made the mistake of doing such a thing earlier myself. > I know this is a huge item of contention, but do people favor having the default be to send replies > > to the list? /vote default-reply-to-list From metaperl at gmail.com Mon Aug 7 21:02:45 2006 From: metaperl at gmail.com (Terrence Brannon) Date: Mon, 7 Aug 2006 15:02:45 -0400 Subject: [Tutor] Beginner's question In-Reply-To: References: Message-ID: On 8/7/06, Mahesh wrote: > > Hi All, Hi Mahesh To start with, please forgive me if this question is already answered. > I am totally new to Python. I heard about Python some 3 years back, > but did not give importance to it. Similar to my story. I have been a 100% Perl professional for 6 years and did not pay much attention to other agile languages during that time. I am hearing a lot about Python > again recently. Amen, me too! It all started when all the mailing lists starting preferring mailman over majordomo... even Perl ones! I was wondering what Python is good for and how will > it help me, since I am already comfortable with C. Well, I just got serious as a heart attack about Python because I really needed to go beyond building websites page by page and nothing in Perl was up to the task. So I started with Drupal and Joomla, both PHP products, but really found Plone to be a more scaleable product and Python to be a more sane language than PHP. Could someone tell me how Python is useful and why is it a good > language to learn apart from C. Python is good for: - clean code: just look at the syntactic requirements - high quality flexible object oriented programming - I really like the approach to controlling objects with things like __init__ - and if you look at the plone videos, you see how default public accessors can have policies added to them by writing the accessor method. He also goes over why he opted on a Python CMS over PHP and even Ruby. - Rapid web app development - Quixote, Django, Turbo Gears, CherryPy and even Plone - Content mgmt - Plone - Large scale development - the import mechanism is very clean and concise compared to Perl's ExtUtils::MakeMaker. The regularity of code is ensured regardless of chosen editor. - The C++ crowd loves to script their code with Python. - google uses Python heavily - TwistedMatrix is a powerful generic server appliance - the community does not have nearly as much elitism as I found in the Perl world. The only difficult thing about Python is that the community discussions and source repositories are highly, highly distributed. In Perl, you have CPAN and Perlmonks.org and maybe a few mailing lists. It was very easy to keep on top of all new Perl developments on a daily basis. With Python, people all keep their source at their repo. Or you have to go through a lot of places like Codezoo, Sourceforge, and others. But Perl has basically run out of steam. Perl 5 was a great language for mixing C and Shell concepts. But Perl has lost control of the webapp space, and for object-oriented programming, the approach is far more manual, especially in the area of creating getters and setters (the leading product for this in Perl is Class::Accessor - just look at how difficult it is to use). Perl 6 is a cryptic imitation of Python and Ruby that will not appeal to Perl 5 fans or anyone seeking a simple easy to use language. And industry will be squeamish over a completely new codebase and a language that looks and has semantics quite different from Perl 5. Also please point me to a good > starting point for learning Python. I started with "Think Like a Computer Scientist" but it has typos and the author never got back to me when I emailed him about them. I think in retrospect, just reading the Tutorial and Library Reference at python.org is all you need. Then some articles like "Functional Programming in Python" http://www.amk.ca/python/writing/functional are good from there. And be sure to read comp.lang.python every day - lots of good Q/A there. And I though ASPN Python Cookbook was a good resource, but the programs are quite buggy based on IRC #python discussions. Thanks > Mahesh > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060807/43907b27/attachment.htm From metaperl at gmail.com Mon Aug 7 21:05:11 2006 From: metaperl at gmail.com (Terrence Brannon) Date: Mon, 7 Aug 2006 15:05:11 -0400 Subject: [Tutor] Invoking bash from python In-Reply-To: <002a01c6ba52$7fb96960$0201a8c0@XPpro> References: <002a01c6ba52$7fb96960$0201a8c0@XPpro> Message-ID: I was thinking that Python would have an expect-like clone and they do: http://pexpect.sourceforge.net/ Don't know how good it is though. On 8/7/06, Alan Gauld wrote: > > >I think I found a solution to my problem and thats to use the os > >module ( > > os.system function). I'm still open to any suggestions you may have. > > os system() will just run the bash program. Not too much avanytage. > If you want to control the program from Python you need the popen > functions - or the new Subprocess module. > > Alan G. > > > > > --Will > > > > On 8/7/06, William Mhlanga wrote: > >> > >> I'd like to write an app that helps a user install a program on > >> Linux > >> after fetching it from a remote site. The program is packaged as a > >> bin file > >> and when run from bash, the user has to agree to a licence > >> agreement by > >> entering "y" or "n" and enter a path for installation. It seems > >> like I need > >> to find a way for my program to invoke bash so that the user can > >> enter the > >> input required. So far, I've figured out that I can use urllib to > >> fetch the > >> file and the commands module to execute some system commands. Any > >> ideas on > >> how I can envoke bash and pass on the users input to bash. > >> > >> Thanks for your input. > >> > >> Will > >> > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060807/04a93119/attachment.html From metaperl at gmail.com Mon Aug 7 21:18:21 2006 From: metaperl at gmail.com (Terrence Brannon) Date: Mon, 7 Aug 2006 15:18:21 -0400 Subject: [Tutor] true and false Message-ID: What values represent true in Python? > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060807/df650b24/attachment.htm From wescpy at gmail.com Mon Aug 7 21:48:12 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 7 Aug 2006 12:48:12 -0700 Subject: [Tutor] true and false In-Reply-To: References: Message-ID: <78b3a9580608071248s5ce4b6abgd86974d6d1b1ecf@mail.gmail.com> > What values represent true in Python? good question. let's look at it from the other way as it's easier: a Boolean False value is any zero or empty container while True is anything *other* than those values. at the risk of plagarizing myself, here is a clip from chapter 4 of "Core Python:" CORE NOTE: Boolean values All standard type objects can be tested for truth value and compared to objects of the same type. Objects have inherent True or False values. Objects take a False value when they are empty, any numeric representation of zero, or the Null object, None. The following are defined as having false values in Python: ? None ? False (Boolean) ? 0 (integer) ? 0.0 (float) ? 0L (long integer) ? 0.0+0.0j (complex) ? "" (empty string) ? [] (empty list) ? () (empty tuple) ? {} (empty dictionary) (? other empty objects) Any value for an object other than the those above is considered to have a true value, i.e., non-empty, non-zero, etc. User-created class instances have a false value when their nonzero (__nonzero__()) or length (__len__()) special methods, if defined, return a zero value. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Mon Aug 7 22:08:59 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 7 Aug 2006 13:08:59 -0700 Subject: [Tutor] Beginner's question In-Reply-To: References: Message-ID: <78b3a9580608071308j5d83caccgf8bdff621f35402f@mail.gmail.com> hi mahesh, welcome to python... once you're here, there is no turning back. :-) > I am hearing a lot about Python > again recently. please tell us how and where you are hearing about Python now... the community is always interested in hearing interesting stories, such as Terrence's. > I was wondering what Python is good for and how will > it help me, since I am already comfortable with C. > > Could someone tell me how Python is useful and why is it a good > language to learn apart from C. Also please point me to a good > starting point for learning Python. i was a C programmer myself... had over 8 years of experience, then began experimenting with C++, Java, Perl, Tcl, etc. the one draw to moving to any language that is more "scriptive" in nature, whether it be Perl, Python or Ruby is that for a slight performance hit (nothing in life is free), you are gaining much more in terms of productivity. you are coding and solving problems at a much more rapid rate than in standard compiled languages like C, C++, and Java. i finally found Python 10 years ago, and have tried to avoid programming in anything else since. :D you are not wasting any (or much) time with boilerplate code, memory management, construction and destruction of primitive and/or heterogeneous data structures, etc. these things are already there for you, so the only things you need to worry about are solving your problems and which algorithms to use. then you can think about all the extra days of vacation you can take because you are not sitting in front of a computer and debugging. another feature of Python is its clean and simple but robust syntax. yes it can do everything that all those other languages can do, but with a syntax as simple as VB or JavaScript? makes others' code easier to read, including your own! you don't have to pull reference books off your shelf to figure out a piece of code you did several months ago. there are many places to start learning Python. since you are already a programmer, you can jump into various online tutorials, such as dive into python ( http://diveintopython.org ), alan gauld's ( http://www.freenetpages.co.uk/hp/alan.gauld/ ), as well as the tutorial in the official docs. if you want to read a book, check out pilgrim's dive into python (same as tutorial above), hetland's beginning python, wrox's (norton et al.), ascher's/lutz's learning python. all are good as python intros for experienced programmers. if you want to dig deeper and not only learn Python, but gain an insight on how things work under the covers, you can also try out my book, core python. it's pretty comprehensive but i try to expose you to enough of how the interpreter works with a goal of making you as *effective* of a Python developer as possible, even as a beginner. as far as Terrence's comment about where things are, in addition to the resources he mentioned, there are two main places to check for existing code: the vaults of parnassus, and PyPI (Python Package Index) aka the Cheeseshop. the latter is the closest thing we have to a "CPAN" at this time. again, welcome to python... we hope you're here to stay. :-) -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Mon Aug 7 22:17:15 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 7 Aug 2006 13:17:15 -0700 Subject: [Tutor] creating a method name on the fly In-Reply-To: <1154975804.28304.835.camel@www.venix.com> References: <200608071810.28043.pythontut@pusspaws.net> <1154975804.28304.835.camel@www.venix.com> Message-ID: <78b3a9580608071317n3034b84tef06a95a8ebece9d@mail.gmail.com> > > list = ['error_button', 'print_button' ... etc ] > > for key in list: > > button= list[key] > > print button, self.button.isChecked() > > > list = ['error_button', 'print_button' ... etc ] > for key in list: > button= getattr(self, key) > print button, button.isChecked() > > You can't use a string directly in an object reference, so self.key and > self.button will not work. You want to use the value in the string to > look up an attribute. The getattr function supports that ability. (See > also setattr and hasattr). dave, lloyd's suggestion is the way one "turns a string into an object," by using getattr(). you are basically saying, i want to look up the "printButton" attribute of self, and if it exists, give that object back to me (as 'button'). then when you access button, you are really manipulating self.printButton directly. also, calling "print button" is only going to give you either the object reference, i.e., "," not extremely useful unless you've defined your __str__ special method. the only other suggestion i'd give here is to not use "list" as a variable name. that is the name of a Python data type and its corresponding factory function, and by overriding it, you're effectively "shadowing" it, so you can't use "list()" to make a list anymore, and it also breaks typechecking with isintance(). cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From pythontut at pusspaws.net Mon Aug 7 22:22:34 2006 From: pythontut at pusspaws.net (dave s) Date: Mon, 7 Aug 2006 20:22:34 +0000 Subject: [Tutor] creating a method name on the fly In-Reply-To: <200608071810.28043.pythontut@pusspaws.net> References: <200608071810.28043.pythontut@pusspaws.net> Message-ID: <200608072022.34946.pythontut@pusspaws.net> Thanks for all your input - the discussion wandered off list a bit ! This solution works a treat ... button= getattr(self, 'error_button') print button, button.isChecked() Cheers Dave From wescpy at gmail.com Mon Aug 7 22:28:11 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 7 Aug 2006 13:28:11 -0700 Subject: [Tutor] os.system() with NO_WAIT In-Reply-To: References: Message-ID: <78b3a9580608071328q42b3d4ecif5ea45bd96f37a0@mail.gmail.com> > os.system('vedicom.exe') > > Have you got any idea how I can strart this windows GUI program with not > waiting its return. instead of os.system(), you want to use the subprocess module if you are using Python 2.4+: http://docs.python.org/lib/module-subprocess.html calling subprocess.Popen(["/bin/mycmd", "myarg"]) is "no wait." to save the PID: pid = subprocess.Popen(["/bin/mycmd", "myarg"]).pid if you are using Python 2.3.x and older, you have to use spawn*(): pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at freenet.co.uk Mon Aug 7 22:29:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 7 Aug 2006 21:29:15 +0100 Subject: [Tutor] creating a method name on the fly References: <200608071810.28043.pythontut@pusspaws.net> Message-ID: <003901c6ba60$26fefe30$0201a8c0@XPpro> >I need to scan a long list of QT tickboxes in a dialog. I need to >execute > pseudo code something like ... > > list = ['error_button', 'print_button' ... etc ] > for key in list: > button= list[key] > print button, self.button.isChecked() > > > where self.button.isChecked() becomes self.error_button.isChecked() > ... > self.print_button.isChecked() .... etc etc > > Can anyone tell me how to do this ? I have looked at apply but with > no luck Why not just add the buttons to a list as you create them then iterate over the list? Or better still use a dictionary with the name as key. buttons['error'] = Button(.....) buttons['print'] = Button(.....) then for name in buttons: print name, "button is", if buttons[name].isChecked(): print "checked" else: print "unchecked" No need to mess around trying to dynamically construct buton names etc. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Aug 7 22:43:45 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 7 Aug 2006 21:43:45 +0100 Subject: [Tutor] help regarding forms... (fwd) References: Message-ID: <004901c6ba62$2dca1ea0$0201a8c0@XPpro> > this list is setup to send to the poster by default. I made the > mistake of doing such a thing earlier myself. > I know this is a huge item of contention, but do people favor having > the default be to send replies to the list? OK, I've got to ask. This comes up every so often and I really don't understand it. I've been on the internet for over 20 years now and every mail tool/newreader I've ever used has (at least) two reply options: 1) Reply = reply to the original sender 2) Reply All = reply to everyone The same principle has always worked for all of the mailing lists I've ever been on. So why do people seem to expect some other kind of response? Are there mail clients out there that don't offer a Reply All option? Why would anyone want a mailing list that didn't offer two options, one for private reply and the other to include everyone? I don't understand why this seems to come as a surprise? What am I missing? Alan G. From alan.gauld at freenet.co.uk Mon Aug 7 22:50:54 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 7 Aug 2006 21:50:54 +0100 Subject: [Tutor] Beginner's question References: Message-ID: <004f01c6ba63$2d726c40$0201a8c0@XPpro> > but did not give importance to it. I am hearing a lot about Python > again recently. I was wondering what Python is good for and how will > it help me, since I am already comfortable with C. One line of Python ~= 10 lines of C So in terms of delivering results quickly Python is much faster than C. Python is also much more reliable than C since there is almost no memory management so you don't get NULL pointers, buffer overruns etc. But, Python is about 5-10 times slower than C and doesn't play well with direct memory access or hardware access, so if you need that stick with C. Or at least write those functions in C and access them from Python... > Could someone tell me how Python is useful and why is it a good > language to learn apart from C. There is an promotional section on the python web site giving the plus points. They are mostly the same plus points you find for any scripting language but python adds readability, modularity and a good OOP model - certainly better than C++ and java etc. > Also please point me to a good starting point for learning Python. If you know C just start with the official tutorial at www.python.org Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Aug 7 22:58:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 7 Aug 2006 21:58:15 +0100 Subject: [Tutor] Invoking bash from python References: <002a01c6ba52$7fb96960$0201a8c0@XPpro> Message-ID: <006901c6ba64$34251820$0201a8c0@XPpro> >I was thinking that Python would have an expect-like clone and they >do: > http://pexpect.sourceforge.net/ > > Don't know how good it is though. Pretty reasonable, its been around for a while. But if you know the order of requests expect is overkill. Expect is really for those situations where you have a dialog with the app and don't know which of many possible prompts you will get back. Its a bit like awk for streams but if you know exactly what you will be asked for and when then simple popen functionality is perfectly adequate and much simpler to code. PS. As an intermediate you can use the telnet module which allow simple checks for prompts ala expect but doesn't have all the timer/timeout richness of expect. Alan G. > > On 8/7/06, Alan Gauld wrote: >> >> >I think I found a solution to my problem and thats to use the os >> >module ( >> > os.system function). I'm still open to any suggestions you may >> > have. >> >> os system() will just run the bash program. Not too much avanytage. >> If you want to control the program from Python you need the popen >> functions - or the new Subprocess module. >> >> Alan G. >> >> > >> > --Will >> > >> > On 8/7/06, William Mhlanga wrote: >> >> >> >> I'd like to write an app that helps a user install a program on >> >> Linux >> >> after fetching it from a remote site. The program is packaged as >> >> a >> >> bin file >> >> and when run from bash, the user has to agree to a licence >> >> agreement by >> >> entering "y" or "n" and enter a path for installation. It seems >> >> like I need >> >> to find a way for my program to invoke bash so that the user can >> >> enter the >> >> input required. So far, I've figured out that I can use urllib >> >> to >> >> fetch the >> >> file and the commands module to execute some system commands. >> >> Any >> >> ideas on >> >> how I can envoke bash and pass on the users input to bash. >> >> >> >> Thanks for your input. >> >> >> >> Will >> >> >> > >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From alan.gauld at freenet.co.uk Mon Aug 7 23:07:20 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 7 Aug 2006 22:07:20 +0100 Subject: [Tutor] true and false References: Message-ID: <009601c6ba65$791c7850$0201a8c0@XPpro> > What values represent true in Python? True Its a built-in boolean type value. But empty strings, lists, tuples etc are considered False Similarly zero and None are considered False The library reference has a full list somewhere, but it's pretty much what intuition would tell you. "Empty" things are false anything else is true. Alan G. From john at fouhy.net Mon Aug 7 23:50:14 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 8 Aug 2006 09:50:14 +1200 Subject: [Tutor] creating a method name on the fly In-Reply-To: <003901c6ba60$26fefe30$0201a8c0@XPpro> References: <200608071810.28043.pythontut@pusspaws.net> <003901c6ba60$26fefe30$0201a8c0@XPpro> Message-ID: <5e58f2e40608071450m6d6df37ci66dab043336a2cf8@mail.gmail.com> On 08/08/06, Alan Gauld wrote: > Why not just add the buttons to a list as you create them then > iterate over the list? Or better still use a dictionary with the name > as key. You can do nice things with tuples. A simple example would be: # (label, callback) buttons = [('OK', self.OnOk), ('Cancel', self.OnCancel)] for label, callback in buttons: b = Button(self, label=label, ...) # place b in your GUI b.Bind(..., self.OnCancel) Obviously, the exact syntax and stuffw ill depend on the GUI toolkit you are using. Also you can put more information in your data structure if you want (eg, information on placing the button, styles for the button, etc). And, if you need to save the Button objects themselves, you could add them to a dict in the body of the loop: self.buttons = {} for label, callback in buttons: # ... self.buttons[label] = b It means that all the information about your GUI is brought together in one place where it's easy to see, and all the mechanical work is pushed off to one side :-) -- John. From wescpy at gmail.com Tue Aug 8 00:28:44 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 7 Aug 2006 15:28:44 -0700 Subject: [Tutor] creating a method name on the fly In-Reply-To: <5e58f2e40608071450m6d6df37ci66dab043336a2cf8@mail.gmail.com> References: <200608071810.28043.pythontut@pusspaws.net> <003901c6ba60$26fefe30$0201a8c0@XPpro> <5e58f2e40608071450m6d6df37ci66dab043336a2cf8@mail.gmail.com> Message-ID: <78b3a9580608071528y1b913a5dk978bab08afa7ee38@mail.gmail.com> > Also you can put more information in your data structure if you want > (eg, information on placing the button, styles for the button, etc). > And, if you need to save the Button objects themselves, you could add > them to a dict in the body of the loop: > > self.buttons = {} > for label, callback in buttons: > # ... > self.buttons[label] = b > > It means that all the information about your GUI is brought together > in one place where it's easy to see, and all the mechanical work is > pushed off to one side :-) on a separate but related tangent, wait till y'all see PFA (partial function application) coming up in 2.5. you can use PFAs to "templatize" GUI development. for example, if you want all the buttons to have the similar look-n-feel except for perhaps the text, you can do something like (here's another clip from Core Python, Example 11.6, pfaGUI.py): #!/usr/bin/env python from functools import partial import Tkinter root = Tkinter.Tk() MyButton = partial(Tkinter.Button, root, fg='white', bg='blue') b1 = MyButton(text='Button 1') b2 = MyButton(text='Button 2') qb = MyButton(text='QUIT', bg='red', command=root.quit) b1.pack() b2.pack() qb.pack(fill=Tkinter.X, expand=True) root.title('PFAs!') root.mainloop() "MyButton" contains all the common stuff for all buttons while the others can take the defaults or override them! it sure looks cleaner than having lots of duplicated code: b1 = Tkinter.Button(root, fg='white', bg='blue', text='Button 1') b2 = Tkinter.Button(root, fg='white', bg='blue', text='Button 2') qb = Tkinter.Button(root, fg='white', text='QUIT', bg='red', command=root.quit) cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From h.finucane at gmail.com Tue Aug 8 00:41:48 2006 From: h.finucane at gmail.com (Henry Finucane) Date: Mon, 7 Aug 2006 15:41:48 -0700 Subject: [Tutor] Community documentation framework? In-Reply-To: <45109da50608061456v67580f30oc42d1d18453f1226@mail.gmail.com> References: <45109da50608061456v67580f30oc42d1d18453f1226@mail.gmail.com> Message-ID: On 8/6/06, Bob Nienhuis wrote: > > Have you had the experience of finding a nifty bit of code on the > web, trying it out, and then discovering that technique > only worked in version X.YY, or requires module Z that > is no longer available? > > Well perhaps we can address this situation. > > I would like to see an online system that facilitates > the collaborative production, cataloging and updating of > community documentation. See an article, "Rethinking Community > Documentation" by Andy Oram > . > > Features I would like to see: > A Wikipedia-like capacity for community update-ability/modifiability > of documentation submissions. > > Database for cataloging available packages, modules, FAQs, How-Tos > tutorials, cookbook code fragments etc. Should have capacity for > developers to add and others to add to their contributions. > > Oram suggests a rating system for submissions so users can assess > the quality of submissions, and point to parts that need modification > or clarification.. > > Might use TurboGears, Django AJAX or other web framework? > > I think main Python documentation is great, but there is a lot > of stuff out there that isn't documented so well, or needs > updating. This project is intended to adress that need. > > What would you like to see? Sounds neat. Personally, I would like to see a bit of consolidation in ways you can look for help. There are oodles of web forums, the Tutor mailing list, the comp.lang.python mailing list, tutorials scattered all about the web, etc. Something like this could either prompt consolidation (good), or simply create more fragmentation (not so great, but acceptable). It all depends on how it gets advertised. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- --H.F. My penguin is bigger than yours, mister... From john at fouhy.net Tue Aug 8 00:44:58 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 8 Aug 2006 10:44:58 +1200 Subject: [Tutor] creating a method name on the fly In-Reply-To: <78b3a9580608071528y1b913a5dk978bab08afa7ee38@mail.gmail.com> References: <200608071810.28043.pythontut@pusspaws.net> <003901c6ba60$26fefe30$0201a8c0@XPpro> <5e58f2e40608071450m6d6df37ci66dab043336a2cf8@mail.gmail.com> <78b3a9580608071528y1b913a5dk978bab08afa7ee38@mail.gmail.com> Message-ID: <5e58f2e40608071544n2c4121bdt267fee553a9e8d31@mail.gmail.com> On 08/08/06, wesley chun wrote: > import Tkinter > > root = Tkinter.Tk() > MyButton = partial(Tkinter.Button, root, fg='white', bg='blue') > b1 = MyButton(text='Button 1') > b2 = MyButton(text='Button 2') > qb = MyButton(text='QUIT', bg='red', command=root.quit) > > "MyButton" contains all the common stuff for all buttons while the > others can take the defaults or override them! it sure looks cleaner > than having lots of duplicated code: > > b1 = Tkinter.Button(root, fg='white', bg='blue', text='Button 1') > b2 = Tkinter.Button(root, fg='white', bg='blue', text='Button 2') > qb = Tkinter.Button(root, fg='white', text='QUIT', bg='red', command=root.quit) I sometimes do this: buttonOpts = { 'fg':'white', 'bg':'blue' } packOpts = { I forget :-) } buttons = [('Button 1', None), ('Button 2', None), ('Button 3', root.quit)] for label, callback in buttons: b = Tkinter.Button(label, command=callback, **buttonOpts) b.pack(**packOpts) But, yeah, partial application will be cool :-) -- John. From dyoo at hkn.eecs.berkeley.edu Tue Aug 8 00:48:30 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 7 Aug 2006 15:48:30 -0700 (PDT) Subject: [Tutor] help regarding forms... (fwd) In-Reply-To: References: Message-ID: > this list is setup to send to the poster by default. I made the > mistake of doing such a thing earlier myself. Hi Terrence, Most email clients have a separate "Reply to All" or "Reply to group" command that's suitable for mailing lists. Check to see if your mail client has this feature. > I know this is a huge item of contention, but do people favor having the > default be to send replies to the list? There are good reasons for keeping the status quo: http://www.unicom.com/pw/reply-to-harmful.html There's no technical reason why we couldn't switch to reply-to munging --- Mailman supports it --- but I haven't heard anything compelling enough that addresses the issues raised by that article above. Best of wishes! From bgailer at alum.rpi.edu Tue Aug 8 01:03:05 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 07 Aug 2006 16:03:05 -0700 Subject: [Tutor] true and false In-Reply-To: <009601c6ba65$791c7850$0201a8c0@XPpro> References: <009601c6ba65$791c7850$0201a8c0@XPpro> Message-ID: <44D7C6A9.2040503@alum.rpi.edu> Alan Gauld wrote: >> What values represent true in Python? >> > > True > > Its a built-in boolean type value. > > But empty strings, lists, tuples etc are considered False > Similarly zero and None are considered False > Let us be precise here. Empty things are considered False when used where a boolean value is expected. In the language reference, under the if statement I quote:"It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section 5.10 for the definition of true and false)" 5:10: "In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: |False|, |None|, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true." The 2 flow control statements that use expressions in this way are if and while. Boolean operations are or, and, not. So in "if [1]: print 1" [1] will be interpreted as True. However in "[1] == True" it will NOT be interpreted as True. -- Bob Gailer 510-978-4454 From anilmrn at yahoo.com Tue Aug 8 01:51:22 2006 From: anilmrn at yahoo.com (anil maran) Date: Mon, 7 Aug 2006 16:51:22 -0700 (PDT) Subject: [Tutor] sending emails with html attachment In-Reply-To: Message-ID: <20060807235122.71529.qmail@web55904.mail.re3.yahoo.com> hi guys What is the best way to construct an email in python and also attach a html file the file is not on disk, but should be dynamically constructed in the python script thanks a lot __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060807/bd0b4c5d/attachment.html From broek at cc.umanitoba.ca Tue Aug 8 04:11:52 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 07 Aug 2006 22:11:52 -0400 Subject: [Tutor] help regarding forms... (fwd) In-Reply-To: <004901c6ba62$2dca1ea0$0201a8c0@XPpro> References: <004901c6ba62$2dca1ea0$0201a8c0@XPpro> Message-ID: <44D7F2E8.8020305@cc.umanitoba.ca> Alan Gauld said unto the world upon 07/08/06 04:43 PM: >> this list is setup to send to the poster by default. I made the >> mistake of doing such a thing earlier myself. >> I know this is a huge item of contention, but do people favor having >> the default be to send replies to the list? > > OK, I've got to ask. This comes up every so often and I really > don't understand it. > > I've been on the internet for over 20 years now and every mail > tool/newreader I've ever used has (at least) two reply options: > 1) Reply = reply to the original sender > 2) Reply All = reply to everyone > > The same principle has always worked for all of the mailing lists > I've ever been on. > > So why do people seem to expect some other kind of response? > Are there mail clients out there that don't offer a Reply All option? > Why would anyone want a mailing list that didn't offer two options, > one for private reply and the other to include everyone? > > I don't understand why this seems to come as a surprise? > What am I missing? Hi all, Alan, I think you are judging based on technical lists, no? In my experience, the further from computing-technical the domain of a mailing list, the more likely it is to be set up with a munged `reply to' header. It could be worse; there is a photography list I've been occasionally on for a decade or so where the list-denizens are steadfast in their reply to list preference and have to cope with 2-3 ``How do I subscribers?'' emails a week. (This despite instructions being provided in the footer of each and every message posted on the list.) Best, Brian vdB From cspears2002 at yahoo.com Tue Aug 8 07:42:46 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 7 Aug 2006 22:42:46 -0700 (PDT) Subject: [Tutor] Rock, Paper, Scissors Message-ID: <20060808054246.54903.qmail@web51606.mail.yahoo.com> I have been looking for a new project to tackle when I came across this link: http://www.ibiblio.org/obp/pyBiblio/practice/wilson/rockpaperscissors.php. Here is some sample output that was provided at the webpage: Welcome to Rock, Paper, Scissors! How many points are required for a win? 3 Choose (R)ock, (P)aper, or (S)cissors? r Human: rock Computer: paper Computer wins! Score: Human 0 Computer 1 Choose (R)ock, (P)aper, or (S)cissors? r Human: rock Computer: scissors Human wins! Score: Human 1 Computer 1 Choose (R)ock, (P)aper, or (S)cissors? p Human: paper Computer: paper A draw Score: Human 1 Computer 1 Choose (R)ock, (P)aper, or (S)cissors? s Human: scissors Computer: paper Human wins! Score: Human 2 Computer 1 Choose (R)ock, (P)aper, or (S)cissors? r Human: rock Computer: scissors Human wins! Final Score: Human 3 Computer 1 This looks like a fun project to work on. From reading the description, I feel this would be pretty straight forward game to program. However, I have no idea how the computer would decide if it wanted a rock, paper, or a pair of scissors. Any hints? From john at fouhy.net Tue Aug 8 07:54:36 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 8 Aug 2006 17:54:36 +1200 Subject: [Tutor] Rock, Paper, Scissors In-Reply-To: <20060808054246.54903.qmail@web51606.mail.yahoo.com> References: <20060808054246.54903.qmail@web51606.mail.yahoo.com> Message-ID: <5e58f2e40608072254q6044e5f9yb8ffcceb176a5e5d@mail.gmail.com> On 08/08/06, Christopher Spears wrote: > This looks like a fun project to work on. From > reading the description, I feel this would be pretty > straight forward game to program. However, I have no > idea how the computer would decide if it wanted a > rock, paper, or a pair of scissors. Any hints? Well, the easiest way to do it would be to make it random --- have a look at the random module in the standard library. For example, random.randrange(3) will give you a random integer in [0, 1, 2], which you could map to rock/paper/scissors. [the random module also has a function randint, which is similar to randrange. I prefer randrange, because the arguments match the arguments to range(), whereas randint is a bit different] Or random.choice(['rock', 'paper', 'scissors']) will give you a string. Of course, if you want to be more clever, I understand that RSP programs that always pick what the human picked in the previous round tend to do better than random (unless the human notices, at which point they start doing very badly :-) ). -- John. From jordangreenberg at gmail.com Tue Aug 8 08:00:37 2006 From: jordangreenberg at gmail.com (Jordan Greenberg) Date: Tue, 08 Aug 2006 02:00:37 -0400 Subject: [Tutor] Rock, Paper, Scissors In-Reply-To: <20060808054246.54903.qmail@web51606.mail.yahoo.com> References: <20060808054246.54903.qmail@web51606.mail.yahoo.com> Message-ID: <44D82885.1080904@gmail.com> Christopher Spears wrote: > This looks like a fun project to work on. From > reading the description, I feel this would be pretty > straight forward game to program. However, I have no > idea how the computer would decide if it wanted a > rock, paper, or a pair of scissors. Any hints? Since theres no real strategy to rock paper scissors, just generate a random number from 0-2 like this: import random random.seed() choice=random.randint(0, 2) if choice==0: #do whatever for rock elif choice==1: #do whatever for paper else: #do whatever for scissors That'll take care of the basics for ya. Later you could try and keep frequency counts over a bunch of trials, see if the human has a preference, and then weight your response appropriately to try and beat them ;) -Jordan Greenberg From janos.juhasz at VELUX.com Tue Aug 8 10:22:55 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 8 Aug 2006 10:22:55 +0200 Subject: [Tutor] os.system() with NO_WAIT In-Reply-To: <78b3a9580608071328q42b3d4ecif5ea45bd96f37a0@mail.gmail.com> Message-ID: Thanks Wesley, I lokked for subprocess.Popen. os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") was to complicated for me based on the manual. Yours sincerely, ______________________________ J?nos Juh?sz VELUX Magyarorsz?g Fert?di ?p?t?komponens Kft. IT Department Malom K?z 1, H-9431 Fert?d Telephone direct: +36 99 537 939 Telephone office: +36 99 537 920 Office fax: +36 99 537 921 Telephone mobile: +36 30 682 6331 @ janos.juhasz at VELUX.com www www.VELUX.com "wesley chun" 2006.08.07 22:28 To "J?nos Juh?sz" cc tutor at python.org Subject Re: [Tutor] os.system() with NO_WAIT > os.system('vedicom.exe') > > Have you got any idea how I can strart this windows GUI program with not > waiting its return. instead of os.system(), you want to use the subprocess module if you are using Python 2.4+: http://docs.python.org/lib/module-subprocess.html calling subprocess.Popen(["/bin/mycmd", "myarg"]) is "no wait." to save the PID: pid = subprocess.Popen(["/bin/mycmd", "myarg"]).pid if you are using Python 2.3.x and older, you have to use spawn*(): pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060808/a7461a4b/attachment.html From member at dorch.wanadoo.co.uk Mon Aug 7 11:02:14 2006 From: member at dorch.wanadoo.co.uk (David Wilson) Date: Mon, 7 Aug 2006 11:02:14 +0200 (CEST) Subject: [Tutor] python Message-ID: <20443208.1154941334662.JavaMail.www@wwinf3101> can you explain functions in python to me and give me some examples From kent37 at tds.net Tue Aug 8 15:48:01 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 8 Aug 2006 9:48:01 -0400 Subject: [Tutor] Community documentation framework? Message-ID: <20060808134801.WJBN22195.outaamta02.mail.tds.net@smtp.tds.net> > > From: "Bob Nienhuis" > > Features I would like to see: > A Wikipedia-like capacity for community update-ability/modifiability > of documentation submissions. Fredrik Lundh has started wikis for the Python docs. I'm on vacation and don't have the links but you should be able to find them in the blog archives at effbot.org. Kent -------------- next part -------------- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From bashu at yandex.ru Tue Aug 8 16:23:43 2006 From: bashu at yandex.ru (Basil Shubin) Date: Tue, 08 Aug 2006 21:23:43 +0700 Subject: [Tutor] Regex search in HTML data Message-ID: <44D89E6F.2080805@yandex.ru> Hi friends, Please, see the attachment and examine a code I have provide. The problem is, I want fetch data from

Comments

until the first occurrence , but with my code data fetchind until the last in htmlData variable, but that is not what I want. So question is, what is my mistake? Thanks in advance. -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: text/x-python Size: 2108 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060808/cba5f438/attachment.py From cappy2112 at gmail.com Tue Aug 8 18:00:59 2006 From: cappy2112 at gmail.com (Tony Cappellini) Date: Tue, 8 Aug 2006 09:00:59 -0700 Subject: [Tutor] Unusual behavior in readline Message-ID: <8249c4ac0608080900p40c2a307yae7134171c2cff4c@mail.gmail.com> I don't understand why readline is producing such unusual behavior. I don't remember it working like this previously. The docs say it is supposed to read a line at a time. this function def ProcessFile(self, Inputfile, Outputfile=None): try: fh=open(Inputfile,"r") except IOError: print"\nError ocurred opening %s for input\n" % Inputfile else: FixedEntry = [] Entry = "" for Entry in fh.readline(): print"Entry = %s" % Entry fh.close() is producing this result Entry = A Entry = l Entry = i Entry = a Entry = s Entry = , Entry = P Entry = h Entry = o Entry = n Entry = e With this input file Alias,Phone JANE SMITH,12131234567 Readline is supposed to read an entire line on each call, yet it is only reading one character. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060808/d7f7e0a7/attachment.htm From Mike.Hansen at atmel.com Tue Aug 8 18:49:22 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Tue, 8 Aug 2006 10:49:22 -0600 Subject: [Tutor] Community documentation framework? Message-ID: <57B026980605A64F9B23484C5659E32E25503B@poccso.US.ad.atmel.com> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Bob Nienhuis Sent: Sunday, August 06, 2006 3:56 PM To: tutor at python.org Subject: [Tutor] Community documentation framework? Have you had the experience of finding a nifty bit of code on the web, trying it out, and then discovering that technique only worked in version X.YY, or requires module Z that is no longer available? Well perhaps we can address this situation. I would like to see an online system that facilitates the collaborative production, cataloging and updating of community documentation. See an article, "Rethinking Community Documentation" by Andy Oram . Features I would like to see: A Wikipedia-like capacity for community update-ability/modifiability of documentation submissions. Database for cataloging available packages, modules, FAQs, How-Tos tutorials, cookbook code fragments etc. Should have capacity for developers to add and others to add to their contributions. Oram suggests a rating system for submissions so users can assess the quality of submissions, and point to parts that need modification or clarification.. Might use TurboGears, Django AJAX or other web framework? I think main Python documentation is great, but there is a lot of stuff out there that isn't documented so well, or needs updating. This project is intended to adress that need. What would you like to see? ---- You might take a look at http://pyfaq.infogami.com/ Mike From alan.gauld at freenet.co.uk Tue Aug 8 18:59:33 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 8 Aug 2006 17:59:33 +0100 Subject: [Tutor] help regarding forms... (fwd) References: <004901c6ba62$2dca1ea0$0201a8c0@XPpro> <44D7F2E8.8020305@cc.umanitoba.ca> Message-ID: <001501c6bb0c$065a7130$0201a8c0@XPpro> >> I've been on the internet for over 20 years now and every mail >> tool/newreader I've ever used has (at least) two reply options: >> ... >> I don't understand why this seems to come as a surprise? >> What am I missing? > > Alan, I think you are judging based on technical lists, no? There are other kinds?!! :-) > mailing list, the more likely it is to be set up with a munged > `reply to' header. What exactly does this mean? I still don't quite see how it works. Does this mean a user hits Reply to reply to the whole list and then Reply All - does what???? The same? What a waste! Alan G. From alan.gauld at freenet.co.uk Tue Aug 8 19:00:53 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 8 Aug 2006 18:00:53 +0100 Subject: [Tutor] Rock, Paper, Scissors References: <20060808054246.54903.qmail@web51606.mail.yahoo.com> Message-ID: <001b01c6bb0c$37df2390$0201a8c0@XPpro> > This looks like a fun project to work on. From > reading the description, I feel this would be pretty > straight forward game to program. However, I have no > idea how the computer would decide if it wanted a > rock, paper, or a pair of scissors. Any hints? Assign a value to rock, paper and scissors. then use the random module to generate one of the 3 values at random. Alan G. From rabidpoobear at gmail.com Tue Aug 8 20:51:13 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 08 Aug 2006 13:51:13 -0500 Subject: [Tutor] Unusual behavior in readline In-Reply-To: <8249c4ac0608080900p40c2a307yae7134171c2cff4c@mail.gmail.com> References: <8249c4ac0608080900p40c2a307yae7134171c2cff4c@mail.gmail.com> Message-ID: <44D8DD21.9010107@gmail.com> Tony Cappellini wrote: > > I don't understand why readline is producing such unusual behavior. > I don't remember it working like this previously. The docs say it is > supposed to read a line at a time. It does :) > > this function > > def ProcessFile(self, Inputfile, Outputfile=None): > > try: > fh=open(Inputfile,"r") > except IOError: > print"\nError ocurred opening %s for input\n" % Inputfile > else: > FixedEntry = [] > Entry = "" > for Entry in fh.readline(): what you're saying in this line is: 1. call the readline method of fh. 2. iterate over each item in the returned value, and assign each item the name 'Entry' while in the loop. What does the readline method of fh return? it returns a single line. So you're looping over a single line, which means that each time through the loop Entry points to a single character. What you want to do is call readline through each iteration of the loop. or, to make it much easier, you could just use readlines :) 'for Entry in fh.readlines():' > [snip stuff] > Readline is supposed to read an entire line on each call, yet it is > only reading one character. > No, it is, in fact, reading an entire line on _each_ call, the only problem being that you only call it once. HTH, -Luke > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hugonz-lists at h-lab.net Tue Aug 8 20:57:45 2006 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 08 Aug 2006 13:57:45 -0500 Subject: [Tutor] python In-Reply-To: <20443208.1154941334662.JavaMail.www@wwinf3101> References: <20443208.1154941334662.JavaMail.www@wwinf3101> Message-ID: <44D8DEA9.8060207@h-lab.net> Hi David, Have you read the grat explanation in Alan's tutorial? What problem specifically are you having with functions? http://www.freenetpages.co.uk/hp/alan.gauld/ Get back to us with any questions... David Wilson wrote: > can you explain functions in python to me and give me some examples > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From asdlinux at yahoo.se Tue Aug 8 22:13:00 2006 From: asdlinux at yahoo.se (=?ISO-8859-1?Q?Magnus_Wirstr=F6m?=) Date: Tue, 08 Aug 2006 22:13:00 +0200 Subject: [Tutor] try & except Message-ID: <44D8F04C.5040306@yahoo.se> Hi I'm playing around with try: and except: i have a code like this try: bibl=os.listdir("c:\\klientdata\\") except: wx.MessageBox("Kunde inte l?sa k?ll biblioteket.","S?kerhetskopiering",wx.OK|wx.ICON_ERROR) (yeah ... it's swedish :) ) So far i get how to use it but i would like to be able to execute the try block again after it jumped to the exception. How can i make it retry to read the directory? Thanks Magnus From dyoo at hkn.eecs.berkeley.edu Tue Aug 8 22:18:36 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 8 Aug 2006 13:18:36 -0700 (PDT) Subject: [Tutor] python In-Reply-To: <20443208.1154941334662.JavaMail.www@wwinf3101> References: <20443208.1154941334662.JavaMail.www@wwinf3101> Message-ID: On Mon, 7 Aug 2006, David Wilson wrote: > can you explain functions in python to me and give me some examples Hi David, Have you looked into a Python tutorial yet? http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Most of the tutorials there talk about functions. If you could give us an example of what you're having trouble with, that would help us to give more specific examples that target that problem. From broek at cc.umanitoba.ca Tue Aug 8 22:31:47 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 08 Aug 2006 16:31:47 -0400 Subject: [Tutor] help regarding forms... (fwd) In-Reply-To: <001501c6bb0c$065a7130$0201a8c0@XPpro> References: <004901c6ba62$2dca1ea0$0201a8c0@XPpro> <44D7F2E8.8020305@cc.umanitoba.ca> <001501c6bb0c$065a7130$0201a8c0@XPpro> Message-ID: <44D8F4B3.8020007@cc.umanitoba.ca> Alan Gauld said unto the world upon 08/08/06 12:59 PM: >>> I've been on the internet for over 20 years now and every mail >>> tool/newreader I've ever used has (at least) two reply options: >>> ... >>> I don't understand why this seems to come as a surprise? >>> What am I missing? >> >> Alan, I think you are judging based on technical lists, no? > > There are other kinds?!! :-) :-) >> mailing list, the more likely it is to be set up with a munged `reply >> to' header. > > What exactly does this mean? I still don't quite see how it works. > Does this mean a user hits Reply to reply to the whole list and > then Reply All - does what???? The same? What a waste! > I've never actually tried `Reply to all' on a munged list. But, since on such lists `Reply' is, in effect, an alias for `Reply to all' I assume that in addition to breaking expectations, munging is also, as you suspect, brought to you by the Department of Redundancy Department. FWIW, the munging preference is pretty runs pretty deep, I think. I my case it took public shame caused by a `private' message that wasn't to see the light. :-[ Burned by the memory, I refuse to munge the class mailing lists I administer. But one day the complaints will wear me down . . . . Best, Brian vdB From alan.gauld at freenet.co.uk Tue Aug 8 22:56:02 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 8 Aug 2006 21:56:02 +0100 Subject: [Tutor] python References: <20443208.1154941334662.JavaMail.www@wwinf3101> Message-ID: <001101c6bb2d$10241380$0201a8c0@XPpro> > can you explain functions in python to me and give me some examples There are many tutorials that do that, including mine. Take a look at the Modules and functions topic... Or if you are experienced in other programming languages try the official tutorial at python.org. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Aug 8 23:06:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 8 Aug 2006 22:06:47 +0100 Subject: [Tutor] Regex search in HTML data References: <44D89E6F.2080805@yandex.ru> Message-ID: <002101c6bb2e$8fa40a60$0201a8c0@XPpro> > Please, see the attachment and examine a code I have provide. The > problem is, I want fetch data from

Comments

until the first > occurrence , Do you mean the unmatched /td that occurs after the dd section? > import re > import string > > htmlData = """ >

Instructions

.... >

Comments

> >
>
None >
> To this one here? Its probably a bad idea to use a regular tag as a marker, some browsers get confused by unmatched tags. Using a comment is usually better. >

Classification

> >

width="100%"> > > But regex don;t like working with nested tags, you have a table cell inside another and writing regexs to match that can get very tricky. So if you want to search into this part of the string you should probably look at using Beautiful Soup or similar HTML parser. > if __name__ == '__main__': > # Extract comments > p = re.search('

Comments

(.+)', htmlData, > re.I | re.S | re.M) Looks like you are getting caught out by the "greedy" nature of regex - they grab as much as they can. You can control that by adding a ? immediately after the + but given the nature of your html I'd try using BeautifulSoup instead. You'll find a short section on greedy expressions in my regex topic on my tutorial site. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From john at fouhy.net Tue Aug 8 23:11:02 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 9 Aug 2006 09:11:02 +1200 Subject: [Tutor] try & except In-Reply-To: <44D8F04C.5040306@yahoo.se> References: <44D8F04C.5040306@yahoo.se> Message-ID: <5e58f2e40608081411maf21514l2dc4107821faeae@mail.gmail.com> On 09/08/06, Magnus Wirstr?m wrote: > Hi > > I'm playing around with try: and except: i have a code like this > try: > bibl=os.listdir("c:\\klientdata\\") > except: > wx.MessageBox("Kunde inte l?sa k?ll > biblioteket.","S?kerhetskopiering",wx.OK|wx.ICON_ERROR) > > (yeah ... it's swedish :) ) > > So far i get how to use it but i would like to be able to execute the > try block again after it jumped to the exception. How can i make it > retry to read the directory? What logic are you looking for? Is it --- "Try to read directory. If it doesn't work, try again. If it still doesn't work, abort." or --- "Try to read directory. If it doesn't work, keep trying until it does." In the former case, you could just put another try block in your except block: try: bibl=os.listdir("c:\\klientdata\\") except: wx.MessageBox("Kunde inte l?sa k?ll biblioteket.","S?kerhetskopiering",wx.OK|wx.ICON_ERROR) try: bibl=os.listdir("c:\\klientdata\\") except: wx.MessageBox("Kunde inte l?sa k?ll biblioteket.","S?kerhetskopiering",wx.OK|wx.ICON_ERROR) In the latter case, you probably want some kind of loop: success = False while not success: try: bibl=os.listdir("c:\\klientdata\\") success = True except: wx.MessageBox("Kunde inte l?sa k?ll biblioteket.","S?kerhetskopiering",wx.OK|wx.ICON_ERROR) Of course, it would be nice to give the users another way out of the loop :-) HTH! -- John. From alan.gauld at freenet.co.uk Tue Aug 8 23:12:39 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 8 Aug 2006 22:12:39 +0100 Subject: [Tutor] Unusual behavior in readline References: <8249c4ac0608080900p40c2a307yae7134171c2cff4c@mail.gmail.com> Message-ID: <003501c6bb2f$61bf45a0$0201a8c0@XPpro> >I don't understand why readline is producing such unusual behavior. > I don't remember it working like this previously. The docs say it is > supposed to read a line at a time. It does. > def ProcessFile(self, Inputfile, Outputfile=None): > > try: > fh=open(Inputfile,"r") > except IOError: > print"\nError ocurred opening %s for input\n" % Inputfile > else: > FixedEntry = [] > Entry = "" You don't need to initialise Entry, the for loop does that for you. > for Entry in fh.readline(): readline returns a string and the for loop iterates over it. You need readl;ines to return all of the strings in the file. Or nowadays just use for Entry in fh: > print"Entry = %s" % Entry BTW Why not just put all this stuff in the body of the try? Thats what try/except is for, to stop cluttering up the code with error handling sections and move that to the end out of the way.... You should very rarely need an else clause when using try/except. > Readline is supposed to read an entire line on each call, > yet it is only reading one character. No, it is reading a line, you are then iterating over that line one character at a time. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Aug 8 23:29:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 8 Aug 2006 22:29:10 +0100 Subject: [Tutor] try & except References: <44D8F04C.5040306@yahoo.se> Message-ID: <004301c6bb31$b07e80f0$0201a8c0@XPpro> > I'm playing around with try: and except: i have a code like this > try: > bibl=os.listdir("c:\\klientdata\\") > except: > wx.MessageBox("Kunde inte l?sa k?ll ... > > So far i get how to use it but i would like to be able to execute > the try block again after it jumped to the exception. Yes, thats a common desire, unfortunately it isn't possible, at least not directly. One way round this is to put the try inside a function then call the function inside an outer try, like this: def mylistdir(d): try: bibl = os.listdir(d) except: raise try: mylistdir("C:\\....") except: print 'oops!' mylistdir(default) But even here you only get wo bites at the pie. If you need more you need to write a loop: success = False while not success try: mylistdir(d) success = True except: print 'oops!' But I agree a retry option would be nice. But I've never found a language yet that supports it. (There are some good reasons why this is the case BTW, to do with the uncertain state of the code block that you exit.) HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Tue Aug 8 23:59:33 2006 From: wescpy at gmail.com (wesley chun) Date: Tue, 8 Aug 2006 14:59:33 -0700 Subject: [Tutor] Unusual behavior in readline In-Reply-To: <003501c6bb2f$61bf45a0$0201a8c0@XPpro> References: <8249c4ac0608080900p40c2a307yae7134171c2cff4c@mail.gmail.com> <003501c6bb2f$61bf45a0$0201a8c0@XPpro> Message-ID: <78b3a9580608081459n319f4d98q302c329e30f49f51@mail.gmail.com> summarizing what folks have already said plus a few more tweaks such as moving the close() to finally (2.5+), following the style guideline of variable non-titlecasing, removing unused variables, etc.: #!/usr/bin/env python2.5 def processFile(inputfile): try: fh = open(inputfile, "r") for entry in fh: print "Entry = %s" % entry.strip() except IOError, e: print "\nError occurred opening %s for input\n" % inputfile finally: fh.close() if __name__ == '__main__': processFile('phone') we get this output: $ tony.py Entry = Alias,Phone Entry = JANE SMITH,12131234567 the try-except-finally statement was unified (again) coming up in 2.5. i say again because it was actually there before but removed in version 0.9.6. :-) how about some 2.6 fun and using the with statement to get rid of finally and closing the file, as a 2.5 preview? #!/usr/bin/env python2.5 from __future__ import with_statement def processFile(inputfile): try: with open(inputfile, "r") as fh: for entry in fh: print "Entry = %s" % entry.strip() except IOError, e: print "\nError occurred opening %s for input\n" % inputfile the context management of the with statement will automagically close the file regardless of exceptions so you do not need to worry about it. in 2.6, both 'with' and 'as' become keywords -- you will be warned in 2.5. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From anilmrn at yahoo.com Wed Aug 9 01:48:19 2006 From: anilmrn at yahoo.com (anil maran) Date: Tue, 8 Aug 2006 16:48:19 -0700 (PDT) Subject: [Tutor] searching for a string in a dictionary Message-ID: <20060808234819.11532.qmail@web55913.mail.re3.yahoo.com> all_types: ..... there is such a list how do i search for a particular string say teststring in this list i tried if teststring in all_types: if teststring in all_types.type: it doesnt work please help me out here should i use lambda --------------------------------- Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1?/min. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060808/b36677ca/attachment.htm From kermit at polaris.net Wed Aug 9 04:54:58 2006 From: kermit at polaris.net (Kermit Rose) Date: Tue, 8 Aug 2006 22:54:58 -0400 (Eastern Daylight Time) Subject: [Tutor] Exercise in writing a python function. Message-ID: <44D94E82.000013.00176@YOUR-4105E587B6> Hello all. I feel more familar with Python now, and when I recently went back to reading the tutorial, I could actually read it without being overwhelmed by too much new detail. I've been staring at the specs for a python function for a while. I wrote one version of it and it worked. Then I changed the specs, and now need to reconstruct my original work. I'm sure I can do it fairly easily. I'm not asking anyone to write the function for me. It did occur to me that it could be a classroom exercise for other students. The current specifications for the function are: def incr(mult,z,zlim,mpylist): # mult is a vector of exponents for the multipliers in mpylist. # z is a positive odd integer. # zlim is the upper bound critical value for the sum of ( mpylist[k][0] * mpylist[k][1] ) # where kth multiplier is mpylist [k][0] # and kth multiplier index is mpylist [k][1] # function incr returns the next value of vector mult. # mult may be thought as a number written in a variable base. # mult[0] is the least significant and matches multiplier mpylist[0][0] # adding one to mult would mean adding 1 to mult[0] # unless doing so would make sum of multiplier * index exceed zlim. # in that case mult[0] is set to zero, and 1 is added to mult[1] # unless doing so would make sum of multilier * index exceed zlim # in that case, mult[0] and mult[1] is set to zero, # and 1 is added to mult[2] # unless . . . # mult[0] is set to -1 to indicate that the largest possible value of mult has been exceeded. # mpylist[0][0] = 2 and all other multipliers in mpylist are odd. # mult[0], the index on multiplier 2, must not equal 1. It may equal zero, or any integer > 1, # provided the zlim constraint is met. From john at fouhy.net Wed Aug 9 05:37:46 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 9 Aug 2006 15:37:46 +1200 Subject: [Tutor] Exercise in writing a python function. In-Reply-To: <44D94E82.000013.00176@YOUR-4105E587B6> References: <44D94E82.000013.00176@YOUR-4105E587B6> Message-ID: <5e58f2e40608082037iad27a01gfa1ce20272acbda8@mail.gmail.com> On 09/08/06, Kermit Rose wrote: > def incr(mult,z,zlim,mpylist): > # mult is a vector of exponents for the multipliers in mpylist. > # z is a positive odd integer. > # zlim is the upper bound critical value for the sum of ( mpylist[k][0] * > mpylist[k][1] ) > # where kth multiplier is mpylist [k][0] > # and kth multiplier index is mpylist [k][1] > > # function incr returns the next value of vector mult. > # mult may be thought as a number written in a variable base. > # mult[0] is the least significant and matches multiplier mpylist[0][0] > # adding one to mult would mean adding 1 to mult[0] > # unless doing so would make sum of multiplier * index exceed zlim. > # in that case mult[0] is set to zero, and 1 is added to mult[1] > # unless doing so would make sum of multilier * index exceed zlim > # in that case, mult[0] and mult[1] is set to zero, > # and 1 is added to mult[2] > # unless . . . > > > # mult[0] is set to -1 to indicate that the largest possible value of mult > has been exceeded. > # mpylist[0][0] = 2 and all other multipliers in mpylist are odd. > # mult[0], the index on multiplier 2, must not equal 1. It may equal zero, > or any integer > 1, > # provided the zlim constraint is met. Hi Kermit, Is there anything particular that you're stuck on? I think I understand your function, although I'm not sure what role z plays. Are you looking for help on how to translate the description you've given into logic suitable for programming? -- John. From john at fouhy.net Wed Aug 9 06:04:27 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 9 Aug 2006 16:04:27 +1200 Subject: [Tutor] Exercise in writing a python function. In-Reply-To: <44D95C9D.000015.00176@YOUR-4105E587B6> References: <5e58f2e40608082037iad27a01gfa1ce20272acbda8@mail.gmail.com> <44D95C9D.000015.00176@YOUR-4105E587B6> Message-ID: <5e58f2e40608082104w6ebefe62h5cfd5310a5175b31@mail.gmail.com> On 09/08/06, Kermit Rose wrote: > Hello John. > > Thanks for replying. > > In my previous version, I used z as the critical value,. > > Since I created zlim, a function of z, to be passed in as a parameter, I no > longer need z > > in the parameter list. > > In another part of the program, z is multiplied by > > product of mpylist[ k][0] ** mult[k] for k in range(len(mpylist)). > > > I'm feeling something akin to writer's block when I sit down and attempt to > start the code. > > I know that if I can just get started then the rest of the code will begin > to flow in my thoughts. > > I did not really expect anyone to help me, but if you wish to indicate the > first few lines of > > either python or psuedo code > for this routine, it probably will help me get started. > > > Kermit < kermit at polaris.net > Hi Kermit, Your basic data structure is a list (actually, several related lists), which you work your way through. So I would start off with a for loop: for k in range(len(mult)): Then, in the body of the loop, your basic logic is: Add 1 to mult[k]. If mult[k] is not too big, exit. Otherwise, ... Hmm, actually, I'm not sure I do understand. Does mpylist ever change? How is mult related to zlim? -- John. From alan.gauld at freenet.co.uk Wed Aug 9 09:14:24 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 08:14:24 +0100 Subject: [Tutor] searching for a string in a dictionary References: <20060808234819.11532.qmail@web55913.mail.re3.yahoo.com> Message-ID: <003101c6bb83$7195cb30$0201a8c0@XPpro> > all_types: > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}> > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}> > ..... > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}> > there is such a list > > how do i search for a particular string say teststring in this list This isn't a list in any sense that Python will recognise. Can you show us the actual data structures please? > if teststring in all_types: This would only work if teststring was exactly equal to a whole string in your list, partial string matches only work against a single string: >>> if "fred" in ["fred", "jack"]: print True True >>> if "red" in ["fred", "jack"]: print True >>> >>> for item in ["fred", "jack"]: >>> if "red" in item: print item ... fred >>> > if teststring in all_types.type: No idea what you think this would do. lists don't have a type attribute and you can't access bits of strings that way either. What Python tutorial are you reading? Almost all the tutorials cover string searching and list access. > should i use lambda Almost certainly not. Why do you think lambda would be useful here? Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Aug 9 09:30:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 08:30:03 +0100 Subject: [Tutor] Exercise in writing a python function. References: <44D94E82.000013.00176@YOUR-4105E587B6> Message-ID: <003501c6bb85$a13ea6c0$0201a8c0@XPpro> > The current specifications for the function are: > > def incr(mult,z,zlim,mpylist): > # mult is a vector of exponents for the multipliers in mpylist. > # z is a positive odd integer. > # zlim is the upper bound critical value for the sum of ( > mpylist[k][0] * > mpylist[k][1] ) Just to clarify what this means. you have mpylist = [(2,3),(3,5),(5,7)] So the products list is: [6,15,35] So zlim in this case should be greater than the sum of products: 6+15+35 = 56 Have I got that right? > # where kth multiplier is mpylist [k][0] > # and kth multiplier index is mpylist [k][1] Not sure what you mean by the multiplier index? The sum above shows mpylist[k][1] being used in the multiplication, not as an index? > # function incr returns the next value of vector mult. I'm still not clear what mult does, your example above doesn't refer to mult anywhere? > # mult may be thought as a number written in a variable base. > # mult[0] is the least significant and matches multiplier > mpylist[0][0] > # adding one to mult would mean adding 1 to mult[0] > # unless doing so would make sum of multiplier * index exceed zlim. > # in that case mult[0] is set to zero, and 1 is added to mult[1] > # unless doing so would make sum of multilier * index exceed zlim > # in that case, mult[0] and mult[1] is set to zero, > # and 1 is added to mult[2] > # unless . . . Sorry, you lost me there, can you provide a concrete example? Or maybe some of our resident math experts recognise what you are up to and can explain? Brian? Danny? > # mult[0] is set to -1 to indicate that the largest possible value > of mult > has been exceeded. > # mpylist[0][0] = 2 and all other multipliers in mpylist are odd. > # mult[0], the index on multiplier 2, must not equal 1. It may > equal zero, > or any integer > 1, > # provided the zlim constraint is met. The only guidance I'd give in this kind of situation is that I'd adopt functional programming approaches and try to copy the structure of the spec in my code. This will be a bitch to test/debug unless you have a wealth of manually validated examples to use as test cases! HTH Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From john at fouhy.net Wed Aug 9 09:41:56 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 9 Aug 2006 19:41:56 +1200 Subject: [Tutor] searching for a string in a dictionary In-Reply-To: <003101c6bb83$7195cb30$0201a8c0@XPpro> References: <20060808234819.11532.qmail@web55913.mail.re3.yahoo.com> <003101c6bb83$7195cb30$0201a8c0@XPpro> Message-ID: <5e58f2e40608090041q526b8e93uab1c620e4b40b74f@mail.gmail.com> On 09/08/06, Alan Gauld wrote: > > all_types: > > > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}> > > > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}> > > ..... > > > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}> > > there is such a list > > > > how do i search for a particular string say teststring in this list > > This isn't a list in any sense that Python will recognise. > Can you show us the actual data structures please? I think what he wants is: if 'teststring' in [s.type for s in all_types] ... -- John. From alan.gauld at freenet.co.uk Wed Aug 9 09:42:48 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 08:42:48 +0100 Subject: [Tutor] Unusual behavior in readline References: <8249c4ac0608080900p40c2a307yae7134171c2cff4c@mail.gmail.com> <003501c6bb2f$61bf45a0$0201a8c0@XPpro> <8249c4ac0608081705m317ba719g8de1eef84e1b4ce5@mail.gmail.com> Message-ID: <004101c6bb87$69490510$0201a8c0@XPpro> >>>You don't need to initialise Entry, the for loop does that for you. > > just a habit- I've always initialized my vars up front. > so I know they are initialized. Fair enough, good practice for other languages certainly. >> >>BTW Why not just put all this stuff in the body of the try? > > Because the try is only setup to catch an IO error. > If something other than an IOerror were to occur, it would be > missed unless other exceptions were trapped. Its missed in the else clause too. But the else clause adds two extra control structures (the except and the else) to the code for the reader to negotiate which significantly impairs comprehension of the main execution path. > The most probable is the IOerror, which is why I trapped it. Which is fine but no reason to put the except clause immediately after the try line, that just clutters the code block. >>>You should very rarely need an else clause when using try/except. > If the exception doesn't happen, then what ? The code just goes through: try: if False: raise ValueError # never happens print 'hello' print 'world' print 'this code is pretty safe' except ValueError: print 'its a mistake!" No need for an else clause. > That's what the else clause is for Nope, the else clause is for a few unusual cases where you need to do stuff if no exception occurs that is not part of the main processing. I've only ever seen a real valid use of it once in dealing with housekeeping of sockets, and even there a finally block could have been used at the cost of an extra try statement. The else just kept it a bit tidier. But else should not be used for mainstream processing. One of the biggest advantages of try/except handling is that it removes all the error processing out of the way of the reader to the bottom of the block. You can just write the happy path stuff as a continuous sequence without worrying about error paths. (FWIW This is also the recommended practice in writing use cases, for the same reasons) Of course else can be used as you did and the code will work, but you lose a big advantage of try/except style. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Aug 9 10:03:58 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 09:03:58 +0100 Subject: [Tutor] searching for a string in a dictionary References: <20060808234819.11532.qmail@web55913.mail.re3.yahoo.com> <003101c6bb83$7195cb30$0201a8c0@XPpro> <5e58f2e40608090041q526b8e93uab1c620e4b40b74f@mail.gmail.com> Message-ID: <000301c6bb8a$5e867970$0201a8c0@XPpro> > On 09/08/06, Alan Gauld wrote: >> > all_types: >> > > > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}> >> > >> > how do i search for a particular string say teststring in this >> > list >> > I think what he wants is: > > if 'teststring' in [s.type for s in all_types] But type is still not accessible as an attribute. It looked to me like he wanted a list of dictionaries in which case it wouyld be: if teststring in [s['type'] for s in all_types] But the submitted data is not in any usable format so far as Python is concxerned and the data structure will be critical to how the code works. Anil, we need to get more specific information from you about your code and error messages, we can't guess what you have done. Alan G From john at fouhy.net Wed Aug 9 10:14:51 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 9 Aug 2006 20:14:51 +1200 Subject: [Tutor] searching for a string in a dictionary In-Reply-To: <000301c6bb8a$5e867970$0201a8c0@XPpro> References: <20060808234819.11532.qmail@web55913.mail.re3.yahoo.com> <003101c6bb83$7195cb30$0201a8c0@XPpro> <5e58f2e40608090041q526b8e93uab1c620e4b40b74f@mail.gmail.com> <000301c6bb8a$5e867970$0201a8c0@XPpro> Message-ID: <5e58f2e40608090114n44bcd2d6xb38dc5953a52d759@mail.gmail.com> On 09/08/06, Alan Gauld wrote: > But type is still not accessible as an attribute. > It looked to me like he wanted a list of dictionaries > in which case it wouyld be: > > if teststring in [s['type'] for s in all_types] Err, that is what I meant :-) -- John. From hokkakada at khmeros.info Wed Aug 9 10:36:05 2006 From: hokkakada at khmeros.info (kakada) Date: Wed, 09 Aug 2006 15:36:05 +0700 Subject: [Tutor] python import problem Message-ID: <44D99E75.3010902@khmeros.info> Hi all, I have problem with import statement. supposed that I have two files in different folders : modules/myfile.py and translate/factory.py. the folders modules and translate are in the same level, so if I want to import factory.py into myfile.py, how can I do? I have already done in myfile.py: from translate import factory but it is still not work. Any solution? Thanks and regards, da From anilmrn at yahoo.com Wed Aug 9 11:55:11 2006 From: anilmrn at yahoo.com (anil maran) Date: Wed, 9 Aug 2006 02:55:11 -0700 (PDT) Subject: [Tutor] searching for a string in a dictionary In-Reply-To: <000301c6bb8a$5e867970$0201a8c0@XPpro> Message-ID: <20060809095511.39539.qmail@web55904.mail.re3.yahoo.com> if teststring in [s['type'] for s in all_types]: print 'contained' else: print 'notcontained' this worked thanks a lot guys pyTutor rocks Alan Gauld wrote: > On 09/08/06, Alan Gauld wrote: >> > all_types: >> > >> > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}> >> > >> > how do i search for a particular string say teststring in this >> > list >> > I think what he wants is: > > if 'teststring' in [s.type for s in all_types] But type is still not accessible as an attribute. It looked to me like he wanted a list of dictionaries in which case it wouyld be: if teststring in [s['type'] for s in all_types] But the submitted data is not in any usable format so far as Python is concxerned and the data structure will be critical to how the code works. Anil, we need to get more specific information from you about your code and error messages, we can't guess what you have done. Alan G --------------------------------- Get your email and more, right on the new Yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060809/5a7561d2/attachment.html From anilmrn at yahoo.com Wed Aug 9 11:59:53 2006 From: anilmrn at yahoo.com (anil maran) Date: Wed, 9 Aug 2006 02:59:53 -0700 (PDT) Subject: [Tutor] searching for a string in a dictionary In-Reply-To: <000301c6bb8a$5e867970$0201a8c0@XPpro> Message-ID: <20060809095953.3795.qmail@web55911.mail.re3.yahoo.com> doesTypeExist=filter(lambda x: typeofstring in x.type, all_types) if 'teststring' in [s.type for s in all_types] this works which is better in terms of speed??? for+in or filter+lambda thanks a lot Alan Gauld wrote: > On 09/08/06, Alan Gauld wrote: >> > all_types: >> > >> > datetime.datetime(2006, 7, 26, 15, 18, 34, 887436)}> >> > >> > how do i search for a particular string say teststring in this >> > list >> > I think what he wants is: > > if 'teststring' in [s.type for s in all_types] But type is still not accessible as an attribute. It looked to me like he wanted a list of dictionaries in which case it wouyld be: if teststring in [s['type'] for s in all_types] But the submitted data is not in any usable format so far as Python is concxerned and the data structure will be critical to how the code works. Anil, we need to get more specific information from you about your code and error messages, we can't guess what you have done. Alan G --------------------------------- Want to be your own boss? Learn how on Yahoo! Small Business. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060809/a5094310/attachment.htm From anilmrn at yahoo.com Wed Aug 9 12:00:51 2006 From: anilmrn at yahoo.com (anil maran) Date: Wed, 9 Aug 2006 03:00:51 -0700 (PDT) Subject: [Tutor] html file - construct attach send... email python Message-ID: <20060809100051.12465.qmail@web55903.mail.re3.yahoo.com> What is the best way to construct an email in python and also attach a html file the html file to be attached is not on disk, but should be dynamically constructed in the python script thanks a lot --------------------------------- Stay in the know. Pulse on the new Yahoo.com. Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060809/ab52339d/attachment.html From asdlinux at yahoo.se Wed Aug 9 12:28:58 2006 From: asdlinux at yahoo.se (=?ISO-8859-1?Q?Magnus_Wirstr=F6m?=) Date: Wed, 09 Aug 2006 12:28:58 +0200 Subject: [Tutor] Global Variables Message-ID: <44D9B8EA.9040600@yahoo.se> Hi I know that this was in the list in the last days but i deleted it by mistake. How to use global variables? Or perhaps you could point me to another solution. I'm converting a packup app that i made to a gui driven app. The console app was very straight forward and didn't use any own functions. That was working fine then but i discover now that i probably have to rethink that because i need to communicate to different events. I'm new to all this so i have a problem to approach this. I would be really happy if you could give me hints and tips or suggestions how to make this. The gui i want to work with is wxPython and i'm using Boa Constructor to build my gui and app. Thanks Magnus From samrobertsmith at gmail.com Wed Aug 9 12:49:15 2006 From: samrobertsmith at gmail.com (linda.s) Date: Wed, 9 Aug 2006 03:49:15 -0700 Subject: [Tutor] about tkinter Message-ID: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com> Is that possible to open two Tkinter from one python shell? From alan.gauld at freenet.co.uk Wed Aug 9 13:11:44 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 12:11:44 +0100 Subject: [Tutor] searching for a string in a dictionary References: <20060809095953.3795.qmail@web55911.mail.re3.yahoo.com> Message-ID: <001301c6bba4$99e85a50$0201a8c0@XPpro> > doesTypeExist=filter(lambda x: typeofstring in x.type, all_types) > > if 'teststring' in [s.type for s in all_types] > this works which is better in terms of speed??? These do two different things. The first returns a list of all_types entries that match The second returns true or false if *any* string matches. The first can be rewritten without lambda using a list comprehension: [ item for item in all_types if teststring in item['type'] ] Calling functions in python is usually fairly slow so using filter/lambda with its function call per item is probably slower than either of the list comprehension methods. If in doubt measure it... Alan G. From alan.gauld at freenet.co.uk Wed Aug 9 13:16:03 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 12:16:03 +0100 Subject: [Tutor] python import problem References: <44D99E75.3010902@khmeros.info> Message-ID: <003501c6bba5$3418db40$0201a8c0@XPpro> > the folders modules and translate are in the same level, so if I > want to > import factory.py into myfile.py, how can I do? You need to make your folders into packages. Its fairly simple, you basically create an init.py file But its worth reading about packages in the docs Come back here ifv you have any questions after that. The other way would be to add each folder to your PYTHONPATH HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kermit at polaris.net Wed Aug 9 16:02:53 2006 From: kermit at polaris.net (Kermit Rose) Date: Wed, 9 Aug 2006 10:02:53 -0400 (Eastern Daylight Time) Subject: [Tutor] Exercise in writing a python function. References: <003501c6bb85$a13ea6c0$0201a8c0@XPpro> Message-ID: <44D9EB0D.000007.03316@YOUR-4105E587B6> From: Alan Gauld Date: 08/09/06 03:30:28 To: Kermit Rose; tutor at python.org Subject: Re: [Tutor] Exercise in writing a python function. > The current specifications for the function are: > > def incr(mult,z,zlim,mpylist): > # mult is a vector of exponents for the multipliers in mpylist. > # z is a positive odd integer. > # zlim is the upper bound critical value for the sum of ( > mpylist[k][0] * > mpylist[k][1] ) Just to clarify what this means. you have mpylist = [(2,3),(3,5),(5,7)] So the products list is: [6,15,35] So zlim in this case should be greater than the sum of products: 6+15+35 = 56 ******* Oops. That is what I said. I made a mistake in the specificiations. I should have specified that for this example that 3*mult[0] + 5 * mult[1] + 7 * mult[2] must be < zlim. >>>>> # where kth multiplier is mpylist [k][0] > # and kth multiplier index is mpylist [k][1] Not sure what you mean by the multiplier index? The sum above shows mpylist[k][1] being used in the multiplication, not as an index? ****** Yes. It's confusing because of my mistake of confusing mpylist[k][1] with mult[k]. >>>> > # function incr returns the next value of vector mult. I'm still not clear what mult does, your example above doesn't refer to mult anywhere? ***** Yes, another consequence of my mistake in the specifications. Kermit < kermit at polaris.net > From kermit at polaris.net Wed Aug 9 16:13:20 2006 From: kermit at polaris.net (Kermit Rose) Date: Wed, 9 Aug 2006 10:13:20 -0400 (Eastern Daylight Time) Subject: [Tutor] Exercise in writing a python function Message-ID: <44D9ED80.00000B.03316@YOUR-4105E587B6> Message: 2 Date: Wed, 9 Aug 2006 16:04:27 +1200 From: "John Fouhy" Subject: Re: [Tutor] Exercise in writing a python function. To: "Tutor mailing list" Hi Kermit, Your basic data structure is a list (actually, several related lists), which you work your way through. So I would start off with a for loop: for k in range(len(mult)): Then, in the body of the loop, your basic logic is: Add 1 to mult[k]. If mult[k] is not too big, exit. Otherwise, ... Hmm, actually, I'm not sure I do understand. Does mpylist ever change? How is mult related to zlim? -- John. ***** Thank you. I confused things by my mistake in the specifications. The criterion for exiting the outer loop is that mpylist[0][1] * mult[0] + mpylist[1][1] * mult[1] + mpylist[2][1] * mult[2] + . . . be > zlim. From tpwilson at hotmail.co.uk Tue Aug 8 16:53:10 2006 From: tpwilson at hotmail.co.uk (Tom Wilson) Date: Tue, 08 Aug 2006 15:53:10 +0100 Subject: [Tutor] python Message-ID: could someone explain to me how the "import" function works? tom _________________________________________________________________ The new Windows Live Toolbar helps you guard against viruses http://toolbar.live.com/?mkt=en-gb From kermit at polaris.net Wed Aug 9 16:46:59 2006 From: kermit at polaris.net (Kermit Rose) Date: Wed, 9 Aug 2006 10:46:59 -0400 (Eastern Daylight Time) Subject: [Tutor] programming exercise in Python Message-ID: <44D9F563.00000F.03316@YOUR-4105E587B6> Thanks to John, I've written tenative code for the incr routine. Now to test and possibly debug it. Here is the routine. It's very short. # # # def incr(mult,zlim,mpylist): # # mult is a vector of exponents for the multipliers in mpylist. # # z is the integer to be factored # # zlim is the critical value for the sum of multiplier * index # # where kth multiplier is mpylist [k][0] # # and kth index is mpylist [k][1] # # # function incr returns the next value of vector mult. # # mult may be thought as a number written in a variable base. # # mult[0] is the least significant and matches multiplier mpylist[0][0] # # adding one to mult would mean adding 1 to mult[0] # # unless doing so would make sum of mpylist[k][1] * mult[k] exceed zlim. # # in that case mult[0] is set to zero, and 1 is added to mult[1] # # unless doing so would make sum of multilier * index exceed zlim # # in that case, mult[0] and mult[1] is set to zero, # # and 1 is added to mult[2] # # unless . . . # # # # mult[0] is set to -1 to indicate that the largest possible value of mult has been exceeded. # # mpylist[0] = 2 and all other values in mpylist are odd. # # mult[0], the index on multiplier 2, must not equal 1. It may equal zero or any integer > 1, # # provided it meets the zlim constraint. # # lenmult = len(mult) # for k in range(lenmult): # mult[k] = mult[k] + 1 # if k == 0: # if mult[k] == 1: # mult[k] = 2 # testsum = 0 # if k > 0: # mult[k-1] = 0 # for j in range(k,lenmult): # testsum = testsum + mpylist[j][1] * mult[j] # if testsum < zlim: # return mult # mult[0] = -1 # return mult # # From dyoo at hkn.eecs.berkeley.edu Wed Aug 9 17:00:55 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Aug 2006 08:00:55 -0700 (PDT) Subject: [Tutor] programming exercise in Python In-Reply-To: <44D9F563.00000F.03316@YOUR-4105E587B6> References: <44D9F563.00000F.03316@YOUR-4105E587B6> Message-ID: On Wed, 9 Aug 2006, Kermit Rose wrote: > I've written tenative code for the incr routine. > > Now to test and possibly debug it. Just as a note: it's usually a much better idea to write your test cases first, even before writing any code. It'll give you a better idea of what you want your function to do. (It'll also probably give the other here a better idea of what the function is supposed to do. I myself don't quite know either what it's supposed to do based solely on the description. *grin*) What are some small test cases you're thinking of for this function? From dyoo at hkn.eecs.berkeley.edu Wed Aug 9 17:05:09 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Aug 2006 08:05:09 -0700 (PDT) Subject: [Tutor] python In-Reply-To: References: Message-ID: On Tue, 8 Aug 2006, Tom Wilson wrote: > could someone explain to me how the "import" function works? Hi Tom, Take a look at: http://www.python.org/doc/tut/node8.html and see if that helps; if not, come back and please feel free to ask more questions about it. In a short summary: import allows us to load additional "modules" into our program. These modules are often written by other people, and provide a lot of interesting functions. There are a set of modules that come standard with each Python distribution: http://www.python.org/doc/lib/ For example, if we wanted to get an approximate value for pi, we could find that in the 'math' module: http://www.python.org/doc/lib/module-math.html and to use it, we'd use 'import' to first pull math support into our program: ###### import math ###### after which we can reach in and get a piece of pi: ###### print math.pi ###### From dyoo at hkn.eecs.berkeley.edu Wed Aug 9 17:07:45 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Aug 2006 08:07:45 -0700 (PDT) Subject: [Tutor] about tkinter In-Reply-To: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com> References: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com> Message-ID: On Wed, 9 Aug 2006, linda.s wrote: > Is that possible to open two Tkinter from one python shell? It is possible to open more Tkinter "toplevel" windows. Is this what you are asking for? See: http://www.pythonware.com/library/tkinter/introduction/toplevel.htm If we build a new Toplevel, we should see a new window on our screen. From dyoo at hkn.eecs.berkeley.edu Wed Aug 9 17:18:30 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Aug 2006 08:18:30 -0700 (PDT) Subject: [Tutor] html file - construct attach send... email python In-Reply-To: <20060809100051.12465.qmail@web55903.mail.re3.yahoo.com> References: <20060809100051.12465.qmail@web55903.mail.re3.yahoo.com> Message-ID: On Wed, 9 Aug 2006, anil maran wrote: > What is the best way to construct an email in python and also attach a > html file Hi Anil, This is a repeat of one of your previous questions; you just sent this question out yesterday: http://mail.python.org/pipermail/tutor/2006-August/048452.html We are forgetful, but we're not THAT senile yet. Please do not repost your questions so early: give some people more time to construct a good answer for you. Repeating a question so soon like this tends to demotivate people. Have you looked at the 'email' module? http://www.python.org/doc/lib/module-email.html And in general, do you know about the Standard Library, or the Python Cookbook? http://www.python.org/doc/lib/ http://aspn.activestate.com/ASPN/Python/Cookbook/ I want to make sure you know about these documentation resources. Good luck to you. From alan.gauld at freenet.co.uk Wed Aug 9 18:36:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 17:36:42 +0100 Subject: [Tutor] about tkinter References: <1d987df30608090349o5643cf8do41a0ae6f8aa169e2@mail.gmail.com> Message-ID: <001d01c6bbd1$ff361050$0201a8c0@XPpro> Linda, > Is that possible to open two Tkinter from one python shell? Tkinter is a python module. You can't really open a Tkinter, you can only import the module. What you can do is write a Tkinter application with multiple windows. You can have as many Tkinter applications running as you like but they will all be separate processes. Can you be clearer about what exactly you want to do? Alan G. From kermit at polaris.net Wed Aug 9 18:39:24 2006 From: kermit at polaris.net (Kermit Rose) Date: Wed, 9 Aug 2006 12:39:24 -0400 (Eastern Daylight Time) Subject: [Tutor] programming exercise in Python References: Message-ID: <44DA0FBC.000011.03316@YOUR-4105E587B6> From: Danny Yoo Date: 08/09/06 11:01:14 To: Kermit Rose Cc: tutor at python.org Subject: Re: [Tutor] programming exercise in Python On Wed, 9 Aug 2006, Kermit Rose wrote: > I've written tenative code for the incr routine. > > Now to test and possibly debug it. Just as a note: it's usually a much better idea to write your test cases first, even before writing any code. It'll give you a better idea of what you want your function to do. (It'll also probably give the other here a better idea of what the function is supposed to do. I myself don't quite know either what it's supposed to do based solely on the description. *grin*) What are some small test cases you're thinking of for this function? s function? ******** Hello Danny. The test cases are For mpylist = [[2, 1], [3, 2], [7, 3], [5, 2], [31, 5], [127, 7]] zlim = 7 Initial value of mult = [0,0,0,0,0,0] next few values of mult are: [2, 0, 0, 0, 0, 0] because mult[0] must skip over value of 1 and 2 * 1 < 7 [3, 0, 0, 0, 0, 0] because 3 * 1 < 7 [4, 0, 0, 0, 0, 0] because 4 * 1 < 7 [5, 0, 0, 0, 0, 0] because 5 * 1 < 7 [6, 0, 0, 0, 0, 0] because 6 * 1 < 7 [0, 1, 0, 0, 0, 0] because 1 * 2 < 7 [2, 1, 0, 0, 0, 0] because 2 * 1 + 1 * 2 < 7 [3, 1, 0, 0, 0, 0] because 3 * 1 + 1 * 2 < 7 [4, 1, 0, 0, 0, 0] because 4 * 1 + 1 * 2 < 7 [0, 2, 0, 0, 0, 0] because 0 * 1 + 2 * 2 < 7 [2, 2, 0, 0, 0, 0] because 2 * 1 + 2 * 2 < 7 and mult[0] value must skip 1 [0, 3, 0, 0, 0, 0] because 0 * 1 + 3 * 2 < 7 [0, 0, 1, 0, 0, 0] because 0 * 1 + 0 * 2 + 1 * 3 < 7 [2, 0, 1, 0, 0, 0] because 2 * 1 + 0 * 2 + 1 * 3 < 7 [3, 0, 1, 0, 0, 0] because 3 * 1 + 0 * 2 + 1 * 3 < 7 [0, 1, 1, 0, 0, 0] because 0 * 1 + 1 * 2 + 1 * 3 < 7 I had the program generate the test cases for me, and then inspected them to verify that they were what I desired. The subroutine passed this initial test. Thanks From alan.gauld at freenet.co.uk Wed Aug 9 18:39:41 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 17:39:41 +0100 Subject: [Tutor] Exercise in writing a python function References: <44D9ED80.00000B.03316@YOUR-4105E587B6> Message-ID: <002701c6bbd2$69cf7e10$0201a8c0@XPpro> > I confused things by my mistake in the specifications. > > The criterion for exiting the outer loop is that > > mpylist[0][1] * mult[0] + mpylist[1][1] * mult[1] + mpylist[2][1] * > mult[2] > + . . . > > be > zlim. Can you try rewriting the spec correctly, because I'm still not sure I understand it? Are you now saying that mpylist[n][0] is never used? Can you show us some sample data structures - just a few entries and how the calculations should work? Alan G. From alan.gauld at freenet.co.uk Wed Aug 9 18:41:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 17:41:42 +0100 Subject: [Tutor] python References: Message-ID: <002b01c6bbd2$b2552a90$0201a8c0@XPpro> Tom, > could someone explain to me how the "import" function works? Which tutorial are you reading? They should all describe import. My tutorial gives the basic description on the Simple sequences topic and then much more info in the Modules & Functions topic and again in the Namespaces topic. Between them and the Python documentation you should find all you need. But if you are still puzzled come back to us with specific questions. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Aug 9 18:53:48 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 17:53:48 +0100 Subject: [Tutor] programming exercise in Python References: <44D9F563.00000F.03316@YOUR-4105E587B6> Message-ID: <002f01c6bbd4$62ff57c0$0201a8c0@XPpro> > # lenmult = len(mult) This is pretty redundant, it only saves two characters typing, you might as well do for k in range(len(mult)): > # for k in range(lenmult): > # mult[k] = mult[k] + 1 > # if k == 0: > # if mult[k] == 1: > # mult[k] = 2 The whole of this bit only happens on the first time through the outer loop. The effect of it is to set mult[0] to 2 if its initial value was 0, so why not move it outside the loop and do: if mult[0] == 0: mult[0] = 1 Then the increment of the whole list will uplift it to 2 along with all the other increments. > # testsum = 0 > # if k > 0: > # mult[k-1] = 0 > # for j in range(k,lenmult): > # testsum = testsum + mpylist[j][1] * mult[j] My brain is bending with this bit! I'm not sure if its right or not... I'm still not sure i understand what its trying to do... > # if testsum < zlim: > # return mult > # mult[0] = -1 > # return mult But I think this can be better expressed as: if testsum >= zlim: mult[0] = -1 # failure condiotion return mult As a matter of interest what does this bizarre algorithm accomplish in a practical sense? What is its purpose? I am truly intrigued... HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kermit at polaris.net Wed Aug 9 19:29:49 2006 From: kermit at polaris.net (Kermit Rose) Date: Wed, 9 Aug 2006 13:29:49 -0400 (Eastern Daylight Time) Subject: [Tutor] programming exercise in Python References: <002f01c6bbd4$62ff57c0$0201a8c0@XPpro> Message-ID: <44DA1B8D.000015.03316@YOUR-4105E587B6> From: Alan Gauld Date: 08/09/06 12:53:59 To: Kermit Rose; tutor at python.org Subject: Re: [Tutor] programming exercise in Python > # lenmult = len(mult) This is pretty redundant, it only saves two characters typing, you might as well do ****** hmm.... I had gotten in the habit of replacing potential multiple function calls and array references with variable name references acting from the hypothesis that variable name references take much less time than array referrences or function calls. I agree that in this case I did not need to do so. >>>>>>> for k in range(len(mult)): > # for k in range(lenmult): > # mult[k] = mult[k] + 1 > # if k == 0: > # if mult[k] == 1: > # mult[k] = 2 The whole of this bit only happens on the first time through the outer loop. The effect of it is to set mult[0] to 2 if its initial value was 0, so why not move it outside the loop and do: if mult[0] == 0: mult[0] = 1 Then the increment of the whole list will uplift it to 2 along with all the other increments. ****** Yes. I see that now. I did see that I asked the computer to do extra work by having it do work conditional of the initial value of k, but did not immediately see how to move that work outside the loop. >>>>>>>> > # testsum = 0 > # if k > 0: > # mult[k-1] = 0 > # for j in range(k,lenmult): > # testsum = testsum + mpylist[j][1] * mult[j] My brain is bending with this bit! I'm not sure if its right or not... I'm still not sure i understand what its trying to do... for k = 0, checks to see if it may add 1 to mult[0] for k = 1, sets mult[0] = 0, and checks to see if it may add 1 to mult[1] for k = 2, sets mult[1] = 0, and checks to see if it may add 1 to mult[2], etc >>>>>>>>>>>> > # if testsum < zlim: > # return mult > # mult[0] = -1 > # return mult But I think this can be better expressed as: if testsum >= zlim: mult[0] = -1 # failure condiotion return mult ***** The indentation did not survive repeated postings. .. if testsum < zlim: .. return mult .. mult[0] = -1 .. return mult if testsum < zlim I return mult if testsum >= zlim, I advance the k loop failure condition is that it get all the way through the k loop and not be able to increment mult. >>>>>>>>> As a matter of interest what does this bizarre algorithm accomplish in a practical sense? What is its purpose? I am truly intrigued... ******* :) The incr routine generates a vector of exponents to apply to the list mpylist [n] [0] m = product of mpylist [k] [0] ** mult[k] Another subroutine uses the number m in an algorithm I've devised, to find a divisor of the number z, from which I had calculated the critical value of zlim, and the mpylist vector. Experimentation will tell if this factor routine is as good as I would like it to be. Kermit < kermit at polaris.net > From alan.gauld at freenet.co.uk Wed Aug 9 19:51:47 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 18:51:47 +0100 Subject: [Tutor] programming exercise in Python References: <002f01c6bbd4$62ff57c0$0201a8c0@XPpro> <44DA1B8D.000015.03316@YOUR-4105E587B6> Message-ID: <000501c6bbdc$7ca22c40$0201a8c0@XPpro> >> # testsum = 0 >> # if k > 0: >> # mult[k-1] = 0 >> # for j in range(k,lenmult): >> # testsum = testsum + mpylist[j][1] * mult[j] > > My brain is bending with this bit! I'm not sure if its right or > not... > > for k = 0, checks to see if it may add 1 to mult[0] > for k = 1, sets mult[0] = 0, and checks to see if it may add 1 to > mult[1] > for k = 2, sets mult[1] = 0, and checks to see if it may add 1 to > mult[2], So you work along mult setting each member to zero after incrementing it? > The incr routine generates a vector of exponents to apply to the > list > > mpylist [n] [0] > > m = product of mpylist [k] [0] ** mult[k] > But haven't you set all of mult[k] to zero, using the example algorithm above? > Experimentation will tell if this factor routine is as good as I > would like > it to be. Its got me baffled, thats for sure! :-) Alan G. From kermit at polaris.net Wed Aug 9 20:28:26 2006 From: kermit at polaris.net (Kermit Rose) Date: Wed, 9 Aug 2006 14:28:26 -0400 (Eastern Daylight Time) Subject: [Tutor] programming exercise in Python References: <000501c6bbdc$7ca22c40$0201a8c0@XPpro> Message-ID: <44DA294A.000019.03316@YOUR-4105E587B6> From: Alan Gauld Date: 08/09/06 13:52:09 To: Kermit Rose Cc: tutor at python.org Subject: Re: [Tutor] programming exercise in Python >> # testsum = 0 >> # if k > 0: >> # mult[k-1] = 0 >> # for j in range(k,lenmult): >> # testsum = testsum + mpylist[j][1] * mult[j] > > My brain is bending with this bit! I'm not sure if its right or > not... > > for k = 0, checks to see if it may add 1 to mult[0] > for k = 1, sets mult[0] = 0, and checks to see if it may add 1 to > mult[1] > for k = 2, sets mult[1] = 0, and checks to see if it may add 1 to > mult[2], So you work along mult setting each member to zero after incrementing it? ****** Yes. After each member has gone through all allowed incrementations, I reset it to zero. Remember that mult is returned as soon as any member is incremented. >>>>>>>>> > The incr routine generates a vector of exponents to apply to the > list > > mpylist [n] [0] > > m = product of mpylist [k] [0] ** mult[k] > But haven't you set all of mult[k] to zero, using the example algorithm above? ******* Ah, now I understandd how I misled you. > for k = 0, checks to see if it may add 1 to mult[0] if it can add 1 to mult[0], do so, and return mult. otherwise continue > for k = 1, sets mult[0] = 0, and checks to see if it may add 1 to > mult[1] if it can add 1 to mult[1], do so, and return mult. otherwise continue > for k = 2, sets mult[1] = 0, and checks to see if it may add 1 to > mult[2], if it can add 1 to mult[2], do so, and return mult. otherwise continue etc Kermit < kermit at polaris.net > From dyoo at hkn.eecs.berkeley.edu Wed Aug 9 22:23:04 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Aug 2006 13:23:04 -0700 (PDT) Subject: [Tutor] programming exercise in Python In-Reply-To: <44DA0FBC.000011.03316@YOUR-4105E587B6> References: <44DA0FBC.000011.03316@YOUR-4105E587B6> Message-ID: > I had the program generate the test cases for me, and then inspected > them to verify that they were what I desired. Hi Kermit, Ah. Try not to do that next time. It's way too easy to be convinced that some test is working by just copying the output of the code and looking for reasonable output. But it's much more useful to write out the complete test case without preconceptions, without the aid of the code you're trying to test. This works because: * You can't cheat yourself. *grin* * Writing out the test cases first can help in writing the real function. Those test cases act as documentation that other people can look at. They're a form of specification --- a requirement --- that allows others to understand the intent of the function. From tbrannon at utekcorp.com Wed Aug 9 22:21:31 2006 From: tbrannon at utekcorp.com (Terrence Brannon) Date: Wed, 9 Aug 2006 16:21:31 -0400 Subject: [Tutor] html file - construct attach send... email python In-Reply-To: <44DA294A.000019.03316@YOUR-4105E587B6> Message-ID: <4CB7A012BD745F4DBAAC57D05A787D073ABC56@utek-exch.utekcorp.local> Here's a script I wrote to email myself the Python Daily webpage as HTML: http://dev.metaperl.com/Members/tbrannon/python/code-snippets/script-to- email-python-daily/ From pythontut at pusspaws.net Wed Aug 9 22:45:22 2006 From: pythontut at pusspaws.net (dave s) Date: Wed, 9 Aug 2006 20:45:22 +0000 Subject: [Tutor] rstrip() failure ? Message-ID: <200608092045.22580.pythontut@pusspaws.net> I have a string problem. The following code skips the loop if the string 'app' is on the banned list ... self.ban_app_list = [' ', 'live_dat', 'exact_sl', 'html_str', 'valid_da', 'datacore', 'check_co', 'logger'] if app in self.ban_app_list: continue the string 'app' is derived from some more string splicing. All works well except for 'logger', the 'app' string becomes 'logger ' so no match. So I app.rstrip() thinking it would sort the problem. no go :( len(app) is still 8. OK ... I am stuck ... Is there a way to show the ascii values of the string - kind of hexedit for a string I am sure the padding blanks are just spaces rstrip() appears to disagree Any help greatly appreciated Dave From alan.gauld at freenet.co.uk Wed Aug 9 22:45:52 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 21:45:52 +0100 Subject: [Tutor] programming exercise in Python References: <44DA0FBC.000011.03316@YOUR-4105E587B6> Message-ID: <002101c6bbf4$ce7a6560$0201a8c0@XPpro> > it's much more useful to write out the complete test case without > preconceptions, without the aid of the code you're trying to test. > This works because: > * Writing out the test cases first can help in writing the > real function. > > Those test cases act as documentation that other people can look at. Can I echo that. After I saw your test output I immediately understood how the function was supposed to work. If you could have posted that sample input/output data along with the spec before writing the code we could have been much more helpful - I think... ;-) Alan G. From dyoo at hkn.eecs.berkeley.edu Wed Aug 9 23:11:52 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Aug 2006 14:11:52 -0700 (PDT) Subject: [Tutor] rstrip() failure ? In-Reply-To: <200608092045.22580.pythontut@pusspaws.net> References: <200608092045.22580.pythontut@pusspaws.net> Message-ID: > Is there a way to show the ascii values of the string - kind of hexedit > for a string Try running repr() on the string: it will show an external programmer-friendly representation that should be easier to read. For example: ########################## >>> msg = 'hello\000world' >>> print repr(msg) 'hello\x00world' ########################## From pythontut at pusspaws.net Wed Aug 9 23:12:28 2006 From: pythontut at pusspaws.net (dave s) Date: Wed, 9 Aug 2006 21:12:28 +0000 Subject: [Tutor] [Doh!] rstrip() failure ? In-Reply-To: <200608092045.22580.pythontut@pusspaws.net> References: <200608092045.22580.pythontut@pusspaws.net> Message-ID: <200608092112.30697.pythontut@pusspaws.net> On Wednesday 09 August 2006 20:45, dave s wrote: > I have a string problem. The following code skips the loop if the string > 'app' is on the banned list ... > > self.ban_app_list = > [' ', 'live_dat', 'exact_sl', 'html_str', 'valid_da', 'datacore', > 'check_co', 'logger'] > > if app in self.ban_app_list: > continue > > the string 'app' is derived from some more string splicing. All works well > except for 'logger', the 'app' string becomes 'logger ' so no match. So I > > app.rstrip() > > thinking it would sort the problem. no go :( > > len(app) is still 8. OK ... I am stuck ... > > Is there a way to show the ascii values of the string - kind of hexedit for > a string > > I am sure the padding blanks are just spaces rstrip() appears to disagree > > Any help greatly appreciated > > Dave > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Stupid basic error held me up for a couple of hours :) app.rstrip() should have been app = app.rstrip() From pythontut at pusspaws.net Wed Aug 9 23:15:11 2006 From: pythontut at pusspaws.net (dave s) Date: Wed, 9 Aug 2006 21:15:11 +0000 Subject: [Tutor] rstrip() failure ? In-Reply-To: References: <200608092045.22580.pythontut@pusspaws.net> Message-ID: <200608092115.12096.pythontut@pusspaws.net> On Wednesday 09 August 2006 21:11, you wrote: > > Is there a way to show the ascii values of the string - kind of hexedit > > for a string > > Try running repr() on the string: it will show an external > programmer-friendly representation that should be easier to read. For > example: > > ########################## > > >>> msg = 'hello\000world' > >>> print repr(msg) > > 'hello\x00world' > ########################## Thanks for that :) Have just found my solution without resorting to ascii strings after all but the above will be usefull Thanks once again Dave From anilmrn at yahoo.com Thu Aug 10 00:16:37 2006 From: anilmrn at yahoo.com (anil maran) Date: Wed, 9 Aug 2006 15:16:37 -0700 (PDT) Subject: [Tutor] What techniques should I use to make my code run faster? Informational Message-ID: <20060809221637.63184.qmail@web55907.mail.re3.yahoo.com> What techniques should I use to make my code run faster? Always profile before you optimize for speed. You should always optimize for readability first: it's easier to tune readable code than to read 'optimized' code, especially if the optimizations are not effective. Before using any technique that makes the code less readable, you should check that it's actually a bottleneck in your application by running your application with the built-in profile.py script. If your program spends 10% of its time running a particular method, even if you increase its speed tenfold you've only shaved 9% off the total running time. Always use a good algorithm when it is available. The exception to the above rule is when there are known large differences in the time complexity of alternative algorithms. Reducing running time from quadratic to linear, or from exponential to polynomial, is always worth doing unless you are sure that the data sets will always be tiny (less than a couple of dozen items). Use the simplest option that could possibly work. Don't use a regular expression if you just want to see if a string starts with a particular substring: use .startswith instead. Don't use .index if you just want to see if a string contains a particular letter: use in instead. Don't use StringIO if you could just use a list of strings. In general, keeping it simple cuts down on bugs and makes your code more readable. Even a complicated combination of .index calls will be much faster than a regular expression, and probably easier to decipher if you're just matching rather than capturing the result. Build strings as a list and use ''.join at the end. Yes, you already saw this one above under "Python Idioms", but it's such an important one that I thought I'd mention it again. join is a string method called on the separator, not the list. Calling it from the empty string concatenates the pieces with no separator, which is a Python quirk and rather surprising at first. This is important: string building with + is quadratic time instead of linear! Wrong: for s in strings: result += s Right: result = ''.join(strings) Use tests for object identity when appropriate: if x is not None rather than if x != None. It is much more efficient to test objects for identity than equality, because identity only checks their address in memory (two objects are identical if they are the same object in the same physical location) and not their actual data. Use dictionaries for searching, not lists. To find items in common between two lists, make the first into a dictionary and then look for items in the second in it. Searching a list for an item is linear-time, while searching a dict for an item is constant time. This can often let you reduce search time from quadratic to linear. Use the built-in sort wherever possible. sort can take a custom comparison function as a parameter, but this makes it very slow because the function has to be called at least O(n log n) times in the inner loop. To save time, turn the list of items into a list of tuples, where the first element of each tuple has the precalculated value of the function for each item (e.g. extracting a field), and the last element is the item itself. This idiom is called DSU for 'decorate-sort-undecorate.' In the 'decorate' step, make a list of tuples containing (transformed_value, second_key, ... , original value). In the 'sort' step, use the built-in sort on the tuples. In the 'undecorate' step, retrieve the original list in the sorted order by extracting the last item from each tuple. For example: aux_list = [i.Count, i.Name, ... i) for i in items] aux_list.sort() #sorts by Count, then Name, ... , then by item itself sorted_list = [i[-1] for i in items] #extracts last item Use map and/or filter to apply functions to lists. map applies a function to each item in a list (technically, sequence) and returns a list of the results. filter applies a function to each item in a sequence, and returns a list containing only those items for which the function evaluated True (using the __nonzero__ built-in method). These functions can make code much shorter. They also make it much faster, since the loop takes place entirely in the C API and never has to bind loop variables to Python objects. Worse: strings = [] for d in data: strings.append(str(d)) Better: strings = map(str, data) Use list comprehensions where there are conditions attached, or where the functions are methods or take more than one parameter. These are cases where map and filter do badly, since you have to make up a new one-argument function that does the operation you want. This makes them much slower, since more work is done in the Python layer. List comprehensions are often surprisingly readable. Worse: result = [] for d in data: if d.Count > 4: result.append[3*d.Count] Better: result = [3*d.Count for d in data if d.Count > 4] If you find yourself making the same list comprehension repeatedly, make utility functions and use map and/or filter: def triple(x): """Returns 3 * x.Count: raises AttributeError if .Count missing.""" return 3 * x.Count def check_count(x): """Returns 1 if x.Count exists and is greater than 3, 0 otherwise.""" try: return x.Count > 3 except: return 0 result = map(triple, filter(check_count, data)) Use function factories to create utility functions. Often, especially if you're using map and filter a lot, you need utility functions that convert other functions or methods to taking a single parameter. In particular, you often want to bind some data to the function once, and then apply it repeatedly to different objects. In the above example, we needed a function that multiplied a particular field of an object by 3, but what we really want is a factory that's able to return for any field name and amount a multiplier function in that family: def multiply_by_field(fieldname, multiplier): """Returns function that multiplies field "fieldname" by multiplier.""" def multiplier(x): return getattr(x, fieldname) * multiplier return multiplier triple = multiply_by_field('Count', 3) quadruple = multiply_by_field('Count', 4) halve_sum = multiply_by_field('Sum', 0.5) This is a very powerful and general technique for producing functions that might do something like search a specified field for a list of words, or perform several actions on different fields of a particular object, etc. It's a pain to write a lot of little functions that do very similar things, but if they're produced by a function factory it's easy. Use the operator module and reduce to get sums, products, etc. reduce takes a function and a sequence. First it applies the function to the first two items, then it takes the result and applies the function to the result and the next item, takes that result and applies the function to it and the next item, and so on until the end of the list. This makes it very easy to accumulate items along a list (or, in fact, any sequence). Note that Python 2.3 has a built-in sum() function (for numbers only), making this less necessary than it used to be. Worse: sum = 0 for d in data: sum += d product = 1 for d in data: product *= d Better: from operator import add, mul sum = reduce(add, data) product = reduce(mul, data) Use zip and dict to map fields to names. zip turns a pair of sequences into a list of tuples containing the first, second, etc. values from each sequence. For example, zip('abc', [1,2,3]) == [('a',1),('b',2),('c',3)]. You can use this to save a lot of typing when you have fields in a known order that you want to map to names: Bad: fields = '|'.split(line) gi = fields[0] accession = fields[1] description = fields[2] #etc. lookup = {} lookup['GI'] = gi lookup['Accession'] = accession lookup['Description'] = description #etc. Good: fieldnames = ['GI', 'Accession', 'Description'] #etc. fields = '|'.split(line) lookup = dict(zip(fieldnames, fields)) Ideal: def FieldWrapper(fieldnames, delimiter, constructor=dict): """Returns function that splits a line and wraps it into an object. Field names are passed in as keyword args, so constructor must be expecting them as such. """ def FieldsToObject(line): fields = [field.strip() for field in line.split(delimiter)] result = constructor(**dict(zip(fieldnames, fields))) return FieldsToObject FastaFactory = FieldWrapper(['GI','Accession','Description'], '|', Fasta) TaxonFactory = FieldWrapper(['TaxonID', 'ParentID', ...], '|', Taxon) CodonFreqFactory = FieldWrapper(['UUU', 'UUC', 'UUA',...], ' ', CodonFreq) #etc for similar data, including any database tables you care to wrap --------------------------------- Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1?/min. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060809/16a5be90/attachment-0001.html From alan.gauld at freenet.co.uk Thu Aug 10 00:41:52 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Aug 2006 23:41:52 +0100 Subject: [Tutor] What techniques should I use to make my code run faster?Informational References: <20060809221637.63184.qmail@web55907.mail.re3.yahoo.com> Message-ID: <001e01c6bc05$0435a240$0201a8c0@XPpro> Hi Anil, It looks like you found the info below somewhere, it would be nice to credit the source and if possible provide a URL - not least so we can all bookmark it and see if it gets updated over time?... :-) Thanks for posting, Alan G. ----- Original Message ----- From: "anil maran" To: Sent: Wednesday, August 09, 2006 11:16 PM Subject: [Tutor] What techniques should I use to make my code run faster?Informational > What techniques should I use to make my code run faster? Always profile before you optimize for speed. You should always optimize for readability first: it's easier to tune readable code than to read 'optimized' code, etc.... From wescpy at gmail.com Thu Aug 10 00:46:59 2006 From: wescpy at gmail.com (wesley chun) Date: Wed, 9 Aug 2006 15:46:59 -0700 Subject: [Tutor] python import problem In-Reply-To: <003501c6bba5$3418db40$0201a8c0@XPpro> References: <44D99E75.3010902@khmeros.info> <003501c6bba5$3418db40$0201a8c0@XPpro> Message-ID: <78b3a9580608091546u13348ff2jcde00388ea6eb453@mail.gmail.com> > > if I want to import factory.py into myfile.py, how can I do? > > You need to make your folders into packages. > Its fairly simple, you basically create an init.py file > But its worth reading about packages in the docs > Come back here ifv you have any questions after that. > > The other way would be to add each folder to > your PYTHONPATH the rules for importing modules in packages is going to change over the next few releases... read up on those changes starting from here: http://docs.python.org/dev/whatsnew/pep-328.html the simplest solution, as alan's described, is to put all directories that have your Python modules in the PYTHONPATH environment variable. if you are on a Unix-based system, just set this variable in your shell. if you are on Win32, right-mouse My Computer -> System Properties -> Advanced -> Environment Variables -> Edit (User or System variables) -> Ok. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From anilmrn at yahoo.com Thu Aug 10 01:17:58 2006 From: anilmrn at yahoo.com (anil maran) Date: Wed, 9 Aug 2006 16:17:58 -0700 (PDT) Subject: [Tutor] What techniques should I use to make my code run faster?Informational In-Reply-To: <001e01c6bc05$0435a240$0201a8c0@XPpro> Message-ID: <20060809231758.60043.qmail@web55913.mail.re3.yahoo.com> http://jaynes.colorado.edu/PythonIdioms.html#idioms_efficient Alan Gauld wrote: Hi Anil, It looks like you found the info below somewhere, it would be nice to credit the source and if possible provide a URL - not least so we can all bookmark it and see if it gets updated over time?... :-) Thanks for posting, Alan G. ----- Original Message ----- From: "anil maran" To: Sent: Wednesday, August 09, 2006 11:16 PM Subject: [Tutor] What techniques should I use to make my code run faster?Informational > What techniques should I use to make my code run faster? Always profile before you optimize for speed. You should always optimize for readability first: it's easier to tune readable code than to read 'optimized' code, etc.... --------------------------------- Do you Yahoo!? Get on board. You're invited to try the new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060809/76f67263/attachment.htm From wescpy at gmail.com Thu Aug 10 01:27:46 2006 From: wescpy at gmail.com (wesley chun) Date: Wed, 9 Aug 2006 16:27:46 -0700 Subject: [Tutor] What techniques should I use to make my code run faster?Informational In-Reply-To: <20060809231758.60043.qmail@web55913.mail.re3.yahoo.com> References: <001e01c6bc05$0435a240$0201a8c0@XPpro> <20060809231758.60043.qmail@web55913.mail.re3.yahoo.com> Message-ID: <78b3a9580608091627j4c68e6f3w9c017780abfb0bbb@mail.gmail.com> the overall root document of this useful read is: http://jaynes.colorado.edu/PythonGuidelines.html -wesley From dyoo at hkn.eecs.berkeley.edu Thu Aug 10 02:58:02 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Aug 2006 17:58:02 -0700 (PDT) Subject: [Tutor] html file - construct attach send... email python (fwd) Message-ID: Can someone help Amil? My hands won't allow me to type too long. Thanks! ---------- Forwarded message ---------- Date: Wed, 9 Aug 2006 17:09:19 -0700 (PDT) From: anil maran To: Danny Yoo Subject: Re: [Tutor] html file - construct attach send... email python i wasnt able to find a useful way to construct email i wasnt sure... abt how to use it thanks for help Danny Yoo wrote: On Wed, 9 Aug 2006, anil maran wrote: > What is the best way to construct an email in python and also attach a > html file Hi Anil, This is a repeat of one of your previous questions; you just sent this question out yesterday: http://mail.python.org/pipermail/tutor/2006-August/048452.html We are forgetful, but we're not THAT senile yet. Please do not repost your questions so early: give some people more time to construct a good answer for you. Repeating a question so soon like this tends to demotivate people. Have you looked at the 'email' module? http://www.python.org/doc/lib/module-email.html And in general, do you know about the Standard Library, or the Python Cookbook? http://www.python.org/doc/lib/ http://aspn.activestate.com/ASPN/Python/Cookbook/ I want to make sure you know about these documentation resources. Good luck to you. --------------------------------- Do you Yahoo!? Next-gen email? Have it all with the all-new Yahoo! Mail Beta. From hokkakada at khmeros.info Thu Aug 10 03:11:05 2006 From: hokkakada at khmeros.info (kakada) Date: Thu, 10 Aug 2006 08:11:05 +0700 Subject: [Tutor] python import problem In-Reply-To: <003501c6bba5$3418db40$0201a8c0@XPpro> References: <44D99E75.3010902@khmeros.info> <003501c6bba5$3418db40$0201a8c0@XPpro> Message-ID: <44DA87A9.7040608@khmeros.info> ???????? Alan Gauld: Hi Alan, >> the folders modules and translate are in the same level, so if I want to >> import factory.py into myfile.py, how can I do? > > You need to make your folders into packages. > Its fairly simple, you basically create an init.py file > But its worth reading about packages in the docs > Come back here ifv you have any questions after that. Sure, I can do it if I move translate folder into modules folder then create an empty init.py file. But I want another way, and PYTHONPATH is your right suggestion > > The other way would be to add each folder to > your PYTHONPATH It works for me now: mport sys import os.path sys.path.append(os.path.join(sys.path[0] ,"translate")) Cheers, da From jorge.castro at msn.com Thu Aug 10 14:32:10 2006 From: jorge.castro at msn.com (Jorge De Castro) Date: Thu, 10 Aug 2006 13:32:10 +0100 Subject: [Tutor] i18n Encoding/Decoding issues Message-ID: Hi all, It seems I can't get rid of my continuous issues i18n with Python :( I've been through: http://docs.python.org/lib/module-email.Header.html and http://www.reportlab.com/i18n/python_unicode_tutorial.html to no avail. Basically, I'm receiving and processing mail that comes with content (from an utf-8 accepting form) from many locales (France, Germany, etc) def splitMessage() does what the name indicates, and send message is the code below. def sendMessage(text): to, From, subject, body = splitMessage(text) msg = MIMEText(decodeChars(body), 'plain', 'UTF-8') msg['From'] = From msg['To'] = to msg['Subject'] = Header(decodeChars(subject), 'UTF-8') def decodeChars(str=""): if not str: return None for characterCode in _characterCodes.keys(): str = str.replace(characterCode, _characterCodes[characterCode]) return str Now as you have noticed, this only works, ie, I get an email sent with the i18n characters displayed correctly, after I pretty much wrote my own 'urldecode' map _characterCodes ={ "%80" : "�", "%82" : "�", "%83" : "�", "%84" : "�", \ "%85" : "�", "%86" : "�", "%87" : "�", "%88" : "�", \ "%89" : "�", "%8A" : "�", "%8B" : "�", "%8C" : "�", \ "%8E" : "�", "%91" : "�", "%92" : "�", "%93" : "�", \ "%94" : "�", "%95" : "�", "%96" : "�", "%97" : "�", \ ... Which feels like an horrible kludge. Note that using urlilib.unquote doesn't do it -I get an error saying that it is unable to . Replacing my decodeChars msg = MIMEText(urllib.unquote(body), 'plain', 'UTF-8') Returns content with i18n characters mangled. Using unicode(body, 'latin-1').encode('utf-8') doesn't work either. Besides, am I the only one to feel that if I want to encode something in UTF-8 it doesn't feel intuitive to have to convert to latin-1 first and then encode? Any ideas? I am dry on other option and really don't want to keep my kludge (unless I absolutely have to) Thanks in advance Cheers j _________________________________________________________________ Download the new Windows Live Toolbar, including Desktop search! http://toolbar.live.com/?mkt=en-gb From emilia12 at mail.bg Thu Aug 10 15:47:43 2006 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Thu, 10 Aug 2006 16:47:43 +0300 Subject: [Tutor] [tutor] ipconfig Message-ID: <1155217663.5c8b2b0d94a92@mail.bg> hello list is there in python an independent from the system way to obtain the IP i am playng around import sys import os ipconfname={'nt':'ipconfig', 'posix':'ifconfig'} ipstr = os.popen(ipconfname[os.name] ).read() #print ipstr but i found out that answer depends on os.name ... in this case i have to use a different parser for each system ... so is there another way to retrieve the IP? regards, e. ----------------------------- http://www.atol.bg - ?????? ??????? ?? ????????? ? ????? ????????! From jason.massey at gmail.com Thu Aug 10 15:55:27 2006 From: jason.massey at gmail.com (Jason Massey) Date: Thu, 10 Aug 2006 08:55:27 -0500 Subject: [Tutor] [tutor] ipconfig In-Reply-To: <1155217663.5c8b2b0d94a92@mail.bg> References: <1155217663.5c8b2b0d94a92@mail.bg> Message-ID: <7e3eab2c0608100655w6e80c150q6b687fa09d3367e1@mail.gmail.com> I found this on an artima forum: http://www.artima.com/forums/flat.jsp?forum=181&thread=113874 This worked on my machine (win xp): socket.getaddrinfo(socket.gethostname(), None)[0][4][0] On 8/10/06, emilia12 at mail.bg wrote: > > hello list > > is there in python an independent from the system way to > obtain the IP > > i am playng around > > import sys > import os > ipconfname={'nt':'ipconfig', 'posix':'ifconfig'} > ipstr = os.popen(ipconfname[os.name] ).read() > #print ipstr > > but i found out that answer depends on os.name ... > > in this case i have to use a different parser for each > system ... so is there another way to retrieve the IP? > > regards, > e. > > ----------------------------- > > http://www.atol.bg - ?????? ??????? ?? ????????? ? ????? ????????! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060810/505c7deb/attachment.htm From mail at ozzmosis.com Thu Aug 10 16:01:40 2006 From: mail at ozzmosis.com (andrew clarke) Date: Fri, 11 Aug 2006 00:01:40 +1000 Subject: [Tutor] [tutor] ipconfig In-Reply-To: <1155217663.5c8b2b0d94a92@mail.bg> References: <1155217663.5c8b2b0d94a92@mail.bg> Message-ID: <20060810140140.GA11356@ozzmosis.com> On Thu, Aug 10, 2006 at 04:47:43PM +0300, emilia12 at mail.bg wrote: > is there in python an independent from the system way to obtain the IP >>> import socket >>> hostname = socket.gethostname() >>> ip = socket.gethostbyname(hostname) >>> print ip 192.168.1.10 From amresh.kulkarni at gmail.com Thu Aug 10 19:59:25 2006 From: amresh.kulkarni at gmail.com (Amresh Kulkarni) Date: Thu, 10 Aug 2006 12:59:25 -0500 Subject: [Tutor] wx.Notebook query in wxpython Message-ID: Hi all, I am developing a GUI which has a notebook with multiple tabs. The tabs are formed by adding pages to the notebook. I have a check menu to select/deselect the tabs(pages) i want. On checking on an item it will must show the respective tab and unchecking should hide it. Simple as it may sound, i cant seem to find a hide method for notebook. Like if i have tabs x, y, z and i have unchecked x item in menu. it will trigger the foll code pageX = self.Notebook.GetPage(xid) --> xid is the id assigned to page x xid.Show(False) This does not work as there is no method show in Notebook. Is there a way to make this work. ~~AMRESH~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060810/382e3b09/attachment.htm From amresh.kulkarni at gmail.com Thu Aug 10 19:59:25 2006 From: amresh.kulkarni at gmail.com (Amresh Kulkarni) Date: Thu, 10 Aug 2006 12:59:25 -0500 Subject: [Tutor] wx.Notebook query in wxpython Message-ID: Hi all, I am developing a GUI which has a notebook with multiple tabs. The tabs are formed by adding pages to the notebook. I have a check menu to select/deselect the tabs(pages) i want. On checking on an item it will must show the respective tab and unchecking should hide it. Simple as it may sound, i cant seem to find a hide method for notebook. Like if i have tabs x, y, z and i have unchecked x item in menu. it will trigger the foll code pageX = self.Notebook.GetPage(xid) --> xid is the id assigned to page x xid.Show(False) This does not work as there is no method show in Notebook. Is there a way to make this work. ~~AMRESH~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060810/382e3b09/attachment.html From alan.gauld at freenet.co.uk Thu Aug 10 20:57:29 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 10 Aug 2006 19:57:29 +0100 Subject: [Tutor] python import problem References: <44D99E75.3010902@khmeros.info><003501c6bba5$3418db40$0201a8c0@XPpro> <44DA87A9.7040608@khmeros.info> Message-ID: <001b01c6bcae$d461d2f0$0201a8c0@XPpro> >> The other way would be to add each folder to >> your PYTHONPATH >It works for me now: >import sys >import os.path >sys.path.append(os.path.join(sys.path[0] ,"translate")) That isn't using PYTHONPATH its updaing sys.path which is slightly different.. This way you need to do that for every program usi9ng your folder but if you modify the PYTHONPATH environment variable you only need to do it once and Python will add it to sys.path for you. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From klappnase at freenet.de Thu Aug 10 21:27:30 2006 From: klappnase at freenet.de (Michael Lange) Date: Thu, 10 Aug 2006 21:27:30 +0200 Subject: [Tutor] i18n Encoding/Decoding issues In-Reply-To: References: Message-ID: <20060810212730.532e0560.klappnase@freenet.de> Hi Jorge, On Thu, 10 Aug 2006 13:32:10 +0100 "Jorge De Castro" wrote: (...) > > Using unicode(body, 'latin-1').encode('utf-8') doesn't work either. Besides, > am I the only one to feel that if I want to encode something in UTF-8 it > doesn't feel intuitive to have to convert to latin-1 first and then encode? > if the above does not work, it is because the original message is not latin-1 encoded. unicode(body, 'latin-1') does not convert *to* latin-1, but convert a latin-1 encoded string into unicode. This will obviously only work as expected if the original string is actually latin-1. In order to safely convert the message body into utf-8 you would have to find out which encoding is used for the message and then do unicode(body, original_encoding).encode('utf-8') Michael From john at fouhy.net Thu Aug 10 22:51:48 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 11 Aug 2006 08:51:48 +1200 Subject: [Tutor] wx.Notebook query in wxpython In-Reply-To: References: Message-ID: <5e58f2e40608101351l1e78d262v9dea8dc9f5a492b2@mail.gmail.com> On 11/08/06, Amresh Kulkarni wrote: > I am developing a GUI which has a notebook with multiple tabs. The tabs are > formed by adding pages to the notebook. > I have a check menu to select/deselect the tabs(pages) i want. On checking > on an item it will must show the respective tab and unchecking should hide > it. [...] Hi Amresh, I suggest you try asking on the wxPython list, wxPython-users at lists.wxwidgets.org (you will probably have to subscribe first). The people on that list are both very knowledgable and very helpful :-) -- John. From anilmrn at yahoo.com Thu Aug 10 23:14:23 2006 From: anilmrn at yahoo.com (anil maran) Date: Thu, 10 Aug 2006 14:14:23 -0700 (PDT) Subject: [Tutor] i18n Encoding/Decoding issues In-Reply-To: <20060810212730.532e0560.klappnase@freenet.de> Message-ID: <20060810211424.97519.qmail@web55902.mail.re3.yahoo.com> how do u find out original encoding thanks Michael Lange wrote: Hi Jorge, On Thu, 10 Aug 2006 13:32:10 +0100 "Jorge De Castro" wrote: (...) > > Using unicode(body, 'latin-1').encode('utf-8') doesn't work either. Besides, > am I the only one to feel that if I want to encode something in UTF-8 it > doesn't feel intuitive to have to convert to latin-1 first and then encode? > if the above does not work, it is because the original message is not latin-1 encoded. unicode(body, 'latin-1') does not convert *to* latin-1, but convert a latin-1 encoded string into unicode. This will obviously only work as expected if the original string is actually latin-1. In order to safely convert the message body into utf-8 you would have to find out which encoding is used for the message and then do unicode(body, original_encoding).encode('utf-8') Michael _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- How low will we go? Check out Yahoo! Messenger?s low PC-to-Phone call rates. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060810/a9d85628/attachment.html From dyoo at hkn.eecs.berkeley.edu Fri Aug 11 01:22:48 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 10 Aug 2006 16:22:48 -0700 (PDT) Subject: [Tutor] i18n Encoding/Decoding issues In-Reply-To: <20060810211424.97519.qmail@web55902.mail.re3.yahoo.com> References: <20060810211424.97519.qmail@web55902.mail.re3.yahoo.com> Message-ID: On Thu, 10 Aug 2006, anil maran wrote: > how do u find out original encoding Read: http://www.joelonsoftware.com/articles/Unicode.html In short: there's no good, reliable way to guess the encoding. But there should be no need to guess: a proper document will have the encoding explicitely written in there. From cspears2002 at yahoo.com Fri Aug 11 01:39:41 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 10 Aug 2006 16:39:41 -0700 (PDT) Subject: [Tutor] Rock, Paper, Scissors Message-ID: <20060810233941.76046.qmail@web51607.mail.yahoo.com> Here is my Rock,Paper,Scissors script: #!/usr/bin/python import random random.seed() class Human: def __init__(self): self.points = 0 self.choice = " " def plays(self): self.choice = raw_input("Pick (R)ock, (P)aper, or (S)cissors! ") if self.choice == 'r': self.choice = 'rocks' elif self.choice == 'p': self.choice = 'paper' elif self.choice == 's': self.choice = 'scissors' else: print "Invalid response" class Computer: def __init__(self): self.points = 0 self.choice = " " def plays(self): comp_choice = random.randint(0,2) if comp_choice == 0: self.choice = 'rocks' #for rocks elif comp_choice == 1: self.choice = 'paper' #for paper else: self.choice = 'scissors' #for scissors def compare_objects(human, computer): print "Human picked ", human.choice print "Computer picked", computer.choice if human.choice == computer.choice: print "Draw!" elif human.choice == 'rocks' and computer.choice == 'paper': print "Computer wins!" computer.points = computer.points + 1 elif human.choice == 'paper' and computer.choice == 'rocks': print "Human wins!" human.points = human.points + 1 elif human.choice == 'scissors' and computer.choice == 'paper': print "Human wins!" human.points = human.points + 1 elif human.choice == 'paper' and computer.choice == 'scissors': print "Computer wins!" computer.points = computer.points + 1 elif human.choice == 'rocks' and computer.choice == 'scissors': print "Human wins!" human.points = human.points + 1 else human.choice == 'scissors' and computer.choice == 'rocks': print "Computer wins!" computer.points = computer.points + 1 if __name__ == "__main__": print "Welcome to Rock, Paper, Scissors!" final_points = raw_input("Play to how many points? ") human = Human() computer = Computer() while (human.points <= final_points or computer.points <= final_points): human.plays() computer.plays() compare_objects(human, computer) print "Score:\tHuman: ",human.points,"\tComputer: ",computer.points My main concern is the compare_objects function. Is there any easier way to write it? Actually, the function does not work because "else condition:" causes a syntax error. -Chris From john at fouhy.net Fri Aug 11 02:02:50 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 11 Aug 2006 12:02:50 +1200 Subject: [Tutor] Rock, Paper, Scissors In-Reply-To: <20060810233941.76046.qmail@web51607.mail.yahoo.com> References: <20060810233941.76046.qmail@web51607.mail.yahoo.com> Message-ID: <5e58f2e40608101702n699ce81l390a0599a363918@mail.gmail.com> Hi Chris, On 11/08/06, Christopher Spears wrote: > def plays(self): > self.choice = raw_input("Pick (R)ock, (P)aper, or > (S)cissors! ") > if self.choice == 'r': > self.choice = 'rocks' > elif self.choice == 'p': > self.choice = 'paper' > elif self.choice == 's': > self.choice = 'scissors' > else: > print "Invalid response" A couple of comments here --- Firstly, to me, 'self.choice' is the thing you want to save, which is distinct from the user's input. So, I would call the result of raw_input something else. eg: fromUser = raw_input("Pick (R)ock, (P)aper, or (S)cissors! ") if fromUser == 'r': self.choice = 'rocks' # etc Secondly, if the user enters 'R' (as you request), your program will say "Invalid response", because 'R' != 'r'. You can get around this by saying: if fromUser.lower() == 'r': Thirdly, a dictionary would make this much simpler. Something like: translate = { 'r':'rock', 's':'scissors', 'p':'paper' } try: self.choice = translate[fromUser.lower()] except KeyError: print 'Invalid response.' # what else are you going to do? what does self.choice become? > def compare_objects(human, computer): > print "Human picked ", human.choice > print "Computer picked", computer.choice > if human.choice == computer.choice: > print "Draw!" > elif human.choice == 'rocks' and computer.choice == > 'paper': > print "Computer wins!" > computer.points = computer.points + 1 [...] You can use a similar dictionary-based approach here. You could use a dictionary to make a data structure that expresses what beats what, and then reduce your code to: if human.choice == computer.choice: print 'Draw!' elif # human beats computer print 'Human wins!' else: print 'Computer wins!' HTH :-) -- John. From alan.gauld at freenet.co.uk Fri Aug 11 12:13:26 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 11 Aug 2006 11:13:26 +0100 Subject: [Tutor] Rock, Paper, Scissors References: <20060810233941.76046.qmail@web51607.mail.yahoo.com> Message-ID: <000a01c6bd2e$c9ab9b90$0201a8c0@XPpro> > My main concern is the compare_objects function. Is > there any easier way to write it? Actually, the > function does not work because "else condition:" > causes a syntax error. I'd do that with a two dimernsional table. The table would be indexed by the computers choice and the human choice and the outcome stored as a value. Thus it becomes outcome = results[computer.choice][human.choice] if outcome == 0: print "Computer Wins" elif outcome == 1: print "Human wins" else: print 'Draw!' Another interesting variation is to create a single Player class and make human and computer instances. Pass in the function for setting choice as a parameter to init... That way your code consists of a Player class, two selection functions and the lookup/display code that could sit in main() This isn't any "better", as such, just different... HTH, Alan G. From peppers at gmail.com Fri Aug 11 16:26:09 2006 From: peppers at gmail.com (Terry Peppers) Date: Fri, 11 Aug 2006 09:26:09 -0500 Subject: [Tutor] Python Block Message-ID: <8ca48b420608110726n40afaa67ja06159e049522ebf@mail.gmail.com> I'm really blocked right now, and I don't want to post this to the main Python list since I think the answer is probably right in front of my face. I'm clearly just too close to see it. I'm able to do frequency counts of items in a list by doing the following: >>> list = ["5100", "5100", "5100", "5200", "5200"] >>> count = {} >>> for l in list: ... count[l] = count.get(l, 0) + 1 ... >>> count {'5200': 2, '5100': 3} >>> Hooray, right?! However, my real problem is dealing with another dimension of data. So suppose I can access the following data: "5100", "foo" "5100", "-" "5100", "-" "5100", "-" "5200", "foo" "5200", - That's a total of 6 line records that I want to output like this: 5100 - 3 5100 foo 1 5200 - 1 5200 foo 1 I want to count the frequency of the second column of data that I can access. I can't seem to get any traction as how to figure this out. Should I put the data in a list of dictionaries? A dictionary of lists? How do I call the data if there are all kinds of duplicate keys? When the data's in some data structure how do I iterate over it to get frequency of column B? Really confused. Can someone help? From wierob at gmx.de Fri Aug 11 18:28:58 2006 From: wierob at gmx.de (Robert Wierschke) Date: Fri, 11 Aug 2006 18:28:58 +0200 Subject: [Tutor] Rock, Paper, Scissors Message-ID: <44DCB04A.2020202@gmx.de> the else part can't have a condition!!! From rabidpoobear at gmail.com Fri Aug 11 18:53:12 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 11 Aug 2006 11:53:12 -0500 Subject: [Tutor] Rock, Paper, Scissors In-Reply-To: <44DCB04A.2020202@gmx.de> References: <44DCB04A.2020202@gmx.de> Message-ID: <44DCB5F8.4080303@gmail.com> Robert Wierschke wrote: > the else part can't have a condition!!! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Are you referring to Alan's post? You should have included the original text in your reply so we would know what you're talking about. If you _are_ talking about Alan's example: #--- outcome = results[computer.choice][human.choice] if outcome == 0: print "Computer Wins" elif outcome == 1: print "Human wins" else: print 'Draw!' #--- his else doesn't have a condition. it's just that he only needed to do one thing in the else clause and it looks neater to put it on one line. else: print 'Draw!' is equivalent to else: print 'Draw!' From wescpy at gmail.com Fri Aug 11 19:42:32 2006 From: wescpy at gmail.com (wesley chun) Date: Fri, 11 Aug 2006 10:42:32 -0700 Subject: [Tutor] Rock, Paper, Scissors In-Reply-To: <001b01c6bb0c$37df2390$0201a8c0@XPpro> References: <20060808054246.54903.qmail@web51606.mail.yahoo.com> <001b01c6bb0c$37df2390$0201a8c0@XPpro> Message-ID: <78b3a9580608111042j255857c9j120963c69e089a94@mail.gmail.com> > This looks like a fun project to work on. From > reading the description, I feel this would be pretty > straight forward game to program. However, I have no > idea how the computer would decide if it wanted a > rock, paper, or a pair of scissors. Any hints? christopher, this is indeed a *great* exercise... i've been using it since i can't remember when... i had it as an exercise in BASIC and Pascal when i was in high school, then turned it into an exercise for my C and Python courses. naturally it's also in Core Python. others have said it and given code already, but this problem breaks down into 3 discrete steps: 1. give values to R, P or S, i.e., an int, char, or some constant 2. have the user choose one via its constant 3. have the computer choose another -- you will need to randomly pick one of the 3 constants 4. logic to determine who the "winner" is of if it is a draw good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Fri Aug 11 19:47:37 2006 From: wescpy at gmail.com (wesley chun) Date: Fri, 11 Aug 2006 10:47:37 -0700 Subject: [Tutor] Python Block In-Reply-To: <8ca48b420608110726n40afaa67ja06159e049522ebf@mail.gmail.com> References: <8ca48b420608110726n40afaa67ja06159e049522ebf@mail.gmail.com> Message-ID: <78b3a9580608111047u15201a79x7bc5f334be9262e7@mail.gmail.com> On 8/11/06, Terry Peppers wrote: > I'm really blocked right now, and I don't want to post this to the > main Python list since I think the answer is probably right in front > of my face. I'm clearly just too close to see it. > > "5100", "foo" > "5100", "-" > "5100", "-" > "5100", "-" > "5200", "foo" > "5200", - > > That's a total of 6 line records that I want to output like this: > > 5100 - 3 > 5100 foo 1 > 5200 - 1 > 5200 foo 1 > > I want to count the frequency of the second column of data that I can > access. I can't seem to get any traction as how to figure this out. > Should I put the data in a list of dictionaries? A dictionary of > lists? How do I call the data if there are all kinds of duplicate > keys? When the data's in some data structure how do I iterate over it > to get frequency of column B? without hacking any code... i can see two possibilities you can try: 1) easiest. use a tuple of pairs as your key, i.e. (5100, 'foo'), (5100, '-'), etc. it's only confusing because you're seeing "5100" in both keys 2) more complex. you suggested a list of dicts or a dict of lists, but it looks like a dict of dicts would be a better fit., i.e. {5100: {'foo': 1, '-': 3}, etc. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From cspears2002 at yahoo.com Sat Aug 12 00:39:21 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 11 Aug 2006 15:39:21 -0700 (PDT) Subject: [Tutor] rock, paper, scissors In-Reply-To: Message-ID: <20060811223921.94136.qmail@web51614.mail.yahoo.com> --- Tom Wilson wrote: > hi, > > could you please explain to me how your rock paper > scissors game script > works because i am a bit confused. > > thanks > tom > > The game does not work in its current form, which may be some cause for confusion. :-) In designing the program, I took the object oriented route. Why? When I started to design the game, I imagined two characters (a human and a computer) playing against each other. Each character has similar attributes, i.e. points and a choice, and behavoir. They play. The behavoir is implemented differently for each character because how a computer makes a decision is different from how a human makes a decision. After the characters decide which object to pick, a function called compare_objects compares the objects and uses logic to determine the winner. After the winner is picked, points are incremented and play continues until one character reaches a set number of points. The two problem areas are the compare_objects function and the while loop. They don't work. (At least, not well.) However, I have gotten several useful tips from tutors, so I will be making a lot of progress next week! -Chris From ismaelgf at adinet.com.uy Sat Aug 12 08:05:10 2006 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sat, 12 Aug 2006 03:05:10 -0300 Subject: [Tutor] Rock, Paper, Scissors In-Reply-To: <44DCB5F8.4080303@gmail.com> References: <44DCB04A.2020202@gmx.de> <44DCB5F8.4080303@gmail.com> Message-ID: <44DD6F96.2050009@adinet.com.uy> Luke Paireepinart escribi?: > Robert Wierschke wrote: > >> the else part can't have a condition!!! >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > Are you referring to Alan's post? > You should have included the original text in your reply so we would > know what you're talking about. He wasn't. From the original post: elif human.choice == 'rocks' and computer.choice == 'scissors': print "Human wins!" human.points = human.points + 1 else human.choice == 'scissors' and computer.choice == 'rocks': print "Computer wins!" computer.points = computer.points + 1 Ismael From rabidpoobear at gmail.com Sat Aug 12 08:10:23 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 12 Aug 2006 01:10:23 -0500 Subject: [Tutor] Rock, Paper, Scissors In-Reply-To: <44DD6F96.2050009@adinet.com.uy> References: <44DCB04A.2020202@gmx.de> <44DCB5F8.4080303@gmail.com> <44DD6F96.2050009@adinet.com.uy> Message-ID: <44DD70CF.9050702@gmail.com> .... > He wasn't. From the original post: > > elif human.choice == 'rocks' and computer.choice == > 'scissors': > print "Human wins!" > human.points = human.points + 1 > else human.choice == 'scissors' and computer.choice > == 'rocks': > print "Computer wins!" > computer.points = computer.points + 1 > > > ah. thanks for clearing this up. From nimrodx at slingshot.co.nz Sat Aug 12 14:03:54 2006 From: nimrodx at slingshot.co.nz (nimrodx) Date: Sat, 12 Aug 2006 22:03:54 +1000 Subject: [Tutor] regular expressions question Message-ID: <44DDC3AA.8010908@slingshot.co.nz> Hi All, I am trying to fish through the history file for the Konquerer web browser, and pull out the web sites visited. The file's encoding is binary or something Here is the first section of the file: '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01\xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x00l' Does that tell you anything? I have been trying to replace the pesky \x00's with something less annoying, but with no success: import re pattern = r"\x00" re.sub(pattern, '', dat2) That seems to work at the command line, but this this: web = re.compile( r"(?P[/a-zA-Z0-9\.]+)" ) res = re.findall(web,dat2) tends to give me back individual alphanumeric characters, "."'s, and "/"'s, as if they had each been separated by an unmatched character: e.g. ['z', 't', 'f', 'i', 'l', 'e', 'h', 'o', 'm', 'e', 'a', 'l', 'p', 'h', 'a',...] I was hoping for one web address per element of the list... Suggestions greatly appreciated!! Thanks, Matt From nimrodx at slingshot.co.nz Sat Aug 12 14:07:57 2006 From: nimrodx at slingshot.co.nz (nimrodx) Date: Sat, 12 Aug 2006 22:07:57 +1000 Subject: [Tutor] Message seemed to bounce, so I will try again Message-ID: <44DDC49D.2010009@slingshot.co.nz> Hi All, I am trying to fish through the history file for the Konquerer web browser, and pull out the web sites visited. The file's encoding is binary or something Here is the first section of the file: '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01\xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x00l' Does that tell you anything? I have been trying to replace the pesky \x00's with something less annoying, but with no success: import re pattern = r"\x00" re.sub(pattern, '', dat2) That seems to work at the command line, but this this: web = re.compile( r"(?P[/a-zA-Z0-9\.]+)" ) res = re.findall(web,dat2) tends to give me back individual alphanumeric characters, "."'s, and "/"'s, as if they had each been separated by an unmatched character: e.g. ['z', 't', 'f', 'i', 'l', 'e', 'h', 'o', 'm', 'e', 'a', 'l', 'p', 'h', 'a',...] I was hoping for one web address per element of the list... Suggestions greatly appreciated!! Thanks, Matt From anilmrn at yahoo.com Sat Aug 12 11:14:31 2006 From: anilmrn at yahoo.com (anil maran) Date: Sat, 12 Aug 2006 02:14:31 -0700 (PDT) Subject: [Tutor] how to remove html ags Message-ID: <20060812091431.74868.qmail@web55905.mail.re3.yahoo.com>

Human nature is not a machin... for example in the above stirng i want to remove

and

i tried str = str.replace('(.*)','') it doesnt work thanks --------------------------------- Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1?/min. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060812/3f253d02/attachment.html From alan.gauld at freenet.co.uk Sat Aug 12 11:23:38 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 12 Aug 2006 10:23:38 +0100 Subject: [Tutor] Python Block References: <8ca48b420608110726n40afaa67ja06159e049522ebf@mail.gmail.com> Message-ID: <001601c6bdf1$02244fe0$0201a8c0@XPpro> > Hooray, right?! However, my real problem is dealing with another > dimension of data. So suppose I can access the following data: > > "5100", "foo" > "5100", "-" > "5100", "-" > "5100", "-" > "5200", "foo" > "5200", - Hint: Dictionaries can be keyed by tuples too. >( 5100, -) : 3 Does that help? Alan G. From alan.gauld at freenet.co.uk Sat Aug 12 11:33:32 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 12 Aug 2006 10:33:32 +0100 Subject: [Tutor] regular expressions question References: <44DDC3AA.8010908@slingshot.co.nz> Message-ID: <002a01c6bdf2$60c69480$0201a8c0@XPpro> > The file's encoding is binary or something > > Here is the first section of the file: > '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01\xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x00l' > > Does that tell you anything? Recall that on a 32 bit computer each "word" is 4 bytes long so to get anyting meaningful you often need to consider 4 byte blocks. 00000002 B8089F00 The next bit is tricky, either 'z' or (ord('z')A80000 etc. Now whether those numbers mean anything to you is a moot point but thats usually the starting point. > I have been trying to replace the pesky \x00's with something less But that is almost certainly the wrong approach, you'll never figure out where the word boundaries are without them! > Suggestions greatly appreciated!! Go look on the Konqueror site (at the code if necessary) to find the format of the data structure in the file and use the struct module to unpack it. You might find the section in my tutorial (under Handling Files) on binary files and using struct useful HTH Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From wierob at gmx.de Sat Aug 12 12:06:56 2006 From: wierob at gmx.de (Robert Wierschke) Date: Sat, 12 Aug 2006 12:06:56 +0200 Subject: [Tutor] Rock, Paper, Scissors In-Reply-To: <44DCB5F8.4080303@gmail.com> References: <44DCB04A.2020202@gmx.de> <44DCB5F8.4080303@gmail.com> Message-ID: <44DDA840.4050602@gmx.de> sorry I answerd to Message: 2 Date: Thu, 10 Aug 2006 16:39:41 -0700 (PDT) From: Christopher Spears Subject: [Tutor] Rock, Paper, Scissors and his else has a condition > else human.choice == 'scissors' and computer.choice >== 'rocks': > print "Computer wins!" > computer.points = computer.points + 1 Luke Paireepinart schrieb: > Robert Wierschke wrote: >> the else part can't have a condition!!! >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > Are you referring to Alan's post? > You should have included the original text in your reply so we would > know what you're talking about. > If you _are_ talking about Alan's example: > #--- > > outcome = results[computer.choice][human.choice] > if outcome == 0: print "Computer Wins" > elif outcome == 1: print "Human wins" > else: print 'Draw!' > #--- > his else doesn't have a condition. > it's just that he only needed to do one thing in the else clause > and it looks neater to put it on one line. > else: print 'Draw!' > is equivalent to > else: > print 'Draw!' > > From nimrodx at slingshot.co.nz Sat Aug 12 16:30:34 2006 From: nimrodx at slingshot.co.nz (nimrodx) Date: Sun, 13 Aug 2006 00:30:34 +1000 Subject: [Tutor] regular expressions question] Message-ID: <44DDE60A.60602@slingshot.co.nz> Hi Alan and other Gurus, if you look carefully at the string below, you see that in amongst the "\x" stuff you have the text I want: z tfile://home/alpha which I know to be an address on my system, plus a bit of preceeding txt. Alan Gauld wrote: >> The file's encoding is binary or something >> >> Here is the first section of the file: >> '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01\xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x00l' >> >> >> Does that tell you anything? > But that is almost certainly the wrong approach, you'll never > figure out where the word boundaries are without them! So I believe this is the right approach. in fact, If I print the string, without any modifications: I get the following sort of stuff: ?z???tfile:/home/alpha/care/my_details.aspx.html????????%o??0%o??0l So this is one approach that will work. I have no idea what sort of encoding it is, but if someone could tell me how to get rid of what I assume are hex digits. In a hex editor it turns out to be readable and sensible url's with spaces between each digit, and a bit of crud at the end of url's, just as above. Any suggestions with that additional info? I've used struct before, it is a very nice module. Could this be some sort of UTF encoding? I think I was a bit light on info with that first post. Thanks for your time, Matt From bashu at yandex.ru Sat Aug 12 13:28:18 2006 From: bashu at yandex.ru (Basil Shubin) Date: Sat, 12 Aug 2006 18:28:18 +0700 Subject: [Tutor] SGMLLib, fetching some weird data Message-ID: <44DDBB52.5080906@yandex.ru> Hi friends, Please, examine attached script. I want fetch some data from online resource and almost achieve this, but I can't fetch some weird formatted data like this '45? Reverse Calf Press'. I got the following error: 45 Reverse Calf Press Reverse Calf Raise Seated Reverse Calf Press Traceback (most recent call last): File "net_exrx.py", line 226, in ? exercisesList = LoadExercisesList(2, 4, 9) File "net_exrx.py", line 86, in LoadExercisesList return parser.GetExercisesList() File "net_exrx.py", line 176, in GetExercisesList self.exerList.append([self.desc[i],self.urls[i]]) IndexError: list index out of range Thanks in advance! -------------- next part -------------- A non-text attachment was scrubbed... Name: net_exrx.py Type: text/x-python Size: 7295 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20060812/93bb7270/attachment.py From amonroe at columbus.rr.com Sat Aug 12 13:54:14 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 12 Aug 2006 07:54:14 -0400 Subject: [Tutor] Python Block In-Reply-To: <8ca48b420608110726n40afaa67ja06159e049522ebf@mail.gmail.com> References: <8ca48b420608110726n40afaa67ja06159e049522ebf@mail.gmail.com> Message-ID: <681067593618.20060812075414@columbus.rr.com> > 5100 - 3 > 5100 foo 1 > 5200 - 1 > 5200 foo 1 > I want to count the frequency of the second column of data that I can > access. It's kind of the long way around, but putting it into a sql database and doing a groupby query might work. Alan From tpwilson at hotmail.co.uk Fri Aug 11 22:06:22 2006 From: tpwilson at hotmail.co.uk (Tom Wilson) Date: Fri, 11 Aug 2006 21:06:22 +0100 Subject: [Tutor] Roack, Paper Scissors Message-ID: could someone please explain to me how the scripts for the rock, paper, scissors game work because i'm not quite sure. tom _________________________________________________________________ Windows Live™ Messenger has arrived. Click here to download it for free! http://imagine-msn.com/messenger/launch80/?locale=en-gb From foxandxss at gmail.com Sat Aug 12 19:00:29 2006 From: foxandxss at gmail.com (Jesus Rodriguez) Date: Sat, 12 Aug 2006 19:00:29 +0200 Subject: [Tutor] Rock, Paper, Scissors In-Reply-To: <78b3a9580608111042j255857c9j120963c69e089a94@mail.gmail.com> References: <20060808054246.54903.qmail@web51606.mail.yahoo.com> <001b01c6bb0c$37df2390$0201a8c0@XPpro> <78b3a9580608111042j255857c9j120963c69e089a94@mail.gmail.com> Message-ID: <2a1edb210608121000ube3972fja3f1913ed1e3c836@mail.gmail.com> Hi, i used a list with R, P, S like: rps = ["Rock", "Paper", "Scissors"] random.shuffle(rps) computerObject = rps[0] Then, the computer pick a random object and i compare my object with computer's object. ;) 2006/8/11, wesley chun : > > > This looks like a fun project to work on. From > > reading the description, I feel this would be pretty > > straight forward game to program. However, I have no > > idea how the computer would decide if it wanted a > > rock, paper, or a pair of scissors. Any hints? > > > christopher, > > this is indeed a *great* exercise... i've been using it since i can't > remember when... i had it as an exercise in BASIC and Pascal when i > was in high school, then turned it into an exercise for my C and > Python courses. naturally it's also in Core Python. > > others have said it and given code already, but this problem breaks > down into 3 discrete steps: > > 1. give values to R, P or S, i.e., an int, char, or some constant > 2. have the user choose one via its constant > 3. have the computer choose another -- you will need to randomly pick > one of the 3 constants > 4. logic to determine who the "winner" is of if it is a draw > > good luck! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060812/dd3294d1/attachment.htm From simplebob at gmail.com Sat Aug 12 23:07:28 2006 From: simplebob at gmail.com (Daniel McQuay) Date: Sat, 12 Aug 2006 17:07:28 -0400 Subject: [Tutor] how to remove html ags In-Reply-To: <20060812091431.74868.qmail@web55905.mail.re3.yahoo.com> References: <20060812091431.74868.qmail@web55905.mail.re3.yahoo.com> Message-ID: <6d87ecf40608121407p5e3f1546ie40da7dbc915e037@mail.gmail.com> hey anil, have you had a look at BeautifulSoup? http://www.crummy.com/software/BeautifulSoup/ i haven't used it but i have seen it mentioned on the list for parsing html. On 8/12/06, anil maran wrote: > >

Human nature is not a machin... > > for example in the above stirng > > i want to remove

> and

> > i tried > > str = str.replace('(.*)','') > > it doesnt work > thanks > > ------------------------------ > Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates > starting at 1?/min. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- Daniel McQuay simplebob at gmail.com boxster.homelinux.org prowiseguys.com H: 814.825.0847 M: 814-341-6233 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060812/0e50bb5b/attachment.html From lavendula6654 at yahoo.com Sun Aug 13 00:09:21 2006 From: lavendula6654 at yahoo.com (Elaine) Date: Sat, 12 Aug 2006 15:09:21 -0700 (PDT) Subject: [Tutor] How to teach Python In-Reply-To: <44C0EF6F.7070907@gmail.com> Message-ID: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com> I am going to be teaching "Introduction to Python Programming" in the Fall at Foothill College in Los Altos Hills, CA. This is a 5 quarter unit class for students who already know one programming language. I have been teaching programming for 20 years now, including Java and C++ as of late. As I prepare this class, I have some questions that I I am hoping you can shed some light on. 1) Programming Style while 1: x = next() if not x: break I have never allowed students to use break or continue in any programming class I have taught. I think of this type of code as belonging with the dreaded GOTO. I find that students who are having difficulty writing complex conditions in a loop use multiple if's with break's inside the loop instead. Also, it is MUCH easier to read a loop if the condition for continuing in the loop is right up at the top of the loop where it belongs. I have always thought of break and continue as hacks that are not compatible with structured programming techniques. The only exception is using break in a switch in C, C++ and Java. However, all Python books seem to contain sample programs like this one. Do you think that code like this is desirable? 2) Since this is an introductory class, I am tempted to leave out "optional" topics like argument matching modes, walk, map, filter, reduce, apply. Do you think these are required for any Python programmer? 3) I need to teach a GUI in this class. I would like something that is easy, standard, and multi-platform. I am considering Tkinter and Jython. Any opnions on this? Thanks for any answers you might have. -Elaine Haight __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kermit at polaris.net Sun Aug 13 01:40:58 2006 From: kermit at polaris.net (Kermit Rose) Date: Sat, 12 Aug 2006 19:40:58 -0400 (Eastern Daylight Time) Subject: [Tutor] function value Message-ID: <44DE670A.000005.02128@YOUR-4105E587B6> A function in my factor package return zeros instead of the correct value. It did this for several times, and then returned the correct value. I inserted print statements in the function and in the calling routine which document this behavior. The calling routine is function function fermat. The function being called is function strongfac. To see the test results , run the function testrange with parameters testrange(10**14+37,10**14+37). Since it takes quite a lot of work to make a copy that survives the email removal of leading blanks I attach the package of function routines here. Results as run on my machine: Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. IDLE 1.1.2 >>> import factor34 >>> from factor34 import testrange >>> testrange(10**14+37,10**14+37) Begin calculating constants to be used in factoring. Finished calculating constants to be used in factoring. Search for a factor of 100000000000037 Could not find factors by strong probable prime test using witnesses < 10000. Try to find factors by using power of 2 mod z as a witness. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 0 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 1 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 2 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 3 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 4 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 5 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 6 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 7 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 8 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 9 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 10 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 11 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 12 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 15306543515214 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 13 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 12123044576953 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 14 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 45391315949900 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 15 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 59571344259390 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 16 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 78029752396948 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 17 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 35863146075772 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 18 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 19712913203085 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 19 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 14607414373499 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 20 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 57761947468766 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 21 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 75604347243674 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 22 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 3561873332543 Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. In strongfac Found1: x = 1858741 Found1: y = 53799857 face = [1858741L, 53799857L, 0] Found1: factor by strong probable prime test, using witnes 96058894729069 . Found1: factors are 1858741 53799857 Found1: returning [1858741L, 53799857L, 0] to fermat routine. Retrieved from strongfac, face = [1858741L, 53799857L, 0] In fermat: k = 23 x = 1858741 y = 53799857 face = [1858741L, 53799857L, 0] index of torial is 23 z = 100000000000037 x = 1858741 y = 53799857 difficulty = 0 >>> Kermit Rose < kermit at polaris.net > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20060812/70aca486/attachment-0001.asc From python at venix.com Sun Aug 13 01:56:04 2006 From: python at venix.com (Python) Date: Sat, 12 Aug 2006 19:56:04 -0400 Subject: [Tutor] How to teach Python In-Reply-To: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com> References: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com> Message-ID: <1155426964.5685.101.camel@www.venix.com> On Sat, 2006-08-12 at 15:09 -0700, Elaine wrote: > I am going to be teaching "Introduction to Python > Programming" in the Fall at Foothill College in Los > Altos Hills, CA. This is a 5 quarter unit class for > students who already know one programming language. > > I have been teaching programming for 20 years now, > including Java and C++ as of late. As I prepare this > class, I have some questions that I I am hoping you > can shed some light on. > > 1) Programming Style > > while 1: > x = next() > if not x: break > > I have never allowed students to use break or continue > in any > programming class I have taught. I think of this type > of code as belonging with the dreaded GOTO. > > I find that students who are having difficulty writing > > complex conditions in a loop use multiple if's with > break's > inside the loop instead. Also, it is MUCH easier to > read a > loop if the condition for continuing in the loop is > right up > at the top of the loop where it belongs. > > I have always thought of break and continue as hacks > that > are not compatible with structured programming > techniques. > The only exception is using break in a switch in C, > C++ and > Java. > > However, all Python books seem to contain sample > programs like this one. Do you think that code like > this is desirable? YES. In C you can code while ((c = getchar()) != EOF) which combines the assignment and the conditional The equivalent Python code is something like: c = getchar() while c != EOF: c = getchar() Because the assignment is a separate statement and not an expression, it cannot be combined with the condition. So the Python consensus seems to be that you are better of with one assignment and embed the condition with a break at the proper spot within the loop. The loop is simply while True: # with newer Pythons c = getchar(1) if c == EOF: break In translating from other languages, note that many while loops can become for loops in Python. The while loop above came from K&R page 17, (The C Programming Language, Kernighan and Ritchie) counting lines in a file. A more natural Python translation would use nl = 0 for line in input: nl += 1 print nl Certainly break and continue can be abused. I would normally expect all break and continue testing to be in one section of the while loop so that it looks like while True: I'm glad to see Python getting taught in schools. When my daughter's college decided to stop teaching C++ as the first programming language (the year she took the course), I urged them to seriously consider Python, but they went with Java. > 2) Since this is an introductory class, I am tempted > to leave out "optional" topics like argument matching > modes, walk, map, filter, reduce, apply. Do you think > these are required for any Python programmer? I think the argument matching is too important to skip. For cases like HTTP POST data, passing a dictionary around is pretty convenient when you can pass it using the ** notation. It allows you to code: def celsius(fahrenheit, **kwds): return (fahrenheit - 32) * 5 / 9.0 postdata['celsius'] = celsius( **postdata) So functions can specify just the dictionary keys they care about. My little example imagines an HTML form with a variety of variables that include temperature conversions. Also zip(*args) is the transpose function. This is too handy to omit, but requires covering the single * mode of matching arguments. > > 3) I need to teach a GUI in this class. I would like > something that is easy, standard, and multi-platform. > I am considering Tkinter and Jython. Any opnions on > this? (not from me.) > > Thanks for any answers you might have. > > -Elaine Haight > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From bgailer at alum.rpi.edu Sun Aug 13 03:38:41 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 12 Aug 2006 18:38:41 -0700 Subject: [Tutor] How to teach Python In-Reply-To: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com> References: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com> Message-ID: <44DE82A1.3000903@alum.rpi.edu> Elaine wrote: > I am going to be teaching "Introduction to Python Programming" in the Fall at Foothill College in Los Altos Hills, CA. Great. Welcome to the Python Teachers Association. I'm your "neighbor" to the north, above Berkeley. > This is a 5 quarter unit class for students who already know one programming language. > I presume you mean "at least one". > I have been teaching programming for 20 years now, including Java and C++ as of late. > I did it for 10 years. Assembler, APL, BASIC, FORTRAN, PL/I,. Pascal, REXX, .... > As I prepare this class, I have some questions that I I am hoping you can shed some light on. > > 1) Programming Style > > while 1: > x = next() > if not x: break > > I have never allowed students to use break or continue in any programming class I have taught. I think of this type of code as belonging with the dreaded GOTO. > Consider that all "structured" programming statements are some form of GOTO. The question is not which are and which are not but rather the effect on readability and maintainability. The alternative to your code fragment is: x = True while x: x = next() IMHO the former is easier to read, understand, maintain. It gets even worse when the terminating condition occurs in the middle of the loop code. Then we are stuck with: limit = 45 x = limit while x >= limit: x = next() if x < limit: do more stuff with x or while 1: x = next() if x >= 45: break do more stuff with x I'd rather have the 2nd. > I find that students who are having difficulty writing complex conditions in a loop use multiple if's with break's inside the loop instead. Also, it is MUCH easier to read a loop if the condition for continuing in the loop is right up at the top of the loop where it belongs. > In some cases that IS where it belongs. In many others that is debatable. See my example above. A nice example from http://en.wikipedia.org/wiki/Control_flow#Early_exit_from_loops: for n in set_of_numbers: if isprime(n): print "Set contains a prime number" break else: print "Set did not contain any prime numbers" > I have always thought of break and continue as hacks that are not compatible with structured programming techniques. The only exception is using break in a switch in C, C++ and Java. > > However, all Python books seem to contain sample programs like this one. Do you think that code like this is desirable? > Consider also that a feature of Python is the generator, in which a function will suspend execution to return (yield) a result, then resume following the yield statement. Extremely useful, and hard to defend using a limited view of structured programming. > 2) Since this is an introductory class, I am tempted to leave out "optional" topics like argument matching modes, walk, map, filter, reduce, apply. Do you think these are required for any Python programmer? > Since many of there will disappear in Python 3 it might be OK to omit them. OTOH for those of us who come from languages like APL, these constructs are dear to our hearts. Also it is worth noting that filter and apply can be rewritten as list comprehensions, so they can be omitted. > 3) I need to teach a GUI in this class. I would like something that is easy, standard, and multi-platform. I am considering Tkinter and Jython. Any opnions on this? > Jython is not a GUI. > Thanks for any answers you might have. > Thanks for asking. And good luck with the class. And just for grins see http://www.fortran.com/come_from.html for FORTRAN's COME FROM statement. -- Bob Gailer 510-978-4454 From dyoo at hkn.eecs.berkeley.edu Sun Aug 13 06:59:33 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 12 Aug 2006 21:59:33 -0700 (PDT) Subject: [Tutor] How to teach Python In-Reply-To: <44DE82A1.3000903@alum.rpi.edu> References: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com> <44DE82A1.3000903@alum.rpi.edu> Message-ID: >> 2) Since this is an introductory class, I am tempted to leave out >> "optional" topics like argument matching modes, walk, map, filter, >> reduce, apply. Do you think these are required for any Python >> programmer? >> > Since many of there will disappear in Python 3 it might be OK to omit > them. OTOH for those of us who come from languages like APL, these > constructs are dear to our hearts. Hi Elaine, More generally: the "function is as first-class value" is a fundamental concept. I'm not sure when that concept should be introduced, but it definitely belongs in an introductory programming course. If one looks at code like this: if input == 'a': doA() elif input == 'b': doB() ... if we know that functions are avlues, we can reconsider it as: dispatchTable = { 'a' : doA, 'b' : doB, ... } dispatchTable[input]() Other textbooks have covered this ground; you may want to look at them for inspriation. Here's my favorite one now (it's not Python, but it's good stuff.): http://www.htdp.org/ From gunny01 at gmail.com Sun Aug 13 07:18:57 2006 From: gunny01 at gmail.com (Gunny -) Date: Sun, 13 Aug 2006 14:48:57 +0930 Subject: [Tutor] Making a CLI Text editor in Python Message-ID: <9bd0fd3d0608122218n1a650d34ma3da4aed76e702e6@mail.gmail.com> Hi, I've been playing around with Python for a while now, and I'm looking for where next to take my skills. I'm thinking of writing a simple text editor (in the style of Nano), but I'm not sure where to start. Some help or a point to a tutorial would be great Cheers Tom. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060813/11c5de8a/attachment.html From anilmrn at yahoo.com Sun Aug 13 09:56:55 2006 From: anilmrn at yahoo.com (anil maran) Date: Sun, 13 Aug 2006 00:56:55 -0700 (PDT) Subject: [Tutor] suggestions for read unread items datastructure Message-ID: <20060813075655.49062.qmail@web55915.mail.re3.yahoo.com> suggestions for read unread items datastructure [input] [input] [input] [input] keep a list of read and unread items hi guys i m building an rss reader and i want you suggestions for datastructure for keeping read and unread list for each use i m assuming it will be very sparse thanks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060813/b60b8ce3/attachment.html From alan.gauld at freenet.co.uk Sun Aug 13 10:18:10 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 13 Aug 2006 09:18:10 +0100 Subject: [Tutor] How to teach Python References: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com> Message-ID: <000c01c6beb1$03fa6c30$0201a8c0@XPpro> Hi Elaine, There is a separate mailing list for people who teach Python as opposed to people learning Python. They might have a more pertinent view on this. However, for what its worth here are my views... > students who already know one programming language. The language they know might make a big difference. For example if they know Lisp or Smalltalk then the aspects of Python that will be familiar are very diffferent than if they know C++/Java. > 1) Programming Style > > while 1: > x = next() > if not x: break Personally I don;t like this style either, its not intuitive and harder to read, but it is now the standard Python idiom in many cases. The reason for this is that you cannot use assignment in the test in Python, as you can with C/C++ etc so you would need to repeat the assignment: x = func() while x: doit() x = func() Some folks don't like the double assignment and so prefer while 1 x = func() if not x: break doit() Personally I prefer the first version... > I have never allowed students to use break or continue > in any programming class I have taught. I think of this type > of code as belonging with the dreaded GOTO. GOTO is no longer consider quite as evil as it used to be... :-) It just has to be used with discretion. > complex conditions in a loop use multiple if's with > break's I agree, and this can be a significant barrier to the understanding and use of boolean expressions. Its quite common to see that on this mailing list, although I admit we very rarely pick it up and comment. > inside the loop instead. Also, it is MUCH easier to > read a loop if the condition for continuing in the loop is > right up at the top of the loop where it belongs. Again I agree. > I have always thought of break and continue as hacks > that are not compatible with structured programming > techniques. In a pure sense you are right because strictly speaking structured programming requires a single exit point in a function or block. But break/continue are not the only culprits here, multiple return statements have the same effect. In practice multiple returns and break/continue can improve the readibility of code significantly as well as the performance. (And this is also true of GOTO which is why academics are giving GOTO a cautious rebirth) > The only exception is using break in a switch in C, > C++ and Java. And that's purely because the switch statement, like so much else, is a badly designed construct in both languages. The default position should be to exit the case condition at the end of the block, not fall through to the next block!. > However, all Python books seem to contain sample > programs like this one. Do you think that code like > this is desirable? No, but it is standard Python idiom so for the sake of students underdstanding other people's Python code you probably need to teach it - although you might leave it to near the end, after showing the alternatives! OTOH I don't discuss break/continue in my tutor until into the advanced topics... And didn't use them at all in the original vesion (c 1998) or in the book. > 2) Since this is an introductory class, I am tempted > to leave out "optional" topics like argument matching > modes, walk, map, filter, reduce, apply. Do you think > these are required for any Python programmer? The functional programming aspects can be left out, argument matching, if you mean what I think, is quite important in a dymanically typed language. I'd keep that in. If you teach list comprehensions you will make the map/filter/reduce set almost irrelevant anyway. > 3) I need to teach a GUI in this class. I would like > something that is easy, standard, and multi-platform. > I am considering Tkinter and Jython. Any opnions on > this? If they already know Java then teach Jython. Otherwise Teach Tkinter because 1) its the python standard 2) its best documented 3) its pretty easy 4) it has a limited widget set (but explore Tix too) which is easy to extend 5) its based on Tk which is also the standard GUI for Tcl and Perl - and there are versions of it for Lisp and C. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From johna at johnaherne.co.uk Sun Aug 13 10:27:46 2006 From: johna at johnaherne.co.uk (John Aherne) Date: Sun, 13 Aug 2006 09:27:46 +0100 Subject: [Tutor] self (again) Message-ID: <44DEE282.5080904@johnaherne.co.uk> I have been following the thread on self because for the past month I have been driven potty trying to be sure that I understand the ramifications of how self works. I have tried to create some code that tries to prove how self, variables, assignment and namespace gel together. I can't convince myself that I have it right. I think it works as follows. I just need to know what is right. Class variables are 'global' for the class and all instances of the class. Using self makes the assignment 'local' to the instance. This is used to create variables that will retain the assigned value for the duration of the instance. This variable is 'global' for the instance. It can be accessed by all the functions in the class/instance without being passed as a parameter from function to function. Self is used if you want to create a class where you store data for a 'long' period of time. Not like local variables that only have duration for the execution of the function. Within the def functions inside the class, assignments inside the function are local. If the def function inside a class takes a set of parameters that are passed in from outside e.g. class one: def func1(parm1,parm2,parm3): These parameters are passed by reference. So they refer to values held elsewhere. If I use the names inside the function what problem will I give myself. Are they local, global. e.g. if parm1=='somevalue': How long can I trust the value in the passed parameter - parm1 What namespace are they in. I run all this under modpython on windows, where one python interpreter runs all the instances so I have multiple copies of the code running in the same interpreter. What is likely to happen to these values being passed by reference if several people log in at once and run the code. Hope I have explained myself so people can understand what I mean. Looking forward to the light of understanding. Regards John Aherne From john.corry at ntlworld.com Sun Aug 13 11:56:32 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sun, 13 Aug 2006 10:56:32 +0100 Subject: [Tutor] key_press_event Message-ID: <000001c6bebe$c5cedcd0$4f3ea8c0@JOHNC> Hi, I'm using Python 2.4, pygtk and Glade2. I have a few text entries. I am trying to put validation on the text entry boxes. I am trying to catch the key_press_event, check the key that has been pressed and either allow it or put back the old text. The code is below with the output after it. class Test: def __init__(self): self.wTree = gtk.glade.XML ("test.glade", "window1") dic={"on_window1_delete_event" : self.quit10, } self.wTree.signal_autoconnect(dic) cancel = self.wTree.get_widget("button2") cancel.connect("clicked", self.quit, ) text1 = self.wTree.get_widget("entry1") text2 = self.wTree.get_widget("entry2") text2.connect("key_press_event",self.callback3) login = self.wTree.get_widget("button1") login.connect("clicked", self.callback2, text1,text2) def callback3(self,data,widget): input = data.get_text() print input data.set_text("test") def callback2(self,data,text1,text2): print 'hello' def quit10(self,obj,data): gtk.main_quit() sys.exit(1) def quit(self,obj): gtk.main_quit() sys.exit(1) if __name__ == '__main__': Test() try: gtk.threads_init() except: print "No threading was enabled when you compiled pyGTK!" import sys sys.exit(1) gtk.threads_enter() gtk.main() gtk.threads_leave() The box starts of with 123 in it. If I hit the 'a' key on the key board I get the following result. 123 is printed and 'atest' appears in the text entry box. Is there a way to catch the key_press (in this case the 'a') and check to see if it is a number. If it is not a number, ignore it. If it is a number accept it. Why does the 'a' appear in 'atest'. It is like the code works first, sets the text to 'test' and then the key press works and inserts the 'a'. Do I need to disconnect the key press signal? Thanks, John. From wescpy at gmail.com Sun Aug 13 12:19:56 2006 From: wescpy at gmail.com (wesley chun) Date: Sun, 13 Aug 2006 03:19:56 -0700 Subject: [Tutor] How to teach Python In-Reply-To: <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com> References: <44C0EF6F.7070907@gmail.com> <20060812220921.46742.qmail@web31709.mail.mud.yahoo.com> Message-ID: <78b3a9580608130319h5460dd71ta28e32a0b52c4c2b@mail.gmail.com> hi elaine, welcome to Tutor. this list is really for those learning Python and/or programming, so i'm going to assume that your question is directed to mainly tutors, but perhaps tutees in reference to their experience in learning Python and how it was/is taught to them. if you want to address teachers and other educational individuals, you should probably post to the EDU-SIG mailing list -- i'd recommend cross-posting there if you wish: http://mail.python.org/mailman/listinfo/edu-sig there have been so many good responses so far that i can just say that you will see "as others have said" quite often in my reply here. > I am going to be teaching "Introduction to Python > Programming" in the Fall at Foothill College in Los > Altos Hills, CA. that's great! i am also a Python teacher professionally and happen to live just 5 minutes away from the campus. if you ever need a substitute and don't wish to cancel class for any some reason, drop me a line. > I have been teaching programming for 20 years now, > including Java and C++ as of late. i have been teaching since 1983... BASIC, C, and Python are the programming languages i have taught over the years. > 1) Programming Style > while 1: > x = next() > if not x: break > > I have never allowed students to use break or continue > in any programming class I have taught. I think of this > type of code as belonging with the dreaded GOTO. > > I have always thought of break and continue as hacks that > are not compatible with structured programming techniques. > The only exception is using break in a switch in C, C++ and > Java. > > However, all Python books seem to contain sample > programs like this one. Do you think that code like > this is desirable? as others have mentioned already, because assignments are not expressions in Python, it is quite a common idiom and should be covered and implemented in this manner to keep the code cleaner and more consistent. remember that "readability counts." its are in all the books because it is one of those basic idioms that ppl *have* to use to get things done. also as others have said, GOTO does not have the stigma that it once had and that there is nothing wrong in principle with break and continue when used with loops, which is what they were designed to do. you pretty much have to be a very experienced programmer in order to know when and where are the right places for that beast. with that said, it would be a good idea to review the Zen to truly understand the philosophy of Python. it is one thing teaching and learning Python, but it is another step when you are able to understand it and program in a "Pythonic" way. (if away from the internet or a book, you can access then Zen using 'import this' or 'python -m this' from the shell.) > 2) Since this is an introductory class, I am tempted > to leave out "optional" topics like argument matching > modes, walk, map, filter, reduce, apply. Do you think > these are required for any Python programmer? list comprehensions (and generator expressions) have obsoleted map() and filter() because in general, their performance is better, but that is not always the case. apply() was deprecated by the new function invocation mechanism using * and ** back in Python 1.6. reduce() will stick around. i'm not sure what "walk" is, and argument matching is important. in fact, you need to cover standard/formal/required argus, default args, keyword args, and variable args (* tuples and ** dictionaries). > 3) I need to teach a GUI in this class. I would like > something that is easy, standard, and multi-platform. > I am considering Tkinter and Jython. Any opnions on > this? Tkinter was chosen as the default for Python way back in the early days because that was easy to understand and teach and was available on the big 3 platforms (Unix, Win, Mac). i teach this in my courses (and also in "Core Python," the textbook i wrote for college-level courses as well as for working professionals), but also try to cover more advanced and related widget sets like Pmw and Tix. if you want to teach the most basic concepts, even leaving off event-driven programming, take a look at EasyGUI. since then, however, it is no longer the only GUI toolkit. wxWindows (and its adapter wxPython) has grown in userbase quite a lot in the last few years -- it is also cross-plat- form. one of its greatst features is that it uses a system's native widget set. in other words, GUIs written on Win32 look like Windoze apps, and the same for Mac and *ix. there are some nice "intro" libraries like PythonCard. for building GUIs in wxPython, one of the most painless ways is using Boa Constructor. you can drag-n-drop widgets onto a canvas. Boa writes the boilerplate code, and you only have to worry about supplying the callbacks. fwiw, i teach both an "Introduction to Programming using Python" course as well as an (intensive) "Introduction to Python" programming course. the first is meant for those with no programming experience whatsoever while the second matches your prerequisite of knowledge of at least one other high-level language is required. if you're curious as to the topics i cover in either course, here are their course descriptions, repsectively: http://roadkill.com/~wesc/cyberweb/ippdsc.html http://roadkill.com/~wesc/cyberweb/pp1dsc.html it is also not by coincidence that the syllabus follows the text and exercises found in "Core Python" very closely. :-) good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From john.corry at ntlworld.com Sun Aug 13 12:47:05 2006 From: john.corry at ntlworld.com (John CORRY) Date: Sun, 13 Aug 2006 11:47:05 +0100 Subject: [Tutor] [pygtk] key_press_event In-Reply-To: <20060813102743.GA11920@casa.e-den.it> Message-ID: <000201c6bec5$d5f89270$4f3ea8c0@JOHNC> Sandro, That's exactly what I need. Thanks, John. > def callback3(self,data,widget): > > input = data.get_text() > print input > data.set_text("test") If you don't return True, default callback will be called that insert the 'a'. I have something like this: def digits_check_input_cb(self, widget, event): """prevents the possibility of inputting wrong chars""" ## fixme: missing comma, and cut&paste key = gtk.gdk.keyval_name (event.keyval) ONLYDIGITS="([0-9.,]|BackSpace|Left|Right|F1|period|Tab|Up|Down)" if not re.match (ONLYDIGITS, key): return True Not sure whether this is the best way thought... sandro *;-) -- Sandro Dentella *:-) http://www.tksql.org TkSQL Home page - My GPL work From pythontut at pusspaws.net Sun Aug 13 13:33:00 2006 From: pythontut at pusspaws.net (dave s) Date: Sun, 13 Aug 2006 11:33:00 +0000 Subject: [Tutor] Style query Message-ID: <200608131133.00864.pythontut@pusspaws.net> As my programs become more complex I am aware of the need to adopt a consistent style. To differentiate between classes, instances & objects I use capital letters for example: A class uses 'MyClass' A class instance 'myInstance' A def uses 'myDef' An object 'myobject' or 'my_object' etc Can any of you more experienced programmers outline your style or critique my way of doing this ? Tell me if you have a different system - I am trying to get myself into good habits :) Is there a Python style guide anywhere ? Cheers Dave PS I have started using packages, so much easier and more flexable than long PYTHONPATH declarations and am now proramming with QT :). From rfquerin at gmail.com Sun Aug 13 14:02:10 2006 From: rfquerin at gmail.com (Richard Querin) Date: Sun, 13 Aug 2006 08:02:10 -0400 Subject: [Tutor] Style query In-Reply-To: <200608131133.00864.pythontut@pusspaws.net> References: <200608131133.00864.pythontut@pusspaws.net> Message-ID: <7d81675b0608130502j2cbad2fap1b224726de99f643@mail.gmail.com> I believe you can find it here: http://www.python.org/doc/essays/styleguide.html Authored by Guido Van Rossum himself. Cheers, Richard On 8/13/06, dave s wrote: > > As my programs become more complex I am aware of the need to adopt a > consistent style. To differentiate between classes, instances & objects I > use > capital letters for example: > > A class uses 'MyClass' > A class instance 'myInstance' > A def uses 'myDef' > An object 'myobject' or 'my_object' etc > > Can any of you more experienced programmers outline your style or critique > my > way of doing this ? Tell me if you have a different system - I am trying > to > get myself into good habits :) > > Is there a Python style guide anywhere ? > > Cheers > > Dave > > > PS > > I have started using packages, so much easier and more flexable than long > PYTHONPATH declarations and am now proramming with QT :). > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060813/cb338018/attachment.html From pythontut at pusspaws.net Sun Aug 13 14:13:19 2006 From: pythontut at pusspaws.net (dave s) Date: Sun, 13 Aug 2006 12:13:19 +0000 Subject: [Tutor] Style query In-Reply-To: <7d81675b0608130502j2cbad2fap1b224726de99f643@mail.gmail.com> References: <200608131133.00864.pythontut@pusspaws.net> <7d81675b0608130502j2cbad2fap1b224726de99f643@mail.gmail.com> Message-ID: <200608131213.21950.pythontut@pusspaws.net> On Sunday 13 August 2006 12:02, you wrote: > I believe you can find it here: > > http://www.python.org/doc/essays/styleguide.html > > Authored by Guido Van Rossum himself. > Thanks :) Dave > > Cheers, > > Richard > > On 8/13/06, dave s wrote: > > As my programs become more complex I am aware of the need to adopt a > > consistent style. To differentiate between classes, instances & objects I > > use > > capital letters for example: > > > > A class uses 'MyClass' > > A class instance 'myInstance' > > A def uses 'myDef' > > An object 'myobject' or 'my_object' etc > > > > Can any of you more experienced programmers outline your style or > > critique my > > way of doing this ? Tell me if you have a different system - I am trying > > to > > get myself into good habits :) > > > > Is there a Python style guide anywhere ? > > > > Cheers > > > > Dave > > > > > > PS > > > > I have started using packages, so much easier and more flexable than long > > PYTHONPATH declarations and am now proramming with QT :). > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Sun Aug 13 18:50:08 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 13 Aug 2006 09:50:08 -0700 Subject: [Tutor] suggestions for read unread items datastructure In-Reply-To: <20060813075655.49062.qmail@web55915.mail.re3.yahoo.com> References: <20060813075655.49062.qmail@web55915.mail.re3.yahoo.com> Message-ID: <44DF5840.7080204@alum.rpi.edu> anil maran wrote: > > suggestions for read unread items datastructure > > > keep a list of read and unread items > > hi guys > i m building an rss reader and i want you suggestions for datastructure > for keeping read and unread list for each use > i m assuming it will be very sparse Just a guess but I think the lack of response is due to (at least for me) not knowing enough about your situation to give a useful response. Please tell us more. -- Bob Gailer 510-978-4454 From simplebob at gmail.com Sun Aug 13 20:22:06 2006 From: simplebob at gmail.com (Daniel McQuay) Date: Sun, 13 Aug 2006 14:22:06 -0400 Subject: [Tutor] suggestions for read unread items datastructure In-Reply-To: <44DF5840.7080204@alum.rpi.edu> References: <20060813075655.49062.qmail@web55915.mail.re3.yahoo.com> <44DF5840.7080204@alum.rpi.edu> Message-ID: <6d87ecf40608131122i29bdcadew16d48d03f3264382@mail.gmail.com> i concur, anil try looking at how you ask a question. http://catb.org/~esr/faqs/smart-questions.html#before On 8/13/06, Bob Gailer wrote: > > anil maran wrote: > > > > suggestions for read unread items datastructure > > > > > > keep a list of read and unread items > > > > hi guys > > i m building an rss reader and i want you suggestions for datastructure > > for keeping read and unread list for each use > > i m assuming it will be very sparse > Just a guess but I think the lack of response is due to (at least for > me) not knowing enough about your situation to give a useful response. > Please tell us more. > > -- > Bob Gailer > 510-978-4454 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Daniel McQuay simplebob at gmail.com boxster.homelinux.org prowiseguys.com H: 814.825.0847 M: 814-341-6233 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060813/51e1a794/attachment.html From anilmrn at yahoo.com Sun Aug 13 21:21:31 2006 From: anilmrn at yahoo.com (anil maran) Date: Sun, 13 Aug 2006 12:21:31 -0700 (PDT) Subject: [Tutor] suggestions for read unread items datastructure In-Reply-To: <44DF5840.7080204@alum.rpi.edu> Message-ID: <20060813192131.98005.qmail@web55912.mail.re3.yahoo.com> there is a blog and it associated feed entries the blog posts when someone clicks it i need to maintain read status for it and when it is unclicked i need the unread status this needs to be maintianed for a huge number of usrs thanks Bob Gailer wrote: anil maran wrote: > > suggestions for read unread items datastructure > > > keep a list of read and unread items > > hi guys > i m building an rss reader and i want you suggestions for datastructure > for keeping read and unread list for each use > i m assuming it will be very sparse Just a guess but I think the lack of response is due to (at least for me) not knowing enough about your situation to give a useful response. Please tell us more. -- Bob Gailer 510-978-4454 __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060813/825cd583/attachment-0001.htm From dyoo at hkn.eecs.berkeley.edu Sun Aug 13 22:18:36 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 13 Aug 2006 13:18:36 -0700 (PDT) Subject: [Tutor] suggestions for read unread items datastructure In-Reply-To: <20060813192131.98005.qmail@web55912.mail.re3.yahoo.com> References: <20060813192131.98005.qmail@web55912.mail.re3.yahoo.com> Message-ID: On Sun, 13 Aug 2006, anil maran wrote: > when someone clicks it i need to maintain read status for it Hi Anil, You've giving some "use case" information, which is useful. Can you also give us some definitions? Are you saying that an rss entry is some data with an associated 'read' status? What else does an rss entry have? What do people do with it? I'm mimicking total ignorance here, but this is not far from the truth. *grin* I really don't know what an RSS reader is supposed to handle, and since it sounds like you're writing one from scratch, you should also explicitely state what things you want out of it. In your earlier question, you asked what an appropriate data structure will be for storing RSS entries. It sounds that you're dealing with two distinct data types: * A singular 'RssEntry' that contains information on a single RSS item. * An 'RssLibrary' collection that has a bunch of 'RssEntries'. Is this accurate, or are you thinking of something else? What are the operations you want to do with your data types? > this needs to be maintianed for a huge number of usrs Let's try to forget efficiency for the moment; I'm not even sure people on the list are even clear about what you are trying to represent yet. Let's get the concepts solid first before talking about scaling to large groups. From alan.gauld at freenet.co.uk Mon Aug 14 01:24:09 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Aug 2006 00:24:09 +0100 Subject: [Tutor] suggestions for read unread items datastructure References: <20060813192131.98005.qmail@web55912.mail.re3.yahoo.com> Message-ID: <00c201c6bf2f$9447f630$0201a8c0@XPpro> Caveat - I know nothing about RSS, it's one of those web technologies that I just can't get excited about, sorry... However... > there is a blog > and it associated feed entries > the blog posts > when someone clicks it i need to maintain read status for it > and when it is unclicked i need the unread status > this needs to be maintianed for a huge number of usrs Whenever you need to maintain data for "a huge number of users" its time to question whether it's your job to maintain the data. Maybe the users should each maintain their own data? That's the idea behind cookies in a web browsing context - does anything similar work for RSS? Alan G. From alan.gauld at freenet.co.uk Mon Aug 14 01:44:46 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Aug 2006 00:44:46 +0100 Subject: [Tutor] self (again) References: <44DEE282.5080904@johnaherne.co.uk> Message-ID: <00c801c6bf32$7581aae0$0201a8c0@XPpro> > I think it works as follows. I just need to know what is right. > > Class variables are 'global' for the class and all instances of the > class. Correct. Classes are containers and they contain the class variables and method definitions shared by all instances of the class (and its subclasses). > Using self makes the assignment 'local' to the instance. Sort of, but self is just a reference to an instance of a class. There is no magic involved (or very little), when you call a method on an instance you simply execute the function stored in the class object but pass in a reference to the called instance as the first argument. > create variables that will retain the assigned value for the > duration of the instance. Correct, the instance is also a container that holds a reference to the defining class and all the instance variables. > This variable is 'global' for the instance. I'd prefer to say local to the instance. Its not shared outside the instance and can only be accessed in methods via the self reference > accessed by all the functions in the class/instance without being > passed as a parameter from function to function. No, it can only be accessed by the methods via the self reference that is passed implicitly in each method call. > Self is used if you want to create a class where you store data for > a 'long' period of time. Not like local variables that only have > duration for the execution of the function. No, self is purely about allowing the methods stored in a class object to access the instance variables of the specific instance that invoked the method at any given point in time. There are many ways to store data over a long period that do not use self (global variables, lists, dictionaries, tuples, files, databases). Even class attributes can do that, regardless of whether any instances are created. > Within the def functions inside the class, assignments inside the > function are local. As they are in any other functuion, again nothing magic is happening here. > If the def function inside a class takes a set of parameters that > are passed in from outside e.g. > class one: > def func1(parm1,parm2,parm3): > > These parameters are passed by reference. So they refer to values > held elsewhere. Again just like any other function, yes. > If I use the names inside the function what problem will I give > myself. None, thats what they are there for. They are your mechanism for comunicating between the world outside the function and the world (or namespace) inside. > Are they local, global. They are local. The name of the parameter bears norelation to what that value is called (or referenced by) outsidfe the function. > e.g. if parm1=='somevalue': How long can I trust the value in the > passed parameter - parm1 Until you change it or exit the function. Example: def f(a,b): if a > b: a = b return a+b x=3 f(x,4) -> 7 print x -> 3 f(x,3) -> 6 print x -> 3 f(x,2) -> 4 print x -> 3 So even in the last case x remains equal to 3 but inside the function the value of a was changed to 2. This is standard function behaviour and there is nothing different about methods in a class. > What namespace are they in. The parameters are in the local namespace of the method. > I run all this under modpython on windows, where one python > interpreter runs all the instances so I have multiple copies of the > code running in the same interpreter. What is likely to happen to > these values being passed by reference if several people log in at > once and run the code. I know nothing about mod_python but assuming it uses threading then you need to avoid changing global variables or class variables without using locks or semaphores. But instances created in a thread should remain independant from each other - a good reason for using OOP for multi threaded code! > Hope I have explained myself so people can understand what I mean. ditto! Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kermit at polaris.net Mon Aug 14 02:37:43 2006 From: kermit at polaris.net (Kermit Rose) Date: Sun, 13 Aug 2006 20:37:43 -0400 (Eastern Daylight Time) Subject: [Tutor] Global variables References: Message-ID: <44DFC5D7.00000D.02912@YOUR-4105E587B6> From: Danny Yoo Date: 08/09/06 16:23:35 To: Kermit Rose Cc: tutor at python.org If I can figure out how to make my main function subroutine declare global variables then I won't need to pass parameters most parameters to the other subroutines, and will bypass the problem I'm having that sometimes the function strongfac SOMETIMES does not return the value it has in the subroutine, back to the calling routine. Kermit < kermit at polaris.net > From dianahawks at optusnet.com.au Mon Aug 14 03:57:53 2006 From: dianahawks at optusnet.com.au (Diana Hawksworth) Date: Mon, 14 Aug 2006 11:57:53 +1000 Subject: [Tutor] Python on network problems Message-ID: <200608140157.k7E1vrWP013862@mail16.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20060814/5244fe1a/attachment.pot From rabidpoobear at gmail.com Mon Aug 14 04:28:37 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 13 Aug 2006 21:28:37 -0500 Subject: [Tutor] Global variables In-Reply-To: <44DFC5D7.00000D.02912@YOUR-4105E587B6> References: <44DFC5D7.00000D.02912@YOUR-4105E587B6> Message-ID: <44DFDFD5.2080208@gmail.com> Kermit Rose wrote: > > > From: Danny Yoo > Date: 08/09/06 16:23:35 > To: Kermit Rose > Cc: tutor at python.org > > > If I can figure out how to make my main function subroutine declare global > variables > then I won't need to pass parameters most parameters to the other > subroutines, > > and will bypass the problem I'm having that sometimes the function strongfac > SOMETIMES does not return the value it has in the subroutine, back to the > calling routine. > are you asking a question? From rabidpoobear at gmail.com Mon Aug 14 04:37:22 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 13 Aug 2006 21:37:22 -0500 Subject: [Tutor] Python on network problems In-Reply-To: <200608140157.k7E1vrWP013862@mail16.syd.optusnet.com.au> References: <200608140157.k7E1vrWP013862@mail16.syd.optusnet.com.au> Message-ID: <44DFE1E2.6000309@gmail.com> Diana Hawksworth wrote: > Dear List, > > I have Python installed on 1 of 4 labs at my High School. The lab is connected to a whole school network. Students login through the network - but Python is active in this lab only. > You have 4 labs. Python is installed on all the computers in a single lab. All of the labs are networked together. Students log into an authentication server and not to the individual computer. Are they given 'virtual' drives? some type of network-based storage? Are they using Windows? What version? What do you mean 'Python is _active_'? > Sometimes I have a student who simply cannot access Python, even though he has been working on it for a number of months now. Usually a change in username will solve the problem - but I would like to know what is causing this to happen. > They can't access the python install on the individual computer on which they're logged, or they can't access a python install that's on a different computer on the network? A change in their network login fixes the problem? > The second problem is much more severe. Seems for the past three weeks now, the entire system will crash. It happens when we are working on Python - so the assumption is that the program is to blame. I cannot see that it is - but it certainly is upsetting when it happens. Has anyone had a similar accurrence with Python and networks? If so - what have you done about it. If not - then any clues about what could be happening so that I can get the system administrator off my back - and get the system working again!! > > Thanks for any suggestions. > Is it like this: Lab1: Computer1 - has python Computer2 - has python Lab2: Computer3 - no python Lab3: Computer4 - no python Lab4: Computer5 - no python A user logs onto the network from Computer5 in Lab4. Do you expect him to be able to run a python script? What interpreter do you expect him to use? One that's installed on a computer in Lab1? Say a user logs onto Computer1. they can run python programs on their computer. Do you expect them to be able to run python programs that are stored on Computer2, using the interpreter that's installed on Computer1? I'm not too clear on how you have this set up, what it's supposed to do, and why the network is involved at all. It seems like the kids should be able to run python scripts on any computer in Lab1 without fiddling with the network whatsoever, so I suspect that there's some additional information that I'm not getting. Can you clarify? Thanks, -Luke > Diana > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From anilmrn at yahoo.com Mon Aug 14 07:59:54 2006 From: anilmrn at yahoo.com (anil maran) Date: Sun, 13 Aug 2006 22:59:54 -0700 (PDT) Subject: [Tutor] suggestions for read unread items datastructure In-Reply-To: <00c201c6bf2f$9447f630$0201a8c0@XPpro> Message-ID: <20060814055954.23253.qmail@web55914.mail.re3.yahoo.com> i m sure the users need to maintain their own data, but as a provider we need to store their information right, sessions and cookies work only during their stay in the site, after they exit, im sure they would like to come back to the same info, wont u so i was wondering what is the best way to maintain the list of read/unread items in a python datastructure, --- Alan Gauld wrote: > Caveat - I know nothing about RSS, it's one of those > web > technologies that I just can't get excited about, > sorry... > > However... > > > there is a blog > > and it associated feed entries > > the blog posts > > when someone clicks it i need to maintain read > status for it > > and when it is unclicked i need the unread status > > this needs to be maintianed for a huge number of > usrs > > Whenever you need to maintain data for "a huge > number of users" > its time to question whether it's your job to > maintain the data. > Maybe the users should each maintain their own data? > That's > the idea behind cookies in a web browsing context - > does > anything similar work for RSS? > > Alan G. > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From rdm at rcblue.com Mon Aug 14 08:30:37 2006 From: rdm at rcblue.com (Dick Moores) Date: Sun, 13 Aug 2006 23:30:37 -0700 Subject: [Tutor] Having trouble getting mind around decimal module Message-ID: <7.0.1.0.2.20060813231658.06d43ff8@rcblue.com> I'm having trouble getting my mind around the decimal module. From the tutorial () I can see how to get 1/7 to, say, 32 places: >>> from decimal import Decimal >>> getcontext().prec = 32 >>> Decimal(1) / Decimal(7) Decimal("0.14285714285714285714285714285714") But I can't figure out how to compute to 32 places things like the square root of 2, or the arc tangent of .41. Could someone please show me? Thanks, Dick Moores rdm at rcblue.com From dianahawks at optusnet.com.au Mon Aug 14 08:55:43 2006 From: dianahawks at optusnet.com.au (Diana Hawksworth) Date: Mon, 14 Aug 2006 16:55:43 +1000 Subject: [Tutor] Python on network problems References: <200608140157.k7E1vrWP013862@mail16.syd.optusnet.com.au> <44E01809.9070200@gmail.com> Message-ID: <000c01c6bf6e$a9c781d0$2e716c3a@SNNECCM> Thanks Tom. I installed the latest version on Friday - but today the system went down again. I am inclined to think it is not a Python problem at all. Just need someone who also has it installed on a network to know if they have had any problems!! Diana ----- Original Message ----- From: "Tom Schinckel" To: Sent: Monday, August 14, 2006 4:28 PM Subject: Re: [Tutor] Python on network problems > Diana Hawksworth wrote: >> Dear List, >> >> I have Python installed on 1 of 4 labs at my High School. The lab is >> connected to a whole school network. Students login through the >> network - but Python is active in this lab only. >> >> Sometimes I have a student who simply cannot access Python, even though >> he has been working on it for a number of months now. Usually a change >> in username will solve the problem - but I would like to know what is >> causing this to happen. >> >> The second problem is much more severe. Seems for the past three weeks >> now, the entire system will crash. It happens when we are working on >> Python - so the assumption is that the program is to blame. I cannot see >> that it is - but it certainly is upsetting when it happens. Has anyone >> had a similar accurrence with Python and networks? If so - what have you >> done about it. If not - then any clues about what could be happening so >> that I can get the system administrator off my back - and get the system >> working again!! >> >> Thanks for any suggestions. >> >> Diana >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > It sounds a tad out of my depth, but when I first installed Python, IDLE > crashed, all the time. > > Try the age old software fix: reinstall. > > Cheers > > Tom > From rabidpoobear at gmail.com Mon Aug 14 09:49:50 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 14 Aug 2006 02:49:50 -0500 Subject: [Tutor] Having trouble getting mind around decimal module In-Reply-To: <7.0.1.0.2.20060813231658.06d43ff8@rcblue.com> References: <7.0.1.0.2.20060813231658.06d43ff8@rcblue.com> Message-ID: <44E02B1E.2070103@gmail.com> Dick Moores wrote: > I'm having trouble getting my mind around the decimal module. From > the tutorial () I > can see how to get 1/7 to, say, 32 places: > > >>> from decimal import Decimal > >>> getcontext().prec = 32 > >>> Decimal(1) / Decimal(7) > Decimal("0.14285714285714285714285714285714") > > But I can't figure out how to compute to 32 places things like the > square root of 2, or the arc tangent of .41. Could someone please show me? > > I think square root calculations, and other math operations, by the built-in math.py package only work on floats since they wrap math.c So you'd have to find a pure-python implementation that supported Decimal objects I guess, or write your own. > Thanks, > > Dick Moores > rdm at rcblue.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at freenet.co.uk Mon Aug 14 09:52:42 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Aug 2006 08:52:42 +0100 Subject: [Tutor] Having trouble getting mind around decimal module References: <7.0.1.0.2.20060813231658.06d43ff8@rcblue.com> Message-ID: <002501c6bf76$9fc805d0$0201a8c0@XPpro> > >>> from decimal import Decimal > >>> getcontext().prec = 32 > >>> Decimal(1) / Decimal(7) > Decimal("0.14285714285714285714285714285714") > > But I can't figure out how to compute to 32 places things like the > square root of 2, or the arc tangent of .41. Could someone please > show me? The first is easy: >>> from decimal import getcontext >>> getcontext().prec = 32 >>> Decimal(2).sqrt() Decimal("1.4142135623730950488016887242097") actan(0.41) is trickier... because you need to use the math module >>> Decimal(str(math.atan(0.41))) 0.38909723105527838 And that limits the precision. If you were working with lower value precision - say 16 digits - then it would be OK. >>> getcontext().prec=12 >>> Decimal(str(math.atan(0.41))) Decimal("0.389097231055") >>> HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Mon Aug 14 09:56:27 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 14 Aug 2006 02:56:27 -0500 Subject: [Tutor] suggestions for read unread items datastructure In-Reply-To: <20060814055954.23253.qmail@web55914.mail.re3.yahoo.com> References: <20060814055954.23253.qmail@web55914.mail.re3.yahoo.com> Message-ID: <44E02CAB.2040507@gmail.com> anil maran wrote: > i m sure the users need to maintain their own data, > but as a provider we need to store their information > right, sessions and cookies work only during their > stay in the site, after they exit, im sure they would > like to come back to the same info, wont u > > so i was wondering what is the best way to maintain > the list of read/unread items in a python > datastructure, > It's not that we don't want to help you, it's that we don't understand what you want to do. Consider this: Are you trying to make a client-side program for this? If so, why do you care about storing multiple user data? Are you making a server that mirrors other RSS feeds for your users? Are you making a client-side program that communicates with a single server that has everyone's RSS feeds on it? Why do you think you need to do things this way? Why are you concerned about the data structure used to store this when there's other things to be concerned about (RSS feed parsing, etc, etc.) This should be one of the last things you worry about. Also, Alan wasn't suggesting you use cookies. He was stating that websites allow the client to maintain information about their own activities, rather than the server trying to manage all the users. He means that maybe you shouldn't be concerned about which RSS feeds your clients have been to and let the clients take care of it themselves. Sort of how my mailserver sends me all my mail, but my E-mail client takes care of marking individual messages 'read/unread' and sorting it into folders. There's no reason for the server to need to know about any of this stuff. Does your server really need to know about which RSS feeds the clients have viewed? > --- Alan Gauld wrote: > > >> Caveat - I know nothing about RSS, it's one of those >> web >> technologies that I just can't get excited about, >> sorry... >> >> However... >> >> >>> there is a blog >>> and it associated feed entries >>> the blog posts >>> when someone clicks it i need to maintain read >>> >> status for it >> >>> and when it is unclicked i need the unread status >>> this needs to be maintianed for a huge number of >>> >> usrs >> >> Whenever you need to maintain data for "a huge >> number of users" >> its time to question whether it's your job to >> maintain the data. >> Maybe the users should each maintain their own data? >> That's >> the idea behind cookies in a web browsing context - >> does >> anything similar work for RSS? >> >> Alan G. >> >> > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at freenet.co.uk Mon Aug 14 09:56:36 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Aug 2006 08:56:36 +0100 Subject: [Tutor] Python on network problems References: <200608140157.k7E1vrWP013862@mail16.syd.optusnet.com.au><44E01809.9070200@gmail.com> <000c01c6bf6e$a9c781d0$2e716c3a@SNNECCM> Message-ID: <002901c6bf77$2b8de210$0201a8c0@XPpro> Diana, It is almost certainly not a Python problem but related to how you have the network set up. As Luke was trying to point out, we mifght be able to help out but your description of the network setup wasn't clear. We need more precise information about things like: what OS you are using? Are you using Domains/NIS/NDS etc? Do you have shared drives, VNC, windows terminal server? How do you define a 'lab'? What do you mean by python being 'active'? And what exactly happens when a failure occurs? None of these things are standardised in anmy way. Alan G ----- Original Message ----- From: "Diana Hawksworth" To: "Tom Schinckel" ; Sent: Monday, August 14, 2006 7:55 AM Subject: Re: [Tutor] Python on network problems > Thanks Tom. I installed the latest version on Friday - but today > the system went down again. I am inclined to think it is not a > Python problem at all. Just need someone who also has it installed > on a network to know if they have had any problems!! > Diana > > ----- Original Message ----- > From: "Tom Schinckel" > To: > Sent: Monday, August 14, 2006 4:28 PM > Subject: Re: [Tutor] Python on network problems > > >> Diana Hawksworth wrote: >>> Dear List, >>> >>> I have Python installed on 1 of 4 labs at my High School. The lab >>> is connected to a whole school network. Students login through >>> the network - but Python is active in this lab only. >>> >>> Sometimes I have a student who simply cannot access Python, even >>> though he has been working on it for a number of months now. >>> Usually a change in username will solve the problem - but I would >>> like to know what is causing this to happen. >>> >>> The second problem is much more severe. Seems for the past three >>> weeks now, the entire system will crash. It happens when we are >>> working on Python - so the assumption is that the program is to >>> blame. I cannot see that it is - but it certainly is upsetting >>> when it happens. Has anyone had a similar accurrence with Python >>> and networks? If so - what have you done about it. If not - then >>> any clues about what could be happening so that I can get the >>> system administrator off my back - and get the system working >>> again!! >>> >>> Thanks for any suggestions. >>> >>> Diana >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> It sounds a tad out of my depth, but when I first installed Python, >> IDLE crashed, all the time. >> >> Try the age old software fix: reinstall. >> >> Cheers >> >> Tom >> > > > > From kent37 at tds.net Mon Aug 14 13:52:44 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Aug 2006 07:52:44 -0400 Subject: [Tutor] i18n Encoding/Decoding issues In-Reply-To: References: Message-ID: <44E0640C.4060904@tds.net> Jorge De Castro wrote: > Hi all, > > It seems I can't get rid of my continuous issues i18n with Python :( > You're not alone :-) > I've been through: > http://docs.python.org/lib/module-email.Header.html > and > http://www.reportlab.com/i18n/python_unicode_tutorial.html > to no avail. > Try these: http://www.joelonsoftware.com/articles/Unicode.html http://jorendorff.com/articles/unicode/index.html > Basically, I'm receiving and processing mail that comes with content (from > an utf-8 accepting form) from many locales (France, Germany, etc) > > def splitMessage() does what the name indicates, and send message is the > code below. > > def sendMessage(text): > to, From, subject, body = splitMessage(text) > msg = MIMEText(decodeChars(body), 'plain', 'UTF-8') > msg['From'] = From > msg['To'] = to > msg['Subject'] = Header(decodeChars(subject), 'UTF-8') > > def decodeChars(str=""): > if not str: return None > for characterCode in _characterCodes.keys(): > str = str.replace(characterCode, _characterCodes[characterCode]) > return str > > Now as you have noticed, this only works, ie, I get an email sent with the > i18n characters displayed correctly, after I pretty much wrote my own > 'urldecode' map > > _characterCodes ={ "%80" : "�", "%82" : "�", "%83" : > "�", "%84" : "�", \ > "%85" : "�", "%86" : "�", "%87" : > "�", "%88" : "�", \ > "%89" : "�", "%8A" : "�", "%8B" : > "�", "%8C" : "�", \ > "%8E" : "�", "%91" : "�", "%92" : > "�", "%93" : "�", \ > "%94" : "�", "%95" : "�", "%96" : > "�", "%97" : "�", \ > ... > > Which feels like an horrible kludge. > This _characterCodes map replaces chars is the range 80-9F with a Unicode "undefined" marker, so I don't understand how using it gives you a correct result. > Note that using urlilib.unquote doesn't do it -I get an error saying that it > is unable to . Replacing my decodeChars > > msg = MIMEText(urllib.unquote(body), 'plain', 'UTF-8') > > Returns content with i18n characters mangled. > From the selection of characters you have chosen to replace, my guess is that your source data is urlencoded Cp1252, not urlencoded UTF-8. So when you unquote it and then call it UTF-8, which is what the above code does, you get incorrect display. What happens if you change UTF-8 to Cp1252 in the call to MIMEText? > Using unicode(body, 'latin-1').encode('utf-8') doesn't work either. Besides, > am I the only one to feel that if I want to encode something in UTF-8 it > doesn't feel intuitive to have to convert to latin-1 first and then encode? > It doesn't work because the urlencoded text is ascii, not latin-1. I suspect that unicode(urllib.unquote(body), 'Cp12521).decode('UTF-8') would give you what you want. > Any ideas? I am dry on other option and really don't want to keep my kludge > (unless I absolutely have to) > Post some of your actual data, it will be obvious whether it is encoded from Cp1252 or UTF-8. Keep trying, it's worth it to actually understand what is going on. Trying to solve encoding problems when you don't understand the basic issues is unlikely to give a good solution. Kent From kent37 at tds.net Mon Aug 14 14:00:53 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Aug 2006 08:00:53 -0400 Subject: [Tutor] how to remove html ags In-Reply-To: <20060812091431.74868.qmail@web55905.mail.re3.yahoo.com> References: <20060812091431.74868.qmail@web55905.mail.re3.yahoo.com> Message-ID: <44E065F5.3090209@tds.net> anil maran wrote: >

Human nature is not a machin... > > > for example in the above stirng > > i want to remove

> and

Try one of these: http://www.oluyede.org/blog/2006/02/13/html-stripper/ http://www.aminus.org/rbre/python/cleanhtml.py > > i tried > > str = str.replace('(.*)','') > > it doesnt work because it looks for a literal "(.*)" in the string and replaces it with an empty string. Since "(.*)" doesn't appear, nothing is replaced. Kent > thanks > > ------------------------------------------------------------------------ > Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great > rates starting at 1?/min. > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Aug 14 14:11:15 2006 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Aug 2006 08:11:15 -0400 Subject: [Tutor] SGMLLib, fetching some weird data In-Reply-To: <44DDBB52.5080906@yandex.ru> References: <44DDBB52.5080906@yandex.ru> Message-ID: <44E06863.4040201@tds.net> Basil Shubin wrote: > Hi friends, > > Please, examine attached script. I want fetch some data from online > resource and almost achieve this, but I can't fetch some weird formatted > data like this '45? Reverse Calf Press'. I got the following error: > > 45 > Reverse Calf Press > Reverse Calf Raise > Seated Reverse Calf Press > Traceback (most recent call last): > File "net_exrx.py", line 226, in ? > exercisesList = LoadExercisesList(2, 4, 9) > File "net_exrx.py", line 86, in LoadExercisesList > return parser.GetExercisesList() > File "net_exrx.py", line 176, in GetExercisesList > self.exerList.append([self.desc[i],self.urls[i]]) > IndexError: list index out of range > Apparently self.desc has more entries than self.urls. This would happen if handle_data() is called more than once for an tag. If you put some print statements in your program you can probably figure out why this is happening. Kent From matthew.williams at cancer.org.uk Mon Aug 14 16:10:19 2006 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Mon, 14 Aug 2006 15:10:19 +0100 Subject: [Tutor] Regex Message-ID: <44E0844B.7080307@cancer.org.uk> Dear All, I know this has come up loads of times before, but I'm stuck with what should be a simple Regex problem. I'm trying to pull all the definitions from a latex document. these are marked \begin{defn} \end{defn} so I thought I'd write something like this: filename = '/home/acl_home/PhD/CurrentPhD/extensions1_14.8.6.tex' infile = open(filename,'r') def_start = "\\begin\{defn\}" def_end = "\end{defn}" def_start_reg = re.compile(def_start) l = 0 while l < 500: line = infile.readline() #print l, line res = re.search(def_start_reg,line) print l, res l = l+1 but it doesn't return any matches (BTW, I know there's a defn tag in that section). I thought it was my regex matching, but I checked it with an online checker, and also with a small bit of text: def_start = "\\begin\{defn\}" def_start_reg = re.compile(def_start) text = """atom that is grounded. These formulae are useful not only for the work on valuation but are also used in later chapters. \begin{defn} A Patient-ground formula is a formula which contains a grounding of $Patient(x)$. The other atoms in the formula may be either ground or non-ground. \end{defn} Having defined our patient ground formulae, we can now use formulae of this form to define our patient values.""" res = re.search(def_start_reg, text) print res and this returns a MatchObject. I'm not sure why there should be any difference between the two - but I'm sure it's very simple. Thanks for any tips, Matt From rdm at rcblue.com Mon Aug 14 16:35:44 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 14 Aug 2006 07:35:44 -0700 Subject: [Tutor] How to un-import modules? Message-ID: <7.0.1.0.2.20060814072726.05946c20@rcblue.com> Actually, my question is, after using IDLE to do some importing of modules and initializing of variables, how to return it to it's initial condition without closing and reopening it. So, for example after I've done >>> import math, psyco >>> a = 4**23 How can I wipe those out without closing IDLE? (I used to know how, but I've forgotten.) Thanks, Dick Moores rdm at rcblue.com From kermit at polaris.net Mon Aug 14 16:47:06 2006 From: kermit at polaris.net (Kermit Rose) Date: Mon, 14 Aug 2006 10:47:06 -0400 (Eastern Daylight Time) Subject: [Tutor] Global variables References: <44DFDFD5.2080208@gmail.com> Message-ID: <44E08CEA.000001.02432@YOUR-4105E587B6> From: Luke Paireepinart Date: 08/13/06 22:28:50 To: Kermit Rose Cc: Danny Yoo; tutor at python.org Subject: Re: [Tutor] Global variables Kermit Rose wrote: > > > From: Danny Yoo > Date: 08/09/06 16:23:35 > To: Kermit Rose > Cc: tutor at python.org > > > If I can figure out how to make my main function subroutine declare global > variables > then I won't need to pass parameters most parameters to the other > subroutines, > > and will bypass the problem I'm having that sometimes the function strongfac > SOMETIMES does not return the value it has in the subroutine, back to the > calling routine. > From: Luke Paireepinart are you asking a question? Kermit Rose wrote: Yes. How can I make a package of functions declare global variables for passing information between the functions in the package? From arcege at gmail.com Mon Aug 14 17:46:08 2006 From: arcege at gmail.com (Michael P. Reilly) Date: Mon, 14 Aug 2006 11:46:08 -0400 Subject: [Tutor] How to un-import modules? In-Reply-To: <7.0.1.0.2.20060814072726.05946c20@rcblue.com> References: <7.0.1.0.2.20060814072726.05946c20@rcblue.com> Message-ID: <7e5ba9220608140846s47feffb7x8569ee5bfe6be5c6@mail.gmail.com> On 8/14/06, Dick Moores wrote: > > Actually, my question is, after using IDLE to do some importing of > modules and initializing of variables, how to return it to it's > initial condition without closing and reopening it. > > So, for example after I've done > >>> import math, psyco > >>> a = 4**23 > > How can I wipe those out without closing IDLE? > (I used to know how, but I've forgotten.) Hi Dick, Usually this entails removing from the "module registry and removing references to it in the code. If you have a _really_ well used module (like one with config parameters imported into every module), then you'll have an additional step of removing it from every module. Also, if you have use "from psyco import ...", then you will not be able to free up the module and the reference to the module easily (is it from that module, or imported from a third module? see "if paranoid: code below). The function below deletes a module by name from the Python interpreter, the "paranoid" parameter is a list of variable names to remove from every other module (supposedly being deleted with the module). Be VERY careful with the paranoid param; it could cause problems for your interpreter if your functions and classes are named the same in different modules. One common occurrance of this is "error" for exceptions. A lot of libraries have one "catch-all" exception called "error" in the module. If you also named your exception "error" and decided to include that in the paranoid list... there go a lot of other exception objects. def delete_module(modname, paranoid=None): from sys import modules try: thismod = modules[modname] except KeyError: raise ValueError(modname) these_symbols = dir(thismod) if paranoid: try: paranoid[:] # sequence support except: raise ValueError('must supply a finite list for paranoid') else: these_symbols = paranoid[:] del modules[modname] for mod in modules.values(): try: delattr(mod, modname) except AttributeError: pass if paranoid: for symbol in these_symbols: if symbol[:2] == '__': # ignore special symbols continue try: delattr(mod, symbol) except AttributeError: pass Then you should be able to use this like: delete_module('psyco') or delete_module('psyco', ['Psycho', 'KillerError']) # only delete these symbols from every other module (for "from psyco import Psycho, KillerError" statements) -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060814/4709e976/attachment.html From anilmrn at yahoo.com Mon Aug 14 22:27:05 2006 From: anilmrn at yahoo.com (anil maran) Date: Mon, 14 Aug 2006 13:27:05 -0700 (PDT) Subject: [Tutor] how to remove html ags In-Reply-To: <44E065F5.3090209@tds.net> Message-ID: <20060814202705.55898.qmail@web55905.mail.re3.yahoo.com> how to do regular expressions and remove waht is in and also the brackets <> Kent Johnson wrote: anil maran wrote: > Human nature is not a machin... > > > for example in the above stirng > > i want to remove > and Try one of these: http://www.oluyede.org/blog/2006/02/13/html-stripper/ http://www.aminus.org/rbre/python/cleanhtml.py > > i tried > > str = str.replace('(.*)','') > > it doesnt work because it looks for a literal "(.*)" in the string and replaces it with an empty string. Since "(.*)" doesn't appear, nothing is replaced. Kent > thanks > > ------------------------------------------------------------------------ > Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great > rates starting at 1?/min. > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Do you Yahoo!? Get on board. You're invited to try the new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060814/f9b9b230/attachment-0001.htm From rabidpoobear at gmail.com Mon Aug 14 23:17:09 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 14 Aug 2006 16:17:09 -0500 Subject: [Tutor] Global variables In-Reply-To: <44E08CEA.000001.02432@YOUR-4105E587B6> References: <44DFDFD5.2080208@gmail.com> <44E08CEA.000001.02432@YOUR-4105E587B6> Message-ID: <44E0E855.1070007@gmail.com> > From: Luke Paireepinart > > are you asking a question? > > > Kermit Rose wrote: > > > Yes. How can I make a package of functions declare global variables for > passing information between > the functions in the package? > > a 'package' meaning a module? If you think you need global variables you're probably going about the problem the wrong way. What are you trying to do? From rabidpoobear at gmail.com Mon Aug 14 23:19:44 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 14 Aug 2006 16:19:44 -0500 Subject: [Tutor] How to un-import modules? In-Reply-To: <7e5ba9220608140846s47feffb7x8569ee5bfe6be5c6@mail.gmail.com> References: <7.0.1.0.2.20060814072726.05946c20@rcblue.com> <7e5ba9220608140846s47feffb7x8569ee5bfe6be5c6@mail.gmail.com> Message-ID: <44E0E8F0.3070909@gmail.com> Michael P. Reilly wrote: > On 8/14/06, *Dick Moores* > wrote: > > Actually, my question is, after using IDLE to do some importing of > modules and initializing of variables, how to return it to it's > initial condition without closing and reopening it. > > So, for example after I've done > >>> import math, psyco > >>> a = 4**23 > > How can I wipe those out without closing IDLE? > (I used to know how, but I've forgotten.) > while you're in the IDLE shell view, hit Ctrl+F6. it restarts the interpreter. From rabidpoobear at gmail.com Mon Aug 14 23:25:03 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 14 Aug 2006 16:25:03 -0500 Subject: [Tutor] how to remove html ags In-Reply-To: <20060814202705.55898.qmail@web55905.mail.re3.yahoo.com> References: <20060814202705.55898.qmail@web55905.mail.re3.yahoo.com> Message-ID: <44E0EA2F.2050701@gmail.com> anil maran wrote: > how to do regular expressions > and remove waht is in and also the brackets > <> I'm not answering any more of your questions until you read http://www.catb.org/~esr/faqs/smart-questions.html The information you want you could find in any regexp tutorial. If you have a problem learning regular expressions and you need clarification about something, ask us. This list is here to help you learn and understand the Python language, not to generate code for you. :-). -Luke From anilmrn at yahoo.com Tue Aug 15 00:08:27 2006 From: anilmrn at yahoo.com (anil maran) Date: Mon, 14 Aug 2006 15:08:27 -0700 (PDT) Subject: [Tutor] how to remove html ags In-Reply-To: <44E0EA2F.2050701@gmail.com> Message-ID: <20060814220827.52188.qmail@web55904.mail.re3.yahoo.com> hi luke i tried to do this for 2 weeks using the regexps i couldnt find it and hence i was asking you guys thanks anil Luke Paireepinart wrote: anil maran wrote: > how to do regular expressions > and remove waht is in and also the brackets > <> --------------------------------- Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1¢/min. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060814/cc72c305/attachment.html From john at fouhy.net Tue Aug 15 00:15:05 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 15 Aug 2006 10:15:05 +1200 Subject: [Tutor] how to remove html ags In-Reply-To: <20060814220827.52188.qmail@web55904.mail.re3.yahoo.com> References: <44E0EA2F.2050701@gmail.com> <20060814220827.52188.qmail@web55904.mail.re3.yahoo.com> Message-ID: <5e58f2e40608141515l1a67b7d6t85c20a0327e41206@mail.gmail.com> On 15/08/06, anil maran wrote: > hi luke > i tried to do this for 2 weeks using the regexps > i couldnt find it > and hence i was asking you guys > thanks > anil What have you tried? What problems were you having? -- John. From alan.gauld at freenet.co.uk Tue Aug 15 00:32:33 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Aug 2006 23:32:33 +0100 Subject: [Tutor] Regex References: <44E0844B.7080307@cancer.org.uk> Message-ID: <001101c6bff1$897bbfd0$0201a8c0@XPpro> > so I thought I'd write something like this: > > filename = '/home/acl_home/PhD/CurrentPhD/extensions1_14.8.6.tex' > > infile = open(filename,'r') > > def_start = "\\begin\{defn\}" > def_end = "\end{defn}" > > def_start_reg = re.compile(def_start) > > l = 0 > while l < 500: > line = infile.readline() > #print l, line > res = re.search(def_start_reg,line) > print l, res > l = l+1 Use a for loop instead of the while loop. And use the methods of the compiled regex object: for n,line in enumerate(open(filename)): res = def_start_reg.search(line) print n,res Does that work? Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Aug 15 00:40:28 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Aug 2006 23:40:28 +0100 Subject: [Tutor] How to un-import modules? References: <7.0.1.0.2.20060814072726.05946c20@rcblue.com> <7e5ba9220608140846s47feffb7x8569ee5bfe6be5c6@mail.gmail.com> Message-ID: <002b01c6bff2$ac42af00$0201a8c0@XPpro> >> Actually, my question is, after using IDLE to do some importing of >> modules and initializing of variables, how to return it to it's >> initial condition without closing and reopening it. Doesn't Shell->Restart shell do this? Alan G. From alan.gauld at freenet.co.uk Tue Aug 15 00:39:15 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Aug 2006 23:39:15 +0100 Subject: [Tutor] Global variables References: <44DFDFD5.2080208@gmail.com> <44E08CEA.000001.02432@YOUR-4105E587B6> Message-ID: <001701c6bff2$79646010$0201a8c0@XPpro> >> If I can figure out how to make my main function subroutine declare >> global >> variables then I won't need to pass parameters most parameters to >> the other >> subroutines, That may be true but you will make your code much less reusable and much more error propne in the process. There are good reasons why global variables are considered evil... >> and will bypass the problem I'm having that sometimes the function > strongfac SOMETIMES does not return the value it has in the > subroutine, > back to the calling routine. I'm not sure how you work that out. If the function uis getting bad data it will still return it regardless of whether you use golobals or return values. > Yes. How can I make a package of functions declare global > variables for > passing information between the functions in the package? just use the global keyword: ############### x,y = 42,27 def f(): global x,y x = 66 y = 42 print x+y print x,y f() print x,y ############ But its very bad practice and ############## x,y = 42,27 def f(x,y): x = 66 y = 42 print x+y return x,y print x,y x,y = f(x,y) print x,y ########## is much better. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kermit at polaris.net Tue Aug 15 00:51:43 2006 From: kermit at polaris.net (Kermit Rose) Date: Mon, 14 Aug 2006 18:51:43 -0400 (Eastern Daylight Time) Subject: [Tutor] Global variables References: <44E0E855.1070007@gmail.com> Message-ID: <44E0FE7F.00000D.02432@YOUR-4105E587B6> From: Luke Paireepinart Date: 08/14/06 17:17:13 To: Kermit Rose Cc: Danny Yoo; tutor at python.org Subject: Re: [Tutor] Global variables > From: Luke Paireepinart > > are you asking a question? > > > Kermit Rose wrote: > > > Yes. How can I make a package of functions declare global variables for > passing information between > the functions in the package? > > a 'package' meaning a module? **** Yes. I mean a module. >>>>> If you think you need global variables you're probably going about the problem the wrong way. What are you trying to do? ***** In my module I have several functions which work together to factor integers One function, called testrange is the main calling routine. It generates Tables and and passes their values to the main factoring subroutine, named fermat. Fermat calls a routine named strongfac. There seems to be some type of bug in Python because I observe that strongfac, depending on the number being factored, will sometimes return 0 instead of the factors it found. I believe that if I can get my main function, testrange, to declare a global variable to hold the caculated factor list, then I can bypass the apparent bug in Python that actualizes only for a few particular numbers to be factored. Also, if I can get testrange to create global variables, then I can shorten the parameter list of many of the functions in the module. Kermit < kermit at polaris.net > From kermit at polaris.net Tue Aug 15 01:33:16 2006 From: kermit at polaris.net (Kermit Rose) Date: Mon, 14 Aug 2006 19:33:16 -0400 (Eastern Daylight Time) Subject: [Tutor] Global variables References: <001701c6bff2$79646010$0201a8c0@XPpro> Message-ID: <44E1083C.000015.02432@YOUR-4105E587B6> From: Alan Gauld Date: 08/14/06 18:42:41 To: Kermit Rose; Luke Paireepinart Cc: tutor at python.org; Danny Yoo Subject: Re: [Tutor] Global variables That may be true but you will make your code much less reusable and much more error propne in the process. There are good reasons why global variables are considered evil... ***** I know that global variable usage can be abused. But in fact I use the same variable names in the subroutine parameter list as in the calling routine for every function in the module. So I believe that in this case global variables would be useful and not likely to increase errors due to confusion of global and local variables. I would never have a local variable with the same name as the global variable. But in this case, it's only because of an apparent bug in Python that want to bypass that I'm considering the use of global variables. My routine strongfac calculates a value for fac in the subroutine, and the calling routine picks up a different vaalue. An illustration. In strong fac: fac = [1,2,3] print fac return fac in fermat: fac = strongfac(z) print fac prints [0,0,0] And most of the time it does not misbehave like this. It is only occasionally, and consistently with certain numbers to be factored. Kermit < kermit at polaris.net > From john at fouhy.net Tue Aug 15 01:50:47 2006 From: john at fouhy.net (John Fouhy) Date: Tue, 15 Aug 2006 11:50:47 +1200 Subject: [Tutor] Global variables In-Reply-To: <44E1083C.000015.02432@YOUR-4105E587B6> References: <001701c6bff2$79646010$0201a8c0@XPpro> <44E1083C.000015.02432@YOUR-4105E587B6> Message-ID: <5e58f2e40608141650m2a0347d5j581a0847daa806e5@mail.gmail.com> On 15/08/06, Kermit Rose wrote: > My routine strongfac calculates a value for fac in the subroutine, and the > calling routine picks up a different vaalue. > > An illustration. > > In strong fac: > > fac = [1,2,3] > print fac > return fac > > in fermat: > > fac = strongfac(z) > print fac > > prints [0,0,0] > > And most of the time it does not misbehave like this. Can you post actual code to illustrate the problem? Don't post your entire module; just show us the functions involved, the input that causes the problem, and what output you expect to get. -- John. From rabidpoobear at gmail.com Tue Aug 15 02:18:34 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 14 Aug 2006 19:18:34 -0500 Subject: [Tutor] Global variables In-Reply-To: <44E1083C.000015.02432@YOUR-4105E587B6> References: <001701c6bff2$79646010$0201a8c0@XPpro> <44E1083C.000015.02432@YOUR-4105E587B6> Message-ID: <44E112DA.3090502@gmail.com> Kermit Rose wrote: > > > From: Alan Gauld > Date: 08/14/06 18:42:41 > To: Kermit Rose; Luke Paireepinart > Cc: tutor at python.org; Danny Yoo > Subject: Re: [Tutor] Global variables > > > That may be true but you will make your code much less reusable > and much more error propne in the process. There are good reasons > why global variables are considered evil... > > > ***** > > I know that global variable usage can be abused. > > But in fact I use the same variable names in the subroutine parameter list > as in the calling routine for every function in the module. > > So I believe that in this case global variables would be useful and not > likely to > increase errors due to confusion of global and local variables. > > I would never have a local variable with the same name as the global > variable. > > It sounds like you should make a Factoring class and have whichever variables are similar for all functions be variables specific to the class instance (I forgot the word for this) Something like: #---- Class Factoring(object): def __init__(self): self.var1 = ['a','b','c'] self.var2 = 5 self.var3 = (0) def method1(self): print self.var1,self.var2 def method2(self): print self.var2,self.var3 fac = Factoring() fac.method1() fac.method2() #----- the output would be ['a','b','c']5 5(0) Thus you prevent global namespace pollution. > But in this case, it's only because of an apparent bug in Python that want > to > bypass that I'm considering the use of global variables. > You probably shouldn't claim there's a bug in Python unless you're sure (I.E. have a snippet of code that reproduces the bug that you'll share with us) > > > My routine strongfac calculates a value for fac in the subroutine, and the > calling routine picks up a different vaalue. > do you think you could use more conventional terminology like 'function' and such? I don't understand what you mean by the subroutine of the routine. def routine(): def subroutine(): print 'hi' subroutine() Is that what you mean? or by 'subroutine' do you mean 'loop inside of function'? By your terminology, if there's a routine that calls strongfac, doesn't that mean strongfac is a subroutine? which would mean that the value for fac is calculated in the subroutine of the subroutine of the calling routine? > > An illustration. > > In strong fac: > > fac = [1,2,3] > print fac > return fac > > in fermat: > > fac = strongfac(z) > print fac > > prints [0,0,0] > what is 'z'? a random parameter? can you give us a cut-down version of your code that just reproduces this erratic behavior you're having a problem with? > > And most of the time it does not misbehave like this. > if random.randint(0,5) < 3: malfunction() > > It is only occasionally, and consistently with certain numbers to be > factored. > so with certain numbers it always occurs, with other numbers it sometimes occurs? > > > Kermit < kermit at polaris.net > > > Luke From bgailer at alum.rpi.edu Tue Aug 15 02:24:06 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 14 Aug 2006 17:24:06 -0700 Subject: [Tutor] Global variables Message-ID: <44E11426.2060700@alum.rpi.edu> A while back you attached factor34.py. Is that the program you are having trouble with? And you said it misbehaves "consistently with certain numbers to be factored." What are these numbers? -- Bob Gailer 510-978-4454 From dianahawks at optusnet.com.au Tue Aug 15 03:19:35 2006 From: dianahawks at optusnet.com.au (Diana Hawksworth) Date: Tue, 15 Aug 2006 11:19:35 +1000 Subject: [Tutor] Python on network problems Message-ID: <200608150119.k7F1JZ9O022639@mail31.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20060815/56d4318a/attachment.asc From jim at well.com Tue Aug 15 04:11:31 2006 From: jim at well.com (jim stockford) Date: Mon, 14 Aug 2006 19:11:31 -0700 Subject: [Tutor] What does import really do? Message-ID: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com> For example, import os import sys My take is that one uses the import keyword in a program. The Python interpreter reads the program and generates machine code. The import keyword directs the Python interpreter to find some library (which is not necessarily named, certainly not necessarily named in the import statement), get some portion of machine code from the library, bind that machine code in current program's process space, and integrate the names of the imported machine code with the program's namespace (probably keeping the namespace of the imported code as a separate name domain). I'm just guessing, of course. Can anyone explain what is really going on under the hood? I'll be grateful for a description of the behavior. newbie From reed at intersiege.com Tue Aug 15 04:44:11 2006 From: reed at intersiege.com (Reed L. O'Brien) Date: Mon, 14 Aug 2006 22:44:11 -0400 Subject: [Tutor] processing multi entry logs Message-ID: <0A65F8F9-3545-46C4-BD93-64DF92383351@intersiege.com> I have a log file. Essentially the file has 2 important entries for each process id. One when the process starts with an id and a another piece of data. the second is when the process finishes, with the result also with the process id. I need to get data from both to make a sensible representation of the data. The file can be very large, in excess of 400MB. And the process id entries can be any random distance apart. I am hoping for input regarding the best way to do it. I can't think of an efficient way to store the data from the first entry. Keep processing line by line and check against the partially recorded ids? Maintain seperate lists and merge them at the end? Ideas and input appreciated? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060814/feb81961/attachment.html From rabidpoobear at gmail.com Tue Aug 15 04:52:19 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 14 Aug 2006 21:52:19 -0500 Subject: [Tutor] What does import really do? In-Reply-To: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com> References: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com> Message-ID: <44E136E3.1020307@gmail.com> jim stockford wrote: Hi Jim. > For example, > import os > import sys > > My take is that one uses the import keyword in a > program. > The Python interpreter reads the program and > generates machine code. > The import keyword directs the Python interpreter > to find some library (which is not necessarily named, > certainly not necessarily named in the import > statement), get some portion of machine code from > the library, bind that machine code in current > program's process space, and integrate the names > of the imported machine code with the program's > namespace (probably keeping the namespace of > the imported code as a separate name domain). > I don't know when code is converted to machine code, but here's how I think import works. you say 'find some library ... not necessarily named in the import statement.' I don't know what you mean by this. If the user says 'import os' first python checks for 'os.pyc' in the current working directory. if it doesn't find this, it looks if 'os.py' is there. If not, then it checks the PYTHONPATH (I believe) for 'os.pyc' and 'os.py' files. When the user says 'import x' the name of the actual filename will be x.pyc or x.py for example: #---- config.py in C:/exprog a = 'hi' b = 'hello' #---- #---- main.py in C:/exprog import config print config.a print config.b #---- when I run main.py for the first time, it looks for 'config.pyc' because of the 'import config' line. It doesn't find it, so it compiles 'config.py' into 'config.pyc' and then imports it. Note that it's not in the global namespace unless I say 'from config import *' instead, you have to reference values stored in the 'config' module using the 'config. ' syntax. if I were to delete config.py and config.pyc, it would look in C:/python24/Lib/site-packages/ for a 'config.py' and 'config.pyc' because that's where my python is installed. At least that's how I think import works :) > I'm just guessing, of course. Can anyone explain > what is really going on under the hood? I'll be > grateful for a description of the behavior. > > newbie > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From rabidpoobear at gmail.com Tue Aug 15 05:02:37 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 14 Aug 2006 22:02:37 -0500 Subject: [Tutor] processing multi entry logs In-Reply-To: <0A65F8F9-3545-46C4-BD93-64DF92383351@intersiege.com> References: <0A65F8F9-3545-46C4-BD93-64DF92383351@intersiege.com> Message-ID: <44E1394D.4000702@gmail.com> Reed L. O'Brien wrote: > I have a log file. Essentially the file has 2 important entries for > each process id. One when the process starts with an id and a another > piece of data. the second is when the process finishes, with the > result also with the process id. I need to get data from both to make > a sensible representation of the data. The file can be very large, in > excess of 400MB. And the process id entries can be any random distance > apart. > Are you in control of the format of the log file? Is it possible that, in the future, you could instead log everything in an SQL table or something of the sort to make it easier to get at the data you want? I understand that now you have a log that you need to parse, but if every time you need something from the log you have to parse 400MB of text it might take a little longer than you'd like. > I am hoping for input regarding the best way to do it. > > I can't think of an efficient way to store the data from the first entry. > > Keep processing line by line and check against the partially recorded ids? > > > Maintain seperate lists and merge them at the end? You could do something like (in semi-python) tasks = {} for item in logfile.readlines(): if item is start_data: tasks[process_id] = [start_data-process_id] elif item is end_data: tasks[process_id].append(end_data-process_id) This should work because you said the process_id is common to both the startdata and enddata. The only problem is determining if the entry is start or end data. Now you have a dictionary where the keywords are the processids and the data is a two-element list. Does that do what you need? HTH, -Luke From jim at well.com Tue Aug 15 05:11:28 2006 From: jim at well.com (jim stockford) Date: Mon, 14 Aug 2006 20:11:28 -0700 Subject: [Tutor] What does import really do? In-Reply-To: <44E136E3.1020307@gmail.com> References: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com> <44E136E3.1020307@gmail.com> Message-ID: many thanks. wrt import and what's named, in the case of the PIL library, the import statement can be import Image # not import PIL my presumption is that the PIL whatever-it-is contains a set of whatever-they-are, one of which is named Image. I like to use proper terminology, by way of explaining my avoidance above. Might help to know I very much liked working in assembler and infer possible assembler correspondences when I wonder about code behavior. Your rundown of search order is helpful. more thanks. jim On Aug 14, 2006, at 7:52 PM, Luke Paireepinart wrote: > jim stockford wrote: > Hi Jim. >> For example, >> import os >> import sys >> >> My take is that one uses the import keyword in a >> program. >> The Python interpreter reads the program and >> generates machine code. >> The import keyword directs the Python interpreter >> to find some library (which is not necessarily named, >> certainly not necessarily named in the import >> statement), get some portion of machine code from >> the library, bind that machine code in current >> program's process space, and integrate the names >> of the imported machine code with the program's >> namespace (probably keeping the namespace of >> the imported code as a separate name domain). >> > I don't know when code is converted to machine code, but here's how I > think > import works. > you say 'find some library ... not necessarily named in the import > statement.' > I don't know what you mean by this. > If the user says 'import os' > first python checks for > 'os.pyc' in the current working directory. > if it doesn't find this, it looks if 'os.py' is there. > If not, then it checks the PYTHONPATH (I believe) > for 'os.pyc' and 'os.py' files. > > When the user says 'import x' the name of the > actual filename will be x.pyc or x.py > for example: > > #---- config.py in C:/exprog > a = 'hi' > b = 'hello' > #---- > > #---- main.py in C:/exprog > import config > print config.a > print config.b > #---- > > when I run main.py for the first time, it looks for > 'config.pyc' because of the 'import config' line. > It doesn't find it, so it compiles 'config.py' into 'config.pyc' > and then imports it. Note that it's not in the global namespace > unless I say 'from config import *' > instead, you have to reference values stored in the 'config' module > using the 'config. ' syntax. > > if I were to delete config.py and config.pyc, it would look in > C:/python24/Lib/site-packages/ for a 'config.py' and 'config.pyc' > because that's where my python is installed. > > At least that's how I think import works :) >> I'm just guessing, of course. Can anyone explain >> what is really going on under the hood? I'll be >> grateful for a description of the behavior. >> >> newbie >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > From cspears2002 at yahoo.com Tue Aug 15 08:42:37 2006 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 14 Aug 2006 23:42:37 -0700 (PDT) Subject: [Tutor] more rps Message-ID: <20060815064237.80516.qmail@web51614.mail.yahoo.com> Here is the latest version of my Rock, Paper, Scissors game: #!/usr/bin/python import random random.seed() class Human: def __init__(self): self.points = 0 self.choice = " " def plays(self): fromUser = raw_input("Pick (R)ock, (P)aper, or (S)cissors! ") translate = {'r':'rock', 's':'scissors', 'p':'paper'} try: self.choice = translate[fromUser.lower()] except KeyError: print 'Invalid Response' class Computer: def __init__(self): self.points = 0 self.choice = " " def plays(self): comp_choice = random.randint(0,2) if comp_choice == 0: self.choice = 'rock' elif comp_choice == 1: self.choice = 'paper' else: self.choice = 'scissors' def compare_objects(human, computer): print "Human picked ", human.choice print "Computer picked", computer.choice results = { 'rock' : {'rock' : 'draw', 'paper': 0, 'scissors': 1}, 'paper' : {'rock' : 1, 'paper': 'draw', 'scissors': 0}, 'scissors' : {'rock' : 0, 'paper' : 1, 'scissors' : 'draw'} } outcome = results[human.choice][computer.choice] if outcome == 0: print "Computer Wins!" computer.points = computer.points + 1 elif outcome == 1: print "Human Wins!" human.points = human.points + 1 else: print "Draw!" if __name__ == "__main__": print "Welcome to Rock, Paper, Scissors!" final_points = raw_input("Play to how many points? ") human = Human() computer = Computer() while (human.points < final_points or computer.points < final_points): human.plays() computer.plays() compare_objects(human, computer) print "Score:\tHuman: ",human.points,"\tComputer: ",computer.points print "Game Over!" I actually figured out how to build the 2x2 matrix. I'm quite proud of this. Like all of my good ideas, the answer came to me in the shower. :-) Unfortunately, my while loop doesn't seem to be working. I've played around with it with no success. Hints, anyone? From rdm at rcblue.com Tue Aug 15 08:58:58 2006 From: rdm at rcblue.com (Dick Moores) Date: Mon, 14 Aug 2006 23:58:58 -0700 Subject: [Tutor] How to un-import modules? In-Reply-To: <44E0E8F0.3070909@gmail.com> References: <7.0.1.0.2.20060814072726.05946c20@rcblue.com> <7e5ba9220608140846s47feffb7x8569ee5bfe6be5c6@mail.gmail.com> <44E0E8F0.3070909@gmail.com> Message-ID: <7.0.1.0.2.20060814235628.05a68540@rcblue.com> At 02:19 PM 8/14/2006, you wrote: >Michael P. Reilly wrote: >>On 8/14/06, *Dick Moores* > wrote: >> >> Actually, my question is, after using IDLE to do some importing of >> modules and initializing of variables, how to return it to it's >> initial condition without closing and reopening it. >> >> So, for example after I've done >> >>> import math, psyco >> >>> a = 4**23 >> >> How can I wipe those out without closing IDLE? >> (I used to know how, but I've forgotten.) >while you're in the IDLE shell view, hit Ctrl+F6. it restarts the >interpreter. Yes! That's it. Or Shell->Restart. I should have poked around in IDLE and found this myself. Thanks! Dick Moores rdm at rcblue.com From kraus at hagen-partner.de Tue Aug 15 09:01:57 2006 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Tue, 15 Aug 2006 09:01:57 +0200 Subject: [Tutor] more rps In-Reply-To: <20060815064237.80516.qmail@web51614.mail.yahoo.com> References: <20060815064237.80516.qmail@web51614.mail.yahoo.com> Message-ID: On 15.08.2006 08:42, Christopher Spears wrote: > Here is the latest version of my Rock, Paper, Scissors > game: > > #!/usr/bin/python > > import random > random.seed() > > class Human: > def __init__(self): > self.points = 0 > self.choice = " " > > def plays(self): > fromUser = raw_input("Pick (R)ock, (P)aper, or > (S)cissors! ") > translate = {'r':'rock', 's':'scissors', > 'p':'paper'} > try: > self.choice = translate[fromUser.lower()] > except KeyError: > print 'Invalid Response' > > class Computer: > def __init__(self): > self.points = 0 > self.choice = " " > > def plays(self): > comp_choice = random.randint(0,2) > if comp_choice == 0: > self.choice = 'rock' > elif comp_choice == 1: > self.choice = 'paper' > else: > self.choice = 'scissors' > > def compare_objects(human, computer): > print "Human picked ", human.choice > print "Computer picked", computer.choice > results = { 'rock' : {'rock' : 'draw', 'paper': 0, > 'scissors': 1}, > 'paper' : {'rock' : 1, 'paper': 'draw', 'scissors': > 0}, > 'scissors' : {'rock' : 0, 'paper' : 1, 'scissors' : > 'draw'} > } > > outcome = results[human.choice][computer.choice] > if outcome == 0: > print "Computer Wins!" > computer.points = computer.points + 1 > elif outcome == 1: > print "Human Wins!" > human.points = human.points + 1 > else: > print "Draw!" > > > if __name__ == "__main__": > print "Welcome to Rock, Paper, Scissors!" > final_points = raw_input("Play to how many points? ") > human = Human() > computer = Computer() > while (human.points < final_points or computer.points > < final_points): > human.plays() > computer.plays() > compare_objects(human, computer) > print "Score:\tHuman: ",human.points,"\tComputer: > ",computer.points > print "Game Over!" > > > I actually figured out how to build the 2x2 matrix. > I'm quite proud of this. Like all of my good ideas, > the answer came to me in the shower. :-) > > Unfortunately, my while loop doesn't seem to be > working. I've played around with it with no success. > Hints, anyone? > Look at the type of human.points and final_points: >>> final_points = raw_input("Play to how many points? ") Play to how many points? 10 >>> type(final_points) >>> 1 < final_points True >>> 100 < final_points True >>> 1000 < final_points True HTH, Wolfram From alan.gauld at freenet.co.uk Tue Aug 15 09:37:05 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 15 Aug 2006 08:37:05 +0100 Subject: [Tutor] Global variables References: <001701c6bff2$79646010$0201a8c0@XPpro> <44E1083C.000015.02432@YOUR-4105E587B6> Message-ID: <000301c6c03d$9b8cc5b0$0201a8c0@XPpro> > That may be true but you will make your code much less reusable > and much more error propne in the process. There are good reasons > why global variables are considered evil... > > But in fact I use the same variable names in the subroutine > parameter list > as in the calling routine for every function in the module. The names have very little to do with it, the danger of global variable use is the reliance on side-effects and the tight coupling that you introduce between the calling module and the called module. Changes to the state of the calling module in an unpredictable manner lead to subtle bugs which are extremely hard to see and fix. > increase errors due to confusion of global and local variables. Confusion of names is of very little import, that really isn't the issue. > I would never have a local variable with the same name as the global > variable. Again thats not a problem. > But in this case, it's only because of an apparent bug in Python > that want > to bypass that I'm considering the use of global variables. I'd be very very doubtful that its a bug in Python. Python is very well tested and while occasionally bugs do surface, the type of bug you are describing is extremely unl;ikely to have remained hidden. It is far more likely to be an error in the code or in the data. > My routine strongfac calculates a value for fac in the subroutine, > and the > calling routine picks up a different vaalue. > > An illustration. > > In strong fac: > > fac = [1,2,3] > print fac > return fac > > in fermat: > > fac = strongfac(z) > print fac > > prints [0,0,0] > > And most of the time it does not misbehave like this. > > It is only occasionally, and consistently with certain numbers to be > factored. All of which points to an error in the code not in Python. The way Python is written it is virtually never going to result in that kind of error dependant on data values. That might happen is if the values are very close to zero and a type conversion occurs, but otherwise I'm very dubious about a Python bug of that type. Alan G. From alan.gauld at freenet.co.uk Tue Aug 15 09:46:02 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 15 Aug 2006 08:46:02 +0100 Subject: [Tutor] Python on network problems References: <200608150119.k7F1JZ9O022639@mail31.syd.optusnet.com.au> Message-ID: <000701c6c03e$dbac5f10$0201a8c0@XPpro> Thanks Diana, > We are running Windows XP. The students log in to a > network server that allows them access to their user > accounts as well as various group folders. > We have 4 rooms full of computers - but Python is installed > on each workstation in this room only .... It is not on the network > and no other computer rooms have access to it. That's much clearer. > Two failures have occurred. > > The first has been intermittent and to individual students > only at rare times. A student will attempt to start IDLE > - and nothing will happen. That could be a local machine/user setup issue. Given the various issues with IDLE and firewalls I might look at the firewall settings on the Python PCs and make sure IDLE is happy with them. > The 2nd is more pervasive, and that is, whenever I have > the class working with Python - the entire school network > becomes inoperable, That is bizarre. And very unlikely to be Python since they are running it frpom their local machine! The only slight possibility is if any of the students are writing code that accesses a networked folder, to open a file say, and is causing some high volume network traffic. Can you check if any of the students are using network paths for file access in their code? Even this shouldn't crash the network, but it can occasionally give rise to problems - although I've never seen it from Python... > Now I am inclined to think it is not a Python problem at all. Me too, but coincidences shouldn't be dismissed lightly. > What I would like to know is if anyone else has had > a similar problem Not with python. Alan G. From alan.gauld at freenet.co.uk Tue Aug 15 09:58:08 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 15 Aug 2006 08:58:08 +0100 Subject: [Tutor] processing multi entry logs References: <0A65F8F9-3545-46C4-BD93-64DF92383351@intersiege.com> Message-ID: <005101c6c040$8c7efbd0$0201a8c0@XPpro> >I have a log file. Essentially the file has 2 important entries for > each process id. One when the process starts with an id and a > another > piece of data. the second is when the process finishes, with the > result also with the process id. > I can't think of an efficient way to store the data from the first > entry. This sounds like a job for a dictionary based on process Id. You can store a tuple of start/stop times and key it by pid. In pseudo code: for line in logfile: pid,event,time = parseData(line) if event == start processes[pid] = [time,0] elif event == stop: processes[pid][1] = time That throws all other events away and leaves you a dictionary holding start and stop times per process id. > Keep processing line by line and check against the partially > recorded > ids? Thats what I've done yes. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Aug 15 18:49:07 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 15 Aug 2006 17:49:07 +0100 Subject: [Tutor] more rps References: <20060815064237.80516.qmail@web51614.mail.yahoo.com> Message-ID: <001f01c6c08a$b9feef30$0201a8c0@XPpro> Let me start by saying that your code is pretty much OK as is. Indeed even using clssses for an RPS game is probably overkill to some extent. What follows should be seen more as some ideas for experimentation and building towards a more flexible/expandable architecture for future projects. Its really about introducing some alternative approaches and increasing consistency. It is definitely not "better" - and indeed could definitely be improved in several ways. > class Human: > def __init__(self): > self.points = 0 > self.choice = " " > > def plays(self): > fromUser = raw_input("Pick (R)ock, (P)aper, or > (S)cissors! ") > translate = {'r':'rock', 's':'scissors', > 'p':'paper'} > try: > self.choice = translate[fromUser.lower()] > except KeyError: > print 'Invalid Response' > > class Computer: > def __init__(self): > self.points = 0 > self.choice = " " > > def plays(self): > comp_choice = random.randint(0,2) > if comp_choice == 0: > self.choice = 'rock' > elif comp_choice == 1: > self.choice = 'paper' > else: > self.choice = 'scissors' While its of little real advantage for this program I'd be tempted to introduce a Player superclass to avoid code duplication. The protocol of both classes here is the same and they both pass the "is-a" test for inheritance - ie. they are both Players. class Player: def __init__(self): self.points = 0 self.choice = " " def getChoice(self): pass # implemented in subclass def plays(self): choice = self.getChoice() if choice == 0: self.choice = 'rock' elif choice == 1: self.choice = 'paper' else: self.choice = 'scissors' Notice I put the plays function in the Player class. By unifying the representation of choice we can use that function for both and just implement a relatively simple getChoice method in each subclass and we are done... (In fact we could simplify still further by storing the choice in its numeric form and using a class level dictionary to translate that to a string for printing - although in fact you never print what the choices were - maybe you should?) class Human(Player): def getChoice(self): choice = raw_input('Choice - rps: ').lower() if choice in 'rps': return {'r':0,'p':1,'s':2}[choice] else: raise ValueError class Computer(Player): def getChoice(self): return randrange(0,3) > > def compare_objects(human, computer): > print "Human picked ", human.choice > print "Computer picked", computer.choice > results = { 'rock' : {'rock' : 'draw', 'paper': 0, > 'scissors': 1}, > 'paper' : {'rock' : 1, 'paper': 'draw', 'scissors': > 0}, > 'scissors' : {'rock' : 0, 'paper' : 1, 'scissors' : > 'draw'} > } > > outcome = results[human.choice][computer.choice] > if outcome == 0: > print "Computer Wins!" > computer.points = computer.points + 1 > elif outcome == 1: > print "Human Wins!" > human.points = human.points + 1 > else: > print "Draw!" By using the number format of storage and the dictionary in the class you can simplify that as in show below using lists. > I actually figured out how to build the 2x2 matrix. > I'm quite proud of this. A nested dictionary is one way. Another is to use numbers to represent the choices and outcomes and create a nested list structure nested list rps = {0:'Rock',1:'Paper',2:'Scissors'} draw,loss,win = 0,1,2 outcomes = [ [0,1,2], [2,0,1], [1,2,0] ] computer = randrange(0,3) human = randrange(0,3) result = outcomes[computer][human] if result == draw: print 'Draw' elif result == loss: print 'Computer lost with', rps[computer] elif result == win: print 'Computer won with', rps[computer] The dictionary is more verbose but does have more readable code. I hope somebody finds at least some of that interesting! :-) I guess what I'm really trying to show is how choosing different data structures makes a big difference to how the code looks. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060815/d33a8c99/attachment.html From sfhaley at gmail.com Tue Aug 15 19:07:11 2006 From: sfhaley at gmail.com (Steve Haley) Date: Tue, 15 Aug 2006 13:07:11 -0400 Subject: [Tutor] The In Operator In-Reply-To: <44C897DD.7040606@tds.net> References: <44C897DD.7040606@tds.net> Message-ID: Hi all, I didn't forget about this - I got involved with some other things, was away for a little while, etc. Thanks for the help. I have tried statements that version 2.1 understands and the "in operator" (so to speak in ver. 21) works fine. As far as downloading a more recent version, I looked briefly at some of the exchanges on the ESRI site and decided it looked a little tricky at best. I think I might wait for ArcView 9.2 and see what it ships with. Thanks again, Steve On 7/27/06, Kent Johnson wrote: > > Steve Haley wrote: > > Finally, my version of 2.1 came bundled with other software (ESRI > > ArcView). Is anyone out there an ESRI user who can tell me if I can I > > go ahead and download a newer version without messing up my ArcView > > installation? > Google is your friend: > http://forums.esri.com/Thread.asp?c=93&f=1729&t=157014&mc=43 > > http://support.esri.com/index.cfm?fa=knowledgebase.techarticles.articleShow&d=26872 > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060815/cb44f590/attachment.htm From Barry.Carroll at psc.com Tue Aug 15 20:21:00 2006 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 15 Aug 2006 11:21:00 -0700 Subject: [Tutor] Python on network problems Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3702@eugsrv400.psc.pscnet.com> Hello, Diana, I have had a little experience with networking problems. Here's my take on your situation. Regards, > Date: Tue, 15 Aug 2006 11:19:35 +1000 > From: Diana Hawksworth > Subject: Re: [Tutor] Python on network problems > To: Alan Gauld > Cc: tutor at python.org > Message-ID: <200608150119.k7F1JZ9O022639 at mail31.syd.optusnet.com.au> > Content-Type: text/plain > <> > > We are running Windows XP. The students log in to a network server that > allows them access to their user accounts as well as various group > folders. We have 4 rooms full of computers - but Python is installed on > each workstation in this room only ie, it is "active" in this room only. > It is not on the network and no other computer rooms have access to it. > The students in this room save their Python files to a networked "user" > account - as they do with all their other files. > >From your description, I gather that a single computer provides authentication service and file service to the entire network. Is this correct? If so, that machine is a single point of failure in your network. If it hangs for any reason, the entire network "goes away". > Two failures have occurred. > > The first has been intermittent and to individual students only at rare > times. A student will attempt to start IDLE - and nothing will happen. > Sometimes, changing that student's log in user name will solve the > problem, and he then has access to Python again. > I don't haven't used IDLE that much, so Alan's ideas are more reliable than mine here: >> That could be a local machine/user setup issue. >> Given the various issues with IDLE and firewalls I might >> look at the firewall settings on the Python PCs and make >> sure IDLE is happy with them. > The 2nd is more pervasive, and that is, whenever I have the class working > with Python - the entire school network becomes inoperable, and the system > administrator needs to reboot it again. Because we have been working on > Python each time this has happened, Python is being blamed for the system > failure. Inoperable - no one is able to open any files in any program, > save any work they have been working on, open files - or even log in if > they haven't already. The whole system is " frozen", from the office to > every other computer in the school. > Now I am inclined to think it is not a Python problem at all. Python is > locally and individually installed on computers in this room only. It has > no network access at all - apart from files being saved in networked user > accounts. > >> The only slight possibility is if any of the students are >> writing code that accesses a networked folder, to open >> a file say, and is causing some high volume network traffic. I think Alan is right here, too, and here's why. (Python internals gurus, please correct any bad assumptions in the following.) Lab #4 is full of users running Python programs. The interpreter is running on each local machine, but the program (and data) files are all stored on the lone network file server. Since Python programs are executed by the interpreter, they access file storage more heavily that compiled programs do. So, every time any of the (15, 20, 25?) computers in the Python lab needs a file, or needs to save a file, it sends a request to that one computer. The potential bottleneck is obvious. I think the network server's capacity is being exceeded in some way. When this happens, instead of degrading service gracefully (e.g. rejecting a request and instructing the client to try again later) the server is getting lost somehow and hanging, causing the failure modes you describe. Here are some areas for your network administrator to investigate: * maximum number of concurrent disk access requests, * maximum number of open files, * file server disk usage, * file server disk fragmentation, * server processor utilization, * network bandwidth utilization, * other limits imposed by the networking software or the server's hardware. > What I would like to know is if anyone else has had a similar problem - > and it has been proven that Python is the cause? If so - how was the > problem solved? > The best solution (IMHO) is also the most expensive: add a redundant server to your network. This would eliminate the single point of failure weakness and reduce the load per server. Also, is one server should hang or fail for any other reason, the duplicate server can keep the network running while the failed machine is rebooted, repaired, etc. If possible, I would recommend using a Unix clone as your server's OS instead of Windows. Even Linux, which is available free of charge, provides a more stable platform for a network server than does Windows. This is relatively easy, especially if your network is based on TCP/IP. Many Windows intranets use Unix/Linux servers. The biggest obstacle, in many cases, is the learning curve required of the network administrator. > Be grateful for any advice - and hope I have made the situation clearer > now. > > Diana > HTH Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From rabidpoobear at gmail.com Tue Aug 15 20:58:03 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 15 Aug 2006 13:58:03 -0500 Subject: [Tutor] more rps In-Reply-To: <001f01c6c08a$b9feef30$0201a8c0@XPpro> References: <20060815064237.80516.qmail@web51614.mail.yahoo.com> <001f01c6c08a$b9feef30$0201a8c0@XPpro> Message-ID: <44E2193B.8010001@gmail.com> [snip] > > class Computer: > > def __init__(self): > > self.points = 0 > > self.choice = " " > > > > def plays(self): > > comp_choice = random.randint(0,2) > > if comp_choice == 0: > > self.choice = 'rock' > > elif comp_choice == 1: > > self.choice = 'paper' > > else: > > self.choice = 'scissors' this could be shortened to 'comp_choice = random.choice(['rock','paper','scissors'])' From alan.gauld at freenet.co.uk Tue Aug 15 22:03:23 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 15 Aug 2006 21:03:23 +0100 Subject: [Tutor] Python on network problems References: <2BBAEE949D384D40A2B851287ADB6A432C3702@eugsrv400.psc.pscnet.com> Message-ID: <001c01c6c0a5$dd692470$0201a8c0@XPpro> > If possible, I would recommend using a Unix clone as your > server's OS instead of Windows. Even Linux, Speaking personally I can't complain about Windows as a server since windows 2000. NT was horrible but Win2K seems to do a fair job. BUT it does need to be set up correctly and running XP Home doesn't count! It is terrible as a server. However given the number of machines in your network I'd expect the basics to bbe catered for. The borttleneck issue that Barry alludes to is one I hadn't even considered but its valid. If the students are all writing code for a similar example and that cpde imports lots of modules which are stored on shared disk on a single server then it could throttle the network. Similarly if they are all accessing a single database or web server stored on the main server - that'd be a pretty bad network setup however! > the learning curve required of the network administrator. And thats pretty massive. Many Windows admins can't work without the GUI tools and Linux really needs command line skills to get the best out of it. Even editing a text file is intimidating for some of these guys! Alan G. From bgailer at alum.rpi.edu Tue Aug 15 22:43:46 2006 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 15 Aug 2006 13:43:46 -0700 Subject: [Tutor] more rps In-Reply-To: <001f01c6c08a$b9feef30$0201a8c0@XPpro> References: <20060815064237.80516.qmail@web51614.mail.yahoo.com> <001f01c6c08a$b9feef30$0201a8c0@XPpro> Message-ID: <44E23202.1070108@alum.rpi.edu> FWIF Here's my "minimalist" version: # rock paper scissors import random media = ('rock', 'paper', 'scissors') outcome = ('tie', 'human', 'computer') winner = ((0,2,1), (1,0,2), (1,2,0)) print 'Human Computer Winner' while 1: h = "rpsvq".find(raw_input('Rock Paper Scissors Verify Quit').lower()) if h == -1: print "Don't recognize " + x elif h == 4: break elif h == 3: # print table of all combinations to verify the winner matrix for r in [(media[h], media[c], outcome[winner[h][c]]) for h in range(3) for c in range(3)]: print '%10s%10s%10s' % r else: c = random.randint(0,2) print '%10s%10s%10s' % (media[h], media[c], outcome[winner[h][c]]) -- Bob Gailer 510-978-4454 From dianahawks at optusnet.com.au Wed Aug 16 00:41:17 2006 From: dianahawks at optusnet.com.au (Diana Hawksworth) Date: Wed, 16 Aug 2006 08:41:17 +1000 Subject: [Tutor] Python on network problems Message-ID: <200608152241.k7FMfHdR020748@mail02.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20060816/b16de59e/attachment.asc From anilmrn at yahoo.com Wed Aug 16 01:57:45 2006 From: anilmrn at yahoo.com (anil maran) Date: Tue, 15 Aug 2006 16:57:45 -0700 (PDT) Subject: [Tutor] getting and storing favicon.ico Message-ID: <20060815235745.74333.qmail@web55907.mail.re3.yahoo.com> /favicon.ico i want to get the favicon.ico from the URL when a blog is added to the aggregator and then display the image, this is the usage scenario Please let me know how to do this in python i m willing to use os.spawnv() and call convert if need be thanks a lot --------------------------------- Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060815/af46d2d6/attachment.html From kent37 at tds.net Wed Aug 16 03:32:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Aug 2006 21:32:19 -0400 Subject: [Tutor] What does import really do? In-Reply-To: References: <5E5EE09E-2C03-11DB-B3EC-000A95EA5592@well.com> <44E136E3.1020307@gmail.com> Message-ID: <44E275A3.9040208@tds.net> jim stockford wrote: > many thanks. > wrt import and what's named, in the case of > the PIL library, the import statement can be > import Image # not import PIL > That is because the directory Lib/site-packages/PIL is in sys.path, so any PIL module can be imported directly without the PIL prefix. (The PIL dir is added to sys.path by the file Lib/site-customize/PIL.pth.) > my presumption is that the PIL whatever-it-is > contains a set of whatever-they-are, one of > which is named Image. > In the above usage I would say PIL is a directory containing a collection of modules. But PIL is also a package, since you can say from PIL import Image Kent From jeffpeery at yahoo.com Wed Aug 16 07:31:22 2006 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue, 15 Aug 2006 22:31:22 -0700 (PDT) Subject: [Tutor] threading Message-ID: <20060816053122.36571.qmail@web30503.mail.mud.yahoo.com> hello, how do I stop a thread? do I need to kill it or can I simply call a stop function... kinda like the start function? I read a bit on google and it sounded like using a kill isn't recommended for some reason... so how is this thing stopped? thanks! Jeff --------------------------------- Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060815/d686a449/attachment.html From john at fouhy.net Wed Aug 16 07:45:13 2006 From: john at fouhy.net (John Fouhy) Date: Wed, 16 Aug 2006 17:45:13 +1200 Subject: [Tutor] threading In-Reply-To: <20060816053122.36571.qmail@web30503.mail.mud.yahoo.com> References: <20060816053122.36571.qmail@web30503.mail.mud.yahoo.com> Message-ID: <5e58f2e40608152245h4e3863e0r1c357072a8f5a011@mail.gmail.com> On 16/08/06, Jeff Peery wrote: > hello, how do I stop a thread? do I need to kill it or can I simply call a > stop function... kinda like the start function? I read a bit on google and > it sounded like using a kill isn't recommended for some reason... so how is > this thing stopped? thanks! The only good way for a thread to stop is for its run() method to exit. It kinda depends what your thread is doing, and what technique you are using to keep it alive, but one possibility is to do something like: class Worker(threading.Thread): def run(self): self.running = True while(self.running): # do stuff def stop(self): self.running = False In this case, the you call .stop() on your Worker object, and the thread will exit when it next gets to the top of the while loop. -- John. From jeffpeery at yahoo.com Wed Aug 16 07:52:16 2006 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue, 15 Aug 2006 22:52:16 -0700 (PDT) Subject: [Tutor] threading In-Reply-To: <5e58f2e40608152245h4e3863e0r1c357072a8f5a011@mail.gmail.com> Message-ID: <20060816055216.65970.qmail@web30502.mail.mud.yahoo.com> hmmmm, ok, well that is what I am currently doing but something is causing it to continue... guess I have some digging around to do. thanks for the help! Jeff John Fouhy wrote: On 16/08/06, Jeff Peery wrote: > hello, how do I stop a thread? do I need to kill it or can I simply call a > stop function... kinda like the start function? I read a bit on google and > it sounded like using a kill isn't recommended for some reason... so how is > this thing stopped? thanks! The only good way for a thread to stop is for its run() method to exit. It kinda depends what your thread is doing, and what technique you are using to keep it alive, but one possibility is to do something like: class Worker(threading.Thread): def run(self): self.running = True while(self.running): # do stuff def stop(self): self.running = False In this case, the you call .stop() on your Worker object, and the thread will exit when it next gets to the top of the while loop. -- John. --------------------------------- Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1?/min. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060815/5bd417e0/attachment-0001.htm From dyoo at hkn.eecs.berkeley.edu Wed Aug 16 07:56:31 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 15 Aug 2006 22:56:31 -0700 (PDT) Subject: [Tutor] threading In-Reply-To: <5e58f2e40608152245h4e3863e0r1c357072a8f5a011@mail.gmail.com> References: <20060816053122.36571.qmail@web30503.mail.mud.yahoo.com> <5e58f2e40608152245h4e3863e0r1c357072a8f5a011@mail.gmail.com> Message-ID: > It kinda depends what your thread is doing, and what technique you are > using to keep it alive, but one possibility is to do something like: > > class Worker(threading.Thread): > def run(self): > self.running = True > while(self.running): > # do stuff > > def stop(self): > self.running = False > > In this case, the you call .stop() on your Worker object, and the thread > will exit when it next gets to the top of the while loop. Hi Jeff, Another variation of this is in here: http://mail.python.org/pipermail/tutor/2006-January/044557.html Some of the method names in that old message are badly named, but I hope its ideas are clear. From emilia12 at mail.bg Wed Aug 16 08:37:27 2006 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Wed, 16 Aug 2006 09:37:27 +0300 Subject: [Tutor] about threads In-Reply-To: References: Message-ID: <1155710247.b9eec2c3f7c1a@mail.bg> Hi all, my question is probably about the threads... I have two IPs and i want to run web.py server for each IP in the same time from one script file. I can run them in two command boxes (and this works) but i want to do this from one ;-) Maybe i can do this with 'threads' but how ? is there some example ?? regards e. ----------------------------- Êàê äà ïîëó÷èòå 10% îòñòúïêà îò öåíèòå çà îðèãèíàëíè êîíñóìàòèâè è ïðèíòåðè íà HP http://digiteq.com/ From rabidpoobear at gmail.com Wed Aug 16 08:52:41 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 16 Aug 2006 01:52:41 -0500 Subject: [Tutor] about threads In-Reply-To: <1155710247.b9eec2c3f7c1a@mail.bg> References: <1155710247.b9eec2c3f7c1a@mail.bg> Message-ID: <44E2C0B9.8060003@gmail.com> emilia12 at mail.bg wrote: > Hi all, > Hi! > my question is probably about the threads... I have two IPs > and i want to run web.py server for each IP in the same > time from one script file. I can run them in two command > boxes (and this works) but i want to do this from one ;-) > > if you run two instances of the python interpreter (like you're doing when you start two command windows,) they're executing in different threads, it's just that the threads are OS level instead of application level. Windows automatically switches between the two instances of the interpreter and gives them both time to do something. This is why you can run an E-mail application at the same time as your web browser. I suspect that OS-level threading in this way would be more efficient in regard to speed, but it'd use more RAM because two interpreter instances would be loaded into memory at the same time. I don't know what web.py is. Is it something you wrote? You'll have to write multi-threaded code if you want it to run multiple threads :) (Unless, of course, Web.py supports threads?) What's your experience with Python? Do you need help with threads in general? threads in Python? >Maybe i can do this with 'threads' but how ? is there some >example ?? There are plenty of examples of threaded code that you could find by googling around, or do you mean 'is there some example [of multi-threading the web.py program]??' If the latter case, I guess you could find that by googling as well, if it exists. > regards > e. > Cheers, -Luke From ismaelgf at adinet.com.uy Wed Aug 16 09:30:15 2006 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Wed, 16 Aug 2006 04:30:15 -0300 Subject: [Tutor] about threads In-Reply-To: <44E2C0B9.8060003@gmail.com> References: <1155710247.b9eec2c3f7c1a@mail.bg> <44E2C0B9.8060003@gmail.com> Message-ID: <44E2C987.7070704@adinet.com.uy> Luke Paireepinart escribi?: > if you run two instances of the python interpreter (like you're doing > when you start two command windows,) > they're executing in different threads, it's just that the threads are > OS level instead of application level. Bear in mind that python threads have the GIL "Global interpreter lock". If you've got two processors, one interpreter, and two python threads there, at most you'll be able to use one processor. The GIL means that only one instruction at a time can be executed. Depending on what you're doing and the load you've got, this may or may not be important. Ismael From alan.gauld at freenet.co.uk Wed Aug 16 11:04:06 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 16 Aug 2006 10:04:06 +0100 Subject: [Tutor] getting and storing favicon.ico References: <20060815235745.74333.qmail@web55907.mail.re3.yahoo.com> Message-ID: <002001c6c112$ee0624f0$0201a8c0@XPpro> Anil, Can you please ask more useful questions? You have already been pointed to the url which describes how to ask good questions. Please read it! > /favicon.ico > > i want to get the favicon.ico from the URL when a blog is added to > the aggregator I have no idea what this means. > and then display the image, > this is the usage scenario Display the image where? On the blog? On a client GUI? In a browser? Don't make us guess, we cannot see your code, we cannot see your system. We only have a vague idea of what you are trying to do based on these fragmentary postings. We try to help but you are making it nearly impossible to give any sensible guidance. What code have you tried to read this icon file? > Please let me know how to do this in python > > i m willing to use os.spawnv() and call convert if need be I have no idea why you think either would be necessaary. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From janos.juhasz at VELUX.com Wed Aug 16 11:09:26 2006 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 16 Aug 2006 11:09:26 +0200 Subject: [Tutor] Build a simple ftp server in python In-Reply-To: Message-ID: Hi All, I am just plannig to make a small ftp server that would serv not a filesystem, but some kind of objects, like stocks or assets. In that case I can use my favorite commander to delete, copy, move objects from one place to another. Have you got any idea which module to use ? Yours sincerely, ______________________________ J?nos Juh?sz -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060816/d5bc0165/attachment.htm From kent37 at tds.net Wed Aug 16 13:22:07 2006 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Aug 2006 07:22:07 -0400 Subject: [Tutor] about threads In-Reply-To: <1155710247.b9eec2c3f7c1a@mail.bg> References: <1155710247.b9eec2c3f7c1a@mail.bg> Message-ID: <44E2FFDF.1000606@tds.net> emilia12 at mail.bg wrote: > Hi all, > > my question is probably about the threads... I have two IPs > and i want to run web.py server for each IP in the same > time from one script file. I can run them in two command > boxes (and this works) but i want to do this from one ;-) > Maybe i can do this with 'threads' but how ? is there some > example ?? What are the commands you use to run the two copies of web.py? Introductory material on threading is pretty scarce, try these: http://mail.python.org/pipermail/tutor/2005-October/041866.html http://linuxgazette.net/107/pai.html Kent From dyoo at hkn.eecs.berkeley.edu Wed Aug 16 17:33:36 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 16 Aug 2006 08:33:36 -0700 (PDT) Subject: [Tutor] getting and storing favicon.ico In-Reply-To: <002001c6c112$ee0624f0$0201a8c0@XPpro> References: <20060815235745.74333.qmail@web55907.mail.re3.yahoo.com> <002001c6c112$ee0624f0$0201a8c0@XPpro> Message-ID: >> i want to get the favicon.ico from the URL when a blog is added to >> the aggregator > > I have no idea what this means. Anil is referring to an icon image file that's often associated with web sites: http://en.wikipedia.org/wiki/Favicon The Python Imaging Library (PIL) should be able to open .ICO files. See: http://www.pythonware.com/products/pil/ From emilia12 at mail.bg Wed Aug 16 17:56:08 2006 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Wed, 16 Aug 2006 18:56:08 +0300 Subject: [Tutor] threads and webpy In-Reply-To: References: Message-ID: <1155743768.c8b5c03c24d33@mail.bg> > Hi! Hi ! > I don't know what web.py is. > Is it something you wrote? no, this is a simple webserver, (http://webpy.org/) > You'll have to write multi-threaded code if you want it > to run multiple > threads :) > (Unless, of course, Web.py supports threads?) i will ask the authors about this ... > What's your experience with Python? > Do you need help with threads in general? threads in > Python? yes, but python related part of threads > >Maybe i can do this with 'threads' but how ? is there > some > >example ?? > There are plenty of examples of threaded code that you > could find by > googling around, > or do you mean 'is there some example [of multi-threading > the web.py > program]??' > If the latter case, I guess you could find that by > googling as well, if > it exists. yes - i will ask the webpy authors but i expected to fond out a way to start two (or more) scripts (web.py) in different threads from one puthon's scrypt. OR two pythons interpretators to execute the above scrypt ? cheers e. ----------------------------- ??????. ???? ? ?????? ?? 4 ??????. From rabidpoobear at gmail.com Wed Aug 16 18:28:02 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 16 Aug 2006 11:28:02 -0500 Subject: [Tutor] threads and webpy In-Reply-To: <1155743768.c8b5c03c24d33@mail.bg> References: <1155743768.c8b5c03c24d33@mail.bg> Message-ID: <44E34792.4030406@gmail.com> > yes - i will ask the webpy authors > > but i expected to fond out a way to start two (or more) > scripts (web.py) in different threads from one puthon's > scrypt. OR two pythons interpretators to execute the above > scrypt ? > Python is a programming language. It's not a question about whether it's possible; rather, it's who will do it. If all you really want to do is start 2 web.py scripts from one python script you'd do something like this: # ---- (non-working code) import subprocess subprocess.Popen('python web.py') subprocess.Popen('python web.py') #----- This may or may not work. You may only be able to subprocess actual executable files. This is probably not what you want to do, though. You'll probably have to learn how to program in Python to do this. ... ... ... ... ... ... I just looked at web.py. It's not a webserver. It's a toolkit you use to write your own webserver. Why are you under the impression that it's a webserver? Did you just google for 'web server in Python' and find this? If you're using some code that you've written (or found) to handle web requests using the 'web.py' module, then show us your code and we'll tell you how to make it into a class that listens on a single IP and how to start two listen() methods of the class using threads, or maybe even handling multiple IPs using a single class instance. But just knowing that you are using 'web.py' isn't very helpful. What actual code are you using to run the webserver? (Or maybe web.py contains a simple webserver in the module when it's run as main?) HTH, -Luke > cheers > e. > > > ----------------------------- > > ??????. ???? ? ?????? ?? 4 ??????. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Wed Aug 16 19:03:05 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 16 Aug 2006 18:03:05 +0100 Subject: [Tutor] getting and storing favicon.ico References: <20060815235745.74333.qmail@web55907.mail.re3.yahoo.com> <002001c6c112$ee0624f0$0201a8c0@XPpro> Message-ID: <000501c6c155$d7d96f50$0201a8c0@XPpro> >>> i want to get the favicon.ico from the URL when a blog is added to >>> the aggregator >> >> I have no idea what this means. > > Anil is referring to an icon image file that's often associated with > web sites: > > http://en.wikipedia.org/wiki/Favicon Sure, that much I understood, but which url, and what is the aggregator? Is this one he is creating? Is his code part of the server or a client monitoring a blog site? Is he trying to detect events on a server site he uses, or one he manages? or one he is writing? Despite his many posts I still don't really understand what exactly anil is trying to do and which parts of it are in Python, which are server side, which are client side and if any of it is server admin related. Nor do I understand what specifically Anil has tried himself and where he is getting stuck and what exactly he wants us to help with. Alan G. From carroll at tjc.com Wed Aug 16 20:43:35 2006 From: carroll at tjc.com (Terry Carroll) Date: Wed, 16 Aug 2006 11:43:35 -0700 (PDT) Subject: [Tutor] threading In-Reply-To: <20060816053122.36571.qmail@web30503.mail.mud.yahoo.com> Message-ID: On Tue, 15 Aug 2006, Jeff Peery wrote: > hello, how do I stop a thread? In all the threaded apps I have so far, I've worked with Queues to give them work. So my technique has been to put a special-purpose element on the Queue, which is recognized by the thread, which exits. I usually have multiple threads accessing the Queue (or what's the point?), so before exiting, the ending thread requeues the "stop" element back onto the Queue it took it from, so that other executing threads can pick it up and process it the same way. From kermit at polaris.net Thu Aug 17 05:42:08 2006 From: kermit at polaris.net (Kermit Rose) Date: Wed, 16 Aug 2006 23:42:08 -0400 (Eastern Daylight Time) Subject: [Tutor] Actual code that illustrates problem Message-ID: <44E3E590.000005.00920@YOUR-4105E587B6> Message: 11 Date: Tue, 15 Aug 2006 11:50:47 +1200 From: "John Fouhy" Subject: Re: [Tutor] Global variables Cc: tutor at python.org Can you post actual code to illustrate the problem? Don't post your entire module; just show us the functions involved, the input that causes the problem, and what output you expect to get. -- John. ******* Here is the output that illustratrates the problem. After the output I'll list the code for the called function, strongfac, and the calling function, fermat. IDLE 1.1.2 >>> import factor34 >>> from factor34 import testrange >>> testrange(10**14+37,10**14+37) Begin calculating constants to be used in factoring. Finished calculating constants to be used in factoring. Search for a factor of 100000000000037 Could not find factors by strong probable prime test using witnesses < 10000. Try to find factors by using power of 2 mod z as a witness. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 0 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 1 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 2 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 3 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 4 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 5 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 6 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 7 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 8 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 9 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 10 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 11 x = 0 y = 0 face = [0, 0, 0] Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 12 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 15306543515214 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 13 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 12123044576953 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 14 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 45391315949900 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 15 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 59571344259390 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 16 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 78029752396948 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 17 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 35863146075772 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 18 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 19712913203085 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 19 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 14607414373499 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 20 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 57761947468766 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 21 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 75604347243674 . Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. Retrieved from strongfac, face = [0, 0, 0] In fermat: k = 22 x = 0 y = 0 face = [0, 0, 0] In strongfac Found1: x = 53799857 Found1: y = 1858741 face = [53799857L, 1858741L, 0] Found1: factor by strong probable prime test, using witnes 3561873332543 Found1: factors are 53799857 1858741 Found1: returning [53799857L, 1858741L, 0] to fermat routine. In strongfac Found1: x = 1858741 Found1: y = 53799857 face = [1858741L, 53799857L, 0] Found1: factor by strong probable prime test, using witnes 96058894729069 . Found1: factors are 1858741 53799857 Found1: returning [1858741L, 53799857L, 0] to fermat routine. Retrieved from strongfac, face = [1858741L, 53799857L, 0] In fermat: k = 23 x = 1858741 y = 53799857 face = [1858741L, 53799857L, 0] index of torial is 23 z = 100000000000037 x = 1858741 y = 53799857 difficulty = 0 >>> # def strongfac(z,w): # x = gcd(z,w-1) # if x > 1: # if x < z: # y = z/x # print "Found factors by P-1 Method as part of Strong probable prime test, using witness",w,"." # print " x = ",x," y = ",y # return [x,y,0] # w2 = (w * w)%z # s = ksqrt(w2) # if w2 == s * s: # if s != w: # x = gcd(z,kabs(w2 - s)) # if x > 1: # if x < z: # print "Found factors by square = square as part of Strong probable prime test, using witness",w,"." # return [x,y,0] # # trace = 0 # t = z - 1 # a = 0 # while t%2 == 0: # t = t/2 # a = a + 1 # test = pow(w,t,z) # if test ==1: # x = gcd(z,w-1) # if x > 1: # if x < z: # y = z/x # print " Found factor by Strong probable prime test, using withness ",w,"." # return [x,y,0] # else: # x = gcd(test-1,z) # if x > 1: # print " " # print " In strongfac " # print " Found1: x = ",x # if x < z: # y = z/x # print " Found1: y = ",y # face = [x,y,0] # print " face = ",face # face[0] = x # face[1] = y # face[2] = 0 # print " Found1: factor by strong probable prime test, using witness ",w," ." # print " Found1: factors are ",face[0],face[1] # print " Found1: returning ",face," to fermat routine." # return face # # if test + 1 == z: # x = gcd(w+1,z) # if x > 1: # if x < z: # y = z/x # print " Found factor by Strong probable prrime test, using withness ",w,"." # return [x,y,0] # for j in range (1,a): # test2 = (test * test)%z # test2sqrt = ksqrt(test2) # if test2sqrt * test2sqrt == test2: # diff = kabs(test - test2sqrt) # if diff !=0: # x = gcd(z,kabs(test - test2sqrt)) # if x > 1: # if x < z: # y = z/x # print " Found factors by strong probable prime test using difference of squares and witness ",w,"." # return [x,y,j] # y = gcd(z,test+test2sqrt) # if y > 1: # if y < z: # print " Found factors by strong probable prime test using difference of squares and witness ",w,"." # return [x,y,j] # test1 = test2 + 1 # test = test2 # if test1 == z: # pass # else: # x = gcd(test1,z) # if x > 1: # if x < z: # print " " # print " In Strongfac " # y = z/x # fac = [x,y,j] # print " Foundj factor by strong probable prime test using witness,",w," ." # print " Returning ",fac," to fermat routine." # return fac # q = 0 # fac = [0,0,0] # return fac # # def fermat(z,maxdiff,pmap,plist,sqlist,sqresidue,torials,limitsteps): # for j in range(2,3): # print " " # print " Try to find factors by using power of ",j," mod z as a witness." # w2 = j # for k in range(100): # w = pow(j,torials[k],z) # face = strongfac(z,w) # print " Retrieved from strongfac, face = ",face # x = face[0] # y = face[1] # print " In fermat: k = ",k," x = ",x," y = ",y," face = " face # if face[0] != 0: # print " index of torial is ",k # return face # if k == 0: # w2 = w # else: # w2 = pow(w2,torials[k],z) # fac = strongfac(z,w2) # print " " # print " Could not find factors by strong probable prime test." Kermit Rose < kermit at polaris.net > From kermit at polaris.net Thu Aug 17 05:51:16 2006 From: kermit at polaris.net (Kermit Rose) Date: Wed, 16 Aug 2006 23:51:16 -0400 (Eastern Daylight Time) Subject: [Tutor] Global variables References: <44E11426.2060700@alum.rpi.edu> Message-ID: <44E3E7AF.000009.00920@YOUR-4105E587B6> From: Bob Gailer Date: 08/14/06 20:24:00 To: kermit at polaris.net; tutor at python.org Subject: RE: [Tutor] Global variables A while back you attached factor34.py. Is that the program you are having trouble with? **** Yes! And you said it misbehaves "consistently with certain numbers to be factored." What are these numbers? ***** One of the numbers for which strongfac fails to return factors which it correctly calculates is Search for a factor of 100000000000037 Kermit < kermit at polaris.net > From kermit at polaris.net Thu Aug 17 06:17:47 2006 From: kermit at polaris.net (Kermit Rose) Date: Thu, 17 Aug 2006 00:17:47 -0400 (Eastern Daylight Time) Subject: [Tutor] Global variables References: <000301c6c03d$9b8cc5b0$0201a8c0@XPpro> Message-ID: <44E3EDEB.00000B.00920@YOUR-4105E587B6> From: Alan Gauld Date: 08/15/06 03:37:21 To: Kermit Rose; rabidpoobear at gmail.com Cc: tutor at python.org; dyoo at hkn.eecs.berkeley.edu Subject: Re: [Tutor] Global variables . The names have very little to do with it, the danger of global variable use is the reliance on side-effects and the tight coupling that you introduce between the calling module and the called module. Changes to the state of the calling module in an unpredictable manner lead to subtle bugs which are extremely hard to see and fix. ***** Huh??? What side effects do you have in mind? I certainly did not know any side effects existed. What do you mean by tight coupling? The only change I can see that would lead to a bug would be if I changed the name of the global variable in the calling routine and not in the function it called. I would know not to do that. >>>>>>>>>>> Confusion of names is of very little import, that really isn't the issue. ********** Is it that global variables are no implemented correctly? I can't imagine what the issue would be if it isn't confusion of names. >>>>>>>>>> I'd be very very doubtful that its a bug in Python. Python is very well tested and while occasionally bugs do surface, the type of bug you are describing is extremely unl;ikely to have remained hidden. It is far more likely to be an error in the code or in the data. ******* I understand your skepiticism. I would be too in if I were in your position. I've just sent the documentation to the list, in my message to Luke. >>>>> All of which points to an error in the code not in Python. The way Python is written it is virtually never going to result in that kind of error dependant on data values. ****** Which is why it surprised me. >>>>>>>>>>> That might happen is if the values are very close to zero and a type conversion occurs, but otherwise I'm very dubious about a Python bug of that type. ***** Indeed. Errors of this type would be found by chance, like I found it. It would be impractical to search for this type of error. It is not a type conversion. The error is occuring between the return statement in the called function and the picking up of that value in the calling function. From amadeo.bellotti at gmail.com Thu Aug 17 06:37:31 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Thu, 17 Aug 2006 00:37:31 -0400 Subject: [Tutor] (no subject) Message-ID: hello is there a way if a condition is not met to restart the whole program? for example if and if statement returns true then re start the whole program? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/83c7bc33/attachment.html From dkuhlman at rexx.com Thu Aug 17 06:53:49 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 16 Aug 2006 21:53:49 -0700 Subject: [Tutor] Build a simple ftp server in python In-Reply-To: References: Message-ID: <20060817045349.GA96382@cutter.rexx.com> On Wed, Aug 16, 2006 at 11:09:26AM +0200, J?nos Juh?sz wrote: > Hi All, > > I am just plannig to make a small ftp server that would serv not a > filesystem, but some kind of objects, like stocks or assets. > In that case I can use my favorite commander to delete, copy, move objects > from one place to another. > > Have you got any idea which module to use ? > Look at Twisted: http://twistedmatrix.com/projects/core/ and Medusa: http://www.nightmare.com/medusa/ And, you might be interested in this thread on twisted and medusa: http://www.gossamer-threads.com/lists/python/python/379675 Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From rabidpoobear at gmail.com Thu Aug 17 08:28:41 2006 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 17 Aug 2006 01:28:41 -0500 Subject: [Tutor] All of Kermit's E-Mails [was: Global Variables] In-Reply-To: <44E3E7AF.000009.00920@YOUR-4105E587B6> References: <44E11426.2060700@alum.rpi.edu> <44E3E7AF.000009.00920@YOUR-4105E587B6> Message-ID: <44E40C99.3060901@gmail.com> Hello, Kermit. Kermit Rose wrote: > > > From: Bob Gailer > Date: 08/14/06 20:24:00 > To: kermit at polaris.net; tutor at python.org > Subject: RE: [Tutor] Global variables > > A while back you attached factor34.py. Is that the program you are > having trouble with? > > > **** > > Yes! > > And you said it misbehaves "consistently with certain numbers to be > factored." > What are these numbers? > > > ***** > > One of the numbers for which strongfac fails to return factors which it > correctly calculates is > > Search for a factor of 100000000000037 > I really dislike the way you reply. Follow the standard format! Leave all the greater-than signs before the previous person's reply so that it will be structured correctly and easy to read. All of this star business is bad. There are two reasons why I think this. First, consider this example. Hello, how are you today? *** I'm fine. Did you have a good day? *** Yes, I did. Now while I'm reading this, I see the dialog going like this. person: 'hello, how are you today?' kermit: 'i'm fine. did you have a good day?' Oh wait! there are stars there. That must mean that part of what I thought was you talking was actually person talking. So I have to actually try to judge which part was the original post and which part is your reply. On this example it's easy to see that 'did you have a good day' is person's speech and not yours because there are only two lines of text between the stars and we know that the first line immediately after any set of stars has to be your reply. Now consider this example: > Hello, how are you today? I'm fine. > Did you have a good day? Yes, I did. Tell me that isn't orders of magnitude clearer. Point 2: I recently read an article on UI design. Basically, what it said was 'the easier it is for your users to intuitively understand your application, the more they'll enjoy it and consider it a good application. This is largely governed by how they've experienced similar applications working in the past, and they expect if they perform similar actions in your application they'll garner similar results as in your predecessor.' How this applies to you: Right away, when I see those stars, I get really agitated, because I know I'm going to have to work twice as hard trying to decipher who's talking when I read your e-mail, and right off the bat you've alienated me and made me not want to address the issue at hand. Clearly you can see this as I've written quite a long reply that is based on nothing to do with your original question. The place where I had a problem understanding who was speaking in this particular e-mail was: >A while back you attached factor34.py. Is that the program you are >having trouble with? > > >**** > >Yes! > >And you said it misbehaves "consistently with certain numbers to be >factored." >What are these numbers? > > >***** > >One of the numbers for which strongfac fails to return factors which it >correctly calculates is As I was reading this, I assumed the 'Yes!' and following paragraph were part of the same thought. When I got to the second set of stars, my immediate reaction was "Why is kermit replying to something she just said?" That was followed by "Oh, somewhere along the line it must've switched between the original poster's and kermit's dialog." I figured out that the 'And you said it misbehaves ...' part was where the OP continued to speak. Now that I'm done with that topic, let's move on. From one of your other e-mails: >From: Alan Gauld >The names have very little to do with it, the danger of global >variable >use is the reliance on side-effects and the tight coupling that you >introduce between the calling module and the called module. >Changes to the state of the calling module in an unpredictable >manner lead to subtle bugs which are extremely hard to see and fix. >***** >Huh??? >What side effects do you have in mind? >I certainly did not know any side effects existed. >What do you mean by tight coupling? >The only change I can see that would lead to a bug would be if I changed the >name of the global variable in >the calling routine and not in the function it called. >I would know not to do that. Okay. >From this it appears that you have no academic training in programming. The term 'side-effect' means that something outside the scope of the called function is modified by the called function. Here is a very basic example. #--- test.py a = ['a','b','c'] def modify_list(alist): del(alist[0]) modify_list(a) modify_list(a) print a #--- #--- output of test.py ['c'] #--- Now remember that in Python, when you pass a variable to a function, only the reference is passed to the function. Imagine that variables are themselves references (which they are.) a = ['a','b','c'] creates the following picture: a ------> ['a','b','c'] modify_list(a) doesn't do modify_list(['a','b','c']) it does modify_list(ptr) where ptr ------> ['a','b','c'] <----- a they both refer to the same object ( a python list containing three characters.) now when in the body of modify_list we say del(alist[0]), what takes place is the index operator, [0], says 'what object is the variable 'alist' pointing to? and python says 'alist ----> ['a','b','c'] <---- a' so when we delete the element out of alist we're also deleting the element out of the calling function's list. This is probably NOT desired behavior. As such it's an unwanted side-effect. A function printing to the screen is also considered a side-effect. Anything a function does that affects anything outside of its own scope is considered a side-effect. To refresh your memory, here's the next part of the e-mail I'm going to address: >The names have very little to do with it, the danger of global >variable >use is the reliance on side-effects and the tight coupling that you >introduce between the calling module and the called module. >Changes to the state of the calling module in an unpredictable >manner lead to subtle bugs which are extremely hard to see and fix. >***** >What do you mean by tight coupling? >The only change I can see that would lead to a bug would be if I changed the >name of the global variable in >the calling routine and not in the function it called. >I would know not to do that. 'tight coupling' is an English phrase meaning roughly (for our purposes) 'close interaction' or 'dependence on each other.' you say, I quote: 'The only change ... that would lead to a bug would be if I changed the name of the global variable in the calling routine.' I think you're misunderstanding Alan. consider this following example (it was hard to come up with something this convoluted) #--- start code def b(): global has_been_greeted has_been_greeted = False print "function B is doing lots of stuff" return "whatever we did in function B that's so important" def greet(): global has_been_greeted if has_been_greeted: print 'we already greeted you.' else: print 'hello!' has_been_greeted = True def c(): print "function C is doing lots of stuff." a = b() print "function C is using value a here." b() greet() greet() c() greet() # --- end code. Now we know we're going to call b() every time on startup, so we set has_been_greeted to false inside of it. Then we call greet, once b() is done calculating its stuff, so it will greet the customer. Then we call greet again to make sure that we already greeted them. (say we're debugging our program and we want to make sure greet's working correctly.) Now we call function C, which relies on function b to get a value that it needs for one of its calculations. Oops, we forgot that b() resets has_been_greeted back to false every time it's called. Now when we call greet after function c again, it greets them again! But it's already greeted them so it shouldn't have greeted them. Now imagine this is much more complicated and there are multiple global variables that you're setting all over the place to store your values, and then imagine trying to find something this obscure. A much more straightforward way to do this would be: #--- start code def b(): print "function B is doing lots of stuff" return "whatever we did in function B that's so important" def greet(): print 'hello!' def c(): print "function C is doing lots of stuff." a = b() print "function C is using value a here." b() greet() has_been_greeted = True if has_been_greeted == False: greet() c() if has_been_greeted == False: greet() #--- I know this was a stupid example but it's all I could come up with. does it help you see how global variables could give you trouble? Maybe Alan can fix my example so it makes more sense. >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> I see here you started using Greater-than signs to separate the Original Post from your replies. WTF. RTFM. This is almost as bad as before. Now I don't have the additional stress of trying to sort out who is speaking at any given time, you or the person you're replying to, but I have these big columns of multi-colored lines to deal with. In my e-mail client, Thunderbird, it converts every > sign to a vertical line of a different color, so I can tell the different levels of replies in any given e-mail. This is super-helpful, unless something like this comes along, and all it does is space out all the messages a tremendous amount and look ugly. Why can't you just use the convention and leave the >> things there? They're there for a reason. Don't fix somethin' that ain't broke, please. >Confusion of names is of very little import, that really isn't the >issue. >********** >Is it that global variables are no implemented correctly? >I can't imagine what the issue would be if it isn't confusion of names. No, it's not that global variables are not implemented correctly. You must understand that there are thousands of people using Python every day, and phrases like 'not implemented correctly' or 'there's a bug in python' are converted in my ears to '*i'm complaining because i can't get my program to work*' It's identical, to me, as when I'm playing Counter-Strike and someone starts yelling 'HACKER!' every time they get killed. It's ____much____ more likely that the person is just good at Counter-Strike than they're cheating, especially since there are a lot of anti-cheat measures. It's ____much____ more likely that your program has a bug than Python itself, because there is a lot of quality-control when a programming language is used frequently by many very skilled coders. >>>>>>>>>> >>>>>>>>>> >>>>>>>>>> You already know my feelings about this. >I'd be very very doubtful that its a bug in Python. >Python is very well tested and while occasionally bugs do surface, >the type of bug you are describing is extremely unl;ikely to have >remained hidden. It is far more likely to be an error in the code >or in the data. >******* >I understand your skepiticism. I would be too in if I were in your >position. >I've just sent the documentation to the list, in my message to Luke. Alan is being diplomatic here. I would not call what you sent 'documentation.' The tangled mess of your functions doesn't prove there's a bug in python, it just makes me think you messed up the value somewhere along the way. >>>>> >>>>> >>>>> Yay, more of this stuff. >All of which points to an error in the code not in Python. >The way Python is written it is virtually never going to result in >that kind of error dependant on data values. >****** >Which is why it surprised me. What Alan means is that your program incorrectly handles certain data values because your functions aren't written correctly. Your first thought when your program doesn't do what you expect it to should not be to blame the return statement of being buggy, but to first blame yourself. It's much more likely that you're at fault. I'm not saying this directly at you. If I wrote a function that returned incorrect values, I would assume it's my fault too. You have to understand that Python has been used for years and if there was such a fundamental bug, no matter how obscure (only occuring on certain return values), it would have been found by now. >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> :( >That might happen >is if the values are very close to zero and a type conversion >occurs, but otherwise I'm very dubious about a Python bug >of that type. >***** >Indeed. Errors of this type would be found by chance, like I found it. >It would be impractical to search for this type of error. >It is not a type conversion. Because it's impractical to search for a certain type of error it must not be that error? Just dwell on that statement a bit and tell me if you still believe it. >The error is occuring between the return statement in the called function >and the picking up of that value >in the calling function. so show us. This is the way I would prove this, if it were my program that uncovered this 'bug.' #--- def func_that_causes_bug(a): print "function is doing a bunch of complex calculations and such." v = 2322**a c = 55/float(v) d = v - a + 543 value = d / 45 print "this is where the problem arises." print "Before I return the value, it is :%s" % value return value tmp = func_that_causes_bug(564) print "And after I return the value, it is :%s" % tmp #--- Do you understand why this would evidence the bug you mentioned? You say it's a problem with the returning of the value. So print the value immediately before the return and immediately after. We'll see if it changes in transit as you claim. Onto your next e-mail: >Can you post actual code to illustrate the problem? Don't post your >entire module; just show us the functions involved, the input that >causes the problem, and what output you expect to get. >-- >John. > >******* > >Here is the output that illustratrates the problem. After the output I'll >list the code for the called function, >strongfac, > >and the calling function, fermat. [snip a ton of debug output.] This doesn't help us at all. What the heck was all that? You must understand that I have no idea what your function is supposed to do. Treat me like a child. Explain everything to me. What part of this output isn't what you wanted? ># def strongfac(z,w): ># x = gcd(z,w-1) ># if x > 1: ># if x < z: >[snip the rest of strongfac] ># def fermat(z,maxdiff,pmap,plist,sqlist,sqresidue,torials,limitsteps): ># for j in range(2,3): ># print " " ># print " Try to find factors by using power of ",j," mod z as a >[snip the rest of fermat] Why the CRAP did you put # signs before every line? I spent about 10 minutes pressing delete, down-arrow, delete, down-arrow. Going through all that trouble just so I could run the code was a pain in the rear. Remember when we were talking about UI usability earlier? Your code usability would be greatly improved if I didn't have to remove a comment from every line to test it. Also, in your example call: >IDLE 1.1.2 > >>> import factor34 > >>> from factor34 import testrange > >>> testrange(10**14+37,10**14+37) You called testrange. Now John originally said 'show us which functions are involved.' Well, after I had gone through the trouble of un-commenting all your code, it turned out that I didn't even have all the pieces there. So I went back in e-mail history and downloaded the attached 'factor34.py' file. Now I wish I didn't have to do this, because you could've made improvements in it since then. But it's the only way I can get a functional test file. Turns out testrange depends on x depends on y depends on z depends on ..... basically all of the functions in the module depend on each other. This is obviously a case for ... .dun-dun-dun!.... object-oriented programming. When you have a collection of functions that all operate together to create something, you make a Class to contain them. I think just in the process of doing this you might learn what's wrong with your program. Link me to all the Wikipedia articles I need in order to understand what you're trying to do. I'll help you rewrite this program from scratch if you want. We'll make it object-oriented the whole way. But there is no hope I will understand factor34. I will not even try. Sorry if I was too harsh anywhere along the way. Feel free to point any of this out and I'll apologize. But this is my honest opinion of the e-mails I've received from you so far. I don't think this is a good programming project for you to be learning a new language with. Perhaps you should do something simpler. If you'd like some recommendations I'd be happy to give some. Have a good day. -Luke From emilia12 at mail.bg Thu Aug 17 09:19:05 2006 From: emilia12 at mail.bg (emilia12 at mail.bg) Date: Thu, 17 Aug 2006 10:19:05 +0300 Subject: [Tutor] threads and webpy In-Reply-To: <44E34792.4030406@gmail.com> References: <1155743768.c8b5c03c24d33@mail.bg> <44E34792.4030406@gmail.com> Message-ID: <1155799145.3d10c7f49700d@mail.bg> > I just looked at web.py. > It's not a webserver. It's a toolkit you use to write > your own webserver. > Why are you under the impression that it's a webserver? > Did you just google for 'web server in Python' and find > this? you are right, i mean that it is the core of the webserver > If you're using some code that you've written (or found) > to handle web > requests > using the 'web.py' module, then show us your code and > we'll tell you > how to make it into a class that listens on a single IP > and how to > start two listen() methods of the class using threads, or > maybe even > handling multiple IPs using a single class instance. > But just knowing that you are using 'web.py' isn't very > helpful. > What actual code are you using to run the webserver? i am playng around this code : import socket import sys import web import datetime urls = ( '/(.*)', 'view' ) class view: def GET(self, name): print datetime.datetime.today() if __name__ == "__main__": hostname = socket.gethostname() ip = socket.gethostbyname(hostname) sys.argv.append(ip +':8080') # <-- probably this is not the right way, but it works web.run(urls) > (Or maybe web.py contains a simple webserver in the > module when it's run > as main?) yes - in this case it responds to http request like a server regards e. ----------------------------- ??? ?? ???????? 10% ???????? ?? ?????? ?? ?????????? ??????????? ? ???????? ?? HP http://digiteq.com/ From dyoo at hkn.eecs.berkeley.edu Thu Aug 17 10:02:20 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 01:02:20 -0700 (PDT) Subject: [Tutor] Actual code that illustrates problem In-Reply-To: <44E3E590.000005.00920@YOUR-4105E587B6> References: <44E3E590.000005.00920@YOUR-4105E587B6> Message-ID: > # def strongfac(z,w): [function body cut] Ok, let's go through this step by step. * What is the intent of strongfac? * What are the inputs? What is 'z', and what is 'w'? * What are the outputs? What is the return value of strongfac? Same questions for fermat(). What are the inputs and outputs, and what's the intent? Get those out and documented, because although I think I can guess at it, I'd rather know that we are sharing the same understanding. There's a bit of code in strongfac() that's nonsensical from a purely technical sense. For example: > # face = [x,y,0] [some code cut] > # face[0] = x > # face[1] = y > # face[2] = 0 The three assignments to face[0] through face[2] don't do anything effective and clutter the code. In fermat(), there are magic numbers: # for j in range(2,3): ^^^^ # for k in range(100): ^^^ These seem pretty arbitrary. Can you explain them? The strongfac() function you have is a good case for writing smaller functions: I can not tell where the function really ends. I see that you have several sub-tests, which I'll categorize as: * P-1 * square = square * ... and there's a few others that I can not categorize yet. But I bet you can. Have you considered breaking those out as independent helper functions? Most of us don't have experience with number theory. What people here on the list have is experience with writing software. My experience informs me that the functions you're writing are way too large. They are monolithic and imposing enough that very few people will be able to (or want to!) understand their reasoning. They really cry out to be broken into smaller subtest functions that can be individually understood. (And even if your program were running perfectly well, I'd still strongly recommend you practice the skill of small, easy-to-understand functions.) You mentioned later that: > One of the numbers for which strongfac fails to return factors which it > correctly calculates is 100000000000037 Two questions: * How do you know that it is being "correctly calculated?" * How do you know that your program is doing something wrong? That is, state explicitely to us what you expected the program to do. What is the expected result, in terms of return values, that your function failed to produce? What part of the program --- which particular subtest --- should have returned those values? Where are you looking at? Again, you have to assume that we don't know anything about number theory. Things that may seem "obvious" to you are not obvious to this audience. *grin* From nimrodx at slingshot.co.nz Thu Aug 17 13:04:59 2006 From: nimrodx at slingshot.co.nz (nimrodx) Date: Thu, 17 Aug 2006 21:04:59 +1000 Subject: [Tutor] [whitelist] Re: regular expressions question In-Reply-To: <001801c6be13$fb72d220$0201a8c0@XPpro> References: <44DDC3AA.8010908@slingshot.co.nz> <002a01c6bdf2$60c69480$0201a8c0@XPpro> <44DDE5D1.1080101@slingshot.co.nz> <001801c6be13$fb72d220$0201a8c0@XPpro> Message-ID: <44E44D5B.6000605@slingshot.co.nz> Hi Alan, I found a pretty complicated way to do it (Alan's way is way more elegant). In case someone is searching the archive, maybe they will find something in it that is useful. It uses the regular experessions module. import re def dehexlify_websites(fle): # get binary data inpt = open(fle,'rb') dat = inpt.read() inpt.close() #strip out the hex "0"'s pattern = r"\x00" res = re.sub(pattern, "", dat) #----------------------------------------- #it seemed easier to do it in two passes #create the pattern regular expression for the stuff we want to keep web = re.compile( r"(?P[/a-zA-Z0-9\.\-:\_%\?&=]+)" ) #grab them all and put them in temp variable res = re.findall(web,res) tmp = "" #oops need some new lines at the end of each one to mark end of #web address, #and need it all as one string for i in res: tmp = tmp + i+'\n' #compile reg expr for everything between :// and the newline web2 = re.compile(r":/(?P
[^\n]+)") #find the websites #make them into an object we can pass res2 = re.findall(web2,tmp) #return 'em return res2 Thanks Alan, Matt Alan Gauld wrote: >> if you look carefully at the string below, you see >> that in amongst the "\x" stuff you have the text I want: >> z tfile://home/alpha > > OK, those characters are obviously string data and it looks > like its using 16 bit characters, so yes some kind of > unicode string. In between and at the end ;lies the binary > data in whatever format it is. > >>>> Here is the first section of the file: >>>> '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01\xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x00l' >>>> > > >> In a hex editor it turns out to be readable and sensible url's with >> spaces between each digit, and a bit of crud at the end of url's, >> just as above. > > Here's a fairly drastic approach: > >>>> s = >>>> '\x00\x00\x00\x02\xb8,\x08\x9f\x00\x00z\xa8\x00\x00\x01\xf4\x00\x00\x01 >>>> > \xf4\x00\x00\x00t\x00f\x00i\x00l\x00e\x00:\x00/\x00h\x00o\x00m\x00e\x00/\x00a\x > > 00l' >>>> ''.join([c for c in s if c.isalnum() or c in '/: ']) > 'ztfile:/home/al' >>>> > > But it gets close... > > Alan g. > From dyoo at hkn.eecs.berkeley.edu Thu Aug 17 10:04:06 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 01:04:06 -0700 (PDT) Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: > hello is there a way if a condition is not met to restart the whole > program? for example if and if statement returns true then re start the > whole program? Question before we go on: why are you trying to do this? It's possible to do this, but it sounds so unusual that I want to know more about the problem. From anilmrn at yahoo.com Thu Aug 17 11:12:59 2006 From: anilmrn at yahoo.com (anil maran) Date: Thu, 17 Aug 2006 02:12:59 -0700 (PDT) Subject: [Tutor] threads and webpy In-Reply-To: <1155743768.c8b5c03c24d33@mail.bg> Message-ID: <20060817091259.75509.qmail@web55903.mail.re3.yahoo.com> did u try os.spawnv() to spawn other unix commands emilia12 at mail.bg wrote: > Hi! Hi ! > I don't know what web.py is. > Is it something you wrote? no, this is a simple webserver, (http://webpy.org/) > You'll have to write multi-threaded code if you want it > to run multiple > threads :) > (Unless, of course, Web.py supports threads?) i will ask the authors about this ... > What's your experience with Python? > Do you need help with threads in general? threads in > Python? yes, but python related part of threads > >Maybe i can do this with 'threads' but how ? is there > some > >example ?? > There are plenty of examples of threaded code that you > could find by > googling around, > or do you mean 'is there some example [of multi-threading > the web.py > program]??' > If the latter case, I guess you could find that by > googling as well, if > it exists. yes - i will ask the webpy authors but i expected to fond out a way to start two (or more) scripts (web.py) in different threads from one puthon's scrypt. OR two pythons interpretators to execute the above scrypt ? cheers e. ----------------------------- ??????. ???? ? ?????? ?? 4 ??????. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Do you Yahoo!? Next-gen email? Have it all with the all-new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/b3fd258f/attachment.html From anilmrn at yahoo.com Thu Aug 17 11:15:30 2006 From: anilmrn at yahoo.com (anil maran) Date: Thu, 17 Aug 2006 02:15:30 -0700 (PDT) Subject: [Tutor] threads and webpy In-Reply-To: <44E34792.4030406@gmail.com> Message-ID: <20060817091530.3530.qmail@web55907.mail.re3.yahoo.com> hi like your post about how to make it listen on one ip and then on two ips isnt this general python, can you please explain how to go about this, this would be very useful thanks then show us your code and we'll tell you how to make it into a class that listens on a single IP and how to start two listen() methods of the class using threads, or maybe even handling multiple IPs using a single class instance. But just knowing that you are using 'web.py' isn't very helpful. What actual code are you using to run the webserver? (Or maybe web.py contains a simple webserver in the module when it's run as main?) HTH, -Luke Luke Paireepinart wrote: > yes - i will ask the webpy authors > > but i expected to fond out a way to start two (or more) > scripts (web.py) in different threads from one puthon's > scrypt. OR two pythons interpretators to execute the above > scrypt ? > Python is a programming language. It's not a question about whether it's possible; rather, it's who will do it. If all you really want to do is start 2 web.py scripts from one python script you'd do something like this: # ---- (non-working code) import subprocess subprocess.Popen('python web.py') subprocess.Popen('python web.py') #----- This may or may not work. You may only be able to subprocess actual executable files. This is probably not what you want to do, though. You'll probably have to learn how to program in Python to do this. ... ... ... ... ... ... I just looked at web.py. It's not a webserver. It's a toolkit you use to write your own webserver. Why are you under the impression that it's a webserver? Did you just google for 'web server in Python' and find this? If you're using some code that you've written (or found) to handle web requests using the 'web.py' module, then show us your code and we'll tell you how to make it into a class that listens on a single IP and how to start two listen() methods of the class using threads, or maybe even handling multiple IPs using a single class instance. But just knowing that you are using 'web.py' isn't very helpful. What actual code are you using to run the webserver? (Or maybe web.py contains a simple webserver in the module when it's run as main?) HTH, -Luke > cheers > e. > > > ----------------------------- > > ??????. ???? ? ?????? ?? 4 ??????. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Do you Yahoo!? Next-gen email? Have it all with the all-new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/544a4e12/attachment.htm From anilmrn at yahoo.com Thu Aug 17 11:17:26 2006 From: anilmrn at yahoo.com (anil maran) Date: Thu, 17 Aug 2006 02:17:26 -0700 (PDT) Subject: [Tutor] about threads In-Reply-To: <1155710247.b9eec2c3f7c1a@mail.bg> Message-ID: <20060817091727.68118.qmail@web55909.mail.re3.yahoo.com> you can configure lighttpd virtual hosts to spawn new webpy instances for each of your ip address Emilia can you explain your problem a little more I have spent quite some time using and asking questions abt the problems ur posting... emilia12 at mail.bg wrote: Hi all, my question is probably about the threads... I have two IPs and i want to run web.py server for each IP in the same time from one script file. I can run them in two command boxes (and this works) but i want to do this from one ;-) Maybe i can do this with 'threads' but how ? is there some example ?? regards e. --------------------------------- Do you Yahoo!? Next-gen email? Have it all with the all-new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/1237fea9/attachment-0001.html From anilmrn at yahoo.com Thu Aug 17 11:19:08 2006 From: anilmrn at yahoo.com (anil maran) Date: Thu, 17 Aug 2006 02:19:08 -0700 (PDT) Subject: [Tutor] about threads In-Reply-To: <44E2C0B9.8060003@gmail.com> Message-ID: <20060817091908.75152.qmail@web55912.mail.re3.yahoo.com> You'll have to write multi-threaded code if you want it to run multiple threads :) (Unless, of course, Web.py supports threads?) Luke, what is the easiest way to run multithreaded programs from webpy is there a page that has common gotchas and pitfalls for doing the same. Luke Paireepinart wrote: emilia12 at mail.bg wrote: > Hi all, > Hi! > my question is probably about the threads... I have two IPs > and i want to run web.py server for each IP in the same > time from one script file. I can run them in two command > boxes (and this works) but i want to do this from one ;-) > > if you run two instances of the python interpreter (like you're doing when you start two command windows,) they're executing in different threads, it's just that the threads are OS level instead of application level. Windows automatically switches between the two instances of the interpreter and gives them both time to do something. This is why you can run an E-mail application at the same time as your web browser. I suspect that OS-level threading in this way would be more efficient in regard to speed, but it'd use more RAM because two interpreter instances would be loaded into memory at the same time. I don't know what web.py is. Is it something you wrote? You'll have to write multi-threaded code if you want it to run multiple threads :) (Unless, of course, Web.py supports threads?) What's your experience with Python? Do you need help with threads in general? threads in Python? >Maybe i can do this with 'threads' but how ? is there some >example ?? There are plenty of examples of threaded code that you could find by googling around, or do you mean 'is there some example [of multi-threading the web.py program]??' If the latter case, I guess you could find that by googling as well, if it exists. > regards > e. > Cheers, -Luke _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great rates starting at 1¢/min. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/dbaeb6b4/attachment.htm From anilmrn at yahoo.com Thu Aug 17 11:48:46 2006 From: anilmrn at yahoo.com (anil maran) Date: Thu, 17 Aug 2006 02:48:46 -0700 (PDT) Subject: [Tutor] Low level socket and threading code in python in HUGE websites - Message-ID: <20060817094846.71075.qmail@web55902.mail.re3.yahoo.com> What kind of low-level socket and threading code is necessary for a db intensive site such as yahoo. How do we use it from python? does anyone have experience using it http://redditblog.blogspot.com/2005/12/on-lisp.html >From moving to python by the founders of reddit Because of the low-level socket and threading code we had to write, reddit would not run on my Mac, and I was always tethered to our FreeBSD development server. Not being able to program offline is a pain. I would imagine that they aren't just using a database. most of the "low level socket stuff" I've seen is about setting timeouts and doing Async IO. --------------------------------- Do you Yahoo!? Get on board. You're invited to try the new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/d9375179/attachment.html From anilmrn at yahoo.com Thu Aug 17 11:55:04 2006 From: anilmrn at yahoo.com (anil maran) Date: Thu, 17 Aug 2006 02:55:04 -0700 (PDT) Subject: [Tutor] web application and database caching technique Message-ID: <20060817095504.35141.qmail@web55911.mail.re3.yahoo.com> i m trying to build a webapplication, i need to cache db records as it has become very slow the sql queries and retrival can you guys helpe me out in designing cache structures/ hash tables for these cases 1. Scenario One: * Huge number of reads * Few writes * One row accessed from db per request * All data written to db is used. * Medium number of records. Since the large number of read need to be fast I chose this design: A hashtable caches records. They are cleared based on expiration time and limit on maximum number of cached records. When a record is updated in the db, it is deleted from the cache and recached next time it is queried. This part could be handled by implementation you linked to. A persistent background thread periodically flushes the changed/new values in the cache to the database. Additional calculations could be added here to chose the optimal cache entrees to delete or precache. 2. Scenario Two: * Few reads * Huge number of writes * Many rows accessed from db per request * Most data written to db is discarded. * Huge number of small records. This is the strangest so far. Because of the huge number of records, most of which will just be discarded anyway, I try to keep away from the database as much as possible. When it's time to flush them to the db I aggregate the records into groups, cpickle, and lzo them. I am still playing with this but I notice a good performance improvement already. 3. Scenario Three: * Huge number of writes * Huge number of reads * One row accessed from db per request * Small number of records. This is the same as the first except I have space to cache everything. This means I can get rid of the time() check for each cache check. --------------------------------- Stay in the know. Pulse on the new Yahoo.com. Check it out. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/5e7d90f8/attachment.htm From anilmrn at yahoo.com Thu Aug 17 11:56:59 2006 From: anilmrn at yahoo.com (anil maran) Date: Thu, 17 Aug 2006 02:56:59 -0700 (PDT) Subject: [Tutor] server push Message-ID: <20060817095659.94897.qmail@web55910.mail.re3.yahoo.com> Hi guys i was wondering if someone has successfuly used server push for apps such as meebo etc using webpy if so can you share some guidelines on using them I have a continuously running python webserver and a website, if there is a new mail or message, how do i ping and let the website or the user know without polling, using twisted web2 thanks a lot New server software is often required to make applications built using Comet scale, but the patterns for event-driven IO on the server side are becoming better distributed. Even Apache will provide a Comet-ready worker module in the upcoming 2.2 release. Until then, tools like Twisted, POE, Nevow, mod_pubsub, and other higher-level event-driven IO abstractions are making Comet available to developers on the bleeding edge. Modern OSes almost all now support some sort of kernel-level event-driven IO system as well. I've even heard that Java's NIO packages will start to take advantage of them in a forthcoming release. These tools are quietly making the event-driven future a reality. --------------------------------- Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail Beta. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/a5ddeaba/attachment.html From kent37 at tds.net Thu Aug 17 12:55:09 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Aug 2006 06:55:09 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <44E44B0D.7050309@tds.net> Amadeo Bellotti wrote: > hello is there a way if a condition is not met to restart the whole > program? for example if and if statement returns true then re start > the whole program? You can probably achieve what you want just by structuring the program correctly. My guess you need to use nested loops, something like this: while True: initialize_everything() while True: if something_is_wrong(): break do_some_work() This will do_some_work() until something_is_wrong(), then it will initialize_everything() and try again. If the test for something_is_wrong() is buried deep in the code you can break the loop by raising an exception which you catch in the top-level loop. Kent From bds at waywood.co.uk Thu Aug 17 14:52:56 2006 From: bds at waywood.co.uk (Barnaby Scott) Date: Thu, 17 Aug 2006 13:52:56 +0100 Subject: [Tutor] Communicating with Win2000 runas.exe Message-ID: <44E466A8.4010902@waywood.co.uk> I have a problem which I was hoping that Python could solve for me, but I have become stuck for days now after only 2 lines of code. My son has a Microsoft game on a shared family computer, which Microsoft in its infinite wisdom requires you to run as 'administrator'. Call me old-fashioned but I don't want to promote an 8 year-old to administrator just so he can run his game! Enter 'runas.exe'... However, because we are on Windows 2000, runas does not allow you to save a password - it has to be entered every time: not much further forward. So I'm thinking along these lines: import subprocess sp = subprocess.Popen(r'C:\WINNT\SYSTEM32\runas.exe /user:administrator C:\Program Files\Microsoft Games\Age of Mythology\aom.exe') #some sort of code to send the password here... #help! Sure enough, this brings up a prompt asking for the administrator's password, but I can't get anything to work in terms of getting the script to provide the password. Am I barking up the wrong tree here? Any clues would be gratefully received. (Even if I do get this to work, my next trick is to hide the password from any prying eyes looking at the script...) Thanks Barnaby Scott From tim.golden at viacom-outdoor.co.uk Thu Aug 17 15:50:09 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 17 Aug 2006 14:50:09 +0100 Subject: [Tutor] Communicating with Win2000 runas.exe Message-ID: [Barnaby Scott] | So I'm thinking along these lines: | | import subprocess | sp = subprocess.Popen(r'C:\WINNT\SYSTEM32\runas.exe | /user:administrator | C:\Program Files\Microsoft Games\Age of Mythology\aom.exe') | #some sort of code to send the password here... | #help! I *think* -- and I'm happy to be wrong -- that there's no way you're going to get that password in there. One place to start looking might be: pywinauto - http://pywinauto.pbwiki.com/ which lets you automate Windows in general; don't know how much use it'll be here. Alternatively, look into the pywin32 package, and in particular at the win32security functions which let you impersonate another user. They're not trivial to use, but their use has been explained a few times over the years I think. Mostly by Roger Upole who wrote most if not all of the Python bindings. Here's a post which looks useful; you'll have to hunt around for others: http://groups.google.com/group/comp.lang.python/msg/6bbefb9d4d45d253 I suggest you ask this question again on the main python / python-win32 lists; it's a bit too platform-specific for the tutor list, I would say. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From dyoo at hkn.eecs.berkeley.edu Thu Aug 17 16:34:00 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 07:34:00 -0700 (PDT) Subject: [Tutor] (no subject) (fwd) Message-ID: ---------- Forwarded message ---------- Date: Thu, 17 Aug 2006 09:44:40 -0400 From: Amadeo Bellotti To: Danny Yoo Subject: Re: [Tutor] (no subject) Mr. Yoo im working on a program to write a sudoku puzzle and if something is wrong with the last row i need to re make the whole puzzle over again. On 8/17/06, Danny Yoo wrote: > > >> hello is there a way if a condition is not met to restart the whole >> program? for example if and if statement returns true then re start the >> whole program? > > Question before we go on: why are you trying to do this? > > It's possible to do this, but it sounds so unusual that I want to know > more about the problem. > From dyoo at hkn.eecs.berkeley.edu Thu Aug 17 16:54:47 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 07:54:47 -0700 (PDT) Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: > Mr. Yoo im working on a program to write a sudoku puzzle and if > something is wrong with the last row i need to re make the whole puzzle > over again. Hi Amadeo, In the future, please use the "Reply to All" feature of your email client, so that we can keep the conversation on the mailing list. Here's a separate question that's related to the first: can you write a function that asks the user to enter a word, and continues prompting until the user enters a non-empty word? From amadeo.bellotti at gmail.com Thu Aug 17 16:59:24 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Thu, 17 Aug 2006 10:59:24 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: Yes I can Mr. Yoo, but i dont really want to make my whole program a loop. On 8/17/06, Danny Yoo wrote: > > > Mr. Yoo im working on a program to write a sudoku puzzle and if > > something is wrong with the last row i need to re make the whole puzzle > > over again. > > Hi Amadeo, > > In the future, please use the "Reply to All" feature of your email client, > so that we can keep the conversation on the mailing list. > > Here's a separate question that's related to the first: can you write a > function that asks the user to enter a word, and continues prompting until > the user enters a non-empty word? > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/9ff9de5c/attachment.html From dyoo at hkn.eecs.berkeley.edu Thu Aug 17 17:46:39 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 08:46:39 -0700 (PDT) Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: >> > Mr. Yoo im working on a program to write a sudoku puzzle and if >> > something is wrong with the last row i need to re make the whole puzzle >> > over again. >> Here's a separate question that's related to the first: can you write a >> function that asks the user to enter a word, and continues prompting until >> the user enters a non-empty word? Hi Amadeo, > Yes I can Mr. Yoo, but i dont really want to make my whole program a > loop. Ok. Why not? I'm curious: is there a particular constraint you're trying to work under, or is it something else? Also, I'm not sure what you mean by "whole program". In any case, here's a way to do it without an explicit 'for' or 'while' loop: #################################### def ask_for_input(): msg = raw_input("enter a word:") if msg: return msg else: return ask_for_input() #################################### This would not be the idiomatic way to do this in Python only because of a technical limitation in the main Python implementation (it doesn't support "tail call optimization"). Still, would this be more acceptable to you, or do you also consider this a "loop"? (Personally, I do. *grin*) From kermit at polaris.net Thu Aug 17 17:49:00 2006 From: kermit at polaris.net (Kermit Rose) Date: Thu, 17 Aug 2006 11:49:00 -0400 (Eastern Daylight Time) Subject: [Tutor] All of Kermit's E-Mails References: <44E40C99.3060901@gmail.com> Message-ID: <44E48FE7.000001.03640@YOUR-4105E587B6> From: Luke Paireepinart Date: 08/17/06 02:29:01 To: Kermit Rose Cc: tutor at python.org Subject: Re: [Tutor] All of Kermit's E-Mails [was: Global Variables] >>> I really dislike the way you reply. Follow the standard format! Leave all the greater-than signs before the previous person's reply so that it will be structured correctly and easy to read. All of this star business is bad. ************* Suggest an alternative, because my email program does not insert the > sign like the standard email program does. I also prefer the standard format, and the first few times I replied in email I typed in all the > in front of each line. After a while I decided that I should find some alternative equivalent that took less time. >>> Okay. >From this it appears that you have no academic training in programming. The term 'side-effect' means that something outside the scope of the called function is modified by the called function. Here is a very basic example. #--- test.py a = ['a','b','c'] def modify_list(alist): del(alist[0]) modify_list(a) modify_list(a) print a #--- #--- output of test.py ['c'] #--- ******************** >From your example: You haven't declared any variable global. does a = [a',b'c'] implicitly declare the variable "a" to be global because it is not inside a function definition? I did not know Python syntax would permit statements to not be inside some function definition. I see that modify_list deletes the zero'th element. The structure of my factor functions are such that this type of mistake could not happen. If I knew how, I would follow up Alan's suggestion of making the module into a class. >>> Now remember that in Python, when you pass a variable to a function, only the reference is passed to the function. Imagine that variables are themselves references (which they are.) a = ['a','b','c'] creates the following picture: a ------> ['a','b','c'] modify_list(a) doesn't do modify_list(['a','b','c']) it does modify_list(ptr) where ptr ------> ['a','b','c'] <----- a they both refer to the same object ( a python list containing three characters.) now when in the body of modify_list we say del(alist[0]), what takes place is the index operator, [0], says 'what object is the variable 'alist' pointing to? and python says 'alist ----> ['a','b','c'] <---- a' so when we delete the element out of alist we're also deleting the element out of the calling function's list. This is probably NOT desired behavior. As such it's an unwanted side-effect. ******************* This confuses me. Isn't the calling functions list [a',b',c'} ? Therefore, wouldn't the resultt of modify_list(a) be [b',c']? That's what I would expect it to be and what I would want it to do. >>> A function printing to the screen is also considered a side-effect. Anything a function does that affects anything outside of its own scope is considered a side-effect. ***************** Ok. Why is this bad. If I'm using global variables, this would be exactly what I would want. But I don't insist on using global variables. The idea of making a factor class appeals to me. I haven't yet learned how. .>>> To refresh your memory, here's the next part of the e-mail I'm going to address: >The names have very little to do with it, the danger of global >variable >use is the reliance on side-effects and the tight coupling that you >introduce between the calling module and the called module. >Changes to the state of the calling module in an unpredictable >manner lead to subtle bugs which are extremely hard to see and fix. >***** >What do you mean by tight coupling? >The only change I can see that would lead to a bug would be if I changed the >name of the global variable in >the calling routine and not in the function it called. >I would know not to do that. 'tight coupling' is an English phrase meaning roughly (for our purposes) 'close interaction' or 'dependence on each other.' you say, I quote: 'The only change ... that would lead to a bug would be if I changed the name of the global variable in the calling routine.' I think you're misunderstanding Alan. consider this following example (it was hard to come up with something this convoluted) #--- start code def b(): global has_been_greeted has_been_greeted = False print "function B is doing lots of stuff" return "whatever we did in function B that's so important" def greet(): global has_been_greeted if has_been_greeted: print 'we already greeted you.' else: print 'hello!' has_been_greeted = True def c(): print "function C is doing lots of stuff." a = b() print "function C is using value a here." b() greet() greet() c() greet() # --- end code. Now we know we're going to call b() every time on startup, so we set has_been_greeted to false inside of it. Then we call greet, once b() is done calculating its stuff, so it will greet the customer. Then we call greet again to make sure that we already greeted them. (say we're debugging our program and we want to make sure greet's working correctly.) Now we call function C, which relies on function b to get a value that it needs for one of its calculations. Oops, we forgot that b() resets has_been_greeted back to false every time it's called. Now when we call greet after function c again, it greets them again! But it's already greeted them so it shouldn't have greeted them. Now imagine this is much more complicated and there are multiple global variables that you're setting all over the place to store your values, and then imagine trying to find something this obscure. A much more straightforward way to do this would be: #--- start code def b(): print "function B is doing lots of stuff" return "whatever we did in function B that's so important" def greet(): print 'hello!' def c(): print "function C is doing lots of stuff." a = b() print "function C is using value a here." b() greet() has_been_greeted = True if has_been_greeted == False: greet() c() if has_been_greeted == False: greet() #--- I know this was a stupid example but it's all I could come up with. does it help you see how global variables could give you trouble? Maybe Alan can fix my example so it makes more sense. ************************* I believe I understand your example. Basically you are saying that if my module becomes sufficiently complicated, I may lose track of how I use the global variables and violate my preset rules for how to use them. >>> I see here you started using Greater-than signs to separate the Original Post from your replies. WTF. RTFM. This is almost as bad as before. **************** Please suggest an alternative that is relatively quick to compensate for my email program, Incredimail, which does not have an option to insert the > in from of each line of the original post. >>> Now I don't have the additional stress of trying to sort out who is speaking at any given time, you or the person you're replying to, but I have these big columns of multi-colored lines to deal with. In my e-mail client, Thunderbird, it converts every > sign to a vertical line of a different color, so I can tell the different levels of replies in any given e-mail. This is super-helpful, unless something like this comes along, and all it does is space out all the messages a tremendous amount and look ugly. Why can't you just use the convention and leave the >> things there? They're there for a reason. Don't fix somethin' that ain't broke, please. *********** Unfortunately, in my email client, Incredimail, it is broken. Thanks for telling me the effect of the > sign in your email client, Thunderbird. I changed all my long lines of > signs to exactly three > signs on a line. >>> No, it's not that global variables are not implemented correctly. You must understand that there are thousands of people using Python every day, and phrases like 'not implemented correctly' or 'there's a bug in python' are converted in my ears to '*i'm complaining because i can't get my program to work*' It's identical, to me, as when I'm playing Counter-Strike and someone starts yelling 'HACKER!' every time they get killed. ******* :) Yes. I understand your response. >>> It's ____much____ more likely that the person is just good at Counter-Strike than they're cheating, especially since there are a lot of anti-cheat measures. It's ____much____ more likely that your program has a bug than Python itself because there is a lot of quality-control when a programming language is used frequently by many very skilled coders. **************** Well, I would not have claimed a possible bug in Python if I could see how my code could possibly have been responsible for a variable to have one value in the called function, and have a different value when it's returned to the calling function. >>> Alan is being diplomatic here. I would not call what you sent 'documentation.' The tangled mess of your functions doesn't prove there's a bug in python, it just makes me think you messed up the value somewhere along the way. ****************** Suggest a way for me to make more clear what is happening. >>> What Alan means is that your program incorrectly handles certain data values because your functions aren't written correctly. Your first thought when your program doesn't do what you expect it to should not be to blame the return statement of being buggy, but to first blame yourself. It's much more likely that you're at fault. I'm not saying this directly at you. If I wrote a function that returned incorrect values, I would assume it's my fault too. ******** Indeed. I first seek to find the error in my code. Only after I proved that the variable changed in value between just before the return statement in the called routine and after its reception in the calling routine did I suggest that there may be a bug in Python. >>> You have to understand that Python has been used for years and if there was such a fundamental bug, no matter how obscure (only occuring on certain return values), it would have been found by now. ***** I would have expected so also. That is why this strange behavior surprised me. >>> Because it's impractical to search for a certain type of error it must not be that error? Just dwell on that statement a bit and tell me if you still believe it. >The error is occuring between the return statement in the called function >and the picking up of that value >in the calling function. so show us. This is the way I would prove this, if it were my program that uncovered this 'bug.' #--- def func_that_causes_bug(a): print "function is doing a bunch of complex calculations and such." v = 2322**a c = 55/float(v) d = v - a + 543 value = d / 45 print "this is where the problem arises." print "Before I return the value, it is :%s" % value return value tmp = func_that_causes_bug(564) print "And after I return the value, it is :%s" % tmp #--- ***** That is exactly what I did!!!! >>> Do you understand why this would evidence the bug you mentioned? You say it's a problem with the returning of the value. So print the value immediately before the return and immediately after. We'll see if it changes in transit as you claim. ***** Yes. That is exactly what I did!!! >>> >Can you post actual code to illustrate the problem? Don't post your >entire module; just show us the functions involved, the input that >causes the problem, and what output you expect to get. >-- >John. > >******* > >Here is the output that illustratrates the problem. After the output I'll >list the code for the called function, >strongfac, > >and the calling function, fermat. [snip a ton of debug output.] This doesn't help us at all. What the heck was all that? You must understand that I have no idea what your function is supposed to do. Treat me like a child. Explain everything to me. What part of this output isn't what you wanted? *********** Huh? That "ton of debug output" is exactly what you said you wanted. So perhaps we should take a closer look at it. Perhaps we should talk in private email a few times to get the output that is generated more readable to you and the others. >>> ># def strongfac(z,w): ># x = gcd(z,w-1) ># if x > 1: ># if x < z: >[snip the rest of strongfac] ># def fermat(z,maxdiff,pmap,plist,sqlist,sqresidue,torials,limitsteps): ># for j in range(2,3): ># print " " ># print " Try to find factors by using power of ",j," mod z as a >[snip the rest of fermat] Why the CRAP did you put # signs before every line? I spent about 10 minutes pressing delete, down-arrow, delete, down-arrow. Going through all that trouble just so I could run the code was a pain in the rear. ****** Either my email program or your email program removes leading blanks. Putting a # in column 1 is one way to transmit the code in a way that preserves the indentation. Suggest an alternative way of transmitting code. >>> Remember when we were talking about UI usability earlier? Your code usability would be greatly improved if I didn't have to remove a comment from every line to test it. ****** What does UI mean? Could you construct a program to delete column 1 from each line? Perhaps such a program already exist in the editor. >>> Also, in your example call: >IDLE 1.1.2 > >>> import factor34 > >>> from factor34 import testrange > >>> testrange(10**14+37,10**14+37) You called testrange. Now John originally said 'show us which functions are involved.' Well, after I had gone through the trouble of un-commenting all your code, it turned out that I didn't even have all the pieces there. So I went back in e-mail history and downloaded the attached 'factor34.py' file. Now I wish I didn't have to do this, because you could've made improvements in it since then. But it's the only way I can get a functional test file. Turns out testrange depends on x depends on y depends on z depends on ..... basically all of the functions in the module depend on each other. This is obviously a case for ... .dun-dun-dun!.... object-oriented programming. When you have a collection of functions that all operate together to create something, you make a Class to contain them. I think just in the process of doing this you might learn what's wrong with your program. *** I am quite willing to make a Class to contain them, after I learn how. And perhaps, after we rewrite my module as a class, the strange behavior will change, perhaps it won't. If the strange behavior does not change, then it should be easier tracing what is happening. >>> Link me to all the Wikipedia articles I need in order to understand what you're trying to do. I'll help you rewrite this program from scratch if you want. We'll make it object-oriented the whole way. But there is no hope I will understand factor34. I will not even try. ***** Thanks very much. I will be glad to get your help making my module into a class. I don't know what information you might need to understand what I'm trying to do. So, if we get started converting to object oriented format, then we may figure out what Wikipedia articles might be useful. >>> Sorry if I was too harsh anywhere along the way. Feel free to point any of this out and I'll apologize. But this is my honest opinion of the e-mails I've received from you so far. ****** No problem. I value honesty. >>> I don't think this is a good programming project for you to be learning a new language with. Perhaps you should do something simpler. If you'd like some recommendations I'd be happy to give some. *** This project is important to me, independently of my need to learn Python well. >>> Have a good day. -Luke **** Thank you very much. Kermit Rose < kermit at polaris.net > From kermit at polaris.net Thu Aug 17 18:13:29 2006 From: kermit at polaris.net (Kermit Rose) Date: Thu, 17 Aug 2006 12:13:29 -0400 (Eastern Daylight Time) Subject: [Tutor] Actual code that illustrates problem References: Message-ID: <44E495A9.000003.03640@YOUR-4105E587B6> >>> From: Danny Yoo Date: 08/17/06 04:02:35 To: Kermit Rose Cc: Tutor Subject: Re: [Tutor] Actual code that illustrates problem > # def strongfac(z,w): [function body cut] Ok, let's go through this step by step. * What is the intent of strongfac? ******* To try to find factors of z, using w. >>> * What are the inputs? What is 'z', and what is 'w'? ****** z is the number to be factores. w is a "witness", a number that may help find the factors of z. >>> * What are the outputs? What is the return value of strongfac? **** The output is the return value of strongfac. fac = [ x, y, difficulty of factoring z using w] or fac = [0,0,0] if strongfac could not factor z using w. >>> Same questions for fermat(). What are the inputs and outputs, and what's the intent? The input z is the number to be factored. The other inputs are constants which may help in finding factors of z. >>> Get those out and documented, because although I think I can guess at it, I'd rather know that we are sharing the same understanding. **** ???? How? >>> There's a bit of code in strongfac() that's nonsensical from a purely technical sense. For example: > # face = [x,y,0] [some code cut] > # face[0] = x > # face[1] = y > # face[2] = 0 The three assignments to face[0] through face[2] don't do anything effective and clutter the code. *** In fact, I knew that. I inserted it in an attempt to overide the apparent bug that I saw. Sometimes it worked. >>> In fermat(), there are magic numbers: # for j in range(2,3): ^^^^ # for k in range(100): ^^^ These seem pretty arbitrary. Can you explain them? ***** Yes. These are limits of ranges. I had not yet evolved the module to replace the range limits with parameters. >>> The strongfac() function you have is a good case for writing smaller functions: I can not tell where the function really ends. I see that you have several sub-tests, which I'll categorize as: * P-1 * square = square * ... and there's a few others that I can not categorize yet. But I bet you can. Have you considered breaking those out as independent helper functions? ***** I have considered it. >>> Most of us don't have experience with number theory. What people here on the list have is experience with writing software. My experience informs me that the functions you're writing are way too large. They are monolithic and imposing enough that very few people will be able to (or want to!) understand their reasoning. They really cry out to be broken into smaller subtest functions that can be individually understood. ******** Luke has promised to work with me to write my module as a class. Perhaps this will automatically shorten the individual functions. I don't expect that you would need to know much number theory to understand what my program is doing, but I'll be glad to answer any question you may have of it. >>> You mentioned later that: > One of the numbers for which strongfac fails to return factors which it > correctly calculates is 100000000000037 Two questions: * How do you know that it is being "correctly calculated?" **** Part of the process of finding any factor is to divide it into z to get remainder equal to zero. Also when I noticed the problem, I printed it out in strong fac, and also in fermat and then saw the strange behavior of having one value before return and another value after return. >>> * How do you know that your program is doing something wrong? That is, state explicitely to us what you expected the program to do. What is the expected result, in terms of return values, that your function failed to produce? What part of the program --- which particular subtest --- should have returned those values? Where are you looking at? **** I first noticed it when I had Strong fac calculate the factors if possible. If it found factors, it printed out that it had found factors using w, and it printed the value of w. After I noticed that strongfac printed out that it had found factors, but fermat did not pick up those factors, I looked more closely. After I had documented to myself that the return value had changed by the time it got back to fermat, I emailed the Tutor list. >>> Again, you have to assume that we don't know anything about number theory. Things that may seem "obvious" to you are not obvious to this audience. *grin* **** So noted. I had not intended to ask any number theory questions here. Kermit < kermit at polaris.net > From dyoo at hkn.eecs.berkeley.edu Thu Aug 17 18:16:02 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 09:16:02 -0700 (PDT) Subject: [Tutor] All of Kermit's E-Mails In-Reply-To: <44E48FE7.000001.03640@YOUR-4105E587B6> References: <44E40C99.3060901@gmail.com> <44E48FE7.000001.03640@YOUR-4105E587B6> Message-ID: > Suggest an alternative way of transmitting code. Hi Kermit, Try sending the code as a file attachment. It's large enough that we want to make sure it goes through without being messed up, but small enough that it can still be posted to the list. Alternatively, post the code on the web somewhere and send the list a link to the URL. This is preferable for large blocks of code, and your factoring program is large enough that this would also be a good way to share the code with the mailing list. Just as a side note: you may want to investigate a good email client such as Thunderbird if you have spare time. http://www.mozilla.com/thunderbird/ Much of the frustration I've been seeing on this thread deals with IncrediMail's feature set; what it is providing you isn't so well suited for the kind of technical communication that's on this list. > This is obviously a case for ... .dun-dun-dun!.... object-oriented > programming. When you have a collection of functions that all operate > together to create something, you make a Class to contain them. I'm going to have to interject and disagree with Luke here; for Kermit's application, classes are not necessary. Kermit's still trying to learn basic structured programming with functions; I'm not convinced that leaning Kermit toward Object Oriented Programming is going to help matters much. Good luck to you! From singh01 at gmail.com Thu Aug 17 18:14:00 2006 From: singh01 at gmail.com (Nagendra Singh) Date: Thu, 17 Aug 2006 12:14:00 -0400 Subject: [Tutor] Which Book Message-ID: Hi All, I have very little programming experience, I have decided to learn Python..there are tons of material and refernces on the web-pages, can you guys please suggest what is the best way to start or which ONE book which I should follow to start. thanks.. Nagendra From jim at well.com Thu Aug 17 18:34:50 2006 From: jim at well.com (jim stockford) Date: Thu, 17 Aug 2006 09:34:50 -0700 Subject: [Tutor] Which Book In-Reply-To: References: Message-ID: <4DE95732-2E0E-11DB-B3EC-000A95EA5592@well.com> i think it's a mistake to concentrate on one book. Cull responses and pick three books to start with. The benefit is that where one book presents a poor explanation, another will do a good job (and one book will omit certain things that another presents). Also, you'll probably find yourself more often refreshed by turning from one book to another as you proceed. On Aug 17, 2006, at 9:14 AM, Nagendra Singh wrote: > Hi All, > > I have very little programming experience, I have decided to learn > Python..there are tons of material and refernces on the web-pages, can > you guys please suggest what is the best way to start or which ONE > book which I should follow to start. > > thanks.. > > Nagendra > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Thu Aug 17 18:57:40 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 09:57:40 -0700 (PDT) Subject: [Tutor] Actual code that illustrates problem In-Reply-To: <44E495A9.000003.03640@YOUR-4105E587B6> References: <44E495A9.000003.03640@YOUR-4105E587B6> Message-ID: > To try to find factors of z, using w. > >>>> > > * What are the inputs? What is 'z', and what is 'w'? > > ****** > > z is the number to be factores. > > w is a "witness", a number that may help find the factors of z. [My apologies in advance; this message is a bit long.] Hi Kermit, Ok, good. You should add this as a comment to the function's header, so that other people can see this. Here is an example: def strongfac(z, w): """z is the number to be factored. w is a witness that may help find the factors of z. """ ## rest of function body. At the very beginning of the function body, we're allowed to make a string that acts as function documentation. Python programmers expect this kind of "documentation string" at the head of a function, so that they're prepared for what comes next. > * What are the outputs? What is the return value of strongfac? > > The output is the return value of strongfac. > fac = [ x, y, difficulty of factoring z using w] > or > fac = [0,0,0] if strongfac could not factor z using w. Great! Ok, I'm assuming that 'x' and 'y' are two arbitrary factors of 'z'. Are there other properties about x and y that you want to state, such as: "x is always prime", or do we make no guarantees about this? At this point, I'm distilling what you've said into a documentation string: def strongfac(z, w): """strongfac: number number -> [x, y, difficulty] Factors z into two pieces, returning those two pieces as well as the difficulty in factoring z. w is a witness that may help find the factors of z. If no factors can be found, returns [0, 0, 0]. """ ## rest of function body. Does this make sense so far? The point is to make it easy for humans to understand your program. >> # face = [x,y,0] > [some code cut] >> # face[0] = x >> # face[1] = y >> # face[2] = 0 > >> The three assignments to face[0] through face[2] don't do anything >> effective and clutter the code. > > In fact, I knew that. I inserted it in an attempt to overide the > apparent bug that I saw. > > Sometimes it worked. This is a bad sign. It should not have worked. *grin* Next time you hit something mysterious like this, mention it to the list. It'll be a good puzzle for the others here to take a look at. Your code should be as rational as possible. Don't just add code in hoping that it'll fix some problem: try to understand why it's not working first. Look for root causes. >> In fermat(), there are magic numbers: > [cut] >> These seem pretty arbitrary. Can you explain them? > Yes. These are limits of ranges. I had not yet evolved the module to > replace the range limits with parameters. About strongfac(): > Have you considered breaking those out as independent helper functions? > > I have considered it. Consider it more strongly. *grin* Here, I'll help you get started. strongfac() starts off looking something like this: ################################################################# def strongfac(z,w): x = gcd(z,w-1) if x > 1: if x < z: y = z/x return [x,y,0] w2 = (w * w)%z s = ksqrt(w2) if w2 == s * s: if s != w: x = gcd(z,kabs(w2 - s)) if x > 1: if x < z: return [x,y,0] ## other tests ################################################################ (I'm trimming out the print statements just to keep this small.) Those two tests, the P-1 and square=square tests, can be broken out into two separate functions. Let's see what this might look like: ############################################################ def check_p_minus_1(z, w): """Checks to see if z can be factored by the P-1 Method. If so, returns [x, y, 0]; otherwise, returns [0, 0, 0]. """ x = gcd(z,w-1) if x > 1: if x < z: y = z/x return [x,y,0] return [0, 0, 0] ############################################################ This "refactoring" allows us to look at check_p_minus_1's action in isolation, and also makes it easier to ask questions like: what happens if x > z? Is it really possible that the return value from gcd() is bigger than the initial inputs to gcd()? (As far as I understand gcd(), NO!) So this refactoring is useful just as a matter of letting someone just look at a small bit of code and understand it completely. As far as I can understand, check_p_minus_1() should work even if it's simplified to: ########################## def check_p_minus_1(z, w): x = gcd(z, w-1) if x != 1: return [x, z/x, 0] return [0, 0, 0] ########################## Anyway, once we break out the P-1 check out into a separate function, we can rewrite strongfac() to use check_p_minus_1(): ################################ def strongfac(z, w): face = check_p_minus_1(z, w) if face != [0, 0, 0]: return face ## ... other tests here ################################ Can you try this? Can you try breaking out the square=square test in a similar way to how I treated the check_p_minus_1() code? The high level goal here is to turn strongfac() into a very simple looking function. In pseudocode, it'll look something like: ############################ def strongfac(z, w): use check_p_minus_1 test and return if it succeeds use square=square test and return if it succeeds ... ############################ This will make strongfac very regular to read. It'll also make it much easier to trace why one of your return values isn't returning what you want. From kent37 at tds.net Thu Aug 17 19:11:19 2006 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Aug 2006 13:11:19 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: <44E44B0D.7050309@tds.net> Message-ID: <44E4A337.30701@tds.net> Amadeo Bellotti wrote: > Mr. Johnson i was hoping i didnt have to make my whole program into a > loop because its about 900 lines of code and tabbing that would take a > long time If your whole program is 900 lines without a subroutine then you have more problems than just tabbing...really, a program this big should have many functions to divide up the work. Looking for a workaround for poor program structure is not a good solution in the long run; fixing the program structure so it is workable is a better idea. As a practical matter, many editors allow you to select and indent a block, including TextPad and Eclipse, the two editors I usually use. Kent PS please reply to the list, not to me personally. > > > > On 8/17/06, *Kent Johnson* > > wrote: > > Amadeo Bellotti wrote: > > hello is there a way if a condition is not met to restart the whole > > program? for example if and if statement returns true then re start > > the whole program? > > You can probably achieve what you want just by structuring the > program > correctly. My guess you need to use nested loops, something like this: > > while True: > initialize_everything() > while True: > if something_is_wrong(): > break > do_some_work() > > This will do_some_work() until something_is_wrong(), then it will > initialize_everything() and try again. > > If the test for something_is_wrong() is buried deep in the code > you can > break the loop by raising an exception which you catch in the > top-level > loop. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From amadeo.bellotti at gmail.com Thu Aug 17 19:28:56 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Thu, 17 Aug 2006 13:28:56 -0400 Subject: [Tutor] (no subject) In-Reply-To: <44E4A337.30701@tds.net> References: <44E44B0D.7050309@tds.net> <44E4A337.30701@tds.net> Message-ID: thank you Mr. Johnson this is my first program so its a little sloppy. I'm using gedit ill check out the other editors that u have thank you On 8/17/06, Kent Johnson wrote: > > Amadeo Bellotti wrote: > > Mr. Johnson i was hoping i didnt have to make my whole program into a > > loop because its about 900 lines of code and tabbing that would take a > > long time > If your whole program is 900 lines without a subroutine then you have > more problems than just tabbing...really, a program this big should have > many functions to divide up the work. Looking for a workaround for poor > program structure is not a good solution in the long run; fixing the > program structure so it is workable is a better idea. > > As a practical matter, many editors allow you to select and indent a > block, including TextPad and Eclipse, the two editors I usually use. > > Kent > > PS please reply to the list, not to me personally. > > > > > > > > On 8/17/06, *Kent Johnson* > > > wrote: > > > > Amadeo Bellotti wrote: > > > hello is there a way if a condition is not met to restart the > whole > > > program? for example if and if statement returns true then re > start > > > the whole program? > > > > You can probably achieve what you want just by structuring the > > program > > correctly. My guess you need to use nested loops, something like > this: > > > > while True: > > initialize_everything() > > while True: > > if something_is_wrong(): > > break > > do_some_work() > > > > This will do_some_work() until something_is_wrong(), then it will > > initialize_everything() and try again. > > > > If the test for something_is_wrong() is buried deep in the code > > you can > > break the loop by raising an exception which you catch in the > > top-level > > loop. > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/8aadaf96/attachment-0001.html From broek at cc.umanitoba.ca Thu Aug 17 19:37:27 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 17 Aug 2006 13:37:27 -0400 Subject: [Tutor] All of Kermit's E-Mails In-Reply-To: References: <44E40C99.3060901@gmail.com> <44E48FE7.000001.03640@YOUR-4105E587B6> Message-ID: <44E4A957.8000703@cc.umanitoba.ca> Danny Yoo said unto the world upon 17/08/06 12:16 PM: >> Suggest an alternative way of transmitting code. > > Hi Kermit, > Just as a side note: you may want to investigate a good email client such > as Thunderbird if you have spare time. > > http://www.mozilla.com/thunderbird/ > > Much of the frustration I've been seeing on this thread deals with > IncrediMail's feature set; what it is providing you isn't so well suited > for the kind of technical communication that's on this list. Hi Kermit, I'd like to second Danny's suggestion of Thunderbird. It is a very nice client by the same people that produce firefox. I spent a few minutes trying to find out how to set IncrediMail to quote properly. Unfortunately, there is no downloadable documentation (at least not separate from the program itself). Searching for `quote' gave no results :-( So, IncrediMail doesn't quite seem so Incredi to me ;-) For what its worth, the feature set that they promote it with (things such as ``Amazing animations'', ''beautiful email backgrounds'', and the ability to ''add funny animations to your emails'') are all likely to be *very* unwelcome on any python or other technical list. If you really like IncrediMail for your personal email, you might think of installing Thunderbird, getting a gmail account and using the combination to post to technical lists, keeping IncrediMail for messages to friends, etc.[*] (If you need help with any of that, you can write me off-list.) [*] My guess is that after a while, you'll find yourself switching to Tbird. :-) Best wishes, Brian vdB From dyoo at hkn.eecs.berkeley.edu Thu Aug 17 19:39:56 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 10:39:56 -0700 (PDT) Subject: [Tutor] (no subject) In-Reply-To: References: <44E44B0D.7050309@tds.net> <44E4A337.30701@tds.net> Message-ID: > thank you Mr. Johnson this is my first program so its a little sloppy. I'm > using gedit ill check out the other editors that u have thank you More fundamentally, spend some time to learn about functions; they'll address much of the original concerns you had. See any of the tutorials on: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers and almost all of them should talk about what functions are, and how to use them. Best of wishes! From dyoo at hkn.eecs.berkeley.edu Thu Aug 17 19:42:50 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 10:42:50 -0700 (PDT) Subject: [Tutor] Making it easier to discuss programs (fwd) Message-ID: Kermit accidently added a typo to the tutor at python.org address; I'll forward this message to the list for him. ---------- Forwarded message ---------- Date: Thu, 17 Aug 2006 13:38:10 -0400 From: Kermit Rose To: dyoo at hkn.eecs.berkeley.edu, "Luke Paireepinart; tutor"@python.org Subject: Making it easier to discuss programs From" Danny Yoo /*Date:*/ 08/17/06 12:16:16 To: Kermit Rose /*Cc:*/ Luke Paireepinart ; tutor at python.org /*Subject:*/ Re: [Tutor] All of Kermit's E-Mails > Hi Kermit, > Try sending the code as a file attachment. It's large enough that we want > to make sure it goes through without being messed up, but small enough > that it can still be posted to the list. > Alternatively, post the code on the web somewhere and send the list a link > to the URL. This is preferable for large blocks of code, and your > factoring program is large enough that this would also be a good way to > share the code with the mailing list. I will consider making it a permanent part of my web page. After I upload it, I can send you the specific URL for it. > Just as a side note: you may want to investigate a good email client such > as Thunderbird if you have spare time. > http://www.mozilla.com/thunderbird/ > Much of the frustration I've been seeing on this thread deals with > IncrediMail's feature set; what it is providing you isn't so well suited > for the kind of technical communication that's on this list. I've download and installed Thunderbird. I'm sending this message through Thunderbird. I did notice one annoying feature of Thunderbird. When I used the up arrow , intending to go up a line, it went up a page. I got around this by using the mouse cursor to move up a line. Does everyone else, that uses Thunderbird, have to move up a few lines by using the mouse cursor, or is there another way, for example by setting preferences? >From Luke: >> This is obviously a case for ... .dun-dun-dun!.... object-oriented >> programming. When you have a collection of functions that all operate >> together to create something, you make a Class to contain them. > I'm going to have to interject and disagree with Luke here; for Kermit's > application, classes are not necessary. Kermit's still trying to learn > basic structured programming with functions; I'm not convinced that > leaning Kermit toward Object Oriented Programming is going to help matters > much. >Good luck to you! > Thank you. I will consider everyone's suggestions. Those that make sense to me I will try to implement. Kermit < kermit at polaris.net > From kermit at polaris.net Thu Aug 17 19:46:23 2006 From: kermit at polaris.net (Kermit Rose) Date: Thu, 17 Aug 2006 13:46:23 -0400 Subject: [Tutor] Undeliverable Mail In-Reply-To: <10608171338.AA09686@smtp.nettally.com> References: <10608171338.AA09686@smtp.nettally.com> Message-ID: <44E4AB6F.3070904@polaris.net> > From" Danny Yoo > /*Date:*/ 08/17/06 12:16:16 > To: Kermit Rose > /*Cc:*/ Luke Paireepinart ; > tutor at python.org > /*Subject:*/ Re: [Tutor] All of Kermit's E-Mails > > > > > > Hi Kermit, > > > Try sending the code as a file attachment. It's large enough that we > want > > to make sure it goes through without being messed up, but small enough > > that it can still be posted to the list. > > > Alternatively, post the code on the web somewhere and send the list a > link > > to the URL. This is preferable for large blocks of code, and your > > factoring program is large enough that this would also be a good way to > > share the code with the mailing list. > > I will consider making it a permanent part of my web page. > > After I upload it, I can send you the specific URL for it. > > > > Just as a side note: you may want to investigate a good email client such > > as Thunderbird if you have spare time. > > > http://www.mozilla.com/thunderbird/ > > > Much of the frustration I've been seeing on this thread deals with > > IncrediMail's feature set; what it is providing you isn't so well suited > > for the kind of technical communication that's on this list. > > > I've download and installed Thunderbird. > > I'm sending this message through Thunderbird. > > I did notice one annoying feature of Thunderbird. > > When I used the up arrow , intending to go up a line, it went up a page. > > I got around this by using the mouse cursor to move up a line. > > Does everyone else, that uses Thunderbird, have to move up a few lines > by using the mouse cursor, or > > is there another way, > > for example by setting preferences? > > > > > > From Luke: > > > > >> This is obviously a case for ... .dun-dun-dun!.... object-oriented > > >> programming. When you have a collection of functions that all operate > > >> together to create something, you make a Class to contain them. > > > > > I'm going to have to interject and disagree with Luke here; for Kermit's > > > application, classes are not necessary. Kermit's still trying to learn > > > basic structured programming with functions; I'm not convinced that > > > leaning Kermit toward Object Oriented Programming is going to help > matters > > > much. > > > > > > >Good luck to you! > > > > > Thank you. I will consider everyone's suggestions. > > > > Those that make sense to me I will try to implement. > > > > Kermit < kermit at polaris.net > > > > > > > > > > > > > > > > > > > > > From amadeo.bellotti at gmail.com Thu Aug 17 19:47:44 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Thu, 17 Aug 2006 13:47:44 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: <44E44B0D.7050309@tds.net> <44E4A337.30701@tds.net> Message-ID: Thank you again i no im a newbie and really inexperianced but thank you On 8/17/06, Danny Yoo wrote: > > > thank you Mr. Johnson this is my first program so its a little sloppy. > I'm > > using gedit ill check out the other editors that u have thank you > > More fundamentally, spend some time to learn about functions; they'll > address much of the original concerns you had. See any of the tutorials > on: > > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > and almost all of them should talk about what functions are, and how to > use them. > > Best of wishes! > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/ba9e76ea/attachment.htm From amadeo.bellotti at gmail.com Thu Aug 17 19:51:24 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Thu, 17 Aug 2006 13:51:24 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: thank you again but i think i found a way to fix it On 8/17/06, Danny Yoo wrote: > > > > >> > Mr. Yoo im working on a program to write a sudoku puzzle and if > >> > something is wrong with the last row i need to re make the whole > puzzle > >> > over again. > > >> Here's a separate question that's related to the first: can you write a > >> function that asks the user to enter a word, and continues prompting > until > >> the user enters a non-empty word? > > Hi Amadeo, > > > > Yes I can Mr. Yoo, but i dont really want to make my whole program a > > loop. > > Ok. Why not? I'm curious: is there a particular constraint you're trying > to work under, or is it something else? > > Also, I'm not sure what you mean by "whole program". > > > In any case, here's a way to do it without an explicit 'for' or 'while' > loop: > > #################################### > def ask_for_input(): > msg = raw_input("enter a word:") > if msg: > return msg > else: > return ask_for_input() > #################################### > > This would not be the idiomatic way to do this in Python only because of a > technical limitation in the main Python implementation (it doesn't support > "tail call optimization"). > > Still, would this be more acceptable to you, or do you also consider this > a "loop"? > > (Personally, I do. *grin*) > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/ecd70e7d/attachment.html From broek at cc.umanitoba.ca Thu Aug 17 20:05:06 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 17 Aug 2006 14:05:06 -0400 Subject: [Tutor] Which Book In-Reply-To: References: Message-ID: <44E4AFD2.4030701@cc.umanitoba.ca> Nagendra Singh said unto the world upon 17/08/06 12:14 PM: > Hi All, > > I have very little programming experience, I have decided to learn > Python..there are tons of material and refernces on the web-pages, can > you guys please suggest what is the best way to start or which ONE > book which I should follow to start. > > thanks.. > > Nagendra ``Beware the man of one book.'' Saint Thomas Aquinas Free ($ sense) books I read and liked: http://www.ibiblio.org/obp/thinkCSpy/ (easy) http://diveintopython.org/ (less easy) Both of those can be bought in dead-tree form, as can I'd start with the first and if you don't like it, try the next. Either way, multiple books compliment each other. Best, Brian vdB From kermit at polaris.net Thu Aug 17 20:20:51 2006 From: kermit at polaris.net (Kermit Rose) Date: Thu, 17 Aug 2006 14:20:51 -0400 Subject: [Tutor] Actual code that illustrates problem In-Reply-To: References: <44E495A9.000003.03640@YOUR-4105E587B6> Message-ID: <44E4B383.3040504@polaris.net> Danny Yoo wrote: > > > Hi Kermit, > > Ok, good. You should add this as a comment to the function's header, > so that other people can see this. Here is an example: > > def strongfac(z, w): > """z is the number to be factored. > w is a witness that may help find the factors of z. > """ > ## rest of function body. Ok. I've added the suggested documentation for strongfac. > >> * What are the outputs? What is the return value of strongfac? >> >> The output is the return value of strongfac. >> fac = [ x, y, difficulty of factoring z using w] >> or >> fac = [0,0,0] if strongfac could not factor z using w. > > Great! Ok, I'm assuming that 'x' and 'y' are two arbitrary factors of > 'z'. Are there other properties about x and y that you want to state, > such as: "x is always prime", or do we make no guarantees about this? > > Yes. That is correct. There is not any expectation that x and y would be prime unless z just happens to be the product of exactly two primes. > > At this point, I'm distilling what you've said into a documentation > string: > > def strongfac(z, w): > """strongfac: number number -> [x, y, difficulty] > > Factors z into two pieces, returning those two pieces as well as the > difficulty in factoring z. w is a witness that may help find the > factors of z. > > If no factors can be found, returns [0, 0, 0]. > """ > ## rest of function body. > > > Does this make sense so far? The point is to make it easy for humans > to understand your program. > > Yes. I've replaced the previously suggested documentation with the above. > >>> # face = [x,y,0] >> [some code cut] >>> # face[0] = x >>> # face[1] = y >>> # face[2] = 0 >> >>> The three assignments to face[0] through face[2] don't do anything >>> effective and clutter the code. >> >> In fact, I knew that. I inserted it in an attempt to overide the >> apparent bug that I saw. >> >> Sometimes it worked. > > This is a bad sign. It should not have worked. *grin* > > Next time you hit something mysterious like this, mention it to the > list. It'll be a good puzzle for the others here to take a look at. > Your code should be as rational as possible. Don't just add code in > hoping that it'll fix some problem: try to understand why it's not > working first. Look for root causes. > > I agree. I reasoned as follows. The root cause is that Python is not returning the correct value of a list. So before I return the list, I will remind Python what's in the list. > > About strongfac(): > > > > Can you try this? Can you try breaking out the square=square test in > a similar way to how I treated the check_p_minus_1() code? > > > I have followed your suggestion and have done so. > > The high level goal here is to turn strongfac() into a very simple > looking function. In pseudocode, it'll look something like: > > ############################ > def strongfac(z, w): > use check_p_minus_1 test and return if it succeeds > use square=square test and return if it succeeds > ... > ############################ > > This will make strongfac very regular to read. It'll also make it > much easier to trace why one of your return values isn't returning > what you want. > you want. Ok. I will work on splitting up the rest of strong fac into a set of functions. I will attempt to maintain a compromise between having too many levels of function calls and having any one function be too long. Kermit < kermit at polaris.net > From kermit at polaris.net Thu Aug 17 20:38:58 2006 From: kermit at polaris.net (Kermit Rose) Date: Thu, 17 Aug 2006 14:38:58 -0400 Subject: [Tutor] All of Kermit's E-Mails In-Reply-To: <44E4A957.8000703@cc.umanitoba.ca> References: <44E40C99.3060901@gmail.com> <44E48FE7.000001.03640@YOUR-4105E587B6> <44E4A957.8000703@cc.umanitoba.ca> Message-ID: <44E4B7C2.9070905@polaris.net> Brian van den Broek wrote: > > > Hi Kermit, > > I'd like to second Danny's suggestion of Thunderbird. It is a very > nice client by the same people that produce firefox. > > I spent a few minutes trying to find out how to set IncrediMail to > quote properly. Unfortunately, there is no downloadable documentation > (at least not separate from the program itself). Searching > for `quote' > gave no results :-( So, IncrediMail doesn't quite seem so Incredi to > me ;-) I agree. In fact, I never did use any of the proudly proclaimed features of IncrediMail . I used it only because when I accidently clobbered my previous email program Pegasus, IncrediMail was the first replacement email program I found on the internet. > > For what its worth, the feature set that they promote it with (things > such as ``Amazing animations'', ''beautiful email backgrounds'', and > the ability to ''add funny animations to your emails'') are all likely > to be *very* unwelcome on any python or other technical list. > Yes. I simply ignored their special features as long as I could get it to send simple emails. When several of you on the tutor list showed me that IncrediMail caused frustration, I agreed to, and did, switch to Thunderbird. Before Danny's suggestion, I did not know of the existence of Thunderbird. Now if I can only get Thunderbird to quit treating the up and down arrow as a page up or page down, whenever it's at the top line or bottom line of what it thinks is a page. Kermit < kermit at polaris.net > From dyoo at hkn.eecs.berkeley.edu Thu Aug 17 20:58:36 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 11:58:36 -0700 (PDT) Subject: [Tutor] Actual code that illustrates problem In-Reply-To: <44E4B383.3040504@polaris.net> References: <44E495A9.000003.03640@YOUR-4105E587B6> <44E4B383.3040504@polaris.net> Message-ID: >>>> # face = [x,y,0] >>> [some code cut] >>>> # face[0] = x >>>> # face[1] = y >>>> # face[2] = 0 > > I agree. I reasoned as follows. > > The root cause is that Python is not returning the correct value of a list. > > So before I return the list, I will remind Python what's in the list. Hi Kermit, Let's take those last three assignments out: they don't do anything as far as I can see. If you do see a functional change in your program after doing so, I'll be very surprised and intrigued. *grin* The reason for taking them out is to, again, make the program as short and sweet as we can for humans to read. A program's readability matters. > Ok. I will work on splitting up the rest of strong fac into a set of > functions. That sounds good! Definitely keep us up-to-date while you do it. We can give suggestions if we see something that can be simplified, and we want to make sure you don't run into any big ruts as you do this. Once your program is in smaller functional chunks, let's look again at your original problem. I'm hoping that it'll be easier to chase the problem down then. > I will attempt to maintain a compromise between having too many levels > of function calls and having any one function be too long. I wouldn't worry about having heavy function call depth too much yet. If it does turn out to be an issue, reversing the refactoring by inlining should be mechanically easy to do. Good luck to you! From josipl2000 at yahoo.com Thu Aug 17 20:59:11 2006 From: josipl2000 at yahoo.com (josip) Date: Thu, 17 Aug 2006 11:59:11 -0700 (PDT) Subject: [Tutor] banners Message-ID: <20060817185911.69182.qmail@web60811.mail.yahoo.com> Hi, I want to solve thi question, but I don't know how Can someone help? When dot matrix printers were at the height of hi- tech fashion, university students used to create banners with words on them using special characters (e.g. a banner with a student?s initials on it formed out of # characters). Write a Python program that spells out your name or nickname using special characters. Call your program banner.py. * * * * * * * ******** * * * * * * * * * * Thanks! --------------------------------- Get your email and more, right on the new Yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/4bb1f086/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Aug 17 21:15:36 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 12:15:36 -0700 (PDT) Subject: [Tutor] banners In-Reply-To: <20060817185911.69182.qmail@web60811.mail.yahoo.com> References: <20060817185911.69182.qmail@web60811.mail.yahoo.com> Message-ID: On Thu, 17 Aug 2006, josip wrote: > Hi, I want to solve thi question, but I don't know how [homework question cut] This is homework; our policy is not to give much help on this, as it's your work to do. Do you have any specific questions? Otherwise, all I can do here is point you toward introductory Python tutorial material at: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers As far as I can tell, you should be able to solve this problem after reading the first section of any Python tutorial. Try to do this homework problem on your own. Frankly speaking, it is not a difficult problem; it's easy in the sense that you can do this if you honestly read through your course materials. From Mike.Hansen at atmel.com Thu Aug 17 21:58:33 2006 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 17 Aug 2006 13:58:33 -0600 Subject: [Tutor] Which Book Message-ID: <57B026980605A64F9B23484C5659E32E255516@poccso.US.ad.atmel.com> > > Hi All, > > I have very little programming experience, I have decided to learn > Python..there are tons of material and refernces on the web-pages, can > you guys please suggest what is the best way to start or which ONE > book which I should follow to start. > > thanks.. > > Nagendra http://pyfaq.infogami.com/tutor-what-are-some-good-books-on-python From alan.gauld at freenet.co.uk Thu Aug 17 22:55:18 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 17 Aug 2006 21:55:18 +0100 Subject: [Tutor] Low level socket and threading code in python in HUGEwebsites - References: <20060817094846.71075.qmail@web55902.mail.re3.yahoo.com> Message-ID: <004101c6c23f$730fc7a0$0201a8c0@XPpro> Anil, I don't know if this is the kind of thuing they did on reddit, but a few years ago I was working on a large network management system (in C++ FWIW). It was monitoring a network of around 100,000 nodes.To ensure a timely flow of alarm traffic the server had 4 network cards and the code used multi threading and low level comms code to access those 4 IP addresses. But the Sun Sparcstation I was using at the time onlky had one network card and IP address, so the code couldn't run without mmajor invasive debug statements, almosty rendering the threading inactive. So in practice I had to run my code on the server each time I worked on the threaded code. I don;t know if thats the kind of issue he means but it might be an example of the kind of thing that a big web farm might experience. On another project I had similar issues where my workstation didn't have enough RAM to compile (actually link) the code (in C++ again), so although I could edit the code on my local machine I had to do the builds on the server (I only had 128M RAM, the server had 512M - and at the time 128M RAM cost over $400 - 8x16M modules!) HTH, Alan G. ----- Original Message ----- From: "anil maran" To: Sent: Thursday, August 17, 2006 10:48 AM Subject: [Tutor] Low level socket and threading code in python in HUGEwebsites - > What kind of low-level socket and threading code is necessary for a > db > intensive site such as yahoo. How do we use it from python? does > anyone have experience using it > > > http://redditblog.blogspot.com/2005/12/on-lisp.html > >From moving to python by the founders of reddit > > > Because of the low-level socket and threading code we had to write, > reddit would not run on my Mac, and I was always tethered to our > FreeBSD development server. Not being able to program offline is a > pain. > > I would imagine that they aren't just using a database. > most of the "low level socket stuff" I've seen is about setting > timeouts and doing Async IO. > > > > --------------------------------- > Do you Yahoo!? > Get on board. You're invited to try the new Yahoo! Mail Beta. From alan.gauld at freenet.co.uk Thu Aug 17 22:58:24 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 17 Aug 2006 21:58:24 +0100 Subject: [Tutor] web application and database caching technique References: <20060817095504.35141.qmail@web55911.mail.re3.yahoo.com> Message-ID: <004d01c6c23f$e17f6ab0$0201a8c0@XPpro> >i m trying to build a webapplication, i need to cache db records > as it has become very slow the sql queries and retrival > can you guys helpe me out in designing cache structures/ hash > tables for these cases Which database? Most relational databases have caching as a feature that you can configure. It may be that you can simply increase the size of the database cache on the server? A lot easier and usually a lot more efficient and reliable too. Fixing database scaleability issues is rarely best done outside of the database! (Small volume query improvements are another matter entirely!) Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Aug 17 23:27:06 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 14:27:06 -0700 (PDT) Subject: [Tutor] web application and database caching technique In-Reply-To: <004d01c6c23f$e17f6ab0$0201a8c0@XPpro> References: <20060817095504.35141.qmail@web55911.mail.re3.yahoo.com> <004d01c6c23f$e17f6ab0$0201a8c0@XPpro> Message-ID: On Thu, 17 Aug 2006, Alan Gauld wrote: >> i m trying to build a webapplication, i need to cache db records as it >> has become very slow the sql queries and retrival can you guys helpe me >> out in designing cache structures/ hash tables for these cases I second Alan's suggestion: talk to your database administrator and make sure you're not doing something that he or she is responsible for. Offhand, it sounds like you're trying to reinvent database indices. From alan.gauld at freenet.co.uk Thu Aug 17 23:39:30 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 17 Aug 2006 22:39:30 +0100 Subject: [Tutor] Which Book References: Message-ID: <009a01c6c245$9f4d40d0$0201a8c0@XPpro> > I have very little programming experience, I have decided to learn > Python..there are tons of material and references on the web-pages, > can > you guys please suggest what is the best way to start or which ONE > book which I should follow to start. Despite the fact that my tutor is available in paper form I personally don't recommend buying a beginners book - -they quickly become redundant so they are poor value. I would advocate working through the web tutorials (mine if you like:-) and then buy a goood reference book (or two). Maybe a general treference like Python in a Nutshell plus maybe a specialised one in the areas you are interested in (Networks, Databases, Web, GUI, text processing etc) But tastes in books is so subjective its hard to give recommendations. I like generalist books like Programming Python, but many people don't like that one at all. I didn't particularly like Text Processing in Python, even though its the best book in its class - but I just didn't like the style much. But I know others who think its a bit of a masterpiece... A lot will depend on your previoius experience too. For example if you can already program in another language and have a fair grasp of computer science terminology then my book would be a complete waste of time, but if you only have ac minimal experience and don;t know the CS terms my book would be a good choice (he says immodestly!) Best thing if possible is to borrow a copy (from a friend or library) or if there is a web version read a bit there first. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Aug 17 23:50:34 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 17 Aug 2006 22:50:34 +0100 Subject: [Tutor] (no subject) References: <44E44B0D.7050309@tds.net><44E4A337.30701@tds.net> Message-ID: <00ac01c6c247$2b350780$0201a8c0@XPpro> > thank you Mr. Johnson this is my first program so its a little > sloppy. I'm > using gedit ill check out the other editors that u have thank you If you have Python you will have either IDLE or Pythonwin (or both) Both of these will allow block indent/unindent so simply load the code into IDLE to do the indentation.. You can go back to gedit afterwards if you like. But as Kent said you should ideally aimto write the code as functions, each about 5-50 lines long (less than 5 and the advantage is minimal, mor than 50 is just too long - around 12 lines per functoion is a good average IMHO But don't use number of lines as the deciding factor! Divide the code into blocks of code that do something logical that you can describe in a few words (see the comments from Danny to Kermit for examples!) Use those few words to name the function. Consider how to pass key data between the funbctions using parameters and return values. If you don't know how to write functions take a look at the Functions topic of my tutor. HTH, Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Aug 17 23:55:56 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 17 Aug 2006 22:55:56 +0100 Subject: [Tutor] All of Kermit's E-Mails References: <44E40C99.3060901@gmail.com> <44E48FE7.000001.03640@YOUR-4105E587B6> <44E4A957.8000703@cc.umanitoba.ca> Message-ID: <00bc01c6c247$eb439820$0201a8c0@XPpro> > gave no results :-( So, IncrediMail doesn't quite seem so Incredi > to me ;-) I'll second that! I have an elderly friend who loves the net and is on lots of non techie mailing lists. She was waxing lyrical about incredimail to me and was amazed that I didn't use it, it was so good. So I downloaded it and used it for 1 day before giving up in disgust - I couldn't find a single feature that lifted it above even the most basic Outlook Express functions! It's big on frippery and zero on useful functions. (For my purposes at least - my friend still thinks its the best thing out there! - and sends me every message with an HTML attached version for free... :-() Alan G. From alan.gauld at freenet.co.uk Fri Aug 18 00:45:01 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 17 Aug 2006 23:45:01 +0100 Subject: [Tutor] Actual code that illustrates problem References: <44E3E590.000005.00920@YOUR-4105E587B6> Message-ID: <00ea01c6c24e$c7188b70$0201a8c0@XPpro> While others have made good suggestions to clarify the code I thought I'd try to tackle the question of whether we had a bug in Python. Unfortunately the debug output does not come from the code that's posted so its difficult to figure out what's been happening. For example, one apparently good and one "faulty" test: > In strongfac > Found1: x = 53799857 > Found1: y = 1858741 > face = [53799857L, 1858741L, 0] > Found1: factor by strong probable prime test, using witnes > 15306543515214 Note the mis-spelling of witnes(sic) - it does not appear in the code! > Found1: factors are 53799857 1858741 > Found1: returning [53799857L, 1858741L, 0] to fermat routine. > Retrieved from strongfac, face = [0, 0, 0] > In fermat: k = 13 x = 0 y = 0 face = [0, 0, 0] Similarly the first line has the text "factors are 53..." But in the code all instances of "factors are" are followed by the word "by" So I conclude the tests are not from this code. The fault may be in this code but I can't be sure... However a couple of observations might help: > # def strongfac(z,w): > # x = gcd(z,w-1) > # if x > 1: > # if x < z: You can simpliffy this 2 stage test using either boolean operartors: if x > 1 and x < z: OR, almost uniquie to pyhon: if 1 < x < z: That removes one whole layer of indentation. This trick can be applied in many places in the algorithm. Also > # y = z/x > # print "Found factors by P-1 Method as part of > Strong > probable prime test, using witness",w,"." > # print " x = ",x," y = ",y > # return [x,y,0] > # w2 = (w * w)%z > # s = ksqrt(w2) > # if w2 == s * s: > # if s != w: > # x = gcd(z,kabs(w2 - s)) > # if x > 1: > # if x < z: > # print "Found factors by square = square as > part of > Strong probable prime test, using witness",w,"." > # return [x,y,0] If x was not between 1 and z in the first test y is not defined at this point. > # trace = 0 > # t = z - 1 > # a = 0 > # while t%2 == 0: > # t = t/2 > # a = a + 1 > # test = pow(w,t,z) > # if test ==1: > # x = gcd(z,w-1) > # if x > 1: > # if x < z: > # y = z/x > # print " Found factor by Strong probable prime > test, >using withness ",w,"." > # return [x,y,0] > # else: > # x = gcd(test-1,z) > # if x > 1: > # print " " > # print " In strongfac " > # print " Found1: x = ",x You could do all of this with a single print: print "\n In strongfac \nFound1: x = ", x I won't go any further because its pointless given the discrepency between the data and the code, but hopefully those pointers will be helpful in your efforts to tidy the code into separate functions. Alan G. From alan.gauld at freenet.co.uk Fri Aug 18 00:52:16 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 17 Aug 2006 23:52:16 +0100 Subject: [Tutor] banners References: <20060817185911.69182.qmail@web60811.mail.yahoo.com> Message-ID: <011601c6c250$35735180$0201a8c0@XPpro> > As far as I can tell, you should be able to solve this problem after > reading the first section of any Python tutorial. I'm not so sure Danny, figuring out how to draw the letters in the banner is not obvious after having read a hello-world program example. There are some tricky-ish aspects to this one. To the OP, Danny is right that we don't give answers to homeworks but if you give it a try and get stuck come back to us with the code you have written and we might ask you some questions to make you think about the solution... Alan G. From dyoo at hkn.eecs.berkeley.edu Fri Aug 18 01:28:00 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Aug 2006 16:28:00 -0700 (PDT) Subject: [Tutor] banners In-Reply-To: <011601c6c250$35735180$0201a8c0@XPpro> References: <20060817185911.69182.qmail@web60811.mail.yahoo.com> <011601c6c250$35735180$0201a8c0@XPpro> Message-ID: > I'm not so sure Danny, figuring out how to draw the letters in the > banner is not obvious after having read a hello-world program example. > There are some tricky-ish aspects to this one. Hi Alan, It's simpler than that: the homework states that the message is hardcoded to show either josip's name or nickname. If the homework had asked to more generally print a banner of a arbitrary message, that would be harder, but his homework assignment is much easier because of the hardcoded nature of it. If I were to write this, my banner.py would be required to display: ***** * * * * * * * * * ** * on the screen. So the parameterization is based on the person who is writing it. It's very much a program in the same difficulty level as "Hello World", which is why I'm trying very hard not to say more about it. From kermit at polaris.net Fri Aug 18 02:09:37 2006 From: kermit at polaris.net (Kermit Rose) Date: Thu, 17 Aug 2006 20:09:37 -0400 Subject: [Tutor] Actual code that illustrates problem In-Reply-To: <00ea01c6c24e$c7188b70$0201a8c0@XPpro> References: <44E3E590.000005.00920@YOUR-4105E587B6> <00ea01c6c24e$c7188b70$0201a8c0@XPpro> Message-ID: <44E50541.9070609@polaris.net> Alan Gauld wrote: > > While others have made good suggestions to clarify the code I thought > I'd try to tackle the question of whether we had a bug in Python. > > Unfortunately the debug output does not come from the code that's > posted so its difficult to figure out what's been happening. > > For example, one apparently good and one "faulty" test: > >> In strongfac >> Found1: x = 53799857 >> Found1: y = 1858741 >> face = [53799857L, 1858741L, 0] >> Found1: factor by strong probable prime test, using witnes >> 15306543515214 > > Note the mis-spelling of witnes(sic) - it does not appear in the code! > Hmm.... Perhaps I caught that spelling error between the time I sent the attached program file and the time I reran the program to demostrate the error. >> Found1: factors are 53799857 1858741 >> Found1: returning [53799857L, 1858741L, 0] to fermat routine. >> Retrieved from strongfac, face = [0, 0, 0] >> In fermat: k = 13 x = 0 y = 0 face = [0, 0, 0] > > Similarly the first line has the text "factors are 53..." > > But in the code all instances of "factors are" are followed by the > word "by" > > So I conclude the tests are not from this code. The fault may be in > this code > but I can't be sure... > After I've followed the many good suggestions for making my program more concise and readable, I'll re-run it and see if I get the same difficulty at the same z's to factor. I will upload the source to my web page and create a path to it in my index.html file. > However a couple of observations might help: > >> # def strongfac(z,w): >> # x = gcd(z,w-1) >> # if x > 1: >> # if x < z: > > You can simpliffy this 2 stage test using either boolean operartors: > > if x > 1 and x < z: > > OR, almost uniquie to pyhon: > > if 1 < x < z: > Hmmmmmm. A good syntax to remember. > That removes one whole layer of indentation. > This trick can be applied in many places in the algorithm. > > > Also > > >> # y = z/x >> # print "Found factors by P-1 Method as part of Strong >> probable prime test, using witness",w,"." >> # print " x = ",x," y = ",y >> # return [x,y,0] >> # w2 = (w * w)%z >> # s = ksqrt(w2) >> # if w2 == s * s: >> # if s != w: >> # x = gcd(z,kabs(w2 - s)) >> # if x > 1: >> # if x < z: >> # print "Found factors by square = square as >> part of >> Strong probable prime test, using witness",w,"." >> # return [x,y,0] > > If x was not between 1 and z in the first test y is not defined at > this point. > Yep. I should have calculated y = z/x before printing. The syntax checker would have found this as soon as I encountered a z that took me to that point. I'll fix it before re-submitting. >> # trace = 0 >> # t = z - 1 >> # a = 0 >> # while t%2 == 0: >> # t = t/2 >> # a = a + 1 >> # test = pow(w,t,z) >> # if test ==1: >> # x = gcd(z,w-1) >> # if x > 1: >> # if x < z: >> # y = z/x >> # print " Found factor by Strong probable prime test, >> using withness ",w,"." >> # return [x,y,0] >> # else: >> # x = gcd(test-1,z) >> # if x > 1: >> # print " " >> # print " In strongfac " >> # print " Found1: x = ",x > > You could do all of this with a single print: > > print "\n In strongfac \nFound1: x = ", x > uuuuuuuuuh.. Too compact for me. I need to see the logic more spread out. > I won't go any further because its pointless given the discrepency > between > the data and the code, but hopefully those pointers will be helpful in > your > efforts to tidy the code into separate functions. > > Alan G. Also a warning to me to not edit the final output to compensate for faulty programming. Thank you. Kermit < kermit at polaris.net > From amonroe at columbus.rr.com Fri Aug 18 02:22:04 2006 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 17 Aug 2006 20:22:04 -0400 Subject: [Tutor] All of Kermit's E-Mails In-Reply-To: <44E48FE7.000001.03640@YOUR-4105E587B6> References: <44E40C99.3060901@gmail.com> <44E48FE7.000001.03640@YOUR-4105E587B6> Message-ID: <901544463741.20060817202204@columbus.rr.com> > my email program does not insert the > sign like the standard email > program does. "The Bat" mail client does a great job of it, but it's not free. http://www.ritlabs.com/ You might try Pegasus Mail, although I don't remember how well it does it. http://www.pmail.com/ If you were desperate and crazy, you could also try typing the messages in XNews's editor and copy/paste them to your mail. http://xnews.newsguy.com/ Alan From amadeo.bellotti at gmail.com Fri Aug 18 04:22:58 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Thu, 17 Aug 2006 22:22:58 -0400 Subject: [Tutor] Which Book In-Reply-To: <009a01c6c245$9f4d40d0$0201a8c0@XPpro> References: <009a01c6c245$9f4d40d0$0201a8c0@XPpro> Message-ID: A good book is Practical Python by Magnus Lie Hetland. On 8/17/06, Alan Gauld wrote: > > > I have very little programming experience, I have decided to learn > > Python..there are tons of material and references on the web-pages, > > can > > you guys please suggest what is the best way to start or which ONE > > book which I should follow to start. > > Despite the fact that my tutor is available in paper form I personally > don't recommend buying a beginners book - -they quickly become > redundant so they are poor value. I would advocate working through > the web tutorials (mine if you like:-) and then buy a goood reference > book (or two). Maybe a general treference like Python in a Nutshell > plus maybe a specialised one in the areas you are interested in > (Networks, Databases, Web, GUI, text processing etc) > > But tastes in books is so subjective its hard to give recommendations. > I like generalist books like Programming Python, but many people > don't like that one at all. I didn't particularly like Text Processing > in > Python, even though its the best book in its class - but I just didn't > like the style much. But I know others who think its a bit of a > masterpiece... > > A lot will depend on your previoius experience too. > For example if you can already program in another language and > have a fair grasp of computer science terminology then my book > would be a complete waste of time, but if you only have ac minimal > experience and don;t know the CS terms my book would be a good > choice (he says immodestly!) > > Best thing if possible is to borrow a copy (from a friend or library) > or if there is a web version read a bit there first. > > HTH, > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060817/27bb538b/attachment.htm From broek at cc.umanitoba.ca Fri Aug 18 04:38:49 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 17 Aug 2006 22:38:49 -0400 Subject: [Tutor] All of Kermit's E-Mails In-Reply-To: <44E4B7C2.9070905@polaris.net> References: <44E40C99.3060901@gmail.com> <44E48FE7.000001.03640@YOUR-4105E587B6> <44E4A957.8000703@cc.umanitoba.ca> <44E4B7C2.9070905@polaris.net> Message-ID: <44E52839.1010500@cc.umanitoba.ca> Kermit Rose said unto the world upon 17/08/06 02:38 PM: > Now if I can only get Thunderbird to quit treating the up and down arrow > as a page up or page down, > whenever it's at the top line or bottom line of what it thinks is a page. Hi Kermit, I'm glad you've given Thunderbird a try and that you seem to have taken all of the advice in the right spirit. I'm not sure what you mean by a `page' in the context of email. Could you describe the exhibited and expected behaviour in a bit more detail? For now, have you tried clicking in the message body and then using the arrows? (That's all I've got.) You might also what to try the mozilla support forums and knowledge base. Best, Brian From amadeo.bellotti at gmail.com Fri Aug 18 06:06:51 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Fri, 18 Aug 2006 00:06:51 -0400 Subject: [Tutor] (no subject) In-Reply-To: <00ac01c6c247$2b350780$0201a8c0@XPpro> References: <44E44B0D.7050309@tds.net> <44E4A337.30701@tds.net> <00ac01c6c247$2b350780$0201a8c0@XPpro> Message-ID: thank you but IDLE doesnt seem to work on Suse 9.2 do you know a way to fix it? On 8/17/06, Alan Gauld wrote: > > > thank you Mr. Johnson this is my first program so its a little > > sloppy. I'm > > using gedit ill check out the other editors that u have thank you > > If you have Python you will have either IDLE or Pythonwin (or both) > Both of these will allow block indent/unindent so simply load the > code into IDLE to do the indentation.. You can go back to gedit > afterwards if you like. > > But as Kent said you should ideally aimto write the code as > functions, each about 5-50 lines long (less than 5 and the advantage > is minimal, mor than 50 is just too long - around 12 lines per > functoion > is a good average IMHO > > But don't use number of lines as the deciding factor! Divide the code > into blocks of code that do something logical that you can describe > in a few words (see the comments from Danny to Kermit for examples!) > Use those few words to name the function. Consider how to pass key > data between the funbctions using parameters and return values. > > If you don't know how to write functions take a look at the Functions > topic of my tutor. > > HTH, > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060818/43219c5d/attachment.htm From bds at waywood.co.uk Fri Aug 18 06:08:25 2006 From: bds at waywood.co.uk (Barnaby Scott) Date: Fri, 18 Aug 2006 05:08:25 +0100 Subject: [Tutor] Communicating with Win2000 runas.exe In-Reply-To: References: Message-ID: <44E53D39.3020100@waywood.co.uk> Tim Golden wrote: > [Barnaby Scott] > > | So I'm thinking along these lines: > | > | import subprocess > | sp = subprocess.Popen(r'C:\WINNT\SYSTEM32\runas.exe > | /user:administrator > | C:\Program Files\Microsoft Games\Age of Mythology\aom.exe') > | #some sort of code to send the password here... > | #help! > > I *think* -- and I'm happy to be wrong -- that there's > no way you're going to get that password in there. One > place to start looking might be: > > pywinauto - http://pywinauto.pbwiki.com/ > > which lets you automate Windows in general; don't know > how much use it'll be here. > > Alternatively, look into the pywin32 package, and in > particular at the win32security functions which let you > impersonate another user. They're not trivial to use, > but their use has been explained a few times over the > years I think. Mostly by Roger Upole who wrote most if > not all of the Python bindings. > > Here's a post which looks useful; you'll have to hunt > around for others: > > http://groups.google.com/group/comp.lang.python/msg/6bbefb9d4d45d253 > > I suggest you ask this question again on the main > python / python-win32 lists; it's a bit too platform-specific > for the tutor list, I would say. > > TJG Thanks for your tips. In fact the first link you gave put me onto Sendkeys (http://www.rutherfurd.net/python/sendkeys/), which is a prerequisite for pywinauto. In the end that was all I needed. In case anyone else is interested here is my code now (with SendKeys installed): import subprocess, SendKeys subprocess.Popen(r'C:\WINNT\system32\runas.exe /user:administrator "C:\Program Files\Microsoft Games\Age of Mythology\aom.exe"') SendKeys.SendKeys('{PAUSE 1}MyAdministratorPassword{ENTER}') Worth knowing about - might be quite useful for all sorts of things, however 'quick and dirty' it feels as a technique! Thanks again BDS From john at fouhy.net Fri Aug 18 06:15:49 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 18 Aug 2006 16:15:49 +1200 Subject: [Tutor] (no subject) In-Reply-To: References: <44E44B0D.7050309@tds.net> <44E4A337.30701@tds.net> <00ac01c6c247$2b350780$0201a8c0@XPpro> Message-ID: <5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com> On 18/08/06, Amadeo Bellotti wrote: > thank you but IDLE doesnt seem to work on Suse 9.2 do you know a way to fix > it? Why not -- what goes wrong? Is there an error message? -- John. From dkuhlman at rexx.com Fri Aug 18 06:30:55 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 17 Aug 2006 21:30:55 -0700 Subject: [Tutor] (no subject) In-Reply-To: References: <44E44B0D.7050309@tds.net> <44E4A337.30701@tds.net> Message-ID: <20060818043055.GA13819@cutter.rexx.com> On Thu, Aug 17, 2006 at 01:28:56PM -0400, Amadeo Bellotti wrote: > thank you Mr. Johnson this is my first program so its a little sloppy. I'm > using gedit ill check out the other editors that u have thank you > I'd also encourage you to look at other editors, as others on this list have. However, if you like and want to stay with gedit, try to do the following (if you have not already) -- Click on menu item Edit/Preferences, then click on the Plugins tab and enable "Indent lines" plugin. After doing so, there should be Indent and Unindent items in the Edit menu. Highlight a block of code, and try those operations. Indent and Unindent operations will enable you to easily convert top level code into a function: specifically, Indent block and add a "def" statement at the top. I apologize if the above is overly simple-minded and if you are already past this. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From amadeo.bellotti at gmail.com Fri Aug 18 06:50:11 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Fri, 18 Aug 2006 00:50:11 -0400 Subject: [Tutor] (no subject) In-Reply-To: <5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com> References: <44E44B0D.7050309@tds.net> <44E4A337.30701@tds.net> <00ac01c6c247$2b350780$0201a8c0@XPpro> <5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com> Message-ID: Mr. Kuhlman it says python is not configured for tk. but on another note does anyone know how to make a 2d array? On 8/18/06, John Fouhy wrote: > > On 18/08/06, Amadeo Bellotti wrote: > > thank you but IDLE doesnt seem to work on Suse 9.2 do you know a way to > fix > > it? > > Why not -- what goes wrong? Is there an error message? > > -- > John. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060818/30fc2a37/attachment.html From john at fouhy.net Fri Aug 18 07:00:36 2006 From: john at fouhy.net (John Fouhy) Date: Fri, 18 Aug 2006 17:00:36 +1200 Subject: [Tutor] (no subject) In-Reply-To: References: <44E44B0D.7050309@tds.net> <44E4A337.30701@tds.net> <00ac01c6c247$2b350780$0201a8c0@XPpro> <5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com> Message-ID: <5e58f2e40608172200s9a00c59x1ae39c411f86495c@mail.gmail.com> On 18/08/06, Amadeo Bellotti wrote: > Mr. Kuhlman it says python is not configured for tk. > > but on another note does anyone know how to make a 2d array? Are you in charge of your machine, or does someone else administer it? I don't know SUSE very well, but I expect that you can fix this by installing a package called something like "python-tkinter". -- John. From tim.golden at viacom-outdoor.co.uk Fri Aug 18 09:34:46 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 18 Aug 2006 08:34:46 +0100 Subject: [Tutor] Communicating with Win2000 runas.exe Message-ID: [Tim Golden] | > [Barnaby Scott] | > | > | So I'm thinking along these lines: | > | | > | import subprocess | > | sp = subprocess.Popen(r'C:\WINNT\SYSTEM32\runas.exe | > | /user:administrator | > | C:\Program Files\Microsoft Games\Age of Mythology\aom.exe') | > | #some sort of code to send the password here... | > | #help! | > | > I *think* -- and I'm happy to be wrong -- that there's | > no way you're going to get that password in there. One | > place to start looking might be: | > | > pywinauto - http://pywinauto.pbwiki.com/ | > | > which lets you automate Windows in general; don't know | > how much use it'll be here. [Barnaby Scott] | Thanks for your tips. In fact the first link you gave put me onto | Sendkeys (http://www.rutherfurd.net/python/sendkeys/), which is a | prerequisite for pywinauto. In the end that was all I needed. In case | anyone else is interested here is my code now (with SendKeys | installed): Excellent! I'm glad it turned out to be so easy, and thanks for posting the code and the link. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From alan.gauld at freenet.co.uk Fri Aug 18 09:43:34 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 18 Aug 2006 08:43:34 +0100 Subject: [Tutor] banners References: <20060817185911.69182.qmail@web60811.mail.yahoo.com> <011601c6c250$35735180$0201a8c0@XPpro> Message-ID: <000501c6c29a$0d52f350$0201a8c0@XPpro> > It's simpler than that: the homework states that the message is > hardcoded to show either josip's name or nickname. Ah, OK, I hadn't noticed that. In that case yes it can be as simple as hello world. Alan G. From alan.gauld at freenet.co.uk Fri Aug 18 09:47:54 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 18 Aug 2006 08:47:54 +0100 Subject: [Tutor] Actual code that illustrates problem References: <44E3E590.000005.00920@YOUR-4105E587B6> <00ea01c6c24e$c7188b70$0201a8c0@XPpro> <44E50541.9070609@polaris.net> Message-ID: <000701c6c29a$9da92d20$0201a8c0@XPpro> >>> # print " " >>> # print " In strongfac " >>> # print " Found1: x = ",x >> >> You could do all of this with a single print: >> >> print "\n In strongfac \nFound1: x = ", x >> > uuuuuuuuuh.. Too compact for me. > I need to see the logic more spread out. \n is the newline character. An alternative is to use triple quotes: print ''' In strongfac Found1: x = ''',x But that still clutters up the code listing with extra lines that have nothing to do with the algorithm - the main advantage in reducing to one print statement.. Alan G. From alan.gauld at freenet.co.uk Fri Aug 18 09:50:09 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 18 Aug 2006 08:50:09 +0100 Subject: [Tutor] (no subject) References: <44E44B0D.7050309@tds.net> <44E4A337.30701@tds.net> <00ac01c6c247$2b350780$0201a8c0@XPpro> Message-ID: <002b01c6c29a$fa21a960$0201a8c0@XPpro> > thank you but IDLE doesnt seem to work on Suse 9.2 do you know a way > to fix > it? I've only used IDLE on Linux a few times but it certainly works on RedHat, Mandriva and Slackware. And it used to work on Suse 5 - the only time I ever used Suse... What hapens when you try to run IDLE? It may just be a case of fixing a path setting or somesuch. Alan G. From alan.gauld at freenet.co.uk Fri Aug 18 09:53:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 18 Aug 2006 08:53:51 +0100 Subject: [Tutor] All of Kermit's E-Mails References: <44E40C99.3060901@gmail.com><44E48FE7.000001.03640@YOUR-4105E587B6> <901544463741.20060817202204@columbus.rr.com> Message-ID: <003301c6c29b$7264b5c0$0201a8c0@XPpro> > "The Bat" mail client does a great job of it, but it's not free. > http://www.ritlabs.com/ > > You might try Pegasus Mail, although I don't remember how well it > does > it. http://www.pmail.com/ Since you seem to be on a PC plain old Outlook Express will do a better job that Incredimail and its installed by default! It will also allow you to read the gmans news archive of the tutor list which I confess to finding so useful I may be unsubscribing from the digest service and use that instead... Even if you set up a separate free email account for your python emails... Alan G. From anilmrn at yahoo.com Fri Aug 18 10:24:21 2006 From: anilmrn at yahoo.com (anil maran) Date: Fri, 18 Aug 2006 01:24:21 -0700 (PDT) Subject: [Tutor] (no subject) In-Reply-To: <44E44B0D.7050309@tds.net> Message-ID: <20060818082421.48084.qmail@web55912.mail.re3.yahoo.com> it is amazing the amount of knowledge that is being disseminated on this group, guido should love it that u guys are doing such a good job, keep it up guys anil --- Kent Johnson wrote: > Amadeo Bellotti wrote: > > hello is there a way if a condition is not met to > restart the whole > > program? for example if and if statement returns > true then re start > > the whole program? > > You can probably achieve what you want just by > structuring the program > correctly. My guess you need to use nested loops, > something like this: > > while True: > initialize_everything() > while True: > if something_is_wrong(): > break > do_some_work() > > This will do_some_work() until something_is_wrong(), > then it will > initialize_everything() and try again. > > If the test for something_is_wrong() is buried deep > in the code you can > break the loop by raising an exception which you > catch in the top-level > loop. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From anilmrn at yahoo.com Fri Aug 18 10:27:53 2006 From: anilmrn at yahoo.com (anil maran) Date: Fri, 18 Aug 2006 01:27:53 -0700 (PDT) Subject: [Tutor] Low level socket and threading code in python in HUGEwebsites - In-Reply-To: <004101c6c23f$730fc7a0$0201a8c0@XPpro> Message-ID: <20060818082753.75918.qmail@web55907.mail.re3.yahoo.com> thanks alan it is very enlightening can one of you guys who have experience building sites such as yahoo mail and stuff, explain what parts of a webserver needs to be multithreaded thanks --- Alan Gauld wrote: > Anil, > > I don't know if this is the kind of thuing they did > on reddit, but a > few years ago I was working on a large network > management > system (in C++ FWIW). It was monitoring a network of > around > 100,000 nodes.To ensure a timely flow of alarm > traffic the server > had 4 network cards and the code used multi > threading and > low level comms code to access those 4 IP addresses. > > But the Sun Sparcstation I was using at the time > onlky > had one network card and IP address, so the code > couldn't > run without mmajor invasive debug statements, > almosty > rendering the threading inactive. So in practice I > had to > run my code on the server each time I worked on the > threaded code. > > I don;t know if thats the kind of issue he means but > it might be > an example of the kind of thing that a big web farm > might > experience. > > On another project I had similar issues where my > workstation > didn't have enough RAM to compile (actually link) > the code > (in C++ again), so although I could edit the code on > my local > machine I had to do the builds on the server (I only > had > 128M RAM, the server had 512M - and at the time > 128M RAM cost over $400 - 8x16M modules!) > > HTH, > > Alan G. > > ----- Original Message ----- > From: "anil maran" > To: > Sent: Thursday, August 17, 2006 10:48 AM > Subject: [Tutor] Low level socket and threading code > in python in > HUGEwebsites - > > > > What kind of low-level socket and threading code > is necessary for a > > db > > intensive site such as yahoo. How do we use it > from python? does > > anyone have experience using it > > > > > > > http://redditblog.blogspot.com/2005/12/on-lisp.html > > >From moving to python by the founders of reddit > > > > > > Because of the low-level socket and threading code > we had to write, > > reddit would not run on my Mac, and I was always > tethered to our > > FreeBSD development server. Not being able to > program offline is a > > pain. > > > > I would imagine that they aren't just using a > database. > > most of the "low level socket stuff" I've seen is > about setting > > timeouts and doing Async IO. > > > > > > > > --------------------------------- > > Do you Yahoo!? > > Get on board. You're invited to try the new Yahoo! > Mail Beta. > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From anilmrn at yahoo.com Fri Aug 18 10:29:29 2006 From: anilmrn at yahoo.com (anil maran) Date: Fri, 18 Aug 2006 01:29:29 -0700 (PDT) Subject: [Tutor] web application and database caching technique In-Reply-To: <004d01c6c23f$e17f6ab0$0201a8c0@XPpro> Message-ID: <20060818082929.80856.qmail@web55906.mail.re3.yahoo.com> Postgresql 8 and python 2.4 let me find out how to do the caching on db, thanks if you have other pointers on how to cache db in python pls let me know --- Alan Gauld wrote: > >i m trying to build a webapplication, i need to > cache db records > > as it has become very slow the sql queries and > retrival > > can you guys helpe me out in designing cache > structures/ hash > > tables for these cases > > Which database? Most relational databases have > caching as a > feature that you can configure. It may be that you > can simply > increase the size of the database cache on the > server? > > A lot easier and usually a lot more efficient and > reliable too. > > Fixing database scaleability issues is rarely best > done > outside of the database! (Small volume query > improvements > are another matter entirely!) > > Alan G. > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From anilmrn at yahoo.com Fri Aug 18 10:33:04 2006 From: anilmrn at yahoo.com (anil maran) Date: Fri, 18 Aug 2006 01:33:04 -0700 (PDT) Subject: [Tutor] Twisted Medusa Athena frameworks Message-ID: <20060818083304.2134.qmail@web55913.mail.re3.yahoo.com> hi guys i m trying to create a simple site, and on certain event triggers the server or python program needs to send out messages to the site. i m tyring to accomplish it using twisted or medusa or Does any one have experience using it or the asyncore module in python please help thanks a ton anil __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at freenet.co.uk Fri Aug 18 10:38:20 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 18 Aug 2006 09:38:20 +0100 Subject: [Tutor] 2D array question [was (no subject)] References: <44E44B0D.7050309@tds.net><44E4A337.30701@tds.net><00ac01c6c247$2b350780$0201a8c0@XPpro><5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com> Message-ID: <006c01c6c2a1$c1fa3000$0201a8c0@XPpro> > Mr. Kuhlman it says python is not configured for tk. Gaarrgh! Why do linux distros do this? Stooopid... You will need to fetch another version of Python with Tk support built in. Its a compile time option so you can either fetch the source an build it yourself or find a Suse package with Tk support already selected. Its really stupid for Suse to do that, it only saves a tiny amount of space and means you can't run any programs based on Tkinter... > but on another note does anyone know how to make a 2d array? This should probably be a separate post. Also can you change the subject line in your posts so people can fiind the thread easily. I've changed it on this one to pick up the 2D array issue.... A 2D array is just a table. There are several ways to do that in Python but the easiest is just a list of lists: Think of a chess game as an example where the boars is represented by an 8x8 2D array: chessBoard = [ [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0] ] Now you can access the third row, 4th column with: chessBoard[2][3] # remember zero indexing! Is that clear? You can also use tuples similarly, or nested dictionaries. A lot will depend on the data you are storing and how you want to access it. Finally you can create a Class with bespoke methods to more closely model your problem, but the class will usaually have one of the above solutions internally anyhow! HTH. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From anilmrn at yahoo.com Fri Aug 18 10:56:53 2006 From: anilmrn at yahoo.com (anil maran) Date: Fri, 18 Aug 2006 01:56:53 -0700 (PDT) Subject: [Tutor] editors Message-ID: <20060818085653.38477.qmail@web55902.mail.re3.yahoo.com> what editors do you guys use? emacs vi? xemacs are there any plugins to configure autocomplete, i want something to do good autocomplete such as showing what type of arguments are available etc thanks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From matthew at CuneiformSoftware.com Fri Aug 18 11:41:47 2006 From: matthew at CuneiformSoftware.com (Matthew Webber) Date: Fri, 18 Aug 2006 10:41:47 +0100 Subject: [Tutor] editors In-Reply-To: <20060818085653.38477.qmail@web55902.mail.re3.yahoo.com> Message-ID: <002901c6c2aa$885fb3c0$0200a8c0@kookaburra> I use Eclipse (www.eclipse.org) with the pydev plugin (pydev.sourceforge.net). Eclipse is written in Java (you need the JVM to run it, and a decent amount of memory) and was originally intended for Java development (that's what most of the docs reflect). It now has plugins available for other languages. It also has am SVN plugin. Matthew -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of anil maran Sent: 18 August 2006 09:57 To: tutor at python.org Subject: [Tutor] editors what editors do you guys use? emacs vi? xemacs are there any plugins to configure autocomplete, i want something to do good autocomplete such as showing what type of arguments are available etc thanks From kent37 at tds.net Fri Aug 18 12:52:06 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Aug 2006 06:52:06 -0400 Subject: [Tutor] Actual code that illustrates problem In-Reply-To: <000701c6c29a$9da92d20$0201a8c0@XPpro> References: <44E3E590.000005.00920@YOUR-4105E587B6> <00ea01c6c24e$c7188b70$0201a8c0@XPpro> <44E50541.9070609@polaris.net> <000701c6c29a$9da92d20$0201a8c0@XPpro> Message-ID: <44E59BD6.1080308@tds.net> Alan Gauld wrote: >>>> # print " " >>>> # print " In strongfac " >>>> # print " Found1: x = ",x >>>> >>> You could do all of this with a single print: >>> >>> print "\n In strongfac \nFound1: x = ", x >>> >>> >> uuuuuuuuuh.. Too compact for me. >> I need to see the logic more spread out. >> > > \n is the newline character. > An alternative is to use triple quotes: > > print ''' > In strongfac > Found1: x = ''',x > > But that still clutters up the code listing with extra lines that > have nothing to do with the algorithm - the main advantage in > reducing to one print statement.. This is obviously a matter of personal preference. I prefer the longer form as well - I usually use a separate print statement for each line of output. I would say it has everything to do with the function, if not the algorithm - it clearly represents the form the output will take. Kent From kent37 at tds.net Fri Aug 18 12:56:55 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Aug 2006 06:56:55 -0400 Subject: [Tutor] 2D array question [was (no subject)] In-Reply-To: <006c01c6c2a1$c1fa3000$0201a8c0@XPpro> References: <44E44B0D.7050309@tds.net><44E4A337.30701@tds.net><00ac01c6c247$2b350780$0201a8c0@XPpro><5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com> <006c01c6c2a1$c1fa3000$0201a8c0@XPpro> Message-ID: <44E59CF7.1070407@tds.net> Alan Gauld wrote: >> but on another note does anyone know how to make a 2d array? >> > > A 2D array is just a table. There are several ways to do that > in Python If you need high-performance arrays you should look at numpy: http://numpy.scipy.org/ Kent From alan.gauld at freenet.co.uk Fri Aug 18 12:57:51 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 18 Aug 2006 11:57:51 +0100 Subject: [Tutor] editors References: <20060818085653.38477.qmail@web55902.mail.re3.yahoo.com> Message-ID: <001c01c6c2b5$277b50e0$0201a8c0@XPpro> > what editors do you guys use? > > emacs > vi? > xemacs Yes. All of the above Also ed, ex, Axe, xedit, pine, Scite, IPFS, EDT, Notepad, Textpad, etc etc. But the bulk of my Python editing these days is done on either Pythonwin/Scite or vim. The more I use Pyhonwin the more I prefer it to IDLE, but for serious editing sessions I still fall back on vim. But put me on a Unix box and its emacs for big edits vim for quick stuff - I'm not sure why the difference! But editor preferences are almost as deeply personal as language preferences. > are there any plugins to configure autocomplete, i > want something to do good autocomplete such as showing > what type of arguments are available etc Both IDLE and Pythonwin do those things. I assume other IDEs like Blackadder, Kimono and Eclipse will also do so. BTW One feature of Scite I like is the tabbed windows, however despite the fact that Pythonwin uses the Scinbtilla/Scite editor I can't find a way to turn that on in Pythonwin - does anyone else know? Alan G From kent37 at tds.net Fri Aug 18 13:18:35 2006 From: kent37 at tds.net (Kent Johnson) Date: Fri, 18 Aug 2006 07:18:35 -0400 Subject: [Tutor] Low level socket and threading code in python in HUGEwebsites - In-Reply-To: <20060818082753.75918.qmail@web55907.mail.re3.yahoo.com> References: <20060818082753.75918.qmail@web55907.mail.re3.yahoo.com> Message-ID: <44E5A20B.8060400@tds.net> anil maran wrote: > thanks alan it is very enlightening > can one of you guys who have experience building sites > such as yahoo mail and stuff, explain what parts of a > webserver needs to be multithreaded Generally you need a thread or process for each HTTP request, otherwise you will process requests serially (one at a time) which severely limits the number of concurrent users you can have. Kent From tiagosaboga at terra.com.br Fri Aug 18 14:47:53 2006 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Fri, 18 Aug 2006 09:47:53 -0300 Subject: [Tutor] man pages parser Message-ID: <200608180947.54028.tiagosaboga@terra.com.br> Hi! I'm working on a front-end to various unix command-line utilities, and I want to be able to retrieve informations from man pages, specially existing options and their help strings. Do you know a good way to handle this? I could parse directly the troff sources (is there already a parser for that?), the resulting man pages, or I could first translate it to docbook (with doclifter) or html (mantohtml) and than use a xml or html parser. All these options require a good amount of time for me, as I don't know any of the parsers, and I don't know the languages, except for html. It's why I'm asking here first if there is a better solution or other advices... Thanks. Tiago Saboga. From dyoo at hkn.eecs.berkeley.edu Fri Aug 18 16:11:31 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 18 Aug 2006 07:11:31 -0700 (PDT) Subject: [Tutor] man pages parser In-Reply-To: <200608180947.54028.tiagosaboga@terra.com.br> References: <200608180947.54028.tiagosaboga@terra.com.br> Message-ID: > to be able to retrieve informations from man pages, specially existing > options and their help strings. Do you know a good way to handle this? I > could parse directly the troff sources (is there already a parser for that?) Hi Tiago, Someone else has done this already. *grin* Check out ESR's doclifter: http://www.catb.org/~esr/doclifter/ From kermit at polaris.net Fri Aug 18 17:14:43 2006 From: kermit at polaris.net (Kermit Rose) Date: Fri, 18 Aug 2006 11:14:43 -0400 Subject: [Tutor] Actual code that illustrates problem In-Reply-To: <000701c6c29a$9da92d20$0201a8c0@XPpro> References: <44E3E590.000005.00920@YOUR-4105E587B6> <00ea01c6c24e$c7188b70$0201a8c0@XPpro> <44E50541.9070609@polaris.net> <000701c6c29a$9da92d20$0201a8c0@XPpro> Message-ID: <44E5D963.5080400@polaris.net> Alan Gauld wrote: > >>>> # print " " >>>> # print " In strongfac " >>>> # print " Found1: x = ",x >>> >>> You could do all of this with a single print: >>> >>> print "\n In strongfac \nFound1: x = ", x >>> >> uuuuuuuuuh.. Too compact for me. >> I need to see the logic more spread out. > > \n is the newline character. > > Ah. Thanks. Explaining the backslash n helped me understand. I will use the backslash n to reduce lines of print statements. Kermit < kermit at polaris.net > From artificiallystupid at yahoo.com Fri Aug 18 17:35:29 2006 From: artificiallystupid at yahoo.com (Johnston Jiaa) Date: Fri, 18 Aug 2006 08:35:29 -0700 (PDT) Subject: [Tutor] first programming project Message-ID: <20060818153529.71944.qmail@web50404.mail.yahoo.com> I have read through many beginner texts on programming and believe myself to be fairly decent at python, but I have no idea how to do anything worthwhile. I understand that before coding a project it's best to design it and write some pseudocode first. I want to create a fun GUI assignment manager. I read about the Tkinter toolkit and would like to use it to write my program. I made a list of features: - root window will be split into three sections: categories, assignments, and an animated creature that responds to actions - assignments will have three attributes: priority, points (grade points for completeness and creative points for how interestingly assignment was done), dates (assigned, completed) - sub-assignments can be added to assignments to break it up into steps - each assignment will fit into a marking period category with two averages (grade average and creative average) - grade average is the percentage found by dividing points earned by total possible points - creature will have two statuses (hunger status, mood status) - hunger status effected by grade points and averages - mood status effected by creative points and averages - each time assignment completed, food appears in creature section and user may feed it or store it in a bin (food more nourishing for higher-point assignments) - increments of creative points (maybe for every 10?) add mini-games to play with creature That's the general idea of my program. I have never written a real program before, am I missing any steps? Is there something I am missing from having this be a complete program? Any help at all is greatly appreciated. Johnston Jiaa __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jim at well.com Fri Aug 18 18:04:01 2006 From: jim at well.com (jim stockford) Date: Fri, 18 Aug 2006 09:04:01 -0700 Subject: [Tutor] first programming project In-Reply-To: <20060818153529.71944.qmail@web50404.mail.yahoo.com> References: <20060818153529.71944.qmail@web50404.mail.yahoo.com> Message-ID: <29ED1D28-2ED3-11DB-B3EC-000A95EA5592@well.com> i hope this helps: what a fun idea! do it! my way is to do a bad job fast then re-visit the plans and reimplement and test and re-visit and reimplement and test and.... consider writing a main program that does the primary work and outputs as text-only. maybe then create four classes: the master, which gets input and drives the other three: the category, the assignment, and the creature. Or you could implement functions instead of classes. On Aug 18, 2006, at 8:35 AM, Johnston Jiaa wrote: > I have read through many beginner texts on programming > and believe myself to be fairly decent at python, but > I have no idea how to do anything worthwhile. I > understand that before coding a project it's best to > design it and write some pseudocode first. I want to > create a fun GUI assignment manager. I read about the > Tkinter toolkit and would like to use it to write my > program. I made a list of features: > > - root window will be split into three sections: > categories, assignments, and an animated creature that > responds to actions > > - assignments will have three attributes: priority, > points (grade points for completeness and creative > points for how interestingly assignment was done), > dates (assigned, completed) > - sub-assignments can be added to assignments to break > it up into steps > - each assignment will fit into a marking period > category with two averages (grade average and creative > average) > - grade average is the percentage found by dividing > points earned by total possible points > > - creature will have two statuses (hunger status, mood > status) > - hunger status effected by grade points and averages > - mood status effected by creative points and averages > - each time assignment completed, food appears in > creature section and user may feed it or store it in a > bin (food more nourishing for higher-point > assignments) > - increments of creative points (maybe for every 10?) > add mini-games to play with creature > > That's the general idea of my program. I have never > written a real program before, am I missing any steps? > Is there something I am missing from having this be a > complete program? Any help at all is greatly > appreciated. > > Johnston Jiaa > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From amadeo.bellotti at gmail.com Fri Aug 18 18:04:20 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Fri, 18 Aug 2006 12:04:20 -0400 Subject: [Tutor] (no subject) In-Reply-To: <002b01c6c29a$fa21a960$0201a8c0@XPpro> References: <44E44B0D.7050309@tds.net> <44E4A337.30701@tds.net> <00ac01c6c247$2b350780$0201a8c0@XPpro> <002b01c6c29a$fa21a960$0201a8c0@XPpro> Message-ID: Mr. Gauld I run it from termainal on GNOME and it says "** IDLE can't import Tkinter. Your Python may not be configured for Tk. **" and Yea I am Administrator this is my Home computer after all im only 15. On 8/18/06, Alan Gauld wrote: > > > > thank you but IDLE doesnt seem to work on Suse 9.2 do you know a way > > to fix > > it? > > I've only used IDLE on Linux a few times but it certainly works > on RedHat, Mandriva and Slackware. And it used to work on > Suse 5 - the only time I ever used Suse... > > What hapens when you try to run IDLE? It may just be a case of > fixing a path setting or somesuch. > > Alan G. > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060818/61012bb3/attachment.html From amadeo.bellotti at gmail.com Fri Aug 18 18:06:39 2006 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Fri, 18 Aug 2006 12:06:39 -0400 Subject: [Tutor] 2D array question [was (no subject)] In-Reply-To: <006c01c6c2a1$c1fa3000$0201a8c0@XPpro> References: <44E44B0D.7050309@tds.net> <44E4A337.30701@tds.net> <00ac01c6c247$2b350780$0201a8c0@XPpro> <5e58f2e40608172115v5f05dcf4t3b12a9d91efd667d@mail.gmail.com> <006c01c6c2a1$c1fa3000$0201a8c0@XPpro> Message-ID: thank you so much Mr. Gauld that really helped On 8/18/06, Alan Gauld wrote: > > > Mr. Kuhlman it says python is not configured for tk. > > Gaarrgh! Why do linux distros do this? Stooopid... > > You will need to fetch another version of Python with > Tk support built in. Its a compile time option so you can > either fetch the source an build it yourself or find a Suse > package with Tk support already selected. > > Its really stupid for Suse to do that, it only saves a tiny > amount of space and means you can't run any programs > based on Tkinter... > > > but on another note does anyone know how to make a 2d array? > > This should probably be a separate post. > > Also can you change the subject line in your posts so people > can fiind the thread easily. I've changed it on this one to pick > up the 2D array issue.... > > A 2D array is just a table. There are several ways to do that > in Python but the easiest is just a list of lists: Think of a chess > game as an example where the boars is represented by > an 8x8 2D array: > > chessBoard = [ > [0,0,0,0,0,0,0,0], > [0,0,0,0,0,0,0,0], > [0,0,0,0,0,0,0,0], > [0,0,0,0,0,0,0,0], > [0,0,0,0,0,0,0,0], > [0,0,0,0,0,0,0,0], > [0,0,0,0,0,0,0,0], > [0,0,0,0,0,0,0,0] > ] > > Now you can access the third row, 4th column with: > > chessBoard[2][3] # remember zero indexing! > > Is that clear? > > You can also use tuples similarly, or nested dictionaries. > A lot will depend on the data you are storing and how you > want to access it. > > Finally you can create a Class with bespoke methods to > more closely model your problem, but the class will usaually > have one of the above solutions internally anyhow! > > HTH. > > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20060818/bb6189a4/attachment.htm From alan.gauld at freenet.co.uk Fri Aug 18 20:05:39 2006 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 18 Aug 2006 19:05:39 +0100 Subject: [Tutor] man pages parser References: <200608180947.54028.tiagosaboga@terra.com.br> Message-ID: <002b01c6c2f0$ea0e8ec0$0201a8c0@XPpro> > to be able to retrieve informations from man pages, specially > existing > options and their help strings. I'd actually try parsing the man page sources. They are already in a layout language so finding the options should be easy - there is a man macro for that I believe. But i've never tried it! If that turns out to be harder than I think, then an XML option would be next best. But i donlt know of a man2xml command. Finally the man2html route is definitely possible and BeautifulSoup should be able to find the option tags for you - but it may find many others besides so you might need some clever selection criteria. But the parsing at least should be done for you. > could parse directly the troff sources (is there already a parser > for that?), I don;t know if there is a parser, but ISTR there is a specific option tag in the man macros for command options so it should be easy to find and extract the data by looking for .OP or whatever the tag is. The good news is that troff macros are nearly always located at the marging and start with a dot so they are easy to locate using simple regex. Actually I just had a quick look and its not so good after all, the format seems to be .SH Options ......text in here .B
 Utility: