From palani at vahaitech.com Sat Jul 2 01:04:27 2016 From: palani at vahaitech.com (Palanikumar Gopalakrishnan) Date: Sat, 2 Jul 2016 10:34:27 +0530 Subject: [Tutor] Help:python based framework show error Message-ID: Hi dudes, I run the python based framework routersploit , it shows the following error. Traceback (most recent call last): File "./rsf.py", line 11, in routersploit() File "./rsf.py", line 7, in routersploit rsf = RoutersploitInterpreter() File "/home/tester/routersploit/routersploit/interpreter.py", line 155, in __init__ super(RoutersploitInterpreter, self).__init__() File "/home/tester/routersploit/routersploit/interpreter.py", line 25, in __init__ self.setup() File "/home/tester/routersploit/routersploit/interpreter.py", line 39, in setup readline.read_history_file(self.history_file) IOError: [Errno 13] Permission denied Thanks in Advance From steve at pearwood.info Sat Jul 2 04:03:09 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 2 Jul 2016 18:03:09 +1000 Subject: [Tutor] Help:python based framework show error In-Reply-To: References: Message-ID: <20160702080308.GN27919@ando.pearwood.info> On Sat, Jul 02, 2016 at 10:34:27AM +0530, Palanikumar Gopalakrishnan wrote: > Hi dudes, > I run the python based framework routersploit , it shows > the following error. Thanks for sharing. Do you have a question? > Traceback (most recent call last): [...] > File "/home/tester/routersploit/routersploit/interpreter.py", line 39, in setup > readline.read_history_file(self.history_file) > IOError: [Errno 13] Permission denied Have you read the error message? It seems pretty obvious to me: you don't have permission to read the history file. That's not a Python problem, it's a permissions problem: - check that you're reading the right file; - check that you're in the right directory; - check that you're running the code as the right user; - check that permissions on the file are right. Do you know how to do these things? -- Steve From min786a at googlemail.com Sat Jul 2 06:46:07 2016 From: min786a at googlemail.com (Minhaj Ahmed) Date: Sat, 2 Jul 2016 11:46:07 +0100 Subject: [Tutor] dont understand part of a code Message-ID: Hi, below is code for a hangman game which I copied from a book I am studying,Python programming for the absolute beginners by Michael Dawson. I have underlined the part of code I do not understand and why it is there. import random HANGMAN = ( """ ------| | | | | ----- """, """ ------| | 0 | | | ----- """, """ ------| | 0 | -+- | | ----- """, """ ------| | 0 | -+- | | ----- """, """ ------| | 0 | /-+- | | ----- """, """ ------| | 0 | /-+-\ | | ----- """, """ ------| | 0 | /-+-\ | | | ----- """, """ ------| | 0 | /-+-\ | | | | ----- """, """ ------| | 0 | /-+-\ | | | | ----- """, """ ------| | 0 | /-+-\ | | | | | ----- """) MAX_WRONG = len(HANGMAN )-1 WORDS = ("PYTHON","RUBY","VISUAL BASIC","PHP","JAVA","UNIX","LINUX","PERL") word = random.choice(WORDS) so_far = "-" * len(word) wrong = 0 used = [] print("Welcome to hangman.Good luck!") while wrong < MAX_WRONG and so_far != word: print(HANGMAN[wrong]) print("\nYou've used the following letterss:\n",used) print("\nSo far,the word is:\n", so_far) guess = input("\nEnter your guess: ") guess = guess.upper() while guess in used: print("You've already guessed the letter",guess) guess = input("Enter your guess: ") guess = guess.upper() used.append(guess) if guess in word: print("\nYes",guess,"is in the word!") new = "" for i in range(len(word)): if guess == word[i]: new += guess * else:* * new += so_far[i] # why is there a else code here?* so_far = new else: print("\nSorry",guess,"isnt in the word") wrong += 1 if wrong == MAX_WRONG: print(HANGMAN[wrog]) print("\nYou have been hanged!!") else: print("\nYou have guessed correct") print("\nThe word was", word) input("\nPress enter to exit") From alan.gauld at yahoo.co.uk Sat Jul 2 08:28:31 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 2 Jul 2016 13:28:31 +0100 Subject: [Tutor] dont understand part of a code In-Reply-To: References: Message-ID: On 02/07/16 11:46, Minhaj Ahmed via Tutor wrote: > have underlined the part of code I do not understand and why it is there. The mailing list is plain text so formatting like underline doesn't show up. Fortunately you added a comment too... > so_far = "-" * len(word) so_far is whats printed as the result so far. > used = [] used is the letters input so far > while wrong < MAX_WRONG and so_far != word: > print(HANGMAN[wrong]) > print("\nYou've used the following letterss:\n",used) > print("\nSo far,the word is:\n", so_far) > guess = input("\nEnter your guess: ") > guess = guess.upper() > > while guess in used: > print("You've already guessed the letter",guess) ... > if guess in word: > print("\nYes",guess,"is in the word!") > > new = "" > for i in range(len(word)): > if guess == word[i]: > new += guess > * else:* > * new += so_far[i] # why is there a else code here?* The else part is needed so that when the guess is noyt at the given position the current value of so_far is put into new. Lets assume the word is python lets assume sop_far contains ____o_ And you guess y On the first letter new should equal _ So because y is not the first letter the if clause is false so the else is selected and new[0] becomes so_far[0], ie '_' new = '_' Now on the next index i = 1 guess == word[1] is true so the if part executes setting new[1] to guess (ie to 'y') new now equals '_y' Now on the next index i = 2 guess == word[2] is false so the el;se gets selected setting new[2] to so_far[2] = '_' new now equals '_y_' and so on. new[i] either acquires the value of guess or so_far[i] (remember that guess may appear more than once...) > so_far = new Finally so_far is replaced with the final value of new. There are arguably easier ways of doing this using lists of characters rather than strings but this works. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Sun Jul 3 01:07:40 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 3 Jul 2016 00:07:40 -0500 Subject: [Tutor] OT: Recommendations for a Linux distribution to dual-boot with Win7-64 bit In-Reply-To: <20160630041249.GK27919@ando.pearwood.info> References: <1A2C40AD-4A44-4B85-8C10-5EA271DA1D5D@graniteweb.com> <40898999-E4E4-49F1-8CCC-4D1466A34D35@graniteweb.com> <20160630041249.GK27919@ando.pearwood.info> Message-ID: <57789D9C.4010706@gmail.com> This is an update and a test to see if I have figured out Thunderbird's settings so that everything comes over as plain text instead of something else. If there are any issues let me know. Friday the Mint crew announced that they were releasing their new version of Mint, version 18, Sarah, so I went _bleeding edge_ and tried to install it. Things did not go well in the sense that I was not able to make a dual-boot installation where Windows 7 was on its existing hard drive and Mint 18 on its own. As far as I can tell I did everything correctly, but upon rebooting there was no option to go to Mint; instead, the boot went directly to Windows 7. After many hours of effort, searching, etc. (It was after 6 AM local time when I gave up.) I decided to simply unplug the Windows 7 hard drive and plug my new hard drive in its place. I successfully installed Mint 18 and it booted up fine with one quirk. My understanding is that I would be prompted to remove my installation USB drive prior to it rebooting, but it didn't and this seemed to cause issues. On my repeat installation effort I removed the USB drive myself when it appeared that the system had just shut down. Things have gone well since. I guess I will save the dual-boot effort for some other day. Now I am updating things, playing with Firefox and Thunderbird, etc. On the latter I was surprised that Thunderbird did not support conversation views out of the box. I am currently testing an extension, "Thunderbird Conversations", which is a bit different in what I was expecting (Compared to Gmail.), but I suppose I will get used to it. We will see how the Linux experiment will work! My plan is to work my way through the book, "How Linux Works", by Brian Ward. So that will probably distract me from Python studies for a while. Again, thanks for all of the help you've collectively given! boB From info at riesrommens.nl Sun Jul 3 15:32:35 2016 From: info at riesrommens.nl (Ries Rommens) Date: Sun, 3 Jul 2016 21:32:35 +0200 Subject: [Tutor] OT: Recommendations for a Linux distribution to dual-boot with Win7-64 bit In-Reply-To: <57789D9C.4010706@gmail.com> References: <1A2C40AD-4A44-4B85-8C10-5EA271DA1D5D@graniteweb.com> <40898999-E4E4-49F1-8CCC-4D1466A34D35@graniteweb.com> <20160630041249.GK27919@ando.pearwood.info> <57789D9C.4010706@gmail.com> Message-ID: <7ff0b317-a41c-dd92-2632-35d683be39f7@riesrommens.nl> Hello boB, > On the latter I was surprised that Thunderbird did not support > conversation views out of the box. After opening Thunderbird you will see a listing of your emails. Clicking on the header of the very first column of the listing will give you the conversation mode. (Second column header is a star, third one the attachments. Be aware that you can alter the columns shown, so things may be different in your case). Kind regards, Ries Op 03-07-16 om 07:07 schreef boB Stepp: > This is an update and a test to see if I have figured out > Thunderbird's settings so that everything comes over as plain text > instead of something else. If there are any issues let me know. > > Friday the Mint crew announced that they were releasing their new > version of Mint, version 18, Sarah, so I went _bleeding edge_ and > tried to install it. Things did not go well in the sense that I was > not able to make a dual-boot installation where Windows 7 was on its > existing hard drive and Mint 18 on its own. As far as I can tell I > did everything correctly, but upon rebooting there was no option to go > to Mint; instead, the boot went directly to Windows 7. After many > hours of effort, searching, etc. (It was after 6 AM local time when I > gave up.) I decided to simply unplug the Windows 7 hard drive and plug > my new hard drive in its place. I successfully installed Mint 18 and > it booted up fine with one quirk. My understanding is that I would be > prompted to remove my installation USB drive prior to it rebooting, > but it didn't and this seemed to cause issues. On my repeat > installation effort I removed the USB drive myself when it appeared > that the system had just shut down. Things have gone well since. > > I guess I will save the dual-boot effort for some other day. > > Now I am updating things, playing with Firefox and Thunderbird, etc. > On the latter I was surprised that Thunderbird did not support > conversation views out of the box. I am currently testing an > extension, "Thunderbird Conversations", which is a bit different in > what I was expecting (Compared to Gmail.), but I suppose I will get > used to it. > > We will see how the Linux experiment will work! My plan is to work my > way through the book, "How Linux Works", by Brian Ward. So that will > probably distract me from Python studies for a while. > > Again, thanks for all of the help you've collectively given! > > boB > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From robertvstepp at gmail.com Sun Jul 3 18:29:27 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 3 Jul 2016 17:29:27 -0500 Subject: [Tutor] OT: Recommendations for a Linux distribution to dual-boot with Win7-64 bit In-Reply-To: <7ff0b317-a41c-dd92-2632-35d683be39f7@riesrommens.nl> References: <1A2C40AD-4A44-4B85-8C10-5EA271DA1D5D@graniteweb.com> <40898999-E4E4-49F1-8CCC-4D1466A34D35@graniteweb.com> <20160630041249.GK27919@ando.pearwood.info> <57789D9C.4010706@gmail.com> <7ff0b317-a41c-dd92-2632-35d683be39f7@riesrommens.nl> Message-ID: <577991C7.8050907@gmail.com> On 07/03/2016 02:32 PM, Ries Rommens wrote: > Hello boB, > >> On the latter I was surprised that Thunderbird did not support >> conversation views out of the box. > After opening Thunderbird you will see a listing of your emails. > Clicking on the header of the very first column of the listing will give > you the conversation mode. > (Second column header is a star, third one the attachments. Be aware > that you can alter the columns shown, so things may be different in your > case). I had found this -- threaded view -- but it lists the entire thread as a collection of separate emails. What I consider _conversation view_ is all of the thread's emails presented in a single window once any of the emails is opened. Alas, I cannot recommend the Thunderbird Conversations extension at this time as the way it presents the conversation view is difficult to distinguish text, at least in how it interacts with my current Mint theme. So I have actually gone back to what you suggest! Thanks! boB From colbychristensen at hotmail.com Mon Jul 4 16:38:01 2016 From: colbychristensen at hotmail.com (Colby Christensen) Date: Mon, 4 Jul 2016 16:38:01 -0400 Subject: [Tutor] iterators Message-ID: I'm sure this is something simple but I'm missing it. When I check the statement with two values, the if statement works. However, for the statement with one value I get an error. keycode = event.GetKeyCode() if keycode in (13, 370): self.enter() elif keycode in (43, 388): self.add() elif keycode in (45, 390): self.sub() elif keycode in (42, 387): self.mult() elif keycode in (47, 392): self.div() elif keycode in (27): self.clear_all() elif keycode in (67, 99): self.display.SetValue('') else: event.Skip()This is the error message. Traceback (most recent call last): ? File "/home/colby/Calculator/Calculator_betaV3.py", line 110, in OnKeyPress ??? elif keycode in (27): TypeError: argument of type 'int' is not iterable I then tried using elif keycode == 27: but this statement didn't work. I'm pretty sure it's something simple that I've overlooked due to my inexperience. Thanks in advance. From alan.gauld at yahoo.co.uk Mon Jul 4 17:36:42 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 4 Jul 2016 22:36:42 +0100 Subject: [Tutor] iterators In-Reply-To: References: Message-ID: On 04/07/16 21:38, Colby Christensen wrote: > File "/home/colby/Calculator/Calculator_betaV3.py", line 110, in OnKeyPress > elif keycode in (27): > TypeError: argument of type 'int' is not iterable The problem is that 'in' needs a collection to test. (27) is not a single element tuple but just an integer with parens around it. To make it a tuple you need to add a comma: elif keycode in (27,): That should do what you want. Whether it's what you really need is another story. I didn't read the rest of the code! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Mon Jul 4 17:57:25 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 4 Jul 2016 16:57:25 -0500 Subject: [Tutor] iterators In-Reply-To: References: Message-ID: <577ADBC5.4010604@gmail.com> On 07/04/2016 03:38 PM, Colby Christensen wrote: > I'm sure this is something simple but I'm missing it. > When I check the statement with two values, the if statement works. However, for the statement with one value I get an error. > keycode = event.GetKeyCode() > if keycode in (13, 370): > self.enter() > elif keycode in (43, 388): > self.add() > elif keycode in (45, 390): > self.sub() > elif keycode in (42, 387): > self.mult() > elif keycode in (47, 392): > self.div() > elif keycode in (27): > self.clear_all() > elif keycode in (67, 99): > self.display.SetValue('') > else: > event.Skip()This is the error message. > Traceback (most recent call last): > File "/home/colby/Calculator/Calculator_betaV3.py", line 110, in OnKeyPress > elif keycode in (27): > TypeError: argument of type 'int' is not iterable I believe that for (27) to be a tuple, you must insert a comma: (27,). boB From ahall at autodist.com Mon Jul 4 17:44:29 2016 From: ahall at autodist.com (Alex Hall) Date: Mon, 4 Jul 2016 17:44:29 -0400 Subject: [Tutor] iterators In-Reply-To: References: Message-ID: <03AFB68C-9B69-4417-BB3C-534570F4B547@autodist.com> I believe the problem is what the error says: you're passing an int. When you give it two values, you're giving it a tuple, like (1, 2). That's a list type object in Python, and the 'in' keyword has to operate on lists. Therefore, it works. When you give it one value, though, you're giving it an integer, which isn't a list type. The 'in' keyword can't do anything with integers, so it errors out. A check for equality seems the best approach here, but, in theory, I suppose you could do If a in [27] To get it to work. > On Jul 4, 2016, at 16:38, Colby Christensen wrote: > > I'm sure this is something simple but I'm missing it. > When I check the statement with two values, the if statement works. However, for the statement with one value I get an error. > keycode = event.GetKeyCode() > if keycode in (13, 370): > self.enter() > elif keycode in (43, 388): > self.add() > elif keycode in (45, 390): > self.sub() > elif keycode in (42, 387): > self.mult() > elif keycode in (47, 392): > self.div() > elif keycode in (27): > self.clear_all() > elif keycode in (67, 99): > self.display.SetValue('') > else: > event.Skip()This is the error message. > Traceback (most recent call last): > File "/home/colby/Calculator/Calculator_betaV3.py", line 110, in OnKeyPress > elif keycode in (27): > TypeError: argument of type 'int' is not iterable > > I then tried using > > elif keycode == 27: > > but this statement didn't work. > > I'm pretty sure it's something simple that I've overlooked due to my inexperience. > > Thanks in advance. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Mon Jul 4 19:47:27 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 5 Jul 2016 00:47:27 +0100 Subject: [Tutor] iterators In-Reply-To: References: Message-ID: On 04/07/16 21:38, Colby Christensen wrote: > elif keycode in (47, 392): > self.div() > elif keycode in (27): > self.clear_all() I meant to say... > I then tried using > > elif keycode == 27: > > but this statement didn't work. I'm not sure why that didn't work. What exactly happened? Did you get a different error message? If so what? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Mon Jul 4 17:56:42 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 4 Jul 2016 14:56:42 -0700 Subject: [Tutor] iterators In-Reply-To: References: Message-ID: On Mon, Jul 4, 2016 at 1:38 PM, Colby Christensen wrote: > I'm sure this is something simple but I'm missing it. > When I check the statement with two values, the if statement works. However, for the statement with one value I get an error. > keycode = event.GetKeyCode() > if keycode in (13, 370): > self.enter() > elif keycode in (43, 388): > self.add() > elif keycode in (45, 390): > self.sub() > elif keycode in (42, 387): > self.mult() > elif keycode in (47, 392): > self.div() > elif keycode in (27): > self.clear_all() > elif keycode in (67, 99): > self.display.SetValue('') > else: > event.Skip() As Alan mentions, you've hit an "edge case" in Python's grammar. Specifically, the grammar for defining tuples has a somewhat strange edge case with regards to the 1-tuple. https://wiki.python.org/moin/TupleSyntax where we need to add a trailing comma, even though it looks funky. Why do we need it? The reason that this edge case exists is to disambiguate the 1-tuple from a different part of Python's grammar involving parenthesized expressions. Parentheses are used to enforce a particular grouping of operations. As an example, the math expression, y * (x + z) uses parentheses to group the "x + z" part. If we didn't use parens there, it's harder to express the idea of adding 'x' and 'z' together before multiplying by 'y', because multiplication "binds" more strongly than addition, according to the grammatical rules. So the extra trailing comma in a 1-tuple parenthesized expression is just there to make it different looking, to disambiguate it from the use of parentheses for expression grouping. From steve at pearwood.info Mon Jul 4 20:42:06 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 5 Jul 2016 10:42:06 +1000 Subject: [Tutor] iterators In-Reply-To: References: Message-ID: <20160705004205.GQ27919@ando.pearwood.info> On Tue, Jul 05, 2016 at 12:47:27AM +0100, Alan Gauld via Tutor wrote: > > I then tried using > > > > elif keycode == 27: > > > > but this statement didn't work. > > I'm not sure why that didn't work. > What exactly happened? Did you get a different error message? > If so what? I expect that the keycode is always a tuple, usually with two items but sometimes with one. So keycode == 27 compares the tuple (27,) with the int 27 and finds them to be different. -- Steve From eryksun at gmail.com Mon Jul 4 21:12:42 2016 From: eryksun at gmail.com (eryk sun) Date: Tue, 5 Jul 2016 01:12:42 +0000 Subject: [Tutor] iterators In-Reply-To: References: Message-ID: On Mon, Jul 4, 2016 at 9:56 PM, Danny Yoo wrote: > So the extra trailing comma in a 1-tuple parenthesized expression is > just there to make it different looking, to disambiguate it from the > use of parentheses for expression grouping. The comma is the distinguishing element of non-empty tuple literals. It's always required in order to create a non-empty tuple, with or without brackets. For example: >>> 27, (27,) The parentheses are optional for a non-empty tuple, but they're often required because a comma has low precedence. For example, with the expression `x in y, z`, Python first evaluates `x in y`. If the goal is to check whether x is in the the tuple `y, z`, then it has to be written `x in (y, z)`. From alan.gauld at yahoo.co.uk Tue Jul 5 04:01:14 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 5 Jul 2016 09:01:14 +0100 Subject: [Tutor] iterators In-Reply-To: <20160705004205.GQ27919@ando.pearwood.info> References: <20160705004205.GQ27919@ando.pearwood.info> Message-ID: On 05/07/16 01:42, Steven D'Aprano wrote: > On Tue, Jul 05, 2016 at 12:47:27AM +0100, Alan Gauld via Tutor wrote: > >>> I then tried using >>> >>> elif keycode == 27: >>> >>> but this statement didn't work. >> >> I'm not sure why that didn't work. >> What exactly happened? Did you get a different error message? >> If so what? > > I expect that the keycode is always a tuple, usually with two items but > sometimes with one. So keycode == 27 compares the tuple (27,) with the > int 27 and finds them to be different. but then the 'in' tests would fail. >>> (27,) in (27,36) False the fact that the 'in' tests work suggests that keycode is an int. But in that case the == test should work... Although I just realized that the OP didn't actually say the 'in' tests worked, just that they pass the compiler... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From usstexas39 at outlook.com Mon Jul 4 23:36:47 2016 From: usstexas39 at outlook.com (Frank Lawrence) Date: Tue, 5 Jul 2016 03:36:47 +0000 Subject: [Tutor] Problem with code Message-ID: Hello, I have a code here that I?m having a problem with. It?s supposed to be a pizza ordering simulator, as you can tell by the title, but I keep trying to add music to it and whenever I try to play the music with the program running, it always freezes up and crashes. Can someone help me with this? It?s really been bugging me. Thanks! Sent from Mail for Windows 10 From alan.gauld at yahoo.co.uk Tue Jul 5 04:17:53 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 5 Jul 2016 09:17:53 +0100 Subject: [Tutor] Problem with code In-Reply-To: References: Message-ID: On 05/07/16 04:36, Frank Lawrence wrote: > Hello, I have a code here that I?m having a problem with. Unfortunately we can't see it. Now, I could see it among a bunch of HTML when I checked it in the moderator queue, so I'm guessing you sent it as some kind of attachment and the server has stripped it off. Please resend the code pasted into the body of the email. > I keep trying to add music to it and whenever I try to play > the music with the program running, it always freezes up > and crashes. I don't know about the crash, but the freezing may be because it needs to run in a separate thread. Anything that takes a long time to process in a GUI should be done in a background thread. (I don't know if you are familiar with threads yet, but they are a kind of lightweight background subprocess that allows your program to do two things at once.) But without seeing the code that is just a guess! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From ahall at autodist.com Tue Jul 5 09:22:52 2016 From: ahall at autodist.com (Alex Hall) Date: Tue, 5 Jul 2016 09:22:52 -0400 Subject: [Tutor] Writing decorators? Message-ID: Hi list, I've read three or four articles on creating decorators. I don't know why, but the use of decorators makes sense, yet the creation of them isn't clicking. I get the idea, but when it comes to precisely how to write one--what goes where and gets returned/called when--it's just not making complete sense. To simplify things, what might be an example of a decorator that, say, prints "decorated" before whatever string the decorated function prints? That is: @prependDecorated() def printSomething(str): print str printSomething("Hello world.") #result should be: decoratedHello world. My attempt would be: def prependDecorated(f): def prepend(): return "decorated"+f() #something should go at this level too? As I said, I've already read several sources on this. Are there any that people find especially clear and helpful? Thanks for any links and/or explanations. -- Alex Hall Automatic Distributors, IT department ahall at autodist.com From alan.gauld at yahoo.co.uk Tue Jul 5 10:40:30 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 5 Jul 2016 15:40:30 +0100 Subject: [Tutor] Writing decorators? In-Reply-To: References: Message-ID: On 05/07/16 14:22, Alex Hall wrote: > To simplify things, what might be an example of a decorator that, say, > prints "decorated" before whatever string the decorated function prints? > My attempt would be: > > def prependDecorated(f): > def prepend(): > return "decorated"+f() > #something should go at this level too? Recall that a decorator is: a function that takes a function as its argument and returns a function Your code fails on the third item. Lets take a trivial example first, a decorator that does nothing. Define a function that takes a function and returns the same function untouched: >>> def donothing(f): return f Now apply it to a square() function: >>> @donothing def square(x): return x*x >>> square >>> square(4) 16 We could do the same without the @ shorthand by using square2 = donothing(square) But the @ syntax makes it more readable. Now lets look at your task We need a function that takes a function and returns a function that prepends a string: def prepend(f): def add_string(*args, **kwargs): # in case f takes arguments return "decorated "+ str(f(*args,**kwargs)) return add_string Now we can apply that to a function @prepend def cube(n): return n*n*n cube(3) I'm biased because I was the tech editor but the book Professional Python has a nice chapter on decorators. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Tue Jul 5 11:26:34 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 6 Jul 2016 01:26:34 +1000 Subject: [Tutor] Writing decorators? In-Reply-To: References: Message-ID: <20160705152633.GR27919@ando.pearwood.info> On Tue, Jul 05, 2016 at 09:22:52AM -0400, Alex Hall wrote: > Hi list, > I've read three or four articles on creating decorators. I don't know why, > but the use of decorators makes sense, yet the creation of them isn't > clicking. I get the idea, but when it comes to precisely how to write > one--what goes where and gets returned/called when--it's just not making > complete sense. *Technically* a decorator can return anything at all, but the most common use for them is to return a function. In this case, the decorator is a function that: (1) Takes as input a single function; (2) Processes or wraps that function in some way; and (3) Returns the original function, or the wrapped function, as output. Back before Python had the "@decorator" syntax, we used to use decorators like this: def func(arg): ... func = decorator(func) which has the disadvantage that we have to write the function name three times, and that the call to the decorator is kinda lost there at the end instead of near the function declaration, but it does have one advantage: it makes it clear that "func" gets set to whatever decorator() returns. Which may be None if you're not careful. > To simplify things, what might be an example of a decorator that, say, > prints "decorated" before whatever string the decorated function prints? import functools def prependDecorated(function): """Wrap function so that it prints "decorated" before running.""" # Here we define a new function that prints "decorated", # then calls the original function. # # We use functools.wraps as a bit of magic to make sure our new # function looks like the original (same name, docstring, etc). # @functools.wraps(function) def inner(*args, **kwargs): print("Decorated!") return function(*args, **kwargs) # # Now that we have our new "inner" function that calls the old # one, we have to return that inner function. return inner @prependDecorated # NO PARENTHESES!!! def lunch(): print("What's for lunch?") print("How about some wonderful SPAM!!!") That's what the great bulk of decorators look like: (1) declare a function that takes one function as argument; (2) define an inner function (usually called "inner"); (3) it will often take arbitrary *args, **kwargs parameters, since you don't normally know what arguments the WRAPPED (decorated) function will take; (3) use functools.wraps to disguise the inner function as the original function (this is important so that it keeps the docstring, the name, any other attached attributes etc. that the original had); (4) inside the "inner" function, do your pre-processing, then call the original function, do any post-processing, and then return the result; (5) finally return the "inner" function. Here's a decorator that makes sure the decorated function returns a string: def stringify(func): @functools.wraps(func) def inner(*args, **kwargs): result = func(*args, **kwargs) return "stringified result: " + str(result) return inner @stringify def add(a, b): """Return the stringified result of adding a and b.""" return a+b Here's a decorator that makes sure the first argument is greater than zero: def verify_arg0(func): @functools.wraps(func) def inner(x, *args, **kwargs): if x <= 0: raise ValueError('x must be greater than zero') return func(x, *args, **kwargs) return inner Here's a neat trick: here's a decorator that doesn't actually modify the function, but registers its name somewhere! THE_REGISTER = [] def register(func): THE_REGISTER.append(func.__name__) return func @register def plus(a, b): return a + b @register def minus(a, b): return a - b > That is: > > @prependDecorated() > def printSomething(str): > print str > > printSomething("Hello world.") > #result should be: > decoratedHello world. This one is trickier than you think, because it requires knowledge of what the original function will do. It *requires* that the original function MUST call print at least once, otherwise you'll have started to print something, but not completed the line. That may mess up your python prompt (in the interactive interpreter) or any other output you print. But here we go: def prepend_actual_print(func): @functools.wraps(func) def inner(*args, **kwargs): ## print("decorated", end='') # Python 3 syntax sys.stdout.write("decorated") # Python 2 return func(*args, **kwargs) return inner Hope this helps! -- Steve From alan.gauld at yahoo.co.uk Tue Jul 5 13:26:00 2016 From: alan.gauld at yahoo.co.uk (Alan G) Date: Tue, 05 Jul 2016 18:26:00 +0100 Subject: [Tutor] Writing decorators? Message-ID: Sorry for top posting, but yes excepting you don't need the parens after log in the @log line. Sent from my Fonepad Alex Hall wrote: Okay, I think I follow. So a decorator to log that a function ran might be: import utils @log() def run(): ** #do things #utils.py logger = #set up logging def log(f): ** def logThatFRan(*args, **kwargs): ****** [1]logger.info("running %s" %(f.__name__) ****** return f(*args, **kwargs) ** return logThatFRan That will log that F ran, then run f with any arguments. I know I'd have to decorate the inner function with functools.wraps for __name__ to work correctly, but that's the general idea, right? On Tue, Jul 5, 2016 at 10:40 AM, Alan Gauld via Tutor <[2]tutor at python.org> wrote: On 05/07/16 14:22, Alex Hall wrote: > To simplify things, what might be an example of a decorator that, say, > prints "decorated" before whatever string the decorated function prints? > My attempt would be: > > def prependDecorated(f): >** **def prepend(): >** ** **return "decorated"+f() >** **#something should go at this level too? Recall that a decorator is: a function that takes a function as its argument and returns a function Your code fails on the third item. Lets take a trivial example first, a decorator that does nothing. Define a function that takes a function and returns the same function untouched: >>> def donothing(f): return f Now apply it to a square() function: >>> @donothing def square(x): return x*x >>> square >>> square(4) 16 We could do the same without the @ shorthand by using square2 = donothing(square) But the @ syntax makes it more readable. Now lets look at your task We need a function that takes a function and returns a function that prepends a string: def prepend(f): ** ** def add_string(*args, **kwargs):** # in case f takes arguments ** ** ** ** return "decorated "+ str(f(*args,**kwargs)) ** ** return add_string Now we can apply that to a function @prepend def cube(n): return n*n*n cube(3) I'm biased because I was the tech editor but the book Professional Python has a nice chapter on decorators. HTH -- Alan G Author of the Learn to Program web site [3]http://www.alan-g.me.uk/ [4]http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: [5]http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist** -** [6]Tutor at python.org To unsubscribe or change subscription options: [7]https://mail.python.org/mailman/listinfo/tutor -- Alex Hall Automatic Distributors, IT department [8]ahall at autodist.com References Visible links 1. http://logger.info/ 2. mailto:tutor at python.org 3. http://www.alan-g.me.uk/ 4. http://www.amazon.com/author/alan_gauld 5. http://www.flickr.com/photos/alangauldphotos 6. mailto:Tutor at python.org 7. https://mail.python.org/mailman/listinfo/tutor 8. mailto:ahall at autodist.com From ahall at autodist.com Tue Jul 5 13:31:04 2016 From: ahall at autodist.com (Alex Hall) Date: Tue, 5 Jul 2016 13:31:04 -0400 Subject: [Tutor] Writing decorators? In-Reply-To: References: Message-ID: On Tue, Jul 5, 2016 at 1:26 PM, Alan G wrote: > Sorry for top posting, but yes excepting you don't need the parens after > log in the @log line. > For decorators, do you never include parentheses except for passing arguments? It seems a bit odd to drop them if they'd be empty, given that anywhere else doing so would return the function object rather than call it. Yet, if arguments are passed, you include them like you would anywhere else. Or am I misunderstanding it? > > Sent from my Fonepad > > Alex Hall wrote: > > Okay, I think I follow. So a decorator to log that a function ran might be: > > import utils > > @log() > def run(): > #do things > > #utils.py > > logger = #set up logging > > def log(f): > def logThatFRan(*args, **kwargs): > logger.info("running %s" %(f.__name__) > return f(*args, **kwargs) > return logThatFRan > > That will log that F ran, then run f with any arguments. I know I'd have > to decorate the inner function with functools.wraps for __name__ to work > correctly, but that's the general idea, right? > > > On Tue, Jul 5, 2016 at 10:40 AM, Alan Gauld via Tutor > wrote: > >> On 05/07/16 14:22, Alex Hall wrote: >> >> > To simplify things, what might be an example of a decorator that, say, >> > prints "decorated" before whatever string the decorated function prints? >> >> > My attempt would be: >> > >> > def prependDecorated(f): >> > def prepend(): >> > return "decorated"+f() >> > #something should go at this level too? >> >> Recall that a decorator is: >> >> a function >> >> that takes a function as its argument >> and returns a function >> >> Your code fails on the third item. >> >> Lets take a trivial example first, a decorator that >> does nothing. Define a function that takes a function >> and returns the same function untouched: >> >> >>> def donothing(f): return f >> >> Now apply it to a square() function: >> >> >>> @donothing >> def square(x): return x*x >> >> >>> square >> >> >>> square(4) >> 16 >> >> We could do the same without the @ shorthand by using >> >> square2 = donothing(square) >> >> But the @ syntax makes it more readable. >> >> Now lets look at your task >> We need a function that takes a function and >> returns a function that prepends a string: >> >> def prepend(f): >> def add_string(*args, **kwargs): # in case f takes arguments >> return "decorated "+ str(f(*args,**kwargs)) >> return add_string >> >> Now we can apply that to a function >> >> @prepend >> def cube(n): return n*n*n >> >> cube(3) >> >> I'm biased because I was the tech editor but the book >> Professional Python has a nice chapter on decorators. >> >> HTH >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> http://www.amazon.com/author/alan_gauld >> Follow my photo-blog on Flickr at: >> http://www.flickr.com/photos/alangauldphotos >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Alex Hall > Automatic Distributors, IT department > ahall at autodist.com > -- Alex Hall Automatic Distributors, IT department ahall at autodist.com From ahall at autodist.com Tue Jul 5 15:05:45 2016 From: ahall at autodist.com (Alex Hall) Date: Tue, 5 Jul 2016 15:05:45 -0400 Subject: [Tutor] isinstance versus 'is'? Message-ID: Hi all, Thanks for all the help regarding decorators. It makes more sense now. I was double checking that I remembered the isinstance order of arguments correctly by using the command line interpreter, and found something very odd. >>> a = 5 >>> isinstance(a, int) True >>> a is int False What happened there? Don't these do the same thing? I thought I could use them interchangeably? -- Alex Hall Automatic Distributors, IT department ahall at autodist.com From michael.selik at gmail.com Tue Jul 5 17:36:24 2016 From: michael.selik at gmail.com (Michael Selik) Date: Tue, 05 Jul 2016 21:36:24 +0000 Subject: [Tutor] dont understand part of a code In-Reply-To: References: Message-ID: On Sat, Jul 2, 2016 at 8:29 AM Alan Gauld via Tutor wrote: > There are arguably easier ways of doing this > I think you'll find that for-loops are preferable to while-loops. Here's an alternative implementation. https://gist.github.com/selik/d8e0a7622ceff0fe8984a7d19d44bfca import random import string drawings = ( r""" ------| | | | | -- """, r""" ------| | 0 | | | -- """, r""" ------| | 0 | -+- | | -- """, r""" ------| | 0 | /-+- | | -- """, r""" ------| | 0 | /-+-\ | | -- """, r""" ------| | 0 | /-+-\ | | | -- """, r""" ------| | 0 | /-+-\ | | | | -- """, r""" ------| | 0 | /-+-\ | | | | | -- """ ) print('Welcome to Hangman.') print('Good luck!') words = 'python ruby php java unix linux perl'.split() target = list(random.choice(words)) known = ['_'] * len(target) used = [] for drawing in drawings: print('-'.join(c if c not in used else ' ' for c in string.ascii_lowercase)) print(drawing, '\n\t', ' '.join(known)) guess = input('\nEnter your guess: ').lower() while guess in used: print("You've already guessed that letter") guess = input('Please enter a new guess: ').lower() used.append(guess) if guess in target: print('Yes, {!r} is in the word!'.format(guess)) for i, letter in enumerate(target): if guess == letter: known[i] = letter else: print('Sorry, {!r} is not in the word.'.format(guess)) if known == target: print('\nYou guessed the word correctly!') break else: print('\nYou have been hanged!') print('The word was {!r}'.format(''.join(target))) From joel.goldstick at gmail.com Tue Jul 5 18:49:38 2016 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 5 Jul 2016 18:49:38 -0400 Subject: [Tutor] isinstance versus 'is'? In-Reply-To: References: Message-ID: On Tue, Jul 5, 2016 at 3:05 PM, Alex Hall wrote: > Hi all, > Thanks for all the help regarding decorators. It makes more sense now. > > I was double checking that I remembered the isinstance order of arguments > correctly by using the command line interpreter, and found something very > odd. > >>>> a = 5 >>>> isinstance(a, int) > True >>>> a is int > False > > What happened there? Don't these do the same thing? I thought I could use > them interchangeably? > > -- > Alex Hall > Automatic Distributors, IT department > ahall at autodist.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor is denotes identity. 5 is not the type int. It is an int, but it is not the same -- if it was 5('16') would be 16. -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From alan.gauld at yahoo.co.uk Tue Jul 5 19:06:49 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 6 Jul 2016 00:06:49 +0100 Subject: [Tutor] Writing decorators? In-Reply-To: References: Message-ID: On 05/07/16 18:31, Alex Hall wrote: > For decorators, do you never include parentheses except for passing > arguments? It seems a bit odd to drop them if they'd be empty, given that > anywhere else doing so would return the function object rather than call > it. Remember what the @ sign is doing. @decorator def func():... is effectively suyntactic sugar for func = decorator(func) If you write @decorator() That translates to @decorator()(func) which is not at all the same thing. Of course you could get into brain melting mode and write a meta-decorator that returns a decorator! >>> def meta(): def decorator(f): def logit(*args,**kwargs): print("called function with ", args, kwargs) return f(*args,**kwargs) return logit return decorator >>> @meta() #with parens and potentially args def square(x): return x*x >>> square(3) called function with (3,) {} 9 >>> yikes! It all starts to get too complicated for my tiny brain at this point and I usually find another more explicit way to do what I need... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Tue Jul 5 19:22:48 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 6 Jul 2016 00:22:48 +0100 Subject: [Tutor] isinstance versus 'is'? In-Reply-To: References: Message-ID: On 05/07/16 20:05, Alex Hall wrote: > I was double checking that I remembered the isinstance order of arguments > correctly by using the command line interpreter, and found something very > odd. > >>>> a = 5 >>>> isinstance(a, int) > True >>>> a is int > False > > What happened there? Don't these do the same thing? Evidently not! Think about it. isinstance() is asking if a is an instance of int. int is a type. 5 is an instance of that type but it's not the type itself. a is int is asking if a and int are the same things (are they actually the same object). Clearly 5 is not the type int. We can check this in the interpreter: >>> isinstance(5,int) True >>> int >>> 5 5 What you may be getting confused with is: >>> type(5) is int True >>> But even then this is not identical to isinstance, because the latter checks for subclass relationships too: >>> class C: pass ... >>> class D(C): pass ... >>> c = C() >>> d = D() >>> isinstance(c, C) True >>> isinstance(c, D) False >>> isinstance(d, C) True >>> isinstance(d, D) True >>> type(c) is C True >>> type(d) is type(C) False And to further complicate matters the above works differently in v2 from v3(above) The bottom line is that isinstance() is usually the best choice. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Tue Jul 5 19:24:36 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 6 Jul 2016 00:24:36 +0100 Subject: [Tutor] Writing decorators? In-Reply-To: References: Message-ID: On 06/07/16 00:06, Alan Gauld via Tutor wrote: > func = decorator(func) > > If you write @decorator() > > That translates to > > @decorator()(func) Ooops, I meant to say func = decorator()(func) Sorry. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Tue Jul 5 19:28:04 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 5 Jul 2016 16:28:04 -0700 Subject: [Tutor] isinstance versus 'is'? In-Reply-To: References: Message-ID: On Tue, Jul 5, 2016 at 12:05 PM, Alex Hall wrote: >>>> a = 5 >>>> isinstance(a, int) > True >>>> a is int > False > > What happened there? Don't these do the same thing? I thought I could use > them interchangeably? 'isinstance' is something else from 'is'. isinstance will tell us if something is considered to be an "instance" of something: it knows how to categorize. This might be important if, when we're running our program, we have some data and want to do some case analysis based on what classification that data falls into. For example, True and False can be identified as instances of the booleans. ################################### >>> isinstance(True, bool) True >>> isinstance(False, bool) True ################################### If we're object oriented programming based on different classes of data, then 'isinstance' can be used to distinguish things based on their class. For example: ############################# class C1(object): pass class C2(object): pass barry = C1() white = C2() print(isinstance(barry, C1)) print(isinstance(barry, C2)) ############################## if we have two classes, we can create instances of them, and use 'isinstance' to find out if they match a particular class-ification. I rarely use this operator in practice because usually, *how* a value operates and behaves is much more important than *what* strata that value belongs to. I suppose that's an ideal of meritocracy. :) In contrast, 'is' is a more low-level notion having to do with *equality*, not classification. These are both operations that compare two things, but their conceptual types are not the same: * 'isinstance' deals with a thing and a category. * 'is' works on two things that, presumably, might be the same type of thing. (Why? Because if we knew in advance that the the two things were of different types, then we already know that 'is' will return False, so we know our answer in advance.) From lohecn at tuta.io Tue Jul 5 19:56:19 2016 From: lohecn at tuta.io (lohecn at tuta.io) Date: Wed, 6 Jul 2016 00:56:19 +0100 (BST) Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW Message-ID: hey everyone. this is my first time trying this -- actually, I've been studying python only for some days now, and I'm afraid my questions are going to be reeeeally simple, but I can't seem to understand this piece of code and thus can't move on. you probably know the book, so you know that zed always makes us write code so that then we can understand how it works, and it's great, but in this exercise there are just too many new functions and without explanation they are a bit hard to understand... so I'm having trouble with most of the lines here. it's not that I want the full explanation to that code, but since I'm unfamiliar with some of its concepts, I'm just going to tell you all the things that I don't understand (sorry for it being a lot): 1. the need to put script into an estipulation for argv (line 3) 2. the what is txt and why it has to be used there (line 4) 3. txt.read() -- which are all new functions(? I dont even know what they are)? (line 7) 4. file_again (line 10) 5. txt_again (line 12) and line 14. as you can see, it's pretty much everything. sorry about that. I'd really appreciate any help at all! thanks a lot, heloisa From alan.gauld at yahoo.co.uk Tue Jul 5 20:28:32 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 6 Jul 2016 01:28:32 +0100 Subject: [Tutor] isinstance versus 'is'? In-Reply-To: References: Message-ID: On 06/07/16 00:22, Alan Gauld via Tutor wrote: >>>> type(c) is C > True >>>> type(d) is type(C) > False The last one should of course be >>> type(d) is C False Apologies. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Tue Jul 5 20:32:28 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 5 Jul 2016 19:32:28 -0500 Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW In-Reply-To: References: Message-ID: <577C519C.5010206@gmail.com> Welcome! On 07/05/2016 06:56 PM, lohecn at tuta.io wrote: > hey everyone. this is my first time trying this -- actually, I've been > studying python only for some days now, and I'm afraid my questions are going > to be reeeeally simple, but I can't seem to understand this piece of code and > thus can't move on. > > you probably know the book, so you know that zed always makes us write code > so that then we can understand how it works, and it's great, but in this > exercise there are just too many new functions and without explanation they > are a bit hard to understand... so I'm having trouble with most of the lines > here. While this book is fairly well known, not everyone has a copy at hand. I would suggest that you resend your email with the full exercise typed into its body (This list does not accept attachments BTW.), and then pose your questions. This way you provide the necessary context *in* your email body, so that everyone can follow along. Cheers! boB From steve at pearwood.info Tue Jul 5 20:54:42 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 6 Jul 2016 10:54:42 +1000 Subject: [Tutor] isinstance versus 'is'? In-Reply-To: References: Message-ID: <20160706005441.GT27919@ando.pearwood.info> On Tue, Jul 05, 2016 at 03:05:45PM -0400, Alex Hall wrote: > >>> a = 5 > >>> isinstance(a, int) > True > >>> a is int > False > > What happened there? Don't these do the same thing? I thought I could use > them interchangeably? You're probably thinking of "is a", as in, "5 is an int", "'Hello World' is a str", "[1, 2, 3] is a list", etc. Python doesn't have an operator for testing "is a" relationships, it uses isinstance(obj, type). There's also issubclass(), for testing whether one class is a subclass of another. "x is y" checks whether the two operands x and y are the same object. That's *not* the same as checking whether they are equal. You should hardly ever use "is" in Python, with the exception of testing for None: "if obj is None: ..." sort of thing. -- Steve From steve at pearwood.info Tue Jul 5 21:04:36 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 6 Jul 2016 11:04:36 +1000 Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW In-Reply-To: References: Message-ID: <20160706010435.GU27919@ando.pearwood.info> Hi Heloisa, and welcome. Do you have a link to the code? Or better still, if it is short (say under fifty lines) can you copy it into an email and send it? On Wed, Jul 06, 2016 at 12:56:19AM +0100, lohecn at tuta.io wrote: [...] > 1. the need to put script into an estipulation for argv (line 3) I'm sorry, I don't know what that word "estipulation" means. Do you mean "stipulation", as in: That which is stipulated, or agreed upon; that which is definitely arranged or contracted; an agreement > 2. the what is txt and why it has to be used there (line 4) > 3. txt.read() -- which are all new functions(? I dont even know what they > are)? (line 7) > 4. file_again (line 10) > 5. txt_again (line 12) > and line 14. The only thing I can guess without seeing the code is that MAYBE txt is an open file, and txt.read() reads the content of the file. -- Steve From ahall at autodist.com Tue Jul 5 21:37:26 2016 From: ahall at autodist.com (Alex Hall) Date: Tue, 5 Jul 2016 21:37:26 -0400 Subject: [Tutor] isinstance versus 'is'? In-Reply-To: <20160706005441.GT27919@ando.pearwood.info> References: <20160706005441.GT27919@ando.pearwood.info> Message-ID: Thanks everyone, that all makes more sense. I think I was indeed thinking of "is None", which is essentially the same as "== None" (I know there's a subtile difference, but they do the same thing). Of course, "is None" fits with this usage, as you're asking if the value is the literal None object. It seems it's the way None is handled, not an exception in the way 'is' works. Anyway, thanks for the explanations. > On Jul 5, 2016, at 20:54, Steven D'Aprano wrote: > > On Tue, Jul 05, 2016 at 03:05:45PM -0400, Alex Hall wrote: > >>>>> a = 5 >>>>> isinstance(a, int) >> True >>>>> a is int >> False >> >> What happened there? Don't these do the same thing? I thought I could use >> them interchangeably? > > You're probably thinking of "is a", as in, "5 is an int", "'Hello > World' is a str", "[1, 2, 3] is a list", etc. > > Python doesn't have an operator for testing "is a" relationships, it > uses isinstance(obj, type). There's also issubclass(), for testing > whether one class is a subclass of another. > > "x is y" checks whether the two operands x and y are the same object. > That's *not* the same as checking whether they are equal. You should > hardly ever use "is" in Python, with the exception of testing for None: > "if obj is None: ..." sort of thing. > > > -- > Steve > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From michael.selik at gmail.com Tue Jul 5 20:34:28 2016 From: michael.selik at gmail.com (Michael Selik) Date: Wed, 06 Jul 2016 00:34:28 +0000 Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW In-Reply-To: References: Message-ID: On Tue, Jul 5, 2016 at 8:24 PM wrote: > I'm having trouble with most of the lines here. > It looks like you tried to attach a file. This mailing list does not allow attachments. Instead, could you paste the code into your email? > things that I don't understand: > 1. the need to put script into an estipulation for argv (line 3) > 2. the what is txt and why it has to be used there (line 4) > 3. txt.read() -- which are all new functions(? I dont even know what they > are) (line 7) > I'm guessing txt is a file object or a file-like object that supports the .read method to read the entire contents of the file into a single string object. > 4. file_again (line 10) > 5. txt_again (line 12) > and line 14. > From michael.selik at gmail.com Tue Jul 5 21:44:56 2016 From: michael.selik at gmail.com (Michael Selik) Date: Wed, 06 Jul 2016 01:44:56 +0000 Subject: [Tutor] dont understand part of a code In-Reply-To: References: Message-ID: On Tue, Jul 5, 2016 at 5:36 PM Michael Selik wrote: > On Sat, Jul 2, 2016 at 8:29 AM Alan Gauld via Tutor > wrote: > >> There are arguably easier ways of doing this >> > > I think you'll find that for-loops are preferable to while-loops. Here's > an alternative implementation. > > https://gist.github.com/selik/d8e0a7622ceff0fe8984a7d19d44bfca > On further reflection, unfortunately a for-loop doesn't seem best for this particular problem. I updated the gist, linked above. I wish the author had chosen a better problem to emphasize Pythonic iteration. From alan.gauld at yahoo.co.uk Wed Jul 6 04:10:02 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 6 Jul 2016 09:10:02 +0100 Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW In-Reply-To: References: Message-ID: <577CBCDA.1010508@yahoo.co.uk> On 06/07/16 00:56, lohecn at tuta.io wrote: > hey everyone. this is my first time trying this Welcome, but... > you probably know the book, Sorry, I don't and I suspect I'm not alone. It's probably a fine book, but we don't all know it. > so you know that zed always makes us write code > so that then we can understand how it works, Good man Zed :-) > exercise there are just too many new functions and without explanation they > are a bit hard to understand... so I'm having trouble with most of the lines > here. And here's the next problem. This is a text based mailing list. As such the server often strips out attachments as potential security risks. So we can't see the code (I'm assuming you attached it?) > 1. the need to put script into an estipulation for argv (line 3) > 2. the what is txt and why it has to be used there (line 4) > 3. txt.read() -- which are all new functions(? I dont even know what they > are) (line 7) > 4. file_again (line 10) > 5. txt_again (line 12) > and line 14. Without sight of the code its hard to know what's going on. But I suspect some of these "functions" are actually variables (or objects) and hopefully zed has already discussed those? Can you repost but include your code inside the mail message. Also try to post in plain text since HTML tends to get garbled in transit. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Wed Jul 6 04:22:06 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 06 Jul 2016 10:22:06 +0200 Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW References: Message-ID: lohecn at tuta.io wrote: > hey everyone. this is my first time trying this -- actually, I've been > studying python only for some days now, and I'm afraid my questions are > going to be reeeeally simple, but I can't seem to understand this piece of > code and thus can't move on. You seem to be talking about http://learnpythonthehardway.org/book/ex15.html """ from sys import argv script, filename = argv txt = open(filename) print "Here's your file %r:" % filename print txt.read() print "Type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read() """ As others said, always provide the code you are asking about, or if that is not possible at least provide a link. > you probably know the book, so you know that zed always makes us write > code so that then we can understand how it works, and it's great, but in > this exercise there are just too many new functions and without > explanation they are a bit hard to understand... so I'm having trouble > with most of the lines here. > > it's not that I want the full explanation to that code, but since I'm > unfamiliar with some of its concepts, I'm just going to tell you all the > things that I don't understand (sorry for it being a lot): > 1. the need to put script into an estipulation for argv (line 3) Write a script tmp.py containing from sys import argv print argv then call it with with one parameter, e. g. $ python tmp.py somefile.txt ['tmp.py', 'somefile.txt'] As you can see argv is a list with two items, the first being "tmp.py", the name of the script you are invoking. You are only interested in the second one, the filename. The easy way to get that is filename = argv[1] the hard way is to use "unpacking" script, filename = argv where python will assign one item from the list on the right to every name on the left: >>> items = ["foo", "bar"] >>> one, two = items >>> one 'foo' >>> two 'bar' What happens if the number of names on the left doesn't match the number of items in the list? >>> one, two, three = items Traceback (most recent call last): File "", line 1, in ValueError: need more than 2 values to unpack You get an exception. That is why you have to provide the name "script" in Zed's example even though you are not actually interested in the script name. > 2. the what is txt and why it has to be used there (line 4) txt is a file object and > 3. txt.read() -- which are all new functions(? I dont even know what they > are) (line 7) read() is a method that here reads the whole file into a string. You use the open() function to open a file and usually assign the file object that is returned by open to a name. You can freely choose that name. The structure is the same for every object, be it a number: x = 42 # assign a number to x y = x + x # do some arithmetic with x and assign the result to y print y # print the result a list: mynumbers = list() # create a list mynumbers.append(42) # append a number to the list print mynumbers # print the list or a file: myfile = open("example.txt") # open the file example.txt in the current # working directory. If the file doesn't exist # you get an error print "first line:", myfile.readline() # read the first line and print it print "rest of the file:" print myfile.read() # read the rest of the file and print it myfile.close() # close the file > 4. file_again (line 10) > 5. txt_again (line 12) > and line 14. 4. and 5. are just a repetition of the first part, with the variation that the filename, assigned to file_again is read interactively with raw_input() instead of passing it as a commandline argument to the script. The names used can be freely chosen by the programmer, a script from sys import argv red_apple, my_hat = argv blue_suede_shoes = open(my_hat) print blue_suede_shoes.read() blue_suede_shoes.close() would work exactly like the first part of the hard-way example. However, picking descriptive names and using them consistently makes it much easier for a human reader to understand what's going on. From ahall at autodist.com Wed Jul 6 08:32:35 2016 From: ahall at autodist.com (Alex Hall) Date: Wed, 6 Jul 2016 08:32:35 -0400 Subject: [Tutor] Subclassing logging.Handler? Message-ID: Hey list, Another day, another Python experiment. I'm wondering what methods I'd have to implement in a custom subclass of logger.Handler. Currently, the recurring jobs I have written log their events to a file each time they run. That's fine, but it doesn't let me keep easily-sorted/searched records. Even if I use a size-based log file handler, it'll get hard to search. I'm pondering logging to a database as well, so that the files will always have the most recent few runs, but the database will have everything. That means subclassing logger.Handler. I found the docs for this, but is emit() the only function I need to implement? There are things about i/o locks, formatting, and so on as well. How much do I need to do, and how much can I leave up to the super class? I'll have to call super(MyLogHandler, self).__init__() I know, but what else do I have to worry about? To be clear, I'm not asking about logging to a database, only what to do to make a Handler subclass capable of logging through whatever mechanisms I want. Thanks. -- Alex Hall Automatic Distributors, IT department ahall at autodist.com From lohecn at tuta.io Wed Jul 6 10:04:27 2016 From: lohecn at tuta.io (lohecn at tuta.io) Date: Wed, 6 Jul 2016 15:04:27 +0100 (BST) Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW In-Reply-To: References: Message-ID: first, sorry everyone for having attached the file instead of just typing it here. second, thanks a lot for the replies; even though I gave you no code it was quite helpful! the code was this: from sys import argv script, filename = argv txt = open (filename) print "Here's your file %r: " % filename print txt.read() print "Type the filename again: " file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read() Peter Otten explained it to me line by line [thanks so much :)] however, I do have one more question: why do I have to create a variable txt_again to assign it to the open function and them print the file? why is it that I can't only write something like open(file_again).read()? 6. Jul 2016 05:22 by __peter__ at web.de: > lohecn at tuta.io> wrote: > >> hey everyone. this is my first time trying this -- actually, I've been >> studying python only for some days now, and I'm afraid my questions are >> going to be reeeeally simple, but I can't seem to understand this piece of >> code and thus can't move on. > > You seem to be talking about > > http://learnpythonthehardway.org/book/ex15.html > > """ > from sys import argv > > script, filename = argv > > txt = open(filename) > > print "Here's your file %r:" % filename > print txt.read() > > print "Type the filename again:" > file_again = raw_input("> ") > > txt_again = open(file_again) > > print txt_again.read() > """ > > As others said, always provide the code you are asking about, or if that is > not possible at least provide a link. > >> you probably know the book, so you know that zed always makes us write >> code so that then we can understand how it works, and it's great, but in >> this exercise there are just too many new functions and without >> explanation they are a bit hard to understand... so I'm having trouble >> with most of the lines here. >> >> it's not that I want the full explanation to that code, but since I'm >> unfamiliar with some of its concepts, I'm just going to tell you all the >> things that I don't understand (sorry for it being a lot): >> 1. the need to put script into an estipulation for argv (line 3) > > Write a script tmp.py containing > > from sys import argv > print argv > > then call it with with one parameter, e. g. > > $ python tmp.py somefile.txt > ['tmp.py', 'somefile.txt'] > > As you can see argv is a list with two items, the first being "tmp.py", the > name of the script you are invoking. You are only interested in the second > one, the filename. The easy way to get that is > > filename = argv[1] > > the hard way is to use "unpacking" > > script, filename = argv > > where python will assign one item from the list on the right to every name > on the left: > >>>> items = ["foo", "bar"] >>>> one, two = items >>>> one > 'foo' >>>> two > 'bar' > > What happens if the number of names on the left doesn't match the number of > items in the list? > >>>> one, two, three = items > Traceback (most recent call last): > File "", line 1, in > ValueError: need more than 2 values to unpack > > You get an exception. That is why you have to provide the name "script" in > Zed's example even though you are not actually interested in the script > name. > >> 2. the what is txt and why it has to be used there (line 4) > > txt is a file object and > >> 3. txt.read() -- which are all new functions(? I dont even know what they >> are) (line 7) > > read() is a method that here reads the whole file into a string. You use > the > open() function to open a file and usually assign the file object that is > returned by open to a name. You can freely choose that name. The structure > is the same for every object, be it a number: > > x = 42 # assign a number to x > y = x + x # do some arithmetic with x and assign the result to y > print y # print the result > > a list: > > mynumbers = list() # create a list > mynumbers.append(42) # append a number to the list > print mynumbers # print the list > > or a file: > > myfile = open("example.txt") # open the file example.txt in the current > # working directory. If the file doesn't > exist > # you get an error > > print "first line:", myfile.readline() # read the first line and print it > print "rest of the file:" > print myfile.read() # read the rest of the file and print it > > myfile.close() # close the file > >> 4. file_again (line 10) >> 5. txt_again (line 12) >> and line 14. > > 4. and 5. are just a repetition of the first part, with the variation that > the filename, assigned to file_again is read interactively with raw_input() > instead of passing it as a commandline argument to the script. > > The names used can be freely chosen by the programmer, a script > > from sys import argv > > red_apple, my_hat = argv > > blue_suede_shoes = open(my_hat) > print blue_suede_shoes.read() > blue_suede_shoes.close() > > would work exactly like the first part of the hard-way example. However, > picking descriptive names and using them consistently makes it much easier > for a human reader to understand what's going on. > > _______________________________________________ > Tutor maillist - > Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From ahall at autodist.com Wed Jul 6 13:01:07 2016 From: ahall at autodist.com (Alex Hall) Date: Wed, 6 Jul 2016 13:01:07 -0400 Subject: [Tutor] Subclassing logging.Handler? In-Reply-To: References: Message-ID: Regarding this project: I've gone ahead and tried a variant of it. I wanted to log to an HTML file, since those are much easier to look at with a screen reader and so I could get used to the concepts involved. Here's what I've come up with so far. I'll ask the question, then paste the code. I'm getting an error on the self.stream.write line in _open that "'ADTimedRotatingLogFileHandler' has no attribute stream". If I'm subclassing TimedRotatingFileHandler, how can it not have stream? import logging import logging.handlers as logHandlers class ADTimedRotatingLogFileHandler(logHandlers.TimedRotatingFileHandler): def __init__(self, filename, when, interval, backupCount, title): """Most parameters are for the superclass, but 'title' is the title you want your HTML file to have.""" super(ADTimedRotatingLogFileHandler, self).__init__(filename, when, interval, backupCount) self._title = title def _open(self): super(ADTimedRotatingLogFileHandler, self)._open() self.stream.write(""" %s """ %(self._title)) def close(self): self.stream.write(""" """) super(ADTimedRotatingLogFileHandler, self).close() On Wed, Jul 6, 2016 at 8:32 AM, Alex Hall wrote: > Hey list, > Another day, another Python experiment. I'm wondering what methods I'd > have to implement in a custom subclass of logger.Handler. > > Currently, the recurring jobs I have written log their events to a file > each time they run. That's fine, but it doesn't let me keep > easily-sorted/searched records. Even if I use a size-based log file > handler, it'll get hard to search. I'm pondering logging to a database as > well, so that the files will always have the most recent few runs, but the > database will have everything. That means subclassing logger.Handler. > > I found the docs for this, but is emit() the only function I need to > implement? There are things about i/o locks, formatting, and so on as well. > How much do I need to do, and how much can I leave up to the super class? > I'll have to call > super(MyLogHandler, self).__init__() > I know, but what else do I have to worry about? To be clear, I'm not > asking about logging to a database, only what to do to make a Handler > subclass capable of logging through whatever mechanisms I want. Thanks. > > -- > Alex Hall > Automatic Distributors, IT department > ahall at autodist.com > -- Alex Hall Automatic Distributors, IT department ahall at autodist.com From ahall at autodist.com Wed Jul 6 13:42:57 2016 From: ahall at autodist.com (Alex Hall) Date: Wed, 6 Jul 2016 13:42:57 -0400 Subject: [Tutor] Subclassing logging.Handler? In-Reply-To: References: Message-ID: On Wed, Jul 6, 2016 at 1:01 PM, Alex Hall wrote: > Regarding this project: I've gone ahead and tried a variant of it. I > wanted to log to an HTML file, since those are much easier to look at with > a screen reader and so I could get used to the concepts involved. Here's > what I've come up with so far. I'll ask the question, then paste the code. > I'm getting an error on the self.stream.write line in _open that > "'ADTimedRotatingLogFileHandler' has no attribute stream". If I'm > subclassing TimedRotatingFileHandler, how can it not have stream? > Again, in case someone is searching for an answer later and finds this thread: you must assign it. def _open(self): self.stream = super(ADTimedRotatingLogFileHandler, self)._open() I'm now getting a different error, in close(): TypeError: must be type, not None I'm not sure what that's about, but at least I now know why I wasn't getting a stream. > > import logging > import logging.handlers as logHandlers > class ADTimedRotatingLogFileHandler(logHandlers.TimedRotatingFileHandler): > > def __init__(self, filename, when, interval, backupCount, title): > """Most parameters are for the superclass, but 'title' is the > title you want your HTML file to have.""" > super(ADTimedRotatingLogFileHandler, self).__init__(filename, > when, interval, backupCount) > self._title = title > > def _open(self): > super(ADTimedRotatingLogFileHandler, self)._open() > self.stream.write(""" > > %s > > > """ %(self._title)) > > def close(self): > self.stream.write(""" > > """) > super(ADTimedRotatingLogFileHandler, self).close() > > > On Wed, Jul 6, 2016 at 8:32 AM, Alex Hall wrote: > >> Hey list, >> Another day, another Python experiment. I'm wondering what methods I'd >> have to implement in a custom subclass of logger.Handler. >> >> Currently, the recurring jobs I have written log their events to a file >> each time they run. That's fine, but it doesn't let me keep >> easily-sorted/searched records. Even if I use a size-based log file >> handler, it'll get hard to search. I'm pondering logging to a database as >> well, so that the files will always have the most recent few runs, but the >> database will have everything. That means subclassing logger.Handler. >> >> I found the docs for this, but is emit() the only function I need to >> implement? There are things about i/o locks, formatting, and so on as well. >> How much do I need to do, and how much can I leave up to the super class? >> I'll have to call >> super(MyLogHandler, self).__init__() >> I know, but what else do I have to worry about? To be clear, I'm not >> asking about logging to a database, only what to do to make a Handler >> subclass capable of logging through whatever mechanisms I want. Thanks. >> >> -- >> Alex Hall >> Automatic Distributors, IT department >> ahall at autodist.com >> > > > > -- > Alex Hall > Automatic Distributors, IT department > ahall at autodist.com > -- Alex Hall Automatic Distributors, IT department ahall at autodist.com From michael.selik at gmail.com Wed Jul 6 11:23:04 2016 From: michael.selik at gmail.com (Michael Selik) Date: Wed, 06 Jul 2016 15:23:04 +0000 Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW In-Reply-To: References: Message-ID: On Wed, Jul 6, 2016 at 10:59 AM wrote: > why do I have to create a variable txt_again to assign it to the open > function and them print the file? > why is it that I can't only write something like open(file_again).read()? > Good insight. In fact you don't need to create the variable. The code ``data = open('filename').read()`` will open the file named "filename" in the current working directory, read it, and assign the data to a variable. However, many programmers use variables not because they must, but because good variable names can make code easier to read. Also, doing less stuff on a line of code can make that code easier to read. From samuel.moses at mymail.champlain.edu Wed Jul 6 13:27:32 2016 From: samuel.moses at mymail.champlain.edu (Moses, Samuel) Date: Wed, 6 Jul 2016 10:27:32 -0700 Subject: [Tutor] error Message-ID: I am getting an error. I tired to run the script in wing IDE. I am getting this error, "Traceback (most recent call last): File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 822, in main args['firststop'], err, netserver, pwfile_path) File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 649, in CreateServer pwfile_path, internal_modules=tuple(internal_modules)) File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 922, in __init__ File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 2234, in __PrepareConnectListener File "C:\Python32\lib\socket.py", line 94, in __init__ _socket.socket.__init__(self, family, type, proto, fileno) socket.error: [Errno 10107] A system call has failed" I tried printing "Christmas" It said there was no TCP/IP connection. Any suggestion would help Thank you Samuel Moses From alan.gauld at yahoo.co.uk Wed Jul 6 14:33:08 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 6 Jul 2016 19:33:08 +0100 Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW In-Reply-To: References: Message-ID: On 06/07/16 15:04, lohecn at tuta.io wrote: > script, filename = argv > txt = open (filename) > > print "Here's your file %r: " % filename > print txt.read() > > print "Type the filename again: " > file_again = raw_input("> ") > > txt_again = open(file_again) > print txt_again.read() > why do I have to create a variable txt_again to assign it to the open > function and them print the file? You don't, and could get away with a single variable - filename. Like this: filename = argv[1] print "Here's your file %r: " % filename print open(filename).read() filename = raw_input("Type the filename again: >") print open(filename).read() But your book is (I assume) trying to teach you good practice. While you could have just printed the result of read directly, its better not to over complicate code by doing too much in one line (for a start, its harder to debug) the same variable. Variables are cheap to create and if given useful names tell us a lot about the purpose of the code. In this case it's all a bit trivial, just printing the file content, but if you were doing more complex processing storing the file (and data) in variables would be the best choice. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Jul 6 14:39:31 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 6 Jul 2016 19:39:31 +0100 Subject: [Tutor] error In-Reply-To: References: Message-ID: On 06/07/16 18:27, Moses, Samuel wrote: > I am getting an error. I tired to run the script in wing IDE. > Without the accompanying code we can only guess. > I am getting this error, > > "Traceback (most recent call last): > File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 822, in > main > args['firststop'], err, netserver, pwfile_path) > File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 649, in > CreateServer > pwfile_path, internal_modules=tuple(internal_modules)) > File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 922, in > __init__ > File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 2234, in > __PrepareConnectListener > File "C:\Python32\lib\socket.py", line 94, in __init__ > _socket.socket.__init__(self, family, type, proto, fileno) > socket.error: [Errno 10107] A system call has failed" Have you checked that you have the requisite permissions? That the socket you are connecting to exists? If its a system call error the problem is most likely in your environment rather than your code. But check the values you pass into socket. Print them out to check they are what you (and Python) expect... > I tried printing "Christmas" I have no idea what that means. Literally putting print "Christmas" in your code probably wouldn't help so I assume you did something else? > It said there was no TCP/IP connection. What said? Was it another error trace? Or something else? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From badouglas at gmail.com Wed Jul 6 15:35:16 2016 From: badouglas at gmail.com (bruce) Date: Wed, 6 Jul 2016 15:35:16 -0400 Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are they? Message-ID: Hi. Saw the decorator thread earlier.. didn't want to pollute it. I know, I could google! But, what are decorators, why are decorators? who decided you needed them! Thanks! From ahall at autodist.com Wed Jul 6 16:56:47 2016 From: ahall at autodist.com (Alex Hall) Date: Wed, 6 Jul 2016 16:56:47 -0400 Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are they? In-Reply-To: References: Message-ID: On Wed, Jul 6, 2016 at 3:35 PM, bruce wrote: > Hi. > > Saw the decorator thread earlier.. didn't want to pollute it. I know, I > could google! > > But, what are decorators, why are decorators? who decided you needed them! > They're functions that modify the decorated function. If I make a function that performs a task, I might decorate with a logging function: @logThis def doSomething(): #do stuff The logThis decorator could log the run, or modify the doSomething output, or do any number of tasks. To get that extra functionality, I need only decorate my own function. I see these a lot in Flask, a web framework, where they are used to define what parts of your website are handled by what functions, for instance. Basically, they let you extend what your functions do without needing to subclass anything. > > Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Alex Hall Automatic Distributors, IT department ahall at autodist.com From ahall at autodist.com Wed Jul 6 17:25:58 2016 From: ahall at autodist.com (Alex Hall) Date: Wed, 6 Jul 2016 17:25:58 -0400 Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are they? In-Reply-To: References: Message-ID: On Wed, Jul 6, 2016 at 4:56 PM, Alex Hall wrote: > > > On Wed, Jul 6, 2016 at 3:35 PM, bruce wrote: > >> Hi. >> >> Saw the decorator thread earlier.. didn't want to pollute it. I know, I >> could google! >> >> But, what are decorators, why are decorators? who decided you needed them! >> > > I thought of an example that may help. It's not a great example, but here goes. Say you own a bakery, and you employ Joe and me. You task me with taking cookies from the kitchen and putting them in the display case in the service area, which I do well. The problem is that I don't know what looks appealing and what doesn't, so I keep putting cookies out that don't look great. You can't teach something like that, it's just something you know. Since you can't modify me to do my task in the way you want, you grab Joe and have him help me. Instead of putting all the cookies out, I now have Joe checking me before I place each one. Joe knows appealing, so is good at this, but he's also usually busy up front so can't carry the cookies out from the kitchen like I can. Joe is the decorator, and I'm the function being decorated. Since I do my task well, but lack a component you want, and since that component would be hard to program, you find an existing version of the component (Joe) and tell us to work together. Joe can modify my output before I return it, letting him filter the appealing cookies out while I do the work of carrying them up and setting out the ones Joe doesn't tell me to reject. Hopefully this makes some sense. > They're functions that modify the decorated function. If I make a function > that performs a task, I might decorate with a logging function: > > @logThis > def doSomething(): > #do stuff > > The logThis decorator could log the run, or modify the doSomething output, > or do any number of tasks. To get that extra functionality, I need only > decorate my own function. I see these a lot in Flask, a web framework, > where they are used to define what parts of your website are handled by > what functions, for instance. Basically, they let you extend what your > functions do without needing to subclass anything. > >> >> Thanks! >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Alex Hall > Automatic Distributors, IT department > ahall at autodist.com > -- Alex Hall Automatic Distributors, IT department ahall at autodist.com From samuel.moses at mymail.champlain.edu Wed Jul 6 14:34:36 2016 From: samuel.moses at mymail.champlain.edu (Moses, Samuel) Date: Wed, 6 Jul 2016 11:34:36 -0700 Subject: [Tutor] OS and Windows version Message-ID: Mine OS: Windows Windows version: 8.1 Python 3.2 Wing IDE: 15.1 Sam From alan.gauld at yahoo.co.uk Wed Jul 6 17:34:47 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 6 Jul 2016 22:34:47 +0100 Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are they? In-Reply-To: References: Message-ID: On 06/07/16 20:35, bruce wrote: > Saw the decorator thread earlier.. didn't want to pollute it. I know, I > could google! > > But, what are decorators, why are decorators? who decided you needed them! decorators are things that modify functions in standard ways. Specifically they are functions that act on functions. Mostly people think of them as being the thing that comes after an @ sign, but in fact they are just functions but with a bit of syntactic sugar to make them more readable. You don't really *need* them as a feature, but if you have the ability to treat functions as values they are a useful technique. Most Python programmers don't implement decorators they just use the standard ones. But as the thread showed implementing them is not too difficult once you get happy with the idea of passing functions around as arguments to other functions. As to who suggested them you'd need to go back through the PEPs to see who first suggested it, and then maybe more to see who's idea finally got accepted. I think it was in Python 2.5. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Jul 6 17:39:50 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 6 Jul 2016 22:39:50 +0100 Subject: [Tutor] OS and Windows version In-Reply-To: References: Message-ID: On 06/07/16 19:34, Moses, Samuel wrote: > Mine > > OS: Windows > Windows version: 8.1 > > Python 3.2 > Wing IDE: 15.1 Thanks for the extra info but it doesn't help much with your problem since we still don't know what your code does nor how your environment is set up. BTW Can you connect to your target socket using telnet? (Use a CMD console)If you get an error message there you probably can't connect from Python either. Finally you could try running the script outside Wing. IDEs can do all sorts of weird stuff to programs. Its always worth a try running it using the vanilla Python interpreter. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Wed Jul 6 20:33:23 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 6 Jul 2016 17:33:23 -0700 Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are they? In-Reply-To: References: Message-ID: > As to who suggested them you'd need to go back through the > PEPs to see who first suggested it, and then maybe more to see > who's idea finally got accepted. I think it was in Python 2.5. Hi Bruce, Yes, it happened back around 2003: https://www.python.org/dev/peps/pep-0318/ Decorators are "syntactic sugar" in the sense that they can be rewritten in terms of more primitive parts of the language (function calls). If you already know about functions that work on functions, then you know what decorators are. However, if you haven't seen the concept of functions that take functions as input, and you want to talk about that, feel free to ask questions! It would likely be a "fun" discussion to have. From dyoo at hashcollision.org Wed Jul 6 20:37:55 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 6 Jul 2016 17:37:55 -0700 Subject: [Tutor] error In-Reply-To: References: Message-ID: > > Have you checked that you have the requisite permissions? That the > socket you are connecting to exists? If its a system call error the > problem is most likely in your environment rather than your code. > That particular error is from Windows. One common cause for it is a network firewall, which normally is great because at least it's working as a first line of defense. If that's the case, you probably want to tell your firewall to make an exception for your program. From steve at pearwood.info Wed Jul 6 22:18:43 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 7 Jul 2016 12:18:43 +1000 Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are they? In-Reply-To: References: Message-ID: <20160707021843.GW27919@ando.pearwood.info> On Wed, Jul 06, 2016 at 03:35:16PM -0400, bruce wrote: > Hi. > > Saw the decorator thread earlier.. didn't want to pollute it. I know, > I could google! > > But, what are decorators, why are decorators? who decided you needed > them! Sometimes you find yourself writing many functions (or methods) that have bits in common. For example, you might have a bunch of mathematical functions that all start off with the same boring code "check that the argument x is a number, raise an exception if it isn't". Sure, it's only two or three lines, but if you've got twenty functions to write, you have to write those same lines twenty times. And then if you decide to change the error message, or change the way you check something is a number, you have to do that in twenty places. A decorator let's you factor out that common code into a single place, so you only need to make changes to *one* place instead of twenty separate functions. You still have to apply the decorator to each of the functions, but that's only once line. Besides, a decorator is not really about cutting back the number of lines of code (although it is nice when that happens) as it is about moving common code to one place. def verify_numeric_argument(func): """Decorator that checks the argument to a function is a number.""" @functools.wraps(func) def inner(x): if isinstance(x, numbers.Number): return func(x) else: kind = type(x).__name__ raise TypeError("expected a number, but got %s" % kind) return inner @verify_numeric_argument def sinc(x): if x == 0: return 1.0 else: return math.sin(x)/x Obviously you wouldn't bother if you're only going to do it *once*. There's a bunch of overhead involved in writing a decorator, usually about five or six lines of code per decorator. The rule of thumb I use is that if I have one or two functions with the same, common, chunk of code, I probably wouldn't bother; if I have three functions, I might, and if I have four or more, then I probably will. But as I said, it's not really about saving lines of code. It's about keeping code that belongs together in one place, and about recognising when functions repeat the same structure. If you have a bunch of functions that look like this: def function(arguments): boring boilerplate that is the same each time interesting bit that is different each time more boring boilingplate return result then this is a great candidate for a decorator: move the boring boilerplate into the decorator, then turn the functions into this: @apply_boilerplate def function(arguments): interesting bit that is different each time return result Doesn't that look better? That's the purpose of the decorator: move the boring bits, or sometimes the hard, complicated bits, away so you can focus on the interesting bits. Depending on just how boring that boilerplate is, I might even do it for ONE function, just to get it out of the way. -- Steve From alan.gauld at yahoo.co.uk Thu Jul 7 04:36:56 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 7 Jul 2016 09:36:56 +0100 Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are they? In-Reply-To: References: Message-ID: On 06/07/16 20:35, bruce wrote: > But, what are decorators, why are decorators? who decided you needed them! Thinking about this a little wider than Python. Decorators are a standard software design pattern and were first(?) formally documented in the famous book known as the "Gang of Four" (GoF) but actually called "Design Patterns" published in 1995. But the GoF decorator pattern is quite different in the way it is implemented (using object inheritance) from Python's functional decorators. But the intent is the same - to add common functionality to another object. I think that's probably the earliest use of "decorator" in a computing context. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From bkd69ster at gmail.com Fri Jul 8 09:22:46 2016 From: bkd69ster at gmail.com (Bruce Dykes) Date: Fri, 8 Jul 2016 09:22:46 -0400 Subject: [Tutor] Counting and grouping dictionary values in Python 2.7 Message-ID: I'm compiling application logs from a bunch of servers, reading the log entries, parsing each log entry into a dictionary, and compiling all the log entries into a single list of dictionaries. At present, all I'm doing with it is writing the list of dictionaries to a .csv file, and to date, we've been able to get by doing some basic analysis by simply using grep and wc, but I need to do more with it now. Here's what the data structures look like: NY = ['BX01','BX02','BK01','MN01','SI01'] NJ = ['NW01','PT01','PT02'] CT = ['ST01','BP01','NH01'] sales = [ {'store':'store','date':'date','time':'time','state':'state',transid':'transid','product':'product','price':'price'}, {'store':'BX01','date':'8','time':'08:55','state':'NY',transid':'387','product':'soup','price':'2.59'}, {'store':'NW01','date':'8','time':'08:57','state':'NJ',transid':'24','product':'apples','price':'1.87'}, {'store':'BX01','date':'8','time':'08:56','state':'NY',transid':'387','product':'crackers','price':'3.44'}] The first group of list with the state abbreviations is there to add the state information to the compiled log, as it's not included in the application log. The first dictionary in the list, with the duplicated key names in the value field is there to provide a header line as the first line in the compiled .csv file. Now, what I need to do with this arbitrarily count and total the values in the dictionaries, ie the total amount and number of items for transaction id 387, or the total number of crackers sold in NJ stores. I think the collections library has the functions I need, but I haven't been able to grok the examples uses I've seen online. Likewise, I know I could build a lot of what I need using regex and lists, etc, but if Python 2.7 already has the blocks there to be used, well let's use the blocks then. Also, is there any particular advantage to pickling the list and having two files, one, the pickled file to be read as a data source, and the .csv file for portability/readability, as opposed to just a single .csv file that gets reparsed by the reporting script? Thanks in advance bkd From SylviaDeAguiar at alphapoint.co.jp Thu Jul 7 23:01:52 2016 From: SylviaDeAguiar at alphapoint.co.jp (Sylvia DeAguiar) Date: Thu, 8 Jul 2016 03:01:52 +0000 Subject: [Tutor] (no subject) Message-ID: http://point.gendelmangroup.com/Sylvia_DeAguiar Sylvia Deaguiar Sent from my iPhone From alan.gauld at yahoo.co.uk Fri Jul 8 13:33:24 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 8 Jul 2016 18:33:24 +0100 Subject: [Tutor] Counting and grouping dictionary values in Python 2.7 In-Reply-To: References: Message-ID: On 08/07/16 14:22, Bruce Dykes wrote: > with it is writing the list of dictionaries to a .csv file, and to date, > we've been able to get by doing some basic analysis by simply using grep > and wc, but I need to do more with it now. I'm a big fan of using the right tool for the job. If you got your data in CSV have you considered using a spreadsheet to read the data and analyse it? They have lots of formulae and stats functions built in and can do really cool graphs etc and can read csv files natively. Python might be a better tool if you want regular identical reports, say on a daily basis, but for ad-hoc analysis, or at least till you know exactly what you need, Excel or Calc are possibly better tools. > Also, is there any particular advantage to pickling the list and having two > files, one, the pickled file to be read as a data source, and the .csv file Probably not, the cost of converting the strings in the csv to objects is not that high unless you have huge volumes to manage(ie millions of records). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From beachkidken at gmail.com Sat Jul 9 10:22:16 2016 From: beachkidken at gmail.com (Ken G.) Date: Sat, 9 Jul 2016 10:22:16 -0400 Subject: [Tutor] Quote and double quotes opens up File Explorer in Windows 10 Message-ID: <57810898.5030400@gmail.com> Hi: In gradually moving over my Python programs (2.7.6) to Windows 10 and using Geany 1.27 to modify or write up a program there, it is noted that whenever I typed in a quote (') or double quote ("), Windows 10 File Explorer opens up. I end up closing it by typing ALT-F4 to resume typing as before. Is there a way to prevent the File Explorer from opening up whenever I use a quote or double quote? Is there another key(s) that does weird thing in Windows 10? Thanks. Ken From eryksun at gmail.com Sat Jul 9 13:02:12 2016 From: eryksun at gmail.com (eryk sun) Date: Sat, 9 Jul 2016 17:02:12 +0000 Subject: [Tutor] Quote and double quotes opens up File Explorer in Windows 10 In-Reply-To: <57810898.5030400@gmail.com> References: <57810898.5030400@gmail.com> Message-ID: On Sat, Jul 9, 2016 at 2:22 PM, Ken G. wrote: > Hi: In gradually moving over my Python programs (2.7.6) to Windows 10 and > using Geany 1.27 to modify or write up a program there, it is noted that > whenever I typed in a quote (') or double quote ("), Windows 10 File > Explorer opens up. I end up closing it by typing ALT-F4 to resume typing as > before. Is there a way to prevent the File Explorer from opening up whenever > I use a quote or double quote? Is there another key(s) that does weird thing > in Windows 10? Thanks. The single/double quote key isn't a standard hotkey in any version of Windows. That would be insane. If this is just happening in Geany, check its keybindings preferences. Otherwise, check that you're using the right keyboard layout and that you don't have any programs (or malware) that's registering a global hotkey. For example, here's a simple script that registers the single quote (US keyboard layout) as a global hotkey to open the desktop in Explorer: #! /usr/bin/python3 import os import ctypes from ctypes import wintypes user32 = ctypes.WinDLL('user32') WM_HOTKEY = 0x0312 MOD_NOREPEAT = 0x4000 VK_OEM_7 = 0xDE # US layout, single/double quote hotkey_id = 1 if user32.RegisterHotKey(None, hotkey_id, MOD_NOREPEAT, VK_OEM_7): print('Hotkey "\'" registered.') msg = wintypes.MSG() count = 0 while (count < 3 and user32.GetMessageW(ctypes.byref(msg), None, 0, 0)): if msg.message == WM_HOTKEY and msg.wParam == hotkey_id: count += 1 print('Hotkey received.') os.startfile('shell:Desktop') From B150612244 at outlook.com Sat Jul 9 22:23:23 2016 From: B150612244 at outlook.com (Chan Cheuk) Date: Sun, 10 Jul 2016 02:23:23 +0000 Subject: [Tutor] Some Python difficulties .. Message-ID: Dear all, I would like to know whether my designed Python program below for Linux route command could not run and show the output onto the textarea that I planned originally. The source code is: #!/usr/bin/python # lb => Label # btn => button # tb => textbox / entry # txtarea => multiline text # cb => Checkbox # rb => radiobutton # e.g. lb_ipaddress, btn_start, tb_output from Tkinter import * root = Tk() root.title("netcat(nc) GUI") option_a = IntVar() option_b = IntVar() option_c = IntVar() option_d = IntVar() def startfping(): print "Start nc button clicked!" fpingcommand = command_gen() print "\tnetcat command: " + nccommand commandresult = runcommand() print "\tCommand output: " + commandresult def command_gen(): print "Generate the netcat command details!" command = "netcat " print "option a: " + str(option_a.get()) if option_a.get(): command = command + "-a " print "option b: " + str(option_b.get()) if option_b.get(): command = command + "-c 1 " print "option c: " + str(option_c.get()) if option_c.get(): command = command + "-q " command = command + tb_ipaddress.get() print "option d: " + str(option_d.get()) if option_d.get(): command = "netcat -h" result = command return result def runcommand(): print "Run command and get return!" result = "Get it" return result lb_ipaddress = Label(root, text="IP Address(s):", fg="orange", justify=LEFT) lb_ipaddress.grid(row=0, column=0, padx=2, pady=5, sticky=W) tb_ipaddress = Entry(root, width=40, bd=5) tb_ipaddress.grid(row=0, column=1, columnspan=3, padx=5, pady=5) cb_option_a = Checkbutton(root, text = "Telnet details",variable=option_a, justify=LEFT) cb_option_a.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky=W) # option a => -a cb_option_b = Checkbutton(root, text="Port scanning", variable=option_b, justify=LEFT) cb_option_b.grid(row=1, column=2, columnspan=2, padx=5, pady=5, sticky=W) # option b => -c 1 cb_option_c = Checkbutton(root, text="Remote Shell/Backdoor", variable=option_c, justify=LEFT) cb_option_c.grid(row=2, column=0, columnspan=2, padx=5, pady=5, sticky=W) # option c => -q cb_option_d = Checkbutton(root, text="Reverse Shells", variable=option_d, justify=LEFT) cb_option_d.grid(row=2, column=2, columnspan=2, padx=5 , pady=5, sticky=W) # option d => -h (but exclude all other options and IP address) btn_run = Button(root, width = 10, text="Run!",justify=RIGHT, command=startfping) btn_run.grid(row=3, column=3, padx=5, pady=5, stick=E) lb_commandoutput = Label(root, text="Command Output:", fg="red", justify=LEFT) lb_commandoutput.grid(row=4, column=0, padx=2, pady=0) txtarea_output = Text(root, height=10, width=60) txtarea_output.grid(row=5, column=0, columnspan=4, padx=10, pady=10) root.mainloop() Thank you for your kindly attention if you tell me how to fix it :'( From __peter__ at web.de Sun Jul 10 05:00:40 2016 From: __peter__ at web.de (Peter Otten) Date: Sun, 10 Jul 2016 11:00:40 +0200 Subject: [Tutor] Some Python difficulties .. References: Message-ID: Chan Cheuk wrote: > I would like to know whether my designed Python program below for Linux > route command could not run and show the output onto the textarea that I > planned originally. When you run the script and click on the Run! button, what do you see? Read the traceback carefully and come back for more hints if you cannot fix the problem yourself. Look at the subprocess module https://docs.python.org/2.7/library/subprocess.html for ways to run an external command and capture its output in a string variable. Once the script works as desired except that it prints to the command line via print statements rather than into the Text widget search your tkinter documentation for a way to insert() text into the widget and replace the print statements with these method calls. > The source code is: > > > #!/usr/bin/python > # lb => Label > # btn => button > # tb => textbox / entry > # txtarea => multiline text > # cb => Checkbox > # rb => radiobutton > # e.g. lb_ipaddress, btn_start, tb_output > > from Tkinter import * > > root = Tk() > root.title("netcat(nc) GUI") > > option_a = IntVar() > option_b = IntVar() > option_c = IntVar() > option_d = IntVar() > > def startfping(): > print "Start nc button clicked!" > fpingcommand = command_gen() > print "\tnetcat command: " + nccommand > commandresult = runcommand() > print "\tCommand output: " + commandresult > > def command_gen(): > print "Generate the netcat command details!" > command = "netcat " > > print "option a: " + str(option_a.get()) > if option_a.get(): > command = command + "-a " > > print "option b: " + str(option_b.get()) > if option_b.get(): > command = command + "-c 1 " > > print "option c: " + str(option_c.get()) > if option_c.get(): > command = command + "-q " > > command = command + tb_ipaddress.get() > > print "option d: " + str(option_d.get()) > if option_d.get(): > command = "netcat -h" > > result = command > return result > > def runcommand(): > print "Run command and get return!" > result = "Get it" > return result > > lb_ipaddress = Label(root, text="IP Address(s):", fg="orange", > justify=LEFT) lb_ipaddress.grid(row=0, column=0, padx=2, pady=5, sticky=W) > > tb_ipaddress = Entry(root, width=40, bd=5) > tb_ipaddress.grid(row=0, column=1, columnspan=3, padx=5, pady=5) > > cb_option_a = Checkbutton(root, text = "Telnet details",variable=option_a, > justify=LEFT) cb_option_a.grid(row=1, column=0, columnspan=2, padx=5, > pady=5, sticky=W) > # option a => -a > > cb_option_b = Checkbutton(root, text="Port scanning", variable=option_b, > justify=LEFT) cb_option_b.grid(row=1, column=2, columnspan=2, padx=5, > pady=5, sticky=W) > # option b => -c 1 > > cb_option_c = Checkbutton(root, text="Remote Shell/Backdoor", > variable=option_c, justify=LEFT) cb_option_c.grid(row=2, column=0, > columnspan=2, padx=5, pady=5, sticky=W) > # option c => -q > > cb_option_d = Checkbutton(root, text="Reverse Shells", variable=option_d, > justify=LEFT) cb_option_d.grid(row=2, column=2, columnspan=2, padx=5 , > pady=5, sticky=W) > # option d => -h (but exclude all other options and IP address) > > btn_run = Button(root, width = 10, text="Run!",justify=RIGHT, > command=startfping) btn_run.grid(row=3, column=3, padx=5, pady=5, stick=E) > > lb_commandoutput = Label(root, text="Command Output:", fg="red", > justify=LEFT) lb_commandoutput.grid(row=4, column=0, padx=2, pady=0) > > txtarea_output = Text(root, height=10, width=60) > txtarea_output.grid(row=5, column=0, columnspan=4, padx=10, pady=10) > > root.mainloop() > > > Thank you for your kindly attention if you tell me how to fix it :'( > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Sun Jul 10 05:16:03 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 10 Jul 2016 19:16:03 +1000 Subject: [Tutor] Some Python difficulties .. In-Reply-To: References: Message-ID: <20160710091556.GF27919@ando.pearwood.info> On Sun, Jul 10, 2016 at 02:23:23AM +0000, Chan Cheuk wrote: > Dear all, > > > I would like to know whether my designed Python program below for > Linux route command could not run and show the output onto the > textarea that I planned originally. Did you try running it? What happened? If you run your code from a shell, so you can watch any error messages that are generated, you will see this error whenever you click the Run button: Exception in Tkinter callback Traceback (most recent call last): File "/usr/local/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__ return self.func(*args) File "netcat.py", line 14, in startfping print "\tnetcat command: " + nccommand NameError: global name 'nccommand' is not defined > def startfping(): > print "Start nc button clicked!" > fpingcommand = command_gen() > print "\tnetcat command: " + nccommand Where is nccommand defined? > commandresult = runcommand() How does runcommand() know what command to run? -- Steve From nitinchandra1 at gmail.com Mon Jul 11 05:18:40 2016 From: nitinchandra1 at gmail.com (nitin chandra) Date: Mon, 11 Jul 2016 14:48:40 +0530 Subject: [Tutor] Python WATable & DB Message-ID: Hi All, Any body got experience in WATable + passing data from DB to JS / json ... and if it is stretching it a bit .. has done it with python. Also, how do I pass link of employee images/photos. I just posted the part of JS , which I believe is concerned with data to be displayed in the table. Really appreciate ... so close and .... still some way to go to insert DB. Thanks Nitin ============================== ... """ The above style / way of coding works. Even on my laptop where the code is in /var/www/ Now I have taken a VPS, using command line, I installed apache2.4, python 2.7, but I am not able to use the same code with triple quotes (""") to open and close the code block. I am forced to use #!/usr/bin/env python import cgi import psycopg2 print "Content-type:text/html\r\n\r\n" print '' print '....' print '...' print '' Do I need to do some thing to apache config such that I can use Triple quote to embed. Also, if I ReUse some of the previous code, it give 500 error. Any solutions ? Thanks Nitin From alan.gauld at yahoo.co.uk Tue Jul 19 15:16:22 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 19 Jul 2016 20:16:22 +0100 Subject: [Tutor] python cgi single double quotes In-Reply-To: References: Message-ID: On 19/07/16 19:43, nitin chandra wrote: > Now I have taken a VPS, using command line, I installed apache2.4, > python 2.7, but I am not able to use the same code with triple quotes > (""") to open and close the code block. > > I am forced to use > > print "Content-type:text/html\r\n\r\n" > print '' > print '....' > Do I need to do some thing to apache config such that I can use Triple > quote to embed. Triple quotes should work anywhere Python works. But first I'd check your python environment. Which interpreter is actually running for example? Try import sys ... print "

+ "sys.version + "

" ... The 500 error sounds like an apache setup or maybe permissions issue. Are your files readable/executable by Apache? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From zuhair72h at yahoo.com Tue Jul 19 18:14:59 2016 From: zuhair72h at yahoo.com (zuhair ali) Date: Tue, 19 Jul 2016 22:14:59 +0000 (UTC) Subject: [Tutor] pyrouge References: <1033420412.2063002.1468966499108.JavaMail.yahoo.ref@mail.yahoo.com> Message-ID: <1033420412.2063002.1468966499108.JavaMail.yahoo@mail.yahoo.com> Hatd I sirI used pyrouge?package for evaluation rouge package and ?I have one problem that i don't know how to create settings.ini file and what i put in this file. This file found in Rouge155().py please can you help me. From alan.gauld at yahoo.co.uk Tue Jul 19 19:24:26 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 20 Jul 2016 00:24:26 +0100 Subject: [Tutor] pyrouge In-Reply-To: <1033420412.2063002.1468966499108.JavaMail.yahoo@mail.yahoo.com> References: <1033420412.2063002.1468966499108.JavaMail.yahoo.ref@mail.yahoo.com> <1033420412.2063002.1468966499108.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 19/07/16 23:14, zuhair ali via Tutor wrote: > I used pyrouge package for evaluation rouge package > and I have one problem that i don't know how to > create settings.ini file and what i put in this file. This list is for the Python language and its standard library so rouge() is a bit off topic. Whether you get any help will depend on whether anyone here has ever used it. You will likely get more help on the pyrouge support forum if such exists. A quick look at the web site suggests not. Failing that you could try the main python list or even emailing the pyrouge author. Although of the 3 contributors only Federico Barrios seems to have an email address! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Tue Jul 19 21:53:07 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 20 Jul 2016 11:53:07 +1000 Subject: [Tutor] pyrouge In-Reply-To: <1033420412.2063002.1468966499108.JavaMail.yahoo@mail.yahoo.com> References: <1033420412.2063002.1468966499108.JavaMail.yahoo.ref@mail.yahoo.com> <1033420412.2063002.1468966499108.JavaMail.yahoo@mail.yahoo.com> Message-ID: <20160720015306.GA27919@ando.pearwood.info> On Tue, Jul 19, 2016 at 10:14:59PM +0000, zuhair ali via Tutor wrote: > Hatd I sirI used pyrouge?package for evaluation rouge package and ?I > have one problem that i don't know how to create settings.ini file and > what i put in this file. This file found in Rouge155().py please can > you help me. I am sorry, I don't know pyrouge. Nut have you tried these? https://www.google.com.au/search?q=pyrouge+settings.ini https://duckduckgo.com/?q=pyrouge%20settings.ini You could try just creating an empty file "settings.ini" and putting it where pyrouge expects to find it. -- Steve From ben+python at benfinney.id.au Wed Jul 20 03:48:23 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 20 Jul 2016 17:48:23 +1000 Subject: [Tutor] Writing decorators? References: Message-ID: <858twwsqbc.fsf@benfinney.id.au> Michael Welle writes: > Somewhere in this thread (or the one talking about decorators after > this thread) it was said that a decorator 'changes a function'. I not > a native English speaker, so it could just be a language problem. But > to me it seems the function is replaced, not changed? That's correct. Don't be surprised, though, if the concept ?replace the object referenced by ?foo? with a different object and discard the prior object at that reference? is glossed to ?change ?foo?? in casual usage :-) -- \ ?Hey Homer! You're late for English!? ?Pff! English, who needs | `\ that? I'm never going to England!? ?Barney & Homer, _The | _o__) Simpsons_ | Ben Finney From Joaquin.Alzola at lebara.com Tue Jul 19 09:36:39 2016 From: Joaquin.Alzola at lebara.com (Joaquin Alzola) Date: Tue, 19 Jul 2016 13:36:39 +0000 Subject: [Tutor] Need Your help In-Reply-To: References: Message-ID: >I'm creating a mobile application [ http://e-aadhaarcard.in ] and I'm using python for a desktop server. However, I don't have access to a static IP on the desktop, but do have a website. Is it possible to connect from mobile http website -> desktop server >and back? Try using a LAN so all your devices have a 192.168.X.X address. You can set it in your PC and Mobile manually or through DHCP. You will be communicating through IP base between your desktop and mobile. That way you can test your application. Also you can ask your IT department to assign a permanent IP if you want to test real live. This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt. From nitinchandra1 at gmail.com Wed Jul 20 04:23:12 2016 From: nitinchandra1 at gmail.com (nitin chandra) Date: Wed, 20 Jul 2016 13:53:12 +0530 Subject: [Tutor] python cgi single double quotes In-Reply-To: References: Message-ID: Hi Alan, vimal at Ubuntu-1404-trusty-64-minimal:~$ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print sys.version 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] >>> Should I test the above from within html code too ? Also, for testing and configuration purpose, I have set 755 / 777 permissions to dir / files respectively. Thank you, Nitin Chandra On 20 July 2016 at 00:46, Alan Gauld via Tutor wrote: > On 19/07/16 19:43, nitin chandra wrote: > >> Now I have taken a VPS, using command line, I installed apache2.4, >> python 2.7, but I am not able to use the same code with triple quotes >> (""") to open and close the code block. >> >> I am forced to use >> >> print "Content-type:text/html\r\n\r\n" >> print '' >> print '....' > >> Do I need to do some thing to apache config such that I can use Triple >> quote to embed. > > Triple quotes should work anywhere Python works. > But first I'd check your python environment. > Which interpreter is actually running for example? > > Try > > import sys > ... > print "

+ "sys.version + "

" > ... > > The 500 error sounds like an apache setup or maybe permissions > issue. Are your files readable/executable by Apache? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at yahoo.co.uk Wed Jul 20 04:27:42 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 20 Jul 2016 09:27:42 +0100 Subject: [Tutor] Writing decorators? In-Reply-To: References: <858twwsqbc.fsf@benfinney.id.au> Message-ID: On 20/07/16 09:08, Michael Welle wrote: >> Don't be surprised, though, if the concept ?replace the object >> referenced by ?foo? with a different object and discard the prior object >> at that reference? is glossed to ?change ?foo?? in casual usage :-) > I'm a bit surprised to see that kind of sloppy use of language on a > Python list ;). But you are right, human language is imprecise. Its not really sloppy. In English change means alter and the function referenced by foo is altered by a decorator. For example we could reasonably say that foo = lambda x: x+1 creates a function called foo And we can therefore also say that foo = lambda x: x+2 changes the function foo. Decorators change the function in a similar way. It depends on whether you are referring to the function name or the function object. So the use of change is not necessarily sloppy but it could be imprecise. :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Jul 20 04:44:10 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 20 Jul 2016 09:44:10 +0100 Subject: [Tutor] python cgi single double quotes In-Reply-To: References: Message-ID: On 20/07/16 09:23, nitin chandra wrote: > vimal at Ubuntu-1404-trusty-64-minimal:~$ python > Python 2.7.6 (default, Jun 22 2015, 17:58:13) > [GCC 4.8.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> print sys.version > 2.7.6 (default, Jun 22 2015, 17:58:13) > [GCC 4.8.2] >>>> > > Should I test the above from within html code too ? Yes, that's what I meant to imply by putting it inside

markers: >> import sys >> ... >> print "

+ "sys.version + "

" >> ... The idea is to make sure that the web server is running the same version of Python that you are. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From nitinchandra1 at gmail.com Wed Jul 20 05:09:25 2016 From: nitinchandra1 at gmail.com (nitin chandra) Date: Wed, 20 Jul 2016 14:39:25 +0530 Subject: [Tutor] python cgi single double quotes In-Reply-To: References: Message-ID: On inserting the line ... print "

+ "sys.version + "

" required slight correction print "

" + sys.version + "

" and the following script and its output are below :- ---------------------------------------- #!/usr/bin/env python import sys import cgi import psycopg2 print "Content-type:text/html\r\n\r\n" print '' print '' print 'Hello Word - First CGI Program' print '' print '' print '

Hello Word! This is my first CGI program

' print "

"+ sys.version + "

" print 'First name:
' print '' print '' --------------------------------------------------- Hello Word! This is my first CGI program 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] First name: On 20 July 2016 at 14:14, Alan Gauld via Tutor wrote: > On 20/07/16 09:23, nitin chandra wrote: > >> vimal at Ubuntu-1404-trusty-64-minimal:~$ python >> Python 2.7.6 (default, Jun 22 2015, 17:58:13) >> [GCC 4.8.2] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import sys >>>>> print sys.version >> 2.7.6 (default, Jun 22 2015, 17:58:13) >> [GCC 4.8.2] >>>>> >> >> Should I test the above from within html code too ? > > Yes, that's what I meant to imply by putting it > inside

markers: > >>> import sys >>> ... >>> print "

+ "sys.version + "

" >>> ... > > The idea is to make sure that the web server is > running the same version of Python that you are. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From __peter__ at web.de Wed Jul 20 05:45:04 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 20 Jul 2016 11:45:04 +0200 Subject: [Tutor] python cgi single double quotes References: Message-ID: nitin chandra wrote: > On inserting the line ... > > print "

+ "sys.version + "

" > > required slight correction > > print "

" + sys.version + "

" > > and the following script and its output are below :- > ---------------------------------------- > #!/usr/bin/env python > > import sys > import cgi > import psycopg2 > > print "Content-type:text/html\r\n\r\n" > print '' > print '' > print 'Hello Word - First CGI Program' > print '' > print '' > print '

Hello Word! This is my first CGI program

' > print "

"+ sys.version + "

" > print 'First name:
' > print '' > print '' > > --------------------------------------------------- > > Hello Word! This is my first CGI program > > 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] > > First name: If you got that from your server like in the session below... $ cat first.py #!/usr/bin/env python import sys import cgi import psycopg2 print "Content-type:text/html\r\n\r\n" print '' print '' print 'Hello Word - First CGI Program' print '' print '' print '

Hello Word! This is my first CGI program

' print "

"+ sys.version + "

" print 'First name:
' print '' print '' $ curl http://myhost/somewhere/first.py Hello Word - First CGI Program

Hello Word! This is my first CGI program

2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]

First name:
... the following should also work: $ cat second.py #!/usr/bin/env python import sys import cgi import psycopg2 print """Content-type:text/html\r\n\r\n Hello Word - First CGI Program

Hello Word! This is my first CGI program

{version}

First name:
""".format(version=sys.version) $ curl http://myhost/somewhere/second.py Hello Word - First CGI Program

Hello Word! This is my first CGI program

2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]

First name:
If it does you can start looking for the actual problem. I don't expect it to have anything to do with your choice of quoting characters, as long as you write legal Python 2. From nitinchandra1 at gmail.com Wed Jul 20 06:16:54 2016 From: nitinchandra1 at gmail.com (nitin chandra) Date: Wed, 20 Jul 2016 15:46:54 +0530 Subject: [Tutor] python cgi single double quotes In-Reply-To: References: Message-ID: Ran both the method #!/usr/bin/env python import cgi import psycopg2 import sys print """Content-type:text/html\r\n\r\n""" print """ Hello Word - First CGI Program

Hello Word! This is my first CGI program

{version}

First name:
""".format(version=sys.version) and its output (below) nitin at nitin-Ideapad-Z570:~$ curl http://passtms.in/vimal.cgi Hello Word - First CGI Program

Hello Word! This is my first CGI program

2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]

First name:
nitin at nitin-Ideapad-Z570:~$ In the first instance also it the same : -------------------------------------------------------------- #!/usr/bin/env python import sys import cgi import psycopg2 print "Content-type:text/html\r\n\r\n" print '' print '' print 'Hello Word - First CGI Program' print '' print '' print '

Hello Word! This is my first CGI program

' print "

"+ sys.version + "

" print 'First name:
' print '' print '' output (below):- nitin at nitin-Ideapad-Z570:~$ curl http://passtms.in/vimal.py Hello Word - First CGI Program

Hello Word! This is my first CGI program

2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]

First name:
On 20 July 2016 at 15:15, Peter Otten <__peter__ at web.de> wrote: > nitin chandra wrote: > >> On inserting the line ... >> >> print "

+ "sys.version + "

" >> >> required slight correction >> >> print "

" + sys.version + "

" >> >> and the following script and its output are below :- >> ---------------------------------------- >> #!/usr/bin/env python >> >> import sys >> import cgi >> import psycopg2 >> >> print "Content-type:text/html\r\n\r\n" >> print '' >> print '' >> print 'Hello Word - First CGI Program' >> print '' >> print '' >> print '

Hello Word! This is my first CGI program

' >> print "

"+ sys.version + "

" >> print 'First name:
' >> print '' >> print '' >> >> --------------------------------------------------- >> >> Hello Word! This is my first CGI program >> >> 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] >> >> First name: > > If you got that from your server like in the session below... > > $ cat first.py > #!/usr/bin/env python > > import sys > import cgi > import psycopg2 > > print "Content-type:text/html\r\n\r\n" > print '' > print '' > print 'Hello Word - First CGI Program' > print '' > print '' > print '

Hello Word! This is my first CGI program

' > print "

"+ sys.version + "

" > print 'First name:
' > print '' > print '' > $ curl http://myhost/somewhere/first.py > > > > Hello Word - First CGI Program > > >

Hello Word! This is my first CGI program

>

2.7.6 (default, Jun 22 2015, 17:58:13) > [GCC 4.8.2]

> First name:
> > > > ... the following should also work: > > $ cat second.py > #!/usr/bin/env python > > import sys > import cgi > import psycopg2 > > print """Content-type:text/html\r\n\r\n > > > Hello Word - First CGI Program > > >

Hello Word! This is my first CGI program

>

{version}

> First name:
> > > """.format(version=sys.version) > $ curl http://myhost/somewhere/second.py > > > > Hello Word - First CGI Program > > >

Hello Word! This is my first CGI program

>

2.7.6 (default, Jun 22 2015, 17:58:13) > [GCC 4.8.2]

> First name:
> > > > If it does you can start looking for the actual problem. I don't expect it > to have anything to do with your choice of quoting characters, as long as > you write legal Python 2. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From ben+python at benfinney.id.au Wed Jul 20 07:47:53 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 20 Jul 2016 21:47:53 +1000 Subject: [Tutor] Writing decorators? References: <858twwsqbc.fsf@benfinney.id.au> <3ur36dxrco.ln2@news.c0t0d0s0.de> Message-ID: <85zipcr0nq.fsf@benfinney.id.au> Michael Welle writes: > so 'the function has changed' really means 'the reference has > changed'? Strange. Humans think in strage ways :-) Really, though, it shouldn't be too surprising. The *perception* is that the reference (a name, or an index in a sequence, or whatever) remains unchanged; at least, you still address the reference exactly the same way. ?foo? in the code remains ?foo?. But what you get from that reference is different. So, because what I get when I refer to ?foo? is different after some operation than what it was prior to that operation, it is natural to speak loosely about ?this operation has changed foo?. > If you hear 'function foo', do you think of the reference 'foo' or do > you think of the referenced thing, the function object? It might be > context dependent, but usually I think about the latter. It is normal for us to think of them as one, because in Python the *only* way to get an object is through some specific reference. Our natural language doesn't easily handle the separable but linked concepts. > But it might just be a language problem. Which is another way of saying thta it's a human thinking problem. Try not to have overly strict expectations of how people think about it, while also striving to express ourselves precisely. -- \ ?Dvorak users of the world flgkd!? ?Kirsten Chevalier, | `\ rec.humor.oracle.d | _o__) | Ben Finney From __peter__ at web.de Wed Jul 20 07:54:40 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 20 Jul 2016 13:54:40 +0200 Subject: [Tutor] python cgi single double quotes References: Message-ID: nitin chandra wrote: > Ran both the method So everything seems to be working as expected. When you go back to your original script you can enable tracebacks rendered as html with #!/usr/bin/env python import cgitb cgitb.enable() ... # your code Provided there are no syntax errors in the script this should simplify detecting any exceptions the code may raise. If there is a traceback that doesn't make sense to you post it here to see if we can help. From steve at pearwood.info Wed Jul 20 08:03:57 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 20 Jul 2016 22:03:57 +1000 Subject: [Tutor] Writing decorators? In-Reply-To: References: Message-ID: <20160720120356.GC27919@ando.pearwood.info> On Wed, Jul 20, 2016 at 09:33:19AM +0200, Michael Welle wrote: > Somewhere in this thread (or the one talking about decorators after this > thread) it was said that a decorator 'changes a function'. I not a > native English speaker, so it could just be a language problem. But to > me it seems the function is replaced, not changed? It might have been me that used the term "changes a function". A decorator can do anything. It can replace the function with a completely new one, ignoring the original function. It can wrap the original function in a closure, returning the wrapper. (The wrapper then calls the original function.) It can turn the function into a class, or a class into a function, or return something altogether different. It can modify the function and return it, or cause some side-effect and then return the original function with no changes made. For example, here is a decorator that ensures that the function has a doc string, and inserts one if it doesn't: def ensure_docstring(func): if func.__doc__ is None: func.__doc__ = "Please see the Fine Manual for '%s'" % func.__name__ return func @ensure_docstring def myfunc(args): pass In this case, the function object is actually changed, not replaced. The most common form of decorator wraps the original function inside a new function, as a closure, and returns the wrapper: def decorate(func): @functools.wraps(func) def inner(*args): print("inside the wrapper") result = func(*args) print("original returns %r" % result) return result # can modify the result return inner Even though the decorator is returning a new function, the original is still hidden deep inside that "inner" function, as part of the closure, so in a sense, it is just a change to that original: it is *wrapped* in another function, which does some pre-processing or post-processing, but the original still does most of the work. Does that help explain matters? -- Steve From nitinchandra1 at gmail.com Wed Jul 20 08:53:18 2016 From: nitinchandra1 at gmail.com (nitin chandra) Date: Wed, 20 Jul 2016 18:23:18 +0530 Subject: [Tutor] python cgi single double quotes In-Reply-To: References: Message-ID: Me a little embarrassed :P ... but now when I retyped the code ... it seems to be working.... Alan, Peter .. .Thank you. On 20 July 2016 at 17:24, Peter Otten <__peter__ at web.de> wrote: > nitin chandra wrote: > >> Ran both the method > > So everything seems to be working as expected. When you go back to your > original script you can enable tracebacks rendered as html with > > #!/usr/bin/env python > import cgitb > cgitb.enable() > > ... # your code > > Provided there are no syntax errors in the script this should simplify > detecting any exceptions the code may raise. If there is a traceback that > doesn't make sense to you post it here to see if we can help. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Wed Jul 20 09:00:32 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 20 Jul 2016 23:00:32 +1000 Subject: [Tutor] strange behavior of matrix**matrix In-Reply-To: References: <6ac21b06-4fb0-88d5-5cfb-166cf79f2642@toya.net.pl> <20160717152300.GT27919@ando.pearwood.info> Message-ID: <20160720130031.GD27919@ando.pearwood.info> On Wed, Jul 20, 2016 at 10:27:50AM +0200, AB wrote: > Hello > > W dniu 2016-07-17 o 17:23, Steven D'Aprano pisze: > >[...] > >What result did you expect? 2**-1 as an int32 cannot be 0.5, as that's a > >float. > > I expected 0.5: as 2^(-1) is in fact 1/2, and as in Python 3 division of > two integers 1/2 produces float 0.5, I naturally expected the case of > arrays to be consistent with this behavior. Ah, but the exponentiation operator ** is not the division operator / and is not guaranteed to give the same results. It looks to me that numpy has array[ints]/int coerce to array[floats], but array[ints]**int remains an array[ints]. In that case, they have to choose between 2**-1 rounds down to 0 or rounds up to 1, and they chose rounding down. Would I make the same decision? Probably not. > >I'm not really sure about the rules that numpy uses for coercing from > >one type to another, but I'm not surprised by this result. I don't know > >if it is documented anywhere, but it seems like the sort of thing numpy > >would do. > > I'm only learning Python, so the behavior of version 3 is natural to me. That's why it was changed :-) > >Here's another similar example: > > > >py> np.array([0])**-1 > >__main__:1: RuntimeWarning: divide by zero encountered in power > >__main__:1: RuntimeWarning: invalid value encountered in power > >array([-2147483648]) > > In my eye it's not similar - 1/0 should always produce an error, so the > behavior is exactly as expected. The point is that the numpy functions seem to me to be designed to be as fast as possible, not as correct as possible. There's no integer value to represent INFINITY, like for floats, and for some reason the numpy people didn't want to halt the calculation with an error, so they have to return *something*, and it has to be a 32-bit signed integer: -2147483648 is 32 "1" bits (including the sign), so that makes a good error value, at least if you think like a C programmer. [...] > I thought that this may be a 'sin of omission', to be corrected in some > future versions of numpy/scipy. If you report it as a bug on the numpy bug tracker, they will hopefully either explain why they think its not a bug, or fix it. -- Steve From alan.gauld at yahoo.co.uk Wed Jul 20 13:09:42 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 20 Jul 2016 18:09:42 +0100 Subject: [Tutor] Writing decorators? In-Reply-To: <31b46dxqsg.ln2@news.c0t0d0s0.de> References: <20160720120356.GC27919@ando.pearwood.info> <31b46dxqsg.ln2@news.c0t0d0s0.de> Message-ID: On 20/07/16 14:30, Michael Welle wrote: > Now it gets interesting ;). Can you give me a hint on how to modify the > code of the function in a decorator or even give a small example, > please? Would I take the route with the bytecode attribute __code__ > (IIRC)? Or use the inspect module? Steven changed the function object by modifying the __doc__ attribute. It is probably possible to modify the __code__ too but I'd strongly recommend that you don't. It's very likely to result in something so "clever"/complex that it will never be maintainable, and maintainability beats nearly everything else in programming priorities. If you cannot do what you want by wrapping the original function you should probably just rewrite it to do what you want. Or, if you own the code, refactor it into chunks and combine the chunks into a new high level function. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Wed Jul 20 14:54:33 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 21 Jul 2016 04:54:33 +1000 Subject: [Tutor] Writing decorators? In-Reply-To: <31b46dxqsg.ln2@news.c0t0d0s0.de> References: <20160720120356.GC27919@ando.pearwood.info> <31b46dxqsg.ln2@news.c0t0d0s0.de> Message-ID: <20160720185433.GE27919@ando.pearwood.info> On Wed, Jul 20, 2016 at 03:30:43PM +0200, Michael Welle wrote: > > It [a decorator] > > can modify the function and return it, > > Now it gets interesting ;). Can you give me a hint on how to modify the > code of the function in a decorator or even give a small example, > please? Would I take the route with the bytecode attribute __code__ > (IIRC)? Or use the inspect module? The inspect module is not really designed for changing objects, only for inspecting them. (Reading, not writing.) Function code objects are immutable, so you cannot change them in place, only replace them with a new code object: py> def f(): ... print("f") ... py> def g(): ... print("g") ... py> f() f py> f.__code__ = g.__code__ py> f() g The code object itself is very complex, and badly documented: py> help(f.__code__) Help on code object: class code(object) | code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring, | constants, names, varnames, filename, name, firstlineno, | lnotab[, freevars[, cellvars]]) | | Create a code object. Not for the faint of heart. so in practice the way to create them is by actually defining a function, then extracting its __code__ object. But if you're going to do that, why not just use the function? There are a couple of projects designed to let you manipulate the byte-code of functions, but because the byte-code format is not part of the public Python API, it tends to change from version to version. If you use the wrong byte-code, you can crash the interpeter and cause a segmentation fault or core dump. However, there is some talk about creating a interface to modify a function's abstract syntax tree. At the moment consider that to be just talk, but its more likely than a supported interface to edit byte-code. But for those brave, or silly, enough, here are some resources for editing byte-code to get you started: http://www.voidspace.org.uk/python/articles/code_blocks.shtml https://wiki.python.org/moin/ByteplayDoc There are ways to modify functions apart from changing their code. For example, you can change argument defaults, add attributes to the function object, change the global namespace that the function works with. I have an experimental project that modifies functions so that instead of searching for variables in this order: locals nonlocals globals builtins it uses: locals nonlocals custom namespace set by the user globals builtins (Technically, I don't "modify" the function, since some parts of the function are immutable and cannot be changed. Instead I replace it with a new function, copied from the original but with a slight modification.) If you are interested in that, see the discussion that starts here: https://mail.python.org/pipermail/python-list/2016-July/711177.html The original version of the code I gave uses a metaclass; the version I have now also supports being called as a decorator. -- Steve From alan.gauld at yahoo.co.uk Wed Jul 20 19:11:24 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 21 Jul 2016 00:11:24 +0100 Subject: [Tutor] python programmin problem In-Reply-To: <20160720.141109.7713.1@webmail09.dca.untd.com> References: <20160720.141109.7713.1@webmail09.dca.untd.com> Message-ID: <5790051C.6050908@yahoo.co.uk> On 20/07/16 22:11, monikajg at netzero.net wrote: > ... if not in python, then in pseudo code. The first question to ask is can you do it without a computer? In other words given input [1,7,2,3,5,4,6] Can you first of all produce a list of all valid runs? [1,2,3,5,6] and [1,2,3,4,6] both have length 5 I also see shorter runs: [7] and [4,6] for example. Can you manually create a list of all valid runs? Once you can do that can you write a program to generate that as a list of lists in Python? If so then the answer to your question is a matter of finding the length of the longest valid run which should be fairly easy. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Jul 20 20:26:59 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 21 Jul 2016 01:26:59 +0100 Subject: [Tutor] python programmin problem In-Reply-To: <20160720.161449.5694.1@webmail10.dca.untd.com> References: <20160720.161449.5694.1@webmail10.dca.untd.com> Message-ID: <579016D3.1020808@yahoo.co.uk> On 21/07/16 00:14, monikajg at netzero.net wrote: > IM not able to figure out algorithm to find the runs. > Here is the code I have: OK, Forget about code for now. just focus on what is being asked. > > The first question to ask is can you do it without a computer? > > In other words given > > > > input [1,7,2,3,5,4,6] > > > > Can you first of all produce a list of all valid runs? Lets try it manually. Start with 1 run = [] 1 > run[-1] so add it to the run -> [1] 1 is followed by 7 which >run[-1] so add it to the run -> [1,7] 7 is followed by 2 which [1] 2 is now greater than run[-1] so add it to the run -> [1,2] 2 is followed by 3 which is > run[-1] so add it to the run -> [1,2,3] 3 is followed by 5 which is > run[-1] so add it to the run -> [1,2,3,5] 5 is followed by 4 which is run[-1] so add it to the run -> [1,2,3,4] 4 is followed by 6 which is > run[-1] so add it to the run -> [1,2,3,4,6] 6 is not followed by anything, run complete. Can you see an algorithm there that you can code? Its not quite complete because it never catches the [1,2,3,5,6] case but its a start. And there are probably more efficient algorithms too, but we are interested in easy to code here not speed. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From monikajg at netzero.net Wed Jul 20 17:11:09 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Wed, 20 Jul 2016 21:11:09 GMT Subject: [Tutor] python programmin problem Message-ID: <20160720.141109.7713.1@webmail09.dca.untd.com> Hi: Can somebody please provide answer to following python programming question? I have spent days on it and cannot come up with any code that would make any sense for it so I cannot provide you any code. But I would appreciate the answer very much, if not in python, then in pseudo code. Thank you very much Monika Here is the problem: Given a list of integers, return the progress of the test The progress is defined as the length of the longest run of strictly increasing scores "with gaps allowed". That is the length of the longest group of numbers such that each number in that block is strictly larger than the previous number, and the group can be formed by choosing some subset of values in the order they appear in the original list. All values are integers. input [1,7,2,3,5,4,6] returns 5 [1,2,3,5,6] and [1,2,3,4,6] both have length 5 and are longer than any other runs Returning 7 is incorrect for [1,2,3,4,5,6,7] as it changes the ordering of the original sequence. Input [1,2,3,4] the run [1,2,3,4] is the entire test and has lenght 4. returns 4 Input [4, 3, 2, 1] returns 1 each result is a run of 1. so we return 1 Input [1,2,0,4,5] return 5 longest run [1,2,4,5] has lenght 4 ____________________________________________________________ Affordable Wireless Plans Set up is easy. Get online in minutes. Starting at only $9.95 per month! www.netzero.net?refcd=nzmem0216 From monikajg at netzero.net Wed Jul 20 19:14:49 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Wed, 20 Jul 2016 23:14:49 GMT Subject: [Tutor] python programmin problem Message-ID: <20160720.161449.5694.1@webmail10.dca.untd.com> IM not able to figure out algorithm to find the runs. Here is the code I have: def ProgressCalc(items): counts = [items[0]] for i in range(1, len(items)-1): print "for loop", items[i], items[i + 1] if counts[- 1] < items[i]: counts += [items[i]] print "inside", items[i], items[i - 1], counts print counts counts = [items[0]] for i in range(1, len(items) - 1): print "for loop", items[i], items[i + 1] if counts[- 1] <= items[i] and items[i] < items[i + 1]: counts += [items[i]] print "inside", items[i], items[i - 1], counts elif counts[- 1] <= items[i] and items[i] > items[i + 1]: counts += [items[i]] i += 2 print counts ProgressCalc(items) ---------- Original Message ---------- From: Alan Gauld To: "monikajg at netzero.net" Cc: tutor at python.org Subject: Re: python programmin problem Date: Thu, 21 Jul 2016 00:11:24 +0100 On 20/07/16 22:11, monikajg at netzero.net wrote: > ... if not in python, then in pseudo code. The first question to ask is can you do it without a computer? In other words given input [1,7,2,3,5,4,6] Can you first of all produce a list of all valid runs? [1,2,3,5,6] and [1,2,3,4,6] both have length 5 I also see shorter runs: [7] and [4,6] for example. Can you manually create a list of all valid runs? Once you can do that can you write a program to generate that as a list of lists in Python? If so then the answer to your question is a matter of finding the length of the longest valid run which should be fairly easy. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ____________________________________________________________ Affordable Wireless Plans Set up is easy. Get online in minutes. Starting at only $9.95 per month! www.netzero.net?refcd=nzmem0216 From dyoo at hashcollision.org Thu Jul 21 01:22:19 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 20 Jul 2016 22:22:19 -0700 Subject: [Tutor] python programmin problem In-Reply-To: <20160720.141109.7713.1@webmail09.dca.untd.com> References: <20160720.141109.7713.1@webmail09.dca.untd.com> Message-ID: On Wed, Jul 20, 2016 at 2:11 PM, monikajg at netzero.net wrote: > Hi: > Can somebody please provide answer to following python programming question? I have spent days on it and cannot come up with any code that would make any sense for it so I cannot provide you any code. But I would appreciate the answer very much, if not in python, then in pseudo code. > Thank you very much > Monika > > Here is the problem: > Given a list of integers, return the progress of the test > The progress is defined as the length of the longest run of strictly increasing scores "with gaps allowed". If I understand the question being asked, this is often presented as an exercise for the technique of "dynamic programming". https://en.wikipedia.org/wiki/Dynamic_programming However, your question hasn't used the term "dynamic programming". Are you familiar with this term? If so, have you been exposed to other problems that can be solved with "dynamic programming"? Your problem is a rough restatement of the "longest increasing subsequence" problem. https://en.wikipedia.org/wiki/Longest_increasing_subsequence Unfortunately, solving this problem is a bit out of scope for Python tutor because it's more advanced than the material we typically talk about here (basic Python programming). I don't think we can help very much. You may get better help by talking with your instructor or study group. From dyoo at hashcollision.org Thu Jul 21 01:38:05 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 20 Jul 2016 22:38:05 -0700 Subject: [Tutor] Help me out please In-Reply-To: References: Message-ID: On Tue, Jul 19, 2016 at 4:31 AM, Marc S?nchez Quibus wrote: > Hi, > First of all I'm gonan introduce myself. My name is Marc and I'm a student > and also a python's programmer begginer. I've been studying/learning python > and now I need some help to finish my project. > I have two scripts, one of them in python (the main script) and the other > one written in html. Well, is just a brief javascript (an app) that I took > by Github. I need to change a variable inside this html script. I was > wondering wether I could change this variable from my python script or not. > Is there some way to do it? Hi Marc, Yes. You might want to read something like this to get some background. Phil Greenspun's Guide to Web Publishing: http://philip.greenspun.com/panda/ Specifically, the chapter "Sites that are really progarms". http://philip.greenspun.com/panda/server-programming You mentioned that you have two scripts, one in Python and the other in HTML. A web site can be seen as this: something that (1) takes in a web request sent by a browser, and (2) spits out a web response. A static web site takes in a web request, looks for an appropriate file, and prints that file back as a web response. But that's not the only way we can build web responses. A programmatic web site can take that request and *generate* a web page on the fly. A web site can actually be a program: not just a plain text file. There are a lot of resources to teach how to write programs that serve web sites. Another by the same author is http://philip.greenspun.com/seia/, which goes into a lot more detail. From night_skystar at hotmail.com Thu Jul 21 07:50:37 2016 From: night_skystar at hotmail.com (la Y) Date: Thu, 21 Jul 2016 11:50:37 +0000 Subject: [Tutor] need help with socket / fuzzer not sure the while loop condition is wrong Message-ID: need help with socket / fuzzer not sure the while loop condition is wrong - its superpose to fuzz testing programs over till program crashes but seems to have some errors. import os import sys import datetime import socket def fuzzer(): #fuzzer #user attack coordinates and junk currentEta = datetime.datetime.now() targetIP = raw_input("hello what is the target IP destinaition address: ") socketPort = int(raw_input("what port number : ")) while ( socketPort < 4 ) and (socketPort <= 65535): socketPort = int(socketPort) junkData = raw_input("paste your junk for fuzzing [pattern create would be perfered]") # Symbolic name meaning all available interface # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((targetIP , socketPort )) s.listen(1) conn, addr = s.accept() print ("Connected by",+ addr) counter = 0 print(currentEta) print("Current Phase 1 initated") print(targetIP) print(socketPort) print(junkData) print(":sending:=================> fuzzie fuzzie") while conn.open(counter,junkData,data): counter =+ 1 junkData = junkData + 1 print(counter) print(junkData) data = conn.recv(1024) if not data: break conn.sendall(junkData) conn.open() #option selection print("Please Select an option") options = input("1: Fuzzer n/ 2: Port Scanner ") if options == 1: #run fuzzer() elif options == 0: exit() From alan.gauld at yahoo.co.uk Thu Jul 21 14:04:35 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 21 Jul 2016 19:04:35 +0100 Subject: [Tutor] need help with socket / fuzzer not sure the while loop condition is wrong In-Reply-To: References: Message-ID: On 21/07/16 12:50, la Y wrote: > need help with socket / fuzzer UI've no idea what fuzzer means but... > not sure the while loop condition is wrong > def fuzzer(): > #fuzzer > #user attack coordinates and junk > currentEta = datetime.datetime.now() > targetIP = raw_input("hello what is the target IP destinaition address: ") > socketPort = int(raw_input("what port number : ")) > > while ( socketPort < 4 ) and (socketPort <= 65535): > socketPort = int(socketPort) This makes no sense at all. The socketPort is already an int because you make it so on the raw_input line. If it is <4 it will also be less than 65535 so the "and" test is superfluous. And if it is <4 the while loop will run forever because you never change the value of socketPort. if x = int(n) then int(x) == x is always true I've no idea what the loop is intended to do so I can't comment on whether you need to just delete it or whether you need to modify it somehow. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Thu Jul 21 16:17:48 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 21 Jul 2016 13:17:48 -0700 Subject: [Tutor] Fwd: Re: Help me out please In-Reply-To: References: Message-ID: Apologies: I don't have time at the moment to answer. Forwarding to the mailing list! ---------- Forwarded message ---------- From: "Marc S?nchez Quibus" Date: Jul 21, 2016 12:08 AM Subject: Re: [Tutor] Help me out please To: "Danny Yoo" Cc: Thanks for your fast reply. I'm gonna explain a little bit more about my problem to be more understood. Well, I have two scripts. One in Python and the other one in html. Inside the html's script you can find out these lines: I need to change these *bold *variables from the Python's script. Inside this one, there are just some prints, system's functions and so on. I would like to create, at least, some variable in python to select the value of the varible in HTML. Better if it could be chosen as input( ). Either some variable or a function. If you need more infromation let me know. Thanks in advance. Marc 2016-07-21 7:38 GMT+02:00 Danny Yoo : > On Tue, Jul 19, 2016 at 4:31 AM, Marc S?nchez Quibus > wrote: > > Hi, > > First of all I'm gonan introduce myself. My name is Marc and I'm a > student > > and also a python's programmer begginer. I've been studying/learning > python > > and now I need some help to finish my project. > > I have two scripts, one of them in python (the main script) and the other > > one written in html. Well, is just a brief javascript (an app) that I > took > > by Github. I need to change a variable inside this html script. I was > > wondering wether I could change this variable from my python script or > not. > > Is there some way to do it? > > Hi Marc, > > Yes. You might want to read something like this to get some > background. Phil Greenspun's Guide to Web Publishing: > > http://philip.greenspun.com/panda/ > > Specifically, the chapter "Sites that are really progarms". > > http://philip.greenspun.com/panda/server-programming > > You mentioned that you have two scripts, one in Python and the other in > HTML. > > A web site can be seen as this: something that (1) takes in a web > request sent by a browser, and (2) spits out a web response. > > A static web site takes in a web request, looks for an appropriate > file, and prints that file back as a web response. But that's not the > only way we can build web responses. A programmatic web site can take > that request and *generate* a web page on the fly. A web site can > actually be a program: not just a plain text file. > > > There are a lot of resources to teach how to write programs that serve > web sites. Another by the same author is > http://philip.greenspun.com/seia/, which goes into a lot more detail. > -- *Marc S?nchez Quibus* From alan.gauld at yahoo.co.uk Thu Jul 21 17:53:02 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 21 Jul 2016 22:53:02 +0100 Subject: [Tutor] Fwd: Re: Help me out please In-Reply-To: References: Message-ID: On 21/07/16 21:17, Danny Yoo wrote: > Well, I have two scripts. One in Python and the other one in html. > Inside the html's script you can find out these lines: > > > > I need to change these *bold *variables from the Python's script. That's technically not too difficult at a file level, especially if you use an html parser like Beautiful Soup. But whether that's the best way depends on how the files are used. How is the html file accessed? Is it independent of the python script? In other words doers the python script run as a batch job that only updates the values occasionally? Or regularly? (How often?) or is it on demand - some other trigger starts the Python script? Or does the Python script somehow start from an action by the html script? Its all very vague just saying you have two files. WE need to understand the intended interaction between them. If it is just a daily or hourly update then the html parser route is probably adequate. If its driven by an external trigger then it might be ok but might not. And if its driven by the html script itself then we almost certainly need a redesign of how you are doing things. So can you start by explaining the use case scenario for these interactions. How do the file get executed? What triggers them? How do they interact (if, indeed, they do)? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Jul 22 02:30:31 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 22 Jul 2016 07:30:31 +0100 Subject: [Tutor] python programmin problem In-Reply-To: <20160721.220249.428.0@webmail11.dca.untd.com> References: <20160721.220249.428.0@webmail11.dca.untd.com> Message-ID: <5791BD87.3080308@yahoo.co.uk> Forwarding to list. Please use reply-all when responding to tutor messages. As Danny suggested this is quite a complex problem. I wasn't sure whether it was just the programming or the bigger algorithm issue you were stuck on. For now I'd stick with the code you have and think about how to use that to build up a list of runs and then find the longest. Hint: Start testing at progressive items in your initial sequence. Hopefully somebody else can pick this up as I have to go away for a fewys... Alan G. On 22/07/16 06:02, monikajg at netzero.net wrote: > Hi: > Thank you so much for your suggestion. I was able to turn it into the code but Im stuck on catching the [1,2,3,5,6] case case. Could you please be so kind and give me a hint? I apologize for not having much experience on this but things like that were never taught in any of the classes I took and I have nowhere else to ask. > Thank you so much. > Monika > > > Here is my code: > > run = [] > for i in range(len(items)): > if i == 0: > run += [items[i]] > continue > else: > if items[i - 1] < items[i]: > run +=[ items[i]] > elif items[i - 1] > items[i]: > del run[-1] > run += [items[i]] > print run > > ---------- Original Message ---------- > From: Alan Gauld via Tutor > To: "monikajg at netzero.net" > Cc: tutor at python.org > Subject: Re: [Tutor] python programmin problem > Date: Thu, 21 Jul 2016 01:26:59 +0100 > > On 21/07/16 00:14, monikajg at netzero.net wrote: >> IM not able to figure out algorithm to find the runs. >> Here is the code I have: > OK, Forget about code for now. just focus on what is being asked. > >>> The first question to ask is can you do it without a computer? >>> In other words given >>> >>> input [1,7,2,3,5,4,6] >>> >>> Can you first of all produce a list of all valid runs? > Lets try it manually. Start with 1 > > run = [] > 1 > run[-1] so add it to the run -> [1] > 1 is followed by 7 which >run[-1] so add it to the run -> [1,7] > 7 is followed by 2 which [1] > 2 is now greater than run[-1] so add it to the run -> [1,2] > 2 is followed by 3 which is > run[-1] so add it to the run -> [1,2,3] > 3 is followed by 5 which is > run[-1] so add it to the run -> [1,2,3,5] > 5 is followed by 4 which is 4 is now >run[-1] so add it to the run -> [1,2,3,4] > 4 is followed by 6 which is > run[-1] so add it to the run -> [1,2,3,4,6] > 6 is not followed by anything, run complete. > > Can you see an algorithm there that you can code? > Its not quite complete because it never catches the [1,2,3,5,6] case > but its a start. And there are probably more efficient algorithms too, > but we are interested in easy to code here not speed. > -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Sat Jul 23 03:13:36 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 23 Jul 2016 00:13:36 -0700 Subject: [Tutor] python programmin problem In-Reply-To: <5791BD87.3080308@yahoo.co.uk> References: <20160721.220249.428.0@webmail11.dca.untd.com> <5791BD87.3080308@yahoo.co.uk> Message-ID: On Thu, Jul 21, 2016 at 11:30 PM, Alan Gauld via Tutor wrote: > > Forwarding to list. Please use reply-all when responding to tutor messages. > > As Danny suggested this is quite a complex problem. I wasn't sure whether > it was just the programming or the bigger algorithm issue you were stuck on. [warning: large message ahead.] This problem is unfortunately not something you can just code by trying to hack it till it works. At this level of difficulty, these kinds of problems are *not* easy: they require some understanding of fundamentals in algorithms, not Python. That is, the actual coding of this is not the hard part. A direct solution to this problem is a couple of lines and involves nothing more loops and arrays. The difficulty is understanding how to use solutions of sub-problems toward the general large problem. I should state this more strongly: trying to hack the solution is not going to work. I have to ignore the code presented in this thread because there's very little to preserve. The approach of trying to look at only the very previous element is simply not viable. The most direct approach I know to do this is by talking about this in terms of subproblems. Here is a sketch of the idea: Let's put on our magical thinking cap, and say that we'd like to design a function L(A, m) with the following funny property: For array A of length N, and for an integer k < N: L(A, k) is the length of the longest increasing subsequence of the prefix of A with length k, where that subsequence needs to include the k'th element too. What is L? This L function tries to capture the idea of having a *partial* solution that involves a portion of the array A. Why is it helpful? Because of two crucial things: 1. If we know L(A, 1), L(A, 2), ... all the way to L(A, N), then we can just look at the maximum value of those pieces. That's going to be a solution to the general problem. 2. For a subproblem L(A, k), if we know the values for L(A, 1), L(A, 2), ... , L(A, k-1), then we can compute L(A, k) by looking at those other subproblems: the result of L(A, k) is related to them. How so? ------------------------------------------------------------------- As a concrete example, consider a list A = [5, 8, 6, 7]. * What is L(A, 1)? We want the length of the longest subsequence of the prefix [5] that includes the 5. And that's just 1. L(A, 1) = 1. That is, we're starting from scratch: we can't do better than just pick the 5 as the start of our subsequence. Since our subsequence just has [5], that's a subsequence of length 1. * What is L(A, 2)? We want the length of the longest subsequence of the prefix [5, 8] that includes the 8. Why does knowing L(A, 1) help us? Because we know L(A, 1) is 1. What does that mean? We look at L(A, 1) to see if maybe we can pick the subsequence that it is measuring, and augment it. We know L(A, 1) is the length of the longest sequence that ends up including the first element of A, so we know that subsequence ends with a [... 5]. And we can extend that subsequence so it look like [..., 5, 8]. And we know that such an extension will be of length 2. Can we do any better? There are no other subproblems, so no. That is, L(A, 2) = 2. * What is L(A, 3)? We want the length of the longest subsequence of the prefix [5, 8, 6] that includes the 6. We look at L(A, 1): can we just extend [..., 5] with a 6? Yes, and that gives us 2 as a possible answer for L(A, 3). Why 2? Because L(A, 1) = 1, and if we extend the subsequence measured by L(A, 1), we make it one element longer, so 1 + 1 = 2. Can we do better? We look at L(A, 2): can we just extend [..., 8] with a 6? No. Ok, so L(A, 3) = 2. * What is L(A, 4)? We want the length of the longest subsequence of the prefix [5, 8, 6, 7] that includes the 7. We look at L(A, 1):. Can we just extend [..., 5] with a 7? Yes, and that gives us 2 as a possible answer for L(A, 4). Can we do better? We look at L(A, 2). Can we just extend [..., 8] with a 7? No. Can we do better? We look at L(A, 3). Can we just extend [..., 6] with a 7? Yes, and that gives us 3 as a possible answer for L(A, 4). Why 3? Because L(A, 3) = 2, and if we extend the subsequence measured by L(A, 3), we make it one element longer, so 2+1 = 3. Ok, we've got L(A, 1), L(A, 2), L(A, 3), and L(A, 4). Which one was the largest? 3. What's the subsequence that's of length 3? We know it's [5, 6, 7], and that's length 3, so that seems to match. So the length of the longest subsequence of the whole A is 3. ------------------------------------------------------------------- Generalizing: when we're looking for a solution for L(A, k), we can look at the prior values L(A, 1), L(A, 2), ... L(A, k), because those represent the lengths of other longest subsequences that we can extend by including the k'th element. But we've got to look to see if the extension is valid ifrst, and that requires looking at elements of A at the respective positions. Once we do this, we can then pick the one that gives us the longest valid extension. -------------------------------------------------------------------- You need to try to do similar reasoning for smaller examples to convince yourself that this approach works in general. For example, try it on the input [5, 8, 3]. . This is the kind of process that's expected when solving this class of problems. If you haven't seen this style of attacking a problem by relating to smaller subproblems, then we strongly urge you to please talk with your professor or study group. From jf_byrnes at comcast.net Sat Jul 23 11:38:52 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Sat, 23 Jul 2016 10:38:52 -0500 Subject: [Tutor] Variable in tkinter? Message-ID: I have been working my way through a Python 3 book and got to the chapter on tkinter. The following is a segment of a example program that works: # the views frame = tkinter.Frame(window) frame.pack() button = tkinter.Button(frame, text='Up', command=click_up) button.pack() button = tkinter.Button(frame, text='Down', command=click_down) button.pack() label = tkinter.Label(frame, textvariable=counter) label.pack() when I first looked at it I thought it would not work, thinking that the second reference to button = would over write the first one. Obviously that is wrong because the program does work. Could someone explain to me why it works? Regards, Jim From amonroe at columbus.rr.com Sat Jul 23 13:55:03 2016 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 23 Jul 2016 13:55:03 -0400 Subject: [Tutor] Variable in tkinter? In-Reply-To: References: Message-ID: <633613714.20160723135503@columbus.rr.com> > button = tkinter.Button(frame, text='Up', command=click_up) > button = tkinter.Button(frame, text='Down', command=click_down) > when I first looked at it I thought it would not work, thinking that the > second reference to button = would over write the first one. It DOES overwrite it, in this sense: The first button is a thing that exists because Button() generates it. "button" is a word you can now use to refer to that thing. Later on, the second call to Button() generates a new, separate thing. "button" is now a word you can use to refer to the second thing, but *the first thing doesn't cease to exist*. Alan From beachkidken at gmail.com Sun Jul 24 11:38:06 2016 From: beachkidken at gmail.com (Ken G.) Date: Sun, 24 Jul 2016 11:38:06 -0400 Subject: [Tutor] Program won't print out in Windows 10 Message-ID: <0e28e522-73d0-d756-3908-46a71530aae3@gmail.com> While the following program prints out fine using Python 2.7.6 in Ubuntu 14.04.4 as developed using Geany 1.23.1, same program won't print out to printer under Windows 10 Pro (64 bit). Geany uses there is version 1.28 using Python 2.7.12. I can use CTRL-P to print out the listing. ================================= # hello2.py import os print print "Hello World!" print pr = os.popen("lpr", "w") for i in range(1,8): pr.write("\n") pr.write("\n") pr.write("\t\t01 02 03 04 05") pr.write("\n") pr.close print print("\tPlease wait several moments for printer to catch up.") print =================================== Thanking you readers in advance in resolving this non Windows printing issue. From steve at pearwood.info Sun Jul 24 12:28:18 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 25 Jul 2016 02:28:18 +1000 Subject: [Tutor] Program won't print out in Windows 10 In-Reply-To: <0e28e522-73d0-d756-3908-46a71530aae3@gmail.com> References: <0e28e522-73d0-d756-3908-46a71530aae3@gmail.com> Message-ID: <20160724162816.GO27919@ando.pearwood.info> On Sun, Jul 24, 2016 at 11:38:06AM -0400, Ken G. wrote: > While the following program prints out fine using > Python 2.7.6 in Ubuntu 14.04.4 as developed using > Geany 1.23.1, same program won't print out to printer > under Windows 10 Pro (64 bit). Geany uses there is > version 1.28 using Python 2.7.12. I can use CTRL-P > to print out the listing. The critical piece of code that does the printing is the external function "lpr". This is not part of Python: it is a Unix/Linux command that controls the "line printer". On some machines lpr doesn't exist and it may be called "lp" instead. Does lpr or lp exist on Windows 10? I can see it exists in Windows 7. If you open up a Windows shell, the command.com or cmd.exe or whatever it is called, and enter "lpr", what happens? Perhaps you are getting a permissions error. Perhaps lpr simply isn't installed, or isn't configured properly, or can't find your printer. Once you get lpr working from the Windows 10 command line, then and only then can you hope to get it working from Python. -- Steve From steve at pearwood.info Sun Jul 24 12:29:34 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 25 Jul 2016 02:29:34 +1000 Subject: [Tutor] Variable in tkinter? In-Reply-To: <633613714.20160723135503@columbus.rr.com> References: <633613714.20160723135503@columbus.rr.com> Message-ID: <20160724162934.GP27919@ando.pearwood.info> On Sat, Jul 23, 2016 at 01:55:03PM -0400, R. Alan Monroe wrote: > > button = tkinter.Button(frame, text='Up', command=click_up) > > button = tkinter.Button(frame, text='Down', command=click_down) > > > > when I first looked at it I thought it would not work, thinking that the > > second reference to button = would over write the first one. > > It DOES overwrite it, in this sense: > > The first button is a thing that exists because Button() generates it. > "button" is a word you can now use to refer to that thing. > > Later on, the second call to Button() generates a new, separate thing. > "button" is now a word you can use to refer to the second thing, > but *the first thing doesn't cease to exist*. Why not? Why isn't the first button not garbage collected? -- Steve From __peter__ at web.de Sun Jul 24 13:20:51 2016 From: __peter__ at web.de (Peter Otten) Date: Sun, 24 Jul 2016 19:20:51 +0200 Subject: [Tutor] Variable in tkinter? References: <633613714.20160723135503@columbus.rr.com> <20160724162934.GP27919@ando.pearwood.info> Message-ID: Steven D'Aprano wrote: > On Sat, Jul 23, 2016 at 01:55:03PM -0400, R. Alan Monroe wrote: >> > button = tkinter.Button(frame, text='Up', command=click_up) >> > button = tkinter.Button(frame, text='Down', command=click_down) >> >> >> > when I first looked at it I thought it would not work, thinking that >> > the second reference to button = would over write the first one. >> >> It DOES overwrite it, in this sense: >> >> The first button is a thing that exists because Button() generates it. >> "button" is a word you can now use to refer to that thing. >> >> Later on, the second call to Button() generates a new, separate thing. >> "button" is now a word you can use to refer to the second thing, >> but *the first thing doesn't cease to exist*. > > Why not? Why isn't the first button not garbage collected? The answer is of course always the same: because there is another reference. The hard part is also always the same: how can that reference be found? Here's a way to do it in this case: $ cat tksnippet.py import tkinter window = tkinter.Tk() def click_up(): pass def click_down(): pass counter = tkinter.StringVar() frame = tkinter.Frame(window) frame.pack() button = tkinter.Button(frame, text='Up', command=click_up) button.pack() print("button whose reference we are going to overwrite:") print(repr(button), button) button = tkinter.Button(frame, text='Down', command=click_down) button.pack() label = tkinter.Label(frame, textvariable=counter) label.pack() $ python3 -i tksnippet.py button whose reference we are going to overwrite: .139999066974024.139999067097744 >>> forgotten_button = frame.nametowidget(".139999066974024.139999067097744") >>> forgotten_button >>> forgotten_button["text"] 'Up' So it is indeed the up-button rather than a reused memory address. The above snippet is only for demonstration purposes; if you plan to access a widget later-on you should always use the straightforward approach and keep a reference around in your own code. From alan.gauld at yahoo.co.uk Sun Jul 24 15:08:35 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 24 Jul 2016 20:08:35 +0100 Subject: [Tutor] Variable in tkinter? In-Reply-To: References: Message-ID: On 23/07/16 16:38, Jim Byrnes wrote: > # the views > frame = tkinter.Frame(window) > frame.pack() > button = tkinter.Button(frame, text='Up', command=click_up) > button.pack() > button = tkinter.Button(frame, text='Down', command=click_down) > button.pack() > that is wrong because the program does work. Could someone explain to > me why it works? Others have pointed out that a hidden reference to the buttons exists. In fact Tkinter, in common with most GUIIs, works by building a tree of objects starting at the top level window and then working down thru' each lower level. Usuially in Tkinter we start with a line like top = tkinter.Tk() # create the topmost widget Then when we create subwidgets, like your frame we pass the outer widget as the parent: frame = tkinter.Frame(top) Then when you create the buttons you pass frame as the first argument which makes frame the parent of the buttons. What happens is that when you create the widget the parent object adds your new instance to its list of child widgets. And that's the hidden reference that keeps your button alive even after you overwrite the button variable. You can access the widget tree of any widget using its 'children' attribute: >>> import tkinter as tk >>> top = tk.Tk() >>> f = tk.Frame(top) >>> f.pack() >>> tk.Label(f,text="Hello there!").pack() >>> f.children {'140411123026128': } >>> But it's not very user friendly so if you need to access a widget after creating it its better to use a unique variable to store a reference. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From monikajg at netzero.net Sat Jul 23 12:26:45 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Sat, 23 Jul 2016 16:26:45 GMT Subject: [Tutor] python programmin problem Message-ID: <20160723.092645.23877.0@webmail08.dca.untd.com> IM sorry I do not understand: For array A of length N, and for an integer k < N: -- By k do you mean value of k or position of k in the list? L(A, k) is the length of the longest increasing subsequence of the prefix of A with length k, where that subsequence needs to include the k'th element too. What is L? This L function tries to capture the idea of having a *partial* solution that involves a portion of the array A. Why is it helpful? Because of two crucial things: 1. If we know L(A, 1), L(A, 2), ... all the way to L(A, N), then we can just look at the maximum value of those pieces. That's going to be a solution to the general problem. -- By maximum value do you mean I have to sum up the values in the list? Why? 2. For a subproblem L(A, k), if we know the values for L(A, 1), L(A, 2), ... , L(A, k-1), then we can compute L(A, k) by looking at those other subproblems: the result of L(A, k) is related to them. -- How do we find those subproblems? And then how do you relate them to the main problem? Can you please explain more in details? Thank you so much Monika ---------- Original Message ---------- From: Danny Yoo To: Alan Gauld Cc: "monikajg at netzero.net" , tutor Subject: Re: [Tutor] python programmin problem Date: Sat, 23 Jul 2016 00:13:36 -0700 On Thu, Jul 21, 2016 at 11:30 PM, Alan Gauld via Tutor wrote: > > Forwarding to list. Please use reply-all when responding to tutor messages. > > As Danny suggested this is quite a complex problem. I wasn't sure whether > it was just the programming or the bigger algorithm issue you were stuck on. [warning: large message ahead.] This problem is unfortunately not something you can just code by trying to hack it till it works. At this level of difficulty, these kinds of problems are *not* easy: they require some understanding of fundamentals in algorithms, not Python. That is, the actual coding of this is not the hard part. A direct solution to this problem is a couple of lines and involves nothing more loops and arrays. The difficulty is understanding how to use solutions of sub-problems toward the general large problem. I should state this more strongly: trying to hack the solution is not going to work. I have to ignore the code presented in this thread because there's very little to preserve. The approach of trying to look at only the very previous element is simply not viable. The most direct approach I know to do this is by talking about this in terms of subproblems. Here is a sketch of the idea: Let's put on our magical thinking cap, and say that we'd like to design a function L(A, m) with the following funny property: For array A of length N, and for an integer k < N: L(A, k) is the length of the longest increasing subsequence of the prefix of A with length k, where that subsequence needs to include the k'th element too. What is L? This L function tries to capture the idea of having a *partial* solution that involves a portion of the array A. Why is it helpful? Because of two crucial things: 1. If we know L(A, 1), L(A, 2), ... all the way to L(A, N), then we can just look at the maximum value of those pieces. That's going to be a solution to the general problem. 2. For a subproblem L(A, k), if we know the values for L(A, 1), L(A, 2), ... , L(A, k-1), then we can compute L(A, k) by looking at those other subproblems: the result of L(A, k) is related to them. How so? ------------------------------------------------------------------- As a concrete example, consider a list A = [5, 8, 6, 7]. * What is L(A, 1)? We want the length of the longest subsequence of the prefix [5] that includes the 5. And that's just 1. L(A, 1) = 1. That is, we're starting from scratch: we can't do better than just pick the 5 as the start of our subsequence. Since our subsequence just has [5], that's a subsequence of length 1. * What is L(A, 2)? We want the length of the longest subsequence of the prefix [5, 8] that includes the 8. Why does knowing L(A, 1) help us? Because we know L(A, 1) is 1. What does that mean? We look at L(A, 1) to see if maybe we can pick the subsequence that it is measuring, and augment it. We know L(A, 1) is the length of the longest sequence that ends up including the first element of A, so we know that subsequence ends with a [... 5]. And we can extend that subsequence so it look like [..., 5, 8]. And we know that such an extension will be of length 2. Can we do any better? There are no other subproblems, so no. That is, L(A, 2) = 2. * What is L(A, 3)? We want the length of the longest subsequence of the prefix [5, 8, 6] that includes the 6. We look at L(A, 1): can we just extend [..., 5] with a 6? Yes, and that gives us 2 as a possible answer for L(A, 3). Why 2? Because L(A, 1) = 1, and if we extend the subsequence measured by L(A, 1), we make it one element longer, so 1 + 1 = 2. Can we do better? We look at L(A, 2): can we just extend [..., 8] with a 6? No. Ok, so L(A, 3) = 2. * What is L(A, 4)? We want the length of the longest subsequence of the prefix [5, 8, 6, 7] that includes the 7. We look at L(A, 1):. Can we just extend [..., 5] with a 7? Yes, and that gives us 2 as a possible answer for L(A, 4). Can we do better? We look at L(A, 2). Can we just extend [..., 8] with a 7? No. Can we do better? We look at L(A, 3). Can we just extend [..., 6] with a 7? Yes, and that gives us 3 as a possible answer for L(A, 4). Why 3? Because L(A, 3) = 2, and if we extend the subsequence measured by L(A, 3), we make it one element longer, so 2+1 = 3. Ok, we've got L(A, 1), L(A, 2), L(A, 3), and L(A, 4). Which one was the largest? 3. What's the subsequence that's of length 3? We know it's [5, 6, 7], and that's length 3, so that seems to match. So the length of the longest subsequence of the whole A is 3. ------------------------------------------------------------------- Generalizing: when we're looking for a solution for L(A, k), we can look at the prior values L(A, 1), L(A, 2), ... L(A, k), because those represent the lengths of other longest subsequences that we can extend by including the k'th element. But we've got to look to see if the extension is valid ifrst, and that requires looking at elements of A at the respective positions. Once we do this, we can then pick the one that gives us the longest valid extension. -------------------------------------------------------------------- You need to try to do similar reasoning for smaller examples to convince yourself that this approach works in general. For example, try it on the input [5, 8, 3]. . This is the kind of process that's expected when solving this class of problems. If you haven't seen this style of attacking a problem by relating to smaller subproblems, then we strongly urge you to please talk with your professor or study group. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ Affordable Wireless Plans Set up is easy. Get online in minutes. Starting at only $9.95 per month! www.netzero.net?refcd=nzmem0216 From diliupg at gmail.com Fri Jul 22 03:38:02 2016 From: diliupg at gmail.com (DiliupG) Date: Fri, 22 Jul 2016 13:08:02 +0530 Subject: [Tutor] (no subject) Message-ID: I am using Python 2.7.12 on Windows 10 filename = "??? ???????? ????????.txt" Why can't I get Python to print the name out? filename = "??? ???????? ????????.txt" Unsupported characters in input filename = u"??? ???????? ????????.txt" Unsupported characters in input above is the python ide output Even from within a program I cant get this to print. any help? Please dont ask me to use python 3. :) -- Kalasuri Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ********************************************************************************************** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ********************************************************************************************** From ing.jdj at gmail.com Sat Jul 23 04:12:55 2016 From: ing.jdj at gmail.com (=?UTF-8?Q?Jos=C3=A9_de_Jesus_Marquez_Rangel?=) Date: Sat, 23 Jul 2016 03:42:55 -0430 Subject: [Tutor] Help with error in paramiko Message-ID: Hello. I have a problem because when I connect to the remote server via SSH gives me an error with paramiko library, but I connect to the same server with programs like putty, ssh and another there is no error. Here the screenshot: *Script.* [image: Im?genes integradas 1] *the result of run* [image: Im?genes integradas 7] *the result of log.* The problem is when the ZAHO command with the library in the logs can see the error highlighted runs. *[image: Im?genes integradas 6]* *PD: *The feature of the remote server unknown but the script work on the Linux server. Feature the computer client. Windows 7 64bits. Python3.4 Library paramiko, From marcus.luetolf at bluewin.ch Sat Jul 23 15:06:14 2016 From: marcus.luetolf at bluewin.ch (=?iso-8859-1?Q?marcus_l=FCtolf?=) Date: Sat, 23 Jul 2016 21:06:14 +0200 Subject: [Tutor] installing openpyxl Message-ID: <013001d1e515$4c0190e0$e404b2a0$@bluewin.ch> Dear Experts, following instructions in a youtube video I thought I finally succeded to install openpyxl. However I got the traceback below: >>> import openpyxl Traceback (most recent call last): File "", line 1, in import openpyxl File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\__init__.py", line 29, in from openpyxl.workbook import Workbook File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\workbook\__init__.py", line 5, in from .workbook import Workbook File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\workbook\workbook.py", line 8, in from openpyxl.worksheet import Worksheet File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\worksheet\__init__.py", line 4, in from .worksheet import Worksheet File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\worksheet\worksheet.py", line 34, in from openpyxl.cell import Cell File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\cell\__init__.py", line 4, in from .cell import Cell, WriteOnlyCell File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\cell\cell.py", line 30, in from openpyxl.utils.datetime import ( File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\utils\datetime.py", line 13, in from jdcal import ( ImportError: No module named 'jdcal' How do I get ?jdcal? ? Tanks everybody for help, Marcus. .. dear Experts, could someone please tell me what exactly I have to type in my a) Python 35 ? command line or b) desktopcomputer ( W10, 64bit)-command line in ordert to install openpyxl which I downloaded in C:\Users\marcus\Downloads on my computer. I have used all kinds of commands with ?pip install? at the end, all unsuccessful. Thanks for help. Marcus. --- Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft. https://www.avast.com/antivirus From marcus.luetolf at bluewin.ch Sun Jul 24 15:04:11 2016 From: marcus.luetolf at bluewin.ch (=?iso-8859-1?Q?marcus_l=FCtolf?=) Date: Sun, 24 Jul 2016 21:04:11 +0200 Subject: [Tutor] installing openpyxl, problem solved Message-ID: <01f901d1e5de$2cae5ce0$860b16a0$@bluewin.ch> Dear Experts, problem solved, don?t bother, Marcus. . Dear Experts, following instructions in a youtube video I thought I finally succeded to install openpyxl. However I got the traceback below: >>> import openpyxl Traceback (most recent call last): File "", line 1, in import openpyxl File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\__init__.py", line 29, in from openpyxl.workbook import Workbook File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\workbook\__init__.py", line 5, in from .workbook import Workbook File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\workbook\workbook.py", line 8, in from openpyxl.worksheet import Worksheet File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\worksheet\__init__.py", line 4, in from .worksheet import Worksheet File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\worksheet\worksheet.py", line 34, in from openpyxl.cell import Cell File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\cell\__init__.py", line 4, in from .cell import Cell, WriteOnlyCell File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\cell\cell.py", line 30, in from openpyxl.utils.datetime import ( File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\utils\datetime.py", line 13, in from jdcal import ( ImportError: No module named 'jdcal' How do I get ?jdcal? ? Tanks everybody for help, Marcus. .. dear Experts, could someone please tell me what exactly I have to type in my a) Python 35 ? command line or b) desktopcomputer ( W10, 64bit)-command line in ordert to install openpyxl which I downloaded in C:\Users\marcus\Downloads on my computer. I have used all kinds of commands with ?pip install? at the end, all unsuccessful. Thanks for help. Marcus. --- Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft. https://www.avast.com/antivirus From jf_byrnes at comcast.net Sun Jul 24 15:27:06 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Sun, 24 Jul 2016 14:27:06 -0500 Subject: [Tutor] Variable in tkinter? In-Reply-To: References: Message-ID: On 07/24/2016 02:08 PM, Alan Gauld via Tutor wrote: > On 23/07/16 16:38, Jim Byrnes wrote: > >> # the views >> frame = tkinter.Frame(window) >> frame.pack() >> button = tkinter.Button(frame, text='Up', command=click_up) >> button.pack() >> button = tkinter.Button(frame, text='Down', command=click_down) >> button.pack() > >> that is wrong because the program does work. Could someone explain to >> me why it works? > > Others have pointed out that a hidden reference to the buttons exists. > In fact Tkinter, in common with most GUIIs, works by building a tree of > objects starting at the top level window and then working down thru' > each lower level. > > Usuially in Tkinter we start with a line like > > top = tkinter.Tk() # create the topmost widget > > Then when we create subwidgets, like your frame we > pass the outer widget as the parent: > > frame = tkinter.Frame(top) > > Then when you create the buttons you pass frame > as the first argument which makes frame the parent > of the buttons. > > What happens is that when you create the widget the > parent object adds your new instance to its list of > child widgets. And that's the hidden reference that keeps > your button alive even after you overwrite the button > variable. > > You can access the widget tree of any widget using > its 'children' attribute: > > >>>> import tkinter as tk >>>> top = tk.Tk() >>>> f = tk.Frame(top) >>>> f.pack() >>>> tk.Label(f,text="Hello there!").pack() >>>> f.children > {'140411123026128': } >>>> > > But it's not very user friendly so if you need to access > a widget after creating it its better to use a unique > variable to store a reference. > Thanks Peter and Alan, After I proved to myself that it worked and I thought about it, I suspected it had to do with a reference. It's nice to have it confirmed is such a clear manner. Regards, Jim From mail at timgolden.me.uk Sun Jul 24 15:54:33 2016 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 24 Jul 2016 20:54:33 +0100 Subject: [Tutor] Program won't print out in Windows 10 In-Reply-To: <0e28e522-73d0-d756-3908-46a71530aae3@gmail.com> References: <0e28e522-73d0-d756-3908-46a71530aae3@gmail.com> Message-ID: On 24/07/2016 16:38, Ken G. wrote: > While the following program prints out fine using > > Python 2.7.6 in Ubuntu 14.04.4 as developed using > > Geany 1.23.1, same program won't print out to printer > > under Windows 10 Pro (64 bit). Geany uses there is > > version 1.28 using Python 2.7.12. I can use CTRL-P > > to print out the listing. > Thanking you readers in advance in resolving this non > > Windows printing issue. Rather: user believing that what works under Linux will work under Windows issue :) You might find this page helpful: http://timgolden.me.uk/python/win32_how_do_i/print.html TJG From dyoo at hashcollision.org Sun Jul 24 15:58:08 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 24 Jul 2016 12:58:08 -0700 Subject: [Tutor] python programmin problem In-Reply-To: <20160723.092645.23877.0@webmail08.dca.untd.com> References: <20160723.092645.23877.0@webmail08.dca.untd.com> Message-ID: On Jul 23, 2016 9:27 AM, "monikajg at netzero.net" wrote: > > IM sorry I do not understand: > > For array A of length N, and for an integer k < N: > -- By k do you mean value of k or position of k in the list? > The letter 'k' is typically intended to be used as an index, a position into a list. I'm trying to say that k had to be pointed somewhere in the list by constraining it to be less than the size of the list. > > 1. If we know L(A, 1), L(A, 2), ... all the way to L(A, N), then > we can just look at the maximum value of those pieces. That's going > to be a solution to the general problem. > -- By maximum value do you mean I have to sum up the values in the list? Why? "Maximum" is a notion of comparing and picking out the biggest thing we see. It doesn't have to do with addition. If we have a bunch of numbers, we can do a lot more than just add then together. Numbers are more interesting than that. Both summation and maximum-finding are operations that are intended to take a bunch of bits of information in order to discover something new. So, conceptually speaking, there *is* a deep, underlying connection. But I don't think that's what you're intending to talk about. > 2. For a subproblem L(A, k), if we know the values for L(A, 1), > L(A, 2), ... , L(A, k-1), then we can compute L(A, k) by looking at > those other subproblems: the result of L(A, k) is related to them. > -- How do we find those subproblems? And then how do you relate them to the main problem? > > Can you please explain more in details? Unfortunately, no. This is the wrong venue. Please: I strongly encourage you to talk with your professor or study group: it really does sound like this is the first time you've seen these kinds of concepts. Longest common subsequence is not the ideal problem to use to introduce these concepts: it is meant to help you *master* them. I would not dare trying to use it as a first example into learning dynamic programming. You probably want to use a problem that has fewer moving parts. Your instructor likely has a much nicer introductory problem so that you can learn the patterns of thinking through these problems. Anyway, hope that makes sense. From danny.yoo at gmail.com Sun Jul 24 16:28:11 2016 From: danny.yoo at gmail.com (Danny Yoo) Date: Sun, 24 Jul 2016 13:28:11 -0700 Subject: [Tutor] python programmin problem In-Reply-To: References: <20160723.092645.23877.0@webmail08.dca.untd.com> Message-ID: > You probably want to use a problem that has fewer moving parts. Your instructor likely has a much nicer introductory problem so that you can learn the patterns of thinking through these problems. Just to add: there are online resources you can use for this. Khan Academy, for example: https://www.khanacademy.org/computing/computer-science/algorithms. For self study, i can also recommend Introduction to Algorithms. https://mitpress.mit.edu/books/introduction-algorithms. When I'm using the term "subproblem", I'm mentally recalling the training I received from learning about recursion. Recursion is much more than about functions calling themselves. That is, if we've learned about recursion and thought: "why use recursion when you have loops?", then we've missed a key point, which is this: it's intended to teach how to think about subproblems and synthesizing from them. That's the answer I should have given to your question about thinking about subproblems. From alan.gauld at yahoo.co.uk Sun Jul 24 19:21:10 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 25 Jul 2016 00:21:10 +0100 Subject: [Tutor] python programmin problem In-Reply-To: References: <20160723.092645.23877.0@webmail08.dca.untd.com> Message-ID: On 24/07/16 20:58, Danny Yoo wrote: > Please: I strongly encourage you to talk with your professor or study > group: it really does sound like this is the first time you've seen these > kinds of concepts. I agree with Danny, you should talk to your teacher. I suspect the teacher may have set the problem without appreciating the full extent of the complexity involved. It certainly doesn't seem like you are properly equipped to solve it. Maybe he/she can provide a simpler subset of problem. Of course this assumes you have a teacher to ask? Your original post doesn't state where you found the problem, it may be you just picked it up on a web site or book and have unwittingly bitten off more than you are ready to chew just now? It also depends a bit on whether the intent is to learn about Python programming or about algorithms. If its the latter then you might just want to ask on a different (math based) forum. But if its Python you are interested in then find an easier problem for now. Otherwise you will lose sight of the Python problem in trying to solve the math one. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Sun Jul 24 19:24:20 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 25 Jul 2016 00:24:20 +0100 Subject: [Tutor] Help with error in paramiko In-Reply-To: References: Message-ID: On 23/07/16 09:12, Jos? de Jesus Marquez Rangel wrote: > Hello. > > I have a problem because when I connect to the remote server via SSH gives > me an error with paramiko library, but I connect to the same server with > programs like putty, ssh and another there is no error. > > Here the screenshot: > > *Script.* > [image: Im?genes integradas 1] > > *the result of run* > [image: Im?genes integradas 7] > This is a text based forum and as such your images didn't make it through the server. If possible just copy/paste the text into a mail message. Also paramiko is really outside the scope of this group (core language and standard library) so you might do better on a paramiko forum such as their mailing list: paramiko at librelist.com -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Sun Jul 24 19:25:38 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 25 Jul 2016 00:25:38 +0100 Subject: [Tutor] installing openpyxl, problem solved In-Reply-To: <01f901d1e5de$2cae5ce0$860b16a0$@bluewin.ch> References: <01f901d1e5de$2cae5ce0$860b16a0$@bluewin.ch> Message-ID: On 24/07/16 20:04, marcus l?tolf wrote: > Dear Experts, problem solved, don?t bother, Marcus. For the sake of the archive can you post a short mail stating what the solution was? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From monikajg at netzero.net Sun Jul 24 19:30:40 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Sun, 24 Jul 2016 23:30:40 GMT Subject: [Tutor] python programmin problem Message-ID: <20160724.163040.26810.0@webmail13.dca.untd.com> Thank you all for your answers. I do not have a teacher or any body else who could guide me. I have taken all python classes offered in my area and many on line. The question is one of questions asked by interviews for a qa position that also does some automation with python. Im just trying to learn so that I could get a job. Nobody offers manual qa jobs anymore so I am working on updating my skills. ---------- Original Message ---------- From: Alan Gauld via Tutor To: tutor at python.org Subject: Re: [Tutor] python programmin problem Date: Mon, 25 Jul 2016 00:21:10 +0100 On 24/07/16 20:58, Danny Yoo wrote: > Please: I strongly encourage you to talk with your professor or study > group: it really does sound like this is the first time you've seen these > kinds of concepts. I agree with Danny, you should talk to your teacher. I suspect the teacher may have set the problem without appreciating the full extent of the complexity involved. It certainly doesn't seem like you are properly equipped to solve it. Maybe he/she can provide a simpler subset of problem. Of course this assumes you have a teacher to ask? Your original post doesn't state where you found the problem, it may be you just picked it up on a web site or book and have unwittingly bitten off more than you are ready to chew just now? It also depends a bit on whether the intent is to learn about Python programming or about algorithms. If its the latter then you might just want to ask on a different (math based) forum. But if its Python you are interested in then find an easier problem for now. Otherwise you will lose sight of the Python problem in trying to solve the math one. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ Affordable Wireless Plans Set up is easy. Get online in minutes. Starting at only $9.95 per month! www.netzero.net?refcd=nzmem0216 From rus.cahimb at gmail.com Mon Jul 25 00:15:42 2016 From: rus.cahimb at gmail.com (Ramanathan Muthaiah) Date: Mon, 25 Jul 2016 04:15:42 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: Hi Dilip, This error has nothing to do with Python or it's versions. OS does not have the support for these unicode characters. You need to fix that. > filename = "??? ???????? ????????.txt" > Why can't I get Python to print the name out? > > filename = "??? ???????? ????????.txt" > Unsupported characters in input > -- regards Ram From steve at pearwood.info Mon Jul 25 06:28:29 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 25 Jul 2016 20:28:29 +1000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <20160725102828.GR27919@ando.pearwood.info> On Fri, Jul 22, 2016 at 01:08:02PM +0530, DiliupG wrote: > I am using Python 2.7.12 on Windows 10 Two errors: - first error is that Unicode strings in Python 2 need to be written as unicode objects, with a "u" prefix in the delimiter: # ASCII byte string: "Hello World" # Unicode string: u"??? ?" ASCII strings "..." cannot give you the right results except by accident. You must use unicode strings u"..." - Second possible problem: using Windows, which may not support the characters you are trying to use. I don't know -- try it and see. If it still doesn't work, then blame Windows. I know that Linux and Mac OS X both use UTF-8 for filenames, and so support all of Unicode. But Windows, I'm not sure. It might be localised to only use Latin-1 (Western European) or similar. -- Steve From eryksun at gmail.com Mon Jul 25 07:19:46 2016 From: eryksun at gmail.com (eryk sun) Date: Mon, 25 Jul 2016 11:19:46 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On Fri, Jul 22, 2016 at 7:38 AM, DiliupG wrote: > I am using Python 2.7.12 on Windows 10 > > filename = u"??? ???????? ????????.txt" > Unsupported characters in input That error message is from IDLE. I'm not an expert with IDLE, so I don't know what the following hack potentially breaks, but it does allow entering the above Unicode filename in the interactive interpreter. Edit "Python27\Lib\idlelib\IOBinding.py". Look for the following section on line 34: if sys.platform == 'win32': # On Windows, we could use "mbcs". However, to give the user # a portable encoding name, we need to find the code page try: encoding = locale.getdefaultlocale()[1] codecs.lookup(encoding) except LookupError: pass Replace the encoding value with "utf-8" as follows: # encoding = locale.getdefaultlocale()[1] encoding = "utf-8" When you restart IDLE, you should see that sys.stdin.encoding is now "utf-8". IOBinding.encoding is used by ModifiedInterpreter.runsource in PyShell.py. When the encoding is UTF-8, it passes the Unicode source string directly to InteractiveInterpreter.runsource, where it gets compiled using the built-in compile() function. Note that IDLE uses the Tk GUI toolkit, which -- at least with Python Tkinter on Windows -- is limited to the first 65,536 Unicode characters, i.e the Basic Multilingual Plane. The BMP includes Sinhalese, so your filename string is fine. From eryksun at gmail.com Mon Jul 25 07:55:20 2016 From: eryksun at gmail.com (eryk sun) Date: Mon, 25 Jul 2016 11:55:20 +0000 Subject: [Tutor] (no subject) In-Reply-To: <20160725102828.GR27919@ando.pearwood.info> References: <20160725102828.GR27919@ando.pearwood.info> Message-ID: On Mon, Jul 25, 2016 at 10:28 AM, Steven D'Aprano wrote: > I know that Linux and Mac OS X both use UTF-8 for filenames, and so support all > of Unicode. But Windows, I'm not sure. It might be localised to only use Latin-1 > (Western European) or similar. Windows filesystems (e.g. NTFS, ReFS, UDF, exFAT, FAT32) use Unicode [1], i.e. UTF-16, as does the Windows wide-character API. Using 16-bit wchar_t strings is a problem for C standard functions such as fopen, which require 8-bit null-terminated strings, so the Windows C runtime also supports wide-character alternatives such as _wfopen. Python's os and io functions use Windows wide-character APIs for unicode arguments, even in 2.x. Unfortunately some 2.x modules such as subprocess use only the 8-bit API (e.g. 2.x Popen calls CreateProcessA instead of CreateProcessW). [1]: https://msdn.microsoft.com/en-us/library/ee681827#limits From marcus.luetolf at bluewin.ch Mon Jul 25 14:59:50 2016 From: marcus.luetolf at bluewin.ch (=?iso-8859-1?Q?marcus_l=FCtolf?=) Date: Mon, 25 Jul 2016 20:59:50 +0200 Subject: [Tutor] installing openpyxl, problem still n o t solved Message-ID: Dear Experts, I was too optimistic. Module ?jdcal? ist indeed installed. However, I get another trace back concerning ?et_xmlfile? even after I downloaded and saved it the same way as I did with ?jdcal?. Since I haven?t got any responses to my previous calls for help ? my problem might be too unimportant - I just try it another time: Why got ?jdcal? accepted and ?et_xmlfile? not ? I must say I unzipped both files directly in C:\Users\marcus\AppData\local\Programs\Python\Python35\Lib\site-packages. The command >pip install was rejected as SyntaxError : invalid syntax. Thanks for any kind of help, Marcus. >>> import openpyxl Traceback (most recent call last): File "", line 1, in import openpyxl File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\__init__.py", line 29, in from openpyxl.workbook import Workbook File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\workbook\__init__.py", line 5, in from .workbook import Workbook File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\workbook\workbook.py", line 8, in from openpyxl.worksheet import Worksheet File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\worksheet\__init__.py", line 4, in from .worksheet import Worksheet File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\worksheet\worksheet.py", line 34, in from openpyxl.cell import Cell File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\cell\__init__.py", line 4, in from .cell import Cell, WriteOnlyCell File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\cell\cell.py", line 44, in from openpyxl.styles import numbers, is_date_format File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\styles\__init__.py", line 5, in from .alignment import Alignment File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\styles\alignment.py", line 6, in from openpyxl.descriptors import Bool, MinMax, Min, Alias, NoneSet File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\descriptors\__init__.py", line 5, in from .sequence import Sequence File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\descriptors\sequence.py", line 5, in from openpyxl.xml.functions import Element File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\xml\functions.py", line 51, in from et_xmlfile import xmlfile ImportError: No module named 'et_xmlfile' >>> Dear Experts, problem solved, don?t bother, Marcus. . Dear Experts, following instructions in a youtube video I thought I finally succeded to install openpyxl. However I got the traceback below: >>> import openpyxl Traceback (most recent call last): File "", line 1, in import openpyxl File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\__init__.py", line 29, in from openpyxl.workbook import Workbook File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\workbook\__init__.py", line 5, in from .workbook import Workbook File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\workbook\workbook.py", line 8, in from openpyxl.worksheet import Worksheet File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\worksheet\__init__.py", line 4, in from .worksheet import Worksheet File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\worksheet\worksheet.py", line 34, in from openpyxl.cell import Cell File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\cell\__init__.py", line 4, in from .cell import Cell, WriteOnlyCell File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\cell\cell.py", line 30, in from openpyxl.utils.datetime import ( File "C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op enpyxl\utils\datetime.py", line 13, in from jdcal import ( ImportError: No module named 'jdcal' How do I get ?jdcal? ? Tanks everybody for help, Marcus. .. dear Experts, could someone please tell me what exactly I have to type in my a) Python 35 ? command line or b) desktopcomputer ( W10, 64bit)-command line in ordert to install openpyxl which I downloaded in C:\Users\marcus\Downloads on my computer. I have used all kinds of commands with ?pip install? at the end, all unsuccessful. Thanks for help. Marcus. --- Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft. https://www.avast.com/antivirus From alan.gauld at yahoo.co.uk Mon Jul 25 18:34:11 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 25 Jul 2016 23:34:11 +0100 Subject: [Tutor] installing openpyxl, problem still n o t solved In-Reply-To: References: Message-ID: On 25/07/16 19:59, marcus l?tolf wrote: > The command >pip install was rejected as SyntaxError : invalid syntax. > Thanks for any kind of help, Marcus. If you get a syntax error that suggests you are running it from the Python >>> prompt. That's wrong. You should run pip from the command prompt of your OS. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Mon Jul 25 23:57:37 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 26 Jul 2016 13:57:37 +1000 Subject: [Tutor] installing openpyxl, problem still n o t solved In-Reply-To: References: Message-ID: <20160726035736.GS27919@ando.pearwood.info> Hello Marcus, I'm afraid it is very difficult for me to understand your email. Your email contains weird control characters as shown here: On Mon, Jul 25, 2016 at 08:59:50PM +0200, marcus l?tolf wrote: > Dear Experts, > > I was too optimistic. Module ?jdcal? ist indeed installed. > However, I get another trace back concerning ?et_xmlfile? even after I > downloaded and saved it the same way as I did with ?jdcal?. I think the reason is that your email program is setting the wrong encoding: your email claims to be Latin-1 but obviously isn't. I think this may be because you are using Microsoft Word as the email editor, and inserting "smart quotes", probably ??. Smart quotes are not part of Latin-1, but Outlook is (wrongly!) setting a header saying that it is using Latin-1. You should be able to fix this by: - turning of Smart Quotes and using ordinary '' or "" quotes instead of curly quotes ?? or ?? - teaching Outlook to use UTF-8 instead of the cp1252 encoding - or at least have Outlook say it is using cp1252 instead of wrongly claiming to be using Latin-1 That will help us be able to read your emails. Another problem is that I actually don't understand what you are saying. First you say that you were too optimistic, at the beginning of the email. Then in the middle of the email you say you have solved your problem, and we should not bother. Then at the beginning you say that you need help. None of these parts are quoted: > Quoted text Not quoted text so it all looks like part of the same email, which is confusing: have you solved the problem? Not solved it? If we understood your questions better, perhaps we could answer them. > Since I haven?t got any responses to my previous calls for help ? my problem > might be too unimportant - I just try it another time: > > Why got ?jdcal? accepted and ?et_xmlfile? not ? > I must say I unzipped both files directly in > C:\Users\marcus\AppData\local\Programs\Python\Python35\Lib\site-packages. Are you talking about this? https://pypi.python.org/pypi/et_xmlfile You should unzip it into your home directory, and then run the setup.py file in the top directory. I think the command will be: python setup.py install as administrator or root superuser. On Linux/Mac you may be able to use: sudo python setup.py install > The command >pip install was rejected as SyntaxError : invalid syntax. > Thanks for any kind of help, Marcus. You need to run pip from the operating system's shell, not from inside Python. Python's default prompt is ">>>". Most shells use "$" or "%" as the prompt. -- Steve From eryksun at gmail.com Tue Jul 26 01:22:28 2016 From: eryksun at gmail.com (eryk sun) Date: Tue, 26 Jul 2016 05:22:28 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: <20160725102828.GR27919@ando.pearwood.info> Message-ID: On Tue, Jul 26, 2016 at 4:39 AM, DiliupG wrote: > I am reading in a list of file names with the following code. > > def get_filelist(self): > """""" > app = QtGui.QApplication(sys.argv) > a = QtGui.QFileDialog.getOpenFileNames() > > filelist = [] > if a: > for name in a: > a = unicode(name) > > filelist.append(a) > > return filelist > > mainprg.filelist = mainprg.get_filelist() > > filelist = mainprg.filelist > > for name in filelist: > print name < ---- THIS IS WHERE THE PROBLEM IS This is an output problem, which is unrelated to the IDLE input error that you initially reported. But IDLE isn't (at least shouldn't be) used for deployed applications. It's a development environment. Generally if you're using Qt then you're not creating a console application that prints to stdout, but instead the program outputs text to a Qt widget such as a QTextEdit. That said, if you need to print Unicode text to the Windows console, for whatever reason (maybe debugging), then pip install and enable the win_unicode_console module. From diliupg at gmail.com Tue Jul 26 00:41:00 2016 From: diliupg at gmail.com (DiliupG) Date: Tue, 26 Jul 2016 10:11:00 +0530 Subject: [Tutor] (no subject) In-Reply-To: <20160725102828.GR27919@ando.pearwood.info> References: <20160725102828.GR27919@ando.pearwood.info> Message-ID: Thank you for the responses. Some filenames I use are in Unicode in this script and there is no display or typing problem in Windows (Vista, 7 and 10). Filenames and text in word processing and text files are ALL displayed properly WITHOUT any errors by the Windows system. When I use a standard font in the local language there is no problem at all but I need to retype ALL display text in all the Python programs which is a tedious task. Having read all answers is there no way this can be done without modifing code on my computer? Thepurpose is to deliver a WIndows software for ALL Windows users. I am reading in a list of file names with the following code. def get_filelist(self): """""" app = QtGui.QApplication(sys.argv) a = QtGui.QFileDialog.getOpenFileNames() filelist = [] if a: for name in a: a = unicode(name) filelist.append(a) return filelist mainprg.filelist = mainprg.get_filelist() filelist = mainprg.filelist for name in filelist: print name < ---- THIS IS WHERE THE PROBLEM IS Thanks for feed back. On Mon, Jul 25, 2016 at 3:58 PM, Steven D'Aprano wrote: > On Fri, Jul 22, 2016 at 01:08:02PM +0530, DiliupG wrote: > > I am using Python 2.7.12 on Windows 10 > > Two errors: > > - first error is that Unicode strings in Python 2 need to be written as > unicode objects, with a "u" prefix in the delimiter: > > # ASCII byte string: > "Hello World" > > # Unicode string: > > u"??? ?" > > ASCII strings "..." cannot give you the right results except by > accident. You must use unicode strings u"..." > > - Second possible problem: using Windows, which may not support the > characters you are trying to use. I don't know -- try it and see. If it > still doesn't work, then blame Windows. I know that Linux and Mac OS X > both use UTF-8 for filenames, and so support all of Unicode. But > Windows, I'm not sure. It might be localised to only use Latin-1 > (Western European) or similar. > > > -- > Steve > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Kalasuri Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ********************************************************************************************** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ********************************************************************************************** From diliupg at gmail.com Tue Jul 26 01:23:17 2016 From: diliupg at gmail.com (DiliupG) Date: Tue, 26 Jul 2016 10:53:17 +0530 Subject: [Tutor] (no subject) In-Reply-To: References: <20160725102828.GR27919@ando.pearwood.info> Message-ID: Thanks for the support. Mu main problem was in the editor I was using which I did not mention. I was using Wing IDE Pro instead of the Python IDE. BY the answer given by erik sun I applied the same idea to th Wing IDE i/o to utf-8 and everything worked. Thanks for your support and pardon me for not supplying all the info. On Tue, Jul 26, 2016 at 10:11 AM, DiliupG wrote: > Thank you for the responses. > Some filenames I use are in Unicode in this script and there is no display > or typing problem in Windows (Vista, 7 and 10). Filenames and text in word > processing and text files are ALL displayed properly WITHOUT any errors by > the Windows system. > > When I use a standard font in the local language there is no problem at > all but I need to retype ALL display text in all the Python programs which > is a tedious task. > > Having read all answers is there no way this can be done without modifing > code on my computer? Thepurpose is to deliver a WIndows software for ALL > Windows users. > > I am reading in a list of file names with the following code. > > def get_filelist(self): > """""" > app = QtGui.QApplication(sys.argv) > a = QtGui.QFileDialog.getOpenFileNames() > > filelist = [] > if a: > for name in a: > a = unicode(name) > > filelist.append(a) > > return filelist > > mainprg.filelist = mainprg.get_filelist() > > filelist = mainprg.filelist > > for name in filelist: > print name < ---- THIS IS WHERE THE PROBLEM IS > > Thanks for feed back. > > On Mon, Jul 25, 2016 at 3:58 PM, Steven D'Aprano > wrote: > >> On Fri, Jul 22, 2016 at 01:08:02PM +0530, DiliupG wrote: >> > I am using Python 2.7.12 on Windows 10 >> >> Two errors: >> >> - first error is that Unicode strings in Python 2 need to be written as >> unicode objects, with a "u" prefix in the delimiter: >> >> # ASCII byte string: >> "Hello World" >> >> # Unicode string: >> >> u"??? ?" >> >> ASCII strings "..." cannot give you the right results except by >> accident. You must use unicode strings u"..." >> >> - Second possible problem: using Windows, which may not support the >> characters you are trying to use. I don't know -- try it and see. If it >> still doesn't work, then blame Windows. I know that Linux and Mac OS X >> both use UTF-8 for filenames, and so support all of Unicode. But >> Windows, I'm not sure. It might be localised to only use Latin-1 >> (Western European) or similar. >> >> >> -- >> Steve >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Kalasuri Diliup Gabadamudalige > > http://www.diliupg.com > http://soft.diliupg.com/ > > > ********************************************************************************************** > This e-mail is confidential. It may also be legally privileged. If you are > not the intended recipient or have received it in error, please delete it > and all copies from your system and notify the sender immediately by return > e-mail. Any unauthorized reading, reproducing, printing or further > dissemination of this e-mail or its contents is strictly prohibited and may > be unlawful. Internet communications cannot be guaranteed to be timely, > secure, error or virus-free. The sender does not accept liability for any > errors or omissions. > > ********************************************************************************************** > > -- Kalasuri Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ********************************************************************************************** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ********************************************************************************************** From crusier at gmail.com Tue Jul 26 12:02:26 2016 From: crusier at gmail.com (Crusier) Date: Tue, 26 Jul 2016 09:02:26 -0700 Subject: [Tutor] Beautiful Soup Message-ID: I am using Python 3 on Windows 7. However, I am unable to download some of the data listed in the web site as follows: 453.IMC 98.28M 18.44M 4.32 5.33 1499.Optiver 70.91M 13.29M 3.12 5.34 7387.???? 52.72M 9.84M 2.32 5.36 When I use Google Chrome and use 'View Page Source', the data does not show up at all. However, when I use 'Inspect', I can able to read the data. 1453.IMC 98.28M 18.44M 4.32 5.33 1499.Optiver 70.91M 13.29M 3.12 5.34 Please kindly explain to me if the data is hide in CSS Style sheet or is there any way to retrieve the data listed. Thank you Regards, Crusier from bs4 import BeautifulSoup import urllib import requests stock_code = ('00939', '0001') def web_scraper(stock_code): broker_url = 'http://data.tsci.com.cn/stock/' end_url = '/STK_Broker.htm' for code in stock_code: new_url = broker_url + code + end_url response = requests.get(new_url) html = response.content soup = BeautifulSoup(html, "html.parser") Buylist = soup.find_all('div', id ="BuyingSeats") Selllist = soup.find_all('div', id ="SellSeats") print(Buylist) print(Selllist) web_scraper(stock_code) From jf_byrnes at comcast.net Tue Jul 26 23:44:42 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Tue, 26 Jul 2016 22:44:42 -0500 Subject: [Tutor] OOP help needed Message-ID: OOP has always driven me crazy. I read the material and follow the examples until I feel I understand them, but when I try to implement it I end up with an error filled mess. So I decided to give it another try. When I got to the chapter on tkinter I decided to solve all the exercises using OOP even though the book solutions did not use OOP. The first one went fine: #exer1.py import tkinter class Goodbye: def __init__(self): self.frame = tkinter.Frame(window) self.frame.pack() self.goodbye_button = tkinter.Button(self.frame, text='Goodbye', #command=quit) command=lambda: quit() ) self.goodbye_button.pack() def quit(): self.window.destroy() if __name__=='__main__': window = tkinter.Tk() myapp = Goodbye() window.mainloop() The second one was more trouble but I finally got it to work. # exer2.py import tkinter class Count: def __init__(self): ''' Increment a button labeled 0, by 1 with each click ''' self.frame = tkinter.Frame(window) self.frame.pack() self.label = tkinter.StringVar() self.label.set('0') self.count_btn = tkinter.Button(self.frame, textvariable=self.label, command=lambda: self.increment(self.label )) self.count_btn.pack() def increment(self, label): count = int(self.label.get()) self.label.set(str(count + 1)) if __name__ == '__main__': window = tkinter.Tk() myapp = Count() window.mainloop() I am having trouble understanding the difference between the two lines that contain lambda: command= .In exer1.py I can do command=lambda: quit(). In exer2.py if I do command=lambda: increment(self.label) I get this error: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__ return self.func(*args) File "exer2.py", line 14, in command=lambda: increment(self.label )) NameError: name 'increment' is not defined Why do I get this error? The situations look the same to me but they must be different somehow and I just don't see the difference. Thanks, Jim From ben+python at benfinney.id.au Wed Jul 27 00:38:16 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 27 Jul 2016 14:38:16 +1000 Subject: [Tutor] OOP help needed References: Message-ID: <85lh0npufb.fsf@benfinney.id.au> Jim Byrnes writes: > So I decided to give it another try. When I got to the chapter on > tkinter I decided to solve all the exercises using OOP even though the > book solutions did not use OOP. Hmm, that sounds ill advised. OOP is one tool among many; trying to apply it where it's a poor fit will result in bad design and probably avoidable errors. When learning to use a hacksaw, trying to solve everything using that tool merely to learn it, would be a poor choice. > # exer2.py > > import tkinter > > class Count: > > def __init__(self): > ''' Increment a button labeled 0, by 1 with each click ''' > [?] > self.count_btn = tkinter.Button(self.frame, textvariable=self.label, > command=lambda: self.increment(self.label )) Here you address the ?self.increment? name, which should work. > def increment(self, label): > count = int(self.label.get()) > self.label.set(str(count + 1)) This is the method that an instance will address via ?self.increment?. > In exer2.py if I do command=lambda: increment(self.label) The lambda expression creates a function, and that function then behaves like any other function. Within that function, the name ?increment? is not defined; within the scope where the function was defined, the name ?increment? is also not defined. Within the global scope the name ?increment? is not defined. So yes, you'll get NameError from that code. > Why do I get this error? The situations look the same to me The difference is that when you invoke ?self.instance?, the lookup of ?self? succeeds because it's defined within the function (you defined it in the parameters of ?__init__?, so ?__init__? knows that name when it is running). You never defined the name ?increment? within the function, nor within the global scope. And you shouldn't because there's no need: you access the instance's own method by accessing the instance first: you ask for ?the ?instance? attribute from the ?self? object?: ?self.instance?. -- \ ?I believe our future depends powerfully on how well we | `\ understand this cosmos, in which we float like a mote of dust | _o__) in the morning sky.? ?Carl Sagan, _Cosmos_, 1980 | Ben Finney From __peter__ at web.de Wed Jul 27 04:12:22 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Jul 2016 10:12:22 +0200 Subject: [Tutor] OOP help needed References: Message-ID: Jim Byrnes wrote: > OOP has always driven me crazy. I read the material and follow the > examples until I feel I understand them, but when I try to implement it > I end up with an error filled mess. > > So I decided to give it another try. When I got to the chapter on > tkinter I decided to solve all the exercises using OOP even though the > book solutions did not use OOP. The first one went fine: No, it didn't. The Goodbye.quit() method is missing the self argument and uses the inexistent self.window attribute. You don't see these bugs when you run the script because there is a global quit()... let's say function... that is called instead of the method. You can put a print() into Goodbye.quit() to verify the above. > #exer1.py > > import tkinter > > class Goodbye: > def __init__(self): > > self.frame = tkinter.Frame(window) > self.frame.pack() > > self.goodbye_button = tkinter.Button(self.frame, text='Goodbye', > #command=quit) > command=lambda: quit() ) The lambda is superfluous -- command=quit will already invoke the global quit(). But what you actually intended is achieved with command=self.quit. self.quit is called "bound method". > self.goodbye_button.pack() > > def quit(): print("you'll never see this") > self.window.destroy() > > if __name__=='__main__': > window = tkinter.Tk() > myapp = Goodbye() > window.mainloop() From programbellworking at gmail.com Tue Jul 26 21:39:58 2016 From: programbellworking at gmail.com (kanishk srivastava) Date: Tue, 26 Jul 2016 21:39:58 -0400 Subject: [Tutor] Python Programming for the absolute beginner 3e Ch3 Challenge 1 Message-ID: Hello, I am working through Michael Dawson's book - Python Programming for absolute beginners 3e. Completed chapter 3, but unable to solve challenge 1. Below code is what I have written but unsure on how to have the program generate the message at random. Any help will be appreciated. # Fortune Cookie # Demonstrates random message generation print("\t\tFortune Cookie") print("\t\tWelcome user!") # fortune messages message1 = "the earth is a school learn in it." message2 = "be calm when confronting an emergency crisis." message3 = "you never hesitate to tackle the most difficult problems." message4 = "hard words break no bones, fine words butter no parsnips." message5 = "Make all you can, save all you can, give all you can." import random print("Your today's fortune ") input("\n\nPress the enter key to exit") Thanks Kyo From alan.gauld at yahoo.co.uk Wed Jul 27 05:04:43 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 27 Jul 2016 10:04:43 +0100 Subject: [Tutor] OOP help needed In-Reply-To: References: Message-ID: On 27/07/16 04:44, Jim Byrnes wrote: > OOP has always driven me crazy. I read the material and follow the > examples until I feel I understand them, but when I try to implement it > I end up with an error filled mess. That suggests that its not the OOP concept thats confusing you but the language syntax. How to turn the concept into code? > So I decided to give it another try. When I got to the chapter on > tkinter I decided to solve all the exercises using OOP even though the > book solutions did not use OOP. The first one went fine: Actually not as fine as you thought. In effect you got lucky by making a mistake that still resulted in your code doing approximately what you expected. But it didn't really do what you thought it did. > import tkinter > > class Goodbye: > def __init__(self): > > self.frame = tkinter.Frame(window) > self.frame.pack() You are using a global variable as your parent here. It would be better to pass that in as an argument. Or better still to make the call to Tk() inside the __init__ method. That's not really an OOP thing though just a general good practice issue. It's best to avoid relying on global variables in your functions. > self.goodbye_button = tkinter.Button(self.frame, text='Goodbye', > #command=quit) > command=lambda: quit() ) > self.goodbye_button.pack() Here you assign quit to the button's command. That's OK because there is a top level built-in function called quit which exits the interpreter. It's a bit of a brutal way to exit your GUI but it works. But I guess you really wanted to call your quit method. Remember to access anything in your class you have to use the self prefix, so you should have said: command=self.quit or command=lambda: self.quit() Lambda doesn't really help in this case but it doesn't do any harm either. > def quit(): > self.window.destroy() When you define a method inside a class you need to explicitly include the self parameter. So this should be: def quit(self): self.window.destroy() But there's a snag, you don't store the window inside the class. So self.window will cause an error. You either need a line like self.window = window in your__init__ method or use the global window variable like def quit(): window.destroy() My preference would be to create a self.window instance variable, inside init()then access the self.window in quit(). You would also call mainloop() using self.window in your init() > if __name__=='__main__': > window = tkinter.Tk() > myapp = Goodbye() > window.mainloop() So if you took my advice this section of code would look like: if __name__=='__main__': Goodbye() and init() would look like: def __init__(self): self.window = tkinter.Tk() self.frame = tkinter.Frame(self.window) self.frame.pack() self.goodbye_button = tkinter.Button(self.frame, text='Goodbye', command=self.quit) self.goodbye_button.pack() self.window.mainloop() If you read through that and understand it, it should give you the clues as to why the second one behaved as it did. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Jul 27 05:13:50 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 27 Jul 2016 10:13:50 +0100 Subject: [Tutor] Python Programming for the absolute beginner 3e Ch3 Challenge 1 In-Reply-To: References: Message-ID: On 27/07/16 02:39, kanishk srivastava wrote: > Hello, > > I am working through Michael Dawson's book - Python Programming for > absolute beginners 3e. > > Completed chapter 3, but unable to solve challenge 1. I don't know the book so don't know how much you know yet. So thee are some suggestions below that might not make sense to you because you haven't covered the material. Apologies in advance! > print("\t\tFortune Cookie") > print("\t\tWelcome user!") > > # fortune messages > message1 = "the earth is a school learn in it." > message2 = "be calm when confronting an emergency crisis." > message3 = "you never hesitate to tackle the most difficult problems." > message4 = "hard words break no bones, fine words butter no parsnips." > message5 = "Make all you can, save all you can, give all you can." Have you covered lists? Rather than a set of numbered messages you could put them in a list and access each message by index: messages = ["the earth is a school learn in it.", "be calm when confronting an emergency crisis.", "you never hesitate to tackle the most difficult problems.", "hard words break no bones, fine words butter no parsnips.", "Make all you can, save all you can, give all you can." ] And access them with messages[0], messages[1], ... messages[4] Although in this case you don't even need to do that, read on... > import random I don't know how many of the random module functions you cover but there are a lot of them. One of them, random.choice(aList), selects a random item from a list. So now that you have a list of messages it becomes trivial to select a random message from the list: > print("Your today's fortune ") use print(random.choice(messages)) here hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From jf_byrnes at comcast.net Wed Jul 27 14:19:47 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 27 Jul 2016 13:19:47 -0500 Subject: [Tutor] OOP help needed In-Reply-To: <85lh0npufb.fsf@benfinney.id.au> References: <85lh0npufb.fsf@benfinney.id.au> Message-ID: On 07/26/2016 11:38 PM, Ben Finney wrote: > Jim Byrnes writes: > >> So I decided to give it another try. When I got to the chapter on >> tkinter I decided to solve all the exercises using OOP even though the >> book solutions did not use OOP. > > Hmm, that sounds ill advised. > > OOP is one tool among many; trying to apply it where it's a poor fit > will result in bad design and probably avoidable errors. > > When learning to use a hacksaw, trying to solve everything using that > tool merely to learn it, would be a poor choice. With anything more complex I would agree. I am simply trying to get myself thinking about how OOP works and there aren't enough exercises in the book calling for OOP to give me much repetition. >> # exer2.py >> >> import tkinter >> >> class Count: >> >> def __init__(self): >> ''' Increment a button labeled 0, by 1 with each click ''' >> [?] >> self.count_btn = tkinter.Button(self.frame, textvariable=self.label, >> command=lambda: self.increment(self.label )) > > Here you address the ?self.increment? name, which should work. > >> def increment(self, label): >> count = int(self.label.get()) >> self.label.set(str(count + 1)) > > This is the method that an instance will address via ?self.increment?. > >> In exer2.py if I do command=lambda: increment(self.label) > > The lambda expression creates a function, and that function then behaves > like any other function. Within that function, the name ?increment? is > not defined; within the scope where the function was defined, the name > ?increment? is also not defined. Within the global scope the name > ?increment? is not defined. > > So yes, you'll get NameError from that code. > >> Why do I get this error? The situations look the same to me > > The difference is that when you invoke ?self.instance?, the lookup of > ?self? succeeds because it's defined within the function (you defined it > in the parameters of ?__init__?, so ?__init__? knows that name when it > is running). > > You never defined the name ?increment? within the function, nor within > the global scope. And you shouldn't because there's no need: you access > the instance's own method by accessing the instance first: you ask for > ?the ?instance? attribute from the ?self? object?: ?self.instance?. > OK thank you. Regards, Jim From jf_byrnes at comcast.net Wed Jul 27 14:25:18 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 27 Jul 2016 13:25:18 -0500 Subject: [Tutor] OOP help needed In-Reply-To: References: Message-ID: On 07/27/2016 03:12 AM, Peter Otten wrote: > Jim Byrnes wrote: > >> OOP has always driven me crazy. I read the material and follow the >> examples until I feel I understand them, but when I try to implement it >> I end up with an error filled mess. >> >> So I decided to give it another try. When I got to the chapter on >> tkinter I decided to solve all the exercises using OOP even though the >> book solutions did not use OOP. The first one went fine: > > No, it didn't. The Goodbye.quit() method is missing the self argument and > uses the inexistent self.window attribute. > You don't see these bugs when you run the script because there is a global > quit()... let's say function... that is called instead of the method. > > You can put a print() into Goodbye.quit() to verify the above. OK right. I ended up concentrating on exer2 when the problem was in exer1. I should have known better than using quit() as a name. >> #exer1.py >> >> import tkinter >> >> class Goodbye: >> def __init__(self): >> >> self.frame = tkinter.Frame(window) >> self.frame.pack() >> >> self.goodbye_button = tkinter.Button(self.frame, text='Goodbye', >> #command=quit) >> command=lambda: quit() ) > > The lambda is superfluous -- command=quit will already invoke the global > quit(). But what you actually intended is achieved with command=self.quit. > self.quit is called "bound method". Ok, thanks. >> self.goodbye_button.pack() >> >> def quit(): > print("you'll never see this") >> self.window.destroy() >> >> if __name__=='__main__': >> window = tkinter.Tk() >> myapp = Goodbye() >> window.mainloop() > Regards, Jim From jf_byrnes at comcast.net Wed Jul 27 14:38:59 2016 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 27 Jul 2016 13:38:59 -0500 Subject: [Tutor] OOP help needed In-Reply-To: References: Message-ID: On 07/27/2016 04:04 AM, Alan Gauld via Tutor wrote: > On 27/07/16 04:44, Jim Byrnes wrote: >> OOP has always driven me crazy. I read the material and follow the >> examples until I feel I understand them, but when I try to implement it >> I end up with an error filled mess. > > That suggests that its not the OOP concept thats confusing > you but the language syntax. How to turn the concept into code? That's exactly my problem, which is why I am solving problems with OOP when it's not necessary. I wanted the practice. >> So I decided to give it another try. When I got to the chapter on >> tkinter I decided to solve all the exercises using OOP even though the >> book solutions did not use OOP. The first one went fine: > > Actually not as fine as you thought. In effect you got lucky by > making a mistake that still resulted in your code doing > approximately what you expected. But it didn't really do > what you thought it did. > >> import tkinter >> >> class Goodbye: >> def __init__(self): >> >> self.frame = tkinter.Frame(window) >> self.frame.pack() > > You are using a global variable as your parent here. It would be > better to pass that in as an argument. Or better still to make > the call to Tk() inside the __init__ method. That's not really > an OOP thing though just a general good practice issue. > It's best to avoid relying on global variables in your > functions. Ok thanks. When I wrote that I was mimicking the style used in the book. I have read about avoiding globals if possible, but didn't think it through. >> self.goodbye_button = tkinter.Button(self.frame, text='Goodbye', >> #command=quit) >> command=lambda: quit() ) >> self.goodbye_button.pack() > > Here you assign quit to the button's command. That's OK because > there is a top level built-in function called quit which exits > the interpreter. It's a bit of a brutal way to exit your GUI > but it works. > > But I guess you really wanted to call your quit method. Remember > to access anything in your class you have to use the self > prefix, so you should have said: > > command=self.quit > > or > > command=lambda: self.quit() > > Lambda doesn't really help in this case but it doesn't do > any harm either. > >> def quit(): >> self.window.destroy() > > When you define a method inside a class you need to > explicitly include the self parameter. So this should be: > > def quit(self): > self.window.destroy() > > But there's a snag, you don't store the window inside the > class. So self.window will cause an error. You either need > a line like > > self.window = window > > in your__init__ method > > or use the global window variable like > > def quit(): > window.destroy() > > My preference would be to create a self.window instance variable, > inside init()then access the self.window in quit(). You would also > call mainloop() using self.window in your init() > >> if __name__=='__main__': >> window = tkinter.Tk() >> myapp = Goodbye() >> window.mainloop() > > So if you took my advice this section of code would look like: > > if __name__=='__main__': > Goodbye() > > > and init() would look like: > > def __init__(self): > self.window = tkinter.Tk() > self.frame = tkinter.Frame(self.window) > self.frame.pack() > > self.goodbye_button = tkinter.Button(self.frame, text='Goodbye', > command=self.quit) > self.goodbye_button.pack() > > self.window.mainloop() > > If you read through that and understand it, it should give > you the clues as to why the second one behaved as it did. > > Ok thanks. I don't want to belabor the point but I basically had it that way because I didn't know any better. Now I know of a different/better way to do it. Regards, Jim From dyoo at hashcollision.org Thu Jul 28 00:30:18 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 27 Jul 2016 21:30:18 -0700 Subject: [Tutor] python programmin problem In-Reply-To: <20160724.163040.26810.0@webmail13.dca.untd.com> References: <20160724.163040.26810.0@webmail13.dca.untd.com> Message-ID: On Sun, Jul 24, 2016 at 4:30 PM, monikajg at netzero.net wrote: > Thank you all for your answers. I do not have a teacher or any body else who could guide me. I have taken all python classes offered in my area and many on line. > The question is one of questions asked by interviews for a qa position that also does some automation with python. If you're training for problems like this, then look for something less focused on a specific programming language. As we said earlier, solving these kinds of problems isn't really a matter of Python programming at this level: you want to look specifically for material about algorithms. For this kind of thing, definitely look into something like the "Develop a strong understanding of algorithms and data structures" recommendations at: https://www.google.com/about/careers/students/guide-to-technical-development.html I've also heard very good things about Skiena's "The Algorithm Design Manual": http://www.algorist.com/ The author has a bunch of videos and lecture material online that might help you: http://www3.cs.stonybrook.edu/~algorith/video-lectures/ In particular, see Lectures 18 and 19. *Especially Lecture 19*. You will see a problem being explained that you should be *very* interested in. :) Here's a link just to give you a taste: https://youtu.be/0yjebrZXJ9A?t=3m I hope that this helps point you in the right direction. Good luck! From dyoo at hashcollision.org Thu Jul 28 00:42:25 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 27 Jul 2016 21:42:25 -0700 Subject: [Tutor] python programmin problem In-Reply-To: References: <20160724.163040.26810.0@webmail13.dca.untd.com> Message-ID: > You will see a problem being explained that you should be *very* > interested in. :) Here's a link just to give you a taste: > > https://youtu.be/0yjebrZXJ9A?t=3m > > > I hope that this helps point you in the right direction. Good luck! He has some more recent videos from 2012: https://youtu.be/Qc2ieXRgR0k?list=PLOtl7M3yp-DV69F32zdK7YJcNXpTunF2b where he again goes over the familiar example in: https://youtu.be/o0V9eYF4UI8?t=34m52s From monikajg at netzero.net Thu Jul 28 00:53:01 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Thu, 28 Jul 2016 04:53:01 GMT Subject: [Tutor] python programmin problem Message-ID: <20160727.215301.641.0@webmail01.dca.untd.com> Thank you very much. I will look into your suggestions. I have been looking for tutorials but could not find anything at my level of understanding. You said to not focus on python but I had a python teacher (a famous python book writer and a friend of Guido) was stressing on doing things in "pythonic" way. Thank you for the links and I will check/read each one of them. Monika ---------- Original Message ---------- From: Danny Yoo To: "monikajg at netzero.net" Cc: Alan Gauld , Python Tutor Mailing List Subject: Re: [Tutor] python programmin problem Date: Wed, 27 Jul 2016 21:42:25 -0700 > You will see a problem being explained that you should be *very* > interested in. :) Here's a link just to give you a taste: > > https://youtu.be/0yjebrZXJ9A?t=3m > > > I hope that this helps point you in the right direction. Good luck! He has some more recent videos from 2012: https://youtu.be/Qc2ieXRgR0k?list=PLOtl7M3yp-DV69F32zdK7YJcNXpTunF2b where he again goes over the familiar example in: https://youtu.be/o0V9eYF4UI8?t=34m52s _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ Affordable Wireless Plans Set up is easy. Get online in minutes. Starting at only $9.95 per month! www.netzero.net?refcd=nzmem0216 From alan.gauld at yahoo.co.uk Thu Jul 28 05:01:49 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 28 Jul 2016 10:01:49 +0100 Subject: [Tutor] python programmin problem In-Reply-To: <20160727.215301.641.0@webmail01.dca.untd.com> References: <20160727.215301.641.0@webmail01.dca.untd.com> Message-ID: On 28/07/16 05:53, monikajg at netzero.net wrote: > I have been looking for tutorials but could not find anything > at my level of understanding. You said to not focus on python > but I had a python teacher ... stressing on doing things in > "pythonic" way. When learning to program there are two aspects to be considered. There are the generic "software engineering" skills that apply to any language. These are concerned with things like data structures, algorithms, architecture and so on. Then there are the programming languages which each have their own ways of doing things. They all do the same basic operations (sequences, loops, branches, modules) but they all do it slightly differently. Then on top of the basic syntax they also have their own idioms - the standard practices developed by that language community. The language style if you like. The software 3engineering bit only needs to be learned once. Whereas the language stuff is re-learned for each language. But you need the software engineering background before you start worrying about the details of a particular language and that's the bit that you seem to be weaker on just now. So Danny's advice to focus on algorithm development is part of the generic skills you need to be a good programmer in any language. Your teacher's advice is about learning the specifics of Python. You need to do both eventually but you should probably focus initially on the more generic aspects. Once you know how to solve the problems then you can worry about expressing that solution in any particular language. This list can help you with both aspects. Just ask when you have a question. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From darahpereira at yahoo.com Fri Jul 29 00:24:02 2016 From: darahpereira at yahoo.com (Darah) Date: Thu, 28 Jul 2016 21:24:02 -0700 Subject: [Tutor] IDLE Subprocess Startup Error Message-ID: Hello, I?ve been using Python?s IDLE for a couple of weeks now and it has been working fine but a few days ago I started getting this error message "IDLE's subprocess didn't make connection. Either IDLE can't start a subprocess or personal firewall software is blocking the connection.? I tried uninstalling it, restarting my computer, found a couple of people that said deleting the created .py files worked for them but it did not for me. I am not sure what else to do. Do you have any suggestions? I am using OS X El Capitan 10.11.5 on mac Regards, Darah Pereira From alan.gauld at yahoo.co.uk Fri Jul 29 03:18:11 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 29 Jul 2016 08:18:11 +0100 Subject: [Tutor] IDLE Subprocess Startup Error In-Reply-To: References: Message-ID: On 29/07/16 05:24, Darah via Tutor wrote: > I?ve been using Python?s IDLE for a couple of weeks now and > it has been working fine but a few days ago I started getting > this error message > "IDLE's subprocess didn't make connection. > Either IDLE can't start a subprocess or personal firewall > software is blocking the connection.? What version of IDLE are you using? That used to be a common error message but since Python v2.6 I've never had it. If its an older version than that you could try upgrading your Python version. Other than that there is a dedicated IDLE mailing list which is quite responsive and should be able to help if you don't get an answer here. The gmane link is: gmane.comp.python.idle hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From crusier at gmail.com Fri Jul 29 03:28:25 2016 From: crusier at gmail.com (Crusier) Date: Fri, 29 Jul 2016 15:28:25 +0800 Subject: [Tutor] Unable to download , using Beautifulsoup Message-ID: I am using Python 3 on Windows 7. However, I am unable to download some of the data listed in the web site as follows: http://data.tsci.com.cn/stock/00939/STK_Broker.htm 453.IMC 98.28M 18.44M 4.32 5.33 1499.Optiver 70.91M 13.29M 3.12 5.34 7387.???? 52.72M 9.84M 2.32 5.36 When I use Google Chrome and use 'View Page Source', the data does not show up at all. However, when I use 'Inspect', I can able to read the data. '1453.IMC' '98.28M' '18.44M' '4.32' '5.33' '1499.Optiver ' ' 70.91M' '13.29M ' '3.12' '5.34' Please kindly explain to me if the data is hide in CSS Style sheet or is there any way to retrieve the data listed. Thank you Regards, Crusier from bs4 import BeautifulSoup import urllib import requests stock_code = ('00939', '0001') def web_scraper(stock_code): broker_url = 'http://data.tsci.com.cn/stock/' end_url = '/STK_Broker.htm' for code in stock_code: new_url = broker_url + code + end_url response = requests.get(new_url) html = response.content soup = BeautifulSoup(html, "html.parser") Buylist = soup.find_all('div', id ="BuyingSeats") Selllist = soup.find_all('div', id ="SellSeats") print(Buylist) print(Selllist) web_scraper(stock_code) From alan.gauld at yahoo.co.uk Fri Jul 29 11:46:19 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 29 Jul 2016 16:46:19 +0100 Subject: [Tutor] Unable to download , using Beautifulsoup In-Reply-To: References: Message-ID: On 29/07/16 08:28, Crusier wrote: > When I use Google Chrome and use 'View Page Source', the data does not > show up at all. However, when I use 'Inspect', I can able to read the > data. > > '1453.IMC' > '98.28M' > '3.12' > '5.34' > > Please kindly explain to me if the data is hide in CSS Style sheet or > is there any way to retrieve the data listed. I don;t know the answer but I would suggest that if you print out (or send to a file) the entire html source returned by the server you can see what is actually happening and from that perhaps figure out what to do with BS to extract what you need. > from bs4 import BeautifulSoup > import urllib > import requests > > stock_code = ('00939', '0001') > > def web_scraper(stock_code): > > broker_url = 'http://data.tsci.com.cn/stock/' > end_url = '/STK_Broker.htm' > > for code in stock_code: > new_url = broker_url + code + end_url > response = requests.get(new_url) > html = response.content Try sending html to a file and examining it in a text editor... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From wprins at gmail.com Fri Jul 29 17:23:54 2016 From: wprins at gmail.com (Walter Prins) Date: Fri, 29 Jul 2016 22:23:54 +0100 Subject: [Tutor] Unable to download , using Beautifulsoup In-Reply-To: References: Message-ID: Hi On 29 July 2016 at 08:28, Crusier wrote: > I am using Python 3 on Windows 7. > > When I use Google Chrome and use 'View Page Source', the data does not > show up at all. However, when I use 'Inspect', I can able to read the > data. > > Please kindly explain to me if the data is hide in CSS Style sheet or > is there any way to retrieve the data listed. > Using inspect is not the same as view source. The inspect tools will give you the DOM tree as it currently is in the browser. That tree may have been modified by any number of things (e.g. likely Javascript) since the initial page source was loaded. It is likely that the data you're trying to get at, is fetched dynamically after the initial page source is fetched, which is why you don't see it when using "view source." As an experiment you can temporarily disable your browser's Javascript engine and reload the webpage. You should then find that you can't see the data you're after at all, even with inspect, if this is what's occurring. (To do this for Chrome, see here: https://productforums.google.com/forum/#!topic/chrome/BYOQskiuGU0) So, if this is what's going on then this presents you with a bit of a problem. Obviously the Python "requests" module is not a full browser and does not include a Javascript runtime, so it cannot by itself yield the same result as a real browser, if the page content is in fact the result of dynamic population by Javascript after loading the initial HTML page source. In order to get around this you would therefore need to fundamentally have a browser of some kind that you can control, and that includes a Javascript runtime that can effectively process and construct the DOM (and render the page image if you so desire) before you retrieve the data you're after. It should be possible to do this, there are projects and questions on the internet about this. Firstly there's a project named "Selenium" that provides a way of automating various browsers, and has Python bindings (I used this some years ago). So you could conceivably use Python+Selenium+(Chrome or Firefox say) for example to fetch the page and then get the data out. This has the disadvantage that there's going to be a real browser and browser window floating around. A slightly better alternative would be to use a "headless" (displayless) browser, such as PhantomJS. It is basically the browser engine with lots of ways to control and automate it. It does not (to my knowledge) include Python bindings directly, but Selenium includes a PhantomJS driver (I think.) There's lighter weight options like "jsdom" and "slimerjs", but I have no idea whether these would suffice or not or whether they would have Python wrappers or not. Perhaps the best option might be Ghost.py, which sounds like it might be exactly what you need, but I have no experience with it. So, I'm afraid to achieve what you want will require a rather more complicated solution than what you've currently got. :( Nevertheless, here's some links for you: Ghost.py: http://jeanphix.me/Ghost.py/ http://ghost-py.readthedocs.io/en/latest/# PhantomJS: http://phantomjs.org/ PhantomJS & Python: http://stackoverflow.com/questions/13287490/is-there-a-way-to-use-phantomjs-in-python http://toddhayton.com/2015/02/03/scraping-with-python-selenium-and-phantomjs/ SlimerJS: http://docs.slimerjs.org/0.9/quick-start.html I also while answering this question stumbled over the following page listing (supposedly) almost every headless browser or framework in existence: https://github.com/dhamaniasad/HeadlessBrowsers I see there's a couple of other possible options on there, but I'll leave it up to you to investigate. Good luck, Walter From badouglas at gmail.com Fri Jul 29 18:10:04 2016 From: badouglas at gmail.com (bruce) Date: Fri, 29 Jul 2016 18:10:04 -0400 Subject: [Tutor] Unable to download , using Beautifulsoup In-Reply-To: References: Message-ID: In following up/on what Walter said. If the browser without cookies/javascript enabled doesn't generate the content, you need to have a different approach. The most "complete" is the use of a headless browser. However, the use/implementation of a headless browser has its' own share of issues. Speed, complexity, etc... A potentially better/useful method is to view/look at the traffic (livehttpheaders for Firefox) to get a feel for exactly what the browser requires. At the same time, view the subordinate jscript functions. I've found it's often enough to craft the requisite cookies/curl functions in order to simulate the browser data. In a few cases though, I've run across situations where a headless browser is the only real soln. On Fri, Jul 29, 2016 at 3:28 AM, Crusier wrote: > I am using Python 3 on Windows 7. > > However, I am unable to download some of the data listed in the web > site as follows: > > http://data.tsci.com.cn/stock/00939/STK_Broker.htm > > 453.IMC 98.28M 18.44M 4.32 5.33 1499.Optiver 70.91M 13.29M 3.12 5.34 > 7387.???? 52.72M 9.84M 2.32 5.36 > > When I use Google Chrome and use 'View Page Source', the data does not > show up at all. However, when I use 'Inspect', I can able to read the > data. > > '1453.IMC' > '98.28M' > '18.44M' > '4.32' > '5.33' > > '1499.Optiver ' > ' 70.91M' > '13.29M ' > '3.12' > '5.34' > > Please kindly explain to me if the data is hide in CSS Style sheet or > is there any way to retrieve the data listed. > > Thank you > > Regards, Crusier > > from bs4 import BeautifulSoup > import urllib > import requests > > > > > stock_code = ('00939', '0001') > > def web_scraper(stock_code): > > broker_url = 'http://data.tsci.com.cn/stock/' > end_url = '/STK_Broker.htm' > > for code in stock_code: > > new_url = broker_url + code + end_url > response = requests.get(new_url) > html = response.content > soup = BeautifulSoup(html, "html.parser") > Buylist = soup.find_all('div', id ="BuyingSeats") > Selllist = soup.find_all('div', id ="SellSeats") > > > print(Buylist) > print(Selllist) > > > > web_scraper(stock_code) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Fri Jul 29 18:59:53 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 29 Jul 2016 23:59:53 +0100 Subject: [Tutor] Unable to download , using Beautifulsoup In-Reply-To: References: Message-ID: On 29/07/16 23:10, bruce wrote: > The most "complete" is the use of a headless browser. However, the > use/implementation of a headless browser has its' own share of issues. > Speed, complexity, etc... Walter and Bruce have jumped ahead a few steps from where I was heading but basically it's an increasingly common scenario where web pages are no longer primarily html but rather are Javascript programs that fetch data dynamically. A headless browser is the brute force way to deal with such issues but a better (purer?) way is to access the same API that the browser is using. Many web sites now publish RESTful APIs with web services that you can call directly. It is worth investigating whether your target has this. If so that will generally provide a much nicer solution than trying to drive a headless browser. Finally you need to consider whether you have the right to the data without running a browser? Many sites provide information for free but get paid by adverts. If you bypass the web screen (adverts) you bypass their revenue and they do not allow that. So you need to be sure that you are legally entitled to scrape data from the site or use an API. Otherwise you may be on the wrong end of a law suite, or at best be contributing to the demise of the very site you are trying to use. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From badouglas at gmail.com Fri Jul 29 20:32:40 2016 From: badouglas at gmail.com (bruce) Date: Fri, 29 Jul 2016 20:32:40 -0400 Subject: [Tutor] Unable to download , using Beautifulsoup In-Reply-To: References: Message-ID: Hey Alan... Wow APIs.. yeah.. would be cool!!! I've worked on scraping data from lots of public sites, that have no issue (as long as you're kind) that have no clue/resource regarding offerning APIs. However, yeah, if you''re looking to "rip" off a site that has adverts, prob not a cool thing to do, no matter what tools are used. On Fri, Jul 29, 2016 at 6:59 PM, Alan Gauld via Tutor wrote: > On 29/07/16 23:10, bruce wrote: > > > The most "complete" is the use of a headless browser. However, the > > use/implementation of a headless browser has its' own share of issues. > > Speed, complexity, etc... > > Walter and Bruce have jumped ahead a few steps from where I was > heading but basically it's an increasingly common scenario where > web pages are no longer primarily html but rather are > Javascript programs that fetch data dynamically. > > A headless browser is the brute force way to deal with such issues > but a better (purer?) way is to access the same API that the browser > is using. Many web sites now publish RESTful APIs with web > services that you can call directly. It is worth investigating > whether your target has this. If so that will generally provide > a much nicer solution than trying to drive a headless browser. > > Finally you need to consider whether you have the right to the > data without running a browser? Many sites provide information > for free but get paid by adverts. If you bypass the web screen > (adverts) you bypass their revenue and they do not allow that. > So you need to be sure that you are legally entitled to scrape > data from the site or use an API. > > Otherwise you may be on the wrong end of a law suite, or at > best be contributing to the demise of the very site you are > trying to use. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From jkornonthecob at yahoo.com Sat Jul 30 00:31:03 2016 From: jkornonthecob at yahoo.com (Justin Korn) Date: Sat, 30 Jul 2016 00:31:03 -0400 Subject: [Tutor] Help on Assginments Message-ID: <24B4556D-A3BE-4AE5-BFE6-17DD86FE242A@yahoo.com> To whom it may concern, I need someone to help me to develop programs for the following assignments: 1. Define a new kind of Turtle, TurtleGTX, that comes with some extra features: it can jump forward a given distance, and it has an odometer that keeps track of how far the turtle has travelled since it came off the production line. (The parent class has a number of synonyms like fd, forward, back, backward, and bk: for this exercise, just focus on putting this functionality into the forward method.) Think carefully about how to count the distance if the turtle is asked to move forward by a negative amount. (We would not want to buy a second-hand turtle whose odometer reading was faked because its previous owner drove it backwards around the block too often. Try this in a car near you, and see if the car?s odometer counts up or down when you reverse.) 2. You are to develop a program (name it trivia_game.py) that will play a trivia game with two players. The game will be played this way: Starting with player 1, each player gets a turn at answering 5 trivia questions. When a question is displayed, 4 possible answers are also displayed (1 of the 4 is the correct answer). A correct answer earns the player 1 point. After both players have answered their 5 questions the program will display the number of points earned by each player and declare the player with the most points the winner (or a tie if both players have earned the same number of points). You must write a class (name it Question.py) to hold the data for a trivia question. The class should have the following attributes: A trivia question Possible answer 1 Possible answer 2 Possible answer 3 Possible answer 4 The number of the correct answer (1, 2, 3, or 4) The Question class should have an appropriate __init__ method, accessors and mutators. Your program should have a list or dictionary containing 10 Question objects, one for each trivia question. You are to make up your own trivia questions. Submit both files (zip the two files if possible). Our final exam is a real world problem about efficiency in a warehouse. 3. XYZ Corporation sells products online. The company has a large warehouse in which it stores its inventory of products. Orders are picked, packed and shipped from the warehouse. XYZ Corporation has contracted with you to write a program that will minimize the number of steps that the staff in the warehouse (called ODA's) take in picking the products ordered by customers. The information you will need to complete this assignment are in the following files: Specifications: CTIM285_Summer_2016_FinalExam.pdf Warehouse Map: WarehouseImage.pdf Data for Analysis: warehouse_data_final_exam_Python.txt Data for Analysis is saved in this order on each line of the file: [orderNumber, partNumber, quantyNumber, aisleNumber, shelfNumber, binNumber] Thanks, Justin From michael.selik at gmail.com Fri Jul 29 22:58:47 2016 From: michael.selik at gmail.com (Michael Selik) Date: Sat, 30 Jul 2016 02:58:47 +0000 Subject: [Tutor] IDLE Subprocess Startup Error In-Reply-To: References: Message-ID: On Fri, Jul 29, 2016, 2:11 AM Darah via Tutor wrote: > "IDLE's subprocess didn't make connection. Either IDLE can't start a > subprocess or personal firewall software is blocking the connection.? > In the last few days, have you installed any other software? Perhaps something has changed your firewall settings. > From alan.gauld at yahoo.co.uk Sat Jul 30 04:07:57 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 30 Jul 2016 09:07:57 +0100 Subject: [Tutor] Help on Assginments In-Reply-To: <24B4556D-A3BE-4AE5-BFE6-17DD86FE242A@yahoo.com> References: <24B4556D-A3BE-4AE5-BFE6-17DD86FE242A@yahoo.com> Message-ID: On 30/07/16 05:31, Justin Korn via Tutor wrote: > ...I need someone to help me to develop programs for the following assignments: That's not really how tutor list works. We will answer your questions and give you hints when you get stuck. But it is the whole list membership helping you, not a designated "someone". As to your projects here's what I'd recommend. 1) Tackle them one by one, it keeps the email threads separate and the archives easier to search. 2) Make a start, write some code. When you get stuck or something doesn't work as expected, ask here. 3) Always remind us of which OS and Python version you are using 4) If there are error messages send the whole error text not a summary. > 1. Define a new kind of Turtle, ... This one slightly confused me since the standard turtle can already jump forward a given distance. The only new feature appears to be the odometer concept? > 2. You are to develop a program (name it trivia_game.py) that > will play a trivia game with two players. ... > You must write a class (name it Question.py) to hold the data This seems straightforward but a tad tedious creating the data. It would have been nice if they provided a data file! > Our final exam is a real world problem about efficiency in a warehouse. Slightly more challenging but nothing too difficult provided you can do the math and the document provided is sufficiently clear. Based on the questions I assume you have a reasonably good understanding of Python basics including the data structures, functions, classes and objects, files, and how to import and use modules? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From jkornonthecob at yahoo.com Sat Jul 30 11:28:28 2016 From: jkornonthecob at yahoo.com (Justin Korn) Date: Sat, 30 Jul 2016 11:28:28 -0400 Subject: [Tutor] Help on Assignments Message-ID: <663CEC8A-2333-4600-AFA8-E252CAB3DF6F@yahoo.com> To whom it may concern, I need someone to help me to develop programs for the following assignments. I have been working on these assignments for a week and a half, and I can't make any progress. I also been dealing with a sick relative, so please help me out immediately. I use the version 3.4.1. Here are the following assignments and what I have so far: 1. Define a new kind of Turtle, TurtleGTX, that comes with some extra features: it can jump forward a given distance, and it has an odometer that keeps track of how far the turtle has travelled since it came off the production line. (The parent class has a number of synonyms like fd, forward, back, backward, and bk: for this exercise, just focus on putting this functionality into the forward method.) Think carefully about how to count the distance if the turtle is asked to move forward by a negative amount. (We would not want to buy a second-hand turtle whose odometer reading was faked because its previous owner drove it backwards around the block too often. Try this in a car near you, and see if the car?s odometer counts up or down when you reverse.) import turtle class turtle_Turtle(): ts = turtle.Screen() ts.title("TurtleGTX") bob = turtle.Turtle() bob.shape("turtle") bob.color("brown") class TurtleGTX(turtle_Turtle): odometer = 0 def forward(x): if (x >= 0): i = 0 while (i < x): self.fd() odometer += 1 i+=1 else: i = 0 while (i > x): self.bk() odometer +=1 i-=1 print ("Odometer is", odemeter) my_turtle = TurtleGTX() my_turtle.foward() 2. You are to develop a program (name it trivia_game.py) that will play a trivia game with two players. The game will be played this way: Starting with player 1, each player gets a turn at answering 5 trivia questions. When a question is displayed, 4 possible answers are also displayed (1 of the 4 is the correct answer). A correct answer earns the player 1 point. After both players have answered their 5 questions the program will display the number of points earned by each player and declare the player with the most points the winner (or a tie if both players have earned the same number of points). You must write a class (name it Question.py) to hold the data for a trivia question. The class should have the following attributes: A trivia question Possible answer 1 Possible answer 2 Possible answer 3 Possible answer 4 The number of the correct answer (1, 2, 3, or 4) The Question class should have an appropriate __init__ method, accessors and mutators. Your program should have a list or dictionary containing 10 Question objects, one for each trivia question. You are to make up your own trivia questions. Submit both files (zip the two files if possible). trivia_game.py import sys import random import Question.py questions = [ Question("How many states start with the letter M", 3, ["6", "7", "8", "9"]), Question("What is the area of a right triagle with a hypotenuse of 10 and an altitude of 8", 1, ["24", "40", "48", "80"]), Question("Which physics quantity is not a vector", 4, ["Acceleration", "Momentum", "Torque", "Work"]), Question("How many inches are in a foot", 2, ["6", "12", "18", "24"]), Question("Who does not play in the NFL anymore", 3, ["Frank Gore", "Richard Sherman", "Peyton Manning", "Antonio Gates"]), Question("What is a bakers dozen equivalent to", 4, ["10", "11", "12", "13"]), Question("Which city has a NBA team", 1, ["Sacramento", "Baltimore", "St. Louis", "Pittsburgh"]), Question("Which of the following elements have eleven protons", 4, ["boron", "sulfur", "floruine", "sodium"]), Question("What is the minimum age to run for president of the United States", 2, ["30", "35", "40", "45"]), Question("Who won super bowl 44", 1, ["New Orleans Saints", "Pittsburgh Steelers", "Minnesota Vikings", "Indianapolis Colts"]) ] random.shuffle(questions) # Randomize the order of the questions for question in questions: question.ask() Question.py 3. Our final exam is a real world problem about efficiency in a warehouse. XYZ Corporation sells products online. The company has a large warehouse in which it stores its inventory of products. Orders are picked, packed and shipped from the warehouse. XYZ Corporation has contracted with you to write a program that will minimize the number of steps that the staff in the warehouse (called ODA's) take in picking the products ordered by customers. The information you will need to complete this assignment are in the following files: Specifications: CTIM285_Summer_2016_FinalExam.pdf Warehouse Map: WarehouseImage.pdf Data for Analysis: warehouse_data_final_exam_Python.txt Data for Analysis is saved in this order on each line of the file: [orderNumber, partNumber, quantyNumber, aisleNumber, shelfNumber, binNumber] infile = open("warehouse_data.txt", "r") for x in infile for j in range(3, 6): if (j == 1): temp=a[0:3] a[0:3]=a[3:] a[3:]=temp Thanks, Justin From alan.gauld at yahoo.co.uk Sat Jul 30 19:03:42 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 31 Jul 2016 00:03:42 +0100 Subject: [Tutor] Help on Assignments - Turtle In-Reply-To: <663CEC8A-2333-4600-AFA8-E252CAB3DF6F@yahoo.com> References: <663CEC8A-2333-4600-AFA8-E252CAB3DF6F@yahoo.com> Message-ID: On 30/07/16 16:28, Justin Korn via Tutor wrote: > I have been working on these assignments for a week and a half, > and I can't make any progress. I also been dealing with a > sick relative, so please help me out immediately. While I sympathise with your circumstances we are all volunteers here so the help you receive will be at the speed that suits the members. I will address your two assignments in separate mails. > import turtle > class turtle_Turtle(): > ts = turtle.Screen() > ts.title("TurtleGTX") > bob = turtle.Turtle() > bob.shape("turtle") > bob.color("brown") I'm not sure what you think this is doing but I'm pretty sure its not what you want. You are basically defining a couple of class variables and nothing else... > class TurtleGTX(turtle_Turtle): I would have expected you to inherit from turtle.Turtle rather than turtle_Turtle. The latter has no methods and only two class variables. So your GTX class likewise has no inherited methods, you will need to define all of its behaviour. > odometer = 0 This is a class variable meaning it is shared by all turtles. I suspect you really want it to be an instance attribute, which means defined within an __init__() > def forward(x): The first parameter of a class method is usually called self because it will refer to the active object. In this case your x will be the object, whereas I think you want it to be the distance to move? But if so x is a bad choice of name since it implies horizontal direction only > if (x >= 0): > i = 0 > while (i < x): > self.fd() > odometer += 1 > i+=1 This is a horribly inefficient way of saying if x>=0: self.fd(x) odometer += x But it won't work because a) You didn't inherit from turtle so you don't have a fd() method b) Even if you had it requires an input value for its distance so should be self.fd(1) > else: > i = 0 > while (i > x): > self.bk() > odometer +=1 > i-=1 Again a very inefficient alternative to else: x = -x self.bk(x) odometer += x > print ("Odometer is", odemeter) Do you really want to print that every time the turtle moves? > my_turtle = TurtleGTX() > my_turtle.foward() You misspelled forward and failed to give it an x value. Please send real code and/or any error messages. This code could never have run so you should have errors. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Sat Jul 30 19:11:40 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 31 Jul 2016 00:11:40 +0100 Subject: [Tutor] Help on Assignments - trivia game In-Reply-To: <663CEC8A-2333-4600-AFA8-E252CAB3DF6F@yahoo.com> References: <663CEC8A-2333-4600-AFA8-E252CAB3DF6F@yahoo.com> Message-ID: On 30/07/16 16:28, Justin Korn via Tutor wrote: > trivia_game.py > import sys > import random > import Question.py You do not include the .py extension in an import statement. It should read import Question Also by convention modules use lowercase names. > questions = [ > Question("How many states start with the letter M", 3, ["6", "7", "8", "9"]), You are trying to instantiate a Question object but it is (presumably) defined in the question.py class which you import. If so you need to prefix it with the module name like so Question.Question(...) > Question("What is the area of a right triagle with a hypotenuse of 10 and an altitude of 8", 1, ["24", "40", "48", "80"]), > Question("Which physics quantity is not a vector", 4, ["Acceleration", "Momentum", "Torque", "Work"]), List indices start from zero so your highest index should be 3. Assuming you intend to use the '4' as an index to the correct answer? > Question("Who won super bowl 44", 1, ["New Orleans Saints", "Pittsburgh Steelers", "Minnesota Vikings", "Indianapolis Colts"]) > ] > > > random.shuffle(questions) # Randomize the order of the questions > > for question in questions: > question.ask() > > Question.py ??? I'm expecting a class definition here with at least __init__() and ask() methods. And it needs to store the question, possible answers and correct answer somewhere too? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From fiberfolly at gmail.com Sun Jul 31 19:14:59 2016 From: fiberfolly at gmail.com (D Wyatt) Date: Sun, 31 Jul 2016 16:14:59 -0700 Subject: [Tutor] Book recommendation Message-ID: Hello. I've been a member of this group for a very long time and have played with Python for years, but have never gotten past being a beginner for various reasons. I just discovered a very good, free book, that is answering many of the questions I have had in the past that I never got answers I could understand from you all. While I appreciate the time and effort you put in helping us out, most of you do not remember what you didn't used to know, and are often less than helpful because of this. This is not meant as a criticism, but just my observation. Anyway, this book I found, Learning Python, is well-written and easy to understand. Here is a url to it. https://www.packtpub.com/tech/python. no affiliation, etc, I just wanted to share this great resource. I am finding this book so easy to read I am reading it instead of my usual non-fiction. -- Deb Wyatt in WA From gokoproject at gmail.com Sun Jul 31 19:35:47 2016 From: gokoproject at gmail.com (John Wong) Date: Sun, 31 Jul 2016 19:35:47 -0400 Subject: [Tutor] Book recommendation In-Reply-To: References: Message-ID: On Sun, Jul 31, 2016 at 7:14 PM, D Wyatt wrote: > Hello. I've been a member of this group for a very long time and have > played with Python for years, but have never gotten past being a beginner > for various reasons. I just discovered a very good, free book, that is > answering many of the questions I have had in the past that I never got > answers I could understand from you all. While I appreciate the time and > effort you put in helping us out, most of you do not remember what you > didn't used to know, and are often less than helpful because of this. This > is not meant as a criticism, but just my observation. > > I think that's a constructive feedback. There are two problems. One is often the question itself is not well-phrased. The other is remote communication is a known challenge. I could spend a whole hour doing pair programming or whiteboarding a solution with someone next to me physically, but I can't do that over the Internet easily. The person asking the question may not respond to my reply the next day (timezone difference). It's a hard problem. I often ask my questions on IRC, and my experience is also not quite as good as I would hope, although there are enough people to chime in. A lot of learning is practice, and then having a mentor available. > Anyway, this book I found, Learning Python, is well-written and easy to > understand. Here is a url to it. https://www.packtpub.com/tech/python. > > Great. I am glad you found one that's helping you. I share the view that any book is a good book as long as the book is giving correct information. A few other ones: * Think Python: How to Think Like a Computer Scientist * Learning Python by Mark Lutz - I started my journey with this, many years ago * Dive Into Python - quite good for beginnger * Google's Python Class - very gentle introduction * Python classes online (e.g. the ones available on MIT OCW) - pretty good if you like slow, lecture-based. * Python documentation * Python Essential Reference (for intermediate -> advanced) * Learn Python the Hard Way (not so much into this, just personal preferences) Just my 3.1415 cents. John