From steve at pearwood.info Tue Jan 1 06:07:38 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Jan 2013 16:07:38 +1100 Subject: [Tutor] Limitation of int() in converting strings In-Reply-To: References: <50D50E32.1080706@pearwood.info> Message-ID: <50E26F1A.1020909@pearwood.info> On 23/12/12 04:38, Oscar Benjamin wrote: > On 22 December 2012 01:34, Steven D'Aprano wrote: >> On 18/12/12 01:36, Oscar Benjamin wrote: >> >>> I think it's unfortunate that Python's int() function combines two >>> distinct behaviours in this way. In different situations int() is used >>> to: >>> 1) Coerce an object of some type other than int into an int without >>> changing the value of the integer that the object represents. >> >> The second half of the sentence (starting from "without changing") is not >> justified. You can't safely make that assumption. All you know is that >> calling int() on an object is intended to convert the object to an int, >> in whatever way is suitable for that object. In some cases, that will >> be numerically exact (e.g. int("1234") will give 1234), in other cases it >> will not be. > > If I was to rewrite that sentence would replace the word 'integer' > with 'number' but otherwise I'm happy with it. Your reference to > "numerically exact" shows that you understood exactly what I meant. Yes. And it is a demonstrable fact that int is *not* intended to coerce objects to int "without changing the value of the number", because changing the value of the number is precisely what int() does, in some circumstances. If you would like to argue that it would have been better if int did not do this, then I might even agree with you. There is certainly precedence: if I remember correctly, you cannot convert floating point values to integers directly in Pascal, you first have to truncate them to an integer-valued float, then convert. # excuse my sloppy Pascal syntax, it has been a few years var i: integer; x: real; begin i = integer(trunc(x)); end; So I'm not entirely against the idea that Python should have had separate int() and trunc() functions, with int raising an exception on (non-whole number?) floats. But back to Python as it actually is, rather than how it might have been. There's no rule that int() must be numerically lossless. It is lossless with strings, and refuses to convert strings-that-look-like-floats to ints. And that makes sense: in an int, the "." character is just as illegal as the characters "k" or "&" or "?", int will raise on "123k456", so why wouldn't it raise on "123.456"? But that (good, conservative) design decision isn't required or enforced. Hence my reply that you cannot safely make the assumption that int() on a non-numeric type will be numerically exact. >>> 2) Round an object with a non-integer value to an integer value. >> >> >> int() does not perform rounding (except in the most generic sense that any >> conversion from real-valued number to integer is "rounding"). That is what >> the round() function does. int() performs truncating: it returns the >> integer part of a numeric value, ignoring any fraction part: > > I was surprised by your objection to my use of the word "rounding" > here. So I looked it up on Wikipedia: > http://en.wikipedia.org/wiki/Rounding#Rounding_to_integer > > That section describes "round toward zero (or truncate..." which is > essentially how I would have put it, and also how you put it below: Well, yes. I explicitly referred to the generic sense where any conversion from real-valued to whole number is "rounding". But I think that it is a problematic, ambiguous term that needs qualification: * sometimes truncation is explicitly included as a kind of rounding; * sometimes truncation is used in opposition to rounding. For example, I think that in everyday English, most people would be surprised to hear you describe "rounding 9.9999999 to 9". In the absence of an explicit rounding direction ("round down", "round up"), some form of "round to nearest" is assumed in everyday English, and as such is used in contrast to merely cutting off whatever fraction part is there (truncation). Hence the need for qualification. >> So you shouldn't think of int(number) as "convert number to an int", since >> that is ambiguous. There are at least six common ways to convert arbitrary >> numbers to ints: > > This is precisely my point. I would prefer if if int(obj) would fail > on non-integers leaving me with the option of calling an appropriate > rounding function. After catching RoundError (or whatever) you would > know that you have a number type object that can be passed to round, > ceil, floor etc. Well, I guess that comes down to the fact that Python is mostly aimed at mathematically and numerically naive users who would be scared off at a plethora of rounding modes :-) >> Python provides truncation via the int and math.trunc functions, floor and >> ceiling via math.floor and math.ceil, and round to nearest via round. >> In Python 2, ties are rounded up, which is biased; in Python 3, the >> unbiased banker's rounding is used. > > I wasn't aware of this change. Thanks for that. Actually, I appear to have been wrong: in Python 2, ties are rounded away from zero rather than up. Positive arguments round up, negative arguments round down: py> round(1.5), round(2.5) (2.0, 3.0) py> round(-1.5), round(-2.5) (-2.0, -3.0) >> Instead, you should consider int(number) to be one of a pair of functions, >> "return integer part", "return fraction part", where unfortunately the >> second function isn't provided directly. In general though, you can get >> the fractional part of a number with "x % 1". For floats, math.modf also >> works. > > Assuming that you know you have an object that supports algebraic > operations in a sensible way then this works, although the > complementary function for "x % 1" would be "x // 1" or > "math.floor(x)" rather than "int(x)". Again, I was mistaken. x%1 is not suitable to get the fraction part of a number in Python: it returns the wrong result for negative values. You need math.modf: py> x = -99.25 py> x % 1 # want -0.25 0.75 py> math.modf(x) (-0.25, -99.0) -- Steven From steve at pearwood.info Tue Jan 1 07:29:48 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Jan 2013 17:29:48 +1100 Subject: [Tutor] how to struct.pack a unicode string? In-Reply-To: References: <1354293788.96740.YahooMailNeo@web163803.mail.gq1.yahoo.com> <50B9B22F.3080605@pearwood.info> <1354455292.11754.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: <50E2825C.1040105@pearwood.info> I'm digging out an old email which I saved as a draft almost a month ago but never got around to sending, because I think the new Unicode implementation in Python 3.3 is one of the coolest things ever. On 03/12/12 16:56, eryksun wrote: > CPython 3.3 has a new implementation that angles for the best of all > worlds, opting for a 1-byte, 2 byte, or 4-byte representation > depending on the maximum code in the string. The internal > representation doesn't use surrogates, so there's no more narrow vs > wide build distinction. The consequences of this may not be clear to some people. Here's the short version: The full range of 1114112 Unicode code points (informally "characters") do not fit the space available to two bytes. Two bytes can cover the values 0 through 65535 (0xFFFF in hexadecimal), while Unicode code points go up to 1114112 (0x10FFFF). So what to do? There are three obvious solutions: 1 If you store each character using four bytes, you can cover the entire Unicode range. The downside is that for English speakers and ASCII users, strings will use four times as much memory as you expect: e.g. the character 'A' will be stored as 0x00000041 (four bytes instead of one in pure ASCII). When you compile the Python interpreter, you can set an option to do this. This is called a "wide" build. 2 Since "wide builds" use so much extra memory for the average ASCII string, hardly anyone uses them. Instead, the default setting for Python is a "narrow" build: characters use only two bytes, which is enough for most common characters. E.g. e.g. the character 'A' will be stored as 0x0041. The less common characters can't be represented as a single two- byte character, so Unicode defines a *pair of characters* to indicate the extra (hopefully rare) characters. These are called "surrogate pairs". For example, Unicode code point 0x10859 is too large for a pair of bytes. So in Python 3.2, you get this: py> c = chr(0x10859) # IMPERIAL ARAMAIC NUMBER TWO py> print(len(c), [hex(ord(x)) for x in c]) 2 ['0xd802', '0xdc59'] Notice that instead of getting a single character, you get two characters. Your software is then supposed to manually check for such surrogate pairs. Unfortunately nobody does, because that's complicated and slow, so people end up with code that cannot handle strings with surrogate pairs safely. It's easy to break the pair up and get invalid strings that don't represent any actual character. In other words, Python *wide builds* use too much memory, and *narrow builds* are buggy and let you break strings. Oops. 3 Python 3.3 takes a third option: when you create a string object, the compiler analyses the string, works out the largest character used, and only then decides how many bytes per character to use. So in Python 3.3, the decision to use "wide" strings (4 bytes per character) or "narrow" strings (2 bytes) is no longer made when compiling the Python interpreter. It is made per string, with the added bonus that purely ASCII or Latin1 strings can use 1 byte per character. That means, no more surrogate pairs, and every Unicode character is now a single character: py> c = chr(0x10859) # Python 3.3 py> print(len(c), [ord(x) for x in c]) 1 ['0x10859'] and a good opportunity for large memory savings. How big are the memory savings? They can be substantial. Purely Latin1 strings (so-called "extended ASCII") can be close to half the size of a narrow build: [steve at ando ~]$ python3.2 -c "import sys; print(sys.getsizeof('?'*1000))" 2030 [steve at ando ~]$ python3.3 -c "import sys; print(sys.getsizeof('?'*1000))" 1037 I don't have a wide build to test, but the size would be roughly twice as big again, about 4060 bytes. But more important than the memory savings, it means that for the first time Python's handling of Unicode strings is correct for the entire range of all one million plus characters, not just the first 65 thousand. And that, I think, is a really important step. All we need now is better fonts that support more of the Unicode range so we can actually *see* the characters. -- Steven From merrittb7 at gmail.com Wed Jan 2 02:27:49 2013 From: merrittb7 at gmail.com (Brandon Merritt) Date: Tue, 1 Jan 2013 17:27:49 -0800 Subject: [Tutor] Tutor Digest, Vol 106, Issue 74 In-Reply-To: References: Message-ID: Sorry, I should have been more clear in what I was trying to accomplish. I am trying to build the latin square as follows: 1234567 2345671 3456712 4567123 5671234 6712345 7123456 So, the "scaleorder" is the n*n scale of the square - in this case, a 7x7. The key is that there should be no duplicate number for each row and for each column. And the "topleft" variable is the number in the topleft that sets how the rest of the square will look - in the example I gave above, it is 1. The link below is the original exercise - I am not in school, purely for my own education as I am really trying hard to become a passable Python programmer. I've been working at it for 6 month now, and I don't know any other languages: http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/02_Control/LatinSquares/Project03.pdf Thank you, Brandon On Mon, Dec 31, 2012 at 3:00 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: help (Mike G) > 2. another for loop question - latin square (Brandon Merritt) > 3. Re: another for loop question - latin square (Steven D'Aprano) > 4. Re: another for loop question - latin square (Dave Angel) > 5. Re: another for loop question - latin square (Mitya Sirenef) > 6. Re: another for loop question - latin square (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sun, 30 Dec 2012 04:30:21 -0800 > From: Mike G > To: tutor at python.org > Subject: Re: [Tutor] help > Message-ID: > PqyxQp14vG608u5rY-6nR2fY-X6m1-z-g at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Hi Randy > > > I am an older newbie teaching myself Python programming. > > > > Me too :) > > > My problem is I hear no system bell; the enter doesn't respond by > quitting the program; > > The problem with the program code the enter key hasn't worked in earlier > programs. > > > > I appreciate any advice I may recieve with this coding glitch. > > > > I copied the code into a blank .py file and ran it from cmd in Windows > XP x86 using Python 273, it worked fine - including the beep. As well, > hitting "Enter" exited the program. > > It sounds like (no pun intended) it may be how you're running the > program. I would use a py file and run it using cmd - holler if you > need help, you may if the path to Python isn't good to go. > > Mike > > > ------------------------------ > > Message: 2 > Date: Sun, 30 Dec 2012 15:59:14 -0800 > From: Brandon Merritt > To: tutor at python.org > Subject: [Tutor] another for loop question - latin square > Message-ID: > < > CAEHLpHWnwwZ82bV52M3BpBbYOQjtPFvxn2WULBsio_t3CMnNpQ at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > I am having trouble figuring out a solution after a couple hours now of > playing with the code. I'm trying to make a latin square using the code > below: > > scaleorder = int(raw_input('Please enter a number for an n*n square: ')) > > > topleft = int(raw_input('Please enter the top left number for the square: > ')) > > firstrow = range((topleft),scaleorder+1) > > count = 0 > > while count < 8: > for i in firstrow: > print i > count += 1 > firstrow[i+1] > > > ----------------------------------------------------------------------- > > It seemed like I could make the for loop work by doing something like this: > > for i in firstrow: > print i, i+2 > > > but that obviously is not a solution either. Any ideas? > > Thanks, > Brandon > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20121230/0d206b45/attachment-0001.html > > > > ------------------------------ > > Message: 3 > Date: Mon, 31 Dec 2012 11:27:22 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] another for loop question - latin square > Message-ID: <50E0DBEA.5060009 at pearwood.info> > Content-Type: text/plain; charset=UTF-8; format=flowed > > On 31/12/12 10:59, Brandon Merritt wrote: > > I am having trouble figuring out a solution after a couple hours now of > > playing with the code. I'm trying to make a latin square using the code > > below: > > > > scaleorder = int(raw_input('Please enter a number for an n*n square: ')) > > topleft = int(raw_input('Please enter the top left number for the > square: ')) > > firstrow = range((topleft),scaleorder+1) > > > > count = 0 > > while count< 8: > > for i in firstrow: > > print i > > count += 1 > > firstrow[i+1] > > > > > > ----------------------------------------------------------------------- > > > > It seemed like I could make the for loop work by doing something like > this: > > > > for i in firstrow: > > print i, i+2 > > > > > > but that obviously is not a solution either. Any ideas? > > > Absolutely none. I don't understand your question. What's a latin square? > Is it the same as a magic square? What do you mean, "make the for loop > work"? > The for loop already works: it iterates over the range topleft to > scaleorder > inclusive. You say "that obviously is not a solution", but a solution to > what? What is it supposed to do? > > I think that you need to think a bit more carefully about what you are > trying to accomplish. Probably the most valuable piece of advice I ever > received was that *writing code* should be the last thing you do when > trying to solve a problem. When I have a tricky problem to accomplish, > I will sometimes spend hours designing my code with pencil and paper > before writing my first line of code. > > Can YOU solve a latin square using pen and paper? If you can't, how do you > expect to write a program to do it? > > Start by writing down the steps that you would take to make a latin square. > I suggest with starting with a fixed size, say, 5x5: > > * pick a number for the top left corner, say, 3 > > * write down the first row: 3 ? ? ? ? > [you need to come up with a rule for making the row] > > * write down the second row: ? ? ? ? ? > [again, you need to come up with a rule for making the next row] > > ... and so on for the other three rows. Now you have an algorithm for > making 5 x 5 latin squares. > > Now you can write some code to do that! > > Once that is working, you can start thinking about changing from fixed > 5 x 5 squares to arbitrary N x N sizes. > > > > -- > Steven > > > ------------------------------ > > Message: 4 > Date: Sun, 30 Dec 2012 19:44:27 -0500 > From: Dave Angel > To: tutor at python.org > Subject: Re: [Tutor] another for loop question - latin square > Message-ID: <50E0DFEB.5000909 at davea.name> > Content-Type: text/plain; charset=ISO-8859-1 > > On 12/30/2012 06:59 PM, Brandon Merritt wrote: > > I am having trouble > > Please tell us what Python version you're targeting. It looks like 2.7, > but you really should specify it for us. > > Next, you should tell us your skill level; are you experienced at > another language and learning Python, or what? Is this latin square an > assignment, from a tutorial or book, or just for fun? If from a > tutorial, have you been doing the earlier problems? Have you completed > any other Python projects which were non-trivial? Do you realize just > how tricky a latin square is to create? > > > figuring out a solution after a couple hours now of > > playing with the code. I'm trying to make a latin square > > For other readers, an nxn latin square (not a magic square) has the same > n symbols in each row and in each column, with no duplicates in any row, > nor in any column. For a 4x4 square, one solution might be > > A B C D > B D A C > C A D B > D C B A > > > > using the code > > below: > > > > scaleorder = int(raw_input('Please enter a number for an n*n square: ')) > > > > > > topleft = int(raw_input('Please enter the top left number for the square: > > ')) > > > > firstrow = range((topleft),scaleorder+1) > > You do realize that this won't necessarily create a list of the > requested size? Specifically, if the user didn't specify a top-left of > exactly 1, then the size will be wrong. > > > count = 0 > > > > while count < 8: > > for i in firstrow: > > print i > > count += 1 > > firstrow[i+1] > > Just what did you expect the last line to accomplish? And what was the > 8 supposed to mean? > > > > > ----------------------------------------------------------------------- > > > > It seemed like I could make the for loop work by doing something like > this: > > > > for i in firstrow: > > print i, i+2 > > > > > > but that obviously is not a solution either. Any ideas? > > > > Thanks, > > Brandon > > > > > > > > Have you constructed a latin square by hand, of any size ? (try 4 for > your first attempt) Do you realize that you could build 3 lines and > then discover that there is no valid fourth line for those 3? > > Have you learned how and why to build functions in your code? I > maintain this problem is too tricky to do without at least factoring > each row into a function. > > > > -- > > DaveA > > > > ------------------------------ > > Message: 5 > Date: Sun, 30 Dec 2012 19:49:23 -0500 > From: Mitya Sirenef > To: tutor at python.org > Subject: Re: [Tutor] another for loop question - latin square > Message-ID: <50E0E113.2020403 at lightbird.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 12/30/2012 06:59 PM, Brandon Merritt wrote: > > I am having trouble figuring out a solution after a couple hours now > > of playing with the code. I'm trying to make a latin square using the > > code below: > > > > scaleorder = int(raw_input('Please enter a number for an n*n square: ')) > > > > > > topleft = int(raw_input('Please enter the top left number for the > > square: ')) > > > > firstrow = range((topleft),scaleorder+1) > > > > count = 0 > > > > while count < 8: > > for i in firstrow: > > print i > > count += 1 > > firstrow[i+1] > > > > > > ----------------------------------------------------------------------- > > > > It seemed like I could make the for loop work by doing something like > > this: > > > > for i in firstrow: > > print i, i+2 > > > It's a bit hard to understand what you're trying to do, but if > my guess is anywhere close to truth, you might be trying > to make the first line of a latin square by incrementing > from a specified number. In this case, you should make a range > from topleft to scaleorder+topleft, and if you want the > top row randomized, you can use random.shuffle(): > > from random import shuffle > > scaleorder = int(raw_input('Please enter a number for an n*n square: ')) > topleft = int(raw_input('Please enter the top left number for the > square: ')) > firstrow = range(topleft, scaleorder+topleft) > shuffle(firstrow) > > print firstrow > > > Does this help? -m > > > > -- > Lark's Tongue Guide to Python: http://lightbird.net/larks/ > > > > ------------------------------ > > Message: 6 > Date: Mon, 31 Dec 2012 00:51:07 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] another for loop question - latin square > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 31/12/12 00:27, Steven D'Aprano wrote: > > On 31/12/12 10:59, Brandon Merritt wrote: > >> I am having trouble figuring out a solution after a couple hours now of > >> playing with the code. I'm trying to make a latin square using the code > >> below: > > I totally agree with everything Steven said. > However there is one glaring mistake in your code.... > > > >> count = 0 > >> while count< 8: > >> for i in firstrow: > >> print i > >> count += 1 > >> firstrow[i+1] > > What do you think that last row is doing? > Whatever it is, you are almost certainly wrong. > But eventually it is likely to throw an index error... > > >> ----------------------------------------------------------------------- > >> > >> It seemed like I could make the for loop work by doing something like > >> this: > >> > >> for i in firstrow: > >> print i, i+2 > >> > >> but that obviously is not a solution either. Any ideas? > > It works perfectly. It prints out i and i+2 for every member of > firstrow. Whether that's what you want to do is another matter. > > As Steven said, try working out what you want to do first, > then write the code. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 106, Issue 74 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacklittlemc at yahoo.com Wed Jan 2 03:02:20 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Tue, 1 Jan 2013 18:02:20 -0800 (PST) Subject: [Tutor] Please help Message-ID: <1357092140.95558.YahooMailNeo@web124503.mail.ne1.yahoo.com> I do not understand my error (it says something about an out-of-function return on line 179) ? my code is at the link http://www.mediafire.com/download.php?4ga0weu4ifc6s1u -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Jan 2 03:07:08 2013 From: d at davea.name (Dave Angel) Date: Tue, 01 Jan 2013 21:07:08 -0500 Subject: [Tutor] another for loop question - latin square (was: Tutor Digest, Vol 106, Issue 74) In-Reply-To: References: Message-ID: <50E3964C.3000005@davea.name> On 01/01/2013 08:27 PM, Brandon Merritt wrote: > Sorry, I should have been more clear in what I was trying to accomplish. I > am trying to build the latin square as follows: > > 1234567 > 2345671 > 3456712 > 4567123 > 5671234 > 6712345 > 7123456 > > So, the "scaleorder" is the n*n scale of the square - in this case, a 7x7. > The key is that there should be no duplicate number for each row and for > each column. And the "topleft" variable is the number in the topleft that > sets how the rest of the square will look - in the example I gave above, it > is 1. > > The link below is the original exercise - I am not in school, purely for my > own education as I am really trying hard to become a passable Python > programmer. I've been working at it for 6 month now, and I don't know any > other languages: > > http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/02_Control/LatinSquares/Project03.pdf > > > Thank you, > Brandon Please reply to a single message, not to some digest. This way your new message will be threaded together with the previous ones. And for those unable to see the threads, at least the subject line will match. Note the first line below of the quote you used: > > On Mon, Dec 31, 2012 at 3:00 AM, wrote: > >> >> >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." >> >> >> So you don't just want a latin-square, you want a particular one. You picked the most trivial one, where all the spots are numeric, and each line is simply sequentially chosen from a ring, 1 through scaleorder. Assuming scaleorder is less than 10, the following should work. table = [str(i) for i in range(1, scaleorder+1) * 3] for row in range(topleft-1, topleft+scaleorder-1): line = table[row:row+scaleorder] print "".join(line) If you have to deal with scaleorders bigger than 9, then you'll need a separator between the numbers. Probably the easiest place to fix that would be in constructing the table. But a q&d fix might be to use " ".join() on the last line. -- DaveA From steve at pearwood.info Wed Jan 2 03:12:53 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Jan 2013 13:12:53 +1100 Subject: [Tutor] Tutor Digest, Vol 106, Issue 74 In-Reply-To: References: Message-ID: <50E397A5.9050300@pearwood.info> Brandon, Please trim your response to only the parts of the email that are actually relevant. As given, you have duplicated SIX emails which we have already seen and don't need to see again, at least not in full, multiple hundreds of lines of text. Also, please ensure that you use a sensible, meaningful subject line. "Re: [Tutor] Tutor Digest, Vol 106, Issue 74" means nothing. More below. On 02/01/13 12:27, Brandon Merritt wrote: > Sorry, I should have been more clear in what I was trying to accomplish. I > am trying to build the latin square as follows: > > 1234567 > 2345671 > 3456712 > 4567123 > 5671234 > 6712345 > 7123456 Right. So start off by writing down how you would do this in ordinary English: Step 1: Write down the list 1234567. Step 2: Take the digits above, move the first digit to the end, and write it down. Step 3: Repeat Step 2 five more times. (Six times in total.) Now try turning that into Python code. Good luck! -- Steven From ryan at hackery.io Wed Jan 2 03:07:41 2013 From: ryan at hackery.io (Ryan Macy) Date: Tue, 01 Jan 2013 20:07:41 -0600 Subject: [Tutor] Please help In-Reply-To: <1357092140.95558.YahooMailNeo@web124503.mail.ne1.yahoo.com> References: <1357092140.95558.YahooMailNeo@web124503.mail.ne1.yahoo.com> Message-ID: <50E3966D.107@hackery.io> Jack Little wrote: > > I do not understand my error (it says something about an > out-of-function return on line 179) > my code is at the link > http://www.mediafire.com/download.php?4ga0weu4ifc6s1u > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I'd like to help, but I'm not going to download anything from that site. Can you instead post it on gist.github.com or bpaste.com? _Ryan -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jan 2 03:14:51 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Jan 2013 13:14:51 +1100 Subject: [Tutor] Please help In-Reply-To: <1357092140.95558.YahooMailNeo@web124503.mail.ne1.yahoo.com> References: <1357092140.95558.YahooMailNeo@web124503.mail.ne1.yahoo.com> Message-ID: <50E3981B.6070102@pearwood.info> On 02/01/13 13:02, Jack Little wrote: > I do not understand my error (it says something about an out-of-function return on line 179) You cannot use "return" unless it is inside a function. # This is okay. def test(): print "test" return "testing complete" # indented, therefore inside the function # this is not okay def test(): print "test" return "testing complete" # not indented, therefore not inside the function -- Steven From jacklittlemc at yahoo.com Wed Jan 2 03:37:35 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Tue, 1 Jan 2013 18:37:35 -0800 (PST) Subject: [Tutor] Please help Message-ID: <1357094255.214.androidMobile@web124501.mail.ne1.yahoo.com> Maybe tomorrow I can just email you the code -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Wed Jan 2 04:16:03 2013 From: pasokan at talentsprint.com (Asokan Pichai) Date: Wed, 2 Jan 2013 08:46:03 +0530 Subject: [Tutor] Please help In-Reply-To: <1357094255.214.androidMobile@web124501.mail.ne1.yahoo.com> References: <1357094255.214.androidMobile@web124501.mail.ne1.yahoo.com> Message-ID: I saw the code; I see too many formatting errors: Line No 24 starts a function definition and the next few lines are indented by two spaces, but Line 29 is a print statement that is in line with the def; IOW it completes the function. It is very likely wrong. You are defining functions within functions; again it is very likely to be wrong. My advice, look at PEP 8 and also some sample python code in the tutorial to understand how to format code. Remember: Leading whitespace is syntactically significant HTH Asokan Pichai Religion offers hope against all the strife and misery of the world caused by religions. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gayathri.s112 at gmail.com Wed Jan 2 08:20:04 2013 From: gayathri.s112 at gmail.com (Gayathri S) Date: Wed, 2 Jan 2013 12:50:04 +0530 Subject: [Tutor] HELP- Regarding working with python Message-ID: Hi.. I am using python 2.7 and scikit-learn for machine learning. And OS is Windows 7. Wanna know how to import our own data sets in scikit-learn? Regards, Gayathri.S -------------- next part -------------- An HTML attachment was scrubbed... URL: From ufukeskici at gmail.com Wed Jan 2 10:22:47 2013 From: ufukeskici at gmail.com (Ufuk Eskici) Date: Wed, 2 Jan 2013 11:22:47 +0200 Subject: [Tutor] Trouble importing Paramiko In-Reply-To: References: <50DC3F62.7090109@pearwood.info> <50DC4389.5000604@pearwood.info> Message-ID: any help is appreciated, thanks... 2012/12/28 Ufuk Eskici > Hello, > My Python version is 2.7.3 and it is installed in "C:\Python27 (on the > web, it says Paramiko-1.7.4 is supported with Python 2.7) > @Dave: Previous output was from IDLE which should be same with CLI. > > I'm getting this output now from Windows Command Line: > > **************************************************** > C:\Python27>python ufo.py > Traceback (most recent call last): > File "ufo.py", line 1, in > import paramiko > ImportError: No module named paramiko > > C:\Python27> > **************************************************** > > This is the output after addning .sys path: > **************************************************** > C:\Python27>python ufo.py > import path is ['C:\\Python27', 'C:\\Windows\\system32\\python27.zip', > 'C:\\Pyt > hon27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', > 'C:\\Python27\ > \lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages'] > Traceback (most recent call last): > File "ufo.py", line 4, in > import paramiko > ImportError: No module named paramiko > **************************************************** > > > 2012/12/27 Francois Dion > >> On Thu, Dec 27, 2012 at 8:48 AM, Ufuk Eskici >> wrote: >> > I got this output with lots of errors: >> > File "build\bdist.win32\egg\paramiko\auth_handler.py", line 311 >> > except SSHException, e: >> > ^ >> > SyntaxError: invalid syntax >> >> Use Python 2.x, Python 3 is in the works, kindoff: >> >> https://github.com/paramiko/paramiko/issues/16 >> https://github.com/paramiko/paramiko/issues/123 >> >> Fran?ois >> >> -- >> www.pyptug.org - raspberry-python.blogspot.com >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jan 2 10:42:47 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Jan 2013 20:42:47 +1100 Subject: [Tutor] Trouble importing Paramiko In-Reply-To: References: <50DC3F62.7090109@pearwood.info> <50DC4389.5000604@pearwood.info> Message-ID: <50E40117.4050707@pearwood.info> On 02/01/13 20:22, Ufuk Eskici wrote: > any help is appreciated, thanks... Have you successfully installed it yet? Last time you tried to install, you tried to install the Python 2 version of Paramiko with Python 3, and got many SyntaxErrors. Until you actually install Paramiko using Python 2, there is no point trying to import it. -- Steven From ufukeskici at gmail.com Wed Jan 2 10:48:21 2013 From: ufukeskici at gmail.com (Ufuk Eskici) Date: Wed, 2 Jan 2013 11:48:21 +0200 Subject: [Tutor] Trouble importing Paramiko In-Reply-To: <50E40117.4050707@pearwood.info> References: <50DC3F62.7090109@pearwood.info> <50DC4389.5000604@pearwood.info> <50E40117.4050707@pearwood.info> Message-ID: Hello Steven, I've written this before: "My Python version is 2.7.3 and it is installed in "C:\Python27 (on the web, it says Paramiko-1.7.4 is supported with Python 2.7)" so I'm using the correct Python verion (2.7.3). But I dont know why I'm getting errors during Paramiko installation as I mentioned before. 2013/1/2 Steven D'Aprano > On 02/01/13 20:22, Ufuk Eskici wrote: > >> any help is appreciated, thanks... >> > > > Have you successfully installed it yet? Last time you tried to install, > you tried to install the Python 2 version of Paramiko with Python 3, > and got many SyntaxErrors. > > Until you actually install Paramiko using Python 2, there is no point > trying to import it. > > > > -- > Steven > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jan 2 10:54:34 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Jan 2013 20:54:34 +1100 Subject: [Tutor] Trouble importing Paramiko In-Reply-To: References: <50DC3F62.7090109@pearwood.info> <50DC4389.5000604@pearwood.info> <50E40117.4050707@pearwood.info> Message-ID: <50E403DA.3090908@pearwood.info> On 02/01/13 20:48, Ufuk Eskici wrote: > Hello Steven, > > I've written this before: > > "My Python version is 2.7.3 and it is installed in "C:\Python27 (on the > web, it says Paramiko-1.7.4 is supported with Python 2.7)" How do you know it is installed in C:\Python27? What is the output of dir C:\Python27\paramiko* from the Windows command.com or cmd.exe (?) shell? > so I'm using the correct Python verion (2.7.3). But I dont know why I'm > getting errors during Paramiko installation as I mentioned before. If you got errors during installation, then Paramiko is NOT installed, or at best it is installed in a broken state and cannot be used. You must SUCCESSFULLY install Paramiko with no errors, or at least no important errors. If Paramiko was installed successfully, then "import paramiko" would work. Since it doesn't work, you have to go back and look at the installation. -- Steven From hugo.yoshi at gmail.com Wed Jan 2 11:04:23 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 2 Jan 2013 11:04:23 +0100 Subject: [Tutor] Trouble importing Paramiko In-Reply-To: References: <50DC3F62.7090109@pearwood.info> <50DC4389.5000604@pearwood.info> <50E40117.4050707@pearwood.info> Message-ID: On Wed, Jan 2, 2013 at 10:48 AM, Ufuk Eskici wrote: > Hello Steven, > > I've written this before: > > "My Python version is 2.7.3 and it is installed in "C:\Python27 (on the > web, it says Paramiko-1.7.4 is supported with Python 2.7)" > > so I'm using the correct Python verion (2.7.3). But I dont know why I'm > getting errors during Paramiko installation as I mentioned before. > > That is very interesting, because when you tried my earlier suggestion to use "python setup.py install" the error messages you gave us came very clearly from python 3.3, not python 2.7.3. Look more closely at some of those error messages: > File "c:\python33\lib\site-packages\paramiko-1.7.4-py3.3. egg\paramiko\transport.py", line 353 > out = ' ^ > SyntaxError: invalid syntax C:\python33 is definitely not C:\python27. That looks to me like you have two versions of python installed on your machine, both python 3.3 and python 2.7. I an only make an educated guess at this, but probably when you invoke python on your command line, it's actually python 3.3 that is started. You can verify this by simply starting a command line, going to your C:\ directory, typing in python, and looking at the version number that comes up. If it is indeed true you have two versions of python installed, try the installation step again, but now make absolutely sure you use the correct version of python to run the setup script, like this: C:\python27\python.exe setup.py install That will use python 2.7 to run the installation script, and *that* in turn will make sure paramiko is actually installed for the correct python version. HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jan 2 12:27:21 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Jan 2013 11:27:21 +0000 Subject: [Tutor] HELP- Regarding working with python In-Reply-To: References: Message-ID: On 02/01/13 07:20, Gayathri S wrote: > Hi.. > I am using python 2.7 and scikit-learn for machine learning. > And OS is Windows 7. Wanna know how to import our own data sets in > scikit-learn? Hi, This list is for learning Python and its standard library. Your question looks to be specific to scikit-learn so will likely get more success asking on a scikit-learn forum or by contacting the author of scikit-learn. If you are very lucky some of the folks on this list might just happen to have scikit-learn experience, but it isn't guaranteed. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jan 2 12:29:26 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Jan 2013 11:29:26 +0000 Subject: [Tutor] HELP- Regarding working with python In-Reply-To: References: Message-ID: On 02/01/13 07:20, Gayathri S wrote: > Hi.. > I am using python 2.7 and scikit-learn for machine learning. > And OS is Windows 7. Wanna know how to import our own data sets in > scikit-learn? Further to my last mail there is a gmane group gmane.comp.python.scikit-learn I'd try looking there, or wherever it is sourced originally. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Wed Jan 2 16:16:48 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 2 Jan 2013 15:16:48 +0000 Subject: [Tutor] Limitation of int() in converting strings In-Reply-To: <50E26F1A.1020909@pearwood.info> References: <50D50E32.1080706@pearwood.info> <50E26F1A.1020909@pearwood.info> Message-ID: On 1 January 2013 05:07, Steven D'Aprano wrote: > On 23/12/12 04:38, Oscar Benjamin wrote: >> >> On 22 December 2012 01:34, Steven D'Aprano wrote: >>> >>> On 18/12/12 01:36, Oscar Benjamin wrote: >>> >>>> I think it's unfortunate that Python's int() function combines two >>>> distinct behaviours in this way. In different situations int() is used >>>> to: >>>> 1) Coerce an object of some type other than int into an int without >>>> changing the value of the integer that the object represents. >>> > [SNIP] > > Yes. And it is a demonstrable fact that int is *not* intended to coerce > objects to int "without changing the value of the number", because > changing the value of the number is precisely what int() does, in some > circumstances. I wonder how often the int() function is used in a situation where the dual behaviour is actually desired. I imagine that the common uses for int are (in descending order or prevalence): 1) Parse a string as an integer 2) Convert an integer-valued numeric object of some other type, to the int type. 3) Truncate a non-integer valued object from a numeric type. The int() function as it stands performs all three operations. I would describe 1) and 2) as changing type but not value and 3) as a value changing operation. I can see use cases where 1) and 2) go together. I can't really envisage a case in which 1) and 3) are wanted at the same time in some particular piece of code. In other words I can't imagine a use case that calls for a function that works precisely as the int() function currently does. > > If you would like to argue that it would have been better if int did > not do this, then I might even agree with you. That's exactly what I would argue. > There is certainly > precedence: if I remember correctly, you cannot convert floating point > values to integers directly in Pascal, you first have to truncate them > to an integer-valued float, then convert. > > # excuse my sloppy Pascal syntax, it has been a few years > var > i: integer; > x: real; > begin > i = integer(trunc(x)); > end; When the idea was discussed in the run up to Python 3, Guido raised exactly this case and said """ I still really wish I had followed Pascal's lead instead of C's here: Pascal requires you to use trunc() to convert a real to an integer. (BTW Pascal also had the division operator right, unlike C, and we're finally fixing this in Py3k by following Pascal's nearly-40-year-old lead.) If we had done it that way, we wouldn't have had to introduce the index() builtin and the corresponding infrastructure (__index__ and a whole slew of C APIs). """ http://mail.python.org/pipermail/python-dev/2008-January/076546.html > So I'm not entirely against the idea that Python should have had separate > int() and trunc() functions, with int raising an exception on (non-whole > number?) floats. It's possible that the reason the idea was rejected before is because it was suggested that int(1.0) would raise an error, analogous to the way that float(1+0j) raises an error even though in both cases the conversion can exactly preserve value. > But back to Python as it actually is, rather than how it might have been. > There's no rule that int() must be numerically lossless. It is lossless > with strings, and refuses to convert strings-that-look-like-floats to ints. > And that makes sense: in an int, the "." character is just as illegal as > the characters "k" or "&" or "?", int will raise on "123k456", so why > wouldn't it raise on "123.456"? I agree. To be fair string handling is not my real complaint. I referred to that initially since the OP asked about that case. > > But that (good, conservative) design decision isn't required or enforced. > Hence my reply that you cannot safely make the assumption that int() on a > non-numeric type will be numerically exact. This is precisely my complaint. The currently available functions are int, operator.index, trunc, math.ceil, math.floor and round. Conspicuously absent is the function that simply converts an object to an integer type at the same time as refusing to change its numeric value. i.e. I would like the special rounding mode that is "no rounding", just an error for non-integral values. It's probably to do with the kind of code I write but I seem to often find myself implementing a (lazy and bug-prone) function for this task. >> [SNIP] >> >> This is precisely my point. I would prefer if if int(obj) would fail >> on non-integers leaving me with the option of calling an appropriate >> rounding function. After catching RoundError (or whatever) you would >> know that you have a number type object that can be passed to round, >> ceil, floor etc. > > Well, I guess that comes down to the fact that Python is mostly aimed at > mathematically and numerically naive users who would be scared off at a > plethora of rounding modes :-) That's true but I think there are some conceptual points that any user of any programming language should be forced to consider. Python can make many common tasks easy for you but there simply is no "one way" to round a number. Providing a particular rounding mode as a default rounding mode leads to people not thinking properly about what rounding mode they really need in a particular problem. This in turn leads to bugs where the wrong rounding mode is used. Oscar From alan.gauld at btinternet.com Wed Jan 2 17:18:17 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Jan 2013 16:18:17 +0000 Subject: [Tutor] Limitation of int() in converting strings In-Reply-To: References: <50D50E32.1080706@pearwood.info> <50E26F1A.1020909@pearwood.info> Message-ID: This is going somewhat off-topic but my curiosity is roused... On 02/01/13 15:16, Oscar Benjamin wrote: > When the idea was discussed in the run up to Python 3, Guido raised > exactly this case and said > """... > (BTW Pascal also had the division operator right, unlike C, and we're > ... If we had done it that way, we wouldn't have had to introduce > the index() builtin and the corresponding infrastructure (__index__ > and a whole slew of C APIs). I don't get the reference to index here. Why would adopting Pascal style division remove the need for index? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Wed Jan 2 17:41:06 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Jan 2013 03:41:06 +1100 Subject: [Tutor] Limitation of int() in converting strings In-Reply-To: References: <50D50E32.1080706@pearwood.info> <50E26F1A.1020909@pearwood.info> Message-ID: <50E46322.10803@pearwood.info> On 03/01/13 03:18, Alan Gauld wrote: > This is going somewhat off-topic but my curiosity is roused... > > On 02/01/13 15:16, Oscar Benjamin wrote: >> When the idea was discussed in the run up to Python 3, Guido raised >> exactly this case and said >> """... >> (BTW Pascal also had the division operator right, unlike C, and we're >> ... If we had done it that way, we wouldn't have had to introduce >> the index() builtin and the corresponding infrastructure (__index__ >> and a whole slew of C APIs). > > I don't get the reference to index here. > Why would adopting Pascal style division remove the need for index? No, the comment about division was a parenthetical aside: "(BTW Pascal also had the division operator right, unlike C, and we're finally fixing this in Py3k by following Pascal's nearly-40-year-old lead.)" The bit about __index__ refers to using trunc(): "I still really wish I had followed Pascal's lead instead of C's here: Pascal requires you to use trunc() to convert a real to an integer. ... If we had done it that way, we wouldn't have had to introduce the index() builtin and the corresponding infrastructure (__index__ and a whole slew of C APIs)." I don't know what this "index() builtin" is, it doesn't appear to exist. But __index__ is a special method that converts to int without rounding or truncating, intended only for types that emulate ints but not other numeric types: py> (123).__index__() 123 py> (123.0).__index__() Traceback (most recent call last): File "", line 1, in AttributeError: 'float' object has no attribute '__index__' The purpose is to allow you to use custom integer-types in sequence indexing, e.g. if n = MyInteger(42), you can use mylist[n] and Python will call n.__index__() to convert to a proper int. In the past, Python would only allow actual ints or longs for indexing. Python cannot use the int() builtin or the regular __int__ method to do the conversion because they will happily convert floats and strings, and you don't want to allow mylist['42'] or mylist[42.0] to succeed. So there needs to be a second special method for converting integer-types to real ints. As is often the case, this need was driven by the numpy community, if I remember correctly, which has int8, int16, int32 and int64 types that don't inherit from int. -- Steven From d at davea.name Wed Jan 2 17:55:21 2013 From: d at davea.name (Dave Angel) Date: Wed, 02 Jan 2013 11:55:21 -0500 Subject: [Tutor] Limitation of int() in converting strings In-Reply-To: <50E46322.10803@pearwood.info> References: <50D50E32.1080706@pearwood.info> <50E26F1A.1020909@pearwood.info> <50E46322.10803@pearwood.info> Message-ID: <50E46679.5010603@davea.name> On 01/02/2013 11:41 AM, Steven D'Aprano wrote: > > > The bit about __index__ refers to using trunc(): > > "I still really wish I had followed Pascal's lead instead of C's here: > Pascal requires you to use trunc() to convert a real to an integer. ... > If we had done it that way, we wouldn't have had to introduce the > index() builtin and the corresponding infrastructure (__index__ > and a whole slew of C APIs)." > > > I don't know what this "index() builtin" is, it doesn't appear to exist. > But __index__ is a special method that converts to int without rounding > or truncating, intended only for types that emulate ints but not other > numeric types: I suspect that at one time, an index() built-in was intended. It's now available as an operator, and simply calls the __index__() as you say. import operator print operator.index(myobject) works, at least in 2.7 and 3.x -- DaveA From alan.gauld at btinternet.com Wed Jan 2 18:59:44 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Jan 2013 17:59:44 +0000 Subject: [Tutor] Limitation of int() in converting strings In-Reply-To: <50E46679.5010603@davea.name> References: <50D50E32.1080706@pearwood.info> <50E26F1A.1020909@pearwood.info> <50E46322.10803@pearwood.info> <50E46679.5010603@davea.name> Message-ID: On 02/01/13 16:55, Dave Angel wrote: > On 01/02/2013 11:41 AM, Steven D'Aprano wrote: >> The bit about __index__ refers to using trunc(): OK, that partially solves it :-) >> >> I don't know what this "index() builtin" is, it doesn't appear to exist. That was also what confused me. The only indexz() I could find was the one that found the index of an item in a collection >>> [1,2,3].index(2) 1 And I didn't see how trunc() or division helped there... >> But __index__ is a special method that converts to int without rounding >> or truncating, intended only for types that emulate ints but not other >> numeric types: And this was the new bit I didn't know about. > import operator > print operator.index(myobject) But I did try >>> import operator as op >>> help(op.index) Help on built-in function index in module operator: index(...) index(a) -- Same as a.__index__() Which was no help at all, so I tried >>> help(a.__index__) Traceback (most recent call last): File "", line 1, in NameError: name 'a' is not defined Which was what I expected! So now with your input I can try: >>> help(int.__index__) Help on wrapper_descriptor: __index__(...) x[y:z] <==> x[y.__index__():z.__index__()] Bingo! Although still doesn't anything explicitly about the need for an integer! But that was harder than it should have been! :-( Thanks guys, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lmergner at gmail.com Wed Jan 2 21:43:59 2013 From: lmergner at gmail.com (Luke Thomas Mergner) Date: Wed, 2 Jan 2013 12:43:59 -0800 Subject: [Tutor] writing effective unittests Message-ID: <20130102204357.GA1974@lmerg-crunchbang> Hi, I am trying to learn a bit of test-driven programming using unittests and nosetests. I am having trouble finding resources that explain how to write effective tests. I am not a programmer or a student, so I do not have access to collegues or classes. I'm hoping that someone knows of a good tutorial that I've missed. Based on the O'Reilly 2-Part introduction, I hope that learning to write tests will make my code better. Thanks, -- Luke Thomas Mergner Glendale, CA Sent from Mutt. From alan.gauld at btinternet.com Thu Jan 3 00:35:38 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Jan 2013 23:35:38 +0000 Subject: [Tutor] writing effective unittests In-Reply-To: <20130102204357.GA1974@lmerg-crunchbang> References: <20130102204357.GA1974@lmerg-crunchbang> Message-ID: On 02/01/13 20:43, Luke Thomas Mergner wrote: > I am trying to learn a bit of test-driven programming using unittests and nosetests. Well done, thats a good idea. > I am having trouble finding resources that explain how to write effective tests. Thee are whole books on the subject of testing. If you stick to unit test level its not too bad there are some useful resources around. This is more of a reference sheet than a tutorial but I find it useful... http://geosoft.no/development/unittesting.html The main things to remember are that in testing you are trying to break your code. Which is a hard thing for any programmer to do because he wrote it and loves it and doesn't want to hear that its broken! TDD helps get over that because you think about testing before that sentimental attachment has fully formed. But the philosophy is the same you are trying to think of every which way your code could break. Other related topics you could research are - preconditions - postconditions - invariants - programming by contract And always remember that just because all your unit tests pass that doesn't mean the system as a whole works, it's just more likely to, and probably easier to fix when it does break. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From conorgrevlos at yahoo.com Thu Jan 3 00:36:42 2013 From: conorgrevlos at yahoo.com (Conor Grevlos) Date: Wed, 2 Jan 2013 15:36:42 -0800 (PST) Subject: [Tutor] Python Programming for Absolute Beginners, 3rd Edition Message-ID: <1357169802.87209.YahooMailNeo@web160303.mail.bf1.yahoo.com> I recently bought and starting reading the Python Programming for Absolute Beginners, 3rd?Edition?by Michael Dawson. I got through the first chapter fine, no problems. But when I got to the second chapter I realized that I did not know how to do the first programming lesson, Game Over 2.0 With the code not being on the page, I went to the directed website and got the downloads, yet I couldn't find the source code anywhere to be found. Am I missing something plainly obvious? I do not understand how to get the cool looking Game Over to show up, nor do I have any idea how to try. I understand that there is some of the code on the page, but the other programs? have no source code to go by either, it is as if you are left to your own knowledge and being this is a beginners book, that seems pretty stupid. Any help would be awesome thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Thu Jan 3 01:07:16 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 3 Jan 2013 00:07:16 +0000 Subject: [Tutor] Python Programming for Absolute Beginners, 3rd Edition In-Reply-To: <1357169802.87209.YahooMailNeo@web160303.mail.bf1.yahoo.com> References: <1357169802.87209.YahooMailNeo@web160303.mail.bf1.yahoo.com> Message-ID: > With the code not being on the page, I went to the directed website and got > the downloads, yet I couldn't find the source code > anywhere to be found. Am I missing something plainly obvious? what exactly did you download? all the source code for every chapter is included in the download From steve at pearwood.info Thu Jan 3 01:56:25 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Jan 2013 11:56:25 +1100 Subject: [Tutor] writing effective unittests In-Reply-To: <20130102204357.GA1974@lmerg-crunchbang> References: <20130102204357.GA1974@lmerg-crunchbang> Message-ID: <50E4D739.6050609@pearwood.info> On 03/01/13 07:43, Luke Thomas Mergner wrote: > Hi, > > I am trying to learn a bit of test-driven programming using >unittests and nosetests. I am having trouble finding resources >that explain how to write effective tests. I am not a programmer > or a student, so I do not have access to collegues or classes. If you program, you are a programmer. And we are your colleagues :) > I'm hoping that someone knows of a good tutorial that I've missed. > Based on the O'Reilly 2-Part introduction, I hope that learning to >write tests will make my code better. There are many resources on the web that talk about "Test Driven Development". The basic idea is, you incrementally write the test first, check that it fails, and then fix the code so the test passes. Then write the next test, see that this one fails, then fix the code so that it passes, and repeat until your code is done. If you google for "Python test driven development tutorial", you will find many resources: https://duckduckgo.com/?q=python%20test%20driven%20development%20tutorial Personally, I don't bother with the strict "write one test at a time" rule, nor do I bother with "always write the test before the code". I am quite happy to write a bunch of code first, and then write half a dozen tests. The important part is to have the tests, not the order in which they get written. For example, suppose you have a function called "spam" that is supposed to return a string: def spam(n): """Return n lots of a yummy meat-like substance.""" return ' '.join("spam")*n So the first thing that I do is decide what sort of behaviour spam should have. It should always return a string; it should only accept a single int argument; if no argument is given, the result should be the same as calling spam(1). So here are my first three unittests. import unittest class SpamTests(unittest.TestCase): # Tests related to the spam function. def testAlwaysReturnString(self): # Test that spam always returns a string. for n in (-5, -2, 0, 1, 2, 3, 15, 100): self.assertTrue(isinstance(spam(n), str)) def testFailOnWrongArgumentCount(self): # Test that spam takes at most one argument. self.assertRaises(TypeError, spam, 1, 2) self.assertRaises(TypeError, spam, 1, 2, 3) def testDefaultArgIsOne(self): # Test that spam with no args is like spam(1). self.assertEqual(spam(), spam(1)) Notice that tests are not necessarily definitive. I haven't tested that spam(n) returns a string for every imaginable integer n, because there are too many. Instead, I just test a small, representative sample. Likewise I haven't tested that spam() might succeed when given four arguments, or forty-four. I trust that if it fails with two arguments, and fails with three arguments, it will fail with more than three too. Don't make the mistake of thinking that tests need to cover EVERYTHING or else they are useless. 10% test coverage is better than nothing, 50% is better still, and 90% is better still. (100% is, of course, impossible.) At this point, I will run the unittests, and see whether they work or not. I haven't actually done so, but I expect that testDefaultArgIsOne will fail (to be precise, it will actually raise an exception). So I then go back to my spam() function and add in a default argument: def spam(n=1): ... # as above Let's add some more tests to SpamTests: def testHasDocString(self): # Test that the spam function has a docstring. doc = spam.__doc__ self.assertTrue(doc is not None) def testFailOnWrongArgumentType(self): # Test that the argument must not be a non-int. for bad_arg in (None, "hello", "42", 23.0, [], {}): self.assertRaises(TypeError, spam, bad_arg) def testReturnResult(self): # Test that spam returns the correct result. self.assertEqual(spam(1), "spam") self.assertEqual(spam(2), "spam spam") self.assertEqual(spam(3), "spam spam spam") self.assertEqual(spam(44), "spam spam spam spam") def testEmpty(self): # Test that spam returns an empty string when appropriate. for n in (0, -1, -2, -99): self.assertEqual(spam(n), "") Then I run the tests. If any fail, I have to either fix the test (perhaps the test is buggy) or fix the function. Once those tests pass, I might decide that I'm finished -- I have enough tests for spam, and can go on to the next part of my code. Or I might decide that I don't actually like the behaviour of spam as it is now. For instance, I might change the function to this: def spam(n=3): """Return n lots of a yummy meat-like substance.""" if n < 0: return "No spam for YOU!!!" return ' '.join("spam")*n Now I run my tests again. I expect that now two tests will fail. Can you see which ones? So I modify the tests, or add new tests as needed, and continue until I'm happy with the results. And then move on to the next part of my code. The important thing here is that there process continually goes back and forth between the tests and the main code. Adding new tests reveals bugs in the code, or missing functionality, which you then fix, then write more tests, until you can no longer think of any more tests. -- Steven From conorgrevlos at yahoo.com Thu Jan 3 02:20:46 2013 From: conorgrevlos at yahoo.com (Conor Grevlos) Date: Wed, 2 Jan 2013 19:20:46 -0600 Subject: [Tutor] Python Programming for Absolute Beginner Message-ID: <9BE69301-005C-4B9A-9CAB-88C5705C6E48@yahoo.com> I downloaded the python source folder, with chapters 1 through 12 I think. But it just opens up the program that is already built, not one that shows me the code. Sent from my iPhone From robert.sjoblom at gmail.com Thu Jan 3 02:27:22 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 3 Jan 2013 02:27:22 +0100 Subject: [Tutor] Python Programming for Absolute Beginner In-Reply-To: <9BE69301-005C-4B9A-9CAB-88C5705C6E48@yahoo.com> References: <9BE69301-005C-4B9A-9CAB-88C5705C6E48@yahoo.com> Message-ID: On Jan 3, 2013 2:22 a.m., "Conor Grevlos" wrote: > > I downloaded the python source folder, with chapters 1 through 12 I think. But it just opens up the program that is already built, not one that shows me the code. Open the files in an editor of your choice, don't run them. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Jan 3 02:29:06 2013 From: d at davea.name (Dave Angel) Date: Wed, 02 Jan 2013 20:29:06 -0500 Subject: [Tutor] Python Programming for Absolute Beginner In-Reply-To: <9BE69301-005C-4B9A-9CAB-88C5705C6E48@yahoo.com> References: <9BE69301-005C-4B9A-9CAB-88C5705C6E48@yahoo.com> Message-ID: <50E4DEE2.8010803@davea.name> On 01/02/2013 08:20 PM, Conor Grevlos wrote: > I downloaded the python source folder, with chapters 1 through 12 I think. But it just opens up the program that is already built, not one that shows me the code. > Starting a new thread with each message is unproductive and impolite. If you actually want help, how about being a tad more specific about what you actually did? What file did you download (exact filename including extension, not an approximation), and from what link? -- DaveA From ryan at hackery.io Thu Jan 3 02:28:36 2013 From: ryan at hackery.io (Ryan Macy) Date: Wed, 02 Jan 2013 19:28:36 -0600 Subject: [Tutor] Python Programming for Absolute Beginner In-Reply-To: <9BE69301-005C-4B9A-9CAB-88C5705C6E48@yahoo.com> References: <9BE69301-005C-4B9A-9CAB-88C5705C6E48@yahoo.com> Message-ID: <50E4DEC4.5040304@hackery.io> Conor Grevlos wrote: > > I downloaded the python source folder, with chapters 1 through 12 I > think. But it just opens up the program that is already built, not one > that shows me the code. > > Sent from my iPhone > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Open the file in a text editor, you're OS is likely executing the source code when you double click it :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Jan 3 13:04:03 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 3 Jan 2013 07:04:03 -0500 Subject: [Tutor] Limitation of int() in converting strings In-Reply-To: References: <50D50E32.1080706@pearwood.info> <50E26F1A.1020909@pearwood.info> <50E46322.10803@pearwood.info> <50E46679.5010603@davea.name> Message-ID: On Tue, Jan 1, 2013 at 12:07 AM, Steven D'Aprano wrote: > > Again, I was mistaken. x%1 is not suitable to get the fraction part of a > number in Python: it returns the wrong result for negative values. You need > math.modf: > > py> x = -99.25 > py> x % 1 # want -0.25 > 0.75 > py> math.modf(x) > (-0.25, -99.0) math.modf wraps libm's modf, which takes a double. This isn't suitable for Decimal, Fraction, or a custom number type. What's wrong with using math.trunc for this? From __peter__ at web.de Thu Jan 3 13:26:01 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Jan 2013 13:26:01 +0100 Subject: [Tutor] writing effective unittests References: <20130102204357.GA1974@lmerg-crunchbang> <50E4D739.6050609@pearwood.info> Message-ID: Steven D'Aprano wrote: > Notice that tests are not necessarily definitive. I haven't tested that > spam(n) returns a string for every imaginable integer n, because there > are too many. Instead, I just test a small, representative sample. > > Likewise I haven't tested that spam() might succeed when given four > arguments, or forty-four. I trust that if it fails with two arguments, > and fails with three arguments, it will fail with more than three too. > > Don't make the mistake of thinking that tests need to cover EVERYTHING > or else they are useless. 10% test coverage is better than nothing, > 50% is better still, and 90% is better still. (100% is, of course, > impossible.) There's no way you can test even 10% of the possible inputs for even the simple def mul(a, b): return a * b as there is an infinite number of such inputs. The more common and less ambitious definition of coverage is "What portion of your code is executed by your tests? There's an excellent tool to answer that question: http://nedbatchelder.com/code/coverage/ It reports executed lines, so problematic code like x = 1 if True else undefined will be reported as 100% coverage, but it is still a big help in improving your tests. > Let's add some more tests to SpamTests: > > def testHasDocString(self): > # Test that the spam function has a docstring. > doc = spam.__doc__ > self.assertTrue(doc is not None) You should rather run a tool like pylint to find missing docstrings. > The important thing here is that there process continually goes back and > forth between the tests and the main code. Adding new tests reveals bugs > in the code, or missing functionality, which you then fix, then write > more tests, until you can no longer think of any more tests. If you take this advice seriously you will soon rewrite your application code to make it easier to test it. At least for me the impact of unittests was larger than I had expected. I really should do more of them... From fomcl at yahoo.com Thu Jan 3 13:50:53 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 3 Jan 2013 04:50:53 -0800 (PST) Subject: [Tutor] writing effective unittests In-Reply-To: <20130102204357.GA1974@lmerg-crunchbang> References: <20130102204357.GA1974@lmerg-crunchbang> Message-ID: <1357217453.36448.YahooMailNeo@web163805.mail.gq1.yahoo.com> > Hi, > > I am trying to learn a bit of test-driven programming using unittests and > nosetests. I am having trouble finding resources that explain how to write > effective tests. I am not a programmer or a student, so I do not have access to > collegues or classes. I'm hoping that someone knows of a good tutorial that > I've missed. Based on the O'Reilly 2-Part introduction, I hope that > learning to write tests will make my code better. > I am currently readingPython Testing: Beginner's Guideby Daniel Arbuckle http://www.amazon.com/Python-Testing-Beginners-Arbuckle-Daniel/dp/1847198848 It covers doctest, unittest, nose, test-driven programming and more (I am just half way the book). It? a beginnner? guide but I like it. Some of the examples are a little too simplistic (the author keeps writing 'fixtures' for datetime.datetime.now(), for example). But again, I am happy that I bought it. The only thing I did wrong: I bought it too late! Apparently hte FIRST thing one has to do is write tests, not the LAST. Cheers, Albert-Jan From eryksun at gmail.com Thu Jan 3 13:52:46 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 3 Jan 2013 07:52:46 -0500 Subject: [Tutor] how to struct.pack a unicode string? In-Reply-To: <50E2825C.1040105@pearwood.info> References: <1354293788.96740.YahooMailNeo@web163803.mail.gq1.yahoo.com> <50B9B22F.3080605@pearwood.info> <1354455292.11754.YahooMailNeo@web163805.mail.gq1.yahoo.com> <50E2825C.1040105@pearwood.info> Message-ID: On Tue, Jan 1, 2013 at 1:29 AM, Steven D'Aprano wrote: > > 2 Since "wide builds" use so much extra memory for the average ASCII > string, hardly anyone uses them. On Windows (and I think OS X, too) a narrow build has been practical since the wchar_t type is 16-bit. As to Linux I'm most familiar with Debian, which uses a wide build. Do you know off-hand which distros release a narrow build? > But more important than the memory savings, it means that for the first > time Python's handling of Unicode strings is correct for the entire range > of all one million plus characters, not just the first 65 thousand. Still, be careful not to split 'characters': >>> list(normalize('NFC', '\u1ebf')) ['?'] >>> list(normalize('NFD', '\u1ebf')) ['e', '?', '?'] From oscar.j.benjamin at gmail.com Thu Jan 3 15:33:54 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 3 Jan 2013 14:33:54 +0000 Subject: [Tutor] Limitation of int() in converting strings In-Reply-To: References: <50D50E32.1080706@pearwood.info> <50E26F1A.1020909@pearwood.info> <50E46322.10803@pearwood.info> <50E46679.5010603@davea.name> Message-ID: On 2 January 2013 17:59, Alan Gauld wrote: > On 01/02/2013 11:41 AM, Steven D'Aprano wrote: > >[SNIP] >> But __index__ is a special method that converts to int without rounding >> or truncating, intended only for types that emulate ints but not other >> numeric types: > > > And this was the new bit I didn't know about. > > [SNIP] >>>> help(int.__index__) > Help on wrapper_descriptor: > > __index__(...) > x[y:z] <==> x[y.__index__():z.__index__()] > > > Bingo! Although still doesn't anything explicitly about the need for an > integer! The operator.index builtin checks that an int/long is returned. The same is true of the underlying C-API that is used internally by indexable sequences (list, tuple, etc.). $ python Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import operator >>> class A(object): ... def __index__(self): ... return 4.5 ... >>> a = A() >>> a.__index__() 4.5 >>> operator.index(a) Traceback (most recent call last): File "", line 1, in TypeError: __index__ returned non-(int,long) (type float) >>> b = [1,2,3] >>> b[a] Traceback (most recent call last): File "", line 1, in TypeError: __index__ returned non-(int,long) (type float) You only need to know about this feature if you are implementing a custom integer type or a custom sequence type (both of which are things that most Python users will never do). This particular special method is probably only really documented in the PEP: http://www.python.org/dev/peps/pep-0357/ For my purposes, the important thing is that the method is only supposed to be implemented on types that always exactly represent integers, so it is not usable for converting e.g. floats to integers. Oscar From steve at pearwood.info Thu Jan 3 18:38:08 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Jan 2013 04:38:08 +1100 Subject: [Tutor] how to struct.pack a unicode string? In-Reply-To: References: <1354293788.96740.YahooMailNeo@web163803.mail.gq1.yahoo.com> <50B9B22F.3080605@pearwood.info> <1354455292.11754.YahooMailNeo@web163805.mail.gq1.yahoo.com> <50E2825C.1040105@pearwood.info> Message-ID: <50E5C200.9080504@pearwood.info> On 03/01/13 23:52, eryksun wrote: > On Tue, Jan 1, 2013 at 1:29 AM, Steven D'Aprano wrote: >> >> 2 Since "wide builds" use so much extra memory for the average ASCII >> string, hardly anyone uses them. > > On Windows (and I think OS X, too) a narrow build has been practical > since the wchar_t type is 16-bit. As to Linux I'm most familiar with > Debian, which uses a wide build. Do you know off-hand which distros > release a narrow build? Centos, and presumably therefore Red Hat do. Fedora did, and I presume still do. I didn't actually realize until now that Debian defaults to a wide build. >> But more important than the memory savings, it means that for the first >> time Python's handling of Unicode strings is correct for the entire range >> of all one million plus characters, not just the first 65 thousand. > > Still, be careful not to split 'characters': > > >>> list(normalize('NFC', '\u1ebf')) > ['?'] > >>> list(normalize('NFD', '\u1ebf')) > ['e', '?', '?'] Yes, but presumably if you are normalizing to decomposed forms (NFD or NFKD modes), you're doing it for a reason and are taking care not to let the accents wander away from their base character, unless you want them to. By the way, for anyone else trying this, the normalize function above is not a built-in, it comes from the unicodedata module. More on normalization: https://en.wikipedia.org/wiki/Unicode_equivalence Doing-a-lot-of-presuming-today-ly y'rs, -- Steven From bjorn.madsen at operationsresearchgroup.com Thu Jan 3 19:37:01 2013 From: bjorn.madsen at operationsresearchgroup.com (Bjorn Madsen) Date: Thu, 3 Jan 2013 18:37:01 +0000 Subject: [Tutor] IronPython any tutors with experience out there? Message-ID: Hello PythonTutor - I'm a scientist and very happy with python 2.7. I have been asked to assist a development program where everything is written in dotNET/ C# (visual studio 2012) and luckily Microsoft Visual Studio supports IronPython which is a clean Python implementation in C#, so I can use the Python syntax I'm so familiar with... However ... to interact with the c# modules which my colleagues wrote, I need to add "clr" references. Example: >>> import clr >>> clr.AddReferenceToFile("Mapack.dll") >>> from Mapack import * >>> dir() Unfortunately I can't get it to run and the tutorials after 12 hours of google-reading are terribly sparse. Is there any experience somewhere in the network with IronPython in VSTO-2012 in this forum and what could the top five clr.addreference bugs be? Kind Regards, -- Bjorn -------------- next part -------------- An HTML attachment was scrubbed... URL: From lmergner at gmail.com Thu Jan 3 20:46:43 2013 From: lmergner at gmail.com (Luke Thomas Mergner) Date: Thu, 3 Jan 2013 11:46:43 -0800 Subject: [Tutor] writing effective unittests In-Reply-To: <1357217453.36448.YahooMailNeo@web163805.mail.gq1.yahoo.com> References: <20130102204357.GA1974@lmerg-crunchbang> <1357217453.36448.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: <20130103194641.GA10033@lmerg-crunchbang> * Albert-Jan Roskam wrote: > > > > Hi, > > > > > I am trying to learn a bit of test-driven programming using unittests and > > nosetests. I am having trouble finding resources that explain how to write > > effective tests. I am not a programmer or a student, so I do not have access to > > collegues or classes. I'm hoping that someone knows of a good tutorial that > > I've missed. Based on the O'Reilly 2-Part introduction, I hope that > > learning to write tests will make my code better. > > I am on the digest version of the list, so I haven't gotten a copy of any replies. Apologies if two copies of my last email hit the list, I'm still learning to use mutt. To partially answer my own question, let me tell you what I've learned in the last 48 hours. It is easy to learn that unittest is the standard testing module in Python > 2.6, that it is backported, that it is being improved in Python 3 with new tools. There are a few PyCon videos that discuss this evolution. It is also easy to learn that unittest is based off of prior library for Java (JUnit) and SmallTalk. It is fairly easy to find an introduction to the syntax of writing a test: >class blargTest(unittest.TestCase) > def testFeature(self): > ... do some stuff... > assertTrue('blarg', blarg) And there are a few videos available that walk through how to put this together into a test suite. (I've included what I found below, so that this email will have some value to others.) What am I missing? The biggest problem is that no one is explaining the rationale behind testing. The trivial examples compare integers: 2 == 2. At first glance this seems pointless. I had assumed that tests would attempt to confuse my functions and teach me how to write more robust code. But I *think* now that tests are a way to determine if new code has changed old behaviors. Testing 2 == 2 is trivial, but if the function starts returning 3 in a few months, it would be helpful to know right away. In general, though, I'm finding it difficult to conceptualize what my tests should be doing, testing, and telling me about my code. The second problem is complexity. I'll paraphrase a well known saying about regex: "I wrote a unittest for my Python code, now I have two problems." Just to test my relatively simple code, I'm trying to do things like create temporary file structures, do some datetime parsing, etc. None of this is easy code for me to write at this stage. When a test fails, it could just as easily be a problem with the test code. (I'm unaccountably reminded about infinite regress here.) I *think* the answer must be that the benefit of writing tests on large, complex projects far outweighs the cost. But I've seen even small projects tout their test coverage. I think what I need is a conceptual shift: how do python programmers use unittests? My next step is to look into buying some real books. Resources Agile Testing Blog: http://agiletesting.blogspot.com/ Tool Taxonomy: http://wiki.python.org/moin/PythonTestingToolsTaxonomy Doug Hellman's Blog: http://www.doughellmann.com/articles/pythonmagazine/completely-different/2008-01-testing-tools/ Unittest Docs: http://docs.python.org/3/library/unittest.html Nose Docs https://nose.readthedocs.org/en/latest/testing.html Fixture Docs http://www.farmdev.com/projects/fixture/index.html PyCon 2010: http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2010-new-and-improved-coming-changes-to-unittest-the-standard-library-test-framework-52-3283307 PyCon 2011: http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2011-testing-with-mock-4899484 PyOhio July 2012. This looks perfect except it is missing about half the audio. https://www.youtube.com/watch?v=jTJHQ-zQMk4 Marakana Tech TV: https://www.youtube.com/watch?v=xdY7svOz6n4 At O'Reilly: http://onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html - Luke Mergner From oberoc at gmail.com Thu Jan 3 21:31:07 2013 From: oberoc at gmail.com (Tino Dai) Date: Thu, 3 Jan 2013 15:31:07 -0500 Subject: [Tutor] writing effective unittests In-Reply-To: <20130103194641.GA10033@lmerg-crunchbang> References: <20130102204357.GA1974@lmerg-crunchbang> <1357217453.36448.YahooMailNeo@web163805.mail.gq1.yahoo.com> <20130103194641.GA10033@lmerg-crunchbang> Message-ID: I think what I need is a conceptual shift: how do python programmers use > unittests? > > Here at the Library, we use unit test to test the cases that have many known inputs. For example, some of the data could come in "foo bar baz", and some others could come in as "foo, bar, baz", and others could come in "foo; bar; baz". As we code for each one of these cases, we write tests to make sure that changes that we make don't break any of our former code. I think that TDD is a good thing to strive for, but in most cases is an ideal that can't be reached in most cases. Hope that helps, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From jared at thehelloworldprogram.com Thu Jan 3 21:59:46 2013 From: jared at thehelloworldprogram.com (Jared Nielsen) Date: Thu, 3 Jan 2013 12:59:46 -0800 Subject: [Tutor] python as poetry Message-ID: I don't know if it's appropriate to post things like this on the list, but I've learned a lot from this group and thought I'd share something I think you all will enjoy: http://www.thehelloworldprogram.com/videos/poetry-corner-red-wheelbarrow/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 3 22:55:24 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 03 Jan 2013 21:55:24 +0000 Subject: [Tutor] writing effective unittests In-Reply-To: <20130103194641.GA10033@lmerg-crunchbang> References: <20130102204357.GA1974@lmerg-crunchbang> <1357217453.36448.YahooMailNeo@web163805.mail.gq1.yahoo.com> <20130103194641.GA10033@lmerg-crunchbang> Message-ID: On 03/01/13 19:46, Luke Thomas Mergner wrote: > What am I missing? The biggest problem is that no one is explaining the rationale behind testing. See my other reply and check out the references to programming by contract, pre/post conditions and invariants. Those are all good things to test. Invariants are probably hardest but also most powerful IMHO. But viesw your code as a contract with the user. What can the user put in, what should they get out? What could break it? > I think what I need is a conceptual shift: how do python programmers use unittests? Personally I only use TDD and formal unit tests when I'm writing something a) big and/or complex b) reusable - I'll be coming back to it in the future For small, one-off tools and scripts the overhead is usually not worth while. And they are never 100% reliable, bugs will still sneak through. So for one-offs I just do informal testing. In most cases with TDD I stick to black box testing but if its a reuseable class or a framework then I'll probably drop down to white box and if it's mission or safety critical I'll do glass box testing (ie 100% code coverage) - That's to say in about 3 projects in 30 years... > My next step is to look into buying some real books. I'd only go there if you are really comfortable with programming in Python. Learn and use the principles but don't sweat over it until you really need to. It's more important to be comfortable writing good Python code than writing good tests for bad code! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Fri Jan 4 00:20:20 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 3 Jan 2013 23:20:20 +0000 Subject: [Tutor] IronPython any tutors with experience out there? In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474180C9331@SCACMX008.exchad.jpmchase.net> Bjorn Madsen wrote: > > Hello PythonTutor > - I'm a scientist?and very happy with python 2.7.?I have been asked to assist a development program where > everything is written in dotNET/ C# (visual studio 2012) and luckily Microsoft Visual Studio supports IronPython > which is a clean Python implementation in C#, so I can use the Python syntax I'm so familiar with... > > However ... to interact with the c# modules which my colleagues wrote, I need to add "clr" references. > > Example: > >>> import clr > >>> clr.AddReferenceToFile("Mapack.dll") > >>> from Mapack import * > >>> dir() > > Unfortunately I can't get it to run and the tutorials after 12 hours of google-reading are terribly sparse.?Is > there any experience somewhere in the network with IronPython in VSTO-2012 in this forum and what could the top > five clr.addreference bugs be? If nobody responds satisfactorily on this list, you may have better luck with the main Python list. Your question is not really in the realm of "teaching python" which is this list's main focus. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Fri Jan 4 00:41:20 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Jan 2013 10:41:20 +1100 Subject: [Tutor] writing effective unittests In-Reply-To: <20130103194641.GA10033@lmerg-crunchbang> References: <20130102204357.GA1974@lmerg-crunchbang> <1357217453.36448.YahooMailNeo@web163805.mail.gq1.yahoo.com> <20130103194641.GA10033@lmerg-crunchbang> Message-ID: <50E61720.7050905@pearwood.info> Hi Luke, My responses inline below. On 04/01/13 06:46, Luke Thomas Mergner wrote: > I am on the digest version of the list, so I haven't gotten a copy of >any replies. All the more reason not to be on the digest version. But you should have received replies *in the digest*. (By the way, thank you for editing the subject line to something meaningful.) > What am I missing? The biggest problem is that no one is explaining >the rationale behind testing. You test software so that you know it does what you expect. Until you actually try it, how do you know it will work as expected? I'm reminded of a famous quote from Donald Knuth, which if memory serves goes something like this: "Beware of bugs in the above code, I have only proven it is correct, not tested it." All testing is aimed at making sure the software does what you want it to do and does not contain bugs. > The trivial examples compare integers: 2 == 2. At first glance this >seems pointless. As given, that is pointless, since there is no possible way for 2 to fail to be 2. A less pointless example would be: x = some_calculation(a, b, c) # expected to return 2 assertEqual(x, 2) # x might not be 2, so we test that it is > I had assumed that tests would attempt to confuse my functions and >teach me how to write more robust code. That is part of it. A solid test suite should cover unexpected input as well as expected input, to ensure that you code does the right thing when faced with bad input. In my earlier post, which I hope you received, I gave an toy example of testing a function that takes at most one integer argument and returns a string. Some of the tests I wrote test that the function *correctly (and safely) fails* with TypeError if you pass more than one argument, or if the argument is not an int. >But I *think* now that tests are a way to determine if new code has > changed old behaviors. Testing 2 == 2 is trivial, but if the > function starts returning 3 in a few months, it would be helpful to >know right away. Yes, exactly! We can write different sorts of tests: * Doc tests are (mostly) intended to act as documentation. The problem with documentation is that it can get out of date as the software changes. How do you know when the documentation is out of date? Because the doc tests fail! * Regression tests are intended to warn you if a bug has come back. Every time you fix a reported bug, you should have a regression test for that bug, so that if any future change accidentally *regresses* the code and reintroduces that bug, you will find out immediately. * Unit tests are intended for testing that code behaves as expected, that parts of the public interface that you expect exist actually does exist. There's no point documenting that you have a class Spam if the class doesn't actually exist, so you have a unit test that confirms that Spam exists, and that it behaves as you expect. (Note that the concept of "unit tests" is more general than the things you write with the unittest module. The unittest module is a framework for writing unit tests, but there are other frameworks, like nose.) * Blackbox testing is when you treat functions and methods as black boxes. Since you can't see inside them, you can only test things which are public knowledge. E.g. "if I pass this input to the function, I should get this output". * Whitebox testing is the opposite: you test based on your knowledge of the function's internal details. E.g. "if I pass this input to the function, it will run the code path A->B->C; but if I pass this other input, it will run the code path A->D->E->C. Therefore I need to test both inputs." The problem with whitebox testing is that if you change the function's implementation, your tests may become obsolete. But the advantage is that the tests cover more of the possible things that could happen. * Fuzz testing is when you check how robust your code is by actually making *random changes to the data*, then seeing how your code responds or fails. One early example was "The Monkey" on Apple Macs in 1983, which fed random mouse clicks and key presses to discover bugs in MacPaint. There are many other forms of testing that are possible: https://en.wikipedia.org/wiki/Software_testing But in general, any testing is better than no testing. My further responses to follow later in the day. -- Steven From alan.gauld at btinternet.com Fri Jan 4 01:07:02 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 04 Jan 2013 00:07:02 +0000 Subject: [Tutor] IronPython any tutors with experience out there? In-Reply-To: References: Message-ID: On 03/01/13 18:37, Bjorn Madsen wrote: > However ... to interact with the c# modules which my colleagues wrote, I > need to add "clr" references. > > Example: >>>> import clr >>>> clr.AddReferenceToFile("Mapack.dll") >>>> from Mapack import * >>>> dir() > > Unfortunately I can't get it to run So does anything work? Is the import OK? Are there any error messages? Can you call any of the other CLR functions? Can you get a basic 'hello world' to run under .NET? I've never used IronPython but I have played around with C# and VB.Net on an earlier .NET framework (V2?) There should be a bunch of functions you can access via CLR, check that they work first to prove CLR integration is OK. For example can you use AddReference() to access a standard .NET assembly rather than AddReferenceToFile() which is I assume for DLLs. Finally there is an active gmane IronPython news group which you could try for more focussed help... gmane.comp.python.ironpython.user It is probably sourced from the IronPython mailing list of you prefer that... http://mail.python.org/mailman/listinfo/ironpython-users Finally I did find this reference: http://stackoverflow.com/questions/3692539/clr-addreferencetofile-fails-in-ironpython-2-7 Which notes that you can only import DLLS compiled for .NET v4 in IronPython 2.7. Might that be the problem? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From brian.van.den.broek at gmail.com Fri Jan 4 08:10:13 2013 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Fri, 4 Jan 2013 02:10:13 -0500 Subject: [Tutor] writing effective unittests In-Reply-To: <20130103194641.GA10033@lmerg-crunchbang> References: <20130102204357.GA1974@lmerg-crunchbang> <1357217453.36448.YahooMailNeo@web163805.mail.gq1.yahoo.com> <20130103194641.GA10033@lmerg-crunchbang> Message-ID: On 3 January 2013 14:46, Luke Thomas Mergner wrote: > * Albert-Jan Roskam wrote: > >> >> >> > Hi, >> >> > >> > I am trying to learn a bit of test-driven programming using unittests and >> > nosetests. I am having trouble finding resources that explain how to write >> > effective tests. I am not a programmer or a student, so I do not have access to > To partially answer my own question, let me tell you what I've learned in the last 48 hours. It is easy to learn that unittest is the standard testing module in Python > 2.6, that it is backported, that it is being improved in Python 3 with new tools. There are a few PyCon videos that discuss this evolution. It is also easy to learn that unittest is based off of prior library for Java (JUnit) and SmallTalk. It is fairly easy to find an introduction to the syntax of writing a test: > And there are a few videos available that walk through how to put this together into a test suite. (I've included what I found below, so that this email will have some value to others.) > > What am I missing? The biggest problem is that no one is explaining the rationale behind testing. The trivial examples compare integers: 2 == 2. At first glance this seems pointless. I had assumed that tests would attempt to confuse my functions and teach me how to write more robust code. But I *think* now that tests are a way to determine if new code has changed old behaviors. Testing 2 == 2 is trivial, but if the function starts returning 3 in a few months, it would be helpful to know right away. In general, though, I'm finding it difficult to conceptualize what my tests should be doing, testing, and telling me about my code. Hi Luke, First, I should like to commend your post; collecting together the results of your research and posting it is a valuable thing to do. While I agree with Steven that you'd be better off not taking the list as a digest, for me at least, the mild irritation that digest use imposes is small compared to the goodwill the effort shown produces. Second, I don't test nearly as much as I ought. So, read with a grain of salt :-) Now, for the meat. A key idea that was implicit in Steven's first reply might be better made explicit. When testing, you want to look for odd or edge cases where things might break and embed tests that will let you know if they do. What counts as an edge or odd case is obviously context dependent. But, if dealing with an arithmetical function of one input, you'd generally want tests for at least 0, 1, -1, some large positive, some large negative, and small and large positive and negative non-integer rational numbers. If writing against 2.x, you'd also want an integer large enough to be a long rather than an int, etc. If testing a function that takes one string, you'd want tests for at least the empty string, a string consisting solely of whitespace, a single character string, a string with "odd whitespacing that you wouldn ' t expect", strings in mixed case, ones with punctuation, etc. Another principle that I use to generate tests: while writing code, every time I find myself considering some possibility and thinking "But, that's impossible!" I try to put in a test to ensure that the impossible actually is. http://www.youtube.com/watch%3Fv%3DD58LpHBnvsI I didn't try to find the context, but testing 2 == 2 does seem a bit pointless. However, a similar sort of test might be worthwhile. Consider: >>> class A(object): def __eq__(self, other): return False >>> a=A() >>> a==a False >>> Now, one might think: "But that's such a stupid bug. I'd never do that". If so tempted, go watch the link above :-) In seriousness, the way that sort of test will help isn't so much to confirm that the code works as intended when written, but that it continues to work several moths later when you've forgotten most of it and need to tweak just one thing that couldn't possibly affect other parts of the code. HTH, Brian vdB From alan.gauld at btinternet.com Fri Jan 4 09:34:33 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 04 Jan 2013 08:34:33 +0000 Subject: [Tutor] writing effective unittests In-Reply-To: References: <20130102204357.GA1974@lmerg-crunchbang> <1357217453.36448.YahooMailNeo@web163805.mail.gq1.yahoo.com> <20130103194641.GA10033@lmerg-crunchbang> Message-ID: On 04/01/13 07:10, Brian van den Broek wrote: ... > confirm that the code works as intended when written, but that it > continues to work several moths later moths? They'll be the bugs I guess? Sorry I couldn't resist :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From brian.van.den.broek at gmail.com Fri Jan 4 10:15:35 2013 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Fri, 4 Jan 2013 04:15:35 -0500 Subject: [Tutor] writing effective unittests In-Reply-To: References: <20130102204357.GA1974@lmerg-crunchbang> <1357217453.36448.YahooMailNeo@web163805.mail.gq1.yahoo.com> <20130103194641.GA10033@lmerg-crunchbang> Message-ID: On 4 January 2013 03:34, Alan Gauld wrote: > On 04/01/13 07:10, Brian van den Broek wrote: > ... > >> confirm that the code works as intended when written, but that it >> continues to work several moths later > > > moths? They'll be the bugs I guess? > > Sorry I couldn't resist :-) :-) I shouldn't like to meet the man who could. From yanglei.fage at gmail.com Fri Jan 4 10:17:14 2013 From: yanglei.fage at gmail.com (lei yang) Date: Fri, 4 Jan 2013 17:17:14 +0800 Subject: [Tutor] help about to how many times the function called Message-ID: Hi experts I have a function will print PASS status def print_pass(t_elapsed): """ Print PASS to stdout with PASS (green) color. """ print_stdout(bcolors.PASS + "PASS" + bcolors.ENDC + " (%.2f s)" % t_elapsed) I want to calculate the pass number, so I want to get " how many times this function called" any help? Lei From steve at pearwood.info Fri Jan 4 10:25:08 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Jan 2013 20:25:08 +1100 Subject: [Tutor] help about to how many times the function called In-Reply-To: References: Message-ID: <50E69FF4.6080503@pearwood.info> On 04/01/13 20:17, lei yang wrote: > Hi experts > > I have a function will print PASS status > > > > def print_pass(t_elapsed): > """ > Print PASS to stdout with PASS (green) color. > """ > print_stdout(bcolors.PASS + "PASS" + bcolors.ENDC + " (%.2f s)" % t_elapsed) > > I want to calculate the pass number, so I want to get " how many times > this function called" > > any help? how_many_times = 0 def print_pass(t_elapsed): """ Print PASS to stdout with PASS (green) color. """ global how_many_times how_many_times += 1 print_stdout(bcolors.PASS + "PASS" + bcolors.ENDC + " (%.2f s)" % t_elapsed) -- Steven From ghasemmg01 at leedslearning.net Fri Jan 4 12:34:57 2013 From: ghasemmg01 at leedslearning.net (Ghadir Ghasemi) Date: Fri, 4 Jan 2013 11:34:57 +0000 Subject: [Tutor] Vending machine program Message-ID: <010FB2F3C55002408EE1404538D1B6AE030D83794786@LLN-SPP-ES-04.user01.lln.local> H I wanted to create a program called vending machine and I wondered if you could do it so I can find out how to do it. Here is how it should work like: A food vending machine accepts 10p, 20p, 50p and ?1 coins. One or more coins are inserted and the current credit is calculated and displayed. A product is selected from those available. The system checks to see if there is enough credit to purchase the product chosen. If there is not enough credit the system displays an error message. If there is enough credit it dispenses the product, updates the credit available and displays the remaining credit. Further selections can be made if there is enough credit. The vending machine simulation should have five products and prices. Design, code, test and evaluate a program for this simulation. Thank you From hugo.yoshi at gmail.com Fri Jan 4 13:43:24 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 4 Jan 2013 13:43:24 +0100 Subject: [Tutor] Vending machine program In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D83794786@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D83794786@LLN-SPP-ES-04.user01.lln.local> Message-ID: On Fri, Jan 4, 2013 at 12:34 PM, Ghadir Ghasemi < ghasemmg01 at leedslearning.net> wrote: > H I wanted to create a program called vending machine and I wondered if > you could do it so I can find out how to do it. > No. This list is meant to help people with specific questions about their python programs. If you make an attempt at writing this program and get stuck or have questions on how to proceed, we will be happy to give you hints and help you out. But we won't do your work for you. Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From ufukeskici at gmail.com Fri Jan 4 14:03:03 2013 From: ufukeskici at gmail.com (Ufuk Eskici) Date: Fri, 4 Jan 2013 15:03:03 +0200 Subject: [Tutor] Trouble importing Paramiko In-Reply-To: References: <50DC3F62.7090109@pearwood.info> <50DC4389.5000604@pearwood.info> <50E40117.4050707@pearwood.info> Message-ID: Hello Hugo, I removed all related softwares from my PC and tried to re-install everyting. At the last step, this command fails (instructions: http://vijaymurthy.blogspot.com/2011/03/installing-paramiko-for-windows.html ) **** C:\paramiko-1.7.4>python setup.py build --compiler=mingw32 bdist_wininst 'python' is not recognized as an internal or external command, operable program or batch file. C:\paramiko-1.7.4> **** What is wrong? 2013/1/2 Hugo Arts > On Wed, Jan 2, 2013 at 10:48 AM, Ufuk Eskici wrote: > >> Hello Steven, >> >> I've written this before: >> >> "My Python version is 2.7.3 and it is installed in "C:\Python27 (on the >> web, it says Paramiko-1.7.4 is supported with Python 2.7)" >> >> so I'm using the correct Python verion (2.7.3). But I dont know why I'm >> getting errors during Paramiko installation as I mentioned before. >> >> > That is very interesting, because when you tried my earlier suggestion to > use "python setup.py install" the error messages you gave us came very > clearly from python 3.3, not python 2.7.3. Look more closely at some of > those error messages: > > > File "c:\python33\lib\site-packages\paramiko-1.7.4-py3.3. > egg\paramiko\transport.py", line 353 > > out = ' > > ^ > > SyntaxError: invalid syntax > > C:\python33 is definitely not C:\python27. That looks to me like you have > two versions of python installed on your machine, both python 3.3 and > python 2.7. I an only make an educated guess at this, but probably when you > invoke python on your command line, it's actually python 3.3 that is > started. You can verify this by simply starting a command line, going to > your C:\ directory, typing in python, and looking at the version number > that comes up. If it is indeed true you have two versions of python > installed, try the installation step again, but now make absolutely sure > you use the correct version of python to run the setup script, like this: > > C:\python27\python.exe setup.py install > > That will use python 2.7 to run the installation script, and *that* in > turn will make sure paramiko is actually installed for the correct python > version. > > HTH, > Hugo > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Fri Jan 4 14:30:59 2013 From: wprins at gmail.com (Walter Prins) Date: Fri, 4 Jan 2013 13:30:59 +0000 Subject: [Tutor] Trouble importing Paramiko In-Reply-To: References: <50DC3F62.7090109@pearwood.info> <50DC4389.5000604@pearwood.info> <50E40117.4050707@pearwood.info> Message-ID: Hi Ufuk, On 4 January 2013 13:03, Ufuk Eskici wrote: > Hello Hugo, > > I removed all related softwares from my PC and tried to re-install > everyting. > > At the last step, this command fails (instructions: > http://vijaymurthy.blogspot.com/2011/03/installing-paramiko-for-windows.html > ) > > **** > C:\paramiko-1.7.4>python setup.py build --compiler=mingw32 bdist_wininst > 'python' is not recognized as an internal or external command, > operable program or batch file. > > Erm, this is actually telling you the problem directly: The system cannot find the "python" command. To explain: the Windows command interpreter has a list of directories (folders) that it searches for matching programs when you enter a command at the commant prompt. When it cannot find any program matching the name entered as a command, it duly displays the above message. Here's some background/references for this so you can improve your understanding of what's going on (as a programmer you really need to understand this stuff): http://superuser.com/questions/284342/what-are-path-and-other-environment-variables-and-how-can-i-set-or-use-them http://www.voidspace.org.uk/python/articles/command_line.shtml So, the implication of you receiving this message is that your Python interpreter location is not on this system path list. To add it, click "Start", then right click "Computer", then "Properties", then click "Advanced system settings" on the left, click the "Environment variables" button at the bottom of the dialog, then look for the variable named "Path" under the section "System variables", click on it to select it then click the "Edit" button, then add ";C:\Python27\" to the existing path list (without the quotes and making sure to include the separator semicolon). Click "OK" and exit all the dialogs. Then re-open a command prompt, and at the prompt type "python" with no arguments and press enter. This should now open up the Python interpreter which if successful will prove that the PATH change was done succesfully. Aside, if you install Python using ActiveState's distribution, this step is done automatically for you. In case you're interested, you can get ActiveState's Python distribution here: http://www.activestate.com/activepython/downloads Note that although they request you to register, it is not obligatory. HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Jan 4 18:41:33 2013 From: bgailer at gmail.com (bob gailer) Date: Fri, 04 Jan 2013 12:41:33 -0500 Subject: [Tutor] help about to how many times the function called In-Reply-To: <50E69FF4.6080503@pearwood.info> References: <50E69FF4.6080503@pearwood.info> Message-ID: <50E7144D.8050601@gmail.com> On 1/4/2013 4:25 AM, Steven D'Aprano wrote: > On 04/01/13 20:17, lei yang wrote: >> Hi experts >> >> I have a function will print PASS status >> >> >> >> def print_pass(t_elapsed): >> """ >> Print PASS to stdout with PASS (green) color. >> """ >> print_stdout(bcolors.PASS + "PASS" + bcolors.ENDC + " (%.2f s)" >> % t_elapsed) >> >> I want to calculate the pass number, so I want to get " how many times >> this function called" It is unclear to me what you want to do with the pass number or what PASS means or where bcolors comes from. If you don't need to refer to the pass number outside the function another way (better IMHO): def print_pass(t_elapsed, how_many_times=0): """ Print PASS to stdout with PASS (green) color. """ how_many_times += 1 print_stdout(bcolors.PASS + "PASS" + bcolors.ENDC + " (%.2f s)" % t_elapsed) I for one would appreciate a more complete explanation. -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Fri Jan 4 18:47:22 2013 From: bgailer at gmail.com (bob gailer) Date: Fri, 04 Jan 2013 12:47:22 -0500 Subject: [Tutor] Vending machine program In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D83794786@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D83794786@LLN-SPP-ES-04.user01.lln.local> Message-ID: <50E715AA.5010006@gmail.com> On 1/4/2013 6:34 AM, Ghadir Ghasemi wrote: > H I wanted to create a program called vending machine and I wondered if you could do it so I can find out how to do it. > Here is how it should work like: > > A food vending machine accepts 10p, 20p, 50p and ?1 coins. > One or more coins are inserted and the current credit is calculated and displayed. > A product is selected from those available. The system checks to see if there is enough credit to purchase the product chosen. > If there is not enough credit the system displays an error message. > If there is enough credit it dispenses the product, updates the credit available and displays the remaining credit. > Further selections can be made if there is enough credit. > The vending machine simulation should have five products and prices. Design, code, test and evaluate a program for this simulation. Where did you get this assignment? What prior programming experience do you have? As already mentioned we prefer to not do your work for you. Further selections can be made if there is enough credit. This is confusing. You could drop that line with no ill effect. I am not sure what it even means. How far did you get in the steps suggested? Did you attempt a design? -- Bob Gailer 919-636-4239 Chapel Hill NC From msirenef at lightbird.net Fri Jan 4 19:54:10 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Fri, 04 Jan 2013 13:54:10 -0500 Subject: [Tutor] Vending machine program In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D83794786@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D83794786@LLN-SPP-ES-04.user01.lln.local> Message-ID: <50E72552.9020509@lightbird.net> On 01/04/2013 06:34 AM, Ghadir Ghasemi wrote: > H I wanted to create a program called vending machine and I wondered if you could do it so I can find out how to do it. > Here is how it should work like: > > A food vending machine accepts 10p, 20p, 50p and ?1 coins. > One or more coins are inserted and the current credit is calculated and displayed. > A product is selected from those available. The system checks to see if there is enough credit to purchase the product chosen. > If there is not enough credit the system displays an error message. > If there is enough credit it dispenses the product, updates the credit available and displays the remaining credit. > Further selections can be made if there is enough credit. > The vending machine simulation should have five products and prices. Design, code, test and evaluate a program for this simulation. > > Thank you > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I would suggest a general design with VendingMachine class with these properties: - product list (if you don't need to handle running out of products) - credit (int, in pence) - method to list products and credit - method to add to credit - method to buy a product A separate class that handles user interface: main loop, accepting the commands: add amount, select product; a method that runs continuously until a valid command is provided & then the command is returned. In the main loop, products are listed, user provides the command, command is delegated to one of VendingMachine methods and then loop goes back to the beginning. Hope this helps, -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From fal at libero.it Fri Jan 4 20:20:53 2013 From: fal at libero.it (Francesco Loffredo) Date: Fri, 04 Jan 2013 20:20:53 +0100 Subject: [Tutor] invalid literal for int error in Game loop In-Reply-To: <66098356-604F-47DB-A78B-2CC859623BBE@gmail.com> References: <50D37A37.4070805@pearwood.info> <50D37E1C.3070901@davea.name> <66098356-604F-47DB-A78B-2CC859623BBE@gmail.com> Message-ID: <50E72B95.8090009@libero.it> Ciaran Mooney wrote: > Thanks for the feedback. > > Steve, If I set the FPS to a default of say 30, the game seems to run at this default FPS=30 regardless of the key pressed in the > function. > > Dave, If I remove the the default value at the start of the function and add it to elif in the loop I get the following error: > > > Traceback (most recent call last): > File "/Users/callanmooneys/Desktop/Pythoin Programmes/Aliens Game/dodger ver 3 instructons.py", line 139, in > FPS = difficultyLevel() > File "/Users/callanmooneys/Desktop/Pythoin Programmes/Aliens Game/dodger ver 3 instructons.py", line 50, in difficultyLevel > return FPS > UnboundLocalError: local variable 'FPS' referenced before assignment > > > I wondered if i could set FPS to nether a string or integer and just declare it by setting FPS=None but I get the following error: > > Traceback (most recent call last): > File "/Users/callanmooneys/Desktop/Pythoin Programmes/Aliens Game/dodger ver 3 instructons.py", line 301, in > mainClock.tick(FPS) > TypeError: a float is required > > Cheers > Ciaran As far as I understood your problem, it seems that you need the difficulty level to be changed at the player's will during the game. In this case, the function gets called many times, maybe at every game loop. If this is true, you need a global FPS value to be changed by the player's choice, not one that you create inside the function. Try this: # put the line below out of the function definition and out of the game loop, usually together with other default program settings FPS = 30 # you want the game to be beginner-friendly, don't you? def difficultyLevel(): global FPS windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT),pygame.FULLSCREEN) windowSurface.fill(BACKGROUNDCOLOUR) drawText('LEVEL OF PLAY', font3, windowSurface, (WINDOWWIDTH/6), (WINDOWHEIGHT/6)) drawText('B: Your an absoulute Begineer', font3, windowSurface, (WINDOWWIDTH/6)-100, (WINDOWHEIGHT/6)+100) drawText('M: Not Too Snazy', font3, windowSurface, (WINDOWWIDTH/6)-100, (WINDOWHEIGHT/6)+150) drawText('H: Deathwish' ,font3,windowSurface, (WINDOWWIDTH/6)-100, (WINDOWHEIGHT/6)+200) pygame.display.update() for event in pygame.event.get(): if event.type == QUIT: terminate() if event.type == KEYDOWN: if event.key == ord('b'): FPS = 30 elif event.key == ord('m'): FPS = 70 elif event.key == ord('h'): FPS = 120 return FPS ... then let us know. Hope that helps Francesco -------------- next part -------------- An HTML attachment was scrubbed... URL: From ufukeskici at gmail.com Fri Jan 4 22:44:26 2013 From: ufukeskici at gmail.com (Ufuk Eskici) Date: Fri, 4 Jan 2013 23:44:26 +0200 Subject: [Tutor] Trouble importing Paramiko In-Reply-To: References: <50DC3F62.7090109@pearwood.info> <50DC4389.5000604@pearwood.info> <50E40117.4050707@pearwood.info> Message-ID: Hi Walter, Adding Python location to sytem path works. :-) Thanks a lot! Ufuk 2013/1/4 Walter Prins > Hi Ufuk, > > On 4 January 2013 13:03, Ufuk Eskici wrote: > >> Hello Hugo, >> >> I removed all related softwares from my PC and tried to re-install >> everyting. >> >> At the last step, this command fails (instructions: >> http://vijaymurthy.blogspot.com/2011/03/installing-paramiko-for-windows.html >> ) >> >> **** >> C:\paramiko-1.7.4>python setup.py build --compiler=mingw32 bdist_wininst >> 'python' is not recognized as an internal or external command, >> operable program or batch file. >> >> > Erm, this is actually telling you the problem directly: The system cannot > find the "python" command. To explain: the Windows command interpreter > has a list of directories (folders) that it searches for matching programs > when you enter a command at the commant prompt. When it cannot find any > program matching the name entered as a command, it duly displays the above > message. > > Here's some background/references for this so you can improve your > understanding of what's going on (as a programmer you really need to > understand this stuff): > > http://superuser.com/questions/284342/what-are-path-and-other-environment-variables-and-how-can-i-set-or-use-them > http://www.voidspace.org.uk/python/articles/command_line.shtml > > So, the implication of you receiving this message is that your Python > interpreter location is not on this system path list. To add it, click > "Start", then right click "Computer", then "Properties", then click > "Advanced system settings" on the left, click the "Environment variables" > button at the bottom of the dialog, then look for the variable named "Path" > under the section "System variables", click on it to select it then click > the "Edit" button, then add ";C:\Python27\" to the existing path list > (without the quotes and making sure to include the separator semicolon). > Click "OK" and exit all the dialogs. Then re-open a command prompt, and at > the prompt type "python" with no arguments and press enter. This should > now open up the Python interpreter which if successful will prove that the > PATH change was done succesfully. > > Aside, if you install Python using ActiveState's distribution, this step > is done automatically for you. In case you're interested, you can get > ActiveState's Python distribution here: > http://www.activestate.com/activepython/downloads > Note that although they request you to register, it is not obligatory. > > HTH, > > Walter > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ghasemmg01 at leedslearning.net Fri Jan 4 23:15:21 2013 From: ghasemmg01 at leedslearning.net (Ghadir Ghasemi) Date: Fri, 4 Jan 2013 22:15:21 +0000 Subject: [Tutor] stuck on a new program Message-ID: <010FB2F3C55002408EE1404538D1B6AE030D83794787@LLN-SPP-ES-04.user01.lln.local> Hi guys I recently created a binary to denary and denary to binary convertor program. It is pretty much finished but I can't get it to work. Can you spot the fault in it please and tell me how it coul be fixed? print("==================") print("1 = binary to denary") print("2 = denary to binary") return = input("enter an option) menu_option = get_option() while True: menu_option = get_option() if menu_option == '1': a = int(input('please enter an 8 bit binary number: '),2); print("the result is", a) if menu_option == '2': b= bin(int(input('please enter a denary number: ')));print("the result is", b) Thank you so much From hugo.yoshi at gmail.com Fri Jan 4 23:43:24 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 4 Jan 2013 23:43:24 +0100 Subject: [Tutor] stuck on a new program In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D83794787@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D83794787@LLN-SPP-ES-04.user01.lln.local> Message-ID: On Fri, Jan 4, 2013 at 11:15 PM, Ghadir Ghasemi < ghasemmg01 at leedslearning.net> wrote: > Hi guys I recently created a binary to denary and denary to binary > convertor program. It is pretty much finished but I can't get it to work. > Can you spot the fault in it please and tell me how it coul be fixed? > > print("==================") > print("1 = binary to denary") > print("2 = denary to binary") > > > return = input("enter an option) > menu_option = get_option() > > > while True: > menu_option = get_option() > > if menu_option == '1': > a = int(input('please enter an 8 bit binary number: '),2); > print("the result is", a) > > if menu_option == '2': > b= bin(int(input('please enter a denary number: ')));print("the > result is", b) > > There are several errors here, in fact. The first error you made is not including the output of your program when you attempted to run it. There should have been an error message of some form, with an indicator of where the error happened. For example, if I run the program on the command line, I get this: File "test.py", line 6 return = input("enter an option) ^ SyntaxError: invalid syntax always, always always include any error messages you get when you send an e-mail to this list or other programming lists. It may not be absolutely necessary for small programs like this, but it still saves everyone a bunch of time. And if there are no error messages, tell us what you expected to happen, and what happened instead. "I can't get it to work" is the least useful problem description in the history of mankind, giving absolutely zero helpful information that can be used to solve the problem. Help us help you, please. The error indicated by python has to do with keywords: python has several "keywords" which are used to indicate certain structures in the language. Examples are "while", "if", and "return". These keywords have a special meaning in the language, and can thus not be used as variable names. You tried to use return as a variable name, which is why the syntax error shows up on that line. There are other mistakes in this program: the get_option() function, for example, which you have used in this program, is not defined anywhere. You used it but never told python what it means. Thus if I corrected the return error and tried to run the program again, python would complain about the "get_option" name not existing (or did you not include the entire program in this e-mail? That would be another mistake. If you did not include an error, and we cannot run the program to see what it is, helping you becomes very difficult indeed). So assuming we fixed that missing function, the program now runs without error messages. However, there are four lines at the bottom that will never be reached by the computer. Why not? Look at these lines above it: while True: menu_option = get_option() what does it do? Well, "while True" describes a loop that runs forever. The only line inside the loop is "menu_option = get_option(). So, the program will keep running that line for eternity, and never reach the two "if" statements below. Can you fix it now? HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jan 5 02:26:49 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 05 Jan 2013 01:26:49 +0000 Subject: [Tutor] Vending machine program In-Reply-To: <50E715AA.5010006@gmail.com> References: <010FB2F3C55002408EE1404538D1B6AE030D83794786@LLN-SPP-ES-04.user01.lln.local> <50E715AA.5010006@gmail.com> Message-ID: On 04/01/13 17:47, bob gailer wrote: > > Further selections can be made if there is enough credit. > > This is confusing. You could drop that line with no ill effect. I am not > sure what it even means. It seemed straightforward enough to me Bob. If you put in $10 and buy a candy bar for $6 you have $4 credit left. You can then choose another item provided it costs less than $4. It just implies another level of loop in the design. In fact given the detail of the spec its hard to see what we could add by way of help until the OP produces some code to critique. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dancingbush at gmail.com Sat Jan 5 12:10:06 2013 From: dancingbush at gmail.com (Ciaran Mooney) Date: Sat, 5 Jan 2013 11:10:06 +0000 Subject: [Tutor] invalid literal for int error in Game loop In-Reply-To: <50E72B95.8090009@libero.it> References: <50D37A37.4070805@pearwood.info> <50D37E1C.3070901@davea.name> <66098356-604F-47DB-A78B-2CC859623BBE@gmail.com> <50E72B95.8090009@libero.it> Message-ID: <0CE70D77-79DD-4ED3-92DE-31C73957DDC2@gmail.com> On 4 Jan 2013, at 19:20, Francesco Loffredo wrote: > Ciaran Mooney wrote: >> Thanks for the feedback. >> >> Steve, If I set the FPS to a default of say 30, the game seems to run at this default FPS=30 regardless of the key pressed in the function. >> >> Dave, If I remove the the default value at the start of the function and add it to elif in the loop I get the following error: >> >> >> Traceback (most recent call last): >> File "/Users/callanmooneys/Desktop/Pythoin Programmes/Aliens Game/dodger ver 3 instructons.py", line 139, in >> FPS = difficultyLevel() >> File "/Users/callanmooneys/Desktop/Pythoin Programmes/Aliens Game/dodger ver 3 instructons.py", line 50, in difficultyLevel >> return FPS >> UnboundLocalError: local variable 'FPS' referenced before assignment >> >> >> I wondered if i could set FPS to nether a string or integer and just declare it by setting FPS=None but I get the following error: >> >> Traceback (most recent call last): >> File "/Users/callanmooneys/Desktop/Pythoin Programmes/Aliens Game/dodger ver 3 instructons.py", line 301, in >> mainClock.tick(FPS) >> TypeError: a float is required >> >> Cheers >> Ciaran > As far as I understood your problem, it seems that you need the difficulty level to be changed at the player's will during the game. In this case, the function gets called many times, maybe at every game loop. If this is true, you need a global FPS value to be changed by the player's choice, not one that you create inside the function. > > Try this: > > # put the line below out of the function definition and out of the game loop, usually together with other default program settings > FPS = 30 # you want the game to be beginner-friendly, don't you? > > def difficultyLevel(): > global FPS > windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT),pygame.FULLSCREEN) > windowSurface.fill(BACKGROUNDCOLOUR) > drawText('LEVEL OF PLAY', font3, windowSurface, (WINDOWWIDTH/6), (WINDOWHEIGHT/6)) > drawText('B: Your an absoulute Begineer', font3, windowSurface, (WINDOWWIDTH/6)-100, (WINDOWHEIGHT/6)+100) > drawText('M: Not Too Snazy', font3, windowSurface, (WINDOWWIDTH/6)-100, (WINDOWHEIGHT/6)+150) > drawText('H: Deathwish' ,font3,windowSurface, (WINDOWWIDTH/6)-100, (WINDOWHEIGHT/6)+200) > pygame.display.update() > > for event in pygame.event.get(): > if event.type == QUIT: > terminate() > > if event.type == KEYDOWN: > if event.key == ord('b'): > FPS = 30 > elif event.key == ord('m'): > FPS = 70 > elif event.key == ord('h'): > FPS = 120 > > return FPS > > ... then let us know. > Hope that helps > > Francesco Thanks Francesco, Ill give it a go and come back to u. Ciaran > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Jan 6 01:21:32 2013 From: bgailer at gmail.com (bob gailer) Date: Sat, 05 Jan 2013 19:21:32 -0500 Subject: [Tutor] Vending machine program In-Reply-To: References: <010FB2F3C55002408EE1404538D1B6AE030D83794786@LLN-SPP-ES-04.user01.lln.local> <50E715AA.5010006@gmail.com> Message-ID: <50E8C38C.6020400@gmail.com> On 1/4/2013 8:26 PM, Alan Gauld wrote: > On 04/01/13 17:47, bob gailer wrote: > >> > Further selections can be made if there is enough credit. >> >> This is confusing. You could drop that line with no ill effect. I am not >> sure what it even means. > > It seemed straightforward enough to me Bob. > If you put in $10 and buy a candy bar for $6 you have $4 credit left. > You can then choose another item provided it costs less than $4. > > It just implies another level of loop in the design. OK I get it. > > In fact given the detail of the spec its hard to see what we could add > by way of help until the OP produces some code to critique. > -- Bob Gailer 919-636-4239 Chapel Hill NC From doanviettrung at gmail.com Sun Jan 6 13:30:14 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Sun, 6 Jan 2013 23:30:14 +1100 Subject: [Tutor] Decorators: Are they good for checking inputs and outputs? Message-ID: Dear tutors After much reading and head-scratching, I think the basic idea of decorators has now clicked for me. I am a beginner in programming and in Python, but I want to eventually develop a serious system. To spend most of my time on developing the ideas and building the code, I need to test my code fairly well but spend as little time doing so as possible. Therefore, I am looking ahead and thinking of using decorators extensively. Specifically, for every function I will write, I don't want to have to write code to check that arguments passed to it are of the permitted number, type, and range, then code to deal with those errors that can be dealt with. This is what I hope: Once I have collected or written all the necessary decorators, from then on I'll just routinely decorate each function with a whole bunch of decorators relevant to it. The above is about inputs, but decorators equally seem able to check outputs and the function's inner workings: that it returns results which are within range, that loops in the function don't go for longer than usual, etc. The above is about functions. As to classes and methods, I am still learning about object-oriented programming, but I'd think decorators can be just as useful. However, it seems not many people think like I do. In the discussions I have read on StackOverflow and elsewhere, few people use decorators for the above purposes, and those who do, don't seem to do it extensively. If decorators are truly as useful as I think they are for the above purposes, surely they would be used more enthusiastically, more extensively, by many more people. So, my first question to the tutors is: Am I giving decorators undeservedly high expectations for the above purposes (ie. checking inputs & outputs, and dealing with some problems therein)? Are there perhaps traps down the line, invisible to me at the moment, which make decorators not as useful as I hope? Second, if decorators are actually suitable for the above purposes, then where can I find repositories of decorators? (I am aware of the PythonDecoratorLibrary - PythonInfo Wiki, the link is not working now, but did a few days ago) Thank you! Trung Doan -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 6 14:44:48 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 06 Jan 2013 13:44:48 +0000 Subject: [Tutor] Decorators: Are they good for checking inputs and outputs? In-Reply-To: References: Message-ID: On 06/01/13 12:30, DoanVietTrungAtGmail wrote: > After much reading and head-scratching, I think the basic idea of > decorators has now clicked for me. Congratulations. It's always good when a new concept finally slots in place. One thing - do you understand the downsides of decorators too? Every feature in a language has an upside and a downside. You don't really understand it until you understand both aspects. > Python, but I want to eventually develop a serious system. To spend most > of my time on developing the ideas and building the code, I need to test > my code fairly well but spend as little time doing so as possible. See the recent discussion on Test Driven Development. You can spend your time writing decorators or you can write test functions/classes. Either way you do it once. With automated tests the time spent testing is usually minimal even with many tests. at least at the unit test level. > Specifically, for every function I will write, I don't want to have to > write code to check that arguments passed to it are of the permitted > number, type, and range, then code to deal with those errors that can be > dealt with. This is what I hope: Once I have collected or written all > the necessary decorators, from then on I'll just routinely decorate each > function with a whole bunch of decorators relevant to it. That's probably possible but remember that each decorator is effectively another function wrapped around your function. Many decorators means many function calls. That may have an impact both on the performance and the ease of debugging your code. > The above is about inputs, but decorators equally seem able to check > outputs and the function's inner workings: that it returns results which > are within range, that loops in the function don't go for longer than > usual, etc. It can check inputs and outputs. I'm not so sure about the last bit though! There might be a way but I can't think of one without some pretty hairy timer techniques. > However, it seems not many people think like I do. In the discussions I > have read on StackOverflow and elsewhere, few people use decorators for > the above purposes, and those who do, don't seem to do it extensively. Most people use a TDD framework and write test functions. They ensure the code works and don't get in the way of the finished version. > If decorators are truly as useful as I think they are for the above > purposes, surely they would be used more enthusiastically, more > extensively, by many more people. Decorators are useful for many things but they have their downsides too. And there is also convention and "standard practice", the culture of Python programming, the common idioms. Decorators haven't really made it into mainstream python coding idioms yet. > So, my first question to the tutors is: Am I giving decorators > undeservedly high expectations for the above purposes (ie. checking > inputs & outputs, and dealing with some problems therein)? Are there > perhaps traps down the line, invisible to me at the moment, which make > decorators not as useful as I hope? I've never tried what you suggest so I don't know the impacts. My initial concerns would be over potential performance penalties and ease of debugging if things do go wrong. > Second, if decorators are actually suitable for the above purposes, then > where can I find repositories of decorators? (I am aware of > the PythonDecoratorLibrary I wasn't and hadn't thought of such a concept till now. Thanks for triggering that idea, I will investigate. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Sun Jan 6 15:31:42 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 6 Jan 2013 14:31:42 +0000 Subject: [Tutor] Decorators: Are they good for checking inputs and outputs? In-Reply-To: References: Message-ID: On 6 January 2013 12:30, DoanVietTrungAtGmail wrote: > Dear tutors > > After much reading and head-scratching, I think the basic idea of decorators > has now clicked for me. I am a beginner in programming and in Python, but I > want to eventually develop a serious system. To spend most of my time on > developing the ideas and building the code, I need to test my code fairly > well but spend as little time doing so as possible. Therefore, I am looking > ahead and thinking of using decorators extensively. > > Specifically, for every function I will write, I don't want to have to write > code to check that arguments passed to it are of the permitted number, type, > and range, then code to deal with those errors that can be dealt with. This > is what I hope: Once I have collected or written all the necessary > decorators, from then on I'll just routinely decorate each function with a > whole bunch of decorators relevant to it. Could you perhaps give a concrete example of a situation where a decorator would be useful for checking the inputs to a function? Unless you are writing many functions that accept the same number and type of arguments, there isn't anyway to get around the fact that your code needs to specify what each function expects. You can use helper functions in the body of a function or decorators to wrap the function from the outside but the effect in terms of code reuse and repeating yourself is pretty much the same. There are potentially other advantages to using decorators in this context however. For example, with decorators it is easy to disable checking at runtime for performance: def checking_decorator(f): if DEBUG: # Wrap the function with a checking call def checking_wrapper(arg): if not valid(arg): raise SomeError return f(arg) return checking_wrapper else: # Return f directly (no performance penalty later) return f Oscar From doanviettrung at gmail.com Mon Jan 7 01:13:53 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Mon, 7 Jan 2013 11:13:53 +1100 Subject: [Tutor] Decorators: Are they good for checking inputs and outputs? In-Reply-To: References: Message-ID: *.. Could you perhaps give a concrete example of a situation where a decorator would be useful for checking the inputs to a function? .. Oscar* Say I write a function that expects 5 positional arguments, and up to 4 ** arguments. Now I want to: a- check that the first positional argument is a sorted list. If not a list, raise an error. If an unsorted list, sort it and pass to the function b- check that the 5th position argument is an 0 < int < 10 c- check that no more than 4 ** arguments are passed In the decorators-make-my-life-simple scenario I hope for, I'll simply open my box of decorators, pick 3 relevant decorators, and put the 3 @ lines above my function. In the @ for the b- test, I'll pass a 5 to tell the decorator to look at the 5th argument, and similarly a 4 for the decorator checking c-. Then I write another function, whose test requirements will be different, I'll simply pick decorators relevant to it, then go on writing more code. If this scenario works as expected, I can focus my mind on the concepts I'm working on rather than having to interrupt the flow of thoughts to write test code. *.. See the recent discussion on Test Driven Development .. Alan* Yes I followed the recent discussion about unit testing. I suppose that decorators can't do everything that a comprehensive unit testing can, but probably decorators plus a few doctests would suffice for my purpose. Trung -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Jan 7 01:24:16 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 7 Jan 2013 00:24:16 +0000 Subject: [Tutor] Decorators: Are they good for checking inputs and outputs? In-Reply-To: References: Message-ID: On 7 January 2013 00:13, DoanVietTrungAtGmail wrote: > .. Could you perhaps give a concrete example of a situation where a > decorator would be useful for checking the inputs to a function? .. Oscar > > Say I write a function that expects 5 positional arguments, and up to 4 ** > arguments. Now I want to: > a- check that the first positional argument is a sorted list. If not a list, > raise an error. If an unsorted list, sort it and pass to the function > b- check that the 5th position argument is an 0 < int < 10 > c- check that no more than 4 ** arguments are passed Is there not a contradiction between the points b and c? In any case, checking the number of arguments is not something that normally needs to be done in Python code, e.g.: def my_function(arg1, arg1): # Raises an error when called with the wrong number of args pass > > In the decorators-make-my-life-simple scenario I hope for, I'll simply open > my box of decorators, pick 3 relevant decorators, and put the 3 @ lines > above my function. In the @ for the b- test, I'll pass a 5 to tell the > decorator to look at the 5th argument, and similarly a 4 for the decorator > checking c-. How is that better than doing the same within the function? I would say that checking the validity of the arguments inside the function is generally clearer to read than adding the checks with decorators. How would a decorator do better than the following? def myfun(a, b, c, d, e): a.sort() if not (0 < e < 10) and int(e) == e: raise ValueError('e should be integer 1-9: %s' % e) # And now the function body pass Oscar From d at davea.name Mon Jan 7 01:43:09 2013 From: d at davea.name (Dave Angel) Date: Sun, 06 Jan 2013 19:43:09 -0500 Subject: [Tutor] Decorators: Are they good for checking inputs and outputs? In-Reply-To: References: Message-ID: <50EA1A1D.1050008@davea.name> On 01/06/2013 07:13 PM, DoanVietTrungAtGmail wrote: > *.. Could you perhaps give a concrete example of a situation where > a decorator would be useful for checking the inputs to a function? .. Oscar* > > Say I write a function that expects 5 positional arguments, and up to 4 ** > arguments. Now I want to: > a- check that the first positional argument is a sorted list. If not a > list, raise an error. If an unsorted list, sort it and pass to the function > b- check that the 5th position argument is an 0 < int < 10 > c- check that no more than 4 ** arguments are passed > > In the decorators-make-my-life-simple scenario I hope for, I'll simply open > my box of decorators, pick 3 relevant decorators, and put the 3 @ lines > above my function. In the @ for the b- test, I'll pass a 5 to tell the > decorator to look at the 5th argument, and similarly a 4 for the decorator > checking c-. > > Then I write another function, whose test requirements will be different, > I'll simply pick decorators relevant to it, then go on writing more code. > > If this scenario works as expected, I can focus my mind on the concepts I'm > working on rather than having to interrupt the flow of thoughts to write > test code. > > *.. See the recent discussion on Test Driven Development .. Alan* > > Yes I followed the recent discussion about unit testing. I suppose that > decorators can't do everything that a comprehensive unit testing can, but > probably decorators plus a few doctests would suffice for my purpose. > > Trung > > I'd say you don't understand TDD at all. Your decorators are NOT validating the function they're applied to, and in one case, they totally modify its behavior. Your decorators make no effort to ensure anything about the behavior of the function, they just test whether the caller is obeying some rules. And even there, nothing here will test what happens if some future caller uses different arguments. Part of the requirement for test code is that its presence have no effect on customer-running code. In some environments, that's done by doing conditional compiles. But if you disabled all these decorators, suddenly the function will get unsorted data. Sounds like you're trying to emulate the type system of C++, or even Pascal or Ada. Why not just use such a language then? If you really want to constrain the caller by code you write at the function site, then use a compiler that can actually reliably make the checks you're talking about, and make most of the checks at compile time. Python is useful for duck-typing, and that's the first feature you're trying to test out of. -- DaveA From jacklittlemc at yahoo.com Mon Jan 7 03:07:20 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Sun, 6 Jan 2013 18:07:20 -0800 (PST) Subject: [Tutor] Here is code, no link for my previous question Message-ID: <1357524440.64862.YahooMailNeo@web124506.mail.ne1.yahoo.com> Here is the code, my error is below the code in itallics ? #This is not free source #Don't cheat by looking at this #If you do you ruin the game #A Towel Production # APOC #------- global ammo1 global ammo2 global ammo3 global health global tech_parts global exp global radio_parts ammo1=10 ammo2=0 ammo3=0 health=100 tech_parts=0 exp=0 radio_parts=0 def simpstart(): ? global ammo ? global health ? global tech_parts ? global radio_parts print "You awake in a haze. A crate,a door and a radio." g1 = raw_input("Which do you choose? ") if g1 == "CRATE" or g1 == "Crate" or g1 == "crate": ??????? print "There is a pack of ammo,some food and an odd microchip" ??????? ammo1=ammo1 + 6 ??????? health=health + 10 ??????? tech_parts=tech_parts + 1 elif g1 =="DOOR" or g1 == "Door" or g1 == "door": ??????? print "You are outside" elif g1 == "RADIO" or g1 == "Radio" or g1 == "radio": ??????? print "It's only a few parts" ??????? radio_parts=radio_parts+3 g2 = raw_input("So this is NYC.Ten years after.There are a few streets.Go west or north? ") if g2 == "WEST" or g2 == "West" or g2 == "west": ??????? path2() elif g2 == "NORTH" or g2 == "North" or g2 == "north": ? ? def path_1pt1(): ??? print "This is where it all started. Freedom Tower. A biotech firm called Aesthos Biotechnology. Based here." ??? print "I worked there." ??? p1 = raw_input("Go in or stay out? ") ??? if p1 == "GO IN" or p1 == "Go in" or p1 == "go in": ??????? print health ??????? print tech_parts ??????? print ammo1 ??????? print "This looks familiar" ??????? print """Flashback 1 ???????????????? Boss: Hey! You go get sample SV57 from the freezer. ???????????????? Me: Will do sir ???????????????? Lab technician: thanks ???????????????? Me: No problem""" ??????? print "Not much in here" ??? elif p1 =="STAY OUT" or p1 == "Stay out" or p1 == "stay out": ??????? print "It seems a lot of people died here" ??????? print """Flashback 1.2 ???????????????? Test subject: AHHGH....What the what! ???????????????? Lab technician: God! What is happening? ???????????????? Me: What sample was that? ???????????????? Lab technician: SV57 ???????????????? Me: RUN LIKE HECK! ???????????????? The lab tech was infected ???????????????? Me: All my fault...All my fault""" ??? print """Man: Hello. ???????????? Me: Who are you. ???????????? Man:That is...unnecessary at this time. ???????????? Me: Then why are you here? ???????????? Man: To help ???????????? Man: I know where your family is. ???????????? Me: Where?! ???????????? Man: Ontario, Canada. That is 282 miles.""" ??? print "? Man: This a long journey, but I believe you can accomplish it." ??? print ??? print ??? print "Ontario is north. Got to get there." ??? p2 = raw_input("There is a pack of crawlers up ahead. Attack or sneak? ") ??? if p2 == "ATTACK" or p2 == "Attack" or p2 == "attack": ??????? print "You attacked the crawlers at the loss of 6 ammo and 19 health, but gained 55 exp" ??????? ammo1=ammo1-6 ??????? health=health-19 ??????? exp=exp+55 ??? elif p2 == "SNEAK" or p2 == "Sneak" or p2 == "sneak": ??????? print "You snuck past the crawlers at the gain of 45 exp" ??????? exp=exp+45 ??? p3 = raw_input("Gangster: You! What you got?! Attack or run away? ") ??? if p3 == "ATTACK" or p3 == "Attack" or p3 == "attack": ??????? print "Several of his comrades swarm you. You died." ??????? return path_1pt1() ??????? health=100 ??? elif p3 == "Run away" or p3 == "RUN AWAY" or p3 == "run away": ??????? print "You got away, but you know you made one more enemy today" ??? p4 = raw_input("A car drives up. Do you carjack it or keep walking? ") ??? if p4 == "CARJACK" or p4 == "Carjack" or p4 == "carjack": ??????????? path_1pt3() ??? elif p4 == "Walk" or p4 == "WALK" or p4 == "walk": ??????????? print "That was a golden opportunity" ??????????? ? def path_1pt2(): ??? print "There is a barbed wire topped fence, about 7 feet high. There is a building." ??? print "The weather is picking up, and the wind is getting fast and violent." ??? p5 = raw_input("Stay outside and risk it or check the inside of the building? ") ??? if p5 == "Stay" or p5 == "STAY" or p5 == "stay": ??????? print "The wind and snow picked up. You got frostbite" ??????? return path_1pt1() ??? elif p5 == "CHECK" or p5 == "Check" or p5 == "check": ??????? print "There is a group of survivors huddled in a corner" ??????? print? """Survivor 1: Who are you? ????????????????? Me: Does that matter? ????????????????? Survivor 2: You aren't of 'em Protectors are ya? ????????????????? Me: The what? ????????????????? Survivor 1: They go around killin' people who don't comply with their rules and live in New Quebec" ????????????????? Me:Huh""" ??????? exp=exp+200 ??????? health=health+50 ??????? ammo1=ammo1+29 ??? p6 = raw_input("Do you wish to take a quest or continue the story?? ") ? if p6 == "QUEST" or p6 == "Quest" or p6 == "quest": ????????? quest1() ? elif p6 == "CONTINUE STORY" or p6 == "Continue story" or p6 == "continue story": ????? print "You declined the quest" ????? print ????? print """Man: Hello ???????????????? Me: Hello ???????????????? Man: I hear you must make it to New Quebec ???????????????? Me: Yes ???????????????? Man: Give me 15 exp and you will teleport there.""" ? p7 = raw_input("Teleport or continue? ") ? if p7 == "TELEPORT" or p7 == "Teleport" or p7 == "teleport": ????????? path_1pt3() ????????? exp=exp-15 ? elif p7 == "CONTINUE" or p7 == "Continue" or p7 == "continue": ??????? print "You chose to continue your route to New Quebec" ??????? print """Survivor 1:Here, take these ???????????????? *He passes car keys* ???????????????? Me: Thanks ???????????????? Survivor 1: No problem. ???????????????? Survivor 2: Just fill up the gas tank""" ? p8 = raw_input("You can either pick up a map or a compass? ") ? if p8 == "MAP" or p8 == "Map" or p8 == "map": ????? print "The map has a special square for gas stations" ????? print "It says go west 2 miles" ? elif p8 == "COMPASS" or p8 == "Compass" or p8 == "compass": ????? print "This seems like it will be impossible to find the gas tank" ????? d1() ? p9 = raw_input("Go east or west? ") ? if p9 == "EAST" or p9 == "east" or p9 == "East": ??? def GasStation(): ????? global ammo1 ????? global ammo2 ????? global ammo3 ????? global health ????? global tech_parts ????? global exp ????? global radio_parts ????? print "There seems to be a group of marauders gaurding the last tank" ????? p10=raw_input("Approach kindly or attack") ????? if p10.lower== "approach kindly": ????????? print """Me: Hey Guys! ?????????????????? Leader:Scram! ?????????????????? Me: Look, I have to find my wife and kids ?????????????????? Leader: I don't care! ?????????????????? Me: I just need that gas tank ?????????????????? Leader: What's in it for me? ?????????????????? Me: Uhhhh.. ammunition ?????????????????? Leader: Sure.""" ????????? ammo1=ammo1-6 ????? else: ??????? print"They murdered you!" ??????? return GasStation() ??????? ammo1=ammo1-6 else: ? return path1_pt2() ? "A snowstorm swept through, killing you." ? ??? Here is the error: ? There's an error in your program: ***'return' outside function(g.py,line 179) -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Jan 7 03:21:02 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 7 Jan 2013 02:21:02 +0000 Subject: [Tutor] Here is code, no link for my previous question In-Reply-To: <1357524440.64862.YahooMailNeo@web124506.mail.ne1.yahoo.com> References: <1357524440.64862.YahooMailNeo@web124506.mail.ne1.yahoo.com> Message-ID: On 7 January 2013 02:07, Jack Little wrote: > Here is the code, my error is below the code in itallics No explanation? > > #This is not free source > #Don't cheat by looking at this > #If you do you ruin the game I was a little concerned when I read this part. I guess it's okay for me to read on... > #A Towel Production > # APOC > #------- > global ammo1 > global ammo2 > global ammo3 > global health > global tech_parts > global exp > global radio_parts > ammo1=10 > ammo2=0 > ammo3=0 > health=100 > tech_parts=0 > exp=0 > radio_parts=0 > def simpstart(): > global ammo > global health > global tech_parts > global radio_parts > print "You awake in a haze. A crate,a door and a radio." > g1 = raw_input("Which do you choose ") > if g1 == "CRATE" or g1 == "Crate" or g1 == "crate": > print "There is a pack of ammo,some food and an odd microchip" > ammo1=ammo1 + 6 > health=health + 10 > tech_parts=tech_parts + 1 > elif g1 =="DOOR" or g1 == "Door" or g1 == "door": > print "You are outside" > elif g1 == "RADIO" or g1 == "Radio" or g1 == "radio": > print "It's only a few parts" > radio_parts=radio_parts+3 > g2 = raw_input("So this is NYC.Ten years after.There are a few streets.Go > west or north ") > if g2 == "WEST" or g2 == "West" or g2 == "west": > path2() > elif g2 == "NORTH" or g2 == "North" or g2 == "north": > > def path_1pt1(): > print "This is where it all started. Freedom Tower. A biotech firm > called Aesthos Biotechnology. Based here." > print "I worked there." > p1 = raw_input("Go in or stay out ") > if p1 == "GO IN" or p1 == "Go in" or p1 == "go in": > print health > print tech_parts > print ammo1 > print "This looks familiar" > print """Flashback 1 > Boss: Hey! You go get sample SV57 from the freezer. > Me: Will do sir > Lab technician: thanks > Me: No problem""" > print "Not much in here" > elif p1 =="STAY OUT" or p1 == "Stay out" or p1 == "stay out": > print "It seems a lot of people died here" > print """Flashback 1.2 > Test subject: AHHGH....What the what! > Lab technician: God! What is happening? > Me: What sample was that? > Lab technician: SV57 > Me: RUN LIKE HECK! > The lab tech was infected > Me: All my fault...All my fault""" > print """Man: Hello. > Me: Who are you. > Man:That is...unnecessary at this time. > Me: Then why are you here? > Man: To help > Man: I know where your family is. > Me: Where?! > Man: Ontario, Canada. That is 282 miles.""" > print " Man: This a long journey, but I believe you can accomplish it." > print > print > print "Ontario is north. Got to get there." > p2 = raw_input("There is a pack of crawlers up ahead. Attack or sneak > ") > if p2 == "ATTACK" or p2 == "Attack" or p2 == "attack": > print "You attacked the crawlers at the loss of 6 ammo and 19 > health, but gained 55 exp" > ammo1=ammo1-6 > health=health-19 > exp=exp+55 > elif p2 == "SNEAK" or p2 == "Sneak" or p2 == "sneak": > print "You snuck past the crawlers at the gain of 45 exp" > exp=exp+45 > p3 = raw_input("Gangster: You! What you got?! Attack or run away ") > if p3 == "ATTACK" or p3 == "Attack" or p3 == "attack": > print "Several of his comrades swarm you. You died." > return path_1pt1() > health=100 > elif p3 == "Run away" or p3 == "RUN AWAY" or p3 == "run away": > print "You got away, but you know you made one more enemy today" > p4 = raw_input("A car drives up. Do you carjack it or keep walking ") > if p4 == "CARJACK" or p4 == "Carjack" or p4 == "carjack": > path_1pt3() > elif p4 == "Walk" or p4 == "WALK" or p4 == "walk": > print "That was a golden opportunity" > > def path_1pt2(): > print "There is a barbed wire topped fence, about 7 feet high. There is > a building." > print "The weather is picking up, and the wind is getting fast and > violent." > p5 = raw_input("Stay outside and risk it or check the inside of the > building ") > if p5 == "Stay" or p5 == "STAY" or p5 == "stay": > print "The wind and snow picked up. You got frostbite" > return path_1pt1() > elif p5 == "CHECK" or p5 == "Check" or p5 == "check": > print "There is a group of survivors huddled in a corner" > print """Survivor 1: Who are you? > Me: Does that matter? > Survivor 2: You aren't of 'em Protectors are ya? > Me: The what? > Survivor 1: They go around killin' people who don't comply > with their rules and live in New Quebec" > Me:Huh""" > exp=exp+200 > health=health+50 > ammo1=ammo1+29 > p6 = raw_input("Do you wish to take a quest or continue the story? ") > if p6 == "QUEST" or p6 == "Quest" or p6 == "quest": > quest1() > elif p6 == "CONTINUE STORY" or p6 == "Continue story" or p6 == "continue > story": > print "You declined the quest" > print > print """Man: Hello > Me: Hello > Man: I hear you must make it to New Quebec > Me: Yes > Man: Give me 15 exp and you will teleport there.""" > p7 = raw_input("Teleport or continue ") > if p7 == "TELEPORT" or p7 == "Teleport" or p7 == "teleport": > path_1pt3() > exp=exp-15 > elif p7 == "CONTINUE" or p7 == "Continue" or p7 == "continue": > print "You chose to continue your route to New Quebec" > print """Survivor 1:Here, take these > *He passes car keys* > Me: Thanks > Survivor 1: No problem. > Survivor 2: Just fill up the gas tank""" > p8 = raw_input("You can either pick up a map or a compass ") > if p8 == "MAP" or p8 == "Map" or p8 == "map": > print "The map has a special square for gas stations" > print "It says go west 2 miles" > elif p8 == "COMPASS" or p8 == "Compass" or p8 == "compass": > print "This seems like it will be impossible to find the gas tank" > d1() > p9 = raw_input("Go east or west ") > if p9 == "EAST" or p9 == "east" or p9 == "East": > def GasStation(): > global ammo1 > global ammo2 > global ammo3 > global health > global tech_parts > global exp > global radio_parts > print "There seems to be a group of marauders gaurding the last tank" > p10=raw_input("Approach kindly or attack") > if p10.lower== "approach kindly": > print """Me: Hey Guys! > Leader:Scram! > Me: Look, I have to find my wife and kids > Leader: I don't care! > Me: I just need that gas tank > Leader: What's in it for me? > Me: Uhhhh.. ammunition > Leader: Sure.""" > ammo1=ammo1-6 > else: > print"They murdered you!" > return GasStation() > ammo1=ammo1-6 > else: I guess this is line 179. As the error says, "return outside function". A return statement is meaningless outside a function. > return path1_pt2() > "A snowstorm swept through, killing you." > > > Here is the error: > > There's an error in your program: > ***'return' outside function(g.py,line 179) Oscar From steve at pearwood.info Mon Jan 7 03:52:17 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 07 Jan 2013 13:52:17 +1100 Subject: [Tutor] Here is code, no link for my previous question In-Reply-To: <1357524440.64862.YahooMailNeo@web124506.mail.ne1.yahoo.com> References: <1357524440.64862.YahooMailNeo@web124506.mail.ne1.yahoo.com> Message-ID: <50EA3861.1010302@pearwood.info> On 07/01/13 13:07, Jack Little wrote: > Here is the code, my error is below the code in itallics What italics? I see no italics. Please don't rely on so-called "rich text" email (italics, fancy fonts, different text sizes, etc), since it uses HTML code in your email and many people turn off such HTML code, or are literally unable to see it even if they wanted to. - HTML code in email is one of the top 3 signs of spam. Many people send "rich text" email straight to the trash as a way of eliminating spam. - HTML code in email is a privacy and security risk. For example, that means that the sender can track whether or not you have read the email using "web bugs" whether or not you consent to being tracked. There are viruses, spyware and other malware that can be transmitted through HTML code in email. - HTML code forces your choice in font, font size, colours, etc. on the reader. Some people prefer to read emails using their own choice of font rather than yours, and consider it rude for others to try to force a different font. - Even if they don't mind the use of "rich text" in principle, in practice once they have received enough emails with pink and yellow text on a purple background with blinking stars and dancing fairies in the background, in pure self-defence they may disable HTML in emails, or delete the emails unread. - Use of colour discriminates against the approximately 10% of the male population who are colour-blind. - Use of italics may discriminate against those who are blind and using screen readers to "read" their email. I once was on a maths mailing list for about three years until I discovered that the most prolific and helpful person there was as blind as a bat. - Programming is a *text-based* activity. Code depends on WHAT you write, not its colour, or the font you use, or whether there are smiley faces in the background winking at you. So especially in programming circles, many people find HTML code in emails to be a distraction and an annoyance. Even if you think that people who dislike HTML emails are wrong, or silly, or being precious, or completely nuts, nevertheless you should indulge us. You are asking for free advice. It does not pay for you to offend or annoy those you are asking for help. -- Steven From steve at pearwood.info Mon Jan 7 04:00:43 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 07 Jan 2013 14:00:43 +1100 Subject: [Tutor] Here is code, no link for my previous question In-Reply-To: <1357524440.64862.YahooMailNeo@web124506.mail.ne1.yahoo.com> References: <1357524440.64862.YahooMailNeo@web124506.mail.ne1.yahoo.com> Message-ID: <50EA3A5B.1000904@pearwood.info> And a second reply: On 07/01/13 13:07, Jack Little wrote: > def simpstart(): > global ammo > global health > global tech_parts > global radio_parts This function does nothing. It declares four globals, and then ends. All the subsequent lines of code are not indented, and so are not part of the function. I am pretty sure that last time you asked about a problem with this code, I told you the same thing. Why are you asking questions if you don't listen to the answer? See my email on the tutor list on 15/12/12. If you don't understand our answers, please ask for further clarification rather than just ignore them. Ignoring answers will be a good way to have your questions ignored too. > else: > return path1_pt2() > "A snowstorm swept through, killing you." > > > Here is the error: > > There's an error in your program: > ***'return' outside function(g.py,line 179) Is that error message not clear enough? You have an "return" statement outside of a function. This is not allowed, because there is nothing to return from, or return to. When asking questions, please try to avoid sending your entire program. Please try to narrow the problem down to the smallest amount of code that fails. We're happy to *help*, but we're not here to do your work for you. In this case, the simplest example that gives you this error may be something like this: def test(): print "inside function test" # indented, inside function return 1 # not indented, outside function -- Steven From d at davea.name Mon Jan 7 04:12:25 2013 From: d at davea.name (Dave Angel) Date: Sun, 06 Jan 2013 22:12:25 -0500 Subject: [Tutor] Here is code, no link for my previous question In-Reply-To: <1357524440.64862.YahooMailNeo@web124506.mail.ne1.yahoo.com> References: <1357524440.64862.YahooMailNeo@web124506.mail.ne1.yahoo.com> Message-ID: <50EA3D19.2030305@davea.name> On 01/06/2013 09:07 PM, Jack Little wrote: > Here is the code, my error is below the code in itallics This is a text mailing list, italics aren't generally visible. If you want to highlight a line, add a useful comment to it. But the problem here is your scoping. All those globals make no sense, since the keyword only has an effect inside a function. Then you define a function simpstart(), but it's only four lines long, consisting of four more global statements. in other words, the function does nothing. Then after some more top-level code, you define another function path_lpt1(), but the definition is inside a conditional. This is legal, but not likely what you intended to do. Then you define another function path_lpt2(), but end it suddenly after the line p6=raw_input(.... I'd expect the next line to get an error, referencing an unknown p6. You have a line health=100 immediately after a return statement, so it'll never execute. And as Oscar points out, you have a return at top-level code, which is to say, not inside any function. Not sure where you got this code, but there's probably lots more wrong; I only really looked at the indentation. I think you're confusing defining a function with calling it. And i suspect you typed the whole thing from a book or something, and just got the whole indentation wrong. -- DaveA From eowens0124 at gmx.com Mon Jan 7 04:48:10 2013 From: eowens0124 at gmx.com (Ed Owens) Date: Sun, 06 Jan 2013 22:48:10 -0500 Subject: [Tutor] Documentation In-Reply-To: <50E72B95.8090009@libero.it> References: <50D37A37.4070805@pearwood.info> <50D37E1C.3070901@davea.name> <66098356-604F-47DB-A78B-2CC859623BBE@gmail.com> <50E72B95.8090009@libero.it> Message-ID: <50EA457A.9030500@gmx.com> I have been working my way through Chun's book /Core Python Applications. /In chapter 9 he has a web crawler program that essentially copies all the files from a web site by finding and downloading the links on that domain. One of the classes has a procedure definition, and I'm having trouble finding documentation for the functions. The code is: def parse_links(self): 'Parse out the links found in downloaded HTML file' f = open(self.file, 'r') data = f.read() f.close() parser = HTMLParser(formatter.AbstractFormatter( formatter.DumbWriter(cStringIO.StringIO()))) parser.feed(data) parser.close() return parser.anchorlist HTMLParser is from htmllib. I'm having trouble finding clear documentation for what the functions that are on the 'parser =' line do and return. The three modules (htmllib, formatter, & cStringIO are all imported, but I can't seem to find much info on how they work and what they do. What this actually does and what it produces is completely obscure to me. Any help would be appreciated. Any links to clear documentation and examples? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhettnaxel at gmail.com Mon Jan 7 04:57:37 2013 From: rhettnaxel at gmail.com (Alexander Mark) Date: Sun, 6 Jan 2013 22:57:37 -0500 Subject: [Tutor] Documentation In-Reply-To: <50EA457A.9030500@gmx.com> References: <50D37A37.4070805@pearwood.info> <50D37E1C.3070901@davea.name> <66098356-604F-47DB-A78B-2CC859623BBE@gmail.com> <50E72B95.8090009@libero.it> <50EA457A.9030500@gmx.com> Message-ID: <4B762DFB-77A4-4A8F-ADD0-119ED0EE340E@gmail.com> On Jan 6, 2013, at 22:48, Ed Owens wrote: > I have been working my way through Chun's book Core Python Applications. > > In chapter 9 he has a web crawler program that essentially copies all the files from a web site by finding and downloading the links on that domain. > > One of the classes has a procedure definition, and I'm having trouble finding documentation for the functions. The code is: > > def parse_links(self): > 'Parse out the links found in downloaded HTML file' > f = open(self.file, 'r') > data = f.read() > f.close() > parser = HTMLParser(formatter.AbstractFormatter( > formatter.DumbWriter(cStringIO.StringIO()))) > parser.feed(data) > parser.close() > return parser.anchorlist > > HTMLParser is from htmllib. > > I'm having trouble finding clear documentation for what the functions that are on the 'parser =' line do and return. The three modules (htmllib, formatter, & cStringIO are all imported, but I can't seem to find much info on how they work and what they do. What this actually does and what it produces is completely obscure to me. > > Any help would be appreciated. Any links to clear documentation and examples? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Hi Ed, maybe this helps: http://docs.python.org/2/library/htmllib.html A -------------- next part -------------- An HTML attachment was scrubbed... URL: From wayne at waynewerner.com Mon Jan 7 06:38:24 2013 From: wayne at waynewerner.com (Wayne Werner) Date: Sun, 6 Jan 2013 23:38:24 -0600 (CST) Subject: [Tutor] IronPython any tutors with experience out there? In-Reply-To: References: Message-ID: On Thu, 3 Jan 2013, Bjorn Madsen wrote: > Hello PythonTutor- I'm a scientist?and very happy with python 2.7.?I have been asked to assist a development program where everything is written in dotNET/ > C# (visual studio 2012) and luckily Microsoft Visual Studio supports IronPython which is a clean Python implementation in C#, so I can use the Python > syntax I'm so familiar with...? > > However ... to interact with the c# modules which my colleagues wrote, I need to add "clr" references. > > Example: > >>> import clr > >>> clr.AddReferenceToFile("Mapack.dll") > >>> from Mapack import * > >>> dir() > > Unfortunately I can't get it to run and the tutorials after 12 hours of google-reading are terribly sparse.?Is there any experience somewhere in the > network with IronPython in VSTO-2012 in this forum and what could the top five clr.addreference bugs be? Assuming everything else checks out... what you have to import is the namespace of whatever the .dll is. So if it was compiled with a root namespace of say, Fizz.Buzz.Foo Then you'll have to do: from Fizz.Buzz.Foo import * Though, I've never tried that version. I always did import Fizz.Buzz.Foo as foo in my own code. HTH, Wayne From alan.gauld at btinternet.com Mon Jan 7 09:01:57 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 07 Jan 2013 08:01:57 +0000 Subject: [Tutor] Here is code, no link for my previous question In-Reply-To: <1357524440.64862.YahooMailNeo@web124506.mail.ne1.yahoo.com> References: <1357524440.64862.YahooMailNeo@web124506.mail.ne1.yahoo.com> Message-ID: On 07/01/13 02:07, Jack Little wrote: > Here is the code, my error is below the code in itallics That does not look like a normal Python error report. How are you running this? If you are using an IDE it may be giving non standard messages. It is usually better to run your code from a command line and then send us the full error traceback. It contains a lot of useful information. Although in this case the error is sufficiently explicit that we can pinpoint the error without it. > global ammo1 > global ammo2 > global ammo3 > global health > global tech_parts > global exp > global radio_parts These do absolutely nothing, get rid of them. > def simpstart(): > global ammo > global health > global tech_parts > global radio_parts > print "You awake in a haze. A crate,a door and a radio." > g1 = raw_input("Which do you choose ") Remember that indentation is significant in Python. By moving the indentation of print out to the margin you have ended your simpstart() function. As a result simpstart() does absolutely nothing. > if g1 == "CRATE" or g1 == "Crate" or g1 == "crate": The usual way to do this is use the lower() method of strings: if g1.lower() == 'crate': > print "There is a pack of ammo,some food and an odd microchip" > ammo1=ammo1 + 6 > health=health + 10 > tech_parts=tech_parts + 1 You can use the += shortcut to save typing ammo1 += 6 health += 10 tech_parts += 1 > elif g2 == "NORTH" or g2 == "North" or g2 == "north": > > def path_1pt1(): > print "This is where it all started. Freedom Tower. A biotech firm > called Aesthos Biotechnology. Based here." You are now trying to define a new function inside the elif block. That's legal Python and you can do it if you really want to, but its very unusual style. Normally functions are defined at outer level and called when needed. > > def path_1pt2(): > print "There is a barbed wire topped fence, about 7 feet high. > There is a building." > print "The weather is picking up, and the wind is getting fast and > violent." > p5 = raw_input("Stay outside and risk it or check the inside of the > building ") > if p5 == "Stay" or p5 == "STAY" or p5 == "stay": > print "The wind and snow picked up. You got frostbite" > return path_1pt1() > elif p5 == "CHECK" or p5 == "Check" or p5 == "check": > print "There is a group of survivors huddled in a corner" > print """Survivor 1: Who are you? > Me: Does that matter? > Survivor 2: You aren't of 'em Protectors are ya? > Me: The what? > Survivor 1: They go around killin' people who don't > comply with their rules and live in New Quebec" > Me:Huh""" > exp=exp+200 > health=health+50 > ammo1=ammo1+29 > p6 = raw_input("Do you wish to take a quest or continue the story? ") p6 is defined inside the path_1pt2 function but not returned. > if p6 == "QUEST" or p6 == "Quest" or p6 == "quest": This line is not part of the function but tests p6. That won;t work. I suspect its an indentation error. indentation is very important in Python. > quest1() Since the quest() function is not defined in your code I assume you are importing it from some other module? > elif p6 == "CONTINUE STORY" or p6 == "Continue story" or p6 == > p9 = raw_input("Go east or west ") > if p9 == "EAST" or p9 == "east" or p9 == "East": > def GasStation(): > if p10.lower== "approach kindly": > print """Me: Hey Guys! > ammo1=ammo1-6 And this is the end of your GasStation() function because the next line is not indented... > else: > print"They murdered you!" > return GasStation() > ammo1=ammo1-6 And the above is probably where your error occurs since return is indeed outside of a function. Incidentally if it were in a function the ammo line would never get executed since it is after the return, so it is pointless. > else: > return path1_pt2() > "A snowstorm swept through, killing you." Same here, the return is outside a function. And the following string is meaningless > Here is the error: > There's an error in your program: > ***'return' outside function(g.py,line 179) As I say, please run the program in an environment that prints proper python error messages and send the full error text in future. You need to go away and read about indentation, function definitions and namespaces. They are the biggest problems in your code at present. Also please use bigger indentation size, a single character makes it really hard to read and spot which indent lines up with what. Also these very long control structures likewise make it hard to look up and see what aligns with what above. (If with else/elif etc) That all makes your code much harder to maintain and debug. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon Jan 7 12:34:01 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 07 Jan 2013 22:34:01 +1100 Subject: [Tutor] Decorators: Are they good for checking inputs and outputs? In-Reply-To: References: Message-ID: <50EAB2A9.9050104@pearwood.info> On 06/01/13 23:30, DoanVietTrungAtGmail wrote: > Dear tutors > > After much reading and head-scratching, I think the basic idea of > decorators has now clicked for me. I am a beginner in programming and in > Python, but I want to eventually develop a serious system. To spend most of > my time on developing the ideas and building the code, I need to test my > code fairly well but spend as little time doing so as possible. Therefore, > I am looking ahead and thinking of using decorators extensively. > > Specifically, for every function I will write, I don't want to have to > write code to check that arguments passed to it are of the permitted > number, type, and range, then code to deal with those errors that can be > dealt with. This is what I hope: Once I have collected or written all the > necessary decorators, from then on I'll just routinely decorate each > function with a whole bunch of decorators relevant to it. That is one use of decorators. It is not the only use. To really understand decorators well, you have to understand the idea of *higher order functions*. Most people get to understand the idea of a function: you pass some arguments, and it returns a result: def plus1(a): return a + 1 def plus2(a): return a + 2 def plus3(a): # this is getting tedious... return a + 3 Higher order functions take that one step higher: instead of returning a result (a number, a string, some other value) they return a function! def plus_factory(value): # Create an inner function. def plus(a): return a + value # value comes from the outer function # Change the name of the inner function, so it looks nicer. plus.__name__ = "plus%d" % value # plus1, plus2, ... plus999 # Return the inner function. return plus Now I can do: plus4 = plus_factory(4) plus100 = plus_factory(100) plus_a_lot = plus_factory(1234567890) print plus4(16) # prints 20 print plus100(16) # prints 116 So now we have seen 1st order functions, which take simple arguments like numbers or strings and return a new number or string, and 2nd order functions, which take a simple argument and returns a function. Now we look at 3rd order functions that take a function as an argument and return a new function! def noisy_function(func): name = func.__name__ def inner(x): print "calling function %s with argument %r" % (name, x) return func(x) return inner Now I can do this: plus4 = noisy_function(plus4) print plus4(16) If I haven't make any mistakes, this will print two lines: calling function plus4 with argument 16 20 Decorators are a way of easily using 3rd order functions. There are many, many different uses for them. > However, it seems not many people think like I do. In the discussions I > have read on StackOverflow and elsewhere, few people use decorators for the > above purposes, and those who do, don't seem to do it extensively. If > decorators are truly as useful as I think they are for the above purposes, > surely they would be used more enthusiastically, more extensively, by many > more people. This is Python. We're not really keen on unnecessary type checking. There are better, or at least different, ways of getting the same effect. > So, my first question to the tutors is: Am I giving decorators undeservedly > high expectations for the above purposes (ie. checking inputs& outputs, > and dealing with some problems therein)? Are there perhaps traps down the > line, invisible to me at the moment, which make decorators not as useful as > I hope? Decorators are awesome! But using decorators for type checking, meh. That's sometimes useful, but more often it is just limiting and annoying. This is Python, not C, and it is best to learn Python styles of coding rather that trying to write C or Java in Python. > Second, if decorators are actually suitable for the above purposes, then > where can I find repositories of decorators? (I am aware of > the PythonDecoratorLibrary - PythonInfo Wiki, the link is not working now, > but did a few days ago) I'm not aware of any specialist "decorator libraries", but many, many libraries include their own decorators which they use for their own purposes. -- Steven From japhy at pearachute.com Thu Jan 3 23:59:03 2013 From: japhy at pearachute.com (Japhy Bartlett) Date: Thu, 3 Jan 2013 16:59:03 -0600 Subject: [Tutor] writing effective unittests In-Reply-To: References: <20130102204357.GA1974@lmerg-crunchbang> <1357217453.36448.YahooMailNeo@web163805.mail.gq1.yahoo.com> <20130103194641.GA10033@lmerg-crunchbang> Message-ID: The general idea is to write tests that use your code in realistic ways and check the results. So if you have a function that takes an input and returns a result, you write a test that passes that function an input checks the result. If some inputs should make it error, you write a test that checks that it errors. In web programming, a common thing is to make a web request with different variations of GET / PUT params, then check that it returns the right status code, or that the result is valid JSON, etc. Basically, try to simulate all the things a real world user would be able to use, and test that your code does what you intend for it to do. TDD is a good principle but usually seems a little too pedantic for real world programming. Where tests (in my experience) get really useful is in making sure that a new change hasn't unexpectedly broken something already written. On Thu, Jan 3, 2013 at 2:31 PM, Tino Dai wrote: > > > I think what I need is a conceptual shift: how do python programmers use >> unittests? >> >> > Here at the Library, we use unit test to test the cases that have many > known inputs. For example, some of the data could come in "foo bar baz", > and some others could come in as "foo, bar, baz", and others could come in > "foo; bar; baz". As we code for each one of these cases, we write tests to > make sure that changes that we make don't break any of our former code. I > think that TDD is a good thing to strive for, but in most cases is an ideal > that can't be reached in most cases. > > Hope that helps, > Tino > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ketchup.candy at gmail.com Tue Jan 8 00:31:02 2013 From: ketchup.candy at gmail.com (Dylan Kaufman) Date: Mon, 7 Jan 2013 18:31:02 -0500 Subject: [Tutor] Python Question Message-ID: Greetings, I take Computer Science in school and for a Python program, I have: from winsound import Beep Beep(196, 1500)#G Beep(262, 270)#C Beep(196, 200)#G Beep(165, 300)#E Beep(175, 200)#F Beep(196, 200)#G Beep(262, 550)#C Beep(196, 200)#G Beep(208, 150)#G# Beep(196, 200)#G Beep(175, 200)#F Beep(165, 200)#E Beep(175, 200)#F Beep(147, 200)#Low D Beep(131, 750)#Low C Beep(131, 150)#Low C Beep(131, 350)#Low C Beep(131, 150)#Low C Beep(262, 350)#C Beep(262, 150)#C Beep(247, 350)#B Beep(247, 150)#B Beep(220, 350)#A Beep(220, 150)#A Beep(294, 200)#D Beep(294, 200)#D Beep(294, 200)#D Beep(294, 200)#D Beep(247, 200)#B Beep(220, 200)#A Beep(196, 550)#G Beep(196, 150)#G Beep(220, 200)#A Beep(220, 200)#A Beep(220, 200)#A Beep(220, 200)#A Beep(220, 200)#A Beep(247, 200)#B Beep(262, 300)#C Beep(196, 150)#G Beep(165, 300)#E Beep(196, 150)#G Beep(165, 200)#E Beep(165, 200)#E When I run it at school it works great, but at home when I try to run it, it says: Traceback (most recent call last): File "/Volumes/PICKLES/School/MyClass/Comp. Sci/Chapter 02 Stuff/program2_cep.py", line 5, in from winsound import Beep ImportError: No module named 'winsound' Could you tell why this is happening and how I can make my program work? -- --Dylan -------------- next part -------------- An HTML attachment was scrubbed... URL: From nathanielhuston at yahoo.com Sat Jan 5 02:27:56 2013 From: nathanielhuston at yahoo.com (Nathaniel Huston) Date: Fri, 4 Jan 2013 17:27:56 -0800 (PST) Subject: [Tutor] modifying global within function without declaring global Message-ID: <1357349276.50451.YahooMailNeo@web162802.mail.bf1.yahoo.com> As far as I understood, this shouldn't be possible. this is python 2.7 weirdness is in deal() at the end ################################################ import random class card: ??? def __init__(self, suit, rank, name): ??????? self.suit = suit ??????? self.rank = rank ??????? self.name = name ??????? def makedeck(): ??? #creates an ordered deck of card objects ??? #ranks are clumped (four 2's, four 3's etc) ??? ??? suits = ['Spades', 'Diamonds', 'Clubs', 'Hearts'] ??? ranks = [] ??? for x in range(2, 15): ??????? ranks.append(x) ??? names = ['Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace'] ??? stack = [] ??? for rank in ranks: ??????? for suit in suits: ??????????? name = names[rank - 2] ??????????? stack.append(card(suit, rank, name)) ??? return stack def deal(quantity): ??? ??? hand = [] ??? for cards in range(0, quantity): ??????? hand.append(deck.pop()) ??? return hand ################################################# #if you run this and do: deck = makedeck() hand = deal(5) #and then finally len(deck) #we find that the global deck has been modified within the deal() function without including global deck #within the deal() function #it seems insane to me that it's possible to alter global variables within functions without declaring global or passing the variable in as an argument. -------------- next part -------------- An HTML attachment was scrubbed... URL: From usamazohad at hotmail.com Tue Jan 1 16:47:04 2013 From: usamazohad at hotmail.com (usama zohad) Date: Tue, 1 Jan 2013 15:47:04 +0000 Subject: [Tutor] got stuck in equation Message-ID: my name is usama khan . . i am the student of civil engeering and we got assignment to make a project program on flexible pavement design using python.i know very litle about programing. still learning from tutorials. u can call me a beginner.now i need to solve this equation so that i can put this in python but the formula of design is very complext Formula is log(W18) = (Z)(S)+9.36log(SN+1) -2.0+(log(dpsi/(4.5-1.5))(/(.40+1094/(SN+1)^2.5)+2.32log(Mr)-8.07 every thing is constant except this SN. . i want to seperate SN like SN= rest of the stuff. how can i seprate it because manualy its impossible to take SN out. so plz help mend kindly tell me the solution that is easiest in python as am beginner. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jan 9 01:59:44 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Jan 2013 00:59:44 +0000 Subject: [Tutor] flushed queue Message-ID: I just finished flushing the moderation queue. It was full of spam over the holidays but there were some genuine messages there too. You'll no doubt see the older dates. Apologies for the delayed response in dealing with these. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jan 9 02:03:03 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Jan 2013 01:03:03 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 16/12/12 23:09, Dustin Guerri wrote: > Hi there, > > I'm completely new to Python and to programming. I have the Python > Launcher (v2.7.3) app installed on my system, and I'm running Mac OS X > Mountain Lion. Does this mean I have Python itself installed ? MacOS uses Python so you will undoubtedly have it onboard. It may not have all the features enabled (eg GUI support) so you may want to download the latest Mac build too (don't delete the standard install though you could break some tools on MacOS that use it!) Try launching it and see if you get a Python prompt: >>> coming up If so check it works with the classic >>> print ('hello world') Also take note of the version in the banner display above the prompt. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jan 9 02:07:57 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Jan 2013 01:07:57 +0000 Subject: [Tutor] modifying global within function without declaring global In-Reply-To: <1357349276.50451.YahooMailNeo@web162802.mail.bf1.yahoo.com> References: <1357349276.50451.YahooMailNeo@web162802.mail.bf1.yahoo.com> Message-ID: On 05/01/13 01:27, Nathaniel Huston wrote: > def deal(quantity): > > hand = [] > for cards in range(0, quantity): > hand.append(deck.pop()) > return hand > #we find that the global deck has been modified within the deal() > function without including > > global deck > > #within the deal() function Notice deal() modifies the contents of deck but not deck itself - it still points to the same list object. You only need to use global if you are changing the value. Since you are only modifying the contents you don't need the global statement. You have to think in terms of objects and names as references to the objects. If you are changing the object that the name refers to you need to use global. If you are only changing the content of the object then there is no need for global. The object here is the list. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Wed Jan 9 02:11:48 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 9 Jan 2013 01:11:48 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 16 December 2012 23:09, Dustin Guerri wrote: > Hi there, > > I'm completely new to Python and to programming. I have the Python Launcher > (v2.7.3) app installed on my system, and I'm running Mac OS X Mountain Lion. > Does this mean I have Python itself installed ? OSX ships with a Python installation, so every Mac has Python. I guess you mean that you have installed a newer Python installation? Try creating a plain text file called hello.py and putting the following text in it: print('hello world') raw_input('Press any key to continue') If you can run that program with the launcher then you're in business. Oscar From kbailey at howlermonkey.net Wed Jan 9 02:07:19 2013 From: kbailey at howlermonkey.net (Kirk Bailey) Date: Tue, 08 Jan 2013 20:07:19 -0500 Subject: [Tutor] Robot Radio program Message-ID: <50ECC2C7.6020908@howlermonkey.net> Simulates an old time radio station. Place program files in the numbered folders, station identifications in the ID folder, commercials in the com folder. run from the command line. directories under the program are: ID, Com, 1,2,3,4,5... ID contains station identifications. COM is commercial recordings. 1,2,3,4,5... each numbered directory contains mp3 files of a particular show. #!c:\Python25\pythonw.exe # from ctypes import * # Don't change any of these import os, time, glob, random # they are all needed import cgitb; cgitb.enable() # for operations or problem handling # ################################################################### # Robot Radio WHEN V:1.0.0 (C)2012, 2013 Kirk D Bailey All rights reserved. # # Visit our website and jawbone with us on the list! http://www.RobotRadio.info # ################################################################### # # there are 2 directories under this one- com and id. There are also numbered folders which # contain files of old broadcasts. The system only referrs to number name directories to play programs # but is taken by the hand to ID or com to play station identifications or commercials respectively. # # To add a broadcast group of 'programs', just create a new numbered directory and load the program # files into it- and that's it, the program adapts to it. DO NOT add any directories EXCEPT numbered # broadcast library file directories. The only 2 exceptions are com and ID. com contains commercials. # ID contains station identification blip, anywhere from 5 to 30 seconds long. You can make your own mp3 # files and place them here. # winmm = windll.winmm # a shorthand way to access a function. # def mciSend(s): # we access a dlll in the operating system to play mp3 files. i=winmm.mciSendStringA(s,0,0,0) if i<>0: print "Error %d in mciSendString %s" % ( i, s ) # def playMP3(mp3Name): # and we arap it in code to make using it really easy. mciSend("Close All") mciSend("Open \"%s\" Type MPEGVideo Alias theMP3" % mp3Name) mciSend("Play theMP3 Wait") mciSend("Close theMP3") # def RandomFile(): # and this lets us pick a ramdom file in the current directory- whatever that is. files=glob.glob("*.mp3") # files is a list of the CURRENT file=random.choice(files) # directories contents return file # and return the filename to be played # os.chdir("./RobotRadio_WHEN/") # starts in cgi-bin, move to application's dirlist=glob.glob("*") # WE WILL NEED THIS LATER IN RandomDir(); once is enough # def RandomDir(): dir=str(1+int(random.random()*(len(dirlist)-2))) return dir # COUNT=8 # this is how many times to do the loop, then quit. limit=COUNT+1 # this masages a offset to helpo display the loop count print "- - - - - - - - - - - - - - BEGIN Broadcast Day - - - - - - - - - - - - - - - - - -" # while COUNT: # this sets the number of loops. Get creative to stop it. # ok, let's do the loop. print "Loop #", limit-COUNT # this lets us display the loop count os.chdir("./ID") # go to the station identification folder mp3file=RandomFile() # print "Station Identification file:",mp3file," AT: ", time.strftime("%a, %d %b %Y %I:%M %p", time.localtime()) playMP3(mp3file) # and pick one at random and play it. os.chdir("..") # go back to the home directory for this program playMP3("./ID/NBCtones.mp3") # play the top of the hour NBC tones print "NBCtones.mp3 - play the NBC tri-tone" # we terimmed it off the end of another file, nice and clear and crisp. time.sleep(2) # a breif pause between file plays os.chdir("./com") # now back go home, then on to the commercial folder mp3file=RandomFile() # pick a commercial print "commercial: ",mp3file," AT: ", time.strftime("%a, %d %b %Y %I:%M %p", time.localtime()) # show me the commercial playMP3(mp3file) # and play it. time.sleep(2) # another pause- so there is a breif hesitation between one and next. os.chdir("..") # this takes us back to the home directory of the application newdir=RandomDir() # pick a dir, any dir, os.chdir(newdir) # and go there. mp3file=RandomFile() # pick a random file from this directory print "Program=", os.getcwd()+"\\"+ mp3file # show us what it is, print "AT:"+ time.strftime("%a, %d %b %Y %I:%M %p", time.localtime()) # And when, playMP3(mp3file) # and play it. os.chdir("../com") # now back go home, then on to the commercial folder mp3file=RandomFile() # pick a commercial playMP3(mp3file) # and play it. print "commercial: ",mp3file," AT: ", time.strftime("%a, %d %b %Y %I:%M %p", time.localtime()),"
" # show me the commercial os.chdir("..") # go home again. print "- - - - - - - - - - - - - - - - - - - - - - - - -" # the lines make it easier for they eye to track the half hour segments time.sleep(2) # this gives us some time to do a CNTL-C to break the loop. COUNT=COUNT-1 print "DONE. Station shutdown @ ",time.strftime("%a, %d %b %Y %I:%M %p", time.localtime()) # Now if we could just find a recording of a station shut down... # ZZZzzz... -- -Shaboom. Kirk Bailey CEO, Freehold Marketing LLC http://www.OneBuckHosting.com/ Fnord! From oscar.j.benjamin at gmail.com Wed Jan 9 02:15:14 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 9 Jan 2013 01:15:14 +0000 Subject: [Tutor] got stuck in equation In-Reply-To: References: Message-ID: On 1 January 2013 15:47, usama zohad wrote: > my name is usama khan . . i am the student of civil engeering and we got > assignment to make a project program on flexible pavement design using > python.i know very litle about programing. still learning from tutorials. u > can call me a beginner.now i need to solve this equation so that i can put > this in python but the formula of design is very complext > > Formula is > log(W18) = (Z)(S)+9.36log(SN+1) > -2.0+(log(dpsi/(4.5-1.5))(/(.40+1094/(SN+1)^2.5)+2.32log(Mr)-8.07 > > every thing is constant except this SN. . i want to seperate SN like SN= > rest of the stuff. how can i seprate it because manualy its impossible to > take SN out. > > so plz help me > nd kindly tell me the solution that is easiest in python as am beginner. Didn't you post this exact question very recently? You should add another post to the original thread if you are not satisfied with answers you got there rather than starting a new one. In any case your problem is not really a Python problem. You could use Python to solve it, but then you can probably get the answer you want just by putting your equation into something like Wolfram Alpha without any programming: http://www.wolframalpha.com/ Oscar From oscar.j.benjamin at gmail.com Wed Jan 9 02:16:41 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 9 Jan 2013 01:16:41 +0000 Subject: [Tutor] got stuck in equation In-Reply-To: References: Message-ID: On 9 January 2013 01:15, Oscar Benjamin wrote: > On 1 January 2013 15:47, usama zohad wrote: >> my name is usama khan . . i am the student of civil engeering and we got >> assignment to make a project program on flexible pavement design using >> python.i know very litle about programing. still learning from tutorials. u >> can call me a beginner.now i need to solve this equation so that i can put >> this in python but the formula of design is very complext >> >> Formula is >> log(W18) = (Z)(S)+9.36log(SN+1) >> -2.0+(log(dpsi/(4.5-1.5))(/(.40+1094/(SN+1)^2.5)+2.32log(Mr)-8.07 >> >> every thing is constant except this SN. . i want to seperate SN like SN= >> rest of the stuff. how can i seprate it because manualy its impossible to >> take SN out. >> >> so plz help me >> nd kindly tell me the solution that is easiest in python as am beginner. > > Didn't you post this exact question very recently? You should add > another post to the original thread if you are not satisfied with > answers you got there rather than starting a new one. I'm sorry, I just saw Alan's message about flushing the queue. I see now that you actually sent this message 8 days ago. My bad... Oscar From oscar.j.benjamin at gmail.com Wed Jan 9 02:21:13 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 9 Jan 2013 01:21:13 +0000 Subject: [Tutor] Python Question In-Reply-To: References: Message-ID: On 7 January 2013 23:31, Dylan Kaufman wrote: > Greetings, > > I take Computer Science in school and for a Python program, I have: > > from winsound import Beep > [SNIP] > > When I run it at school it works great, but at home when I try to run it, it > says: > > Traceback (most recent call last): > File "/Volumes/PICKLES/School/MyClass/Comp. Sci/Chapter 02 > Stuff/program2_cep.py", line 5, in > from winsound import Beep > ImportError: No module named 'winsound' Judging from the path "/Volumes/PICKLES/..." I'd say you're not running Windows and... > > Could you tell why this is happening and how I can make my program work? winsound only works on Windows (it quietly says "Platforms: Windows" at the top of this page): http://docs.python.org/2/library/winsound.html Oscar From oscar.j.benjamin at gmail.com Wed Jan 9 02:32:29 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 9 Jan 2013 01:32:29 +0000 Subject: [Tutor] modifying global within function without declaring global In-Reply-To: References: <1357349276.50451.YahooMailNeo@web162802.mail.bf1.yahoo.com> Message-ID: On 9 January 2013 01:07, Alan Gauld wrote: > On 05/01/13 01:27, Nathaniel Huston wrote: > >> def deal(quantity): >> >> hand = [] >> for cards in range(0, quantity): >> hand.append(deck.pop()) >> return hand > > >> #we find that the global deck has been modified within the deal() >> function without including >> >> global deck >> >> #within the deal() function > > Notice deal() modifies the contents of deck but not deck itself - it still > points to the same list object. > > You only need to use global if you are changing the value. Since you are > only modifying the contents you don't need the global statement. I agree entirely with what Alan said but have a slightly different way of thinking about it: you only need the global statement if you want to assign directly to a name (and have the assignment apply globally). Examples: x = some_obj() def some_function(): x = b # direct assignment (global statement needed) def some_other_function(): x.e = c # attribute assignment (global not needed) x[f] = d # item assignment (global not needed) x.mutating_func(g) # method call (global not needed) The only one of the above statements that is affected by a "global x" statement is the first. The other three calls will all modify x in place regardless of any global statement. A global statement is needed when you want to assign directly to a variable name and have the assignment apply in an outer scope as is the case with the "x = b" line above. In any other situation the global statement does nothing. Oscar From msirenef at lightbird.net Wed Jan 9 02:32:40 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Tue, 08 Jan 2013 20:32:40 -0500 Subject: [Tutor] modifying global within function without declaring global In-Reply-To: References: <1357349276.50451.YahooMailNeo@web162802.mail.bf1.yahoo.com> Message-ID: <50ECC8B8.1020603@lightbird.net> On Tue 08 Jan 2013 08:07:57 PM EST, Alan Gauld wrote: > On 05/01/13 01:27, Nathaniel Huston wrote: > >> def deal(quantity): >> >> hand = [] >> for cards in range(0, quantity): >> hand.append(deck.pop()) >> return hand > > > #we find that the global deck has been modified within the deal() > > function without including > > > > global deck > > > > #within the deal() function > > Notice deal() modifies the contents of deck but not deck itself - it > still points to the same list object. > > You only need to use global if you are changing the value. Since you > are only modifying the contents you don't need the global statement. > > You have to think in terms of objects and names as references to the > objects. If you are changing the object that the name refers to you > need to use global. If you are only changing the content of the object > then there is no need for global. The object here is the list. > Actually, modifying a global name is OK, it is not OK to rebind it, e.g.: # OK: l=[] def f(): l.append(1) # won't rebind global: def b(): l=[2] After you run both, you'll see l is [1] This is a very important difference, if it helps, it's similar to this real-world example: Let's say you're a student in a school and you have a teacher who is standing before a blackboard and writing something. After he gets to the end of the blackboard, he picks up a phone and says "supply room? Can you please order a new blackboard and deliver to me, I've run out of space". Then a few minutes go by and a delivery person shows up, with a spanking new black board, installs it and then leaves. The teacher goes back to writing down his formulas but soon runs out of space again and has to call for a new board again. Someone raises a hand and asks him why he does not erase the board, instead. He looks puzzled and replies that he thought it's the same thing, whether you erase the board or make a new one. In Python, of course, both operations are equally fast (more or less), so it's easy to forget about the difference. # order new board board = [] # OR board = list() # erase the existing board board[:] = [] So, back to local and global bindings... If the board is not a global name, you CAN modify it, but you can NOT order a new board and have it available globally -- unless you use the 'global' keyword. Integers, floats and strings are immutable so you can't modify them anyway, when you change them, you can only rebind: # global is NOT changed! x = 5 def f(): x = 6 Hope this helps, -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From krush1954 at yahoo.com Wed Jan 9 07:56:20 2013 From: krush1954 at yahoo.com (ken brockman) Date: Tue, 8 Jan 2013 22:56:20 -0800 (PST) Subject: [Tutor] using 'and ' and 'or' with integers Message-ID: <1357714580.67142.YahooMailNeo@web39305.mail.mud.yahoo.com> I was looking through some lab material from a computer course offered at UC Berkeley and came across some examples in the form of questions on a test about python. 1 and 2 and 3 ?answer 3 I've goggled it till i was red in the fingers, but to no avail.. Could someone be kind enuff to direct me to some docs that explain this?? I've no clue what the hell is going on here.. Thanks much for any help you may supply. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gayathri.s112 at gmail.com Wed Jan 9 08:28:43 2013 From: gayathri.s112 at gmail.com (Gayathri S) Date: Wed, 9 Jan 2013 12:58:43 +0530 Subject: [Tutor] HELP- Regarding working with python In-Reply-To: References: Message-ID: Hi.. I would like to use Principal component analysis independent component analysis in python. Wanna know whether it will support this efficiently or not? On Wed, Jan 2, 2013 at 4:59 PM, Alan Gauld wrote: > On 02/01/13 07:20, Gayathri S wrote: > >> Hi.. >> I am using python 2.7 and scikit-learn for machine learning. >> And OS is Windows 7. Wanna know how to import our own data sets in >> scikit-learn? >> > > Further to my last mail there is a gmane group > > gmane.comp.python.scikit-learn > > I'd try looking there, or wherever it is sourced originally. > > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Keep Smiling......... Regards........ Gayu.... -------------- next part -------------- An HTML attachment was scrubbed... URL: From andipersti at gmail.com Wed Jan 9 08:36:31 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Wed, 09 Jan 2013 08:36:31 +0100 Subject: [Tutor] using 'and ' and 'or' with integers In-Reply-To: <1357714580.67142.YahooMailNeo@web39305.mail.mud.yahoo.com> References: <1357714580.67142.YahooMailNeo@web39305.mail.mud.yahoo.com> Message-ID: <50ED1DFF.2070509@gmail.com> [Please don't send HTML to this list. Just use plain text] On 09.01.2013 07:56, ken brockman wrote: > I was looking through some lab material from a computer course > offered at UC Berkeley and came across some examples in the form of > questions on a test about python. 1 and 2 and 3 answer 3 I've goggled > it till i was red in the fingers, but to no avail.. Could someone be > kind enuff to direct me to some docs that explain this?? Language Reference - 6.10 Boolean operations (for Python 3.3; it's 5.10 for Python 2.7): http://docs.python.org/3.3/reference/expressions.html#boolean-operations "The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned." Bye, Andreas From msirenef at lightbird.net Wed Jan 9 08:41:03 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Wed, 09 Jan 2013 02:41:03 -0500 Subject: [Tutor] using 'and ' and 'or' with integers In-Reply-To: <1357714580.67142.YahooMailNeo@web39305.mail.mud.yahoo.com> References: <1357714580.67142.YahooMailNeo@web39305.mail.mud.yahoo.com> Message-ID: <50ED1F0F.6080705@lightbird.net> On Wed 09 Jan 2013 01:56:20 AM EST, ken brockman wrote: > I was looking through some lab material from a computer course offered > at UC Berkeley and came across some examples in the form of questions > on a test about python. > 1 and 2 and 3 > answer 3 > I've goggled it till i was red in the fingers, but to no avail.. Could > someone be kind enuff to direct me to some docs that explain this?? > I've no clue what the hell is going on here.. > Thanks much for any help you may supply. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor It returns last evaluated value. If you have '1 and 2', 1 is 'truthy', so it needs to evaluate 2, and then 2 is returned. With '0 and 2', 0 is falsy, so it does not need to evaluate past it and returns 0. With '0 or 2', it needs to evaluate 2 and returns its value. This is particularly useful to assign only when a value is falsy: default_x = 5 def f(x): x = x or default_x So if x is provided, it is used, but if x is, let's say, None, default_x will be used. HTH, - mitya -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From steve at alchemy.com Wed Jan 9 09:05:22 2013 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 9 Jan 2013 00:05:22 -0800 Subject: [Tutor] Python Question In-Reply-To: References: Message-ID: <31C1DDBD-B3B8-49B4-A87D-74C334E34F53@alchemy.com> On 2013-1?-7, at ??3:31, Dylan Kaufman wrote: > Greetings, > > I take Computer Science in school and for a Python program, I have: > > from winsound import Beep > The first thing I notice is "from winsound import ?" Could that be a WINDOWS library which might not work on a Macintosh? > Beep(196, 1500)#G > Beep(262, 270)#C > Beep(196, 200)#G > > Traceback (most recent call last): > File "/Volumes/PICKLES/School/MyClass/Comp. Sci/Chapter 02 Stuff/program2_cep.py", line 5, in > from winsound import Beep > ImportError: No module named 'winsound' > Looking at this, /Volumes/PICKLES/School/... that looks like a Mac filesystem mount point name to me. Looks like you're using something that works on Windows at school, then trying to use it on a non-Windows system at home. Try looking for a sound library which works on all platforms. Failing that, look for something that works on a mac. As a side note, you probably want to replace all those Beep() calls with some code which reads in a set of note values as data. From brian.van.den.broek at gmail.com Wed Jan 9 08:49:07 2013 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Wed, 9 Jan 2013 02:49:07 -0500 Subject: [Tutor] using 'and ' and 'or' with integers In-Reply-To: <1357714580.67142.YahooMailNeo@web39305.mail.mud.yahoo.com> References: <1357714580.67142.YahooMailNeo@web39305.mail.mud.yahoo.com> Message-ID: On 9 January 2013 01:56, ken brockman wrote: > I was looking through some lab material from a computer course offered at UC > Berkeley and came across some examples in the form of questions on a test > about python. > 1 and 2 and 3 > answer 3 > I've goggled it till i was red in the fingers, but to no avail.. Could > someone be kind enuff to direct me to some docs that explain this?? I've no > clue what the hell is going on here.. > Thanks much for any help you may supply. > Ken, I don't have a link, but I'll take a stab. Any non-zero integer evaluates to True: >>> if 42: print "!" ! Python's boolean operators use short-circuit evaluation---they return a value as soon as they have seen enough to know what truth-value the compound evaluates to. And, the value they return isn't always True or False. Rather, they return the object in virtue of which they had seen enough to know whether the evaluated value is True or False: >>> True or 4 True >>> 4 or True 4 Since 4 evaluates as True, and `something True or anything at all' will evaluate to True, in the second case 4 is returned. Likewise, in your case: >>> 1 and 2 and 3 3 >>> (1 and 2) and 3 3 >>> 1 and (2 and 3) 3 >>> (I put the two bracketting ones in as I cannot recall if python associates to the left or to the right. I'm pretty sure left, but it doesn't matter here.) Consider the last version. Since 1 evals as True, python has to look at the left conjunct. 2 does, too, so it has to look at 3. Since 3 does, and python now knows the whole evals as True, it returns 3. HTH, Brian vdB From alan.gauld at btinternet.com Wed Jan 9 09:53:48 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Jan 2013 08:53:48 +0000 Subject: [Tutor] using 'and ' and 'or' with integers In-Reply-To: <1357714580.67142.YahooMailNeo@web39305.mail.mud.yahoo.com> References: <1357714580.67142.YahooMailNeo@web39305.mail.mud.yahoo.com> Message-ID: On 09/01/13 06:56, ken brockman wrote: > 1 and 2 and 3 > answer 3 > I've goggled it till i was red in the fingers, but to no avail.. Could > someone be kind enuff to direct me to some docs that explain this?? I've > no clue what the hell is going on here.. Its to do with the way Python evaluates booleans using short circuit evaluation. There is a short section in my tutorial under the "Functional Propgramming" topic, in the 'other contructs heading about half way down. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From chakrabarti.somnath at gmail.com Wed Jan 9 10:38:24 2013 From: chakrabarti.somnath at gmail.com (somnath chakrabarti) Date: Wed, 9 Jan 2013 04:38:24 -0500 Subject: [Tutor] pexports python27.dll > python27.def (pygraphviz 1.1 package ) Message-ID: I have mingw and python 2.7 in a Windows 7 box and trying to install PyGraphViz-1.1 using the following CLI utility python setup.py install build --compiler=mingw32 However, it ends up compiling error with undefined references as follows: ... build\temp.win-amd64-2.7\Release\pygraphviz\graphviz_wrap.o:graphviz_wrap.c:(.text+0x5a73): undefined reference to '_imp__PyInt_FromLong' collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 I checked in the link (see here) which suggests exporting definitions from C:\Windows\System32\python27.dll to python27.def and then using dlltool to create libpython27.a and finally placing the libpython.a file under C:\Python27\libs of the Python distribution for MinGW to interpret Python libraries. I have the C:\MinGW\bin added to my system path and been trying to do the export using pexports C:\Windows\System32\python27.dll > C:\Windows\System32\python27.def but each time I am receiving Access is Denied Message. I did some searching and found that MS Visual Studio users can avail another export option with DUMPBIN but since I don't have MSVS installed, I would like to get some alternative to get rid of the problem and need to use the PyGraphViz-1.1 package. Any suggestions will be very helpful Somnath Chakrabarti MS Student CSEE Department University of Maryland Baltimore County 1000 Hilltop Circle Baltimore, MD 21250 M: 443-812-5609 mail: chakra1 at umbc.edu gmail: chakrabarti.somnath at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Wed Jan 9 12:20:13 2013 From: timomlists at gmail.com (Timo) Date: Wed, 09 Jan 2013 12:20:13 +0100 Subject: [Tutor] Parsing and evaluating user input Message-ID: <50ED526D.9080303@gmail.com> I'm having trouble finding a safe way to parse and evaluate user input in my program. In my app, I'm using a calculation like this: (a / b) * 100 The user should be able to override this and their preference is stored in a configuration file for later use. So I now have a string with the user defined calculation template, for example: >>> config.get('custom-calc') '(a * b) / 10' I could tell the user the values should be entered like %(a)s and %(b)s which makes parsing easier I think, because I can do this: >>> custom_calc = config.get('custom-calc') >>> custom_calc '(%(a)s * %(b)s) / 10' >>> calc_str = custom_calc % {'a': get_value_a(), 'b': get_value_b()} I should parse this, fill in the values which the program has at that point and calculate the outcome. What is the safest way? Timo From oscar.j.benjamin at gmail.com Wed Jan 9 12:52:36 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 9 Jan 2013 11:52:36 +0000 Subject: [Tutor] Parsing and evaluating user input In-Reply-To: <50ED526D.9080303@gmail.com> References: <50ED526D.9080303@gmail.com> Message-ID: On 9 January 2013 11:20, Timo wrote: > I'm having trouble finding a safe way to parse and evaluate user input in my > program. > > In my app, I'm using a calculation like this: > (a / b) * 100 > The user should be able to override this and their preference is stored in a > configuration file for later use. So I now have a string with the user > defined calculation template, for example: > >>>> config.get('custom-calc') > '(a * b) / 10' > > I could tell the user the values should be entered like %(a)s and %(b)s > which makes parsing easier I think, because I can do this: >>>> custom_calc = config.get('custom-calc') >>>> custom_calc > '(%(a)s * %(b)s) / 10' >>>> calc_str = custom_calc % {'a': get_value_a(), 'b': get_value_b()} I don't think this '%(x)' part is really necessary. If you can parse the arithmetic expression and compute the result, then it's easy enough to subsitute variable names for values after parsing the string. However, this is a big if. > > I should parse this, fill in the values which the program has at that point > and calculate the outcome. What is the safest way? A very similar question was recently asked on the python-list mailing list: https://mail.python.org/pipermail/python-list/2013-January/637869.html Currently there is no really safe way to do it using the standard library but there are a number of suggestions in that thread. My own suggestion in that thread was to use the third-party numexpr module: >>> import numexpr >>> int(numexpr.evaluate('(a * b) / 10', {'a':20, 'b':30})) 60 http://code.google.com/p/numexpr/ Oscar From wayne at waynewerner.com Wed Jan 9 12:56:20 2013 From: wayne at waynewerner.com (Wayne Werner) Date: Wed, 9 Jan 2013 05:56:20 -0600 (CST) Subject: [Tutor] writing effective unittests In-Reply-To: References: <20130102204357.GA1974@lmerg-crunchbang> <1357217453.36448.YahooMailNeo@web163805.mail.gq1.yahoo.com> <20130103194641.GA10033@lmerg-crunchbang> Message-ID: On Thu, 3 Jan 2013, Japhy Bartlett wrote: > The general idea is to write tests that use your code in realistic ways and check the results. ?So if you have a function that takes an input and returns > a result, you write a test that passes that function an input checks the result. ?If some inputs should make it error, you write a test that checks that > it errors. > In web programming, a common thing is to make a web request with different variations of GET / PUT params, then check that it returns the right status > code, or that the result is valid JSON, etc. ?Basically, try to simulate all the things a real world user would be able to use, and test that your code > does what you intend for it to do. > > TDD is a good principle but usually seems a little too pedantic for real world programming. ?Where tests (in my experience) get really useful is in > making sure that a new change hasn't unexpectedly broken something already written. That's funny, I find it exactly the opposite - unless I'm writing some prototype throw-away code, doing TDD has actually exposed problems with the underlying program structure precisely because it *is* pedantic. Granted, if I needed to get a fix in place in production code that was costing buckets of cash every minute it wasn't fixed, I'd write the code, push that out, and *then* write the tests... but when I've been practicing TDD I've not had that problem. My experience is that it has a tendency to bundle all the development costs right up front - instead of a little here, a little there. But... that's just my experience ;) -Wayne From oscar.j.benjamin at gmail.com Wed Jan 9 12:58:50 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 9 Jan 2013 11:58:50 +0000 Subject: [Tutor] pexports python27.dll > python27.def (pygraphviz 1.1 package ) In-Reply-To: References: Message-ID: Please post in plain text on this mailing list (not html). On 9 January 2013 09:38, somnath chakrabarti wrote: > > I have mingw and python 2.7 in a Windows 7 box and trying to install > PyGraphViz-1.1 using the following CLI utility > > python setup.py install build --compiler=mingw32 > > However, it ends up compiling error with undefined references as follows: > > ... > build\temp.win-amd64-2.7\Release\pygraphviz\graphviz_wrap.o:graphviz_wrap.c:(.text+0x5a73): > undefined reference to '_imp__PyInt_FromLong' > collect2: ld returned 1 exit status > error: command 'gcc' failed with exit status 1 > > I checked in the link (see here) which suggests exporting definitions from > C:\Windows\System32\python27.dll to python27.def and then using dlltool to > create libpython27.a and finally placing the libpython.a file under > C:\Python27\libs of the Python distribution for MinGW to interpret Python > libraries. > > I have the C:\MinGW\bin added to my system path and been trying to do the > export using > > pexports C:\Windows\System32\python27.dll > C:\Windows\System32\python27.def > > but each time I am receiving Access is Denied Message. That's a system folder. You'll probably need to run that command as an administrator or something (not really sure how that works on Windows). > > I did some searching and found that MS Visual Studio users can avail another > export option with DUMPBIN but since I don't have MSVS installed, I would > like to get some alternative to get rid of the problem and need to use the > PyGraphViz-1.1 package. Any suggestions will be very helpful My suggestion is to ask somewhere else. This mailing list is for beginners looking for help with general aspects of Python. Your question is very specific and is about distutils, PyGraphViz and mingw32. I suggest that you contact either the author(s) of PyGraphViz or the distutils-sig mailing list: https://mail.python.org/mailman/listinfo/distutils-sig Oscar From chakrabarti.somnath at gmail.com Wed Jan 9 13:09:18 2013 From: chakrabarti.somnath at gmail.com (somnath chakrabarti) Date: Wed, 9 Jan 2013 07:09:18 -0500 Subject: [Tutor] pexports python27.dll > python27.def (pygraphviz 1.1 package ) In-Reply-To: References: Message-ID: Actually I embedded a link to the refer site from where I have been following the procedure. I am new to Python too and have been following the book "Mining the Social Web" by Matthew Russell and thought Tutor mailing list would be the right place to post the question. Anyways will try to post in text and more python generic questions next time. Thanks for pointing out though! :) -Somnath On Wed, Jan 9, 2013 at 6:58 AM, Oscar Benjamin wrote: > Please post in plain text on this mailing list (not html). > > On 9 January 2013 09:38, somnath chakrabarti > wrote: > > > > I have mingw and python 2.7 in a Windows 7 box and trying to install > > PyGraphViz-1.1 using the following CLI utility > > > > python setup.py install build --compiler=mingw32 > > > > However, it ends up compiling error with undefined references as follows: > > > > ... > > > build\temp.win-amd64-2.7\Release\pygraphviz\graphviz_wrap.o:graphviz_wrap.c:(.text+0x5a73): > > undefined reference to '_imp__PyInt_FromLong' > > collect2: ld returned 1 exit status > > error: command 'gcc' failed with exit status 1 > > > > I checked in the link (see here) which suggests exporting definitions > from > > C:\Windows\System32\python27.dll to python27.def and then using dlltool > to > > create libpython27.a and finally placing the libpython.a file under > > C:\Python27\libs of the Python distribution for MinGW to interpret Python > > libraries. > > > > I have the C:\MinGW\bin added to my system path and been trying to do the > > export using > > > > pexports C:\Windows\System32\python27.dll > > C:\Windows\System32\python27.def > > > > but each time I am receiving Access is Denied Message. > > That's a system folder. You'll probably need to run that command as an > administrator or something (not really sure how that works on > Windows). > > > > > I did some searching and found that MS Visual Studio users can avail > another > > export option with DUMPBIN but since I don't have MSVS installed, I would > > like to get some alternative to get rid of the problem and need to use > the > > PyGraphViz-1.1 package. Any suggestions will be very helpful > > My suggestion is to ask somewhere else. This mailing list is for > beginners looking for help with general aspects of Python. Your > question is very specific and is about distutils, PyGraphViz and > mingw32. I suggest that you contact either the author(s) of PyGraphViz > or the distutils-sig mailing list: > https://mail.python.org/mailman/listinfo/distutils-sig > > > Oscar > -- Somnath Chakrabarti MS Student CSEE Department University of Maryland Baltimore County 1000 Hilltop Circle Baltimore, MD 21250 M: 443-812-5609 mail: chakra1 at umbc.edu gmail: chakrabarti.somnath at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Wed Jan 9 13:41:59 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 9 Jan 2013 07:41:59 -0500 Subject: [Tutor] Python Question In-Reply-To: References: Message-ID: On Mon, Jan 7, 2013 at 6:31 PM, Dylan Kaufman wrote: > > from winsound import Beep > > Beep(196, 1500)#G winsound.Beep wraps the Windows (win32) system call of the same name. Instead, consider using a cross-platform library such as PortAudio or PortMidi: http://sourceforge.net/apps/trac/portmedia One option is to synthesize PCM audio and play it with PyAudio, which wraps PortAudio. But you'll probably have more fun with MIDI (Musical Instrument Digital Interface). Installing pyPortMidi involves compiling libportmidi and the Cython/Pyrex extension module. If you run into trouble there, hopefully an OS X user on the list can help. Alternatively, pygame includes pyPortMidi as pygame.midi: pygame installers: http://www.pygame.org/download.shtml Demo: import and initialize: >>> from time import sleep >>> from pygame import midi >>> midi.init() list devices: >>> for i in range(midi.get_count()): ... print i, midi.get_device_info(i) ... 0 ('ALSA', 'Midi Through Port-0', 0, 1, 0) 1 ('ALSA', 'Midi Through Port-0', 1, 0, 0) 2 ('ALSA', 'TiMidity port 0', 0, 1, 0) 3 ('ALSA', 'TiMidity port 1', 0, 1, 0) 4 ('ALSA', 'TiMidity port 2', 0, 1, 0) 5 ('ALSA', 'TiMidity port 3', 0, 1, 0) open output for MIDI device 2: >>> device = 2 >>> latency = 0 >>> out = midi.Output(device, latency) set the channel 0 instrument to GM (General MIDI) steel drum: >>> instrument = STEEL_DRUM = 114 >>> channel = 0 >>> out.set_instrument(instrument, channel) play some notes: >>> MAX_VOL = 127 >>> MID_C = 60 >>> for i in range(12): ... out.note_on(MID_C + i, MAX_VOL, channel) ... sleep(0.5) ... out.note_off(MID_C + i, MAX_VOL, channel) You can also write MIDI messages directly (0x90 + n is "note on" for channel n): >>> out.write_short(0x90 + channel, MID_C, MAX_VOL) General Links MIDI and Music Synthesis http://www.midi.org/aboutmidi/tut_midimusicsynth.php Message Protocol http://www.midi.org/techspecs/midimessages.php GM Sound Set http://www.midi.org/techspecs/gm1sound.php Note Numbers: http://www.midimountain.com/midi/midi_note_numbers.html From cranky.frankie at gmail.com Wed Jan 9 13:45:33 2013 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Wed, 9 Jan 2013 07:45:33 -0500 Subject: [Tutor] Python Question Message-ID: Dylan Kaufman wrote: <> snip the rest I was able to get this to work in Python 3.2 under Windows 7 by changing all occurances of "Beep" to "winsound.Beep" -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?Take the risks and you?ll get the payoffs. Learn from your mistakes until you succeed. It?s that simple.? - Bobby Flay From steve at pearwood.info Wed Jan 9 15:16:04 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 10 Jan 2013 01:16:04 +1100 Subject: [Tutor] Robot Radio program In-Reply-To: <50ECC2C7.6020908@howlermonkey.net> References: <50ECC2C7.6020908@howlermonkey.net> Message-ID: <50ED7BA4.3070602@pearwood.info> On 09/01/13 12:07, Kirk Bailey wrote: > Simulates an old time radio station. Place program files in the numbered > folders, station identifications in the ID folder, commercials in the com >folder. run from the command line. [...] Did you have a question, or where you just sharing the code with us? -- Steven From steve at pearwood.info Wed Jan 9 15:37:27 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 10 Jan 2013 01:37:27 +1100 Subject: [Tutor] Documentation In-Reply-To: <50EA457A.9030500@gmx.com> References: <50D37A37.4070805@pearwood.info> <50D37E1C.3070901@davea.name> <66098356-604F-47DB-A78B-2CC859623BBE@gmail.com> <50E72B95.8090009@libero.it> <50EA457A.9030500@gmx.com> Message-ID: <50ED80A7.7070209@pearwood.info> On 07/01/13 14:48, Ed Owens wrote: [...] > parser = HTMLParser(formatter.AbstractFormatter( > formatter.DumbWriter(cStringIO.StringIO()))) > HTMLParser is from htmllib. > > I'm having trouble finding clear documentation for what the functions >that are on the 'parser =' line do and return. The three modules >(htmllib, formatter, & cStringIO are all imported, but I can't seem to > find much info on how they work and what they do. What this actually >does and what it produces is completely obscure to me. > > Any help would be appreciated. Any links to clear documentation and >examples? I'll start with the easiest: cStringIO, and it's slower cousin StringIO, are modules for creating fake in-memory file-like objects. Basically they create an object that holds a string in memory but behaves as if it were a file object. http://docs.python.org/2/library/stringio.html The formatter module is used to produce an object that you can use for creating formatted text. It's quite abstract, and to be honest I have never used it and don't know how it works. http://docs.python.org/2/library/formatter.html The htmllib module is a library for parsing HTML code. Essentially, you use it to read the content of webpages (.html files). http://docs.python.org/2/library/htmllib.html Unfortunately, there is not a lot of documentation for the htmllib.HTMLParser object, so I can't help you with that. -- Steven From richkappler at gmail.com Wed Jan 9 19:27:26 2013 From: richkappler at gmail.com (richard kappler) Date: Wed, 9 Jan 2013 13:27:26 -0500 Subject: [Tutor] .strip question Message-ID: I have a sort of a dictionary resulting from psutil.disk_usage('/') that tells me info about my hard drive, specifically: usage(total=147491323904, used=62555189248, free=77443956736, percent=42.4) I'm having a bit of a brain fudge here and can't remember how to strip out what I want. All I want to end up with is the number percent (in this case 42.4) I started playing with .strip but the usage term before the parens gets in the way. If it weren't for that I could convert this into a dict and just pull the number by the key, right? So how do I strip out the 'usage' string? Once I do that, I think I know what I'm doing but here's my proposed code to look at if you would. import psutil as ps disk = ps.disk_usage('/') # whatever I need to do to strip usage out d = {} for item in disk.split(','): item = item.strip() key, value = item.split(':') key = key.strip() value = value.strip() d[key] = float(value) return d Mind you, this is as of yet untested code, so before you ask for tracebacks, I can't give any until I figure out how to get rid of the preceding 'usage'. regards, Richard -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From msirenef at lightbird.net Wed Jan 9 19:44:32 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Wed, 09 Jan 2013 13:44:32 -0500 Subject: [Tutor] .strip question In-Reply-To: References: Message-ID: <50EDBA90.90504@lightbird.net> On Wed 09 Jan 2013 01:27:26 PM EST, richard kappler wrote: > I have a sort of a dictionary resulting from psutil.disk_usage('/') > that tells me info about my hard drive, specifically: > > usage(total=147491323904, used=62555189248, free=77443956736, > percent=42.4) > > I'm having a bit of a brain fudge here and can't remember how to strip > out what I want. All I want to end up with is the number percent (in > this case 42.4) I started playing with .strip but the usage term > before the parens gets in the way. If it weren't for that I could > convert this into a dict and just pull the number by the key, right? > So how do I strip out the 'usage' string? Once I do that, I think I > know what I'm doing but here's my proposed code to look at if you would. > > import psutil as ps > > disk = ps.disk_usage('/') > > # whatever I need to do to strip usage out > > d = {} > for item in disk.split(','): > item = item.strip() > key, value = item.split(':') > key = key.strip() > value = value.strip() > d[key] = float(value) > return d > > Mind you, this is as of yet untested code, so before you ask for > tracebacks, I can't give any until I figure out how to get rid of the > preceding 'usage'. > > regards, Richard > > > -- > > quando omni flunkus moritati > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Is it actually a string, though? Can you do disk.percent or disk['percent'] ? If it IS a string, you can get percent value like so: # split by equal sign, strip parens from last value print(disk.split('=')[-1].strip(')')) - mitya -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From __peter__ at web.de Wed Jan 9 20:01:35 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 Jan 2013 20:01:35 +0100 Subject: [Tutor] .strip question References: Message-ID: richard kappler wrote: > I have a sort of a dictionary resulting from psutil.disk_usage('/') that > tells me info about my hard drive, specifically: > > usage(total=147491323904, used=62555189248, free=77443956736, > percent=42.4) > > I'm having a bit of a brain fudge here and can't remember how to strip out > what I want. All I want to end up with is the number percent (in this case > 42.4) I started playing with .strip but the usage term before the parens > gets in the way. If it weren't for that I could convert this into a dict > and just pull the number by the key, right? So how do I strip out the > 'usage' string? Once I do that, I think I know what I'm doing but here's > my proposed code to look at if you would. > > import psutil as ps > > disk = ps.disk_usage('/') > > # whatever I need to do to strip usage out > > d = {} > for item in disk.split(','): > item = item.strip() > key, value = item.split(':') > key = key.strip() > value = value.strip() > d[key] = float(value) > return d > > Mind you, this is as of yet untested code, so before you ask for > tracebacks, I can't give any until I figure out how to get rid of the > preceding 'usage'. Problems like this are easily attacked in the interactive interpreter. With dir() you can find out an object's attributes: >>> import psutil >>> du = psutil.disk_usage("/") >>> du usage(total=244020019200, used=72860221440, free=158764216320, percent=29.9) >>> dir(du) ['__add__', '__class__', '__contains__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '_asdict', '_fields', '_make', '_replace', 'count', 'free', 'index', 'percent', 'total', 'used'] As you can see one of du's attributes is percent, so let's have a look at its contents: >>> du.percent 29.9 So that was easy, wasn't it? No need for string manipulation. From tgirowall at yahoo.com Thu Jan 10 02:14:45 2013 From: tgirowall at yahoo.com (T. Girowall) Date: Wed, 9 Jan 2013 17:14:45 -0800 (PST) Subject: [Tutor] run perl script files and capture results Message-ID: <1357780485.90601.YahooMailNeo@web140003.mail.bf1.yahoo.com> New to programing and need some help. ? I have?multiple perl script files that I would like to automate using python. Currently each one is ran individually and the output is manually examined. The perl script is ran form the command promp with arguments as follows: ? c:\scripts\perl>perl plscript.pl -cmnd1 -cmnd2 ? cmnd1 and cmnd2 are ran on files that reside within "perl" directory. The output is displayed in DOS window. ? My objective: 1. Run the perl script using python 2. Capture the results from the DOS window and save it to python. Output consists of text names and corresponding numbers. ? I'm using python 2.7 ? Thank you! Tim -------------- next part -------------- An HTML attachment was scrubbed... URL: From eowens0124 at gmx.com Thu Jan 10 03:26:15 2013 From: eowens0124 at gmx.com (Ed Owens) Date: Wed, 09 Jan 2013 21:26:15 -0500 Subject: [Tutor] Flow charts In-Reply-To: <50ED80A7.7070209@pearwood.info> References: <50D37A37.4070805@pearwood.info> <50D37E1C.3070901@davea.name> <66098356-604F-47DB-A78B-2CC859623BBE@gmail.com> <50E72B95.8090009@libero.it> <50EA457A.9030500@gmx.com> <50ED80A7.7070209@pearwood.info> Message-ID: <50EE26C7.1080501@gmx.com> I'm working my way through Chun's book "Core Python Applications Programming" and can't get one of the examples to actually work. In trying to analyze the problem (good learning approach) I had troubles understanding the interactions between the two classes of objects. As an old FORTRAN programmer, I picked up my pencil to flowchart the code, then realized I didn't know how to flowchart an OOP. Google led me to UML (Unified Modeling Language) and OMG (apparently Oh My God!!!). Looks more complicated than the code I'm trying to understand. It there a technique that people use to figure out how do design OOP models, objects, and the information flow? Thanks for helping a newby. Ed From msirenef at lightbird.net Thu Jan 10 04:04:32 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Wed, 09 Jan 2013 22:04:32 -0500 Subject: [Tutor] Flow charts In-Reply-To: <50EE26C7.1080501@gmx.com> References: <50D37A37.4070805@pearwood.info> <50D37E1C.3070901@davea.name> <66098356-604F-47DB-A78B-2CC859623BBE@gmail.com> <50E72B95.8090009@libero.it> <50EA457A.9030500@gmx.com> <50ED80A7.7070209@pearwood.info> <50EE26C7.1080501@gmx.com> Message-ID: <50EE2FC0.8040702@lightbird.net> On Wed 09 Jan 2013 09:26:15 PM EST, Ed Owens wrote: > I'm working my way through Chun's book "Core Python Applications > Programming" and can't get one of the examples to actually work. In > trying to analyze the problem (good learning approach) I had troubles > understanding the interactions between the two classes of objects. As > an old FORTRAN programmer, I picked up my pencil to flowchart the > code, then realized I didn't know how to flowchart an OOP. > > Google led me to UML (Unified Modeling Language) and OMG (apparently > Oh My God!!!). Looks more complicated than the code I'm trying to > understand. > > It there a technique that people use to figure out how do design OOP > models, objects, and the information flow? > > Thanks for helping a newby. > Ed > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Here's what I do sometimes: 1. write down the steps that need to be done 2. write pseudo-code for the steps 3. revise 4. make one single class with many methods. If you are familiar with programming with just functions, this is the same but instead of functions you have methods. 5. note which methods should logically be split up into separate classes & refactor Once you do this with a few programs, you'll be able to start with several classes right away, without the need for intermediary 'main' class. I haven't used diagrams to design in a long time so I won't comment on that. HTH, - m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From d at davea.name Thu Jan 10 06:36:10 2013 From: d at davea.name (Dave Angel) Date: Thu, 10 Jan 2013 00:36:10 -0500 Subject: [Tutor] Flow charts In-Reply-To: <50EE26C7.1080501@gmx.com> References: <50D37A37.4070805@pearwood.info> <50D37E1C.3070901@davea.name> <66098356-604F-47DB-A78B-2CC859623BBE@gmail.com> <50E72B95.8090009@libero.it> <50EA457A.9030500@gmx.com> <50ED80A7.7070209@pearwood.info> <50EE26C7.1080501@gmx.com> Message-ID: <50EE534A.1030408@davea.name> On 01/09/2013 09:26 PM, Ed Owens wrote: > I'm working my way through Chun's book "Core Python Applications > Programming" and can't get one of the examples to actually work. In > trying to analyze the problem (good learning approach) I had troubles > understanding the interactions between the two classes of objects. As > an old FORTRAN programmer, I picked up my pencil to flowchart the > code, then realized I didn't know how to flowchart an OOP. > > Google led me to UML (Unified Modeling Language) and OMG (apparently > Oh My God!!!). Looks more complicated than the code I'm trying to > understand. > > It there a technique that people use to figure out how do design OOP > models, objects, and the information flow? > > Thanks for helping a newby. > Ed > ________ You're probably making it more complicated than it needs to be. A class is simply an organized way to associate a collection of data, with functions (methods) that operate on that data. You instantiate the class one or more times to create one or more objects. And when you invoke the method on a particular object, it has access to all the data in that particular object. Many times the class represents a bunch of data that is analogous to real life information. So a class might name a natural collection, like a person, and the data members of that class are attributes that exist for all persons, but have different values. So you might have an attribute for hair color, value brown, and an attribute for height, value 68 inches. A separate instance describing a different person would have the same attributes, but different values for them. A method on such a class is something that affects one or more attributes, or that returns information derived from one or more attributes. For example, the die() method might change the hair color attribute. Many times the class is more abstract than that, but the attributes still should be related to each other in some useful way. So a file class represents a file on disk, and contains attributes like filename, seek-position, mode, and buffer, and has methods like read, write, seek. HTH. -- DaveA From kliateni at gmail.com Thu Jan 10 07:01:24 2013 From: kliateni at gmail.com (Karim) Date: Thu, 10 Jan 2013 07:01:24 +0100 Subject: [Tutor] How to run multiline shell command within python In-Reply-To: References: Message-ID: <50EE5934.7090609@gmail.com> Hello all, I want to run multiline shell command within python without using a command file but directly execute several lines of shell. I already use *subprocess.checkoutput("csh -f my_file.csh".split())* but I want to know if it is posssible to avoid making file and execute shell lines of code directly. Example: cat< myfile echo "foo" echo "bar" ... EOF Regards Karim From eryksun at gmail.com Thu Jan 10 07:43:55 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 10 Jan 2013 01:43:55 -0500 Subject: [Tutor] run perl script files and capture results In-Reply-To: <1357780485.90601.YahooMailNeo@web140003.mail.bf1.yahoo.com> References: <1357780485.90601.YahooMailNeo@web140003.mail.bf1.yahoo.com> Message-ID: On Wed, Jan 9, 2013 at 8:14 PM, T. Girowall wrote: > > > c:\scripts\perl>perl plscript.pl -cmnd1 -cmnd2 > > cmnd1 and cmnd2 are ran on files that reside within "perl" directory. > > My objective: > 1. Run the perl script using python > 2. Capture the results from the DOS window and save it to python. Output > consists of text names and corresponding numbers. > > I'm using python 2.7 subprocess.check_output returns piped stdout (optionally including stderr) from a process http://docs.python.org/2/library/subprocess#subprocess.check_output universal_newlines=True replaces the Windows CRLF ('\r\n') line endings with LF ('\n'). To set the working directory use cwd='c:/scripts/perl' (see [1]). On Windows you can pass args as a string if you need non-standard quoting. If you use a list instead, subprocess builds a string quoted according to Microsoft's rules: http://docs.python.org/2/library/subprocess#converting-argument-sequence If the call fails check_output raises subprocess.CalledProcessError: http://docs.python.org/2/library/subprocess#subprocess.CalledProcessError For example: import subprocess output = subprocess.check_output( ['perl.exe', 'plscript.pl', '-cmnd1', '-cmnd2'], universal_newlines=True, cwd='c:/scripts/perl', ) Windows CreateProcess will search for 'perl.exe' on the system PATH. For increased security you can use an absolute path such as 'C:/perl/bin/perl.exe'. 1. Using a forward slash in paths is OK for DOS/Windows system calls (e.g. opening a file or setting the cwd of a new process), dating back to the file system calls in MS-DOS 2.0 (1983). Otherwise a backslash is usually required (e.g. shell commands and paths in commandline arguments, where forward slash is typically used for options). In this case use a raw string or os.path.join. For a raw string, note that a trailing backslash is not allowed, e.g. r'C:\Python27\'. Instead you could use r'C:\Python27' '\\', among other options: http://docs.python.org/2/faq/design.html#why-can-t-raw-strings-r-strings-end-with-a-backslash From hugo.yoshi at gmail.com Thu Jan 10 09:31:43 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 10 Jan 2013 09:31:43 +0100 Subject: [Tutor] How to run multiline shell command within python In-Reply-To: <50EE5934.7090609@gmail.com> References: <50EE5934.7090609@gmail.com> Message-ID: On Thu, Jan 10, 2013 at 7:01 AM, Karim wrote: > > > Hello all, > > I want to run multiline shell command within python without using a > command file but directly execute several lines of shell. > I already use *subprocess.checkoutput("csh -f my_file.csh".split())* but I > want to know if it is posssible to avoid making file and execute > shell lines of code directly. > > Yes, this is very possible. Specify shell=True as an argument and you can do anything you can do in a shell: >>> commands = """echo hello ... echo hello | wc -l ... ps aux | grep python""" >>> b = subprocess.check_output(commands, shell=True) >>> print(b.decode('ascii')) hello 1 hugo 1255 1.0 0.6 777316 49924 ? Sl 09:14 0:08 /usr/bin/python2 /usr/bi hugo 6529 0.0 0.0 42408 7196 pts/0 S+ 09:23 0:00 python hugo 6559 0.0 0.0 10656 1128 pts/0 S+ 09:28 0:00 grep python >>> watch out though, accepting user input into the commands variable will lead to shell injection, which can be a dangerous security vulnerability. HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 10 10:30:19 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Jan 2013 09:30:19 +0000 Subject: [Tutor] Flow charts In-Reply-To: <50EE26C7.1080501@gmx.com> References: <50D37A37.4070805@pearwood.info> <50D37E1C.3070901@davea.name> <66098356-604F-47DB-A78B-2CC859623BBE@gmail.com> <50E72B95.8090009@libero.it> <50EA457A.9030500@gmx.com> <50ED80A7.7070209@pearwood.info> <50EE26C7.1080501@gmx.com> Message-ID: On 10/01/13 02:26, Ed Owens wrote: First, please start a new thread for a new topic, don't reply to an existing one. Threaded mail/news readers are not fooled by a simple change of subject so your post gets buried deep in an old thread. Just create a brand new mail to the list address. Anyway... > I'm working my way through Chun's book "Core Python Applications > Programming" and can't get one of the examples to actually work. In > trying to analyze the problem (good learning approach) I had troubles > understanding the interactions between the two classes of objects. As > an old FORTRAN programmer, I picked up my pencil to flowchart the code, > then realized I didn't know how to flowchart an OOP. Us a message sequence chart(MSC). A vertical line represents an object. Draw arrows between the lines to represent the messages passing between them. Messages correspond to function calls in procedural programming. MSCs are a very old design tool from the communications world but adopted by OOP and included in UML (see below) > Google led me to UML (Unified Modeling Language) and OMG (apparently Oh > My God!!!). Looks more complicated than the code I'm trying to understand. OMG (Object Management Group) is a body overseeeing many things OO based. Design tools, integration technologies, languages and specifications etc. UML is a design language that, if used to its limit, can be used to generate working code. As a result it has a lot of stuff in there to represent fine grained detail. So yes, it is as complex as code because in a sense that's what it is. Graphical code. In addition UML is designed to completely represent a large software system so it includes notations for designing networks and data centres as well as application code. The good news is that most people don't use UML like that and only use about 20% of UML or less. The main diagrams you are likely to use as a Python programmer are class diagram, MSC, activity diagram(flow charts!) and state charts. Focus on those areas and don't obsess on the details and UML becomes useful to ordinary mortals. I use UML in the v3 version of my tutor in the OOP topic, the examples there hopefully show how UML can be used even in simple designs. > It there a technique that people use to figure out how do design OOP > models, objects, and the information flow? There are lots of them, that's why UML was invented to bring the best bits together into a single Unified Modelling Language. But OOP is more about a different way of thinking about the problem. You have to start thinking about objects and their responsibilities. Objects own data and provide services. Other objects use those services to provide their services and so on. So we tend to get a bottom up style of design. Build (or select from the library) the lowest level objects then build the next layer up that consume those. Don;t be scared to split objects into two(or more) if they start to get unweildy or to combine two (or more) if they don;t seem to have a purpose or are duplicating services. CRC cards - not part of UML - are a good place to start when building OOP systems. A very easy technique that does not require any fancy tools. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From tm at tobix.eu Thu Jan 10 11:13:32 2013 From: tm at tobix.eu (Tobias Marquardt) Date: Thu, 10 Jan 2013 11:13:32 +0100 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: <50EE93D2.4030504@tobix.eu> References: <50EE93D2.4030504@tobix.eu> Message-ID: <50EE944C.7060102@tobix.eu> Hello, I have a class with some class methods that are also stored in a list. Now I have a problem calling these methods. Essentially the relevant code looks like this: class MyClass(object): @classmethod def foo(cls): cls.method_list[0]() @classmethod def bar(cls): print("Hello World") method_list = [bar] So foo() takes bar() from the list and tries calls it, which results in an error: File "aco/antsystem/test.py", line 11, in foo cls.method_list[0]() TypeError: 'classmethod' object is not callable I guess the reason is that bar() needs to be called on the class like: cls.bar(), but how to I achieve this here? Any suggestions? Tobias From __peter__ at web.de Thu Jan 10 12:00:19 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jan 2013 12:00:19 +0100 Subject: [Tutor] Problem with calling class methods stored in a list References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> Message-ID: Tobias Marquardt wrote: > Hello, > > I have a class with some class methods that are also stored in a list. > Now I have a problem calling these methods. > Essentially the relevant code looks like this: > > class MyClass(object): > > @classmethod > def foo(cls): > cls.method_list[0]() > > @classmethod > def bar(cls): > print("Hello World") > > method_list = [bar] At this point MyClass is not yet defined, so bar has no information about it. > So foo() takes bar() from the list and tries calls it, which results in > an error: > > File "aco/antsystem/test.py", line 11, in foo > cls.method_list[0]() > TypeError: 'classmethod' object is not callable > > I guess the reason is that bar() needs to be called on the class like: > cls.bar(), but how to I achieve this here? > Any suggestions? Build the list outside the class: MyClass.method_list = [MyClass.bar] From hugo.yoshi at gmail.com Thu Jan 10 12:05:55 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 10 Jan 2013 12:05:55 +0100 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: <50EE944C.7060102@tobix.eu> References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> Message-ID: On Thu, Jan 10, 2013 at 11:13 AM, Tobias Marquardt wrote: > Hello, > > I have a class with some class methods that are also stored in a list. > Now I have a problem calling these methods. > Essentially the relevant code looks like this: > > class MyClass(object): > > @classmethod > def foo(cls): > cls.method_list[0]() > > @classmethod > def bar(cls): > print("Hello World") > > method_list = [bar] > > > So foo() takes bar() from the list and tries calls it, which results in > an error: > > File "aco/antsystem/test.py", line 11, in foo > cls.method_list[0]() > TypeError: 'classmethod' object is not callable > > I guess the reason is that bar() needs to be called on the class like: > cls.bar(), but how to I achieve this here? > Any suggestions? > > Why do you need the method list at all? if you simply get rid of that and call cls.bar() you would be rid of the problem entirely. What piece of your code requires this list? Perhaps we can redesign that to be rid of it. Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From tm at tobix.eu Thu Jan 10 12:36:15 2013 From: tm at tobix.eu (Tobias M.) Date: Thu, 10 Jan 2013 12:36:15 +0100 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> Message-ID: <50EEA7AF.9020704@tobix.eu> Peter Otten wrote: > Build the list outside the class: MyClass.method_list = [MyClass.bar] Thanks, that is a solution. But I don't really like to put the list outside the class as it is strongly related to the class and not used outside. Hugo Arts wrote: > What piece of your code requires this list? Perhaps we can redesign > that to be rid of it. Actually in my code it's not a list but a dictionary. The class is part of a network server and handles incomming packets. It reads the header of the packet and determines the packet type. The dictionary has the packet type as key and the method to handle the packet of the corresponding type as value. So the dictionary is used to look up the correct method to process the packet. With this I try to avoid a lot of "if...elif..." statements and make it easy to expand the network protocol by just adding a new handle method and put it in the dictionary. From steve at pearwood.info Thu Jan 10 13:11:46 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 10 Jan 2013 23:11:46 +1100 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: <50EE944C.7060102@tobix.eu> References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> Message-ID: <50EEB002.6030904@pearwood.info> On 10/01/13 21:13, Tobias Marquardt wrote: > Hello, > > I have a class with some class methods that are also stored in a list. > Now I have a problem calling these methods. Peter Otten has already given one solution. Read on for two more. > Essentially the relevant code looks like this: > > class MyClass(object): > > @classmethod > def foo(cls): > cls.method_list[0]() > > @classmethod > def bar(cls): > print("Hello World") > > method_list = [bar] > > > So foo() takes bar() from the list and tries calls it, which results in > an error: > > File "aco/antsystem/test.py", line 11, in foo > cls.method_list[0]() > TypeError: 'classmethod' object is not callable > > I guess the reason is that bar() needs to be called on the class like: > cls.bar(), but how to I achieve this here? To answer your direct question, all you need to do is manually imitate what Python does when you call a descriptor (see below): py> MyClass.method_list[0].__get__(MyClass, None)() Hello World So, inside the foo() method, do this: @classmethod def foo(cls): cls.method_list[0].__get__(cls, None)() and it should work. "What the hell is a descriptor?" I hear you ask. Don't worry about them, they are an advanced part of Python, used to implement methods (regular, class and static) and properties. If you care, you can read this: http://docs.python.org/2/howto/descriptor.html but you may find it heavy going. (I know I did the first five times I read it.) Here's another solution: use a regular function object instead of a method. This relies on an unusual, but deliberate, quirk of the way Python implements methods: they are actually regular functions inside the class body when the class is created, and don't get turned into methods until you do a lookup like "self.spam" or "cls.ham". class MyClass(object): @classmethod def foo(cls): # Note that you manually provide the class argument. cls.method_list[0](cls) def bar(cls): print("Hello World") # At this time, bar is still a regular function object, not a # method of any sort. method_list = [bar] del bar # just to avoid any confusion By *not* turning bar into a class method, it remains an ordinary function object. You then store the function object inside the list, and when you access it via method_list[0] Python gives you the regular function, not a method. Since it is a regular function, it is callable, but you have to manually provide the cls argument. -- Steven From __peter__ at web.de Thu Jan 10 13:48:33 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jan 2013 13:48:33 +0100 Subject: [Tutor] Problem with calling class methods stored in a list References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEA7AF.9020704@tobix.eu> Message-ID: Tobias M. wrote: > Peter Otten wrote: >> Build the list outside the class: MyClass.method_list = [MyClass.bar] > Thanks, that is a solution. But I don't really like to put the list > outside the class as it is strongly related to the class and not used > outside. > Actually in my code it's not a list but a dictionary. The class is part Well, I usually prefer to keep things simple, but you can do the binding manually: >>> class A(object): ... @classmethod ... def foo(cls): ... print "Hello from A.foo()" ... lookup = {"foo": foo} ... @classmethod ... def get_handler(cls, packet_type): ... return cls.lookup[packet_type].__get__(None, cls) ... >>> A.get_handler("foo")() Hello from A.foo() If you adopt this approach you might omit the lookup dictionary and use getattr(): >>> class B(object): ... @classmethod ... def handle_foo(cls): print "Hello from B.handle_foo()" ... @classmethod ... def get_handler(cls, packet_type): ... return getattr(cls, "handle_" + packet_type) ... >>> B.get_handler("foo")() Hello from B.handle_foo() (I've added the "handle_" prefix so an attacker can't just invent package types to have arbitrary methods invoked.) From tm at tobix.eu Thu Jan 10 13:53:29 2013 From: tm at tobix.eu (Tobias M.) Date: Thu, 10 Jan 2013 13:53:29 +0100 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: <50EEB002.6030904@pearwood.info> References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEB002.6030904@pearwood.info> Message-ID: <50EEB9C9.4030105@tobix.eu> Steven D'Aprano wrote: > To answer your direct question, all you need to do is manually imitate > what > Python does when you call a descriptor (see below): > > > py> MyClass.method_list[0].__get__(MyClass, None)() > Hello World > > > So, inside the foo() method, do this: > > @classmethod > def foo(cls): > cls.method_list[0].__get__(cls, None)() > > > and it should work. > > "What the hell is a descriptor?" I hear you ask. Don't worry about them, > they are an advanced part of Python, used to implement methods (regular, > class and static) and properties. If you care, you can read this: > > http://docs.python.org/2/howto/descriptor.html > > but you may find it heavy going. (I know I did the first five times I > read it.) > > Here's another solution: use a regular function object instead of a > method. This relies on an unusual, but deliberate, quirk of the way > Python > implements methods: they are actually regular functions inside the class > body when the class is created, and don't get turned into methods > until you > do a lookup like "self.spam" or "cls.ham". > > > class MyClass(object): > @classmethod > def foo(cls): > # Note that you manually provide the class argument. > cls.method_list[0](cls) > > def bar(cls): > print("Hello World") > > # At this time, bar is still a regular function object, not a > # method of any sort. > method_list = [bar] > del bar # just to avoid any confusion > > > By *not* turning bar into a class method, it remains an ordinary > function object. You then store the function object inside the list, > and when you access it via method_list[0] Python gives you the regular > function, not a method. Since it is a regular function, it is callable, > but you have to manually provide the cls argument. > Thank you for this great answer! I like the first approach (using __get__()). I tried it out but got problem when bar operates on a class variable of MyClass: class MyClass(object): x = "Hello World" @classmethod def foo(cls): cls.method_list[0].__get__(cls, None)() @classmethod def bar(cls): print(cls.x) method_list = [bar] I get: File "test.py", line 17, in bar print(cls.x) AttributeError: type object 'type' has no attribute 'x' When using Peter Otten's solution bar is able to access cls.x. From eryksun at gmail.com Thu Jan 10 13:57:35 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 10 Jan 2013 07:57:35 -0500 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: <50EEB002.6030904@pearwood.info> References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEB002.6030904@pearwood.info> Message-ID: On Thu, Jan 10, 2013 at 7:11 AM, Steven D'Aprano wrote: > > So, inside the foo() method, do this: > > @classmethod > def foo(cls): > cls.method_list[0].__get__(cls, None)() That should be cls.method_list[0].__get__(None, cls)() The way you have it binds the method to type(MyClass), which in this case is "type" itself. See cm_descr_get in funcobject.c, CPython 2.7 (line 645): http://hg.python.org/cpython/file/70274d53c1dd/Objects/funcobject.c#l635 Also see the slot wrapper wrap_descr_get for the mapping from None to NULL (line 4671): http://hg.python.org/cpython/file/70274d53c1dd/Objects/typeobject.c#l4660 From tm at tobix.eu Thu Jan 10 14:03:58 2013 From: tm at tobix.eu (Tobias M.) Date: Thu, 10 Jan 2013 14:03:58 +0100 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEB002.6030904@pearwood.info> Message-ID: <50EEBC3E.5000308@tobix.eu> Am 10.01.2013 13:57, schrieb eryksun: > That should be > > cls.method_list[0].__get__(None, cls)() > > The way you have it binds the method to type(MyClass), which in this > case is "type" itself. See cm_descr_get in funcobject.c, CPython 2.7 > (line 645): > > http://hg.python.org/cpython/file/70274d53c1dd/Objects/funcobject.c#l635 > > Also see the slot wrapper wrap_descr_get for the mapping from None to > NULL (line 4671): > > http://hg.python.org/cpython/file/70274d53c1dd/Objects/typeobject.c#l4660 This works. Thanks! From eryksun at gmail.com Thu Jan 10 14:10:40 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 10 Jan 2013 08:10:40 -0500 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEA7AF.9020704@tobix.eu> Message-ID: On Thu, Jan 10, 2013 at 7:48 AM, Peter Otten <__peter__ at web.de> wrote: > > If you adopt this approach you might omit the lookup dictionary and use > getattr(): > >>>> class B(object): > ... @classmethod > ... def handle_foo(cls): print "Hello from B.handle_foo()" > ... @classmethod > ... def get_handler(cls, packet_type): > ... return getattr(cls, "handle_" + packet_type) > ... >>>> B.get_handler("foo")() > Hello from B.handle_foo() > > (I've added the "handle_" prefix so an attacker can't just invent package > types to have arbitrary methods invoked.) This approach also makes it simpler to override handlers in a subclass. You don't have to worry about separately updating a copy of a list or dict. From tm at tobix.eu Thu Jan 10 14:12:06 2013 From: tm at tobix.eu (Tobias M.) Date: Thu, 10 Jan 2013 14:12:06 +0100 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEA7AF.9020704@tobix.eu> Message-ID: <50EEBE26.7090005@tobix.eu> Am 10.01.2013 13:48, schrieb Peter Otten: > If you adopt this approach you might omit the lookup dictionary and use > getattr(): > > ... @classmethod > ... def handle_foo(cls): print "Hello from B.handle_foo()" > ... @classmethod > ... def get_handler(cls, packet_type): > ... return getattr(cls, "handle_" + packet_type) > ... Well I think this is an elegant solution. But due to my protocol a packet type is uniquely defined by a combination of two header fields (that contain integers). Building a verbose method name from these would complicate it again. From d at davea.name Thu Jan 10 14:24:10 2013 From: d at davea.name (Dave Angel) Date: Thu, 10 Jan 2013 08:24:10 -0500 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: <50EEA7AF.9020704@tobix.eu> References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEA7AF.9020704@tobix.eu> Message-ID: <50EEC0FA.30209@davea.name> On 01/10/2013 06:36 AM, Tobias M. wrote: > Peter Otten wrote: >> Build the list outside the class: MyClass.method_list = [MyClass.bar] > Thanks, that is a solution. But I don't really like to put the list > outside the class as it is strongly related to the class and not used > outside. But as it's the simplest solution, and one with no runtime overhead, you really should consider it. Having a line or two following the class definition is not uncommon in Python, and comments can make sure the reader of the code understands it's part of the class initialization. If that really offends you, put the code in a _setup() method of the same class, and run MyClass._setup() immediately after defining the class. _setup() can be a classmethod as well, and you could have it protect itself against running more than once, perhaps by refusing to run if the list/dict already contains entries. -- DaveA From tm at tobix.eu Thu Jan 10 14:26:42 2013 From: tm at tobix.eu (Tobias M.) Date: Thu, 10 Jan 2013 14:26:42 +0100 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: <50EEBE26.7090005@tobix.eu> References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEA7AF.9020704@tobix.eu> <50EEBE26.7090005@tobix.eu> Message-ID: <50EEC192.1050403@tobix.eu> Tobias M. wrote: > Well I think this is an elegant solution. > > But due to my protocol a packet type is uniquely defined by a > combination of two header fields (that contain integers). Building a > verbose method name from these would complicate it again. EDIT: I actually meant "meaningful method name". From tm at tobix.eu Thu Jan 10 14:49:11 2013 From: tm at tobix.eu (Tobias M.) Date: Thu, 10 Jan 2013 14:49:11 +0100 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: <50EEC0FA.30209@davea.name> References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEA7AF.9020704@tobix.eu> <50EEC0FA.30209@davea.name> Message-ID: <50EEC6D7.5000108@tobix.eu> Dave Angel wrote: > But as it's the simplest solution, and one with no runtime overhead, you > really should consider it. Having a line or two following the class > definition is not uncommon in Python, and comments can make sure the > reader of the code understands it's part of the class initialization. > > If that really offends you, put the code in a _setup() method of the > same class, and run MyClass._setup() immediately after defining the > class. _setup() can be a classmethod as well, and you could have it > protect itself against running more than once, perhaps by refusing to > run if the list/dict already contains entries. > Interesting objection! However I'll probably implement the solution using __get__(None, cls) to get the method from the dictionary. It doesn't really add complexity and the additional overhead is insignificant in my use case. There will be only one client connected at a time and not much communication. The time the server will need to process the packet data will be disproportionally larger than the time to read the header and choose the handler method. From richkappler at gmail.com Thu Jan 10 15:06:21 2013 From: richkappler at gmail.com (richard kappler) Date: Thu, 10 Jan 2013 09:06:21 -0500 Subject: [Tutor] garbage collection/class question Message-ID: Class is still something I struggle with. I think I'm finally starting to get my head wrapped around it, but the discussion in a different thread has sparked a question. First, please check my understanding: A class creates objects, it's like a template that allows me to create as many copies as I want of the object but allows me to have slightly different versions of the object by having different values for the variables within the object, which I can set with arguments? By using __init__ (self) I instantiate a new copy of the object? Whether the above is correct or not (and do please correct me/ tutor me), my question is, if I create objects in a while True loop, do the objects get garbage collected, ie. disappear when the loop returns to the beginning and creates new versions of the objects? Psuedo code example: (presuming I have a class that creates a lemon, a lime and has a function that operates on them called juice) while True: lemon = yellow() # create a yellow object called lemon lime = green() # create a green object called lime drink = juice(lemon, lime) # operate on objects lemon and lime in a function called juice resident in the class So, using the above example, when the loop reaches the end and returns to the beginning, new lemons and limes are created, yes? What happens to the old ones? Or have I still got this completed boggled? regards, RIchard -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Jan 10 15:15:35 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Jan 2013 15:15:35 +0100 Subject: [Tutor] Problem with calling class methods stored in a list References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEA7AF.9020704@tobix.eu> <50EEBE26.7090005@tobix.eu> Message-ID: Tobias M. wrote: > Am 10.01.2013 13:48, schrieb Peter Otten: >> If you adopt this approach you might omit the lookup dictionary and use >> getattr(): >> >> ... @classmethod >> ... def handle_foo(cls): print "Hello from B.handle_foo()" >> ... @classmethod >> ... def get_handler(cls, packet_type): >> ... return getattr(cls, "handle_" + packet_type) >> ... > Well I think this is an elegant solution. > > But due to my protocol a packet type is uniquely defined by a > combination of two header fields (that contain integers). Building a > verbose method name from these would complicate it again. Technically, not much: >>> class C(object): ... @classmethod ... def handle_1_42(self): print "Hi" ... @classmethod ... def get_handler(cls, packet_type): ... return getattr(cls, "handle_%d_%d" % packet_type) ... >>> C.get_handler((1, 42))() Hi Of course handle_1_42() is not exactly the method name one would hope for. You could, again, strive for simplicity and add a lookup table that maps protocol tuples to function /names/ , but as simplicity doesn't seem to be your cup of tea: class HandlersType(type): def __init__(cls, name, bases, classdict): cls.lookup_protocol = lookup = {} for k, v in classdict.items(): if isinstance(v, protocol_method): lookup[v.protocol] = getattr(cls, k) class protocol_method(classmethod): pass def protocol(x, y): def attach_protocol(f): f = protocol_method(f) f.protocol = x, y return f return attach_protocol class D: __metaclass__ = HandlersType @protocol(42, 17) def foo(cls): print "Hi" D.lookup_protocol[42, 17]() ;) From kliateni at gmail.com Thu Jan 10 15:25:57 2013 From: kliateni at gmail.com (Karim) Date: Thu, 10 Jan 2013 15:25:57 +0100 Subject: [Tutor] How to run multiline shell command within python In-Reply-To: References: <50EE5934.7090609@gmail.com> Message-ID: <50EECF75.5020400@gmail.com> On 10/01/2013 09:31, Hugo Arts wrote: > On Thu, Jan 10, 2013 at 7:01 AM, Karim > wrote: > > > > Hello all, > > I want to run multiline shell command within python without using > a command file but directly execute several lines of shell. > I already use *subprocess.checkoutput("csh -f > my_file.csh".split())* but I want to know if it is posssible to > avoid making file and execute > shell lines of code directly. > > > Yes, this is very possible. Specify shell=True as an argument and you > can do anything you can do in a shell: > > >>> commands = """echo hello > ... echo hello | wc -l > ... ps aux | grep python""" > >>> b = subprocess.check_output(commands, shell=True) > >>> print(b.decode('ascii')) > hello > 1 > hugo 1255 1.0 0.6 777316 49924 ? Sl 09:14 0:08 > /usr/bin/python2 /usr/bi > hugo 6529 0.0 0.0 42408 7196 pts/0 S+ 09:23 0:00 python > hugo 6559 0.0 0.0 10656 1128 pts/0 S+ 09:28 0:00 grep python > > >>> > > watch out though, accepting user input into the commands variable will > lead to shell injection, which can be a dangerous security vulnerability. > > HTH, > Hugo Many thanks Hugo. It makes my day! In my case there are no possibilities for shell injection. It is internal to a class. Regards Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Thu Jan 10 16:01:59 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 10 Jan 2013 16:01:59 +0100 Subject: [Tutor] garbage collection/class question In-Reply-To: References: Message-ID: On Thu, Jan 10, 2013 at 3:06 PM, richard kappler wrote: > Class is still something I struggle with. I think I'm finally starting to > get my head wrapped around it, but the discussion in a different thread has > sparked a question. First, please check my understanding: > A class creates objects, it's like a template that allows me to create as > many copies as I want of the object but allows me to have slightly > different versions of the object by having different values for the > variables within the object, which I can set with arguments? > By using __init__ (self) I instantiate a new copy of the object? > > This is essentially correct. There are some intricacies in python with __init__, which doesn't create a new object but merely initiates it. Python also has __new__, which actually creates a new instance. But this is mostly just details, in 99% of cases we can simply write an __init__ method for initialization and not worry about __new__ > Whether the above is correct or not (and do please correct me/ tutor me), > my question is, if I create objects in a while True loop, do the objects > get garbage collected, ie. disappear when the loop returns to the beginning > and creates new versions of the objects? > > Psuedo code example: > > (presuming I have a class that creates a lemon, a lime and has a function > that operates on them called juice) > > while True: > lemon = yellow() # create a yellow object called lemon > lime = green() # create a green object called lime > drink = juice(lemon, lime) # operate on objects lemon and lime in a > function called juice resident in the class > > So, using the above example, when the loop reaches the end and returns to > the beginning, new lemons and limes are created, yes? What happens to the > old ones? Or have I still got this completed boggled? > > In a general sense, objects are garbage collected when there are no more references to these objects, i.e. when you become unable to use them. On each pass of the loop, you make the names lemon, lime and drink point to new instances. The instances they were pointing to previously thus become inaccessible. If there are no other references to these objects in the program, they will be garbage collected (whether this happens immediately or after a while differs depending on python implementation). Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Jan 10 16:31:44 2013 From: d at davea.name (Dave Angel) Date: Thu, 10 Jan 2013 10:31:44 -0500 Subject: [Tutor] garbage collection/class question In-Reply-To: References: Message-ID: <50EEDEE0.6010606@davea.name> On 01/10/2013 09:06 AM, richard kappler wrote: Since you don't specify Python version or implementation, I'll use CPython version 2.7 for the details below. Jython (for java environments) and other implementations are likely to differ in their garbage collection details. But the effect will be the same. I'm also assuming new-style classes, which are all that's available in Python 3, but in 2.7, you get one by making sure your class is derived from object. > Class is still something I struggle with. I think I'm finally starting to > get my head wrapped around it, but the discussion in a different thread has > sparked a question. First, please check my understanding: > A class creates objects, it's like a template that allows me to create as > many copies as I want of the object but allows me to have slightly > different versions of the object by having different values for the > variables within the object, which I can set with arguments? Python is already full of class objects. The only special thing about 'class' is it lets you define your own types of objects. There are dozens of built-in and library types, and you're probably already familiar with many of them. For example, every integer is an instance of the int class. Python has a special syntax that lets you create them invisibly, but they are there, nonetheless. I don't think it's useful to think of them as copies of a master int, but rather as independent int objects, each with some content that may or may not be unique. > By using __init__ (self) I instantiate a new copy of the object? The new INSTANCE is made when somebody invokes MyClass(arg1). During that creation, two methods of MyClass are called. The __new__() method actually creates the empty class object, and associates methods and such to it. And then the __init__() method gets control and can add other attributes to it. Most programs let the default __new__() method do its thing. > Whether the above is correct or not (and do please correct me/ tutor me), > my question is, if I create objects in a while True loop, do the objects > get garbage collected, ie. disappear when the loop returns to the beginning > and creates new versions of the objects? > > Psuedo code example: > > (presuming I have a class that creates a lemon, a lime and has a function > that operates on them called juice) But your code below does not fit the sentence above. > while True: > lemon = yellow() # create a yellow object called lemon Actually, the object has no name. The name lemon is bound to the object in that line, but it's really a one-way binding. However, CPython keeps a count of such bindings for each object, called a reference count. > lime = green() # create a green object called lime > drink = juice(lemon, lime) # operate on objects lemon and lime in a > function called juice resident in the class Since you don't give any context, I don't know where() juice is defined, or where this loop is defined, nor what you mean by 'the class'. But if you mean what you say, then you're missing an object parameter to the juice method. > So, using the above example, when the loop reaches the end and returns to > the beginning, new lemons and limes are created, yes? Not exactly. New instances of class yellow and class green are created, and the names lemon and lime are unbound from the old objects, and bound to those new objects. If this loop is all the code, then the old objects now have zero reference counts and will be immediately freed. Technically this is different than garbage collection, but the effect is the same. > What happens to the > old ones? Or have I still got this completed boggled? > > regards, RIchard > > Objects that have no bindings are inaccessible, and eventually go away (get freed). -- DaveA From tm at tobix.eu Thu Jan 10 17:25:08 2013 From: tm at tobix.eu (Tobias M.) Date: Thu, 10 Jan 2013 17:25:08 +0100 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEA7AF.9020704@tobix.eu> <50EEBE26.7090005@tobix.eu> Message-ID: <50EEEB64.50409@tobix.eu> Am 10.01.2013 15:15, schrieb Peter Otten: > Of course handle_1_42() is not exactly the method name one would hope for. > You could, again, strive for simplicity and add a lookup table that maps > protocol tuples to function /names/ , but as simplicity doesn't seem to be > your cup of tea: > > class HandlersType(type): > def __init__(cls, name, bases, classdict): > cls.lookup_protocol = lookup = {} > for k, v in classdict.items(): > if isinstance(v, protocol_method): > lookup[v.protocol] = getattr(cls, k) > > class protocol_method(classmethod): > pass > > def protocol(x, y): > def attach_protocol(f): > f = protocol_method(f) > f.protocol = x, y > return f > return attach_protocol > > class D: > __metaclass__ = HandlersType > > @protocol(42, 17) > def foo(cls): > print "Hi" > > D.lookup_protocol[42, 17]() > > ;) > In my eyes this is anything but simple. Correct me if I'm wrong: I already use a lookup table in my code, called "method_list" in my first post. The advantage of your above code is that I don't need to manually take care of the lookup table and extension by subclassing is easier. From FowlerTM at hendrix.edu Thu Jan 10 17:34:39 2013 From: FowlerTM at hendrix.edu (Fowler, Trent) Date: Thu, 10 Jan 2013 10:34:39 -0600 Subject: [Tutor] running multiple versions of python Message-ID: The archives aren't searchable or I would have started there. If there is a thread dealing with this, please send me there. I am running Windows 7 and I've installed two versions of python, 3.3 and 2.7. Python 3.3 was the first version I installed and I was able to run scripts from the desktop (not the command line). I installed python 2.7 so that I could get numpy, scipy, and matplotlib down the road, but I found that all the scripts on my desktop defaulted to python 2.7. Since I coded in 3.3 this caused some issues. I was able to fix this by right clicking the script icon, browsing programs, navigating to the python 3.3 file in my C: drive, and selecting the idle inside that directory. But then I found I wasn't able to run those scripts with python 2.7 using the exact same procedure. Unfortunately I don't know command-line programming very much at all, and it seemed like most of what I've seen online is geared towards that as a solution. Ideally I'd like to specify which python I want to run a script from the desktop, or possibly while I'm editing the script. If it's relevant I'm running the eric python IDE, version 5. I'd be happy to do the work of reading something fairly technical and long (like a blog post or PDF), but it won't help me much if it isn't aimed at beginners. Thanks in advance, -Trent From eryksun at gmail.com Thu Jan 10 18:44:27 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 10 Jan 2013 12:44:27 -0500 Subject: [Tutor] running multiple versions of python In-Reply-To: References: Message-ID: On Thu, Jan 10, 2013 at 11:34 AM, Fowler, Trent wrote: > > Python 3.3 was the first version I installed and I was able to run scripts > from the desktop (not the command line). I installed python 2.7 so that > I could get numpy, scipy, and matplotlib down the road, but I found that > all the scripts on my desktop defaulted to python 2.7. numpy, scipy, and matplotlib are available for Python 3. 3.3 includes launchers (py.exe and pyw.exe) that process UNIX-style shebangs in order to run a script with a given version of Python, provided it's available. These launchers should be installed in the Windows directory (e.g. C:\Windows). Try reinstalling 3.3. Then open a console and verify the following settings: C:\>assoc .py .py=Python.File C:\>ftype Python.File Python.File=C:\Windows\py.ex "%1" %* C:\>assoc .pyw .pyw=Python.NoConFile C:\>ftype Python.NoConFile Python.NoConFile="C:\Windows\pyw.exe" "%1" %* > Ideally I'd like to specify which python I want to run a script from the desktop, > or possibly while I'm editing the script. Refer to PEP 397 and the docs for the launcher: https://bitbucket.org/vinay.sajip/pylauncher/src/tip/Doc/launcher.rst For example, it accepts common UNIX shebangs such as #! /usr/bin/env python2 I think the launcher defaults to the latest 2.x if it's installed. If you want a different default such as 3.3, edit py.ini in your profile's AppData\Local folder. The following should open the file (or create it) with notepad: notepad %LOCALAPPDATA%\py.ini Refer to the "Customization via INI files" section of the docs. From msirenef at lightbird.net Thu Jan 10 18:50:01 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Thu, 10 Jan 2013 12:50:01 -0500 Subject: [Tutor] garbage collection/class question In-Reply-To: References: Message-ID: <50EEFF49.5060700@lightbird.net> On 01/10/2013 09:06 AM, richard kappler wrote: > Class is still something I struggle with. I think I'm finally starting > to get my head wrapped around it, but the discussion in a different > thread has sparked a question. First, please check my understanding: > A class creates objects, it's like a template that allows me to create > as many copies as I want of the object but allows me to have slightly > different versions of the object by having different values for the > variables within the object, which I can set with arguments? There are good answers already, I just want to address this question; you are correct but classes allow you to do other things, too. You may want to use a class even if you don't need multiple instances. Classes allow you to group related functionality and data together: class Tree(object): height = 0 def grow(self): self.height += 1 You may have a dozen of related functions and you can logically group them together by making them methods of a class, making it easier to think about and work on the logic of your program. Classes also create a namespace for each instance: x = 1 class A(object): x = 2 a = A() a.x = 3 Here, a.x is completely independent of the global namespace's 'x'. In instance methods, it can be called with 'self.x' . There are other things classes provide, but these are the most important in small / medium size programs. You can read up on OOP here: http://en.wikipedia.org/wiki/Object-oriented_programming HTH, - m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From alan.gauld at btinternet.com Thu Jan 10 19:32:02 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Jan 2013 18:32:02 +0000 Subject: [Tutor] running multiple versions of python In-Reply-To: References: Message-ID: On 10/01/13 16:34, Fowler, Trent wrote: > The archives aren't searchable The archives on ActiveState and gmane are. :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jan 10 19:39:41 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Jan 2013 18:39:41 +0000 Subject: [Tutor] running multiple versions of python In-Reply-To: References: Message-ID: On 10/01/13 16:34, Fowler, Trent wrote: > Ideally I'd like to specify which python I want to run a script from the desktop Eryksun has mentioned the launchers but you can do this with standard Windows functionality. You just need to edit the file associations to create new extensions .py2 and .py3, associate them with the right python executable and name the files appropriately. Alternatively create new context menu entries for .py files to "Run in Python2" and "Run in Python 3" (and edit ones too if you want - "Edit in IDLE2", "Edit in IDLE3") From memory you access the options to do that from the Windows Explorer menus. Try searching the windows help for details. No need to mess with command prompts... although as a programmer you should probably learn that skill anyway. Quote: "GUIs make easy things trivial and hard things impossible" - anon. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kliateni at gmail.com Thu Jan 10 20:07:16 2013 From: kliateni at gmail.com (Karim) Date: Thu, 10 Jan 2013 20:07:16 +0100 Subject: [Tutor] How to run multiline shell command within python In-Reply-To: References: <50EE5934.7090609@gmail.com> <50EECF75.5020400@gmail.com> Message-ID: <50EF1164.5020004@gmail.com> On 10/01/2013 16:21, Matty Sarro wrote: > Have you looked a the pexpect class? It works like gangbusters, > especially if you're trying to run something with an interactive shell. > > http://www.noah.org/wiki/pexpect > > > On Thu, Jan 10, 2013 at 9:25 AM, Karim > wrote: > > On 10/01/2013 09:31, Hugo Arts wrote: >> On Thu, Jan 10, 2013 at 7:01 AM, Karim > > wrote: >> >> >> >> Hello all, >> >> I want to run multiline shell command within python without >> using a command file but directly execute several lines of shell. >> I already use *subprocess.checkoutput("csh -f >> my_file.csh".split())* but I want to know if it is posssible >> to avoid making file and execute >> shell lines of code directly. >> >> >> Yes, this is very possible. Specify shell=True as an argument and >> you can do anything you can do in a shell: >> >> >>> commands = """echo hello >> ... echo hello | wc -l >> ... ps aux | grep python""" >> >>> b = subprocess.check_output(commands, shell=True) >> >>> print(b.decode('ascii')) >> hello >> 1 >> hugo 1255 1.0 0.6 777316 49924 ? Sl 09:14 0:08 >> /usr/bin/python2 /usr/bi >> hugo 6529 0.0 0.0 42408 7196 pts/0 S+ 09:23 0:00 >> python >> hugo 6559 0.0 0.0 10656 1128 pts/0 S+ 09:28 0:00 >> grep python >> >> >>> >> >> watch out though, accepting user input into the commands variable >> will lead to shell injection, which can be a dangerous security >> vulnerability. >> >> HTH, >> Hugo > > Many thanks Hugo. It makes my day! > In my case there are no possibilities for shell injection. It is > internal to a class. > > Regards > Karim > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Thanks Matty! I will have a look specially for interactive session. Regards Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Jan 10 23:55:53 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 11 Jan 2013 09:55:53 +1100 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEB002.6030904@pearwood.info> Message-ID: <50EF46F9.7020408@pearwood.info> On 10/01/13 23:57, eryksun wrote: > On Thu, Jan 10, 2013 at 7:11 AM, Steven D'Aprano wrote: >> >> So, inside the foo() method, do this: >> >> @classmethod >> def foo(cls): >> cls.method_list[0].__get__(cls, None)() > > That should be > > cls.method_list[0].__get__(None, cls)() Oops, yes, thanks for the correction. -- Steven From __peter__ at web.de Fri Jan 11 10:58:51 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Jan 2013 10:58:51 +0100 Subject: [Tutor] Problem with calling class methods stored in a list References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEA7AF.9020704@tobix.eu> <50EEBE26.7090005@tobix.eu> <50EEEB64.50409@tobix.eu> Message-ID: Tobias M. wrote: > Am 10.01.2013 15:15, schrieb Peter Otten: >> Of course handle_1_42() is not exactly the method name one would hope >> for. You could, again, strive for simplicity and add a lookup table that >> maps protocol tuples to function /names/ , but as simplicity doesn't seem >> to be your cup of tea: >> >> class HandlersType(type): >> def __init__(cls, name, bases, classdict): >> cls.lookup_protocol = lookup = {} >> for k, v in classdict.items(): >> if isinstance(v, protocol_method): >> lookup[v.protocol] = getattr(cls, k) >> >> class protocol_method(classmethod): >> pass >> >> def protocol(x, y): >> def attach_protocol(f): >> f = protocol_method(f) >> f.protocol = x, y >> return f >> return attach_protocol >> >> class D: >> __metaclass__ = HandlersType >> >> @protocol(42, 17) >> def foo(cls): >> print "Hi" >> >> D.lookup_protocol[42, 17]() >> >> ;) >> > In my eyes this is anything but simple. > Correct me if I'm wrong: > I already use a lookup table in my code, called "method_list" in my > first post. The advantage of your above code is that I don't need to > manually take care of the lookup table and extension by subclassing is > easier. You are right; the misunderstanding is that I wasn't advertising the above "fancy" solution (which is buggy, btw). I have now implemented what I had in mind with the protocol to function name mapping, and I think /that/ is reasonably complex. I'm using instance methods in the demo, but it should work with class methods as well. class Error(Exception): def __init__(self, protocol): Exception.__init__(self, self.template.format(protocol)) class UnknownProtocolError(Error): template = "Unknown protocol {}" class ProtocolNotSupportedError(Error): template = "Protocol {} not supported" FOO = (42, 17) BAR = (1, 2) BAZ = (3, 4) HAM = (4, 5) SPAM = (5, 6) class HandlersBase(object): protocol_to_methodname = { FOO: "foo", BAR: "bar", BAZ: "baz", HAM: "ham", } def get_handler(self, protocol): try: methodname = self.protocol_to_methodname[protocol] except KeyError: raise UnknownProtocolError(protocol) method = getattr(self, methodname, None) if method is None: raise ProtocolNotSupportedError(protocol) return method class A(HandlersBase): def foo(self): print "A.foo" def bar(self): print "A.bar" def baz(self): print "A.baz" class B(A): def bar(self): print "B.bar" baz = None # hide parent implementation if __name__ == "__main__": for Class in A, B: inst = Class() print "---", Class.__name__, "---" for protocol in FOO, BAR, BAZ, SPAM: try: inst.get_handler(protocol)() except Error as err: print err From fomcl at yahoo.com Fri Jan 11 11:22:29 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 11 Jan 2013 02:22:29 -0800 (PST) Subject: [Tutor] OT: brainf**k program Message-ID: <1357899749.46238.YahooMailNeo@web163801.mail.gq1.yahoo.com> Not quite PEP8 compliant, but quite nifty: http://www.cs.princeton.edu/~ynaamad/misc/bf.htm The program below interprets the?follwing string as "Hello World": ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. ? (lambda t:(lambda a:(lambda b:(lambda l,e,s:((lambda(Y,o,N,A,t),a,n:e('v',(Y,o,N,A,t))or[e('v',(lambda(Y,o,N,A,t):({'>':(lambda(Y,o,N,A,t),a,n:(Y,o,N+1,A+1,t)),'<':(lambda(Y,o,N,A,t),a,n:(Y,o,N-1,A+1,t)),'+':(lambda(Y,o,N,A,t),a,n:((Y[:N]+[Y[N]+1]+Y[N+1:],o,N,A+1,t)if N>=0 else(Y,o[:-N-1]+[o[-N-1]+1]+o[-N:],N,A+1,t))),'-':(lambda(Y,o,N,A,t),a,n:((Y[:N]+[Y[N]-1]+Y[N+1:],o,N,A+1,t)if N>=0 else(Y,o[:-N-1]+[o[-N-1]-1]+o[-N:],N,A+1,t))),'.':(lambda(Y,o,N,A,t),a,n:__import__('sys').stdout.write(chr(Y[N] if N>=0 else o[-N-1]))or(Y,o,N,A+1,t)),',':(lambda(Y,o,N,A,t),a,n:(Y[:N]+[ord(t[0])if len(t)else -1]+Y[N+1:]if A>=0 else Y,o[:-N-1]+[ord(t[0])if len(t)else -1]+o[-N:]if A<0 else o,N,A+1,t[1:])),'[':(lambda(Y,o,N,A,t),a,n:(Y,o,N,n[A]+1 if(Y[N]==0 if N>=0 else o[-N-1]==0)else A+1,t)),']':(lambda(Y,o,N,A,t),a,n:(Y,o,N,n[A]+1 if(Y[N]>=1 if N>=0 else o[-N-1]>=1)else A+1,t))}[a[A]]((Y+[0]*(9+len(Y)) if A>=len(Y)-5 else Y,o+[0]*(9+len(o)) if -A>=len(o)-5 else o,N,A,t),a,n)if A]".count,open(__import__('sys').argv[1]).read())))(raw_input()) Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? -------------- next part -------------- An HTML attachment was scrubbed... URL: From quentius at gmail.com Fri Jan 11 15:10:46 2013 From: quentius at gmail.com (Chris Rogers) Date: Fri, 11 Jan 2013 08:10:46 -0600 Subject: [Tutor] Books for Learning Python Message-ID: Hello all, I've began my journey into Python (2.7 currently) and I'm finding it a bit rough using the python.org tutorials. Although chalked full of information I find it a bit overwhelming. Can anyone recommend a book, or two, or three that would be great material for really learning the language. I tend to learn better with a little structure and I feel a good book would be the best approach for myself. Any advice would be greatly appreciated. --Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From femibanjo at hotmail.com Fri Jan 11 18:52:04 2013 From: femibanjo at hotmail.com (Femi Banjo) Date: Fri, 11 Jan 2013 17:52:04 +0000 Subject: [Tutor] Books for Learning Python In-Reply-To: References: Message-ID: Not Books but have you tried any of the online learning courses? They're free and look very good from my equally beginner perspective as I struggle through them(allow more time than you think :[ ) www.coursera.org www.edx.org www.udacity.com all very good, take you pick! From: quentius at gmail.com Date: Fri, 11 Jan 2013 08:10:46 -0600 To: tutor at python.org Subject: [Tutor] Books for Learning Python Hello all, I've began my journey into Python (2.7 currently) and I'm finding it a bit rough using the python.org tutorials. Although chalked full of information I find it a bit overwhelming. Can anyone recommend a book, or two, or three that would be great material for really learning the language. I tend to learn better with a little structure and I feel a good book would be the best approach for myself. Any advice would be greatly appreciated. --Thanks! _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From xperimental22 at gmail.com Fri Jan 11 19:14:13 2013 From: xperimental22 at gmail.com (jh) Date: Fri, 11 Jan 2013 13:14:13 -0500 Subject: [Tutor] Books for Learning Python In-Reply-To: References: Message-ID: <012301cdf027$76c67200$64535600$@gmail.com> There is also this - http://www.codecademy.com/#!/exercises/0 From: Tutor [mailto:tutor-bounces+xperimental22=gmail.com at python.org] On Behalf Of Chris Rogers Sent: Friday, January 11, 2013 9:11 AM To: tutor at python.org Subject: [Tutor] Books for Learning Python Hello all, I've began my journey into Python (2.7 currently) and I'm finding it a bit rough using the python.org tutorials. Although chalked full of information I find it a bit overwhelming. Can anyone recommend a book, or two, or three that would be great material for really learning the language. I tend to learn better with a little structure and I feel a good book would be the best approach for myself. Any advice would be greatly appreciated. --Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jan 11 19:39:10 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Jan 2013 18:39:10 +0000 Subject: [Tutor] Books for Learning Python In-Reply-To: References: Message-ID: On 11/01/13 14:10, Chris Rogers wrote: > Hello all, I've began my journey into Python (2.7 currently) and I'm > finding it a bit rough using the python.org > tutorials. You don't tell us your starting point. Are you experienced in programming in other languages or is python your first foray into Programming? Are you a professional or hobbyist? Do you have a scientific or math background? All of these influence what makes a book suitable. Some of the tutorials listed on Python.org are also paper books (including mine). Which tutorials have you looked at? The official tutor is good for people who can already program. The non-programmes ones are better if you can't already program (as you'd expect!). There are also several python videos available on sites like showmedo.com If you can answer the above questions we might be able to recommend some books. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bashyam69 at gmail.com Fri Jan 11 19:58:11 2013 From: bashyam69 at gmail.com (MDB) Date: Fri, 11 Jan 2013 13:58:11 -0500 Subject: [Tutor] help for a beginner Message-ID: Hi, I am a beginner to progrmming and want to learn basic python. I am a scientist (with less math background) with absolutely no programming experience. Are there any web based tutorials/videos/books to learn python. Any help is deeply appreciated, thanks Murail -- Murali Dharan Bashyam, PhD, MNAScI Staff Scientist and Chief, Laboratory of Molecular Oncology, Centre for DNA Fingerprinting and Diagnostics (CDFD), Tuljaguda complex, Nampally, Hyderabad 500001, INDIA Ph: 91-40-24749383 Fax: 91-40-24749448 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dextrous85 at gmail.com Fri Jan 11 20:13:29 2013 From: dextrous85 at gmail.com (vishwajeet singh) Date: Sat, 12 Jan 2013 00:43:29 +0530 Subject: [Tutor] help for a beginner In-Reply-To: References: Message-ID: On Sat, Jan 12, 2013 at 12:28 AM, MDB wrote: > Hi, > I am a beginner to progrmming and want to learn basic python. I am a > scientist (with less math background) with absolutely no programming > experience. Are there any web based tutorials/videos/books to learn python. > The best book for beginners in my experience is Python for Absolute Beginners, I liked it's approach in making learning a bit fun. A good online resource is http://www.alan-g.me.uk/ > Any help is deeply appreciated, > thanks > Murail > -- > Murali Dharan Bashyam, PhD, MNAScI > Staff Scientist and Chief, > Laboratory of Molecular Oncology, > Centre for DNA Fingerprinting and Diagnostics (CDFD), > Tuljaguda complex, Nampally, > Hyderabad 500001, INDIA > Ph: 91-40-24749383 > Fax: 91-40-24749448 > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Vishwajeet Singh +91-9657702154 | dextrous85 at gmail.com | http://bootstraptoday.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet -------------- next part -------------- An HTML attachment was scrubbed... URL: From gwd711 at gmail.com Fri Jan 11 20:29:40 2013 From: gwd711 at gmail.com (Graham Dubow) Date: Fri, 11 Jan 2013 14:29:40 -0500 Subject: [Tutor] help for a beginner In-Reply-To: References: Message-ID: Murail, Check out Udacity.com and the CS101 course. Great video lectures reinforced by "homework" and problems (with answers) that you can do yourself. Also has a very good forum and active user base to ask questions. It is a good starting point for a beginner and teaches the basics behind how to build a simple web crawler using Python. Cheers, Graham On Fri, Jan 11, 2013 at 1:58 PM, MDB wrote: > Hi, > I am a beginner to progrmming and want to learn basic python. I am a > scientist (with less math background) with absolutely no programming > experience. Are there any web based tutorials/videos/books to learn python. > > Any help is deeply appreciated, > thanks > Murail > -- > Murali Dharan Bashyam, PhD, MNAScI > Staff Scientist and Chief, > Laboratory of Molecular Oncology, > Centre for DNA Fingerprinting and Diagnostics (CDFD), > Tuljaguda complex, Nampally, > Hyderabad 500001, INDIA > Ph: 91-40-24749383 > Fax: 91-40-24749448 > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From janpeterr at freenet.de Fri Jan 11 20:41:11 2013 From: janpeterr at freenet.de (Jan Riechers) Date: Fri, 11 Jan 2013 21:41:11 +0200 Subject: [Tutor] garbage collection/class question In-Reply-To: <50EEFF49.5060700@lightbird.net> References: <50EEFF49.5060700@lightbird.net> Message-ID: <50F06AD7.90305@freenet.de> On 10.01.2013 19:50, Mitya Sirenef wrote: > On 01/10/2013 09:06 AM, richard kappler wrote: > > class Tree(object): > height = 0 > > def grow(self): > self.height += 1 > > You may have a dozen of related functions and you can logically group > them together by making them methods of a class, making it easier to > think about and work on the logic of your program. > > > Actually one question about those "dozens of related" instances generated by: greenwoodTree = Tree() oakTree = Tree() .... Both, greenwoodTree and oakTree, are derived from Tree class, thus receiving the features and also - if so - holding unique values created in there __init__ generator method - "self.height", "self.color" and so forth uniquely each. But do both share the same function memory space from the class "Tree"? I am currently trying also to get my head wrapped around OOP in general, but not 100% sure so that derived instances use the same functions (also memory wise speaking) - or are there several definitions of "grow" ? The confusion came somehow when reading about "classmethods" and "staticmethods" and patterns like Singleton, monostate, borg... from which I understand only ensure that the "self.height" properties are shared across multiple instances of a given class? From what I tried out using id() and generating functions in a loop - the "id(class.function) provided the same result when printed out, according to that: http://stackoverflow.com/questions/121396/accessing-object-memory-address So I assume the functions are shared across thus one decleration has been made in "Tree" class and all siblings are using that one? Thank you in advance for clarification. Jan From gray at psu.edu Fri Jan 11 21:14:28 2013 From: gray at psu.edu (Gary L. Gray) Date: Fri, 11 Jan 2013 15:14:28 -0500 Subject: [Tutor] Books for Learning Python In-Reply-To: References: Message-ID: <08073EDD-4BF3-48A7-B2D7-1258F188076E@psu.edu> On Jan 11, 2013, at 1:39 PM, Alan Gauld wrote: > On 11/01/13 14:10, Chris Rogers wrote: >> Hello all, I've began my journey into Python (2.7 currently) and I'm >> finding it a bit rough using the python.org >> tutorials. > > You don't tell us your starting point. > > Are you experienced in programming in other languages or is python your first foray into Programming? Are you a professional or hobbyist? > > Do you have a scientific or math background? > > All of these influence what makes a book suitable. > Some of the tutorials listed on Python.org are also paper books (including mine). > > Which tutorials have you looked at? The official tutor is good for people who can already program. The non-programmes ones are better if you can't already program (as you'd expect!). There are also several python videos available on sites likeshowmedo.com > > If you can answer the above questions we might be able to recommend some books. I am also looking for some good resources for learning Python. Here is my background. I did a lot of programming in Fortran 77 while working on my Ph.D. in engineering mechanics (graduated in 1993). I did some simple programming in Matlab and Mathematica in the 90s, but all the coding for my research since then has been done by my graduate students. I want to get back into programming so that I can create applications and animate the motion of objects for undergraduate and graduate dynamics courses I teach. Friends tell me Python is a good choice for an object oriented language (about which I know almost nothing) that has a readable syntax. With this in mind, I have two questions: (1) Will Python allow me to create applications that provide a simple GUI interface to something like an integrator for ODEs? Does it have graphics libraries that allow one to animate the motion of simple objects (e.g., spheres, ellipsoids, parallelepipeds, etc.) based on the results of numerical simulations? (2) If the answers to the above questions are generally "yes," where are some good places to get started learning Python to achieve my goals? Thank you. Gary L. Gray From d at davea.name Fri Jan 11 22:32:01 2013 From: d at davea.name (Dave Angel) Date: Fri, 11 Jan 2013 16:32:01 -0500 Subject: [Tutor] garbage collection/class question In-Reply-To: <50F06AD7.90305@freenet.de> References: <50EEFF49.5060700@lightbird.net> <50F06AD7.90305@freenet.de> Message-ID: <50F084D1.8010300@davea.name> On 01/11/2013 02:41 PM, Jan Riechers wrote: > On 10.01.2013 19:50, Mitya Sirenef wrote: >> On 01/10/2013 09:06 AM, richard kappler wrote: >> >> class Tree(object): >> height = 0 >> >> def grow(self): >> self.height += 1 >> >> You may have a dozen of related functions and you can logically group >> them together by making them methods of a class, making it easier to >> think about and work on the logic of your program. >> >> >> > > Actually one question about those "dozens of related" instances > generated by: > greenwoodTree = Tree() > oakTree = Tree() > .... > > Both, greenwoodTree and oakTree, are derived from Tree class, It's important that we use correct, or at least close terminology. A derived class is VERY different from an instance. greenWoodTree and oakTree are bound to different instances of Tree. > thus receiving the features and also - if so - holding unique values > created in there __init__ generator method __init__ is not a generator. it's simply a method. A method is a function that's defined inside a class > - "self.height", "self.color" and so forth uniquely each. We have to be careful here. Such data can be attributes of an instance, or they can be attributes of a class. Strangely enough, this example has a self.height and tree.height that are both called height, but technically distinct values. I think it's best if you avoid such things, and use unique names till you've got the fundamentals straight. > > But do both share the same function memory space from the class "Tree"? > I wouldn't use the term function memory space, but I'll say this much. Unless you do something tricky, there is only one method Tree.grow, and all instances share that same method. No duplicated memory at all. > I am currently trying also to get my head wrapped around OOP in > general, but not 100% sure so that derived instances use the same > functions (also memory wise speaking) - or are there several > definitions of "grow" ? Not yet. Creating instances don't duplicate any methods. You'd have to do something explicit, and advanced. > > The confusion came somehow when reading about "classmethods" and > "staticmethods" and patterns like Singleton, monostate, borg... > from which I understand only ensure that the "self.height" properties > are shared across multiple instances of a given class? > I'd consider all of those as advanced techniques, and a complete confusion at your present stage. classmethods and staticmethods affect the parameters that a method gets, not whether data properties belong to the class or to the method. > From what I tried out using id() and generating functions in a loop - > the "id(class.function) provided the same result when printed out, > according to that: > http://stackoverflow.com/questions/121396/accessing-object-memory-address > > So I assume the functions are shared across thus one decleration has > been made in "Tree" class and all siblings are using that one? > Without showing the code in this loop, I can't comment on what you observed. Don't have any idea what you mean by a sibling. The only meaning I can think of is that two classes each derived from a common base class can be considered siblings. But you don't do any deriving in this email. -- DaveA From ghasemmg01 at leedslearning.net Fri Jan 11 22:51:16 2013 From: ghasemmg01 at leedslearning.net (Ghadir Ghasemi) Date: Fri, 11 Jan 2013 21:51:16 +0000 Subject: [Tutor] Binary/Decimal convertor Message-ID: <010FB2F3C55002408EE1404538D1B6AE030D83794789@LLN-SPP-ES-04.user01.lln.local> Hi, I made a program called binary/denary convertor. Can anyone tell me about how I could stop the user entering a binary number with more than 8 numbers or 8 bit by repeating the question over and over until they do enter a correct binary number( 8-bit or less) Here is the code. I started off by entering 'len' function. def add_binary_numbers(num1, num2): return num1 + num2 num1 = int(input('please enter the first 8 bit binary number: '),2) if len(num1) > 8: print("please enter an 8 bit binary number") return int(num1,2) num2 = int(input('please enter the second 8 bit binary number: '),2) result = add_binary_numbers(num1, num2) print('the result is', bin(result)[2:]) Thanks, Ghadir From lconrad at go2france.com Fri Jan 11 22:51:40 2013 From: lconrad at go2france.com (lconrad at go2france.com) Date: Fri, 11 Jan 2013 15:51:40 -0600 Subject: [Tutor] Books for Learning Python Message-ID: <50f0896c.460.2ab93000.639469c@go2france.com> on line Python courses with labs google "python the hard way" udemy.com also has python courses https://developers.google.com/edu/python/ http://www.codecademy.com/tracks/python google "free online python programming classes courses" Len On Friday 11/01/2013 at 3:18 pm, Gary L. Gray wrote: > On Jan 11, 2013, at 1:39 PM, Alan Gauld > wrote: > >> >> On 11/01/13 14:10, Chris Rogers wrote: >>> >>> Hello all, I've began my journey into Python (2.7 currently) and I'm >>> finding it a bit rough using the python.org >>> tutorials. >> >> You don't tell us your starting point. >> >> Are you experienced in programming in other languages or is python >> your first foray into Programming? Are you a professional or hobbyist? >> >> Do you have a scientific or math background? >> >> All of these influence what makes a book suitable. >> Some of the tutorials listed on Python.org are also paper books >> (including mine). >> >> Which tutorials have you looked at? The official tutor is good for >> people who can already program. The non-programmes ones are better if >> you can't already program (as you'd expect!). There are also several >> python videos available on sites likeshowmedo.com >> >> If you can answer the above questions we might be able to recommend >> some books. > > I am also looking for some good resources for learning Python. Here is > my background. > > I did a lot of programming in Fortran 77 while working on my Ph.D. in > engineering mechanics (graduated in 1993). I did some simple > programming in Matlab and Mathematica in the 90s, but all the coding > for my research since then has been done by my graduate students. I > want to get back into programming so that I can create applications > and animate the motion of objects for undergraduate and graduate > dynamics courses I teach. Friends tell me Python is a good choice for > an object oriented language (about which I know almost nothing) that > has a readable syntax. > > With this in mind, I have two questions: > > (1) Will Python allow me to create applications that provide a simple > GUI interface to something like an integrator for ODEs? Does it have > graphics libraries that allow one to animate the motion of simple > objects (e.g., spheres, ellipsoids, parallelepipeds, etc.) based on > the results of numerical simulations? > > (2) If the answers to the above questions are generally "yes," where > are some good places to get started learning Python to achieve my > goals? > > Thank you. > > Gary L. Gray > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at graniteweb.com Fri Jan 11 23:10:07 2013 From: david at graniteweb.com (David Rock) Date: Fri, 11 Jan 2013 16:10:07 -0600 Subject: [Tutor] Binary/Decimal convertor In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D83794789@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D83794789@LLN-SPP-ES-04.user01.lln.local> Message-ID: <20130111221007.GF22522@wdfs.bad> * Ghadir Ghasemi [2013-01-11 21:51]: > Hi, I made a program called binary/denary convertor. Can anyone tell > me about how I could stop the user entering a binary number with more > than 8 numbers or 8 bit by repeating the question over and over until > they do enter a correct binary number( 8-bit or less) Here is the > code. I started off by entering 'len' function. > > def add_binary_numbers(num1, num2): > return num1 + num2 > > num1 = int(input('please enter the first 8 bit binary number: '),2) > if len(num1) > 8: > print("please enter an 8 bit binary number") > return int(num1,2) > num2 = int(input('please enter the second 8 bit binary number: '),2) > result = add_binary_numbers(num1, num2) > print('the result is', bin(result)[2:]) It looks like the first thing you need to do is figure out how to use a loop (eg, while loop, for loop). I would recommend thinking about some pseudocode to determine your program's flow and then try to build something to accomplish that. -- David Rock david at graniteweb.com From d at davea.name Fri Jan 11 23:17:17 2013 From: d at davea.name (Dave Angel) Date: Fri, 11 Jan 2013 17:17:17 -0500 Subject: [Tutor] Binary/Decimal convertor In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D83794789@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D83794789@LLN-SPP-ES-04.user01.lln.local> Message-ID: <50F08F6D.3020205@davea.name> On 01/11/2013 04:51 PM, Ghadir Ghasemi wrote: > Hi, I made a program called binary/denary convertor. Can anyone tell me about how I could stop the user entering a binary number with more than 8 numbers or 8 bit by repeating the question over and over until they do enter a correct binary number( 8-bit or less) > Here is the code. I started off by entering 'len' function. > > def add_binary_numbers(num1, num2): > return num1 + num2 > > num1 = int(input('please enter the first 8 bit binary number: '),2) > if len(num1) > 8: > print("please enter an 8 bit binary number") > return int(num1,2) > num2 = int(input('please enter the second 8 bit binary number: '),2) > result = add_binary_numbers(num1, num2) > print('the result is', bin(result)[2:]) > > 1. Specify the Python version. I'll assume version 3.3 2. Show whatever error you got. I'd guess something like the following: File "", line 1, in TypeError: object of type 'int' has no len() The len() function operates on strings, lists, and other sequences and mappings. But although you had a string at first, you've already converted it to an int, which has no len() method. It might be simplest to compare the value num to 0 and 255. Alternatively, you could compare it before doing the int function. Since you're doing it twice, it probably makes sense to do this in a function. Write a function that repeatedly asks the user till it gets a value in the right range. The other error that jumps out is that you have a return statement at top-level, while the statement only makes sense inside a function. That problem goes away once you put the input logic inside a function. -- DaveA From alan.gauld at btinternet.com Fri Jan 11 23:27:47 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Jan 2013 22:27:47 +0000 Subject: [Tutor] garbage collection/class question In-Reply-To: <50F06AD7.90305@freenet.de> References: <50EEFF49.5060700@lightbird.net> <50F06AD7.90305@freenet.de> Message-ID: On 11/01/13 19:41, Jan Riechers wrote: >> class Tree(object): >> height = 0 >> >> def grow(self): >> self.height += 1 >> > > Actually one question about those "dozens of related" instances > generated by: > greenwoodTree = Tree() > oakTree = Tree() > .... > > Both, greenwoodTree and oakTree, are derived from Tree class, Ok, a small terminology issue. They are not derived from Tree, they are Trees. They are two instances of the same class. Derived is used to suggest that they are sub classes of Tree via inheritance, a whole different discussion. > receiving the features and also - if so - holding unique values created > in there __init__ generator method - "self.height", "self.color" and so > forth uniquely each. > > But do both share the same function memory space from the class "Tree"? Yes. each instance holds a reference to its class. The class holds the function definitions. That's why you need a self parameter, it tells the class method definition which instance is being operated upon. > I am currently trying also to get my head wrapped around OOP in general, > but not 100% sure so that derived instances use the same functions (also > memory wise speaking) - or are there several definitions of "grow" ? instances all refer to their class which holds the methods for the class. Where inheritance is concerned the class then holds a further reference to its parent class and Python looks for the earliest method definition as it traverses that class hierarchy. In other words if the object class doesn't have a method definition to match the message name then it looks in the superclass's definition for such a method, and if not there it looks in the superclass's superclass and so on until it finds a match. It is this search that makes methods different to simple functions. > The confusion came somehow when reading about "classmethods" and > "staticmethods" and patterns like Singleton, monostate, borg... > from which I understand only ensure that the "self.height" properties > are shared across multiple instances of a given class? Not quite. Class attributes are common across *all* instances of the class. Class methods are, like instance methods, stored in the class but do not need an instance to exist to call them. In fact class methods can be used as "factories" to create instances. This is a common pattern where you want a way to recover stored classes from a database or file or over a network connection. For example: foo = MYClass() # create a brand new instance in memory id = foo.store(DB) # save it in database del(foo) # get rid of the object in memory foo2 =- MYClass.restore(db, id) # new instance loaded from DB. bar = MYClass.load(someSocket) #instance read from network port store() is an instance method that stores the instance data in a database. restore() is a class method that resurrects that instance by loading it from the database load() is a class method that reads the data on a network port and interprets it as instance data and returns a new instance with those values.. > From what I tried out using id() and generating functions in a loop - > the "id(class.function) provided the same result when printed out, Yes, because they are shared. But note that this is all implementation detail, there are other OOP languages that do things differently. Python's approach is the most common but not guaranteed. In fact I'm not even sure if it's guaranteed across different Python implementations! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From 3n2solutions at gmail.com Fri Jan 11 23:29:18 2013 From: 3n2solutions at gmail.com (3n2 Solutions) Date: Fri, 11 Jan 2013 14:29:18 -0800 Subject: [Tutor] Working with output of a subprocess Message-ID: Hello, Need some help with working with a text file. Is it possible to get the values associated with each of the parameter in the below text file format? For example: 1. How can I check what the Min and Max values are? 2. How to check the second column value associated with "epoch2"? Your help is greatly appreciated. I'm using Python 2.7 on Windows7. Examining file: 5521W2310000.txt Duration : 0h : 59m First meas : week : 86 : 1721 Last meas : week : 89 : 1721 Min val : 15 Max val : 18 3D : 3600 100.0% summary Total Missed Rate epoch1 : 1378 0 0\1000 epoch2 : 2154 1 0\1000 Thanks, Tim -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jan 11 23:51:16 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 11 Jan 2013 22:51:16 +0000 (GMT) Subject: [Tutor] Books for Learning Python In-Reply-To: <08073EDD-4BF3-48A7-B2D7-1258F188076E@psu.edu> References: <08073EDD-4BF3-48A7-B2D7-1258F188076E@psu.edu> Message-ID: <1357944676.12301.YahooMailNeo@web186006.mail.ir2.yahoo.com> > I did a lot of programming in Fortran 77 while working on my Ph.D. in engineering mechanics > >That's OK, it's not permanent damage. :-) > >> (1) Will Python allow me to create applications that provide a simple GUI >> interface to something like an integrator for ODEs? > >No idea what an ODE is but yes Python can do simple graphics/GUIs. The >Tkinter GUI library and friends are part of the standard library. Other tookits >exist such as wxPython, pyGTK etc. > >> Does it have graphics libraries that allow one to animate the motion of simple >> objects (e.g., spheres, ellipsoids, parallelepipeds, etc.) based on the results of >> numerical simulations? > >Yes, you can use things like gnuplot for grpahs/chartys or more dynamic you >can use pyGame to define your own sprites and manoevre them around the screen. >You can also access libraries such as Scipy and R for heavyweight number crunching. > >Start with the official tutorial, supplement with some of themore basic for >new concepts like OOP (mine if you like! :-). Once confident with vanila python >look at specialist tutorials for TKinter, PyGame, Scipy, R etc. > >Python is well suited to your needs, obnce you have the foundation in place >(and that should take only 2 or 3 days effort to polish up the rusty bits) the >new stuff can be learned as needed. > >HTH > >Alan g. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From francois.dion at gmail.com Sat Jan 12 00:04:53 2013 From: francois.dion at gmail.com (Francois Dion) Date: Fri, 11 Jan 2013 18:04:53 -0500 Subject: [Tutor] Books for Learning Python In-Reply-To: <08073EDD-4BF3-48A7-B2D7-1258F188076E@psu.edu> References: <08073EDD-4BF3-48A7-B2D7-1258F188076E@psu.edu> Message-ID: On Fri, Jan 11, 2013 at 3:14 PM, Gary L. Gray wrote: > On Jan 11, 2013, at 1:39 PM, Alan Gauld wrote: > (1) Will Python allow me to create applications that provide a simple GUI interface to something like an integrator for ODEs? Does it have graphics libraries that allow one to animate the motion of simple objects (e.g., spheres, ellipsoids, parallelepipeds, etc.) based on the results of numerical simulations? Ordinary Differential Equations, I'm assuming. Python has tons of math / sci libraries. Matplotlib, scipy, pylab etc. Under Windows, get Python(X,Y) and you will get an IDE, Python, and all the modules I've mentionned. A quick google, for those coming from a matlab background: http://www.christopheralbert.net/2011/03/equivalent-ode-integrators-in-matlab.html What OS will you be using? Francois -- www.pyptug.org - raspberry-python.blogspot.com From d at davea.name Sat Jan 12 00:09:46 2013 From: d at davea.name (Dave Angel) Date: Fri, 11 Jan 2013 18:09:46 -0500 Subject: [Tutor] Working with output of a subprocess In-Reply-To: References: Message-ID: <50F09BBA.7010309@davea.name> On 01/11/2013 05:29 PM, 3n2 Solutions wrote: > Hello, > > Need some help with working with a text file. > Is it possible to get the values associated with each of the parameter in > the below text file format? For example: There are no intrinsic parameters and values in a text file. it's free form characters. On the other hand, if the format is a standard one, there may be a library that parses it for you. For example, configparser. On the other hand, if you have a spec, you can write a parser. Your example doesn't look like any standard, so we'd be guessing. > > 1. How can I check what the Min and Max values are? Assuming that the value of Min is " "val : 15" then you could get it by scanning through the file looking for the line that begins with the string "Min " ... if line.startswith("Min "): result = line[4:] > 2. How to check the second column value associated with "epoch2"? Use the same approach to find the value of epoch2: Then split based on the colon, and then on whitespace. parts = line.split(":") subparts = parts[1].split() > Your help is greatly appreciated. I'm using Python 2.7 on Windows7. > > > > Examining file: 5521W2310000.txt > > Duration : 0h : 59m > First meas : week : 86 : 1721 > Last meas : week : 89 : 1721 > > Min val : 15 > Max val : 18 > 3D : 3600 100.0% > > summary Total Missed Rate > epoch1 : 1378 0 0\1000 > epoch2 : 2154 1 0\1000 > > > Thanks, > Tim > > -- DaveA From chakrabarti.somnath at gmail.com Sat Jan 12 01:12:11 2013 From: chakrabarti.somnath at gmail.com (somnath chakrabarti) Date: Fri, 11 Jan 2013 19:12:11 -0500 Subject: [Tutor] pexports python27.dll > python27.def (pygraphviz 1.1 package ) In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474180DB7FE@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF474180DB7FE@SCACMX008.exchad.jpmchase.net> Message-ID: Actually the problem was the access permission for the destination folder. I changed to my account-specific path and it worked. Thanks Somnath On Fri, Jan 11, 2013 at 7:08 PM, Prasad, Ramit wrote: > somnath chakrabarti wrote: > > I have mingw and python 2.7 in a Windows 7 box and trying to install > PyGraphViz-1.1 using the following CLI > > utility > > > > python setup.py install build --compiler=mingw32 > > However, it ends up compiling error with undefined references as follows: > > > > ... > > > build\temp.win-amd64-2.7\Release\pygraphviz\graphviz_wrap.o:graphviz_wrap.c:(.text+0x5a73): > undefined reference > > to '_imp__PyInt_FromLong' > > collect2: ld returned 1 exit status > > error: command 'gcc' failed with exit status 1 > > I checked in the link (see here) which suggests exporting definitions > from C:\Windows\System32\python27.dll to > > python27.def and then using dlltool to create libpython27.a and finally > placing the libpython.a file under > > C:\Python27\libs of the Python distribution for MinGW to interpret > Python libraries. > > I have the C:\MinGW\bin added to my system path and been trying to do > the export using > > > > pexports C:\Windows\System32\python27.dll > > C:\Windows\System32\python27.def > > but each time I am receiving Access is Denied Message. > > I did some searching and found that MS Visual Studio users can avail > another export option with DUMPBIN but > > since I don't have MSVS installed, I would like to get some alternative > to get rid of the problem and need to > > use the PyGraphViz-1.1 package. Any suggestions will be very helpful > > > > Somnath Chakrabarti > > MS Student > > CSEE Department > > University of Maryland Baltimore County > > 1000 Hilltop Circle > > Baltimore, MD 21250 > > M: 443-812-5609 > > mail: chakra1 at umbc.edu > > gmail: chakrabarti.somnath at gmail.com > > Do you *need* to build PygraphViz? Seems like you can download binaries or > just install from pypi. > See: http://networkx.lanl.gov/pygraphviz/install.html > > Not sure you will have great luck here, as this list is about learning > Python. > You might have better luck in the Google Group [1], on the developer's > site[2], > or as a last resort the main Python mailing list. > > > [1] http://groups.google.com/group/pygraphviz-discuss > [2] http://networkx.lanl.gov/trac/wiki/PyGraphviz > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -- Somnath Chakrabarti MS Student CSEE Department University of Maryland Baltimore County 1000 Hilltop Circle Baltimore, MD 21250 M: 443-812-5609 mail: chakra1 at umbc.edu gmail: chakrabarti.somnath at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From msirenef at lightbird.net Sat Jan 12 01:19:21 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Fri, 11 Jan 2013 19:19:21 -0500 Subject: [Tutor] garbage collection/class question In-Reply-To: <50F06AD7.90305@freenet.de> References: <50EEFF49.5060700@lightbird.net> <50F06AD7.90305@freenet.de> Message-ID: <50F0AC09.7050802@lightbird.net> On 01/11/2013 02:41 PM, Jan Riechers wrote: > On 10.01.2013 19:50, Mitya Sirenef wrote: >> On 01/10/2013 09:06 AM, richard kappler wrote: >> >> class Tree(object): >> height = 0 >> >> def grow(self): >> self.height += 1 >> >> You may have a dozen of related functions and you can logically group >> them together by making them methods of a class, making it easier to >> think about and work on the logic of your program. >> >> >> > > Actually one question about those "dozens of related" instances generated by: > greenwoodTree = Tree() > oakTree = Tree() > .... I just want to clarify, I meant you may have dozens of related functions and then move them all into a single class (i.e. I wasn't talking about instances, although you can of course have dozens of instances, too). So, let's say, you have: def f1(): .. def f2(): .. def f3(): .. .... And it occurs to you, since they're all related, it's good to have them all in the same class: class F(object): def f1(self): .. def f2(self): .. def f3(self): .. There are already really good answers so I'll just add a few notes below... > > Both, greenwoodTree and oakTree, are derived from Tree class, thus receiving the features and also - if so - holding unique values created in there __init__ generator method - "self.height", "self.color" and so forth uniquely each. > > But do both share the same function memory space from the class "Tree"? > > I am currently trying also to get my head wrapped around OOP in general, but not 100% sure so that derived instances use the same functions (also memory wise speaking) - or are there several definitions of "grow" ? Functions are the same, (called methods), but the self object is different for each instance, and represents the instance. Consider that since the logic performed by the method is the same (if it wasn't, you'd define it as a separate method, right?), there would be no reason to make a separate method for each instance. As you know from working with functions, the same function may create different output if its arguments are different (from another call), but if the arguments are the same, it will create the same output (I'm ignoring things like random module). Well, that's why the first argument for a method is 'self', which is different for each instance. > > The confusion came somehow when reading about "classmethods" and "staticmethods" and patterns like Singleton, monostate, borg... > from which I understand only ensure that the "self.height" properties are shared across multiple instances of a given class? The core idea of having a class and one or more instances is very versatile and powerful, all of the other concepts are much less needed especially as you're starting out. For example, you can have a class tree and methods and a bunch of tree instances; a classmethod would allow you to perform an action without making an instance first, but it's not like it's hard to make an instance -- it's just that in some cases it's clearer and more straightforward to use a classmethod, like Alan pointed out, but if you happen to forget about classmethods, you could easily get by without them. The same applies to Borg pattern, etc. Learn to be comfortable with classes and instances and you'll be able to make a wide range of programs. > > From what I tried out using id() and generating functions in a loop - the "id(class.function) provided the same result when printed out, according to that: > http://stackoverflow.com/questions/121396/accessing-object-memory-address > > So I assume the functions are shared across thus one decleration has been made in "Tree" class and all siblings are using that one? They are usually called methods if they belong to a class, and yes they're shared. HTH, - mitya -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From ramit.prasad at jpmorgan.com Sat Jan 12 01:23:00 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Sat, 12 Jan 2013 00:23:00 +0000 Subject: [Tutor] writing effective unittests In-Reply-To: References: <20130102204357.GA1974@lmerg-crunchbang> <1357217453.36448.YahooMailNeo@web163805.mail.gq1.yahoo.com> <20130103194641.GA10033@lmerg-crunchbang> Message-ID: <5B80DD153D7D744689F57F4FB69AF474180DB853@SCACMX008.exchad.jpmchase.net> Japhy Bartlett wrote: > TDD is a good principle but usually seems a little too pedantic for real world programming. ?Where tests (in my > experience) get really useful is in making sure that a new change hasn't unexpectedly broken something already > written. > I would argue that TDD is a pedantic for non-real world (i.e. academic) programming and not at all for real world programming. In the academic world, manually testing is fine assuming sufficient manual testing (unless the professor is testing your testing). It was rare for me to use a project more than once or edit it enough that to find automated testing (TDD/unit) useful. Now group projects are a completely different story. Of course, this depends on your level of degree and subject matter. In the working world, testing is much more essential because money (yours or your company's) relies on the code being correct. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From msirenef at lightbird.net Sat Jan 12 01:24:54 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Fri, 11 Jan 2013 19:24:54 -0500 Subject: [Tutor] garbage collection/class question In-Reply-To: <50F084D1.8010300@davea.name> References: <50EEFF49.5060700@lightbird.net> <50F06AD7.90305@freenet.de> <50F084D1.8010300@davea.name> Message-ID: <50F0AD56.1090807@lightbird.net> On 01/11/2013 04:32 PM, Dave Angel wrote: > On 01/11/2013 02:41 PM, Jan Riechers wrote: >> On 10.01.2013 19:50, Mitya Sirenef wrote: >>> On 01/10/2013 09:06 AM, richard kappler wrote: >>> >>> class Tree(object): >>> height = 0 >>> >>> def grow(self): >>> self.height += 1 >>> >>> You may have a dozen of related functions and you can logically group >>> them together by making them methods of a class, making it easier to >>> think about and work on the logic of your program. >>> >>> >>> >> >> Actually one question about those "dozens of related" instances >> generated by: >> greenwoodTree = Tree() >> oakTree = Tree() >> .... >> >> Both, greenwoodTree and oakTree, are derived from Tree class, > > It's important that we use correct, or at least close terminology. A > derived class is VERY different from an instance. greenWoodTree and > oakTree are bound to different instances of Tree. > >> thus receiving the features and also - if so - holding unique values >> created in there __init__ generator method > > __init__ is not a generator. it's simply a method. A method is a > function that's defined inside a class > >> - "self.height", "self.color" and so forth uniquely each. > > We have to be careful here. Such data can be attributes of an instance, > or they can be attributes of a class. Strangely enough, this example > has a self.height and tree.height that are both called height, but > technically distinct values. I think it's best if you avoid such > things, and use unique names till you've got the fundamentals straight. > >> >> But do both share the same function memory space from the class "Tree"? >> > > I wouldn't use the term function memory space, but I'll say this much. > Unless you do something tricky, there is only one method Tree.grow, and > all instances share that same method. No duplicated memory at all. > >> I am currently trying also to get my head wrapped around OOP in >> general, but not 100% sure so that derived instances use the same >> functions (also memory wise speaking) - or are there several >> definitions of "grow" ? > > Not yet. Creating instances don't duplicate any methods. You'd have to > do something explicit, and advanced. > >> >> The confusion came somehow when reading about "classmethods" and >> "staticmethods" and patterns like Singleton, monostate, borg... >> from which I understand only ensure that the "self.height" properties >> are shared across multiple instances of a given class? >> > > I'd consider all of those as advanced techniques, and a complete > confusion at your present stage. classmethods and staticmethods affect > the parameters that a method gets, not whether data properties belong to > the class or to the method. > >> From what I tried out using id() and generating functions in a loop - >> the "id(class.function) provided the same result when printed out, >> according to that: >> http://stackoverflow.com/questions/121396/accessing-object-memory-address >> >> So I assume the functions are shared across thus one decleration has >> been made in "Tree" class and all siblings are using that one? >> > > Without showing the code in this loop, I can't comment on what you > observed. Don't have any idea what you mean by a sibling. The only > meaning I can think of is that two classes each derived from a common > base class can be considered siblings. But you don't do any deriving in > this email. > > I think it's very intuitive (at least, it was to me when I was learning), to view it as a common starting point for all instances. In this example it makes sense that all trees (or a general idea of a tree) starts with a 0 height, and then each particular tree ends up with a different height after a while. -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From ramit.prasad at jpmorgan.com Sat Jan 12 01:33:44 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Sat, 12 Jan 2013 00:33:44 +0000 Subject: [Tutor] run perl script files and capture results In-Reply-To: References: <1357780485.90601.YahooMailNeo@web140003.mail.bf1.yahoo.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474180DB8AB@SCACMX008.exchad.jpmchase.net> eryksun wrote: [snip] > 1. Using a forward slash in paths is OK for DOS/Windows system calls > (e.g. opening a file or setting the cwd of a new process), dating back > to the file system calls in MS-DOS 2.0 (1983). Otherwise a backslash > is usually required (e.g. shell commands and paths in commandline > arguments, where forward slash is typically used for options). In this > case use a raw string or os.path.join. For a raw string, note that a > trailing backslash is not allowed, e.g. r'C:\Python27\'. Instead you > could use r'C:\Python27' '\\', among other options: > > http://docs.python.org/2/faq/design.html#why-can-t-raw-strings-r-strings-end-with-a-backslash Why not just use r'C:\Python27\\'? Might be too confusing for a beginner to remember, I suppose. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Sat Jan 12 01:08:08 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Sat, 12 Jan 2013 00:08:08 +0000 Subject: [Tutor] pexports python27.dll > python27.def (pygraphviz 1.1 package ) In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474180DB7FE@SCACMX008.exchad.jpmchase.net> somnath chakrabarti wrote: > ?I?have mingw and python 2.7 in a Windows 7 box and trying to install PyGraphViz-1.1 using the following CLI > utility > > python setup.py install build --compiler=mingw32 > However, it ends up compiling error with undefined references as follows: > > ... > build\temp.win-amd64-2.7\Release\pygraphviz\graphviz_wrap.o:graphviz_wrap.c:(.text+0x5a73): undefined reference > to '_imp__PyInt_FromLong' > collect2: ld returned 1 exit status > error: command 'gcc' failed with exit status 1 > I checked in the link (see here) which suggests exporting definitions from C:\Windows\System32\python27.dll to > python27.def and then using dlltool to create libpython27.a and finally placing the libpython.a file under > C:\Python27\libs of the Python distribution for MinGW to interpret Python libraries. > I have the C:\MinGW\bin added to my system path and been trying to do the export using > > pexports C:\Windows\System32\python27.dll > C:\Windows\System32\python27.def > but each time I am receiving Access is Denied Message. > I did some searching and found that MS Visual Studio users can avail another export option with DUMPBIN but > since I don't have MSVS installed, I would like to get some alternative to get rid of the problem and need to > use the PyGraphViz-1.1 package. Any suggestions will be very helpful > > Somnath Chakrabarti > MS Student > CSEE Department > University of Maryland Baltimore County > 1000 Hilltop Circle > Baltimore, MD 21250 > M: 443-812-5609 > mail: chakra1 at umbc.edu > gmail: chakrabarti.somnath at gmail.com Do you *need* to build PygraphViz? Seems like you can download binaries or just install from pypi. See: http://networkx.lanl.gov/pygraphviz/install.html Not sure you will have great luck here, as this list is about learning Python. You might have better luck in the Google Group [1], on the developer's site[2], or as a last resort the main Python mailing list. [1] http://groups.google.com/group/pygraphviz-discuss [2] http://networkx.lanl.gov/trac/wiki/PyGraphviz This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Sat Jan 12 01:11:54 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Sat, 12 Jan 2013 00:11:54 +0000 Subject: [Tutor] pexports python27.dll > python27.def (pygraphviz 1.1 package ) In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474180DB81C@SCACMX008.exchad.jpmchase.net> somnath chakrabarti wrote: > Actually I embedded a link to the refer site from where I have been following the procedure. I am new to Python > too and have been following the book "Mining the Social Web" by Matthew Russell and thought Tutor mailing list > would be the right place to post the question. Anyways will try to post in text and more python generic > questions next time. Thanks for pointing out though! > :) > -Somnath And try and post in-line or after quoting relevant text (and trimming irrelevant text). Thanks! ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Sat Jan 12 01:59:13 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Jan 2013 00:59:13 +0000 Subject: [Tutor] Binary/Decimal convertor In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D83794789@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D83794789@LLN-SPP-ES-04.user01.lln.local> Message-ID: On 11/01/13 21:51, Ghadir Ghasemi wrote: > Hi, I made a program called binary/denary convertor. > Can anyone tell me about how I could stop the user entering a binary > number with more than 8 numbers or 8 bit Why would you want to? Your code can handle much bigger binary numbers, why limit the user to 8 bits? > Here is the code. I started off by entering 'len' function. > num1 = int(input('please enter the first 8 bit binary number: '),2) Here hyou read the number as a string and already convert it to a real number in Python. So the conversion from binary has already happened regardless of how long the string was. > if len(num1) > 8: > print("please enter an 8 bit binary number") You now try to see how long the number is, but numvers don;t have a length. So to do what you claim you want you need to do the len() check before you do the inty() conversion. Something like: num1 = input('please enter the first 8 bit binary number: ') if len(num1) > 8: print("please enter an 8 bit binary number") else: num = int(num,2) Then put that in while a loop that repeats until the length is <=8 > return int(num1,2) And here you return which would terminate your function except you don't have a function so it will give a syntax error. And trying to convert a num as a binary won't work because its already stored internally as a binary number. This only works if you still have the string as described above. > num2 = int(input('please enter the second 8 bit binary number: '),2) And this doesn't do any len() checks.... > result = add_binary_numbers(num1, num2) > print('the result is', bin(result)[2:]) I'd suggest that you make your add_binary_numbers() function return the binary string. Otherwise it doesn't add any value over the standard plus sign... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jan 12 02:07:31 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Jan 2013 01:07:31 +0000 Subject: [Tutor] Working with output of a subprocess In-Reply-To: References: Message-ID: On 11/01/13 22:29, 3n2 Solutions wrote: > Need some help with working with a text file. > Is it possible to get the values associated with each of the parameter > in the below text file format? For example: Yes, but it's non trivial. You need to parse the text. > 1. How can I check what the Min and Max values are? > 2. How to check the second column value associated with "epoch2"? In both cases you can extract the line using the startswith() string method. You can then use a combination of split() and strip(), lstrip() and rstrip() and slicing to extract the substrings you need. Then convert the strings to numbers as necessary. I'd probably write value extraction functions for each required parameter, given a line of input. Then iterate over the text and all the appropriate function based on the startswith() result: for line in open('myfile.txt'): if line.startswith('Min'): min = getSingleNumber(line) elif line startswith('Max'): max = getSingleNumber(line) elif .... elif line.startswith('epoch2'): epoch2 = getCol2(line) .... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From richkappler at gmail.com Sat Jan 12 02:18:00 2013 From: richkappler at gmail.com (richard kappler) Date: Fri, 11 Jan 2013 20:18:00 -0500 Subject: [Tutor] a Pygtk question sort of Message-ID: Before anybody jumps me about this question being inappropriate for this list, yes, I know it probably is BUT, the two places where it might be appropriate are down pretty hard, so this is my only option (I think). The question is in regards to pygtk I think, and pocketsphinx obliquely. Appended below is code from the CMU Sphinx website that I wish to ever so slightly modify, but am not quite sure how to proceed. This code creates a gui with a button that stops and starts the pocketsphinx speech recognition engine. When the button reads "speak" and you push it, the button goes blank iirc, pocketsphinx listens, performs speech recognition and sends the resulting text to the gui, changing the button text back to "speak" and putting the pocketsphinx engine ostensibly (though not in actuality) on pause. I understand how the below code does all of this, including how pocketsphinx works. Here's the issue: I want to use this code or code like it (pocketsphinx can be imported and run directly in python but apparently only to decode wav files, not as a real-time decoder unless you run it through gst as shown in the appended code as I understand it) in my bot program, so I don't need the gui, button or any of that. I need pocketsphinx to work exactly as below, but send the text output back to the main program or to a different program (chatbot) instead of the gui. Make sense? I've been pouring over this code off and on for months as I've been learning, and it's not quite as simple as dump the gui method and the button. The problem is the button controls the vader (determines begin and end of utterances) as well. Detailed explanation here: http://cmusphinx.sourceforge.net/wiki/gstreamer So can anyone give me some guidance here or point me towards a place to discuss this? The forums at Python.org are under construction, the CMUSphinx forums at Sourceforge are down (404) so I'm not quite sure where to go for help. regards, Richard #!/usr/bin/env python # Copyright (c) 2008 Carnegie Mellon University. # # You may modify and redistribute this file under the same terms as # the CMU Sphinx system. See # http://cmusphinx.sourceforge.net/html/LICENSE for more information. import pygtk pygtk.require('2.0') import gtk import gobject import pygst pygst.require('0.10') gobject.threads_init() import gst class DemoApp(object): """GStreamer/PocketSphinx Demo Application""" def __init__(self): """Initialize a DemoApp object""" self.init_gui() self.init_gst() def init_gui(self): """Initialize the GUI components""" self.window = gtk.Window() self.window.connect("delete-event", gtk.main_quit) self.window.set_default_size(400,200) self.window.set_border_width(10) vbox = gtk.VBox() self.textbuf = gtk.TextBuffer() self.text = gtk.TextView(self.textbuf) self.text.set_wrap_mode(gtk.WRAP_WORD) vbox.pack_start(self.text) self.button = gtk.ToggleButton("Speak") self.button.connect('clicked', self.button_clicked) vbox.pack_start(self.button, False, False, 5) self.window.add(vbox) self.window.show_all() def init_gst(self): """Initialize the speech components""" self.pipeline = gst.parse_launch('gconfaudiosrc ! audioconvert ! audioresample ' + '! vader name=vad auto-threshold=true ' + '! pocketsphinx name=asr ! fakesink') asr = self.pipeline.get_by_name('asr') asr.connect('partial_result', self.asr_partial_result) asr.connect('result', self.asr_result) asr.set_property('configured', True) bus = self.pipeline.get_bus() bus.add_signal_watch() bus.connect('message::application', self.application_message) self.pipeline.set_state(gst.STATE_PAUSED) def asr_partial_result(self, asr, text, uttid): """Forward partial result signals on the bus to the main thread.""" struct = gst.Structure('partial_result') struct.set_value('hyp', text) struct.set_value('uttid', uttid) asr.post_message(gst.message_new_application(asr, struct)) def asr_result(self, asr, text, uttid): """Forward result signals on the bus to the main thread.""" struct = gst.Structure('result') struct.set_value('hyp', text) struct.set_value('uttid', uttid) asr.post_message(gst.message_new_application(asr, struct)) def application_message(self, bus, msg): """Receive application messages from the bus.""" msgtype = msg.structure.get_name() if msgtype == 'partial_result': self.partial_result(msg.structure['hyp'], msg.structure['uttid']) elif msgtype == 'result': self.final_result(msg.structure['hyp'], msg.structure['uttid']) self.pipeline.set_state(gst.STATE_PAUSED) self.button.set_active(False) def partial_result(self, hyp, uttid): """Delete any previous selection, insert text and select it.""" # All this stuff appears as one single action self.textbuf.begin_user_action() self.textbuf.delete_selection(True, self.text.get_editable()) self.textbuf.insert_at_cursor(hyp) ins = self.textbuf.get_insert() iter = self.textbuf.get_iter_at_mark(ins) iter.backward_chars(len(hyp)) self.textbuf.move_mark(ins, iter) self.textbuf.end_user_action() def final_result(self, hyp, uttid): """Insert the final result.""" # All this stuff appears as one single action self.textbuf.begin_user_action() self.textbuf.delete_selection(True, self.text.get_editable()) self.textbuf.insert_at_cursor(hyp) self.textbuf.end_user_action() def button_clicked(self, button): """Handle button presses.""" if button.get_active(): button.set_label("Stop") self.pipeline.set_state(gst.STATE_PLAYING) else: button.set_label("Speak") vader = self.pipeline.get_by_name('vad') vader.set_property('silent', True) app = DemoApp() gtk.main() -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jan 12 02:37:20 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Jan 2013 01:37:20 +0000 Subject: [Tutor] a Pygtk question sort of In-Reply-To: References: Message-ID: On 12/01/13 01:18, richard kappler wrote: > Before anybody jumps me about this question being inappropriate for this > list, yes, I know it probably is BUT, the two places where it might be > appropriate are down pretty hard, so this is my only option (I think). I'm not sure what you mean by "down pretty hard" but this definitely looks like a question for a pocketsphinx forum... > ....I want to use this code or code > like it ....in my bot program, so I don't need the gui, button or any of that. I > need pocketsphinx to work exactly as below, but send the text output > back to the main program or to a different program (chatbot) instead of > the gui. Make sense? Sadly no. Can you explain exactly how you intend running pocketspinx? What is the main program? A Python script? Or some other external program? Where does chatbot fit in? Is it just an arbitrary example or is there some specific symbiosis going on? > gui method and the button. The problem is the button controls the vader > (determines begin and end of utterances) as well. Detailed explanation Nope, you lost me again... > So can anyone give me some guidance here or point me towards a place to > discuss this? The forums at Python.org are under construction, the > CMUSphinx forums at Sourceforge are down (404) so I'm not quite sure > where to go for help. Googling pocketsphinx python threw up at least half a dozen useful looking links.... You could also try the main python mailing list (or its mirror on the comp.lang.python newsgroup) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Sat Jan 12 02:41:00 2013 From: d at davea.name (Dave Angel) Date: Fri, 11 Jan 2013 20:41:00 -0500 Subject: [Tutor] run perl script files and capture results In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474180DB8AB@SCACMX008.exchad.jpmchase.net> References: <1357780485.90601.YahooMailNeo@web140003.mail.bf1.yahoo.com> <5B80DD153D7D744689F57F4FB69AF474180DB8AB@SCACMX008.exchad.jpmchase.net> Message-ID: <50F0BF2C.8000708@davea.name> On 01/11/2013 07:33 PM, Prasad, Ramit wrote: > [snip] > Why not just use r'C:\Python27\\'? Might be too confusing for > a beginner to remember, I suppose. > > Because that'd have two trailing backslashes. (in Python 2.7 anyway) -- DaveA From eowens0124 at gmx.com Sat Jan 12 03:47:37 2013 From: eowens0124 at gmx.com (Ed Owens) Date: Fri, 11 Jan 2013 21:47:37 -0500 Subject: [Tutor] Is a link broken? Message-ID: <50F0CEC9.2060102@gmx.com> I'm still working through Chun's "Core Python Applications". I got the web crawler (Example 9-2) working after I found a ':' typing error. Now I'm trying to convert that to a program that checks for broken links. This is not in the book. The problem I'm having now is knowing whether a link is working. I've written an example that I hope illustrates my problem: #!/usr/bin/env python import urllib2 sites = ('http://www.catb.org', 'http://ons-sa.org', 'www.notasite.org') for site in sites: try: page = urllib2.urlopen(site) print page.geturl(), "didn't return error on open" print 'Reported server is', page.info()['Server'] except: print site, 'generated an error on open' try: page.close() print site, 'successfully closed' except: print site, 'generated error on close' Site 1 is alive, the other two dead. Yet this code only returns an error on site three. Notice that I checked for a redirection (I think) of the site if it opened, and that didn't help with site two. Is there an unambiguous way to determine if a link has died -- knowing nothing about the link in advance? Ed From janpeterr at freenet.de Sat Jan 12 09:09:55 2013 From: janpeterr at freenet.de (Jan Riechers) Date: Sat, 12 Jan 2013 10:09:55 +0200 Subject: [Tutor] garbage collection/class question In-Reply-To: <50F0AC09.7050802@lightbird.net> References: <50EEFF49.5060700@lightbird.net> <50F06AD7.90305@freenet.de> <50F0AC09.7050802@lightbird.net> Message-ID: <50F11A53.2070801@freenet.de> On 12.01.2013 02:19, Mitya Sirenef wrote: > > Functions are the same, (called methods), but the self object is > different for each instance, and represents the instance. Consider that > since the logic performed by the method is the same (if it wasn't, you'd > define it as a separate method, right?), there would be no reason to > make a separate method for each instance. As you know from working with > functions, the same function may create different output if its > arguments are different (from another call), but if the arguments are > the same, it will create the same output (I'm ignoring things like > random module). > > Well, that's why the first argument for a method is 'self', which is > different for each instance. > >> So to rephrase what you and also other wrote: By setting "oakTree = Tree()" I create a new "Tree()" class instance. Now calls to "oakTree.grow()" access functions of the Tree class, by traversing to it's "Superclass" Tree. The "self" then, which also is used in the Superclass Function only tells, work with the "own" (self) values of the class instance, instead of the values of the class itself. I guess that's right. > > The core idea of having a class and one or more instances is very > versatile and powerful, all of the other concepts are much less needed > especially as you're starting out. For example, you can have a class > tree and methods and a bunch of tree instances; a classmethod would > allow you to perform an action without making an instance first, but > it's not like it's hard to make an instance -- it's just that in some > cases it's clearer and more straightforward to use a classmethod, like > Alan pointed out, but if you happen to forget about classmethods, you > could easily get by without them. The same applies to Borg pattern, etc. > Actually Im puzzled with the difference between a classmethod and a regular function definition inside a class object. Does the classmethod just mean that I can use the class "math" and call "math.random()" without creating an instance of math before using "random()" ? To what you write, it would make sense like that. Of course the math module has to be imported first. But thats not the point now I guess :) > > So I assume the functions are shared across thus one decleration has > been made in "Tree" class and all siblings are using that one? > > > They are usually called methods if they belong to a class, and yes > they're shared. > Okay, that makes sense - that class functions/methods (confusing with that decorator to talk about) are accessible and shared across all class instances - and its also what I noticed by using some code like following and the id() function. Dave was asking what code I meant to get the "memory address" on where a function is lurking: --------- class market(): def __init__(self): self.name = 'Market' def getMarketPrice(self): print self print self.__dict__ myInstancesList = [] for x in range(0, 10): myInstancesList.append( market() ) print id(myInstancesList[x].getMarketPrice) print myInstancesList --------- Which outputs the same memory reference for the function "getMarketPrice" of all instances of the "market" class plus the instances inside a list "myInstancesList". I dont use a dictionary which might be confusing, but makes more sense to work with. Also id() mentioned here: http://stackoverflow.com/questions/121396/accessing-object-memory-address And thank you all for the explanations. :) Jan From eryksun at gmail.com Sat Jan 12 10:18:28 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 12 Jan 2013 04:18:28 -0500 Subject: [Tutor] run perl script files and capture results In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474180DB8AB@SCACMX008.exchad.jpmchase.net> References: <1357780485.90601.YahooMailNeo@web140003.mail.bf1.yahoo.com> <5B80DD153D7D744689F57F4FB69AF474180DB8AB@SCACMX008.exchad.jpmchase.net> Message-ID: On Fri, Jan 11, 2013 at 7:33 PM, Prasad, Ramit wrote: > > Why not just use r'C:\Python27\\'? Might be too confusing for > a beginner to remember, I suppose. Off the top of my heard I can think of 3 raw-escape uses of backslash in a raw string literal: placing an even number of backslashes at the end of the literal (an odd number is a syntax error), including the quote character, and raw line continuation (includes the LF): >>> list(r'\\') ['\\', '\\'] >>> list(r'\'') ['\\', "'"] >>> list(r"\"") ['\\', '"'] >>> s = r'\ ... ' >>> list(s) ['\\', '\n'] From alan.gauld at btinternet.com Sat Jan 12 10:24:00 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Jan 2013 09:24:00 +0000 Subject: [Tutor] garbage collection/class question In-Reply-To: <50F11A53.2070801@freenet.de> References: <50EEFF49.5060700@lightbird.net> <50F06AD7.90305@freenet.de> <50F0AC09.7050802@lightbird.net> <50F11A53.2070801@freenet.de> Message-ID: On 12/01/13 08:09, Jan Riechers wrote: > So to rephrase what you and also other wrote: > By setting "oakTree = Tree()" I create a new "Tree()" class instance. > Now calls to "oakTree.grow()" access functions of the Tree class, by > traversing to it's "Superclass" Tree. No, they traverse to its Tree class. Superclasses are only involved when you use inheritance. Consider: class Tree: def __init__(self,height=0): self.height = height def getHeight(self): return self.height def EverGreen(Tree): # subclass of Tree def __init__(self, height=0, color='green'): Tree.__init__(self,height) self.color = color def getColor(self): return self.color t = Tree() print t.getHeight() # calls Tree.getHeight g = EverGreen() print g.getHeight() # calls Tree.getHeight by searching superclass print g.getColor() # calls EverGreen.getColor So the superclass is only used in the case of g.getHeight() Python looks for getHeight in the class of EverGreen and can't find it. So it looks in the superclass Tree to see if it can find getHeight there. > The "self" then, which also is used in the Superclass Function only > tells, work with the "own" (self) values of the class instance, instead > of the values of the class itself. > > I guess that's right. Maybe, I'm not sure what you mean. self is a reference to the instance invoking the method. > Actually Im puzzled with the difference between a classmethod and a > regular function definition inside a class object. All methods are functions defined inside classes. "regular functions" are by definition NOT defined in a class. regular functions require no lookup mechanism and do not have a "magic" first parameter like self. > Does the classmethod just mean that I can use the class "math" and call > "math.random()" without creating an instance of math before using > "random()" ? Maybe, if math were a class. But math is actually a module which is different to a class. > Okay, that makes sense - that class functions/methods (confusing with > that decorator to talk about) The decorator is only used for classmethods not for instance methods. Most of the time you don't need to use classmethods you only need instance methods. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eryksun at gmail.com Sat Jan 12 10:52:04 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 12 Jan 2013 04:52:04 -0500 Subject: [Tutor] pexports python27.dll > python27.def (pygraphviz 1.1 package ) In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF474180DB7FE@SCACMX008.exchad.jpmchase.net> Message-ID: On Fri, Jan 11, 2013 at 7:12 PM, somnath chakrabarti wrote: > > Actually the problem was the access permission for the destination folder. I > changed to my account-specific path and it worked. You should be OK using gcc as long as you're not using C++. But why not use Microsoft's free (as in beer) compiler from the Windows 7 SDK? Instructions: http://wiki.cython.org/64BitCythonExtensionsOnWindows From janpeterr at freenet.de Sat Jan 12 11:55:17 2013 From: janpeterr at freenet.de (Jan Riechers) Date: Sat, 12 Jan 2013 12:55:17 +0200 Subject: [Tutor] garbage collection/class question In-Reply-To: References: <50EEFF49.5060700@lightbird.net> <50F06AD7.90305@freenet.de> <50F0AC09.7050802@lightbird.net> <50F11A53.2070801@freenet.de> Message-ID: <50F14115.8000507@freenet.de> On 12.01.2013 11:24, Alan Gauld wrote: > On 12/01/13 08:09, Jan Riechers wrote: > >> So to rephrase what you and also other wrote: >> By setting "oakTree = Tree()" I create a new "Tree()" class instance. >> Now calls to "oakTree.grow()" access functions of the Tree class, by >> traversing to it's "Superclass" Tree. > > No, they traverse to its Tree class. Superclasses are only involved when > you use inheritance. Consider: > > class Tree: > def __init__(self,height=0): > self.height = height > > def getHeight(self): > return self.height > > def EverGreen(Tree): # subclass of Tree > def __init__(self, height=0, color='green'): > Tree.__init__(self,height) > self.color = color > > def getColor(self): > return self.color > > > t = Tree() > print t.getHeight() # calls Tree.getHeight > > g = EverGreen() > print g.getHeight() # calls Tree.getHeight by searching superclass > print g.getColor() # calls EverGreen.getColor > > So the superclass is only used in the case of g.getHeight() > Python looks for getHeight in the class of EverGreen and can't find it. > So it looks in the superclass Tree to see if it can find getHeight there. > Actually I miss the terminology but that was what I thought to describe - also referring to your initial post on my question. If a class is based on a super class, the message lookup traversal goes from child to superclass, which now makes sense. >> The "self" then, which also is used in the Superclass Function only >> tells, work with the "own" (self) values of the class instance, instead >> of the values of the class itself. >> >> I guess that's right. > > Maybe, I'm not sure what you mean. self is a reference to the instance > invoking the method. > Given: class Market(): def __init__(self): self.traders = 0 def addTrader(self): self.traders += 1 instanceMarket = market() print instanceMarket.traders # 0 instanceMarket.addTrader() print instanceMarket.traders # 1 So the value of "traders" is unique to the instance, but the class function "addTrader", refers to the instance on which the function is invoked on (using self), but is declared only once for all instances based on "market". That also does now make sense. :) >> Actually Im puzzled with the difference between a classmethod and a >> regular function definition inside a class object. > > All methods are functions defined inside classes. "regular functions" > are by definition NOT defined in a class. regular functions require no > lookup mechanism and do not have a "magic" first parameter like self. > >> Does the classmethod just mean that I can use the class "math" and call >> "math.random()" without creating an instance of math before using >> "random()" ? > > Maybe, if math were a class. But math is actually a module which is > different to a class. > I think again the terms are mixing things up. I tried that with the "classmethod" decorator and ended up with something like this: class market(): __balance = 500 @classmethod def getBalance(cls): print cls.__balance In this case now, from what was explained and what meant to say, market.getBalance() can now called without creating an instance of that class (like a module, even so it is not.) So calling: market.getBalance() # --> 500 >> Okay, that makes sense - that class functions/methods (confusing with >> that decorator to talk about) > > The decorator is only used for classmethods not for instance methods. > Most of the time you don't need to use classmethods you only need > instance methods. > Sorry again for the long post and mixing up the wordings, I guess I have to practice and read a bit more, but I understand now more of the OOP concept and inner workings than before - so it helped already :) Jan From steve at pearwood.info Sat Jan 12 13:16:49 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Jan 2013 23:16:49 +1100 Subject: [Tutor] Is a link broken? In-Reply-To: <50F0CEC9.2060102@gmx.com> References: <50F0CEC9.2060102@gmx.com> Message-ID: <50F15431.4030403@pearwood.info> On 12/01/13 13:47, Ed Owens wrote: > I've written an example that I hope illustrates my problem: > > #!/usr/bin/env python > > import urllib2 > > sites = ('http://www.catb.org', 'http://ons-sa.org', 'www.notasite.org') > for site in sites: > try: > page = urllib2.urlopen(site) > print page.geturl(), "didn't return error on open" > print 'Reported server is', page.info()['Server'] > except: > print site, 'generated an error on open' Incorrect. Your "except" clause is too general, and so the error message is misleading. The correct error message should be: print site, """something went wrong in either opening the url, getting the url, fetching info about the page, printing the results, or something completely unrelated to any of those things, or the user typed Ctrl-C to interrupt processing, or something that I haven't thought of... """ Which of course is so general that it is useless. Lesson 1: never, ever use a bare "except" clause. (For experts only: almost never use a bare "except" clause.) Always specify what sort of exceptions you wish to catch. Lesson 2: always keep the amount of code inside a "try" clause to the minimum needed. Lesson 3: whenever possible, *don't* catch exceptions at all. It is infinitely better to get a full exception, with lots of useful debugging information, that to catch the exception, throw away that useful debugging information, and replace it with a lame and useless error message like "generated an error on open". What sort of error? What generated that error? What error code was it? Is it a permanent error (e.g. like error 404, page not found) or a temporary error? Is the error at the HTTP level, or the lower networking level, or a bug in your Python code? These are all vital questions that can be answered by inspecting the exception and stack trace that Python gives you. The error message "generated an error on open" is not only *useless*, but it is also *wrong*. I recommend that you start by not catching any exception at all. Just let the exception (if any) print as normal, and see what you can learn from that. > Site 1 is alive, the other two dead. Incorrect. Both site 1 and site 2 work in my browser. Try it and see for yourself. > Yet this code only returns an error on site three. Notice that I >checked for a redirection (I think) of the site if it opened, and that >didn't help with site two. There is no redirection with site 2. > Is there an unambiguous way to determine if a link has died -- knowing >nothing about the link in advance? No. Define "line has died". That could mean: - the individual page is gone; - the entire web server is not responding; - the web server is responding, but slowly, and requests time-out; - the web server does respond, but only to say "sorry, too busy to talk now, try again later"; - the web server refuses to respond because you haven't logged in; - you have a low-level network error, but the site is still okay; - your network connection is down; etc. There are literally dozens upon dozens of different types of errors here. -- Steven From janpeterr at freenet.de Sat Jan 12 16:28:02 2013 From: janpeterr at freenet.de (Jan Riechers) Date: Sat, 12 Jan 2013 17:28:02 +0200 Subject: [Tutor] Working with output of a subprocess In-Reply-To: References: Message-ID: <50F18102.3070102@freenet.de> On 12.01.2013 00:29, 3n2 Solutions wrote: > Need some help with working with a text file. > Is it possible to get the values associated with each of the parameter > in the below text file format? For example: > > 1. How can I check what the Min and Max values are? > 2. How to check the second column value associated with "epoch2"? > > > > > Examining file: 5521W2310000.txt > > Duration : 0h : 59m > First meas : week : 86 : 1721 > Last meas : week : 89 : 1721 > > Min val : 15 > Max val : 18 > 3D : 3600 100.0% > > summary Total Missed Rate > epoch1 : 1378 0 0\1000 > epoch2 : 2154 1 0\1000 > Alan's approach, writing a parser is right, just what I might want to add. Just by looking at the general structure of the file: For example the line: "epoch1 : 1378 0 0\1000" its like: command/parameter TAB TAB ":" value TAB value TAB value"\"secondValue Having a deeper look: 1) go line by line and check if the line starts with a searched value, like said 2) use a split to break up the structure of that line if its a command you want to get the values from, diving it to command, value pair using ":" as a split character (for the epoch line) Now you could split the value part result[2] = result[2].split('\t') by "\t" tabulator sign and access the subvalues of that. So the structure will be something like, after the 2nd split: ['epoch1', [1378, 0, '0\1000']] If you encounter that there are tabs inside the command result, you can use str.rstrip('\t') to cut off tabs. To avoid that the timestamp gets broken up into two parts, use str.split(':', 1) (only one split of that line) or similar. Hope that helps. Jan From ghasema01 at leedslearning.net Sat Jan 12 18:32:38 2013 From: ghasema01 at leedslearning.net (Ali Raza Ghasemi) Date: Sat, 12 Jan 2013 17:32:38 +0000 Subject: [Tutor] (no subject) Message-ID: I have to make a program that adds binary numbers together. The program has to accept two binary values (up to 8 binary digits) and output their total in binary. The output should not contain any leading zeros. I have a problem in that I don't know how to limit the number digits to 8 as it accepts however many digits you enter, I also want the program to ignore anything other than 8-bit 0s and 1s. It is a python version 3.2.3 Here is my code: def add_binary_numbers(num1, num2): while True: return num1 + num2 if len(str(num1)) > 8: print("Please enter an 8 bit binary number") continue num1 = int(input('please enter the first 8 bit binary number: '),2) num2 = int(input('please enter the second 8 bit binary number: '),2) result = add_binary_numbers(num1, num2) print('the result is', bin(result)[2:]) -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sat Jan 12 19:00:26 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 12 Jan 2013 13:00:26 -0500 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: First, you need to type in a useful subject line for your question. Second, it is nicer if you use plain text instead of rtf because rtf messes up indentations sometimes. This looks like homework. That's ok. But you should say so. You haven't really asked a question. You state the assignment, then say that you don't know how to deal with the 8 digit limit. The int() function will raise a value error if you give it a number that doesn't work for the base you set: >>> int('123',2) Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 2: '123' >>> So, you could write a small function that reads in the user's data and then checks its length and whether it doesn't raise the V alueError If it passes both tests, return its value. Call it again for the second number. Since you ask a different prompt for each number, you should pass the prompt into your function as a parameter. Add the two values, convert to binary, and display your result On Sat, Jan 12, 2013 at 12:32 PM, Ali Raza Ghasemi < ghasema01 at leedslearning.net> wrote: > I have to make a program that adds binary numbers together. The program > has to accept two binary values (up to 8 binary digits) and output their > total in binary. The output should not contain any leading zeros. > I have a problem in that I don't know how to limit the number digits to 8 > as it accepts however many digits you enter, I also want the program to > ignore anything other than 8-bit 0s and 1s. It is a python version 3.2.3 > Here is my code: > > def add_binary_numbers(num1, num2): > while True: > return num1 + num2 > if len(str(num1)) > 8: > print("Please enter an 8 bit binary number") > continue > num1 = int(input('please enter the first 8 bit binary number: '),2) > num2 = int(input('please enter the second 8 bit binary number: '),2) > result = add_binary_numbers(num1, num2) > print('the result is', bin(result)[2:]) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Jan 12 19:10:19 2013 From: d at davea.name (Dave Angel) Date: Sat, 12 Jan 2013 13:10:19 -0500 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <50F1A70B.90808@davea.name> On 01/12/2013 12:32 PM, Ali Raza Ghasemi wrote: > I have to make a program that adds binary numbers together. The program has to accept two binary values (up to 8 binary digits) and output their total in binary. The output should not contain any leading zeros. > I have a problem in that I don't know how to limit the number digits to 8 as it accepts however many digits you enter, I also want the program to ignore anything other than 8-bit 0s and 1s. It is a python version 3.2.3 > Here is my code: > > def add_binary_numbers(num1, num2): > while True: > return num1 + num2 > if len(str(num1)) > 8: > print("Please enter an 8 bit binary number") > continue" > num1 = int(input('please enter the first 8 bit binary number: '),2) > num2 = int(input('please enter the second 8 bit binary number: '),2) > result = add_binary_numbers(num1, num2) > print('the result is', bin(result)[2:]) > > See yesterday's thread in this same mailing list entitled "Binary/Decimal convertor" probably started by a classmate. -- DaveA From tm at tobix.eu Sat Jan 12 19:28:24 2013 From: tm at tobix.eu (Tobias M.) Date: Sat, 12 Jan 2013 19:28:24 +0100 Subject: [Tutor] Problem with calling class methods stored in a list In-Reply-To: References: <50EE93D2.4030504@tobix.eu> <50EE944C.7060102@tobix.eu> <50EEA7AF.9020704@tobix.eu> <50EEBE26.7090005@tobix.eu> <50EEEB64.50409@tobix.eu> Message-ID: <50F1AB48.1090406@tobix.eu> Peter Otten wrote: > You are right; the misunderstanding is that I wasn't advertising the above > "fancy" solution (which is buggy, btw). Yes, I wasn't sure about the irony in you last post ;) Peter Otten wrote: > > I have now implemented what I had in mind with the protocol to function name > mapping, and I think /that/ is reasonably complex. I'm using instance > methods in the demo, but it should work with class methods as well. > > class Error(Exception): > def __init__(self, protocol): > Exception.__init__(self, self.template.format(protocol)) > > class UnknownProtocolError(Error): > template = "Unknown protocol {}" > > class ProtocolNotSupportedError(Error): > template = "Protocol {} not supported" > > FOO = (42, 17) > BAR = (1, 2) > BAZ = (3, 4) > HAM = (4, 5) > SPAM = (5, 6) > > class HandlersBase(object): > protocol_to_methodname = { > FOO: "foo", > BAR: "bar", > BAZ: "baz", > HAM: "ham", > } > def get_handler(self, protocol): > try: > methodname = self.protocol_to_methodname[protocol] > except KeyError: > raise UnknownProtocolError(protocol) > > method = getattr(self, methodname, None) > if method is None: > raise ProtocolNotSupportedError(protocol) > return method > > class A(HandlersBase): > def foo(self): print "A.foo" > def bar(self): print "A.bar" > def baz(self): print "A.baz" > > class B(A): > def bar(self): print "B.bar" > baz = None # hide parent implementation > > if __name__ == "__main__": > > for Class in A, B: > inst = Class() > print "---", Class.__name__, "---" > for protocol in FOO, BAR, BAZ, SPAM: > try: > inst.get_handler(protocol)() > except Error as err: > print err Thanks for the code! It's very similar to what I implemented but more flexible regarding inheritance. From ghasema01 at leedslearning.net Sat Jan 12 19:27:40 2013 From: ghasema01 at leedslearning.net (Ali Raza Ghasemi) Date: Sat, 12 Jan 2013 18:27:40 +0000 Subject: [Tutor] Binary Addition Message-ID: Hi, the program that I sent you is not homework. It is merely something I did in my free time. I don't know what you mean so can you make it a little bit clearer by sending me the code. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jan 12 19:44:47 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 12 Jan 2013 18:44:47 +0000 (GMT) Subject: [Tutor] a Pygtk question sort of In-Reply-To: References: Message-ID: <1358016287.79805.YahooMailNeo@web186005.mail.ir2.yahoo.com> Forwarding to the List Pleae use ReplyAll for list responses. ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ >________________________________ > From: richard kappler >To: Alan Gauld >Sent: Saturday, 12 January 2013, 2:15 >Subject: Re: [Tutor] a Pygtk question sort of > > > > > >I'm not sure what you mean by "down pretty hard" but this definitely looks like a question for a pocketsphinx forum... >> > > >CMU Sphinx runs forums that would have been appropriate on Sourceforge, but those are "down hard" eg trying to access them gives a 404 error (this is new, they have never been down before, at least in my experience). ?The help/discussion forums at python.org are apparently in the midst of migrating to a new format/software and, while there, are unsearchable and mostly missing for the next few days. >? >....I want to use this code or code >>>like it ....in my bot program, so I don't need the gui, button or any of that. I >>> >>>need pocketsphinx to work exactly as below, but send the text output >>>back to the main program or to a different program (chatbot) instead of >>>the gui. Make sense? >>> >>Sadly no. >>Can you explain exactly how you intend running pocketspinx? >>What is the main program? A Python script? Or some other external program? Where does chatbot fit in? Is it just an arbitrary example or is there some specific symbiosis going on? > > >It's a robot I've been working on for some months. It consists of a laptop interfaced with an Arduino board that reads sensors, sends the data to the laptop for decision making and controls the motors based on commands generated by the "main" bot program on the laptop, written in python (2.73).? > > >Among the many separate programs called by the python program that is the "main" part of the bot, will be pocketsphinx for speech recognition, festival for text to speech, Chatscript for the chatbot, the Arduino which coms through serial and other things still being worked out. The Arduino is coded and communicating quite well with the laptop/python program. Chatscript (via boost) and Festival are working well enough for now. I'm trying to work the pocketsphinx bit now. > > >What pocketsphinx needs to do is convert the user's speech to text and send it to the python program ("main program" think master control) via the gst pipe set up in the script I appended to the original post. Come to think of it my terminology is way off here, as I believe the appended script will ultimately be a class within the bot's python program, so think of it more as a main loop within the python program. In that loop the sensors will be read, the AI will determine priorities based on needs or commands, pocketsphinx will listen and convert speech to text returning the text output to the main loop, where the text will be either matched with a few preset sentences for commands like "move forward," "turn left," etc or, if there are no matches there, the text is sent out to Chatscript (a separate, C++ program) for NLP processing and response, which response will be returned to the python program and sent out to Festival for text to speech response, then the loop starts over unless the "end program" command is given, in which case the loop is exited and the program terminates. > > >Hopefully better? > > >? >gui method and the button. The problem is the button controls the vader >>>(determines begin and end of utterances) as well. Detailed explanation >>> >> Nope, you lost me again... > > >The previously appended code basically does three things:? >1) it creates a little gui text box with a button. ? >2) it uses gst to receive real time audio from the mic and opens a pipeline to --- >3) send the audio to pocketsphinx speech rec engine for decoding to text > > >How it works: start the program, a gui pops up with a button labeled "speak" and behind the scenes gst and pocketsphinx are started/initialized. The vader (voice activity detector), controlled by the button method, determines the beginning and endpoint of an "utterance" (think sentence). So, once the program/script is started and everything up and running, when you push the "speak" button, gstreamer receives the audiostream from the mic, the button changes to "stop" and the vader sets to work breaking the audio stream into utterances for pocketsphinx to process/convert to text. The output from pocketshinx, what the engine thinks you said, is displayed in real time in the text box of the gui. > > >I want that text directed into the python program for further processing instead of the text box. > > >regards, Richard > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ghasema01 at leedslearning.net Sat Jan 12 21:43:29 2013 From: ghasema01 at leedslearning.net (Ali Raza Ghasemi) Date: Sat, 12 Jan 2013 20:43:29 +0000 Subject: [Tutor] Adding Binary Message-ID: I am making a program that adds binary numbers together. The program has to accept two binary values (up to 8 binary digits) and output their total in binary. The output should not contain any leading zeros. I have a problem in that I don't know how to limit the number digits to 8 as it accepts however many digits you enter, I also want the program to ignore anything other than 8-bit 0s and 1s. It is a python version 3.2.3 Here is my code: def add_binary_numbers(num1, num2): while True: return num1 + num2 if len(str(num1)) > 8: print("Please enter an 8 bit binary number") continue num1 = int(input('please enter the first 8 bit binary number: '),2) num2 = int(input('please enter the second 8 bit binary number: '),2) result = add_binary_numbers(num1, num2) print('the result is', bin(result)[2:]) I know this isn't a question but it is something I needed help on. This program isn't a homework or an assignment. Help would be much appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Jan 12 23:44:23 2013 From: d at davea.name (Dave Angel) Date: Sat, 12 Jan 2013 17:44:23 -0500 Subject: [Tutor] Adding Binary In-Reply-To: References: Message-ID: <50F1E747.5030703@davea.name> On 01/12/2013 03:43 PM, Ali Raza Ghasemi wrote: > I am making a program that adds binary numbers together. The program has to accept two binary values (up to 8 binary digits) and output their total in binary. The output should not contain any leading zeros. > I have a problem in that I don't know how to limit the number digits to 8 as it accepts however many digits you enter, I also want the program to ignore anything other than 8-bit 0s and 1s. It is a python version 3.2.3 > Here is my code: > def add_binary_numbers(num1, num2): > while True: > return num1 + num2 > if len(str(num1)) > 8: > print("Please enter an 8 bit binary number") > continue > num1 = int(input('please enter the first 8 bit binary number: '),2) > num2 = int(input('please enter the second 8 bit binary number: '),2) > result = add_binary_numbers(num1, num2) > print('the result is', bin(result)[2:]) > > > > I know this isn't a question but it is something I needed help on. This program isn't a homework or an assignment. Help would be much appreciated. > > > What did you learn from the other thread I told you about? Is Ghadir Chasemi ghasemmg01 at leedslearning.net related to you? Your email addresses only differ by a couple of letters. Your code and his/hers differ only in the ordering and other minor details, so it'd be an amazing coincidence if it didn't have a common source. Why are you still using html/rtf text? Joel Goldstick pointed out that it frequently messes up formatting on a text mailing list. Look above and see how all the indentation you presumably had is lost when I see it. Do you realize that in a function, after an unconditional return statement, no other code "in" the function will execute. Of course, without fixing the indentation, nothing is inside the function. Perhaps you'd find the problem easier if you restate the limit, from 8 digits to a value range. If num1 is less than zero, or greater than 255, it's not correct. You do know the user could blow up your program by simply entering something other than a binary value? Like "2' How is that different than entering a value out of the range you tell him? If you need to catch the one case, you should catch the other. For that you need try/catch. Instead of writing a function that does nothing more complex than a "+" operator, why not write one that accepts a string from the user, try to convert it, range check it, catch any exceptions, and loop till a valid value is encountered. -- DaveA From alan.gauld at btinternet.com Sat Jan 12 23:48:50 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Jan 2013 22:48:50 +0000 Subject: [Tutor] Adding Binary In-Reply-To: References: Message-ID: On 12/01/13 20:43, Ali Raza Ghasemi wrote: > I am making a program that adds binary numbers together. The program has > to accept two binary values (up to 8 binary digits) and output their > total in binary. The output should not contain any leading zeros. The first thing to realize is that all numbers in a computer are binary. Its the repressentation of them on screen that determines whether they are in decimal, hex or binary format. Display is a string function. Addition is a numeric function so you are going to have to translate between the two. And its probably best if your program separates the two concepts. > I have a problem in that I don't know how to limit the number digits to > 8 as it accepts however many digits you enter This is presumably an exercise somewhere since we had an identical request earlier. And I ask the same question, why would you want to restrict the length, its a bizarre requirement. But since I assume its part of the problem spec I'll ignore that... > to ignore anything other than 8-bit 0s and 1s. OK, that's an extra wrinkle we didn't have last time but its a valid thing to check. > Here is my code: And here is a problem, you seem to have posted in HTML and thats lost all the formatting so we don't know how your code looks. Pleae post in plain text to the list. Especially because formatting is critical in Python... But your first post format is visible ok so I'll use that for reference... > def add_binary_numbers(num1, num2): > while True: > return num1 + num2 > if len(str(num1)) > 8: > print("Please enter an 8 bit binary number") > continue Because the return ends the function the lines after that are *never* executed. You probably want the return at the end of the function after doing all the checks. And you probably don't want the checks inside the function, its better to keep a function that adds to just doing addition. Lets assume you do swap them round the next problem is that str() will convert to decimal not binary. So you really want to use bin() there. And bin will add a '0b' prefix so your len() needs to check for 10 not 8 characters. Finally calling continue repeats the loop but since you don't change anything - nowhere to enter a new number it just repeats forever. So a bit of a rethink of the logic needed there. > num1 = int(input('please enter the first 8 bit binary number: '),2) > num2 = int(input('please enter the second 8 bit binary number: '),2) This is fine except by converting the numbers straight away you miss anb opportunity to check the user input. And its always best to validate input as soon as possible. So i suggest just read the string and check the length there and then. Then after checking convert to int() That way you don't need the check inside the function. Finally the int(n,2) won't convert if there are non 1/0 characters in the string so you can simply catch an error in int() to ensure you get valid 1s and 0s. >>> int('1213',2) Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 2: '1213' HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wayne at waynewerner.com Sun Jan 13 05:35:16 2013 From: wayne at waynewerner.com (Wayne Werner) Date: Sat, 12 Jan 2013 22:35:16 -0600 (CST) Subject: [Tutor] running multiple versions of python In-Reply-To: References: Message-ID: On Thu, 10 Jan 2013, Fowler, Trent wrote: > I am running Windows 7 and I've installed two versions of python, 3.3 and 2.7. Python 3.3 was the first version I installed and I was able to run scripts from the desktop (not the command line). I installed python 2.7 so that I could get numpy, scipy, and matplotlib down the road, but I found that all the scripts on my desktop defaulted to python 2.7. Since I coded in 3.3 this caused some issues. > > I was able to fix this by right clicking the script icon, browsing programs, navigating to the python 3.3 file in my C: drive, and selecting the idle inside that directory. But then I found I wasn't able to run those scripts with python 2.7 using the exact same procedure. > > Unfortunately I don't know command-line programming very much at all, and it seemed like most of what I've seen online is geared towards that as a solution. Ideally I'd like to specify which python I want to run a script from the desktop, or possibly while I'm editing the script. I basically have this same setup. To make things work for me, I do this: - Go to your Python 2 directory ( probably C:\Python2.7> ) and rename python.exe to python2.exe and pythonw.exe to pythonw2.exe - Make sure that both your Python 2 directory and Python 3 directories are on your path. You do this by opening the Start Menu and typing "Path" - then hit enter. You should have an environment variable called PATH - if not, create a new one. You'll want to make sure that you have the paths to Python 3 and 2 in there. Assuming you've got C:\Python3.3> and C:\Python2.7>, you'd want to have a path that contains C:\Python3.3;C:\Python2.7; Now if you run a python script from cmd or powershell you should be able to do: C:\some\path> python2 a_matplot_program.py HTH, Wayne From railroadcancellation at gmail.com Mon Jan 14 03:58:51 2013 From: railroadcancellation at gmail.com (what ever) Date: Sun, 13 Jan 2013 19:58:51 -0700 Subject: [Tutor] Installing Python Packages Message-ID: I'm new to programming and I'm having trouble understanding the way packaging works in Python. I've spent the past 0week reading up on the subject, and I have a general idea of how it all works, but this is still very frustrating for me. I want to install four packages. Their names are pip, distribute, nose, and virtualenv. The big question is: How would you recommend I install these packages on my system? I was also hoping you could explain Python packaging in general. If you can show me how to install these packages or point me in the right direction, it would be greatly appreciated! I am running OS X Leopard also known as OS 10.6.8 I am running Python 2.6.1 (python came pre-installed) Thank you! =D From paradox at pobox.com Mon Jan 14 04:58:17 2013 From: paradox at pobox.com (Paradox) Date: Mon, 14 Jan 2013 11:58:17 +0800 Subject: [Tutor] Installing Python Packages :p: In-Reply-To: References: Message-ID: <50F38259.8010904@pobox.com> On 01/14/2013 10:58 AM, what ever wrote: > I want to install four packages. Their names are pip, distribute, > nose, and virtualenv. > The big question is: How would you recommend I install these packages > on my system? > I was also hoping you could explain Python packaging in general. > I only recently discovered this article myself - wonderful for setting some of the basics to understand packaging and how the parts fit together. http://mirnazim.org/writings/python-ecosystem-introduction/ thomas From chigga101 at gmail.com Mon Jan 14 16:14:50 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Mon, 14 Jan 2013 15:14:50 +0000 Subject: [Tutor] unclear topic Message-ID: hey guys, this is not really a Python question. When ever im doing a tutorial, it could be pygame or some gui application, i usually find everything straight forward until the demonstration involves drawing. Then maths is applied and i can't follow along as easily. In the end by commenting out certain lines of code, i understand what each line is doing but the fact is im still faced with being very weak at drawing and working out the logic behind it. I also can't imagine if im designing a program and need to do drawings of my own how i would work out the calculations and be able to think for myself. The help im asking for is what do i need to study to be able to design my own programs that involve drawing? do i need to go off and learn maths? if so which type? some sort of geometry? or do i start studying some sort of physics? or does the answer lie within some framework/library python tutorial? on amazon ive seen: maths books physics book 2d engine physics books(box2d etc) game physics books - http://www.amazon.co.uk/Game-Physics-/dp/147103397X/ my other problem is i don't want to over do it. do i need to buy a game physics book, if all i want to do is understand how to implement my own calculations for complex objects etc? then again maybe that's not so bad. If you know your way around this stuff? what did you learn that gave you these skills? From ramit.prasad at jpmorgan.com Mon Jan 14 22:19:52 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 14 Jan 2013 21:19:52 +0000 Subject: [Tutor] unclear topic In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47418105351@SCACMX008.exchad.jpmchase.net> Matthew Ngaha wrote: > hey guys, this is not really a Python question. When ever im doing a > tutorial, it could be pygame or some gui application, i usually find > everything straight forward until the demonstration involves drawing. > Then maths is applied and i can't follow along as easily. In the end > by commenting out certain lines of code, i understand what each line > is doing but the fact is im still faced with being very weak at > drawing and working out the logic behind it. I also can't imagine if > im designing a program and need to do drawings of my own how i would > work out the calculations and be able to think for myself. The help im > asking for is what do i need to study to be able to design my own > programs that involve drawing? do i need to go off and learn maths? if > so which type? some sort of geometry? or do i start studying some sort > of physics? or does the answer lie within some framework/library > python tutorial? > > on amazon ive seen: > > maths books > physics book > 2d engine physics books(box2d etc) > game physics books - http://www.amazon.co.uk/Game-Physics-/dp/147103397X/ > > > my other problem is i don't want to over do it. do i need to buy a > game physics book, if all i want to do is understand how to implement > my own calculations for complex objects etc? then again maybe that's > not so bad. If you know your way around this stuff? what did you learn > that gave you these skills? You should at least have enough math knowledge to understand Cartesian coordinates systems. Once you think of things in terms of objects based on their the coordinate location (x, y, z) it becomes easier to place objects where you want them and move them. Some trigonometry/ algebra might also be helpful. I (personally) would not buy a game physics book unless you are looking to create a 3D game or a 2D game with an actual physics engine (e.g. World of Goo). Of course, this is based on my personal experience and education which may vastly vary from your own. Or, as they say "on them internets," YMMV. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From swordangel at gmail.com Tue Jan 15 02:53:31 2013 From: swordangel at gmail.com (Kal Sze) Date: Tue, 15 Jan 2013 09:53:31 +0800 Subject: [Tutor] unclear topic In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47418105351@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF47418105351@SCACMX008.exchad.jpmchase.net> Message-ID: On 15 January 2013 05:19, Prasad, Ramit wrote: > > Matthew Ngaha wrote: > > hey guys, this is not really a Python question. When ever im doing a > > tutorial, it could be pygame or some gui application, i usually find > > everything straight forward until the demonstration involves drawing. > > Then maths is applied and i can't follow along as easily. In the end > > by commenting out certain lines of code, i understand what each line > > is doing but the fact is im still faced with being very weak at > > drawing and working out the logic behind it. I also can't imagine if > > im designing a program and need to do drawings of my own how i would > > work out the calculations and be able to think for myself. The help im > > asking for is what do i need to study to be able to design my own > > programs that involve drawing? do i need to go off and learn maths? if > > so which type? some sort of geometry? or do i start studying some sort > > of physics? or does the answer lie within some framework/library > > python tutorial? > > > > on amazon ive seen: > > > > maths books > > physics book > > 2d engine physics books(box2d etc) > > game physics books - http://www.amazon.co.uk/Game-Physics-/dp/147103397X/ > > > > > > my other problem is i don't want to over do it. do i need to buy a > > game physics book, if all i want to do is understand how to implement > > my own calculations for complex objects etc? then again maybe that's > > not so bad. If you know your way around this stuff? what did you learn > > that gave you these skills? > > You should at least have enough math knowledge to understand Cartesian > coordinates systems. Once you think of things in terms of objects > based on their the coordinate location (x, y, z) it becomes easier > to place objects where you want them and move them. Some trigonometry/ > algebra might also be helpful. > > I (personally) would not buy a game physics book unless you are > looking to create a 3D game or a 2D game with an actual physics engine > (e.g. World of Goo). Of course, this is based on my personal > experience and education which may vastly vary from your own. Or, > as they say "on them internets," YMMV. > > > ~Ramit > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Hi Matthew, Knowledge of Lineage Algebra is also invaluable. It forms the basis for geometric transformations in 2D and 3D. ~Kal From doanviettrung at gmail.com Tue Jan 15 04:14:24 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Tue, 15 Jan 2013 14:14:24 +1100 Subject: [Tutor] Why doesn't line n execute before line n+1? Message-ID: Dear tutors In learning about the __call__ magic method, in the code below I deliberately omitted __call__ and, as expected, I got the error message "TypeError: 'Test' object is not callable". But I am surprised that the print statement was not executed, even though the interpreter sees it first. Why is that? I thought that the Python interpreter executes line by line. That is, in the code below,: -First, it executes the class definition because these 2 lines are what it sees first -Second, it creates an instance of the class Test, called test -Third, it executes the print statement -Only then would it encounter the error of calling the instance as if it were callable class Test(object): pass test = Test() print "I am puzzled. Why isn't this line printed?" test() Making the puzzle worse for me, when I tried adding another print statement before the test = Test() line, the interpreter behaved as I expected! Trung -------------- next part -------------- An HTML attachment was scrubbed... URL: From msirenef at lightbird.net Tue Jan 15 04:33:03 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Mon, 14 Jan 2013 22:33:03 -0500 Subject: [Tutor] Why doesn't line n execute before line n+1? In-Reply-To: References: Message-ID: <50F4CDEF.9070304@lightbird.net> On Mon 14 Jan 2013 10:14:24 PM EST, DoanVietTrungAtGmail wrote: > Dear tutors > > In learning about the __call__ magic method, in the code below I > deliberately omitted __call__ and, as expected, I got the error > message "TypeError: 'Test' object is not callable". But I am surprised > that the print statement was not executed, even though the interpreter > sees it first. Why is that? > > I thought that the Python interpreter executes line by line. That is, > in the code below,: > -First, it executes the class definition because these 2 lines are > what it sees first > -Second, it creates an instance of the class Test, called test > -Third, it executes the print statement > -Only then would it encounter the error of calling the instance as if > it were callable > > class Test(object): > pass > test = Test() > print "I am puzzled. Why isn't this line printed?" > test() > > Making the puzzle worse for me, when I tried adding another print > statement before the test = Test() line, the interpreter behaved as I > expected! > > Trung > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor It does print the line for both in 2.7 and 3.3. - mitya -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From doanviettrung at gmail.com Tue Jan 15 04:54:34 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Tue, 15 Jan 2013 14:54:34 +1100 Subject: [Tutor] Why doesn't line n execute before line n+1? In-Reply-To: <50F4CDEF.9070304@lightbird.net> References: <50F4CDEF.9070304@lightbird.net> Message-ID: Yes you are right, it was printed. I think my eyes are tired. I left the PC, came back, and saw your reply plus the printed line. Thanks Mitya, and I apologise to everyone about false alarm! The answer of 42 was staring at me and I didn't see it. Trung On Tue, Jan 15, 2013 at 2:33 PM, Mitya Sirenef wrote: > On Mon 14 Jan 2013 10:14:24 PM EST, DoanVietTrungAtGmail wrote: > >> Dear tutors >> >> In learning about the __call__ magic method, in the code below I >> deliberately omitted __call__ and, as expected, I got the error >> message "TypeError: 'Test' object is not callable". But I am surprised >> that the print statement was not executed, even though the interpreter >> sees it first. Why is that? >> >> I thought that the Python interpreter executes line by line. That is, >> in the code below,: >> -First, it executes the class definition because these 2 lines are >> what it sees first >> -Second, it creates an instance of the class Test, called test >> -Third, it executes the print statement >> -Only then would it encounter the error of calling the instance as if >> it were callable >> >> class Test(object): >> pass >> test = Test() >> print "I am puzzled. Why isn't this line printed?" >> test() >> >> Making the puzzle worse for me, when I tried adding another print >> statement before the test = Test() line, the interpreter behaved as I >> expected! >> >> Trung >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > It does print the line for both in 2.7 and 3.3. - mitya > > > -- > Lark's Tongue Guide to Python: http://lightbird.net/larks/ > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From adel.afzal at gmail.com Sun Jan 13 17:10:17 2013 From: adel.afzal at gmail.com (Adel Afzal) Date: Sun, 13 Jan 2013 11:10:17 -0500 Subject: [Tutor] new user question Message-ID: <50F2DC69.5050203@gmail.com> Hi, I am new to Python, and my interest in learning is to make a Python script that can do something like what I describe below. Could you please provide some advice, or direct me to some resources that may help me along in this process? Lets say there are three pages: http://bob.com/dogs.html http://bob.com/cats.html http://bob.com/birds.html contains the text "dogs chase cats" contains the text "cats chase birds" contains the text "birds don't bother anyone" I'd like to know how to search the content of those three pages for the string "cats" in the text body. I'd like to then output the URLs, whose html files contain "cats", as a plain text list. Like this: : http://bob.com/dogs.html http://bob.com/cats.html Kind regards, Adel adel.afzal at gmail.com From ialectum at gmail.com Sun Jan 13 18:36:26 2013 From: ialectum at gmail.com (-) Date: Sun, 13 Jan 2013 12:36:26 -0500 Subject: [Tutor] UnicodeWarning: Comparing String Message-ID: <50F2F09A.7010502@gmail.com> Hi, I am trying to check if a Unicode string matches data from an Easygui "enterbox". I spent one hour looking online how to solve this problem and I'm still stuck because I don't understand all of the explanations I find. Lots of trial and error didn't help either. I use Python 2.5.1. ===This is the error message:=== > UnicodeWarning: Unicode equal comparison failed to convert both > arguments to Unicode - interpreting them as being unequal I do understand that everything has to be in Unicode for my code to work, but I do not know how to properly change my code. ===This is my code:=== > # coding: iso-8859-1 > > from easygui import * > import sys > > good_answer = "puret?" # notice the accute accent > > answer_given = enterbox("Type your answer!\n\nHint: 'puret?'") > > if answer_given == good_answer: > msgbox("Correct! The answer is 'puret?'") > else: > msgbox("Bug!") Thank you in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: From msarro at gmail.com Thu Jan 10 16:21:53 2013 From: msarro at gmail.com (Matty Sarro) Date: Thu, 10 Jan 2013 10:21:53 -0500 Subject: [Tutor] How to run multiline shell command within python In-Reply-To: <50EECF75.5020400@gmail.com> References: <50EE5934.7090609@gmail.com> <50EECF75.5020400@gmail.com> Message-ID: Have you looked a the pexpect class? It works like gangbusters, especially if you're trying to run something with an interactive shell. http://www.noah.org/wiki/pexpect On Thu, Jan 10, 2013 at 9:25 AM, Karim wrote: > On 10/01/2013 09:31, Hugo Arts wrote: > > On Thu, Jan 10, 2013 at 7:01 AM, Karim wrote: > >> >> >> Hello all, >> >> I want to run multiline shell command within python without using a >> command file but directly execute several lines of shell. >> I already use *subprocess.checkoutput("csh -f my_file.csh".split())* but >> I want to know if it is posssible to avoid making file and execute >> shell lines of code directly. >> >> > Yes, this is very possible. Specify shell=True as an argument and you > can do anything you can do in a shell: > > >>> commands = """echo hello > ... echo hello | wc -l > ... ps aux | grep python""" > >>> b = subprocess.check_output(commands, shell=True) > >>> print(b.decode('ascii')) > hello > 1 > hugo 1255 1.0 0.6 777316 49924 ? Sl 09:14 0:08 > /usr/bin/python2 /usr/bi > hugo 6529 0.0 0.0 42408 7196 pts/0 S+ 09:23 0:00 python > hugo 6559 0.0 0.0 10656 1128 pts/0 S+ 09:28 0:00 grep > python > > >>> > > watch out though, accepting user input into the commands variable will > lead to shell injection, which can be a dangerous security vulnerability. > > HTH, > Hugo > > > Many thanks Hugo. It makes my day! > In my case there are no possibilities for shell injection. It is internal > to a class. > > Regards > Karim > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Tue Jan 15 23:26:55 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 15 Jan 2013 22:26:55 +0000 Subject: [Tutor] UnicodeWarning: Comparing String In-Reply-To: <50F2F09A.7010502@gmail.com> References: <50F2F09A.7010502@gmail.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF4741811028E@SCACMX008.exchad.jpmchase.net> ialectum at gmail.com wrote: > Hi, > > I am trying to check if a Unicode string matches data from an Easygui "enterbox". I spent one hour looking > online how to solve this problem and I'm still stuck because I don't understand all of the explanations I find. > Lots of trial and error didn't help either. > > I use Python 2.5.1. > > ===This is the error message:=== > > > UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as > being unequal > > I do understand that everything has to be in Unicode for my code to work, but I do not know how to properly > change my code. That is not the full text of the error message. The full text includes a stack trace and should always be included verbatim. Copy and paste rather than retyping as accuracy of the message is important in helping you. > > ===This is my code:=== > > > # coding: iso-8859-1 > > from easygui import * > import sys > > good_answer = "puret?"? # notice the accute accent > > answer_given = enterbox("Type your answer!\n\nHint: 'puret?'") If good_answer is always manually defined (rather than being retrieved from somewhere, you can just manually set it to Unicode by prefixing the string with a 'u'. good_answer = u'puret?' # acute accent and now Unicode! Otherwise you will have to use one of the below lines. good_answer.decode() # converts to Unicode. # answer_given.encode() # converts from Unicode to format > > if answer_given == good_answer: > ??? msgbox("Correct! The answer is 'puret?'") > else: > ??? msgbox("Bug!") > > Thank you in advance! Unicode is fairly complex, but maybe this[0] will help if you run into problems (or just come back to the list). You can find the list of encoding formats (called codecs) here[1]. [0] http://docs.python.org/howto/unicode.html [1] http://docs.python.org/2/library/codecs.html#standard-encodings Please do not post in HTML or with a colored background. This list prefers the usage of plain text emails as HTML can remove indentation and since Python's indentation is significant it makes it much more difficult to help you. Also, top posting discouraged in favor of either bottom or in-line posting. Thanks! ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Tue Jan 15 23:56:38 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Jan 2013 22:56:38 +0000 Subject: [Tutor] new user question In-Reply-To: <50F2DC69.5050203@gmail.com> References: <50F2DC69.5050203@gmail.com> Message-ID: On 13/01/13 16:10, Adel Afzal wrote: > contains the text "dogs chase cats" > contains the text "cats chase birds" > contains the text "birds don't bother anyone" > > I'd like to know how to search the content of those three pages for the > string "cats" in the text body. Look at the urllib modules in the standard library. Also Beautiful Soup is a third part module that many find useful for reading HTML, especially if it is not cleanly formatted. That assumes that although new to python you are familiar with HTML and parsing in general. If not then you may need more hand holding after reading the docs. If so come back with some specific questions so we can gauge your level of understanding and respond accordingly. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From rohit_medi at hotmail.com Wed Jan 16 00:12:24 2013 From: rohit_medi at hotmail.com (Rohit Mediratta) Date: Tue, 15 Jan 2013 15:12:24 -0800 Subject: [Tutor] Assigning multi line value to a variable Message-ID: Hi, I am using Centos 6.3 and python 2.6.6. When I try to assign a variables value inside a multiple line message, it does not work. >>>cardName = "ActualCardName" >>>data = """ """ >>> print data I would like %cardName to be replaced by "actualCardName". As you can see I am trying to use XML and therefore I will have several such replacements that I will need to do. If someone can suggest a clean way for me to achieve my goal, that would be great. Please note, my input is going to be several lines long. thanks, Rohit -------------- next part -------------- An HTML attachment was scrubbed... URL: From etanes.rm at gmail.com Wed Jan 16 00:40:24 2013 From: etanes.rm at gmail.com (Scurvy Scott) Date: Tue, 15 Jan 2013 15:40:24 -0800 Subject: [Tutor] Question regarding lists and manipulating items in lists. Message-ID: Hello guys, I'm using Ubuntu 12.10 and Python 2.7 right now. I'm working on code using the Mingus module but this question isn't specific to this module, per se. What I'm trying to do is to generate the fibonacci numbers up to a given N and then do modulo 12 on each number in order to create a list of numbers for the Mingus module to convert to notes. What I would like to do is store each note created in a different element in a list so that I can later manipulate it, say by removing certain note letters from the list at will. That way the scales created by the program can become more useful, for example I could remove all notes that aren't present in say a Harmonic Minor scale, and only keep the list items that do exist in that scale in a given key. That way it becomes, in a way, like the computer is writing your guitar solos! Pretty neat I think. Anyways, the problem I'm having is I'm not really sure how to search a list for multiple elements and remove just those elements. Below is my code so far, and information y'all could provide would be appreciated. Thanks. import mingus.core.notes as notes #fibonacci def fib(num1,num2): a, b = 0, 1 for i in xrange(num1,num2): c = b % 12 #modulo 12 on each generated fibonacci number a_list= [notes.int_to_note(c)] #using Mingus to translate the Fib mod12 numbers into notes and then (I think) storing each one as an element in a list? a, b = b, a+b #this is just the algorithm for the fibonacci numbers -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Wed Jan 16 00:45:16 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 15 Jan 2013 23:45:16 +0000 Subject: [Tutor] Assigning multi line value to a variable In-Reply-To: References: Message-ID: On 15 January 2013 23:12, Rohit Mediratta wrote: > Hi, > I am using Centos 6.3 and python 2.6.6. > > When I try to assign a variables value inside a multiple line message, it > does not work. > >>>>cardName = "ActualCardName" >>>>data = """ > """ >>>> print data > > > > > I would like %cardName to be replaced by "actualCardName". As you can see I > am trying to use XML and therefore I will have several such replacements > that I will need to do. How about this? >>> data = """ ... """ >>> >>> print data >>> print data % {'cardName':'actualCardName'} Oscar From steve at pearwood.info Wed Jan 16 00:49:36 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 16 Jan 2013 10:49:36 +1100 Subject: [Tutor] Assigning multi line value to a variable In-Reply-To: References: Message-ID: <50F5EB10.1020405@pearwood.info> On 16/01/13 10:12, Rohit Mediratta wrote: > > Hi, > I am using Centos 6.3 and python 2.6.6. > > When I try to assign a variables value inside a multiple line message, it does not work. > >>>> cardName = "ActualCardName" >>>> data = """ > """ >>>> print data > > > > > I would like %cardName to be replaced by "actualCardName". As you can see > I am trying to use XML and therefore I will have several such replacements >that I will need to do. The error you show has nothing to do with "multiple line message", since it also doesn't work with a single line message: py> x = "Hello" py> msg = "%x" py> print msg %x The way to fix this is the same regardless of whether the message is one line or a million lines. Python does not automatically substitute variables into strings, since that is a bad idea. However you can tell Python to substitute any values you like, using the % operator and string interpolation: py> a = "spam" py> b = "eggs" py> msg = "Breakfast today is %s and %s." py> print msg % (a, b) Breakfast today is spam and eggs. String interpolation codes include %s for strings, %d for integers, and %f for floats (among others). You can also name the interpolation codes instead of substituting them by position: py> values = {"bird": "parrot", "colour": "green"} py> msg = "The %(colour)s %(bird)s ate the fruit." py> print msg % values The green parrot ate the fruit. This leads to a clever trick: if you name the interpolation codes with the variable names you want, you can get the values of variables using the locals() function: py> a = 42 py> b = "Hello World" py> msg = "My variables include %(a)s and %(b)s." py> print msg % locals() My variables include 42 and Hello World. More information about the string interpolation can be read here: http://docs.python.org/2/library/stdtypes.html#string-formatting-operations If you are familiar with C, you should find this very familiar. Other alternatives include the string format method, and string templates: http://docs.python.org/2/library/stdtypes.html#str.format http://docs.python.org/2/library/string.html#template-strings For example: py> import string py> msg = string.Template("My variables include $a and $b but not $c.") py> print msg.safe_substitute(locals()) My variables include 42 and Hello World but not $c. -- Steven From oscar.j.benjamin at gmail.com Wed Jan 16 00:50:56 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 15 Jan 2013 23:50:56 +0000 Subject: [Tutor] Question regarding lists and manipulating items in lists. In-Reply-To: References: Message-ID: On 15 January 2013 23:40, Scurvy Scott wrote: [SNIP] > > Anyways, the problem I'm having is I'm not really sure how to search a list > for multiple elements and remove just those elements. Below is my code so > far, and information y'all could provide would be appreciated. Thanks. Perhaps you'd like to use a list comprehension to filter out the values you are interested in: >>> my_list = [1,4,12,3,5,2,1,45,6,32] >>> my_filtered_list = [x for x in my_list if x%2] # only the odd numbers >>> print my_filtered_list [1, 3, 5, 1, 45] > > import mingus.core.notes as notes > #fibonacci > def fib(num1,num2): > a, b = 0, 1 > for i in xrange(num1,num2): > c = b % 12 #modulo 12 on each generated fibonacci number > a_list= [notes.int_to_note(c)] #using Mingus to translate the Fib mod12 > numbers into notes and then (I think) storing each one as an element in a > list? > a, b = b, a+b #this is just the algorithm for the fibonacci numbers Please post in plain-text rather than html as it screws up the code formatting (see above). Oscar From ramit.prasad at jpmorgan.com Wed Jan 16 00:30:07 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 15 Jan 2013 23:30:07 +0000 Subject: [Tutor] Assigning multi line value to a variable In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47418110565@SCACMX008.exchad.jpmchase.net> Rohit Mediratta wrote: > > Hi, > ?? I am using Centos 6.3 and python 2.6.6. > > When I try to assign a variables value inside a multiple line message, it does not work. > > >>>cardName = "ActualCardName" > >>>data = """ > ??????? """ > >>> print data > ? > ??????? > > > I would like %cardName to be replaced by "actualCardName". As you can see I am trying to use XML and therefore I > will have several such replacements that I will need to do. > data = """ """.format( cardName ) See here for more information on formatting syntax. http://docs.python.org/2/library/string.html#formatstrings > > If someone can suggest a clean way for me to achieve my goal, that would be great. > > Please note, my input is going to be several lines long. > > thanks, > Rohit ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From oscar.j.benjamin at gmail.com Wed Jan 16 01:00:39 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 16 Jan 2013 00:00:39 +0000 Subject: [Tutor] Question regarding lists and manipulating items in lists. In-Reply-To: References: Message-ID: On 15 January 2013 23:53, Scurvy Scott wrote: >> > Anyways, the problem I'm having is I'm not really sure how to search a list >> > for multiple elements and remove just those elements. Below is my code so >> > far, and information y'all could provide would be appreciated. Thanks. >> [SNIP] > > What I meant to say is, I want to be able to search the generated list > for a specific set of strings so like > > list = ['a','b','c','d','e','f','g'] > search = ['b','d','g'] > list.del[search] How about: new_list = [element for element in list if element not in search] (It would be more efficient to use a set but it's not strictly necessary) Oscar From steve at pearwood.info Wed Jan 16 01:01:42 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 16 Jan 2013 11:01:42 +1100 Subject: [Tutor] Question regarding lists and manipulating items in lists. In-Reply-To: References: Message-ID: <50F5EDE6.3070009@pearwood.info> On 16/01/13 10:40, Scurvy Scott wrote: [...] > Anyways, the problem I'm having is I'm not really sure how to search a list > for multiple elements and remove just those elements. Below is my code so > far, and information y'all could provide would be appreciated. Thanks. Actually, your problem so far is that you aren't even producing a list of elements at all, you keep creating a *single* element, then throwing it away when you generate the next Fibonacci number. Also, you, or more likely Gmail, lost the indentation in your code, so I'm going to have to guess what you intended rather than what you have. That's because you are sending HTML email, which eats spaces. > import mingus.core.notes as notes > #fibonacci > def fib(num1,num2): > a, b = 0, 1 > for i in xrange(num1,num2): > c = b % 12 #modulo 12 on each generated fibonacci number > a_list= [notes.int_to_note(c)] #using Mingus to translate the Fib mod12 > numbers into notes and then (I think) storing each one as an element in a > list? > a, b = b, a+b #this is just the algorithm for the fibonacci numbers Firstly, I recommend that you follow the principle "separation of concerns". Keep a separate function for each part of the problem: * generate Fibonacci numbers; * turn them into notes; So here I extract out of your code (untested!) a generator which produces an infinite series of Fibonacci numbers, one at a time: def fib(): a, b = 0, 1 while True: yield b a, b = b, a+b This is untested, I may have got it wrong. Next, a function to generate notes from those Fibonacci numbers: def make_notes(num_notes): it = fib() notes = [] # start with an empty list for i in range(num_notes): n = next(it) % 12 # get the next Fibonacci number, modulo 12 notes.append(notes.int_to_note(n)) return notes That returns a list of notes. Does that help? Start with that, and see how you go. -- Steven From etanes.rm at gmail.com Wed Jan 16 01:23:27 2013 From: etanes.rm at gmail.com (Scurvy Scott) Date: Tue, 15 Jan 2013 16:23:27 -0800 Subject: [Tutor] Question regarding lists and manipulating items in lists. In-Reply-To: <50F5EDE6.3070009@pearwood.info> References: <50F5EDE6.3070009@pearwood.info> Message-ID: On Tue, Jan 15, 2013 at 4:01 PM, Steven D'Aprano wrote: > On 16/01/13 10:40, Scurvy Scott wrote: > [...] > >> Anyways, the problem I'm having is I'm not really sure how to search a >> list >> for multiple elements and remove just those elements. Below is my code so >> far, and information y'all could provide would be appreciated. Thanks. > > > Actually, your problem so far is that you aren't even producing a list of > elements at all, you keep creating a *single* element, then throwing it > away when you generate the next Fibonacci number. > > Also, you, or more likely Gmail, lost the indentation in your code, so I'm > going to have to guess what you intended rather than what you have. That's > because you are sending HTML email, which eats spaces. > > > >> import mingus.core.notes as notes >> #fibonacci >> def fib(num1,num2): >> a, b = 0, 1 >> for i in xrange(num1,num2): >> c = b % 12 #modulo 12 on each generated fibonacci number >> a_list= [notes.int_to_note(c)] #using Mingus to translate the Fib mod12 >> numbers into notes and then (I think) storing each one as an element in a >> list? >> a, b = b, a+b #this is just the algorithm for the fibonacci numbers > > > > Firstly, I recommend that you follow the principle "separation of concerns". > Keep a separate function for each part of the problem: > > * generate Fibonacci numbers; > * turn them into notes; > > > So here I extract out of your code (untested!) a generator which produces > an infinite series of Fibonacci numbers, one at a time: > > def fib(): > > a, b = 0, 1 > while True: > yield b > > a, b = b, a+b > > > This is untested, I may have got it wrong. > > Next, a function to generate notes from those Fibonacci numbers: > > > def make_notes(num_notes): > it = fib() > notes = [] # start with an empty list > for i in range(num_notes): > n = next(it) % 12 # get the next Fibonacci number, modulo 12 > notes.append(notes.int_to_note(n)) > return notes > > > That returns a list of notes. > > > Does that help? Start with that, and see how you go. > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Steve After playing with your example I keep being told that list has no attribute int_to_note. I know what the problem is, I just don't know how to fix it. Also, I believe I've fixed my email so it will no longer be in HTML or anything fancy, just plain text. So right now my code is: import mingus.core.notes as notes #fibonacci def fib(): a, b = 0, 1 while True: yield b a, b = b, a+b def make_notes(num_notes): it = fib() notes = [] for i in range(num_notes): n = next(it) % 12 notes.append(notes.int_to_note(n)) return notes Which is pretty different from what my original code was. The generator function doesn't actually do anything when called, it just tells me it's a generator function and where it's located. And like I said the listing function doesn't want to comply with the module being called under append method. My code was working almost as I intended it to, it just wasn't creating a list properly of everything, which I didn't notice until after one of you guys mentioned it to me. Now I see it and I can sorta visualize what I'm supposed to do, but can't see what to do to fix it, if that makes any sense. From etanes.rm at gmail.com Wed Jan 16 01:49:51 2013 From: etanes.rm at gmail.com (Scurvy Scott) Date: Tue, 15 Jan 2013 16:49:51 -0800 Subject: [Tutor] Question regarding lists and manipulating items in lists. In-Reply-To: References: <50F5EDE6.3070009@pearwood.info> Message-ID: >> So here I extract out of your code (untested!) a generator which produces >> an infinite series of Fibonacci numbers, one at a time: >> >> def fib(): >> >> a, b = 0, 1 >> while True: >> yield b >> >> a, b = b, a+b >> >> >> This is untested, I may have got it wrong. >> >> Next, a function to generate notes from those Fibonacci numbers: >> >> >> def make_notes(num_notes): >> it = fib() >> notes = [] # start with an empty list >> for i in range(num_notes): >> n = next(it) % 12 # get the next Fibonacci number, modulo 12 >> notes.append(notes.int_to_note(n)) >> return notes >> >> >> That returns a list of notes. >> >> >> Does that help? Start with that, and see how you go. >> >> >> >> -- >> Steven >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > Steve > After playing with your example I keep being told that list has no > attribute int_to_note. I know what the problem is, I just don't know > how to fix it. > Also, I believe I've fixed my email so it will no longer be in HTML or > anything fancy, just plain text. > > So right now my code is: > > import mingus.core.notes as notes > > > #fibonacci > def fib(): > a, b = 0, 1 > while True: > yield b > a, b = b, a+b > > > def make_notes(num_notes): > it = fib() > notes = [] > for i in range(num_notes): > n = next(it) % 12 > notes.append(notes.int_to_note(n)) > return notes > > Which is pretty different from what my original code was. The > generator function doesn't actually do anything when called, it just > tells me it's a generator function and where it's located. And like I > said the listing function doesn't want to comply with the module being > called under append method. My code was working almost as I intended > it to, it just wasn't creating a list properly of everything, which I > didn't notice until after one of you guys mentioned it to me. Now I > see it and I can sorta visualize what I'm supposed to do, but can't > see what to do to fix it, if that makes any sense. On a hunch I've gone back to my original code, and feel I've almost got the list properly working. import mingus.core.notes as notes #fibonacci def fib(num1,num2): a, b = 0, 1 for i in xrange(num1,num2): c = b % 12 a_list= [] a, b = b, a+b while True: a_list.append(notes.int_to_note(c)) print a_list The problem here, which most of you will probably see immediately, is that all this does is infinitely append the same note to the list over and over again, which is not my intention. This is the closest I've gotten the code to actually working somewhat correctly as far as this list is concerned. Any hints would be helpful. I also think Oscars solution with searching the list for items in the 'search' list and then just removing them is the most elegant so far but I'm still open to anything you guys can show me, that's why you're the tutors and I came here to ask, right? I appreciate any information y'all can share. From ginarf at comcast.net Wed Jan 16 03:05:12 2013 From: ginarf at comcast.net (Gina) Date: Tue, 15 Jan 2013 20:05:12 -0600 Subject: [Tutor] reading from text files Message-ID: <50F60AD8.9010307@comcast.net> I have version 3 I am trying to read a text file ("the_file.txt") and then write a new file where the characters are in uppercase but i don't know how/where i should use the .upper I think i should use it where the ****** is, but i got errors when i tried that text_file = open("the_file.txt", "r") print(text_file.read()) text_file.close() new_file = open("the_file_upper.txt", "w+") new_file.write(*****) print(new_file.read()) new_file.close() From ginarf at comcast.net Wed Jan 16 03:31:38 2013 From: ginarf at comcast.net (Gina) Date: Tue, 15 Jan 2013 20:31:38 -0600 Subject: [Tutor] text files Message-ID: <50F6110A.4000505@comcast.net> I have version 3 I am trying to read a text file ("the_file.txt") and then write a new file where the characters are in uppercase but i don't know how/where i should use the .upper I think i should use it where the ****** is, but i got errors when i tried that text_file = open("the_file.txt", "r") print(text_file.read()) text_file.close() new_file = open("the_file_upper.txt", "w+") new_file.write(*****) print(new_file.read()) new_file.close() From d at davea.name Wed Jan 16 04:16:55 2013 From: d at davea.name (Dave Angel) Date: Tue, 15 Jan 2013 22:16:55 -0500 Subject: [Tutor] text files In-Reply-To: <50F6110A.4000505@comcast.net> References: <50F6110A.4000505@comcast.net> Message-ID: <50F61BA7.1090806@davea.name> On 01/15/2013 09:31 PM, Gina wrote: > I have version 3 > > I am trying to read a text file ("the_file.txt") and then write a new > file where the characters are in uppercase > but i don't know how/where i should use the .upper > I think i should use it where the ****** is, but i got errors when i > tried that > > > text_file = open("the_file.txt", "r") > print(text_file.read()) > text_file.close() > > new_file = open("the_file_upper.txt", "w+") > new_file.write(*****) > print(new_file.read()) > new_file.close() Did you have a good reason to send a second identical message after waiting only 25 minutes for a response from the first? How about if you must do so, say SOMETHING new in the message, and make it a reply to the first, so they get threaded together and have the same subject line. Anyway, your first problem is you never save any data from the first file. You're trying to do two very separate things in the same line. You read the data and immediately print it, without putting it any place you can reference it. Try something like: indata = text_file.read() print(indata) #optional Now, you can do something to indata before writing it to the output file. See how you get along with that. Another point: If you get an error, be explicit. Show us what you tried, and quote the exact error (including the traceback of course). Otherwise it's like making an anonymous call to the police: "Hello, somebody burglarized some house yesterday. Can you please tell me what they did with the toaster they broke?" And then hanging up immediately. BTW, thanks for sending a text message instead of html. -- DaveA From andipersti at gmail.com Wed Jan 16 07:20:15 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Wed, 16 Jan 2013 07:20:15 +0100 Subject: [Tutor] Question regarding lists and manipulating items in lists. In-Reply-To: References: <50F5EDE6.3070009@pearwood.info> Message-ID: <50F6469F.2030400@gmail.com> On 16.01.2013 01:23, Scurvy Scott wrote: > After playing with your example I keep being told that list has no > attribute int_to_note. I know what the problem is, I just don't know > how to fix it. [SNIP] > So right now my code is: > > import mingus.core.notes as notes ^^^^^ On this line you import your module and give it the name "notes". > def make_notes(num_notes): > it = fib() > notes = [] ^^^^^ Inside your function "notes" is a list. > for i in range(num_notes): > n = next(it) % 12 > notes.append(notes.int_to_note(n)) ^^^^^ Since "notes" is a list inside the function, Python tries to find the method "int_to_note" for a list and fails. But I think you want to use the function which is defined in your module. You have to either rename your module reference or your list. Bye, Andreas From alan.gauld at btinternet.com Wed Jan 16 12:38:45 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Jan 2013 11:38:45 +0000 Subject: [Tutor] text files In-Reply-To: <50F6110A.4000505@comcast.net> References: <50F6110A.4000505@comcast.net> Message-ID: On 16/01/13 02:31, Gina wrote: > new_file = open("the_file_upper.txt", "w+") In general consider the w+ file option to be for advanced use only. Either open it for reading or writing, don't try to do both at the same time. It's a bit like sitting on a tree branch with a saw to cut it down. If you cut on the wrong side you get hurt... > new_file.write(*****) > print(new_file.read()) This won't read anything because the file cursor is at the end of the string that you wrote (remember the branch illustration?) > new_file.close() And this just closes the file with a short line of asterisks in it... Not really what you want. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Wed Jan 16 14:57:49 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Jan 2013 00:57:49 +1100 Subject: [Tutor] Question regarding lists and manipulating items in lists. In-Reply-To: References: <50F5EDE6.3070009@pearwood.info> Message-ID: <50F6B1DD.5080006@pearwood.info> On 16/01/13 11:23, Scurvy Scott wrote: > After playing with your example I keep being told that list has no > attribute int_to_note. I know what the problem is, I just don't know > how to fix it. Oops, sorry about that, that is my fault. I did warn that my code was untested! If you know what the problem is, the solution should be obvious. Before reading ahead, try explaining to yourself what you think the problem actually is. If you do that, the answer should pop right out at you. Still need a hint? Okay, try this: "I need to convert the Fibonacci integers to musical notes, using the notes.int_to_note function imported from mingus.core. But inside Steven's make_notes function, he sets a local variable `notes = []`, which means that inside the function I cannot access the global notes.int_to_note." Or, a shorter version: "I have notes.int_to_note, which I need, but accessing it is blocked by the local variable notes which is a list." So the obvious solution is... ...rename the local variable `notes` to something else. def make_notes(num_notes): it = fib() music = [] # start with an empty list for i in range(num_notes): n = next(it) % 12 # get the next Fibonacci number, modulo 12 music.append(notes.int_to_note(n)) return music Still untested. > Also, I believe I've fixed my email so it will no longer be in HTML or > anything fancy, just plain text. Many thanks! More comments below. > So right now my code is: > > import mingus.core.notes as notes > > #fibonacci > def fib(): > a, b = 0, 1 > while True: > yield b > a, b = b, a+b I have now tested that, and it works fine: py> it = fib() py> [next(it) for i in range(15)] [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] Some people prefer to start the Fibonacci sequence with 0. That's an easy change to make: change the line "yield b" to "yield a". But Wolfram Mathworld and Mathematica start the Fibonacci sequence with 1, 1, 2, ... rather than 0, 1, 1, ... so that's good enough for me. http://mathworld.wolfram.com/FibonacciNumber.html > def make_notes(num_notes): > it = fib() > notes = [] > for i in range(num_notes): > n = next(it) % 12 > notes.append(notes.int_to_note(n)) > return notes > > Which is pretty different from what my original code was. Maybe so, but I'm teaching you a practice that will see you in good stead whenever you program: each function should do *one* thing. Think of programming as creating tools. You wouldn't try to create a single tool for cutting wood, driving screws into it, and painting it. Instead we have three tools: saw, screwdriver, paint brush. It's *much* easier to make three separate tools than a single tool that tries to do all three jobs. Likewise for your program. It is better to write separate functions to: * create the Fibonacci numbers; * turn them into musical notes; than to do both jobs in one function. Now in *this* case, the labour saved is relatively small. But it is a good habit to get into, and when you get to large, complex programs it becomes essential. > The > generator function doesn't actually do anything when called, it just > tells me it's a generator function and where it's located. If you look at how my code uses the generator function, you will see the correct way to use it. Here's another example: py> it = fib() py> n = next(it) py> while n < 100: ... print n ... n = next(it) ... 1 1 2 3 5 8 13 21 34 55 89 -- Steven From fomcl at yahoo.com Wed Jan 16 22:06:34 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 16 Jan 2013 13:06:34 -0800 (PST) Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently Message-ID: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> Hello, Is there a builtin function that can set LD_LIBRARY_PATH or equivalents platform-independently? It would be nice use such a function in a setup script. The code below illustrates what I mean, although it's entirely untested. import sys import os def setPath(loc): ??? """Set LD_LIBRARY_PATH and equivalents platform-independently""" ??? p = {"win": "PATH", ??????? ? ? "lin": "LD_LIBRARY_PATH", ??????????? "solaris": "LD_LIBRARY_PATH", ??????????? "aix": "LIBPATH", ??????????? "darwin": "DYLD_LIBRARY_PATH", ??????????? "hpux": "SHLIB_PATH"} ??? pf = sys.platform() ??? sep = ";" if pf.startswith("win") else ":" ??? try: ??????? os.environ[p[pf]] += (sep + loc) ??? except KeyError: ??????? print "Platform %s not supported" % pf ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? -------------- next part -------------- An HTML attachment was scrubbed... URL: From dotancohen at gmail.com Wed Jan 16 22:15:57 2013 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 16 Jan 2013 23:15:57 +0200 Subject: [Tutor] Json encode and decode on Puython 2.4 Message-ID: Hi all, I'm just getting into porting some PHP scripts to Python. One issue that I'm having is that the scripts need to run on a host with Python 2.4 that has neither the json nor simplejson packages available. I figure that I'll have to include the loads() and dumps() functions in my application. Where might I find the source for these two functions? What would be the best way to include them? Thanks. -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From 3n2solutions at gmail.com Wed Jan 16 22:22:17 2013 From: 3n2solutions at gmail.com (3n2 Solutions) Date: Wed, 16 Jan 2013 13:22:17 -0800 Subject: [Tutor] how to track an entry in a large text file Message-ID: Say I have a text file (example below) that has multiple records with the same format but not always the same number of lines. Each record is separated by the line that starts with ?Examining file? as in below example. If you notice, the 3D Val is not there for the second record. How do I report that the ?3D Val? is not present for that particular record ?8866W2310089.txt?? Thanks to Alan for his reply. Examining file: 5521W2310000.txt Duration : 0h : 59m First meas : week : 86 : 1721 Last meas : week : 89 : 1721 Min val : 15 Max val : 18 3D : 3600 100.0% summary Total Missed Rate epoch1 : 1378 0 0\1000 epoch2 : 2154 1 0\1000 Examining file: 8866W2310089.txt Duration : 0h : 59m First meas : week : 87 : 1721 Last meas : week : 84 : 1721 Min val : 16 Max val : 19 summary Total Missed Rate epoch1 : 1378 0 0\1000 epoch From ramit.prasad at jpmorgan.com Wed Jan 16 22:50:02 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 16 Jan 2013 21:50:02 +0000 Subject: [Tutor] Json encode and decode on Puython 2.4 In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474181123F4@SCACMX008.exchad.jpmchase.net> Dotan Cohen wrote: > > Hi all, I'm just getting into porting some PHP scripts to Python. One > issue that I'm having is that the scripts need to run on a host with > Python 2.4 that has neither the json nor simplejson packages > available. I figure that I'll have to include the loads() and dumps() > functions in my application. Where might I find the source for these > two functions? What would be the best way to include them? > > Thanks. > > -- > Dotan Cohen Python 2.4 is quite old and simplejson supports 2.5+. I can see a yield in the encoder code, so it is unlikely to be easy to modify and get working with 2.4. According to a stack overflow question you may want to look at older releases (example: 2.0.9/2.1) as being more 2.4 compatible. SimpleJson source: https://github.com/simplejson/simplejson Change the version in the link to see if PyPi has a different version. http://pypi.python.org/pypi/simplejson/2.1.0 I have no idea if you can get the json library to work with 2.4. I did not seen anything in my cursory glance that suggested it would not. http://hg.python.org/cpython-fullhistory/file/8e0b617c6c22/Lib/json/ You may want to see if you can get a newer python installed on the machine. You probably want it alt-installed so you are not replacing the system expected Python. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From abhishek.vit at gmail.com Wed Jan 16 22:54:55 2013 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Wed, 16 Jan 2013 13:54:55 -0800 Subject: [Tutor] learning to program in cython Message-ID: Hi Guys With the help of an awesome python community I have been able to pick up the language and now willing to explore other cool extensions of it. I routinely have large loops which could be ported to cython for speed. However I have never written a single line of cython code. Any pointers on getting started. A tutorial text or video would be of great help. Thanks! -Abhi -------------- next part -------------- An HTML attachment was scrubbed... URL: From dotancohen at gmail.com Wed Jan 16 22:58:00 2013 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 16 Jan 2013 23:58:00 +0200 Subject: [Tutor] Json encode and decode on Puython 2.4 In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474181123F4@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF474181123F4@SCACMX008.exchad.jpmchase.net> Message-ID: On Wed, Jan 16, 2013 at 11:50 PM, Prasad, Ramit wrote: > Python 2.4 is quite old and simplejson supports 2.5+. I can see a > yield in the encoder code, so it is unlikely to be easy to modify > and get working with 2.4. According to a stack overflow question > you may want to look at older releases (example: 2.0.9/2.1) as being > more 2.4 compatible. > SimpleJson source: https://github.com/simplejson/simplejson > Change the version in the link to see if PyPi has a different version. > http://pypi.python.org/pypi/simplejson/2.1.0 > > I have no idea if you can get the json library to work with 2.4. > I did not seen anything in my cursory glance that suggested it would > not. > http://hg.python.org/cpython-fullhistory/file/8e0b617c6c22/Lib/json/ > > You may want to see if you can get a newer python installed on > the machine. You probably want it alt-installed so you are not > replacing the system expected Python. > > Thanks, Ramit. I'm now trying to install an older simplejson with simple_install by defining the install directory since I don't have root on this machine. Unfortunately, installing a newer Python (or anything else needed by root) is not going to happen on this particular webhost. Thanks. -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From oscar.j.benjamin at gmail.com Thu Jan 17 00:03:54 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 16 Jan 2013 23:03:54 +0000 Subject: [Tutor] learning to program in cython In-Reply-To: References: Message-ID: On 16 January 2013 21:54, Abhishek Pratap wrote: > Hi Guys > > With the help of an awesome python community I have been able to pick up the > language and now willing to explore other cool extensions of it. Good work! > > I routinely have large loops which could be ported to cython for speed. > However I have never written a single line of cython code. Any pointers on > getting started. There are two reasons for using cython: 1) To interface directly with existing C libraries. 2) To speed up CPU-intensive code. It sounds like you're interested in case 2). However, not all loops benefit from cythonisation. Loosely cython is good when a) you're doing something that can be written in a small amount of efficient C code b) but the corresponding Python code involves a lot of repeated function calls or expression evaluations. If you're already familiar with C then you'll probably have some idea when a) and b) apply. I would say that a prerequisite for learning to speed up CPU-intensive code with cython would be learning to use the python profilers. In particular you should learn to use cProfile and timeit: http://docs.python.org/2/library/profile.html http://docs.python.org/2/library/timeit.html As with any optimisation it is important to study the performance of your code and identify bottlenecks first. It is also generally true that you should (at least) consider algorithmic optimisation before you consider using something like cython for micro-optimisation. One of the guiding principles in the design of the Python language is that big-O complexity is often more important than micro-optimisation. Similarly, you should normally try to optimise and benchmark your code in pure Python before attempting to improve on that with cython. > > A tutorial text or video would be of great help. Here is the official "basic tutorial" for cython: http://docs.cython.org/src/userguide/tutorial.html There are also lots of helpful people on the cython-users mailing list: https://groups.google.com/forum/?fromgroups#!forum/cython-users If you have a particular problem in mind that might benefit from cythonisation, then why not post (a shortened but complete version of) it here to see if anyone has any pointers about how to improve the performance with/without cython. Oscar From oscar.j.benjamin at gmail.com Thu Jan 17 00:14:43 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 16 Jan 2013 23:14:43 +0000 Subject: [Tutor] how to track an entry in a large text file In-Reply-To: References: Message-ID: On 16 January 2013 21:22, 3n2 Solutions <3n2solutions at gmail.com> wrote: > Say I have a text file (example below) that has multiple records with > the same format but not always the same number of lines. Each record > is separated by the line that starts with ?Examining file? as in below > example. If you notice, the 3D Val is not there for the second record. > How do I report that the ?3D Val? is not present for that particular > record ?8866W2310089.txt?? > Thanks to Alan for his reply. I don't follow what you mean by 'How do I report that the ?3D Val? is not present for that particular record ?8866W2310089.txt??' The obvious answer would be (assuming the filename is currently set to ?8866W2310089.txt?): print('3D Val not present in %s' % filename) I wonder if your actual question is: 1) How do I detect that it is not present? - check for a line starting with '3D' while reading the file. 2) How do I mark it is not being present in my data structure? - depends what kind of data structure you are using. A common idiom would be to simply use the value None as a place-holder for situations where the value is not supplied. 3) Something else... > > Examining file: 5521W2310000.txt > > Duration : 0h : 59m > First meas : week : 86 : 1721 > Last meas : week : 89 : 1721 > > Min val : 15 > Max val : 18 > 3D : 3600 100.0% > > summary Total Missed Rate > epoch1 : 1378 0 0\1000 > epoch2 : 2154 1 0\1000 > > > > Examining file: 8866W2310089.txt > > Duration : 0h : 59m > First meas : week : 87 : 1721 > Last meas : week : 84 : 1721 > > Min val : 16 > Max val : 19 > > summary Total Missed Rate > epoch1 : 1378 0 0\1000 > epoch Oscar From steve at pearwood.info Thu Jan 17 00:15:43 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Jan 2013 10:15:43 +1100 Subject: [Tutor] Json encode and decode on Puython 2.4 In-Reply-To: References: Message-ID: <50F7349F.6030900@pearwood.info> On 17/01/13 08:15, Dotan Cohen wrote: > Hi all, I'm just getting into porting some PHP scripts to Python. One > issue that I'm having is that the scripts need to run on a host with > Python 2.4 that has neither the json nor simplejson packages > available. I figure that I'll have to include the loads() and dumps() > functions in my application. Where might I find the source for these > two functions? What would be the best way to include them? Python 2.4 is no longer receiving security updates. If you're exposing a web app on the Internet using Python 2.4, it's just a matter of time before you're hacked. Time to change hosting companies, methinks. If it is a Centos or RedHat based Linux system, it will support simplejson. [steve at ando /]$ sudo yum install simplejson [sudo] password for steve: [...extremely long output deleted...] Installed: python-simplejson.i386 0:2.0.9-8.el5 Complete! [steve at ando /]$ python2.4 Python 2.4.3 (#1, Jun 18 2012, 08:55:31) [GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2 Type "help", "copyright", "credits" or "license" for more information. py> import simplejson py> print simplejson -- Steven From steve at pearwood.info Thu Jan 17 00:16:15 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Jan 2013 10:16:15 +1100 Subject: [Tutor] Json encode and decode on Puython 2.4 In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474181123F4@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF474181123F4@SCACMX008.exchad.jpmchase.net> Message-ID: <50F734BF.5010501@pearwood.info> On 17/01/13 08:50, Prasad, Ramit wrote: > Python 2.4 is quite old and simplejson supports 2.5+. I can see a > yield in the encoder code, so it is unlikely to be easy to modify > and get working with 2.4. Python 2.4 supports yield. -- Steven From ramit.prasad at jpmorgan.com Thu Jan 17 00:19:43 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 16 Jan 2013 23:19:43 +0000 Subject: [Tutor] Json encode and decode on Puython 2.4 In-Reply-To: <50F734BF.5010501@pearwood.info> References: <5B80DD153D7D744689F57F4FB69AF474181123F4@SCACMX008.exchad.jpmchase.net> <50F734BF.5010501@pearwood.info> Message-ID: <5B80DD153D7D744689F57F4FB69AF47418112742@SCACMX008.exchad.jpmchase.net> Steven D'Aprano wrote: > > On 17/01/13 08:50, Prasad, Ramit wrote: > > > Python 2.4 is quite old and simplejson supports 2.5+. I can see a > > yield in the encoder code, so it is unlikely to be easy to modify > > and get working with 2.4. > > Python 2.4 supports yield. Thanks for the correction; I did not realize it was added in 2.2/2.3. Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From msirenef at lightbird.net Thu Jan 17 00:32:30 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Wed, 16 Jan 2013 18:32:30 -0500 Subject: [Tutor] how to track an entry in a large text file In-Reply-To: References: Message-ID: <50F7388E.1020502@lightbird.net> On 01/16/2013 04:22 PM, 3n2 Solutions wrote: > Say I have a text file (example below) that has multiple records with > the same format but not always the same number of lines. Each record > is separated by the line that starts with ?Examining file? as in below > example. If you notice, the 3D Val is not there for the second record. > How do I report that the ?3D Val? is not present for that particular > record ?8866W2310089.txt?? > Thanks to Alan for his reply. > > > > Examining file: 5521W2310000.txt > > Duration : 0h : 59m > First meas : week : 86 : 1721 > Last meas : week : 89 : 1721 > > Min val : 15 > Max val : 18 > 3D : 3600 100.0% > > summary Total Missed Rate > epoch1 : 1378 0 0\1000 > epoch2 : 2154 1 0\1000 > > > > Examining file: 8866W2310089.txt > > Duration : 0h : 59m > First meas : week : 87 : 1721 > Last meas : week : 84 : 1721 > > Min val : 16 > Max val : 19 > > summary Total Missed Rate > epoch1 : 1378 0 0\1000 > epoch > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > If the file isn't very huge, you can split by "Examining file: ", then iterate over the list, check if '3D' is in the item; if it isn't, split the item by newlines and print first line. HTH, - mitya -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From alan.gauld at btinternet.com Thu Jan 17 01:05:22 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Jan 2013 00:05:22 +0000 Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On 16/01/13 21:06, Albert-Jan Roskam wrote: > Is there a builtin function that can set LD_LIBRARY_PATH or equivalents > platform-independently? No. But there is putenv() in the os module. But how well it works across OS I'm not sure. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Thu Jan 17 03:10:31 2013 From: d at davea.name (Dave Angel) Date: Wed, 16 Jan 2013 21:10:31 -0500 Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: <50F75D97.7060805@davea.name> On 01/16/2013 07:05 PM, Alan Gauld wrote: > On 16/01/13 21:06, Albert-Jan Roskam wrote: > >> Is there a builtin function that can set LD_LIBRARY_PATH or equivalents >> platform-independently? > > No. > But there is putenv() in the os module. > But how well it works across OS I'm not sure. > I don't recall enough about Windows to be sure whether putenv would work, but the environment variable Windows uses to search for DLL's is certainly not LD_LIBRARY_PATH -- DaveA From alan.gauld at btinternet.com Thu Jan 17 09:35:52 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Jan 2013 08:35:52 +0000 Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: <50F75D97.7060805@davea.name> References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> <50F75D97.7060805@davea.name> Message-ID: On 17/01/13 02:10, Dave Angel wrote: > I don't recall enough about Windows to be sure whether putenv would > work, but the environment variable Windows uses to search for DLL's is > certainly not LD_LIBRARY_PATH If you check the code Albert is actually using different variables per platform. For Windows he is using PATH... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Thu Jan 17 12:52:41 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 17 Jan 2013 03:52:41 -0800 (PST) Subject: [Tutor] learning to program in cython In-Reply-To: References: Message-ID: <1358423561.57878.YahooMailNeo@web163804.mail.gq1.yahoo.com> >> With the help of an awesome python community I have been able to pick up the >> language and now willing to explore other cool extensions of it. > >Good work! > >> >> I routinely have large loops which could be ported to cython for speed. >> However I have never written a single line of cython code. Any pointers on >> getting started. > >There are two reasons for using cython: >1) To interface directly with existing C libraries. >2) To speed up CPU-intensive code. > >It sounds like you're interested in case 2). However, not all loops >benefit from cythonisation. Loosely cython is good when >a) you're doing something that can be written in a small amount of >efficient C code >b) but the corresponding Python code involves a lot of repeated >function calls or expression evaluations. > >If you're already familiar with C then you'll probably have some idea >when a) and b) apply. I would say that a prerequisite for learning to >speed up CPU-intensive code with cython would be learning to use the >python profilers. In particular you should learn to use cProfile and >timeit: (and of course pstats) I recently used Cython for the first time and I found it surprisingly easy. The installation under Linux is easy, but seems to be not really trivial under Windows (I never tried installing it under windows though; I'd first try one of the unofficial binaries: http://www.lfd.uci.edu/~gohlke/pythonlibs/#cython). One gotcha that I only found out later: it is possible to generate an html report of your Cythonized code. The yellower the code is coloured, the more it might still benefit from speed improvements: http://stackoverflow.com/questions/11058933/cython-a-flag-to-generate-yellow-shaded-html-without-command-line It's pretty cool to use cProfile to make a Cython-Python comparison of the function you're trying to speed up. In my case it was 87 % faster IIRC (this difference was not only significant, but also relevent: a use case where this would save 15 minutes is totally realistic) . Yaay! Albert-Jan From fomcl at yahoo.com Thu Jan 17 13:14:35 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 17 Jan 2013 04:14:35 -0800 (PST) Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: <50F75D97.7060805@davea.name> References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> <50F75D97.7060805@davea.name> Message-ID: <1358424875.71193.YahooMailNeo@web163806.mail.gq1.yahoo.com> > Subject: Re: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently > > On 01/16/2013 07:05 PM, Alan Gauld wrote: >> On 16/01/13 21:06, Albert-Jan Roskam wrote: >> >>> Is there a builtin function that can set LD_LIBRARY_PATH or equivalents >>> platform-independently? >> >> No. >> But there is putenv() in the os module. >> But how well it works across OS I'm not sure. >> > > I don't recall enough about Windows to be sure whether putenv would > work, but the environment variable Windows uses to search for DLL's is > certainly not LD_LIBRARY_PATH Hi Alan, Dave, Thanks for your replies. os.putenv() may be easier than os.environ because, hopefully, it takes care of the OS-specific separators of the values (";" for Windows, ":" for Linux, others I don't know but I'd guess they're all ":").? Then again, this sentence from the Python page is a little worrying: "*If* the platform supports the putenv() function, ...". (emphasis added). But os.environ has its own problems: "On some platforms, including FreeBSD and Mac OS X, setting environ may cause memory leaks. Refer to the system documentation for putenv()." Hmmmm. As an alternative, I used os.chdir to tell the OS where to start looking for libraries, but somebody on this list (I forgot who) warned me that this could have nasty side effects. http://docs.python.org/2/library/os.html os.environ A mapping object representing the string environment. For example, environ['HOME'] is the pathname of your home directory (on some platforms), and is equivalent to getenv("HOME") in C. This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly. If the platform supports the putenv() function, this mapping may be used to modify the environment as well as query the environment. putenv() will be called automatically when the mapping is modified. Note. Calling putenv() directly does not change os.environ, so it?s better to modify os.environ. Note. On some platforms, including FreeBSD and Mac OS X, setting environ may cause memory leaks. Refer to the system documentation for putenv(). If putenv() is not provided, a modified copy of this mapping may be passed to the appropriate process-creation functions to cause child processes to use a modified environment. Regards, Albert-Jan From eryksun at gmail.com Thu Jan 17 15:21:35 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 17 Jan 2013 09:21:35 -0500 Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On Wed, Jan 16, 2013 at 4:06 PM, Albert-Jan Roskam wrote: > > Is there a builtin function that can set LD_LIBRARY_PATH or equivalents > platform-independently? It would be nice use such a function in a setup > script. Modifying LD_LIBRARY_PATH only affects child processes (ld.so caches the search path). In contrast, Windows evaluates the current PATH when searching for DLLs (other than SxS assemblies). What's the immediate goal here? For building an extension module with distutils you can use library_dirs and runtime_library_dirs (UNIX, embed an rpath). From eryksun at gmail.com Thu Jan 17 15:40:35 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 17 Jan 2013 09:40:35 -0500 Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: <1358424875.71193.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> <50F75D97.7060805@davea.name> <1358424875.71193.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On Thu, Jan 17, 2013 at 7:14 AM, Albert-Jan Roskam wrote: > > Thanks for your replies. os.putenv() may be easier than os.environ because, > hopefully, it takes care of the OS-specific separators of the values (";" > for Windows, ":" for Linux, others I don't know but I'd guess they're all > ":"). os.environ wraps the initial posix.environ dict and uses putenv/unsetenv to keep it consistent with the process: http://hg.python.org/cpython/file/70274d53c1dd/Lib/os.py#l391 convertenviron in posixmodule.c (module posix, nt, or os2) populates the initial dict: http://hg.python.org/cpython/file/70274d53c1dd/Modules/posixmodule.c#l442 For the path separator, use os.pathsep or os.path.pathsep: http://docs.python.org/2/library/os#os.pathsep From fomcl at yahoo.com Thu Jan 17 16:33:45 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 17 Jan 2013 07:33:45 -0800 (PST) Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: <1358436825.25405.YahooMailNeo@web163803.mail.gq1.yahoo.com> ---- Original Message ----- > From: eryksun > To: Albert-Jan Roskam > Cc: Python Mailing List > Sent: Thursday, January 17, 2013 3:21 PM > Subject: Re: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently > > On Wed, Jan 16, 2013 at 4:06 PM, Albert-Jan Roskam > wrote: >> >> Is there a builtin function that can set LD_LIBRARY_PATH or equivalents >> platform-independently? It would be nice use such a function in a setup >> script. > > Modifying LD_LIBRARY_PATH only affects child processes (ld.so caches > the search path). In contrast, Windows evaluates the current PATH when > searching for DLLs (other than SxS assemblies). What's the immediate > goal here? For building an extension module with distutils you can use > library_dirs and runtime_library_dirs (UNIX, embed an rpath) Hi Eryksun, The goal is to load the C libraries (dll, so, dylib, etc) that my program needs. Your suggestion about distutils seems very useful! I've also been checking distutils2, setuptools and distribute and I still wasn't sure which package to choose (distutils2.core doesn't seem to exist anymore, so I'll just try to use distutils). Anyway, I looked up your two suggestions about library_dirs and runtime_library_dirs. What is meant by "at link time"? (it might be that I don't understand this because English is not my mother tongue). Given your explanation, the "runtime_library_dirs" does not seem to be an option. Then your remark about rpath. Does this mean that the ELF header of the library itself is modified (I believe I read something about that on StackOverflow)? The libraries I am using are copyrighted (one can freely use them, but no reverse engineering, disentangling, etc). I am not sure whether adding an rpath will be copyright infringement. Logically, I'd say no, but I doubt whether logic applies in legal stuff. ;-) ?? library_dirs : [string] ?|????? list of directories to search for C/C++ libraries at link time ?|??? libraries : [string] ?|????? list of library names (not filenames or paths) to link against ?|??? runtime_library_dirs : [string] ?|????? list of directories to search for C/C++ libraries at run time ?|????? (for shared extensions, this is when the extension is loaded) Regards, Albert-Jan From alan.gauld at btinternet.com Thu Jan 17 19:10:29 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Jan 2013 18:10:29 +0000 Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: <1358424875.71193.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> <50F75D97.7060805@davea.name> <1358424875.71193.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On 17/01/13 12:14, Albert-Jan Roskam wrote: > > Thanks for your replies. os.putenv() may be easier than os.environ because, > hopefully, it takes care of the OS-specific separators of the values > (";" for Windows, ":" for Linux, others I don't know I wouldn't count on it. Support for changing environment variables on the fly is iffy in most languages and is not something I'd ever do lightly. The environment is something that usually should be set up when the user logs in to reflect their preferences, its not really polite of a program to try and alter the users environment... > Then again, this sentence from the Python page is a little worrying: > "*If* the platform supports the putenv() function, ...". Not all OS allow changes to the environment variables. Others only allow the value to be a fixed size allocated at startup and if you write more bytes than are already assigned you will overwrite the next value! The OS assumes that this stuff is set up once and not changed. putenv() should always be considered a platform specific bit of code. > As an alternative, I used os.chdir to tell the OS where to start > looking for libraries, but somebody on this list (I forgot who) > warned me that this could have nasty side effects. Again the user may expect to be in a certain directory so as a minimum you need to change back to where they were when you exit. The normal way to deal with local file locations is to have a resource file that's read when the program starts up - like .vimrc or .emacs Then if the file doesn't exist you either create it at install time or use default values and allow the user to override them. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Thu Jan 17 19:33:08 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 17 Jan 2013 18:33:08 +0000 Subject: [Tutor] learning to program in cython In-Reply-To: <1358423561.57878.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1358423561.57878.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: On 17 January 2013 11:52, Albert-Jan Roskam wrote: > > I recently used Cython for the first time and I found it surprisingly easy. The installation under Linux > is easy, but seems to be not really trivial under Windows (I never tried installing it under windows though; I'd first try one of the unofficial binaries: http://www.lfd.uci.edu/~gohlke/pythonlibs/#cython). I've never had a problem installing cython under Windows. Although, cython does require a Python-compatible C compiler. This can be (the right version of) MSVC or (with a little fiddling) mingw32. I use mingw32 and, although it is not officially supported by CPython I think it is officially supported by Cython. I have had problems getting the right C-compiler on Windows. In any case, once you have a C compiler installed it should be straightforward to install cython: 1) Get the archive from here: http://cython.org/#download 2) Extract it 3) python setup.py install If you have pip or easy_install then it's as easy as running 'pip install cython' or 'easy_install cython' in your terminal. Oscar From dotancohen at gmail.com Thu Jan 17 19:30:18 2013 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 17 Jan 2013 20:30:18 +0200 Subject: [Tutor] Json encode and decode on Puython 2.4 In-Reply-To: <50F7349F.6030900@pearwood.info> References: <50F7349F.6030900@pearwood.info> Message-ID: On Thu, Jan 17, 2013 at 1:15 AM, Steven D'Aprano wrote: > Python 2.4 is no longer receiving security updates. If you're exposing a > web app on the Internet using Python 2.4, it's just a matter of time > before you're hacked. > > Time to change hosting companies, methinks. > The time to get rid of this host has long passed, alas it is not my decision! In any case the only thing running on it are non-critical stuff used to test that the critical stuff hosted on a real server are working as intended. Nothing facing the bid bad web. Thanks. -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From steve at pearwood.info Thu Jan 17 23:50:05 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Jan 2013 09:50:05 +1100 Subject: [Tutor] Warning for users of the Python and Jython wiki Message-ID: <50F8801D.7030400@pearwood.info> Hello all, Some time recently, the wiki at http://wiki.python.org/ was hacked. The vandal who broke in deleted all the wiki data. However, it is possible that before destroying the data, he may have gained access to user passwords. If you had an account on the wiki, and use the same password elsewhere, then you should change that password immediately. In general, you should not use the same password for multiple systems, and naturally once a password has been (potentially) compromised, never use it, or trivial modifications of it, again. http://thehackernews.com/2013/01/official-debian-and-python-wiki-servers.html#_ -- Steven From eryksun at gmail.com Fri Jan 18 04:07:56 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 17 Jan 2013 22:07:56 -0500 Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: <1358436825.25405.YahooMailNeo@web163803.mail.gq1.yahoo.com> References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> <1358436825.25405.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: On Thu, Jan 17, 2013 at 10:33 AM, Albert-Jan Roskam wrote: > > The goal is to load the C libraries (dll, so, dylib, etc) that my program > needs. > > Anyway, I looked up your two suggestions about library_dirs and > runtime_library_dirs. What is meant by "at link time"? library_dirs adds search paths for the linker (e.g. ld) for finding shared libraries (.so) and static libraries (.a archives of relocatable object files). Linking to a shared library is handled by the runtime loader/linker (e.g. /lib/ld-linux.so.2). For Linux, ld.so searches the system-defined directories (/lib, /usr/lib, and those set by /etc/ld.so.conf), which are cached in /etc/ld.so.cache (created by ldconfig). This is where distutils runtime_library_dirs comes into play. For ELF it configures an embedded RPATH, which the loader searches before the system directories. You can also convert the RPATH to a RUNPATH, which can be overridden by LD_LIBRARY_PATH. > Does this mean that the ELF header of the library itself is modified readelf -d shows the .dynamic section (including strings from .dynstr), which you can use to verify the RPATH/RUNPATH. chrpath lets you change (but not add) an RPATH, up to its existing length. It also lets you convert an RPATH to a RUNPATH. patchELF can add or extend an RPATH/RUNPATH. http://nixos.org/patchelf.html > The libraries I am using are copyrighted (one can freely use them, but > no reverse engineering, disentangling, etc). I am not sure whether > adding an rpath will be copyright infringement. Logically, I'd say no, > but I doubt whether logic applies in legal stuff. It should be OK for internal administration. You'd have to ask a legal expert about distribution. If you stick with LD_LIBRARY_PATH, etc, keep in mind it has to be set before the process starts, typically in a wrapper script. On Windows, however, you can modify PATH at runtime. From gayathri.s112 at gmail.com Fri Jan 18 07:11:23 2013 From: gayathri.s112 at gmail.com (Gayathri S) Date: Fri, 18 Jan 2013 11:41:23 +0530 Subject: [Tutor] HELP- Regarding working with python In-Reply-To: References: Message-ID: hi... I am using principal component analysis for dimensionality reduction in python. am having this following error... >>> import numpy as np >>> import matplotlib.pyplot as plt >>> import mlpy >>> np.random.seed(0) >>> mean,cov,n=[0,0],[[1,1],[1,1.5]],100 >>> x=np.random.multivariate_normal(mean,cov,n) >>> pca.learn(x) Traceback (most recent call last): File "", line 1, in NameError: name 'pca' is not defined >>> would you please help me in finding the error...? what was my fault? how could i use PCA in python..? Thanks.....! On Wed, Jan 9, 2013 at 12:58 PM, Gayathri S wrote: > Hi.. > I would like to use Principal component analysis independent > component analysis in python. Wanna know whether it will support this > efficiently or not? > > > On Wed, Jan 2, 2013 at 4:59 PM, Alan Gauld wrote: > >> On 02/01/13 07:20, Gayathri S wrote: >> >>> Hi.. >>> I am using python 2.7 and scikit-learn for machine learning. >>> And OS is Windows 7. Wanna know how to import our own data sets in >>> scikit-learn? >>> >> >> Further to my last mail there is a gmane group >> >> gmane.comp.python.scikit-learn >> >> I'd try looking there, or wherever it is sourced originally. >> >> >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > > -- > > > > > Keep Smiling......... > Regards........ > Gayu.... > -- Keep Smiling......... Regards........ Gayu.... -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Fri Jan 18 09:07:27 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 18 Jan 2013 00:07:27 -0800 Subject: [Tutor] HELP- Regarding working with python In-Reply-To: References: Message-ID: On Thu, Jan 17, 2013 at 10:11 PM, Gayathri S wrote: > >>> import numpy as np > >>> import matplotlib.pyplot as plt > >>> import mlpy > >>> np.random.seed(0) > >>> mean,cov,n=[0,0],[[1,1],[1,1.5]],100 > >>> x=np.random.multivariate_normal(mean,cov,n) > >>> pca.learn(x) > Traceback (most recent call last): > File "", line 1, in > NameError: name 'pca' is not defined > >>> > would you please help me in finding the error...? what was my fault? how > could i use PCA in python..? > > The error means exactly what it says: you've referred to "pca", but you haven't told Python what "pca" is. I don't know the actual name of the PCA module you're using, but you need to import it the same way you've imported the other packages: - if it's called simply "pca", then just write "import pca" - if it has some other, slightly longer name, and you want to shorten it (as you did with "numpy", shortening it to "np"), then: "import longPCAname as pca" -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Jan 18 09:25:44 2013 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 18 Jan 2013 19:25:44 +1100 Subject: [Tutor] HELP- Regarding working with python In-Reply-To: References: Message-ID: On 18/01/13 17:11, Gayathri S wrote: > hi... > I am using principal component analysis for dimensionality > reduction in python. am having this following error... > >>> import numpy as np > >>> import matplotlib.pyplot as plt > >>> import mlpy > >>> np.random.seed(0) > >>> mean,cov,n=[0,0],[[1,1],[1,1.5]],100 > >>> x=np.random.multivariate_normal(mean,cov,n) > >>> pca.learn(x) > Traceback (most recent call last): > File "", line 1, in > NameError: name 'pca' is not defined > >>> > would you please help me in finding the error...? what was my fault? how > could i use PCA in python..? You might want to start with a more basic tutorials for working with python, for example the official tutorial at http://docs.python.org/2/tutorial/ You should go through at least the first 5-6 chapters, which should take no more than several hours to skim through if you already have experience in any other languages. As in your particular problem, the basic issue is that you have not defined 'pca' to refer to any object. You need to create an object named pca, which in this particular case the object is probably an instance of mlpy.PCA, which can be constructed like this: pca = mlpy.PCA() From ljmamoreira at gmail.com Fri Jan 18 12:11:28 2013 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Fri, 18 Jan 2013 11:11:28 +0000 Subject: [Tutor] list of references to object properties Message-ID: Hello Suppose I have a list l_obj of similar objects. Is there any way I can generate a list l_prp of references to a given property of those objects in such a way that, if change the value of one element in l_prp, the corresponding object in l_obj gets its property updated, and vice-versa? Let give an example of what I have in mind. In [1]: class MyCls(object): ...: def __init__(self,a): ...: self.prp = a ...: In [2]: l_obj = [MyCls(float(i)) for i in range(3)] In [3]: l_prp = [item.prp for item in l_obj] In [4]: for ob in l_obj: ...: print ob.prp, ...: 0.0 1.0 2.0 In [5]: l_prp Out[5]: [0.0, 1.0, 2.0] In [6]: l_prp[1]=5. In [7]: l_obj[1].prp Out[7]: 1.0 As expected, changes in l_prp do not change the properties of the elements in l_obj, neither do changes in l_obj's element's properties change the values in l_prp. Is there a simple way to implement such connections? Thanks, Ze -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Jan 18 12:37:26 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Jan 2013 12:37:26 +0100 Subject: [Tutor] list of references to object properties References: Message-ID: Jose Amoreira wrote: > Hello > Suppose I have a list l_obj of similar objects. Is there any way I can > generate a list l_prp of references to a given property of those objects > in such a way that, if change the value of one element in l_prp, the > corresponding object in l_obj gets its property updated, and vice-versa? > Let give an example of what I have in mind. > > In [1]: class MyCls(object): > > ...: def __init__(self,a): > > ...: self.prp = a > > ...: > > In [2]: l_obj = [MyCls(float(i)) for i in range(3)] > > In [3]: l_prp = [item.prp for item in l_obj] > > In [4]: for ob in l_obj: > > ...: print ob.prp, > > ...: > > 0.0 1.0 2.0 > > In [5]: l_prp > > Out[5]: [0.0, 1.0, 2.0] > > In [6]: l_prp[1]=5. > > In [7]: l_obj[1].prp > > Out[7]: 1.0 > > As expected, changes in l_prp do not change the properties of the elements > in l_obj, neither do changes in l_obj's element's properties change the > values in l_prp. > > Is there a simple way to implement such connections? No. You'd need something like the observer pattern (listeners in Java), where the class owning the property (MyCls) has to cooperate. The administrative overhead is relatively high. The pythonic way is to regenerate the l_prp list every time you need an up- to-date overview of the current values. An intermediate approach is to turn l_prp into a view on the l_obj list: from collections import Sequence class A(object): def __init__(self, attrib): self.attrib = attrib class AttribView(Sequence): def __init__(self, items): self._items = items def __getitem__(self, index): return self._items[index].attrib def __len__(self): return len(self._items) def __repr__(self): return repr(list(self)) items = [A(c) for c in "abcde"] attribs = AttribView(items) print attribs items[1].attrib = 42 print attribs From ljmamoreira at gmail.com Fri Jan 18 13:15:19 2013 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Fri, 18 Jan 2013 12:15:19 +0000 Subject: [Tutor] list of references to object properties In-Reply-To: References: Message-ID: Thanks, Peter. I was trying to avoid the regenerate step for updating. But maybe I can restructure my code and objects to make this simpler. Before that I'll try this view approach. Thanks again Ze On Fri, Jan 18, 2013 at 11:37 AM, Peter Otten <__peter__ at web.de> wrote: > Jose Amoreira wrote: > > > Hello > > Suppose I have a list l_obj of similar objects. Is there any way I can > > generate a list l_prp of references to a given property of those objects > > in such a way that, if change the value of one element in l_prp, the > > corresponding object in l_obj gets its property updated, and vice-versa? > > Let give an example of what I have in mind. > > > > In [1]: class MyCls(object): > > > > ...: def __init__(self,a): > > > > ...: self.prp = a > > > > ...: > > > > In [2]: l_obj = [MyCls(float(i)) for i in range(3)] > > > > In [3]: l_prp = [item.prp for item in l_obj] > > > > In [4]: for ob in l_obj: > > > > ...: print ob.prp, > > > > ...: > > > > 0.0 1.0 2.0 > > > > In [5]: l_prp > > > > Out[5]: [0.0, 1.0, 2.0] > > > > In [6]: l_prp[1]=5. > > > > In [7]: l_obj[1].prp > > > > Out[7]: 1.0 > > > > As expected, changes in l_prp do not change the properties of the > elements > > in l_obj, neither do changes in l_obj's element's properties change the > > values in l_prp. > > > > Is there a simple way to implement such connections? > > No. You'd need something like the observer pattern (listeners in Java), > where the class owning the property (MyCls) has to cooperate. The > administrative overhead is relatively high. > > The pythonic way is to regenerate the l_prp list every time you need an up- > to-date overview of the current values. > > An intermediate approach is to turn l_prp into a view on the l_obj list: > > from collections import Sequence > > class A(object): > def __init__(self, attrib): > self.attrib = attrib > > class AttribView(Sequence): > def __init__(self, items): > self._items = items > def __getitem__(self, index): > return self._items[index].attrib > def __len__(self): > return len(self._items) > def __repr__(self): > return repr(list(self)) > > items = [A(c) for c in "abcde"] > attribs = AttribView(items) > print attribs > items[1].attrib = 42 > print attribs > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Fri Jan 18 14:03:29 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 18 Jan 2013 08:03:29 -0500 Subject: [Tutor] HELP- Regarding working with python In-Reply-To: References: Message-ID: On Fri, Jan 18, 2013 at 3:25 AM, Lie Ryan wrote: > On 18/01/13 17:11, Gayathri S wrote: >> >> >>> import numpy as np >> >>> import matplotlib.pyplot as plt >> >>> import mlpy >> >>> np.random.seed(0) >> >>> mean,cov,n=[0,0],[[1,1],[1,1.5]],100 >> >>> x=np.random.multivariate_normal(mean,cov,n) >> >>> pca.learn(x) >> Traceback (most recent call last): >> File "", line 1, in >> NameError: name 'pca' is not defined > > As in your particular problem, the basic issue is that you have not defined > 'pca' to refer to any object. You need to create an object named pca, which > in this particular case the object is probably an instance of mlpy.PCA, > which can be constructed like this: > > pca = mlpy.PCA() Yes, it's a mistake in the PCA example from the docs: http://mlpy.sourceforge.net/docs/3.5/dim_red.html#principal-component-analysis-pca From sk4085 at ymail.com Fri Jan 18 21:40:48 2013 From: sk4085 at ymail.com (Roger Shaw) Date: Fri, 18 Jan 2013 12:40:48 -0800 (PST) Subject: [Tutor] sqlite search syntax Message-ID: <1358541648.53337.YahooMailNeo@web161802.mail.bf1.yahoo.com> Hello, I am very new to python. Wrote a small program to use on my android phone using pickle/shelve to access data. That worked fine but i realised it would be better to use sqlite as a database to more easily modify the data. I havent got a clue about sqlite, have a book but cant find the answer My problem is this.? I can access data by putting characters to search for into the program but i want it to be a variable string that i can search for. Specificaly a couple of letters? i input from keypad. At the moment this works to search for everything beginning with A sql = "SELECT * FROM plants WHERE genus LIKE 'A%'"; cursor.execute(sql); slt =cursor.fetchone(); What i really need is to search for everything beginning with two letters from an input command. As in A is a variable that could be Bl or An or someother two letter combination Hope you can help. Roger -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Fri Jan 18 22:07:27 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 18 Jan 2013 13:07:27 -0800 (PST) Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> <50F75D97.7060805@davea.name> <1358424875.71193.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: <1358543247.60697.YahooMailNeo@web163804.mail.gq1.yahoo.com> >> Thanks for your replies. os.putenv() may be easier than os.environ because, >> hopefully, it takes care of the OS-specific separators of the values >> (";" for Windows, ":" for Linux, others I don't > know > > I wouldn't count on it. Support for changing environment variables on the > fly is iffy in most languages and is not something I'd ever do lightly. > > The environment is something that usually should be set up when the user logs in > to reflect their preferences, its not really polite of a program to try and > alter the users environment... If you put it that way... yes, I now realize that it could be (and in fact is) really annoying if programs do such things. ;-) I hate programs that nest themselves everywhere in my OS, using resources. RealPlayer used to be notorious in this respect: shell integration, auto-updater, quickstart, icons all over the place, waaah). ? >> Then again, this sentence from the Python page is a little worrying: >> "*If* the platform supports the putenv() function, ...". > > Not all OS allow changes to the environment variables. Others only allow the > value to be a fixed size allocated at startup and if you write more bytes than > are already assigned you will overwrite the next value! The OS assumes that this > stuff is set up once and not changed. > > putenv() should always be considered a platform specific bit of code. > > >> As an alternative, I used os.chdir to tell the OS where to start >> looking for libraries, but somebody on this list (I forgot who) >> warned me that this could have nasty side effects. > > Again the user may expect to be in a certain directory so as a minimum you need > to change back to where they were when you exit. Yes, I considered first using oldpath = os.getcwd(), then use os.chdir in a try clause, and os.chdir(oldpath) in a finally clause. > The normal way to deal with local file locations is to have a resource file > that's read when the program starts up - like .vimrc or .emacs > Then if the file doesn't exist you either create it at install time or use > default values and allow the user to override them. You mean something like a setup.cfg that is read by ConfigParser? The coolest would be if it worked out-of-the-box, but this may be the next best thing. I want my C libraries and my .py files to live in the same dir (so not in a standard location such as /usr/lib, but in site-packages. Thank you Alan! Albert-Jan From ramit.prasad at jpmorgan.com Fri Jan 18 22:15:04 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 18 Jan 2013 21:15:04 +0000 Subject: [Tutor] sqlite search syntax In-Reply-To: <1358541648.53337.YahooMailNeo@web161802.mail.bf1.yahoo.com> References: <1358541648.53337.YahooMailNeo@web161802.mail.bf1.yahoo.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF47418116A89@SCACMX008.exchad.jpmchase.net> Roger Shaw wrote: > > Hello, > I am very new to python. > > Wrote a small program to use on my android phone using pickle/shelve to access data. > > That worked fine but i realised it would be better to use sqlite as a database to more easily modify the data. > > I havent got a clue about sqlite, have a book but cant find the answer > > My problem is this. > > I can access data by putting characters to search for into the program but i want it to be a variable string > that i can search for. > > Specificaly a couple of letters? i input from keypad. > > > > At the moment this works to search for everything beginning with A > sql = "SELECT * FROM plants WHERE genus LIKE 'A%'"; > cursor.execute(sql); You should avoid the above style query if you ever get data from an untrusted source (user/internet) as bad things (obligatory xkcd: http://xkcd.com/327/ ) can happen. Instead, use parameterized queries which will handle escaping the input. sql = "SELECT * FROM plants where genus LIKE ?" cursor.execute(sql, (genus + '%')) # Add wildcard to parameter, not the base # query. Using this notation, genus can hold one character or any amount. > slt =cursor.fetchone(); > What i really need is to search for everything beginning with two letters from an input command. > > As in A is a variable that could be Bl or An or someother two letter combination > ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Sat Jan 19 01:04:42 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Jan 2013 00:04:42 +0000 Subject: [Tutor] list of references to object properties In-Reply-To: References: Message-ID: On 18/01/13 11:11, Jose Amoreira wrote: > Suppose I have a list l_obj of similar objects. Is there any way I can > generate a list l_prp of references to a given property of those objects > in such a way that, if change the value of one element in l_prp, the > corresponding object in l_obj gets its property updated, and vice-versa? Not easily, and for very good reason, it breaks one of the fundamental principles of OOP. Objects should manage their own data and clients should manage the objects. So getting a list of the prp values is fine. Trying to modify those values without going through the object is asking for trouble and creating a nightmare for debugging. So unless you have a very specific reason to do so just modify the objects prp through the object. > As expected, changes in l_prp do not change the properties of the > elements in l_obj, neither do changes in l_obj's element's properties > change the values in l_prp. As you say, it's as expected and very worrying if it did otherwise! > Is there a simple way to implement such connections? It's difficult by intent. It's to save you from yourself. Is there a good reason to want to do such a thing? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Sat Jan 19 04:24:14 2013 From: bgailer at gmail.com (bob gailer) Date: Fri, 18 Jan 2013 22:24:14 -0500 Subject: [Tutor] HELP- Regarding working with python In-Reply-To: References: Message-ID: <50FA11DE.2090300@gmail.com> On 1/18/2013 8:03 AM, eryksun wrote: > Yes, it's a mistake in the PCA example from the docs: > > http://mlpy.sourceforge.net/docs/3.5/dim_red.html#principal-component-analysis-pca There seems to be no way to report a bug in that documentation! Or am I missing something? -- Bob Gailer 919-636-4239 Chapel Hill NC From moorejohn90 at googlemail.com Sat Jan 19 08:08:27 2013 From: moorejohn90 at googlemail.com (Moore John) Date: Sat, 19 Jan 2013 13:38:27 +0630 Subject: [Tutor] Python's OOP-Inheritance make me confuse. Message-ID: Hi, I am new to Python language. I have only 10 days experience on it. When I start learning there is no difficult, but it make me slow down when I reach "Object Oriented Concept", especially "Inherited". Some of my background knowledge about "Inherited is the child class can get all of characteristic and behaviour of parent class, in other words - data and methods of parent". Ok, I am going to show the concept that make me confuse with two programs. Both of them are getting the same result, so why people are making different. -----------------------------------Frist---------------------------------------------------------- class Parent(): parentdata = 0 def __init__(self): pass def getParentData(self): return Parent.parentdata def setParentData(self, setdata): Parent.parentdata = setdata class Child(Parent): childdata = 0 def __init__(self): pass def getChildData(self): return Child.childdata def setChildData(self, setdata): Child.childdata = setdata child = Child() print "Default Child's Data is :" + str(child.getChildData())#getting 0 child.setChildData(3) print "After Adding Child's Data is :"+ str(child.getChildData()) # getting 3 print "Default Parent's Data is:"+ str(child.getParentData())# getting 0 child.setParentData(1) print "After Adding Parent's Data is :"+str(child.getParentData())# getting 1 -----------------------------Second------------------------------------------------------------- class Parent(): parentdata = 0 def __init__(self): pass def getParentData(self): return Parent.parentdata def setParentData(self, setdata): Parent.parentdata = setdata class Child(Parent): childdata = 0 def __init__(self): #super(Child, self).__init__() #super(Child, self).__init__(self, self) Parent.__init__(self) def getChildData(self): return Child.childdata def setChildData(self, setdata): Child.childdata = setdata child = Child() print "Default Child's Data is :" + str(child.getChildData())#getting 0 child.setChildData(3) print "After Adding Child's Data is :"+ str(child.getChildData()) # getting 3 print "Default Parent's Data is:"+ str(child.getParentData())# getting 0 child.setParentData(1) print "After Adding Parent's Data is :"+str(child.getParentData())# getting 1 ----------------------------------------------------------------------------------------------- And also guide me, how to use "Super()" method for instance of "Parent.__init__(self) Somebody used, Super method ih there and some are doing as my way. I am not clearly these two different. In these two program - I am not using "__init__" as constructor. If I am going to use "__init__" as to add data into the class's data(childdata, parentdata), how do I insert parameter in "Parent.__init__(self)" and both of their "def __init__(self):" method. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Jan 19 09:37:48 2013 From: d at davea.name (Dave Angel) Date: Sat, 19 Jan 2013 03:37:48 -0500 Subject: [Tutor] Python's OOP-Inheritance make me confuse. In-Reply-To: References: Message-ID: <50FA5B5C.1060000@davea.name> On 01/19/2013 02:08 AM, Moore John wrote: > Hi, I am new to Python language. > I have only 10 days experience on it. > When I start learning there is no difficult, but it make me slow down when > I reach "Object Oriented Concept", especially "Inherited". > Some of my background knowledge about "Inherited is the child class can get > all of characteristic and behaviour of parent class, in other words - data > and methods of parent". > Ok, I am going to show the concept that make me confuse with two programs. > Both of them are getting the same result, so why people are making > different. > -----------------------------------Frist---------------------------------------------------------- > class Parent(): > > parentdata = 0 > > def __init__(self): > > pass > > L Is there a reason that you doublespaced all the code? It makes it hard to see much at a time on the screen. Or is that a consequence of composing the mail as html (also a bad idea here, for several reasons). First, by omitting the derivation from object, you've made Parent an old style class. Change it to: class Parent(object): In version 3.* Python has only new-style classes, and the change would be unnecessary. But you're using version 2.x After comparison, I see the only difference was the call to Parent.__init__(). That makes no difference, since the called function does nothing. So of course the two files produce the same results. The real question is what you expected either of them to do. You have no instance data in either class, so the only thing you're "sharing" is the methods. In other words, if you created ten instances of Chld, they'd all be identical To use instance data, you need to use the "self" namespace. So if the Parent class wants instance data called pdata, you'd do something like this inside the __init__() method. self.pdata = 42 Now, that data will be accessible in the child methods, by doing something like temp = self.pdata .....do something with temp.... > > ----------------------------------------------------------------------------------------------- > And also guide me, how to use "Super()" method for instance of > "Parent.__init__(self) > Somebody used, Super method ih there and some are doing as my way. > I am not clearly these two different. > In these two program - I am not using "__init__" as constructor. > If I am going to use "__init__" as to add data into the class's > data(childdata, parentdata), how do I insert parameter in > "Parent.__init__(self)" and both of their > "def __init__(self):" method. > Thanks > > > Parameters are done the same in __init__() method as in any other one. If you want to take 3 arguments, you might do something as simple as def __init__(self, arg1, arg2, arg3): self.data1 = arg1 self.data2 = arg2 self.data3 = arg3 Naturally, you'd pick better names. Anyway, then you can create an instance by doing: my_object = Parent(value1, value2, value3) Now you have the beginnings of a useful class. Each instance stores data which can be specified when the instance is created, and modified later. Worry about inheritance after you see what a class is used for to begin with. I think you should play with some realistic classes for a while, not just read about them. -- DaveA From bdrake at crosswire.org Sat Jan 19 12:14:26 2013 From: bdrake at crosswire.org (Barry Drake) Date: Sat, 19 Jan 2013 11:14:26 +0000 Subject: [Tutor] Struggling with logic ..... Message-ID: <50FA8012.2010502@crosswire.org> Hi there .... Some months ago I decided to have a crack at Python. I set myself the task of coding the 'Mastermind' game and got into great problems where the random generated number contained duplicated digits. I recently decided to get back to it as I have volunteered to introduce the older kids at the local junior school to programming i initially using 'Scratch' and then touching on Python. I found some Mastermind example coding on the internet and took a look. I'm playing with the attached: It seemed to work OK so I re-wrote the input code to be (IMO) more logical, and added more text to make it obvious what is happening. Then I noticed it doesn't get the scoring right when there are duplicate digits! I'm no expert, so I wonder if you guys can explain in simple terms what is happening. I have to say I feel a bit stupid here. Below is one of the 'mistakes': $ python mastermind_2.py I have chosen a random four digit number. You have to guess what it is. Give me your guess at the four digit number ..... Enter four digits between 1 and 6: 1234 line is: ['1', '2', '3', '4'] Length: 4 Random Code: (3, 4, 2, 3) Result: 0 - you have a correct number in an incorrect position Result: 0 - you have a correct number in an incorrect position Result: 0 - you have a correct number in an incorrect position Result: -1 - you have an incorrect number I have chosen a random four digit number. You have to guess what it is. Give me your guess at the four digit number ..... Enter four digits between 1 and 6: 4215 line is: ['4', '2', '1', '5'] Length: 4 Random Code: (3, 4, 2, 3) Result: 0 - you have a correct number in an incorrect position Result: 0 - you have a correct number in an incorrect position Result: -1 - you have an incorrect number Result: -1 - you have an incorrect number -- Barry Drake is a member of the the Ubuntu Advertising team. http://ubuntu.com/ -------------- next part -------------- A non-text attachment was scrubbed... Name: mastermind_2.py Type: text/x-python Size: 2715 bytes Desc: not available URL: From fomcl at yahoo.com Sat Jan 19 13:24:01 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 19 Jan 2013 04:24:01 -0800 (PST) Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> <1358436825.25405.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: <1358598241.33663.YahooMailNeo@web163803.mail.gq1.yahoo.com> > On Thu, Jan 17, 2013 at 10:33 AM, Albert-Jan Roskam > wrote: >> >> The goal is to load the C libraries (dll, so, dylib, etc) that my program >> needs. >> >> Anyway, I looked up your two suggestions about library_dirs and >> runtime_library_dirs. What is meant by "at link time"? > > library_dirs adds search paths for the linker (e.g. ld) for finding > shared libraries (.so) and static libraries (.a archives of > relocatable object files). > > Linking to a shared library is handled by the runtime loader/linker > (e.g. /lib/ld-linux.so.2). For Linux, ld.so searches the > system-defined directories (/lib, /usr/lib, and those set by > /etc/ld.so.conf), which are cached in /etc/ld.so.cache (created by > ldconfig). This is where distutils runtime_library_dirs comes into > play. For ELF it configures an embedded RPATH, which the loader > searches before the system directories. You can also convert the RPATH > to a RUNPATH, which can be overridden by LD_LIBRARY_PATH. Thank you! I am getting a whole lot wiser wrt Linux. I checked 'man ld' and 'man ldconfig'. Especially the ld command is pretty extensive. The Rpath/Runpath solution seems nice in that no wrapper is needed (contrary to when one uses LD_LIBRARY_PATH). But is Windows the only exception in the way that libraries are dealt with? Or do DLLs also have a dynamic area? ? >> Does this mean that the ELF header of the library itself is modified > > readelf -d shows the .dynamic section (including strings from > .dynstr), which you can use to verify the RPATH/RUNPATH. chrpath lets > you change (but not add) an RPATH, up to its existing length. It also > lets you convert an RPATH to a RUNPATH. patchELF can add or extend an > RPATH/RUNPATH. > > http://nixos.org/patchelf.html > >> The libraries I am using are copyrighted (one can freely use them, but >> no reverse engineering, disentangling, etc). I am not sure whether >> adding an rpath will be copyright infringement. Logically, I'd say no, >> but I doubt whether logic applies in legal stuff. > > It should be OK for internal administration. You'd have to ask a legal > expert about distribution. Yes, that would indeed be interesting to know. Unfortuntately, unlike developers, these folks are hard to get in touch with. Maybe they?e also a rare species. I think I'?l have to follow conservative approach here and not patch the ELF. > If you stick with LD_LIBRARY_PATH, etc, keep in mind it has to be set > before the process starts, typically in a wrapper script. On Windows, > however, you can modify PATH at runtime. So if, at runtime, I do something evil like del os.environ['PATH'] in Windows this actually deletes/propagates to my path?? Unlike other OS where os.environ is 'just' a dict that contains the paths, that once loaded, cannot be modified (well you can modify them, but the OS won know about the changes). From alan.gauld at btinternet.com Sat Jan 19 15:33:52 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Jan 2013 14:33:52 +0000 Subject: [Tutor] Struggling with logic ..... In-Reply-To: <50FA8012.2010502@crosswire.org> References: <50FA8012.2010502@crosswire.org> Message-ID: On 19/01/13 11:14, Barry Drake wrote: > I noticed it doesn't get the scoring right when there are duplicate > digits! You haven't given an example with duplicate digits so I'll need to take your word for it! > line is: ['1', '2', '3', '4'] Length: 4 > Random Code: (3, 4, 2, 3) > Result: 0 - you have a correct number in an incorrect position > Result: 0 - you have a correct number in an incorrect position > Result: 0 - you have a correct number in an incorrect position > Result: -1 - you have an incorrect number Looks good to me > line is: ['4', '2', '1', '5'] Length: 4 > Random Code: (3, 4, 2, 3) > Result: 0 - you have a correct number in an incorrect position > Result: 0 - you have a correct number in an incorrect position > Result: -1 - you have an incorrect number > Result: -1 - you have an incorrect number Same here. Sooo... Some comments on the code. ########################## > import random > # generate random code > code = (random.randrange(1, 6), random.randrange(1, 6), > random.randrange(1, 6), random.randrange(1, 6)) > > line = ['','','',''] # line from user You probably don't need this although it does no harm > cc = [] # code count > cl = [] # line count Not sure why you need a list for these.... > matched = 0 # number of matched items > result = [-1, -1, -1, -1] # result > user_own = False > max_attempts = 10 # XXX How to define a constant variable? Yes, although convention puts constants in uppercase so: MAX_ATTEMPTS = 10 It just makes the intention clear. This is not supposed to be changed by the program. > attempts = 0 > > while not user_own and attempts < max_attempts: > print "I have chosen a random four digit number. You have to > guess what it is." > input_str = str(input("Give me your guess at the four digit number > ..... Enter four digits between 1 and 6: ")) > for i in range(len(input_str)): > line[i] = input_str[i] Probably easier to just use list(), maybe with a length check too: if len(input_str) == 4: line = list(input_str) else: # print an error message continue > print "line is: ", line, " Length: ", len(line) # debug hint Catch the error don't just display it... > if len(line) != 4: > # won't be considered an attempt > print "Please enter only 4 digits " > continue I'd do this earlier, see above > # convert list members in integer > line = [int(l) for l in line] You could do this in the conversion above which becomes: if len(input_str) == 4: line = [int(d) for d in list(input_str)] else: # print an error message continue > # TODO check for color in range 1 to 6???? > > # game has 6 colors > cc = [0, 0, 0, 0, 0, 0] > cl = [0, 0, 0, 0, 0, 0] This just overwrote the initialisation at the top rendering it irrelevant. And where do the colors fit in? Your output only used numbers- no reference to colors so while debugging get rid of the irrelevant stuff... it only distracts. > matched = 0 > for i in range(len(line)): > if line[i] == code[i]: > # matched guess > matched += 1 > else: > cc[code[i] - 1] += 1 > cl[line[i] - 1] += 1 I don't understand what this else clause is doing.... > if matched == 4: > user_own = True > continue > > # user is not own, evaluate user guesses > i = 0 > result = [-1, -1, -1, -1] again you are overwriting the initialised value so its pointless doing the original initialisation. > while i < matched: > # color matched along with position > result[i] = 1 > i += 1 > > ri = i > for i in range(len(cc)): > x = min(cc[i], cl[i]) OK, at this point I give up, this is way too complicated for what you are doing. Consider using sets. If you create your line as a set of tuples (value,position) and the same for your input. The intersect of the two sets is your correct value and position. Remove these items from both sets and store as the 'matched' set. For each item in the remaining input set see if there is a corresponding value in the line set, if so, remove it from both and store in the 'nearly' set. Now report how many items in matched and nearly. Example: 1225 -> lineset = {(1,0),(2,1),(2,2),(5,3)} 1122 -> inset = {(1,0),(1,1),(2,2),(2,3)} intersect = {(1,0),(2.2)} -> matchset remainder now: lineset = {(2,1),(5,3)} inset = {(1,1),(2,3)} The first inset item does not match any value in linest. The second inset item matches the value of first item in lineset so add it to nearlyset: nearlyset = {(2,3)} So the final result is: matchset = {(1,0),(2.2)} -> len = 2 nearlyset = {2,3) -> len = 1 So result is 2 perfect matches and 1 in wrong position. Most of this can be done using the python set operations/methods... I think you'll find it easier... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jan 19 15:39:07 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Jan 2013 14:39:07 +0000 Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: <1358598241.33663.YahooMailNeo@web163803.mail.gq1.yahoo.com> References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> <1358436825.25405.YahooMailNeo@web163803.mail.gq1.yahoo.com> <1358598241.33663.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: On 19/01/13 12:24, Albert-Jan Roskam wrote: > Thank you! I am getting a whole lot wiser wrt Linux. I checked 'man ld' and 'man ldconfig'. > Especially the ld command is pretty extensive. The Rpath/Runpath solution seems nice in that > no wrapper is needed (contrary to when one uses LD_LIBRARY_PATH). But is Windows the only > exception in the way that libraries are dealt with? Or do DLLs also have a dynamic area? Every OS is different in how it builds executables and links to libraries. DOS is different to Windows and Unix. VMS is different again. IBM OS/390 is different again. And other OS like Vxworks, and OS/9 are similar to *nix but not quite the same. You are really in the depths of OS internals and need to research every platform on its own merits. The good news is that all unix variants (including Solaris, BSD, Darwin(MacOS) and linux work very similarly) And Windows is the only mainstream exception, at least on the desktop. So unless you are writing server software its not too bad. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eryksun at gmail.com Sat Jan 19 15:42:33 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 19 Jan 2013 09:42:33 -0500 Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: <1358543247.60697.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> <50F75D97.7060805@davea.name> <1358424875.71193.YahooMailNeo@web163806.mail.gq1.yahoo.com> <1358543247.60697.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: On Fri, Jan 18, 2013 at 4:07 PM, Albert-Jan Roskam wrote: > > Alan said: >> Support for changing environment variables on the fly is iffy in most >> languages and is not something I'd ever do lightly. > > If you put it that way... yes, I now realize that it could be (and in fact > is) really annoying if programs do such things. ;-) As initialized by exec, spawn, or Win32 CreateProcess, a child process uses a copy of the parent's environment, or a new environment. Modifying it doesn't carry over to the user's profile, or even the parent process. That said, there's no portable ANSI C function to modify the environment. CPython uses putenv; it's in the POSIX spec and available in Windows. If putenv isn't supported on the platform, then os.environ is just a dict. The environment consists of the environ array, with pointers to combined strings, such as 'foo=bar', that are initially in a contiguous block of memory. putenv realloc's environ to grow the number of variables. On a POSIX system the caller is responsible for allocating the new strings on the heap (not automatic memory on the stack), and as the name implies the exact string is 'put' into environ. Windows, in contrast, stores a copy, which is more like POSIX setenv. Either way, CPython keeps an internal reference so the memory doesn't get free'd. Another Windows difference is that when putenv is first called it copies the entire environment block as separately allocated strings. You can expand on the simple example below to explore how memory gets malloc'd and realloc'd outside of the initial environment. >>> from ctypes import * >>> env = POINTER(c_char_p).in_dll(CDLL(None), 'environ') >>> i = 0 >>> while env[i]: i += 1 # the last entry is NULL ... >>> import os >>> os.environ['spam'] = 'eggs' >>> env[i] 'spam=eggs' >>> print env[i+1] # new NULL terminator None CDLL(None), for accessing global symbols, is particular to POSIX dlopen. On Windows it works if I use "_environ" out of the active CRT (e.g. msvcr90.dll, msvcr100.dll, but not msvcrt.dll), which can be found with find_library('c'): >>> from ctypes import * >>> from ctypes.util import find_library >>> env = POINTER(c_char_p).in_dll(CDLL(find_library('c')), '_environ') ... On Windows, Python uppercases the keys set via os.environ. Windows getenv is case insensitive, so the os.py authors opted to normalize to uppercase so that 'Path' and 'PATH' have the same dict entry. In 2.x it still calls putenv with mixed-case keys (as long as the values stay consistent with the dict it doesn't matter), but 3.x only sets uppercase keys as part of the Unicode encode/decode redesign. Unicode also lead to changes for non-Windows platforms: the surrogateescape encoding and os.environb (bytes). >>> As an alternative, I used os.chdir to tell the OS where to start >>> looking for libraries, but somebody on this list (I forgot who) >>> warned me that this could have nasty side effects. That works for Windows LoadLibrary and OS X dlopen. Linux dlopen doesn't look in the current directory for a non-path, but you can use a relative path (e.g. "./libfoo.so"). For a non-path (i.e. no '/' in the string), ld.so uses the ELF RPATH, LD_LIBRARY_PATH, ELF RUNPATH, /etc/ld.so.cache, /lib, and /usr/lib. As to nasty side effects, your process has its own cwd; changing it doesn't affect the parent (as in the shell). If desired, you can use a context manager to automatically return to the previous directory, even (especially) if there's an exception. > You mean something like a setup.cfg that is read by ConfigParser? The coolest > would be if it worked out-of-the-box, but this may be the next best thing. I > want my C libraries and my .py files to live in the same dir (so not in a > standard location such as /usr/lib, but in site-packages. If you're loading libraries with ctypes, as mentioned above you can provide an absolute or relative path. The path for the Python module is os.path.dirname(__file__). Your libs can be installed there as package data. If nothing was done to modify the search path, you'll have to manage dependencies manually. For example, If libspam depends on libeggs, you can manually load libeggs before loading libspam. For ELF .so files this requires that libeggs has a correct SONAME tag. Verify it with readelf -d filename. This will also show dependencies listed as NEEDED, or you can use ldd to list the dependencies. From eryksun at gmail.com Sat Jan 19 16:09:16 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 19 Jan 2013 10:09:16 -0500 Subject: [Tutor] Set LD_LIBRARY_PATH and equivalents platform-independently In-Reply-To: <1358598241.33663.YahooMailNeo@web163803.mail.gq1.yahoo.com> References: <1358370394.19025.YahooMailNeo@web163806.mail.gq1.yahoo.com> <1358436825.25405.YahooMailNeo@web163803.mail.gq1.yahoo.com> <1358598241.33663.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: On Sat, Jan 19, 2013 at 7:24 AM, Albert-Jan Roskam wrote: > > But is Windows the only exception in the way that libraries are dealt with? > Or do DLLs also have a dynamic area? DLLs can have an embedded manifest. To solve the DLL Hell problem, Windows introduced side-by-side assemblies (WinSxS): Everything you Never Wanted to Know about WinSxS http://omnicognate.wordpress.com/2009/10/05/winsxs > So if, at runtime, I do something evil like del os.environ['PATH'] in > Windows this actually deletes/propagates to my path?? Unlike other OS > where os.environ is 'just' a dict that contains the paths, that once loaded, > cannot be modified (well you can modify them, but the OS won know about the > changes). That would only unset PATH for your current process, not the parent process, and not your user profile or system PATH. The latter are set in the registry (i.e. you need to use _winreg/winreg). If putenv is supported, os.environ uses it. That point about Windows PATH is that LoadLibrary evaluates it for each call. That means you can modify it in Python before calling CDLL. In Linux, ld.so caches the value of LD_LIBRARY_PATH when the process starts; it can't be set in Python before calling CDLL. You have to inherit it from the parent process or explicitly set it in bash/Python script (e.g. os.fork followed by os.execle with a modified environment). From ljmamoreira at gmail.com Sat Jan 19 16:47:16 2013 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Sat, 19 Jan 2013 15:47:16 +0000 Subject: [Tutor] list of references to object properties In-Reply-To: References: Message-ID: <1421727.xaN2XiEOm3@mu.site> Thanks for the explanation, Alan > > Is there a good reason to want to do such a thing? There is a reason, but maybe you won't consider it a good one... I was writing a small program to simulate the gravitational dynamics of a system of many planets, using scipy's odeint to solve the equations of motion. I defined a class, CelestialBody, that describes objects that represent planets in my simulation. These objects have three attributes: position, velocity and mass (the first two are 3D-vectors; as such, the number of attributes is actually 7). The many-body system is represented in the simulation by a list of CelestialBody objects. The dynamical state of the system is represented by a 6N (N being the number of planets) component array storing the components of the position and linear momentum of each body, and the integration procedures (odeint in this case) usually take this array as argument. So, in my simulation code I have a list of planets (objects of class CelestialBody) because it is a natural way of representing the systems I want to simulate, and another list (an numpy.array, actually) storing the positions and momenta of each planet, needed for the numerical processing of the simulation. But the positions and momenta are already present in the planet list, since the objects themselves store that information. Then, the second list, even if necessary, is a duplication of things that already are defined in the code. I don't like it. It'd be better (no duplication) if it was just a list of references to the values stored in the planet objects, I think. But I see your point. Thanks again, Jose Amoreira -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdrake at crosswire.org Sat Jan 19 17:50:15 2013 From: bdrake at crosswire.org (Barry Drake) Date: Sat, 19 Jan 2013 16:50:15 +0000 Subject: [Tutor] Struggling with logic ..... In-Reply-To: References: <50FA8012.2010502@crosswire.org> Message-ID: <50FACEC7.7000702@crosswire.org> On 19/01/13 14:33, Alan Gauld wrote: >> line is: ['1', '2', '3', '4'] Length: 4 >> Random Code: (3, 4, 2, 3) >> Result: 0 - you have a correct number in an incorrect position >> Result: 0 - you have a correct number in an incorrect position >> Result: 0 - you have a correct number in an incorrect position >> Result: -1 - you have an incorrect number > > Looks good to me > >> line is: ['4', '2', '1', '5'] Length: 4 >> Random Code: (3, 4, 2, 3) > > Same here. Sooo... Some comments on the code. Thanks. I seem to have misunderstood what the original coder had intended. I suppose the above output is making sense after all. > > OK, at this point I give up, this is way too complicated for what you > are doing. I guess this is exactly why I have been struggling to understand some of the logic in the original code! I like your idea of sets of tuples for input and solution - I'll play around with the idea. Also, I think I want to alter the random initialisation - I don't like the way in which four separate random digits each with a range of only six are generated. I think generating a four digit number and splitting the digits will be a better option. As you mention, the use of colours in the original code is a distraction - I think that is the reason for limiting the digits to numbers between 1 and 6 - simply based on the old board-game. There's no other logical reason so I'll do away with that concept. Thanks again for your time. I'm GOING to learn to code Python! I used to code in C many years ago and never made the jump to C++, but Python has much nicer features for a novice. Incidentally, if I re-code the example, should I alter it to Python3 syntax while I'm at it? Is there any good reason to move away from Python2? Kind regards, Barry. -- Barry Drake is a member of the the Ubuntu Advertising team. http://ubuntu.com/ From alan.gauld at btinternet.com Sat Jan 19 19:01:04 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Jan 2013 18:01:04 +0000 Subject: [Tutor] list of references to object properties In-Reply-To: <1421727.xaN2XiEOm3@mu.site> References: <1421727.xaN2XiEOm3@mu.site> Message-ID: On 19/01/13 15:47, Jose Amoreira wrote: > motion. I defined a class, CelestialBody, that describes objects that > represent planets in my simulation. These objects have three attributes: > position, velocity and mass (the first two are 3D-vectors; as such, the > number of attributes is actually 7). The many-body system is represented > in the simulation by a list of CelestialBody objects. OK, why not hold that list in the CelestialBody class? Then get the list to either hold a copy of the key values or generate it on demand. If the list of values is also in the class definition all the descendant types of body can update the class list at the same time as updating their own copy. It means duplicating data but it keeps the instances in control of the data while making it available (read-only, from the class) when needed. The overhead is creating the getter/setter methods to update the class list in parallel with the instance data. Alternatively store it once at class level and create properties of the instance that do all access in the class list. That way it looks like you are updating the instance but the instance delegates the storage to the class list. The instance can store its own index into the class list as advised by the class on creation. There are ways of doing what you want that keep responsibility in the object. The choice will depend on how often you need to vary the instance values as opposed to using the class list. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jan 19 19:04:02 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Jan 2013 18:04:02 +0000 Subject: [Tutor] Struggling with logic ..... In-Reply-To: <50FACEC7.7000702@crosswire.org> References: <50FA8012.2010502@crosswire.org> <50FACEC7.7000702@crosswire.org> Message-ID: On 19/01/13 16:50, Barry Drake wrote: > has much nicer features for a novice. Incidentally, if I re-code the > example, should I alter it to Python3 syntax while I'm at it? Is there > any good reason to move away from Python2? Python 3 is the future so getting used to it sooner rather than later is a good thing. But functionally, for now, there is no great reason to move. If I were you, starting out relatively fresh, I'd probably go Pyton 3 just to save relearning. But be aware not all 3rd party libraries are ported yet... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From etanes.rm at gmail.com Sat Jan 19 21:11:45 2013 From: etanes.rm at gmail.com (Scurvy Scott) Date: Sat, 19 Jan 2013 12:11:45 -0800 Subject: [Tutor] Question regarding lists and manipulating items in lists. In-Reply-To: <50F6B1DD.5080006@pearwood.info> References: <50F5EDE6.3070009@pearwood.info> <50F6B1DD.5080006@pearwood.info> Message-ID: [SNIP] Thank you guys so much, sorry for the delayed response. It's awesome being able to learn a thing or two from people who know so much about their craft. I've got the code working the way I envisioned it now and probably couldn't without y'alls help. I'm so glad this mailing list exists, thanks again. Scott From anthonym at att.net Sat Jan 19 21:31:25 2013 From: anthonym at att.net (anthonym) Date: Sat, 19 Jan 2013 12:31:25 -0800 Subject: [Tutor] Traffic Light Message-ID: Hello All, I am new to Python and taking a course now. One of my exercises is to create a traffic light using tkinter. The exercise also requires that I create radio buttons that allow the user to click on the color and the corresponding light will come on. I followed some examples in my book to write the code but get some errors that I don't understand . Code and error messages below Thanks, Tony from tkinter import * # Import tkinter class Trafficlight: def __init__(self): window = Tk() # Create a window window.title("Traffic Light") # Set a title # Add three radio buttons to frame1 frame1 = Frame(window) # Create and add a frame to window frame1.pack() self.v1 = IntVar() self.v2 = IntVar() rbRed = Radiobutton(frame1, text = "Red", bg = "red", variable = self.v2, value = 1, command = self.processRadiobutton) rbYellow = Radiobutton(frame1, text = "Yellow", bg = "yellow", variable = self.v2, value = 2, command = self.processRadiobutton) rbGreen = Radiobutton(frame1, text = "Green", bg = "green", variable = self.v2, value = 3, command = self.processRadiobutton) rbRed.grid(row = 10, column = 1) rbYellow.grid(row = 10, column = 2) rbGreen.grid(row = 10, column = 3) # Add Radio Button process below once I figure that out # Place canvas in the window self.canvas = Canvas(window, width = 480, height = 480, bg = "white") self.canvas.pack() # Display a rectangle def displayRect(self): self.canvas.create_rectangle(10, 10, 190, tages = "rect") # Display a Oval for the top light def displayOval(self): self.canvas.create_oval(10, 10, 10, 10) # Display an Oval for the middle light def displayOval(self): self.canvas.create_oval(20, 20, 20, 20) # Display an Oval for the bottom light def displayOval(self): self.canvas.create_oval(30, 30, 30, 30) # Create an event loop Trafficlight() Error messages Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 02:56:36) [GCC 4.2.1 (Apple Inc. build 5577)] on darwin Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>> Traceback (most recent call last): File "/Users/anthonym/Downloads/pybook/Traffic Light Tony.py", line 57, in Trafficlight() File "/Users/anthonym/Downloads/pybook/Traffic Light Tony.py", line 16, in __init__ command = self.processRadiobutton) AttributeError: 'Trafficlight' object has no attribute 'processRadiobutton' >>> ================================ RESTART ================================ >>> Traceback (most recent call last): File "/Users/anthonym/Downloads/pybook/Traffic Light Tony.py", line 57, in Trafficlight() File "/Users/anthonym/Downloads/pybook/Traffic Light Tony.py", line 16, in __init__ command = self.processRadiobutton) AttributeError: 'Trafficlight' object has no attribute 'processRadiobutton' >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jan 19 22:02:40 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Jan 2013 21:02:40 +0000 Subject: [Tutor] Traffic Light In-Reply-To: References: Message-ID: On 19/01/13 20:31, anthonym wrote: > rbRed = Radiobutton(frame1, text = "Red", bg = "red", > variable = self.v2, > value = 1, > command = self.processRadiobutton) Here you assign your method to the button > # Add Radio Button process below once I figure that out But you haven't defined it, it does not exist. So python complains. You need to define something, even just a pass: def processRadioButton(self): pass > 16, in __init__ > command = self.processRadiobutton) > AttributeError: 'Trafficlight' object has no attribute 'processRadiobutton' HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From anthonym at att.net Sat Jan 19 23:56:13 2013 From: anthonym at att.net (anthonym) Date: Sat, 19 Jan 2013 14:56:13 -0800 Subject: [Tutor] Traffic Light In-Reply-To: Message-ID: Thanks again for the info Alan. I am still passing the button process until I can get my rectangle and ovals on the canvass. The program runs and produces a window with the radio buttons on top. I would like them on the bottom but changes to the row field have no effect. Anybody have any ideas on why I don't see my shape on the canvass? Thanks, Tony On 1/19/13 1:02 PM, "Alan Gauld" wrote: >On 19/01/13 20:31, anthonym wrote: > >> rbRed = Radiobutton(frame1, text = "Red", bg = "red", >> variable = self.v2, >> value = 1, >> command = self.processRadiobutton) > >Here you assign your method to the button > >> # Add Radio Button process below once I figure that out > >But you haven't defined it, it does not exist. >So python complains. > >You need to define something, even just a pass: > > > def processRadioButton(self): pass > > >> 16, in __init__ >> command = self.processRadiobutton) >> AttributeError: 'Trafficlight' object has no attribute >>'processRadiobutton' > > >HTH > >-- >Alan G >Author of the Learn to Program web site >http://www.alan-g.me.uk/ > >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor From doanviettrung at gmail.com Sun Jan 20 00:05:24 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Sun, 20 Jan 2013 10:05:24 +1100 Subject: [Tutor] list of references to object properties In-Reply-To: References: <1421727.xaN2XiEOm3@mu.site> Message-ID: Hi Jose, have you thought about shallow copying? I am learning Python too, so I can be wrong here. But I have just tried the idea and it worked for me: class celestialBody(object): def __init__(self, m, x, y, z): self.mass = m self.pos = [x, y, z] def __str__(self): return str(self.mass) + ' and ' + str(self.pos) earth = celestialBody(1, 0, 0, 0) jupiter = celestialBody(2, 2, 2, 2) asteroid = celestialBody(0.00001, 1, 1, 1) planetSystem = [earth, jupiter] positionVectors = [earth.pos, jupiter.pos] print "object earth's mass and original position is", earth # Now we make changes to earth's coordinates one by one # not by manipulating earth but by manipulating the positionVectors positionVectors[0][0] = positionVectors[0][0] + 0.01*asteroid.pos[0] positionVectors[0][1] = positionVectors[0][1] + 0.01*asteroid.pos[1] positionVectors[0][2] = positionVectors[0][2] + 0.01*asteroid.pos[2] print "object earth's new position, as seen in positionVectors, is", positionVectors[0] print "object earth's mass and new position, as seen in earth object, is", earth print "object earth's mass and new position, as seen in planetSystem, is", planetSystem[0] >>> ====================== RESTART ====================== >>> object earth's mass and original position is 1 and [0, 0, 0] object earth's new position, as seen in positionVectors, is [0.01, 0.01, 0.01] object earth's mass and new position, as seen in earth object, is 1 and [0.01, 0.01, 0.01] object earth's mass and new position, as seen in planetSystem, is 1 and [0.01, 0.01, 0.01] >>> As to Alan's ideas below, I don't really understand them. Trung Doan ============ On Sun, Jan 20, 2013 at 5:01 AM, Alan Gauld wrote: > On 19/01/13 15:47, Jose Amoreira wrote: > > motion. I defined a class, CelestialBody, that describes objects that >> represent planets in my simulation. These objects have three attributes: >> position, velocity and mass (the first two are 3D-vectors; as such, the >> number of attributes is actually 7). The many-body system is represented >> in the simulation by a list of CelestialBody objects. >> > > OK, why not hold that list in the CelestialBody class? > > Then get the list to either hold a copy of the key values or generate it > on demand. If the list of values is also in the class definition all the > descendant types of body can update the class list at the same time as > updating their own copy. It means duplicating data but it keeps the > instances in control of the data while making it available (read-only, from > the class) when needed. The overhead is creating the getter/setter methods > to update the class list in parallel with the instance data. > > Alternatively store it once at class level and create properties of the > instance that do all access in the class list. That way it looks like you > are updating the instance but the instance delegates the storage to the > class list. The instance can store its own index into the class list as > advised by the class on creation. > > There are ways of doing what you want that keep responsibility in the > object. The choice will depend on how often you need to vary the instance > values as opposed to using the class list. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Sun Jan 20 00:14:25 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sat, 19 Jan 2013 23:14:25 +0000 Subject: [Tutor] Traffic Light In-Reply-To: References: Message-ID: On Sat, Jan 19, 2013 at 10:56 PM, anthonym wrote: > Thanks again for the info Alan. I am still passing the button process > until I can get my rectangle and ovals on the canvass. The program runs > and produces a window with the radio buttons on top. I would like them on > the bottom but changes to the row field have no effect. > > Anybody have any ideas on why I don't see my shape on the canvass? i doubt i can help, but it might help if you could paste the section of the code in relation to what you're explaining and tell us what it's doing? some people don't use tkinter so its a bit hard to understand what you're saying. From anthonym at att.net Sun Jan 20 00:29:08 2013 From: anthonym at att.net (anthonym) Date: Sat, 19 Jan 2013 15:29:08 -0800 Subject: [Tutor] Traffic Light In-Reply-To: Message-ID: Sure thing. Here is the code. And after that is the box I get with the radio buttons but no shapes. from tkinter import * # Import tkinter class Trafficlight: def __init__(self): window = Tk() # Create a window window.title("Traffic Light") # Set a title # Place canvas in the window self.canvas = Canvas(window, width = 480, height = 480, bg = "white") self.canvas.pack() # Add three radio buttons to frame1 frame1 = Frame(window) # Create and add a frame to window frame1.pack() self.v1 = IntVar() self.v2 = IntVar() rbRed = Radiobutton(frame1, text = "Red", bg = "red", variable = self.v2, value = 1, command = self.processRadiobutton) rbYellow = Radiobutton(frame1, text = "Yellow", bg = "yellow", variable = self.v2, value = 2, command = self.processRadiobutton) rbGreen = Radiobutton(frame1, text = "Green", bg = "green", variable = self.v2, value = 3, command = self.processRadiobutton) rbRed.grid(row = 400, column = 1) rbYellow.grid(row = 400, column = 2) rbGreen.grid(row = 400, column = 3) window.mainloop() # Create an event loop # Display a rectangle def displayRect(self): self.canvas.create_rectangle(10, 10, 100, 100, tages = "rect") # Display a Oval for the top light def displayOval(self): self.canvas.create_oval(10, 10, 10, 10) # Display an Oval for the middle light def displayOval(self): self.canvas.create_oval(20, 20, 20, 20) # Display an Oval for the bottom light def displayOval(self): self.canvas.create_oval(30, 30, 30, 30) # Add Radio Button process below once I figure that out def processRadiobutton(self): pass Trafficlight() from tkinter import * # Import tkinter class Trafficlight: def __init__(self): window = Tk() # Create a window window.title("Traffic Light") # Set a title # Place canvas in the window self.canvas = Canvas(window, width = 480, height = 480, bg = "white") self.canvas.pack() # Add three radio buttons to frame1 frame1 = Frame(window) # Create and add a frame to window frame1.pack() self.v1 = IntVar() self.v2 = IntVar() rbRed = Radiobutton(frame1, text = "Red", bg = "red", variable = self.v2, value = 1, command = self.processRadiobutton) rbYellow = Radiobutton(frame1, text = "Yellow", bg = "yellow", variable = self.v2, value = 2, command = self.processRadiobutton) rbGreen = Radiobutton(frame1, text = "Green", bg = "green", variable = self.v2, value = 3, command = self.processRadiobutton) rbRed.grid(row = 400, column = 1) rbYellow.grid(row = 400, column = 2) rbGreen.grid(row = 400, column = 3) window.mainloop() # Create an event loop # Display a rectangle def displayRect(self): self.canvas.create_rectangle(10, 10, 100, 100, tages = "rect") # Display a Oval for the top light def displayOval(self): self.canvas.create_oval(10, 10, 10, 10) # Display an Oval for the middle light def displayOval(self): self.canvas.create_oval(20, 20, 20, 20) # Display an Oval for the bottom light def displayOval(self): self.canvas.create_oval(30, 30, 30, 30) # Add Radio Button process below once I figure that out def processRadiobutton(self): pass Trafficlight() On 1/19/13 3:14 PM, "Matthew Ngaha" wrote: >On Sat, Jan 19, 2013 at 10:56 PM, anthonym wrote: >> Thanks again for the info Alan. I am still passing the button process >> until I can get my rectangle and ovals on the canvass. The program runs >> and produces a window with the radio buttons on top. I would like them >>on >> the bottom but changes to the row field have no effect. >> >> Anybody have any ideas on why I don't see my shape on the canvass? > >i doubt i can help, but it might help if you could paste the section >of the code in relation to what you're explaining and tell us what >it's doing? some people don't use tkinter so its a bit hard to >understand what you're saying. >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor From brownboyrx at gmail.com Sun Jan 20 00:27:46 2013 From: brownboyrx at gmail.com (Polo Heysquierdo) Date: Sat, 19 Jan 2013 18:27:46 -0500 Subject: [Tutor] Python gmail script for conky Message-ID: I'm getting the following error on my script for conky. "Traceback (most recent call last): File "/home/troll/.gmail/gmail.py", line 1, in import urllib.request ImportError: No module named request" code below: import urllib.request from xml.etree import ElementTree as etree # Enter your username and password below within quotes below, in place of ****. # Set up authentication for gmail auth_handler = urllib.request.HTTPBasicAuthHandler() auth_handler.add_password(realm='New mail feed', url='https://mail.google.com/', user= 'username', passwd= 'gmail') opener = urllib.request.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. urllib.request.install_opener(opener) gmail = 'https://mail.google.com/gmail/feed/atom' NS = '{http://purl.org/atom/ns#}' with urllib.request.urlopen('https://mail.google.com/gmail/feed/atom') as source: tree = etree.parse(source) fullcount = tree.find(NS + 'fullcount').text print(fullcount + ' new') -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Sun Jan 20 01:06:49 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 20 Jan 2013 00:06:49 +0000 Subject: [Tutor] Traffic Light In-Reply-To: References: Message-ID: On Sun, Jan 20, 2013 at 12:05 AM, Matthew Ngaha wrote: > On Sat, Jan 19, 2013 at 11:29 PM, anthonym wrote: >> Sure thing. Here is the code. And after that is the box I get with the >> radio buttons but no shapes. > i might be way off as im struggling to understand how tkinter works, but i noticed a few things which hopefully might help. starting with you wanting the buttons on the bottom of the window and not at the top where they are showing. >> from tkinter import * # Import tkinter >> >> class Trafficlight: >> def __init__(self): >> window = Tk() >> self.canvas = Canvas(window, width = 480, height = 480, bg = >> "white") >> self.canvas.pack() >> >> # Add three radio buttons to frame1 >> frame1 = Frame(window) >> frame1.pack() >> >> rbRed = Radiobutton(frame1, text = "Red", bg = "red", >> variable = self.v2, >> value = 1, >> command = self.processRadiobutton) >> rbYellow = Radiobutton(frame1, text = "Yellow", bg = "yellow", >> variable = self.v2, value = 2, >> command = self.processRadiobutton) >> rbGreen = Radiobutton(frame1, text = "Green", bg = "green", >> variable = self.v2, value = 3, >> command = self.processRadiobutton) >> >> rbRed.grid(row = 400, column = 1) >> rbYellow.grid(row = 400, column = 2) >> rbGreen.grid(row = 400, column = 3) >> > row = 400 seems a bit odd? do you really have 399 occupied rows? you define the canvas with absolute positioning: Canvas(window, width = 480, height = 480). where you trying to place the buttons with absolute positioning also? it seems they are appearing inside the frame in which you have put them in so why are you trying to move them again? im guessing you would have to reposition the Frame itself. also you are not using instance variables(self) for either the frame or the buttons, maybe they lose the reference to them once moved outside the frame. as for your shapes not appearing: > >>def displayRect(self): >> self.canvas.create_rectangle(10, 10, 100, 100, tages = "rect") >> >> # Display a Oval for the top light >> def displayOval(self): >> self.canvas.create_oval(10, 10, 10, 10) >> # Display an Oval for the middle light >> def displayOval(self): >> self.canvas.create_oval(20, 20, 20, 20) >> # Display an Oval for the bottom light >> def displayOval(self): >> self.canvas.create_oval(30, 30, 30, 30) > If that is the complete code you showed.. Your buttons are not doing anything. they are calling a method that does nothing: def processRadiobutton(self): pass also i dont see anywhere in your code where you are calling any of those methods that create the shapes. you have to fix your method that your buttons are calling, and have it call the correct method for your specific shape. From alan.gauld at btinternet.com Sun Jan 20 02:02:59 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Jan 2013 01:02:59 +0000 Subject: [Tutor] Traffic Light In-Reply-To: References: Message-ID: On 19/01/13 23:29, anthonym wrote: > Sure thing. Here is the code. And after that is the box I get with the > radio buttons but no shapes. It all runs fine for me. I'm not sure what you are expecting but it does exactly what I'd expect... The shapes aren't there because you don't draw them. you have some functions that might draw shapes but you never call them. And the drawOval function gets overwritten twice, so only the last version actually exists. You need to call that function with the params or rename it something like drawTopLeftOval(). But frankly the generic version is better, just keep it to one and pass the values in. > # Display a rectangle > def displayRect(self): > self.canvas.create_rectangle(10, 10, 100, 100, tages = "rect") > > # Display a Oval for the top light > def displayOval(self): > self.canvas.create_oval(10, 10, 10, 10) > > # Display an Oval for the middle light > def displayOval(self): > self.canvas.create_oval(20, 20, 20, 20) > > # Display an Oval for the bottom light > def displayOval(self): > self.canvas.create_oval(30, 30, 30, 30) Only the last version is actually available in your program it overwrites the earlier versions. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eryksun at gmail.com Sun Jan 20 02:04:31 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 19 Jan 2013 20:04:31 -0500 Subject: [Tutor] list of references to object properties In-Reply-To: <1421727.xaN2XiEOm3@mu.site> References: <1421727.xaN2XiEOm3@mu.site> Message-ID: On Sat, Jan 19, 2013 at 10:47 AM, Jose Amoreira wrote: > > I defined a class, CelestialBody, that describes objects that > represent planets in my simulation. These objects have three attributes: > position, velocity and mass (the first two are 3D-vectors; as such, the > number of attributes is actually 7). The many-body system is represented in > the simulation by a list of CelestialBody objects. > > The dynamical state of the system is represented by a 6N (N being the number > of planets) component array storing the components of the position and > linear momentum of each body, and the integration procedures (odeint in this > case) usually take this array as argument. Working with views: >>> import numpy as np 2 planets: >>> system_state = np.zeros(12) Create a view for each planet: >>> mars, earth = [system_state[6*i:6*(i+1)] for i in range(2)] Modify the views, which also changes the original array: >>> mars += 1 >>> earth += 2 >>> system_state array([ 1., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2., 2.]) So you can use a CelestialSystem that has the overall state array and CelestialBody objects that use a view on the latter. Velocity can be a property, computed from linear momentum and mass. From oscar.j.benjamin at gmail.com Sun Jan 20 02:15:23 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 20 Jan 2013 01:15:23 +0000 Subject: [Tutor] list of references to object properties In-Reply-To: <1421727.xaN2XiEOm3@mu.site> References: <1421727.xaN2XiEOm3@mu.site> Message-ID: On 19 January 2013 15:47, Jose Amoreira wrote: > Thanks for the explanation, Alan > >> Is there a good reason to want to do such a thing? > > There is a reason, but maybe you won't consider it a good one... > > I was writing a small program to simulate the gravitational dynamics of a > system of many planets, I have many times written code for this kind of problem. > using scipy's odeint to solve the equations of > motion. I haven't checked but I wouldn't automatically trust scipy's odeint to solve these equations through a significant period of time. A simple method to indicate (not prove) the accuracy of your program would be to measure how well energy is conserved over time (assuming that your equations are Hamiltonian). > I defined a class, CelestialBody, that describes objects that > represent planets in my simulation. These objects have three attributes: > position, velocity and mass (the first two are 3D-vectors; as such, the > number of attributes is actually 7). It is useful in this kind of problem to draw a distinction between parameters and variables. Mass is a parameter. Position and velocity are variables (they change over time). > The many-body system is represented in > the simulation by a list of CelestialBody objects. > > The dynamical state of the system is represented by a 6N (N being the number > of planets) component array storing the components of the position and > linear momentum of each body, and the integration procedures (odeint in this > case) usually take this array as argument. > I would make a class to represent the system as a whole. class SystemAsAWhole(object): def __init__(self): self.numdimensions = 0 self.subsystems = [] def add_subsystem(self, subsys): # Add to the list of systems to consider when evaluating the derivative self.subsystems.append(subsys) # Adjust the variable indices in the subsystem self.subsystems.shift(self.numdimensions) self.numdimensions += subsys.numdimensions def f(self, x, t, dxdt): for sys in self.subsystems: sys.f(x, t, dxdt) class SubSystem(object): def __init__(self): for n, var in self.VARIABLES: setattr(self, var, n) # Called when the subsystem is incorporated into a larger system # Need to adjust our indices to be part of a larger state vector def shift(self, N): for var in self.variables: setattr(self, var, getattr(self, var) + N) def f(self, x, t, dxdt): # Compute and return derivative (subclasses need to implement this) raise NotImplementedError And then subclass SubSystem to implement the derivative and describe the variables/parameters: class SelestialBody(SubSystem): VARIABLES = ['x', 'y', 'z', 'vx', 'vy', 'vz'] def __init__(self, mass): self.mass = mass def f(self, x, t, dxdt): dxdt[self.x] = x[self.vx] dxdt[self.y] = x[self.vy] dxdt[self.z] = x[self.vz] ax, ay, az = self.force(x) dxdt[self.vx] = ax dxdt[self.vy] = ay dxdt[self.vz] = az > > > So, in my simulation code I have a list of planets (objects of class > CelestialBody) because it is a natural way of representing the systems I > want to simulate, and another list (an numpy.array, actually) storing the > positions and momenta of each planet, needed for the numerical processing of > the simulation. But the positions and momenta are already present in the > planet list, since the objects themselves store that information. Then, the > second list, even if necessary, is a duplication of things that already are > defined in the code. I don't like it. It'd be better (no duplication) if it > was just a list of references to the values stored in the planet objects, I > think. If you understand the code above you'll see that each planet instance has attributes giving the indices of the particular variable into the state vector. This is much better than storing the values as attributes in the instances themselves. The position of the Earth is a property of a state of the system which is in turn part of a particular trajectory. It should be stored as part of a trajectory not as a property of the object itself. To access the y velocity of the Earth from the state vector x you can just use x[earth.vy]. Oscar From andipersti at gmail.com Sun Jan 20 06:25:56 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Sun, 20 Jan 2013 06:25:56 +0100 Subject: [Tutor] Python gmail script for conky In-Reply-To: References: Message-ID: <50FB7FE4.8070102@gmail.com> On 20.01.2013 00:27, Polo Heysquierdo wrote: > I'm getting the following error on my script for conky. > > "Traceback (most recent call last): > File "/home/troll/.gmail/gmail.py", line 1, in > import urllib.request > ImportError: No module named request" What's your python version? (Type "python -V" on the command line or "import sys; sys.version" in the interpreter) Bye, Andreas From alan.gauld at btinternet.com Sun Jan 20 08:47:36 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 20 Jan 2013 07:47:36 +0000 (GMT) Subject: [Tutor] Traffic Light In-Reply-To: References: Message-ID: <1358668056.9224.YahooMailNeo@web186001.mail.ir2.yahoo.com> That must be what I am missing.? How do I call the functions so I can have >the shapes appear on the canvas? > >AG> the same way you call all the other functions. >AG> The bit I can't answer is *where* you call them. I'm not sure >AG> where in your code you want them. >AG> Is it before you press the buttons or is it when you press them? > >On 1/19/13 5:02 PM, "Alan Gauld" wrote: > >>The shapes aren't there because you don't draw them. you have some >>functions that might draw shapes but you never call them. > >> >>>? ? ? # Display a rectangle >>>? ? ? def displayRect(self): >>>? ? ? ? ? self.canvas.create_rectangle(10, 10, 100, 100, tages = "rect") >>> >>>? ? ? # Display a Oval for the top light >>>? ? ? def displayOval(self): >>>? ? ? ? ? self.canvas.create_oval(10, 10, 10, 10) > >AG> So somewhere you need to write >AG> >AG> self.displayRect() > > >AG> and >AG> >AG>self.displayOval() >AG> >AG>Except you probably want to modify them so you do it with the location: >AG> >AG>self.displayOval(10,10,10,10) > >-- >Alan G >Author of the Learn to Program web site >http://www.alan-g.me.uk/ > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dfjennings at gmail.com Sun Jan 20 03:33:16 2013 From: dfjennings at gmail.com (Don Jennings) Date: Sat, 19 Jan 2013 21:33:16 -0500 Subject: [Tutor] Python gmail script for conky In-Reply-To: References: Message-ID: <6FB57B39-8278-4AAD-BF98-BB8AB64F7216@gmail.com> On Jan 19, 2013, at 8:15 PM, tutor-request at python.org wrote: > Date: Sat, 19 Jan 2013 18:27:46 -0500 > From: Polo Heysquierdo > To: Tutor at python.org > Subject: [Tutor] Python gmail script for conky > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > I'm getting the following error on my script for conky. > > "Traceback (most recent call last): > File "/home/troll/.gmail/gmail.py", line 1, in > import urllib.request > ImportError: No module named request" (Probably someone will beat me to the punch since I get the digest of this list, still?) Most likely, you are using python 2 to run python 3 code as the urllib.request is available in python 3 (see note at top of this page [1]). Take care, Don [1] http://docs.python.org/2/library/urllib.html From russel at winder.org.uk Sun Jan 20 13:25:35 2013 From: russel at winder.org.uk (Russel Winder) Date: Sun, 20 Jan 2013 12:25:35 +0000 Subject: [Tutor] Traffic Light In-Reply-To: References: Message-ID: <1358684735.11071.113.camel@anglides.winder.org.uk> On Sat, 2013-01-19 at 12:31 -0800, anthonym wrote: > Hello All, > > I am new to Python and taking a course now. One of my exercises is to > create a traffic light using tkinter. The exercise also requires that I > create radio buttons that allow the user to click on the color and the > corresponding light will come on. A side-note here rather than a direct contribution to your problem at hand: radio buttons are not a good way of implementing traffic lights if internationalization is a factor. In the UK and other places, there is a state where both red and yellow are on at the same time. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From Marcin.Mleczko at onet.eu Mon Jan 21 15:45:05 2013 From: Marcin.Mleczko at onet.eu (Marcin Mleczko) Date: Mon, 21 Jan 2013 15:45:05 +0100 Subject: [Tutor] Question regular expressions - the non-greedy pattern In-Reply-To: References: Message-ID: <50FD5471.1070900@onet.eu> Hello, in the howto (http://docs.python.org/2/howto/regex.html#regex-howto) there are code examples near the end of the page (the non-greedy pattern) I am referring to: s = 'Title' >>> len(s) 32 >>> print re.match('<.*>', s).span() (0, 32) >>> print re.match('<.*>', s).group() Title print re.match('<.*?>', s).group() #<- I'm referring to this So far everything is fine. Now I'm changing the input string to (adding an extra '<'): s = '<Title' and evoking the last command again: print re.match('<.*?>', s).group() I would expect to get the same result as I'm using the non-greedy pattern. What I get is < Did I get the concept of non-greedy wrong or is this really a bug? I've treid this with python -V Python 2.7.3 on Win 7 64 Bit as well as Ubuntu 64 bit. I'd be glad to here from you soon. Thank's a lot for your effort. best regards Marcin From hugo.yoshi at gmail.com Mon Jan 21 16:36:44 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 21 Jan 2013 16:36:44 +0100 Subject: [Tutor] Question regular expressions - the non-greedy pattern In-Reply-To: <50FD5471.1070900@onet.eu> References: <50FD5471.1070900@onet.eu> Message-ID: On Mon, Jan 21, 2013 at 3:45 PM, Marcin Mleczko wrote: > Now I'm changing the input string to (adding an extra '<'): > > s = '<Title' > > and evoking the last command again: > > print re.match('<.*?>', s).group() > I would expect to get the same result > > > > as I'm using the non-greedy pattern. What I get is > > < > > Did I get the concept of non-greedy wrong or is this really a bug? > No, this is not a bug. Note first that you are using re.match, which only tries to match from the beginning of the string. If you want to match anywhere inside the string, you should use re.search, which returns the first match found. However even re.search will still return '<' since that *is* a valid match of the regular expression '<.*?>', and re.search returns the first match it finds. in essence, re.search first tries calling match(regex, s), then match(regex, s[1:]), then match(regex, s[2:]) and so on and so on, moving on one character at the time until the regular expression produces a match. Since the regex produces a match on the first character, matching on the second isn't even tried. It is true that non-greedy matching will try to match the fewest number of characters possible. However, it will not cause the regular expression engine to backtrack, i.e. go back on parts of the pattern already matched and match them elsewhere to try and see if that produces a shorter match. If a greedy variant of a regex matches, then the non-greedy variant *will* also match at the same place. The only difference is the length of the result. more generally, regexes can not parse HTML fully since they simply lack the power. HTML is just not a regular language. If you want to parse arbitrary HTML documents, or even sufficiently complex HTML documents you should get a real HTML parser library (python includes one, check the docs). If you just want to grab some data from HTML tags it's probably ok to use regexes though, if you're careful. HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Jan 21 17:23:39 2013 From: wprins at gmail.com (Walter Prins) Date: Mon, 21 Jan 2013 16:23:39 +0000 Subject: [Tutor] Question regular expressions - the non-greedy pattern In-Reply-To: <50FD5471.1070900@onet.eu> References: <50FD5471.1070900@onet.eu> Message-ID: Hi, On 21 January 2013 14:45, Marcin Mleczko wrote: > Did I get the concept of non-greedy wrong or is this really a bug? Hugo's already explained the essence of your problem, but just to add/reiterate: a) match() will match at the beginning of the string (first character) or not at all. As specified your regex does in fact match from the first character as shown so the result is correct. (Aside, "" in "<" does not in fact match *from the beginning of the string* so is besides the point for the match() call.) b) Changing your regexp so that the body of the tag *cannot* contain "<", and then using search() instead, will fix your specific case for you: import re s = '<Title' tag_regex = '<[^<]*?>' matchobj = re.match(tag_regex, s) print "re.match() result:", matchobj # prints None since no match at start of s matchobj = re.search(tag_regex, s) # prints something since regex matches at index 1 of string print "re.search() result:\n", print "span:", matchobj.span() print "group:", matchobj.group() Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Jan 21 17:32:09 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Jan 2013 03:32:09 +1100 Subject: [Tutor] Question regular expressions - the non-greedy pattern In-Reply-To: <50FD5471.1070900@onet.eu> References: <50FD5471.1070900@onet.eu> Message-ID: <50FD6D89.9080900@pearwood.info> On 22/01/13 01:45, Marcin Mleczko wrote: > Now I'm changing the input string to (adding an extra '<'): > > s = '<Title' > > and evoking the last command again: > > print re.match('<.*?>', s).group() > I would expect to get the same result > > > > as I'm using the non-greedy pattern. What I get is > > < > > Did I get the concept of non-greedy wrong or is this really a bug? Definitely not a bug. Your regex says: "Match from the beginning of the string: less-than sign, then everything up to the FIRST (non-greedy) greater-than sign." So it matches the "<" at the beginning of the string, followed by the "". To get the result you are after, you could do this: # Match two < signs, but only report from the second on re.match('<(<.*?>)', s).group(1) # Skip the first character re.match('<.*?>', s[1:]).group() # Don't match on < inside the <> tags re.search('<[^<]*?>', s).group() Notice that the last example must use re.search, not re.match, because it does not match the beginning of the string. By the way, you cannot parse general purpose HTML with a regular expressions. You really should learn how to use Python's html parsers, rather than trying to gerry-rig something that will do a dodgy job. -- Steven From Marcin.Mleczko at onet.eu Tue Jan 22 00:11:52 2013 From: Marcin.Mleczko at onet.eu (Marcin Mleczko) Date: Tue, 22 Jan 2013 00:11:52 +0100 Subject: [Tutor] Question regular expressions - the non-greedy pattern In-Reply-To: References: <50FD5471.1070900@onet.eu> Message-ID: <50FDCB38.5000805@onet.eu> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello Hugo, hello Walter, first thank you very much for the quick reply. The functions used here i.e. re.match() are taken directly form the example in the mentioned HowTo. I'd rather use re.findall() but I think the general interpretetion of the given regexp sould be nearly the same in both functions. So I'd like to neglect the choise of a particular function for a moment a concentrate on the pure theory. What I got so far: in theory form s = '<Title' '<.*?>' would match '' '' '' '' to achieve this the engine should: 1. walk forward along the text until it finds < 2. walk forward from that point until in finds > 3. walk backward form that point (the one of >) until it finds < 4. return the string between < from 3. and > from 2. as this gives the least possible string between < and > Did I get this right so far? Is this (=least possible string between < and >), what non-greedy really translates to? For some reason, I did not get so far the regexp engine in Python omits step 3. and returns the string between < from 1. and > from 2. resulting in '<' Am I right? If so, is there an easily graspable reason for the engine designers to implement it this way? If I'm wrong, where is my fault? Marcin Am 21.01.2013 17:23, schrieb Walter Prins: > Hi, > > > > On 21 January 2013 14:45, Marcin Mleczko > wrote: > > Did I get the concept of non-greedy wrong or is this really a bug? > > > Hugo's already explained the essence of your problem, but just to > add/reiterate: > > a) match() will match at the beginning of the string (first > character) or not at all. As specified your regex does in fact > match from the first character as shown so the result is correct. > (Aside, "" in "<" does not in fact match *from the > beginning of the string* so is besides the point for the match() > call.) > > b) Changing your regexp so that the body of the tag *cannot* > contain "<", and then using search() instead, will fix your > specific case for you: > > import re > > s = '<Title' tag_regex = '<[^<]*?>' > > matchobj = re.match(tag_regex, s) print "re.match() result:", > matchobj # prints None since no match at start of s > > matchobj = re.search(tag_regex, s) # prints something since regex > matches at index 1 of string print "re.search() result:\n", print > "span:", matchobj.span() print "group:", matchobj.group() > > > Walter > > -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.17 (MingW32) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iQEcBAEBAgAGBQJQ/cs4AAoJEDAt44dGkgj1CSUH/iT7b7jKafu8ugXGlNiLtISy Abt6GcAZuwxeuokH7dna4FGA54x5BZzjrglu+VWrRJx8hsherL04Qt216V725Tpx SN4IgLtK+AYAuhI73iBvyWK51vOTkWDzLrs6DYjNEWohw+n9QEtZVEkgMej/p760 6YDs8lbrHxVqUGiFTQr+vpCb6W85sOr+RlfkBsFibC3S17wRNVtaYWITc85I5Dfr lLBh2kPzi9ITKPIFag4GRNzj1rWtp0NUGGAjyhmgijdl2GbiCLAGteJGoUvajOa1 889UuPItCi4zVJ5PJv0PDej8eD0ppd+k0rRHQK3SgaSgtTDgviGOvs3Ch4A9/Sk= =Qo8U -----END PGP SIGNATURE----- From steve at pearwood.info Tue Jan 22 01:31:01 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Jan 2013 11:31:01 +1100 Subject: [Tutor] Question regular expressions - the non-greedy pattern In-Reply-To: <50FDCB38.5000805@onet.eu> References: <50FD5471.1070900@onet.eu> <50FDCB38.5000805@onet.eu> Message-ID: <50FDDDC5.6030500@pearwood.info> On 22/01/13 10:11, Marcin Mleczko wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hello Hugo, hello Walter, > > first thank you very much for the quick reply. > > The functions used here i.e. re.match() are taken directly form the > example in the mentioned HowTo. I'd rather use re.findall() but I > think the general interpretetion of the given regexp sould be nearly > the same in both functions. Regular expressions are not just "nearly" the same, they are EXACTLY the same, in whatever re function you call, with one exception: re.match only matches at the start of the string. > So I'd like to neglect the choise of a particular function for a > moment a concentrate on the pure theory. > What I got so far: > in theory form s = '<Title' > '<.*?>' would match'''''''' Incorrect. It will match '<' '' '' '' Why don't you try it and see? py> s = '<Title' py> import re py> re.findall('<.*?>', s) ['<', '', '', ''] The re module is very stable. The above is what happens in every Python version between *at least* 1.5 and 3.3. > to achieve this the engine should: > 1. walk forward along the text until it finds< Correct. That matches the first "<". > 2. walk forward from that point until in finds> Correct. That matches the first ">". Since the regex has now found a match, it moves on to the next part of the regex. Since this regex is now complete, it is done, and returns what it has found. > 3. walk backward form that point (the one of>) until it finds< Regexes only backtrack on *misses*, not once they successfully find a match. Once a regex has found a match, it is done. > 4. return the string between< from 3. and> from 2. as this gives the > least possible string between< and> Incorrect. > Did I get this right so far? Is this (=least possible string between< > and>), what non-greedy really translates to? No. The ".*" regex searches forward as far as possible; the ".*?" searches forward as little as possible. They do not backtrack. The only time a non-greedy regex will backtrack is if the greedy version will backtrack. Since ".*" has no reason to backtrack, neither does ".*?". > For some reason, I did not get so far the regexp engine in Python > omits step 3. and returns the string between< from 1. and> from 2. > resulting in '<' > > Am I right? If so, is there an easily graspable reason for the engine > designers to implement it this way? Because that's the way regexes work. You would need to learn about regular expression theory, which is not easy material. But you can start here: http://en.wikipedia.org/wiki/Regular_expression and for more theoretical approach: http://en.wikipedia.org/wiki/Chomsky_hierarchy http://en.wikipedia.org/wiki/Regular_language http://en.wikipedia.org/wiki/Regular_grammar If you don't understand all the theory, don't worry, neither do I. -- Steven From wprins at gmail.com Tue Jan 22 01:39:58 2013 From: wprins at gmail.com (Walter Prins) Date: Tue, 22 Jan 2013 00:39:58 +0000 Subject: [Tutor] Question regular expressions - the non-greedy pattern In-Reply-To: <50FDCB38.5000805@onet.eu> References: <50FD5471.1070900@onet.eu> <50FDCB38.5000805@onet.eu> Message-ID: Hi Marcin, On 21 January 2013 23:11, Marcin Mleczko wrote: > first thank you very much for the quick reply. > No problem... > The functions used here i.e. re.match() are taken directly form the > example in the mentioned HowTo. I'd rather use re.findall() but I > think the general interpretetion of the given regexp sould be nearly > the same in both functions. > ... except that the results are fundamentally different due to the different goals for the 2 functions: the one (match) only matches a regex from the first character of a string. (No conceptual "walking forward" unless you've managed to match the string to a regex.) The other (find), matches the first possible match (conceptually walking the starting point forward only as far as necessary to find a possible match.) > So I'd like to neglect the choise of a particular function for a > moment a concentrate on the pure theory. > What I got so far: > in theory form s = '<Title' > '<.*?>' would match '' '' '' '' > to achieve this the engine should: > 1. walk forward along the text until it finds < > 2. walk forward from that point until in finds > > Here, conceptually the regex engines work for your original regex is complete and it returns a match. > 3. walk backward form that point (the one of >) until it finds < > No. No further walking backward when you've already matched the regex. 4. return the string between < from 3. and > from 2. as this gives the > least possible string between < and > > "Non greedy" doesn't imply the conceptually altering the starting point in a backwards manner after you've already found a match. > Did I get this right so far? Is this (=least possible string between < > and >), what non-greedy really translates to? > No, as explained above. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Jan 22 01:44:31 2013 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 22 Jan 2013 11:44:31 +1100 Subject: [Tutor] Question regular expressions - the non-greedy pattern In-Reply-To: <50FDCB38.5000805@onet.eu> References: <50FD5471.1070900@onet.eu> <50FDCB38.5000805@onet.eu> Message-ID: On 22/01/13 10:11, Marcin Mleczko wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hello Hugo, hello Walter, > > first thank you very much for the quick reply. > > The functions used here i.e. re.match() are taken directly form the > example in the mentioned HowTo. I'd rather use re.findall() but I > think the general interpretetion of the given regexp sould be nearly > the same in both functions. > > So I'd like to neglect the choise of a particular function for a > moment a concentrate on the pure theory. > What I got so far: > in theory form s = '<Title' > '<.*?>' would match '' '' '' '' > to achieve this the engine should: > 1. walk forward along the text until it finds < > 2. walk forward from that point until in finds > > 3. walk backward form that point (the one of >) until it finds < > 4. return the string between < from 3. and > from 2. as this gives the > least possible string between < and > > > Did I get this right so far? Is this (=least possible string between < > and >), what non-greedy really translates to? Nope, that's not how regex works. In particular, it does not do step 3, non-greedy regex do not walk backward to find the shortest string that matches. What it does for the non-greedy pattern <.*?> is: 1. walk forward along the text until it finds < 2. if the next character matches . (any chars) then step one character forward, otherwise backtrack from where we left off in the previous step 3. if the next char is >, then we find a match, otherwise backtrack from where we left off in the previous step 4. return the string between < from 1 and > from 3 or alternatively 1. walk forward along the text until it finds < 2. walk forward from that point until in finds > 3. return the string between < from 1 and > from 2 From alan.gauld at btinternet.com Tue Jan 22 01:45:15 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Jan 2013 00:45:15 +0000 Subject: [Tutor] Question regular expressions - the non-greedy pattern In-Reply-To: <50FDCB38.5000805@onet.eu> References: <50FD5471.1070900@onet.eu> <50FDCB38.5000805@onet.eu> Message-ID: Your understanding is flawed. Try these actions and ponder their significance... >>> s = '<Title' >>> re.search('<.*?>',s).group() '<' >>> re.search('<.*>',s).group() '<Title' >>> s = '<Title-title' >>> re.search('<.*>',s).group() '<<html><head><title>' >>> re.search('<.*t',s).group() '<<html><head><title>Title-tit' >>> re.search('<.*?t',s).group() '<<ht' >>> The non greediness applies to what follows the '?' not what precedes it. That is, it swallows everything up until the last possible matching pattern by default. Non greedy only swallows up to the first matching pattern after the ? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From Marcin.Mleczko at onet.eu Tue Jan 22 12:30:16 2013 From: Marcin.Mleczko at onet.eu (Marcin Mleczko) Date: Tue, 22 Jan 2013 12:30:16 +0100 Subject: [Tutor] Question regular expressions - the non-greedy pattern In-Reply-To: <mailman.13.1358852402.9721.tutor@python.org> References: <mailman.13.1358852402.9721.tutor@python.org> Message-ID: <50FE7848.3030800@onet.eu> Now I think I got it. Thanks a lot again. Marcin Am 22.01.2013 12:00, schrieb tutor-request at python.org: > > Message: 1 > Date: Tue, 22 Jan 2013 11:31:01 +1100 > From: Steven D'Aprano <steve at pearwood.info> > To: tutor at python.org > Subject: Re: [Tutor] Question regular expressions - the non-greedy > pattern > Message-ID: <50FDDDC5.6030500 at pearwood.info> > Content-Type: text/plain; charset=UTF-8; format=flowed > > On 22/01/13 10:11, Marcin Mleczko wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> Hello Hugo, hello Walter, >> >> first thank you very much for the quick reply. >> >> The functions used here i.e. re.match() are taken directly form the >> example in the mentioned HowTo. I'd rather use re.findall() but I >> think the general interpretetion of the given regexp sould be nearly >> the same in both functions. > > Regular expressions are not just "nearly" the same, they are EXACTLY > the same, in whatever re function you call, with one exception: > > re.match only matches at the start of the string. > > >> So I'd like to neglect the choise of a particular function for a >> moment a concentrate on the pure theory. >> What I got so far: >> in theory form s = '<<html><head><title>Title' >> '<.*?>' would match'''''''' > > Incorrect. It will match > > '<' > '' > '' > '' > > > Why don't you try it and see? > > py> s = '<Title' > py> import re > py> re.findall('<.*?>', s) > ['<', '', '', ''] > > > The re module is very stable. The above is what happens in every Python > version between *at least* 1.5 and 3.3. > > >> to achieve this the engine should: >> 1. walk forward along the text until it finds< > > Correct. That matches the first "<". > > >> 2. walk forward from that point until in finds> > > Correct. That matches the first ">". > > Since the regex has now found a match, it moves on to the next part > of the regex. Since this regex is now complete, it is done, and > returns what it has found. > > >> 3. walk backward form that point (the one of>) until it finds< > > Regexes only backtrack on *misses*, not once they successfully find > a match. Once a regex has found a match, it is done. > > >> 4. return the string between< from 3. and> from 2. as this gives the >> least possible string between< and> > > Incorrect. > > >> Did I get this right so far? Is this (=least possible string between< >> and>), what non-greedy really translates to? > > No. The ".*" regex searches forward as far as possible; the ".*?" searches > forward as little as possible. They do not backtrack. > > The only time a non-greedy regex will backtrack is if the greedy version > will backtrack. Since ".*" has no reason to backtrack, neither does ".*?". > > >> For some reason, I did not get so far the regexp engine in Python >> omits step 3. and returns the string between< from 1. and> from 2. >> resulting in '<' >> >> Am I right? If so, is there an easily graspable reason for the engine >> designers to implement it this way? > > Because that's the way regexes work. You would need to learn about > regular expression theory, which is not easy material. But you can start > here: > > http://en.wikipedia.org/wiki/Regular_expression > > and for more theoretical approach: > > http://en.wikipedia.org/wiki/Chomsky_hierarchy > http://en.wikipedia.org/wiki/Regular_language > http://en.wikipedia.org/wiki/Regular_grammar > > If you don't understand all the theory, don't worry, neither do I. > > > From anthonym at att.net Wed Jan 23 03:52:07 2013 From: anthonym at att.net (anthonym) Date: Tue, 22 Jan 2013 18:52:07 -0800 Subject: [Tutor] Calculate hours Message-ID: Hello All, I originally wrote this program to calculate and print the employee with the most hours worked in a week. I would now like to change this to calculate and print the hours for all 8 employees in ascending order. The employees are named employee 0 - 8 Any ideas? Thanks, Tony Code below: # Create table of hours worked matrix = [ [2, 4, 3, 4, 5, 8, 8], [7, 3, 4, 3, 3, 4, 4], [3, 3, 4, 3, 3, 2, 2], [9, 3, 4, 7, 3, 4, 1], [3, 5, 4, 3, 6, 3, 8], [3, 4, 4, 6, 3, 4, 4], [3, 7, 4, 8, 3, 8, 4], [6, 3, 5, 9, 2, 7, 9]] maxRow = sum(matrix[0]) # Get sum of the first row in maxRow indexOfMaxRow = 0 for row in range(1, len(matrix)): if sum(matrix[row]) > maxRow: maxRow = sum(matrix[row]) indexOfMaxRow = row print("Employee 7", indexOfMaxRow, "has worked: ", maxRow, "hours") -------------- next part -------------- An HTML attachment was scrubbed... URL: From msirenef at lightbird.net Wed Jan 23 04:08:58 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Tue, 22 Jan 2013 22:08:58 -0500 Subject: [Tutor] Calculate hours In-Reply-To: References: Message-ID: <50FF544A.7000905@lightbird.net> On 01/22/2013 09:52 PM, anthonym wrote: > Hello All, > > I originally wrote this program to calculate and print the employee > with the most hours worked in a week. I would now like to change this > to calculate and print the hours for all 8 employees in ascending > order. > > The employees are named employee 0 - 8 > > Any ideas? > > Thanks, > Tony > > Code below: > > > > # Create table of hours worked > > matrix = [ > [2, 4, 3, 4, 5, 8, 8], > [7, 3, 4, 3, 3, 4, 4], > [3, 3, 4, 3, 3, 2, 2], > [9, 3, 4, 7, 3, 4, 1], > [3, 5, 4, 3, 6, 3, 8], > [3, 4, 4, 6, 3, 4, 4], > [3, 7, 4, 8, 3, 8, 4], > [6, 3, 5, 9, 2, 7, 9]] > > maxRow = sum(matrix[0]) # Get sum of the first row in maxRow > indexOfMaxRow = 0 > > for row in range(1, len(matrix)): > if sum(matrix[row]) > maxRow: > maxRow = sum(matrix[row]) > indexOfMaxRow = row > > print("Employee 7", indexOfMaxRow, "has worked: ", maxRow, "hours") There is an issue with this program: it omits the first row. It's better to use enumerate, e.g.: for n, row in enumerate(matrix): ... To make the change you need, use list comprehension to make sums of all rows, sort it (using list sort method); iterate over it using enumerate() and print out "employee N, sum of hours:" HTH, -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Idleness is the mother of psychology. Friedrich Nietzsche From d at davea.name Wed Jan 23 04:10:43 2013 From: d at davea.name (Dave Angel) Date: Tue, 22 Jan 2013 22:10:43 -0500 Subject: [Tutor] Calculate hours In-Reply-To: References: Message-ID: <50FF54B3.70405@davea.name> On 01/22/2013 09:52 PM, anthonym wrote: > Hello All, > > I originally wrote this program to calculate and print the employee with the > most hours worked in a week. I would now like to change this to calculate > and print the hours for all 8 employees in ascending order. > > The employees are named employee 0 - 8 > > Any ideas? > > Thanks, > Tony > > Code below: > > > > # Create table of hours worked > > matrix = [ > [2, 4, 3, 4, 5, 8, 8], > [7, 3, 4, 3, 3, 4, 4], > [3, 3, 4, 3, 3, 2, 2], > [9, 3, 4, 7, 3, 4, 1], > [3, 5, 4, 3, 6, 3, 8], > [3, 4, 4, 6, 3, 4, 4], > [3, 7, 4, 8, 3, 8, 4], > [6, 3, 5, 9, 2, 7, 9]] > > maxRow = sum(matrix[0]) # Get sum of the first row in maxRow > indexOfMaxRow = 0 > > for row in range(1, len(matrix)): > if sum(matrix[row]) > maxRow: > maxRow = sum(matrix[row]) > indexOfMaxRow = row > > print("Employee 7", indexOfMaxRow, "has worked: ", maxRow, "hours") > > What other constraints does your professor make? For example, are you allowed to use sorting with custom key function? If you want to keep it simple, then invert your logic to find the min element. Then after finding that min element, print it, delete it, and repeat the whole thing till the matrix is empty. -- DaveA From d at davea.name Wed Jan 23 04:34:07 2013 From: d at davea.name (Dave Angel) Date: Tue, 22 Jan 2013 22:34:07 -0500 Subject: [Tutor] Calculate hours In-Reply-To: <50FF544A.7000905@lightbird.net> References: <50FF544A.7000905@lightbird.net> Message-ID: <50FF5A2F.40909@davea.name> On 01/22/2013 10:08 PM, Mitya Sirenef wrote: > On 01/22/2013 09:52 PM, anthonym wrote: >> Hello All, > > > > I originally wrote this program to calculate and print the employee > > with the most hours worked in a week. I would now like to change this > > to calculate and print the hours for all 8 employees in ascending > > order. > > > > The employees are named employee 0 - 8 > > > > Any ideas? > > > > Thanks, > > Tony > > > > Code below: > > > > > > > > # Create table of hours worked > > > > matrix = [ > > [2, 4, 3, 4, 5, 8, 8], > > [7, 3, 4, 3, 3, 4, 4], > > [3, 3, 4, 3, 3, 2, 2], > > [9, 3, 4, 7, 3, 4, 1], > > [3, 5, 4, 3, 6, 3, 8], > > [3, 4, 4, 6, 3, 4, 4], > > [3, 7, 4, 8, 3, 8, 4], > > [6, 3, 5, 9, 2, 7, 9]] > > > > maxRow = sum(matrix[0]) # Get sum of the first row in maxRow > > indexOfMaxRow = 0 > > > > for row in range(1, len(matrix)): > > if sum(matrix[row]) > maxRow: > > maxRow = sum(matrix[row]) > > indexOfMaxRow = row > > > > print("Employee 7", indexOfMaxRow, "has worked: ", maxRow, "hours") > > > There is an issue with this program: it omits the first row. No, it doesn't. The OP fills in item 0 in the initial values for maxRow and indexOfMaxRow. Then he figures he can skip that row in the loop, which is correct. > > It's better to use enumerate, e.g.: > > for n, row in enumerate(matrix): ... > > > To make the change you need, use list comprehension to make sums of all > rows, sort it (using list sort method); iterate over it using > enumerate() and print out "employee N, sum of hours:" > > > HTH, -m > > -- DaveA From msirenef at lightbird.net Wed Jan 23 04:55:22 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Tue, 22 Jan 2013 22:55:22 -0500 Subject: [Tutor] Calculate hours In-Reply-To: <50FF5A2F.40909@davea.name> References: <50FF544A.7000905@lightbird.net> <50FF5A2F.40909@davea.name> Message-ID: <50FF5F2A.8060906@lightbird.net> On 01/22/2013 10:34 PM, Dave Angel wrote: > On 01/22/2013 10:08 PM, Mitya Sirenef wrote: >> On 01/22/2013 09:52 PM, anthonym wrote: >>> Hello All, >> > >> > I originally wrote this program to calculate and print the employee >> > with the most hours worked in a week. I would now like to change this >> > to calculate and print the hours for all 8 employees in ascending >> > order. >> > >> > The employees are named employee 0 - 8 >> > >> > Any ideas? >> > >> > Thanks, >> > Tony >> > >> > Code below: >> > >> > >> > >> > # Create table of hours worked >> > >> > matrix = [ >> > [2, 4, 3, 4, 5, 8, 8], >> > [7, 3, 4, 3, 3, 4, 4], >> > [3, 3, 4, 3, 3, 2, 2], >> > [9, 3, 4, 7, 3, 4, 1], >> > [3, 5, 4, 3, 6, 3, 8], >> > [3, 4, 4, 6, 3, 4, 4], >> > [3, 7, 4, 8, 3, 8, 4], >> > [6, 3, 5, 9, 2, 7, 9]] >> > >> > maxRow = sum(matrix[0]) # Get sum of the first row in maxRow >> > indexOfMaxRow = 0 >> > >> > for row in range(1, len(matrix)): >> > if sum(matrix[row]) > maxRow: >> > maxRow = sum(matrix[row]) >> > indexOfMaxRow = row >> > >> > print("Employee 7", indexOfMaxRow, "has worked: ", maxRow, "hours") >> >> >> There is an issue with this program: it omits the first row. > > No, it doesn't. The OP fills in item 0 in the initial values for maxRow and indexOfMaxRow. Then he figures he can skip that row in the loop, which is correct. Yes, I noticed after writing the reply.. To the OP: that's an odd way to handle it, you can set maxRow to 0 and then iterate over all rows. -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Habit is stronger than reason. George Santayana From anthonym at att.net Wed Jan 23 05:18:49 2013 From: anthonym at att.net (anthonym) Date: Tue, 22 Jan 2013 20:18:49 -0800 Subject: [Tutor] Calculate hours In-Reply-To: <50FF54B3.70405@davea.name> Message-ID: Thanks Dave I think I would like to keep it simple. How would I get it to repeat and print before deleting? On 1/22/13 7:10 PM, "Dave Angel" wrote: >On 01/22/2013 09:52 PM, anthonym wrote: >> Hello All, >> >> I originally wrote this program to calculate and print the employee >>with the >> most hours worked in a week. I would now like to change this to >>calculate >> and print the hours for all 8 employees in ascending order. >> >> The employees are named employee 0 - 8 >> >> Any ideas? >> >> Thanks, >> Tony >> >> Code below: >> >> >> >> # Create table of hours worked >> >> matrix = [ >> [2, 4, 3, 4, 5, 8, 8], >> [7, 3, 4, 3, 3, 4, 4], >> [3, 3, 4, 3, 3, 2, 2], >> [9, 3, 4, 7, 3, 4, 1], >> [3, 5, 4, 3, 6, 3, 8], >> [3, 4, 4, 6, 3, 4, 4], >> [3, 7, 4, 8, 3, 8, 4], >> [6, 3, 5, 9, 2, 7, 9]] >> >> maxRow = sum(matrix[0]) # Get sum of the first row in maxRow >> indexOfMaxRow = 0 >> >> for row in range(1, len(matrix)): >> if sum(matrix[row]) > maxRow: >> maxRow = sum(matrix[row]) >> indexOfMaxRow = row >> >> print("Employee 7", indexOfMaxRow, "has worked: ", maxRow, "hours") >> >> > >What other constraints does your professor make? For example, are you >allowed to use sorting with custom key function? > >If you want to keep it simple, then invert your logic to find the min >element. Then after finding that min element, print it, delete it, and >repeat the whole thing till the matrix is empty. > > > > >-- >DaveA >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor From d at davea.name Wed Jan 23 11:12:42 2013 From: d at davea.name (Dave Angel) Date: Wed, 23 Jan 2013 05:12:42 -0500 Subject: [Tutor] Calculate hours In-Reply-To: References: Message-ID: <50FFB79A.8040201@davea.name> On 01/22/2013 11:18 PM, anthonym wrote: > Thanks Dave > > I think I would like to keep it simple. How would I get it to repeat and > print before deleting? > To repeat something, write a loop. So you have a while loop *outside* the one you've written (you'll have to indent your present loop another level). The condition for the while loop is simply a test to see if matrix has any elements in it. So your outer loop loops till the matrix is empty. Inside the loop, determine the minimum element, print it out, then delete it. If you're familiar with functions yet, then move the inner loop into its own function, and it'll read more clearly. -- DaveA From alan.gauld at btinternet.com Thu Jan 24 00:13:53 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Jan 2013 23:13:53 +0000 Subject: [Tutor] Calculate hours In-Reply-To: <50FF544A.7000905@lightbird.net> References: <50FF544A.7000905@lightbird.net> Message-ID: On 23/01/13 03:08, Mitya Sirenef wrote: > To make the change you need, use list comprehension to make sums of all > rows, sort it (using list sort method); iterate over it using > enumerate() and print out "employee N, sum of hours:" One problem with that approach is that the employees are identified by their index in the original row so you probably need to maintain a note of that index. So before sorting you might want to create a tuple with the id and the values then sort on the second element. Only slightly more complex... hth. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Thu Jan 24 00:19:13 2013 From: d at davea.name (Dave Angel) Date: Wed, 23 Jan 2013 18:19:13 -0500 Subject: [Tutor] Calculate hours In-Reply-To: References: <50FF544A.7000905@lightbird.net> Message-ID: <51006FF1.4050206@davea.name> On 01/23/2013 06:13 PM, Alan Gauld wrote: > On 23/01/13 03:08, Mitya Sirenef wrote: > >> To make the change you need, use list comprehension to make sums of all >> rows, sort it (using list sort method); iterate over it using >> enumerate() and print out "employee N, sum of hours:" > > One problem with that approach is that the employees are identified by > their index in the original row so you probably need to maintain a note > of that index. So before sorting you might want to create a tuple > with the id and the values then sort on the second element. Only > slightly more complex... > Complex or not, the first question is whether the OP's class has covered sorting yet. And especially supplying key functions. I suspect not. BTW, if I were building the tuples, I'd just let the key value be first, and the index be second. That way the default key function works great. -- DaveA From msirenef at lightbird.net Thu Jan 24 00:24:47 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Wed, 23 Jan 2013 18:24:47 -0500 Subject: [Tutor] Calculate hours In-Reply-To: References: <50FF544A.7000905@lightbird.net> Message-ID: <5100713F.6000509@lightbird.net> On 01/23/2013 06:13 PM, Alan Gauld wrote: > On 23/01/13 03:08, Mitya Sirenef wrote: > >> To make the change you need, use list comprehension to make sums of all >> rows, sort it (using list sort method); iterate over it using >> enumerate() and print out "employee N, sum of hours:" > > One problem with that approach is that the employees are identified by their index in the original row so you probably need to maintain a note of that index. So before sorting you might want to create a tuple > with the id and the values then sort on the second element. Only slightly more complex... > > hth. > Oh, that's right - thanks for catching this. -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ The best author will be the one who is ashamed to become a writer. Friedrich Nietzsche From anthonym at att.net Thu Jan 24 02:00:32 2013 From: anthonym at att.net (anthonym) Date: Wed, 23 Jan 2013 17:00:32 -0800 Subject: [Tutor] Calculate hours In-Reply-To: <51006CD1.7030307@davea.name> Message-ID: Thanks Dave. I forgot to hit the reply to all last time. I am going to try the loop when I get back home and will let you know how I make out. Also we have done some functions. Sort and append being among them. I try the simplest way first then stream line later. Probably not the fastest way. Tony On 1/23/13 3:05 PM, "Dave Angel" wrote: >You posted this privately to me. It should have been a message to the >forum, with tutor at python.org as its to: field. > >On 01/23/2013 10:42 AM, anthonym wrote: >> Should the outside loop have a print command in it so I don't loose that >> information like I do now? >> > >Yes, the print and the delete are technically in the outer loop. I was >thinking in terms of a function, in which case I probably would have >included those two elements in the function. But my wording was wrong. > >Can you write an attempted solution, and post it to the thread, along >with whatever difficulty you still see? > >Rough pseudo-code > >while something-in-list > find minimum element (this is a loop, similar to the one you >already wrote) > print out whatever you need from that element > delete that element > >print out "success" > > > >-- >DaveA From scs.bns001 at gmail.com Thu Jan 24 06:32:24 2013 From: scs.bns001 at gmail.com (SCS Barry) Date: Thu, 24 Jan 2013 00:32:24 -0500 Subject: [Tutor] Small personal project to fill CDs/DVDs... Message-ID: Need to fill some DVDs. Figured Python would be the tool to quickly write this tool in, since I have seen similar tools written in python. I even found something onlist to start from... from August 2004. Sent: Sunday, August 15, 2004 9:22 PM Subject: Re: [Tutor] List files in directory "Bernard Lebel" wrote: > > Hello, > > Anyone has advice on how to collect filenames from a directory? > I want to print only the files contains in the currently visited directory. This is simple enough that I can help: import os path="C:\\somedirectory" # insert the path to the directory of interest here dirList=os.listdir(path) for fname in dirList: print fname I have lots of DOS, Unix and Linux scripts, as well as 30 years of development in all types of environments. I am currently looking to create a python application that works on many different platforms, but can work without problems on Windows (ALL), Linux (ALL) using Gtk/xfce/other (need suggestions), and Unix (really need suggestions). Need help in defining environment standards to research learn, and looking for pointers in modules to use developing my new open source app. ;) Scratchy overview -- Full solution for me will accept start directory and -c or -d parm (CD/DVD) if passed from command line or shell script. If start directory is not passed, there will be a "browse" interface to choose the directory to start from (will determine OS from os call) and a media drop-down selection. Will require a standard GUI environment like windows/gtk/"something". The main process will create a list of fully-qualified file names, file sizes. Then, it will build a grouped list of files, filling media as effectively as possible. Last, it will print on screen the lists of FQFNs and filesizes that will go on each backup disk. Should be just a list of simple printfs. I have done some maintenance on python, but this is the first app that I have written from scratch, so I need to focus on each area -- Barry Smith Secure Computer Services c 704-497-4217 e bnsmith001 at gmail.com e scs.bns001 at gmail.com w1 http://bit.ly/l8QJup w2 http://scs-llc.info/ DUNS 83-099-9384 EIN 27-4523550 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 24 09:38:03 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Jan 2013 08:38:03 +0000 Subject: [Tutor] Small personal project to fill CDs/DVDs... In-Reply-To: References: Message-ID: On 24/01/13 05:32, SCS Barry wrote: > Need to fill some DVDs. Sounds like an interesting project. Most of what you need is in the os module. > create a python application that works on many different platforms, but > can work without problems on Windows (ALL), Linux (ALL) using > Gtk/xfce/other (need suggestions), and Unix (really need suggestions). Tkinter or even EasyGUI should work fine for this and is portable. > Full solution for me will accept start directory and -c or -d parm How do you specify the size? CD Roms come in 650M, 800M and 900M variants (probably more!) Same with DVDs, single sided v double etc... > is not passed, there will be a "browse" interface to choose the > directory to start from (will determine OS from os call) and a media > drop-down selection. Will require a standard GUI environment like > windows/gtk/"something". Any GUI framework will do that. > The main process will create a list of fully-qualified file names, file > sizes. listdir or os.walk will do that combined with the file property functions to get size. > Then, it will build a grouped list of files, filling media as > effectively as possible. Thats just standard programming. Wikipedia might have saome best-fit algorithms that can help. > Last, it will print on screen the lists of FQFNs and filesizes that will > go on each backup disk. Again straight programming. The trickiest bit might be the actual writing to the media. I'm not sure how you do that portably... More research there I suspect. Maybe the OS will do it transparently if you are lucky. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bettame at gmail.com Thu Jan 24 14:29:05 2013 From: bettame at gmail.com (Krupkina Lesya Olegovna) Date: Thu, 24 Jan 2013 17:29:05 +0400 Subject: [Tutor] String formatting expression "g" conversion type case. Message-ID: <1848362719.20130124172905@gmail.com> Hello! I?m newcomer to Python and I?m on documentation reading stage and trying some of examples. I?m using Win7 x64 OS and Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)]. I try to understand how string format expression (%)works. Everything is almost clear but except one case: using ofg(G) conversion type and # flag. Let?s take a look at documentation here: http://docs.python.org/release/2.7.3/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange Document declares for g(G) conversion type in case of using # flag (4th note): ?The precision determines the number of significant digits before and after the decimal point and defaults to 6?. I have noticed behavior that does not meet documentation declaration and looks like a bug in case when using g(G) conversion type with # flag with omitted precision and zero integer part of the decimal. Could someone, please comment the case it is a bug or right use case result? If it is correct, please explain why. Steps to reproduce the case: 1.Start python interactive mode 2.Enter string with g(G) conversion type and using #flag like this: "%#g"%0.3 ? precision parameter is omitted and integer part of the decimal is zero. 3.Watch the output results Actual result: Python outputs decimal as declared as but with more significant digits than default value of 6 - if integer part of the decimal is equal to zero. >>> "%#g"%0.3 '0.300000' >>> "%#G"%0.3 '0.300000' >>> "%#G"%0.004 '0.00400000' >>> Expected results: As declared in documentation ? there will be 6 significant digits before and after decimal point by default. Thanks, Regards, Lesya. From chigga101 at gmail.com Thu Jan 24 14:46:08 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 24 Jan 2013 13:46:08 +0000 Subject: [Tutor] how can i use python 2 alongside 3? Message-ID: hi guys i am a python 3.1.1. user but really need to use python 2 to be able to use certain libraries and frameworks. i have installed python 2.7 but they cant run together as all .py and .pyw files are opened with python 3. i can open simple python 2 files by right clicking and finding pythons 2's python.exe, but these only works for simple files with no imports because the import i think seems to look in the python 3 directory and can't find the packages. i have checked stackoverflow for answers but i get lost in all the terms and keywords they use to solve this. is there a simple straightfoward way to fix this that is easy for someone like me to understand or follow? thanks. i use windows vista From __peter__ at web.de Thu Jan 24 15:12:10 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Jan 2013 15:12:10 +0100 Subject: [Tutor] String formatting expression "g" conversion type case. References: <1848362719.20130124172905@gmail.com> Message-ID: Krupkina Lesya Olegovna wrote: > Python outputs decimal as declared as but with more significant digits > than default value of 6 - if integer part of the decimal is equal to zero. >>>> "%#g"%0.3 > '0.300000' In this context "significant digits" are the first non-zero digit and any digits (including zero) that follow it. From bds at waywood.co.uk Thu Jan 24 15:23:21 2013 From: bds at waywood.co.uk (Barnaby Scott) Date: Thu, 24 Jan 2013 14:23:21 +0000 Subject: [Tutor] String formatting expression "g" conversion type case. In-Reply-To: <1848362719.20130124172905@gmail.com> References: <1848362719.20130124172905@gmail.com> Message-ID: <510143D9.5040807@waywood.co.uk> On 24/01/2013 13:29, Krupkina Lesya Olegovna wrote: > Hello! > I?m newcomer to Python and I?m on documentation reading stage and trying some of examples. > I?m using Win7 x64 OS and Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)]. > I try to understand how string format expression (%)works. Everything is almost clear but except one case: using ofg(G) conversion type and # flag. > Let?s take a look at documentation here: > http://docs.python.org/release/2.7.3/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange > Document declares for g(G) conversion type in case of using # flag (4th note): > ?The precision determines the number of significant digits before and after the decimal point and defaults to 6?. > > I have noticed behavior that does not meet documentation declaration and looks like a bug in case when using g(G) conversion type with # flag > with omitted precision and zero integer part of the decimal. Could > someone, please comment the case it is a bug or right use case result? If it is correct, please explain why. > > Steps to reproduce the case: > > 1.Start python interactive mode > 2.Enter string with g(G) conversion type and using #flag like this: "%#g"%0.3 ? precision parameter is omitted and integer part of the decimal is zero. > 3.Watch the output results > > Actual result: > > Python outputs decimal as declared as but with more significant digits than default value of 6 - if integer part of the decimal is equal to zero. >>>> "%#g"%0.3 > '0.300000' >>>> "%#G"%0.3 > '0.300000' >>>> "%#G"%0.004 > '0.00400000' >>>> > > Expected results: > As declared in documentation ? there will be 6 significant digits before and after decimal point by default. > > Thanks, > Regards, Lesya. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > My experience is that things that look odd at first sight are VERY rarely bugs - especially in something as mature as Python 2.7. Maybe the documentation could be slightly clearer, but I see it as saying the following: '#g' and '#G' both convert to exponential format (with some exceptions) with a default precision of 6 *significant figures*. It is certainly talking about significant figures, not decimal places. So your final example may look odd, but it really is doing what it says - there are 6 s.f. shown, and it has not converted to exponential form because the exponent would not be less than -4. With significant digits before the decimal point, it appears to convert to exponential form only if the number of them exceeds the precision. Best Barnaby From breamoreboy at yahoo.co.uk Thu Jan 24 15:28:02 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Jan 2013 14:28:02 +0000 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: Message-ID: On 24/01/2013 13:46, Matthew Ngaha wrote: > hi guys i am a python 3.1.1. user but really need to use python 2 to > be able to use certain libraries and frameworks. i have installed > python 2.7 but they cant run together as all .py and .pyw files are > opened with python 3. i can open simple python 2 files by right > clicking and finding pythons 2's python.exe, but these only works for > simple files with no imports because the import i think seems to look > in the python 3 directory and can't find the packages. > > i have checked stackoverflow for answers but i get lost in all the > terms and keywords they use to solve this. is there a simple > straightfoward way to fix this that is easy for someone like me to > understand or follow? > > thanks. i use windows vista > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > See http://www.python.org/dev/peps/pep-0397/ which leads to https://bitbucket.org/vinay.sajip/pylauncher -- Cheers. Mark Lawrence From d at davea.name Thu Jan 24 16:53:42 2013 From: d at davea.name (Dave Angel) Date: Thu, 24 Jan 2013 10:53:42 -0500 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: Message-ID: <51015906.9080205@davea.name> On 01/24/2013 08:46 AM, Matthew Ngaha wrote: > hi guys i am a python 3.1.1. user but really need to use python 2 to > be able to use certain libraries and frameworks. i have installed > python 2.7 but they cant run together as all .py and .pyw files are > opened with python 3. i can open simple python 2 files by right > clicking and finding pythons 2's python.exe, but these only works for > simple files with no imports because the import i think seems to look > in the python 3 directory and can't find the packages. > > i have checked stackoverflow for answers but i get lost in all the > terms and keywords they use to solve this. is there a simple > straightfoward way to fix this that is easy for someone like me to > understand or follow? > > thanks. i use windows vista > Python 3.3 for Windows comes with a "launcher", which will approximate (for Python only) what Unix and Linux users have had for years for any scripting language. You can get it separately, as Mark Lawrence has said, but maybe it's time to bring your 3.x current. -- DaveA From chigga101 at gmail.com Thu Jan 24 17:11:04 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 24 Jan 2013 16:11:04 +0000 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: <51015906.9080205@davea.name> References: <51015906.9080205@davea.name> Message-ID: > > Python 3.3 for Windows comes with a "launcher", which will approximate (for > Python only) what Unix and Linux users have had for years for any scripting > language. You can get it separately, as Mark Lawrence has said, but maybe > it's time to bring your 3.x current. > there was a lot of reading in the previous links, i got a bit lost as i didnt recognize a lot of the words they were using. If i install Pyhon 3.3 do i need to uninstall my current python 3.1 and reinstall all the downloaded modules/packages i installed? From d at davea.name Thu Jan 24 17:38:05 2013 From: d at davea.name (Dave Angel) Date: Thu, 24 Jan 2013 11:38:05 -0500 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: <51015906.9080205@davea.name> Message-ID: <5101636D.3060601@davea.name> On 01/24/2013 11:11 AM, Matthew Ngaha wrote: >> >> Python 3.3 for Windows comes with a "launcher", which will approximate (for >> Python only) what Unix and Linux users have had for years for any scripting >> language. You can get it separately, as Mark Lawrence has said, but maybe >> it's time to bring your 3.x current. >> > there was a lot of reading in the previous links, i got a bit lost as > i didnt recognize a lot of the words they were using. If i install > Pyhon 3.3 do i need to uninstall my current python 3.1 and reinstall > all the downloaded modules/packages i installed? I don't really know, so all the rest of this message is a guess. My guess is that 3.1 and 3.3 can coexist, but that you'd need to reinstall the modules/packages that you're using, and hope that they all can handle 3.3 When upgrading a minor upgrade (eg. from 3.1.1 to 3.1.2), I believe it'd go in the same place, and not require reinstalling the packages. -- DaveA From breamoreboy at yahoo.co.uk Thu Jan 24 18:04:33 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 Jan 2013 17:04:33 +0000 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: <51015906.9080205@davea.name> Message-ID: On 24/01/2013 16:11, Matthew Ngaha wrote: > > there was a lot of reading in the previous links, i got a bit lost as > i didnt recognize a lot of the words they were using. If i install > Pyhon 3.3 do i need to uninstall my current python 3.1 and reinstall > all the downloaded modules/packages i installed? > You don't have to uninstall 3.1 but you would have to install all the downloaded modules or packages that you have in your 3.1 site packages folder to the 3.3 site packages folder. Maybe it's easier to simply grab the standalone pylauncher as I suggested earlier. Only you know what is the path of least resistance. -- Cheers. Mark Lawrence From chigga101 at gmail.com Thu Jan 24 18:36:55 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 24 Jan 2013 17:36:55 +0000 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: <51015906.9080205@davea.name> Message-ID: > > You don't have to uninstall 3.1 but you would have to install all the > downloaded modules or packages that you have in your 3.1 site packages > folder to the 3.3 site packages folder. Maybe it's easier to simply grab > the standalone pylauncher as I suggested earlier. Only you know what is the > path of least resistance. > yes the 2nd option (standalone pylauncher) sounds more convienient for me. i just have to try and comprehend all the instructions given.. hopefully ill get there in the end From chigga101 at gmail.com Thu Jan 24 19:26:26 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 24 Jan 2013 18:26:26 +0000 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: <51015906.9080205@davea.name> Message-ID: > yes the 2nd option (standalone pylauncher) sounds more convienient for > me. i just have to try and comprehend all the instructions given.. > hopefully ill get there in the end i managed to install the laucher. on the site when i click the correct launcher 32bit, i chose "run" and it automatically installed rather than asking me or allowing me to install it in cmd like their directions showed. my python 3 files still open but python 2 files still return errors like: print "string" is invalid syntax which tells me its still using python 3 to open these files. when i right click .py files a new option has been added to "open with" which is open with Python Launcher for Windows. Even when i do this my python 2 files won't open From d at davea.name Thu Jan 24 19:43:50 2013 From: d at davea.name (Dave Angel) Date: Thu, 24 Jan 2013 13:43:50 -0500 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: <51015906.9080205@davea.name> Message-ID: <510180E6.3060104@davea.name> On 01/24/2013 01:26 PM, Matthew Ngaha wrote: >> yes the 2nd option (standalone pylauncher) sounds more convienient for >> me. i just have to try and comprehend all the instructions given.. >> hopefully ill get there in the end > > i managed to install the laucher. on the site when i click the correct > launcher 32bit, i chose "run" and it automatically installed rather > than asking me or allowing me to install it in cmd like their > directions showed. my python 3 files still open but python 2 files > still return errors like: print "string" is invalid syntax which tells > me its still using python 3 to open these files. when i right click > .py files a new option has been added to "open with" which is open > with Python Launcher for Windows. Even when i do this my python 2 > files won't open Have you added shebang lines to those scripts yet? -- DaveA From chigga101 at gmail.com Thu Jan 24 19:56:54 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 24 Jan 2013 18:56:54 +0000 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: <510180E6.3060104@davea.name> References: <51015906.9080205@davea.name> <510180E6.3060104@davea.name> Message-ID: > > Have you added shebang lines to those scripts yet? > yes i added them. i think the problem is at the start where it asks me to: You should ensure the launcher is on your PATH - depending on how it was installed it may already be there, but check just in case it is not. >From a command-prompt, execute the following command: py You should find that the latest version of Python 2.x you have installed is started .. py is not recognized and and it said "depending on how it was installed". the problem is it didnt allow me to select a path when installing. it just automatically did everything. i have searched my PC for python launcher but it cant find it, so i dont know where its location is. i see it in "control panel" to uninstall a program but right clicking it doesnt give me an option to see its containing folder From d at davea.name Thu Jan 24 20:12:14 2013 From: d at davea.name (Dave Angel) Date: Thu, 24 Jan 2013 14:12:14 -0500 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: <51015906.9080205@davea.name> <510180E6.3060104@davea.name> Message-ID: <5101878E.3080504@davea.name> On 01/24/2013 01:56 PM, Matthew Ngaha wrote: >> >> Have you added shebang lines to those scripts yet? >> > yes i added them. i think the problem is at the start where it asks me to: > > You should ensure the launcher is on your PATH - depending on how it was > installed it may already be there, but check just in case it is not. > >>From a command-prompt, execute the following command: > py > You should find that the latest version of Python 2.x you have installed is > started .. > > py is not recognized and and it said "depending on how it was > installed". the problem is it didnt allow me to select a path when > installing. it just automatically did everything. i have searched my > PC for python launcher but it cant find it, so i dont know where its > location is. i see it in "control panel" to uninstall a program but > right clicking it doesnt give me an option to see its containing > folder I'm not using it, since I'm not using Windows. So these are guesses based on years stuck\b\b\b\b\b spent in the Windows environment. Clearly, the name of the program is py.exe, so that's what you should try searching for. From the cmd prompt, try dir /s py.exe Or, you could just try searching under c:\windows since that's where it's likely to be. To see your PATH, type PATH at the cmd prompt. To make temporary changes to your PATH (if py.exe is in an obscure place), just type set PATH=c:\mydir;%PATH% To make permanent changes to PATH, you have to change the environment variables in the Control Panel. I've done it many times, but don't recall just where it is. Such permanent changes will affect any new runs of CMD, as well as affect any other program subsequently started. -- DaveA From chigga101 at gmail.com Thu Jan 24 21:14:22 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 24 Jan 2013 20:14:22 +0000 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: <5101878E.3080504@davea.name> References: <51015906.9080205@davea.name> <510180E6.3060104@davea.name> <5101878E.3080504@davea.name> Message-ID: > I'm not using it, since I'm not using Windows. So these are guesses based > on years stuck\b\b\b\b\b spent in the Windows environment. > > Clearly, the name of the program is py.exe, so that's what you should try > searching for. From the cmd prompt, try dir /s py.exe > > Or, you could just try searching under c:\windows since that's where it's > likely to be. > > To see your PATH, type PATH at the cmd prompt. > > To make temporary changes to your PATH (if py.exe is in an obscure place), > just type > set PATH=c:\mydir;%PATH% > > To make permanent changes to PATH, you have to change the environment > variables in the Control Panel. I've done it many times, but don't recall > just where it is. Such permanent changes will affect any new runs of CMD, > as well as affect any other program subsequently started. > thanks Dave. the file was py.exe as you said and the temporary path is able to open both version 2 and 3's python.exe. There seems to be a problem. python 2 seems to be the only version opening my files unless i do a few things. So with the shebang set: the python launcher, launches my python 3 files with the correct version if i double click the file or run it from a console. But it uses the wrong version if i run it from IDLE or if i right click the file and open with the Python Launcher. i guess i can live with that, but is there anyway around this? From oscar.j.benjamin at gmail.com Thu Jan 24 21:30:42 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 24 Jan 2013 20:30:42 +0000 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: <51015906.9080205@davea.name> <510180E6.3060104@davea.name> <5101878E.3080504@davea.name> Message-ID: On 24 January 2013 20:14, Matthew Ngaha wrote: >> > thanks Dave. the file was py.exe as you said and the temporary path is > able to open both version 2 and 3's python.exe. There seems to be a > problem. python 2 seems to be the only version opening my files unless > i do a few things. So with the shebang set: > > the python launcher, launches my python 3 files with the correct > version if i double click the file or run it from a console. But it > uses the wrong version if i run it from IDLE or if i right click the > file and open with the Python Launcher. i guess i can live with that, > but is there anyway around this? Each version of Python has it's own version of IDLE. If you use the IDLE that came with Python 2 it will always run in Python 2. I think the same is true for the "Python launcher". Probably you have more than one version of these programs installed. You could create shortcuts (or something like that) to run the Python 3 versions. In any case, this is the reason that the py.exe launcher was created, so that you could have one launcher that would run each script in the appropriate version of Python. Oscar From eryksun at gmail.com Thu Jan 24 22:35:05 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 24 Jan 2013 16:35:05 -0500 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: <51015906.9080205@davea.name> <510180E6.3060104@davea.name> Message-ID: On Thu, Jan 24, 2013 at 1:56 PM, Matthew Ngaha wrote: > > py is not recognized and and it said "depending on how it was > installed". the problem is it didnt allow me to select a path when > installing. The simpler installer is launchwin.msi, which installs to the Windows directory. This directory should already be on the PATH. In a cmd shell, check that 'assoc .py' is "Python.File" and that 'ftype Python.File' points to py.exe in your Windows directory, e.g. "C:\Windows\py.exe "%1" %*'. If it's wrong, re-install. Or fix it manually using assoc and ftype in an elevated cmd shell, which updates the local machine registry keys in HKLM\Software\Classes. Also, Windows Explorer has an "Open With" dialog that configures per-user settings for multiple associations, including a default (i.e. the "Always use..." checkbox). These keys are stored in HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.py. Make sure that UserChoice is set to the Progid "Python.File". You should be able to change this using the 'Open With->Choose Default Program...' dialog. You can customize pylauncher by editing its ini file in your profile. For example, run 'notepad %localappdata%\py.ini' to create/edit it. See the docs for the settings, such as changing the default interpreter and adding custom shebangs. From chigga101 at gmail.com Thu Jan 24 23:06:48 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 24 Jan 2013 22:06:48 +0000 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: <51019A31.4020707@davea.name> References: <51015906.9080205@davea.name> <510180E6.3060104@davea.name> <5101878E.3080504@davea.name> <51019A31.4020707@davea.name> Message-ID: > Did you find the "control-panel-way" to modify the PATH (assuming py.exe > wasn't already in there) ? Without it, I'd be surprised if right-click > would work correctly. > > And as for IDLE, there are two different IDLEs, one in each directory. So > run the one that corresponds to the python you'll be using. How to do that? > I dunno, since I don't use IDLE, but I'd find or make batch files called > something like IDLE2.bat and IDLE3.bat that know how to find and run the > appropriate IDLE. > i didnt use the control panel way but the right click is now working, it was an error that in the script i had a txt.file open() and the right click way said "no such file" but the other ways found the txt file which is weird but right clicking works for other files without a txt file. i can live with that. i think it wise for me to try to permanently add the path with control panel. Thanks for all the help, its such a relief to now be able to run python 2 files From chigga101 at gmail.com Thu Jan 24 23:09:57 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 24 Jan 2013 22:09:57 +0000 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: <51015906.9080205@davea.name> <510180E6.3060104@davea.name> Message-ID: On Thu, Jan 24, 2013 at 9:35 PM, eryksun wrote: > On Thu, Jan 24, 2013 at 1:56 PM, Matthew Ngaha wrote: >> >> py is not recognized and and it said "depending on how it was >> installed". the problem is it didnt allow me to select a path when >> installing. > > The simpler installer is launchwin.msi, which installs to the Windows > directory. This directory should already be on the PATH. > > In a cmd shell, check that 'assoc .py' is "Python.File" and that > 'ftype Python.File' points to py.exe in your Windows directory, e.g. > "C:\Windows\py.exe "%1" %*'. If it's wrong, re-install. Or fix it > manually using assoc and ftype in an elevated cmd shell, which updates > the local machine registry keys in HKLM\Software\Classes. > > Also, Windows Explorer has an "Open With" dialog that configures > per-user settings for multiple associations, including a default (i.e. > the "Always use..." checkbox). These keys are stored in > HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.py. > Make sure that UserChoice is set to the Progid "Python.File". You > should be able to change this using the 'Open With->Choose Default > Program...' dialog. > > You can customize pylauncher by editing its ini file in your profile. > For example, run 'notepad %localappdata%\py.ini' to create/edit it. > See the docs for the settings, such as changing the default > interpreter and adding custom shebangs. sorry i didnt see this message. I havent read it yet although it looks complicated. Thanks ill report back if i need help From chigga101 at gmail.com Thu Jan 24 23:39:16 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 24 Jan 2013 22:39:16 +0000 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: <51015906.9080205@davea.name> <510180E6.3060104@davea.name> Message-ID: > In a cmd shell, check that 'assoc .py' is "Python.File" and that > 'ftype Python.File' points to py.exe in your Windows directory, e.g. > "C:\Windows\py.exe "%1" %*'. If it's wrong, re-install. Or fix it > manually using assoc and ftype in an elevated cmd shell, which updates > the local machine registry keys in HKLM\Software\Classes. i think this is ok, i got these results. D:\Data\Py\mywork>assoc .py .py=Python.File D:\Data\Py\mywork>ftype Python.File Python.File="D:\Data\Py2.7\python.exe" "%1" %* > Also, Windows Explorer has an "Open With" dialog that configures > per-user settings for multiple associations, including a default (i.e. > the "Always use..." checkbox). These keys are stored in > HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.py. > Make sure that UserChoice is set to the Progid "Python.File". You > should be able to change this using the 'Open With->Choose Default > Program...' dialog. > i dont quit understand when you say UserChoice is set to the Progid "Python.File"? what is Progid? i cant seem to locate that path HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.py. From eryksun at gmail.com Fri Jan 25 05:44:34 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 24 Jan 2013 23:44:34 -0500 Subject: [Tutor] how can i use python 2 alongside 3? In-Reply-To: References: <51015906.9080205@davea.name> <510180E6.3060104@davea.name> Message-ID: On Thu, Jan 24, 2013 at 5:39 PM, Matthew Ngaha wrote: > > D:\Data\Py\mywork>ftype Python.File > Python.File="D:\Data\Py2.7\python.exe" "%1" %* That's the file class created by the 2.7 installer in the HKLM (local machine) Software hive. Overview of the Windows Registry: http://en.wikipedia.org/wiki/Windows_Registry The cmd shell's assoc/ftype use HKLM classes. However, I see now that the standalone launcher configures HKCU (current user) classes. These take precedence over HKLM classes, so assoc and ftype aren't showing the complete picture. HKCR (classes root) is the merged view. The following shows the current default command to open a Python.File: reg query HKCR\Python.File\shell\open\command > i dont quit understand when you say UserChoice is set to the Progid > "Python.File"? what is Progid? i cant seem to locate that path > HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.py. reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.py\UserChoice If you've selected a default using the "Open With" dialog, there should be a 'Progid' set to, for example, Python.File. Modify this using the Explorer "Open With"/"Choose Default Program..." dialog. I mention this because installers don't generally modify this key. It's set manually by the user -- possibly to an editor or a specific Python executable instead of the configured Python.File class. From 3n2solutions at gmail.com Fri Jan 25 18:52:37 2013 From: 3n2solutions at gmail.com (3n2 Solutions) Date: Fri, 25 Jan 2013 09:52:37 -0800 Subject: [Tutor] Can Python monitor web browser content Message-ID: Hello, I was wondering if Python can monitor web browser content. Specifically, I'm connected to a Machine to Machine device (essentially a Gateway) and monitoring its activity on a web browser (either IE or Chrome). There are certain parameters like RSSI (received signal strength indicator ) that I would like to monitor (read and record) for a one minute period. Is this possible in Python? If not, what can achieve this? I'm using Python 2.7 on Windows 7 Thank you! Tim From alan.gauld at btinternet.com Fri Jan 25 20:54:47 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Jan 2013 19:54:47 +0000 Subject: [Tutor] Can Python monitor web browser content In-Reply-To: References: Message-ID: On 25/01/13 17:52, 3n2 Solutions wrote: > I was wondering if Python can monitor web browser content. Browsers just display html text and Python can read html so yes you can do it by getting your program to emulate a browser. Look at the standard library modules urllibm htmllib and htmlParser. Or for more adventurous parsing try the external module BeautifulSoup, it tends to handle badly formed html better and is arguably easier to use than the standard options.. On Windows you can also read the content of IE using COM but that's probably not the best approach. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From shantanoo at gmail.com Fri Jan 25 22:08:05 2013 From: shantanoo at gmail.com (=?UTF-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Sat, 26 Jan 2013 02:38:05 +0530 Subject: [Tutor] Calculate hours In-Reply-To: References: Message-ID: <5102F435.9070003@gmail.com> Reply inline. On 23/01/13 8:22 AM, anthonym wrote: > Hello All, > > I originally wrote this program to calculate and print the employee > with the most hours worked in a week. I would now like to change this > to calculate and print the hours for all 8 employees in ascending order. > > The employees are named employee 0 - 8 > > Any ideas? > > Thanks, > Tony > > Code below: > > > > # Create table of hours worked > > matrix = [ > [2, 4, 3, 4, 5, 8, 8], > [7, 3, 4, 3, 3, 4, 4], > [3, 3, 4, 3, 3, 2, 2], > [9, 3, 4, 7, 3, 4, 1], > [3, 5, 4, 3, 6, 3, 8], > [3, 4, 4, 6, 3, 4, 4], > [3, 7, 4, 8, 3, 8, 4], > [6, 3, 5, 9, 2, 7, 9]] > === s = [sum(x) for x in matrix] for q in sorted([(x,y) for x,y in enumerate(s)], key=operator.itemgetter(1)): print("Employee %d has worked %d hours" % (q[0], q[1])) === Output: Employee 2 has worked 20 hours Employee 1 has worked 28 hours Employee 5 has worked 28 hours Employee 3 has worked 31 hours Employee 4 has worked 32 hours Employee 0 has worked 34 hours Employee 6 has worked 37 hours Employee 7 has worked 41 hours From __peter__ at web.de Fri Jan 25 22:42:15 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 Jan 2013 22:42:15 +0100 Subject: [Tutor] Calculate hours References: <5102F435.9070003@gmail.com> Message-ID: ????? wrote: > s = [sum(x) for x in matrix] > for q in sorted([(x,y) for x,y in enumerate(s)], > key=operator.itemgetter(1)): > print("Employee %d has worked %d hours" % (q[0], q[1])) A minor simplification: s = (sum(x) for x in matrix) for q in sorted(enumerate(s), key=operator.itemgetter(1)): print("Employee %d has worked %d hours" % q) From anthonym at att.net Sat Jan 26 00:57:51 2013 From: anthonym at att.net (anthonym) Date: Fri, 25 Jan 2013 15:57:51 -0800 Subject: [Tutor] lambda Message-ID: Hello All, I have the code below that I used to create a simple tic tac toe game for class. I am learning Python but have programmed in C+ before so I brought over a lambda and found that it worked in Python. Unfortunately I don't think my classmates will understand the use of lambda here but I am having are hard time converting that to strictly python. Let me know if it can be done. Thanks from tkinter import * def ttt(r,c): global player if player == 'X': b[r][c].configure(text = 'X') player = 'O' else: b[r][c].configure(text = 'O') player = 'X' root = Tk() b = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for i in range(3): for j in range(3): b[i][j] = Button(font=('Aerial', 56), width=3, bg='yellow', command = lambda r=i,c=j: ttt(r,c)) b[i][j].grid(row = i, column = j) player = 'X' mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jan 26 01:14:05 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Jan 2013 00:14:05 +0000 Subject: [Tutor] lambda In-Reply-To: References: Message-ID: On 25/01/13 23:57, anthonym wrote: > I don't think my classmates will understand the use of lambda here but I > am having are hard time converting that to strictly python. lambdas are strictly python but they can be easily reanslated into a named function as lambda p: expr becomes def f(p): return expr so in your case > b[i][j] = Button(font=('Aerial', 56), width=3, bg='yellow', > command = lambda r=i,c=j: ttt(r,c)) becomes def bCmd(r=i,c=j): return ttt(r,c) b[i][j] = Button(font=('Aerial', 56), width=3, bg='yellow', command = bCmd) Your problem of course is that you need i and j to be dynamically defined so you need to create and call a function that returns a function like this def buttonFunMaker(i,j): def func(x=i,y=j): return ttt(x,y) return func b[i][j] = Button(font=('Aerial', 56), width=3, bg='yellow', command = buttonFunMaker(i,j)) Personally I prefer the lambda... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dyoo at hashcollision.org Sat Jan 26 01:25:22 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 25 Jan 2013 17:25:22 -0700 Subject: [Tutor] lambda In-Reply-To: References: Message-ID: On Fri, Jan 25, 2013 at 4:57 PM, anthonym wrote: > I have the code below that I used to create a simple tic tac toe game for > class. I am learning Python but have programmed in C+ before so I brought > over a lambda and found that it worked in Python. Unfortunately I don't > think my classmates will understand the use of lambda here but I am having > are hard time converting that to strictly python. The code is expressing the idea of referring to a function, not to call it immediately, but rather to pass it as a value for someone else to call. This is something that's expressible in C++ too. http://en.wikipedia.org/wiki/C%2B%2B11#Lambda_functions_and_expressions But you probably won't see this in beginner-level code. Dealing with functions as values is important to learn, though, if you want to build an intermediate mastery of programming. The concept is a key component to things like event-driven programming, where you tell some other system what to do when certain things happen. That "what to do" is usually expressed by passing the thing a function value. In traditional C++, the kind of C++ you'd see several years ago, you can do the same sort of thing by passing around objects that have a virtual method. In that way, you can have a "function-like" value that can be passed and called. From anthonym at att.net Sat Jan 26 01:35:44 2013 From: anthonym at att.net (anthonym) Date: Fri, 25 Jan 2013 16:35:44 -0800 Subject: [Tutor] lambda In-Reply-To: Message-ID: Thanks Alan. I prefer the lambda too. Especially given how much code I saved. I forgot about i and j being dynamic and the call function. On 1/25/13 4:14 PM, "Alan Gauld" wrote: >On 25/01/13 23:57, anthonym wrote: > >> I don't think my classmates will understand the use of lambda here but I >> am having are hard time converting that to strictly python. > >lambdas are strictly python but they can be easily reanslated into a >named function as > >lambda p: expr > >becomes > >def f(p): > return expr > >so in your case > > > b[i][j] = Button(font=('Aerial', 56), width=3, bg='yellow', > > command = lambda r=i,c=j: ttt(r,c)) > >becomes > >def bCmd(r=i,c=j): > return ttt(r,c) > >b[i][j] = Button(font=('Aerial', 56), width=3, bg='yellow', > command = bCmd) > >Your problem of course is that you need i and j to be dynamically >defined so you need to create and call a function that returns a >function like this > >def buttonFunMaker(i,j): > def func(x=i,y=j): > return ttt(x,y) > return func > >b[i][j] = Button(font=('Aerial', 56), width=3, bg='yellow', > command = buttonFunMaker(i,j)) > >Personally I prefer the lambda... > >HTH > >-- >Alan G >Author of the Learn to Program web site >http://www.alan-g.me.uk/ > >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor From eryksun at gmail.com Sat Jan 26 02:22:02 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 25 Jan 2013 20:22:02 -0500 Subject: [Tutor] lambda In-Reply-To: References: Message-ID: On Fri, Jan 25, 2013 at 7:14 PM, Alan Gauld wrote: > > Your problem of course is that you need i and j to be dynamically defined so > you need to create and call a function that returns a function like this > > def buttonFunMaker(i,j): > def func(x=i,y=j): > return ttt(x,y) > return func > > b[i][j] = Button(font=('Aerial', 56), width=3, bg='yellow', > command = buttonFunMaker(i,j)) With a function call you no longer need the default parameter hack (i.e. x=i, y=j). You can make a closure over the local i and j in buttonFunMaker: def buttonFunMaker(i, j): def func(): return ttt(i, j) return func or: def buttonFunMaker(i, j): return lambda: ttt(i, j) With only lambda expressions, this structure is a bit awkward: command=(lambda i, j: lambda: ttt(i, j))(i, j) From alan.gauld at btinternet.com Sat Jan 26 08:37:04 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Jan 2013 07:37:04 +0000 Subject: [Tutor] lambda In-Reply-To: References: Message-ID: On 26/01/13 01:22, eryksun wrote: > With a function call you no longer need the default parameter hack > (i.e. x=i, y=j). You can make a closure over the local i and j in > buttonFunMaker: > > def buttonFunMaker(i, j): > def func(): > return ttt(i, j) > return func Good catch! > def buttonFunMaker(i, j): > return lambda: ttt(i, j) Since the point was to get away from lambda I discounted this option, but it was my first instinct! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dustinguerri at gmail.com Wed Jan 16 23:47:54 2013 From: dustinguerri at gmail.com (Dustin Guerri) Date: Wed, 16 Jan 2013 23:47:54 +0100 Subject: [Tutor] First Python Test Message-ID: Hi there, I'm trying to create a plain text file called "hello.py" with the following text : print('hello world') raw_input('Press any key to continue') I'd then like to run this program with Python Launcher on a Mac. I'd lke to use Xcode as my text editor. Once I have Xcode open, which template should I use to input the text ? Thanks, *Dustin Guerri* Mobile : (+ 34) 625 857 967 dustinguerri at gmail.com | www.vimeo.com/dustinguerri/pop [image: LinkedIn] Contact me: [image: Google Talk] dustinguerri [image: Skype] dustinguerri Get a signature like this. CLICK HERE. -------------- next part -------------- An HTML attachment was scrubbed... URL: From grady905 at gmail.com Wed Jan 23 22:37:58 2013 From: grady905 at gmail.com (Grady Trexler) Date: Wed, 23 Jan 2013 16:37:58 -0500 Subject: [Tutor] Python Help Message-ID: Below is my code. I am using python 2.4 It tells me I have a syntax error. Please help! (I think the first twenty lines have what you would be looking for. After that it just repeats itself.) #scenario maker #created by: Grady Trexler #started on 1/3/13 #last update: 1/3/13 def rungame() guyone = raw_input("Please enter a name:") guytwo = raw_input("Please enter a name:") g1pers = raw_input("Please enter a personality: happy, sad or mad:") g2pers = raw_input("Please enter a personality: happy, sad or mad:") place = raw_input("Please enter a place: theater, mall, or gamestop:") if g1pers == "happy" and g2pers == "happy" and place == "theater" : print "%s: Wow! I can't wait to see this movie!" % (guyone) print "%s: Me too! My mom says it is awesome!" % (guytwo) print "%s and %s high five." % (guyone, guytwo) print "Then %s and %s became best friends." % (guyone, guytwo) elif g1pers == "happy" and g2pers == "happy" and place == "mall" : print "%s and %s met in the mall at the food court." % (guyone, guytwo) print "%s: Why are you here?" % (guytwo) print "%s: I went to Barnes and Noble. You?" % (guyone) print "%s: I came to shop for clothing. Bye now!" % (guytwo) print "%s: Goodbye!" % (guyone) print "%s and %s would never meet again, but would remain to be happy forever." % (guyone, guytwo) elif g1pers == "happy" and g2pers == "happy" and place == "gamestop" : print "Waiting in line at Gamestop, %s struck up a conversation with the person next to him, who was %s." % (guyone, guytwo) print "%s: What are you coming to buy?" % (guytwo) print "%s: Halo 4. You?" % (guyone) print "%s: Some games for my NES, as well as COD 3." % (guyone) print "%s: NES?" % (guytwo) print "%s: Nintendo Entertainment System, Nintendo's original console. No Halo's for that bad boy." % (guytwo) print "%s: Oh, cool." % (guyone) print "%s and %s left Gamestop and went home." elif g1pers == "happy" and g2pers == "sad" and place == "theater" : print "%s and %s were in line next to eachother." % (guyone, guytwo) print "%s, sensing %s was sad tried to start a conversation." % (guyone, guytwo) print "%s: What's wrong, brother?" % (guyone) print "%s: EVERYTHING!!!!" % (guytwo) print "%s pushed passed %s and ran away. The two never saw eachother again." % (guytwo, guyone) rungame() -- --T-rexmix Check out my website- www.thegradypage.weebly.com It has new blog posts all the time! Fight against Gandalf. Like a Balrog. -------------- next part -------------- An HTML attachment was scrubbed... URL: From per.fagrell at gmail.com Wed Jan 16 21:03:01 2013 From: per.fagrell at gmail.com (Per Fagrell) Date: Wed, 16 Jan 2013 21:03:01 +0100 Subject: [Tutor] Cheese shop tutorial mirror Message-ID: Hello, I'm interested in uploading a module to pypi, but with the python wiki down after the hack there's no access to the Cheese shop tutorial. Does anyone have a mirror or reasonable facsimile that could be used until the wiki is back on-line and repopulated? Best regards, Per Fagrell -------------- next part -------------- An HTML attachment was scrubbed... URL: From rogershaw39 at hotmail.com Fri Jan 18 19:11:18 2013 From: rogershaw39 at hotmail.com (Roger) Date: Fri, 18 Jan 2013 18:11:18 -0000 Subject: [Tutor] sqlite search Message-ID: Hello, I am very new to python. Wrote a small program to use on my android phone using pickle/shelve to access data. That worked fine but i realised it would be better to use sqlite as a database to more easily modify the data. I havent got a clue about sqlite, have a book but cant find the answer My problem is this. i can access data by putting characters to search for in the program but i want it to be a variable that i can search for characters i input from keypad. I am guessing its a syntax problem? At the moment this works to search for everything beginning with A sql = "SELECT * FROM plants WHERE genus LIKE 'A%'"; cursor.execute(sql); slt =cursor.fetchone(); What i really need is to search for everything beginning with two letters from an input command -------------- next part -------------- An HTML attachment was scrubbed... URL: From Steven.Carpenter at oakland.k12.mi.us Fri Jan 18 13:56:53 2013 From: Steven.Carpenter at oakland.k12.mi.us (Carpenter, Steven) Date: Fri, 18 Jan 2013 07:56:53 -0500 Subject: [Tutor] Help! Message-ID: <24E6F5EE90519B48AAC334D4F18BE42C709F1B5D56@SIMON.os.oaklandschools.net> To Whom it May Concern, I'm trying to get this code working. Here's my question: Consider a triangle with sides of length 3, 7, and 9. The law of cosines states that given three sides of a triangle (a, b, and c) and angle C between sides a and b: Write Python code to calculate the three angles in the triangle. Here's my code: # Calculate the angles in a triangle # Imports the Math data import math # Sets up the different angles with corresponding letters # The first angle is a a = 3 # The second angle is b b = 7 # The third angle is c c = 9 # Calculates angle "C" print(math.acos(((a**2)+(b**2)-(c**2))/(2(a*b)))) Here's my output: Traceback (most recent call last): File "E:\Programming\Problem4.py", line 12, in print(math.acos(((a**2)+(b**2)-(c**2))/(2(a*b)))) TypeError: 'int' object is not callable Steven Carpenter -------------- next part -------------- An HTML attachment was scrubbed... URL: From joskerc at gmail.com Sat Jan 26 09:25:43 2013 From: joskerc at gmail.com (Jos Kerc) Date: Sat, 26 Jan 2013 09:25:43 +0100 Subject: [Tutor] Help! In-Reply-To: <24E6F5EE90519B48AAC334D4F18BE42C709F1B5D56@SIMON.os.oaklandschools.net> References: <24E6F5EE90519B48AAC334D4F18BE42C709F1B5D56@SIMON.os.oaklandschools.net> Message-ID: You are missing a multiplication sign. Near the end of your formula. On Fri, Jan 18, 2013 at 1:56 PM, Carpenter, Steven < Steven.Carpenter at oakland.k12.mi.us> wrote: > To Whom it May Concern,**** > > I?m trying to get this code working. *Here?s my question:***** > > Consider a triangle with sides of length 3, 7, and 9. The law of cosines > states that given three sides of a triangle (a, b, and c) and angle C > between sides a and b: Write Python code to calculate the three angles in > the triangle.**** > > *Here?s my code: * > > # Calculate the angles in a triangle**** > > # Imports the Math data**** > > import math**** > > # Sets up the different angles with corresponding letters**** > > # The first angle is a**** > > a = 3**** > > # The second angle is b**** > > b = 7**** > > # The third angle is c**** > > c = 9**** > > # Calculates angle "C"**** > > print(math.acos(((a**2)+(b**2)-(c**2))/(2(a*b))))**** > > *Here?s my output:* > > Traceback (most recent call last):**** > > File "E:\Programming\Problem4.py", line 12, in **** > > print(math.acos(((a**2)+(b**2)-(c**2))/(2(a*b))))**** > > TypeError: 'int' object is not callable**** > > ** ** > > *Steven Carpenter* > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Jan 26 09:29:51 2013 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 Jan 2013 09:29:51 +0100 Subject: [Tutor] Cheese shop tutorial mirror References: Message-ID: Per Fagrell wrote: > I'm interested in uploading a module to pypi, but with the python wiki > down after the hack there's no access to the Cheese shop tutorial. Does > anyone have a mirror or reasonable facsimile that could be used until the > wiki is back on-line and repopulated? You're lucky, the wiki is up again: http://wiki.python.org/moin/CheeseShopTutorial From farhanraza132 at yahoo.com Sat Jan 26 09:39:16 2013 From: farhanraza132 at yahoo.com (Farhan Farhan) Date: Sat, 26 Jan 2013 00:39:16 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 107, Issue 79 In-Reply-To: References: Message-ID: <1359189556.70524.YahooMailNeo@web121602.mail.ne1.yahoo.com> plz don't send me any msg again.plzzzzzzzzz i want to unfreind you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jarod_v6 at libero.it Sat Jan 26 10:21:24 2013 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Sat, 26 Jan 2013 10:21:24 +0100 (CET) Subject: [Tutor] Read and write list on I file Message-ID: <16411644.5363861359192084909.JavaMail.defaultUser@defaultHost> HI there!!! I have a file like this: 12345-2 ppppppppppppppppppppppppppppppppppppppppppp 12389-4 iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii ... I want to read this file and organize in different way: The second number present after "-" mean the times are ripetuted the elements..so in the example In the end I want to have this result 12345-1 ppppppppppppppppppppppppppppppppppppppppppp 12345-2 ppppppppppppppppppppppppppppppppppppppppppp 12389-1 iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii 12389-2 iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii 12389-3 iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii 12389-4 iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii Someone have a suggestion how to do this simple task.. I write some code but don't do all the think I want. import re f = open("file.txt","r") for item in f: if re.match(r'['0-9]',item): line=iteme.strip.split("\t") num = line[0].split("-") key = num[0] vl = in(num[1]) for i in range(1,vl): .... else: print all line" thanks in advance for any help! From russel at winder.org.uk Sat Jan 26 10:40:05 2013 From: russel at winder.org.uk (Russel Winder) Date: Sat, 26 Jan 2013 10:40:05 +0100 Subject: [Tutor] Help! In-Reply-To: <24E6F5EE90519B48AAC334D4F18BE42C709F1B5D56@SIMON.os.oaklandschools.net> References: <24E6F5EE90519B48AAC334D4F18BE42C709F1B5D56@SIMON.os.oaklandschools.net> Message-ID: <1359193205.6245.5.camel@lionors.winder.org.uk> Following up on Jos Kerc's answer: On Fri, 2013-01-18 at 07:56 -0500, Carpenter, Steven wrote: [?] > print(math.acos(((a**2)+(b**2)-(c**2))/(2(a*b)))) 2(a*b) ? 2 * (a * b) > TypeError: 'int' object is not callable Juxtaposition does not imply multiplication in Python as it does in mathematics. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From fomcl at yahoo.com Sat Jan 26 11:35:28 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 26 Jan 2013 02:35:28 -0800 (PST) Subject: [Tutor] Can Python monitor web browser content In-Reply-To: References: Message-ID: <1359196528.41464.YahooMailNeo@web163802.mail.gq1.yahoo.com> ---- Original Message ----- > From: Alan Gauld > To: tutor at python.org > Cc: > Sent: Friday, January 25, 2013 8:54 PM > Subject: Re: [Tutor] Can Python monitor web browser content > > On 25/01/13 17:52, 3n2 Solutions wrote: > >> I was wondering if Python can monitor web browser content. > > Browsers just display html text and Python can read html so > yes you can do it by getting your program to emulate a browser. > > Look at the standard library modules urllibm htmllib and htmlParser. > Or for more adventurous parsing try the external module BeautifulSoup, it tends > to handle badly formed html better and is arguably easier to use than the > standard options.. I used the mechanize package before: http://pypi.python.org/pypi/mechanize/ From wrw at mac.com Sat Jan 26 14:19:18 2013 From: wrw at mac.com (wrw at mac.com) Date: Sat, 26 Jan 2013 08:19:18 -0500 Subject: [Tutor] Python Help In-Reply-To: References: Message-ID: <22E60704-7606-425D-B563-58E7703F6AC6@mac.com> On Jan 23, 2013, at 4:37 PM, Grady Trexler wrote: > > Below is my code. I am using python 2.4 It tells me I have a syntax error. Please help! (I think the first twenty lines have what you would be looking for. After that it just repeats itself.) > #scenario maker > #created by: Grady Trexler > #started on 1/3/13 > #last update: 1/3/13 > > def rungame() > guyone = raw_input("Please enter a name:") > [megabyte] > print "%s: EVERYTHING!!!!" % (guytwo) > print "%s pushed passed %s and ran away. The two never saw eachother again." % (guytwo, guyone) > rungame() > -- > --T-rexmix > Check out my website- > www.thegradypage.weebly.com > It has new blog posts all the time! > Fight against Gandalf. Like a Balrog. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor In the future, please also show us the error and the traceback so we don't have to read through your whole code looking for lints. File "text.py", line 1 def rungame() ^ SyntaxError: invalid syntax You forgot the colon after the closing ) in the def statement. -Bill From davea at davea.name Sat Jan 26 15:24:26 2013 From: davea at davea.name (Dave Angel) Date: Sat, 26 Jan 2013 09:24:26 -0500 Subject: [Tutor] Python Help In-Reply-To: References: Message-ID: <5103E71A.8020903@davea.name> On 01/23/2013 04:37 PM, Grady Trexler wrote: > Below is my code. I am using python 2.4 It tells me I have a syntax error. I don't see any such thing. Plesae include the traceback, which will indicate WHERE you have a syntax error. And if you look yourself, you'll probably spot it, since it's usually either in the line specified or the one right before it. Also, please use text mail. By using html, you have killed the indentation that you presumably had in your original. If you didn't have it in your original, then that's your second syntax error. All right, I gave up and tried pasting your misformed code into a text editor. Looks like you have a problem on the very first non-comment line: no colon on the def line > Please help! (I think the first twenty lines have what you would be > looking for. After that it just repeats itself.) > #scenario maker > #created by: Grady Trexler > #started on 1/3/13 > #last update: 1/3/13 > > def rungame() > guyone = raw_input("Please enter a name:") > > guytwo = raw_input("Please enter a name:") > Also please pick a better topic than "Python Help". Nearly every new thread here is asking for help with Python, so how does yours stand out? Even "syntax error" would be a better one. -- DaveA From sntshkmr60 at gmail.com Sat Jan 26 17:38:28 2013 From: sntshkmr60 at gmail.com (Santosh Kumar) Date: Sat, 26 Jan 2013 22:08:28 +0530 Subject: [Tutor] How does # -*- coding: utf-8 -*- work? Message-ID: Everything starting with hash character in Python is comment and is not interpreted by the interpreter. So how does that works? Give me full explanation. From joel.goldstick at gmail.com Sat Jan 26 17:46:54 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 26 Jan 2013 11:46:54 -0500 Subject: [Tutor] How does # -*- coding: utf-8 -*- work? In-Reply-To: References: Message-ID: On Sat, Jan 26, 2013 at 11:38 AM, Santosh Kumar wrote: > Everything starting with hash character in Python is comment and is > not interpreted by the interpreter. So how does that works? Give me > full explanation. > If you google you get this: http://stackoverflow.com/questions/4872007/where-does-this-come-from-coding-utf-8 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Jan 26 20:52:32 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Jan 2013 06:52:32 +1100 Subject: [Tutor] Read and write list on I file In-Reply-To: <16411644.5363861359192084909.JavaMail.defaultUser@defaultHost> References: <16411644.5363861359192084909.JavaMail.defaultUser@defaultHost> Message-ID: <51043400.9030608@pearwood.info> On 26/01/13 20:21, jarod_v6 at libero.it wrote: (edited slightly to make it more clear) > HI there!!! > I have a file like this: > > 12345-2 ppppp > 12389-4 iiiii > > I want to read this file and organize in different way: The second number > present after "-" mean the times are ripetuted the elements..so in the > example In the end I want to have this result > > 12345-1 ppppp > 12345-2 ppppp > 12389-1 iiiii > 12389-2iiiii > 12389-3iiiii > 12389-4iiiii > > Someone have a suggestion how to do this simple task.. Untested, but this should work. Adding error checking is left up to you. f = open('file.txt', 'r') # each line looks like: # ddddd-d ccc... # where d is a digit and c is any non-space character. for line in f: head, tail = line.split(' ') head, num = head.split('-') num = int(num) for i in range(1, num+1): print "%s-%s %s" % (head, i, tail) f.close() -- Steven From eryksun at gmail.com Sun Jan 27 00:50:39 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 26 Jan 2013 18:50:39 -0500 Subject: [Tutor] How does # -*- coding: utf-8 -*- work? In-Reply-To: References: Message-ID: On Sat, Jan 26, 2013 at 11:38 AM, Santosh Kumar wrote: > > Everything starting with hash character in Python is comment and is > not interpreted by the interpreter. So how does that works? Give me > full explanation. The encoding declaration is parsed in the process of compiling the source. CPython uses the function get_coding_spec in tokenizer.c. CPython 2.7.3 source link: http://hg.python.org/cpython/file/70274d53c1dd/Parser/tokenizer.c#l205 You can use the parser module to represent the nodes of a parsed source tree as a sequence of nested tuples. The first item in each tuple is the node type number. The associated names for each number are split across two dictionaries. symbol.sym_name maps non-terminal node types, and token.tok_name maps terminal nodes (i.e. leaf nodes in the tree). In CPython 2.7/3.3, node types below 256 are terminal. Here's an example source tree for two types of encoding declaration: >>> src1 = '# -*- coding: utf-8 -*-' >>> parser.suite(src1).totuple() (339, (257, (0, '')), 'utf-8') >>> src2 = '# coding=utf-8' >>> parser.suite(src2).totuple() (339, (257, (0, '')), 'utf-8') As expected, src1 and src2 are equivalent. Now find the names of node types 339, 257, and 0: >>> symbol.sym_name[339] 'encoding_decl' >>> symbol.sym_name[257] 'file_input' >>> token.ISTERMINAL(0) True >>> token.tok_name[0] 'ENDMARKER' The base node is type 339 (encoding_decl). The child is type 257 (file_input), which is just the empty body of the source (to keep it simple, src1 and src2 lack statements). Tacked on at the end is the string value of the encoding_decl (e.g. 'utf-8'). From alan.gauld at btinternet.com Sun Jan 27 19:21:27 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Jan 2013 18:21:27 +0000 Subject: [Tutor] sqlite search In-Reply-To: References: Message-ID: On 18/01/13 18:11, Roger wrote: > At the moment this works to search for everything beginning with A > sql = "SELECT * FROM plants WHERE genus LIKE 'A%'"; > cursor.execute(sql); SQLlite supports a form of format string where you put in some magic charactrs then provide arguments which SQLLite will substitute in your SQL statement. You can see examples of that in the database topic in my tutorial: file:///home/alang/Documents/HomePage/tutor/tutdbms.htm Look at the address book example near the end for the 'Find Entry' feature, and definitely read the 'word about security' subheading for the correct way to do it! hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Sun Jan 27 20:30:27 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 27 Jan 2013 19:30:27 +0000 Subject: [Tutor] sqlite search In-Reply-To: References: Message-ID: On 27 January 2013 18:21, Alan Gauld wrote: > On 18/01/13 18:11, Roger wrote: > >> At the moment this works to search for everything beginning with A >> sql = "SELECT * FROM plants WHERE genus LIKE 'A%'"; >> cursor.execute(sql); > > > SQLlite supports a form of format string where you put in some magic > charactrs then provide arguments which SQLLite will substitute in your SQL > statement. > > You can see examples of that in the database topic in my tutorial: > > file:///home/alang/Documents/HomePage/tutor/tutdbms.htm You might have better luck using this link: http://www.alan-g.me.uk/tutor/tutdbms.htm > > Look at the address book example near the end for the 'Find Entry' feature, > and definitely read the 'word about security' subheading for the correct way > to do it! Oscar From alan.gauld at btinternet.com Mon Jan 28 01:07:51 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 28 Jan 2013 00:07:51 +0000 (GMT) Subject: [Tutor] sqlite search In-Reply-To: References: Message-ID: <1359331671.34917.YahooMailNeo@web186006.mail.ir2.yahoo.com> >> file:///home/alang/Documents/HomePage/tutor/tutdbms.htm > >You might have better luck using this link: >http://www.alan-g.me.uk/tutor/tutdbms.htm > > > > >Oops, thanks for spotting that!? I keep two copies of the site open in separate browser tabs and mistakenly used the local? file version when copying the link.?Silly me! Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kurt+python-tutor at lieber.org Mon Jan 28 07:16:13 2013 From: kurt+python-tutor at lieber.org (Kurt Lieber) Date: Sun, 27 Jan 2013 22:16:13 -0800 Subject: [Tutor] using ranges with argparse() Message-ID: Hi -- brand new to python, but trying to write a simple script that takes command line arguments. One of the arguments needs to test if a value is a) an integer and b) within a stated range. I currently have: parser.add_argument("-f", "--floor", default=6000, help="floor is the minimum amount of bonus points.",type=int, choices=range(5995, 6001)) This works, but when the user enters an out of bounds value, the help message is unfriendly: % ./bonus.py -f 10000 usage: bonus.py [-h] [-f {5995,5996,5997,5998,5999,6000}] MAM-bonus.py: error: argument -f/--floor: invalid choice: 10000 (choose from 5995, 5996, 5997, 5998, 5999, 6000) The problem is my default range is actually 0,10000 -- I changed it above for brevity's sake. So in the real world, it floods the screen to the point where it's unreadable. I can suppress the whole thing with argparse.SUPPRESS, but then I'm left with no help message at all. Is there a way to suppress the "(choose from 1,2,3,etc.)" part of the help message? Or a cleaner/different way altogether to accomplish the same thing? thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gayathri.s112 at gmail.com Mon Jan 28 08:26:40 2013 From: gayathri.s112 at gmail.com (Gayathri S) Date: Mon, 28 Jan 2013 12:56:40 +0530 Subject: [Tutor] HELP- Regarding working with python In-Reply-To: <50FA11DE.2090300@gmail.com> References: <50FA11DE.2090300@gmail.com> Message-ID: Hi all..! wanna know how to compile python script in python command line, and is there any need for setting path for python like JAVA? whats the difference between .py file and .pyc file? Thanks...! On Sat, Jan 19, 2013 at 8:54 AM, bob gailer wrote: > On 1/18/2013 8:03 AM, eryksun wrote: > >> Yes, it's a mistake in the PCA example from the docs: >> >> http://mlpy.sourceforge.net/**docs/3.5/dim_red.html#** >> principal-component-analysis-**pca >> > There seems to be no way to report a bug in that documentation! Or am I > missing something? > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Keep Smiling......... Regards........ Gayu.... -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Jan 28 09:20:30 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Jan 2013 19:20:30 +1100 Subject: [Tutor] HELP- Regarding working with python In-Reply-To: References: <50FA11DE.2090300@gmail.com> Message-ID: <510634CE.6090803@pearwood.info> On 28/01/13 18:26, Gayathri S wrote: > Hi all..! > wanna know how to compile python script in python command line, > and is there any need for setting path for python like JAVA? whats the > difference between .py file and .pyc file? Python is a byte-code compiled language, like Java many years ago. Normally to compile a python module, you just import it from within Python. That is not very convenient for scripts, so from the shell (bash, command.com, cmd.exe, or similar) you can run python -m compileall NAME NAME ... to compile scripts. You do not necessarily need to set the PYTHONPATH, but you can if you need to. .py files are source code. .pyc are compiled byte code. .pyo are compiled byte code with optimization turned on. Don't get too excited, the standard Python optimization doesn't do very much. -- Steven From __peter__ at web.de Mon Jan 28 09:33:45 2013 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 Jan 2013 09:33:45 +0100 Subject: [Tutor] using ranges with argparse() References: Message-ID: Kurt Lieber wrote: > Hi -- brand new to python, but trying to write a simple script that takes > command line arguments. One of the arguments needs to test if a value is > a) > an integer and b) within a stated range. I currently have: > > parser.add_argument("-f", "--floor", default=6000, help="floor is the > minimum amount of bonus points.",type=int, choices=range(5995, 6001)) > > This works, but when the user enters an out of bounds value, the help > message is unfriendly: > > % ./bonus.py -f 10000 > usage: bonus.py [-h] [-f {5995,5996,5997,5998,5999,6000}] > MAM-bonus.py: error: argument -f/--floor: invalid choice: 10000 (choose > from 5995, 5996, 5997, 5998, 5999, 6000) > > The problem is my default range is actually 0,10000 -- I changed it above > for brevity's sake. So in the real world, it floods the screen to the > point where it's unreadable. > > I can suppress the whole thing with argparse.SUPPRESS, but then I'm left > with no help message at all. Is there a way to suppress the "(choose from > 1,2,3,etc.)" part of the help message? Or a cleaner/different way > altogether to accomplish the same thing? You can supply a custom function as the type to the add_argument() method: http://docs.python.org/2/library/argparse.html#type Here's a basic example: $ cat argparse_intrange.py import argparse def check_range(arg): try: value = int(arg) except ValueError as err: raise argparse.ArgumentTypeError(str(err)) if value < 0 or value > 10000: message = "Expected 0 <= value <= 10000, got value = {}".format(value) raise argparse.ArgumentTypeError(message) return value if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("alpha", type=check_range, nargs="?") print(parser.parse_args()) $ python argparse_intrange.py Namespace(alpha=None) $ python argparse_intrange.py 100 Namespace(alpha=100) $ python argparse_intrange.py -100 usage: argparse_intrange.py [-h] [alpha] argparse_intrange.py: error: argument alpha: Expected 0 <= value <= 10000, got value = -100 $ python argparse_intrange.py 100000 usage: argparse_intrange.py [-h] [alpha] argparse_intrange.py: error: argument alpha: Expected 0 <= value <= 10000, got value = 100000 $ python argparse_intrange.py x usage: argparse_intrange.py [-h] [alpha] argparse_intrange.py: error: argument alpha: invalid literal for int() with base 10: 'x' If you want to use check_range() with arbitrary ranges you can parameterise it: import functools def check_range(arg, min, max): # your code check_range_alpha = functools.partial(check_range, min=0, max=10000) check_range_beta = functools.partial(check_range, min=-10, max=10) parser = argparse.ArgumentParser() parser.add_argument("alpha", type=check_range_alpha, nargs="?") parser.add_argument("beta", type=check_range_beta, nargs="?") From aaronmisquith at gmail.com Mon Jan 28 16:40:33 2013 From: aaronmisquith at gmail.com (Aaron Misquith) Date: Mon, 28 Jan 2013 21:10:33 +0530 Subject: [Tutor] Facebook login using python Message-ID: I am working on a program which is used to login to facebook, get my friend lists using graph api and export them into pdf format. So far i'm able to login with facebook and get the friend list. I would like if someone is able to provide me a code to export the output to pdf. Another thing is that i'm hardcoding username, password and access tokens; is there anyway this can be obtained using user input? Code: import urllib2, cookielib, re, os, sys from facepy import GraphAPI class Facebook(): def __init__(self, email, password): self.email = email self.password = password cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) opener.addheaders = [('Referer', 'http://login.facebook.com/login.php'), ('Content-Type', 'application/x-www-form-urlencoded'), ('User-Agent', 'Mozilla/8.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)')] self.opener = opener def login(self): url = 'https://login.facebook.com/login.php?login_attempt=1' data = "locale=en_US&non_com_login=&email="+self.email+"&pass="+self.password+"&lsd=20TOl" usock = self.opener.open('http://www.facebook.com') usock = self.opener.open(url, data) if "Logout" in usock.read(): print "Logged in." else: print "failed login" print usock.read() sys.exit() f = Facebook("Enter email", "Password") f.login() graph=GraphAPI('Enter Access code from fql in developer's page') nik=graph.fql('select uid, name, friends from user where uid in (select first_name, middle_name, last_name from friend where uid1 = me())') print nik -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Mon Jan 28 16:54:30 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 28 Jan 2013 15:54:30 +0000 Subject: [Tutor] sqlite search In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF4741813527C@SCACMX008.exchad.jpmchase.net> Alan Gauld wrote: > > On 18/01/13 18:11, Roger wrote: > > > At the moment this works to search for everything beginning with A > > sql = "SELECT * FROM plants WHERE genus LIKE 'A%'"; > > cursor.execute(sql); > > SQLlite supports a form of format string where you put in some magic > charactrs then provide arguments which SQLLite will substitute in your > SQL statement. > > You can see examples of that in the database topic in my tutorial: > > file:///home/alang/Documents/HomePage/tutor/tutdbms.htm > > Look at the address book example near the end for the 'Find Entry' > feature, and definitely read the 'word about security' subheading for > the correct way to do it! > Just to clarify, the '%' should go in the parameter string, not as part of the query string. The query string should retain the '?' (without any quotations). ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From davea at davea.name Mon Jan 28 17:53:04 2013 From: davea at davea.name (Dave Angel) Date: Mon, 28 Jan 2013 11:53:04 -0500 Subject: [Tutor] Facebook login using python In-Reply-To: References: Message-ID: <5106ACF0.60807@davea.name> On 01/28/2013 10:40 AM, Aaron Misquith wrote: > I am working on a program which is used to login to facebook, get my friend > lists using graph api and export them into pdf format. > So far i'm able to login with facebook and get the friend list. I would > like if someone is able to provide me a code to export the output to pdf. > Another thing is that i'm hardcoding username, password and access tokens; > is there anyway this can be obtained using user input? > > Code: > > import urllib2, cookielib, re, os, sys > from facepy import GraphAPI > class Facebook(): You should derive all classes from object, or from another class that already does. Old-style classes are long deprecated (and eliminated in Python 3.x) > def __init__(self, email, password): Please fix the indentation, and send as a text message, not html. > self.email = email > self.password = password > > cj = cookielib.CookieJar() > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > opener.addheaders = [('Referer', 'http://login.facebook.com/login.php'), > ('Content-Type', 'application/x-www-form-urlencoded'), > ('User-Agent', 'Mozilla/8.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.7) > Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)')] > > self.opener = opener > > def login(self): > url = 'https://login.facebook.com/login.php?login_attempt=1' > data = > "locale=en_US&non_com_login=&email="+self.email+"&pass="+self.password+"&lsd=20TOl" > > usock = self.opener.open('http://www.facebook.com') > usock = self.opener.open(url, data) > if "Logout" in usock.read(): > print "Logged in." > else: > print "failed login" > print usock.read() > sys.exit() > f = Facebook("Enter email", "Password") > f.login() > graph=GraphAPI('Enter Access code from fql in developer's page') > > nik=graph.fql('select uid, name, friends from user where uid in (select > first_name, middle_name, last_name from friend where uid1 = me())') > > print nik > > Before doing too much work on such an app, consider if you're violating Facebook's terms of service. The following links may not be the right ones, but it could get you started thinking, anyway. http://developers.facebook.com/blog/post/2013/01/25/clarifying-our-platform-policies/ http://www.facebook.com/help/131112897028467/ As for creating a pdf from a simple text list, I think you'd be best shelling out to a program that does just that. Naturally, the choices vary by OS, and I have not recommendations. As for username and password, why not use raw_input ? -- DaveA From alan.gauld at btinternet.com Mon Jan 28 17:56:29 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Jan 2013 16:56:29 +0000 Subject: [Tutor] Facebook login using python In-Reply-To: References: Message-ID: On 28/01/13 15:40, Aaron Misquith wrote: > I am working on a program which is used to login to facebook, get my > friend lists using graph api and export them into pdf format. > So far i'm able to login with facebook and get the friend list. I would > like if someone is able to provide me a code to export the output to > pdf. There is a third part module for this, a Google search for pyPDF should find it... and several tutorials. > Another thing is that i'm hardcoding username, password and access > tokens; is there anyway this can be obtained using user input? raw_input()? or am I missing something? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kwpolska at gmail.com Mon Jan 28 18:01:45 2013 From: kwpolska at gmail.com (Kwpolska) Date: Mon, 28 Jan 2013 18:01:45 +0100 Subject: [Tutor] Facebook login using python In-Reply-To: References: Message-ID: I will kill the one who invented this bullshit with the Reply button. (sent 1 h 13 min ago) ---------- Forwarded message ---------- From: Kwpolska Date: Mon, Jan 28, 2013 at 4:48 PM Subject: Re: [Tutor] Facebook login using python To: Aaron Misquith On Mon, Jan 28, 2013 at 4:40 PM, Aaron Misquith wrote: > I am working on a program which is used to login to facebook, get my friend > lists using graph api and export them into pdf format. > So far i'm able to login with facebook and get the friend list. I would like > if someone is able to provide me a code to export the output to pdf. Another > thing is that i'm hardcoding username, password and access tokens; is there > anyway this can be obtained using user input? > > Code: > > import urllib2, cookielib, re, os, sys > from facepy import GraphAPI > class Facebook(): > def __init__(self, email, password): > self.email = email > self.password = password > > cj = cookielib.CookieJar() > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > opener.addheaders = [('Referer', 'http://login.facebook.com/login.php'), > ('Content-Type', 'application/x-www-form-urlencoded'), > ('User-Agent', 'Mozilla/8.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.7) > Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)')] > > self.opener = opener > > def login(self): > url = 'https://login.facebook.com/login.php?login_attempt=1' > data = > "locale=en_US&non_com_login=&email="+self.email+"&pass="+self.password+"&lsd=20TOl" > > usock = self.opener.open('http://www.facebook.com') > usock = self.opener.open(url, data) > if "Logout" in usock.read(): > print "Logged in." > else: > print "failed login" > print usock.read() > sys.exit() > f = Facebook("Enter email", "Password") > f.login() > graph=GraphAPI('Enter Access code from fql in developer's page') > > nik=graph.fql('select uid, name, friends from user where uid in (select > first_name, middle_name, last_name from friend where uid1 = me())') > > print nik > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > 1. Code indentation was lost in your message. Everything below is based on guessing, guessing and guessing. 2. In order to get user data, do (assuming Python 2): import getpass self.email= raw_input('E-mail address: ') self.password = getpass.getpass('Password: ') devcode = raw_input(Developer access code: ') Although you should provide the user with the tokens, using the same methods REAL developers use, i.e. app authentication. 3. http://lmgtfy.com/?q=python+pdf -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From alan.gauld at btinternet.com Mon Jan 28 18:00:43 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Jan 2013 17:00:43 +0000 Subject: [Tutor] Facebook login using python In-Reply-To: References: Message-ID: On 28/01/13 15:40, Aaron Misquith wrote: > like if someone is able to provide me a code to export the output to > pdf. Oops, sorry ReportLab is the module I was thinking of not pyPDF. The latter is mainly for reading PDF not producing them. Apologies. http://www.reportlab.com/software/opensource/ -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From D.Wilder at F5.com Mon Jan 28 20:15:24 2013 From: D.Wilder at F5.com (Dave Wilder) Date: Mon, 28 Jan 2013 19:15:24 +0000 Subject: [Tutor] Question on re.findall usage Message-ID: Hello, I am trying using re.findall to parse the string below and then create a list from the results. junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet interface 1.3 {\r\n media-capabilities {\r\n none\r\n auto\r\n 40000SR4-FD\r\n 10T-HD\r\n 100TX-FD\r\n 100TX-HD\r\n 1000T-FD\r\n 40000LR4-FD\r\n 1000T-HD\r\n }\r\n}\r\n' What I am doing now is obviously quite ugly, but I have not yet able to manipulate it to work how I want but in a much more efficient and modular way. I did some research on re.findall but am still confused as to how to do character repetition searches, which I guess is what I need to do here. >> junk_list = re.findall(r'(auto|[1|4]0+[A-Z]-[HF]D|[1|4]0+[A-Z][A-Z]-[HF]D|[1|4]0+[A-Z][A-Z][0-9])', junk_list) >> junk_list ['auto', '40000SR4', '10T-HD', '100TX-FD', '100TX-HD', '40000LR4', '1000T-FD', '1000T-HD'] >>> Basically, all I need to search on is: - auto - anything that starts w/ '1' or '4' and then any number of subsequent zeroes e.g. 10T-HD, 40000LR4-FD, 100TX-FD My environment: [root at f5ite ~/tests]$ uname -a Linux VM-QA-ITE-03 2.6.32-220.17.1.el6.i686 #1 SMP Tue May 15 22:09:39 BST 2012 i686 i686 i386 GNU/Linux [root at f5ite ~/tests]$ [root at f5ite ~/tests]$ /usr/bin/python Python 2.7 (r27:82500, Jul 6 2010, 02:54:50) [GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2 Type "help", "copyright", "credits" or "license" for more information. Any ideas? Thanks, Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Jan 28 20:43:56 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 28 Jan 2013 19:43:56 +0000 Subject: [Tutor] Question on re.findall usage In-Reply-To: References: Message-ID: Please post in plain text (not html) as otherwise the code gets screwed up. When I paste your code into a terminal this is what happens: >>> junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet interface 1.3 {\r\n media-capabilities {\r\n none\r\n auto\r\n 40000SR4-FD\r\n 10T-HD\r\n 100TX-FD\r\n 100TX-HD\r\n 1000T-FD\r\n 40000LR4-FD\r\n 1000T-HD\r\n }\r\n}\r\n' >>> junk_list 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet interface 1.3 {\r\n\xc2\xa0\xc2\xa0\xc2\xa0 media-capabilities {\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 none\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 auto\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 40000SR4-FD\r\n\xc2\xa0 10T-HD\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 100TX-FD\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 100TX-HD\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 1000T-FD\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 40000LR4-FD\r\n \xc2\xa0\xc2\xa0\xc2\xa0 1000T-HD\r\n\xc2\xa0\xc2\xa0\xc2\xa0 }\r\n}\r\n' Those \xc2\xa0 characters are non-breaking space characters. The trouble is that I don't know if they were added by your email client or are actually part of your junk string. I've assumed the former and replaced them with spaces in the code I show below. On 28 January 2013 19:15, Dave Wilder wrote: > Hello, > > I am trying using re.findall to parse the string below and then create a > list from the results. > junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet > interface 1.3 {\r\n media-capabilities {\r\n none\r\n > auto\r\n 40000SR4-FD\r\n 10T-HD\r\n 100TX-FD\r\n > 100TX-HD\r\n 1000T-FD\r\n 40000LR4-FD\r\n 1000T-HD\r\n > }\r\n}\r\n' > > What I am doing now is obviously quite ugly, but I have not yet able to > manipulate it to work how I want but in a much more efficient and modular > way. > I did some research on re.findall but am still confused as to how to do > character repetition searches, which I guess is what I need to do here. >>> junk_list = >>> re.findall(r'(auto|[1|4]0+[A-Z]-[HF]D|[1|4]0+[A-Z][A-Z]-[HF]D|[1|4]0+[A-Z][A-Z][0-9])', >>> junk_list) >>> junk_list > ['auto', '40000SR4', '10T-HD', '100TX-FD', '100TX-HD', '40000LR4', > '1000T-FD', '1000T-HD'] This output doesn't match what I would expect from the string above. Why is '1000T-FD' after '40000LR4-FD'? Is that the problem with the code you posted? >>>> > > Basically, all I need to search on is: > > auto > anything that starts w/ ?1? or ?4? and then any number of subsequent zeroes > e.g. 10T-HD, 40000LR4-FD, 100TX-FD Does "any number" mean "one or more" or "zero or more"? Some people like to use regexes for everything. I prefer to try string methods first as I find them easier to understand. Here's my attempt: >>> junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet interface 1.3 {\r\n media-capabilities {\r\n none\r\n auto\r\n 40000SR4-FD\r\n 10T-HD\r\n 100TX-FD\r\n 100TX-HD\r\n 1000T-FD\r\n 40000LR4-FD\r\n 1000T-HD\r\n }\r\n}\r\n' >>> junk_list = [s.strip() for s in junk_list.splitlines()] >>> junk_list = [s for s in junk_list if s == 'auto' or s[:2] in ('10', '40')] >>> junk_list ['auto', '40000SR4-FD', '10T-HD', '100TX-FD', '100TX-HD', '1000T-FD', '40000LR4-FD', '1000T-HD'] Does that do what you want? Oscar From joel.goldstick at gmail.com Mon Jan 28 21:02:50 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 28 Jan 2013 15:02:50 -0500 Subject: [Tutor] Question on re.findall usage In-Reply-To: References: Message-ID: On Mon, Jan 28, 2013 at 2:15 PM, Dave Wilder wrote: > Hello, > > I am trying using re.findall to parse the string below and then create a > list from the results. > junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet > interface 1.3 {\r\n media-capabilities {\r\n none\r\n > auto\r\n 40000SR4-FD\r\n 10T-HD\r\n 100TX-FD\r\n > 100TX-HD\r\n 1000T-FD\r\n 40000LR4-FD\r\n 1000T-HD\r\n > }\r\n}\r\n' > This looks like a variation on the questions you asked over the last couple of months. Printing junk_list I get this: >>> print junk_list pabilitiesnet interface 1.3 media-ca net interface 1.3 { media-capabilities { none auto 40000SR4-FD 10T-HD 100TX-FD 100TX-HD 1000T-FD 40000LR4-FD 1000T-HD } } How do you get junk_list? Read from a file? Is there more in the file besides what is in junk_list? Do you have this exact file format every time? You might do better to use readline() instead of read(), and strip() each line so that you don't have the new line issue. I'm guessing but it looks like you can toss every line until you get past media-capabilities, and toss every line that contains }. But maybe I am reading more into the data format than is appropriate. If my guesses are correct, you don't need regex stuff at all, because each line (that you don't toss) contains something you want, and you can build you list > What I am doing now is obviously quite ugly, but I have not yet able to > manipulate it to work how I want but in a much more efficient and modular > way. > I did some research on re.findall but am still confused as to how to do > character repetition searches, which I guess is what I need to do here. > >> junk_list = > re.findall(r'(auto|[1|4]0+[A-Z]-[HF]D|[1|4]0+[A-Z][A-Z]-[HF]D|[1|4]0+[A-Z][A-Z][0-9])', > junk_list) > >> junk_list > ['auto', '40000SR4', '10T-HD', '100TX-FD', '100TX-HD', '40000LR4', > '1000T-FD', '1000T-HD'] > >>> > > Basically, all I need to search on is: > > - auto > - anything that starts w/ ?1? or ?4? and then any number of subsequent > zeroes e.g. 10T-HD, 40000LR4-FD, 100TX-FD > > > My environment: > [root at f5ite ~/tests]$ uname -a > Linux VM-QA-ITE-03 2.6.32-220.17.1.el6.i686 #1 SMP Tue May 15 22:09:39 BST > 2012 i686 i686 i386 GNU/Linux > [root at f5ite ~/tests]$ > [root at f5ite ~/tests]$ /usr/bin/python > Python 2.7 (r27:82500, Jul 6 2010, 02:54:50) > [GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > Any ideas? > > Thanks, > > Dave > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From D.Wilder at F5.com Mon Jan 28 21:19:21 2013 From: D.Wilder at F5.com (Dave Wilder) Date: Mon, 28 Jan 2013 20:19:21 +0000 Subject: [Tutor] Question on re.findall usage In-Reply-To: References: Message-ID: On 28 January 2013 2:44, : Oscar Benjamin [mailto:oscar.j.benjamin at gmail.com wrote: Please post in plain text (not html) as otherwise the code gets screwed up. ... Some people like to use regexes for everything. I prefer to try string methods first as I find them easier to understand. Here's my attempt: >>> junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet interface 1.3 {\r\n media-capabilities {\r\n none\r\n auto\r\n 40000SR4-FD\r\n 10T-HD\r\n 100TX-FD\r\n 100TX-HD\r\n 1000T-FD\r\n 40000LR4-FD\r\n 1000T-HD\r\n }\r\n}\r\n' >>> junk_list = [s.strip() for s in junk_list.splitlines()] junk_list = >>> [s for s in junk_list if s == 'auto' or s[:2] in ('10', '40')] >>> junk_list ['auto', '40000SR4-FD', '10T-HD', '100TX-FD', '100TX-HD', '1000T-FD', '40000LR4-FD', '1000T-HD'] Does that do what you want? Oscar ***************************** Got it Oscar. Thank you for your respectful corrections and your solution. I used "Rich Text" which is what I thought was recommended by the list gurus at one point. Plain Text it is then. Your response definitely does the trick and I can use that as a base for the future. As per Joel's comment that it is a variation of questions I asked in the past, right you are. I had to put this away for a while and am picking it up again now. I will get string manipulation / RegEx educated. Thank You, Dave From msirenef at lightbird.net Mon Jan 28 21:41:51 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Mon, 28 Jan 2013 15:41:51 -0500 Subject: [Tutor] Question on re.findall usage In-Reply-To: References: Message-ID: <5106E28F.4020601@lightbird.net> On 01/28/2013 03:19 PM, Dave Wilder wrote: > > On 28 January 2013 2:44, : Oscar Benjamin [mailto:oscar.j.benjamin at gmail.com wrote: > > Please post in plain text (not html) as otherwise the code gets screwed up. > ... > > Some people like to use regexes for everything. I prefer to try string methods first as I find them easier to understand. > Here's my attempt: >>>> junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet interface 1.3 {\r\n media-capabilities {\r\n none\r\n auto\r\n 40000SR4-FD\r\n 10T-HD\r\n 100TX-FD\r\n 100TX-HD\r\n 1000T-FD\r\n 40000LR4-FD\r\n 1000T-HD\r\n }\r\n}\r\n' >>>> junk_list = [s.strip() for s in junk_list.splitlines()] junk_list = >>>> [s for s in junk_list if s == 'auto' or s[:2] in ('10', '40')] >>>> junk_list > ['auto', '40000SR4-FD', '10T-HD', '100TX-FD', '100TX-HD', '1000T-FD', '40000LR4-FD', '1000T-HD'] > > Does that do what you want? > > > Oscar > > > ***************************** > > Got it Oscar. Thank you for your respectful corrections and your solution. > I used "Rich Text" which is what I thought was recommended by the list gurus at one point. Plain Text it is then. > > Your response definitely does the trick and I can use that as a base for the future. > > As per Joel's comment that it is a variation of questions I asked in the past, right you are. I had to put this away for a while and am picking it up again now. > I will get string manipulation / RegEx educated. > > Thank You, > > Dave I would like to emphasize that regex is an entirely wrong approach for this task. The reason is that it's very brittle, hard to read, hard to debug and update if the text file changes. The first step should be to simplfy the task -- in this case, to split the string into lines and strip each line. List comps as shown by Oscar is the best approach, but if you don't feel comfortable with list comps, you can then use a loop: lst = [] for line in junk_list: if line == "auto" : lst.append(line) elif line.startswith("10") : lst.append(line) elif line.startswith("40") : lst.append(line) You could even use a regex as part of the loop: for line in junk_list: if re.match("^(auto|10|40)", line): lst.append(line) It's still much better than using a humongous regex. - m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ When a friend succeeds, I die a little. Gore Vidal From ghasemmg01 at leedslearning.net Mon Jan 28 22:22:42 2013 From: ghasemmg01 at leedslearning.net (Ghadir Ghasemi) Date: Mon, 28 Jan 2013 21:22:42 +0000 Subject: [Tutor] Help! Message-ID: <010FB2F3C55002408EE1404538D1B6AE030D8379478A@LLN-SPP-ES-04.user01.lln.local> Hi guys I wanted to make a program called Binary/decimal converter. But I want to do it the hard way e.g. not using built in python functions. Can you give me an idea about how I can do that? Thank you. From mzanfardino at gmail.com Mon Jan 28 22:46:05 2013 From: mzanfardino at gmail.com (Mark K. Zanfardino) Date: Mon, 28 Jan 2013 13:46:05 -0800 Subject: [Tutor] Help! In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D8379478A@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D8379478A@LLN-SPP-ES-04.user01.lln.local> Message-ID: <5106F19D.6090703@gmail.com> Ghadir, I did a quick google search for how to convert digital to binary. The first link was to http://www.ehow.com/how_5164721_convert-digital-binary.html which gives a pretty clear example of the process for converting digital to binary. Of course, you will need to translate this psuedo-code into an algorithm using Python. Cheers! Mark K. Zanfardino On 01/28/2013 01:22 PM, Ghadir Ghasemi wrote: > Hi guys I wanted to make a program called Binary/decimal converter. But I want to do it the hard way e.g. not using built in python functions. Can you give me an idea about how I can do that? > Thank you. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Mon Jan 28 22:51:57 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 28 Jan 2013 14:51:57 -0700 Subject: [Tutor] Help! In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D8379478A@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D8379478A@LLN-SPP-ES-04.user01.lln.local> Message-ID: > Hi guys I wanted to make a program called Binary/decimal converter. But I want to do it the hard way e.g. not using built in python functions. Can you give me an idea about how I can do that? Do you have an idea of what kind of things would be useful test cases for this converter? Thinking about this may help solidify what it is you're trying to do. By it, we want to help you express concretely what you mean when you say "binary/decimal converter". --- For example, if I wanted to write a program to convert "snow" to "water", I might start like this: I want to write a program to take words like "snow" and rewrite them to "water". But anything else should stay the same. Let me give a name to this. Call it "melt". Here are some examples I'd like to make work (or not work). melt("The snow is cold!") ==> "The water is cold!" melt("The snowflakes are falling") ==> "The snowflakes are falling" melt("Snow and ice") ==> "Water and ice" That is, I want to make sure the translation is case sensitive, but only applies when the whole word "snow" shows up. ... etc. A potential approach might use regular expression replacement, with a little bit of care about using a function for the replacement argument so we can handle the weird uppercasing requirement... --- If you plan like this, and include concrete test cases, then you'll have a better shot at solving the problem. From joel.goldstick at gmail.com Mon Jan 28 23:17:19 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 28 Jan 2013 17:17:19 -0500 Subject: [Tutor] Help! In-Reply-To: References: <010FB2F3C55002408EE1404538D1B6AE030D8379478A@LLN-SPP-ES-04.user01.lln.local> Message-ID: On Mon, Jan 28, 2013 at 4:51 PM, Danny Yoo wrote: > > Hi guys I wanted to make a program called Binary/decimal converter. But > I want to do it the hard way e.g. not using built in python functions. Can > you give me an idea about how I can do that? > > > See if you can write the steps to do this by hand. You take binary number -- say 10110 and convert it to decimal. If you can do that with pad and pencil, you are off to a good start. If you can't, then you have to learn that first. Its not magic. Learning about bit shifting will help > Do you have an idea of what kind of things would be useful test cases > for this converter? Thinking about this may help solidify what it is > you're trying to do. By it, we want to help you express concretely > what you mean when you say "binary/decimal converter". > > --- > > For example, if I wanted to write a program to convert "snow" to > "water", I might start like this: > > I want to write a program to take words like "snow" and rewrite them > to "water". But anything else should stay the same. Let me give a > name to this. Call it "melt". Here are some examples I'd like to > make work (or not work). > > melt("The snow is cold!") ==> "The water is cold!" > melt("The snowflakes are falling") ==> "The snowflakes are falling" > melt("Snow and ice") ==> "Water and ice" > > That is, I want to make sure the translation is case sensitive, but > only applies when the whole word "snow" shows up. > > > ... etc. A potential approach might use regular expression > replacement, with a little bit of care about using a function for the > replacement argument so we can handle the weird uppercasing > requirement... > > --- > > > If you plan like this, and include concrete test cases, then you'll > have a better shot at solving the problem. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bfishbein79 at gmail.com Mon Jan 28 23:51:15 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Mon, 28 Jan 2013 16:51:15 -0600 Subject: [Tutor] automate add-to-cart with python Message-ID: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> Hello, I'm trying to automate putting a series of items into my cart. Here's the html for the add-to-cart button on the website: Add to cart Using the cookielib and urllib2 module, I did: a= text.find("href")+6 b = text.find('"', a) url = text[a:b] new_text = opener.open(url).read() It goes to the page that shows my cart, but there are zero items--the item is not added to the cart. I'm guessing this has something to do with: class="PDP_button_addToCart2" I'm not sure how to have Python click the button. In general, despite scouring the Internet, I haven't been able to figure out how to get Python to cause javascripts I find in the html to be run. Any help would be greatly appreciated. Thanks, Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jan 29 00:32:43 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Jan 2013 23:32:43 +0000 Subject: [Tutor] automate add-to-cart with python In-Reply-To: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> References: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> Message-ID: On 28/01/13 22:51, Benjamin Fishbein wrote: > In general, despite scouring the Internet, I haven't been able to figure > out how to get Python to cause javascripts I find in the html to be run. That's because Javascript is run in the browser which has a Javascript interpreter built in. Python doesn't have a Javascript interpreter so can't run Javascript. But that's usually the wrong thing to do anyway so it doesn't matter. What you need to do is figure out what the Javascript is doing - usually sending some data to a server - and replicate that. Alternatively fire up a real browser and drive that with automation. How you do that will largely depend on the browser and the OS. Or maybe, just maybe, somebody has written a javascript interpreter in Python as a module that you can import. It sounds just about crazy enough that it might even exist! But as I said, that's probably the wrong thing to do... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dyoo at hashcollision.org Tue Jan 29 00:42:21 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 28 Jan 2013 16:42:21 -0700 Subject: [Tutor] automate add-to-cart with python In-Reply-To: References: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> Message-ID: > Or maybe, just maybe, somebody has written a javascript interpreter in > Python as a module that you can import. It sounds just about crazy enough > that it might even exist! But as I said, that's probably the wrong thing to > do... A direct approach would probably use the webdriver API to automate the browser. Selenium has one: http://selenium.googlecode.com/svn/trunk/docs/api/py/index.html That being said, I agree with you that this is most likely an overkill approach. Better to see if the site has an officially supported REST-style API that can be more easily mechanized. From oscar.j.benjamin at gmail.com Mon Jan 28 23:04:35 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 28 Jan 2013 22:04:35 +0000 Subject: [Tutor] Set Reply-To field to Tutor@python.org Message-ID: I have both sent and received messages on this list that went off-list by mistake. It's an easy mistake to make that you use reply instead of reply-all and then the message goes just to one person instead of the whole list. This problem is not unique to the python-tutor. I see it happening often on other mailing lists (often it's noticeable by the fact that someone forwards an off-list message back to the list which can sometimes break the threading of email software). One particular list that I receive has recently made an administrative change so that, from now on, all emails have the "Reply-To" header set to the list address. This means that the default behaviour when replying to a message is that the reply goes to the list. I think that this is the right thing to do by default since replying off-list is much less common and more likely to be something that you are consciously aware of when you do it. The change seems to have gone down well on the other list so I wondered: could it be done for this list as well? Oscar From alan.gauld at btinternet.com Tue Jan 29 00:49:48 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 28 Jan 2013 23:49:48 +0000 (GMT) Subject: [Tutor] automate add-to-cart with python In-Reply-To: References: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> Message-ID: <1359416988.77413.YahooMailNeo@web186004.mail.ir2.yahoo.com> >> Or maybe, just maybe, somebody has written a javascript interpreter in >> Python as a module that you can import. It sounds just about crazy enough >> that it might even exist! But as I said, that's probably the wrong thing to >> do... > >A direct approach would probably use the webdriver API to automate the >browser.? Selenium has one: > >? ? http://selenium.googlecode.com/svn/trunk/docs/api/py/index.html > > > >You could use COM to drive IE on Windows or Applescript to drive? a MacOS browser. No idea what you'd do on Linux... But direct API or even a simple CGI url call would be better. Alan g. PS.? Nice to see you posting on tutor again Danny :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Jan 29 02:17:39 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Jan 2013 12:17:39 +1100 Subject: [Tutor] Set Reply-To field to Tutor@python.org In-Reply-To: References: Message-ID: <51072333.5060302@pearwood.info> On 29/01/13 09:04, Oscar Benjamin wrote: > One particular list that I receive has recently made an administrative > change so that, from now on, all emails have the "Reply-To" header set > to the list address. This means that the default behaviour when > replying to a message is that the reply goes to the list. I think that > this is the right thing to do by default since replying off-list is > much less common and more likely to be something that you are > consciously aware of when you do it. > > The change seems to have gone down well on the other list so I > wondered: could it be done for this list as well? http://www.unicom.com/pw/reply-to-harmful.html http://woozle.org/~neale/papers/reply-to-still-harmful.html versus http://www.betacantrips.com/bits/reply_to_munging_considered_harmful_considered_infuriating/ http://www.metasystema.net/essays/reply-to.mhtml -- Steven From doanviettrung at gmail.com Tue Jan 29 04:35:38 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Tue, 29 Jan 2013 14:35:38 +1100 Subject: [Tutor] Set Reply-To field to Tutor@python.org In-Reply-To: <51072333.5060302@pearwood.info> References: <51072333.5060302@pearwood.info> Message-ID: As a student user of this list, I prefer leaving the Reply-To field unchanged. I like the fact that this means a deliberate decision is required to send public emails. Trung On Tue, Jan 29, 2013 at 12:17 PM, Steven D'Aprano wrote: > On 29/01/13 09:04, Oscar Benjamin wrote: > > One particular list that I receive has recently made an administrative >> change so that, from now on, all emails have the "Reply-To" header set >> to the list address. This means that the default behaviour when >> replying to a message is that the reply goes to the list. I think that >> this is the right thing to do by default since replying off-list is >> much less common and more likely to be something that you are >> consciously aware of when you do it. >> >> The change seems to have gone down well on the other list so I >> wondered: could it be done for this list as well? >> > > > http://www.unicom.com/pw/**reply-to-harmful.html > http://woozle.org/~neale/**papers/reply-to-still-harmful.**html > > versus > > http://www.betacantrips.com/**bits/reply_to_munging_** > considered_harmful_considered_**infuriating/ > http://www.metasystema.net/**essays/reply-to.mhtml > > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From glez_b at comunidad.unam.mx Tue Jan 29 06:41:03 2013 From: glez_b at comunidad.unam.mx (Boris Vladimir Comi) Date: Tue, 29 Jan 2013 05:41:03 +0000 Subject: [Tutor] Plot trajectories on an map using matplotlib-basemap Message-ID: <9D6FC4172EA6B64B9044B9B8196DBB250E009F3C@BL2PRD0710MB373.namprd07.prod.outlook.com> #! /usr/bin/python import numpy as np data = np.loadtxt('path-tracks.csv',dtype=np.str,delimiter=',',skiprows=1) print data [['19.70' '-95.20' '2/5/04 6:45 AM' '1' '-38' 'CCM'] ['19.70' '-94.70' '2/5/04 7:45 AM' '1' '-48' 'CCM'] ['19.30' '-93.90' '2/5/04 8:45 AM' '1' '-60' 'CCM'] ['19.00' '-93.50' '2/5/04 9:45 AM' '1' '-58' 'CCM'] ['19.00' '-92.80' '2/5/04 10:45 AM' '1' '-50' 'CCM'] ['19.20' '-92.60' '2/5/04 11:45 AM' '1' '-40' 'CCM'] ['19.90' '-93.00' '2/5/04 12:45 PM' '1' '-43' 'CCM'] ['20.00' '-92.80' '2/5/04 1:15 PM' '1' '-32' 'CCM'] ['23.10' '-100.20' '30/5/04 4:45 AM' '2' '-45' 'SCME'] ['23.20' '-100.00' '30/5/04 5:45 AM' '2' '-56' 'SCME'] ['23.30' '-100.00' '30/5/04 6:45 AM' '2' '-48' 'SCME'] ['23.30' '-100.20' '30/5/04 7:45 AM' '2' '-32' 'SCME'] ['23.40' '-99.00' '31/5/04 3:15 AM' '3' '-36' 'SCM'] ['23.50' '-98.90' '31/5/04 4:15 AM' '3' '-46' 'SCM'] ['23.60' '-98.70' '31/5/04 5:15 AM' '3' '-68' 'SCM'] ['23.70' '-98.80' '31/5/04 6:15 AM' '3' '-30' 'SCM']] with the above code I get an array whose columns represent: [Lat, Lon, Date, Identifier, Temperatures, Category]. Now, I will put a code that allows me to plot the first and second column on the map of Mexico: #!/usr/bin/python #Project Storm: Plot trajectories of convective systems #import libraries import numpy as np from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as pl # Plot a map for Mexico m = Basemap(projection='cyl', llcrnrlat=12, urcrnrlat=35,llcrnrlon=-120, urcrnrlon=-80, resolution='c', area_thresh=1000.) m.bluemarble() m.drawcoastlines(linewidth=0.5) m.drawcountries(linewidth=0.5) m.drawstates(linewidth=0.5) #Draw parallels and meridians m.drawparallels(np.arange(10.,35.,5.)) m.drawmeridians(np.arange(-120.,-80.,10.)) m.drawmapboundary(fill_color='aqua') #Open file whit numpy data = np.loadtxt('path-tracks.csv', dtype=np.str,delimiter=' , ', skiprows=1) latitude = data[:,0] longitude = data[:,1] #Convert latitude and longitude to coordinates X and Y x, y = m(longitude, latitude) #Plot the points on the map pl.plot(x,y,'ro-') pl.show() The points plotted on the map, corresponding to three different paths with a line connecting all points. Mi final idea is to draw a line connecting the points associated with each path, How I can do this? or How should I structure my data to plot the different paths? is posible draw an identifier or a mark for each path? how I can set the size of the figure so that it can distinguish the separation between the points? -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Tue Jan 29 11:12:00 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 29 Jan 2013 10:12:00 +0000 Subject: [Tutor] Set Reply-To field to Tutor@python.org In-Reply-To: References: <51072333.5060302@pearwood.info> Message-ID: On 29 January 2013 03:35, DoanVietTrungAtGmail wrote: > As a student user of this list, I prefer leaving the Reply-To field > unchanged. I like the fact that this means a deliberate decision is > required to send public emails. If you don't mind my asking, do you send many off-list messages as replies to on-list ones? I see the mailing list as being fundamentally a public message forum and only very occasionally send an off-list message. Usually the reason that I do this is because someone else has sent me a message off-list and even though I'm fairly sure they meant it to be on-list I don't want to assume that they did by replying back to the list. Often this means that the archives are incomplete, so that there is a thread but the part of the thread where the OP says "Thanks, this is the solution that worked" or "Sorry, that's not what I meant. My actual problem is..." is missing. Not having this information on the list is unhelpful. It is unhelpful for people reading the archives in the future, for people who keep replying to a thread that is essentially solved, and for people who offer suggestions and don't get feedback on whether their suggestions were useful. Of course if the message is deliberately sent off-list then that is fine but I find that I send/receive many more accidentally off-list messages than deliberate ones. It's hard to predict how often the alternative, accidentally sending a private message to the list, would occur. Although judging from other lists where reply-to-list is the default I would say not very often. I don't find that replying to the list is a deliberate decision to engage in public conversation since the fact that I read and respond to the list at all is because I have already made that decision. For me at least, it is replying off-list that requires explicit consideration. Oscar From doanviettrung at gmail.com Tue Jan 29 12:47:42 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Tue, 29 Jan 2013 22:47:42 +1100 Subject: [Tutor] Set Reply-To field to Tutor@python.org In-Reply-To: References: <51072333.5060302@pearwood.info> Message-ID: On Tue, Jan 29, 2013 at 9:12 PM, Oscar Benjamin wrote: > If you don't mind my asking, do you send many off-list messages as > replies to on-list ones? > Oscar > For this list, I have sent 1 public reply and 2 private replies (to thank individual tutors). Both numbers are too small to have any significance. Reading the Chip Rosenthal article that Steven referred to, I thought that in the case of this Tutor list, his arguments are neither here nor there. It probably comes down to personal preference, and that's why I stated mine. The reason for my personal preference is that for other lists, I am frequently annoyed by private-reply emails landing in my inbox, and sometimes I absent-mindedly do the same thing, thus annoying others. For most lists, group-reply ought to be deliberate. For a few lists it doesn't matter either way. What if, as Oscar seems to say, this Tutor list is in a category where private-reply ought to be deliberate? Most people would only form 1 habit for all lists, rather than 1 for each of the several lists they participate in. If so, I think the habit of deliberate public-reply would serve us better in terms of etiquette. Trung -------------- next part -------------- An HTML attachment was scrubbed... URL: From jguadamuz at gmail.com Tue Jan 29 13:41:42 2013 From: jguadamuz at gmail.com (=?ISO-8859-1?Q?Jonat=E1n_Guadamuz?=) Date: Tue, 29 Jan 2013 06:41:42 -0600 Subject: [Tutor] Set Reply-To field to Tutor@python.org In-Reply-To: References: <51072333.5060302@pearwood.info> Message-ID: <4493147435342726267@unknownmsgid> El 29/01/2013, a las 04:14 a.m., Oscar Benjamin escribi?: > I see the mailing list as being fundamentally a public message forum > and only very occasionally send an off-list message. > Often this means that the archives are incomplete, so that there is a > thread but the part of the thread where the OP says "Thanks, this is > the solution that worked" or "Sorry, that's not what I meant. My > actual problem is..." is missing. Not having this information on the > list is unhelpful. It is unhelpful for people reading the archives in > the future, for people who keep replying to a thread that is > essentially solved, and for people who offer suggestions and don't get > feedback on whether their suggestions were useful. > For me at least, it is replying off-list that requires explicit > consideration. The fact of giving and receiving help by a public mean, and having this help available to others as well, complete in the archives, it's for me enough reason to give +1 to set reply-to field to tutor address. If I am reading something which comes from a mailing list then I think the most proper way to reply would be to send an answer to all the people which originally received the same message. That way, I can avoid duplicate answers, even better this conduct can lead to additional complementary answers because someone can construct on previous partial solutions/suggestions. But this needs all answers are available to everyone. This is my opinion. I hope my writing is understandable. -- Jonatan G From kushal.kumaran+python at gmail.com Tue Jan 29 02:11:07 2013 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 29 Jan 2013 06:41:07 +0530 Subject: [Tutor] Set Reply-To field to Tutor@python.org In-Reply-To: References: Message-ID: <510721b3.4553420a.4681.fffff522@mx.google.com> Oscar Benjamin writes: > I have both sent and received messages on this list that went off-list > by mistake. It's an easy mistake to make that you use reply instead of > reply-all and then the message goes just to one person instead of the > whole list. > > This problem is not unique to the python-tutor. I see it happening > often on other mailing lists (often it's noticeable by the fact that > someone forwards an off-list message back to the list which can > sometimes break the threading of email software). > > One particular list that I receive has recently made an administrative > change so that, from now on, all emails have the "Reply-To" header set > to the list address. This means that the default behaviour when > replying to a message is that the reply goes to the list. I think that > this is the right thing to do by default since replying off-list is > much less common and more likely to be something that you are > consciously aware of when you do it. > > The change seems to have gone down well on the other list so I > wondered: could it be done for this list as well? > To summarize existing opinions on this matter: http://marc.merlins.org/netrants/listreplyto.html You might want to familiarize yourself with existing literature on the matter before starting a new flame war. -- regards, kushal From kwpolska at gmail.com Tue Jan 29 15:50:36 2013 From: kwpolska at gmail.com (Kwpolska) Date: Tue, 29 Jan 2013 15:50:36 +0100 Subject: [Tutor] Help! In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D8379478A@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D8379478A@LLN-SPP-ES-04.user01.lln.local> Message-ID: On Mon, Jan 28, 2013 at 10:22 PM, Ghadir Ghasemi wrote: > Hi guys I wanted to make a program called Binary/decimal converter. That?s easy, int('11', 2) and bin(3) should be enough. > But I want to do it the hard way e.g. not using built in python functions. Can you give me an idea about how I can do that? Are you crazy or is it an assignment? Write code according to this: http://en.wikipedia.org/wiki/Binary_number#Conversion_to_and_from_other_numeral_systems (or other methods you can find on the Internet or in math textbooks). Alternatively, you can find out how it is done in other programming languages or even Python itself. And use that. PS. actually, it is impossible to do it in plain Python without using built-in functions. Because multiplication, division and exponentiation and whatnot are built-ins. OP, please tell your mail provider that it shouldn?t filter swearwords, and even if it does, that it shouldn?t inform me of that. -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From fomcl at yahoo.com Tue Jan 29 16:44:53 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 29 Jan 2013 07:44:53 -0800 (PST) Subject: [Tutor] Set Reply-To field to Tutor@python.org In-Reply-To: <510721b3.4553420a.4681.fffff522@mx.google.com> References: <510721b3.4553420a.4681.fffff522@mx.google.com> Message-ID: <1359474293.64460.YahooMailNeo@web163804.mail.gq1.yahoo.com> > > To summarize existing opinions on this matter: > > http://marc.merlins.org/netrants/listreplyto.html > > You might want to familiarize yourself with existing literature on the > matter before starting a new flame war. Hmmm... False alarm? ? Page blocked? The page you've been trying to access was blocked. Reason: Access Denied! The requested URL is a Spyware site. Transaction ID is 5107F01CFF920603D57F.? From bfishbein79 at gmail.com Tue Jan 29 19:52:00 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Tue, 29 Jan 2013 12:52:00 -0600 Subject: [Tutor] automate add-to-cart with python In-Reply-To: References: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> Message-ID: >> > > A direct approach would probably use the webdriver API to automate the > browser. Selenium has one: > I decided to use Selenium. It may be overkill for this particular problem, but I'll want to use it for other things. This is my first time trying to install a new module to Python. I've been working on it all morning with no success. I'm on Mac OSX and I downloaded : selenium-2.29.0.tar.gz and then opened it to get: selenium-2.29.0 In the README file, it said for installing to Python, to type: pip install -U selenium So in terminal, I went to: cd /Users/bfishbein/Downloads/selenium-2.29.0 and typed: pip install -U selenium I got: -bash: pip: command not found so I tried downloading pip After downloading pip, I tried to install it: cd /Applications/pip-1.2.1 install pip I got this strange message: usage: install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode] [-o owner] file1 file2 install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode] [-o owner] file1 ... fileN directory install -d [-v] [-g group] [-m mode] [-o owner] directory ... Benjamins-MacBook-Air:pip-1.2.1 bfishbein$ Apparently it didn't install. Do you know what I'm doing wrong? Any help would be appreciated. I didn't expect it to be so tough to install a python module. Ben From dyoo at hashcollision.org Tue Jan 29 20:18:08 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 29 Jan 2013 12:18:08 -0700 Subject: [Tutor] automate add-to-cart with python In-Reply-To: References: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> Message-ID: > After downloading pip, I tried to install it: > cd /Applications/pip-1.2.1 > install pip > > I got this strange message: > usage: install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode] > [-o owner] file1 file2 > install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode] > [-o owner] file1 ... fileN directory > install -d [-v] [-g group] [-m mode] [-o owner] directory ... > Benjamins-MacBook-Air:pip-1.2.1 bfishbein$ > > Apparently it didn't install. > Do you know what I'm doing wrong? > Any help would be appreciated. > I didn't expect it to be so tough to install a python module. Technically, this is not pure Python code; expect some friction here due to the different levels of technologies being interconnected. I've been out of the Python development community for a very long time, so hopefully someone else will help correct me. I believe pip, a Python package installer, should be installed by following the instructions in: http://www.pip-installer.org/en/latest/installing.html Have you looked at this yet? The error message you're seeing is conceptually due to the assumption that "install" is a universal thing. It's not. "install" in the context of the command line is something else entirely separate from Python: it's a command to install BSD binary utilities. From pacificmorrowind at gmail.com Tue Jan 29 20:33:30 2013 From: pacificmorrowind at gmail.com (Nick W) Date: Tue, 29 Jan 2013 11:33:30 -0800 Subject: [Tutor] Set Reply-To field to Tutor@python.org In-Reply-To: <1359474293.64460.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <510721b3.4553420a.4681.fffff522@mx.google.com> <1359474293.64460.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: My personal opinion (with whatever limited weight that has on this list since I've only answered a few questions - and probably half of them I've accidentally only sent to the op)/how I read it is that RFC 2822 actually allows lists to set reply-to header; by my view the list software is forwarding to everyone else and therefor counts as the most recent sender/author. I admit that that is a somewhat different conclusion to others that I've read as to the meaning of 2822, but that seems logical to me and also my personal preference is for having the reply-to header be set to the list address. Nick On Tue, Jan 29, 2013 at 7:44 AM, Albert-Jan Roskam wrote: > > > > > > To summarize existing opinions on this matter: > > > > http://marc.merlins.org/netrants/listreplyto.html > > > > You might want to familiarize yourself with existing literature on the > > matter before starting a new flame war. > > Hmmm... False alarm? > > Page blocked > > The page you've been trying to access was blocked. > Reason: Access Denied! The requested URL is a Spyware site. > Transaction ID is 5107F01CFF920603D57F. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Tue Jan 29 20:49:50 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 29 Jan 2013 19:49:50 +0000 Subject: [Tutor] automate add-to-cart with python In-Reply-To: References: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474181393E8@SCACMX008.exchad.jpmchase.net> Benjamin Fishbein wrote: > >> > > > > A direct approach would probably use the webdriver API to automate the > > browser. Selenium has one: > > > I decided to use Selenium. It may be overkill for this particular problem, but I'll want to use it for other > things. > This is my first time trying to install a new module to Python. I've been working on it all morning with no > success. > I'm on Mac OSX and I downloaded : > selenium-2.29.0.tar.gz > and then opened it to get: > selenium-2.29.0 > > In the README file, it said for installing to Python, to type: > pip install -U selenium > > So in terminal, I went to: > > cd /Users/bfishbein/Downloads/selenium-2.29.0 Looks like you are on OS X. You can (probably) install pip from MacPorts or HomeBrew (which can also properly install alternative versions of Python without messing up the system installed version). Not that these are necessary, but they are helpful. Keep them in mind for the future, especially if you test with multiple versions of Python on the same machine. > > and typed: > pip install -U selenium > > I got: > -bash: pip: command not found > so I tried downloading pip > > After downloading pip, I tried to install it: > cd /Applications/pip-1.2.1 > install pip > > I got this strange message: > usage: install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode] > [-o owner] file1 file2 > install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode] > [-o owner] file1 ... fileN directory > install -d [-v] [-g group] [-m mode] [-o owner] directory ... > Benjamins-MacBook-Air:pip-1.2.1 bfishbein$ > > Apparently it didn't install. > Do you know what I'm doing wrong? > Any help would be appreciated. > I didn't expect it to be so tough to install a python module. Normally you want to do `python setup.py install` when manually installing (or similar). I think you should follow the pip install directions here: http://www.pip-installer.org/en/latest/installing.html You need to install distribute or setuptools (use the "source installation" directions for manually installing), but I believe the install script for pip (not get-pip.py) will install the dependencies for you. All of this will install to the global python install which is not always desireable or even recommended. I would highly recommend installing virtual env ( http://www.virtualenv.org/en/latest/ ). This will let you install and try modules without contaminating your global install. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From francois.dion at gmail.com Tue Jan 29 21:12:11 2013 From: francois.dion at gmail.com (Francois Dion) Date: Tue, 29 Jan 2013 15:12:11 -0500 Subject: [Tutor] automate add-to-cart with python In-Reply-To: References: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> Message-ID: On Mon, Jan 28, 2013 at 6:32 PM, Alan Gauld wrote: > On 28/01/13 22:51, Benjamin Fishbein wrote: >> In general, despite scouring the Internet, I haven't been able to figure >> out how to get Python to cause javascripts I find in the html to be run. > > > That's because Javascript is run in the browser which has a Javascript > interpreter built in. Python doesn't have a Javascript interpreter so can't > run Javascript. > > But that's usually the wrong thing to do anyway so it doesn't matter. What > you need to do is figure out what the Javascript is doing - usually sending > some data to a server - and replicate that. > > Alternatively fire up a real browser and drive that with automation. How you > do that will largely depend on the browser and the OS. > > Or maybe, just maybe, somebody has written a javascript interpreter in > Python as a module that you can import. It sounds just about crazy enough > that it might even exist! But as I said, that's probably the wrong thing to > do... The other way around does exists, python in your web browser: http://brython.info Did a quick iPhone web app that way and demoed it to our local Python group last night: http://raspberry-python.blogspot.com/2013/01/iphone-app-with-python.html You could easily extend this concept where your python script server side controls your python script client side through reverse Ajax. And of course it's also possible to do the whole thing client side, without a server. Works on all modern browsers too. Fran?ois -- www.pyptug.org - raspberry-python.blogspot.com - @f_dion From gayathri.s112 at gmail.com Wed Jan 30 06:18:28 2013 From: gayathri.s112 at gmail.com (Gayathri S) Date: Wed, 30 Jan 2013 10:48:28 +0530 Subject: [Tutor] HELP- Regarding working with python In-Reply-To: <510634CE.6090803@pearwood.info> References: <50FA11DE.2090300@gmail.com> <510634CE.6090803@pearwood.info> Message-ID: Hi all...! I don't know how to import our own data sets in python. its always importing the in built data sets. could you just tell me how to do that...! Thanks...! On Mon, Jan 28, 2013 at 1:50 PM, Steven D'Aprano wrote: > On 28/01/13 18:26, Gayathri S wrote: > >> Hi all..! >> wanna know how to compile python script in python command >> line, >> and is there any need for setting path for python like JAVA? whats the >> difference between .py file and .pyc file? >> > > > Python is a byte-code compiled language, like Java many years ago. > Normally to compile a python module, you just import it from within Python. > > That is not very convenient for scripts, so from the shell (bash, > command.com, cmd.exe, or similar) you can run > > python -m compileall NAME NAME ... > > to compile scripts. > > > You do not necessarily need to set the PYTHONPATH, but you can if you need > to. > > .py files are source code. .pyc are compiled byte code. .pyo are compiled > byte code with optimization turned on. Don't get too excited, the standard > Python optimization doesn't do very much. > > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Keep Smiling......... Regards........ Gayu.... -------------- next part -------------- An HTML attachment was scrubbed... URL: From bfishbein79 at gmail.com Wed Jan 30 06:19:39 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Tue, 29 Jan 2013 23:19:39 -0600 Subject: [Tutor] automate add-to-cart with python In-Reply-To: References: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> Message-ID: <4037A769-6EB1-4E0D-9F46-ECFF36B58203@gmail.com> > > > http://www.pip-installer.org/en/latest/installing.html > I went to this pip site. It told me to install virtualenv. http://www.virtualenv.org/en/latest/#installation The virtualenv site told me: You can install virtualenv with pip install virtualenv, or the latest development version with pip install https://github.com/pypa/virtualenv/tarball/develop. But since I didn't yet have pip, I couldn't use it to install virtualenv. Then it said: You can also use easy_install, or if you have no Python package manager available at all, you can just grab the single file virtualenv.py and run it with pythonvirtualenv.py. I don't have easy_install. When I tried to download easy_install, it came in an EGG format that I couldn't open despite downloading several opener apps. I tried this page: https://raw.github.com/pypa/virtualenv/master/virtualenv.py I think this is what I'll have to use for installing virtualenv, but I have not idea what to do with it. I cut and pasted into a python file, then ran it in IDLE. When I ran main(), it returned the error: Traceback (most recent call last): File "", line 1, in virtual_1.main() File "/Users/bfishbein/Documents/virtual_1.py", line 935, in main sys.exit(2) SystemExit: 2 I don't have much experience with command prompt interfaces which I think is causing most of my trouble. There's probably something simple I'm missing, like a semicolon or quotes. Please help if you can. Thank you, Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Jan 30 06:37:36 2013 From: bgailer at gmail.com (bob gailer) Date: Wed, 30 Jan 2013 00:37:36 -0500 Subject: [Tutor] how to import our own data sets Message-ID: <5108B1A0.1080505@gmail.com> This seems to be a new subject. Please start a new email and give it a new and relevant subject. Otherwise your post gets mixed up with older and not relevant posts. On 1/30/2013 12:18 AM, Gayathri S wrote: > Hi all...! > I don't know how to import our own data sets in > python. its always importing the in built data sets. could you just > tell me how to do that...! Perhaps someone else understands your question. I have no idea what you want. What are "data sets"? What do you mean by "built data sets"? What do you mean by "import"? Python uses import to load modules. What are you trying to do? -- Bob Gailer 919-636-4239 Chapel Hill NC From marc.tompkins at gmail.com Wed Jan 30 06:49:32 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 29 Jan 2013 21:49:32 -0800 Subject: [Tutor] automate add-to-cart with python In-Reply-To: <4037A769-6EB1-4E0D-9F46-ECFF36B58203@gmail.com> References: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> <4037A769-6EB1-4E0D-9F46-ECFF36B58203@gmail.com> Message-ID: On Tue, Jan 29, 2013 at 9:19 PM, Benjamin Fishbein wrote:Then it said: > > You can also use easy_install, or if you have no Python package manager > available at all, you can just grab the single file virtualenv.py and > run it with pythonvirtualenv.py. > I'm pretty sure that's a typo. It should say: python virtualenv.py In general, to run a Python script, the simplest (and most usually-expected) way is to start a command prompt (a.k.a. terminal session) and simply type the word "python", followed by the name of the script. IDLE is meant for convenient editing and running - and it's very far from the best tool even for that - but it is definitely NOT recommended as a way to run production code; it introduces too much extraneous junk into the Python environment. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gayathri.s112 at gmail.com Wed Jan 30 07:51:40 2013 From: gayathri.s112 at gmail.com (Gayathri S) Date: Wed, 30 Jan 2013 12:21:40 +0530 Subject: [Tutor] HELP-Regarding python Message-ID: Hi All....! I don't know how to read text file in python. If the data values are stored in a text file format, for example(1,30,60,90,120...200) means what i would do for reading it in python. could you just explain it. Thanks....! Keep Smiling.........[?] Regards........ Gayu....[?] -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: 335.png Type: image/png Size: 640 bytes Desc: not available URL: From davea at davea.name Wed Jan 30 07:57:50 2013 From: davea at davea.name (Dave Angel) Date: Wed, 30 Jan 2013 01:57:50 -0500 Subject: [Tutor] HELP-Regarding python In-Reply-To: References: Message-ID: <5108C46E.6050204@davea.name> On 01/30/2013 01:51 AM, Gayathri S wrote: > Hi All....! > I don't know how to read text file in python. If the data > values are stored in a text file format, for example(1,30,60,90,120...200) > means what i would do for reading it in python. could you just explain it. > > infile = open("filename", "rt") will open a text file line = infile.readline() will read one line from it, as a str After that, you can parse it anyway you like. -- DaveA From spawgi at gmail.com Wed Jan 30 08:01:59 2013 From: spawgi at gmail.com (spawgi at gmail.com) Date: Wed, 30 Jan 2013 12:31:59 +0530 Subject: [Tutor] HELP-Regarding python In-Reply-To: <5108C46E.6050204@davea.name> References: <5108C46E.6050204@davea.name> Message-ID: A safer approach would be - with open(, as : //operation with the file. This way, you do not have to remember to close the file explicitly. On Wed, Jan 30, 2013 at 12:27 PM, Dave Angel wrote: > On 01/30/2013 01:51 AM, Gayathri S wrote: > >> Hi All....! >> I don't know how to read text file in python. If the >> data >> values are stored in a text file format, for example(1,30,60,90,120...200) >> means what i would do for reading it in python. could you just explain it. >> >> >> > infile = open("filename", "rt") will open a text file > > line = infile.readline() will read one line from it, as a str > > After that, you can parse it anyway you like. > > > > > -- > DaveA > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From spawgi at gmail.com Wed Jan 30 08:02:58 2013 From: spawgi at gmail.com (spawgi at gmail.com) Date: Wed, 30 Jan 2013 12:32:58 +0530 Subject: [Tutor] HELP-Regarding python In-Reply-To: References: <5108C46E.6050204@davea.name> Message-ID: missed a parenthesis, it should look like - with open(, ) as : //operation with the file. On Wed, Jan 30, 2013 at 12:31 PM, wrote: > A safer approach would be - > with open(, as : > //operation with the file. > > This way, you do not have to remember to close the file explicitly. > > > On Wed, Jan 30, 2013 at 12:27 PM, Dave Angel wrote: > >> On 01/30/2013 01:51 AM, Gayathri S wrote: >> >>> Hi All....! >>> I don't know how to read text file in python. If the >>> data >>> values are stored in a text file format, for >>> example(1,30,60,90,120...200) >>> means what i would do for reading it in python. could you just explain >>> it. >>> >>> >>> >> infile = open("filename", "rt") will open a text file >> >> line = infile.readline() will read one line from it, as a str >> >> After that, you can parse it anyway you like. >> >> >> >> >> -- >> DaveA >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > > -- > http://spawgi.wordpress.com > We can do it and do it better. > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Jan 30 10:15:35 2013 From: wprins at gmail.com (Walter Prins) Date: Wed, 30 Jan 2013 09:15:35 +0000 Subject: [Tutor] Fwd: HELP-Regarding python In-Reply-To: References: Message-ID: Gayathri, On 30 January 2013 06:51, Gayathri S wrote: > Hi All....! > I don't know how to read text file in python. If the data > values are stored in a text file format, for example(1,30,60,90,120...200) > means what i would do for reading it in python. could you just explain it. > > > > Thanks....! > > The answers you've been given so far assume vanilla Python and no add-on packages. However your previous similar questions regarding this was apparently in the context of some sort of machine learning or data analysis context, and was using scikit or some other addon package (pandas?) for Python. So I suspect your question really is (supposing you're using the Python "Pandas" package), "how do I read a text file into a Pandas dataframe?" Can you please clarify what you're really asking and whether the above question is still in the context of some other package? You must understand that Python is a general purpose programming language, and therefore that the idioms and ways of expressing certain things (like reading a text file "into" Python) in the base language will be different from how one would do it if you're using a specific specialized package. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From bfishbein79 at gmail.com Wed Jan 30 13:07:06 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Wed, 30 Jan 2013 06:07:06 -0600 Subject: [Tutor] automate add-to-cart with python In-Reply-To: References: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> <4037A769-6EB1-4E0D-9F46-ECFF36B58203@gmail.com> Message-ID: <91211044-255E-4D91-AE31-2F7015D41197@gmail.com> On Jan 29, 2013, at 11:49 PM, Marc Tompkins wrote: > > I'm pretty sure that's a typo. It should say: > python virtualenv.py > Woohoo!!! It works. You're right. It worked this way and I was able to install pip. And I got selenium to work. Apparently the problem is that selenium isn't compatible with Python 2.5, so I installed 2.7 and when I typed "import selenium," it worked! Now I just have to figure out how to write the code with the selenium module. Thanks for your help, everyone. Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Jan 30 15:15:07 2013 From: wprins at gmail.com (Walter Prins) Date: Wed, 30 Jan 2013 14:15:07 +0000 Subject: [Tutor] automate add-to-cart with python In-Reply-To: <91211044-255E-4D91-AE31-2F7015D41197@gmail.com> References: <69E88944-2E72-4A76-BFF8-BD51455BCB90@gmail.com> <4037A769-6EB1-4E0D-9F46-ECFF36B58203@gmail.com> <91211044-255E-4D91-AE31-2F7015D41197@gmail.com> Message-ID: Hi, Now I just have to figure out how to write the code with the selenium > module. > > Install the Firefox extension/add-on "Selenium IDE" which will help with that too: http://seleniumhq.org/download/ http://seleniumhq.org/docs/02_selenium_ide.jsp# It's effectively a browser macro recorder which can emit the action recording in multiple languages, including 2 flavours of Python (depending on how you're using Selenium.) You can copy/paste the actions directly from the recorder or export them as Python. Set the clipboard format as "Python" under the "Options"->"Clipboard format" menu, then select some recorded commands (click, shift-click as per usual and then ctrl-c to copy and ctrl-v to paste, or to export them click "File"->"Export test-case as" and pick one of the Python options. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From bfishbein79 at gmail.com Wed Jan 30 15:39:57 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Wed, 30 Jan 2013 08:39:57 -0600 Subject: [Tutor] changing unicode to ascii Message-ID: <1D66C1B0-C6A9-4026-8426-94B8C1D770E1@gmail.com> I was trying to write text to a file and got the following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 5495: ordinal not in range(128) I tried several things I found online, such as: text.encode("ascii", "ignore") which gave me the same error and text.replace("\xa0", "") again, UnicodeEncodeError I tried text.decode("ascii", "ignore") and got the same result. I'm using Python 2.7, so there's some special technique for this version? I think the utf-8 data is unnecessary; I can strip it if I can't convert it to ascii. Of course, I can't figure out how to strip it either. Any help is much appreciated. Thanks, Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Jan 30 16:33:15 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Jan 2013 16:33:15 +0100 Subject: [Tutor] changing unicode to ascii References: <1D66C1B0-C6A9-4026-8426-94B8C1D770E1@gmail.com> Message-ID: Benjamin Fishbein wrote: > I was trying to write text to a file and got the following error: > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in > position 5495: ordinal not in range(128) > > I tried several things I found online, such as: > text.encode("ascii", "ignore") > which gave me the same error Try saving text with assert type(text) == unicode with open(filename, "w") as f: f.write(text.encode("ascii", "ignore")) If that fails please give the exact traceback. Don't paraphrase, use cut- and-paste! If the above works you can preserve your precious data including non-ascii characters with import io assert type(text) == unicode with io.open(filename, "w") as f: f.write(text) From hugo.yoshi at gmail.com Wed Jan 30 16:32:48 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 30 Jan 2013 15:32:48 +0000 Subject: [Tutor] changing unicode to ascii In-Reply-To: <1D66C1B0-C6A9-4026-8426-94B8C1D770E1@gmail.com> References: <1D66C1B0-C6A9-4026-8426-94B8C1D770E1@gmail.com> Message-ID: On Wed, Jan 30, 2013 at 2:39 PM, Benjamin Fishbein wrote: > I was trying to write text to a file and got the following error: > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in > position 5495: ordinal not in range(128) > > I tried several things I found online, such as: > > text.encode("ascii", "ignore") > > which gave me the same error > > and > text.replace("\xa0", "") > > again, UnicodeEncodeError > > I tried > text.decode("ascii", "ignore") > and got the same result. > > I'm using Python 2.7, so there's some special technique for this version? > I think the utf-8 data is unnecessary; I can strip it if I can't convert > it to ascii. > Of course, I can't figure out how to strip it either. > Any help is much appreciated. > Thanks, > Ben > > Please show us the relevant parts of your code so we can properly diagnose the issue. Using text.encode("ascii", "ignore") should absolutely work. You could also just write the file in UTF-8 if you don't absolutely need ascii by using text.encode("utf-8"). Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From bfishbein79 at gmail.com Wed Jan 30 19:05:04 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Wed, 30 Jan 2013 12:05:04 -0600 Subject: [Tutor] changing unicode to ascii In-Reply-To: References: <1D66C1B0-C6A9-4026-8426-94B8C1D770E1@gmail.com> Message-ID: <5A19A4B5-686E-4617-A773-86DC3615493A@gmail.com> > Using text.encode("ascii", "ignore") should absolutely work. You could also just write the file in UTF-8 if you don't absolutely need ascii by using text.encode("utf-8"). > > Hugo You're right. It does work. I forgot to assign the result to a variable: text = text.encode("ascii", "ignore") Thanks. From bgailer at gmail.com Wed Jan 30 22:13:41 2013 From: bgailer at gmail.com (bob gailer) Date: Wed, 30 Jan 2013 16:13:41 -0500 Subject: [Tutor] HELP-Regarding python In-Reply-To: References: Message-ID: <51098D05.5070509@gmail.com> On 1/30/2013 1:51 AM, Gayathri S wrote: I am sorry that you chose to ignore my request to start a new email with a relevant subject. Please next time do so. The easier you make it for us to help you the more likely we will want to help. -- Bob Gailer 919-636-4239 Chapel Hill NC From godsofliberty at lavabit.com Thu Jan 31 19:36:02 2013 From: godsofliberty at lavabit.com (heathen) Date: Thu, 31 Jan 2013 13:36:02 -0500 Subject: [Tutor] operator order Message-ID: why is this: >>> d = 2 >>> d *= 3 + 4 >>> d 14 not this: >>> d = 2 >>> d = d * 3 + 4 >>> d 10 From pacificmorrowind at gmail.com Thu Jan 31 20:16:37 2013 From: pacificmorrowind at gmail.com (Nick W) Date: Thu, 31 Jan 2013 11:16:37 -0800 Subject: [Tutor] operator order In-Reply-To: References: Message-ID: because python process the expression on the right side of the assignment first. ie d *= 3+4 basically is the equivalent of writing (2) * (3+4). Hope that explains it. Nick On Thu, Jan 31, 2013 at 10:36 AM, heathen wrote: > why is this: > > >>> d = 2 > >>> d *= 3 + 4 > >>> d > 14 > > not this: > > >>> d = 2 > >>> d = d * 3 + 4 > >>> d > 10 > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Thu Jan 31 20:20:48 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 31 Jan 2013 12:20:48 -0700 Subject: [Tutor] operator order In-Reply-To: References: Message-ID: On Thu, Jan 31, 2013 at 11:36 AM, heathen wrote: > why is this: > >>>> d *= 3 + 4 The gory details about how Python understands this expression can be found in: http://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements Technically, "3 + 4" is the "expression list" part of the statement, so it gets evaluated. Then it does the multiplication of the target (d) and the value of the expression list (7). From aurelien at cwb.io Thu Jan 31 20:17:59 2013 From: aurelien at cwb.io (=?utf-8?Q?Aur=C3=A9lien_DESBRI=C3=88RES?=) Date: Thu, 31 Jan 2013 20:17:59 +0100 Subject: [Tutor] operator order In-Reply-To: (heathen's message of "Thu, 31 Jan 2013 13:36:02 -0500") References: Message-ID: <87wqut9n6g.fsf@pbot.home> heathen writes: > why is this: > >>>> d = 2 >>>> d *= 3 + 4 >>>> d > 14 hmm ... because d * the result of 3 + 4 > not this: > >>>> d = 2 >>>> d = d * 3 + 4 >>>> d > 10 and here it d multiply by 3 + 4 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Aur?lien DESBRI?RES Ride free! Ride GNU.ORG From hugo.yoshi at gmail.com Thu Jan 31 23:53:22 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 31 Jan 2013 23:53:22 +0100 Subject: [Tutor] operator order In-Reply-To: References: Message-ID: On Thu, Jan 31, 2013 at 8:20 PM, Danny Yoo wrote: > On Thu, Jan 31, 2013 at 11:36 AM, heathen > wrote: > > why is this: > > > >>>> d *= 3 + 4 > > > The gory details about how Python understands this expression can be found > in: > > > http://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements > > Technically, "3 + 4" is the "expression list" part of the statement, > so it gets evaluated. Then it does the multiplication of the target > (d) and the value of the expression list (7). > > The docs really hit it with that "similar but not exactly equal" phrase. Augmented assignment is one of those things that is sort-of-but-not-really equivalent, so it can really bite you in the ass. I recently encountered this little gem on: >>> a = ([], []) >>> a[0] += [1] Traceback (most recent call last): File "", line 1, in a[0] += [1] TypeError: 'tuple' object does not support item assignment >>> a ([1], []) >>> tuples are immutable, but lists *do* support in-place modification. And thus we get an operation that both fails and succeeds at the same time.. -------------- next part -------------- An HTML attachment was scrubbed... URL: