From agkiran2 at gmail.com Fri May 1 03:33:43 2020 From: agkiran2 at gmail.com (kiran AG) Date: Fri, 1 May 2020 00:33:43 -0700 Subject: [Tutor] Overridable methods Message-ID: Hi, Are all the methods in python classes overridable or is there a way to make it not-overridable? -- Thanks & Regards, Kiran From ekesawi at yahoo.com Fri May 1 04:38:36 2020 From: ekesawi at yahoo.com (EK Esawi) Date: Fri, 1 May 2020 08:38:36 +0000 (UTC) Subject: [Tutor] Rearrange a list References: <790085832.289061.1588322316111.ref@mail.yahoo.com> Message-ID: <790085832.289061.1588322316111@mail.yahoo.com> Hi All--, I have a list, e.g. x=[1,2,3,4,5,6,7,8,9,10,??]. I want to rearrange the order of the positions of the list values as follow [1,2,4,3,5,6,8,7,9,10,12,13,15??]. Or something like this? [1,[2,4],[3,5],[6,8],[7,9],[10,12],??] which then can be flattened. I am not concerned about the 1st item on the list. I am hoping that this can be done vis list comprehension or something like it w/o using other Python modules. Here is my attempt but the resulting pairing is wrong. It contains unwanted pairs such as [4,6] and [8,10] ? X= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b=[[i, i + 2] for i in range(1,len(x) - 1)] b=[[1, 3], [2, 4], [3, 5], [4, 6], [5, 7], [6, 8], [7, 9], [8, 10]] again, I am not concerned with the 1st sublist Thanks EK From __peter__ at web.de Fri May 1 07:44:07 2020 From: __peter__ at web.de (Peter Otten) Date: Fri, 01 May 2020 13:44:07 +0200 Subject: [Tutor] Rearrange a list References: <790085832.289061.1588322316111.ref@mail.yahoo.com> <790085832.289061.1588322316111@mail.yahoo.com> Message-ID: EK Esawi via Tutor wrote: > Hi All--, > > I have a list, e.g. x=[1,2,3,4,5,6,7,8,9,10,??]. I want to rearrange the > order of the positions of the list values as follow > [1,2,4,3,5,6,8,7,9,10,12,13,15??]. Or something like this > [1,[2,4],[3,5],[6,8],[7,9],[10,12],??] which then can be flattened. I am > not concerned about the 1st item on the list. I am hoping that this can be > done vis list comprehension or something like it w/o using other Python > modules. > > Here is my attempt but the resulting pairing is wrong. It contains > unwanted pairs such as [4,6] and [8,10] > > > X= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > b=[[i, i + 2] for i in range(1,len(x) - 1)] > > b=[[1, 3], [2, 4], [3, 5], [4, 6], [5, 7], [6, 8], [7, 9], [8, 10]] > > again, I am not concerned with the 1st sublist How about >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> x[3::4], x[2::4] = x[2::4], x[3::4] >>> x [1, 2, 4, 3, 5, 6, 8, 7, 9, 10] ? From __peter__ at web.de Fri May 1 07:51:33 2020 From: __peter__ at web.de (Peter Otten) Date: Fri, 01 May 2020 13:51:33 +0200 Subject: [Tutor] Rearrange a list References: <790085832.289061.1588322316111.ref@mail.yahoo.com> <790085832.289061.1588322316111@mail.yahoo.com> Message-ID: Peter Otten wrote: > EK Esawi via Tutor wrote: > >> Hi All--, >> >> I have a list, e.g. x=[1,2,3,4,5,6,7,8,9,10,??]. I want to rearrange the >> order of the positions of the list values as follow >> [1,2,4,3,5,6,8,7,9,10,12,13,15??]. Or something like this >> [1,[2,4],[3,5],[6,8],[7,9],[10,12],??] which then can be flattened. I am >> not concerned about the 1st item on the list. I am hoping that this can >> be done vis list comprehension or something like it w/o using other >> Python modules. >> >> Here is my attempt but the resulting pairing is wrong. It contains >> unwanted pairs such as [4,6] and [8,10] >> >> >> X= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >> >> b=[[i, i + 2] for i in range(1,len(x) - 1)] >> >> b=[[1, 3], [2, 4], [3, 5], [4, 6], [5, 7], [6, 8], [7, 9], [8, 10]] >> >> again, I am not concerned with the 1st sublist > > How about > >>>> x > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>> x[3::4], x[2::4] = x[2::4], x[3::4] >>>> x > [1, 2, 4, 3, 5, 6, 8, 7, 9, 10] > > ? To be more explicit about a potential problem: this doesn't work for arbitrary lengths: >>> x [1, 2, 3, 4, 5, 6, 7] >>> x[3::4], x[2::4] = x[2::4], x[3::4] Traceback (most recent call last): File "", line 1, in ValueError: attempt to assign sequence of size 2 to extended slice of size 1 From mats at wichmann.us Fri May 1 08:20:46 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 1 May 2020 06:20:46 -0600 Subject: [Tutor] Rearrange a list In-Reply-To: <790085832.289061.1588322316111@mail.yahoo.com> References: <790085832.289061.1588322316111.ref@mail.yahoo.com> <790085832.289061.1588322316111@mail.yahoo.com> Message-ID: <7b2265b4-4e2c-7d50-1e44-8be083ab89b7@wichmann.us> On 5/1/20 2:38 AM, EK Esawi via Tutor wrote: > Hi All--, > > I have a list, e.g. x=[1,2,3,4,5,6,7,8,9,10,??]. I want to rearrange the order of the positions of the list values as follow [1,2,4,3,5,6,8,7,9,10,12,13,15??]. Or something like this? [1,[2,4],[3,5],[6,8],[7,9],[10,12],??] which then can be flattened. I am not concerned about the 1st item on the list. I am hoping that this can be done vis list comprehension or something like it w/o using other Python modules. > > Here is my attempt but the resulting pairing is wrong. It contains unwanted pairs such as [4,6] and [8,10] I think you need to describe the problmm accurately in words before you can see how to approach how to translate that into Python. Clearly this forms part of the translated description (but do it in words anyway, as part of the process): b=[[i, i + 2] for i in range(1,len(x) - 1)] But your translation of into code misses anything which reflects that [4, 6] would be an invalid pair. Please describe why it is so. From mats at wichmann.us Fri May 1 08:23:27 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 1 May 2020 06:23:27 -0600 Subject: [Tutor] Overridable methods In-Reply-To: References: Message-ID: On 5/1/20 1:33 AM, kiran AG wrote: > Hi, > > Are all the methods in python classes overridable or is there a way to make > it not-overridable? > You can play some games that make it harder, but please describe why you want to do this first. From alan.gauld at yahoo.co.uk Fri May 1 09:22:55 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 1 May 2020 14:22:55 +0100 Subject: [Tutor] Overridable methods In-Reply-To: References: Message-ID: On 01/05/2020 08:33, kiran AG wrote: > Are all the methods in python classes overridable or is there a way to make > it not-overridable? While it might be possible using meta-classes its not normal. Python adopts an "all responsible adults" approach to OOP and leaves most things open to modification. The assumption being that you won't do anything stupid. But it is an edge case thats ot normally needed so I don't think Python has any builtin mechanism. -- 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 May 1 09:47:45 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 1 May 2020 14:47:45 +0100 Subject: [Tutor] Rearrange a list In-Reply-To: <790085832.289061.1588322316111@mail.yahoo.com> References: <790085832.289061.1588322316111.ref@mail.yahoo.com> <790085832.289061.1588322316111@mail.yahoo.com> Message-ID: On 01/05/2020 09:38, EK Esawi via Tutor wrote: > I have a list, e.g. x=[1,2,3,4,5,6,7,8,9,10,??]. I want to rearrange the order of the positions > of the list values as follow [1,2,4,3,5,6,8,7,9,10,12,13,15??]. > Or something like this? [1,[2,4],[3,5],[6,8],[7,9],[10,12],??] which then can be flattened. Here's one method: >>> odds = range(3,50,2) >>> evens = range(2,50,2) >>> [1] + [list(odds[n-1:n+1]) if n%2 else list(evens[n:n+2]) for n in range(0,20)] [1, [2, 4], [3, 5], [6, 8], [7, 9], [10, 12], [11, 13], [14, 16], [15, 17], [18, 20], [19, 21], [22, 24], [23, 25], [26, 28], [27, 29], [30, 32], [31, 33], [34, 36], [35, 37], [38, 40], [39, 41]] 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 alan.gauld at yahoo.co.uk Fri May 1 09:51:42 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 1 May 2020 14:51:42 +0100 Subject: [Tutor] Help with Pygame In-Reply-To: References: Message-ID: On 01/05/2020 01:11, Benjamin Tsai wrote: > I am using Pycharm and using my system interpreter of python 3.7, which I > installed using homebrew in the terminal. I've installed the pygame module > and the code runs fine (the message "Hello from the pygame community" pops > up in the console). In addition, a pop-up window called "pygame window" > opens, but nothing in my test code after my for loop works. And what is this test code? How do you expect us to suggest an answer for code that we can't see? Please embed your code as text in a message. Also, there is a pygame support forum where you are likely to find more people with pygame experience than on this list. https://www.pygame.org/wiki/info -- 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 PyTutor at danceswithmice.info Fri May 1 17:01:20 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Sat, 2 May 2020 09:01:20 +1200 Subject: [Tutor] [OT] Cool vim feature In-Reply-To: <6747a199-82b1-0812-0e99-c62dcd93a631@wichmann.us> References: <0e5d3dae-8158-c668-2e5b-4c82d14b90f4@wichmann.us> <6662800b-a61a-10bf-dba8-21e673640501@DancesWithMice.info> <6747a199-82b1-0812-0e99-c62dcd93a631@wichmann.us> Message-ID: <4a7e1858-6ec0-fa65-08f1-3ca4c635b57b@DancesWithMice.info> On 30/04/20 8:02 AM, Mats Wichmann wrote: > On 4/29/20 1:38 PM, DL Neil via Tutor wrote: > >>> probably don't have a lot of incentive to keep exploring new stuff... at >>> least that's been the case for me, I've discovered new stuff quite >>> slowly. >> Are Release Notes largely treated in the same manner as License Agreements? >> (that's a bit long, I'm not going to read that/will come back to it later?) > > In my case, I get updates through a package manager... dnf or apt on > Linux, and chocolatey on Windows. So new versions "just install", I > would have to go looking for release notes, and if there's not a reason > you know you need to, why? Apologies for going 'all sociological' on you. This thread evidences a very good reason! ("should" cf "need") One assumes that security-matters aside, package-maintainers have made changes for good reason, eg an extension to facilities. If we don't read the docs, we miss-out on potential advantage. A disadvantage? Any changing of default values or actions may cause existing applications to 'break' - and likely in a reasonably illogical fashion and thus be difficult to track-down and debug. In an environment where systems are critical, 'changes' may not be made without first verifying their effects - parallel environments, 'sand-boxes' etc. Many use venvs to achieve something similar, I use VMs. Like yourself, I tend to wait for Fedora-Linux to update their repo before I think about upgrading my Python(s). Even then, I do not tend to upgrade immediately, but to schedule a 'project' - and then, yes, read the docs (can you just see the virtue shining from my eyes and the halo surrounding my skull?), and to 'have a play' with the new features - see also question about 'walrus operator' I tossed into another thread, elsewhere (I hadn't (and still haven't) had time to experiment with it - yet!). Of course, there are exceptions. When some new feature is a 'must have', then 'the rules' change - but on a very consistent basis, please understand! -- Regards =dn From ekesawi at yahoo.com Fri May 1 18:20:24 2020 From: ekesawi at yahoo.com (EK Esawi) Date: Fri, 1 May 2020 22:20:24 +0000 (UTC) Subject: [Tutor] Rearrange a list References: <1188456035.634972.1588371624898.ref@mail.yahoo.com> Message-ID: <1188456035.634972.1588371624898@mail.yahoo.com> Thank you Peter, Mats and Alan. Allan?s answer is close. ?I am suing Matplotlib, to create a char, which I understand that Matplotlib is a 3rd party software and thus the question may not be suitable here. But here is a detailed description just in case it helps. I created a plot and I wanted to draw a set of straight lines between 2 sets of coordinate points. I wanted each line to not be connected with the line after it. ?My solution is to go back and forth to avoid the diagonal line that connects the 2nd coordinate of the previous point and the 1st coordinate of the following one. ?Here is a little drawing if it helps: My solution is to start at 1 then move to 2, 4, 3, 5, 6 etc. If I don?t do this I get additional diagonal lines drown between 2 and 3 , 5 and 6, etc. Hope this helps. Alan?s solution produces extra points and misses ones. Here is a set of points that I want to get (2,4),(4,3),(3,5),(5,6),(6,8),(8,7), (7,9), (9,10), (10,12), (12,11), etc ?? ? ? ? ? ? ? ? ??? ? ? ? ?? . 1 ?? ??? ??? ??? ????????? 4 .____.2 ???????????????????? 3._________.5 ???????????????? 6.____________.8 Thanks again EK From PyTutor at DancesWithMice.info Fri May 1 19:34:29 2020 From: PyTutor at DancesWithMice.info (DL Neil) Date: Sat, 2 May 2020 11:34:29 +1200 Subject: [Tutor] Help with Pygame In-Reply-To: References: Message-ID: On 1/05/20 12:11 PM, Benjamin Tsai wrote: > Hi there, > > I just recently bought a new computer back in december and installed python > on my computer. However, for some reason, I can't run pygame successfully. > > I am using Pycharm and using my system interpreter of python 3.7, which I > installed using homebrew in the terminal. I've installed the pygame module > and the code runs fine (the message "Hello from the pygame community" pops > up in the console). In addition, a pop-up window called "pygame window" > opens, but nothing in my test code after my for loop works. I've tried > looking for a lot of solutions online and deleted and redownloaded python a > few times and I'm quite new to Pycharm so I'm not sure if this is a pycharm > or python problem. Any help would be appreciated. After various setup commands, Pygame will open its window (as described). The usual problem with display thereafter, is forgetting to update the display window/flip the screen-buffers. This needs to be accomplished within the event loop, after every 'move' or change to the screen's contents. It's often the last line of code within the event-loop. > Sidenote: is there an easy way I can get back to "square one" with python > without damaging the python that inherently comes with my computer? That sounds like a PyCharm question and depends upon how you/it installed the version of Python other than the system-version. -- Regards =dn From timothyg347 at gmail.com Fri May 1 22:46:20 2020 From: timothyg347 at gmail.com (Tim G.) Date: Fri, 1 May 2020 19:46:20 -0700 Subject: [Tutor] Pyautogui clicking on a modal pop-up dialog In-Reply-To: References: Message-ID: Hey Jim, There's a simple way to do that just get a screenshot of the ok button, crop it down to just the button and then put it in the parenthesis. It should look like pyautogui.click("button.png") You can find a sample in the docs here: https://pyautogui.readthedocs.io/en/latest/screenshot.html On Wed, Apr 8, 2020 at 3:41 PM Jim wrote: > I am using OOSheet and Pyautogui to update a Libreoffice calc sheet. > > The following code snippet works until it hits the paste() function. > > cols_to_copy = copy_cellrange() > # Copy the columns necessary to calculate the portfolios diversity > colA = S(cols_to_copy[0]).copy() > S('Diversification.R1').paste() > pyautogui.click() > > Once I get to paste() it pops up a Libreoffice dialog warning me I am > pasting into cells that contain data, do I want to paste. The cursor > sits over the OK button but the click() never runs. > > Is there anyway to get Pyautogui to click the button? > > Thanks, Jim > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From jf_byrnes at comcast.net Sat May 2 10:53:39 2020 From: jf_byrnes at comcast.net (Jim) Date: Sat, 2 May 2020 09:53:39 -0500 Subject: [Tutor] Pyautogui clicking on a modal pop-up dialog In-Reply-To: References: Message-ID: On 5/1/20 9:46 PM, Tim G. wrote: > Hey Jim, > There's a simple way to do that just get a screenshot of the ok button, > crop it down to just the button and then put it in the parenthesis. It > should look like pyautogui.click("button.png") > You can find a sample in the docs here: > https://pyautogui.readthedocs.io/en/latest/screenshot.html Tim, I was able to solve the problem by changing the original paste() line to S().dispatch('PasteSpecial', ('Format', 0)) This prevented the popup from showing and the script continued without interruption. Regards, Jim > On Wed, Apr 8, 2020 at 3:41 PM Jim wrote: > >> I am using OOSheet and Pyautogui to update a Libreoffice calc sheet. >> >> The following code snippet works until it hits the paste() function. >> >> cols_to_copy = copy_cellrange() >> # Copy the columns necessary to calculate the portfolios diversity >> colA = S(cols_to_copy[0]).copy() >> S('Diversification.R1').paste() >> pyautogui.click() >> >> Once I get to paste() it pops up a Libreoffice dialog warning me I am >> pasting into cells that contain data, do I want to paste. The cursor >> sits over the OK button but the click() never runs. >> >> Is there anyway to get Pyautogui to click the button? >> >> Thanks, Jim >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From oscar.j.benjamin at gmail.com Sun May 3 09:08:26 2020 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 3 May 2020 14:08:26 +0100 Subject: [Tutor] Do you use doctests to show API use even when you normally use unit tests? In-Reply-To: References: Message-ID: On Sun, 26 Apr 2020 at 05:22, boB Stepp wrote: > > They discuss the > question of doctests versus unit tests, and, of course, heavily vote > for unit testing as the way to go. However, they never stop inserting > doctests into their function and method docstrings. I am assuming > that they consider it best practice as to how to document how to use a > function or method. > > My question is: Is this what you would consider to be best > documentation practice? Best documentation practice is to think carefully about what is the clearest way to explain something to users. Even a single very simple example can do a lot to clarify a description. Of course the doctest can only give examples so the description is always needed to explain things like the full scope of the function. You shouldn't think of doctests as an alternative to unit tests. Unit tests are for testing the code whereas doctests are for testing the docs. As well as helping to clarify the usage of a function to end users doctests also remind authors of the code to keep the documentation up to date. In a larger project this means that if any contributor wants to change the behaviour of a function then they will have to update the doctests which should then trigger a review of the docstring as a whole (either by the author or by whoever reviews their work). -- Oscar From PyTutor at danceswithmice.info Sun May 3 16:44:56 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Mon, 4 May 2020 08:44:56 +1200 Subject: [Tutor] Do you use doctests to show API use even when you normally use unit tests? In-Reply-To: References: Message-ID: On 4/05/20 1:08 AM, Oscar Benjamin wrote: > On Sun, 26 Apr 2020 at 05:22, boB Stepp wrote: >> >> They discuss the >> question of doctests versus unit tests, and, of course, heavily vote >> for unit testing as the way to go. However, they never stop inserting >> doctests into their function and method docstrings. I am assuming >> that they consider it best practice as to how to document how to use a >> function or method. >> >> My question is: Is this what you would consider to be best >> documentation practice? > > Best documentation practice is to think carefully about what is the > clearest way to explain something to users. Even a single very simple > example can do a lot to clarify a description. Of course the doctest > can only give examples so the description is always needed to explain > things like the full scope of the function. > > You shouldn't think of doctests as an alternative to unit tests. Unit > tests are for testing the code whereas doctests are for testing the > docs. As well as helping to clarify the usage of a function to end > users doctests also remind authors of the code to keep the > documentation up to date. In a larger project this means that if any > contributor wants to change the behaviour of a function then they will > have to update the doctests which should then trigger a review of the > docstring as a whole (either by the author or by whoever reviews their > work). The word "users" is a little ambiguous - even though we (all) use it, all the time - the "user" of a library is likely to be a programmer, whereas the "user" of an application is likely a 'normal person'. (above, the distinction seems clear to me, but when it comes to documentation, both definitions apply - but to different documents, written at different levels of complexity and for different audiences) This is good advice. I often think the TDD cycle is slightly wrong (apologies to all who reacted to such heresy with a sharp intake of breath). Instead of the usually summarised cycle of: designing a test, then writing the code, then running (all) tests, and finally refactoring (either?both); I've thought it should be: 1 understand the purpose of the next step 2 in the code, add comment(s) which document 'the objective' AND anything necessary about 'the solution' 3 then write the test(s) - informed by the previous 4 write the code - equally so etc Will welcome critique... Meantime, you may like to review Divio's "documentation system" (https://documentation.divio.com/). They identify four main types of documentation: Reference, Explanation, Tutorial, and How-To. Which of these are relevant to this conversation? I doubt that docstrings and supportive comments are the place for tutorials. Indeed most of the doctests mentioned earlier are at a level where 'tutorial' would be inappropriate - for example. However, one of the irritating, almost arrogant, features of many F/LOSS projects (not specifically Python then) is the way some authors insist that the way to learn about their grand-creation, is to read the code (cf RTFM!). This is true, and doubly-so for security reasons, but... it is also a high 'barrier to entry'. Many a project would receive better take-up if it explained its API, at least with How-to examples. Initial application would be a lot faster (and motivational!), per @Alan's comment. Par example: how easy did you find learning Python, compared with some other language? Did the documentation library support your efforts to a greater or lesser degree than equivalents? So, my 2-cents: doctests are not so much useful for unit testing (I am using Pytest for that, at the moment), but for illustrating a routine's API and the variations, combinations, and permutations the code has been built to handle/reject. That they may also be used for 'unit testing' is somewhat, bonus-value! Lastly, let me toss into the arena of your considerations, the idea that if all of the (functional) code was 'lost', would your testing suite (largely unit- and functional-/integration-tests) be sufficient to enable reconstruction? In which case, would much of the 'added' documentation I described earlier (assuming your concurrence) be better placed in the tests rather than 'cluttering up' the functional-code modules? -- Regards =dn From cs at cskk.id.au Sun May 3 20:17:34 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 4 May 2020 10:17:34 +1000 Subject: [Tutor] Do you use doctests to show API use even when you normally use unit tests? In-Reply-To: References: Message-ID: <20200504001734.GA41294@cskk.homeip.net> On 04May2020 08:44, DL Neil wrote: [...snip...] >However, one of the irritating, almost arrogant, features of many >F/LOSS projects (not specifically Python then) is the way some authors >insist that the way to learn about their grand-creation, is to read the >code (cf RTFM!). This is true, and doubly-so for security reasons, >but... it is also a high 'barrier to entry'. Many a project would >receive better take-up if it explained its API, at least with How-to >examples. Initial application would be a lot faster (and >motivational!), per @Alan's comment. [...] I also find this irritating, but for other reasons. Reading the code is indeed a great way to learn how something was implemented, and in principle to learn what assumptions the author may have made which are not clarified in the documentation, and/or what bugs/limitations the implementation may have which are no elucidated in the documentation. _If_ the code is accessable, meaning here "readable". However, it is a LOUSY way to learn about the problem that is being solved, and about the _semantics_ which are purported to be supplied. Here I mean that the code will tell you what happens. But only the docs will tell you which implementation specific aspects of the code are to be relied upon by the user of the code. A typical trite example is interning strings of the same value or ints of the same value, or interning re regexp object with the same pattern definition. In Python, these are CPython implementation details (eg happens for small ints, and I think the re module guarentees a limited size cache), but someone reading the code might presume that this is guarenteed, and therefore that "s1 is s2" is a fast way to compare strings for equality. (Which, IIRC, in PHP _is_ guarenteed.) Any number of more complex examples abound, such as presuming some internal data structure (and therefore specific performance characteristics or features). I trip over devs all the time who confuse the implementation with the specification. And I hate it. Most recent example was a dev who asserted that anyone would read something's docstring out of the source file versus say, help(). Bah! I for one have things which augument the raw source docstring. help() and/or the generated docs are the reference. Grumblingly, Cameron Simpson From mikeycrooks17 at gmail.com Sun May 3 17:50:14 2020 From: mikeycrooks17 at gmail.com (Michael Crooks) Date: Sun, 3 May 2020 17:50:14 -0400 Subject: [Tutor] my function doesn't print out anything when i pass an argument through it Message-ID: From alan.gauld at yahoo.co.uk Mon May 4 03:20:00 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 4 May 2020 08:20:00 +0100 Subject: [Tutor] my function doesn't print out anything when i pass an argument through it In-Reply-To: References: Message-ID: On 03/05/2020 22:50, Michael Crooks wrote: > I assume you attached your code rather than pasted it into the message? (I saw it when it was in the moderation queue so I know it was originally there!) Unfortunately the server strips attachments for security reasons, so you need to post the code pasted into the message. I didn't look closely but one obvious issue you had was that your return statement was inside your for loop so it always returns after the first element. It never processes the others. If that doesn't fix the issue repost with the code pasted into the body. -- 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 PyTutor at danceswithmice.info Mon May 4 16:33:35 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Tue, 5 May 2020 08:33:35 +1200 Subject: [Tutor] Do you use doctests to show API use even when you normally use unit tests? In-Reply-To: <20200504001734.GA41294@cskk.homeip.net> References: <20200504001734.GA41294@cskk.homeip.net> Message-ID: <08e7d6fb-12d2-7216-ec7b-d67b144932c7@DancesWithMice.info> On 4/05/20 12:17 PM, Cameron Simpson wrote: > On 04May2020 08:44, DL Neil wrote: > [...snip...] >> However, one of the irritating, almost arrogant, features of many >> F/LOSS projects (not specifically Python then) is the way some authors >> insist that the way to learn about their grand-creation, is to read >> the code (cf RTFM!). This is true, and doubly-so for security reasons, >> but... it is also a high 'barrier to entry'. Many a project would >> receive better take-up if it explained its API, at least with How-to >> examples. Initial application would be a lot faster (and >> motivational!), per @Alan's comment. [...] > > I also find this irritating, but for other reasons. > > Reading the code is indeed a great way to learn how something was > implemented, and in principle to learn what assumptions the author may > have made which are not clarified in the documentation, and/or what > bugs/limitations the implementation may have which are no elucidated in > the documentation. _If_ the code is accessable, meaning here "readable". > > However, it is a LOUSY way to learn about the problem that is being > solved, and about the _semantics_ which are purported to be supplied. > Here I mean that the code will tell you what happens. But only the docs > will tell you which implementation specific aspects of the code are to > be relied upon by the user of the code. ... > I trip over devs all the time who confuse the implementation with the > specification. And I hate it. ... > Grumblingly, Don't feel such "grumbling" is negative, if we can learn/improve from it (but a grumpy, old, man would say that, wouldn't he?) A question for all (cf addressing only @Cameron):- Most programmers (and programming courses) have difficulty handling and covering documentation. Even those who consciously, and conscientiously, attempt to behave in a responsible and professional fashion. Ref "implementation with the specification" (above) Is this (in part) because we do confuse these two? I attempt to carry as much of the specification (in distilled form) forward, as possible. So, design docs feature restatements of the specification. Similarly, such design docs are 'carried forward' into code outlines. However, the way the code implements the identified needs may not lend itself to carrying such information forward into (say) class or method docstrings. However, when it comes to writing tests - at the level of basic unit-testing, are we testing against "implementation" or "specification". At an higher level of testing, does that change? So, when we design our tests (back to earlier-posted 'TDD heresy'), should we carry-forward "design" documentation cf "implementation", neither, or both? Another counter-argument/discussion-point: with doctests particularly - but maybe not (?) do we find that our code has become 'cluttered' with all of this natural-language, which makes it unnecessarily difficult to see our Python? -- Regards =dn From jf_byrnes at comcast.net Mon May 4 22:41:04 2020 From: jf_byrnes at comcast.net (Jim) Date: Mon, 4 May 2020 21:41:04 -0500 Subject: [Tutor] I need to ignore an error let the script continue to run Message-ID: I ended up writing the program that lets me view parts of an email header in a pop up window without opening the message. It worked great until I received an email with a header that did not contain all the items I was trying to retrieve. The parse_header function processes the data and passes it on to another part of the script to display it. In the header I am working with there is no 'Recepient username' in the header.I need a way to ignore any missing keys and process the ones that are there. It seems try/except will not process the keys after the missing one. I looked at something like dict.get(key, 'blank') but I can't figure out how to handle these two cases: 'Recepient username: ' + header['to'].addresses[0].username+'\n', 'Sender name: ' + header['from'].addresses[0].display_name They don't look like keys, but they do resolve to the info I want if it is in the header. Here is the function: def parse_header(msg): with open('/home/jfb/' + email_msg, 'rb') as fp: header = BytesParser(policy=default).parse(fp) # Now the header items can be accessed as a dictionary: try: headers = ['To: ' + header['to']+'\n' , 'From: ' + header['from']+'\n', 'Subject: ' + header['subject']+'\n', 'Return-Path: ' + header['return-path']+'\n' , #This does not exist in some headers 'Recepient username: ' + header['to'].addresses[0].username+'\n', 'Sender name: ' + header['from'].addresses[0].display_name ] msg_header = [] for item in headers: msg_header.append(item) except IndexError as error: print(error) # ~ except: # ~ pass return msg_header This is the output if the username line is commented out: To: undisclosed-recipients:; From: Admin Subject: restore Return-Path: Sender name: Admin Any help appreciated, Jim From schro124 at umn.edu Mon May 4 19:18:41 2020 From: schro124 at umn.edu (Sue Schroeder) Date: Mon, 4 May 2020 18:18:41 -0500 Subject: [Tutor] installing numpy for Python 2.7 Message-ID: Hi, I am having trouble installing numpy and scipy with Python 2.7 for use conducting partial least square analysis with SPSS 25. I have successfully installed numpy and scipy for Python 3.8, but SPSS 25 is apparently set up to run Python 2.7. The error message that I receive is pasted below: C:\Program Files\IBM\SPSS\Statistics\25\Python>pip install C:\numpy-1.10.4+mkl-cp27-cp27m-win_amd64.whl ERROR: numpy-1.10.4+mkl-cp27-cp27m-win_amd64.whl is not a supported wheel on this platform. Thanks for any help you can provide! -- Susan (Sue) A. Schroeder, Ph.D. Research Associate Minnesota Cooperative Fish and Wildlife Research Unit University of Minnesota 200 Hodson Hall 1980 Folwell Ave. St. Paul, MN 55108 612-624-3479 (phone) 612-625-5299 (fax) sas at umn.edu From alan.gauld at yahoo.co.uk Tue May 5 03:47:18 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 5 May 2020 08:47:18 +0100 Subject: [Tutor] installing numpy for Python 2.7 In-Reply-To: References: Message-ID: On 05/05/2020 00:18, Sue Schroeder wrote: > installed numpy and scipy for Python 3.8, but SPSS 25 is apparently set up > to run Python 2.7. The error message that I receive is pasted below: Installing Scipy has traditionally been something of a lack art with most cases working and many cases just failing for any one of a number of reasons. My advice to anyone installing more than one of the Scipy packages is just grab the lot in a dedicated distro. The best known is Anaconda: https://www.anaconda.com/products/individual That should install everything you need and be guaranteed to have compatible versions. There is also an active support community to sort out issues. There are other similar packages available if you don't for some reason want to use Anaconda. This will install a brand new Python version on your system so if you have significant projects already under way using 2.7 you may need to tweak them to point at the right libraries, paths etc. -- 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 May 5 04:01:54 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 5 May 2020 09:01:54 +0100 Subject: [Tutor] I need to ignore an error let the script continue to run In-Reply-To: References: Message-ID: On 05/05/2020 03:41, Jim wrote: > It seems try/except will not process the keys after the missing one. You need to wrap each bit that needs to continue in try/except. Clunky I agree. > 'Recepient username: ' + header['to'].addresses[0].username+'\n', > 'Sender name: ' + header['from'].addresses[0].display_name > > They don't look like keys, but they do resolve to the info I want if it > is in the header. They aren't keys they are accessing attributes of some class that is returned. You could check the return value from header first using an if test. Or you could just wrap those two calls in their own try/except. Or you could use get() and return a dummy instance of whatever class it is with whatever default values you need. So several solutions only you can decide which suits you best. > def parse_header(msg): > with open('/home/jfb/' + email_msg, 'rb') as fp: > header = BytesParser(policy=default).parse(fp) > # Now the header items can be accessed as a dictionary: > try: > headers = [> 'To: ' + header['to']+'\n' , Notice you access header['to'] here and print it directly. > 'Recepient username: ' + > header['to'].addresses[0].username+'\n', But here you try to access attributes. You can't have it both ways. Either its a printable string or its an object with an addresses list... If you do get a header with an object the first use is likely to break.. > msg_header = [] > > for item in headers: > msg_header.append(item) This would be easier as a list comprehension: msg_header = [item for item in headers] But given its just a direct copy it would be easier still with msg_header = headers[:] -- 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 mats at wichmann.us Tue May 5 09:51:53 2020 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 5 May 2020 07:51:53 -0600 Subject: [Tutor] I need to ignore an error let the script continue to run In-Reply-To: References: Message-ID: <5e112542-c563-c22b-ea91-98f4b3edc455@wichmann.us> On 5/4/20 8:41 PM, Jim wrote: > I ended up writing the program that lets me view parts of an email > header in a pop up window without opening the message. It worked great > until I received an email with a header that did not contain all the > items I was trying to retrieve. > > The parse_header function processes the data and passes it on to another > part of the script to display it. In the header I am working with there > is no 'Recepient username' in the header.I need a way to ignore any > missing keys and process the ones that are there. > > It seems try/except will not process the keys after the missing one. > > I looked at something like dict.get(key, 'blank') but I can't figure out > how to handle these two cases: > > 'Recepient username: ' + header['to'].addresses[0].username+'\n', > 'Sender name: ' + header['from'].addresses[0].display_name I believe these are wired to work so you can do "in" checks: if 'Recipient username' in header: # do something with the field > ??????? header = BytesParser(policy=default).parse(fp) is there a reason you don't use BytesHeaderParser, since your area of interest is the headers? > ??????? #? Now the header items can be accessed as a dictionary: > ??? try: > ??????? headers = ['To: ' + header['to']+'\n' , > ??????? 'From: ' + header['from']+'\n', > ??????? 'Subject: ' + header['subject']+'\n', > ??????? 'Return-Path: ' + header['return-path']+'\n' , > ??????? #This does not exist in some headers > ??????? 'Recepient username: ' + header['to'].addresses[0].username+'\n', > ??????? 'Sender name: ' + header['from'].addresses[0].display_name > ??????? ] > ??????? msg_header = [] > > ??????? for item in headers: > ??????????? msg_header.append(item) this seems a complete waste: you've made a list, and then you loop over the list and append its elements to a new list. From jf_byrnes at comcast.net Tue May 5 10:38:35 2020 From: jf_byrnes at comcast.net (Jim) Date: Tue, 5 May 2020 09:38:35 -0500 Subject: [Tutor] I need to ignore an error let the script continue to run In-Reply-To: References: Message-ID: On 5/5/20 3:01 AM, Alan Gauld via Tutor wrote: > On 05/05/2020 03:41, Jim wrote: > >> It seems try/except will not process the keys after the missing one. > > You need to wrap each bit that needs to continue in try/except. > Clunky I agree. > >> 'Recepient username: ' + header['to'].addresses[0].username+'\n', >> 'Sender name: ' + header['from'].addresses[0].display_name >> >> They don't look like keys, but they do resolve to the info I want if it >> is in the header. > > They aren't keys they are accessing attributes of some class that is > returned. You could check the return value from header first using an if > test. Or you could just wrap those two calls in their own try/except. > > Or you could use get() and return a dummy instance of whatever class it > is with whatever default values you need. > > So several solutions only you can decide which suits you best. OK, thanks, I'll give them a try and see which on works best. >> def parse_header(msg): >> with open('/home/jfb/' + email_msg, 'rb') as fp: >> header = BytesParser(policy=default).parse(fp) >> # Now the header items can be accessed as a dictionary: >> try: >> headers = [> 'To: ' + header['to']+'\n' , > > Notice you access header['to'] here and print it directly. > >> 'Recepient username: ' + >> header['to'].addresses[0].username+'\n', > > But here you try to access attributes. > You can't have it both ways. Either its a printable string > or its an object with an addresses list... > If you do get a header with an object the first use is likely to break.. When I started looking in to doing this I googled and one of the first hits was the Python docs. This function was based on of the examples. It did about 95% of what I wanted to do with out modification. It looks that way but they actually return slightly different information. I just ran it against a message with all the elements in the header to verify it. > >> msg_header = [] >> >> for item in headers: >> msg_header.append(item) > > This would be easier as a list comprehension: > > msg_header = [item for item in headers] > > But given its just a direct copy it would be easier still with > > msg_header = headers[:] > Thanks, I always have trouble understanding some of the more complex list comprehension so I guess I don't even think about the simpler one like this one. I completely forgot about [:]. Thanks, Jim From jf_byrnes at comcast.net Tue May 5 10:47:27 2020 From: jf_byrnes at comcast.net (Jim) Date: Tue, 5 May 2020 09:47:27 -0500 Subject: [Tutor] I need to ignore an error let the script continue to run In-Reply-To: <5e112542-c563-c22b-ea91-98f4b3edc455@wichmann.us> References: <5e112542-c563-c22b-ea91-98f4b3edc455@wichmann.us> Message-ID: On 5/5/20 8:51 AM, Mats Wichmann wrote: > On 5/4/20 8:41 PM, Jim wrote: >> I ended up writing the program that lets me view parts of an email >> header in a pop up window without opening the message. It worked great >> until I received an email with a header that did not contain all the >> items I was trying to retrieve. >> >> The parse_header function processes the data and passes it on to another >> part of the script to display it. In the header I am working with there >> is no 'Recepient username' in the header.I need a way to ignore any >> missing keys and process the ones that are there. >> >> It seems try/except will not process the keys after the missing one. >> >> I looked at something like dict.get(key, 'blank') but I can't figure out >> how to handle these two cases: >> >> 'Recepient username: ' + header['to'].addresses[0].username+'\n', >> 'Sender name: ' + header['from'].addresses[0].display_name > > I believe these are wired to work so you can do "in" checks: OK, I'll give that a try. > if 'Recipient username' in header: > # do something with the field > >> ??????? header = BytesParser(policy=default).parse(fp) > > is there a reason you don't use BytesHeaderParser, since your area of > interest is the headers? Yes, I got this from the Python docs and their example did almost exactly what I wanted to do. I was so happy it worked I didn't look closer at it to realize I was grabbing unnecessary info. Thanks for pointing that out. >> ??????? #? Now the header items can be accessed as a dictionary: >> ??? try: >> ??????? headers = ['To: ' + header['to']+'\n' , >> ??????? 'From: ' + header['from']+'\n', >> ??????? 'Subject: ' + header['subject']+'\n', >> ??????? 'Return-Path: ' + header['return-path']+'\n' , >> ??????? #This does not exist in some headers >> ??????? 'Recepient username: ' + header['to'].addresses[0].username+'\n', >> ??????? 'Sender name: ' + header['from'].addresses[0].display_name >> ??????? ] >> ??????? msg_header = [] >> >> ??????? for item in headers: >> ??????????? msg_header.append(item) > > this seems a complete waste: you've made a list, and then you loop over > the list and append its elements to a new list. In it's present form it is. Originally I just hard coded the list and returned it. Then I had the error with the missing element and was playing around with it trying to find a way to handle the error. I was thinking if I built the list item by item maybe I could check for errors and handle them somehow. So far I haven't been successful, but now I have some more things to try. Thanks, Jim > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From jf_byrnes at comcast.net Tue May 5 16:28:05 2020 From: jf_byrnes at comcast.net (Jim) Date: Tue, 5 May 2020 15:28:05 -0500 Subject: [Tutor] I need to ignore an error let the script continue to run In-Reply-To: References: Message-ID: On 5/5/20 9:38 AM, Jim wrote: > On 5/5/20 3:01 AM, Alan Gauld via Tutor wrote: >> On 05/05/2020 03:41, Jim wrote: >> >>> It seems try/except will not process the keys after the missing one. >> >> You need to wrap each bit that needs to continue in try/except. >> Clunky I agree. >> >>> 'Recepient username: ' + header['to'].addresses[0].username+'\n', >>> 'Sender name: ' + header['from'].addresses[0].display_name >>> >>> They don't look like keys, but they do resolve to the info I want if it >>> is in the header. >> >> They aren't keys they are accessing attributes of some class that is >> returned. You could check the return value from header first using an if >> test. Or you could just wrap those two calls in their own try/except. >> >> Or you could use get() and return a dummy instance of whatever class it >> is with whatever default values you need. >> >> So several solutions only you can decide which suits you best. > > OK, thanks, I'll give them a try and see which on works best. > It seems every time I tried to test the return value from header I would get an error, so I went the try/except route. This what I ended up with: def parse_header(msg): with open('/home/jfb/' + email_msg, 'rb') as fp: header = BytesHeaderParser(policy=default).parse(fp) # Now the header items can be accessed as a dictionary: try: username = header['to'].addresses[0].username + '\n' except: username = ' Blank \n' try: sender = header['to'].addresses[0].display_name + '\n' except: sender = ' Blank \n' return ['To: ' + header['to']+'\n' , 'From: ' + header['from']+'\n', 'Subject: ' + header['subject']+'\n', 'Return-Path: ' + header['return-path']+'\n' , #These do not exist in some headers' 'Recepient username: ' + username, 'Sender name: ' + sender, ] This works when every thing is in the header and when the last two are missing, so thanks for your help. Regards, Jim From breamoreboy at gmail.com Tue May 5 17:13:11 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Tue, 5 May 2020 22:13:11 +0100 Subject: [Tutor] I need to ignore an error let the script continue to run In-Reply-To: References: Message-ID: On 05/05/2020 21:28, Jim wrote: > On 5/5/20 9:38 AM, Jim wrote: >> On 5/5/20 3:01 AM, Alan Gauld via Tutor wrote: >>> On 05/05/2020 03:41, Jim wrote: >>> >>>> It seems try/except will not process the keys after the missing one. >>> >>> You need to wrap each bit that needs to continue in try/except. >>> Clunky I agree. >>> >>>> 'Recepient username: ' + header['to'].addresses[0].username+'\n', >>>> 'Sender name: ' + header['from'].addresses[0].display_name >>>> >>>> They don't look like keys, but they do resolve to the info I want if it >>>> is in the header. >>> >>> They aren't keys they are accessing attributes of some class that is >>> returned. You could check the return value from header first using an if >>> test. Or you could just wrap those two calls in their own try/except. >>> >>> Or you could use get() and return a dummy instance of whatever class it >>> is with whatever default values you need. >>> >>> So several solutions only you can decide which suits you best. >> >> OK, thanks, I'll give them a try and see which on works best. >> > > It seems every time I tried to test the return value from header I would > get an error, so I went the try/except route. This what I ended up with: > > def parse_header(msg): > ??? with open('/home/jfb/' + email_msg, 'rb') as fp: > ??????? header = BytesHeaderParser(policy=default).parse(fp) > ??????? #? Now the header items can be accessed as a dictionary: > ??????? try: > ??????????? username =? header['to'].addresses[0].username + '\n' > ??????? except: Never use a bare except as in the long term it's asking for trouble, catch what you know can occur and let anything else raise it's own exception. > ??????????? username = ' Blank \n' > > ??????? try: > ??????????? sender =? header['to'].addresses[0].display_name + '\n' > ??????? except: > ??????????? sender = ' Blank \n' > > ??????? return ['To: ' + header['to']+'\n' , > ??????? 'From: ' + header['from']+'\n', > ??????? 'Subject: ' + header['subject']+'\n', > ??????? 'Return-Path: ' + header['return-path']+'\n' , > ??????? #These do not exist in some headers' > ??????? 'Recepient username: ' + username, > ??????? 'Sender name: ' + sender, > ??????? ] > This works when every thing is in the header and when the last two are > missing, so thanks for your help. > > Regards,? Jim > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From jf_byrnes at comcast.net Tue May 5 16:34:49 2020 From: jf_byrnes at comcast.net (Jim) Date: Tue, 5 May 2020 15:34:49 -0500 Subject: [Tutor] I need to ignore an error let the script continue to run In-Reply-To: References: <5e112542-c563-c22b-ea91-98f4b3edc455@wichmann.us> Message-ID: On 5/5/20 9:47 AM, Jim wrote: >>> >>> It seems try/except will not process the keys after the missing one. >>> >>> I looked at something like dict.get(key, 'blank') but I can't figure out >>> how to handle these two cases: >>> >>> 'Recepient username: ' + header['to'].addresses[0].username+'\n', >>> 'Sender name: ' + header['from'].addresses[0].display_name >> >> I believe these are wired to work so you can do "in" checks: > > OK, I'll give that a try. > It seems like every time I tried to use the 'in' check what I was checking would resolve itself (if that's correct terminology) and throw an error. I ended up using Alan's idea of wrapping them both individually in try/except and that worked. Thanks for taking the time to look at my problem. Regards, Jim From jf_byrnes at comcast.net Tue May 5 20:36:31 2020 From: jf_byrnes at comcast.net (Jim) Date: Tue, 5 May 2020 19:36:31 -0500 Subject: [Tutor] I need to ignore an error let the script continue to run In-Reply-To: References: Message-ID: On 5/5/20 4:13 PM, Mark Lawrence wrote: > On 05/05/2020 21:28, Jim wrote: >> On 5/5/20 9:38 AM, Jim wrote: >>> On 5/5/20 3:01 AM, Alan Gauld via Tutor wrote: >>>> On 05/05/2020 03:41, Jim wrote: >>>> >>>>> It seems try/except will not process the keys after the missing one. >>>> >>>> You need to wrap each bit that needs to continue in try/except. >>>> Clunky I agree. >>>> >>>>> 'Recepient username: ' + header['to'].addresses[0].username+'\n', >>>>> 'Sender name: ' + header['from'].addresses[0].display_name >>>>> >>>>> They don't look like keys, but they do resolve to the info I want >>>>> if it >>>>> is in the header. >>>> >>>> They aren't keys they are accessing attributes of some class that is >>>> returned. You could check the return value from header first using >>>> an if >>>> test. Or you could just wrap those two calls in their own try/except. >>>> >>>> Or you could use get() and return a dummy instance of whatever class it >>>> is with whatever default values you need. >>>> >>>> So several solutions only you can decide which suits you best. >>> >>> OK, thanks, I'll give them a try and see which on works best. >>> >> >> It seems every time I tried to test the return value from header I >> would get an error, so I went the try/except route. This what I ended >> up with: >> >> def parse_header(msg): >> ???? with open('/home/jfb/' + email_msg, 'rb') as fp: >> ???????? header = BytesHeaderParser(policy=default).parse(fp) >> ???????? #? Now the header items can be accessed as a dictionary: >> ???????? try: >> ???????????? username =? header['to'].addresses[0].username + '\n' >> ???????? except: > > Never use a bare except as in the long term it's asking for trouble, > catch what you know can occur and let anything else raise it's own > exception. > >> ???????????? username = ' Blank \n' I just write small scripts for my own use, so I really haven't had the occasion to use try/except much. I'm sure your advice it correct in most cases. I'm using try/except more like an 'if'. I needed some way to test if certain items were not in the header data being returned. It seemed that no matter how I tried to reference them I got an error because they tried to return data that was not there. Maybe it can be done but I could never figure it out. Alan suggested a couple of things, one of which was try/except. That's how I came up with what you see. I'm probably abusing try/except, but it works and if it breaks I'll just have to fix it. Thanks for your input. Jim >> ???????? try: >> ???????????? sender =? header['to'].addresses[0].display_name + '\n' >> ???????? except: >> ???????????? sender = ' Blank \n' >> >> ???????? return ['To: ' + header['to']+'\n' , >> ???????? 'From: ' + header['from']+'\n', >> ???????? 'Subject: ' + header['subject']+'\n', >> ???????? 'Return-Path: ' + header['return-path']+'\n' , >> ???????? #These do not exist in some headers' >> ???????? 'Recepient username: ' + username, >> ???????? 'Sender name: ' + sender, >> ???????? ] >> This works when every thing is in the header and when the last two are >> missing, so thanks for your help. >> >> Regards,? Jim >> > > > From alan.gauld at yahoo.co.uk Wed May 6 03:44:42 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 6 May 2020 08:44:42 +0100 Subject: [Tutor] I need to ignore an error let the script continue to run In-Reply-To: References: Message-ID: On 06/05/2020 01:36, Jim wrote: > On 5/5/20 4:13 PM, Mark Lawrence wrote: >>> def parse_header(msg): >>> ???? with open('/home/jfb/' + email_msg, 'rb') as fp: >>> ???????? header = BytesHeaderParser(policy=default).parse(fp) >>> ???????? #? Now the header items can be accessed as a dictionary: >>> ???????? try: >>> ???????????? username =? header['to'].addresses[0].username + '\n' >>> ???????? except: >> >> Never use a bare except as in the long term it's asking for trouble, >> catch what you know can occur and let anything else raise it's own >> exception. > I just write small scripts for my own use, so I really haven't had the > occasion to use try/except much. I'm sure your advice it correct in most > cases. I'm using try/except more like an 'if'. I needed some way to test > if certain items were not in the header data being returned. Where you are using try/except is not the issue, it is how. Mark is saying you should never use a "bare except", by which he means you should always specify the errors that you want to catch. In your case its a KeyERrror so you should have: try: username = header['to'].addresses[0].username + '\n' except KeyError: username = ' Blank \n' The problem with your code is that it catches all errors (IOError, OSError, anything at all that may go wrong in the library function) and just blindly assigns 'blank'. So you have no way of telling that something potentially serious has gone wrong. Something that may cause more errors further down your code, but you won't know where to look because the second error will now point at the wrong place. That's why Mark is telling you not to use a bare except. He is not saying do not use try/except as a control mechanism, but just to always specify the errors you expect to occur. Allow unexpected ones to generate an error trace. -- 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 May 6 05:28:13 2020 From: __peter__ at web.de (Peter Otten) Date: Wed, 06 May 2020 11:28:13 +0200 Subject: [Tutor] I need to ignore an error let the script continue to run References: Message-ID: Jim wrote: > On 5/5/20 4:13 PM, Mark Lawrence wrote: >> On 05/05/2020 21:28, Jim wrote: >>> On 5/5/20 9:38 AM, Jim wrote: >>>> On 5/5/20 3:01 AM, Alan Gauld via Tutor wrote: >>>>> On 05/05/2020 03:41, Jim wrote: >>>>> >>>>>> It seems try/except will not process the keys after the missing one. >>>>> >>>>> You need to wrap each bit that needs to continue in try/except. >>>>> Clunky I agree. >>>>> >>>>>> 'Recepient username: ' + header['to'].addresses[0].username+'\n', >>>>>> 'Sender name: ' + header['from'].addresses[0].display_name >>>>>> >>>>>> They don't look like keys, but they do resolve to the info I want >>>>>> if it >>>>>> is in the header. >>>>> >>>>> They aren't keys they are accessing attributes of some class that is >>>>> returned. You could check the return value from header first using >>>>> an if >>>>> test. Or you could just wrap those two calls in their own try/except. >>>>> >>>>> Or you could use get() and return a dummy instance of whatever class >>>>> it is with whatever default values you need. >>>>> >>>>> So several solutions only you can decide which suits you best. >>>> >>>> OK, thanks, I'll give them a try and see which on works best. >>>> >>> >>> It seems every time I tried to test the return value from header I >>> would get an error, so I went the try/except route. This what I ended >>> up with: >>> >>> def parse_header(msg): >>> with open('/home/jfb/' + email_msg, 'rb') as fp: >>> header = BytesHeaderParser(policy=default).parse(fp) >>> # Now the header items can be accessed as a dictionary: >>> try: >>> username = header['to'].addresses[0].username + '\n' >>> except: >> >> Never use a bare except as in the long term it's asking for trouble, >> catch what you know can occur and let anything else raise it's own >> exception. >> >>> username = ' Blank \n' > > I just write small scripts for my own use, so I really haven't had the > occasion to use try/except much. I'm sure your advice it correct in most > cases. I'm using try/except more like an 'if'. I needed some way to test > if certain items were not in the header data being returned. It seemed > that no matter how I tried to reference them I got an error because they > tried to return data that was not there. Maybe it can be done but I > could never figure it out. Alan suggested a couple of things, one of > which was try/except. That's how I came up with what you see. I'm > probably abusing try/except, but it works and if it breaks I'll just > have to fix it. > > Thanks for your input. > I just write small scripts for my own use I sometimes use that as an excuse to do nasty things, too, but with broad excepts you tend to make your life harder than need be. And it's really easy to be specific. If you run your script and get an exception in the line username = header['to'].addresses[0].username + '\n' the traceback will tell you what exception to catch, or what problem to guard against. For instance: [...] username = header['to'].addresses[0].username + '\n' AttributeError: 'NoneType' object has no attribute 'addresses' You could catch the AttributeError, but the error message tells you that header["to"] is None, so you probably don't use try...except at all: header_to = header["to"] if header_to is None: username = "#missing" else: username = header_to.adresses[0].username + "\n" The code runs for a while, and then you get username = header_to.addresses[0].username + "\n" IndexError: list index out of range Again you could catch try: address = header_to.addresses[0] except IndexError: ... else username = address.username + "\n" or add an explicit check: addresses = header_to.addresses if len(addresses) > 0: # the idiomatic check would be 'if addresses: ...' username = addresses[0].username else: ... In short: you run(*) your script, see a specific exception, and write code to handle just that exception, either by catching it or by adding a check to avoid it. A bare except will sabotage this iterative process and you won't see other problems at the line where they originate, making them much harder to debug. (*) The "professional" version of "run your script" is of course to write unit tests and run those. From akleider at sonic.net Wed May 6 20:06:52 2020 From: akleider at sonic.net (Alex Kleider) Date: Wed, 06 May 2020 17:06:52 -0700 Subject: [Tutor] how to install python3.8 (using virtualenvwrapper) Message-ID: <7c0d32749d6eade903dc96c80c9d010c@sonic.net> My platform is Debian 10 (aka Buster/Stable) with Xfce. Python 2.7 and 3.7 come preinstalled. I've been successful in setting up a virtual environment using virtualenvwrapper but only with Python 3.7 as the interpreter. mkvirtualenv -p python3.7 p37 was successful but mkvirtualenv -p python3.8 p38 failed. Do I need to compile from source as described here[1] or can I do it using pip? Suggestions would be most welcome. Cheers, Alex [1] https://tecadmin.net/install-python-3-8-ubuntu/ -- Alex Kleider (sent from my current gizmo) From jf_byrnes at comcast.net Wed May 6 21:41:11 2020 From: jf_byrnes at comcast.net (Jim) Date: Wed, 6 May 2020 20:41:11 -0500 Subject: [Tutor] I need to ignore an error let the script continue to run In-Reply-To: References: Message-ID: On 5/6/20 2:44 AM, Alan Gauld via Tutor wrote: > On 06/05/2020 01:36, Jim wrote: >> On 5/5/20 4:13 PM, Mark Lawrence wrote: > >>>> def parse_header(msg): >>>> ???? with open('/home/jfb/' + email_msg, 'rb') as fp: >>>> ???????? header = BytesHeaderParser(policy=default).parse(fp) >>>> ???????? #? Now the header items can be accessed as a dictionary: >>>> ???????? try: >>>> ???????????? username =? header['to'].addresses[0].username + '\n' >>>> ???????? except: >>> >>> Never use a bare except as in the long term it's asking for trouble, >>> catch what you know can occur and let anything else raise it's own >>> exception. > >> I just write small scripts for my own use, so I really haven't had the >> occasion to use try/except much. I'm sure your advice it correct in most >> cases. I'm using try/except more like an 'if'. I needed some way to test >> if certain items were not in the header data being returned. > > Where you are using try/except is not the issue, it is how. > Mark is saying you should never use a "bare except", by which he means > you should always specify the errors that you want to catch. > In your case its a KeyERrror so you should have: > > try: > username = header['to'].addresses[0].username + '\n' > except KeyError: > username = ' Blank \n' > > The problem with your code is that it catches all errors (IOError, > OSError, anything at all that may go wrong in the library > function) and just blindly assigns 'blank'. > > So you have no way of telling that something potentially serious > has gone wrong. Something that may cause more errors further down > your code, but you won't know where to look because the second > error will now point at the wrong place. > > That's why Mark is telling you not to use a bare except. He is not > saying do not use try/except as a control mechanism, but just to > always specify the errors you expect to occur. Allow unexpected > ones to generate an error trace. > OK thanks, I understand now. Regards, Jim From jf_byrnes at comcast.net Wed May 6 21:54:55 2020 From: jf_byrnes at comcast.net (Jim) Date: Wed, 6 May 2020 20:54:55 -0500 Subject: [Tutor] I need to ignore an error let the script continue to run In-Reply-To: References: Message-ID: On 5/6/20 4:28 AM, Peter Otten wrote: > Jim wrote: > >> On 5/5/20 4:13 PM, Mark Lawrence wrote: >>> On 05/05/2020 21:28, Jim wrote: >>>> On 5/5/20 9:38 AM, Jim wrote: >>>>> On 5/5/20 3:01 AM, Alan Gauld via Tutor wrote: >>>>>> On 05/05/2020 03:41, Jim wrote: >>>>>> >>>>>>> It seems try/except will not process the keys after the missing one. >>>>>> >>>>>> You need to wrap each bit that needs to continue in try/except. >>>>>> Clunky I agree. >>>>>> >>>>>>> 'Recepient username: ' + header['to'].addresses[0].username+'\n', >>>>>>> 'Sender name: ' + header['from'].addresses[0].display_name >>>>>>> >>>>>>> They don't look like keys, but they do resolve to the info I want >>>>>>> if it >>>>>>> is in the header. >>>>>> >>>>>> They aren't keys they are accessing attributes of some class that is >>>>>> returned. You could check the return value from header first using >>>>>> an if >>>>>> test. Or you could just wrap those two calls in their own try/except. >>>>>> >>>>>> Or you could use get() and return a dummy instance of whatever class >>>>>> it is with whatever default values you need. >>>>>> >>>>>> So several solutions only you can decide which suits you best. >>>>> >>>>> OK, thanks, I'll give them a try and see which on works best. >>>>> >>>> >>>> It seems every time I tried to test the return value from header I >>>> would get an error, so I went the try/except route. This what I ended >>>> up with: >>>> >>>> def parse_header(msg): >>>> with open('/home/jfb/' + email_msg, 'rb') as fp: >>>> header = BytesHeaderParser(policy=default).parse(fp) >>>> # Now the header items can be accessed as a dictionary: >>>> try: >>>> username = header['to'].addresses[0].username + '\n' >>>> except: >>> >>> Never use a bare except as in the long term it's asking for trouble, >>> catch what you know can occur and let anything else raise it's own >>> exception. >>> >>>> username = ' Blank \n' >> >> I just write small scripts for my own use, so I really haven't had the >> occasion to use try/except much. I'm sure your advice it correct in most >> cases. I'm using try/except more like an 'if'. I needed some way to test >> if certain items were not in the header data being returned. It seemed >> that no matter how I tried to reference them I got an error because they >> tried to return data that was not there. Maybe it can be done but I >> could never figure it out. Alan suggested a couple of things, one of >> which was try/except. That's how I came up with what you see. I'm >> probably abusing try/except, but it works and if it breaks I'll just >> have to fix it. >> >> Thanks for your input. > >> I just write small scripts for my own use > > I sometimes use that as an excuse to do nasty things, too, but with broad > excepts you tend to make your life harder than need be. > > And it's really easy to be specific. If you run your script and get an > exception in the line > > username = header['to'].addresses[0].username + '\n' > > the traceback will tell you what exception to catch, or what problem to > guard against. For instance: > > [...] > username = header['to'].addresses[0].username + '\n' > AttributeError: 'NoneType' object has no attribute 'addresses' > > You could catch the AttributeError, but the error message tells you that > header["to"] is None, so you probably don't use try...except at all: > > header_to = header["to"] > if header_to is None: > username = "#missing" > else: > username = header_to.adresses[0].username + "\n" > > The code runs for a while, and then you get > > username = header_to.addresses[0].username + "\n" > IndexError: list index out of range > > Again you could catch > > try: > address = header_to.addresses[0] > except IndexError: > ... > else > username = address.username + "\n" > > or add an explicit check: > > addresses = header_to.addresses > if len(addresses) > 0: # the idiomatic check would be 'if addresses: ...' > username = addresses[0].username > else: ... I have never been able to construct an 'if' that allows the script to run. Finally I gave up and used Alan's explanation and suggestion about specific try/except's. Thanks, Jim > In short: you run(*) your script, see a specific exception, and write code > to handle just that exception, either by catching it or by adding a check to > avoid it. > > A bare except will sabotage this iterative process and you won't see other > problems at the line where they originate, making them much harder to debug. > > (*) The "professional" version of "run your script" is of course to write > unit tests and run those. > From HDoran at air.org Fri May 8 12:22:55 2020 From: HDoran at air.org (Doran, Harold C.) Date: Fri, 8 May 2020 16:22:55 +0000 Subject: [Tutor] Flask File Uploads and Sessions Message-ID: I am new to Flask (and relatively new to python) and am working to do the following: 1) read in a .csv data file 2) populate a drop down menu with the variables (column names) in the data file read in 3) User chooses a variable from the drop down menu and the mean of that column is computed. I am successful with both (1) and (2) but have now spent more than 4 days trying to solve (3) and cannot find a tutorial or documentation. I'm certain it exists, and think my "newness" to the concepts needed might be masking an obvious answer. Below is the relevant portion of my app.py file which runs my flask app and some minimal HTML. When running this, I can read in a file and my drop down is populated as expected. For now, the mean of some variable is hard coded (that's easy to solve). After reading and experimenting for days, I believe the problem is that my file orig_df is not stored in a session. In fact, if I uncomment the line that hard codes a local read in I can do everything I want. So, what I want is for the data orig_df to be read in from the UI and reusable for things I would want to do with it (compute statistics on columns I choose, etc). I am terribly lost. This link below is to where I have fully built and deployed a similar system using R/shiny and my goal is to port my code from R to python and rebuild my app using flask. Can anyone offer some support on how I can make my file orig_df available so that it can be used in a session? I do not want this to be a global variable or even stored on the server, the file should be available to the user only during their browser session and then it would vaporize when they close their browser session. Thank you https://shiny.airast.org/METRICS/ from flask import Flask, render_template, request import numpy as np import pandas as pd app = Flask(__name__) @app.route('/', methods=['POST', 'GET']) def data_tools_upload(): if request.method == 'POST': orig_df = pd.read_csv(request.files.get('file')) #orig_df = pd.read_csv(/path/to/file.csv) var2use = request.form.get("vars2use") vars = list(orig_df.columns) mean = orig_df[vars[4]].mean() dims = orig_df.shape message = 'You have data! There are %s rows and %s columns and the variable %s has mean %s' % (dims[0],dims[1],vars[4],round(mean,3)) table = orig_df.head(10).to_html(classes='data', header = "true") return render_template('upload2.html', tables = [table], message = message, vars = vars, showVar=var2use) return render_template('upload2.html') if __name__ == '__main__': app.run(debug=True) # or just app.run() And some minimal HTML

Read in a data file



{{message}} {{showVar}}


{% for table in tables %} {{ table|safe }} {% endfor %}
From alan.gauld at yahoo.co.uk Fri May 8 18:24:48 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 8 May 2020 23:24:48 +0100 Subject: [Tutor] Flask File Uploads and Sessions In-Reply-To: References: Message-ID: On 08/05/2020 17:22, Doran, Harold C. wrote: ... 3) User chooses a variable from the drop down menu and the mean of that column is computed. > > I am successful with both (1) and (2) but have now spent more than 4 days trying to solve (3) > When running this, I can read in a file and my drop down is populated as expected.... > I believe the problem is that my file orig_df is not stored in a session. Indeed. It dies as soon as the function terminates because that's what local variables in functions do. If you want something to persist between calls you will need to store it somewhere, either as a local file or in a database or possibly in an application level global - although if you have multiple users that's almost certainly a bad idea! > So, what I want is for the data orig_df to be read in from the UI and > reusable for things I would want to do with it The normal approach would be to store it in a database somehow. Maybe SQL if the data collumns are standard or maybe a document centric database like Mongo if the data is more open ended. It may come down to what your web server supports. If that fails just store the original file and then re-read it for each request but that becomes slow if you have big files. > ...global variable or even stored on the server, If its not on the server how can the server see it? It would need to download it each time. I don't know how your R code is doing it but it must be storing it somehow, either in memory or in a file/database. >the file should be available to the user only during their browser session > and then it would vaporize when they close their browser session. It might be possible to stor it(or the filename?) as a cookie and then upload the file each time they connect. But tat will require some smart client side JavaScript as well as server side code to support it. All in all the simplest approach is to store the data you need on the server along with some kind of key to identify the associated user and session.(which may well be in a cookie) > def data_tools_upload(): > if request.method == 'POST': > orig_df = pd.read_csv(request.files.get('file')) This is a local in-memory variable on the server. > var2use = request.form.get("vars2use") > vars = list(orig_df.columns) > mean = orig_df[vars[4]].mean() > dims = orig_df.shape > message = 'You have data! There are %s rows and %s columns and the variable %s has mean %s' % (dims[0],dims[1],vars[4],round(mean,3)) > table = orig_df.head(10).to_html(classes='data', header = "true") > return render_template('upload2.html', tables = [table], message = message, vars = vars, showVar=var2use) > return render_template('upload2.html') And it goes out of scope here and will be deleted. -- 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 akleider at sonic.net Fri May 8 22:14:33 2020 From: akleider at sonic.net (Alex Kleider) Date: Fri, 08 May 2020 19:14:33 -0700 Subject: [Tutor] how to install python3.8 using virtualenvwrapper Message-ID: My platform is Debian 10 (Buster) which comes with Python 2.7 and Python 3.7 preinstalled. I've successfully got virtualenvwrapper running: [ # install python3-pip $ pip3 install virtualenvwrapper then make the appropriate entries in ~/.bashrc and source it...] Now I'd like to have an env using python 3.8. $ makevirtualenv -p python3.7 p37 gives me a Python 3.7 environment but $ makevirtualenv -p python3.8 p38 fails. Is it possible to bring in python 3.8 using pip (or some other means) or must I build from source?[1] [1] as described here: https://tecadmin.net/install-python-3-8-ubuntu/ Any suggestions would be very much appreciated. Cheers, Alex PS Forgive me if this is a duplication. I remember composing this request for help within the last few days but don't remember seeing it on the list and can't find it in my 'sent' folder. -- Alex Kleider (sent from my current gizmo) From mikeycrooks17 at gmail.com Sat May 9 02:08:39 2020 From: mikeycrooks17 at gmail.com (Michael Crooks) Date: Sat, 9 May 2020 02:08:39 -0400 Subject: [Tutor] cant send email using python keep getting error Message-ID: raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials m203sm3339543vka.41 - gsmtp') From alan.gauld at yahoo.co.uk Sat May 9 04:23:03 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 9 May 2020 09:23:03 +0100 Subject: [Tutor] cant send email using python keep getting error In-Reply-To: References: Message-ID: On 09/05/2020 07:08, Michael Crooks wrote: > raise SMTPAuthenticationError(code, resp) > smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not > accepted. Learn more at\n5.7.8 > https://support.google.com/mail/?p=BadCredentials m203sm3339543vka.41 - > gsmtp') Please include the full error trace as well as the code that generated it(at least). Its hard to say what you did wrong (if anything) when we don;t know what you did! PS. Paste the code as plain text do not use an attachment. -- 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 arj.python at gmail.com Sat May 9 04:42:30 2020 From: arj.python at gmail.com (Abdur-Rahmaan Janhangeer) Date: Sat, 9 May 2020 12:42:30 +0400 Subject: [Tutor] cant send email using python keep getting error In-Reply-To: References: Message-ID: You can paste it in a service like this one: https://dpaste.org Kind Regards, Abdur-Rahmaan Janhangeer compileralchemy.com | github Mauritius On Sat, May 9, 2020 at 12:23 PM Alan Gauld via Tutor wrote: > On 09/05/2020 07:08, Michael Crooks wrote: > > raise SMTPAuthenticationError(code, resp) > > smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not > > accepted. Learn more at\n5.7.8 > > https://support.google.com/mail/?p=BadCredentials m203sm3339543vka.41 - > > gsmtp') > > Please include the full error trace as well as the code that > generated it(at least). Its hard to say what you did wrong > (if anything) when we don;t know what you did! > > PS. Paste the code as plain text do not use an attachment. > > -- > 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 mikeycrooks17 at gmail.com Sat May 9 04:31:16 2020 From: mikeycrooks17 at gmail.com (Michael Crooks) Date: Sat, 9 May 2020 04:31:16 -0400 Subject: [Tutor] Full code i get error when i send email using python Message-ID: import smtplib host = "smtp.gmail.com" port = 587 username ="testingprogramsmichael at gmail.com" password = "Oliver17" from_email = username to_list = ["testingprogramsmichael at gmail.com"] email_conn = smtplib.SMTP(host, port) email_conn.ehlo() email_conn.starttls() email_conn.login(username, password) email_conn.sendmail(from_email, to_list, "hello there this is an email message") email_conn.quit() This is what i get when i run it in terminal ( i think google is blocking me because im running this from pi 4 using terminal) >>> import smtplib >>> >>> host = "smtp.gmail.com" >>> port = 587 >>> username ="testingprogramsmichael at gmail.com" >>> password = "Oliver17" >>> from_email = username >>> to_list = ["testingprogramsmichael at gmail.com"] >>> >>> email_conn = smtplib.SMTP(host, port) >>> email_conn.ehlo() (250, b'smtp.gmail.com at your service, [63.143.118.227]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8') >>> email_conn.starttls() (220, b'2.0.0 Ready to start TLS') >>> email_conn.login(username, password) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.7/smtplib.py", line 730, in login raise last_exception File "/usr/lib/python3.7/smtplib.py", line 721, in login initial_response_ok=initial_response_ok) File "/usr/lib/python3.7/smtplib.py", line 642, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials 64sm3599843vkx.12 - gsmtp') >>> email_conn.sendmail(from_email, to_list, "hello there this is an email message") Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.7/smtplib.py", line 867, in sendmail raise SMTPSenderRefused(code, resp, from_addr) smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError 64sm3599843vkx.12 - gsmtp', 'testingprogramsmichael at gmail.com') From akleider at sonic.net Sat May 9 12:54:24 2020 From: akleider at sonic.net (Alex Kleider) Date: Sat, 09 May 2020 09:54:24 -0700 Subject: [Tutor] cant send email using python keep getting error In-Reply-To: References: Message-ID: <78728fbb1efc10fc3a29cdb3f19678dd@sonic.net> On 2020-05-08 23:08, Michael Crooks wrote: > raise SMTPAuthenticationError(code, resp) > smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password > not > accepted. Learn more at\n5.7.8 > https://support.google.com/mail/?p=BadCredentials m203sm3339543vka.41 - > gsmtp') > Did you "allow less secure apps to access your account"? (It's mentioned in the link you provided above. It's this 'feature' which caused me to turn to an agent other than gmail. I've been happy with easydns.com but you'll have to spend some money.) From akleider at sonic.net Sat May 9 13:16:03 2020 From: akleider at sonic.net (Alex Kleider) Date: Sat, 09 May 2020 10:16:03 -0700 Subject: [Tutor] how to install python3.8 using virtualenvwrapper In-Reply-To: References: Message-ID: <4b392d6d124e8f42521ae75570a9e824@sonic.net> On 2020-05-08 19:14, Alex Kleider wrote: - snip - > > Is it possible to bring in python 3.8 using pip (or some other means) > or must I build from source?[1] > > > [1] as described here: > https://tecadmin.net/install-python-3-8-ubuntu/ > Not having received any suggestions, I forged ahead with building from source and the process turned out to be quite painless. The one thing worth mentioning is that attempting to install the package checkinstall results in: E: Unable to locate package checkinstall [2] ... but everything worked fine without it. [2] I could find no documentation anywhere of checkinstall being withdrawn as a package. From robertvstepp at gmail.com Sat May 9 13:25:10 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 9 May 2020 12:25:10 -0500 Subject: [Tutor] Full code i get error when i send email using python In-Reply-To: References: Message-ID: <20200509172510.GA17365@Dream-Machine1> I have spent the past couple of days getting mutt to work with my Gmail account. Some of that might be relevant to what you are attempting. On Sat, May 09, 2020 at 04:31:16AM -0400, Michael Crooks wrote: > import smtplib > > host = "smtp.gmail.com" > port = 587 > username ="testingprogramsmichael at gmail.com" > password = "Oliver17" > from_email = username > to_list = ["testingprogramsmichael at gmail.com"] Gmail will not allow you to connect with just a user name and password like you would in its web interface when you are trying to access it programmatically. As far as I can tell you have three possibilities to satisfy Gmail authentication requirements: 1) Generate an application-specific password for your Google account (your only option if you are using two-factor authentication). See https://support.google.com/accounts/answer/185833 2) Turn on less-secure app access (not an option with two-factor authentication). See https://myaccount.google.com/lesssecureapps?pli=1 [The above two points were copied near verbatim from https://unix.stackexchange.com/questions/226936/how-to-install-setup-mutt-with-gmail-on-centos-and-ubuntu] 3) There are ways to use OAuth2.0, but it appears to be more complicated. I will leave it to you to search for articles on using this with Gmail if it is relevant to your use case. Guessing from what you are appearing to be trying to do I would guess that option (1) might be the way to go. It is designed to generate an app-specific user name/password combination, so that if these become public (As your "test account" credentials above have become ~(:>)) ) only that app has been compromised, not your entire Google account. -- Wishing you only the best, boB Stepp From akleider at sonic.net Sat May 9 13:56:04 2020 From: akleider at sonic.net (Alex Kleider) Date: Sat, 09 May 2020 10:56:04 -0700 Subject: [Tutor] cant send email using python keep getting error In-Reply-To: References: Message-ID: <2e3c6f4d50ce19fdcc9e6de831067973@sonic.net> On 2020-05-08 23:08, Michael Crooks wrote: > raise SMTPAuthenticationError(code, resp) > smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password > not > accepted. Learn more at\n5.7.8 > https://support.google.com/mail/?p=BadCredentials m203sm3339543vka.41 - > gsmtp') > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor Is your goal simply to have a python program send (one or more) emails via your gmail account? If so, I might be able to help you. I've done it but was unhappy because if the recipient was also a gmail user the email contained an ominous warning about the email's authenticity. For this reason I switched to easydns.com. I was able to add a 'Reply-To' header so replies would come to my gmail account and most users would think the email came from that same gmail account. Let me know and if you want I'll 'dust off' the code that used gmail, see if it still works and, if so, share it. (It's all on github[1] but mixed in with a lot of other stuff the sorting out of which would probably be daunting!) [1] https://github.com/alexKleider/Club_Utilities From jf_byrnes at comcast.net Sat May 9 09:23:40 2020 From: jf_byrnes at comcast.net (Jim) Date: Sat, 9 May 2020 08:23:40 -0500 Subject: [Tutor] how to install python3.8 using virtualenvwrapper In-Reply-To: References: Message-ID: On 5/8/20 9:14 PM, Alex Kleider wrote: > > My platform is Debian 10 (Buster) > which comes with Python 2.7 and Python 3.7 preinstalled. > > I've successfully got virtualenvwrapper running: > [ # install python3-pip > ? $ pip3 install virtualenvwrapper > then make the appropriate entries in ~/.bashrc and source it...] > > Now I'd like to have an env using python 3.8. > > $ makevirtualenv -p python3.7 p37 > gives me a Python 3.7 environment but > $ makevirtualenv -p python3.8 p38 > fails. > > Is it possible to bring in python 3.8 using pip (or some other means) > or must I build from source?[1] > > > [1] as described here: > https://tecadmin.net/install-python-3-8-ubuntu/ > > Any suggestions would be very much appreciated. > Cheers, > Alex > > > PS Forgive me if this is a duplication.? I remember composing this > request for help within the last few days but don't remember seeing > it on the list and can't find it in my 'sent' folder. Alex, You could look for a PPA that has it. I installed 3.8 from LP-PPA-deadsnakes. However the last time I looked they don't offer 3.8 anymore. They show 3.7 and 3.9. They say 3.8 comes with later versions of Ubuntu. You could look there to see if maybe they have it buried some place. There are other PPA's around, maybe on of them has it. Hope this helps, Jim From dfjennings at gmail.com Sat May 9 21:18:37 2020 From: dfjennings at gmail.com (Don Jennings) Date: Sat, 9 May 2020 21:18:37 -0400 Subject: [Tutor] how to install python3.8 using virtualenvwrapper In-Reply-To: <4b392d6d124e8f42521ae75570a9e824@sonic.net> References: <4b392d6d124e8f42521ae75570a9e824@sonic.net> Message-ID: <046EDD46-D18E-4ADB-BB8D-F0CD8A3B75DC@gmail.com> I?m glad you were able to make progress. I?ve been using pyenv [1] ever since I read a piece by Jacob Kaplan-Moss about his choice of tools [2]. Recently I replaced pipenv with pyenv-virtualenv [3] and direnv [4] to the mix. It?s the best setup I?ve ever used for managing multiple projects with differing requirements. I?d be remiss if I didn?t mention pipx [5] for python command line tools like black, flake8 and awscli. Best, Don [1] https://github.com/pyenv/pyenv [2] https://jacobian.org/2018/feb/21/python-environment-2018/ [3] https://github.com/pyenv/pyenv-virtualenv [4] https://direnv.net [5] https://github.com/pipxproject/pipx > On May 9, 2020, at 1:16 PM, Alex Kleider wrote: > > On 2020-05-08 19:14, Alex Kleider wrote: > > - snip - >> Is it possible to bring in python 3.8 using pip (or some other means) >> or must I build from source?[1] >> [1] as described here: >> https://tecadmin.net/install-python-3-8-ubuntu/ > > Not having received any suggestions, I forged ahead with building from source > and the process turned out to be quite painless. > The one thing worth mentioning is that attempting to install the package checkinstall results in: > E: Unable to locate package checkinstall [2] > ... but everything worked fine without it. > > [2] I could find no documentation anywhere of checkinstall being withdrawn as a package. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From akleider at sonic.net Sat May 9 21:43:01 2020 From: akleider at sonic.net (Alex Kleider) Date: Sat, 09 May 2020 18:43:01 -0700 Subject: [Tutor] how to install python3.8 using virtualenvwrapper In-Reply-To: <046EDD46-D18E-4ADB-BB8D-F0CD8A3B75DC@gmail.com> References: <4b392d6d124e8f42521ae75570a9e824@sonic.net> <046EDD46-D18E-4ADB-BB8D-F0CD8A3B75DC@gmail.com> Message-ID: <0c61ffd57eaa1bafe16511c15682276e@sonic.net> On 2020-05-09 18:18, Don Jennings wrote: > I?m glad you were able to make progress. > > I?ve been using pyenv [1] ever since I read a piece by Jacob > Kaplan-Moss about his choice of tools [2]. Recently I replaced pipenv > with pyenv-virtualenv [3] and direnv [4] to the mix. It?s the best > setup I?ve ever used for managing multiple projects with differing > requirements. I?d be remiss if I didn?t mention pipx [5] for python > command line tools like black, flake8 and awscli. > > Best, > Don > > [1] https://github.com/pyenv/pyenv > [2] https://jacobian.org/2018/feb/21/python-environment-2018/ > [3] https://github.com/pyenv/pyenv-virtualenv > [4] https://direnv.net > [5] https://github.com/pipxproject/pipx > So many choices. I notice there is an update to your reference [2]: https://jacobian.org/2019/nov/11/python-environment-2020/ It also seems that your system allows you to bring in any version of python without compiling locally. My impression (rightly or wrongly) is that for virtualenv (and virtualenvwrapper) there's a file system with all python related code for each venv while with the system(s) you describe, there's only one copy of each version of Python and the venv 'knows' which one to use thus saving disk space. That would be a considerable advantage if you had many venvs using the same Python version but different in other respects (imported modules.) Thanks for your note. Alex From nitishworks1 at gmail.com Sun May 10 23:46:25 2020 From: nitishworks1 at gmail.com (Nitish Kumar) Date: Mon, 11 May 2020 09:16:25 +0530 Subject: [Tutor] project euler #4 Message-ID: i am an ansolute noob at python...i started teaching myself a while back please review my code....and please point out the errors... can i not call or a function in a loop?? #largest 3x3 digit palindrome no palin = [] for i in range(100, 999): for j in range(100, 999): x = (i* j) if x isPalindrome(x) palind.append(t) print(palin) def isPalindrome(n): temp = n rev = 0 while(n > 0): digit = n % 10 rev = rev*10 + digit n = n // 10 if rev == temp: return True From alan.gauld at yahoo.co.uk Mon May 11 04:01:54 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 11 May 2020 09:01:54 +0100 Subject: [Tutor] project euler #4 In-Reply-To: References: Message-ID: On 11/05/2020 04:46, Nitish Kumar wrote: > i am an ansolute noob at python...i started teaching myself a while back > please review my code....and please point out the errors... It would help us if you could point out the errors. Specifically include any error messages and tell us what happens when you run it. Don't expect us to run a strangers code from an email.) > can i not call or a function in a loop?? You can call all the functions you want. > #largest 3x3 digit palindrome no > > palin = [] > for i in range(100, 999): > for j in range(100, 999): > x = (i* j) I'm not sure why you put this in parens, it not needed. > if x isPalindrome(x) This should give a syntax error - no : And no indented block > palind.append(t) And this should give a name error. Check the spelling. > print(palin) > > > > > def isPalindrome(n): > temp = n > rev = 0 > while(n > 0): > digit = n % 10 > rev = rev*10 + digit > n = n // 10 This loop should never end since n will always be greater than zero, albeit becoming very small. > if rev == temp: > return True -- 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 nulla.epistola at web.de Mon May 11 05:04:42 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Mon, 11 May 2020 11:04:42 +0200 Subject: [Tutor] project euler #4 In-Reply-To: References: Message-ID: Am 11.05.2020 um 10:01 schrieb Alan Gauld via Tutor: > On 11/05/2020 04:46, Nitish Kumar wrote: >> i am an ansolute noob at python...i started teaching myself a while back >> please review my code....and please point out the errors... > >> def isPalindrome(n): >> temp = n >> rev = 0 >> while(n > 0): >> digit = n % 10 >> rev = rev*10 + digit >> n = n // 10 > > This loop should never end since n will always be > greater than zero, albeit becoming very small. > Wrong. The division is integer division, of course n will be zero. This might be a little faster using divmod(n, 10) - and learning about divmod will often be useful. But the function is quite correct. Greetings Sibylle From nulla.epistola at web.de Mon May 11 05:04:42 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Mon, 11 May 2020 11:04:42 +0200 Subject: [Tutor] project euler #4 In-Reply-To: References: Message-ID: Am 11.05.2020 um 10:01 schrieb Alan Gauld via Tutor: > On 11/05/2020 04:46, Nitish Kumar wrote: >> i am an ansolute noob at python...i started teaching myself a while back >> please review my code....and please point out the errors... > >> def isPalindrome(n): >> temp = n >> rev = 0 >> while(n > 0): >> digit = n % 10 >> rev = rev*10 + digit >> n = n // 10 > > This loop should never end since n will always be > greater than zero, albeit becoming very small. > Wrong. The division is integer division, of course n will be zero. This might be a little faster using divmod(n, 10) - and learning about divmod will often be useful. But the function is quite correct. Greetings Sibylle From PyTutor at danceswithmice.info Mon May 11 07:17:03 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Mon, 11 May 2020 23:17:03 +1200 Subject: [Tutor] project euler #4 In-Reply-To: References: Message-ID: On 11/05/20 9:04 PM, Sibylle Koczian wrote: > Am 11.05.2020 um 10:01 schrieb Alan Gauld via Tutor: >> On 11/05/2020 04:46, Nitish Kumar wrote: >>> i am an ansolute noob at python...i started teaching myself a while back >>> please review my code....and please point out the errors... >> >>> def isPalindrome(n): >>> ???? temp = n >>> ???? rev = 0 >>> ???? while(n > 0): >>> ???????? digit = n % 10 >>> ???????? rev = rev*10 + digit >>> ???????? n = n // 10 >> >> This loop should never end since n will always be >> greater than zero, albeit becoming very small. >> > Wrong. The division is integer division, of course n will be zero. This > might be a little faster using divmod(n, 10) - and learning about divmod > will often be useful. But the function is quite correct. To solve problems of this nature add 'debug print' calls, to keep track of pertinent values, eg before modifying "n" in the while loop, add: print( "Loop values:", n, digit, rev ) The debug-print will immediately demonstrate if the code is working, step-by-step (loop-by-loop?) - or not, and thus allow you to debug on your own. That said, this algorithm is attempting to solve the problem in a mathematical fashion. It will only work with numbers. Many play with palindromes that are words, eg everyone's ?favorite? band: ABBA. If, the input number were converted to a string (it might even have originally been input as a string?), then the process of proving a palindrome becomes an exercise in string indexing or slicing - depending upon whether each character is considered in-turn, or whether the algorithm slices the word in half, reverses the characters in one half and then tries for equality with the other... (study operations on strings of characters) At which point, you would have a more flexible solution that works for 'both' input types, cf only 'numbers'! As a newbie, you may like to follow-up on the (Computer Science) definition of "polymorphism"... Please note: I am not saying that your approach is "wrong", will never work, nor that it is inferior or "insufficient" for your objectives! -- Regards =dn From alan.gauld at yahoo.co.uk Mon May 11 12:36:25 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 11 May 2020 17:36:25 +0100 Subject: [Tutor] project euler #4 In-Reply-To: References: Message-ID: On 11/05/2020 10:04, Sibylle Koczian wrote: >>> n = n // 10 >> >> This loop should never end since n will always be >> greater than zero, albeit becoming very small. >> > Wrong. The division is integer division, Good catch, I didn't notice the double // And also a goof point on use of divmod(). -- 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 Mon May 11 12:39:18 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 11 May 2020 17:39:18 +0100 Subject: [Tutor] project euler #4 In-Reply-To: References: Message-ID: On 11/05/2020 17:36, Alan Gauld via Tutor wrote: > Good catch, I didn't notice the double // > And also a goof point on use of divmod(). goof -> good... doh! -- 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 mats at wichmann.us Mon May 11 14:08:14 2020 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 11 May 2020 12:08:14 -0600 Subject: [Tutor] project euler #4 In-Reply-To: References: Message-ID: <0240fc70-192b-4abd-d7e7-5ce9b5774175@wichmann.us> On 5/11/20 5:17 AM, DL Neil via Tutor wrote: > > That said, this algorithm is attempting to solve the problem in a > mathematical fashion. It will only work with numbers. > > Many play with palindromes that are words, eg everyone's ?favorite? > band: ABBA. > > If, the input number were converted to a string (it might even have > originally been input as a string?), then the process of proving a > palindrome becomes an exercise in string indexing or slicing - depending > upon whether each character is considered in-turn, or whether the > algorithm slices the word in half, reverses the characters in one half > and then tries for equality with the other... > (study operations on strings of characters) > > > At which point, you would have a more flexible solution that works for > 'both' input types, cf only 'numbers' So to Nitish, the OP: congratulations on taking on the project Euler problems, they're really neat. You've also stumbled on an interesting thing that sometimes happens with this list, and in fact any general help forum. The Euler problems are attempting to teach _mathematical_ concepts (encouraging the use of a computer to assist), while where here on the list tend to approach problems as ones of what are optimal Python approaches. Just like DL Neil, I immediately thought of solving this by using strings, which Python handles very easily. So this replacement function works quite nicely, and teaches you nothing about mathematics - was that your aim? Or was Python your aim? def isPalindrome(n): n = str(n).casefold() # eliminate any string case differences return n == n[::-1] the right-hand side n[::-1] steps backwards through the string giving you a new string which is the reverse of the original (this syntax is what is called "slicing"); if old and new are equal it's a palindrome and the return will be True, else the return will be False. since your problem is to find the largest, after you've collected the list of palindromes, you can emit it with print(max(palin)) From robertvstepp at gmail.com Mon May 11 14:36:35 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 11 May 2020 13:36:35 -0500 Subject: [Tutor] Newline issues Message-ID: <20200511183635.GA27750@Dream-Machine1> My end goal: Get my Google contacts into Mutt. My process so far: Export contacts from Google Contacts as a vCard file. Use VObject (http://eventable.github.io/vobject/) to parse the vCard file. But the file that exports from Google-land has some issues that causes VCard to throw parsing exceptions. I have identified in contacts.vcf (the vCard file) the problems that cause the parsing exceptions. (1) All address lines have a duplicate entry tacked onto the end with embedded '\n's. (2) In the notes entry there are embedded '\n's. So I first was going to address the embedded '\n's by using a s.replace('\n', ' ') approach. This failed. So I wrote the following test program to try to understand what was happening: with open("test.txt") as f: for line in f: print(line) print(line.replace("\n", "")) print(line.replace(r"\n", "")) print(line.replace("\\", "")) test.txt (an actual excerpt from a fake Google contact export): NOTE:This is a test contact to see all fields.\n2nd line\: Did not fill in \"Chat\" field.\n3rd line\: Did not fill in \"Internet call\" field.\n4t h line\: I will keep typing until the editor flows this text to the follo wing line. It will now happen.\n1st custom label: My first custom field\n 2nd custom label: My second custom field\n3rd custom label: My third custo m field Running the program on this file produced the following output: NOTE:This is a test contact to see all fields.\n2nd line\: Did not fill in NOTE:This is a test contact to see all fields.\n2nd line\: Did not fill in NOTE:This is a test contact to see all fields.2nd line\: Did not fill in NOTE:This is a test contact to see all fields.n2nd line: Did not fill in [-- snipped remaining output --] The first line appears as is. The second had no effect on replacing the apparent '\n' characters. The third line shows that using raw strings *did* remove the apparent '\n' characters. Finally, the fourth line (removing the forward slashes) did so leaving all associated 'n's. My conclusion is that in the file the apparent newline characters are actually *two* characters, '\' and 'n'. Now we get to my point of confusion. When I copy and paste the text.txt contents into a triple-quoted string variable in the interpreter I get results I am not sure I understand: 3.7.5: s = """ ... NOTE:This is a test contact to see all fields.\n2nd line\: Did not fill in ... \"Chat\" field.\n3rd line\: Did not fill in \"Internet call\" field.\n4t ... h line\: I will keep typing until the editor flows this text to the follo ... wing line. It will now happen.\n1st custom label: My first custom field\n ... 2nd custom label: My second custom field\n3rd custom label: My third custo ... m field ... """ 3.7.5: s '\nNOTE:This is a test contact to see all fields.\n2nd line\\: Did not fill in\n "Chat" field.\n3rd line\\: Did not fill in "Internet call" field.\n4t\n h line\\: I will keep typing until the editor flows this text to the follo\n wing line. It will now happen.\n1st custom label: My first custom field\n\n 2nd custom label: My second custom field\n3rd custom label: My third custo\n m field\n' 3.7.5: print(s) NOTE:This is a test contact to see all fields. 2nd line\: Did not fill in "Chat" field. 3rd line\: Did not fill in "Internet call" field. 4t h line\: I will keep typing until the editor flows this text to the follo wing line. It will now happen. 1st custom label: My first custom field 2nd custom label: My second custom field 3rd custom label: My third custo m field I am not certain how just entering "s" in the interpreter will display in your MUAs, but in my display it as if the natural line breaks have vanished with the exception of the manual one I entered immediately after the first triple-quote and what I entered just before the final triple-quote. Finally, the print(s) apparently treats those '\' + 'n' characters as a genuine newline. Would someone please clarify the interpreter behavior for me and the difference from what I observed with the actual file? -- Wishing you only the best, boB Stepp From nulla.epistola at web.de Mon May 11 15:35:29 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Mon, 11 May 2020 21:35:29 +0200 Subject: [Tutor] project euler #4 In-Reply-To: <0240fc70-192b-4abd-d7e7-5ce9b5774175@wichmann.us> References: <0240fc70-192b-4abd-d7e7-5ce9b5774175@wichmann.us> Message-ID: <43a627c8-bf12-053a-654b-bea7229e842c@web.de> Am 11.05.2020 um 20:08 schrieb Mats Wichmann: > > So to Nitish, the OP: congratulations on taking on the project Euler > problems, they're really neat. You've also stumbled on an interesting > thing that sometimes happens with this list, and in fact any general > help forum. > > The Euler problems are attempting to teach _mathematical_ concepts > (encouraging the use of a computer to assist), while where here on the > list tend to approach problems as ones of what are optimal Python > approaches. Just like DL Neil, I immediately thought of solving this by > using strings, which Python handles very easily. So this replacement > function works quite nicely, and teaches you nothing about mathematics - > was that your aim? Or was Python your aim? > Well - does splitting a number into its digits really teach much about mathematics, however it is done? But it's needed for several Euler problems, so a reusable way to do it, and do it fast, is useful. I'm not sure, by the way, which way is faster (division or converting to a string) - probably depends on problem details. So best write functions for both methods and keep them. Greetings Sibylle From nulla.epistola at web.de Mon May 11 15:35:29 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Mon, 11 May 2020 21:35:29 +0200 Subject: [Tutor] project euler #4 In-Reply-To: <0240fc70-192b-4abd-d7e7-5ce9b5774175@wichmann.us> References: <0240fc70-192b-4abd-d7e7-5ce9b5774175@wichmann.us> Message-ID: <43a627c8-bf12-053a-654b-bea7229e842c@web.de> Am 11.05.2020 um 20:08 schrieb Mats Wichmann: > > So to Nitish, the OP: congratulations on taking on the project Euler > problems, they're really neat. You've also stumbled on an interesting > thing that sometimes happens with this list, and in fact any general > help forum. > > The Euler problems are attempting to teach _mathematical_ concepts > (encouraging the use of a computer to assist), while where here on the > list tend to approach problems as ones of what are optimal Python > approaches. Just like DL Neil, I immediately thought of solving this by > using strings, which Python handles very easily. So this replacement > function works quite nicely, and teaches you nothing about mathematics - > was that your aim? Or was Python your aim? > Well - does splitting a number into its digits really teach much about mathematics, however it is done? But it's needed for several Euler problems, so a reusable way to do it, and do it fast, is useful. I'm not sure, by the way, which way is faster (division or converting to a string) - probably depends on problem details. So best write functions for both methods and keep them. Greetings Sibylle From akleider at sonic.net Mon May 11 15:50:33 2020 From: akleider at sonic.net (Alex Kleider) Date: Mon, 11 May 2020 12:50:33 -0700 Subject: [Tutor] Newline issues In-Reply-To: <20200511183635.GA27750@Dream-Machine1> References: <20200511183635.GA27750@Dream-Machine1> Message-ID: On 2020-05-11 11:36, boB Stepp wrote: > My end goal: Get my Google contacts into Mutt. Are you trying to create a "~/.muttalias" file? If so, I can send you some code that accomplishes this (using a gmail exported contacts.csv file as input.) Let me know. Alex > > My process so far: Export contacts from Google Contacts as a vCard > file. > Use VObject (http://eventable.github.io/vobject/) to parse the vCard > file. But > the file that exports from Google-land has some issues that causes > VCard to throw parsing exceptions. I have identified in contacts.vcf > (the vCard file) the problems that cause the parsing exceptions. (1) > All > address lines have a duplicate entry tacked onto the end with embedded > '\n's. (2) In the notes entry there are embedded '\n's. > > So I first was going to address the embedded '\n's by using a > s.replace('\n', ' ') approach. This failed. So I wrote the following > test > program to try to understand what was happening: > > with open("test.txt") as f: > for line in f: > print(line) > print(line.replace("\n", "")) > print(line.replace(r"\n", "")) > print(line.replace("\\", "")) > > test.txt (an actual excerpt from a fake Google contact export): > > NOTE:This is a test contact to see all fields.\n2nd line\: Did not > fill in > \"Chat\" field.\n3rd line\: Did not fill in \"Internet call\" > field.\n4t > h line\: I will keep typing until the editor flows this text to the > follo > wing line. It will now happen.\n1st custom label: My first custom > field\n > 2nd custom label: My second custom field\n3rd custom label: My third > custo > m field > > Running the program on this file produced the following output: > > NOTE:This is a test contact to see all fields.\n2nd line\: Did not > fill in > > NOTE:This is a test contact to see all fields.\n2nd line\: Did not > fill in > NOTE:This is a test contact to see all fields.2nd line\: Did not fill > in > > NOTE:This is a test contact to see all fields.n2nd line: Did not fill > in > [-- snipped remaining output --] > > The first line appears as is. > > The second had no effect on replacing the apparent '\n' characters. > > The third line shows that using raw strings *did* remove the apparent > '\n' > characters. > > Finally, the fourth line (removing the forward slashes) did so leaving > all > associated 'n's. > > My conclusion is that in the file the apparent newline characters are > actually *two* characters, '\' and 'n'. > > Now we get to my point of confusion. When I copy and paste the > text.txt > contents into a triple-quoted string variable in the interpreter I get > results I am not sure I understand: > > 3.7.5: s = """ > ... NOTE:This is a test contact to see all fields.\n2nd line\: > Did not fill in > ... \"Chat\" field.\n3rd line\: Did not fill in \"Internet > call\" field.\n4t > ... h line\: I will keep typing until the editor flows this text > to the follo > ... wing line. It will now happen.\n1st custom label: My first > custom field\n > ... 2nd custom label: My second custom field\n3rd custom label: > My third custo > ... m field > ... """ > 3.7.5: s > '\nNOTE:This is a test contact to see all fields.\n2nd line\\: Did > not fill in\n "Chat" field.\n3rd line\\: Did not fill in "Internet > call" field.\n4t\n h line\\: I will keep typing until the editor > flows this text to the follo\n wing line. It will now happen.\n1st > custom label: My first custom field\n\n 2nd custom label: My second > custom field\n3rd custom label: My third custo\n m field\n' > 3.7.5: print(s) > > NOTE:This is a test contact to see all fields. > 2nd line\: Did not fill in > "Chat" field. > 3rd line\: Did not fill in "Internet call" field. > 4t > h line\: I will keep typing until the editor flows this text to the > follo > wing line. It will now happen. > 1st custom label: My first custom field > > 2nd custom label: My second custom field > 3rd custom label: My third custo > m field > > I am not certain how just entering "s" in the interpreter will display > in > your MUAs, but in my display it as if the natural line breaks have > vanished with the exception of the manual one I entered immediately > after > the first triple-quote and what I entered just before the final > triple-quote. > > Finally, the print(s) apparently treats those '\' + 'n' characters as a > genuine newline. Would someone please clarify the interpreter behavior > for > me and the difference from what I observed with the actual file? From robertvstepp at gmail.com Mon May 11 15:59:05 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 11 May 2020 14:59:05 -0500 Subject: [Tutor] Newline issues In-Reply-To: References: <20200511183635.GA27750@Dream-Machine1> Message-ID: <20200511195905.GA28948@Dream-Machine1> On Mon, May 11, 2020 at 12:50:33PM -0700, Alex Kleider wrote: > On 2020-05-11 11:36, boB Stepp wrote: > > My end goal: Get my Google contacts into Mutt. > > Are you trying to create a "~/.muttalias" file? > If so, I can send you some code that accomplishes this (using a gmail > exported contacts.csv file as input.) > Let me know. I was originally going to take that approach, but I stumbled across the simple abook address book program designed to work with Mutt, so my end goal is to get as many of my contacts' details into abook as possible, which will probably be just about everything now that I know more about configuring abook. After that is accomplished I will be able to use my contacts inside Mutt. -- Wishing you only the best, boB Stepp From oscar.j.benjamin at gmail.com Mon May 11 16:13:35 2020 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 11 May 2020 21:13:35 +0100 Subject: [Tutor] project euler #4 In-Reply-To: <0240fc70-192b-4abd-d7e7-5ce9b5774175@wichmann.us> References: <0240fc70-192b-4abd-d7e7-5ce9b5774175@wichmann.us> Message-ID: On Mon, 11 May 2020 at 19:08, Mats Wichmann wrote: > > On 5/11/20 5:17 AM, DL Neil via Tutor wrote: > > > > That said, this algorithm is attempting to solve the problem in a > > mathematical fashion. It will only work with numbers. > > The Euler problems are attempting to teach _mathematical_ concepts > (encouraging the use of a computer to assist), while where here on the > list tend to approach problems as ones of what are optimal Python > approaches. Optimal Python approaches should bear in mind the problem which in this case *is* mathematical. The Euler problem is here: https://projecteuler.net/problem=4 I think the intention behind the problem is not how to implement is_palindromic efficiently but how to reduce the search space so that you don't have to call is_palindromic for all of the 1000*1000 possibilities. In the 2 digit example given in the Euler problem the question would be to find the largest palindromic number that is a product of two 2 digit numbers. For that you might loop over the 10000 possible pairs of two digit numbers or you could reason it through: We want the largest Z = X*Y where Z is palindromic and X and Y are 2 digit numbers. 1. The largest possible product of two 2 digit numbers is 99*99 = 9801 which is not palindromic but it shows how high we can go. Let's make the ansatz that Z is a 4 digit number with leading coefficient 9. 2. Our assumption implies that X and Y both have 1st digit 9 because the largest possibility not satisfying that is too small: 89*99 < 90*100 == 9000. 3. Since the 1st digit of Z is 9 the last digit is 9 as well so Z is like 9??9. Since the final digit is 9 we know that the last digits of X and Y have to have a product with last digit 9 so they have to be both odd and not 5 i.e. 1, 3, 7, or 9. There are only 3 possibilities for the last digits: (1, 9), (3, 3), (7, 7). 4. That leaves 3 possibilities to test: >>> 91*99 9009 >>> 93*93 8649 >>> 97*97 9409 So we see that 9009 is the largest palindromic number that is a product of two 2 digit numbers. We assumed a leading digit 9 but clearly anything else would be smaller so we don't have to consider the other possibilities. In this example we can reduce the search space from 10000 to 3 which is enough to calculate by hand. In the 3 digit case the brute force search space is 100x bigger but can still be reduced substantially. -- Oscar From akleider at sonic.net Mon May 11 16:19:54 2020 From: akleider at sonic.net (Alex Kleider) Date: Mon, 11 May 2020 13:19:54 -0700 Subject: [Tutor] Newline issues In-Reply-To: <20200511195905.GA28948@Dream-Machine1> References: <20200511183635.GA27750@Dream-Machine1> <20200511195905.GA28948@Dream-Machine1> Message-ID: <403a006a1e51fc5bd3f76b0bccce8e20@sonic.net> On 2020-05-11 12:59, boB Stepp wrote: > On Mon, May 11, 2020 at 12:50:33PM -0700, Alex Kleider wrote: >> On 2020-05-11 11:36, boB Stepp wrote: >> > My end goal: Get my Google contacts into Mutt. >> >> Are you trying to create a "~/.muttalias" file? >> If so, I can send you some code that accomplishes this (using a gmail >> exported contacts.csv file as input.) >> Let me know. > > I was originally going to take that approach, but I stumbled across the > simple abook address book program designed to work with Mutt, so my end > goal is to get as many of my contacts' details into abook as possible, > which will probably be just about everything now that I know more about > configuring abook. > > After that is accomplished I will be able to use my contacts inside > Mutt. I see that abook provides 'export filters' one of which works from muttalias so you could create a muttalias file and then use it through the filter into abook. What is it about abook that you want/like/need? What functionality does it provide? The only 'features' described on their sourceforge page seem to be the import and export filters. From robertvstepp at gmail.com Mon May 11 16:51:20 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 11 May 2020 15:51:20 -0500 Subject: [Tutor] Newline issues In-Reply-To: <403a006a1e51fc5bd3f76b0bccce8e20@sonic.net> References: <20200511183635.GA27750@Dream-Machine1> <20200511195905.GA28948@Dream-Machine1> <403a006a1e51fc5bd3f76b0bccce8e20@sonic.net> Message-ID: <20200511205120.GB28948@Dream-Machine1> On Mon, May 11, 2020 at 01:19:54PM -0700, Alex Kleider wrote: > On 2020-05-11 12:59, boB Stepp wrote: > I see that abook provides 'export filters' one of which works from muttalias > so you could create a muttalias file and then use it through the filter into > abook. I actually don't need an alias file with abook. I can hook directly into its database. Just about three lines in my muttrc file. > What is it about abook that you want/like/need? What functionality does it > provide? > The only 'features' described on their sourceforge page seem to be the > import and export filters. Nothing spectacular. Just a convenient place to keep names, addresses, phone numbers, email addresses, notes on a contact, etc. Actually its import/export features are week, mostly in formats that don't get a lot of use from most people nowadays. -- Wishing you only the best, boB Stepp From akleider at sonic.net Mon May 11 16:56:32 2020 From: akleider at sonic.net (Alex Kleider) Date: Mon, 11 May 2020 13:56:32 -0700 Subject: [Tutor] Newline issues In-Reply-To: <20200511205120.GB28948@Dream-Machine1> References: <20200511183635.GA27750@Dream-Machine1> <20200511195905.GA28948@Dream-Machine1> <403a006a1e51fc5bd3f76b0bccce8e20@sonic.net> <20200511205120.GB28948@Dream-Machine1> Message-ID: <97b7beae8f1ccb2813cf883a39eb1020@sonic.net> On 2020-05-11 13:51, boB Stepp wrote: > On Mon, May 11, 2020 at 01:19:54PM -0700, Alex Kleider wrote: >> On 2020-05-11 12:59, boB Stepp wrote: > >> I see that abook provides 'export filters' one of which works from >> muttalias >> so you could create a muttalias file and then use it through the >> filter into >> abook. > > I actually don't need an alias file with abook. I can hook directly > into > its database. Just about three lines in my muttrc file. > >> What is it about abook that you want/like/need? What functionality >> does it >> provide? >> The only 'features' described on their sourceforge page seem to be the >> import and export filters. > > Nothing spectacular. Just a convenient place to keep names, addresses, > phone numbers, email addresses, notes on a contact, etc. > > Actually its import/export features are week, mostly in formats that > don't > get a lot of use from most people nowadays. Thanks for the info. As much as I dislike gmail, I do find that google's contacts is very useful since it is so full featured. I've yet to get the hang of using mutt all the time but really should. From akleider at sonic.net Mon May 11 17:05:07 2020 From: akleider at sonic.net (Alex Kleider) Date: Mon, 11 May 2020 14:05:07 -0700 Subject: [Tutor] Newline issues In-Reply-To: <20200511183635.GA27750@Dream-Machine1> References: <20200511183635.GA27750@Dream-Machine1> Message-ID: <20200511210507.GA2784@uno.bo.lan> On Mon, May 11, 2020 at 01:36:35PM -0500, boB Stepp wrote: > My end goal: Get my Google contacts into Mutt. > > My process so far: Export contacts from Google Contacts as a vCard file. Why vCard? Why not csv? Then you can use the csv module and specifically DictReader. From robertvstepp at gmail.com Mon May 11 17:11:41 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 11 May 2020 16:11:41 -0500 Subject: [Tutor] Newline issues In-Reply-To: <20200511210507.GA2784@uno.bo.lan> References: <20200511183635.GA27750@Dream-Machine1> <20200511210507.GA2784@uno.bo.lan> Message-ID: <20200511211141.GC28948@Dream-Machine1> On Mon, May 11, 2020 at 02:05:07PM -0700, Alex Kleider wrote: > On Mon, May 11, 2020 at 01:36:35PM -0500, boB Stepp wrote: > > My end goal: Get my Google contacts into Mutt. > > > > My process so far: Export contacts from Google Contacts as a vCard file. > > Why vCard? Why not csv? Then you can use the csv module and > specifically DictReader. Using the VObject library, which is designed to parse vCard and iCalendar formats, I already will have direct access to all attributes I am interested in. It should make it quite trivial to map vCard attributes to standard and the custom fields I mean to create in abook's addressbook format, which is a very straightforward and simple format. -- Wishing you only the best, boB Stepp From alan.gauld at yahoo.co.uk Mon May 11 19:21:42 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 12 May 2020 00:21:42 +0100 Subject: [Tutor] Newline issues In-Reply-To: <20200511183635.GA27750@Dream-Machine1> References: <20200511183635.GA27750@Dream-Machine1> Message-ID: On 11/05/2020 19:36, boB Stepp wrote: > Now we get to my point of confusion. When I copy and paste the text.txt > contents into a triple-quoted string variable in the interpreter I get > results I am not sure I understand: > > 3.7.5: s = """ > ... NOTE:This is a test contact to see all fields.\n2nd line\: Did not fill in > ... \"Chat\" field.\n3rd line\: Did not fill in \"Internet call\" field.\n4t > ... h line\: I will keep typing until the editor flows this text to the follo > ... wing line. It will now happen.\n1st custom label: My first custom field\n > ... 2nd custom label: My second custom field\n3rd custom label: My third custo > ... m field > ... """ > 3.7.5: s > '\nNOTE:This is a test contact to see all fields.\n2nd line\\: Did not fill in\n "Chat" field.\n3rd line\\: Did not fill in "Internet call" field.\n4t\n h line\\: I will keep typing until the editor flows this text to the follo\n wing line. It will now happen.\n1st custom label: My first custom field\n\n 2nd custom label: My second custom field\n3rd custom label: My third custo\n m field\n' > 3.7.5: print(s) > > NOTE:This is a test contact to see all fields. > 2nd line\: Did not fill in > "Chat" field. > 3rd line\: Did not fill in "Internet call" field. > 4t > h line\: I will keep typing until the editor flows this text to the follo > wing line. It will now happen. > 1st custom label: My first custom field > > 2nd custom label: My second custom field > 3rd custom label: My third custo > m field > > I am not certain how just entering "s" in the interpreter will display in > your MUAs, but in my display it as if the natural line breaks have > vanished with the exception of the manual one I entered immediately after > the first triple-quote and what I entered just before the final > triple-quote. I think you are seeing the difference between str.__repr__() and str.__str__() It happens with double or soingle quoted strings too: >>> print("this is a double\nline of text") this is a double line of text >>> "this is a double\nline of text" 'this is a double\nline of text' >>> repr() just outputs the characters without taking heed of escape characters like newlines whereas str() interprets escape characters. -- 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 Mon May 11 19:39:20 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 12 May 2020 00:39:20 +0100 Subject: [Tutor] project euler #4 In-Reply-To: <0240fc70-192b-4abd-d7e7-5ce9b5774175@wichmann.us> References: <0240fc70-192b-4abd-d7e7-5ce9b5774175@wichmann.us> Message-ID: On 11/05/2020 19:08, Mats Wichmann wrote: > > def isPalindrome(n): > n = str(n).casefold() # eliminate any string case differences I hadn't noticed casefold() before, but when I experiment it seems to be the same as lower(). What is the difference? The help() documentation doesn't clarify things much. -- 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 mats at wichmann.us Mon May 11 21:19:03 2020 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 11 May 2020 19:19:03 -0600 Subject: [Tutor] project euler #4 In-Reply-To: References: <0240fc70-192b-4abd-d7e7-5ce9b5774175@wichmann.us> Message-ID: On 5/11/20 5:39 PM, Alan Gauld via Tutor wrote: > On 11/05/2020 19:08, Mats Wichmann wrote: >> >> def isPalindrome(n): >> n = str(n).casefold() # eliminate any string case differences > > I hadn't noticed casefold() before, but when I experiment it seems > to be the same as lower(). What is the difference? > The help() documentation doesn't clarify things much. > > str.casefold() Return a casefolded copy of the string. Casefolded strings may be used for caseless matching. Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter '?' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to '?'; casefold() converts it to "ss". The casefolding algorithm is described in section 3.13 of the Unicode Standard. From alan.gauld at yahoo.co.uk Tue May 12 03:52:34 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 12 May 2020 08:52:34 +0100 Subject: [Tutor] project euler #4 In-Reply-To: References: <0240fc70-192b-4abd-d7e7-5ce9b5774175@wichmann.us> Message-ID: On 12/05/2020 02:19, Mats Wichmann wrote: > On 5/11/20 5:39 PM, Alan Gauld via Tutor wrote: >> On 11/05/2020 19:08, Mats Wichmann wrote: >>> >>> def isPalindrome(n): >>> n = str(n).casefold() # eliminate any string case differences >> > Casefolding is similar to lowercasing but more aggressive because it > is intended to remove all case distinctions in a string. For example, > the German lowercase letter '?' is equivalent to "ss". Since it is > already lowercase, lower() would do nothing to '?'; casefold() converts > it to "ss". Aha! We don't have any equivalent ambiguities in English so no wonder I couldn't find a difference. Thanks for clarifying. -- 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 May 12 03:52:34 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 12 May 2020 08:52:34 +0100 Subject: [Tutor] project euler #4 In-Reply-To: References: <0240fc70-192b-4abd-d7e7-5ce9b5774175@wichmann.us> Message-ID: On 12/05/2020 02:19, Mats Wichmann wrote: > On 5/11/20 5:39 PM, Alan Gauld via Tutor wrote: >> On 11/05/2020 19:08, Mats Wichmann wrote: >>> >>> def isPalindrome(n): >>> n = str(n).casefold() # eliminate any string case differences >> > Casefolding is similar to lowercasing but more aggressive because it > is intended to remove all case distinctions in a string. For example, > the German lowercase letter '?' is equivalent to "ss". Since it is > already lowercase, lower() would do nothing to '?'; casefold() converts > it to "ss". Aha! We don't have any equivalent ambiguities in English so no wonder I couldn't find a difference. Thanks for clarifying. -- 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 May 12 14:47:46 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 12 May 2020 13:47:46 -0500 Subject: [Tutor] Better way to remove lines from a list? Message-ID: <20200512184746.GA7019@Dream-Machine1> I have a test file with the following contents: ADR;TYPE=HOME:;;11601 Southridge Dr;Little Rock;AR;72212-1733;US;11601 Sout hridge Dr\nLittle Rock\, AR 72212-1733\nUS ADR;TYPE=WORK:;;1912 Green Mountain Dr;Little Rock;AR;72212;US;1912 Green M ountain Dr\nLittle Rock\, AR 72212\nUS more meaningless stuff even more meaningless stuff ADR:100;;4700 E McCain Blvd;North Little Rock;AR;72117;US;4700 E McCain Blv d\n100\nNorth Little Rock\, AR 72117\nUS I wish to remove the part of lines starting with "ADR" from the last semi-colon to the EOL *and* any following lines that continue this duplicated address. As far as I can tell every such instance in my actual vCard file has these subsequent lines starting with a single space before a new legitimate vCard property line occurs which always has a character in the first column of the line. I have a solution that works relying on these file-specific facts. After reading the file into a list using readlines() I have this function to do this processing: def clean_address(vCard): cleaned_vCard = [] for index, line in enumerate(vCard): clean_line = line if line.startswith("ADR"): clean_line = line.rpartition(";")[0] while True: if vCard[index + 1].startswith(" "): vCard.pop(index + 1) else: break cleaned_vCard.append(clean_line) return cleaned_vCard In the inner while loop I wanted to do the equivalent of saying "advance the outer for loop while staying inside the while loop". If I were able to do this I would not need to modify the vCard list in place. I tried to find a way to do this with ideas of next() or .__next__(), but I could not discover online how to access the for loop's iterator. I feel sure there is a better way to do what I want to accomplish, possibly completely altering the logic of my function or doing something along my above speculations. The other thing that bothers me is the fragility of my approach. I am relying on two things that I am sure are not true for a general export of a Google vCard: (1) What if I have an exceptionally long legitimate address that cannot be encompassed on a single line starting with "ADR"? In this case my function as written would not yield a correct address. (2) I am relying on illegitimate address duplicates starting on following lines beginning with a single space. For my particular vCard file I don't think these will affect me, but I would like to make this more robust just because it is the right thing to do. But at the moment I don't see how. And for a rhetorical question: Why can't I just make myself write the quick, obvious, but flawed program that would have had me done with this Sunday? -- Wishing you only the best, boB Stepp From __peter__ at web.de Tue May 12 17:59:18 2020 From: __peter__ at web.de (Peter Otten) Date: Tue, 12 May 2020 23:59:18 +0200 Subject: [Tutor] Better way to remove lines from a list? References: <20200512184746.GA7019@Dream-Machine1> Message-ID: boB Stepp wrote: > I have a test file with the following contents: > > ADR;TYPE=HOME:;;11601 Southridge Dr;Little Rock;AR;72212-1733;US;11601 > Sout > hridge Dr\nLittle Rock\, AR 72212-1733\nUS > ADR;TYPE=WORK:;;1912 Green Mountain Dr;Little Rock;AR;72212;US;1912 Green > M > ountain Dr\nLittle Rock\, AR 72212\nUS > more meaningless stuff > even more meaningless stuff > ADR:100;;4700 E McCain Blvd;North Little Rock;AR;72117;US;4700 E McCain > Blv > d\n100\nNorth Little Rock\, AR 72117\nUS > > I wish to remove the part of lines starting with "ADR" from the last > semi-colon to the EOL *and* any following lines that continue this > duplicated address. As far as I can tell every such instance in my actual > vCard file has these subsequent lines starting with a single space before > a new legitimate vCard property line occurs which always has a character > in the first column of the line. > > I have a solution that works relying on these file-specific facts. After > reading the file into a list using readlines() I have this function to do > this processing: > > def clean_address(vCard): > cleaned_vCard = [] > for index, line in enumerate(vCard): > clean_line = line > if line.startswith("ADR"): > clean_line = line.rpartition(";")[0] > while True: > if vCard[index + 1].startswith(" "): > vCard.pop(index + 1) > else: > break > cleaned_vCard.append(clean_line) > return cleaned_vCard > > In the inner while loop I wanted to do the equivalent of saying "advance > the outer for loop while staying inside the while loop". If I were > able to do this I would not need to modify the vCard list in place. I > tried to find a way to do this with ideas of next() or .__next__(), but I > could not discover online how to access the for loop's iterator. I feel > sure there is a better way to do what I want to accomplish, possibly > completely altering the logic of my function or doing something along my > above speculations. > > The other thing that bothers me is the fragility of my approach. I am > relying on two things that I am sure are not true for a general export of > a > Google vCard: (1) What if I have an exceptionally long legitimate address > that cannot be encompassed on a single line starting with "ADR"? In this > case my function as written would not yield a correct address. (2) I am > relying on illegitimate address duplicates starting on following lines > beginning with a single space. For my particular vCard file I don't think > these will affect me, but I would like to make this more robust just > because it is the right thing to do. But at the moment I don't see how. I doubt that the extra stuff in the ADR lines is illegitimate and think that the best solution would be to find a tool that can parse the data as-is. However, practicality beats purity. So how about merging the line and then removing everything starting with the 8th semicolon? Like # assuming that the colon after one of your ADRs is a typo def cleaned(line): if line.startswith("ADR;"): line = ";".join(line.split(";")[:8]) return line + "\n" cleaned_text = "".join( cleaned(line) for line in text.replace("\n ", "").splitlines() ) where text is the complete file as a string. From robertvstepp at gmail.com Tue May 12 19:33:38 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 12 May 2020 18:33:38 -0500 Subject: [Tutor] Better way to remove lines from a list? In-Reply-To: References: <20200512184746.GA7019@Dream-Machine1> Message-ID: <20200512233338.GB7019@Dream-Machine1> On Tue, May 12, 2020 at 11:59:18PM +0200, Peter Otten wrote: >boB Stepp wrote: > >> I have a test file with the following contents: >> >> ADR;TYPE=HOME:;;11601 Southridge Dr;Little Rock;AR;72212-1733;US;11601 >> Sout >> hridge Dr\nLittle Rock\, AR 72212-1733\nUS >> ADR;TYPE=WORK:;;1912 Green Mountain Dr;Little Rock;AR;72212;US;1912 Green >> M >> ountain Dr\nLittle Rock\, AR 72212\nUS >> more meaningless stuff >> even more meaningless stuff >> ADR:100;;4700 E McCain Blvd;North Little Rock;AR;72117;US;4700 E McCain >> Blv >> d\n100\nNorth Little Rock\, AR 72117\nUS >I doubt that the extra stuff in the ADR lines is illegitimate and think that >the best solution would be to find a tool that can parse the data as-is. I have to disagree about the illegitimacy of the data. According to "vCard 3.0 format specification" at https://www.evenx.com/vcard-3-0-format-specification an example of a properly formatted ADR property would be: ADR;TYPE=dom,home,postal,parcel: ;;123 Main Street;Any Town;CA;91921; where the bare semicolons indicate that post office address, extended address and country content fields, respectively, have been omitted. There is no provision for tacking on additional content fields to the ADR property. I double-checked this at the official standard RFC 2426 (https://tools.ietf.org/html/rfc2426#section-3.2.1) I have noted, though, that my full Google contacts vCard file includes quite a few extension fields to the standard vCard ones. So perhaps you are correct in the sense that Google intended this addition of a duplication of the address (with newlines embedded), but it is not the standard format. The parser I have found expects a standard vCard format and does parse extensions properly begun with "X-". Another possibility is that there is some non-standard expectation by Apple for their accepted vCard format. The Google Contacts page states that the export in vCard format is intended for iOS Contacts. >However, practicality beats purity. So how about merging the line and then >removing everything starting with the 8th semicolon? Like ># assuming that the colon after one of your ADRs is a typo That eighth semicolon is no typo. That is a direct copy and paste from a Google contacts export in vCard format. >def cleaned(line): > if line.startswith("ADR;"): > line = ";".join(line.split(";")[:8]) > return line + "\n" > >cleaned_text = "".join( > cleaned(line) for line in text.replace("\n ", "").splitlines() >) > >where text is the complete file as a string. However, this "practical" code looks useful for me. Thanks! -- Wishing you only the best, boB Stepp From __peter__ at web.de Wed May 13 14:04:10 2020 From: __peter__ at web.de (Peter Otten) Date: Wed, 13 May 2020 20:04:10 +0200 Subject: [Tutor] Better way to remove lines from a list? References: <20200512184746.GA7019@Dream-Machine1> <20200512233338.GB7019@Dream-Machine1> Message-ID: boB Stepp wrote: > On Tue, May 12, 2020 at 11:59:18PM +0200, Peter Otten wrote: >>boB Stepp wrote: >>I doubt that the extra stuff in the ADR lines is illegitimate and think >>that the best solution would be to find a tool that can parse the data >>as-is. > > I have to disagree about the illegitimacy of the data. After looking around a bit I've found no hints that you can add extra parts. It looks like you're right. >># assuming that the colon after one of your ADRs is a typo > > That eighth semicolon is no typo. That is a direct copy and paste from a > Google contacts export in vCard format. >>> ADR:100;;4700 E McCain Blvd;North Little Rock;AR;72117;US;4700 E McCain I meant the ":" after "ADR" in the line above, not the ";" after US in >>> ADR;TYPE=HOME:;;11601 Southridge Dr;Little Rock;AR;72212-1733;US;11601 From robertvstepp at gmail.com Wed May 13 14:49:22 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Wed, 13 May 2020 13:49:22 -0500 Subject: [Tutor] Better way to remove lines from a list? In-Reply-To: References: <20200512184746.GA7019@Dream-Machine1> <20200512233338.GB7019@Dream-Machine1> Message-ID: <20200513184922.GC7019@Dream-Machine1> On Wed, May 13, 2020 at 08:04:10PM +0200, Peter Otten wrote: >boB Stepp wrote: > >> On Tue, May 12, 2020 at 11:59:18PM +0200, Peter Otten wrote: >>># assuming that the colon after one of your ADRs is a typo >> >> That eighth semicolon is no typo. That is a direct copy and paste from a >> Google contacts export in vCard format. Oops! I did read your "colon" as semicolon. But despite that... >>>> ADR:100;;4700 E McCain Blvd;North Little Rock;AR;72117;US;4700 E McCain > >I meant the ":" after "ADR" in the line above, not the ";" after US in That is still legitimate syntax (with the colon after ADR). The "TYPE=" is entirely optional. I notice that the lack of "TYPE=" shows up in my Google contacts export whenever the type set in Google Contacts is "Other". -- Wishing you only the best, boB Stepp From __peter__ at web.de Wed May 13 15:41:06 2020 From: __peter__ at web.de (Peter Otten) Date: Wed, 13 May 2020 21:41:06 +0200 Subject: [Tutor] Better way to remove lines from a list? References: <20200512184746.GA7019@Dream-Machine1> <20200512233338.GB7019@Dream-Machine1> <20200513184922.GC7019@Dream-Machine1> Message-ID: boB Stepp wrote: > On Wed, May 13, 2020 at 08:04:10PM +0200, Peter Otten wrote: >>boB Stepp wrote: >> >>> On Tue, May 12, 2020 at 11:59:18PM +0200, Peter Otten wrote: > >>>># assuming that the colon after one of your ADRs is a typo >>> >>> That eighth semicolon is no typo. That is a direct copy and paste from >>> a Google contacts export in vCard format. > > Oops! I did read your "colon" as semicolon. But despite that... > >>>>> ADR:100;;4700 E McCain Blvd;North Little Rock;AR;72117;US;4700 E >>>>> McCain >> >>I meant the ":" after "ADR" in the line above, not the ";" after US in > > That is still legitimate syntax (with the colon after ADR). The "TYPE=" > is > entirely optional. I notice that the lack of "TYPE=" shows up in my > Google contacts export whenever the type set in Google Contacts is > "Other". > Then my suggested startswith check def cleaned(line): if line.startswith("ADR;"): line = ";".join(line.split(";")[:8]) return line + "\n" is wrong. I felt a little uneasy with just line.startswith("ADR") because in theory more letters could follow. From ekesawi at yahoo.com Thu May 14 05:16:32 2020 From: ekesawi at yahoo.com (EK Esawi) Date: Thu, 14 May 2020 09:16:32 +0000 (UTC) Subject: [Tutor] Replace nth item with single value in each nested list References: <948562158.44934.1589447792972.ref@mail.yahoo.com> Message-ID: <948562158.44934.1589447792972@mail.yahoo.com> Hi All-- i have a nested list like this a=[[1,2],[4,5],[7,8]]. i want to replace the second element in each nested list with a specific value i want something like this [[1,11],[4,11],]7,11]. I tried several things but nothing worked. I am hoping for a list comprehension solution Thanks--EK From mats at wichmann.us Thu May 14 08:47:12 2020 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 14 May 2020 06:47:12 -0600 Subject: [Tutor] Replace nth item with single value in each nested list In-Reply-To: <948562158.44934.1589447792972@mail.yahoo.com> References: <948562158.44934.1589447792972.ref@mail.yahoo.com> <948562158.44934.1589447792972@mail.yahoo.com> Message-ID: <79326295-1ff6-7ff7-c0f4-f1bb5202c755@wichmann.us> On 5/14/20 3:16 AM, EK Esawi via Tutor wrote: > Hi All-- > > i have a nested list like this a=[[1,2],[4,5],[7,8]]. i want to replace the second element in each nested list with a specific value > i want something like this [[1,11],[4,11],]7,11]. I tried several things but nothing worked. > I am hoping for a list comprehension solution It depends on how well-formed your data is. If it *always* looks like the above (the items in 'a' are always lists, and always have at least two elements), then: for sub in a: sub[1] = 11 If not consistent, then you have to take a bit more care to deal with errors. It also depends on what you want. A list comprehension could be written, but will give you a new list. Since lists are mutable you have the change in place option - if you want it. From ekesawi at yahoo.com Thu May 14 10:28:08 2020 From: ekesawi at yahoo.com (EK Esawi) Date: Thu, 14 May 2020 14:28:08 +0000 (UTC) Subject: [Tutor] Replace nth item with single value in each nested list References: <1484902566.164119.1589466488809.ref@mail.yahoo.com> Message-ID: <1484902566.164119.1589466488809@mail.yahoo.com> Hi all-- Thank you Mats for the help. On my previous post, I did not state my question accurately. The question is how do I replace the 2nd element in each sublist based on a condition? For example, replace the 2nd element with 11 in each sublist if it?s greater than 5. If a=[[1,2],[4,5],[7,8],[3,6]] then the desired results would be? a=[[1,2],[4,5],[7,11],[3,11]]. if possible via list comprehension Thanks again--EK. ? From breamoreboy at gmail.com Thu May 14 16:50:28 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Thu, 14 May 2020 21:50:28 +0100 Subject: [Tutor] Replace nth item with single value in each nested list In-Reply-To: <1484902566.164119.1589466488809@mail.yahoo.com> References: <1484902566.164119.1589466488809.ref@mail.yahoo.com> <1484902566.164119.1589466488809@mail.yahoo.com> Message-ID: On 14/05/2020 15:28, EK Esawi via Tutor wrote: > Hi all-- > > > Thank you Mats for the help. > > On my previous post, I did not state my question accurately. The question is how do I replace the 2nd element in each sublist based on a condition? For example, replace the 2nd element with 11 in each sublist if it?s greater than 5. If a=[[1,2],[4,5],[7,8],[3,6]] then the desired results would be? a=[[1,2],[4,5],[7,11],[3,11]]. if possible via list comprehension > > Thanks again--EK. > Why not extend Mats' example? for sub in a: if sub[1] > 5: sub[1] = 11 Why the list comprehension, what do you gain, if anything, from using one? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From narasimha928 at gmail.com Thu May 14 16:39:26 2020 From: narasimha928 at gmail.com (Narasimharao Nelluri) Date: Thu, 14 May 2020 13:39:26 -0700 Subject: [Tutor] Replace nth item with single value in each nested list In-Reply-To: <1484902566.164119.1589466488809@mail.yahoo.com> References: <1484902566.164119.1589466488809.ref@mail.yahoo.com> <1484902566.164119.1589466488809@mail.yahoo.com> Message-ID: check below solution. In [23]: a = [[1, 2], [4, 5], [7, 8], [3, 6]] In [24]: for out in a: ...: if out[-1] > 5: ...: out[-1] =11 ...: ...: In [25]: a Out[25]: [[1, 2], [4, 5], [7, 11], [3, 11]] In [26]: Thanks Narasimha On Thu, May 14, 2020 at 1:00 PM EK Esawi via Tutor wrote: > Hi all-- > > > Thank you Mats for the help. > > On my previous post, I did not state my question accurately. The question > is how do I replace the 2nd element in each sublist based on a condition? > For example, replace the 2nd element with 11 in each sublist if it?s > greater than 5. If a=[[1,2],[4,5],[7,8],[3,6]] then the desired results > would be a=[[1,2],[4,5],[7,11],[3,11]]. if possible via list comprehension > > Thanks again--EK. > > _______________________________________________ > 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 Thu May 14 17:32:18 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 14 May 2020 22:32:18 +0100 Subject: [Tutor] Replace nth item with single value in each nested list In-Reply-To: <1484902566.164119.1589466488809@mail.yahoo.com> References: <1484902566.164119.1589466488809.ref@mail.yahoo.com> <1484902566.164119.1589466488809@mail.yahoo.com> Message-ID: On 14/05/2020 15:28, EK Esawi via Tutor wrote: > If a=[[1,2],[4,5],[7,8],[3,6]] then the desired results would be? a=[[1,2],[4,5],[7,11],[3,11]]. > if possible via list comprehension Why do you want to use a list comprehension? They are used for creating new lists not modifying existing ones. It rather sounds like a homework exercise - a bad homework exercise at that. We don't do homework for you, although we can offer suggestions. But trying to force this into a list comprehension when it doesn't naturally fit is a strange request. It can be done but it wouldn't be very idiomatic Python. -- 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 ekesawi at yahoo.com Thu May 14 18:01:46 2020 From: ekesawi at yahoo.com (EK Esawi) Date: Thu, 14 May 2020 22:01:46 +0000 (UTC) Subject: [Tutor] Replace nth item with single value in each nested list References: <1048791361.482884.1589493706823.ref@mail.yahoo.com> Message-ID: <1048791361.482884.1589493706823@mail.yahoo.com> Hi All Thank you Narasimharao? and Alan for the help. The reason i want to use list comprehension is because I used it through my project and I just like it because it?s concise and short.? Lastly, I find it amusing and disappointing that some people seem to make judgment without any proof about a posting as whether the question asked is a homework or not-very disappointing indeed. In any case thank you. EK From alan.gauld at yahoo.co.uk Thu May 14 19:23:14 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 15 May 2020 00:23:14 +0100 Subject: [Tutor] Replace nth item with single value in each nested list In-Reply-To: <1048791361.482884.1589493706823@mail.yahoo.com> References: <1048791361.482884.1589493706823.ref@mail.yahoo.com> <1048791361.482884.1589493706823@mail.yahoo.com> Message-ID: On 14/05/2020 23:01, EK Esawi via Tutor wrote: > I find it amusing and disappointing that some people seem to make judgment > without any proof about a posting as whether the question asked is a > homework or not-very disappointing indeed. But there was evidence. An irrational desire to use an entirely inappropriate programming idiom to solve a problem. That's a very common sign that the question is a homework, as some teacher has come up with a challenge to test her students on the use of the current topic, whether its suitable in the real world or not.... List comprehensions are deceptively concise, but in this case it would result in extra memory usage and probably slower performance than the simpler in-place solution. Shorter code is not necessarily the best code. -- 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 akleider at sonic.net Thu May 14 23:43:43 2020 From: akleider at sonic.net (Alex Kleider) Date: Thu, 14 May 2020 20:43:43 -0700 Subject: [Tutor] Fwd: Re: Replace nth item with single value in each nested list In-Reply-To: <47df6e32284b8ecee840ae526f94f896@sonic.net> References: <1048791361.482884.1589493706823.ref@mail.yahoo.com> <1048791361.482884.1589493706823@mail.yahoo.com> <47df6e32284b8ecee840ae526f94f896@sonic.net> Message-ID: <1dd71875929fc9148e3a667b50cfc9c9@sonic.net> Inadvertently hit Reply instead of Reply-All; Sorry. -------- Original Message -------- Subject: Re: [Tutor] Replace nth item with single value in each nested list Date: 2020-05-14 20:42 From: Alex Kleider To: EK Esawi On 2020-05-14 15:01, EK Esawi via Tutor wrote: > Hi All > > Thank you Narasimharao? and Alan for the help. The reason i want to > use list comprehension is because I used it through my project and I > just like it because it?s concise and short.? Lastly, I find it > amusing and disappointing that some people seem to make judgment > without any proof about a posting as whether the question asked is a > homework or not-very disappointing indeed. I suggest you not express to much disappointment in/to people who are trying to help you. As to your desire to use list comprehension: I found your wish to do it this way intriguing but couldn't make it work until I did a little research and found the answer here: https://stackoverflow.com/questions/4260280/if-else-in-a-list-comprehension From ekesawi at yahoo.com Fri May 15 02:26:07 2020 From: ekesawi at yahoo.com (EK Esawi) Date: Fri, 15 May 2020 06:26:07 +0000 (UTC) Subject: [Tutor] Replace nth item with single value in each nested list References: <499457659.653655.1589523967961.ref@mail.yahoo.com> Message-ID: <499457659.653655.1589523967961@mail.yahoo.com> Hi All-- Thank you all for your input. It?s highly appreciated. With your help, I managed to produce something that works for me; but only works for nested lists with two entries. For more than two entire nested lists, it produces only 2 entries nested lists. Here is my formula: aa=[[x[0],60] if x[1] >= 3 else [x[0],x[1]] for x in a] a is my list ? Thanks again and have a nice weekend--EK From matthewrodrigues707 at gmail.com Fri May 15 02:06:13 2020 From: matthewrodrigues707 at gmail.com (Boi0) Date: Thu, 14 May 2020 23:06:13 -0700 Subject: [Tutor] Inventory problem Message-ID: I'm trying to make an RPG and I came across the issue of the inventory. I want the inventory to be opened by simply pressing i. I've looked everywhere on the internet for a solution to this (relatively simple) problem. Could someone answer this for me? From PyTutor at danceswithmice.info Fri May 15 03:04:20 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Fri, 15 May 2020 19:04:20 +1200 Subject: [Tutor] Inventory problem In-Reply-To: References: Message-ID: <9cf6a536-ad1c-63aa-47e0-5f75ea96c522@DancesWithMice.info> On 15/05/20 6:06 PM, Boi0 wrote: > I'm trying to make an RPG and I came across the issue of the inventory. I > want the inventory to be opened by simply pressing i. I've looked > everywhere on the internet for a solution to this (relatively simple) > problem. Could someone answer this for me? A Rocket-Propelled Grenade? As well as Python, which GUI are you employing? -- Regards =dn From alan.gauld at yahoo.co.uk Fri May 15 03:12:36 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 15 May 2020 08:12:36 +0100 Subject: [Tutor] Inventory problem In-Reply-To: References: Message-ID: On 15/05/2020 07:06, Boi0 wrote: > I'm trying to make an RPG and I came across the issue of the inventory. I > want the inventory to be opened by simply pressing i. We need a bit more information. How does your RPG work? Is it in a GUI or a text terminal? Or a web page? Are you using a particular framework such as PyGame? Or a particular GUI or web framework? Also, when you say "simply pressing i" does that mean you want to detect the keypress regardless of what else s happening in the game and immediately present the inventory? Or is this within the context of a menu or command line in which case it may involve hitting "enter" too? Finally, we need to know which OS you are using since these kinds of operations are often platform specific. -- 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 Fri May 15 10:15:12 2020 From: __peter__ at web.de (Peter Otten) Date: Fri, 15 May 2020 16:15:12 +0200 Subject: [Tutor] Replace nth item with single value in each nested list References: <499457659.653655.1589523967961.ref@mail.yahoo.com> <499457659.653655.1589523967961@mail.yahoo.com> Message-ID: EK Esawi via Tutor wrote: > Hi All-- > > > Thank you all for your input. It?s highly appreciated. With your help, I > managed to produce something that works for me; but only works for nested > lists with two entries. For more than two entire nested lists, it produces > only 2 entries nested lists. > > Here is my formula: > > aa=[[x[0],60] if x[1] >= 3 else [x[0],x[1]] for x in a] > > a is my list You can generalize this a little with slices aa = [x[:1] + [60 if x[1] >= 3 else x[1]] + x[2:] for x in a] but as was pointed out this is more complex than the inplace solution, for x in a: if x[1] >= 3: x[1] = 60 needs to do more work, and requires more memory. If you have numpy around there is another alternative: b = numpy.array(a) b[:,1][b[:,1] >= 3] = 60 Very concise, but I'd probably rewrite that with a helper variable b = numpy.array(a) c = b[:,1] c[c>=3] = 60 or transpose the array. From PyTutor at DancesWithMice.info Fri May 15 15:08:13 2020 From: PyTutor at DancesWithMice.info (DL Neil) Date: Sat, 16 May 2020 07:08:13 +1200 Subject: [Tutor] Replace nth item with single value in each nested list In-Reply-To: <1048791361.482884.1589493706823@mail.yahoo.com> References: <1048791361.482884.1589493706823.ref@mail.yahoo.com> <1048791361.482884.1589493706823@mail.yahoo.com> Message-ID: <57e8e866-a8ba-6bc0-4790-723de2833cf5@DancesWithMice.info> On 15/05/20 10:01 AM, EK Esawi via Tutor wrote: ...Lastly, I find it amusing and disappointing that some people seem to make judgment without any proof about a posting as whether the question asked is a homework or not-very disappointing indeed. 1 the people who have responded to you, have volunteered their time to assist - at no cost to yourself. Are you passing judgment on them? 2 did you explain the narrow confines of your use-case or learning-objective? Conversely, have you noticed the proportion of people who do actually declare that their question stems from a 'homework' assignment? Also, do you concede that someone asking for help with homework actually requires a different answer (promoting his/her learning objectives, cf earning a grade for him/her) to someone who has a problem coding Python (and wants a line of code corrected from a presumed construction to its working 'equivalent')? 3 were the alternative suggestions-provided, accurate? (and therefore, technically helpful - as well as coming from a person whose intent is to be helpful) 4 do you concede that the above (2 and 3) demonstrates your request and requirement to be beyond the average call for a solution to a coding problem? 5 have you noticed that your messages re-start a conversational-thread (at least three threads for this one conversation, in Thunderbird), whereas people who hit ReplyAll continue the same thread? 6 on the basis of the technical-level of questions you have posed 'here', you demonstrate a degree of programming expertise. Have you attempted to use that to help learners on the list (per 1, above)? - in the process you will learn how difficult it can be to understand someone's request when it may be filtered through English-language difficulties, the questioner's unfamiliarity with Python, and/or a basic lack of communication skills? -- Regards =dn From robertvstepp at gmail.com Fri May 15 16:31:03 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 15 May 2020 15:31:03 -0500 Subject: [Tutor] File path requirements (absolute or relative)? Message-ID: <20200515203103.GA3736@Dream-Machine1> My file structure for a project is as follows: ~ | Projects | project_name | docs | src project_name.py | tests test.py test_csv_file.csv I wish to pass the path for "test_csv_file.csv" from the test.py program to the function in src/project_name.py which processes csv files. Ideally I would like to use a relative path name like "../tests/test_csv_file" and have the function in src/project_name.py to be able to use it. But so far all of my efforts to use a relative path name have failed. Even "~/Projects/project_name/tests/test_csv_file.csv" fails. Only when I use the absolute path name "/Home/bob/Projects/project_name/tests/test_csv_file.csv" does the test complete successfully. What am I misunderstanding? -- Wishing you only the best, boB Stepp From mats at wichmann.us Fri May 15 16:35:59 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 15 May 2020 14:35:59 -0600 Subject: [Tutor] File path requirements (absolute or relative)? In-Reply-To: <20200515203103.GA3736@Dream-Machine1> References: <20200515203103.GA3736@Dream-Machine1> Message-ID: On 5/15/20 2:31 PM, boB Stepp wrote: > My file structure for a project is as follows: > > ~ > ??? | Projects > ??????? | project_name > ??????????? | docs > ??????????? | src > ??????????????? project_name.py > ??????????? | tests > ??????????????? test.py > ??????????????? test_csv_file.csv > > I wish to pass the path for "test_csv_file.csv" from the test.py program to > the function in src/project_name.py which processes csv files.? Ideally I > would like to use a relative path name like "../tests/test_csv_file" and > have the function in src/project_name.py to be able to use it.? But so far > all of my efforts to use a relative path name have failed.? Even > "~/Projects/project_name/tests/test_csv_file.csv" fails.? Only when I use > the absolute path name > "/Home/bob/Projects/project_name/tests/test_csv_file.csv" does the test > complete successfully.? What am I misunderstanding? > ~username is not interpreted by Python directly, it's a shell thing. For Python you can use os.path.expanduser or pathlib's Path.home() for the rest - if a relative path doesn't work, it usually means it isn't being evaluated in the context you think it is. relative paths certainly work, so you're likely getting them relative to someplace else. some debugging prints should help... From __peter__ at web.de Fri May 15 17:46:25 2020 From: __peter__ at web.de (Peter Otten) Date: Fri, 15 May 2020 23:46:25 +0200 Subject: [Tutor] File path requirements (absolute or relative)? References: <20200515203103.GA3736@Dream-Machine1> Message-ID: boB Stepp wrote: > My file structure for a project is as follows: > > ~ > | Projects > | project_name > | docs > | src > project_name.py > | tests > test.py > test_csv_file.csv > > I wish to pass the path for "test_csv_file.csv" from the test.py program > to > the function in src/project_name.py which processes csv files. Ideally I > would like to use a relative path name like "../tests/test_csv_file" and For that to work the current working directory has to be src, or docs, or tests. If you want to be independent from the working directory you can determine the directory containing tests.py from within tests.py with os.path.dirname(__file__). > have the function in src/project_name.py to be able to use it. But so far > all of my efforts to use a relative path name have failed. Even > "~/Projects/project_name/tests/test_csv_file.csv" fails. Only when I use > the absolute path name > "/Home/bob/Projects/project_name/tests/test_csv_file.csv" does the test > complete successfully. What am I misunderstanding? > From alan.gauld at yahoo.co.uk Fri May 15 17:46:41 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 15 May 2020 22:46:41 +0100 Subject: [Tutor] File path requirements (absolute or relative)? In-Reply-To: <20200515203103.GA3736@Dream-Machine1> References: <20200515203103.GA3736@Dream-Machine1> Message-ID: On 15/05/2020 21:31, boB Stepp wrote: > My file structure for a project is as follows: > > ~ > | Projects > | project_name > | docs > | src > project_name.py > | tests > test.py > test_csv_file.csv > > I wish to pass the path for "test_csv_file.csv" from the test.py program to > the function in src/project_name.py which processes csv files. Ideally I > would like to use a relative path name like "../tests/test_csv_file" and > have the function in src/project_name.py to be able to use it. But so far > all of my efforts to use a relative path name have failed. Can you show us some code? Relative paths should work, but they will b relative to the CWD. Where are you running the code from? -- 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 Fri May 15 18:16:55 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 15 May 2020 17:16:55 -0500 Subject: [Tutor] File path requirements (absolute or relative)? In-Reply-To: References: <20200515203103.GA3736@Dream-Machine1> Message-ID: <20200515221655.GB3736@Dream-Machine1> After reading this and Peter's reply my conclusion: I am so forgetful! I now realize I struggled with this same topic a couple of years ago and forgot what I then learned with the help of this forum. Heavy sigh. On Fri, May 15, 2020 at 02:35:59PM -0600, Mats Wichmann wrote: >~username is not interpreted by Python directly, it's a shell thing. I keep forgetting this. >For Python you can use os.path.expanduser or pathlib's Path.home() > >for the rest - if a relative path doesn't work, it usually means it >isn't being evaluated in the context you think it is. relative paths >certainly work, so you're likely getting them relative to someplace else. Yes. This should have awakened my sleeping faculties. >some debugging prints should help... If I wasn't so hard-headed in believing what I *thought was true*, I might have done so and not generated this thread. Thanks, Mats, for your patience. -- Wishing you only the best, boB Stepp From robertvstepp at gmail.com Fri May 15 18:20:27 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 15 May 2020 17:20:27 -0500 Subject: [Tutor] File path requirements (absolute or relative)? In-Reply-To: References: <20200515203103.GA3736@Dream-Machine1> Message-ID: <20200515222027.GC3736@Dream-Machine1> On Fri, May 15, 2020 at 11:46:25PM +0200, Peter Otten wrote: >If you want to be independent from the working directory you can determine >the directory containing tests.py from within tests.py with >os.path.dirname(__file__). This paragraph is what *finally* brought everything back to mind. If I would more consistently work on programming instead of every blue moon I might start remembering things. Another heavy sigh. Thanks, Peter, for your help and patience as well. -- Wishing you only the best, boB Stepp From matthewrodrigues707 at gmail.com Fri May 15 21:05:22 2020 From: matthewrodrigues707 at gmail.com (Boi0) Date: Fri, 15 May 2020 18:05:22 -0700 Subject: [Tutor] Tutor Digest, Vol 195, Issue 23 In-Reply-To: References: Message-ID: I'm working on a text-based RPG, I am on a Windows, and I want the inventory to open (by pressing i) without pressing enter. On Fri, May 15, 2020 at 9:00 AM wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > Today's Topics: > > 1. Replace nth item with single value in each nested list (EK Esawi) > 2. Inventory problem (Boi0) > 3. Re: Inventory problem (DL Neil) > 4. Re: Inventory problem (Alan Gauld) > 5. Re: Replace nth item with single value in each nested list > (Peter Otten) > > > > ---------- Forwarded message ---------- > From: EK Esawi > To: "akleider at sonic.net" > Cc: Tutor Com > Bcc: > Date: Fri, 15 May 2020 06:26:07 +0000 (UTC) > Subject: [Tutor] Replace nth item with single value in each nested list > Hi All-- > > > Thank you all for your input. It?s highly appreciated. With your help, I > managed to produce something that works for me; but only works for nested > lists with two entries. For more than two entire nested lists, it produces > only 2 entries nested lists. > > Here is my formula: > > aa=[[x[0],60] if x[1] >= 3 else [x[0],x[1]] for x in a] > > a is my list > > > > Thanks again and have a nice weekend--EK > > > > > ---------- Forwarded message ---------- > From: Boi0 > To: Tutor at python.org > Cc: > Bcc: > Date: Thu, 14 May 2020 23:06:13 -0700 > Subject: [Tutor] Inventory problem > I'm trying to make an RPG and I came across the issue of the inventory. I > want the inventory to be opened by simply pressing i. I've looked > everywhere on the internet for a solution to this (relatively simple) > problem. Could someone answer this for me? > > > > > ---------- Forwarded message ---------- > From: DL Neil > To: Tutor at python.org > Cc: > Bcc: > Date: Fri, 15 May 2020 19:04:20 +1200 > Subject: Re: [Tutor] Inventory problem > On 15/05/20 6:06 PM, Boi0 wrote: > > I'm trying to make an RPG and I came across the issue of the inventory. I > > want the inventory to be opened by simply pressing i. I've looked > > everywhere on the internet for a solution to this (relatively simple) > > problem. Could someone answer this for me? > > > A Rocket-Propelled Grenade? > > As well as Python, which GUI are you employing? > -- > Regards =dn > > > > > ---------- Forwarded message ---------- > From: Alan Gauld > To: tutor at python.org > Cc: > Bcc: > Date: Fri, 15 May 2020 08:12:36 +0100 > Subject: Re: [Tutor] Inventory problem > On 15/05/2020 07:06, Boi0 wrote: > > I'm trying to make an RPG and I came across the issue of the inventory. I > > want the inventory to be opened by simply pressing i. > > We need a bit more information. How does your RPG work? > Is it in a GUI or a text terminal? Or a web page? > Are you using a particular framework such as PyGame? > Or a particular GUI or web framework? > > Also, when you say "simply pressing i" does that mean you want to > detect the keypress regardless of what else s happening in the > game and immediately present the inventory? Or is this within the > context of a menu or command line in which case it may involve > hitting "enter" too? > > Finally, we need to know which OS you are using since these > kinds of operations are often platform specific. > > -- > 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 > > > > > > > ---------- Forwarded message ---------- > From: Peter Otten <__peter__ at web.de> > To: tutor at python.org > Cc: > Bcc: > Date: Fri, 15 May 2020 16:15:12 +0200 > Subject: Re: [Tutor] Replace nth item with single value in each nested list > EK Esawi via Tutor wrote: > > > Hi All-- > > > > > > Thank you all for your input. It?s highly appreciated. With your help, I > > managed to produce something that works for me; but only works for nested > > lists with two entries. For more than two entire nested lists, it > produces > > only 2 entries nested lists. > > > > Here is my formula: > > > > aa=[[x[0],60] if x[1] >= 3 else [x[0],x[1]] for x in a] > > > > a is my list > > You can generalize this a little with slices > > aa = [x[:1] + [60 if x[1] >= 3 else x[1]] + x[2:] for x in a] > > but as was pointed out this is more complex than the inplace solution, > > for x in a: > if x[1] >= 3: > x[1] = 60 > > needs to do more work, and requires more memory. > > If you have numpy around there is another alternative: > > b = numpy.array(a) > b[:,1][b[:,1] >= 3] = 60 > > Very concise, but I'd probably rewrite that with a helper variable > > b = numpy.array(a) > c = b[:,1] > c[c>=3] = 60 > > or transpose the array. > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Sat May 16 04:47:09 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 16 May 2020 09:47:09 +0100 Subject: [Tutor] Tutor Digest, Vol 195, Issue 23 In-Reply-To: References: Message-ID: On 16/05/2020 02:05, Boi0 wrote: > I'm working on a text-based RPG, I am on a Windows, and I want the > inventory to open (by pressing i) without pressing enter. OK, Thanks. They simplest way to read keystrokes in Windows is using the msvcrt module which includes the getch() function. But it is quite tricky to use since it literally just reads the keyboard at the point you call it. So you usually have to create a while loop to wait for a keypress. One way to do that is to create a background thread that monitors for keystrokes and then sets a flag somewhere that the main program can check intermittently. (I don't know if you are familiar with threads, they can be quite tricky, but this usage is one of the simplest provided you ensure only the thread ever writes to the flag and only the main program reads it.) Another option which is probably better for your case but will require a major redesign of your code is to use the curses library. Unfortunately curses does not ship with Windows Python so you need to install the windows version from PyPi. https://pypi.org/project/windows-curses/ But curses provides three things you can use - a getch() function which blocks until a key is pressed (and that includes mouse clicks!) and the ability to create small subwindows on your text terminal. Into these you can insert text - like your inventory or a menu, say. Also it lets you control colour and style(bold etc) of text. Again the learning curve is relatively steep and you have to use curses for your whole program you can't mix n match with normal print/input etc. You can see both approaches at work in the event-driven programming topic of my tutorial(see .sig below) Finally there are another couple of modules for terminal keyboard handling in Windows, but they are very similar to the above approaches. Fred Lundh's Console module: http://effbot.org/zone/console-index.htm and the ANSI library for drawing boxes and setting colors: https://pypi.org/project/easy-ansi/ You still need msvcrt for input but its easier than curses for drawing boxes(aka windows) etc. -- 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 May 16 04:47:09 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 16 May 2020 09:47:09 +0100 Subject: [Tutor] Tutor Digest, Vol 195, Issue 23 In-Reply-To: References: Message-ID: On 16/05/2020 02:05, Boi0 wrote: > I'm working on a text-based RPG, I am on a Windows, and I want the > inventory to open (by pressing i) without pressing enter. OK, Thanks. They simplest way to read keystrokes in Windows is using the msvcrt module which includes the getch() function. But it is quite tricky to use since it literally just reads the keyboard at the point you call it. So you usually have to create a while loop to wait for a keypress. One way to do that is to create a background thread that monitors for keystrokes and then sets a flag somewhere that the main program can check intermittently. (I don't know if you are familiar with threads, they can be quite tricky, but this usage is one of the simplest provided you ensure only the thread ever writes to the flag and only the main program reads it.) Another option which is probably better for your case but will require a major redesign of your code is to use the curses library. Unfortunately curses does not ship with Windows Python so you need to install the windows version from PyPi. https://pypi.org/project/windows-curses/ But curses provides three things you can use - a getch() function which blocks until a key is pressed (and that includes mouse clicks!) and the ability to create small subwindows on your text terminal. Into these you can insert text - like your inventory or a menu, say. Also it lets you control colour and style(bold etc) of text. Again the learning curve is relatively steep and you have to use curses for your whole program you can't mix n match with normal print/input etc. You can see both approaches at work in the event-driven programming topic of my tutorial(see .sig below) Finally there are another couple of modules for terminal keyboard handling in Windows, but they are very similar to the above approaches. Fred Lundh's Console module: http://effbot.org/zone/console-index.htm and the ANSI library for drawing boxes and setting colors: https://pypi.org/project/easy-ansi/ You still need msvcrt for input but its easier than curses for drawing boxes(aka windows) etc. -- 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 PyTutor at DancesWithMice.info Sat May 16 22:52:10 2020 From: PyTutor at DancesWithMice.info (DL Neil) Date: Sun, 17 May 2020 14:52:10 +1200 Subject: [Tutor] [nzpug] SuperHELP ready to use (a no-install notebook option available) Message-ID: <015af11d-943c-2129-76a2-645200e2c463@etelligence.info> Greetings! A fellow member of the New Zealand Python User Group has recently released SuperHELP which has many potential uses for both tutors and learners. Herewith his release announcement, FYI:- Regards =dn Hi, The Python SuperHELP project is now ready to use - available from Pypi/pip3. You don't have to install SuperHELP if you just want a quick look - there is a button in the README with a Binder link to a Jupyter notebook. A big thanks to Ben Denham for suggesting this approach and providing an example from his own project :-). From the README: > Superhelp is Help for Humans! The goal is to provide customised help > for simple code snippets. Superhelp is not intended to replace the > built-in Python help but to supplement it for basic Python code > structures. Superhelp will also be opinionated. Help can be provided > in a variety of contexts including the terminal and web browsers > (perhaps as part of on-line tutorials). > > > Example Use Cases > > * > > Charlotte is a Python beginner and wants to get advice on a > five-line function she wrote to display greetings to a list of > people. She learns about Python conventions for variable naming > and better ways of combining strings. > > * > > Avi wants to get advice on a named tuple. He learns how to add doc > strings to individual fields. > > * > > Zach is considering submitting some code to Stack Overflow but > wants to improve it first (or possibly get ideas for a solution > directly). He discovers that a list comprehension might work. He > also becomes aware of dictionary comprehensions for the first time. > > * > > Noor has written a simple Python decorator but is wanting to see > if there is anything which can be improved. She learns how to use > functool.wrap from an example provided. > > * > > Al is an experienced Python developer but tends to forget things > like doc strings in his functions. He learns a standard approach > and starts using it more often. > This is an early version of SuperHELP but it should be useful enough already (fingers crossed) to start getting real-world user feedback. All the best, Grant From grant at p-s.co.nz Sun May 17 00:22:27 2020 From: grant at p-s.co.nz (Grant Paton-Simpson) Date: Sun, 17 May 2020 16:22:27 +1200 Subject: [Tutor] [nzpug] SuperHELP ready to use (a no-install notebook option available) In-Reply-To: <015af11d-943c-2129-76a2-645200e2c463@etelligence.info> References: <015af11d-943c-2129-76a2-645200e2c463@etelligence.info> Message-ID: <322bf93d-b435-9530-a63b-9b469a0147c8@p-s.co.nz> The latest version makes it even easier to get help. Assuming you already have superhelp pip installed just add the following two lines to the top of a Python 3.6+ script and run the script: import superhelp superhelp.this() Feedback welcome at superhelp at p-s.co.nz On 17/05/20 2:52 pm, DL Neil wrote: > Greetings! > > A fellow member of the New Zealand Python User Group has recently > released SuperHELP which has many potential uses for both tutors and > learners. Herewith his release announcement, FYI:- > > Regards =dn > > > > > Hi, > > The Python SuperHELP project is now ready to use - available from > Pypi/pip3. > > You don't have to install SuperHELP if you just want a quick look - > there is a button in the README with a Binder link to a Jupyter > notebook. A big thanks to Ben Denham for suggesting this approach and > providing an example from his own project :-). > > ?From the README: > >> Superhelp is Help for Humans! The goal is to provide customised help >> for simple code snippets. Superhelp is not intended to replace the >> built-in Python help but to supplement it for basic Python code >> structures. Superhelp will also be opinionated. Help can be provided >> in a variety of contexts including the terminal and web browsers >> (perhaps as part of on-line tutorials). >> >> >> ??? Example Use Cases >> >> ?* >> >> ??? Charlotte is a Python beginner and wants to get advice on a >> ??? five-line function she wrote to display greetings to a list of >> ??? people. She learns about Python conventions for variable naming >> ??? and better ways of combining strings. >> >> ?* >> >> ??? Avi wants to get advice on a named tuple. He learns how to add doc >> ??? strings to individual fields. >> >> ?* >> >> ??? Zach is considering submitting some code to Stack Overflow but >> ??? wants to improve it first (or possibly get ideas for a solution >> ??? directly). He discovers that a list comprehension might work. He >> ??? also becomes aware of dictionary comprehensions for the first time. >> >> ?* >> >> ??? Noor has written a simple Python decorator but is wanting to see >> ??? if there is anything which can be improved. She learns how to use >> ??? functool.wrap from an example provided. >> >> ?* >> >> ??? Al is an experienced Python developer but tends to forget things >> ??? like doc strings in his functions. He learns a standard approach >> ??? and starts using it more often. >> > This is an early version of SuperHELP but it should be useful enough > already (fingers crossed) to start getting real-world user feedback. > > All the best, > Grant From upwkwd at gmail.com Mon May 18 10:34:18 2020 From: upwkwd at gmail.com (shubham sinha) Date: Mon, 18 May 2020 20:04:18 +0530 Subject: [Tutor] class-inheritence Message-ID: Hi, we have" package" class that represents a software package which could be installed on machine on our network. "Repository" class that represent all the packages we have available for installation internally. In this case "Repository" is not a "package" and vice-versa. Instead of this 'Repository' contains "Packages" Below given is the repository class -> class Repository: def __init__(self): self.packages = {} def add_packages(self, package): self.packages[package.name] = package def rem_packages(self, package): del self.packages[package.name] def total_size(self): result = 0 for package in self.packages.values(): result += package.size return result My problem: I am unable to define or call package class by which repository class will contain package class. Please help me through this as this is the example given to me by those who taught me class inheritance in which one class have relation with other but one class is not child/inherit to other. Guide me through this so that i can think clearly regarding to object oriented programming problems. ---------------------------------------- Thanks in advance! ---------------------------------------- Regards, Shubham Kumar sinha From akleider at sonic.net Mon May 18 15:38:09 2020 From: akleider at sonic.net (Alex Kleider) Date: Mon, 18 May 2020 12:38:09 -0700 Subject: [Tutor] class-inheritence In-Reply-To: References: Message-ID: <987996b9fc6a45e4e9c869116049357a@sonic.net> On 2020-05-18 07:34, shubham sinha wrote: > Hi, > we have" package" class that represents a software package which could > be > installed on machine on our network. > "Repository" class that represent all the packages we have available > for > installation internally. > In this case "Repository" is not a "package" and vice-versa. Instead of > this 'Repository' contains "Packages" > > Below given is the repository class -> > > class Repository: > def __init__(self): > self.packages = {} > def add_packages(self, package): > self.packages[package.name] = package > def rem_packages(self, package): > del self.packages[package.name] > def total_size(self): > result = 0 > for package in self.packages.values(): > result += package.size > return result > > My problem: > I am unable to define or call package class by which repository class > will > contain package class. > Please help me through this as this is the example given to me by those > who > taught me class inheritance in which one class have relation with other > but > one class is not child/inherit to other. > Guide me through this so that i can think clearly regarding to object > oriented programming problems. > ---------------------------------------- The following might help get you going until the more expert tutors chime in. (I offer this since they generally are pretty quiet week ends.) """ You must indent all that defines your classes. I suggest you delete the ending 's' in the names of your add and remove methods since you are removing single packages not groups there of. The 'for' loop in total_size needed a bit of a rewrite. What follows works. rem_package not tested. """ class Package(object): def __init__(self, size, name): self.size = size self.name = name def __repr__(self): # I added this to help with debugging. return("package.size: {}, package.name: {}" .format(self.size, self.name)) class Repository(object): def __init__(self): self.packages = {} def add_package(self, package): self.packages[package.name] = package def rem_package(self, package): del self.packages[package.name] def total_size(self): result = 0 for key in self.packages: result += self.packages[key].size return result p1 = Package(3, 'p1') p2 = Package(5, 'p2') r = Repository() r.add_package(p1) r.add_package(p2) print("total size of repository is {}." From alan.gauld at yahoo.co.uk Mon May 18 16:24:00 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 18 May 2020 21:24:00 +0100 Subject: [Tutor] class-inheritence In-Reply-To: References: Message-ID: On 18/05/2020 15:34, shubham sinha wrote: > I am unable to define or call package class by which repository class will > contain package class. Since you haven't shown us your package class or how you are trying to use it, its hard for us to know what might be wrong. Alex has shown what we'd normally expect. If you are doing something different you will need to let us see some code plus any error messages. > Please help me through this as this is the example given to me by those who > taught me class inheritance in which one class have relation with other but > one class is not child/inherit to other. I'm not sure where you think inheritance fits in here? Inheritance is a mechanism to reduce code duplication. (and in some languages, although not in Python, it is also the mechanism that enables polymorphism) The relationship is defined as an "is-a" relationship. The relationship in your example is a "has-a" relationship, also known as aggregation or containment. No inheritance needed. -- 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 mats at wichmann.us Mon May 18 16:24:38 2020 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 18 May 2020 14:24:38 -0600 Subject: [Tutor] class-inheritence In-Reply-To: References: Message-ID: <9a795507-88cc-436a-06c0-412676d8a9e3@wichmann.us> On 5/18/20 8:34 AM, shubham sinha wrote: > Hi, > we have" package" class that represents a software package which could be > installed on machine on our network. > "Repository" class that represent all the packages we have available for > installation internally. > In this case "Repository" is not a "package" and vice-versa. Instead of > this 'Repository' contains "Packages" > > Below given is the repository class -> > > class Repository: > def __init__(self): > self.packages = {} > def add_packages(self, package): > self.packages[package.name] = package > def rem_packages(self, package): > del self.packages[package.name] > def total_size(self): > result = 0 > for package in self.packages.values(): > result += package.size > return result > > My problem: > I am unable to define or call package class by which repository class will > contain package class. > Please help me through this as this is the example given to me by those who > taught me class inheritance in which one class have relation with other but > one class is not child/inherit to other. > Guide me through this so that i can think clearly regarding to object > oriented programming problems. This looks okay conceptually. You're implementing "composition" by letting Repository "have a" Package - you're storing those in a dictionary "packages" where the key is the package name and the value is the Package instance. Can you say more about what isn't working out for you? Your Package class should have attributes describing details of a package - name, version, architecture (ia32 vs x64 vs arm), description, etc. You might need more or less of those. === Going a bit beyond your question: Might observe that as written, you have a "last name wins" policy, whereas you might want to do some validation - like perhaps complaining if a pkg name is seen a second time, since names have to be unique as they're used as the key. That is, for a trivial case: class Package: def __init__(self, name, arch='noarch'): self.name = name self.arch = arch repo = Repository() repo.add_package(Package("qemu-system", "686")) repo.add_package(Package("qemu-system", "x86_64")) the second overwrites the first, because this method doesn't care if it's already in self.packages: def add_packages(self, package): self.packages[package.name] = package From nathanprince121 at gmail.com Mon May 18 16:36:23 2020 From: nathanprince121 at gmail.com (Nathan Prince) Date: Mon, 18 May 2020 15:36:23 -0500 Subject: [Tutor] Request Module Corrupts Zip File Message-ID: Why does a downloaded zip file using requests end up corrupted? Trying to make a program that starts a download a specified time. Code: import requests import time import datetime tim = datetime.datetime.now() print("########So Far Only Works With mp4, png, jpg, pkg and exe files########") time.sleep(1) DLTime = input("Time\nHH:MM\n") url = input("URL:\n") Location = ("/Users/jenniferprince/Downloads/" + input("File Name\n")) print("Waiting...") while(True): tim = datetime.datetime.now() if tim.strftime("%H:%M") == DLTime: print("Download Started") myfile = requests.get(url) open(Location, 'wb').write(myfile.content) print("\nDownload Finished") input("Press Enter To Finish") exit() time.sleep(1) Note: Had to use tim not time due to interference with other parts of code. From alan.gauld at yahoo.co.uk Mon May 18 19:14:29 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 19 May 2020 00:14:29 +0100 Subject: [Tutor] Request Module Corrupts Zip File In-Reply-To: References: Message-ID: On 18/05/2020 21:36, Nathan Prince wrote: > Why does a downloaded zip file using requests end up corrupted? > while(True): > tim = datetime.datetime.now() > if tim.strftime("%H:%M") == DLTime: > print("Download Started") > myfile = requests.get(url) > open(Location, 'wb').write(myfile.content) You should never do this. Although you say it only fails with zip files it is just a matter of time before it fails with others. When writing to a file always close the file to force the buffers to be flushed from memory to the file. (Or call flush() explicitly) The Pythonic way to do this is to use with: with open(Location, 'wb') as outfile: outfile.write(myfile.content) And 'with' will guarantee to close the file for you. -- 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 chris_roysmith at internode.on.net Tue May 19 01:20:34 2020 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Tue, 19 May 2020 15:20:34 +1000 Subject: [Tutor] how to "forget" some checkbuttons on a window Message-ID: <603bce7d-389d-f577-70ae-6515d1e0dc2d@internode.on.net> Hi Python 3.6 Ubuntu 18.04 I am trying to hide some Checkbuttons. here is my code: ===================================== #! /usr/bin/python3 from tkinter import * testDat=[0,1,2,3,4,5,6,7,8,9] def remove(e): for i in range(9): r=var[i].get() if r==True: e[i].forget() master=Tk() master.title('experiment') e=[" " for i in range(len(testDat))] var=[IntVar() for i in range(len(testDat))] for i in range(len(testDat)): e[i]=Checkbutton(master, text=str(i), variable=var[i], onvalue=True, offvalue=False).grid(row=i, column=0) Button(master, text='remove checked', command=lambda i=e: remove(i)).grid(row=11, column=0) master.mainloop() =================================== I get the following error =================================== Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__ return self.func(*args) File "./frames.py", line 17, in Button(master, text='remove checked', command=lambda i=e: remove(i)).grid(row=11, column=0) File "./frames.py", line 8, in remove e[i].forget() AttributeError: 'NoneType' object has no attribute 'forget' ================================= I was expecting that any checked Checkbuttons to disappear, Obviously this doesn't happen, as I get the error on that line. How do I go about correcting my code? Regards, Chris Roy-Smith From __peter__ at web.de Tue May 19 03:44:08 2020 From: __peter__ at web.de (Peter Otten) Date: Tue, 19 May 2020 09:44:08 +0200 Subject: [Tutor] how to "forget" some checkbuttons on a window References: <603bce7d-389d-f577-70ae-6515d1e0dc2d@internode.on.net> Message-ID: Chris Roy-Smith wrote: > Hi > Python 3.6 > Ubuntu 18.04 > > I am trying to hide some Checkbuttons. > > here is my code: > ===================================== > #! /usr/bin/python3 > from tkinter import * > testDat=[0,1,2,3,4,5,6,7,8,9] > def remove(e): > for i in range(9): > r=var[i].get() > if r==True: Everytime you do this a kitten dies ;) Don't compare to True or False, write if r: instead. You are around long enough to know. > e[i].forget() > > master=Tk() > master.title('experiment') > > e=[" " for i in range(len(testDat))] > var=[IntVar() for i in range(len(testDat))] > for i in range(len(testDat)): > e[i]=Checkbutton(master, text=str(i), variable=var[i], > onvalue=True, offvalue=False).grid(row=i, column=0) > Button(master, text='remove checked', command=lambda i=e: > remove(i)).grid(row=11, column=0) > > master.mainloop() > > =================================== > I get the following error > =================================== > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__ > return self.func(*args) > File "./frames.py", line 17, in > Button(master, text='remove checked', command=lambda i=e: > remove(i)).grid(row=11, column=0) > File "./frames.py", line 8, in remove > e[i].forget() > AttributeError: 'NoneType' object has no attribute 'forget' > > ================================= > > I was expecting that any checked Checkbuttons to disappear, Obviously > this doesn't happen, as I get the error on that line. > > How do I go about correcting my code? You cannot chain checkbutton = Checkbutton(...).grid(...) assert checkbutton is None because the grid() returns None. You need to proceed in steps: checkbutton = Checkbutton(...) assert checkbutton is not None checkbutton.grid(...) Also, when I ran your code checkbutton.forget() seemed to have no effect. Instead I had to use checkbutton.grid_forget() > Regards, > Chris Roy-Smith From alan.gauld at yahoo.co.uk Tue May 19 03:52:21 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 19 May 2020 08:52:21 +0100 Subject: [Tutor] how to "forget" some checkbuttons on a window In-Reply-To: <603bce7d-389d-f577-70ae-6515d1e0dc2d@internode.on.net> References: <603bce7d-389d-f577-70ae-6515d1e0dc2d@internode.on.net> Message-ID: On 19/05/2020 06:20, Chris Roy-Smith wrote: > I am trying to hide some Checkbuttons. Do you actually want them to become invisible? Or just to disable them(grey them out?) Most GUIS don;t hide controls they just disable them. A changing interface is confusing to users. > from tkinter import * > testDat=[0,1,2,3,4,5,6,7,8,9] > def remove(e): > for i in range(9): > r=var[i].get() > if r==True: > e[i].forget() Notice no return value here so remove() always returns none. > master=Tk() > master.title('experiment') > > e=[" " for i in range(len(testDat))] You could just do: e = [" "] * 10 But given your code below thre is no point since you just overwrite the values. You might as well use an empty list and append the controls below. > var=[IntVar() for i in range(len(testDat))] > for i in range(len(testDat)): > e[i]=Checkbutton(master, text=str(i), variable=var[i], > onvalue=True, offvalue=False).grid(row=i, column=0) You could have created the IntVar here as well which would save a little bit of time since you'd only have one loop.. But, you've fallen into one of the classic traps of Tkinter programming. You are storing the return value from grid() Which is None. You must create and store the control then grid it. Rewriting your code above: var = [] for i in testDat: # no need for range var.append(IntVar()) e.append(Checkbutton(master, text = str(i),variable = var[-1], onvalue = true, offvalue=False)) e[-1].grid(row=i,column=0) > Button(master, text='remove checked', command=lambda i=e: > remove(i)).grid(row=11, column=0) And here you use grid on the return value of remove, but remove has no return value so again you get a none as default. > File "./frames.py", line 8, in remove > e[i].forget() > AttributeError: 'NoneType' object has no attribute 'forget' NoneType because of the premature grid() call above. -- 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 chris_roysmith at internode.on.net Tue May 19 04:37:25 2020 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Tue, 19 May 2020 18:37:25 +1000 Subject: [Tutor] how to "forget" some checkbuttons on a window In-Reply-To: References: <603bce7d-389d-f577-70ae-6515d1e0dc2d@internode.on.net> Message-ID: On 19/5/20 5:44 pm, Peter Otten wrote: > Chris Roy-Smith wrote: > >> Hi >> Python 3.6 >> Ubuntu 18.04 >> >> I am trying to hide some Checkbuttons. >> >> here is my code: >> ===================================== >> #! /usr/bin/python3 >> from tkinter import * >> testDat=[0,1,2,3,4,5,6,7,8,9] >> def remove(e): >> for i in range(9): >> r=var[i].get() >> if r==True: > > Everytime you do this a kitten dies ;) > Don't compare to True or False, write > > if r: > > instead. You are around long enough to know. Hi Peter, Thank you for pointing this out, never thought of that. > >> e[i].forget() >> >> master=Tk() >> master.title('experiment') >> >> e=[" " for i in range(len(testDat))] >> var=[IntVar() for i in range(len(testDat))] >> for i in range(len(testDat)): >> e[i]=Checkbutton(master, text=str(i), variable=var[i], >> onvalue=True, offvalue=False).grid(row=i, column=0) >> Button(master, text='remove checked', command=lambda i=e: >> remove(i)).grid(row=11, column=0) >> >> master.mainloop() >> >> =================================== >> I get the following error >> =================================== >> >> Exception in Tkinter callback >> Traceback (most recent call last): >> File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__ >> return self.func(*args) >> File "./frames.py", line 17, in >> Button(master, text='remove checked', command=lambda i=e: >> remove(i)).grid(row=11, column=0) >> File "./frames.py", line 8, in remove >> e[i].forget() >> AttributeError: 'NoneType' object has no attribute 'forget' >> >> ================================= >> >> I was expecting that any checked Checkbuttons to disappear, Obviously >> this doesn't happen, as I get the error on that line. >> >> How do I go about correcting my code? > > You cannot chain > > checkbutton = Checkbutton(...).grid(...) > assert checkbutton is None > > because the grid() returns None. You need to proceed in steps: > > checkbutton = Checkbutton(...) > assert checkbutton is not None > checkbutton.grid(...) Perhaps I should use 2 lines for this always, I have been caught with this some time ago, but didn't understand why 2 lines needed here. > > Also, when I ran your code > > checkbutton.forget() > > seemed to have no effect. Instead I had to use > > checkbutton.grid_forget() I got a bit confused here, as I found some people saying .grid_forget, and some saying forget_grid! ...I know, don't believe everything on the internet! > >> Regards, >> Chris Roy-Smith > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From chris_roysmith at internode.on.net Tue May 19 04:53:33 2020 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Tue, 19 May 2020 18:53:33 +1000 Subject: [Tutor] how to "forget" some checkbuttons on a window In-Reply-To: References: <603bce7d-389d-f577-70ae-6515d1e0dc2d@internode.on.net> Message-ID: <99120cda-593f-588d-1a47-23a06b7753f6@internode.on.net> On 19/5/20 5:52 pm, Alan Gauld via Tutor wrote: > On 19/05/2020 06:20, Chris Roy-Smith wrote: >> I am trying to hide some Checkbuttons. > > Do you actually want them to become invisible? > Or just to disable them(grey them out?) > Most GUIS don;t hide controls they just disable them. > A changing interface is confusing to users. Hi Alan, Thank you for your assistance, I was thinking that as these items would not be of any interest to whoever uses this code once it's been checked off. Therefore I didn't consider just greying out. The data in the query behind this routine will not be available once the item is checked off anyway. > >> from tkinter import * >> testDat=[0,1,2,3,4,5,6,7,8,9] >> def remove(e): >> for i in range(9): >> r=var[i].get() >> if r==True: >> e[i].forget() > > Notice no return value here so remove() always returns none. > >> master=Tk() >> master.title('experiment') >> >> e=[" " for i in range(len(testDat))] > > You could just do: > > e = [" "] * 10 > > But given your code below thre is no point since > you just overwrite the values. You might as well > use an empty list and append the controls below. > >> var=[IntVar() for i in range(len(testDat))] >> for i in range(len(testDat)): >> e[i]=Checkbutton(master, text=str(i), variable=var[i], >> onvalue=True, offvalue=False).grid(row=i, column=0) > > You could have created the IntVar here as well > which would save a little bit of time since > you'd only have one loop.. > > > But, you've fallen into one of the classic traps of Tkinter > programming. > You are storing the return value from grid() Which is None. > You must create and store the control then grid it. As I said to Peter Otten, I have been caught by this before, but the person who showed me the flaw in my code didn't explain why there was a need to separate the grid method from the widget creation. Am I better off always keeping the two separate? The OLD python (python 2.6!) text I have been using didn't discuss this at all. > Rewriting your code above: > > var = [] > for i in testDat: # no need for range > var.append(IntVar()) > e.append(Checkbutton(master, text = str(i),variable = var[-1], > onvalue = true, offvalue=False)) > e[-1].grid(row=i,column=0) Is appending preferred to creating lists and lists of lists, if so I'll try that out in what I have previously done in other projects. > >> Button(master, text='remove checked', command=lambda i=e: >> remove(i)).grid(row=11, column=0) > > And here you use grid on the return value of remove, but remove has no > return value so again you get a none as default. Knowing why makes things much clearer to me. > >> File "./frames.py", line 8, in remove >> e[i].forget() >> AttributeError: 'NoneType' object has no attribute 'forget' > > NoneType because of the premature grid() call above. > > From alan.gauld at yahoo.co.uk Tue May 19 06:48:59 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 19 May 2020 11:48:59 +0100 Subject: [Tutor] how to "forget" some checkbuttons on a window In-Reply-To: <99120cda-593f-588d-1a47-23a06b7753f6@internode.on.net> References: <603bce7d-389d-f577-70ae-6515d1e0dc2d@internode.on.net> <99120cda-593f-588d-1a47-23a06b7753f6@internode.on.net> Message-ID: On 19/05/2020 09:53, Chris Roy-Smith wrote: > As I said to Peter Otten, I have been caught by this before, but the > person who showed me the flaw in my code didn't explain why there was a > need to separate the grid method from the widget creation. Am I better > off always keeping the two separate? The only time you can combine them is for widgets that you will NEVER need to work with again. An example might be a static label object, once created you never change it. But if its a label that you will update then you need to separate them. For anything that will be modified in any way you must store the widget then apply grid(), pack(), place(), form() or whatever. All the layout manager methods return None. >> Rewriting your code above: >> >> var = [] >> for i in testDat: # no need for range >> var.append(IntVar()) >> e.append(Checkbutton(master, text = str(i),variable = var[-1], >> onvalue = true, offvalue=False)) >> e[-1].grid(row=i,column=0) > > Is appending preferred to creating lists and lists of lists, if so I'll > try that out in what I have previously done in other projects. It's not necessarily better all the time but it is better than creating a list of dummy values and then overwriting them with real ones. Where you could use insertion is if you had a list of objects keyed by some calculated index. Then you would need to create the list and later insert the objects at the correct position. But if you are just building a list item by item then append is usually the best option. (Or a list comprehension which does the same thing just a bit faster) -- 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 PyTutor at danceswithmice.info Tue May 19 14:59:04 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Wed, 20 May 2020 06:59:04 +1200 Subject: [Tutor] class-inheritence In-Reply-To: References: Message-ID: <11ac2be9-8bb2-f643-8f0d-8f3bae39cf6f@DancesWithMice.info> On 19/05/20 2:34 AM, shubham sinha wrote: > Hi, > we have" package" class that represents a software package which could be > installed on machine on our network. > "Repository" class that represent all the packages we have available for > installation internally. > In this case "Repository" is not a "package" and vice-versa. Instead of > this 'Repository' contains "Packages" > > Below given is the repository class -> > > class Repository: > def __init__(self): > self.packages = {} > def add_packages(self, package): > self.packages[package.name] = package > def rem_packages(self, package): > del self.packages[package.name] > def total_size(self): > result = 0 > for package in self.packages.values(): > result += package.size > return result Others have covered the ground. Herewith further critique: - always copy-paste code from your editor/command-line [the above is missing tabs and thus immediately appears in-error] - it would be polite to mention if this is a 'homework' assignment, and/or if you are working from a particular text-book or on-line course [to which we might refer for context/clarification] - "rem_packages" is not a good name: just because "add" is a three letter word there is no reason why "remove" should not be spelled-out in-full [easing readability] - Repository is essentially a list (or, you may later prefer, a dict[ionary]) in which case it could be coded as a sub-class list or UserList [and receive a bunch of pre-coded, powerful-stuff, 'for free'] - Python lists come with a built-in len method, but if you wish to maintain a different approach, might others be expecting/more used to seeing, len()? cf total_size() [not that there is anything wrong with having a method with a better/self-documenting name to fit the context - indeed one could be made a synonym for the other and you'd 'inherit' (hah!) the best of both worlds!] Web.Ref: https://treyhunner.com/2019/04/why-you-shouldnt-inherit-from-list-and-dict-in-python/ -- Regards =dn From wescpy at gmail.com Thu May 21 03:36:13 2020 From: wescpy at gmail.com (wesley chun) Date: Thu, 21 May 2020 00:36:13 -0700 Subject: [Tutor] When to use __new__ vs. __init__ ? In-Reply-To: <53e2e0e8-68cd-f4aa-efc2-0dd340bd2088@DancesWithMice.info> References: <53e2e0e8-68cd-f4aa-efc2-0dd340bd2088@DancesWithMice.info> Message-ID: On Fri, May 1, 2020 at 2:09 PM tutor wrote: > On 30/04/20 11:52 AM, wesley chun wrote: > > I concur with both Mats' and Alan's responses, and add that more > > explicitly, __new__() is really only used for subclassing existing (user > or > > built-in) *immutable* types, not all Python built-in types. (If you > > subclass dict or list, you don't need __new__() ). (Although, subclassing > > mutable types have their own issues > > < > https://treyhunner.com/2019/04/why-you-shouldnt-inherit-from-list-and-dict-in-python/ > > > > .) > > > > With traditional object-oriented languages, you have constructors (and > > destructors) whose job it is to allocate/create (and deallocate/destroy) > > objects. Python works differently in that the *Python interpreter* > manages > > your memory, i.e., it does the creation (and destruction) of regular > > objects. That's why __init__() is named as an "initializer" more than a > > constructor. > > > > For immutables, it's different because you need to be able to specify > what > > you want in such an object *before* it's created, so __new__() serves > that > > purpose... to specify its setup and then let Python create that object. > For > > normal/mutable objects, Python creates the object first, then lets you > > initialize/customize it with __init__() before it's returned to be used > by > > your application. You'd only pick one (normal/mutable/__init__ or > immutable/ > > __new__) and never both. > > > "Never both"? > > Given that __new__ has a different purpose to __init__ it seems > reasonable that one might use both, on the face of it. > > Is the "never" a Python law, or best-practice/good advice? > (cannot recall ever trying both!) > -- > Regards =dn > I'm only speaking for myself, but I've not seen that pattern after 20 years of Python coding in production. Yes, you can physically do it, such as in this SO Q&A , but in practice, not that I've seen. The thing is why would you *need* both? If you're creating an immutable object, it only makes sense to setup your object in `__new__` because once it's created, you can't do anything about it. OTOH (on the other hand), you'd typically use `__init__` to setup instance attributes, and you'd only do that for mutable objects. Even if you *could* use both (let's assume you can do setup before and after an object is instantiated), you might as well put all of that code in one or the other so as to avoid 2 function calls when creating an object. It just doesn't make sense to me. Now, I haven't written large Python systems in years, so I suppose there may be some use case out there, but it's something I haven't seen before. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." +wesley chun : wescpy at gmail : @wescpy Python training & consulting : http://CyberwebConsulting.com "Core Python" books : http://CorePython.com Python blog: http://wescpy.blogspot.com From jet_pistol at outlook.fr Thu May 21 20:25:11 2020 From: jet_pistol at outlook.fr (jet pistol) Date: Fri, 22 May 2020 00:25:11 +0000 Subject: [Tutor] tflearn Message-ID: Traceback (most recent call last): File "c:/Users/Arno/Desktop/Deeplearning/ia.py", line 50, in import tflearn File "C:\Python38\lib\site-packages\tflearn\__init__.py", line 4, in from . import config File "C:\Python38\lib\site-packages\tflearn\config.py", line 5, in from .variables import variable File "C:\Python38\lib\site-packages\tflearn\variables.py", line 7, in from tensorflow.contrib.framework.python.ops import add_arg_scope as contrib_add_arg_scope ModuleNotFoundError: No module named 'tensorflow.contrib' I?ve got this error when using Tflrarn module http://tflearn.org/ From alan.gauld at yahoo.co.uk Fri May 22 04:17:27 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 22 May 2020 09:17:27 +0100 Subject: [Tutor] tflearn In-Reply-To: References: Message-ID: On 22/05/2020 01:25, jet pistol wrote: > Traceback (most recent call last): > File "c:/Users/Arno/Desktop/Deeplearning/ia.py", line 50, in > import tflearn This list is really for querstions about the Python language and its standard library so you are more likely to get answers about 3rd party packages like tflearn on a dedicated support forum. However... > File "C:\Python38\lib\site-packages\tflearn\__init__.py", line 4, in > from . import config > File "C:\Python38\lib\site-packages\tflearn\config.py", line 5, in > from .variables import variable > File "C:\Python38\lib\site-packages\tflearn\variables.py", line 7, in > from tensorflow.contrib.framework.python.ops import add_arg_scope as contrib_add_arg_scope > ModuleNotFoundError: No module named 'tensorflow.contrib' This looks like an installation/configuration issue with tflearn. you could just uninstall and reinstall - checking you have the correct tflearn version for your Python version etc. Are you sure it is a Python 3.8 compatible package? That might fix it. Failing that you might have to dig deeper - check that the package is indeed installed where it should be. It hasn't gone into another Python install heirarchy or somesuch. Failing that you are back to asking the tflearn community I suspect. -- 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 mats at wichmann.us Fri May 22 11:09:43 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 22 May 2020 09:09:43 -0600 Subject: [Tutor] tflearn In-Reply-To: References: Message-ID: <489cb1d8-aa2f-0691-f687-ec793e0bfd67@wichmann.us> On 5/22/20 2:17 AM, Alan Gauld via Tutor wrote: > On 22/05/2020 01:25, jet pistol wrote: >> Traceback (most recent call last): >> File "c:/Users/Arno/Desktop/Deeplearning/ia.py", line 50, in >> import tflearn > > This list is really for querstions about the Python language and its > standard library so you are more likely to get answers about 3rd party > packages like tflearn on a dedicated support forum. However... > > >> File "C:\Python38\lib\site-packages\tflearn\__init__.py", line 4, in >> from . import config >> File "C:\Python38\lib\site-packages\tflearn\config.py", line 5, in >> from .variables import variable >> File "C:\Python38\lib\site-packages\tflearn\variables.py", line 7, in >> from tensorflow.contrib.framework.python.ops import add_arg_scope as contrib_add_arg_scope >> ModuleNotFoundError: No module named 'tensorflow.contrib' I wanted to add, and this may be good news or bad news, depending on your viewpoint, this error is *always* a search path error. To wit, either (a) there is no instance of tensorflow.contrib on your system at all - i.e. there is no path that would ever work, or (b) tensorflow and its contrib component (in case it's optional - don't know anything about this package) are installed, but the Python you're running doesn't know the path to find it. If the former, install it. If the latter, make sure the Python you intend to run was used to do the install. In either case, if you're running Python directly from a command shell, use it. Let's say, for discussion, that you use the Python Launcher, so that you run Python by typing "py": py -m pip install tensorflow Instructions _probably_ say to do "pip install" which runs the program pip, rather than running it as a module of your current Python, and in modern systems there's quite a good chance you have more than one version of Python and pip will point to the wrong one. If you're using Python through a packaged system - Anaconda, say; or an IDE like PyCharm, then it's usually best to install the wanted package through that system, so that everything stays consistent. Hope this helps at least a bit... From __peter__ at web.de Fri May 22 11:33:28 2020 From: __peter__ at web.de (Peter Otten) Date: Fri, 22 May 2020 17:33:28 +0200 Subject: [Tutor] tflearn References: Message-ID: jet pistol wrote: > Traceback (most recent call last): > File "c:/Users/Arno/Desktop/Deeplearning/ia.py", line 50, in > import tflearn > File "C:\Python38\lib\site-packages\tflearn\__init__.py", line 4, in > > from . import config > File "C:\Python38\lib\site-packages\tflearn\config.py", line 5, in > > from .variables import variable > File "C:\Python38\lib\site-packages\tflearn\variables.py", line 7, in > > from tensorflow.contrib.framework.python.ops import add_arg_scope as > contrib_add_arg_scope > ModuleNotFoundError: No module named 'tensorflow.contrib' > > > I?ve got this error when using Tflrarn module > > http://tflearn.org/ Searching for tensorflow.contrib brings up https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/contrib """ Warning: The tf.contrib module is not included in TensorFlow 2. Many of its submodules have been integrated into TensorFlow core, or spun-off into other projects like tensorflow_io, or tensorflow_addons. For instructions on how to upgrade see the Migration guide. """ You may have incompatible versions of tensorflow and tflearn installed. From michaelkommenda at gmx.de Sat May 23 04:44:00 2020 From: michaelkommenda at gmx.de (Michael Kommenda) Date: Sat, 23 May 2020 10:44:00 +0200 Subject: [Tutor] Partition in Windows or Linux References: Message-ID: Hello, ? Unfortunately, I couldn't find an answer to the FAQ. ? How to define a partition in Windows or Linux in Python 3? So e.g. "F:/" or "sda3"? I know a definition of a file, is there a special term for partitions? ? Thank you for your efforts Michael Kommenda ? From __peter__ at web.de Sat May 23 08:57:20 2020 From: __peter__ at web.de (Peter Otten) Date: Sat, 23 May 2020 14:57:20 +0200 Subject: [Tutor] Partition in Windows or Linux References: Message-ID: Michael Kommenda wrote: > How to define a partition in Windows or Linux in Python 3? So e.g. > "F:/" or "sda3"? I know a definition of a file, is there a special term > for partitions? Your question sounds odd. Can you expand a bit, may telling us what you're up to? From mats at wichmann.us Sat May 23 10:14:40 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sat, 23 May 2020 08:14:40 -0600 Subject: [Tutor] Partition in Windows or Linux In-Reply-To: References: Message-ID: <0fb7eb1a-71fe-6643-468c-f7b9f6ce35b3@wichmann.us> On 5/23/20 2:44 AM, Michael Kommenda wrote: > Hello, > ? > Unfortunately, I couldn't find an answer to the FAQ. > ? > How to define a partition in Windows or Linux in Python 3? So e.g. "F:/" > or "sda3"? I know a definition of a file, is there a special term for > partitions? There are some different concepts in play here. A Python program should not need to worry about what are actually (physical or logical) partitions. They're not visible to running programs unless the system has made them available, and if they're available, they're under a different name than the partition name. Windows partitions, *if* they look like they have valid Windows-readable file systems on them *and* haven't been excluded by volume management settings, are mapped in to the "filesystem" as a drive letter (that even includes local network storage). Drive letter handling in Python is a bit awkward... a drive letter like "F:" is not technically part of a path, it is in addition to the path, but Python needs to treat is as if it is to present some kind of consistent treatment across systems. Unfortunately, Windows shells have a working directory per drive letter and Python doesn't which can lead to some confusion when the paths are relative paths but a drive letter is also specified. Okay - I'll stop now. You can get some idea of the concepts in play if you look at the documentation for the pathlib module, which has a bit more to say than os.path does. Linux partitions are only visible parts of the file system when they are mounted, and if they are, access is through the path to the mount point. Is this even what you were asking? From maryknauth at mac.com Sat May 23 11:08:48 2020 From: maryknauth at mac.com (Mary Knauth) Date: Sat, 23 May 2020 11:08:48 -0400 Subject: [Tutor] for Loops with Squared Message-ID: <14B4AECB-967A-4C45-8323-B440096CA516@mac.com> Hello! I am just diving into Python, and I?m having difficulty with for Loops right now. The exercise I am working on is: We will provide you with a value N. You should calculate the sum of each value of N squared from 0 up to and including N. In mathematical notation, this is written as ?Ni=0i2 ? i = 0 N i 2 So if we passed in 3, you would output 02+12+22+32=14 My script is: # Get N from the command line import sys N= int(sys.argv[1]) square = 0 for i in range(0, N+1): square = (i * i) + square print(square) I?m pretty sure my mistake is in line 10, but I?m missing what I?m doing incorrectly. Thanks! Warm Regards, Mary From Richard at Damon-Family.org Sat May 23 13:50:14 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Sat, 23 May 2020 13:50:14 -0400 Subject: [Tutor] for Loops with Squared In-Reply-To: <14B4AECB-967A-4C45-8323-B440096CA516@mac.com> References: <14B4AECB-967A-4C45-8323-B440096CA516@mac.com> Message-ID: On 5/23/20 11:08 AM, Mary Knauth via Tutor wrote: > Hello! > > I am just diving into Python, and I?m having difficulty with for Loops right now. > > The exercise I am working on is: > We will provide you with a value N. You should calculate the sum of each value of N squared from 0 up to and including N. > > In mathematical notation, this is written as ?Ni=0i2 > ? > i > = > 0 > N > i > 2 > > > So if we passed in 3, you would output 02+12+22+32=14 > > My script is: > # Get N from the command line > import sys > N= int(sys.argv[1]) > > > > square = 0 > > for i in range(0, N+1): > square = (i * i) + square > print(square) > > > I?m pretty sure my mistake is in line 10, but I?m missing what I?m doing incorrectly. > > Thanks! > > Warm Regards, > > Mary > First question, and what is the program doing wrong? I think your intuition seems on, looking at you code, can you see why that is happening? Remember, in Python, code blocks are defined by indentation. -- Richard Damon From alan.gauld at yahoo.co.uk Sat May 23 13:49:57 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 23 May 2020 18:49:57 +0100 Subject: [Tutor] for Loops with Squared In-Reply-To: <14B4AECB-967A-4C45-8323-B440096CA516@mac.com> References: <14B4AECB-967A-4C45-8323-B440096CA516@mac.com> Message-ID: On 23/05/2020 16:08, Mary Knauth via Tutor wrote: > calculate the sum of each value of N squared from 0 up to and including N. > > So if we passed in 3, you would output 02+12+22+32=14 > > My script is: > # Get N from the command line > import sys > N= int(sys.argv[1]) > square = 0 > > for i in range(0, N+1): > square = (i * i) + square > print(square) > I?m pretty sure my mistake is in line 10, but I?m missing what I?m doing incorrectly. Since you don't tell us what is going wrong its hard to know. The code above looks like it should work and print(for 3) 0 1 5 14 If that's not what you get - or not what you expected - then tell us what is happening. If you get an error message send the complete error message. -- 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 alexkleider at protonmail.com Sat May 23 14:45:21 2020 From: alexkleider at protonmail.com (alexkleider) Date: Sat, 23 May 2020 18:45:21 +0000 Subject: [Tutor] for Loops with Squared In-Reply-To: <14B4AECB-967A-4C45-8323-B440096CA516@mac.com> References: <14B4AECB-967A-4C45-8323-B440096CA516@mac.com> Message-ID: ??????? Original Message ??????? On Saturday, May 23, 2020 8:08 AM, Mary Knauth via Tutor wrote: > Hello! > > I am just diving into Python, and I?m having difficulty with for Loops right now. > > The exercise I am working on is: > We will provide you with a value N. You should calculate the sum of each value of N squared from 0 up to and including N. > > 0 > N > i > 2 > > So if we passed in 3, you would output 02+12+22+32=14 > > My script is: > > Get N from the command line > > ============================ > > import sys > N= int(sys.argv[1]) > > square = 0 > > for i in range(0, N+1): > square = (i * i) + square > print(square) > > I?m pretty sure my mistake is in line 10, but I?m missing what I?m doing incorrectly. > Although not tested your code seems correct to me. If you pass in 3, the calculation (it seems to me) should be 1*1+2*2+3*3 => 14 From maryknauth at mac.com Sat May 23 15:20:44 2020 From: maryknauth at mac.com (Mary Knauth) Date: Sat, 23 May 2020 15:20:44 -0400 Subject: [Tutor] for Loops with Squared In-Reply-To: References: <14B4AECB-967A-4C45-8323-B440096CA516@mac.com> Message-ID: Hi All, This is an amazing support community! @Richard - you are correct, indentation IS EVERYTHING The print() function needed to be outside the loop. This is for a scripting class at SNHU... Thanks! Warm Regards, Mary Knauth > On May 23, 2020, at 14:45, alexkleider wrote: > > > ??????? Original Message ??????? > On Saturday, May 23, 2020 8:08 AM, Mary Knauth via Tutor wrote: > >> Hello! >> >> I am just diving into Python, and I?m having difficulty with for Loops right now. >> >> The exercise I am working on is: >> We will provide you with a value N. You should calculate the sum of each value of N squared from 0 up to and including N. >> >> 0 >> N >> i >> 2 >> >> So if we passed in 3, you would output 02+12+22+32=14 >> >> My script is: >> >> Get N from the command line >> >> ============================ >> >> import sys >> N= int(sys.argv[1]) >> >> square = 0 >> >> for i in range(0, N+1): >> square = (i * i) + square >> print(square) >> >> I?m pretty sure my mistake is in line 10, but I?m missing what I?m doing incorrectly. >> > > Although not tested your code seems correct to me. > If you pass in 3, the calculation (it seems to me) should be > 1*1+2*2+3*3 => 14 > From narasimha928 at gmail.com Sat May 23 13:34:39 2020 From: narasimha928 at gmail.com (Narasimharao Nelluri) Date: Sat, 23 May 2020 10:34:39 -0700 Subject: [Tutor] for Loops with Squared In-Reply-To: <14B4AECB-967A-4C45-8323-B440096CA516@mac.com> References: <14B4AECB-967A-4C45-8323-B440096CA516@mac.com> Message-ID: Hi Mary, You can Below snippet to get the Desired Result. In [7]: N= 3 In [8]: sum(num*num for num in range(N+1)) Out[8]: 14 Thanks Narasimha. On Sat, May 23, 2020 at 10:18 AM Mary Knauth via Tutor wrote: > Hello! > > I am just diving into Python, and I?m having difficulty with for Loops > right now. > > The exercise I am working on is: > We will provide you with a value N. You should calculate the sum of each > value of N squared from 0 up to and including N. > > In mathematical notation, this is written as ?Ni=0i2 > ? > i > = > 0 > N > i > 2 > > > So if we passed in 3, you would output 02+12+22+32=14 > > My script is: > # Get N from the command line > import sys > N= int(sys.argv[1]) > > > > square = 0 > > for i in range(0, N+1): > square = (i * i) + square > print(square) > > > I?m pretty sure my mistake is in line 10, but I?m missing what I?m doing > incorrectly. > > Thanks! > > Warm Regards, > > Mary > > > > > > _______________________________________________ > 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 Sun May 24 19:12:33 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 25 May 2020 00:12:33 +0100 Subject: [Tutor] Python curses document review? Message-ID: I've spent the last two weeks of lockdown translating the Linux Documentation Project's "Curses Programming HOWTO" document, by Pradeep Padala, into Python curses. I'm about half way through which means I've covered all of the basic curses module stuff and am just starting on the curses.panel module. Given that relatively few users probably work with panel I thought this might be a good opportunity to see if anyone fancies giving me early feedbak on the curses section? It's a PDF of about 60 pages length - much longer than all the existing python curses documents put together! It is not exhaustive but does cover most of what most users need: input/output/colours/windows/text menus/mouse control etc. I must emphasize that this is very much Pradeep's document with the code translated from C to python, I've only tweaked the text where necessary because of differences between the libraries. Any volunteers? Anyone fancy having a crack at writing an old school console game?! Space invaders maybe? :-) Let me know and I'll email the PDF. -- 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 cs at cskk.id.au Sun May 24 19:31:54 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 25 May 2020 09:31:54 +1000 Subject: [Tutor] Python curses document review? In-Reply-To: References: Message-ID: <20200524233154.GA73051@cskk.homeip.net> On 25May2020 00:12, Alan Gauld wrote: >I've spent the last two weeks of lockdown translating the Linux >Documentation Project's "Curses Programming HOWTO" document, >by Pradeep Padala, into Python curses. > >I'm about half way through which means I've covered all of >the basic curses module stuff and am just starting on the >curses.panel module. Given that relatively few users >probably work with panel I thought this might be a good >opportunity to see if anyone fancies giving me early feedbak >on the curses section? > >It's a PDF of about 60 pages length - much longer than all >the existing python curses documents put together! It is not >exhaustive but does cover most of what most users need: >input/output/colours/windows/text menus/mouse control etc. > >I must emphasize that this is very much Pradeep's document >with the code translated from C to python, I've only tweaked >the text where necessary because of differences between >the libraries. > >Any volunteers? >Anyone fancy having a crack at writing an old school >console game?! Space invaders maybe? :-) > >Let me know and I'll email the PDF. I'd be happy to. Do you have a link to Pradeep Padala's document for comparison? Remembering that I've done little curses, and very little in Python. But I'm familia with it to a degree. Maybe I am a good audience. Cheers, Cameron Simpson From david at graniteweb.com Sun May 24 21:20:18 2020 From: david at graniteweb.com (David Rock) Date: Sun, 24 May 2020 20:20:18 -0500 Subject: [Tutor] Python curses document review? In-Reply-To: References: Message-ID: <20200525012018.GA11984@apple.graniteweb.com> * Alan Gauld via Tutor [2020-05-25 00:12]: > > Any volunteers? > Anyone fancy having a crack at writing an old school > console game?! Space invaders maybe? :-) I don't know how much time I'd have, but playing with curses has always been something I'm interested in. I spend 75% of my day in a terminal and have a soft spot for playing in this area. -- David Rock david at graniteweb.com From robertvstepp at gmail.com Sun May 24 21:35:02 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 24 May 2020 20:35:02 -0500 Subject: [Tutor] Python curses document review? In-Reply-To: <20200525012018.GA11984@apple.graniteweb.com> References: <20200525012018.GA11984@apple.graniteweb.com> Message-ID: <20200525013502.GJ19043@Dream-Machine1> On Sun, May 24, 2020 at 08:20:18PM -0500, David Rock wrote: >* Alan Gauld via Tutor [2020-05-25 00:12]: >> >> Any volunteers? >> Anyone fancy having a crack at writing an old school >> console game?! Space invaders maybe? :-) > >I don't know how much time I'd have, but... Likewise, I don't know how much time I'd be able to devote, but I have a project I started to implement a curses interface for that I would like to resurrect. Your document might very well ease my cursing at curses. ~(:>)) -- Wishing you only the best, boB Stepp From linuxwebdeveloper at gmail.com Sun May 24 20:09:32 2020 From: linuxwebdeveloper at gmail.com (April Morone) Date: Sun, 24 May 2020 20:09:32 -0400 Subject: [Tutor] Trigonometric Functions in Python Message-ID: I signed up for the ITP100 Software Design (Python Programming) class for this Summer. I have been working ahead through the book, but came across an issue with understanding something within Chapter 4 of the book "Python for Everybody: Exploring Data in Python 3" that is by the author Charles Severance on page 45. Please explain for me how the following checks the result of the conversion from degrees to radius to get 0.7071067811865476 to see if the result is correct: math.sqrt(2) / 2. of the following: >>> degrees = 45 >>> radians = degrees / 360.0 * 2 * math.pi >>> math.sin(radians) 0.7071067811865475 I never got to complete PreCalc w/Trig class (had to withdraw from it even though I had a C in it for several reasons, so this doesn't fully make sense to me, even though the formula itself to convert degrees to radians does make sense. The way to check results however, does not make sense to me. How does the following check the result of the above conversion from degrees to radius to see if the result is correct? >>> math.sqrt(2) / 2.0 From alan.gauld at yahoo.co.uk Mon May 25 03:29:16 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 25 May 2020 08:29:16 +0100 Subject: [Tutor] Trigonometric Functions in Python In-Reply-To: References: Message-ID: On 25/05/2020 01:09, April Morone wrote: > Severance on page 45. Please explain for me how the following checks the > result of the conversion from degrees to radius to get 0.7071067811865476 > to see if the result is correct: > > math.sqrt(2) / 2. This is a slightly unusual way of expressing 1/sqrt(2) which is the definititive value for sin(45degrees) (Think of a 45 degree right-angled triangle of short length 1. By pythagorus the hypoteneuse is sqrt(2) so sine is 1/sqrt(2)... >>>> degrees = 45 >>>> radians = degrees / 360.0 * 2 * math.pi >>>> math.sin(radians) > 0.7071067811865475 And this is the sin(45 degrees) using radian conversion. So if both values are the same it demonstrates that the radian conversion must be correct. 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 iamsatyabrata428 at gmail.com Mon May 25 15:49:05 2020 From: iamsatyabrata428 at gmail.com (SATYABRATA DATTA) Date: Tue, 26 May 2020 01:19:05 +0530 Subject: [Tutor] How to plot possible values of a function on specified range Message-ID: Let say I have a function def f:x,y,z return x**2+abs(exp(5*y)-5*z) x=range[0,2.65] y=range[0,3.86] z=range[0,6] Now I have to plot possible values of the function f[x,y,z] against z. It will look like a scattered discrete points in f-z plan( each point will indicate the values of f for randomly varied x,y,z) From PyTutor at danceswithmice.info Mon May 25 21:04:35 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Tue, 26 May 2020 13:04:35 +1200 Subject: [Tutor] How to plot possible values of a function on specified range In-Reply-To: References: Message-ID: <5052177f-5dc5-329f-70bb-c85a4e123196@DancesWithMice.info> On 26/05/20 7:49 AM, SATYABRATA DATTA wrote: > Let say I have a function > > def f:x,y,z return x**2+abs(exp(5*y)-5*z) x=range[0,2.65] y=range[0,3.86] > z=range[0,6] > > Now I have to plot possible values of the function f[x,y,z] against z. It > will look like a scattered discrete points in f-z plan( each point will > indicate the values of f for randomly varied x,y,z) The above is not Python code. Please copy-paste appropriate code from your text-editor/IDE. What is your question? Is this an 'homework' assignment? (if so, which course?) -- Regards =dn From robertvstepp at gmail.com Mon May 25 21:24:59 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 25 May 2020 20:24:59 -0500 Subject: [Tutor] Trigonometric Functions in Python In-Reply-To: References: Message-ID: <20200526012459.GE17105@Dream-Machine1> Greetings April! On Sun, May 24, 2020 at 08:09:32PM -0400, April Morone wrote: >I signed up for the ITP100 Software Design (Python Programming) class for >this Summer. I have been working ahead through the book, but came across an >issue with understanding something within Chapter 4 of the book "Python for >Everybody: Exploring Data in Python 3" that is by the author Charles >Severance on page 45. Please explain for me how the following checks the >result of the conversion from degrees to radius to get 0.7071067811865476 >to see if the result is correct: > >math.sqrt(2) / 2. > >of the following: > >>>> degrees = 45 >>>> radians = degrees / 360.0 * 2 * math.pi >>>> math.sin(radians) >0.7071067811865475 It is not totally clear to me exactly where you are not following things. It appears that it is the math, not the Python, which is unclear. By definition there will be 2 * pi radians in a full 360 degree angle, or pi radians for a half-circle angle. So 2 * pi radians = 360 degrees. So the line above might be rewritten: 2 * pi radians = 360 degrees 1 radian = 360/(2 * pi) degrees, or 1 degree = (2 * pi)/360 radians Does that make sense? So if 1 degree is the above, then 45 degrees would be: 45 * 1 degrees = (45 * 2 * pi)/360 radians, which simplifies to 45 degrees = pi/4 radians For a right triangle (implying a 90 degree angle) if one of the other two angles is 45 degrees then the other one will be, too, as the sum of all angles in a triangle must add up to 180 degrees. And the two 45 degree angles imply that the height of the right triangle will equal the width of the triangle. Using the Pythagorean Theorem which states that the sum of the squares of the sides must equal the square of the hypotenuse, or, if the width of the side is x, the height y and the hypotenuse length r, then x**2 + y**2 = r**2 If we arbitrarily choose x = y = 1 for our 45 degree angle we would have: r**2 = 1**2 + 1**2 r**2 = 2, and taking the square root of both sides: r = sqrt(2) Sine of an angle = height / hypotenuse, so sine(45 degrees) = 1/sqrt(2) If you multiply the top and bottom by sqrt(2) you get sine(45 degrees) = (sqrt(2) * 1) / (sqrt(2) * sqrt(2)) = sqrt(2) / 2 If you divide that out you will get the result you stated. >How does the following check the result of the above conversion from >degrees to radius to see if the result is correct? > >>>> math.sqrt(2) / 2.0 See above. Does any of this help? Note that what I wrote above is not actual Python code statements. I am just trying to help you see the math. -- Wishing you only the best, boB Stepp From PyTutor at danceswithmice.info Mon May 25 22:07:46 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Tue, 26 May 2020 14:07:46 +1200 Subject: [Tutor] Trigonometric Functions in Python In-Reply-To: <20200526012459.GE17105@Dream-Machine1> References: <20200526012459.GE17105@Dream-Machine1> Message-ID: On 26/05/20 1:24 PM, boB Stepp wrote: > Greetings April! > > On Sun, May 24, 2020 at 08:09:32PM -0400, April Morone wrote: >> I signed up for the ITP100 Software Design (Python Programming) class for >> this Summer. I have been working ahead through the book, but came >> across an >> issue with understanding something within Chapter 4 of the book >> "Python for >> Everybody: Exploring Data in Python 3" that is by the author Charles >> Severance on page 45. Please explain for me how the following checks the >> result of the conversion from degrees to radius to get >> 0.7071067811865476 >> to see if the result is correct: >> >> math.sqrt(2) / 2. >> >> of the following: >> >>>>> degrees = 45 >>>>> radians = degrees / 360.0 * 2 * math.pi >>>>> math.sin(radians) >> 0.7071067811865475 > > It is not totally clear to me exactly where you are not following things. > It appears that it is the math, not the Python, which is unclear. > > By definition there will be 2 * pi radians in a full 360 degree angle, or > pi radians for a half-circle angle.? So 2 * pi radians = 360 degrees.? So > the line above might be rewritten: > > 2 * pi radians = 360 degrees > 1 radian = 360/(2 * pi) degrees, or > 1 degree = (2 * pi)/360 radians > > Does that make sense?? So if 1 degree is the above, then 45 degrees would > be: > > 45 * 1 degrees = (45 * 2 * pi)/360 radians, which simplifies to > 45 degrees = pi/4 radians > > For a right triangle (implying a 90 degree angle) if one of the other two > angles is 45 degrees then the other one will be, too, as the sum of all > angles in a triangle must add up to 180 degrees.? And the two 45 degree > angles imply that the height of the right triangle will equal the width of > the triangle. > > Using the Pythagorean Theorem which states that the sum of the squares of > the sides must equal the square of the hypotenuse, or, if the width of the > side is x, the height y and the hypotenuse length r, then > > x**2 + y**2 = r**2 > > If we arbitrarily choose x = y = 1 for our 45 degree angle we would have: > > r**2 = 1**2 + 1**2 > r**2 = 2, and taking the square root of both sides: > r = sqrt(2) > > Sine of an angle = height / hypotenuse, so > > sine(45 degrees) = 1/sqrt(2) > > If you multiply the top and bottom by sqrt(2) you get > > sine(45 degrees) = (sqrt(2) * 1) / (sqrt(2) * sqrt(2)) = sqrt(2) / 2 > > If you divide that out you will get the result you stated. > > >> How does the following check the result of the above conversion from >> degrees to radius to see if the result is correct? >> >>>>> math.sqrt(2) / 2.0 > > See above.? Does any of this help?? Note that what I wrote above is not > actual > Python code statements.? I am just trying to help you see the math. I think boB knows all the angles [joke], but like him, I wasn't sure how best to respond. If 'trig' is the source of your problems (as opposed to Python), then perhaps a little research around the web would be helpful, eg https://www.mathsisfun.com/sine-cosine-tangent.html That page helpfully illustrates the idea of extending your single angle into a right-angled triangle (per @Alan) and thereafter the relationships between sine, cosine, and tangent - which will bring you to the point of being able to take the sine result (above) and checking its relationship with the others, to prove correctness. When my memory is (mathematically) insufficient http://wolframalpha.com/ will frequently perform a rescue. NB I didn't look, but Sal Khan's Academy may offer suitable 'revision' topics... -- Regards =dn From breamoreboy at gmail.com Mon May 25 17:42:26 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Mon, 25 May 2020 22:42:26 +0100 Subject: [Tutor] How to plot possible values of a function on specified range In-Reply-To: References: Message-ID: On 25/05/2020 20:49, SATYABRATA DATTA wrote: > Let say I have a function > > def f:x,y,z return x**2+abs(exp(5*y)-5*z) x=range[0,2.65] y=range[0,3.86] > z=range[0,6] > > Now I have to plot possible values of the function f[x,y,z] against z. It > will look like a scattered discrete points in f-z plan( each point will > indicate the values of f for randomly varied x,y,z) https://matplotlib.org/ -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From __peter__ at web.de Tue May 26 03:43:38 2020 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 May 2020 09:43:38 +0200 Subject: [Tutor] Trigonometric Functions in Python References: <20200526012459.GE17105@Dream-Machine1> Message-ID: boB Stepp wrote: > Greetings April! > > On Sun, May 24, 2020 at 08:09:32PM -0400, April Morone wrote: >>I signed up for the ITP100 Software Design (Python Programming) class for >>this Summer. I have been working ahead through the book, but came across >>an issue with understanding something within Chapter 4 of the book "Python >>for Everybody: Exploring Data in Python 3" that is by the author Charles >>Severance on page 45. Please explain for me how the following checks the >>result of the conversion from degrees to radius to get 0.7071067811865476 >>to see if the result is correct: >> >>math.sqrt(2) / 2. >> >>of the following: >> >>>>> degrees = 45 >>>>> radians = degrees / 360.0 * 2 * math.pi >>>>> math.sin(radians) >>0.7071067811865475 > > It is not totally clear to me exactly where you are not following things. > It appears that it is the math, not the Python, which is unclear. > > By definition there will be 2 * pi radians in a full 360 degree angle, or > pi radians for a half-circle angle. So 2 * pi radians = 360 degrees. So > the line above might be rewritten: > > 2 * pi radians = 360 degrees > 1 radian = 360/(2 * pi) degrees, or > 1 degree = (2 * pi)/360 radians > > Does that make sense? So if 1 degree is the above, then 45 degrees would > be: > > 45 * 1 degrees = (45 * 2 * pi)/360 radians, which simplifies to > 45 degrees = pi/4 radians > > For a right triangle (implying a 90 degree angle) if one of the other two > angles is 45 degrees then the other one will be, too, as the sum of all > angles in a triangle must add up to 180 degrees. And the two 45 degree > angles imply that the height of the right triangle will equal the width of > the triangle. > > Using the Pythagorean Theorem which states that the sum of the squares of > the sides must equal the square of the hypotenuse, or, if the width of the > side is x, the height y and the hypotenuse length r, then > > x**2 + y**2 = r**2 > > If we arbitrarily choose x = y = 1 for our 45 degree angle we would have: I think the usual approach is to choose r = 1. Then for a point on the unit circle the arc starting at three'o'clock (x=1, y=0) is the radians, y the sine, and x the cosine. Pythagoras applies all the same ;) > r**2 = 1**2 + 1**2 > r**2 = 2, and taking the square root of both sides: > r = sqrt(2) > > Sine of an angle = height / hypotenuse, so > > sine(45 degrees) = 1/sqrt(2) > > If you multiply the top and bottom by sqrt(2) you get > > sine(45 degrees) = (sqrt(2) * 1) / (sqrt(2) * sqrt(2)) = sqrt(2) / 2 > > If you divide that out you will get the result you stated. > > >>How does the following check the result of the above conversion from >>degrees to radius to see if the result is correct? >> >>>>> math.sqrt(2) / 2.0 > > See above. Does any of this help? Note that what I wrote above is not > actual > Python code statements. I am just trying to help you see the math. > From robertvstepp at gmail.com Tue May 26 09:03:05 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 26 May 2020 08:03:05 -0500 Subject: [Tutor] Trigonometric Functions in Python In-Reply-To: References: <20200526012459.GE17105@Dream-Machine1> Message-ID: <20200526130305.GF17105@Dream-Machine1> On Tue, May 26, 2020 at 09:43:38AM +0200, Peter Otten wrote: >boB Stepp wrote: >> x**2 + y**2 = r**2 >> >> If we arbitrarily choose x = y = 1 for our 45 degree angle we would have: > >I think the usual approach is to choose r = 1. Then for a point on the unit >circle the arc starting at three'o'clock (x=1, y=0) is the radians, y the >sine, and x the cosine. Pythagoras applies all the same ;) I originally considered to go with the unit circle approach, but thought that what I did choose to do would be clearer to someone new to trigonometry. Based on my two kids they initially found the unit circle approach confusing when they first encountered it and responded well to just thinking about about a simple right triangle without explicitly talking about coordinate planes, etc. I did cheat a little and label my triangle sides conventionally for leading into a coordinate plane discussion thought. -- Wishing you only the best, boB Stepp From jet_pistol at outlook.fr Tue May 26 10:38:54 2020 From: jet_pistol at outlook.fr (jet pistol) Date: Tue, 26 May 2020 14:38:54 +0000 Subject: [Tutor] Selenium Message-ID: Hi, I was trying to get a webscrapping script to work on my rapsberry, It worked fine on my Windows 10. I installed all modules, the chromium browser and the chromedriver. But this happens every time i try to launch the script on my rapsberry pi. I have no issues with all the modules import in python 3.8.3 pi at raspberrypi:~/bot $ python3.8 webpronote.py Traceback (most recent call last): File "webpronote.py", line 29, in driver = webdriver.Chrome() File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__ self.service.start() File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/common/service.py", line 72, in start self.process = subprocess.Popen(cmd, env=self.env, File "/usr/local/lib/python3.8/subprocess.py", line 854, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/local/lib/python3.8/subprocess.py", line 1702, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) OSError: [Errno 8] Exec format error: 'chromedriver' Thanks for helping me out with chromedriver From yawantwiadjei at gmail.com Tue May 26 13:41:47 2020 From: yawantwiadjei at gmail.com (YAW ANTWI-ADJEI) Date: Tue, 26 May 2020 17:41:47 +0000 Subject: [Tutor] What is the Copy Parameter in the Pandas Series Method For Message-ID: I would like to know what difference the copy parameter in the Pandas Series() Method makes in the creation of a Series? For example: [image: image.png] I cannot see any difference between TestSeries1 and TestSeries2. In fact, I checked the *id* and they have different *id *as shown below: *>>> id(TestSeries1)* 135039368 >>> *>>> id(TestSeries2)* 63220056 So what actually does the copy argument do? Yaw From jet_pistol at outlook.fr Tue May 26 15:37:26 2020 From: jet_pistol at outlook.fr (jet pistol) Date: Tue, 26 May 2020 19:37:26 +0000 Subject: [Tutor] Chromedriver Message-ID: Hi, I was trying to get a webscrapping script to work on my rapsberry, It worked fine on my Windows 10. I installed all modules, the chromium browser and the chromedriver. But this happens every time i try to launch the script on my rapsberry pi. I have no issues with all the modules import in python 3.8.3. I installed the arm7l version of chromedriver Traceback (most recent call last): File "webpronote.py", line 29, in driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver') File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py", line 76, in __init__ RemoteWebDriver.__init__( File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__ self.start_session(capabilities, browser_profile) File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally. (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) Thanks for helping me out with chromedriver From adameyring at gmail.com Tue May 26 22:36:44 2020 From: adameyring at gmail.com (Adam Eyring) Date: Tue, 26 May 2020 22:36:44 -0400 Subject: [Tutor] Chromedriver In-Reply-To: References: Message-ID: If you haven't seen them, there are forums at raspberrypi.org that may be able to help if not here. https://www.raspberrypi.org/forums/ On Tue, May 26, 2020 at 6:16 PM jet pistol wrote: > Hi, I was trying to get a webscrapping script to work on my rapsberry, It > worked fine on my Windows 10. > I installed all modules, the chromium browser and the chromedriver. But > this happens every time i try to launch the script on my rapsberry pi. I > have no issues with all the modules import in python 3.8.3. I installed the > arm7l version of chromedriver > > > Traceback (most recent call last): > File "webpronote.py", line 29, in > driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver') > File > "/usr/local/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py", > line 76, in __init__ > RemoteWebDriver.__init__( > File > "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", > line 157, in __init__ > self.start_session(capabilities, browser_profile) > File > "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", > line 252, in start_session > response = self.execute(Command.NEW_SESSION, parameters) > File > "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", > line 321, in execute > self.error_handler.check_response(response) > File > "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", > line 242, in check_response > raise exception_class(message, screen, stacktrace) > selenium.common.exceptions.WebDriverException: Message: unknown error: > Chrome failed to start: exited abnormally. > (unknown error: DevToolsActivePort file doesn't exist) > (The process started from chrome location /usr/bin/google-chrome is no > longer running, so ChromeDriver is assuming that Chrome has crashed.) > > > Thanks for helping me out with chromedriver > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From dvsree123 at gmail.com Wed May 27 06:09:32 2020 From: dvsree123 at gmail.com (Divya) Date: Wed, 27 May 2020 15:39:32 +0530 Subject: [Tutor] Installation of pycharm Message-ID: How do I install pycharm in windows 8.1? Can you suggest IDE other than pycharm? From awadgaurav21 at gmail.com Wed May 27 10:41:37 2020 From: awadgaurav21 at gmail.com (c j) Date: Wed, 27 May 2020 20:11:37 +0530 Subject: [Tutor] Installation of pycharm In-Reply-To: References: Message-ID: You can use online interpreter like codeskulptor or replit or download atom On Wed, May 27, 2020, 7:54 PM Divya wrote: > How do I install pycharm in windows 8.1? > Can you suggest IDE other than pycharm? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From breamoreboy at gmail.com Wed May 27 10:39:56 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Wed, 27 May 2020 15:39:56 +0100 Subject: [Tutor] Installation of pycharm In-Reply-To: References: Message-ID: On 27/05/2020 11:09, Divya wrote: > How do I install pycharm in windows 8.1? https://www.jetbrains.com/help/pycharm/installation-guide.html# > Can you suggest IDE other than pycharm? I find Visual Studio Code perfectly adequate for my needs https://code.visualstudio.com/docs/languages/python -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From mats at wichmann.us Wed May 27 13:02:50 2020 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 27 May 2020 11:02:50 -0600 Subject: [Tutor] Installation of pycharm In-Reply-To: References: Message-ID: <82ca8000-f127-e57d-0473-75e0da179637@wichmann.us> On 5/27/20 8:39 AM, Mark Lawrence wrote: > On 27/05/2020 11:09, Divya wrote: >> How do I install pycharm in windows 8.1? > > https://www.jetbrains.com/help/pycharm/installation-guide.html# > >> Can you suggest IDE other than pycharm? > > I find Visual Studio Code perfectly adequate for my needs > https://code.visualstudio.com/docs/languages/python > Without "suggest" - hate to try to pick a winner - here's a big ol' uncurated list: https://wiki.python.org/moin/IntegratedDevelopmentEnvironments From eryksun at gmail.com Thu May 28 13:51:30 2020 From: eryksun at gmail.com (Eryk Sun) Date: Thu, 28 May 2020 12:51:30 -0500 Subject: [Tutor] Partition in Windows or Linux In-Reply-To: <0fb7eb1a-71fe-6643-468c-f7b9f6ce35b3@wichmann.us> References: <0fb7eb1a-71fe-6643-468c-f7b9f6ce35b3@wichmann.us> Message-ID: On 5/23/20, Mats Wichmann wrote: > > Windows partitions, *if* they look like they have valid Windows-readable > file systems on them *and* haven't been excluded by volume management > settings, are mapped in to the "filesystem" as a drive letter (that even > includes local network storage). Device names are created in the object manager namespace, not a filesystem. Most devices are created in the r"\Device" directory. Persistent links to devices, and paths on devices (e.g. mapped and subst drives), are created for a given logon context in r"\Sessions\0\DosDevices\", except the SYSTEM logon uses "\GLOBAL??" instead. For non-SYSTEM logons, the local device-link directory implicitly shadows the global SYSTEM directory, and there's also an explicit "Global" link. For example, if the user has a mapped drive named "Z:" and there's also a global r"\GLOBAL\Z:" defined, the global path "Z:/path/to/file" can be accessed via "//?/Global/Z:/path/to/file". A volume device might not be assigned a drive-letter, but it will always be assigned a persistent "Volume{GUID}" name, where a GUID is a unique 16-byte identifier, which is rendered as a hexadecimal string with 32 digits. For example, the persistent volume name is of the form "Volume{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}". Note that the primary mountpoint is the root path on a device, e.g. "C:/", and not the device name itself. "C:" is a drive-relative path that evaluates to the current directory on the drive and can be used with a remaining path. For example, if the working directory on the drive is "C:/eggs", then "C:spam" resolves to "C:/eggs/spam". Drive-relative paths don't apply to a fully-qualified device path, i.e. a path that's rooted in the local device object directory "//./" or "//?/". For example, "//?/C:" is the volume device itself, which opens as something similar to a Unix block-device file (e.g. you have to read and write in multiples of the sector size), and "//?/C:/" is the root mountpoint if the volume device is mounted. You can use CMD's `mklink /j` command to create a mountpoint (aka a junction), which can target any directory in a filesystem that's mounted on any local device. This is basically equivalent to a Unix "bind" mountpoint, though not as powerful. (A junction is not equivalent to a Unix symlink. The parsing semantics and access rules are different from symlinks. Windows has symlinks if that's what you need.) The Windows API has particular behavior for "volume mountpoints" that target the filesystem root directory using the "Volume{GUID}" volume device name. Such mountpoints are usually set via mountvol.exe or diskmgmt.msc. For example, the GetVolumePathNameW function looks for volume mountpoints. They're more like regular Unix mountpoints, as opposed to bind mountpoints. Though, in some respects, all mountpoints except for the root path on a device are like Unix bind mountpoints. A folder mountpoint is technically a filesystem reparse point with the reparse tag IO_REPARSE_TAG_MOUNT_POINT. The system reparses to the target path. Ultimately, all opens use the primary mountpoint at the root path of a device. For example, if "C:/Mount/BackupDrive" is a junction to "//?/Volume{GUID}/", then opening "C:/Mount/BackupDrive/file" will reparse to opening "//?/Volume{GUID}/file" and ultimately to r"\Device\HarddiskVolume\file", where "" is its current volume device number. The latter is not persistent across boots or for removable drives that get swapped in and out of the system, which is why we use the "Volume{GUID}" device name. Symlinks are also implemented as reparse points, with the tag IO_REPARSE_TAG_SYMBOLIC_LINK, but they have different parsing behavior. Symlinks resolve to the target path while parsing a path, whereas mountpoints are handled more like regular directories while a path is being parsed, which is relevant when parsing traverses relative symlinks. Also, remote symlinks are always evaluated locally using local devices, whereas remote mountpoints are evaluated remotely using the remote system's devices. Symlinks are also subject to the L2L (local to local), L2R (local to remote), R2L, and R2R evaluation policies. R2L should almost always be disallowed. The link target either won't be resolved or it will resolve to a local path that's unrelated to the intended target (e.g. "//server/share/symlink" -> "C:/Users/johnsmith"). L2R and R2R can be enabled to allow symlinks to target remote paths, which mountpoints can never target since they get evaluated remotely. (If mountpoints allowed remote devices, consider the problem of delegating the user's security context across a succession of servers acting on behalf of the user.) Creating symlinks also requires a user to have the symlink privilege, unless the system is in developer mode. > a drive letter like "F:" is not technically part of a path, The primary mountpoint in Windows is the root path of the volume device, so device names are an *integral* component of Windows file paths. (This contrasts with Unix, where filesystems have to be mounted on a directory, i.e. "/dev/sda1/spam" makes no sense in Unix.) Names such as "F:" and "Volume{GUID}" are persistent, registered names for an automatic device name, but ultimately resolve to the base device name. For example, opening "F:/spam" gets translated to the native NT path r"\??\F:\spam" and passed to the kernel, which resolves "F:" to the current path of the volume device, such as r"\Device\HarddiskVolume10". When opening r"\Device\HarddiskVolume10\spam", the object manager in the kernel parses the path up to "HarddiskVolume10" device object. The device-object type has its own parse routine set by the I/O manager. This routine sends an IRP_MJ_CREATE request to the device with the remaining path r"\spam". Since this is a mounted volume device, the request goes to the filesystem device that mounted the volume device instead of directly to the volume device. This is the case even if you open the volume device directly, e.g. "//?/C:" (aka r"\Device\HarddiskVolume2"), with no remaining path. The filesystem device has complete control over access to the volume. > Unfortunately, Windows shells have a working directory per drive letter > and Python doesn't which can lead to some confusion when the paths are > relative paths but a drive letter is also specified. Okay - I'll stop now. For drives A:-Z:, per-drive working directories are set in conventionally hidden environment variables such as "=C:" and "=Z:". The Windows API automatically reads these environment variables, but SetCurrentDirectoryW doesn't set them. It's up to each process to set them. If they're not set, the API defaults to using the root path (e.g. "Z:/"). Python's implementation of os.chdir() sets these per-drive variables, and ntpath.abspath() is based on WinAPI GetFullPathNameW, which uses them. Thus Windows Python participates fully in the per-drive working directory system. By default, child processes inherit the parent's environment block, so by default they inherit the parent's per-drive working directories. From lupchinskileonardo at gmail.com Thu May 28 14:44:23 2020 From: lupchinskileonardo at gmail.com (Markzer) Date: Thu, 28 May 2020 20:44:23 +0200 Subject: [Tutor] some problem, please help me Message-ID: -------------- next part -------------- from pythonclass import Question question_prompts =[ "What is the name of the creator of the program?\n(a) Joaquin\n(b) Gabriel\n(c) Leonardo\n(d) All others are incorrect\n\n", "What is the favorite color of the creator?\n(a) Blue\n(b) Gray\n(c) Yellow\n(d) White\n\n", "How old is the creator?\n(a) 15 (b) 16 (c)13 (d) 14\n\n" ] questions = [ Question(question_prompts[0], "c"), Question(question_prompts[1], "a"), Question(question_prompts[2], "d") ] def run_test(questions): score = 0 for question in questions: answer = input(question.prompt) if answer == question.answer: score += 1 print("You got " + str(score) + "/" + str(len(questions)) + " Correct") run_test(questions) From PyTutor at danceswithmice.info Thu May 28 19:01:45 2020 From: PyTutor at danceswithmice.info (DL Neil) Date: Fri, 29 May 2020 11:01:45 +1200 Subject: [Tutor] some problem, please help me In-Reply-To: References: Message-ID: <0c4edd3b-cfca-e37b-0cd2-f1f8492ad1ab@DancesWithMice.info> On 29/05/20 6:44 AM, Markzer wrote: The message-received features only code in a text-attachment. What is your question? What happens when you run this code? What are the error messages that (might) appear? Are you aware of Python's requirements to consistently indent blocks of code? If this is a 'homework' assignment for some training course, please tell us the name of the course or text-book, for reference. -- Regards =dn From alan.gauld at yahoo.co.uk Thu May 28 19:47:48 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 29 May 2020 00:47:48 +0100 Subject: [Tutor] some problem, please help me In-Reply-To: References: Message-ID: On 28/05/2020 19:44, Markzer wrote: You haven't asked a question? If you expect someone to take the time to respond please take the time to provide information. What do you expect to happen? What does happen? If you get an error message post it - all of it. Which version of python are you using? On which OS? Finally never expect anyone else to run your code. It would be extremely foolish to do so without studying it first, since it could contain any kind of dangerous code. And who has the time to read random bits of code from the internet? Also this is a text based list so attachments usually get stripped off, its better to put your code into the email body. I've done that for you below.... #################################### from pythonclass import Question question_prompts =[ "What is the name of the creator of the program?\n(a) Joaquin\n(b) Gabriel\n(c) Leonardo\n(d) All others are incorrect\n\n", "What is the favorite color of the creator?\n(a) Blue\n(b) Gray\n(c) Yellow\n(d) White\n\n", "How old is the creator?\n(a) 15 (b) 16 (c)13 (d) 14\n\n" ] questions = [ Question(question_prompts[0], "c"), Question(question_prompts[1], "a"), Question(question_prompts[2], "d") ] def run_test(questions): score = 0 for question in questions: answer = input(question.prompt) if answer == question.answer: score += 1 print("You got " + str(score) + "/" + str(len(questions)) + " Correct") run_test(questions) ################################# Bear in mind that we are not on your class. we have no idea what pythonclass is or what Question looks like or does - formats my hard drive in the background perhaps? BTW. You might want to think about the indentation level of your if statement.... -- 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 dfjennings at gmail.com Thu May 28 20:48:35 2020 From: dfjennings at gmail.com (Don Jennings) Date: Thu, 28 May 2020 20:48:35 -0400 Subject: [Tutor] Selenium In-Reply-To: References: Message-ID: <63791631-A677-4B73-8C2C-8777C19AE94A@gmail.com> Hi. I don?t know how you installed chromedriver, but https://stackoverflow.com/questions/38833589/oserror-errno-8-exec-format-error-selenium#38836361 suggests that it?s not the correct version for the platform. Best, Don > On May 26, 2020, at 10:38 AM, jet pistol wrote: > > Hi, I was trying to get a webscrapping script to work on my rapsberry, It worked fine on my Windows 10. > I installed all modules, the chromium browser and the chromedriver. But this happens every time i try to launch the script on my rapsberry pi. I have no issues with all the modules import in python 3.8.3 > > > pi at raspberrypi:~/bot $ python3.8 webpronote.py > Traceback (most recent call last): > File "webpronote.py", line 29, in > driver = webdriver.Chrome() > File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__ > self.service.start() > File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/common/service.py", line 72, in start > self.process = subprocess.Popen(cmd, env=self.env, > File "/usr/local/lib/python3.8/subprocess.py", line 854, in __init__ > self._execute_child(args, executable, preexec_fn, close_fds, > File "/usr/local/lib/python3.8/subprocess.py", line 1702, in _execute_child > raise child_exception_type(errno_num, err_msg, err_filename) > OSError: [Errno 8] Exec format error: 'chromedriver' > > > Thanks for helping me out with chromedriver > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From maryknauth at mac.com Sat May 30 10:06:56 2020 From: maryknauth at mac.com (Mary Knauth) Date: Sat, 30 May 2020 10:06:56 -0400 Subject: [Tutor] Odd & Even lists Message-ID: <3F96E0B1-66EC-4F31-9EC3-6434BCD2285F@mac.com> Hello, I am working through a Python course, and I?m really stuck on working with lists. The script I am working on now is: Task: We are passing in a list of numbers. You need to create 2 new lists in your chart, then put all odd numbers in one list put all even numbers in the other list output the odd list first, the even list second Current code I am running: # Get our input from the command line import sys numbers = sys.argv[1].split(',') for i in range(0,len(numbers)): # 0 to the length of the list numbers[i]= int(numbers[i]) # creates a list of numbers and converts numberes to an integer # Modulo operator to decifer even numbers def isEven(n) : return ((n % 2) == 0) # n % 2 leaves no remainder, therefore even for i in range(numbers) if i == isEven: def listEven = [i] else: def listOdd = [i] print(listOdd) listOdd.append(i) print(listEven) listEven.append(i) Any advice in the right direction is appreciated, thank you! Warm Regards, Mary http://www.zephyrsolutions.us From mats at wichmann.us Sat May 30 12:33:52 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sat, 30 May 2020 10:33:52 -0600 Subject: [Tutor] Odd & Even lists In-Reply-To: <3F96E0B1-66EC-4F31-9EC3-6434BCD2285F@mac.com> References: <3F96E0B1-66EC-4F31-9EC3-6434BCD2285F@mac.com> Message-ID: On 5/30/20 8:06 AM, Mary Knauth via Tutor wrote: > Hello, > > I am working through a Python course, and I?m really stuck on working with lists. The script I am working on now is: > > Task: > > We are passing in a list of numbers. You need to create 2 new lists in your chart, then > > put all odd numbers in one list > put all even numbers in the other list > output the odd list first, the even list second > Current code I am running: > > > # Get our input from the command line > import sys > numbers = sys.argv[1].split(',') > for i in range(0,len(numbers)): # 0 to the length of the list > numbers[i]= int(numbers[i]) # creates a list of numbers and converts numberes to an integer > > # Modulo operator to decifer even numbers > def isEven(n) : > return ((n % 2) == 0) # n % 2 leaves no remainder, therefore even > > for i in range(numbers) > if i == isEven: > def listEven = [i] > else: > def listOdd = [i] > > print(listOdd) > listOdd.append(i) > print(listEven) > listEven.append(i) > > Any advice in the right direction is appreciated, thank you! Write tests for your function. Then develop code so that it passes the tests. Your isEven function is okay. The next bit isn't. A 'def' statement is used to write a function. Only. You appear to be using it for assignment, which is just =. You aren't calling your isEven function, a function call is always designated by (). This may be too much for you at the moment, but functions are "first class" in Python, so you can do things with them that you could do with other objects. The line: if i == isEven: tests if the value referred to by i is equal to the value referred to by isEven, which will never be the case; isEven refers to a function object and i refers to an integer. You want something more like: if isEven(i): then think about what you want to do if that evaluates true.... You can try to talk this out in your head, it often helps. Like: loop through a range of numbers if number is even, add it to the even list if number is odd, add it to the odd list Does that change how you would write the code? From alan.gauld at yahoo.co.uk Sat May 30 12:40:04 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 30 May 2020 17:40:04 +0100 Subject: [Tutor] Odd & Even lists In-Reply-To: <3F96E0B1-66EC-4F31-9EC3-6434BCD2285F@mac.com> References: <3F96E0B1-66EC-4F31-9EC3-6434BCD2285F@mac.com> Message-ID: On 30/05/2020 15:06, Mary Knauth via Tutor wrote: > We are passing in a list of numbers. You need to create 2 new lists in your chart, then > > put all odd numbers in one list > put all even numbers in the other list > output the odd list first, the even list second > Current code I am running: If you search the archives ovver the last two or three months you'll find this exact problem discussed in detail. > import sys > numbers = sys.argv[1].split(',') > for i in range(0,len(numbers)): # 0 to the length of the list > numbers[i]= int(numbers[i]) # creates a list of numbers and converts numberes to an integer > > # Modulo operator to decifer even numbers > def isEven(n) : > return ((n % 2) == 0) # n % 2 leaves no remainder, therefore even > So far so good, you are on the right track, but... > for i in range(numbers) range doesn't take a list of numbers as an argument, it expects a start,stop, step sequence of integers. I suspect what you really want here is the simpler for i in numbers: > if i == isEven: > def listEven = [i] But this makes no sense watsoever. def is for defining functions like isEven above. I think you need to do some revision on how to populate a list. In particular consider the append() method.. > print(listOdd) > listOdd.append(i) This needs to happen in the if construct. You are way too late down here... -- 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 cs at cskk.id.au Sat May 30 19:15:13 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 31 May 2020 09:15:13 +1000 Subject: [Tutor] Odd & Even lists In-Reply-To: References: Message-ID: <20200530231513.GA7406@cskk.homeip.net> On 30May2020 17:40, Alan Gauld wrote: >On 30/05/2020 15:06, Mary Knauth via Tutor wrote: >> We are passing in a list of numbers. You need to create 2 new lists >> in your chart, then >> >> put all odd numbers in one list >> put all even numbers in the other list >> output the odd list first, the even list second >> Current code I am running: [...] >> for i in range(numbers) > >range doesn't take a list of numbers as an argument, it expects a >start,stop, step sequence of integers. I suspect what you really want >here is the simpler > >for i in numbers: I think it is worth mentioning the enmerate() function here, a great way to get a sequence of (index,value) pairs from a list of values. This makes Mary's test easier to do. Cheers, Cameron Simpson From alexkleider at protonmail.com Sat May 30 19:46:23 2020 From: alexkleider at protonmail.com (alexkleider) Date: Sat, 30 May 2020 23:46:23 +0000 Subject: [Tutor] Odd & Even lists In-Reply-To: <20200530231513.GA7406@cskk.homeip.net> References: <20200530231513.GA7406@cskk.homeip.net> Message-ID: ??????? Original Message ??????? On Saturday, May 30, 2020 4:15 PM, Cameron Simpson wrote: > I think it is worth mentioning the enmerate() function here, a great way > to get a sequence of (index,value) pairs from a list of values. This > makes Mary's test easier to do. I agree with the first statement but I don't understand how that helps Mary with her problem. Can you elucidate? Thanks, Alex From robertvstepp at gmail.com Sat May 30 21:42:08 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 30 May 2020 20:42:08 -0500 Subject: [Tutor] Type annotation errors Message-ID: <20200531014208.GA23247@Dream-Machine1> The following function yields type annotation errors and I do not understand why: def evaluate_portfolio( portfolio: List[Dict[str, Union[str, int, float]]], stock_prices: Dict[str, float] ) -> Tuple[float, float]: """Compute the current value and gain/loss of a portfolio.""" portfolio_value = 0.0 gain_loss = 0.0 for stock in portfolio: current_value = stock["shares"] * stock_prices[stock["name"]] current_gain_loss = current_value - (stock["shares"] * stock["price"]) portfolio_value += current_value gain_loss += current_gain_loss return portfolio_value, gain_loss The error messages generated are: report.py|47 col 43 info| Left operand is of type "Union[str, int, float]" report.py|47 col 43 error| Unsupported operand types for * ("str" and "float") report.py|47 col 56 error| Invalid index type "Union[str, int, float]" for "Dict[str, float]"; expected type "str" report.py|48 col 29 info| Both left and right operands are unions report.py|48 col 29 error| Unsupported operand types for - ("float" and "str") report.py|48 col 46 error| Unsupported operand types for * ("str" and "str") report.py|48 col 46 error| Unsupported operand types for * ("str" and "float") report.py|48 col 46 error| Unsupported operand types for * ("float" and "str") For reference line 47 is the line in the for loop beginning "current_value..." portfolio is a list of dictionaries where each dictionary is of the form {"name": "stock name", "shares": number_of_shares_owned, "price": price_per_share} The code runs flawlessly and gives the expected results. Where am I going wrong in my type annotations? -- Wishing you only the best, boB Stepp From cs at cskk.id.au Sat May 30 22:11:07 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 31 May 2020 12:11:07 +1000 Subject: [Tutor] Odd & Even lists In-Reply-To: References: Message-ID: <20200531021107.GA34429@cskk.homeip.net> On 30May2020 23:46, alexkleider wrote: >On Saturday, May 30, 2020 4:15 PM, Cameron Simpson >wrote: >> I think it is worth mentioning the enmerate() function here, a great >> way to get a sequence of (index,value) pairs from a list of values. This >> makes Mary's test easier to do. > >I agree with the first statement but I don't understand how that helps >Mary with her problem. Can you elucidate? Alas, no. I misread her requirements as a sort of unzip: put every other element into alternate lists (which would have cared about the indices), rather than picking the even and odd values. I blame the filter-as-XOR thread elsewhere for my confusion :-) Thanks for the catch, Cameron Simpson