title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Error in nested for loops (Python)
1,487,561
<p>I am getting an error in the following code. The Error message is <code>"Error: Inconsistent indentation detected!"</code></p> <pre><code>s=[30,40,50] a=[5e6,6e6,7e6,8e6,8.5e6,9e6,10e6,12e6] p=[0.0,0.002,0.004,0.006,0.008,0.01,0.015,0.05,0.1,0.15,0.2] j=0 b=0 x=0 for j in s: h=s[j] print "here is the first loop" +h for b in a: c=a[b] #too much indentation print"here is the second loop" +c #too much indentation for x in p: #too much indentation k=p[x] print"here is the third loop" +k </code></pre> <p>If there is any other error I will be highly obliged if anyone here could correct me.</p> <p>Thanks.</p> <p>/Gillani</p>
1
2009-09-28T15:05:01Z
1,487,573
<p>Your three lines initing your variable to zero are at a different indentation than the rest of your code. Even the code display here on stackoverflow shows that. </p> <p>Also, check that you haven't mixed tabs and spaces.</p>
2
2009-09-28T15:06:09Z
[ "python", "syntax" ]
Error in nested for loops (Python)
1,487,561
<p>I am getting an error in the following code. The Error message is <code>"Error: Inconsistent indentation detected!"</code></p> <pre><code>s=[30,40,50] a=[5e6,6e6,7e6,8e6,8.5e6,9e6,10e6,12e6] p=[0.0,0.002,0.004,0.006,0.008,0.01,0.015,0.05,0.1,0.15,0.2] j=0 b=0 x=0 for j in s: h=s[j] print "here is the first loop" +h for b in a: c=a[b] #too much indentation print"here is the second loop" +c #too much indentation for x in p: #too much indentation k=p[x] print"here is the third loop" +k </code></pre> <p>If there is any other error I will be highly obliged if anyone here could correct me.</p> <p>Thanks.</p> <p>/Gillani</p>
1
2009-09-28T15:05:01Z
1,487,586
<p>Once you cleaned your tabs and spaces (you should have only tabs or only spaces), you'd need to fix your loops:</p> <pre><code>s = [30,40,50] a = [5e6,6e6,7e6,8e6,8.5e6,9e6,10e6,12e6] p = [0.0,0.002,0.004,0.006,0.008,0.01,0.015,0.05,0.1,0.15,0.2] for j in s: # within loop j is being 30 then 40 then 50, same true for other loops print "here is the first loop" + j for b in a: print"here is the second loop" + b for x in p: print"here is the third loop" + x </code></pre> <p>Otherwise you'd have <code>IndexError</code>.</p>
6
2009-09-28T15:09:28Z
[ "python", "syntax" ]
Error in nested for loops (Python)
1,487,561
<p>I am getting an error in the following code. The Error message is <code>"Error: Inconsistent indentation detected!"</code></p> <pre><code>s=[30,40,50] a=[5e6,6e6,7e6,8e6,8.5e6,9e6,10e6,12e6] p=[0.0,0.002,0.004,0.006,0.008,0.01,0.015,0.05,0.1,0.15,0.2] j=0 b=0 x=0 for j in s: h=s[j] print "here is the first loop" +h for b in a: c=a[b] #too much indentation print"here is the second loop" +c #too much indentation for x in p: #too much indentation k=p[x] print"here is the third loop" +k </code></pre> <p>If there is any other error I will be highly obliged if anyone here could correct me.</p> <p>Thanks.</p> <p>/Gillani</p>
1
2009-09-28T15:05:01Z
1,487,630
<p>I also think it's a tab/space mixing problem. Some editors, like Textmate, has the option for displaying 'invisible' characters, like tab and newline. Comes very handy when you code, especially in Python.</p>
1
2009-09-28T15:17:04Z
[ "python", "syntax" ]
Error in nested for loops (Python)
1,487,561
<p>I am getting an error in the following code. The Error message is <code>"Error: Inconsistent indentation detected!"</code></p> <pre><code>s=[30,40,50] a=[5e6,6e6,7e6,8e6,8.5e6,9e6,10e6,12e6] p=[0.0,0.002,0.004,0.006,0.008,0.01,0.015,0.05,0.1,0.15,0.2] j=0 b=0 x=0 for j in s: h=s[j] print "here is the first loop" +h for b in a: c=a[b] #too much indentation print"here is the second loop" +c #too much indentation for x in p: #too much indentation k=p[x] print"here is the third loop" +k </code></pre> <p>If there is any other error I will be highly obliged if anyone here could correct me.</p> <p>Thanks.</p> <p>/Gillani</p>
1
2009-09-28T15:05:01Z
1,487,639
<p>SilentGhost is correct -- unlike languages like Javascript, when you write</p> <pre><code>s = [30, 40, 50] for j in s: </code></pre> <p>Then j is not assigned 0, 1, and 2 -- it is assigned the actual values 30, 40, and 50. So there is no need to say, on another line,</p> <pre><code>h = s[j] </code></pre> <p>In fact, if you do that, the first time through the loop, it will evaluate as</p> <pre><code>h = s[30] </code></pre> <p>Which is way out of bounds for a three-element list, and you'll get an IndexError.</p> <p>If you really wanted to do it the other way -- if you <em>really</em> needed the indexes as well as the values, you could do something like this:</p> <pre><code>s = [30, 40, 50] for j in range(len(s)): h = s[j] </code></pre> <p>len(s) gives you the length of s (3, in this case), and the range function makes a new list for you, range(n) contains the integers from 0 to n-1. In this case, range(3) returns [0, 1, 2]</p> <p>As SilentGhost points out in the comments, this is much more pythonic:</p> <pre><code>s = [30, 40, 50] for (j, h) in enumerate(s): # do stuff here </code></pre> <p>enumerate(s) returns the three pairs (0, 30), (1, 40), and (2, 50), in that order. With that, you have the indexes into s, as well as the actual element, at the same time.</p>
5
2009-09-28T15:18:42Z
[ "python", "syntax" ]
Error in nested for loops (Python)
1,487,561
<p>I am getting an error in the following code. The Error message is <code>"Error: Inconsistent indentation detected!"</code></p> <pre><code>s=[30,40,50] a=[5e6,6e6,7e6,8e6,8.5e6,9e6,10e6,12e6] p=[0.0,0.002,0.004,0.006,0.008,0.01,0.015,0.05,0.1,0.15,0.2] j=0 b=0 x=0 for j in s: h=s[j] print "here is the first loop" +h for b in a: c=a[b] #too much indentation print"here is the second loop" +c #too much indentation for x in p: #too much indentation k=p[x] print"here is the third loop" +k </code></pre> <p>If there is any other error I will be highly obliged if anyone here could correct me.</p> <p>Thanks.</p> <p>/Gillani</p>
1
2009-09-28T15:05:01Z
1,487,767
<p>This part:</p> <pre> for b in a: c=a[b] #too much indentation </pre> <p>the "c=a[b]" is indented 8 spaces instead of 4. It needs to be only 4 spaces (ie. one python indentation).</p> <p>And Ian is right, the "for x in y" syntax is different than other languages.</p> <pre> list1 = [10, 20, 30] for item in list1: print item </pre> <p>The output will be: "10, 20, 30", not "1, 2, 3".</p>
0
2009-09-28T15:40:54Z
[ "python", "syntax" ]
Type of object from udp buffer in python using metaclasses/reflection
1,487,582
<p>Is it possible to extract type of object or class name from message received on a udp socket in python using metaclasses/reflection ?</p> <p>The scenario is like this:</p> <ol> <li><p>Receive udp buffer on a socket.</p></li> <li><p>The UDP buffer is a serialized binary string(a message). But the type of message is not known at this time. So can't de-serialize into appropriate message.</p> <p>Now, my ques is Can I know the classname of the seraialized binary string(recvd as UDP buffer) so that I can de-serialize into appropriate message and process further.</p></li> </ol> <p>Thanks in Advance.</p>
1
2009-09-28T15:08:34Z
1,487,602
<p>Updated answer after updated question:</p> <p>"But the type of message is not known at this time. So can't de-serialize into appropriate message."</p> <p>What you get is a sequence of bytes. How that sequence of types should be interpreted is a question of how the protocol looks. Only you know what protocol you use. So if you don't know the type of message, then there is nothing you can do about it. If you are to receive a stream of data an interpret it, you must know what that data means, otherwise you can't interpret it.</p> <p>It's as simple as that.</p> <p>"Now, my ques is Can I know the classname of the seraialized binary string"</p> <p>Yes. The classname is "str", as all strings. (Unless you use Python 3, in which case you would not get a str but a binary). The data inside that str has no classname. It's just binary data. It means whatever the sender wants it to mean.</p> <p>Again, I need to stress that you should not try to make this into a generic question. Explain exactly what you are trying to do, not generically, but specifically.</p>
0
2009-09-28T15:12:17Z
[ "python", "sockets", "udp" ]
Type of object from udp buffer in python using metaclasses/reflection
1,487,582
<p>Is it possible to extract type of object or class name from message received on a udp socket in python using metaclasses/reflection ?</p> <p>The scenario is like this:</p> <ol> <li><p>Receive udp buffer on a socket.</p></li> <li><p>The UDP buffer is a serialized binary string(a message). But the type of message is not known at this time. So can't de-serialize into appropriate message.</p> <p>Now, my ques is Can I know the classname of the seraialized binary string(recvd as UDP buffer) so that I can de-serialize into appropriate message and process further.</p></li> </ol> <p>Thanks in Advance.</p>
1
2009-09-28T15:08:34Z
1,487,612
<p>You need to use a serialization module. <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle</a> and <a href="http://docs.python.org/library/marshal.html" rel="nofollow">marshal</a> are both options. They provide functions to turn objects into bytestreams, and back again.</p>
0
2009-09-28T15:13:37Z
[ "python", "sockets", "udp" ]
Type of object from udp buffer in python using metaclasses/reflection
1,487,582
<p>Is it possible to extract type of object or class name from message received on a udp socket in python using metaclasses/reflection ?</p> <p>The scenario is like this:</p> <ol> <li><p>Receive udp buffer on a socket.</p></li> <li><p>The UDP buffer is a serialized binary string(a message). But the type of message is not known at this time. So can't de-serialize into appropriate message.</p> <p>Now, my ques is Can I know the classname of the seraialized binary string(recvd as UDP buffer) so that I can de-serialize into appropriate message and process further.</p></li> </ol> <p>Thanks in Advance.</p>
1
2009-09-28T15:08:34Z
1,487,619
<p>What you receive from the udp socket is a byte string -- that's all the "type of object or class name" that's actually <em>there</em>. If the byte string was built as a serialized object (e.g. via <code>pickle</code>, or maybe <code>marshal</code> etc) then you can deserialize it back to an object (using e.g. <code>pickle.loads</code>) and <strong>then</strong> introspect to your heart's content. But most byte strings were built otherwise and will raise exceptions when you try to <code>loads</code> from them;-).</p> <p><strong>Edit</strong>: the OP's edit mentions the string is "a serialized object" but still doesn't say what serialization approach produced it, and that makes all the difference. <code>pickle</code> (and for a much narrower range of type <code>marshal</code>) place enough information on the strings they produce (via the <code>.dumps</code> functions of the modules) that their respective <code>loads</code> functions can deserialize back to the appropriate type; but other approaches (e.g., <code>struct.pack</code>) do not place such metadata in the strings they produce, so it's not feasible to deserialize without other, "out of bands" so to speak, indications about the format in use. So, o O.P., <em>how</em> was that serialized string of bytes produced in the first place...?</p>
2
2009-09-28T15:14:52Z
[ "python", "sockets", "udp" ]
Server side clusters of coordinates based on zoom level
1,487,704
<p>Thanks to this <a href="http://stackoverflow.com/questions/986852/clustering-coordinates-on-server-side/995876#995876">answer </a> I managed to come up with a temporary solution to my problem.</p> <p>However, with a list of 6000 points that grows everyday it's becoming slower and slower.</p> <p>I can't use a third party service* therefore I need to come up with my own solution. </p> <p>Here are my requirements:</p> <ol> <li><p>Clustering of the coordinates need to work with any zoom level of the map.</p></li> <li><p>All clusters need to be cached</p></li> <li><p>Ideally there won't be a need to cluster (calculate distances) on all points if a new point is added.</p></li> </ol> <p>So far I have implemented quadtree that returns the four boundaries of my map and returns whatever coordinates are within the viewable section of the map. </p> <p>What I need and I know this isn't easy is to have clusters of the points returned from the DB (postgres).</p>
1
2009-09-28T15:28:20Z
1,487,750
<p>I don't see why you have to "cluster" on the fly. Summarize at each zoom level at a resolution you're happy with.</p> <p>Have a simply structure of X, Y, # of links. When someone adds a link, you insert the real locations (Zoom level max, or whatever), then start bubbling up from there.</p> <p>Eventually you'll have 10 (if you have 10 zoom levels) sets of distinct coordinates, one for each different zoom level.</p> <p>The calculation is trivial, and you only have to do it once.</p>
2
2009-09-28T15:37:08Z
[ "python", "google-maps", "postgresql", "google-maps-markers", "cluster-analysis" ]
Server side clusters of coordinates based on zoom level
1,487,704
<p>Thanks to this <a href="http://stackoverflow.com/questions/986852/clustering-coordinates-on-server-side/995876#995876">answer </a> I managed to come up with a temporary solution to my problem.</p> <p>However, with a list of 6000 points that grows everyday it's becoming slower and slower.</p> <p>I can't use a third party service* therefore I need to come up with my own solution. </p> <p>Here are my requirements:</p> <ol> <li><p>Clustering of the coordinates need to work with any zoom level of the map.</p></li> <li><p>All clusters need to be cached</p></li> <li><p>Ideally there won't be a need to cluster (calculate distances) on all points if a new point is added.</p></li> </ol> <p>So far I have implemented quadtree that returns the four boundaries of my map and returns whatever coordinates are within the viewable section of the map. </p> <p>What I need and I know this isn't easy is to have clusters of the points returned from the DB (postgres).</p>
1
2009-09-28T15:28:20Z
1,488,040
<p>I am currently doing dynamic server-side clustering of about 2,000 markers, but it runs pretty quick up to 20,000. You can see discussion of my algorithm here:</p> <p><a href="http://stackoverflow.com/questions/1434222/">Map Clustering Algorithm</a></p> <p>Whenever the user moves the map I send a request with the zoom level and the boundaries of the view to the server, which clusters the viewable markers and sends it back to the client. </p> <p>I don't cache the clusters because the markers can be dynamically filtered and searched - but if they were pre-clustered it would be super fast!</p>
1
2009-09-28T16:34:55Z
[ "python", "google-maps", "postgresql", "google-maps-markers", "cluster-analysis" ]
Python object inspector?
1,487,952
<p>besides from using a completely integrated IDE with debugger for python (like with Eclipse), is there any little tool for achieving this:</p> <ul> <li>when running a program, i want to be able to hook somewhere into it (similar to inserting a print statement) and call a window with an object inspector (a tree view) </li> <li>after closing the window, the program should resume</li> </ul> <p>It doesnt need to be polished, not even absolutely stable, it could be introspection example code for some widget library like wx. Platform independent would be nice though (not a PyObjC program, or something like that on Windows).</p> <p>Any Ideas ? </p> <p><em>Edit</em>: Yes, i know about pdb, but I'm looking for a graphical tree of all the current objects. </p> <p>Nevertheless, here is a nice introduction on how to use pdb (in this case in Django): <a href="http://ericholscher.com/blog/2008/aug/31/using-pdb-python-debugger-django-debugging-series-/" rel="nofollow">pdb + Django</a></p>
2
2009-09-28T16:17:53Z
1,488,064
<p>You can use ipython, with the <code>%debug</code> statement. Once your code crashes, you can add breakpoints, see objects etc. A very crude way to kickoff the debugger is to <code>raise Exception</code> at some line of your code, run it in ipython, the type <code>%debug</code> when it crashes.</p>
0
2009-09-28T16:39:38Z
[ "python", "debugging", "introspection" ]
Python object inspector?
1,487,952
<p>besides from using a completely integrated IDE with debugger for python (like with Eclipse), is there any little tool for achieving this:</p> <ul> <li>when running a program, i want to be able to hook somewhere into it (similar to inserting a print statement) and call a window with an object inspector (a tree view) </li> <li>after closing the window, the program should resume</li> </ul> <p>It doesnt need to be polished, not even absolutely stable, it could be introspection example code for some widget library like wx. Platform independent would be nice though (not a PyObjC program, or something like that on Windows).</p> <p>Any Ideas ? </p> <p><em>Edit</em>: Yes, i know about pdb, but I'm looking for a graphical tree of all the current objects. </p> <p>Nevertheless, here is a nice introduction on how to use pdb (in this case in Django): <a href="http://ericholscher.com/blog/2008/aug/31/using-pdb-python-debugger-django-debugging-series-/" rel="nofollow">pdb + Django</a></p>
2
2009-09-28T16:17:53Z
1,488,102
<p>pdb isn't windowed, it runs in a console, but it's the standard way to debug in Python programs.</p> <p>Insert this where you want to stop:</p> <pre><code>import pdb;pdb.set_trace() </code></pre> <p>you'll get a prompt on stdout.</p>
3
2009-09-28T16:44:42Z
[ "python", "debugging", "introspection" ]
Python object inspector?
1,487,952
<p>besides from using a completely integrated IDE with debugger for python (like with Eclipse), is there any little tool for achieving this:</p> <ul> <li>when running a program, i want to be able to hook somewhere into it (similar to inserting a print statement) and call a window with an object inspector (a tree view) </li> <li>after closing the window, the program should resume</li> </ul> <p>It doesnt need to be polished, not even absolutely stable, it could be introspection example code for some widget library like wx. Platform independent would be nice though (not a PyObjC program, or something like that on Windows).</p> <p>Any Ideas ? </p> <p><em>Edit</em>: Yes, i know about pdb, but I'm looking for a graphical tree of all the current objects. </p> <p>Nevertheless, here is a nice introduction on how to use pdb (in this case in Django): <a href="http://ericholscher.com/blog/2008/aug/31/using-pdb-python-debugger-django-debugging-series-/" rel="nofollow">pdb + Django</a></p>
2
2009-09-28T16:17:53Z
1,488,138
<p>If a commercial solution is acceptable, <a href="http://www.wingware.com/" rel="nofollow">Wingware</a> may be the answer to the OP's desires (Wingware does have free versions, but I don't think they have the full debugging power he requires, which the for-pay versions do provide).</p>
1
2009-09-28T16:53:57Z
[ "python", "debugging", "introspection" ]
Python object inspector?
1,487,952
<p>besides from using a completely integrated IDE with debugger for python (like with Eclipse), is there any little tool for achieving this:</p> <ul> <li>when running a program, i want to be able to hook somewhere into it (similar to inserting a print statement) and call a window with an object inspector (a tree view) </li> <li>after closing the window, the program should resume</li> </ul> <p>It doesnt need to be polished, not even absolutely stable, it could be introspection example code for some widget library like wx. Platform independent would be nice though (not a PyObjC program, or something like that on Windows).</p> <p>Any Ideas ? </p> <p><em>Edit</em>: Yes, i know about pdb, but I'm looking for a graphical tree of all the current objects. </p> <p>Nevertheless, here is a nice introduction on how to use pdb (in this case in Django): <a href="http://ericholscher.com/blog/2008/aug/31/using-pdb-python-debugger-django-debugging-series-/" rel="nofollow">pdb + Django</a></p>
2
2009-09-28T16:17:53Z
1,488,917
<p><a href="http://winpdb.org/">Winpdb</a> is a <strong>platform independent</strong> graphical GPL Python debugger with an object inspector.</p> <p>It supports remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.</p> <p>Some other features:</p> <ul> <li>GPL license. Winpdb is Free Software.</li> <li>Compatible with CPython 2.3 through 2.6 and Python 3000</li> <li>Compatible with wxPython 2.6 through 2.8</li> <li>Platform independent, and tested on Ubuntu Jaunty and Windows XP.</li> <li>User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.</li> </ul> <p>Here's a screenshot that shows the local object tree at the top-left.</p> <p><img src="http://winpdb.org/images/screenshot%5Fwinpdb%5Fsmall.jpg" alt="Screenshot" /></p>
5
2009-09-28T19:29:55Z
[ "python", "debugging", "introspection" ]
Python object inspector?
1,487,952
<p>besides from using a completely integrated IDE with debugger for python (like with Eclipse), is there any little tool for achieving this:</p> <ul> <li>when running a program, i want to be able to hook somewhere into it (similar to inserting a print statement) and call a window with an object inspector (a tree view) </li> <li>after closing the window, the program should resume</li> </ul> <p>It doesnt need to be polished, not even absolutely stable, it could be introspection example code for some widget library like wx. Platform independent would be nice though (not a PyObjC program, or something like that on Windows).</p> <p>Any Ideas ? </p> <p><em>Edit</em>: Yes, i know about pdb, but I'm looking for a graphical tree of all the current objects. </p> <p>Nevertheless, here is a nice introduction on how to use pdb (in this case in Django): <a href="http://ericholscher.com/blog/2008/aug/31/using-pdb-python-debugger-django-debugging-series-/" rel="nofollow">pdb + Django</a></p>
2
2009-09-28T16:17:53Z
1,490,283
<p><a href="http://aymanh.com/python-debugging-techniques" rel="nofollow">Python Debugging Techniques</a> is worth reading. and <a href="http://www.reddit.com/r/programming/comments/9fst4/python%5Fdebugging%5Ftechniques/" rel="nofollow">it's Reddit's comment</a> is worth reading too. I have really find some nice debug tricks from Brian's comment. such as <a href="http://www.reddit.com/r/programming/comments/9fst4/python%5Fdebugging%5Ftechniques/c0cmbqf" rel="nofollow">this comment</a> and <a href="http://www.reddit.com/r/programming/comments/9fst4/python%5Fdebugging%5Ftechniques/c0cmmvy" rel="nofollow">this comment</a>.<br /> Of course, WingIDE is cool (for general Python coding and Python code debugging) and I use it everyday. unlucky for WingIDE still can't embedded a IPython at now.</p>
1
2009-09-29T02:23:25Z
[ "python", "debugging", "introspection" ]
scipy 'Minimize the sum of squares of a set of equations'
1,488,227
<p>I face a problem in scipy 'leastsq' optimisation routine, if i execute the following program it says</p> <pre><code> raise errors[info][1], errors[info][0] TypeError: Improper input parameters. </code></pre> <p>and sometimes <code>index out of range for an array</code>...</p> <pre><code>from scipy import * import numpy from scipy import optimize from numpy import asarray from math import * def func(apar): apar = numpy.asarray(apar) x = apar[0] y = apar[1] eqn = abs(x-y) return eqn Init = numpy.asarray([20.0, 10.0]) x = optimize.leastsq(func, Init, full_output=0, col_deriv=0, factor=100, diag=None, warning=True) print 'optimized parameters: ',x print '******* The End ******' </code></pre> <p>I don't know what is the problem with my func optimize.leastsq() call, please help me</p>
1
2009-09-28T17:12:23Z
1,488,516
<p>Just looking at the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html" rel="nofollow">least squares docs</a>, it might be that your function <code>func</code> is defined incorrectly. You're assuming that you always receive an array of at least length 2, but the optimize function is insanely vague about the length of the array you will receive. You might try writing to screen whatever <code>apar</code> is, to see what you're actually getting.</p> <p>If you're using something like <code>ipython</code> or the python shell, you ought to be getting stack traces that show you exactly which line the error is occurring on, so start there. If you can't figure it out from there, posting the stack trace would probably help us.</p>
1
2009-09-28T18:10:54Z
[ "python", "scipy" ]
scipy 'Minimize the sum of squares of a set of equations'
1,488,227
<p>I face a problem in scipy 'leastsq' optimisation routine, if i execute the following program it says</p> <pre><code> raise errors[info][1], errors[info][0] TypeError: Improper input parameters. </code></pre> <p>and sometimes <code>index out of range for an array</code>...</p> <pre><code>from scipy import * import numpy from scipy import optimize from numpy import asarray from math import * def func(apar): apar = numpy.asarray(apar) x = apar[0] y = apar[1] eqn = abs(x-y) return eqn Init = numpy.asarray([20.0, 10.0]) x = optimize.leastsq(func, Init, full_output=0, col_deriv=0, factor=100, diag=None, warning=True) print 'optimized parameters: ',x print '******* The End ******' </code></pre> <p>I don't know what is the problem with my func optimize.leastsq() call, please help me</p>
1
2009-09-28T17:12:23Z
1,488,889
<p><code>leastsq</code> works with vectors so the residual function, <code>func</code>, needs to return a vector of length at least two. So if you replace <code>return eqn</code> with <code>return [eqn, 0.]</code>, your example will work. Running it gives:</p> <pre><code>optimized parameters: (array([10., 10.]), 2) </code></pre> <p>which is one of the many correct answers for the minimum of the absolute difference.</p> <p>If you want to minimize a scalar function, <code>fmin</code> is the way to go, <code>optimize.fmin(func, Init)</code>.</p> <p>The issue here is that these two functions, although they look the same for a scalars are aimed at different goals. <code>leastsq</code> finds the least squared error, generally from a set of idealized curves, and is just one way of doing a "best fit". On the other hand <code>fmin</code> finds the minimum value of a scalar function.</p> <p>Obviously yours is a toy example, for which neither of these really makes sense, so which way you go will depend on what your final goal is.</p>
2
2009-09-28T19:24:23Z
[ "python", "scipy" ]
scipy 'Minimize the sum of squares of a set of equations'
1,488,227
<p>I face a problem in scipy 'leastsq' optimisation routine, if i execute the following program it says</p> <pre><code> raise errors[info][1], errors[info][0] TypeError: Improper input parameters. </code></pre> <p>and sometimes <code>index out of range for an array</code>...</p> <pre><code>from scipy import * import numpy from scipy import optimize from numpy import asarray from math import * def func(apar): apar = numpy.asarray(apar) x = apar[0] y = apar[1] eqn = abs(x-y) return eqn Init = numpy.asarray([20.0, 10.0]) x = optimize.leastsq(func, Init, full_output=0, col_deriv=0, factor=100, diag=None, warning=True) print 'optimized parameters: ',x print '******* The End ******' </code></pre> <p>I don't know what is the problem with my func optimize.leastsq() call, please help me</p>
1
2009-09-28T17:12:23Z
1,489,194
<p>Since you want to minimize a simple scalar function (<code>func()</code> returns a single value, not a list of values), <code>scipy.optimize.leastsq()</code> should be replaced by a call to one of the <code>fmin</code> functions (with the appropriate arguments):</p> <pre><code>x = optimize.fmin(func, Init) </code></pre> <p>correctly works!</p> <p>In fact, <code>leastsq()</code> minimizes the sum of squares of a list of values. It does not appear to work on a (list containing a) single value, as in your example (even though it could, in theory).</p>
1
2009-09-28T20:26:18Z
[ "python", "scipy" ]
Mimic Python's strip() function in C
1,488,372
<p>I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects. </p> <p>Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that is encountered.</p> <p>fgets doesn't help either as I still have newlines sticking around. I did try a strchr() to search for a whitespace and setting the returned pointer to '\0' explicitly but that doesn't seem to work.</p>
3
2009-09-28T17:41:06Z
1,488,398
<p>Seems like you want something like trim, a quick search on google leads to <a href="http://www.unix.com/high-level-programming/21264-how-trim-white-space-around-string-c-program.html" rel="nofollow">this</a> forum thread.</p>
0
2009-09-28T17:47:02Z
[ "python", "c", "string", "fgets" ]
Mimic Python's strip() function in C
1,488,372
<p>I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects. </p> <p>Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that is encountered.</p> <p>fgets doesn't help either as I still have newlines sticking around. I did try a strchr() to search for a whitespace and setting the returned pointer to '\0' explicitly but that doesn't seem to work.</p>
3
2009-09-28T17:41:06Z
1,488,403
<p>Python strings' <code>strip</code> method removes both trailing and leading whitespace. The two halves of the problem are very different when working on a C "string" (array of char, \0 terminated).</p> <p>For trailing whitespace: set a pointer (or equivalently index) to the existing trailing \0. Keep decrementing the pointer until it hits against the start-of-string, or any non-white character; set the \0 to right after this terminate-backwards-scan point.</p> <p>For leading whitespace: set a pointer (or equivalently index) to the start of string; keep incrementing the pointer until it hits a non-white character (possibly the trailing \0); memmove the rest-of-string so that the first non-white goes to the start of string (and similarly for everything following).</p>
12
2009-09-28T17:48:10Z
[ "python", "c", "string", "fgets" ]
Mimic Python's strip() function in C
1,488,372
<p>I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects. </p> <p>Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that is encountered.</p> <p>fgets doesn't help either as I still have newlines sticking around. I did try a strchr() to search for a whitespace and setting the returned pointer to '\0' explicitly but that doesn't seem to work.</p>
3
2009-09-28T17:41:06Z
1,488,419
<p>There is no standard C implementation for a strip() or trim() function. That said, here's the one included in the Linux kernel:</p> <pre><code>char *strstrip(char *s) { size_t size; char *end; size = strlen(s); if (!size) return s; end = s + size - 1; while (end &gt;= s &amp;&amp; isspace(*end)) end--; *(end + 1) = '\0'; while (*s &amp;&amp; isspace(*s)) s++; return s; } </code></pre>
9
2009-09-28T17:51:07Z
[ "python", "c", "string", "fgets" ]
Mimic Python's strip() function in C
1,488,372
<p>I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects. </p> <p>Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that is encountered.</p> <p>fgets doesn't help either as I still have newlines sticking around. I did try a strchr() to search for a whitespace and setting the returned pointer to '\0' explicitly but that doesn't seem to work.</p>
3
2009-09-28T17:41:06Z
1,488,503
<p>If you want to remove, <b>in place</b>, the final newline on a line, you can use this snippet:</p> <pre><code>size_t s = strlen(buf); if (s &amp;&amp; (buf[s-1] == '\n')) buf[--s] = 0; </code></pre> <p>To faithfully mimic Python's <code>str.strip([chars])</code> method (the way I interpreted its workings), you need to allocate space for a new string, fill the new string and return it. After that, when you no longer need the stripped string you need to free the memory it used to have no memory leaks.</p> <p>Or you can use C pointers and modify the initial string and achieve a similar result.<br> Suppose your initial string is <code>"____forty two____\n"</code> and you want to strip all underscores and the '\n'</p> <pre><code>____forty two___\n ^ ptr </code></pre> <p>If you change <code>ptr</code> to the 'f' and replace the first '_' after <code>two</code> with a <code>'\0'</code> the result is the same as Python's <code>"____forty two____\n".strip("_\n");</code></p> <pre><code>____forty two\0___\n ^ptr </code></pre> <p>Again, this is not the same as Python. The string is modified in place, there's no 2nd string and you cannot revert the changes (the original string is lost).</p>
0
2009-09-28T18:07:47Z
[ "python", "c", "string", "fgets" ]
Mimic Python's strip() function in C
1,488,372
<p>I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects. </p> <p>Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that is encountered.</p> <p>fgets doesn't help either as I still have newlines sticking around. I did try a strchr() to search for a whitespace and setting the returned pointer to '\0' explicitly but that doesn't seem to work.</p>
3
2009-09-28T17:41:06Z
1,489,407
<p>I wrote C code to implement this function. I also wrote a few trivial tests to make sure my function does sensible things.</p> <p>This function writes to a buffer you provide, and should never write past the end of the buffer, so it should not be prone to buffer overflow security issues.</p> <p>Note: only Test() uses stdio.h, so if you just need the function, you only need to include ctype.h (for isspace()) and string.h (for strlen()).</p> <pre><code>// strstrip.c -- implement white space stripping for a string in C // // This code is released into the public domain. // // You may use it for any purpose whatsoever, and you don't need to advertise // where you got it, but you aren't allowed to sue me for giving you free // code; all the risk of using this is yours. #include &lt;ctype.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; // strstrip() -- strip leading and trailing white space from a string // // Copies from sIn to sOut, writing at most lenOut characters. // // Returns number of characters in returned string, or -1 on an error. // If you get -1 back, then nothing was written to sOut at all. int strstrip(char *sOut, unsigned int lenOut, char const *sIn) { char const *pStart, *pEnd; unsigned int len; char *pOut; // if there is no room for any output, or a null pointer, return error! if (0 == lenOut || !sIn || !sOut) return -1; pStart = sIn; pEnd = sIn + strlen(sIn) - 1; // skip any leading whitespace while (*pStart &amp;&amp; isspace(*pStart)) ++pStart; // skip any trailing whitespace while (pEnd &gt;= sIn &amp;&amp; isspace(*pEnd)) --pEnd; pOut = sOut; len = 0; // copy into output buffer while (pStart &lt;= pEnd &amp;&amp; len &lt; lenOut - 1) { *pOut++ = *pStart++; ++len; } // ensure output buffer is properly terminated *pOut = '\0'; return len; } void Test(const char *s) { int len; char buf[1024]; len = strstrip(buf, sizeof(buf), s); if (!s) s = "**null**"; // don't ask printf to print a null string if (-1 == len) *buf = '\0'; // don't ask printf to print garbage from buf printf("Input: \"%s\" Result: \"%s\" (%d chars)\n", s, buf, len); } main() { Test(NULL); Test(""); Test(" "); Test(" "); Test("x"); Test(" x"); Test(" x "); Test(" x y z "); Test("x y z"); } </code></pre>
0
2009-09-28T21:13:15Z
[ "python", "c", "string", "fgets" ]
Mimic Python's strip() function in C
1,488,372
<p>I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects. </p> <p>Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that is encountered.</p> <p>fgets doesn't help either as I still have newlines sticking around. I did try a strchr() to search for a whitespace and setting the returned pointer to '\0' explicitly but that doesn't seem to work.</p>
3
2009-09-28T17:41:06Z
1,489,496
<p>I asked a very similar question long ago. See <a href="http://stackoverflow.com/questions/122616/painless-way-to-trim-leading-trailing-whitespace-in-c">here</a>; there are ways to do it both in-place and with a new copy.</p>
0
2009-09-28T21:34:48Z
[ "python", "c", "string", "fgets" ]
What are good python libraries for the following needs?
1,488,691
<p>What are good python libraries for the following needs:</p> <ul> <li>MVC</li> <li>Domain Abstraction</li> <li>Database Abstraction</li> <li>Video library (just to create thumbnails) </li> </ul> <p>I already know that SQLAlchemy is really good for Database Abstraction so don't bother with it unless you want to suggest a better one. </p> <p><strong>Edit:</strong> This might seem stupid to mention but I'm talking about MVC for GUI and not for web, just mentioning for clarification </p> <p><strong>Edit:</strong> Also does the MVC part contain GUI part or can I use a separate library for GUI like PyQt</p>
2
2009-09-28T18:45:36Z
1,488,707
<p><a href="http://www.djangoproject.com/" rel="nofollow" title="django">django</a> is a pretty good mvc framework with an orm</p>
1
2009-09-28T18:48:14Z
[ "python", "model-view-controller", "libraries", "domain-model", "database-abstraction" ]
What are good python libraries for the following needs?
1,488,691
<p>What are good python libraries for the following needs:</p> <ul> <li>MVC</li> <li>Domain Abstraction</li> <li>Database Abstraction</li> <li>Video library (just to create thumbnails) </li> </ul> <p>I already know that SQLAlchemy is really good for Database Abstraction so don't bother with it unless you want to suggest a better one. </p> <p><strong>Edit:</strong> This might seem stupid to mention but I'm talking about MVC for GUI and not for web, just mentioning for clarification </p> <p><strong>Edit:</strong> Also does the MVC part contain GUI part or can I use a separate library for GUI like PyQt</p>
2
2009-09-28T18:45:36Z
1,488,731
<p>You could go with <a href="http://turbogears.org/" rel="nofollow">http://turbogears.org/</a> . Its like Django, but uses "of the shelves" existing modules.</p> <blockquote> <p>TurboGears 2 is the built on top of the experience of several next generation web frameworks including TurboGears 1 (of course), Django, and Rails. All of these frameworks had limitations which were frustrating in various ways, and TG2 is an answer to that frustration. We wanted something that had:</p> <ul> <li>Real multi-database support</li> <li>Horizontal data partitioning (sharding)</li> <li>Support for a variety of JavaScript toolkits, and new widget system to make building ajax heavy apps easier</li> <li>Support for multiple data-exchange formats.</li> <li>Built in extensibility via standard WSGI components</li> </ul> </blockquote>
1
2009-09-28T18:52:03Z
[ "python", "model-view-controller", "libraries", "domain-model", "database-abstraction" ]
What are good python libraries for the following needs?
1,488,691
<p>What are good python libraries for the following needs:</p> <ul> <li>MVC</li> <li>Domain Abstraction</li> <li>Database Abstraction</li> <li>Video library (just to create thumbnails) </li> </ul> <p>I already know that SQLAlchemy is really good for Database Abstraction so don't bother with it unless you want to suggest a better one. </p> <p><strong>Edit:</strong> This might seem stupid to mention but I'm talking about MVC for GUI and not for web, just mentioning for clarification </p> <p><strong>Edit:</strong> Also does the MVC part contain GUI part or can I use a separate library for GUI like PyQt</p>
2
2009-09-28T18:45:36Z
1,488,832
<p>Have you tried wxWidgets (well, <a href="http://www.wxpython.org" rel="nofollow">wxPython</a> in fact)? </p> <p>It has nice documentation (which is always a good thing), and allows creating code in MVC manner. It's just the GUI library, but allows some simple image manipulation (if it's not good enough for you try using Python version of ImageMagick). It uses native controls, so the application looks native on the OS it's being ran.</p> <p><a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">PyQt</a> on the other hand has even better docs than wxWidgets or wxPython, but I could never get used to the look&amp;feel of its GUI (it's custom, so it doesn't look native on any OS). Because riverbankcomputing couldn't agree with nokia on a license nokia started a project called <a href="http://pyside.org" rel="nofollow">PySide</a> which is a LGPL version of the Qt-bindings. It's supposed to be finished in early 2010.</p>
4
2009-09-28T19:13:23Z
[ "python", "model-view-controller", "libraries", "domain-model", "database-abstraction" ]
save method in a view
1,489,041
<p>I have a very simple model:</p> <pre><code>class Artist(models.Model): name = models.CharField(max_length=64, unique=False) band = models.CharField(max_length=64, unique=False) instrument = models.CharField(max_length=64, unique=False) def __unicode__ (self): return self.name </code></pre> <p>that I'm using as a model form:</p> <pre><code>from django.forms import ModelForm from artistmod.artistcat.models import * class ArtistForm(ModelForm): class Meta: model = Artist </code></pre> <p>but I can't seem to construct a view that will save the form data to the database. Currently I'm using:</p> <pre><code>def create_page(request): if request.method == 'POST': form = ArtistForm(request.POST) if form.is_valid(): form.save() return render_to_response('display.html') else: form = ArtistForm() return render_to_response('create.html', { 'form': form, }) </code></pre> <p>can anyone help the newbie?</p>
1
2009-09-28T19:57:35Z
1,490,428
<p>Apparently the problem resided in my template. I was using </p> <pre><code> &lt;form action="display/" method="POST"&gt; </code></pre> <p>as opposed to</p> <pre><code> &lt;form action="." method="POST"&gt; </code></pre> <p>also changed my HttpRequest object from <code>render_to_response</code> to <code>HttpResponseRedirect</code></p> <p>true newbie errors but at least it works now</p>
1
2009-09-29T03:24:33Z
[ "python", "django", "django-forms" ]
Managing Perl habits in a Python environment
1,489,355
<p>Perl habits die hard. Variable declaration, scoping, global/local is different between the 2 languages. Is there a set of recommended python language idioms that will render the transition from perl coding to python coding less painful. </p> <p>Subtle variable misspelling can waste an extraordinary amount of time.</p> <p>I understand the variable declaration issue is quasi-religious among python folks I'm not arguing for language changes or features, just a reliable bridge between the 2 languages that will not cause my perl habits sink my python efforts.</p> <p>Thanks.</p>
6
2009-09-28T21:02:51Z
1,489,505
<p>I like the question, but I don't have any experience in Perl so I'm not sure how to best advise you.</p> <p>I suggest you do a Google search for "Python idioms". You will find some gems. In particular:</p> <p><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html" rel="nofollow">http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html</a></p> <p><a href="http://docs.python.org/dev/howto/doanddont.html" rel="nofollow">http://docs.python.org/dev/howto/doanddont.html</a></p> <p><a href="http://jaynes.colorado.edu/PythonIdioms.html" rel="nofollow">http://jaynes.colorado.edu/PythonIdioms.html</a></p> <p>As for the variable "declaration" issue, here's my best advice for you:</p> <p>Remember that in Python, objects have a life of their own, separate from variable names. A variable name is a tag that is bound to an object. At any time, you may rebind the name to a different object, perhaps of a completely different type. Thus, this is perfectly legal:</p> <pre><code>x = 1 # bind x to integer, value == 1 x = "1" # bind x to string, value is "1" </code></pre> <p>Python is in fact strongly typed; try executing the code 1 + "1" and see how well it works, if you don't believe me. The integer object with value 1 does not accept addition of a string value, in the absence of explicit type coercion. So Python names never ever have sigil characters that flag properties of the variable; that's just not how Python does things. Any legal identifier name could be bound to any Python object of any type.</p>
1
2009-09-28T21:36:16Z
[ "python", "perl", "transitions" ]
Managing Perl habits in a Python environment
1,489,355
<p>Perl habits die hard. Variable declaration, scoping, global/local is different between the 2 languages. Is there a set of recommended python language idioms that will render the transition from perl coding to python coding less painful. </p> <p>Subtle variable misspelling can waste an extraordinary amount of time.</p> <p>I understand the variable declaration issue is quasi-religious among python folks I'm not arguing for language changes or features, just a reliable bridge between the 2 languages that will not cause my perl habits sink my python efforts.</p> <p>Thanks.</p>
6
2009-09-28T21:02:51Z
1,489,635
<p>In python $_ does not exist except in the python shell and variables with global scope are frowned upon.</p> <p>In practice this has two major effects:</p> <ol> <li>In Python you can't use regular expressions as naturally as Perl, s0 matching each iterated $_ and similarly catching matches is more cumbersome</li> <li>Python functions tend to be called explicitly or have default variables</li> </ol> <p>However these differences are fairly minor when one considers that in Python just about everything becomes a class. When I used to do Perl I thought of "carving"; in Python I rather feel I am "composing".</p> <p>Python doesn't have the idiomatic richness of Perl and I think it is probably a mistake to attempt to do the translation.</p>
1
2009-09-28T22:11:47Z
[ "python", "perl", "transitions" ]
Managing Perl habits in a Python environment
1,489,355
<p>Perl habits die hard. Variable declaration, scoping, global/local is different between the 2 languages. Is there a set of recommended python language idioms that will render the transition from perl coding to python coding less painful. </p> <p>Subtle variable misspelling can waste an extraordinary amount of time.</p> <p>I understand the variable declaration issue is quasi-religious among python folks I'm not arguing for language changes or features, just a reliable bridge between the 2 languages that will not cause my perl habits sink my python efforts.</p> <p>Thanks.</p>
6
2009-09-28T21:02:51Z
1,489,799
<p>Don't mis-type your variable names. Seriously. Use short, easy, descriptive ones, use them locally, and don't rely on the global scope. </p> <p>If you're doing a larger project that isn't served well by this, use pylint, unit tests and coverage.py to make SURE your code does what you expect.</p> <p>Copied from a comment in one of the <a href="http://stackoverflow.com/questions/613364/">other threads</a>:</p> <p>"‘strict vars’ is primarily intended to stop typoed references and missed-out ‘my’s from creating accidental globals (well, package variables in Perl terms). This can't happen in Python as bare assignments default to local declaration, and bare unassigned symbols result in an exception."</p>
0
2009-09-28T23:06:07Z
[ "python", "perl", "transitions" ]
Managing Perl habits in a Python environment
1,489,355
<p>Perl habits die hard. Variable declaration, scoping, global/local is different between the 2 languages. Is there a set of recommended python language idioms that will render the transition from perl coding to python coding less painful. </p> <p>Subtle variable misspelling can waste an extraordinary amount of time.</p> <p>I understand the variable declaration issue is quasi-religious among python folks I'm not arguing for language changes or features, just a reliable bridge between the 2 languages that will not cause my perl habits sink my python efforts.</p> <p>Thanks.</p>
6
2009-09-28T21:02:51Z
1,490,948
<p>Splitting Python classes into separate files (like in Java, one class per file) helps find scoping problems, although this is not idiomatic python (that is, not pythonic).</p> <p>I have been writing python after much perl and found this from tchrist to be useful, even though it is old:</p> <p><a href="http://linuxmafia.com/faq/Devtools/python-to-perl-conversions.html" rel="nofollow">http://linuxmafia.com/faq/Devtools/python-to-perl-conversions.html</a></p> <p>Getting used to doing without perl's most excellent variable scoping has been the second most difficult issue with my perl->python transition. The first is obvious if you have much perl: CPAN.</p>
2
2009-09-29T06:42:14Z
[ "python", "perl", "transitions" ]
Managing Perl habits in a Python environment
1,489,355
<p>Perl habits die hard. Variable declaration, scoping, global/local is different between the 2 languages. Is there a set of recommended python language idioms that will render the transition from perl coding to python coding less painful. </p> <p>Subtle variable misspelling can waste an extraordinary amount of time.</p> <p>I understand the variable declaration issue is quasi-religious among python folks I'm not arguing for language changes or features, just a reliable bridge between the 2 languages that will not cause my perl habits sink my python efforts.</p> <p>Thanks.</p>
6
2009-09-28T21:02:51Z
1,491,218
<p>Read, understand, follow, and love <strong><a href="http://python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a></strong>, which details the style guidelines for <em>everything</em> about Python.</p> <p>Seriously, if you want to know about the recommended idioms and habits of Python, that's the source.</p>
1
2009-09-29T08:17:38Z
[ "python", "perl", "transitions" ]
When is it advisable to use a ret_val variable?
1,489,372
<p>I have seen conflicting advice on whether the following code is better</p> <pre><code>def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val </code></pre> <p>or whether this is better:</p> <pre><code>def function(): if some_condition(): return 2 else: return 3 </code></pre> <p>This is a simple example, and I've written it in python-style, but what I'm looking for is a general principle as to when to use some "accumulator" variable to keep track of the return value, or whether to use multiple exit points. I know different languages might have different reasons for using one style over the other, so I'd appreciate differing viewpoints for why a particular language might stick with a particular style. (Specifically in the past I've heard that structured programming in C avoids having multiple exit points for a function.)</p>
3
2009-09-28T21:06:45Z
1,489,400
<p>It depends on the language to a large extent, however I would go with the second method returning the value directly rather than imposing another superfluous variable. The second method is cleaner, more precise and therefore more maintainable in my opinion.</p>
1
2009-09-28T21:11:45Z
[ "python", "coding-style", "return-value" ]
When is it advisable to use a ret_val variable?
1,489,372
<p>I have seen conflicting advice on whether the following code is better</p> <pre><code>def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val </code></pre> <p>or whether this is better:</p> <pre><code>def function(): if some_condition(): return 2 else: return 3 </code></pre> <p>This is a simple example, and I've written it in python-style, but what I'm looking for is a general principle as to when to use some "accumulator" variable to keep track of the return value, or whether to use multiple exit points. I know different languages might have different reasons for using one style over the other, so I'd appreciate differing viewpoints for why a particular language might stick with a particular style. (Specifically in the past I've heard that structured programming in C avoids having multiple exit points for a function.)</p>
3
2009-09-28T21:06:45Z
1,489,404
<p>In Python, it is quite common to have a return statement in the middle of the function - in particular, if it is an early exit. Your example often is rewritten as</p> <pre><code>def function(): if some_condition(): return 2 return 3 </code></pre> <p>I.e. you drop the else case when the if ends with a return.</p>
5
2009-09-28T21:12:36Z
[ "python", "coding-style", "return-value" ]
When is it advisable to use a ret_val variable?
1,489,372
<p>I have seen conflicting advice on whether the following code is better</p> <pre><code>def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val </code></pre> <p>or whether this is better:</p> <pre><code>def function(): if some_condition(): return 2 else: return 3 </code></pre> <p>This is a simple example, and I've written it in python-style, but what I'm looking for is a general principle as to when to use some "accumulator" variable to keep track of the return value, or whether to use multiple exit points. I know different languages might have different reasons for using one style over the other, so I'd appreciate differing viewpoints for why a particular language might stick with a particular style. (Specifically in the past I've heard that structured programming in C avoids having multiple exit points for a function.)</p>
3
2009-09-28T21:06:45Z
1,489,409
<p>In a language with function prototypes like C++ or Java, the compiler enforces that you return <em>something</em> of the correct type, even if execution would otherwise fall off the end of the function. In Python, since there are no function prototypes, falling off the end of the function will return the special value <code>None</code>. For this reason, you may want to use an accumulator variable and an explicit <code>return ret_val</code> at the end when coding in Python. Or use another style that ensures that execution <em>cannot</em> fall off the end without returning a value.</p>
0
2009-09-28T21:13:24Z
[ "python", "coding-style", "return-value" ]
When is it advisable to use a ret_val variable?
1,489,372
<p>I have seen conflicting advice on whether the following code is better</p> <pre><code>def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val </code></pre> <p>or whether this is better:</p> <pre><code>def function(): if some_condition(): return 2 else: return 3 </code></pre> <p>This is a simple example, and I've written it in python-style, but what I'm looking for is a general principle as to when to use some "accumulator" variable to keep track of the return value, or whether to use multiple exit points. I know different languages might have different reasons for using one style over the other, so I'd appreciate differing viewpoints for why a particular language might stick with a particular style. (Specifically in the past I've heard that structured programming in C avoids having multiple exit points for a function.)</p>
3
2009-09-28T21:06:45Z
1,489,463
<p>Returning values directly is not terrible for small functions like your example. However, if you have a large or complex function then multiple return points can be more difficult to debug. If you have a coding standard I'd refer to it (here the variable is preferred according to our company coding standard).</p>
0
2009-09-28T21:24:09Z
[ "python", "coding-style", "return-value" ]
When is it advisable to use a ret_val variable?
1,489,372
<p>I have seen conflicting advice on whether the following code is better</p> <pre><code>def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val </code></pre> <p>or whether this is better:</p> <pre><code>def function(): if some_condition(): return 2 else: return 3 </code></pre> <p>This is a simple example, and I've written it in python-style, but what I'm looking for is a general principle as to when to use some "accumulator" variable to keep track of the return value, or whether to use multiple exit points. I know different languages might have different reasons for using one style over the other, so I'd appreciate differing viewpoints for why a particular language might stick with a particular style. (Specifically in the past I've heard that structured programming in C avoids having multiple exit points for a function.)</p>
3
2009-09-28T21:06:45Z
1,489,466
<p>I suppose it's more a question of style and coding conventions. Generally, theory tells us that multiple exit points are bad. In practice it can be easier to follow to simply return inside each condition. The code is likely to be compiled down to very similar if not identical instructions, so it has little to no functional impact.</p> <p>My rule of thumb is this: If the function is longer than one page (25 lines) avoid multiple exit points. If you can see it all at once, do whatever seems best at the time you write it.</p>
1
2009-09-28T21:25:11Z
[ "python", "coding-style", "return-value" ]
When is it advisable to use a ret_val variable?
1,489,372
<p>I have seen conflicting advice on whether the following code is better</p> <pre><code>def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val </code></pre> <p>or whether this is better:</p> <pre><code>def function(): if some_condition(): return 2 else: return 3 </code></pre> <p>This is a simple example, and I've written it in python-style, but what I'm looking for is a general principle as to when to use some "accumulator" variable to keep track of the return value, or whether to use multiple exit points. I know different languages might have different reasons for using one style over the other, so I'd appreciate differing viewpoints for why a particular language might stick with a particular style. (Specifically in the past I've heard that structured programming in C avoids having multiple exit points for a function.)</p>
3
2009-09-28T21:06:45Z
1,489,468
<p>Don't use an accumulator unless it's absolutely unavoidable. It introduces unnecessary statefulness and branching into your procedures, which you then have to track manually. By returning early, you can reduce the state and branch count of your code.</p> <blockquote> <p>Specifically in the past I've heard that structured programming in C avoids having multiple exit points for a function.</p> </blockquote> <p>Precisely the opposite -- structured programming discourages multiple points of <em>entry</em>, but multiple points of exit are acceptable and even encouraged (eg "guard clauses").</p>
5
2009-09-28T21:26:25Z
[ "python", "coding-style", "return-value" ]
When is it advisable to use a ret_val variable?
1,489,372
<p>I have seen conflicting advice on whether the following code is better</p> <pre><code>def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val </code></pre> <p>or whether this is better:</p> <pre><code>def function(): if some_condition(): return 2 else: return 3 </code></pre> <p>This is a simple example, and I've written it in python-style, but what I'm looking for is a general principle as to when to use some "accumulator" variable to keep track of the return value, or whether to use multiple exit points. I know different languages might have different reasons for using one style over the other, so I'd appreciate differing viewpoints for why a particular language might stick with a particular style. (Specifically in the past I've heard that structured programming in C avoids having multiple exit points for a function.)</p>
3
2009-09-28T21:06:45Z
1,489,470
<p>A further alternative in recent versions of Python (since 2.6?) is a ternary operator statement like this:</p> <pre><code>def function(): return (2 if some_condition() else 3) </code></pre> <p>Just in case you like that better.</p>
1
2009-09-28T21:27:29Z
[ "python", "coding-style", "return-value" ]
When is it advisable to use a ret_val variable?
1,489,372
<p>I have seen conflicting advice on whether the following code is better</p> <pre><code>def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val </code></pre> <p>or whether this is better:</p> <pre><code>def function(): if some_condition(): return 2 else: return 3 </code></pre> <p>This is a simple example, and I've written it in python-style, but what I'm looking for is a general principle as to when to use some "accumulator" variable to keep track of the return value, or whether to use multiple exit points. I know different languages might have different reasons for using one style over the other, so I'd appreciate differing viewpoints for why a particular language might stick with a particular style. (Specifically in the past I've heard that structured programming in C avoids having multiple exit points for a function.)</p>
3
2009-09-28T21:06:45Z
1,489,654
<p>For primitives, it doesn't matter. In a language like C++ (&amp; presumably with structs in C it's the compiler will do something similar), the compiler is able to optimize the <a href="http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.9" rel="nofollow">copy constructor</a> out if you ensure all code paths return the same variable. For example:</p> <pre><code>Foo someFunction() { Foo result(5); if (someConditionA()) return result; else if (someConditionB()) result.doSomething(); result.doSomethingElse(); return result; } </code></pre> <p>becomes more efficient than (unless your compiler is very very good):</p> <pre><code>Foo someFunction() { if (someConditionA()) return Foo(5); if (someConditionB()) { Foo result(5); result.doSomething(); result.doSomethingElse(); return result; } Foo result(5); result.doSomethingElse(); return result; } </code></pre> <p>In all other cases, it's more style-preference &amp; readability. In the end, choose the format that's more readable for that particular case.</p>
1
2009-09-28T22:16:42Z
[ "python", "coding-style", "return-value" ]
When is it advisable to use a ret_val variable?
1,489,372
<p>I have seen conflicting advice on whether the following code is better</p> <pre><code>def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val </code></pre> <p>or whether this is better:</p> <pre><code>def function(): if some_condition(): return 2 else: return 3 </code></pre> <p>This is a simple example, and I've written it in python-style, but what I'm looking for is a general principle as to when to use some "accumulator" variable to keep track of the return value, or whether to use multiple exit points. I know different languages might have different reasons for using one style over the other, so I'd appreciate differing viewpoints for why a particular language might stick with a particular style. (Specifically in the past I've heard that structured programming in C avoids having multiple exit points for a function.)</p>
3
2009-09-28T21:06:45Z
1,489,690
<p>Although people advocate single exit strategy, I find it useful to return early. That way you don't have to keep track when you are adding code later.</p>
1
2009-09-28T22:26:49Z
[ "python", "coding-style", "return-value" ]
When is it advisable to use a ret_val variable?
1,489,372
<p>I have seen conflicting advice on whether the following code is better</p> <pre><code>def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val </code></pre> <p>or whether this is better:</p> <pre><code>def function(): if some_condition(): return 2 else: return 3 </code></pre> <p>This is a simple example, and I've written it in python-style, but what I'm looking for is a general principle as to when to use some "accumulator" variable to keep track of the return value, or whether to use multiple exit points. I know different languages might have different reasons for using one style over the other, so I'd appreciate differing viewpoints for why a particular language might stick with a particular style. (Specifically in the past I've heard that structured programming in C avoids having multiple exit points for a function.)</p>
3
2009-09-28T21:06:45Z
1,489,917
<p>Stylistics aside, let's take a look at the disassembly for the two approaches:</p> <pre><code>&gt;&gt;&gt; def foo(): ... r = 0 ... if bar(): ... r = 2 ... else: ... r = 3 ... return r ... &gt;&gt;&gt; dis.dis(foo) 2 0 LOAD_CONST 1 (0) 3 STORE_FAST 0 (r) 3 6 LOAD_GLOBAL 0 (bar) 9 CALL_FUNCTION 0 12 JUMP_IF_FALSE 10 (to 25) 15 POP_TOP 4 16 LOAD_CONST 2 (2) 19 STORE_FAST 0 (r) 22 JUMP_FORWARD 7 (to 32) &gt;&gt; 25 POP_TOP 6 26 LOAD_CONST 3 (3) 29 STORE_FAST 0 (r) 7 &gt;&gt; 32 LOAD_FAST 0 (r) 35 RETURN_VALUE </code></pre> <p>14 bytecode instructions in the first approach...</p> <pre><code>&gt;&gt;&gt; def quux(): ... if bar(): ... return 2 ... else: ... return 3 ... &gt;&gt;&gt; dis.dis(quux) 2 0 LOAD_GLOBAL 0 (bar) 3 CALL_FUNCTION 0 6 JUMP_IF_FALSE 5 (to 14) 9 POP_TOP 3 10 LOAD_CONST 1 (2) 13 RETURN_VALUE &gt;&gt; 14 POP_TOP 5 15 LOAD_CONST 2 (3) 18 RETURN_VALUE 19 LOAD_CONST 0 (None) 22 RETURN_VALUE </code></pre> <p>11 in the second approach...</p> <p>And a third approach, slightly shorter than the second:</p> <pre><code>&gt;&gt;&gt; def baz(): ... if bar(): ... return 2 ... return 3 ... &gt;&gt;&gt; dis.dis(baz) 2 0 LOAD_GLOBAL 0 (bar) 3 CALL_FUNCTION 0 6 JUMP_IF_FALSE 5 (to 14) 9 POP_TOP 3 10 LOAD_CONST 1 (2) 13 RETURN_VALUE &gt;&gt; 14 POP_TOP 4 15 LOAD_CONST 2 (3) 18 RETURN_VALUE </code></pre> <p>Has just nine instructions. The differences may not seem like much, but it actually makes a bit of a difference over a million runs with <code>timeit</code>, with <code>bar</code> defined to return alternating zeros and ones:</p> <pre> $ sudo nice -n -19 python b.py ('foo', 1.3846859931945801) ('quux', 1.282526969909668) ('baz', 1.2973799705505371) $ sudo nice -n -19 python b.py ('foo', 1.354640007019043) ('quux', 1.2609632015228271) ('baz', 1.2767179012298584) $ sudo nice -n -19 python3 b.py foo 1.72521305084 quux 1.62322306633 baz 1.62547206879 $ sudo nice -n -19 python3 b.py foo 1.73264288902 quux 1.67029309273 baz 1.62204194069 </pre> <p><code>quux</code> and <code>baz</code> tended to be close to the same time, both of which were consistently faster than <code>foo</code>.</p> <p>If you're still on the fence about which one is better, hopefully this illustrates another advantage of the accumulator-less approach that nobody else mentioned so far.</p>
2
2009-09-28T23:53:41Z
[ "python", "coding-style", "return-value" ]
When is it advisable to use a ret_val variable?
1,489,372
<p>I have seen conflicting advice on whether the following code is better</p> <pre><code>def function(): ret_val = 0 if some_condition(): ret_val = 2 else: ret_val = 3 return ret_val </code></pre> <p>or whether this is better:</p> <pre><code>def function(): if some_condition(): return 2 else: return 3 </code></pre> <p>This is a simple example, and I've written it in python-style, but what I'm looking for is a general principle as to when to use some "accumulator" variable to keep track of the return value, or whether to use multiple exit points. I know different languages might have different reasons for using one style over the other, so I'd appreciate differing viewpoints for why a particular language might stick with a particular style. (Specifically in the past I've heard that structured programming in C avoids having multiple exit points for a function.)</p>
3
2009-09-28T21:06:45Z
1,490,154
<p>Did we forget why "multiple exit points" was considered harmful in the first place? Back in the day (before widespread access to good exception handling and finally constructs, or managing objects like <code>auto_ptr</code> that do cleanup when they leave scope), this was the problem that haunted many multi-exit functions:</p> <pre><code>int function blah(arg1, arg2) allocate resource if early failure detection return failure_status ... much later... release resource // oh rats! resource didn't release return success_status </code></pre> <p>If the resource is memory, this creates a memory leak. If it's a database transaction, we are heading for bad database contention or deadlock. For that matter, with the advent of more exception support, we implicitly add <em>many</em> potential exits from a method (by virtue of an unhandled exception). In my C++ days, I developed the habit of <em>never</em> calling delete, but instead using <code>auto_ptr</code>, so that allocated memory was cleaned up when the <code>auto_ptr</code> exited its scope, even if some unexpected exception reared its head.</p> <p>In our garbage collected Python world, we can still have this issue, even though many of our objects, such as files, or locks, have improved self-cleaning behavior. But in implementations other than CPython (jython and IronPython to name two), there is no guarantee just when a destructor will get called, so something more proactive needs to be built into your method. The first mechanism for this purpose was try/finally:</p> <pre><code>int function blah(arg1, arg2) allocate resource try: if early failure detection return failure_status ... much later... return success_status finally: release resource // always releases no matter what </code></pre> <p>But now Python has context managers, in conjunction with the new 'with' syntax:</p> <pre><code>int function blah(arg1, arg2) allocate resource with context_manager(resource): // releases on exit from 'with' if early failure detection return failure_status ... much later... return success_status </code></pre> <p>So let's be sure that we tell the whole story, that the reason we can discard this old chestnut is that newer coding practices make it unnecessary.</p>
8
2009-09-29T01:35:54Z
[ "python", "coding-style", "return-value" ]
How do I find out my python path using python?
1,489,599
<p>How do I find out which directories are listed in my system’s <code>PYTHONPATH</code> variable, from within a Python script (or the interactive shell)?</p>
174
2009-09-28T22:01:26Z
1,489,625
<p><code>sys.path</code> might include items that aren't specifically in your <code>PYTHONPATH</code> environment variable. To query the variable directly, use:</p> <pre><code>import os try: user_paths = os.environ['PYTHONPATH'].split(os.pathsep) except KeyError: user_paths = [] </code></pre>
118
2009-09-28T22:08:36Z
[ "python", "python-module", "pythonpath" ]
How do I find out my python path using python?
1,489,599
<p>How do I find out which directories are listed in my system’s <code>PYTHONPATH</code> variable, from within a Python script (or the interactive shell)?</p>
174
2009-09-28T22:01:26Z
1,489,694
<p>Can't seem to edit the other answer. Has a minor error in that it is Windows-only. The more generic solution is to use os.sep as below:</p> <p>sys.path might include items that aren't specifically in your PYTHONPATH environment variable. To query the variable directly, use:</p> <pre><code>import os os.environ['PYTHONPATH'].split(os.pathsep) </code></pre>
9
2009-09-28T22:27:31Z
[ "python", "python-module", "pythonpath" ]
How do I find out my python path using python?
1,489,599
<p>How do I find out which directories are listed in my system’s <code>PYTHONPATH</code> variable, from within a Python script (or the interactive shell)?</p>
174
2009-09-28T22:01:26Z
13,178,935
<p>You would probably also want this:</p> <pre><code>import sys print(sys.path) </code></pre> <p>Or as a one liner from the terminal:</p> <pre><code>python -c "import sys; print '\n'.join(sys.path)" </code></pre>
297
2012-11-01T14:15:11Z
[ "python", "python-module", "pythonpath" ]
How to exit the entire application from a Python thread?
1,489,669
<p>How can I exit my entire Python application from one of its threads? sys.exit() only terminates the thread in which it is called, so that is no help.</p> <p>I would not like to use an os.kill() solution, as this isn't very clean.</p>
24
2009-09-28T22:20:59Z
1,489,838
<p>Short answer: use <a href="http://docs.python.org/library/os.html#os.%5Fexit"><code>os._exit</code></a>.</p> <p>Long answer with example:</p> <p>I yanked and slightly modified a simple threading example from <a href="http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/">a tutorial on DevShed</a>:</p> <pre><code>import threading, sys, os theVar = 1 class MyThread ( threading.Thread ): def run ( self ): global theVar print 'This is thread ' + str ( theVar ) + ' speaking.' print 'Hello and good bye.' theVar = theVar + 1 if theVar == 4: #sys.exit(1) os._exit(1) print '(done)' for x in xrange ( 7 ): MyThread().start() </code></pre> <p>If you keep <code>sys.exit(1)</code> commented out, the script will die after the third thread prints out. If you use <code>sys.exit(1)</code> and comment out <code>os._exit(1)</code>, the third thread does <em>not</em> print <code>(done)</code>, and the program runs through all seven threads.</p> <p><code>os._exit</code> "should normally only be used in the child process after a fork()" -- and a separate thread is close enough to that for your purpose. Also note that there are several enumerated values listed right after <code>os._exit</code> in that manual page, and you should prefer those as arguments to <code>os._exit</code> instead of simple numbers like I used in the example above.</p>
16
2009-09-28T23:21:53Z
[ "python", "multithreading" ]
How to exit the entire application from a Python thread?
1,489,669
<p>How can I exit my entire Python application from one of its threads? sys.exit() only terminates the thread in which it is called, so that is no help.</p> <p>I would not like to use an os.kill() solution, as this isn't very clean.</p>
24
2009-09-28T22:20:59Z
1,489,972
<p>If all your threads except the main ones are daemons, the best approach is generally <a href="https://docs.python.org/2/library/thread.html#thread.interrupt_main" rel="nofollow">thread.interrupt_main()</a> -- any thread can use it to raise a <code>KeyboardInterrupt</code> in the main thread, which can normally lead to reasonably clean exit from the main thread (including finalizers in the main thread getting called, etc).</p> <p>Of course, if this results in some non-daemon thread keeping the whole process alive, you need to followup with <code>os._exit</code> as Mark recommends -- but I'd see that as the last resort (kind of like a <code>kill -9</code>;-) because it terminates things quite brusquely (finalizers not run, including <code>try/finally</code> blocks, <code>with</code> blocks, <code>atexit</code> functions, etc).</p>
24
2009-09-29T00:17:28Z
[ "python", "multithreading" ]
How to exit the entire application from a Python thread?
1,489,669
<p>How can I exit my entire Python application from one of its threads? sys.exit() only terminates the thread in which it is called, so that is no help.</p> <p>I would not like to use an os.kill() solution, as this isn't very clean.</p>
24
2009-09-28T22:20:59Z
25,419,716
<p>Using <code>thread.interrupt_main()</code> may not help in some situation. <code>KeyboardInterrupt</code>s are often used in command line applications to exit the current command or to clean the input line.</p> <p>In addition, <code>os._exit</code> will kill the process immediately without running any <code>finally</code> blocks in your code, which may be dangerous (files and connections will not be closed for example).</p> <p>The solution I've found is to register a signal handler in the main thread that raises a custom exception. Use the background thread to fire the signal.</p> <pre><code>import signal import os import threading import time class ExitCommand(Exception): pass def signal_handler(signal, frame): raise ExitCommand() def thread_job(): time.sleep(5) os.kill(os.getpid(), signal.SIGUSR1) signal.signal(signal.SIGUSR1, signal_handler) threading.Thread(target=thread_job).start() # thread will fire in 5 seconds try: while True: command raw_input('Blocked by raw_input loop ') # do something with 'command' except ExitCommand: pass finally: print('finally will still run') </code></pre> <p>Related questions:</p> <ul> <li><a href="http://stackoverflow.com/q/905189/1224456">Why does sys.exit() not exit when called inside a thread in Python?</a></li> <li><a href="http://stackoverflow.com/q/4591917/1224456">Python: How to quit CLI when stuck in blocking raw_input?</a></li> </ul>
6
2014-08-21T06:37:29Z
[ "python", "multithreading" ]
Migration to GAE
1,489,886
<p>What is the best way to migrate MySQL tables to Google Datastore and create python models for them?</p> <p>I have a PHP+MySQL project that I want to migrate to Python+GAE project. So far the big obstacle is migrating the tables and creating corresponding models. Each table is about 110 columns wide. Creating a model for the table manually is a bit tedious, let alone creating a loader and importing a generated csv table representation.</p> <p>Is there a more efficient way for me to do the migration?</p>
2
2009-09-28T23:39:58Z
1,489,954
<p>In your shoes, I'd write a one-shot Python script to read the existing MySQL schema (with <a href="http://sourceforge.net/projects/mysql-python/" rel="nofollow">MySQLdb</a>), generating a models.py to match (then do some manual checks and edits on the generated code, just in case). That's assuming that a data model with "about 110" properties per entity is something you're happy with and want to preserve, of course; it might be worth to take the opportunity to break things up a bit (indeed you may have to if your current approach also relies on joins or other SQL features GAE doesn't give you), but that of course requires more manual work.</p> <p>Once the data model is in place, <a href="http://code.google.com/appengine/docs/python/tools/uploadingdata.html" rel="nofollow">bulk loading</a> can happen, typically via intermediate CSV files (there are several ways you can generate those).</p>
1
2009-09-29T00:11:18Z
[ "python", "django", "google-app-engine", "gae-datastore" ]
Migration to GAE
1,489,886
<p>What is the best way to migrate MySQL tables to Google Datastore and create python models for them?</p> <p>I have a PHP+MySQL project that I want to migrate to Python+GAE project. So far the big obstacle is migrating the tables and creating corresponding models. Each table is about 110 columns wide. Creating a model for the table manually is a bit tedious, let alone creating a loader and importing a generated csv table representation.</p> <p>Is there a more efficient way for me to do the migration?</p>
2
2009-09-28T23:39:58Z
1,491,862
<p>In general, generating your models automatically shouldn't be <em>too</em> difficult. Suppose you have a csv file for each table, with lines consisting of (field name, data type), then something like this would do the job:</p> <pre><code># Maps MySQL types to Datastore property classes type_map = { 'char': 'StringProperty', 'text': 'TextProperty', 'int': 'IntegerProperty', # ... } def generate_model_class(classname, definition_file): ret = [] ret.append("class %s(db.Model):" % (classname,)) for fieldname, type in csv.reader(open(definition_file)): ret.append(" %s = db.%s()" % (fieldname, type_map[type])) return "\n".join(ret) </code></pre> <p>Once you've defined your schema, you can bulk load directly from the DB - no need for intermediate CSV files. See <a href="http://blog.notdot.net/2009/9/Advanced-Bulk-Loading-part-3-Alternate-datasources" rel="nofollow">my blog post</a> on the subject.</p>
4
2009-09-29T10:57:15Z
[ "python", "django", "google-app-engine", "gae-datastore" ]
Migration to GAE
1,489,886
<p>What is the best way to migrate MySQL tables to Google Datastore and create python models for them?</p> <p>I have a PHP+MySQL project that I want to migrate to Python+GAE project. So far the big obstacle is migrating the tables and creating corresponding models. Each table is about 110 columns wide. Creating a model for the table manually is a bit tedious, let alone creating a loader and importing a generated csv table representation.</p> <p>Is there a more efficient way for me to do the migration?</p>
2
2009-09-28T23:39:58Z
1,491,888
<p><a href="http://code.google.com/p/approcket/" rel="nofollow">approcket</a> can mysql⇌gae or gae builtin remote api from google </p>
2
2009-09-29T11:04:17Z
[ "python", "django", "google-app-engine", "gae-datastore" ]
Migration to GAE
1,489,886
<p>What is the best way to migrate MySQL tables to Google Datastore and create python models for them?</p> <p>I have a PHP+MySQL project that I want to migrate to Python+GAE project. So far the big obstacle is migrating the tables and creating corresponding models. Each table is about 110 columns wide. Creating a model for the table manually is a bit tedious, let alone creating a loader and importing a generated csv table representation.</p> <p>Is there a more efficient way for me to do the migration?</p>
2
2009-09-28T23:39:58Z
1,492,132
<p>You could <a href="http://docs.djangoproject.com/en/dev/howto/legacy-databases/" rel="nofollow">migrate them to django models first</a></p> <p>In particular use</p> <pre><code>python manage.py inspectdb &gt; models.py </code></pre> <p>And edit models.py until satisfied. You might have to put ForeignKeys in, adjusts the length of CharFields etc.</p> <p>I've converted several legacy databases to django like this with good success.</p> <p>Django models however are different to GAE models (which I'm not very familiar with) so that may not be terribly helpful I don't know!</p>
1
2009-09-29T12:03:24Z
[ "python", "django", "google-app-engine", "gae-datastore" ]
Migration to GAE
1,489,886
<p>What is the best way to migrate MySQL tables to Google Datastore and create python models for them?</p> <p>I have a PHP+MySQL project that I want to migrate to Python+GAE project. So far the big obstacle is migrating the tables and creating corresponding models. Each table is about 110 columns wide. Creating a model for the table manually is a bit tedious, let alone creating a loader and importing a generated csv table representation.</p> <p>Is there a more efficient way for me to do the migration?</p>
2
2009-09-28T23:39:58Z
7,971,333
<p>you don't need to</p> <p><a href="http://code.google.com/apis/sql/" rel="nofollow">http://code.google.com/apis/sql/</a></p> <p>:)</p>
1
2011-11-01T18:47:28Z
[ "python", "django", "google-app-engine", "gae-datastore" ]
Chat server with Twisted framework in python can't receive data from flash client
1,489,931
<p>I've develop a chat server using Twisted framework in Python. It works fine with a Telnet client. But when I use my flash client problem appear... </p> <p>(the flash client work find with my old php chat server, I rewrote the server in python to gain performance) </p> <p>The connexion is establish between the flash client and the twisted server: XMLSocket .onConnect return TRUE. So it's not a problem of permission with the policy file. </p> <p>I'm not able to send any message from Flash clien with XMLSOCket function send(), nothing is receive on th server side. I tried to end those message with '\n' or '\n\0' or '\0' without succes.</p> <p>You have any clue?</p>
1
2009-09-29T00:02:51Z
1,490,530
<p>I find out that the default delimiter for line, use by Twisted is '\r\n'. It can be overwrite in a your children class with:</p> <p>LineOnlyReceiver.delimiter = '\n' </p>
0
2009-09-29T04:13:14Z
[ "python", "flash", "twisted" ]
Chat server with Twisted framework in python can't receive data from flash client
1,489,931
<p>I've develop a chat server using Twisted framework in Python. It works fine with a Telnet client. But when I use my flash client problem appear... </p> <p>(the flash client work find with my old php chat server, I rewrote the server in python to gain performance) </p> <p>The connexion is establish between the flash client and the twisted server: XMLSocket .onConnect return TRUE. So it's not a problem of permission with the policy file. </p> <p>I'm not able to send any message from Flash clien with XMLSOCket function send(), nothing is receive on th server side. I tried to end those message with '\n' or '\n\0' or '\0' without succes.</p> <p>You have any clue?</p>
1
2009-09-29T00:02:51Z
1,729,776
<p>Changing <code>LineOnlyReceiver.delimiter</code> is a pretty bad idea, since that changes the delivery for <em>all</em> instances of <code>LineOnlyReceiver</code> (unless they've changed it themselves on a subclass or on the instance). If you ever happen to use any such code, it will probably break.</p> <p>You should change <code>delimiter</code> by setting it on your <code>LineOnlyReceiver</code> subclass, since it's <em>your</em> subclass that has this requirement.</p>
1
2009-11-13T15:06:58Z
[ "python", "flash", "twisted" ]
ElementTree in Python 2.6.2 Processing Instructions support?
1,489,949
<p>I'm trying to create XML using the ElementTree object structure in python. It all works very well except when it comes to processing instructions. I can create a PI easily using the factory function ProcessingInstruction(), but it doesn't get added into the elementtree. I can add it manually, but I can't figure out how to add it above the root element where PI's are normally placed. Anyone know how to do this? I know of plenty of alternative methods of doing it, but it seems that this must be built in somewhere that I just can't find.</p>
4
2009-09-29T00:09:27Z
1,490,057
<p>Yeah, I don't believe it's possible, sorry. ElementTree provides a simpler interface to (non-namespaced) element-centric XML processing than DOM, but the price for that is that it doesn't support the whole XML infoset.</p> <p>There is no apparent way to represent the content that lives outside the root element (comments, PIs, the doctype and the XML declaration), and these are also discarded at parse time. (Aside: this appears to include any default attributes specified in the DTD internal subset, which makes ElementTree strictly-speaking a non-compliant XML processor.)</p> <p>You can probably work around it by subclassing or monkey-patching the Python native ElementTree implementation's <code>write()</code> method to call <code>_write</code> on your extra PIs before _writeing the <code>_root</code>, but it could be a bit fragile.</p> <p>If you need support for the full XML infoset, probably best stick with DOM.</p>
2
2009-09-29T00:52:37Z
[ "python", "xml", "elementtree" ]
ElementTree in Python 2.6.2 Processing Instructions support?
1,489,949
<p>I'm trying to create XML using the ElementTree object structure in python. It all works very well except when it comes to processing instructions. I can create a PI easily using the factory function ProcessingInstruction(), but it doesn't get added into the elementtree. I can add it manually, but I can't figure out how to add it above the root element where PI's are normally placed. Anyone know how to do this? I know of plenty of alternative methods of doing it, but it seems that this must be built in somewhere that I just can't find.</p>
4
2009-09-29T00:09:27Z
1,490,588
<p>I don't know much about ElementTree. But it is possible that you might be able to solve your problem using a library I wrote called "xe".</p> <p>xe is a set of Python classes designed to make it easy to create structured XML. I haven't worked on it in a long time, for various reasons, but I'd be willing to help you if you have questions about it, or need bugs fixed.</p> <p>It has the bare bones of support for things like processing instructions, and with a little bit of work I think it could do what you need. (When I started adding processing instructions, I didn't really understand them, and I didn't have any need for them, so the code is sort of half-baked.)</p> <p>Take a look and see if it seems useful.</p> <p><a href="http://home.avvanta.com/~steveha/xe.html" rel="nofollow">http://home.avvanta.com/~steveha/xe.html</a></p> <p>Here's an example of using it:</p> <pre><code>import xe doc = xe.XMLDoc() prefs = xe.NestElement("prefs") prefs.user_name = xe.TextElement("user_name") prefs.paper = xe.NestElement("paper") prefs.paper.width = xe.IntElement("width") prefs.paper.height = xe.IntElement("height") doc.root_element = prefs prefs.user_name = "John Doe" prefs.paper.width = 8 prefs.paper.height = 10 c = xe.Comment("this is a comment") doc.top.append(c) </code></pre> <p>If you ran the above code and then ran <code>print doc</code> here is what you would get:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;!-- this is a comment --&gt; &lt;prefs&gt; &lt;user_name&gt;John Doe&lt;/user_name&gt; &lt;paper&gt; &lt;width&gt;8&lt;/width&gt; &lt;height&gt;10&lt;/height&gt; &lt;/paper&gt; &lt;/prefs&gt; </code></pre> <p>If you are interested in this but need some help, just let me know.</p> <p>Good luck with your project.</p>
1
2009-09-29T04:35:44Z
[ "python", "xml", "elementtree" ]
ElementTree in Python 2.6.2 Processing Instructions support?
1,489,949
<p>I'm trying to create XML using the ElementTree object structure in python. It all works very well except when it comes to processing instructions. I can create a PI easily using the factory function ProcessingInstruction(), but it doesn't get added into the elementtree. I can add it manually, but I can't figure out how to add it above the root element where PI's are normally placed. Anyone know how to do this? I know of plenty of alternative methods of doing it, but it seems that this must be built in somewhere that I just can't find.</p>
4
2009-09-29T00:09:27Z
1,494,992
<p>Try the <code>lxml</code> library: it follows the ElementTree api, plus adds a lot of extra's. From the <a href="http://codespeak.net/lxml/compatibility.html" rel="nofollow">compatibility overview</a>:</p> <blockquote> <p>ElementTree ignores comments and processing instructions when parsing XML, while etree will read them in and treat them as Comment or ProcessingInstruction elements respectively. This is especially visible where comments are found inside text content, which is then split by the Comment element.</p> <p>You can disable this behaviour by passing the boolean <code>remove_comments</code> and/or <code>remove_pis</code> keyword arguments to the parser you use. For convenience and to support portable code, you can also use the <code>etree.ETCompatXMLParser</code> instead of the default <code>etree.XMLParser</code>. It tries to provide a default setup that is as close to the ElementTree parser as possible.</p> </blockquote> <p>Not in the stdlib, I know, but in my experience the best bet when you need stuff that the standard ElementTree doesn't provide.</p>
4
2009-09-29T21:15:50Z
[ "python", "xml", "elementtree" ]
ElementTree in Python 2.6.2 Processing Instructions support?
1,489,949
<p>I'm trying to create XML using the ElementTree object structure in python. It all works very well except when it comes to processing instructions. I can create a PI easily using the factory function ProcessingInstruction(), but it doesn't get added into the elementtree. I can add it manually, but I can't figure out how to add it above the root element where PI's are normally placed. Anyone know how to do this? I know of plenty of alternative methods of doing it, but it seems that this must be built in somewhere that I just can't find.</p>
4
2009-09-29T00:09:27Z
8,200,120
<p>With the lxml API it couldn't be easier, though it is a bit "underdocumented":</p> <p>If you need a top-level processing instruction, create it like this:</p> <pre><code>from lxml import etree root = etree.Element("anytagname") root.addprevious(etree.ProcessingInstruction("anypi", "anypicontent")) </code></pre> <p>The resulting document will look like this:</p> <pre><code>&lt;?anypi anypicontent?&gt; &lt;anytagname /&gt; </code></pre> <p>They certainly should add this to their FAQ because IMO it is another feature that sets this fine API apart.</p>
2
2011-11-20T07:38:15Z
[ "python", "xml", "elementtree" ]
ElementTree in Python 2.6.2 Processing Instructions support?
1,489,949
<p>I'm trying to create XML using the ElementTree object structure in python. It all works very well except when it comes to processing instructions. I can create a PI easily using the factory function ProcessingInstruction(), but it doesn't get added into the elementtree. I can add it manually, but I can't figure out how to add it above the root element where PI's are normally placed. Anyone know how to do this? I know of plenty of alternative methods of doing it, but it seems that this must be built in somewhere that I just can't find.</p>
4
2009-09-29T00:09:27Z
34,194,103
<pre><code>f = open('D:\Python\XML\test.xml', 'r+') old = f.read() f.seek(44,0) #place cursor after xml declaration f.write('&lt;?xml-stylesheet type="text/xsl" href="C:\Stylesheets\expand.xsl"?&gt;'+ old[44:]) </code></pre> <p>I was facing the same problem and came up with this crude solution after failing to insert the PI into the .xml file correctly even after using one of the Element methods in my case <code>root.insert (0, PI)</code> and trying multiple ways to cut and paste the inserted PI to the correct location only to find the data to be deleted from unexpected locations.</p>
0
2015-12-10T05:08:16Z
[ "python", "xml", "elementtree" ]
Precise response to tablet/mouse events in Windows
1,490,011
<p>How can I tell Windows not to do unhelpful pre-processing on tablet pen events?</p> <p>I am programming in Python 2.6, targetting tablet PCs running Windows 7 (though I would like my program to work with little modification on XP with a SMART interactive whiteboard, and for mouse users on Linux/Mac). I've written a program which hooks into the normal Windows mouse events, WM_MOUSEMOVE etc., and writes on a canvas.</p> <p>The problem is that the mouse messages are being fiddled with before they reach my application. I found that if I make long strokes and pause between strokes then the mouse messages are sent properly. But if I make several rapid short strokes, then something is doing unhelpful pre-processing. Specifically, if I make a down-stroke about 10 pixels long, and then make another downstroke about five pixels to the right of the first, then the second WM_MOUSEDOWN reports that it comes from exactly the same place as the first.</p> <p>This looks like some sort of pre-processing, perhaps so that naive applications don't get confused about double-clicks. But for my application, where I want very faithful response to rapid gestures, it's unhelpful.</p> <p>I found a reference to the MicrosoftTabletPenServiceProperty atom, and to CS_DBLCLKS window style, and I turned them both off with the following piece of Python code:</p> <pre><code>hwnd = self.GetHandle() tablet_atom = "MicrosoftTabletPenServiceProperty" atom_ID = windll.kernel32.GlobalAddAtomA(tablet_atom) windll.user32.SetPropA(hwnd,tablet_atom,1) currentstyle = windll.user32.GetClassLongA(hwnd, win32con.GCL_STYLE) windll.user32.SetClassLongA(hwnd, win32con.GCL_STYLE, currentstyle &amp; ~win32con.CS_DBLCLKS) </code></pre> <p>But it has no effect.</p> <p>I tried writing a low-level hook for the mouse driver, with SetWindowsHookEx, but it doesn't work -- obviously the mouse messages are being pre-processed even before they are sent to my low-level Windows hook.</p> <p>I would be very grateful for advice about how to turn off this pre-processing. I do not want to switch to RealTimeStylus -- first because it won't work on Windows XP plus SMART interactive whiteboard, second because I can't see how to use RealTimeStylus in CPython, so I would need to switch to IronPython, and then my code would no longer run on Linux/Mac.</p> <p>Damon.</p>
0
2009-09-29T00:36:39Z
1,492,026
<p>For raw mouse messages, you can use <a href="http://msdn.microsoft.com/en-us/library/ms645590%28VS.85%29.aspx" rel="nofollow"><code>WM_INPUT</code></a> on XP and later. Seven added some touch specific stuff: <a href="http://msdn.microsoft.com/en-us/library/dd353242%28VS.85%29.aspx" rel="nofollow"><code>WM_GESTURE</code></a> and <a href="http://msdn.microsoft.com/en-us/library/dd317341%28VS.85%29.aspx" rel="nofollow"><code>WM_TOUCH</code></a></p>
1
2009-09-29T11:41:04Z
[ "python", "winapi", "tablet-pc" ]
calling Objective C functions from Python?
1,490,039
<p>Is there a way to dynamically call an Objective C function from Python?</p> <p>For example, On the mac I would like to call this Objective C function</p> <pre><code>[NSSpeechSynthesizer availableVoices] </code></pre> <p>without having to precompile any special Python wrapper module.</p>
7
2009-09-29T00:47:28Z
1,490,077
<p>You probably want <a href="http://pyobjc.sourceforge.net/" rel="nofollow">PyObjC</a>. That said, I've never actually used it myself (I've only ever seen demos), so I'm not certain that it will do what you need.</p>
3
2009-09-29T00:59:07Z
[ "python", "objective-c", "osx" ]
calling Objective C functions from Python?
1,490,039
<p>Is there a way to dynamically call an Objective C function from Python?</p> <p>For example, On the mac I would like to call this Objective C function</p> <pre><code>[NSSpeechSynthesizer availableVoices] </code></pre> <p>without having to precompile any special Python wrapper module.</p>
7
2009-09-29T00:47:28Z
1,490,078
<p>Mac OS X from 10.5 onward has shipped with Python and the objc module that will let you do what you want.</p> <p>An example:</p> <pre><code>from Foundation import * thing = NSKeyedUnarchiver.unarchiveObjectWithFile_(some_plist_file) </code></pre> <p>You can find more documentation <a href="http://pyobjc.sourceforge.net/" rel="nofollow">here</a>.</p>
4
2009-09-29T00:59:27Z
[ "python", "objective-c", "osx" ]
calling Objective C functions from Python?
1,490,039
<p>Is there a way to dynamically call an Objective C function from Python?</p> <p>For example, On the mac I would like to call this Objective C function</p> <pre><code>[NSSpeechSynthesizer availableVoices] </code></pre> <p>without having to precompile any special Python wrapper module.</p>
7
2009-09-29T00:47:28Z
1,490,461
<p>Since OS X 10.5, OS X has shipped with the <a href="http://pyobjc.sourceforge.net/">PyObjC</a> bridge, a Python-Objective-C bridge. It uses the <a href="http://bridgesupport.macosforge.org/trac/">BridgeSupport</a> framework to map Objective-C frameworks to Python. Unlike, MacRuby, PyObjC is a classical bridge--there is a proxy object on the python side for each ObjC object and visa versa. The bridge is pretty seamless, however, and its possible to write entire apps in PyObjC (Xcode has some basic PyObjC support, and you can download the app and file templates for Xcode from the PyObjC SVN at the above link). Many folks use it for utilities or for app-scripting/plugins. Apple's developer site also has an <a href="http://developer.apple.com/cocoa/pyobjc.html">introduction</a> to developing Cocoa applications with Python via PyObjC which is slightly out of date, but may be a good overview for you.</p> <p>In your case, the following code will call <code>[NSSpeechSynthesizer availableVoices]</code>:</p> <pre><code>from AppKit import NSSpeechSynthesizer NSSpeechSynthesizer.availableVoices() </code></pre> <p>which returns</p> <pre><code>( "com.apple.speech.synthesis.voice.Agnes", "com.apple.speech.synthesis.voice.Albert", "com.apple.speech.synthesis.voice.Alex", "com.apple.speech.synthesis.voice.BadNews", "com.apple.speech.synthesis.voice.Bahh", "com.apple.speech.synthesis.voice.Bells", "com.apple.speech.synthesis.voice.Boing", "com.apple.speech.synthesis.voice.Bruce", "com.apple.speech.synthesis.voice.Bubbles", "com.apple.speech.synthesis.voice.Cellos", "com.apple.speech.synthesis.voice.Deranged", "com.apple.speech.synthesis.voice.Fred", "com.apple.speech.synthesis.voice.GoodNews", "com.apple.speech.synthesis.voice.Hysterical", "com.apple.speech.synthesis.voice.Junior", "com.apple.speech.synthesis.voice.Kathy", "com.apple.speech.synthesis.voice.Organ", "com.apple.speech.synthesis.voice.Princess", "com.apple.speech.synthesis.voice.Ralph", "com.apple.speech.synthesis.voice.Trinoids", "com.apple.speech.synthesis.voice.Vicki", "com.apple.speech.synthesis.voice.Victoria", "com.apple.speech.synthesis.voice.Whisper", "com.apple.speech.synthesis.voice.Zarvox" ) </code></pre> <p>(a bridged NSCFArray) on my SL machine.</p>
6
2009-09-29T03:38:21Z
[ "python", "objective-c", "osx" ]
calling Objective C functions from Python?
1,490,039
<p>Is there a way to dynamically call an Objective C function from Python?</p> <p>For example, On the mac I would like to call this Objective C function</p> <pre><code>[NSSpeechSynthesizer availableVoices] </code></pre> <p>without having to precompile any special Python wrapper module.</p>
7
2009-09-29T00:47:28Z
1,490,644
<p>As others have mentioned, PyObjC is the way to go. But, for completeness' sake, here's how you can do it with <a href="http://docs.python.org/library/ctypes.html">ctypes</a>, in case you need it to work on versions of OS X prior to 10.5 that do not have PyObjC installed:</p> <pre><code>import ctypes import ctypes.util # Need to do this to load the NSSpeechSynthesizer class, which is in AppKit.framework appkit = ctypes.cdll.LoadLibrary(ctypes.util.find_library('AppKit')) objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc')) objc.objc_getClass.restype = ctypes.c_void_p objc.sel_registerName.restype = ctypes.c_void_p objc.objc_msgSend.restype = ctypes.c_void_p objc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p] # Without this, it will still work, but it'll leak memory NSAutoreleasePool = objc.objc_getClass('NSAutoreleasePool') pool = objc.objc_msgSend(NSAutoreleasePool, objc.sel_registerName('alloc')) pool = objc.objc_msgSend(pool, objc.sel_registerName('init')) NSSpeechSynthesizer = objc.objc_getClass('NSSpeechSynthesizer') availableVoices = objc.objc_msgSend(NSSpeechSynthesizer, objc.sel_registerName('availableVoices')) count = objc.objc_msgSend(availableVoices, objc.sel_registerName('count')) voiceNames = [ ctypes.string_at( objc.objc_msgSend( objc.objc_msgSend(availableVoices, objc.sel_registerName('objectAtIndex:'), i), objc.sel_registerName('UTF8String'))) for i in range(count)] print voiceNames objc.objc_msgSend(pool, objc.sel_registerName('release')) </code></pre> <p>It ain't pretty, but it gets the job done. The final list of available names is stored in the <code>voiceNames</code> variable above.</p> <p><strong>2012-4-28 Update</strong>: Fixed to work in 64-bit Python builds by making sure all parameters and return types are passed as pointers instead of 32-bit integers.</p>
18
2009-09-29T04:58:47Z
[ "python", "objective-c", "osx" ]
Python Modules most worthwhile reading
1,490,190
<p>I have been programming Python for a while and I have a very good understanding of its features, but I would like to improve my coding style. I think reading the source code of the Python Modules would be a good idea. Can anyone recommend any ones in particular?</p> <p>Related Threads:</p> <ul> <li><a href="http://stackoverflow.com/questions/125019/beginner-looking-for-beautiful-and-instructional-python-code">Beginner looking for beautiful and instructional Python code</a>: This thread actually inspired this question</li> </ul>
9
2009-09-29T01:48:51Z
1,490,204
<p>I vote for <a href="http://docs.python.org/library/itertools.html">itertools</a>. You'll learn a lot of functional programming style from using this code, though perhaps not from reading the source.</p> <p>For a good module-by-module tutorial, try Doug Hellmann's <a href="http://www.doughellmann.com/PyMOTW/modindex.html">Python Module of the Week</a>. I also like the python programming style/practices explored and developed at <a href="http://wordaligned.org/tag/python">WordAligned</a>. I also like <a href="http://norvig.com/">Peter Norvig's code</a>, especially the <a href="http://norvig.com/spell-correct.html">spelling corrector code</a> and the <a href="http://norvig.com/sudoku.html">sudoku solver</a>.</p> <p>Other cool modules to learn: collections, operator, os.path, optparse, and the process/threading modules.</p>
6
2009-09-29T01:53:23Z
[ "python" ]
Python Modules most worthwhile reading
1,490,190
<p>I have been programming Python for a while and I have a very good understanding of its features, but I would like to improve my coding style. I think reading the source code of the Python Modules would be a good idea. Can anyone recommend any ones in particular?</p> <p>Related Threads:</p> <ul> <li><a href="http://stackoverflow.com/questions/125019/beginner-looking-for-beautiful-and-instructional-python-code">Beginner looking for beautiful and instructional Python code</a>: This thread actually inspired this question</li> </ul>
9
2009-09-29T01:48:51Z
1,490,205
<p>I am learning Django and I really like their coding style,</p> <p><a href="http://www.djangoproject.com/" rel="nofollow">http://www.djangoproject.com/</a></p>
0
2009-09-29T01:54:10Z
[ "python" ]
Python Modules most worthwhile reading
1,490,190
<p>I have been programming Python for a while and I have a very good understanding of its features, but I would like to improve my coding style. I think reading the source code of the Python Modules would be a good idea. Can anyone recommend any ones in particular?</p> <p>Related Threads:</p> <ul> <li><a href="http://stackoverflow.com/questions/125019/beginner-looking-for-beautiful-and-instructional-python-code">Beginner looking for beautiful and instructional Python code</a>: This thread actually inspired this question</li> </ul>
9
2009-09-29T01:48:51Z
1,490,212
<p><a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> is the "standard" Python coding style, for whatever version of "standard" you want to use. =)</p>
0
2009-09-29T01:56:46Z
[ "python" ]
Python Modules most worthwhile reading
1,490,190
<p>I have been programming Python for a while and I have a very good understanding of its features, but I would like to improve my coding style. I think reading the source code of the Python Modules would be a good idea. Can anyone recommend any ones in particular?</p> <p>Related Threads:</p> <ul> <li><a href="http://stackoverflow.com/questions/125019/beginner-looking-for-beautiful-and-instructional-python-code">Beginner looking for beautiful and instructional Python code</a>: This thread actually inspired this question</li> </ul>
9
2009-09-29T01:48:51Z
1,490,216
<p><a href="http://svn.python.org/view/python/trunk/Lib/Queue.py?revision=70405&amp;view=markup" rel="nofollow">Queue.py</a> shows you how to make a class thread-safe, and the proper use of the <a href="http://en.wikipedia.org/wiki/Template%5Fmethod%5Fpattern" rel="nofollow">Template Method</a> design pattern.</p> <p><a href="http://svn.python.org/view/python/trunk/Lib/sched.py?revision=72932&amp;view=markup" rel="nofollow">sched.py</a> is a great example of the <a href="http://en.wikipedia.org/wiki/Dependency%5Finjection" rel="nofollow">Dependency Injection</a> pattern.</p> <p><a href="http://svn.python.org/view/python/trunk/Lib/heapq.py?revision=70691&amp;view=markup" rel="nofollow">heapq.py</a> is a really well-crafted implementation of the <a href="http://en.wikipedia.org/wiki/Heap%5F%28data%5Fstructure%29" rel="nofollow">Heap</a> data structure.</p> <p>If I had to pick my three favorite modules in the Python standard library, this triplet would probably be my choice. (It doesn't hurt that they're all so <strong>very</strong> useful... but I'm picking in terms of quality of code, comments and design, first and foremost).</p>
18
2009-09-29T01:59:29Z
[ "python" ]
In python, how do you launch an Amazon EC2 instance from within a Google App Engine app?
1,490,429
<p>In python, what is the best way to launch an Amazon EC2 instance from within a Google App Engine app? I would like to keep my AWS keys as secure as possible and be able to retrieve the public DNS for the newly launched EC2 instance. </p>
3
2009-09-29T03:25:00Z
1,490,484
<p>I believe you can use <a href="http://code.google.com/p/boto/">boto</a> with the current App Engine release (and maybe <a href="http://code.google.com/p/app-engine-patch/">AEP</a> to help, though maybe that's not needed for your specific task of starting an instance and retrieving its public domain name). <a href="http://blog.localkinegrinds.com/2009/04/02/lessons-learned-google-app-engine-app-engine-patch-django-boto/">This post</a> has a good overview of "lessons learned" while getting all this to work. (Sorry, no personal experience -- my occasional playing with AWS has been done from my laptop, disconnected with my more intense use of GAE;-).</p> <p>If this doesn't work for you or doesn't meet you needs, perhaps you could give us details of what you tried, how it failed, and what different behavior(s) you're looking for...?</p>
5
2009-09-29T03:46:51Z
[ "python", "google-app-engine", "amazon-ec2" ]
Difference between attributes and style tags in lxml
1,490,474
<p>I am trying to learn lxml after having used BeautifulSoup. However, I am not a strong programmer in general.</p> <p>I have the following code in some source html:</p> <pre><code>&lt;p style="font-family:times;text-align:justify"&gt;&lt;font size="2"&gt;&lt;b&gt;&lt;i&gt; The reasons to eat pickles include: &lt;/i&gt;&lt;/b&gt;&lt;/font&gt;&lt;/p&gt; </code></pre> <p>Because the text is bolded, I want to pull that text. I can't seem to be able to differentiate that that particular line is bolded.</p> <p>When I started this work this evening I was working with a document that had the word bold in the style attrib like the following:</p> <pre><code>&lt;p style="font-style:italic;font-weight:bold;margin:0pt 0pt 6.0pt;text-indent:0pt;"&gt;&lt;b&gt;&lt;i&gt;&lt;font size="2" face="Times New Roman" style="font-size:10.0pt;"&gt;The reason I like tomatoes include:&lt;/font&gt;&lt;/i&gt;&lt;/b&gt;&lt;/p&gt; </code></pre> <p>I should say that the document I am working from is a fragment that I read in the lines, joined the lines together and then used the html.fromstring function</p> <pre><code>txtFile=open(r'c:\myfile.htm','r').readlines() strHTM=''.join(txtFile) newHTM=html.fromstring(strHTM) </code></pre> <p>and so the first line of htm code I have above is newHTM[19]</p> <p>Humm this seems to be getting me closer</p> <pre><code>newHTM.cssselect('b') </code></pre> <p>I don't fully understand yet but here is the solution:</p> <pre><code>for each in newHTM: if each.cssselect('b') each.text_content() </code></pre>
0
2009-09-29T03:41:44Z
1,490,790
<p>Using the CSS API really isn't the right approach. If you want to find all b elements, do</p> <pre><code>strHTM=open(r'c:\myfile.htm','r').read() # no need to split it into lines first newHTM=html.fromString(strHTM) bELements = newHTM.findall('b') for b in bElements: print b.text_content() </code></pre>
0
2009-09-29T05:59:08Z
[ "python", "lxml" ]
Django slugified urls - how to handle collisions?
1,490,559
<p>I'm currently working on a toy project in Django.</p> <p>Part of my app allows users to leave reviews. I'd like to take the title of the review and slugify it to create a url.</p> <p>So, if a user writes a review called "The best thing ever!", the url would be something like: <code>www.example.com/reviews/the-best-thing-ever</code>. </p> <p>That's all well and good, but what is the best way to handle case where two users pick the same title? I don't want to make the title required to be unique.</p> <p>I've thought about adding the review id in the url somewhere, but I'd like to avoid that extra info for any urls that don't collide.</p> <p>Any ideas?</p>
6
2009-09-29T04:23:55Z
1,490,624
<pre><code>from django.template.defaultfilters import slugify def slugify_unique(value, model, slugfield="slug"): suffix = 0 potential = base = slugify(value) while True: if suffix: potential = "-".join([base, str(suffix)]) if not model.objects.filter(**{slugfield: potential}).count(): return potential suffix += 1 """ above function is not my code, but i don't remember exactly where it comes from you can find many snippets with such solutions searching for 'unique slug' and so """ class ReviewForm(forms.ModelForm): def save(self, user, commit=True): self.instance.slug = slugify_unique(self.cleaned_data['title'], self.Meta.model) review = super(ReviewForm, self).save(commit) review.save() return review class Meta: model = Review </code></pre> <p>of course change the appropriate names and form definition, but you get the idea :)</p>
2
2009-09-29T04:53:03Z
[ "python", "django", "url", "slug", "collision" ]
Django slugified urls - how to handle collisions?
1,490,559
<p>I'm currently working on a toy project in Django.</p> <p>Part of my app allows users to leave reviews. I'd like to take the title of the review and slugify it to create a url.</p> <p>So, if a user writes a review called "The best thing ever!", the url would be something like: <code>www.example.com/reviews/the-best-thing-ever</code>. </p> <p>That's all well and good, but what is the best way to handle case where two users pick the same title? I don't want to make the title required to be unique.</p> <p>I've thought about adding the review id in the url somewhere, but I'd like to avoid that extra info for any urls that don't collide.</p> <p>Any ideas?</p>
6
2009-09-29T04:23:55Z
1,490,682
<p>I would recommend something like <a href="http://bitbucket.org/neithere/django-autoslug/wiki/Home">AutoSlugField</a>. It has a few options available with respect to configuring uniqueness (<code>unique</code> and <code>unique_with</code>), and has the added benefit of being able to automatically generate slugs based on another field on your model, if you so choose.</p>
6
2009-09-29T05:21:33Z
[ "python", "django", "url", "slug", "collision" ]
Django slugified urls - how to handle collisions?
1,490,559
<p>I'm currently working on a toy project in Django.</p> <p>Part of my app allows users to leave reviews. I'd like to take the title of the review and slugify it to create a url.</p> <p>So, if a user writes a review called "The best thing ever!", the url would be something like: <code>www.example.com/reviews/the-best-thing-ever</code>. </p> <p>That's all well and good, but what is the best way to handle case where two users pick the same title? I don't want to make the title required to be unique.</p> <p>I've thought about adding the review id in the url somewhere, but I'd like to avoid that extra info for any urls that don't collide.</p> <p>Any ideas?</p>
6
2009-09-29T04:23:55Z
1,492,882
<p>One thing I never liked about the unique slug fields/methods is that if you have a lot of clashes for a single title, you'll end up running several queries to try and determine an available slug. I know you mentioned you don't want to show the id for non-clashing slugs, but, as far as performance, I think it's the better route to take. To make the URL a little nicer looking, I prefer also to embed the id before the slug, so that a URL takes the form of www.example.com/reviews/1/the-best-thing-ever.</p>
6
2009-09-29T14:25:10Z
[ "python", "django", "url", "slug", "collision" ]
Django slugified urls - how to handle collisions?
1,490,559
<p>I'm currently working on a toy project in Django.</p> <p>Part of my app allows users to leave reviews. I'd like to take the title of the review and slugify it to create a url.</p> <p>So, if a user writes a review called "The best thing ever!", the url would be something like: <code>www.example.com/reviews/the-best-thing-ever</code>. </p> <p>That's all well and good, but what is the best way to handle case where two users pick the same title? I don't want to make the title required to be unique.</p> <p>I've thought about adding the review id in the url somewhere, but I'd like to avoid that extra info for any urls that don't collide.</p> <p>Any ideas?</p>
6
2009-09-29T04:23:55Z
2,340,063
<p>I would (in the form validation) just check to see if the slug is used, and then add something to it, either a number "my-cool-idea_2" or the actual id</p>
0
2010-02-26T07:24:34Z
[ "python", "django", "url", "slug", "collision" ]
Comparing performance between ruby and python code
1,490,841
<p>I have a memory and CPU intensive problem to solve and I need to benchmark the different solutions in ruby and python on different platforms.</p> <p>To do the benchmark, I need to measure the time taken and the memory occupied by objects (not the entire program, but a selected list of objects) in both python and ruby.</p> <p>Please recommend ways to do it, and also let me know if it is possible to do it without using OS specify tools like (Task Manager and ps). Thanks!</p> <p>Update: Yes, I know that both Python and Ruby are not strong in performance and there are better alternatives like c, c++, Java etc. I am actually more interested in comparing the performance of Python and Ruby. And please no fame-wars.</p>
1
2009-09-29T06:15:28Z
1,490,987
<p>For Python I recommend <a href="http://guppy-pe.sourceforge.net/" rel="nofollow">heapy</a></p> <pre><code>from guppy import hpy h = hpy() print h.heap() </code></pre> <p>or <a href="http://www.aminus.net/wiki/Dowser" rel="nofollow">Dowser</a> or <a href="http://pysizer.8325.org/" rel="nofollow">PySizer</a></p> <p>For Ruby you can use the <a href="http://www.rubyinside.com/bleakhouse-tool-to-find-memory-leaks-in-your-rails-applications-470.html" rel="nofollow">BleakHouse Plugin</a> or just read <a href="http://stackoverflow.com/questions/161315/ruby-ruby-on-rails-memory-leak-detection">this</a> answer on memory leak debugging (ruby).</p>
3
2009-09-29T06:57:34Z
[ "python", "ruby", "performance", "memory-management" ]
Comparing performance between ruby and python code
1,490,841
<p>I have a memory and CPU intensive problem to solve and I need to benchmark the different solutions in ruby and python on different platforms.</p> <p>To do the benchmark, I need to measure the time taken and the memory occupied by objects (not the entire program, but a selected list of objects) in both python and ruby.</p> <p>Please recommend ways to do it, and also let me know if it is possible to do it without using OS specify tools like (Task Manager and ps). Thanks!</p> <p>Update: Yes, I know that both Python and Ruby are not strong in performance and there are better alternatives like c, c++, Java etc. I am actually more interested in comparing the performance of Python and Ruby. And please no fame-wars.</p>
1
2009-09-29T06:15:28Z
1,491,010
<p>If you are using Python for CPU intensive algorithmic tasks I suggest use Numpy/Scipy to speed up your numerical calculations and use the Psyco JIT compiler for everything else. Your speeds can approach that of much lower-level languages if you use optimized components.</p>
2
2009-09-29T07:05:20Z
[ "python", "ruby", "performance", "memory-management" ]
Comparing performance between ruby and python code
1,490,841
<p>I have a memory and CPU intensive problem to solve and I need to benchmark the different solutions in ruby and python on different platforms.</p> <p>To do the benchmark, I need to measure the time taken and the memory occupied by objects (not the entire program, but a selected list of objects) in both python and ruby.</p> <p>Please recommend ways to do it, and also let me know if it is possible to do it without using OS specify tools like (Task Manager and ps). Thanks!</p> <p>Update: Yes, I know that both Python and Ruby are not strong in performance and there are better alternatives like c, c++, Java etc. I am actually more interested in comparing the performance of Python and Ruby. And please no fame-wars.</p>
1
2009-09-29T06:15:28Z
1,491,746
<p>If you really need to write fast code in a language like this (and not a language far more suited to CPU intensive operations and close control over memory usage such as C++) then I'd recommend pushing the bulk of the work out to <a href="http://www.cython.org/" rel="nofollow">Cython</a>.</p> <blockquote> <p>Cython is a language that makes writing C extensions for the Python language as easy as Python itself. Cython is based on the well-known Pyrex, but supports more cutting edge functionality and optimizations.</p> <p>The Cython language is very close to the Python language, but Cython additionally supports calling C functions and declaring C types on variables and class attributes. This allows the compiler to generate very efficient C code from Cython code.</p> </blockquote> <p>That way you can get most of the efficiency of C with most of the ease of use of Python.</p>
3
2009-09-29T10:30:03Z
[ "python", "ruby", "performance", "memory-management" ]
Comparing performance between ruby and python code
1,490,841
<p>I have a memory and CPU intensive problem to solve and I need to benchmark the different solutions in ruby and python on different platforms.</p> <p>To do the benchmark, I need to measure the time taken and the memory occupied by objects (not the entire program, but a selected list of objects) in both python and ruby.</p> <p>Please recommend ways to do it, and also let me know if it is possible to do it without using OS specify tools like (Task Manager and ps). Thanks!</p> <p>Update: Yes, I know that both Python and Ruby are not strong in performance and there are better alternatives like c, c++, Java etc. I am actually more interested in comparing the performance of Python and Ruby. And please no fame-wars.</p>
1
2009-09-29T06:15:28Z
1,497,527
<p>I'd be wary of trying to measure just the memory consumption of an object graph over the lifecycle of an application. After all, you really don't care about that, in the end. You care that your application, in its entirety, has a sufficiently low footprint.</p> <p>If you choose to limit your observation of memory consumption anyway, include garbage collector timing in your list of considerations, then look at ruby-prof:</p> <p><a href="http://ruby-prof.rubyforge.org/" rel="nofollow">http://ruby-prof.rubyforge.org/</a></p> <p>Ciao,<br/> Sheldon.</p>
1
2009-09-30T11:20:31Z
[ "python", "ruby", "performance", "memory-management" ]
Comparing performance between ruby and python code
1,490,841
<p>I have a memory and CPU intensive problem to solve and I need to benchmark the different solutions in ruby and python on different platforms.</p> <p>To do the benchmark, I need to measure the time taken and the memory occupied by objects (not the entire program, but a selected list of objects) in both python and ruby.</p> <p>Please recommend ways to do it, and also let me know if it is possible to do it without using OS specify tools like (Task Manager and ps). Thanks!</p> <p>Update: Yes, I know that both Python and Ruby are not strong in performance and there are better alternatives like c, c++, Java etc. I am actually more interested in comparing the performance of Python and Ruby. And please no fame-wars.</p>
1
2009-09-29T06:15:28Z
1,498,047
<p>(you didn't specify py 2.5, 2.6 or 3; or ruby 1.8 or 1.9, jruby, MRI; The JVM has a wealth of tools to attack memory issues; Generally it 's helpful to zero in on memory depletion by posting stripped down versions of programs that replicate the problem</p> <p>Heapy, ruby-prof, bleak house are all good tools, here are others:</p> <p>Ruby </p> <p><a href="http://eigenclass.org/R2/writings/object-size-ruby-ocaml" rel="nofollow">http://eigenclass.org/R2/writings/object-size-ruby-ocaml</a></p> <p>watch ObjectSpace yourself <a href="http://www.coderoshi.com/2007/08/cheap-tricks-ix-spying-on-ruby.html" rel="nofollow">http://www.coderoshi.com/2007/08/cheap-tricks-ix-spying-on-ruby.html</a></p> <p><a href="http://sporkmonger.com/articles/2006/10/22/a-question" rel="nofollow">http://sporkmonger.com/articles/2006/10/22/a-question</a></p> <p>(ruby and python) <a href="http://www.softwareverify.com/" rel="nofollow">http://www.softwareverify.com/</a></p>
0
2009-09-30T13:15:29Z
[ "python", "ruby", "performance", "memory-management" ]
Mapping std::map to Python
1,491,037
<p>Sometimes it makes sense to have a key-ordered dictionary. In C++, this is often implemented with a Red-black tree. But any self-balancing binary search tree will do (fwiw, Knuth is particularly clear on this subject). The best solution I've been able to come up with so far is to take <a href="http://sourceforge.net/projects/pyavl/">R. McGraw's AVL-tree type</a> and create a wrapper class that basically implements the STL map interface (also counting on the handy ordering of pairs (two element tuples) in Python). Such a tuple basically corresponds to std::map::value_type.</p> <p>Yes, there's Python's bisect module, and while that is logarithmic at insertion time in the same way that self-balancing binary trees are logarithmic at insertion time (right?), frankly I just want an object. Called OrderedDict or something (and no, the Python 3.1 OrderedDict doesn't qualify -- that's for 'insertion-time' ordering -- and frankly what insertion-time ordering has to do with ordering is not quite obvious).</p> <p>Note, a key-ordered dictionary is highly useful in many industries (in finance for instance, it's ordinary to keep track of price books of data, which are basically ordered dictionaries of price -> quantity, aggregated order information, etc.). </p> <p>If anyone has any other ideas, that's great. All I know is I just got five million times smarter by Alex Martelli's 'answers' here. So I thought I'd ask.</p>
6
2009-09-29T07:14:53Z
1,491,055
<p>I got exactly the same need, and Alex Martelli's answer has totally convinced me: best is keeping a dictionary and a list of partially sorted keys, then sort when needed. This is efficient because of the very particular behaviour of python's sort algorithm (AKA Timsort). <a href="http://stackoverflow.com/questions/1319763/key-ordered-dict-in-python">http://stackoverflow.com/questions/1319763/key-ordered-dict-in-python</a></p> <p>I tested his implementation and mine, and his was best (because he does not insert in the middle of the list)</p> <p>(I strongly advise you to read the paper linked in AM's comment about the timsort, which is a pearl).</p>
2
2009-09-29T07:23:38Z
[ "python", "dictionary" ]
Mapping std::map to Python
1,491,037
<p>Sometimes it makes sense to have a key-ordered dictionary. In C++, this is often implemented with a Red-black tree. But any self-balancing binary search tree will do (fwiw, Knuth is particularly clear on this subject). The best solution I've been able to come up with so far is to take <a href="http://sourceforge.net/projects/pyavl/">R. McGraw's AVL-tree type</a> and create a wrapper class that basically implements the STL map interface (also counting on the handy ordering of pairs (two element tuples) in Python). Such a tuple basically corresponds to std::map::value_type.</p> <p>Yes, there's Python's bisect module, and while that is logarithmic at insertion time in the same way that self-balancing binary trees are logarithmic at insertion time (right?), frankly I just want an object. Called OrderedDict or something (and no, the Python 3.1 OrderedDict doesn't qualify -- that's for 'insertion-time' ordering -- and frankly what insertion-time ordering has to do with ordering is not quite obvious).</p> <p>Note, a key-ordered dictionary is highly useful in many industries (in finance for instance, it's ordinary to keep track of price books of data, which are basically ordered dictionaries of price -> quantity, aggregated order information, etc.). </p> <p>If anyone has any other ideas, that's great. All I know is I just got five million times smarter by Alex Martelli's 'answers' here. So I thought I'd ask.</p>
6
2009-09-29T07:14:53Z
1,491,109
<p>As you said, you can roll your own implementation with bisect:</p> <pre><code>class OrderedDict: def __init__(self, keyvalues_iter): self.__srtlst__ = sorted(keyvalues_iter) def __len__(self): return len(self.__srtlst__) def __contains__(self, key): index = bisect(self.__srtlst__, key) if index&lt;len(self.__srtlst__) and self.__srtlst__[index][0] == key: return True else: return False def __getitem__(self, key): index = bisect(self.__srtlst__, key) if index&lt;len(self.__srtlst__) and self.__srtlst__[index][0] == key: return self.__srtlst__[index][1] else: raise KeyError(key) def __setitem__(sekf, key, value): index = bisect(self.__srtlst__, key) if index&lt;len(self.__srtlst__) and self.__srtlst__[index][0] == key: self.__srtlst__[index][1] = value else: self.__srtlst__[index]=(key, value) def __delitem__(sekf, key, value): index = bisect(self.__srtlst__, key) if index&lt;len(self.__srtlst__) and self.__srtlst__[index][0] == key: del __srtlst__[index] else: raise KeyError(key) def __iter__(self): return (v for k,v in self.__srtlst__) def clear(self): self.__srtlst__ = [] def get(self, key, default=None): index = bisect(self.__srtlst__, key) if index&lt;len(self.__srtlst__) and self.__srtlst__[index][0] == key: return self.__srtlst__[index][1] else: return default def items(self): return self.__srtlst__[:] def iteritems(self): return iter(self.__srtlst__) def iterkeys(self): return (k for k,v in self.__srtlst__) def itervalues(self): return (v for k,v in self.__srtlst__) def keys(self): return [k for k,v in self.__srtlst__] def values(self): return [v for k,v in self.__srtlst__] def setdefault(self, key, default): index = bisect(self.__srtlst__, key) if index&lt;len(self.__srtlst__) and self.__srtlst__[index][0] == key: return self.__srtlst__[index][1] else: self.__srtlst__[index]=(key, default) return default def update(self, other): #a more efficient implementation could be done merging the sorted lists for k, v in other.iteritems(): self[k] = v </code></pre> <p>hmmm... it seems that I already did that for you, d'oh!</p>
-1
2009-09-29T07:48:42Z
[ "python", "dictionary" ]
Mapping std::map to Python
1,491,037
<p>Sometimes it makes sense to have a key-ordered dictionary. In C++, this is often implemented with a Red-black tree. But any self-balancing binary search tree will do (fwiw, Knuth is particularly clear on this subject). The best solution I've been able to come up with so far is to take <a href="http://sourceforge.net/projects/pyavl/">R. McGraw's AVL-tree type</a> and create a wrapper class that basically implements the STL map interface (also counting on the handy ordering of pairs (two element tuples) in Python). Such a tuple basically corresponds to std::map::value_type.</p> <p>Yes, there's Python's bisect module, and while that is logarithmic at insertion time in the same way that self-balancing binary trees are logarithmic at insertion time (right?), frankly I just want an object. Called OrderedDict or something (and no, the Python 3.1 OrderedDict doesn't qualify -- that's for 'insertion-time' ordering -- and frankly what insertion-time ordering has to do with ordering is not quite obvious).</p> <p>Note, a key-ordered dictionary is highly useful in many industries (in finance for instance, it's ordinary to keep track of price books of data, which are basically ordered dictionaries of price -> quantity, aggregated order information, etc.). </p> <p>If anyone has any other ideas, that's great. All I know is I just got five million times smarter by Alex Martelli's 'answers' here. So I thought I'd ask.</p>
6
2009-09-29T07:14:53Z
1,491,476
<p>Lists are a miserable substitute for a tree.</p> <p>Insertions need to move the whole list around to make space; deletions need to move the list back down. Adding or deleting stuff in batch is fine when it's possible, but it's very often not, or takes unnatural contortions to arrange it. A fundamental attribute of a tree is that insertions and deletions are O(log n); no amount of handwaving will turn O(n) into O(log n).</p> <p>Inserting an item into a tree when you already know where it's going to go is O(1). Equivalently, deleting an item from a tree based on its node is also O(1). std::map supports both of these. These are both O(n) with a list.</p> <p>Another fundamental property of a tree is that iterating over a range of values is O(1) per iteration. Combining list and dict loses this, because each iteration needs to do a dict lookup. (The list-of-tuples approach doesn't have this problem.)</p> <p>Trees are among the most basic of data types. Python's lack of a tree container type is a wart. Maybe there's a third-party library implementing one (eg. the one linked by Mr. "Unknown", which I havn't tried so I can't vouch for), but there's no standard Python type for it.</p>
1
2009-09-29T09:23:37Z
[ "python", "dictionary" ]
Mapping std::map to Python
1,491,037
<p>Sometimes it makes sense to have a key-ordered dictionary. In C++, this is often implemented with a Red-black tree. But any self-balancing binary search tree will do (fwiw, Knuth is particularly clear on this subject). The best solution I've been able to come up with so far is to take <a href="http://sourceforge.net/projects/pyavl/">R. McGraw's AVL-tree type</a> and create a wrapper class that basically implements the STL map interface (also counting on the handy ordering of pairs (two element tuples) in Python). Such a tuple basically corresponds to std::map::value_type.</p> <p>Yes, there's Python's bisect module, and while that is logarithmic at insertion time in the same way that self-balancing binary trees are logarithmic at insertion time (right?), frankly I just want an object. Called OrderedDict or something (and no, the Python 3.1 OrderedDict doesn't qualify -- that's for 'insertion-time' ordering -- and frankly what insertion-time ordering has to do with ordering is not quite obvious).</p> <p>Note, a key-ordered dictionary is highly useful in many industries (in finance for instance, it's ordinary to keep track of price books of data, which are basically ordered dictionaries of price -> quantity, aggregated order information, etc.). </p> <p>If anyone has any other ideas, that's great. All I know is I just got five million times smarter by Alex Martelli's 'answers' here. So I thought I'd ask.</p>
6
2009-09-29T07:14:53Z
1,491,569
<p>For a list that stays sorted, you can try module heapq.</p>
0
2009-09-29T09:45:41Z
[ "python", "dictionary" ]
Mapping std::map to Python
1,491,037
<p>Sometimes it makes sense to have a key-ordered dictionary. In C++, this is often implemented with a Red-black tree. But any self-balancing binary search tree will do (fwiw, Knuth is particularly clear on this subject). The best solution I've been able to come up with so far is to take <a href="http://sourceforge.net/projects/pyavl/">R. McGraw's AVL-tree type</a> and create a wrapper class that basically implements the STL map interface (also counting on the handy ordering of pairs (two element tuples) in Python). Such a tuple basically corresponds to std::map::value_type.</p> <p>Yes, there's Python's bisect module, and while that is logarithmic at insertion time in the same way that self-balancing binary trees are logarithmic at insertion time (right?), frankly I just want an object. Called OrderedDict or something (and no, the Python 3.1 OrderedDict doesn't qualify -- that's for 'insertion-time' ordering -- and frankly what insertion-time ordering has to do with ordering is not quite obvious).</p> <p>Note, a key-ordered dictionary is highly useful in many industries (in finance for instance, it's ordinary to keep track of price books of data, which are basically ordered dictionaries of price -> quantity, aggregated order information, etc.). </p> <p>If anyone has any other ideas, that's great. All I know is I just got five million times smarter by Alex Martelli's 'answers' here. So I thought I'd ask.</p>
6
2009-09-29T07:14:53Z
4,936,985
<p>I stumbled on this question needing an OrderedMap myself, and found to my horror that the accepted answer is complete garbage. So I rolled my own, in case anyone finds it useful:</p> <pre><code>from bisect import * class OrderedMap: """Much less efficient than a dict, but keys don't need to be hashable.""" __default_arg = object() def __init__(self, keyvalues_iter = None): self.clear() if keyvalues_iter is not None: self.update(keyvalues_iter) def clear(self): self.__keys = [] self.__values = [] def __index(self, key): if self.__keys: index = bisect(self.__keys, key)-1 if self.__keys[index] == key: return index raise KeyError(key) def __len__(self): return len(self.__keys) def __contains__(self, key): try: self.__index(key) return True except KeyError: return False def __getitem__(self, key): index = self.__index(key) return self.__values[index] def __setitem__(self, key, value): try: index = self.__index(key) # exists self.__values[index] = value except KeyError: # new index = bisect(self.__keys, key) self.__keys.insert(index, key) self.__values.insert(index, value) def __delitem__(self, key): index = self.__index(key) self.__keys.pop(index) self.__values.pop(index) def __iter__(self): return iter(self.__keys) def get(self, key, default=__default_arg): try: return self[key] except KeyError: if default != OrderedMap.__default_arg: return default raise def setdefault(self, key, default = None): try: return self[key] except KeyError: if default != OrderedMap.__default_arg: self[key] = default return default raise def items(self): return zip(self.__keys, self.__values) def iteritems(self): return iter((self.__keys[x], self.__values[x]) for x in xrange(len(self))) def keys(self): return self.__keys[:] def iterkeys(self): return iter(self.__keys) def values(self): return self.__values[:] def itervalues(self): return iter(self.__values) def update(self, other): for k, v in other.iteritems(): self[k] = v def __repr__(self): s = ", ".join("%s: %s" % (repr(self.__keys[x]), repr(self.__values[x])) for x in xrange(len(self))) return "OrderedMap{%s}" % (s,) </code></pre>
1
2011-02-08T18:45:00Z
[ "python", "dictionary" ]
Mapping std::map to Python
1,491,037
<p>Sometimes it makes sense to have a key-ordered dictionary. In C++, this is often implemented with a Red-black tree. But any self-balancing binary search tree will do (fwiw, Knuth is particularly clear on this subject). The best solution I've been able to come up with so far is to take <a href="http://sourceforge.net/projects/pyavl/">R. McGraw's AVL-tree type</a> and create a wrapper class that basically implements the STL map interface (also counting on the handy ordering of pairs (two element tuples) in Python). Such a tuple basically corresponds to std::map::value_type.</p> <p>Yes, there's Python's bisect module, and while that is logarithmic at insertion time in the same way that self-balancing binary trees are logarithmic at insertion time (right?), frankly I just want an object. Called OrderedDict or something (and no, the Python 3.1 OrderedDict doesn't qualify -- that's for 'insertion-time' ordering -- and frankly what insertion-time ordering has to do with ordering is not quite obvious).</p> <p>Note, a key-ordered dictionary is highly useful in many industries (in finance for instance, it's ordinary to keep track of price books of data, which are basically ordered dictionaries of price -> quantity, aggregated order information, etc.). </p> <p>If anyone has any other ideas, that's great. All I know is I just got five million times smarter by Alex Martelli's 'answers' here. So I thought I'd ask.</p>
6
2009-09-29T07:14:53Z
11,381,235
<p>You might be looking for a SortedCollection: <a href="http://code.activestate.com/recipes/577197-sortedcollection/" rel="nofollow">http://code.activestate.com/recipes/577197-sortedcollection/</a></p>
1
2012-07-08T06:48:07Z
[ "python", "dictionary" ]
Mapping std::map to Python
1,491,037
<p>Sometimes it makes sense to have a key-ordered dictionary. In C++, this is often implemented with a Red-black tree. But any self-balancing binary search tree will do (fwiw, Knuth is particularly clear on this subject). The best solution I've been able to come up with so far is to take <a href="http://sourceforge.net/projects/pyavl/">R. McGraw's AVL-tree type</a> and create a wrapper class that basically implements the STL map interface (also counting on the handy ordering of pairs (two element tuples) in Python). Such a tuple basically corresponds to std::map::value_type.</p> <p>Yes, there's Python's bisect module, and while that is logarithmic at insertion time in the same way that self-balancing binary trees are logarithmic at insertion time (right?), frankly I just want an object. Called OrderedDict or something (and no, the Python 3.1 OrderedDict doesn't qualify -- that's for 'insertion-time' ordering -- and frankly what insertion-time ordering has to do with ordering is not quite obvious).</p> <p>Note, a key-ordered dictionary is highly useful in many industries (in finance for instance, it's ordinary to keep track of price books of data, which are basically ordered dictionaries of price -> quantity, aggregated order information, etc.). </p> <p>If anyone has any other ideas, that's great. All I know is I just got five million times smarter by Alex Martelli's 'answers' here. So I thought I'd ask.</p>
6
2009-09-29T07:14:53Z
25,988,280
<p>The Python <a href="http://www.grantjenks.com/docs/sortedcontainers/" rel="nofollow">sortedcontainers</a> module provides a <a href="http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html" rel="nofollow">SortedDict</a> data type for exactly these purposes. It uses a modified B-tree type data structure and is written in pure-Python. The module has 100% test coverage and hours of stress. Though pure-Python, it's faster that C-implementations and has a <a href="http://www.grantjenks.com/docs/sortedcontainers/performance.html" rel="nofollow">performance comparison</a> to back it up.</p> <p>Because it's pure-Python, installation is a breeze with pip:</p> <pre><code>pip install sortedcontainers </code></pre> <p>Then you simply:</p> <pre><code>from sortedcontainers import SortedDict help(SortedDict) </code></pre> <p>The <a href="http://www.grantjenks.com/docs/sortedcontainers/performance.html" rel="nofollow">performance comparison</a> includes a pretty comprehensive list of alternative implementations. It's worth a look.</p>
0
2014-09-23T06:28:09Z
[ "python", "dictionary" ]
deploying django to UserDir
1,491,102
<p>I would like to deploy my django pet-project on our student server. We have apache2 with UserDir mod and I don't have access to apache2 config files. How do I deploy? :-D</p> <p>I come from PHP background and I deploy my PHP scripts by uploading them to my <code>public_html</code> dir and everything shows up on <a href="http://ourserver.com/~myusername" rel="nofollow">http://ourserver.com/~myusername</a>. I read django documentation and it says I should add <code>&lt;Location&gt;some stuff&lt;/Location&gt;</code> to our apache config file. I don't have access to it, so I tried putting it in .htaccess in my <code>public_html</code> dir and that didn't work. I googled a lot and I think I read somewhere you can't put <code>&lt;Location&gt;</code> in .htaccess, but now I can't find that quote.</p> <p>So, anybody here deployed django to UserDir without harassing apache admins?</p> <p><strong>edit:</strong> I tested mod_python as Graham Dumpleton advised <a href="http://stackoverflow.com/questions/1491102/deploying-django-to-userdir/1496446#1496446">here</a>, and I can use mod_python without problems. Also, I found error log and here is what error log says when I put <code>&lt;Location&gt;some stuff&lt;/Location&gt;</code> in .htaccess:</p> <p><code>"[Thu Oct 01 21:33:19 2009] [alert] [client 188.129.74.66] /path/to/my/.htaccess: &lt;Location not allowed here"</code></p> <p>So, it seems like I really can't put <code>&lt;Location&gt;</code> into .htaccess. So, what are my options?</p>
0
2009-09-29T07:46:51Z
1,491,295
<p>Are <code>mod_python</code> or <code>mod_wsgi</code> enabled on the base Apache? You'll need that as a minimum.</p>
0
2009-09-29T08:36:33Z
[ "python", "django", "apache" ]
deploying django to UserDir
1,491,102
<p>I would like to deploy my django pet-project on our student server. We have apache2 with UserDir mod and I don't have access to apache2 config files. How do I deploy? :-D</p> <p>I come from PHP background and I deploy my PHP scripts by uploading them to my <code>public_html</code> dir and everything shows up on <a href="http://ourserver.com/~myusername" rel="nofollow">http://ourserver.com/~myusername</a>. I read django documentation and it says I should add <code>&lt;Location&gt;some stuff&lt;/Location&gt;</code> to our apache config file. I don't have access to it, so I tried putting it in .htaccess in my <code>public_html</code> dir and that didn't work. I googled a lot and I think I read somewhere you can't put <code>&lt;Location&gt;</code> in .htaccess, but now I can't find that quote.</p> <p>So, anybody here deployed django to UserDir without harassing apache admins?</p> <p><strong>edit:</strong> I tested mod_python as Graham Dumpleton advised <a href="http://stackoverflow.com/questions/1491102/deploying-django-to-userdir/1496446#1496446">here</a>, and I can use mod_python without problems. Also, I found error log and here is what error log says when I put <code>&lt;Location&gt;some stuff&lt;/Location&gt;</code> in .htaccess:</p> <p><code>"[Thu Oct 01 21:33:19 2009] [alert] [client 188.129.74.66] /path/to/my/.htaccess: &lt;Location not allowed here"</code></p> <p>So, it seems like I really can't put <code>&lt;Location&gt;</code> into .htaccess. So, what are my options?</p>
0
2009-09-29T07:46:51Z
1,496,042
<p>Would you be allowed to run your own long-running server process on some port other than 80? This might allow you to serve Django content either with a Django test server or your own copy of Apache with local configuration files.</p>
0
2009-09-30T03:54:36Z
[ "python", "django", "apache" ]
deploying django to UserDir
1,491,102
<p>I would like to deploy my django pet-project on our student server. We have apache2 with UserDir mod and I don't have access to apache2 config files. How do I deploy? :-D</p> <p>I come from PHP background and I deploy my PHP scripts by uploading them to my <code>public_html</code> dir and everything shows up on <a href="http://ourserver.com/~myusername" rel="nofollow">http://ourserver.com/~myusername</a>. I read django documentation and it says I should add <code>&lt;Location&gt;some stuff&lt;/Location&gt;</code> to our apache config file. I don't have access to it, so I tried putting it in .htaccess in my <code>public_html</code> dir and that didn't work. I googled a lot and I think I read somewhere you can't put <code>&lt;Location&gt;</code> in .htaccess, but now I can't find that quote.</p> <p>So, anybody here deployed django to UserDir without harassing apache admins?</p> <p><strong>edit:</strong> I tested mod_python as Graham Dumpleton advised <a href="http://stackoverflow.com/questions/1491102/deploying-django-to-userdir/1496446#1496446">here</a>, and I can use mod_python without problems. Also, I found error log and here is what error log says when I put <code>&lt;Location&gt;some stuff&lt;/Location&gt;</code> in .htaccess:</p> <p><code>"[Thu Oct 01 21:33:19 2009] [alert] [client 188.129.74.66] /path/to/my/.htaccess: &lt;Location not allowed here"</code></p> <p>So, it seems like I really can't put <code>&lt;Location&gt;</code> into .htaccess. So, what are my options?</p>
0
2009-09-29T07:46:51Z
1,496,446
<p>If mod_python installed, first see if you can actually use it without needing administrator to do anything. Read:</p> <p><a href="http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking" rel="nofollow">http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking</a></p> <p>Unless you are a trusted user or administrators don't know what they are doing, they shouldn't be allowing you to use mod_python because your code will run as Apache user and if anyone else also running applications same way, you could interfere with each others applications and data. In other words it isn't secure and shouldn't be used in shared hosting environments where multiple users on same Apache instance.</p> <p><hr /></p> <p>UPDATE 1</p> <p>On the basis that you now have mod_python working, you should be able to replace contents of mptest.py with something like:</p> <pre><code>import os os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import sys sys.path.insert(0, '/some/path/to/project/area/mysite') sys.path.insert(0, '/some/path/to/project/area') from django.core.handlers.modpython import handler as _handler def handler(req): req.get_options()['django.root'] = '/~myusername/mptest.py' return _handler(req) </code></pre> <p>Obviously, various paths and values in that should be changed per your naming.</p> <p>The site would be accessed as '/~myusername/mptest.py'.</p> <p>At this point you will find out silly using mod_python is where you don't have control of Apache. This is because when you change code in your site, you will need to ask the administrators to restart Apache for you for your changes to be picked up.</p> <p>Using mod_wsgi in its daemon mode with you as owner of daemon process would be much better, but if they are already running mod_python I wouldn't be recommending they load both modules at same time as mod_python issues screw up use of mod_wsgi in some cases and if they haven't installed Python properly, you are just likely to have lots of issues and so not worth the trouble.</p> <p>In short, using mod_python in shared hosting environment where you have no control of Apache is silly and insecure.</p> <p>All the same, have documented how to run Django out of per user directory as I don't think it has been documented anywhere previously.</p>
1
2009-09-30T06:43:19Z
[ "python", "django", "apache" ]
deploying django to UserDir
1,491,102
<p>I would like to deploy my django pet-project on our student server. We have apache2 with UserDir mod and I don't have access to apache2 config files. How do I deploy? :-D</p> <p>I come from PHP background and I deploy my PHP scripts by uploading them to my <code>public_html</code> dir and everything shows up on <a href="http://ourserver.com/~myusername" rel="nofollow">http://ourserver.com/~myusername</a>. I read django documentation and it says I should add <code>&lt;Location&gt;some stuff&lt;/Location&gt;</code> to our apache config file. I don't have access to it, so I tried putting it in .htaccess in my <code>public_html</code> dir and that didn't work. I googled a lot and I think I read somewhere you can't put <code>&lt;Location&gt;</code> in .htaccess, but now I can't find that quote.</p> <p>So, anybody here deployed django to UserDir without harassing apache admins?</p> <p><strong>edit:</strong> I tested mod_python as Graham Dumpleton advised <a href="http://stackoverflow.com/questions/1491102/deploying-django-to-userdir/1496446#1496446">here</a>, and I can use mod_python without problems. Also, I found error log and here is what error log says when I put <code>&lt;Location&gt;some stuff&lt;/Location&gt;</code> in .htaccess:</p> <p><code>"[Thu Oct 01 21:33:19 2009] [alert] [client 188.129.74.66] /path/to/my/.htaccess: &lt;Location not allowed here"</code></p> <p>So, it seems like I really can't put <code>&lt;Location&gt;</code> into .htaccess. So, what are my options?</p>
0
2009-09-29T07:46:51Z
1,506,113
<p>Have you tried using <code>&lt;Directory&gt;</code> instead of <code>&lt;Location&gt;</code>? If that isn't blocked by local policy you should be able to do something like this:</p> <pre><code>&lt;Directory /path/to/your/home/public_html&gt; # mod_python stuff here &lt;/Directory&gt; </code></pre> <p>I'd go with either <code>mod_wsgi</code> or <code>fastcgi</code> if you're on good terms with your admin. If that's the case, however, you should simply be able to give your admin the <code>mod_wsgi</code> config since it supports update-based reloading and running as an alternate user. He should be able to set it up to simply run a single wsgi file under your account - something like this, possibly with an <code>allow from all</code> depending on how security is configured:</p> <pre><code>&lt;Directory /home/you/public_html&gt; WSGIApplicationGroup PROJECT WSGIDaemonProcess YOU threads=15 processes=2 python-path=/home/YOU/.virtualenvs/PROJECT-env/lib/python2.6/site-packages WSGIProcessGroup YOUR_GROUP WSGIScriptAlias / /home/YOU/PROJECT/deploy/PROJECT.wsgi &lt;/Directory&gt; </code></pre> <p>As an aside, the above assumes the use of the awesome, highly-recommended <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a> and <a href="http://www.doughellmann.com/projects/virtualenvwrapper/" rel="nofollow">virtualenvwrapper</a> to create a local python sandbox in your home directory. This will massively simplify life running as a non-admin or when you have more than one project. If you don't use virtualenv the <code>python-path</code> above can be removed entirely.</p>
0
2009-10-01T19:59:52Z
[ "python", "django", "apache" ]
deploying django to UserDir
1,491,102
<p>I would like to deploy my django pet-project on our student server. We have apache2 with UserDir mod and I don't have access to apache2 config files. How do I deploy? :-D</p> <p>I come from PHP background and I deploy my PHP scripts by uploading them to my <code>public_html</code> dir and everything shows up on <a href="http://ourserver.com/~myusername" rel="nofollow">http://ourserver.com/~myusername</a>. I read django documentation and it says I should add <code>&lt;Location&gt;some stuff&lt;/Location&gt;</code> to our apache config file. I don't have access to it, so I tried putting it in .htaccess in my <code>public_html</code> dir and that didn't work. I googled a lot and I think I read somewhere you can't put <code>&lt;Location&gt;</code> in .htaccess, but now I can't find that quote.</p> <p>So, anybody here deployed django to UserDir without harassing apache admins?</p> <p><strong>edit:</strong> I tested mod_python as Graham Dumpleton advised <a href="http://stackoverflow.com/questions/1491102/deploying-django-to-userdir/1496446#1496446">here</a>, and I can use mod_python without problems. Also, I found error log and here is what error log says when I put <code>&lt;Location&gt;some stuff&lt;/Location&gt;</code> in .htaccess:</p> <p><code>"[Thu Oct 01 21:33:19 2009] [alert] [client 188.129.74.66] /path/to/my/.htaccess: &lt;Location not allowed here"</code></p> <p>So, it seems like I really can't put <code>&lt;Location&gt;</code> into .htaccess. So, what are my options?</p>
0
2009-09-29T07:46:51Z
2,067,690
<p>If mod_fcgi is configured, you can use that. See <a href="http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/" rel="nofollow">http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/</a></p>
0
2010-01-14T21:26:41Z
[ "python", "django", "apache" ]
Python WebkitGtk: How to respond to the default context menu items?
1,491,179
<p>The default context menu contains items like "Open link in new window" and "Download linked file", which don't seem to do anything. I obviously like to react on these items, but can't figure out how, since the port's documentation is a bit sparse. Does anybody know?</p>
2
2009-09-29T08:08:45Z
1,493,356
<p>In the C port, you have to connect to the '<code>create-web-view</code>', '<code>new-window-policy-decision-requested</code>', and '<code>download-requested</code>' signals. I think the Python port works the same way. See this page for the documentation on the C versions of those signals:</p> <p><a href="http://webkitgtk.org/reference/webkitgtk-WebKitWebView.html" rel="nofollow">http://webkitgtk.org/reference/webkitgtk-WebKitWebView.html</a></p>
2
2009-09-29T15:36:45Z
[ "python", "gtk", "webkit" ]
Python Regex "object has no attribute"
1,491,277
<p>I've been putting together a list of pages that we need to update with new content (we're switching media formats). In the process I'm cataloging pages that correctly have the new content. </p> <p>Here's the general idea of what I'm doing: </p> <ol> <li>Iterate through a file structure and get a list of files </li> <li>For each file read to a buffer and, using regex search, match a specific tag </li> <li>If matched, test 2 more regex matches </li> <li>write the resulting matches (one or the other) into a database </li> </ol> <p>Everything works fine up until the 3rd regex pattern match, where I get the following: </p> <p><code>'NoneType' object has no attribute 'group'</code></p> <pre><code># only interested in embeded content pattern = "(&lt;embed .*?&lt;/embed&gt;)" # matches content pointing to our old root pattern2 = 'data="(http://.*?/media/.*?")' # matches content pointing to our new root pattern3 = 'data="(http://.*?/content/.*?")' matches = re.findall(pattern, filebuffer) for match in matches: if len(match) &gt; 0: urla = re.search(pattern2, match) if urla.group(1) is not None: print filename, urla.group(1) urlb = re.search(pattern3, match) if urlb.group(1) is not None: print filename, urlb.group(1) </code></pre> <p>thank you.</p>
6
2009-09-29T08:32:01Z
1,491,439
<p>Your exception means that urla has a value of None. Since urla's value is determined by the re.search call, it follows that re.search returns None. And this happens when the string doesn't match the pattern.</p> <p>So basically you should use:</p> <pre><code>urla = re.search(pattern2, match) if urla is not None: print filename, urla.group(1) </code></pre> <p>instead of what you have now.</p>
15
2009-09-29T09:13:49Z
[ "python", "regex" ]
Python Regex "object has no attribute"
1,491,277
<p>I've been putting together a list of pages that we need to update with new content (we're switching media formats). In the process I'm cataloging pages that correctly have the new content. </p> <p>Here's the general idea of what I'm doing: </p> <ol> <li>Iterate through a file structure and get a list of files </li> <li>For each file read to a buffer and, using regex search, match a specific tag </li> <li>If matched, test 2 more regex matches </li> <li>write the resulting matches (one or the other) into a database </li> </ol> <p>Everything works fine up until the 3rd regex pattern match, where I get the following: </p> <p><code>'NoneType' object has no attribute 'group'</code></p> <pre><code># only interested in embeded content pattern = "(&lt;embed .*?&lt;/embed&gt;)" # matches content pointing to our old root pattern2 = 'data="(http://.*?/media/.*?")' # matches content pointing to our new root pattern3 = 'data="(http://.*?/content/.*?")' matches = re.findall(pattern, filebuffer) for match in matches: if len(match) &gt; 0: urla = re.search(pattern2, match) if urla.group(1) is not None: print filename, urla.group(1) urlb = re.search(pattern3, match) if urlb.group(1) is not None: print filename, urlb.group(1) </code></pre> <p>thank you.</p>
6
2009-09-29T08:32:01Z
1,491,448
<p>The reason for <code>TypeError</code> is that <code>search</code> or <code>match</code> usually return either a <code>MatchObject</code> or a <code>None</code>. Only one of these has a <code>group</code> method. And it's not a <code>None</code>. So you need to do:</p> <pre><code>url = re.search(pattern2, match) if url is not None: print(filename, url.group(0)) </code></pre> <p><strong>P.S.</strong> <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP-8</a> suggests using 4 spaces for indentation. It's not just an opinion, it's a good practice. Your code is fairly hard to read.</p>
2
2009-09-29T09:14:54Z
[ "python", "regex" ]
Python Regex "object has no attribute"
1,491,277
<p>I've been putting together a list of pages that we need to update with new content (we're switching media formats). In the process I'm cataloging pages that correctly have the new content. </p> <p>Here's the general idea of what I'm doing: </p> <ol> <li>Iterate through a file structure and get a list of files </li> <li>For each file read to a buffer and, using regex search, match a specific tag </li> <li>If matched, test 2 more regex matches </li> <li>write the resulting matches (one or the other) into a database </li> </ol> <p>Everything works fine up until the 3rd regex pattern match, where I get the following: </p> <p><code>'NoneType' object has no attribute 'group'</code></p> <pre><code># only interested in embeded content pattern = "(&lt;embed .*?&lt;/embed&gt;)" # matches content pointing to our old root pattern2 = 'data="(http://.*?/media/.*?")' # matches content pointing to our new root pattern3 = 'data="(http://.*?/content/.*?")' matches = re.findall(pattern, filebuffer) for match in matches: if len(match) &gt; 0: urla = re.search(pattern2, match) if urla.group(1) is not None: print filename, urla.group(1) urlb = re.search(pattern3, match) if urlb.group(1) is not None: print filename, urlb.group(1) </code></pre> <p>thank you.</p>
6
2009-09-29T08:32:01Z
1,496,037
<p>Please also note your mistaken assumption that the error was in the <em>third</em> match, when it was in fact in the second. This seems to have led to the mistaken assumption that the second match was doing something to invalidate the third, sending you way off track.</p>
0
2009-09-30T03:50:00Z
[ "python", "regex" ]
Python Regex "object has no attribute"
1,491,277
<p>I've been putting together a list of pages that we need to update with new content (we're switching media formats). In the process I'm cataloging pages that correctly have the new content. </p> <p>Here's the general idea of what I'm doing: </p> <ol> <li>Iterate through a file structure and get a list of files </li> <li>For each file read to a buffer and, using regex search, match a specific tag </li> <li>If matched, test 2 more regex matches </li> <li>write the resulting matches (one or the other) into a database </li> </ol> <p>Everything works fine up until the 3rd regex pattern match, where I get the following: </p> <p><code>'NoneType' object has no attribute 'group'</code></p> <pre><code># only interested in embeded content pattern = "(&lt;embed .*?&lt;/embed&gt;)" # matches content pointing to our old root pattern2 = 'data="(http://.*?/media/.*?")' # matches content pointing to our new root pattern3 = 'data="(http://.*?/content/.*?")' matches = re.findall(pattern, filebuffer) for match in matches: if len(match) &gt; 0: urla = re.search(pattern2, match) if urla.group(1) is not None: print filename, urla.group(1) urlb = re.search(pattern3, match) if urlb.group(1) is not None: print filename, urlb.group(1) </code></pre> <p>thank you.</p>
6
2009-09-29T08:32:01Z
5,692,616
<p>I got the same problem.</p> <p>Using python2.6, you can solve it in this way:</p> <pre> for match in matches: if len(match) > 0: urla = re.search(pattern2, match) try: urla.group(1): print filename, urla.group(1) excpet: print "Problem with",pattern2 urlb = re.search(pattern3, match) try: urlb.group(1) print filename, urlb.group(1) except: print "Problem with",pattern3 </pre>
2
2011-04-17T09:06:03Z
[ "python", "regex" ]
Telnet automation / scripting
1,491,494
<p>I have already checked <a href="http://stackoverflow.com/questions/709801/creating-a-script-for-a-telnet-session">This Question</a> but could not find what i'm looking for. I am running Windows (the client), and the server is a legacy mainframe type server.</p> <p>Basically I need to write a script, python code or whatever, to send some know commands to the server via telnet, and preferable capture the output. Then return when done.</p> <p>What's the best approach?</p>
5
2009-09-29T09:29:42Z
1,491,516
<p>There's a <a href="http://docs.python.org/library/telnetlib.html">python library for telnet</a> connections that reads and writes from/to a telnet connection.</p> <p>Check the link. It has some basic examples of what you are looking for.</p> <p>Here's an example from the link:</p> <pre><code>import getpass import sys import telnetlib HOST = "localhost" user = raw_input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.write("ls\n") tn.write("exit\n") print tn.read_all() </code></pre> <p>It connects to a telnet server. Sends your login credentials and then executes the unix command <code>ls</code>. Then exits the session and prints all output from the telnet server.</p>
15
2009-09-29T09:33:54Z
[ "python", "windows", "scripting", "automation", "telnet" ]