Can someone help please
Hi Can someone help me with this code below please, For some reason it will not send me the first text file in the directory. I made up an empty file a.txt file with nothing on it and it sends the files i need but would like to fix the code. Thanks total = ' ' os.chdir('/home/woodygar/Desktop/Docs') for i in os.listdir('.'): if '.txt' in i: f = open(i, 'r') total += f.read() f.close() message = """\ Subject: %s %s """% (SUBJECT,total) -- http://mail.python.org/mailman/listinfo/python-list
Design advice for unit test asserters
I'm working on a project where I'm doing various file manipulations. I'm not familiar with the idioms are common or good for this situation, so I'd appreciate advice and suggestions. Question 1: A number of checks apply to a set of files. So I'm wondering whether to have something like: def test_SomeTest(...): ... self.AssertAllFilesExist(fileList) or def test_SomeTest(...): ... [ self.AssertFileExists(f) for f in fileList ] In a statically typed, tiny method design approach, the former would be preferred. But in Python the latter seems easy enough and more natural. And I'm wondering if I'm missing some other Python idiom that would be even better. Question 2: A more complicated example: My object defines its own conditions that can be queried, e.g. def test_SomeTest(...): myObject.DoSomething() self._assert(myObject.isFileTypeQ(someFile)) but the parameter someFile is often an expression that should be encapsulated into the assertion. This gives me two possibilities: I can define a stand-alone query that takes myObject as a parameter: def AssertIsTypeQ(theObjectBeingTested, rawFileInfo): someComputedFile = DoStuff(rawFileInfo) return theObjectBeingTested.isFileTypeQ(someComputedFile) and then call it from within various tests as: self._assert(AssertIsFileTypeQ(myObject, someFile) or I can define an intermediate unit test case: class myTester(unittest.TestCase): def AssertIsFileTypeQ(self, rawFileInfo): someComputedFile = DoStuff(rawFileInfo) self.theObject.isFileTypeQ(someComputedFile) and then define my test cases as class test_MyObjectX(myTester): def test_Sometest(): self.theObject = ClassBeingTested() self.theObject.DoSomething() self.AssertIsFileTypeQ(someFile) With these simple cases, this seems like six of one and a half dozen of the other. But the problem grows, in that there are several of these assertions, and they often need to be applied to lists of things. At one point I was getting really complicated by abstracting out both the looping and the computed file names, passing in a functor containing the simple test and the name (for the message). I gave up on this and now I'm leaning towards the first, but again, I wonder if I'm missing a better or more natural way to solve this problem. Thanks, Gary -- http://mail.python.org/mailman/listinfo/python-list
Re: Design advice for unit test asserters
First, thanks to both Kent and Edvard for useful comments. I certainly need to consider whether it make sense to switch to py.test at this time; its simplicity is attractive. In response to Edvards question: Edvard Majakari wrote: > "Gary" <[EMAIL PROTECTED]> writes: ... > > self.AssertAllFilesExist(fileList) ... > > > > def test_SomeTest(...): > > ... > > [ self.AssertFileExists(f) for f in fileList ] > > I prefer the latter, because then you'd get error for the missing file - > otherwise you'd just know a file didn't exist (but not which, unless you > explicitly coded that in, no?) Yes, my intent is that AssertAllFilesExist(fileList) would be something like the following, more or less: def AssertAllFilesExist(fileList): for f in fileList: self.assert_(os.path.isfile(f) and not os.path.islink(f), "File %s is missing" % f) It's the smarts in these that caused me to instantly see applicability of the Template Pattern - which became quite a distraction to me, because after doing it, I think it was obviously unnecessary overkill. Gary -- http://mail.python.org/mailman/listinfo/python-list
hi can someone help please key bind
Hi im trying to use key bind on Tkinter to call this function def Start(): for i in range(60,-1,-1): ent['text'] = i time.sleep(1) root.update() ent['text'] = 'Time Out!' root.update() i know the function is ok as i have assigned a button and i calls the function as i expect but root.bind('',Start) gives the following error Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__ return self.func(*args) TypeError: Start() takes no arguments (1 given) Thanks -- http://mail.python.org/mailman/listinfo/python-list
Business & Spirituality
If you are interested in Business and Spirituality visit us at http://www.executivecoachingservices.ca -- http://mail.python.org/mailman/listinfo/python-list
Empty string namespace on XP in minidom
Howdy I ran into a difference between Python on Windows XP and Linux Fedora 6. Writing a dom to xml with minidom works on Linux. It gives an error on XP if there is an empty namespace. The problem was handled in CVS a while ago. http://mail.python.org/pipermail/xml-sig/2003-October/009904.html Here is an example on XP Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from xml.dom.minidom import parseString >>> doc = parseString('value') >>> doc.toxml() u'value' >>> doc = parseString('value') >>> doc.toxml() Traceback (most recent call last): File "", line 1, in File "C:\tools\Python25\lib\xml\dom\minidom.py", line 45, in toxml return self.toprettyxml("", "", encoding) File "C:\tools\Python25\lib\xml\dom\minidom.py", line 57, in toprettyxml self.writexml(writer, "", indent, newl, encoding) File "C:\tools\Python25\lib\xml\dom\minidom.py", line 1744, in writexml node.writexml(writer, indent, addindent, newl) File "C:\tools\Python25\lib\xml\dom\minidom.py", line 809, in writexml _write_data(writer, attrs[a_name].value) File "C:\tools\Python25\lib\xml\dom\minidom.py", line 299, in _write_data data = data.replace("&", "&").replace("<", "<") AttributeError: 'NoneType' object has no attribute 'replace' and it's working on Linux Python 2.4.4 (#1, Oct 23 2006, 13:58:00) [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from xml.dom.minidom import parseString >>> doc = parseString('value') >>> doc.toxml() u'\nvalue' >>> doc = parseString('value') >>> doc.toxml() u'\nvalue' Should the library on XP be updated? Gary -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing Arbitrary Indentation in Python
Hi! I'd like to join the fray, as the person who posted that original LJ rant. First, some full disclosure, and stampings out of what seem to me to be misconceptions... 1) I am not a CS major. I majored in Computer Animation at an art college. I'm quite well aware that I don't know all there is to know about scripting, let alone programming. I've always been rather technically minded, and many have wondered why I didn't just go the CS route, but I think I'm too much of a hippy artsy type for it. 2) I started in gw basic, and Qbasic, in '92, but have also used a bit of C++, x86 Assembly, PIC Assembly (PIC Microchips), many BASICs for software and hardware (e.g. DarkBASIC, PBasic (Parallax BASIC Stamps), TI BASIC for calculators, etc), lots of Perl for several years, Actionscript/Javascript, a bit of Java, of course many of the web languages, some bash script, pretty much anything that exposes some scripting tools to me, and have even toyed lightly in Lisp, and am curious about Haskell. I'm certainly no expert programmer, but I've been around the block, and at least know a bit of, and about what's out there. 3) I'm not at all married to anything. I've been on 4 different Windows since '92, and used Macs between '95-'99, but switched entirely (at home) to Linux over a year ago. I've since mostly given up on GUI text editors, preferring the sleekness of Vim, and the power of work in the shell. Now that Python is available to me in Maya, I'm VERY interested in leaving MEL behind :) Clearly, I'm capable of change, and even do so rather willingly at times. 4) I know deep down that you may all be right, and that I could even be completely insane, making any of my thoughts the irrational mumblings of a crazed man, but in order to accomplish anything, like getting out of bed in the morning, I must at least believe I am capable of rational thought, learning, and self-improvement. As an example, I believe this point #4 to be at least a somewhat rational set of statements. Grant Edwards said: "Code should work the way it looks and look the way it works." I fully agree. To that end, the MEL UI code I write does look exactly like how it works to me. To me, the layouts are a stack of a containers, which can be thought of in 3D like this (example found online): http://homepages.inf.ed.ac.uk/group/slip0506_a/shen/img/gui_layout.jpg ...which look quite like indented blocks in that view, with siblings indented the same amount beyond their parent. Here's the thing that really gets me, though about everyone's total consternation here: What I'm doing in MEL is not a new concept, or even a strange concept. It's not even what a huge chunk of the populace would call a *bad* concept. It's ostensibly HTML. HTML is a declarative language. The way I'm using the MEL UI code here is very much that - declarative. Perhaps the problem here is that you're all steeped in imperative thoughts, but honestly, I don't see much of a difference here. The examples so far in the group are nests of functions that are honestly, woefully less readable to me than simple indentations to 'declare' (to myself, visually) how things line up in the hierarchy, which when it comes down to it, is all that UIs are - they're hierarchies of containers - but they don't ultimately change what I'm doing, or express anything much differently. You're still creating a nesting, or a hierarchy of controls and layouts. You just seem to want to wrap them all in functions, which then all nest each other to create the layout. I don't get what I win by doing that, but I do see something perhaps minor that I clearly lose by doing that - readability (sorry, but I do). Hierarchies are by-and-large expressed with indentations. Here's a perfect example: http://borumat.de/bilder/dreamweaver/html-quellcode-und-wysiwym-editor.png Knowing only one thing about HTML itself - namely, that tags tend to have a closing version of themselves - anyone can see immediately what's going on. For example, I could tell in 2 seconds that the ul element had 2 li elements, the second of which seems to have a table element, which itself has 2 tr elements. I don't even need to know what those are, but I can see them, and clearly, and immediately. But why stop there? How about XML? Here's another example: http://www.redversconsulting.co.uk/cobol/xml/cobol-xml-sample.gif Right away, I can see that there's a TRAIN that has a LOCOMOTIVE, and 2 CARRIAGES. So can you. So can anyone, which is why they came up with the concept of indenting blocks of siblings under their parents in this fashion. It makes sense. It's natural. Glade - a cross-browser UI building toolset primarily for Linux uses XML now to store the UIs you build. Because of this, it's highly human- readable. You can read the files it saves out just as in my examples above, because of the indents that visually group everything. This also means you can easily tweak things after the fact, say on apps you download - and I have, and it was fun,
Re: Allowing Arbitrary Indentation in Python
Hi! I'd like to join the fray, as the person who posted that original LJ rant. First, some full disclosure, and stampings out of what seem to me to be misconceptions... 1) I am not a CS major. I majored in Computer Animation at an art college. I'm quite well aware that I don't know all there is to know about scripting, let alone programming. I've always been rather technically minded, and many have wondered why I didn't just go the CS route, but I think I'm too much of a hippy artsy type for it. 2) I started in gw basic, and Qbasic, in '92, but have also used a bit of C++, x86 Assembly, PIC Assembly (PIC Microchips), many BASICs for software and hardware (e.g. DarkBASIC, PBasic (Parallax BASIC Stamps), TI BASIC for calculators, etc), lots of Perl for several years, Actionscript/Javascript, a bit of Java, of course many of the web languages, some bash script, pretty much anything that exposes some scripting tools to me, and have even toyed lightly in Lisp, and am curious about Haskell. I'm certainly no expert programmer, but I've been around the block, and at least know a bit of, and about what's out there. 3) I'm not at all married to anything. I've been on 4 different Windows since '92, and used Macs between '95-'99, but switched entirely (at home) to Linux over a year ago. I've since mostly given up on GUI text editors, preferring the sleekness of Vim, and the power of work in the shell. Now that Python is available to me in Maya, I'm VERY interested in leaving MEL behind :) Clearly, I'm capable of change, and even do so rather willingly at times. 4) I know deep down that you may all be right, and that I could even be completely insane, making any of my thoughts the irrational mumblings of a crazed man, but in order to accomplish anything, like getting out of bed in the morning, I must at least believe I am capable of rational thought, learning, and self-improvement. As an example, I believe this point #4 to be at least a somewhat rational set of statements. Grant Edwards said: "Code should work the way it looks and look the way it works." I fully agree. To that end, the MEL UI code I write does look exactly like how it works to me. To me, the layouts are a stack of a containers, which can be thought of in 3D like this (example found online): http://homepages.inf.ed.ac.uk/group/slip0506_a/shen/img/gui_layout.jpg ...which look quite like indented blocks in that view, with siblings indented the same amount beyond their parent. Here's the thing that really gets me, though about everyone's total consternation here: What I'm doing in MEL is not a new concept, or even a strange concept. It's not even what a huge chunk of the populace would call a *bad* concept. It's ostensibly HTML. HTML is a declarative language. The way I'm using the MEL UI code here is very much that - declarative. Perhaps the problem here is that you're all steeped in imperative thoughts, but honestly, I don't see much of a difference here. The examples so far in the group are nests of functions that are honestly, woefully less readable to me than simple indentations to 'declare' (to myself, visually) how things line up in the hierarchy, which when it comes down to it, is all that UIs are - they're hierarchies of containers - but they don't ultimately change what I'm doing, or express anything much differently. You're still creating a nesting, or a hierarchy of controls and layouts. You just seem to want to wrap them all in functions, which then all nest each other to create the layout. I don't get what I win by doing that, but I do see something perhaps minor that I clearly lose by doing that - readability (sorry, but I do). Hierarchies are by-and-large expressed with indentations. Here's a perfect example: http://borumat.de/bilder/dreamweaver/html-quellcode-und-wysiwym-editor.png Knowing only one thing about HTML itself - namely, that tags tend to have a closing version of themselves - anyone can see immediately what's going on. For example, I could tell in 2 seconds that the ul element had 2 li elements, the second of which seems to have a table element, which itself has 2 tr elements. I don't even need to know what those are, but I can see them, and clearly, and immediately. But why stop there? How about XML? Here's another example: http://www.redversconsulting.co.uk/cobol/xml/cobol-xml-sample.gif Right away, I can see that there's a TRAIN that has a LOCOMOTIVE, and 2 CARRIAGES. So can you. So can anyone, which is why they came up with the concept of indenting blocks of siblings under their parents in this fashion. It makes sense. It's natural. Glade - a cross-browser UI building toolset primarily for Linux uses XML now to store the UIs you build. Because of this, it's highly human- readable. You can read the files it saves out just as in my examples above, because of the indents that visually group everything. This also means you can easily tweak things after the fact, say on apps you download - and I have, and it was fun,
Re: Allowing Arbitrary Indentation in Python
On Dec 19, 3:19 pm, Grant Edwards <[EMAIL PROTECTED]> wrote: > The problem is that to everybody else in the world, indentation > in Python represents control flow nesting, not GUI widget > nesting. Thanks, Grant. That's the first solid reasoning I've seen, and it's a very solid argument, as well. To that end, I'm thinking a few things. For one, your argument correctly puts forth that using the code in 2 separate ways is not good. Despite doing just that for 6 years with no problems, I can agree with you on that point. For another, I don't really think the proposals, or hints at how to do it in Python are all that great, either, because they create what I believe to be a bigger mess. I'm kind of leaning toward a Glade approach, wherein I wrap the UI elements up with an XML parser (I'm sure those exist for me already), and have some set of UI building functions build the UI for me with the crappy Maya calls underneath, based on data extracted from the XML. Then the UIs would be built as part of the parsing effort. This sort of hides the ugly stepchild of the Maya method of creating UIs under calls that each only do one thing, which rids the need to nest anything directly in Python, and separates out the UI data into XML - a language specifically made to be indented in a readable fashion, perfect for UI information. The extra benefit is that UI snippets can then be reused in the manner of templates, and even 'widgets,' from which all of my UIs can potentially benefit. I'm sure there's more to think about in regards to all of this, but it's not only the basis for a game plan, but it has precedent in places like Glade, to suggest that it's a viable, and decent option. Again, thanks. -g -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing Arbitrary Indentation in Python
On Dec 19, 3:50 pm, "Chris Mellon" <[EMAIL PROTECTED]> wrote: > You have been done a disservice > by whoever wrote the Maya python bindings, as far as using this tool > to improve your knowledge and understanding of Python goes. No worries there. I'm definitely not using Maya as the way to learn Python. I'm using it as the reason to learn it, with additional supporting reasons being that it aids me in the shell, opens up libraries (and thus abilities) like PyGTK, and can help me create the kinds of tools I create for myself on Linux, but with a lot more power, and expressed more intelligently. > Yes, HTML is a very bad way of doing GUI layout. It's a textual markup > language, not a layout format. HTML per se has almost no layout > capabilities at all, and CSS while much better is still quite limited. Fair enough. I would say in this sense, it feels similar to the concept of duck typing to me. The UI sections of my MEL code looked (to me) like HTML, and were formed in the same way, and the output was essentially a 1:1 mapping of what similar, declarative, HTML-style markup might produce. That it was clearly *not* what it seemed to be was beside the point. It quacked like a duck for me, and always got the job done. But I'm ready for a real duck now. > This is the internet, we don't shy away from scoffing at millions of > misguided souls here ;) I wrote that bit, admittedly, with a dark grin on my face. I often find I disagree with the majority. I suppose I was being a *bit* defensive, though. After all, I was - ostensibly - doing the same thing in my code that one would do in HTML. That I was violating laws of code (codes of law?) was very much an extension of the fact that I really didn't have a choice. After all, I did try unsuccessfully several times (as have others) to create a system whereby I'd design the layouts in an editor, and save them out to some declarative format. However, in that I needed to create a rather intricate UI in MEL that could create UIs in MEL, with the terrible UI abilities in MEL, and using MEL itself, which is vastly underpowered, it was something more fit for an entire ship of fools to create, rather than one lone code warrior. It was just too much work. I think it will be not only possible, but end up rather powerful to create it in Python. > > ...and keeps on rolling with: > > "All those setParent calls! *shiver*." > > > Alright, I'll give you those :) I hated them for the first year. > > Still, they're basically just HTML close tags, with the added power > > that you can replace '..' with a specific layout to jump into that. > > You can also think of them as close braces in your choice of C-like > > languages. Don't be such a scaredy-cat. > > They aren't a close tag, they're state management, and the fact that > you have to litter your code with them is a real flaw in the GUI > toolkit. I agree. I've known that I'm simply manipulating states, but the overarching points here are that it was my only real option, and I managed to dress it up prettily enough that I could fool myself, and not be bothered by it. It helps that I own all my code, and that it's only been used by 2-4 people these past 6 years. Now that the company is growing, and I'm wanting more to share code, and build more powerful things, I'm eager to shed some of my youthful, carefree ways, and code properly, and powerfully. > > Jonathan Gardener promised this: > > "...let me try to explain why you'd never want to indent code that > > way, let alone write code that way." > > > But then never actually explained it. > > > He states: > > "...it's best to create functions and then nest the functions." > > > But never says why it's best - just that it is. None of you so far > > have said why your thoughts have any merit. So far, it's just all been > > declarative statements that your ways are better, that my ways are > > "terrible," and all with not one substantiation of either sentiment. > > Weren't any of you folks in debate club? I wasn't, but I think I'm > > winning :) > > I'm not him, but I'll say why *I* might have said this. What you're > doing with your nesting is creating and managing a stack of states. It > just so happens that you have a very powerful programming language all > ready to do this for you, because that's exactly what it does when you > make nested function calls. So rather than writing imperative code > that tries to look declarative, you can just write imperative code (or > you could use/invent a real declarative language for declaring these > GUIs, and load the UI from that. This is what GUI builders like Glade > do). Remember that you are *not* writing markup. You are writing code > in a real programming language and you have all the power of that > language at your disposal for breaking code down into small, easily > handled pieces. I too have written UIs that scale to hundreds of > individual GUI elements (although not neccesarily controls, because a > UI screen that cluttered i
Re: Allowing Arbitrary Indentation in Python
On Dec 19, 6:44 pm, Ross Ridge <[EMAIL PROTECTED]> wrote: > Sam <[EMAIL PROTECTED]> wrote: > >cmds.window(t='gwfUI Builder') > >cmds.paneLayout(configuration='vertical3', ps=((1, 25, 100), (3, 20, > >100))) > >cmds.paneLayout(configuration='horizontal2') > >cmds.frameLayout(l='Layouts') > >cmds.scrollLayout(cr=True) > >cmds.columnLayout(adj=True, cat=('both', 2)) > >for i in layouts: > >cmds.button(l=i) > >cmds.setParent('..') > >cmds.setParent('..') > >cmds.setParent('..') > >cmds.setParent('..') > >cmds.setParent('..') > >cmds.showWindow() > > An alternative would be to do something like the following: > > cmds.window(t='gwfUI Builder') > cmds.paneLayout(configuration='vertical3', ps=((1, 25, 100), >(3, 20, 100))) > cmds.paneLayout(configuration='horizontal2') > cmds.frameLayout(l='Layouts') > cmds.scrollLayout(cr=True) > cmds.columnLayout(adj=True, cat=('both', 2)) > for i in layouts: > cmds.button(l=i) > cmds.setParent('..') > cmds.setParent('..') > cmds.setParent('..') > cmds. setParent('..') > cmds.setParent('..') > cmds.showWindow() > > Stylistically it's not much better, but you don't need to change Python > interpreter for it work. I'm adding this to my list of crazy things not to do :) I'm also adding it to my list of code snippets I can use to injure Python programmers, if the need arises. Thanks! -g -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing Arbitrary Indentation in Python
On Dec 19, 6:44 pm, Ross Ridge <[EMAIL PROTECTED]> wrote: > Sam <[EMAIL PROTECTED]> wrote: > >cmds.window(t='gwfUI Builder') > >cmds.paneLayout(configuration='vertical3', ps=((1, 25, 100), (3, 20, > >100))) > >cmds.paneLayout(configuration='horizontal2') > >cmds.frameLayout(l='Layouts') > >cmds.scrollLayout(cr=True) > >cmds.columnLayout(adj=True, cat=('both', 2)) > >for i in layouts: > >cmds.button(l=i) > >cmds.setParent('..') > >cmds.setParent('..') > >cmds.setParent('..') > >cmds.setParent('..') > >cmds.setParent('..') > >cmds.showWindow() > > An alternative would be to do something like the following: > > cmds.window(t='gwfUI Builder') > cmds.paneLayout(configuration='vertical3', ps=((1, 25, 100), >(3, 20, 100))) > cmds.paneLayout(configuration='horizontal2') > cmds.frameLayout(l='Layouts') > cmds.scrollLayout(cr=True) > cmds.columnLayout(adj=True, cat=('both', 2)) > for i in layouts: > cmds.button(l=i) > cmds.setParent('..') > cmds.setParent('..') > cmds.setParent('..') > cmds. setParent('..') > cmds.setParent('..') > cmds.showWindow() > > Stylistically it's not much better, but you don't need to change Python > interpreter for it work. I'm adding this to my list of crazy things not to do :) I'm also adding it to my list of code snippets I can use to injure Python programmers, if the need arises. Thanks! -g -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing Arbitrary Indentation in Python
On Dec 19, 7:01 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > Hi, Gary. Welcome to Python. I hope you will take some of the reaction > you got as initiatory ribbing. Thanks, Terry, and absolutely! You guys are quite tame compared to some of the lions whose dens I've stumbled into on usenet. You're also all well-spoken, passionate, and informative. I'm thinking of sticking around in here while the learning's good. > Anyone who loves Python obvious likes the idea of meaningful indentation. > The problem with your suggestion and example is with mixing two meanings in > the same hierarchy. Hence the suggestion that you separate program text > and declarative text. It would seem that's been the biggest stumbling block - my wanton mixing of imperative and declarative styles. I did do my best to separate them geographically in my scripts - with the UI bits always coming at the end :) I've made my justifications above - namely that "Hey, it always worked fine!" and "Sorry, but there wasn't much in the way of options," - but I'm quite ready to do things cleanly, properly, extensibly, and Pythonically. > | I'm not sure exactly what you mean by this, but I'm not really asking > | for the language to be changed. > > You fooled me as well as others. Sorry about that. I most definitely didn't want to have Python fork, or change into some version compatible with my mind. I was mostly stamping my feet, and whining about how all the options for doing what I must do all the time seemed so overly complicated in comparison to what I've already been doing. The full separation of the declarative portion is the right answer to my problem, though, and requires no changes, except to my methodology, and in that, only for the better. > A reasonable question would be something like this. "I currently do gui > layout with MEL [what is that?] and like this but not that. I am looking > at Python because of X. How do people express gui layout within or in > conjuction with Python code?" Fair enough. Of course, if I'd actually posted to this newsgroup in the first place, I probably would have stated it in a very similar way. I'm quite polite, and descriptive in newsgroups, usually. This was cross-posted to here from my LJ by my online friend, Sam, as an unintended surprise gift to me :) Really, he was just curious about what this group would have to say about my problems, and when he told me of his crosspost, I was immediately quite interested as well. It worked out for me, too, because now I have a better sense of the right ways to go about a task I must do too often not to do intelligently. Thanks for your help, Terry. -g -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing Arbitrary Indentation in Python
On Dec 19, 7:01 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > Hi, Gary. Welcome to Python. I hope you will take some of the reaction > you got as initiatory ribbing. Thanks, Terry, and absolutely! You guys are quite tame compared to some of the lions whose dens I've stumbled into on usenet. You're also all well-spoken, passionate, and informative. I'm thinking of sticking around in here while the learning's good. > Anyone who loves Python obvious likes the idea of meaningful indentation. > The problem with your suggestion and example is with mixing two meanings in > the same hierarchy. Hence the suggestion that you separate program text > and declarative text. It would seem that's been the biggest stumbling block - my wanton mixing of imperative and declarative styles. I did do my best to separate them geographically in my scripts - with the UI bits always coming at the end :) I've made my justifications above - namely that "Hey, it always worked fine!" and "Sorry, but there wasn't much in the way of options," - but I'm quite ready to do things cleanly, properly, extensibly, and Pythonically. > | I'm not sure exactly what you mean by this, but I'm not really asking > | for the language to be changed. > > You fooled me as well as others. Sorry about that. I most definitely didn't want to have Python fork, or change into some version compatible with my mind. I was mostly stamping my feet, and whining about how all the options for doing what I must do all the time seemed so overly complicated in comparison to what I've already been doing. The full separation of the declarative portion is the right answer to my problem, though, and requires no changes, except to my methodology, and in that, only for the better. > A reasonable question would be something like this. "I currently do gui > layout with MEL [what is that?] and like this but not that. I am looking > at Python because of X. How do people express gui layout within or in > conjuction with Python code?" Fair enough. Of course, if I'd actually posted to this newsgroup in the first place, I probably would have stated it in a very similar way. I'm quite polite, and descriptive in newsgroups, usually. This was cross-posted to here from my LJ by my online friend, Sam, as an unintended surprise gift to me :) Really, he was just curious about what this group would have to say about my problems, and when he told me of his crosspost, I was immediately quite interested as well. It worked out for me, too, because now I have a better sense of the right ways to go about a task I must do too often not to do intelligently. Thanks for your help, Terry. -g -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing Arbitrary Indentation in Python
On Dec 19, 10:10 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > ElementTree is a good candidate for processing xml: > http://effbot.org/zone/element.htm > It provides a "natural" way to access elements and attributes, instead of > writing the same handler again and again or using slow DOM functions of > gigantic names. That does look pretty easy. I'll look into it after I get back from the holidays. Thanks, Gabriel. -g -- http://mail.python.org/mailman/listinfo/python-list
Re: Allowing Arbitrary Indentation in Python
On Dec 19, 10:10 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > ElementTree is a good candidate for processing xml: > http://effbot.org/zone/element.htm > It provides a "natural" way to access elements and attributes, instead of > writing the same handler again and again or using slow DOM functions of > gigantic names. That does look pretty easy. I'll look into it after I get back from the holidays. Thanks, Gabriel. -g -- http://mail.python.org/mailman/listinfo/python-list
Re: file write collision consideration
It would help to know which version of Python when giving examples... I recollect that so-called mutex operation wasn't actually thread safe when using Python 2.5, but perhaps that was wrong, or subsequent versions have fixed that? -- http://mail.python.org/mailman/listinfo/python-list
Proxy server?
I've seen examples for HTTP and FTP use, but not for simply any TCP data on any port, which is what I require. Can anyone please point me in the right direction? TIA -- http://mail.python.org/mailman/listinfo/python-list
Re: Proxy server?
"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Gary wrote: > For what? A non-transparent proxy, for anonymity purposes only. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proxy server?
"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Gary schrieb: > > "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > You can't make any TCP/IP communication run through a proxy, unless it's > transparent. Thanks for all the info. I'm puzzled though that a such a transaction isn't possible by rewriting the headers. So client X connects to my PS, which passes on the data to the target but with the header changed to indicate the PS as the original source. The intended target responds to the PS, this is then resent to client X with the header modified so that the transaction appears transparent. So it's *effectively* transparent target>client but non-transparent client>target, if you see what I mean. Can you please explain why this wouldn't work? Thanks, Gary -- http://mail.python.org/mailman/listinfo/python-list
Re: problems with looping, i suppose
John -- I looked at your exercise. As it appears in my browser, there appear to be a couple of problems with the bottom "While" block. 0 Alignment problem with the "except" clause. As I'm sure you've already discovered, Python is "whitespace sensitive". If it looks like a block, it is; otherwise it isn't. The "if" .. "elif" statements aren't "inside" ("to the right of") the "try". Python will, I believe, interpret this as "try" with no matching "except" or "finally" and will toss this as a syntax error -- and thus, I suspect, the flashing screen. o logic error. if "guess" == "number", program as written will print "congrats" forever. Assuming my "cut, copy, paste" works ok, try this: (hmm, the print "congrats" line looks like it's broken into two lines when I preview this. Please ignore -- it should all be on one line): import random number = random.choice(range(1, 100)) tries = 0 while True: try: guess = input('Enter a number between 1 and 100: ') break except NameError: print 'Invalid number\n' continue while True: tries += 1 try: if guess < number: guess = input('Too low. Try again: ') elif guess > number: guess = input('Too high. Try again: ') else: print 'Congratulations! You got it in ',tries,'guess(es).' break except NameError: print 'Invalid number\n' continue raw_input() I altered the "if" a bit -- just my own preference that an "if" always have a matching "else". If you're looking for something with an editor and a debugger -- try "IDLE". If your installation is like mine, it's included. Look in your Python directory under Lib/idelib for file "idle.pyw". (NB: At the moment, I'm running a WinXP box and that's where it is here. My poor old mind can't dredge up whether it's in the same relative place in say, a Linux installation.) "IDLE" isn't perfect but it'll get you started. (Also, FWIW, if you run this under "IDLE", you can omit the trailing "raw_input()") hope this helps. gary John Salerno wrote: > John Salerno wrote: > > Here's an exercise I was doing > > This might help: > > import random > > number = random.choice(range(1, 100)) > tries = 0 > > while True: > try: > guess = input('Enter a number between 1 and 100: ') > break > except NameError: > print 'Invalid number\n' > continue > > while True: > tries += 1 > try: > if guess == number: > print 'Congratulations! You got it in', tries, 'guess(es).' > break > elif guess < number: > guess = input('Too low. Try again: ') > elif guess > number: > guess = input('Too high. Try again: ') > except NameError: > print 'Invalid number\n' > continue > > raw_input() -- http://mail.python.org/mailman/listinfo/python-list
Re: Append to python List
On 05/08/2013 11:36 PM, RAHUL RAJ wrote: Checkout the following code: sample2 = [x+y for x in range(1,10) for y in range(1,10) if x!=y] output=[] output=[x for x in sample2 if x not in output] This statement is not doing what you expect. It is not building a list in the variable named output, it is building a list (anonymously) then binding it to the variable output once it's built. Therefore output is [] for the whole list building operation. The later operation works, because your *are* building the list in place as you go. the output I get is 3 4 5 6 7 8 9 10 3 5 6 7 8 9 10 11 4 5 7 8 9 10 11 12 5 6 7 9 10 11 12 13 6 7 8 9 11 12 13 14 7 8 9 10 11 13 14 15 8 9 10 11 12 13 15 16 9 10 11 12 13 14 15 17 10 11 12 13 14 15 16 17 which contains duplicate values. But if I do like this: sample2 = [x+y for x in range(1,10) for y in range(1,10) if x!=y] output=[] for x in sample2: if x not in output: output.append(x) the value of 'output' I get like this: 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 I know that both the programs have the same functionality, but why do I have different outputs? Please help! -- http://mail.python.org/mailman/listinfo/python-list
Re: create new python file
On 06/04/2013 09:07 AM, kakararunachalserv...@gmail.com wrote: Hi, Can anyone please tell me how to dynamically create a new python file within a program??? What do you mean by a "python file"? If you mean a text file containing python code, then create it like any other text file. For instance: with open("Hello.py", "w") as f: print("print('Hello world')\n", file=f) will create a file containing a simple one-line Python program. If you meant something else, then please take the time to provide more detail. Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On 06/19/2013 12:17 PM, Ahmed Abdulshafy wrote: I'm reading the Python.org tutorial right now, and I found this part rather strange and incomprehensible to me> Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes This code: def f(a, L=[]): L.append(a) return L does the same as this code: M=[] def f(a, L=M): L.append(a) return L where it's slightly more obvious that the list is created once, and modified with each call to the function (or rather with each call to the function that does not supply its own value for L). Gary Herron print(f(1)) print(f(2)) print(f(3)) This will print [1] [1, 2] [1, 2, 3] How the list is retained between successive calls? And why? -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
On 06/21/2013 02:17 PM, Yves S. Garret wrote: Hi, I have a question about breaking up really long lines of code in Python. I have the following line of code: log.msg("Item wrote to MongoDB database %s/%s" %(settings['MONGODB_DB'], settings['MONGODB_COLLECTION']), level=log.DEBUG, spider=spider) Given the fact that it goes off very far to the right on my screen is not terribly pleasing to my eyes (and can be rude for other developers). I was thinking of splitting it up like so: log.msg("Item wrote to MongoDB database %s/%s" %(settings['MONGODB_DB'], settings['MONGODB_COLLECTION']), level=log.DEBUG, spider=spider) Is this ok? Are there any rules in Python when it comes to breaking up long lines of code? This is how I'd do it: (And it's *FAR* clearer -- You win no points for clarity by having it all in one statement.) fmt = "Item wrote to MongoDB database %s/%s" msg = fmt % (settings['MONGODB_DB'], settings['MONGODB_COLLECTION']) log.msg(msg, level=log.DEBUG, spider=spider) Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: analyzing time
On 07/05/2013 12:18 PM, noydb wrote: Hello All, I have a table with a column of type date, with dates and time combined (like '1/6/2013 3:52:69PM'), that spans many months. How would I pull out records that are the first and last entries per day? Also, if I wanted to find time clusters per day (or per week) -- like if an entry is made every day around 11am -- is there a way to get at that temporal statistical cluster? Python 2.7, Windows 7. Any guidance would be greatly appreciated! Time seems tricky... Thanks, N Are you asking a Python question, like how to turn a string "1/6/2013 3:52:69PM" into an internal representation of time, or are you asking a data analysis and statistical question? If the former, then look at datetime.strptime from the datetime module. If the later, then you may get an answer here, but I'd suggest trying somewhere that discusses statistics and analysis. Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: RAM slots problem
On 07/08/2013 10:06 PM, saadharana wrote: I've got some annoying problem with RAM. I was depth cleaning my case, everything regular, it wasn't my first time. And when I put it all together and powered it on, it wasn't working, just beeps fast. But how that happend when I put all back in like it was before?? Later I realised that problem was in position of RAM sticks. I still can't understand what happend, but now computer won't work on every RAM position, and especially not like it was before. - used computers in chennai -- View this message in context: http://python.6.x6.nabble.com/RAM-slots-problem-tp5024183.html Sent from the Python - python-list mailing list archive at Nabble.com. This is a PYTHON list -- for discussing issues concerning Python. You'd best ask for HARDWARE help elsewhere. Good luck. -- http://mail.python.org/mailman/listinfo/python-list
Re: Storing a very large number
On 07/17/2013 12:21 PM, Hasit Mistry wrote: I came across a problem that requires me to store a very large number (say >10^100). How do I do it efficiently? And also, how do I select a particular number (say 209th) from that very large number? I am relatively new to Python. Thank you in advance. Python already has long numbers (integers) built in.: >>> 10**100 1L The 'L' on the end notifies you it's a *long* int. I can't speak about its efficiency, but I assume it's OK. By 209th number, do you mean 209th *digit*?I'd say just get a string representation and index the 209th character: >>> str(12**345) '2077446682327378559843444695582704973572786912705232236931705903179519704325276892191015329301807037794598378537132233994613616420526484930777273718077112370160566492728059713895917217042738578562985773221381211423961068296308572143393854703167926779929682604844469621152130457090778409728703018428147734622401526422774317612081074841839507864189781700150115308454681772032' >>> str(12**345)[209] '1' Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a Program to Decompose a Number and Run a Function on that Decomposition
On 07/18/2013 02:57 PM, CTSB01 wrote: On Thursday, July 18, 2013 5:12:08 AM UTC-4, Joshua Landau wrote: On 18 July 2013 00:58, CTSB01 wrote: Please let me know if this is unclear. I will certainly continue revising until it makes sense to those reading. Can you summarize what your question is? Leave aside the details of the function, just explain what thing in particular you aren't able to do. Hi Joshua, I actually managed to find a certain block like this: def phi_m(x, m): ... rtn = [] ... for n2 in range(0, len(x) * m - 2: That 'for' line has miss-matched parentheses. ... n = n2 / m ... r = n2 - n * m ... rtn.append(m * x[n] + r * (x[n + 1] - x[n])) ... print 'n2 =', n2, ': n =', n, ' r =' , r, ' rtn =', rtn ... rtn However, I am getting the error "expected an indented block" on line two. Any idea why? -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: Has anyone gotten Pyglet to work
On 07/29/2013 01:56 PM, Devyn Collier Johnson wrote: I tried Pyglet in a Python3 and a Python2 script, but both fail. The error code is below and the script is attached. The 'boot.ogg' file is Ubuntu's default bootup sound. I got my code from this link (http://guzalexander.com/2012/08/17/playing-a-sound-with-python.html). collier@Nacho-Laptop:~$ ./pyglet.py Traceback (most recent call last): File "./pyglet.py", line 2, in import pyglet File "/home/collier/pyglet.py", line 3, in song = pyglet.media.load('./boot.ogg') AttributeError: 'module' object has no attribute 'media' Mahalo, DCJ You appear to have confused Python by having a module named pyglet AND a local file named pyglet.py. This when you say import pyglet, you are not getting the pyglet module, but instead your own file pyglet.py, which of course, has nothing named media in it. Rename your file and try again. P.S. It is a common newbie error to hide a system file like this and suffer the consequence. We've all done it -- at least once. :^) ) -- http://mail.python.org/mailman/listinfo/python-list
Re: binary key in dictionary
On 07/30/2013 01:29 PM, cerr wrote: Hi, In my application I have followingf lines: print curr_mac print hexlify(buf) binmac = unhexlify(curr_mac) tmpgndict[binmac] += buf curr_mac being a 3Byte MAVC address in ASCII and I want to populate a dictionary where the value(buf) is indexed by binary mac. I get this in my code: Traceback (most recent call last): File "gateway.py", line 2485, in main() File "gateway.py", line 2459, in main cloud_check() File "gateway.py", line 770, in cloud_check gnstr_dict[src] = gn_from_cloud(curr_mac) File "gateway.py", line 2103, in gn_from_cloud tmpgndict[binmac] += "HELLO" KeyError: '\x04\xeeu' but then again, the following works fine in the python interpreter: mac = '04ee75' dat = '2a0001016d03c400040001000a' mydict = {} mydict[unhexlify(mac)]=dat print mydict {'\x04\xeeu': '2a0001016d03c400040001000a'} I really seem to do something wrong and can't see what it is. Can anyone help me further here? Thank you very much! Ron You are confusing the problem with excess code. Examine the following simpler example which illustrates the problem: >>> d = {} >>> d[1] = 99 >>> d[2] += 98 Traceback (most recent call last): File "", line 1, in KeyError: 2 >>> The line d[1] = 99 creates a key-value pair in the dictionary, but the line d[2] += 98 tries to add 98 to an already existing value at d[2], But there is no value at d[2] until you set it: d[2] = 0 # for instance You may want to look at defaultdict from the collections module. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: What’s the differences between these two pieces of code ?
On 07/06/2012 09:56 PM, iMath wrote: What’s the differences between these two pieces of code ? (1) for i in range(1, 7): print(2 * i, end=' ') (2) for i in range(1, 7): print(2 * i, end=' ') print() when executed both respectively in Python shell ,I get the same effect . Who can tell me why ? What "effect" are you referring to? What did you expect? What did you get? What version of Python? (3 I'd guess). As for me, the first one fails because of a syntax (indentation) error and the second prints the even numbers 2 through 12. What are we supposed to be comparing? Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: python CAD libraries?
On 09/10/2012 02:10 PM, Jayden wrote: Are there any python CAD libraries that can (1) build simple 3D primitives solids such as spheres, cylinders and so on (2) perform bool operations on 3D solids (3) better if it has some transformations such has scaling, sweeping, and lofting Please recommend some good ones for me? Thanks a lot!! Try PythonCAD: http://sourceforge.net/projects/pythoncad/ (Google would have been faster. :-) ) Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: how to insert random error in a programming
On 10/15/2012 06:55 AM, Debashish Saha wrote: how to insert random error in a programming? Drink several beers before you start programming. :-) -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: date and time comparison how to
On 10/29/2012 04:13 PM, noydb wrote: All, I need help with a date and time comparison. Say a user enters a date-n-time and a file on disk. I want to compare the date and time of the file to the entered date-n-time; if the file is newer than the entered date-n-time, add the file to a list to process. How best to do? I have looked at the datetime module, tried a few things, no luck. Is os.stat a part of it? Tried, not sure of the output, the st_mtime/st_ctime doesnt jive with the file's correct date and time. ?? Any help would be appreciated! Use the datetime module (distributed with Python) to compare date/times. You can turn a filesystem time into a datetime with something like the following: import datetime, os, stat mtime = os.lstat(filename)[stat.ST_MTIME] // the files modification time dt = datetime.datetime.fromtimestamp(mtime) -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: logger doesn't roll over
Ron, LOGFILE, maxBytes=(1048576*10), backupCount=5 What am I doing wrong here, I don't get it. 10 * 1048576 = 10MB -- GC -- http://mail.python.org/mailman/listinfo/python-list
Re: Conversion of List of Tuples
On 12/03/2012 11:58 AM, subhabangal...@gmail.com wrote: [(1,2), (3,4)] >>> L=[(1,2), (3,4)] >>> >>> [b for a in L for b in a] [1, 2, 3, 4] -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Gary Sokolich - 3463
3463 W Gary Sokolich 801 Kings Road Newport Beach, CA 92663-5715 (949) 650-5379 Local PD 949-644-3681 Residence: 1029 S Point View St Los Angeles CA 90035 (310) 650-5379 and 5309 Victoria Ave., Los Angeles, CA, 90043 http://web.archive.org/web/20080821231423/http://www.tbpe.state.tx.us/da/da022808.htm TEXAS BOARD OF PROFESSIONAL ENGINEERS February 28, 2008 Board Meeting Disciplinary Actions W. Gary Sokolich , Newport Beach, California – File B-29812 - It was alleged that. Sokolich unlawfully offered or attempted to practice engineering in Texas (...) Sokolich chose to end the proceedings by signing a Consent Order that was accepted by the Board to cease and desist from representing himself as an “Engineer” in Texas, from any and all representations that he can offer or perform engineering services and from the actual practice of engineering in Texas (...) Sokolich was also assessed a $1,360.00 administrative penalty. ___ http://articles.latimes.com/1988-04-14/local/me-1922_1_ucla-researcher A former UCLA employee has agreed to provide copies of his research to the school to settle a lawsuit the university filed against him in 1985, lawyers in the case said. (...) The University of California Board of Regents filed a $620,000 lawsuit against Sokolich, accusing him of taking research on the hearing capabilities of animals in June, 1982. Sokolich was dismissed by UCLA (...). (...) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, email temperature
On 12/22/2012 12:36 PM, Alexander Ranstam wrote: Hi! Im totally new to Python, and im using it on my Raspberry pi. I found a program that sends an email, and one that checks the temperature of my CPU, but i cant seem to combine the to into the funktion that i want, sending me the CPU temp via Email. The two programs work very well on their own, but this doesnt work. this works: server.sendmail(fromaddr, toaddrs, msg) but this doesnt: server.sendmail(fromaddr, toaddrs, cpu_temperature) despite the command "print cputemp" working in the same program. When i run the program i get the error: Traceback (most recent call last): File "sendcpu.py", line 36, in msg = cpu_temperature NameError: name 'cpu_temperature' is not defined Does anyone know why the program claims that cpu_temperature isnt defined, when it is? Thanx! //Alexander Could it be this easy? In one spot you refer to it as "cpu_temperature" and in another as "cputemp". If that's not it, you'd probably better show us your *real* code, otherwise we're just guessing. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, email temperature
On 12/22/2012 12:54 PM, KarlE wrote: On Saturday, December 22, 2012 9:44:39 PM UTC+1, Joel Goldstick wrote: On Sat, Dec 22, 2012 at 3:36 PM, Alexander Ranstam wrote: Hi! Im totally new to Python, and im using it on my Raspberry pi. I found a program that sends an email, and one that checks the temperature of my CPU, but i cant seem to combine the to into the funktion that i want, sending me the CPU temp via Email. The two programs work very well on their own, but this doesnt work. this works: server.sendmail(fromaddr, toaddrs, msg) but this doesnt: server.sendmail(fromaddr, toaddrs, cpu_temperature) despite the command "print cputemp" working in the same program. When i run the program i get the error: Traceback (most recent call last): File "sendcpu.py", line 36, in msg = cpu_temperature NameError: name 'cpu_temperature' is not defined Does anyone know why the program claims that cpu_temperature isnt defined, when it is? You should copy and paste the code here including the context around the error. You say print cputemp works, but cpu_temperature is not defined. They are spelled differently. Start there Thanx! //Alexander -- http://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick Hi! I made a typing error, and couldnt edit the post :( this is the code: #!/usr/bin/env python from __future__ import division from subprocess import PIPE, Popen import psutil import smtplib def get_cpu_temperature(): process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE) output, _error = process.communicate() return float(output[output.index('=') + 1:output.rindex("'")]) def main(): cpu_temperature = get_cpu_temperature() cpu_usage = psutil.cpu_percent() ram = psutil.phymem_usage() ram_total = ram.total / 2**20 # MiB. ram_used = ram.used / 2**20 ram_free = ram.free / 2**20 ram_percent_used = ram.percent disk = psutil.disk_usage('/') disk_total = disk.total / 2**30 # GiB. disk_used = disk.used / 2**30 disk_free = disk.free / 2**30 disk_percent_used = disk.percent # # Print top five processes in terms of virtual memory usage. # print 'CPU temperature is: ', cpu_temperature fromaddr = 'myemailadress' toaddrs = 'myemailadress' #msg = 'There was a terrible error that occured and I wanted you to know!' msg = cpu_temperature # Credentials (if needed) username = 'myusername' password = 'mypassword' # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, cpu_temperature) server.quit() if __name__ == '__main__': main() running it gives the following error: pi@raspberrypi /home/python $ python sendcpu.py Traceback (most recent call last): File "sendcpu.py", line 36, in msg = cpu_temperature NameError: name 'cpu_temperature' is not defined pi@raspberrypi /home/python $ isnt cpu_temperature defined? First: Learn about Python SCOPES. You are defining variables inside (as local variables) the procedure main, but they are lost as soon as main returns. If you want values computed inside main but available outside main, you should return them. Second: Some confusion over what order things are executed in. The code in main is run when you call main -- ans that's at the very end of the file. The lines before the call to main expect to use the value cpu_temperature when you have not yet called main to compute the value (and which doesn't even return the value as noted above). The confusion is partly caused by having some of your code inside main and some of it outside main and expecting the two parts to communicate.I'd suggest putting everything up through the server.quit() into procedure main. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to solve complex equation?
On 01/01/2013 11:02 AM, Usama Khan wrote: how to solve complex equation in pyhton? and then use it to make a program. . i have created new post as my last post is i guessed ranked as a cheater. .:( i know very litle about python as well as programing. . which equation am taliking u will be thinking. . i am giving u the link kindly c that equation. . n kindly let me know the way. . https://groups.google.com/forum/?fromgroups=#!topic/comp.lang.python/cxG7DLxXgmo Please STOP asking this question, and try to understand the answers you have already been given. Short answer: This is NOT a python question, and you can't solve it in Python. Longer answer: This is a math question. Some equations can be solved with algebra, and some can't, in which case perhaps you need some sort of a technique for numerical approximation.Other's have indicated that your problem probably falls into the later category.What YOU need to do is investigate iterative techniques for numerical solutions and pick one. (And this Python list is CERTAINLY the wrong place for such math questions.) Once you know what solution technique you want to use, you could then come back to this group and ask for help implementing it. P.S. I have implemented several such techniques, and I have taught college courses involving such techniques, and I'll say this: What you ask is the subject of AT LEAST several hours of lectures and possibly several semesters worth of study. No one is going to put that kind of time into answering your question here. -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: Using an object inside a class
On 01/23/2012 11:44 AM, Jonno wrote: I have a pretty complicated bit of code that I'm trying to convert to more clean OOP. Without getting too heavy into the details I have an object which I am trying to make available inside another class. The reference to the object is rather long and convoluted but what I find is that within my class definition this works: class Class1: def __init__(self): def method1(self): foo.bar.object But this tells me "global name foo is not defined": class Class1: def __init__(self): foo.bar.object Obviously I want the object to be available throughout the class (I left out the self.object = etc for simplicity). Any ideas why I can reference foo inside the method but not in __init__? You're not telling us everything. In fact, with the code you gave us, neither method1 nor __init__ will work correctly, because you have not defined foo *anywhere*. Without knowledge of what you are *really* doing, I'll say this: Both method1 and __init__ are methods of Class1, and both have the same rules for looking up variables. If either method binds a value to foo, then your code may access it: class Class1: def __init__(self): foo = whatever # Local to this method foo.bar.object If the method does not bind it, then Python will look in the class for foo. This could work class Class1: foo = whatever # Available to all instances def __init__(self): foo.bar.object If that fails, Python will look in the globals, so this could work: foo = whatever # Available across the full module class Class1: def __init__(self): foo.bar.object Python goes on one further level when searching for a variable -- that being the builtins. -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting 1172026 entries
On 05/06/2012 09:29 AM, J. Mwebaze wrote: sorry see, corrected code for filename in txtfiles: temp=[] f=open(filename) for line in f.readlines(): line = line.strip() line=line.split() temp.append((parser.parse(line[0]), float(line[1]))) temp=sorted(temp) with open(filename.strip('.txt')+ '.sorted', 'wb') as p: for i, j in temp: p.write('%s %s\n' %(str(i),j)) Don't do temp = sorted(temp) That will create a *new* copy of the list to sort, and the assignment will free up the original list for deletion and garbage collection. Instead do the in-place sort: temp.sort() Same result, less thrashing. This will make your program slightly more efficient, HOWEVER, it is not the solution of your week-long sort problem. Gary Herron On Sun, May 6, 2012 at 6:26 PM, J. Mwebaze <mailto:jmweb...@gmail.com>> wrote: I have attached one of the files, try to sort and let me know the results. Kindly sort by date. ooops - am told the file exceed 25M. below is the code import glob txtfiles =glob.glob('*.txt') import dateutil.parser as parser for filename in txtfiles: temp=[] f=open(filename) for line in f.readlines(): line = line.strip() line=line.split() temp.append((parser.parse(line[0]), float(line[1]))) temp=sorted(temp) with open(filename.strip('.txt')+ '.sorted', 'wb') as p: for i, j in temp: p.write('%s %s\n' %(str(i),j)) On Sun, May 6, 2012 at 6:21 PM, Devin Jeanpierre mailto:jeanpierr...@gmail.com>> wrote: On Sun, May 6, 2012 at 12:11 PM, J. Mwebaze mailto:jmweb...@gmail.com>> wrote: > [ (datatime, int) ] * 1172026 I can't duplicate slowness. It finishes fairly quickly here. Maybe you could try posting specific code? It might be something else that is making your program take forever. >>> x = [(datetime.datetime.now() + datetime.timedelta(random.getrandbits(10)), random.getrandbits(32)) for _ in xrange(1172026)] >>> random.shuffle(x) >>> x.sort() >>> -- Devin -- *Mob UG: +256 (0) 70 1735800 | NL +31 (0) 6 852 841 38 | Gtalk: jmwebaze | skype: mwebazej | URL: www.astro.rug.nl/~jmwebaze <http://www.astro.rug.nl/%7Ejmwebaze> /* Life runs on code */* -- *Mob UG: +256 (0) 70 1735800 | NL +31 (0) 6 852 841 38 | Gtalk: jmwebaze | skype: mwebazej | URL: www.astro.rug.nl/~jmwebaze <http://www.astro.rug.nl/%7Ejmwebaze> /* Life runs on code */* -- http://mail.python.org/mailman/listinfo/python-list
Kathryn Sokolich Spawned A Crook
Sure did http://www.manta.com/c/mmlq5dm/w-gary-sokolich W Gary Sokolich 801 Kings Road Newport Beach, CA 92663-5715 (949) 650-5379 http://www.tbpe.state.tx.us/da/da022808.htm TEXAS BOARD OF PROFESSIONAL ENGINEERS February 28, 2008 Board Meeting Disciplinary Actions W. Gary Sokolich , Newport Beach, California – File B-29812 - It was alleged that Dr. Sokolich unlawfully offered or attempted to practice engineering in Texas (...) Dr. Sokolich chose to end the proceedings by signing a Consent Order that was accepted by the Board to cease and desist from representing himself as an “Engineer” in Texas, from any and all representations that he can offer or perform engineering services and from the actual practice of engineering in Texas (...) Dr. Sokolich was also assessed a $1,360.00 administrative penalty. ___ http://articles.latimes.com/1988-04-14/local/me-1922_1_ucla-researcher A former UCLA physiologist has agreed to provide copies of his research to the school to settle a lawsuit the university filed against him in 1985, lawyers in the case said. (...) The University of California Board of Regents filed a $620,000 lawsuit against Sokolich, accusing him of taking research on the hearing capabilities of animals in June, 1982. Sokolich was dismissed by UCLA because research funding had run out. (...) -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to customise math.sqrt(x) for some x?
On 07/16/2011 01:35 AM, Steven D'Aprano wrote: I have a custom object that customises the usual maths functions and operators, such as addition, multiplication, math.ceil etc. Is there a way to also customise math.sqrt? I don't think there is, but I may have missed something. Create a file named myMath.py containing: -- from math import * def sqrt(x): ...whatever you want... --- Then you can: import math #to get normal stuff and import myMath # to get your customized stuff or import myMath as math # to get your stuff but named math. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Can someone help please
On 07/21/2011 10:02 AM, Gary wrote: Hi Can someone help me with this code below please, For some reason it will not send me the first text file in the directory. I made up an empty file a.txt file with nothing on it and it sends the files i need but would like to fix the code. Thanks total = ' ' os.chdir('/home/woodygar/Desktop/Docs') for i in os.listdir('.'): if '.txt' in i: f = open(i, 'r') total += f.read() f.close() message = """\ Subject: %s %s """% (SUBJECT,total) Huh? Confused I am. If your first file is empty and you concatenate the contents of each file (that's what total+=f.read() does), then what do you expect to see? If you concatenate nothing (that is, the empty file), then you should see nothing. I see no problem with the code, but perhaps a problem with your expectations. If I've misunderstood your question, the please reword and resend it, but this time include more information: The files in '.', their content, the output you do get, and the output you expected. Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: Can someone help please
On 07/21/2011 10:23 AM, Billy Mays wrote: On 07/21/2011 01:02 PM, Gary wrote: Hi Can someone help me with this code below please, For some reason it will not send me the first text file in the directory. I made up an empty file a.txt file with nothing on it and it sends the files i need but would like to fix the code. Thanks total = ' ' os.chdir('/home/woodygar/Desktop/Docs') for i in os.listdir('.'): if '.txt' in i: f = open(i, 'r') total += f.read() f.close() message = """\ Subject: %s %s """% (SUBJECT,total) Does the file end with '.TXT' ? This might help: total = ' ' os.chdir('/home/woodygar/Desktop/Docs') txts = (nm for nm in os.listdir('.') if nm.lower().endswith('.txt') ) for nm in txts: f = open(nm, 'r') total += f.readlines() f.close() message = """\ Subject: %s %s """% (SUBJECT,total) I also changed read to readlines(). That won't work (You must not have even tried to run this.) The call f.readlines() returns a list which causes an error when added to a string: TypeError: cannot concatenate 'str' and 'list' objects Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: Can someone help please
Hi Thanks for your reply's and sorry guys for not explaining properly ok the problem with the code, which i never realised before, is it sends the first txt file as the header or subject field in an email and the rest in the body of the email which i don't want. I would like all the txt files in the body of an email Thanks On Thu, Jul 21, 2011 at 6:23 PM, Billy Mays < 81282ed9a88799d21e77957df2d84bd6514d9...@myhashismyemail.com> wrote: > On 07/21/2011 01:02 PM, Gary wrote: > >> Hi >> Can someone help me with this code below please, >> For some reason it will not send me the first text file in the directory. >> I made up an empty file a.txt file with nothing on it and it sends the >> files i need but would like to fix the code. >> Thanks >> >> >> >> >> total = ' ' >> os.chdir('/home/woodygar/**Desktop/Docs') >> for i in os.listdir('.'): >> if '.txt' in i: >> f = open(i, 'r') >> total += f.read() >> f.close() >> message = """\ >> Subject: %s >> %s >> >> """% (SUBJECT,total) >> >> > Does the file end with '.TXT' ? This might help: > > > total = ' ' > os.chdir('/home/woodygar/**Desktop/Docs') > txts = (nm for nm in os.listdir('.') if nm.lower().endswith('.txt') ) > for nm in txts: >f = open(nm, 'r') >total += f.readlines() > >f.close() > message = """\ > Subject: %s > %s > > """% (SUBJECT,total) > > > > > I also changed read to readlines(). > > -- > http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list> > -- http://mail.python.org/mailman/listinfo/python-list
Re: how to separate a list into two lists?
On 08/06/2011 10:07 AM, smith jack wrote: if a list L is composed with tuple consists of two elements, that is L = [(a1, b1), (a2, b2) ... (an, bn)] is there any simple way to divide this list into two separate lists , such that L1 = [a1, a2... an] L2=[b1,b2 ... bn] i do not want to use loop, any methods to make this done? List comprehension: L1 = [item[0] for item in L] L2 = [item[1] for item in L] which *is* still a loop. (You are going to have to write *really* arcane code to have no loop.) Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: pairwise combination of two lists
On 08/17/2011 01:22 PM, Yingjie Lin wrote: Hi Python users, I have two lists: li1 = ['a', 'b'] li2 = ['1', '2'] and I wish to obtain a list like this li3 = ['a1', 'a2', 'b1', 'b2'] Is there a handy and efficient function to do this, especially when li1 and li2 are long lists. I found zip() but it only gives [('a', '1'), ('b', '2')], not exactly what I am looking for. Thank you. - Yingjie >>> li1 = ['a', 'b'] >>> li2 = ['1', '2'] >>> print [a+b for a in li1 for b in li2] ['a1', 'a2', 'b1', 'b2'] Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Floating point multiplication in python
On 09/05/2011 10:57 PM, xyz wrote: hi all: As we know , 1.1 * 1.1 is 1.21 . But in python ,I got following : 1.1 * 1.1 1.2102 why python get wrong result? Who can tell me where's the 0.0002 from? It's not a python errorIt's the nature of floating point arithmetic to be inaccurate on *ANY* computer.Python just allows you to see the inaccuracies. (But try: print 1.1*1.1 and see that the print statement does hide the roundoff error from you.) Read this for more info: http://pyfaq.infogami.com/why-are-floating-point-calculations-so-inaccurate -- http://mail.python.org/mailman/listinfo/python-list
Re: I am confused by
On 09/07/2011 03:57 PM, Martin Rixham wrote: Hi all I would appreciate some help understanding something. Basically I am confused by the following: >>> a = [[0, 0], [0, 0]] >>> b = list(a) >>> b[0][0] = 1 >>> a [[1, 0], [0, 0]] I expected the last line to be [[0, 0], [0, 0]] I hope that's clear enough. Martin You were expecting the assignment to "b" to create a copy of the original list, and it does, but the copy is only one level deep. So a and b are different lists, but a[i] and b[i] are the same objects for each i. There is a "deepcopy" in the library which may do what you expect. Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
On 04/01/2011 12:52 PM, Karl wrote: Hello, one beginner question: aList = [0, 1, 2, 3, 4] bList = [2*i for i in aList] sum = 0 for j in bList: sum = sum + bList[j] Your j is already an element of bList. You don't need to index bList again. Instead do for b in bList: sum = sum+b print j 0 2 4 *IndexError:* 'list index out of range' Why is j in the second run 2 and not 1 in the for-loop?? I think j is a control variable with 0, 1, 2, 3, ... No, it's not a control variable, it's the actual elements of the list. If you want a control variable as an index you can do for j in range(len(bList)): sum = sum + bList[j] But that is less efficient Thanks! Karl -- http://mail.python.org/mailman/listinfo/python-list
Re: Fibonacci series recursion error
On 04/29/2011 08:22 PM, lalit wrote: import os def fib(n): if n == 1: return(n) else: return (fib(n-1)+fib(n-2)) list=fib(20) print(list) The above function return the return (fib(n-1)+fib(n-2)) RuntimeError: maximum recursion depth exceeded in comparison [36355 refs] can any one help You correctly test for n==1, but what about when n==2?When the recursion works its way down to fib(2), you call both fib(1) and fib(0), but the latter starts an infinite sequence of calls to fib(-1), fib(-2) and so on without end. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: None is None but not working
On 09/27/2017 01:05 PM, Sayth Renshaw wrote: Hi I have got a successful script setup to rotate through dates and download json data from the url. As the api returns 200 whether successful I want to check if the file returned is not successful. when a file doesn't exist the api returns {'RaceDay': None, 'ErrorInfo': {'SystemId': 200, 'ErrorNo': 55013, 'DisplayMessage': 'File Not Found.', 'ContactSupport': False, 'SupportErrorReference': '200-55013'}, 'Success': False} When I call data = r.json() it says its type is None if it is not successful so I thought it easier to check that. However checking for None does not work the flow in my if else falls straight to else. for dates in fullUrl: r = requests.get(dates) data = r.json() if data is None: print("Nothing here") else: print(data["RaceDay"]) Your data is not None, it's a full dictionary. However, data["RaceDay"] *is* None as shown in your output. Thus your test should be: if data["RaceDay"] is None: ... rather than if data is None: ... and I get output of None None {'MeetingDate': '2017-01- ... and so on. How can I actually get this to check? If i use type(data) I also get None. Cheers Sayth -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Please Help
On 01/26/2018 08:33 PM, mohammedfaraz...@gmail.com wrote: import numpy as np x=np.unit8([250) print(x) y=np.unit8([10]) print(y) z=x+y print(z) output [250] [10] [4] My question how is z [4] Despite all the typos in your post, you appear to be doing 8 bit unsigned arithmetic. Do you know what that means? The answer you might have expected (i.e. 260) does not fit in the 0 ... 255 range of 8 bits, and so the result has overflowed and "wrapped around" to produce 4. Try this for a simpler example of the same: >>> np.uint8(260) 4 Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: =- and -= snag
On 3/13/23 2:26 PM, morp...@gmail.com wrote: Hi. I was working in Python today, and sat there scratching my head as the numbers for calculations didn't add up. It went into negative numbers, when that shouldn't have been possible. Turns out I had a very small typo, I had =- instead of -=. Isn't it unpythonic to be able to make a mistake like that? Regards, Morten These all mean the same thing, but I don't see a good way to designate the second or third as an error. x = -5 x=-5 x =- 5 Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology -- https://mail.python.org/mailman/listinfo/python-list
Re: Standard class for time *period*?
The Python standard library module datetime seems to be what you want. It has objects representing date/times, and deltatimes (i.e., durations). These can be timezone aware or not as you wish. Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology On 3/27/23 6:00 AM, loris.benn...@fu-berlin.de wrote: Hi, I have been around long enough to know that, due to time-zones, daylight saving and whatnot, time-related stuff is complicated. So even if I think something connected with time should exist, there may well be a very good reason why it does not. My problem: I need to deal with what I call a 'period', which is a span of time limited by two dates, start and end. The period has a 'duration', which is the elapsed time between start and end. The duration is essentially a number of seconds, but in my context, because the durations are usually hours or days, I would generally want to display the duration in a format such as "dd-hh:mm:ss" My (possibly ill-founded) expectation: There is a standard class which encapsulates this sort of functionality. My (possibly insufficiently researched) conclusion: Such a standard class does not exist. What is at fault here? My expectation or my conclusion? Cheers, Loris -- https://mail.python.org/mailman/listinfo/python-list
Re: Change first occurrence of character x in a string - how?
The string type has a replace function that does what you want. Except you can't change a string -- they are immutable -- so this creates a new string. >>> s = 'linux-raid.vger.kernel.org' >>> new_s = s.replace('.', '@', 1) >>> new_s 'linux-r...@vger.kernel.org' On 2/14/21 1:14 PM, c...@isbd.net wrote: What's the easiest way to change the first occurrence of a specified character in a string? E.g. I want to change linux-raid.vger.kernel.org to linux-r...@vger.kernel.org, it's a fairly general requirement of needing to change '.' to '@'. Alternatively is there an RE 'match' function that would test if linux-r...@vger.kernel.org matches linux-raid.vger.kernel.org? I don't really care if the '.' are all regarded as wild cards, the match will be accurate enough. -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: A strange list concatenation result
On 08/11/2016 03:06 PM, Mok-Kong Shen wrote: def test(list1,list2): list1+=[4,5,6] list2=list2+[4,5,6] print("inside ",list1,list2) return # With list1=list2=[1,2,3] test(list1,list2) print("outside",list1,list2) # I got the following: # inside [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 4, 5, 6] # outside [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] # With list1=[1,2,3] list2=[1,2,3] test(list1,list2) print("outside",list1,list2) # I got the following: # inside [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] # outside [1, 2, 3, 4, 5, 6] [1, 2, 3] I think the following shows the same issue in a much simpler fashion: In this (and your first) example, there is only one list, although it has two names to reference it. >>> list1 = list2 = [1,2,3] >>> list1 += [4,5,6] >>> print(list1, list2) [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] In this next example, there are two separate lists: >>> list1 = [1,2,3] >>> list2 = [1,2,3] >>> list1 += [4,5,6] >>> print(list1, list2) [1, 2, 3, 4, 5, 6] [1, 2, 3] Does that help? Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
DED processing
I have to go out for a while, so for DED processing two options from my end: 1. Process as you all have been in the past for now. If you all do this, the records that have not been mailed prior to the latest list are contained in a MailManage Job name DED_master. If you chose to process as in the past, these records should be exported to a spreadsheet and added to whatever new file you have for today. 2. I can come in tomorrow morning at about 9:00 and walk Greg thru the way I process the DED job. Let me know. -- https://mail.python.org/mailman/listinfo/python-list
Re: degrees and radians.
On 08/23/2016 09:08 PM, murdocksgra...@gmail.com wrote: On Saturday, May 4, 2002 at 3:37:07 AM UTC-4, Jim Richardson wrote: -BEGIN PGP SIGNED MESSAGE- Hash: SHA1 I am trying to get the math module to deal with degrees rather than radians. (that it deals with radians for the angular functions like sin() isn't mentioned in the docs, which was sort of an eyeopener :) I can't find any info on doing this. I can convert from-to degrees in the code calling the function, but that's a bit clunky. Any pointers to an FM to R? :) -BEGIN PGP SIGNATURE- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE804+jd90bcYOAWPYRAt9KAKCuqeC4ozuXSaKZ5xY27Wv+k04QuQCcCrCZ WyichPnKgXo+GaDdAebsaeU= =h+vc -END PGP SIGNATURE- -- Jim Richardson Anarchist, pagan and proud of it http://www.eskimo.com/~warlock Linux, from watches to supercomputers, for grandmas and geeks. For what is is worth.. Electrical Engineers for the most part work in degrees NOT Radians for example try doing polar to rectangular or vice versa in polar. I have never seen it done. Also Borland C and C++ used Degrees and NOT Radians.. go look at the libraries Just for what its worth. Do you really need anything more complex than this? >>> toRadians = math.pi/180.0 >>> math.sin(90*toRadians) 1.0 Perhaps I'm not understanding what you mean by "clunky", but this seems pretty clean and simple to me. Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: why this code loop forever after a draw a rectangle
On 09/16/2016 04:24 AM, meInvent bbird wrote: im = img.copy() cntcounter = 0 for cnt in contours: epsilon = 0.1*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) #peri = cv2.arcLength(cnt, True) #approx = cv2.approxPolyDP(c, 0.5 * peri, True) #print("len(approx)="+str(len(approx))) if len(approx) == 4: print("approx=" + str(approx)) cntcounter = cntcounter + 1 print("here1") x,y,w,h = cv2.boundingRect(cnt) print("here2") while im is None: time.sleep(1) if im is not None: print("here3") im = cv2.rectangle(im.copy(), (x,y), (x+w, y+h), (0,255,0), 2) #im = cv2.line(im,(x,y),(x+w,y),(0,255,0),2) #im = cv2.line(im,(x+w,y),(x+w,y+h),(0,255,0),2) #im = cv2.line(im,(x,y+h),(x+w,y+h),(0,255,0),2) #im = cv2.line(im,(x,y),(x,y+h),(0,255,0),2) cv2.imwrite(r'C:\Users\tester\Documents\masda.png',im) These two lines: while im is None: time.sleep(1) are an infinite loop if im is None; Since you haven't told us what im (or img, contours, cv2) are, I can't tell how im might become None, but it does look like you (confusingly) use im for two different things: an img.copy() and a cv2.rectangle, whatever those may be. Pure guesswork: if cv2.rectangle draws a rectangle, what does it return? If it doesn't return anything, the line im = cv2.rectangle(...) is how im gets the value of None. -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: why this code loop forever after a draw a rectangle
On 09/16/2016 05:18 AM, meInvent bbird wrote: i follow this post to give some time it to operate, wait a long time still looping http://answers.opencv.org/question/60094/libpng-warning-image-width-is-zero-in-ihdr/ i can not stand this Ninja coding life any more, i have to open my code for ask this error import cv2 import numpy as np #from matplotlib import pyplot as plt import time #print("1=" + str(int(sys.argv[1]))) #print("2=" + str(int(sys.argv[2]))) #print("3=" + str(int(sys.argv[3]))) img_rgb = cv2.imread(r'C:\Users\martin\Documents\scree2.png') img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) template = cv2.imread(r'C:\Users\martin\Documents\dragob.png',0) w, h = template.shape[::-1] res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) threshold = 0.64 loc = np.where( res >= threshold) pt = [(0,0)] while not zip(*loc[::-1]): threshold = threshold - 0.02 loc = np.where( res >= threshold) counter = 1 print("threshold="+str(threshold)) for pt2 in zip(*loc[::-1]): cv2.rectangle(img_rgb, pt2, (pt2[0] + w, pt2[1] + h), (0,0,255), 2) pt = pt2 crop_img = img_rgb[pt[1]:(pt[1]+h), pt[0]:(pt[0]+w)] counter = counter + 1 cv2.imwrite("C:\\Users\\tester\\Documents\\res.png",crop_img) #import cv2 #winName = "Movement Indicator" #cv2.namedWindow(winName, cv2.WINDOW_NORMAL) img = cv2.imread(r'C:\Users\tester\Documents\res.png',1) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) height, width = gray.shape edges = cv2.Canny(gray,height,width,apertureSize = 3) #edges = cv2.Canny(gray,30,200) #gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) #ret,thresh = cv2.threshold(edges.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE,0) ret,thresh = cv2.threshold(edges,250,150,0) contours,hierarchy = cv2.findContours(thresh, 1, 2) #contours = sorted(contours, key = cv2.contourArea, reverse = True)[:10] im = img.copy() cntcounter = 0 for cnt in contours: epsilon = 0.1*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) #peri = cv2.arcLength(cnt, True) #approx = cv2.approxPolyDP(c, 0.5 * peri, True) #print("len(approx)="+str(len(approx))) if len(approx) == 4: print("approx=" + str(approx)) cntcounter = cntcounter + 1 print("here1") x,y,w,h = cv2.boundingRect(cnt) print("here2") #im = img.copy() while im is None: time.sleep(1) if im is not None: print("here3") im = cv2.rectangle(im.copy(), (x,y), (x+w, y+h), (0,255,0), 2) #cv2.imwrite("C:\\Users\\martin\\Documents\\masda"+str(cntcounter)+".png",imi) #im = cv2.line(im,(x,y),(x+w,y),(0,255,0),2) #im = cv2.line(im,(x+w,y),(x+w,y+h),(0,255,0),2) #im = cv2.line(im,(x,y+h),(x+w,y+h),(0,255,0),2) #im = cv2.line(im,(x,y),(x,y+h),(0,255,0),2) On Friday, September 16, 2016 at 7:34:04 PM UTC+8, Waffle wrote: On 16 September 2016 at 14:24, meInvent bbird wrote: im = img.copy() cntcounter = 0 for cnt in contours: epsilon = 0.1*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) #peri = cv2.arcLength(cnt, True) #approx = cv2.approxPolyDP(c, 0.5 * peri, True) #print("len(approx)="+str(len(approx))) if len(approx) == 4: print("approx=" + str(approx)) cntcounter = cntcounter + 1 print("here1") x,y,w,h = cv2.boundingRect(cnt) print("here2") while im is None: time.sleep(1) if im is not None: print("here3") im = cv2.rectangle(im.copy(), (x,y), (x+w, y+h), (0,255,0), 2) #im = cv2.line(im,(x,y),(x+w,y),(0,255,0),2) #im = cv2.line(im,(x+w,y),(x+w,y+h),(0,255,0),2) #im = cv2.line(im,(x,y+h),(x+w,y+h),(0,255,0),2) #im = cv2.line(im,(x,y),(x,y+h),(0,255,0),2) cv2.imwrite(r'C:\Users\tester\Documents\masda.png',im) -- https://mail.python.org/mailman/listinfo/python-list not sure but.. this bit reads really suspicious: while im is None: time.sleep(1) if im is ever None then how will it ever become not None? unless there is some other thread at work i can't really see this happening. and if there is some other thread at work then there is probably some better solution than sleep() Reading the manual for opencv, we see that cv2.rectangle does indeed return None: Python: cv.Rectangle(img, pt1, pt2, color, thickness=1, lineType=8, shift=0) → None So the first pass through your loop
Re: specifying the same argument multiple times with argparse
On 04/16/2018 02:31 PM, larry.mart...@gmail.com wrote: Is there a way using argparse to be able to specify the same argument multiple times and have them all go into the same list? For example, I'd like to do this: script.py -foo bar -foo baz -foo blah and have the dest for foo have ['bar', 'baz', 'blah'] From the argparse web page (https://docs.python.org/3/library/argparse.html): 'append' - This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. Example usage: >>> >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', action='append') >>> parser.parse_args('--foo 1 --foo 2'.split()) Namespace(foo=['1', '2']) I hope that helps. -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Weird side effect of default parameter
This is a well known feature of Python. It's a very common "gotcha" to new Python programmers. Google "Mutable default parameters in Python" for long list of explanations and fixes. In short, don't use a mutable object as a default parameter. Gary Herron On 05/03/2018 12:47 PM, python-list@python.org wrote: Hello, I don't understand the behavior of the code below. Why does the dict property "a" of both objects contain the same keys? This is only if "a=dict" is in the initializer. If I put self.a = dict() into the init function, I get two separate dicts class Foo(object): def __init__(self, x, a=dict()): self.x = x self.a = a self.a[x] = x c = Foo(1) d = Foo(2) print(c.__dict__) print(d.__dict__) robert -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Numpy array
The "indexing" page of the documentation might help you with this: https://docs.scipy.org/doc/numpy-1.14.0/reference/arrays.indexing.html On 05/18/2018 09:50 PM, sharan.basa...@gmail.com wrote: This is regarding numpy array. I am a bit confused how parts of the array are being accessed in the example below. 1 import scipy as sp 2 data = sp.genfromtxt("web_traffic.tsv", delimiter="\t") 3 print(data[:10]) 4 x = data[:,0] 5 y = data[:,1] Apparently, line 3 prints the first 10 entries in the array line 4 & 5 is to extract all rows but only 1st and second columns alone for x and y respectively. I am confused as to how data[:10] gives the first 10 rows while data[:,0] gives all rows -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: How can an int be '+' with a tuple?
In fact, the value of *any* is *not* an integer. The *any notation causes Python to pack all the arguments into a tuple. This feature is usually used when there are multiple (and an unknown number) of parameters, but it works perfectly well with a single parameter. Here's an example: >>> def progress(*any): print(any) >>> progress(1) (1,) >>> progress(1,2,3) (1, 2, 3) >>> On 06/02/2018 07:55 PM, jf...@ms4.hinet.net wrote: The attached is a script which can run under Python 3.4/Windows Vista correctly. One thing make me puzzled is that the "any + context" at line 18. The "any" was passed as an integer from line 43 and the "context" was defined as a tuple at line 35. This concatenation works! how? Best Regards, Jach Fong --- This email has been checked for viruses by Avast antivirus software. https://www.avast.com/antivirus -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: curve_fit in scipy
This is a Python forum, but what you are asking is not a Python question. You might find a better source of answers on a scipy specific forum. But here's my attempt at answers: On 06/19/2018 08:26 AM, sharan.basa...@gmail.com wrote: Hi All, I am working out an exercise on curve_fit function available scipy package. While I understand in general about curve_fit, I am unable to understand the following: params, params_covariance = optimize.curve_fit(test_func, x_data, y_data, p0=[2, 2]) Firstly, I don't understand why test_func is passed as an argument to cur_fit You are trying to fit a curve to some data, right. The curve_fit procedure needs to know what curve you are trying to fit. Is it a linear curve, exponential, polynomial or ...? In this example it's a sine function with parameters for regulating amplitude and frequency. But it could be any function with any parameters. To be more precise, test_function is not a single function y=f(x), but a whole family of functions y=f(x; a,b) where a and b define a particular function. Secondly, I don't understand how curve_fit knows the number of arguments that test_func takes. Part of the dynamic nature of Python is that a function carries with it the number of parameters (as just one among many such properties). We call it "introspection" when we examine such properties of objects. The curve_fit function usees such an introspection to find that test_function has two parameters (a and b) defining the family of curves. Full code is available below for reference: import numpy as np # Seed the random number generator for reproducibility np.random.seed(0) x_data = np.linspace(-5, 5, num=50) y_data = 2.9 * np.sin(1.5 * x_data) + np.random.normal(size=50) # And plot it import matplotlib.pyplot as plt plt.figure(figsize=(6, 4)) plt.scatter(x_data, y_data) from scipy import optimize def test_func(x, a, b): return a * np.sin(b * x) params, params_covariance = optimize.curve_fit(test_func, x_data, y_data, p0=[2, 2]) print(params) plt.figure(figsize=(6, 4)) plt.scatter(x_data, y_data, label='Data') plt.plot(x_data, test_func(x_data, params[0], params[1]), label='Fitted function') plt.legend(loc='best') plt.show() -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Probability
On 09/11/2018 11:54 AM, end...@freemail.hu wrote: Hello, I am new to Python and I have an exercise which I struggle with. The question is: In the strategic board game called Risk, one player can attack up to three soldiers simultaneously, while the defending player can defend up to two. In the case of exactly three attackers and two defenders, the collision is as follows. An attacking player rolls three red dice while the defending player rolls two blue dice. Then they compare the bigest throws of the attacker and the defender. The lesser value loses a soldier, in the case of equal values the attacker loses one soldier. Then the second largest numbers are also compared in the same way. Thus, the battle has three outcomes: the attacker loses two soldiers, each side loses 1-1 soldiers, the defender loses two soldiers. Simulate 1000 times the experiment and determine the relative frequency of the three events.Simulate 100 times the experiment and determine the relative frequency of the three events.Calculate the exact probability of the three outcomes by examining all possible cases. The probability is the ratio of the favorable cases and the total number of cases. Write these results with 5 decimal places leaving 3 spaces between them! The output of the program looks like this (of course with other numbers) Attacker Draw Defender 1000 experiment 0.35222 0.4 0.20334 100 experiment 0.33988 0.43011 0.23001 Probability 0.34000 0.43000 0.23000 The aim of this task is to get acquainted with the classical probability field, the relative frequency and the relation of it to the probability.Programming goal: recalling the basic elements of Python programming and generating random numbers.Help: by loading the random package (import random) and calling random.random() one may get a random number between 0 and 1 (by uniform distribution). The code int(random.random()*6)+1 gives back an integer number between 1 and 6. So I did like: import random def dice(): attacker_dice=[random.randint(1,6) for _ in range(3)] defender_dice=[random.randint(1,6) for _ in range(2)] a=max(attacker_dice) b=max(defender_dice) for i in range(1000): F=0 S=0 T=0 if a>b: F+=1 if a==b: S+=1 else: T+=1 Every time through this loop, you set F, S and T to zero. If you want those variables to accumulate values, move the three initialization lines to before the loop: F = 0 S = 0 T = 0 for ... if a>b: F += 1 ... and so on ... But you have another problem. You simulate rolling the dice only once. For your 1000 trials, you need to roll the dice 1000 times. The first few lines that simulate the dice roll must be inside the loop so that each pass through the loop rolls the dice. and I wanted to divide the F,T,S with 6^5 and make a table. But its giving me zeros or 333. And to get 5digits after the zero i wanted to use "%.5f " %First. Could you help me to finish this, and tell me what am I doing wrong? Thank you -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Probability
On 09/11/2018 11:54 AM, end...@freemail.hu wrote: Hello, I am new to Python and I have an exercise which I struggle with. The question is: In the strategic board game called Risk, one player can attack up to three soldiers simultaneously, while the defending player can defend up to two. In the case of exactly three attackers and two defenders, the collision is as follows. An attacking player rolls three red dice while the defending player rolls two blue dice. Then they compare the bigest throws of the attacker and the defender. The lesser value loses a soldier, in the case of equal values the attacker loses one soldier. Then the second largest numbers are also compared in the same way. Thus, the battle has three outcomes: the attacker loses two soldiers, each side loses 1-1 soldiers, the defender loses two soldiers. Simulate 1000 times the experiment and determine the relative frequency of the three events.Simulate 100 times the experiment and determine the relative frequency of the three events.Calculate the exact probability of the three outcomes by examining all possible cases. The probability is the ratio of the favorable cases and the total number of cases. Write these results with 5 decimal places leaving 3 spaces between them! The output of the program looks like this (of course with other numbers) Attacker Draw Defender 1000 experiment 0.35222 0.4 0.20334 100 experiment 0.33988 0.43011 0.23001 Probability 0.34000 0.43000 0.23000 The aim of this task is to get acquainted with the classical probability field, the relative frequency and the relation of it to the probability.Programming goal: recalling the basic elements of Python programming and generating random numbers.Help: by loading the random package (import random) and calling random.random() one may get a random number between 0 and 1 (by uniform distribution). The code int(random.random()*6)+1 gives back an integer number between 1 and 6. So I did like: import random def dice(): attacker_dice=[random.randint(1,6) for _ in range(3)] defender_dice=[random.randint(1,6) for _ in range(2)] a=max(attacker_dice) b=max(defender_dice) for i in range(1000): F=0 S=0 T=0 if a>b: F+=1 if a==b: S+=1 else: T+=1 Every time through this loop, you set F, S and T to zero. If you want those variables to accumulate values, move the three initialization lines to before the loop: F = 0 S = 0 T = 0 for ... if a>b: F += 1 ... and so on ... But you have another problem. You simulate rolling the dice only once. For your 1000 trials, you need to roll the dice 1000 times. The first few lines that simulate the dice roll must be inside the loop so that each pass through the loop rolls the dice. and I wanted to divide the F,T,S with 6^5 and make a table. But its giving me zeros or 333. And to get 5digits after the zero i wanted to use "%.5f " %First. Could you help me to finish this, and tell me what am I doing wrong? Thank you -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: trying to connect the setarrange and blendshape input target weight while running the script am getting error in the 8th line. (for each in lip_val_list: )
Your indentation of that line is incorrect. You also have indentation errors on lines 14 and 21. (Possibly more, that's all the further I checked.) Do you understand Python's indentation rules? In the future, you can do a lot better to help us help you. First, tell us the error you got instead of just saying you got an error. (Copy and paste the full error message.) Also tell us what version of Python (2 or 3), and what platform, in case any of that matters. Your subject line contains lots of meaningless distractions: What's a setarrange, what's a blendshape, what's an input target weight, what does it mean to connect them? Either none of that is important (as is the case in this simple indentation error), so don't include such distractions, or it does matter, so take the time to define those terms. Gary Herron On 09/13/2018 12:11 AM, christyso...@gmail.com wrote: lf_main_attr = "head_icon.Lf_Sticky_Lips" rt_main_attr = "head_icon.Rt_Sticky_Lips" lip_val_list = [18, 14] lip_name_list = ['upperLip', 'lowerLip'] name_counter = 0 for each in lip_val_list: half_val = (each / 2) + 1 total_val = each + 1 div_val = 10.0 / half_val counter = 0 while(counter -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: import inspect error
You appear to have a local file named keyword.py which is hiding a python installation file of the same name. Gary Herron On 09/17/2018 01:06 AM, jupiter@gmail.com wrote: I have following errors running on Ubuntu 18, any insight how to fix it? Thank you. Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. import inspect Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/inspect.py", line 42, in from collections import namedtuple File "/usr/lib/python2.7/collections.py", line 22, in from keyword import iskeyword as _iskeyword File "keyword.py", line 3, in from inspect import currentframe, getframeinfo ImportError: cannot import name currentframe -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Program to find Primes of the form prime(n+2) * prime(n+1) - prime(n) +- 1.
On 10/02/2018 01:23 PM, tomusa...@gmail.com wrote: Primes of the form prime(n+2) * prime(n+1) - prime(n) +- 1. DATA 31, 71, 73, 137, 211, 311, 419, 421, 647, 877, 1117, 1487, 1979, 2447, 3079, 3547, 4027, 7307, 7309, 12211, 14243, 18911, 18913, 23557, 25439, 28729, 36683, 37831, 46853, 50411, 53129, 55457, 57367, 60251, 67339, 70489, 74797, 89669, 98909, 98911 EXAMPLE 7*5 - 3 - 1 = 31 11*7 - 5 - 1 = 71 11*7 - 5 + 1 = 73 13*11 - 7 + 1 = 137 Can someone put this in a Python program and post? No, sorry, but that's not how this works. We're not here to do your homework for you, and you won't learn anything if we do. You make an attempt at solving this, asking any specific Python related questions you need help with, and you'll find this to be prompt, friendly, and helpful group. Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: My python code has suddenly started to give me error. Please see code below**
So, tell us the error and we'll see what we can do. Give us something to work with: Cut and past the full error message, trace back, whatever you can. Also tell us what version of Python, what system you are running on, how you run this code, ... On 10/08/2018 10:17 PM, upadhyay.kamay...@gmail.com wrote: ## Calculating the Lower Limits(LLi) and Upper Limit(ULi) for each Band, where i is 1,2,.10 LL1=0 print(LL1) print(P2) print(D2) if(P2>25): UL1=D1 print(UL1) elif(UL1==D2): print(UL1) LL2=UL1 if(P3>25): UL2=D2 print(UL2) elif(UL2==D3): print(UL2) LL3=UL2 if(P4>25): UL3=D3 print(UL3) elif(UL3==D4): print(UL3) LL4=UL3 if(P5>25): UL4=D4 print(UL4) elif(UL4==D5): print(UL4) LL5=UL4 if(P6>25): UL5=D5 print(UL5) elif(UL5==D6): print(UL5) LL6=UL5 if(P7>25): UL6=D6 print(UL6) elif(UL6==D7): print(UL6) LL7=UL6 if(P8>25): UL7=D7 print(UL7) elif(UL7==D8): print(UL7) LL8=UL7 if(P9>25): UL8=D8 print(UL8) elif(UL8==D9): print(UL8) LL9=UL8 if(P10>25): UL9=D9 print(UL9) elif(UL9==D10): print(UL9) LL10=UL9 UL10=("& Above") print(UL10) ** n1=int(UL1) count=0 while (n1>0): count=count+1 n1=n1//10 print(count) B11=LL1 If((count)/2)==0: B12=int((UL1)/(10**(count-2))) B12 elif(B12=int((UL1)/(10**(count-1: B12 B1=(B11,"-",B12,"M") B1 -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Advice on law firm
This is a Python related forum, but your question has nothing to do with Python. While you might get an answer here, I'm sure you could find a better place to post your question. On 10/17/2018 07:36 PM, rj.amdphr...@gmail.com wrote: Correction: specializing in warranty of merchantability, software licenses, and possibly class action suits. Sent from Mail for Windows 10 From: Ryan Johnson Sent: Wednesday, October 17, 2018 9:26 PM To: python-list@python.org Subject: Advice on law firm Anyone know a good US based law firm that specializes in software licenses and class action suits? Sent from Mail for Windows 10 -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: namedtuples anamoly
On 10/17/2018 11:13 PM, me.vi...@gmail.com wrote: Hi, I tried using namedtuples and just found a behaviour which I am not able to conclude as correct behaviour. from collections import namedtuple (n, categories) = (int(input()), input().split()) Grade = namedtuple('Grade', categories) Grade.ID = 1 #print(Grade.ID) ob = Grade(10, 50) print(ob.ID) print(ob.MARKS) ob1 = Grade(20, 100) print(ob1.ID) 2 ID MARKS 1 50 1 100 If we set GRADE.ID =1 , Whoa! Don't do that. The Grade object created with the namedtuple call is a class, and part of it's internal implementation is stored in Grade.ID. Try these lines: >>> print(Grade) >>> print(Grade.ID) >>> By reassigning Grade.ID, you are sabotaging the internals of the class. Without looking at those internals, it's not really a surprise that things stop working after you destroy the it so carefully stored in Grade.ID. So now the real question is: What were you trying to accomplish with the assignment? Tell us, and let's see if we can find a way to accomplish yor goal without wrecking the internals of the Grade class. Gary Herron it has impact on all variables. Is this behaviour just like class variable and it has global scope. I expected ob.ID and ob1.ID to be 10. Correct me if Iam wrong. Appreciate any quick response. Kind Rgds, Vinu -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: what is the difference between one-line-operation and 2-line-operation
On 04/25/2016 07:13 AM, oyster wrote: for a simple code [code] vexList = [1, 2, 3] print('vexList', list(vexList)) vexList=map(lambda e: e+1, vexList) print('vexList', list(vexList)) vexList = list(vexList) print('vexList', list(vexList)) vexList=map(lambda e: e*2,vexList) print('vexList', list(vexList)) [/code] py27 says [quote] ('vexList', [1, 2, 3]) ('vexList', [2, 3, 4]) ('vexList', [2, 3, 4]) ('vexList', [4, 6, 8]) [/quote] but py34 says [quote] vexList [1, 2, 3] vexList [2, 3, 4] vexList [] vexList [] [/quote] The difference in behaviour between Python2 and Python3 is the map function. In P2 it returned a list, while in P3 it returns an iterator. Your code runs through that iterator twice with the list() function. The first time it gets the elements of the list as expected, but the second time, the iterator is exhausted and returns no objects. A simpler example: "b" is a map object (iterator), then list(b) is run twice. >>> a = [1,2,3] >>> b = map(lambda e: e+1, a) >>> b >>> list(b) [2, 3, 4] >>> list(b) [] I hope that helps. Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: def __init__(self):
On 04/25/2016 11:21 PM, San wrote: Hi All, Pls let me why " def __init__(self): " declaration required, what's the use of this one.Pls explain me in details. Thanks in advance. If you understand object-oriented-programming, then this will make sense: The __init__ method is the constructor for instances of a class. It is not required, but the situations in which a constructor is not needed are few and unusual. If you don't know object-oriented-programming, then I'd suggest you put that high on your list of things to learn. It's a valuable tool. Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: def __init__(self):
On 04/26/2016 06:49 AM, Random832 wrote: On Tue, Apr 26, 2016, at 03:34, Ben Finney wrote: That's needlessly confusing: ‘__init__’ is not a constructor because it does not construct the instance. The ‘__new__’ method is the constructor for a class (and returns the new instance). the __new__ method is the *allocator*. "constructor" is used in many languages to name a method that initializes an object once it already "exists". Saying you can't call it that in Python is needlessly confusing. Agreed. For a newbie asking about __init__, I'll stick with my original answer (that it's the constructor), and suggest ignoring the overly pedantic (and confusing) response to the contrary. -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Image loading problem
On 05/21/2016 08:22 AM, sweating_...@yahoo.com wrote: Hi All, I am working on an image project, and I can display my image in main(). I mean, I can load my image in my main(). Needless, it is awkward. I am trying to load my image with a function, but got an empty image window popped up, no image content loaded. Please take a look at code: rom Tkinter import * def load_img(win): img = PhotoImage(file="xxx.gif") Label(win, image=img).pack() win = Tk() load_img(win) win.mainloop() Somebody can help me out? Thanks! I believe this the problem (However It's been long since I used Tkinter, so be warned ... ): The function load_img creates a local variable named img which goes out of scope and is deleted immediately when the function returns. However, Tkinter needs you to keep that image around as long as the Label uses it. So, some solutions are: keep_me = [] # Global for keeping references to images def load_img(win): img = PhotoImage(file="xxx.gif") keep_me.append(img) Label(win, image=img).pack() or def load_img(win): img = PhotoImage(file="xxx.gif") Label(win, image=img).pack() return img saved_img = load_img(win) ... Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Spreading a class over multiple files
On 06/04/2016 11:55 PM, Mark Summerfield wrote: Sometimes I want to spread a class over multiple files. There’s and easy way to do this in Python using what's called a Mixin class and (multiple) inheritance: (See https://en.wikipedia.org/wiki/Mixin for more information.) In one file, say extras.py class ExtraMethodsMixin: def extra_1(...): ... def extra_2(...): ... In the main class file: from extras import ExtraMethodsMixin class MainClass(ExtraMethodsMixin): def __init__(...): ... # and so on The result will be essentially the same as if all three methods were defined in MainCLass. Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 My primary use case is when I create a "Model" class to reflect an entire SQL database. I want a model instance to provide a single point of access to the database, but the database has many tables each requiring its own methods since they differ in their structure, purpose, validation needs, etc. A secondary use case is when I create "MainWindow" classes in GUI programming and have lots of methods to reflect all the actions (e.g., menu options and toolbar actions, plus interaction with the main widget(s)). To meet these needs I've devised an approach that I think is easy to use and understand and which doesn't use any tricky or hard to maintain code. My question is -- are there nicer/better ways to achieve this? Here's a summary of my approach. A fuller discussion is on my website: https://www.qtrac.eu/pyclassmulti.html # Lib.py # This provides the two functions (both decorators) used to support my approach def add_methods_from(*modules): def decorator(Class): for module in modules: for method in getattr(module, "__methods__"): setattr(Class, method.__name__, method) return Class return decorator def register_method(methods): # A decorator used purely for its side-effect def register_method(method): methods.append(method) return method # Unchanged and not strictly necessary return register_method # Model.py # This provides my model but some methods are in separate files import Lib import _ModelConfig import _ModelOutput @Lib.add_methods_from(_ModelConfig, _ModelOutput) class Model: ... def small_method(self): ... # _ModelConfig.py # _ModelOutput has the same structure so not shown import Lib __methods__ = [] # self is a Model register_method = Lib.register_method(__methods__) @register_method def config(self): ... So, that's the overall pattern of my solution. Is there a nicer/better way? Could I cleanly avoid the explicit imports (e.g., import _ModelConfig), without resorting to stack frame hacks or similar? -- https://mail.python.org/mailman/listinfo/python-list
Re: Operator precedence problem
On 06/04/2016 11:53 PM, ICT Ezy wrote: 2 ** 3 ** 2 Answer is 512 Why not 64? Order is right-left or left-right? Evidently right to left, but you already figured that out. Python 3.5.1+ (default, Mar 30 2016, 22:46:26) [GCC 5.3.1 20160330] on linux Type "help", "copyright", "credits" or "license" for more information. >>> 2 ** 3 ** 2 512 >>> 2 ** (3 ** 2) 512 >>> (2 ** 3) ** 2 64 >>> Here's the relevant documentation page: https://docs.python.org/3/reference/expressions.html Look for "... except for exponentiation, which groups from right to left" Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: CAD Application
On 5/5/19 10:23 PM, britt...@gmail.com wrote: Hello All, What are the frameworks available for developing a CAD application with Python? Regards Britto Well, there's PythonCadhttps://sourceforge.net/projects/pythoncad/ It seems to have stopped development about 5 years ago, but it's still available for download. -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Multiprocessing and memory management
On 7/3/19 9:37 AM, ijbrews...@alaska.edu wrote: I have a script that benefits greatly from multiprocessing (it’s generating a bunch of images from data). Of course, as expected each process uses a chunk of memory, and the more processes there are, the more memory used. The amount used per process can vary from around 3 GB (yes, gigabytes) to over 40 or 50 GB, depending on the amount of data being processed (usually closer to 10GB, the 40/50 is fairly rare). This puts me in a position of needing to balance the number of processes with memory usage, such that I maximize resource utilization (running one process at a time would simply take WAY to long) while not overloading RAM (which at best would slow things down due to swap). Obviously this process will be run on a machine with lots of RAM, but as I don’t know how large the datasets that will be fed to it are, I wanted to see if I could build some intelligence into the program such that it doesn’t overload the memory. A couple of approaches I thought of: 1) Determine the total amount of RAM in the machine (how?), assume an average of 10GB per process, and only launch as many processes as calculated to fit. Easy, but would run the risk of under-utilizing the processing capabilities and taking longer to run if most of the processes were using significantly less than 10GB Try psutil to get information about memory (and cpu usage and lots more). For example: >>> import psutil >>> psutil.virtual_memory() svmem(total=16769519616, available=9151971328, percent=45.4, used=7031549952, free=4486520832, active=9026158592, inactive=2238566400, buffers=312815616, cached=4938633216, shared=234295296, slab=593375232) Home page: https://github.com/giampaolo/psutil 2) Somehow monitor the memory usage of the various processes, and if one process needs a lot, pause the others until that one is complete. Of course, I’m not sure if this is even possible. 3) Other approaches? --- Israel Brewster Software Engineer Alaska Volcano Observatory Geophysical Institute - UAF 2156 Koyukuk Drive Fairbanks AK 99775-7320 Work: 907-474-5172 cell: 907-328-9145 -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Calculations and Variables
On 10/31/19 11:46 AM, ferzan...@gmail.com wrote: The code below which I have written should print the result of 43.6 with the given values I have included at the end of this question, but for some odd reason I get the result of 44.44. bill = (input("Enter the total cost of the meal: \n")) tip = (input("Enter how much the tip is: \n")) split = (input("Enter how many people there are: \n")) total = bill + (bill / tip) Don't you mean total = bill + (bill * tip) ? eachPay = total / split print("Each person will have to pay %.2f" % eachPay) I am aiming for the result of 43.6, but somehow get the result of 44.44. (meal cost: 200) (Tip: 9) (people: 5) I seem to do the calculation below, but get different results each time. Total * Percentage Amount / 100 -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Source Code for a HTTP Proxy
llothar wrote: >Hello, > >i'm looking for a simple http proxy in python. >Does anybody know about something like this ? > > > Here's a list, maintained by Alan Kennedy, of about 20 proxys written in Python: http://xhaus.com/alan/python/proxies.html Enjoy, Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you use as symbols for Python ?
Erik Max Francis wrote: >Pierre Barbier de Reuille wrote: > > > >>When you need some symbols in your program, what do you use in Python ? >> >>For example, an object get a state. This state is more readable if >>expressed as a symbols, for example "opened", "closed", "error". >>Typically, in C or C++, I would use an enum for that: >>enum OBJECT_STATE >>{ >> opened, closed, error >>} >> >> > > OPENED, CLOSED, ERROR = range(3) > > object.state = OPENED > > Another similar approach that keeps those values together in a single namespace is this (my favorite): class State: OPENED, CLOSED, ERROR = range(3) Then you can refer to the values as State.OPENED State.CLOSED State.ERROR The extra clarity (and slight wordiness) of the dotted notation seems, somehow, quite Pythonic to me. Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Re: weird problem with os.chmod
James Colannino wrote: >James Colannino wrote: > > > >>So then I entered the command print 0600, and saw that the >>actual number being output was 384 (why would it output 384?!) >> >> >> >> > >Ok, so further research revealed that 0600 is actually the octal >representation for 384 (which makes sense.) So then, I guess my >question would have to be, is there a way for me to make Python aware >that the 0600 I'm passing to int() is octal and not decimal so that I >will get 384 instead of 600? > > int('0600',8) will do, but why would you want to do that? Any of x = 0600 x = 384 x = 0x180 x = int('0600',8) will bind x to the same value (11000 in binary if you care). But once you've got the valued defined, through whatever human readable representation you want, the command chmod(filename, x) can be issued without further thought. -- http://mail.python.org/mailman/listinfo/python-list
How to write an API for a Python application?
Hello I would like to create an API for a piece of Python code. The API is for use by non Python code. It should support interaction in both directions, both accessing functions on the API and the ability for the API to raise events on its clients. What is the best way to do that? I though of doing it as a python COM server but I am not familiar with COM and I saw that implementing a COM server with events in python is not trivial. Is there a better (or simpler) solution?What are the common ways for doing that? Any answer would be greatly appreciated. Regards Gary -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert between type string and token
This is not really a Python question, but a question on how to use the nltk package. I've never used, installed nor even seen that package, so of course I can't answer your question, but I do have a suggestion. A quick goggle finds a web page for nltk: http://nltk.sourceforge.net/. Is that where your nltk package comes from? If so, look there for an email list where you can ask this question. If not, they appear to have tutorials and documentation that might help. If not, you may be able to get an answer here, but the other pro-active suggestions are likely to produce better results faster. Good luck, Gary Herron enas khalil wrote: > > hello all > when i run the code : > # -*- coding: cp1256 -*- > from nltk.tagger import * > from nltk.corpus import brown > from nltk.tokenizer import WhitespaceTokenizer > # Tokenize ten texts from the Brown Corpus > train_tokens = [] > xx=Token(TEXT=open('fataha2.txt').read()) > WhitespaceTokenizer().tokenize(xx) > for l in xx: > train_tokens.append(l) > #Initialise and train a unigram tagger > mytagger = UnigramTagger(SUBTOKENS='WORDS') > for tok in train_tokens: mytagger.train(tok) > #Once a UnigramTagger has been trained, the tag() method can be > used to tag new text: > text_token = Token(TEXT="ÇáÍãÏ ááå ÑÈ ÇáÚÇáãíä") > WhitespaceTokenizer(SUBTOKENS='WORDS').tokenize(text_token) > mytagger.tag(text_token) > print 'The first example : Using Unigram Tagger the reseults are : > '*print > acc = tagger_accuracy(mytagger, train_tokens) > print ' With Accuracy :Accuracy = %4.1f%%,' % (100 * acc) * > * * > * * > * * > *i got the following error :* > * * > *Traceback (most recent call last): > File "F:\MSC first Chapters\unigramgtag1.py", line 14, in -toplevel- > for tok in train_tokens: mytagger.train(tok) > File "C:\Python24\Lib\site-packages\nltk\tagger\__init__.py", > line 324, in train > assert chktype(1, tagged_token, Token) > File "C:\Python24\Lib\site-packages\nltk\chktype.py", line 316, > in chktype > raise TypeError(errstr) > TypeError: * > * * > * Argument 1 to train() must have type: Token > (got a str)* > * * > * * > * * > *please i want a help on how to recover this error , in other > words how can i convert between type string and token , as im > still new in python* > * * > *thanks in advance* > * * > * * > > * * > > ---- > * Yahoo! FareChase - Search multiple travel sites in one click. > <http://us.lrd.yahoo.com/_ylc=X3oDMTFqODRtdXQ4BF9TAzMyOTc1MDIEX3MDOTY2ODgxNjkEcG9zAzEEc2VjA21haWwtZm9vdGVyBHNsawNmYw--/SIG=110oav78o/**http%3a//farechase.yahoo.com/> > > * -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
Sending an event from a python COM server to a VB COM client
Hello I am trying to send an event from a Python COM server to a VB (or VB.NET) COM client. I am a newbie both in VB and in python. Can anyone give me a simple (but complete) code example both of the Python server side and the VB client side for raising a single event. Any answer would be highly appreciated. Regards Gary -- http://mail.python.org/mailman/listinfo/python-list
Re: Sending an event from a python COM server to a VB COM client
Thank you Steve. I have already went over that book, I didn't find there an example of sending events from a python server to a VB client (just direct function calls from the VB client to the Python server, which is trivial). And in any case, since I am a newbie both in VB and in Python, I am really looking for an example that will spell things out for me. There's a lot of 'wrapping' happening under the hood in this technology and I am kind of lost between what is done for me on each side and what I should explicitly do my self. Thanks again for taking the time to answer. Gary "Stephen Prinster" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Gary Kshepitzki wrote: >> Hello >> I am trying to send an event from a Python COM server to a VB (or VB.NET) >> COM client. >> I am a newbie both in VB and in python. >> Can anyone give me a simple (but complete) code example both of the >> Python >> server side and the VB client side for raising a single event. >> >> Any answer would be highly appreciated. >> Regards >> Gary >> >> > > I suggest the book _Python Programming on Win32_ by Mark Hammond and > Andy Robinson. There is a chapter online and I believe it even includes > the example you need. > > http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html > > Steve P. -- http://mail.python.org/mailman/listinfo/python-list
How to write an API for a Python application?
Hello I would like to create an API for a piece of Python code. The API is for use by non Python code. It should support interaction in both directions, both accessing functions on the API and the ability for the API to raise events on its client. What is the best way to do that? I though of doing it as a python COM server but I am not familiar with COM and I saw that implementing a COM server with events in python is not trivial for me. Is there a better (or simpler) solution? What are the common ways for doing that? Any answer would be highly appreciated. Regards Gary -- http://mail.python.org/mailman/listinfo/python-list
Re: How to write an API for a Python application?
Thanks Its an interesting solution but I need a more closely coupled solution, with real time events, so the communication really has to be 2 ways, and not by polling. Thanks for putting the time and though. Gary <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > While not sure of the behavior you are trying to achieve, XML-RPC comes > to mind. But it's based on HTTP protocol in which the client puts > request to the server which has to respond. The server cannot initiate > interactions. > XML-RPC is both widely avalaible, and very easy to implement. > > NOTE: in order for the server to raise events in the client, the client > needs only raise periodically a *need-anything-from-me* type of request > which permits the server to return its request in response to the > client. Naturally this solution makes superfluous calls takes some > bandwidth, so it might not be appropriate in every circumstance. > -- http://mail.python.org/mailman/listinfo/python-list
Re: what's wrong with "lambda x : print x/60,x%60"
Mohammad Jeffry wrote: > Dear All, > > Can't a lambda uses the input parameter more then once in the lambda > body? > eg: > lambda x : print x/60,x%60 > > I tried with def and it works but got syntax error with lambda. Below > is an interactive sample: Lambda evaluates a single *expression* and returns the result. As print is a statement it does not qualify (and would provide nothing to return even if it did). So just use a def. It is constantly pointed out on this list that the lambda provides no extra expressive power, it is merely a shortcut and, as you just found out, a rather restrictive one at that. See the reference manual entry: http://www.python.org/doc/2.4.2/ref/lambdas.html As for your next question, lambda x : x/60,x%60 is parsed as (lambda x: x/60), x%60 That is, the scope of the lambda (and its x) are finished by the comma. Perhaps being more explicit about the returned tuple would produce what you want. lambda x : (x/60,x%60) Gary Herron > > [EMAIL PROTECTED] ~ $ python > Python 2.4.2 (#1, Nov 18 2005, 19:32:15) > [GCC 3.3.6 (Gentoo 3.3.6, ssp-3.3.6-1.0, pie-8.7.8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> def func_hrs(x): print x/60,x%60 > ... > >>> func_hrs(400) > 6 40 > >>> lambda_hrs = lambda x : print x/60,x%60 > File "", line 1 > lambda_hrs = lambda x : print x/60,x%60 > ^ > SyntaxError: invalid syntax > >>> > > My main concern is how can I do this in lambda? > > > > -- > And whoever does an atom's weight of evil will see it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reaching the real world
"Fuzzyman" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I have a friend who would like to move and program lights and other > electric/electro-mechanical devices by computer. I would like to help - > and needless to say Python would be an ideal language for the > 'programmers interface'. > > What I'd like is an electronic interface that connects to several > relays and a python extension module to switch on and off the relays. > I've had a quick google and can't see anything too similar to what I > want. pyro (python robotics) seems to require expensive (relatively) > robotic equipment. > > Does anyone know anything *similar* to what I have in mind, or have > alternative suggestions ? > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > Take a look at: http://www.geocities.com/hagtronics/pic_das/index.html Very easy to interface to Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: IPython colors in windows
Claudio Grondi <[EMAIL PROTECTED]> wrote: > "Ashot" <[EMAIL PROTECTED]> schrieb im Newsbeitrag > news:[EMAIL PROTECTED] > > whoa, that was quick, looks like it works for me. Thanks a lot! > > It would be nice to be able to set the colors in the prefs file, although > > its possible to edit the pyColorize file as Claudio mentioned. > To get the coloured texts on a grey (instead of white) background > I have extended the Console.py to accept sequences as e.g. > "0;33;47" (see attachment) > have extended also the > def make_color_table(in_class): > in the ColorANSI.py of IPython > and adjusted the pyColorize.py file, but it had not the desired effect. > IPython seems not to be sending to Console.py the sequences > defined in the The problem *may* be the way I insert the background color in Console.py. I simply hacked it to OR the initial value into the colors I get out of my table. If you want to have some colors with the background set, then we'd need to work out a way to signal that. Perhaps instead of or'ing in the value all the time, we should insert the background value into the table entries that don't specify the background. I'm happy to see someone hacking on it. The source is all there and it is all Python. The Win32 API stuff is ugly but well documented online. If you change the "if 0:" up at the top of Console.py to "if 1:" you'll get a file debug.txt with the contents of the various calls to "log". That way you can "print" stuff from within console without messing up the window. gb -- http://mail.python.org/mailman/listinfo/python-list
Re: IPython colors in windows
On SourceForge you will find release 1.12 of my Python readline module. If you don't want to hack the colors, there is no reason to upgrade from 1.11 to 1.12. They *should* work the same. But if you'd like to hack the iPython colors this new version makes it possible. In your ipythonrc file add a line like: execfile hackcolors.py Now in hackcolors.py you can change colors and backgrounds like this: hackcolors.py import readline # reach deep into the bowels of readline to get the color table escape_to_color = readline.rl.console.escape_to_color # change a color escape_to_color['0;32'] = 0x72 del escape_to_color del readline # The two hex digits are the background and foreground color respectively. In the example above I'm setting the color to green on a grey background. Here is the table that is normally used to translate colors. escape_to_color = { '0;30': 0x0, #black '0;31': 0x4, #red '0;32': 0x2, #green '0;33': 0x4+0x2, #brown? '0;34': 0x1, #blue '0;35': 0x1+0x4, #purple '0;36': 0x2+0x4, #cyan '0;37': 0x1+0x2+0x4, #grey '1;30': 0x1+0x2+0x4, #dark gray '1;31': 0x4+0x8, #red '1;32': 0x2+0x8, #light green '1;33': 0x4+0x2+0x8, #yellow '1;34': 0x1+0x8, #light blue '1;35': 0x1+0x4+0x8, #light purple '1;36': 0x1+0x2+0x8, #light cyan '1;37': 0x1+0x2+0x4+0x8, #white '0': None, } An interested party should be able to arbitrarily map colors and their backgrounds. Enjoy, gb -- http://mail.python.org/mailman/listinfo/python-list
Re: Slicing every element of a list
Alex Dempsey wrote: >Recently I tried to slice every element of a list of strings. First I tried: > >f = open("export.xls", "r") >lines = f.readlines() > >for line in lines: >line = line[1:-5] >line = line.split('\"\t\"') > > This, in fact, did do the operation you expected, but after creating the new value and assigning it to line, you promptly threw it away. (Because the loop then went back to the top and (re)assigned the next thing in lines to line wiping out your nicely sliced computation in lines.) You need to *do* something with the value in line before you end the loop -- but what? >This went without returning any errors, but nothing was sliced or >split. Next I tried: > >for i in range(len(lines)): >lines[i] = lines[i][1:-5] >lines[i] = lines[i].split('\"\t\"') > >This of course worked, but why didn't the first one work. Further why >didn't the first one return an error? > > Dr. Gary Herron Digipen Institute of Technology -- http://mail.python.org/mailman/listinfo/python-list