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
Can I damage the system by running time.sleep() with this newbie code in Python?
1,169,185
<p>Im sure there is a better way to do this, but I am quite the newbie so I did it the only way I could figure it out. The thing is, I have a script that updates a textfile with the newest posts from an RSS feed (I got some help from you guys to figure it out). But I want this script to be automated, so I made this:</p> <pre><code>import time import os seconds = 3600 kjor = 'python vg.py' time.sleep(seconds) os.system(kjor) time.sleep(seconds) os.system(kjor) time.sleep(seconds) os.system(kjor) </code></pre> <p>I continued with copying those 24x downwards. I know this problably can be done alot better with some loop (while?), but Im afraid I dont have alot of knowledge in that field (yet).</p> <p>My question, however, is as following: Can the system be damaged in any way if I let this run over a longer period of time?</p>
1
2009-07-23T01:53:46Z
1,169,195
<p>Use xrange please, don't copying your code 24x times.</p> <pre><code>for loop in xrange(240): time.sleep(seconds) os.system(kjor) </code></pre> <p>It will not damage your system, as far as I know.</p>
1
2009-07-23T01:57:53Z
[ "python", "while-loop" ]
Can I damage the system by running time.sleep() with this newbie code in Python?
1,169,185
<p>Im sure there is a better way to do this, but I am quite the newbie so I did it the only way I could figure it out. The thing is, I have a script that updates a textfile with the newest posts from an RSS feed (I got some help from you guys to figure it out). But I want this script to be automated, so I made this:</p> <pre><code>import time import os seconds = 3600 kjor = 'python vg.py' time.sleep(seconds) os.system(kjor) time.sleep(seconds) os.system(kjor) time.sleep(seconds) os.system(kjor) </code></pre> <p>I continued with copying those 24x downwards. I know this problably can be done alot better with some loop (while?), but Im afraid I dont have alot of knowledge in that field (yet).</p> <p>My question, however, is as following: Can the system be damaged in any way if I let this run over a longer period of time?</p>
1
2009-07-23T01:53:46Z
1,169,205
<p>To answer your question, no, this won't hurt anything. While the time.sleeps are sleeping, the program will take very little processing power and the rest of the system can run normally.</p> <p>Now, as for your looping issue. If you want the code run forever (or until you stop the program) the code you want is</p> <pre><code> while True: os.system(kjor) time.sleep(seconds) </code></pre> <p>This is, literally, and infinite loop, but in this case that (is probably) what you want.</p> <p>If you are attached to having a particular number of iterations, then you could do something like sunqiang's answer (repeated here)</p> <pre><code>for loop in xrange(240): os.system(kjor) time.sleep(seconds) </code></pre> <p>Finally, if you are on a Unix platform (such as Linux or Mac) you should take a look at cron, as it is designed to set up recurring programs to run and particular time periods. You could set it up to run your script every minute and it will happily do so until the end of time (or you remove it, whichever comes first).</p>
9
2009-07-23T02:04:56Z
[ "python", "while-loop" ]
Can I damage the system by running time.sleep() with this newbie code in Python?
1,169,185
<p>Im sure there is a better way to do this, but I am quite the newbie so I did it the only way I could figure it out. The thing is, I have a script that updates a textfile with the newest posts from an RSS feed (I got some help from you guys to figure it out). But I want this script to be automated, so I made this:</p> <pre><code>import time import os seconds = 3600 kjor = 'python vg.py' time.sleep(seconds) os.system(kjor) time.sleep(seconds) os.system(kjor) time.sleep(seconds) os.system(kjor) </code></pre> <p>I continued with copying those 24x downwards. I know this problably can be done alot better with some loop (while?), but Im afraid I dont have alot of knowledge in that field (yet).</p> <p>My question, however, is as following: Can the system be damaged in any way if I let this run over a longer period of time?</p>
1
2009-07-23T01:53:46Z
1,169,288
<p>It does not damage any system and it is pretty common as well.</p> <p>Just create a loop so as your application will gently stop running after some time; Or better yet, make it check for a condition, maybe listen to a tcp port waiting for someone to ask it to quit (then you'll need to create a second application to send this quit message).</p>
1
2009-07-23T02:34:25Z
[ "python", "while-loop" ]
Python Wiki Style Doc Generator
1,169,357
<p>Looking for something like PyDoc that can generate a set of Wiki style pages vs the current HTML ones that export out of PyDoc. I would like to be able to export these in Google Code's Wiki as an extension to the current docs up there now.</p>
3
2009-07-23T02:55:40Z
1,169,664
<p>Take a look at pydoc.TextDoc. If this contains too little markup, you can inherit from it and make it generate markup according to your wiki's syntax.</p>
1
2009-07-23T04:49:58Z
[ "python", "documentation", "wiki" ]
Python Wiki Style Doc Generator
1,169,357
<p>Looking for something like PyDoc that can generate a set of Wiki style pages vs the current HTML ones that export out of PyDoc. I would like to be able to export these in Google Code's Wiki as an extension to the current docs up there now.</p>
3
2009-07-23T02:55:40Z
1,170,041
<p>Have you taken a look at <a href="http://sphinx.pocoo.org/" rel="nofollow">Sphinx</a>?</p>
0
2009-07-23T06:51:10Z
[ "python", "documentation", "wiki" ]
Rearrange equations for solver
1,169,593
<p>I am looking for a generic python way to manipulate text into solvable equations.</p> <p>For example:</p> <p>there may be some constants to initialize</p> <pre><code>e1,e2=0.58,0.62 ma1,ma2=0.85,1.15 mw=0.8 Cpa,Cpw=1.023,4.193 dba,dbr=0.0,25.0 </code></pre> <p>and a set of equations (written here for readability rather than the solver)</p> <pre><code>Q=e1*ma1*Cpa*(tw1-dba) Q=ma1*Cpa*(dbs-dba) Q=mw*Cpw*(tw1-tw2) Q=e2*ma2*Cpa*(dbr-tw2) Q=ma2*Cpa*(dbr-dbo) </code></pre> <p>This leaves 5 unknowns, so presumably the system can be solved.</p> <pre><code>Q, dbo, dbr, tw1, tw2 </code></pre> <p>Actual systems are non-linear and much more complicated.</p> <p>I have already solved this easy example with scipy, Delphi, Sage... so I'm not looking for the solve part.</p> <p>The equations are typed directly into a text editor and I want a Python program to give me an array of unknowns and an array of error functions.</p> <pre><code>y = mysolver.fsolve(f, x) </code></pre> <p>So, for the above example</p> <pre><code>x=[Q,dbo,dbr,tw1,tw2] f=[Q-e1*ma1*Cpa*(tw1-dba), Q-ma1*Cpa*(dbs-dba), Q-mw*Cpw*(tw1-tw2), Q-e2*ma2*Cpa*(dbr-tw2), Q-ma2*Cpa*(dbr-dbo)] </code></pre> <p>I just don't know how to extract the unknowns and create the error functions.</p> <p>I tried the compile.parse() function and it seems to give a structured breakdown.</p> <p>Can anyone give some ideas on the best approach.</p>
1
2009-07-23T04:22:39Z
1,169,643
<p>If you don't want to write a parser for your own expression language, you can indeed try to use the Python syntax. Don't use the compiler module; instead, use some kind of abstract syntax. Since 2.5, you can use the _ast module:</p> <pre><code>py&gt; import _ast py&gt; tree = compile("e1,e2=0.58,0.62", "&lt;string&gt;", "exec", _ast.PyCF_ONLY_AST) py&gt; tree &lt;_ast.Module object at 0xb7cd5fac&gt; py&gt; tree.body[0] &lt;_ast.Assign object at 0xb7cd5fcc&gt; py&gt; tree.body[0].targets[0] &lt;_ast.Tuple object at 0xb7cd5fec&gt; py&gt; tree.body[0].targets[0].elts [&lt;_ast.Name object at 0xb7cd5e4c&gt;, &lt;_ast.Name object at 0xb7cd5f6c&gt;] py&gt; tree.body[0].targets[0].elts[0].id 'e1' py&gt; tree.body[0].targets[0].elts[1].id 'e2' </code></pre> <p>In earlier versions, you would have to use parser.suite, which gives you a concrete-syntax tree that is more difficult to process.</p>
1
2009-07-23T04:41:15Z
[ "python", "equation", "solver" ]
Rearrange equations for solver
1,169,593
<p>I am looking for a generic python way to manipulate text into solvable equations.</p> <p>For example:</p> <p>there may be some constants to initialize</p> <pre><code>e1,e2=0.58,0.62 ma1,ma2=0.85,1.15 mw=0.8 Cpa,Cpw=1.023,4.193 dba,dbr=0.0,25.0 </code></pre> <p>and a set of equations (written here for readability rather than the solver)</p> <pre><code>Q=e1*ma1*Cpa*(tw1-dba) Q=ma1*Cpa*(dbs-dba) Q=mw*Cpw*(tw1-tw2) Q=e2*ma2*Cpa*(dbr-tw2) Q=ma2*Cpa*(dbr-dbo) </code></pre> <p>This leaves 5 unknowns, so presumably the system can be solved.</p> <pre><code>Q, dbo, dbr, tw1, tw2 </code></pre> <p>Actual systems are non-linear and much more complicated.</p> <p>I have already solved this easy example with scipy, Delphi, Sage... so I'm not looking for the solve part.</p> <p>The equations are typed directly into a text editor and I want a Python program to give me an array of unknowns and an array of error functions.</p> <pre><code>y = mysolver.fsolve(f, x) </code></pre> <p>So, for the above example</p> <pre><code>x=[Q,dbo,dbr,tw1,tw2] f=[Q-e1*ma1*Cpa*(tw1-dba), Q-ma1*Cpa*(dbs-dba), Q-mw*Cpw*(tw1-tw2), Q-e2*ma2*Cpa*(dbr-tw2), Q-ma2*Cpa*(dbr-dbo)] </code></pre> <p>I just don't know how to extract the unknowns and create the error functions.</p> <p>I tried the compile.parse() function and it seems to give a structured breakdown.</p> <p>Can anyone give some ideas on the best approach.</p>
1
2009-07-23T04:22:39Z
1,181,358
<p>Actually, I've implemented exactly the same thing in python. I'm also familiar with the Eureka and the other programs you mentioned. You can see my implementation at xyzsolve.appspot.com (Sorry for the shameless plug). The implementation is in all python. I'll list the iterations the code went through: </p> <p>Iteration #0: Do a simple search a replace for each variable in the equation and replace the variable with its value. For example x * y would become 1.1 * 2.2 if the values of x and y are 1.1 and 2.2. After you get the transformed string, you can just use eval and put its value into the residual (or f vector, in your case). Scipy's fsolve/fmin function lets you pass additional arguments into your residual function, so make use of that. I.e. pass a dictionary that contains the index of each named variable. Your dict should contain something like {'x': 0, 'y':1} and then you can just do a search and replace for each equation. This works, but very slowly since you have to do a search-replace everytime the residual function is called.</p> <p>Iteration #1: Do the same as iteration #0, except replace variables with the x array element directly, so 'y' would become 'x[1]'. In fact you can do all this to generate a function string; something that looks like "def f(x): return x[0]+x[1], x[0] - x[1]". Then you can use the exec function in python to create the function to pass to fsolve/fmin. No speed hit and you can stop at this point if your equations are in the form of valid python syntax. You can't do much more with this approach if you want to support more extensive equation input format.</p> <p>Iteration #2: Implement a custom lexer and parser. This isn't as hard to do as it sounds. I used <a href="http://www.evanfosmark.com/2009/02/sexy-lexing-with-python/" rel="nofollow">http://www.evanfosmark.com/2009/02/sexy-lexing-with-python/</a> for the lexer. I created a recursive descent parser (this isn't hard at all, 100 or so lines of code) to parse each equation. This gives you complete flexibilty with the equation format. I just keep track of the variables, constants that occur on each side of the equation in separate lists. As the parser parses the equation, it builds a equation string that looks like 'var_000 + var_001 * var_002' and so on. Finally I just replace the 'var_000' with the appropriate index from the x vector. So 'var_000' becomes 'x[0]' and so on. If you want you can build an AST and do many more sophisticated transformations but I stopped here.</p> <p>Finally, you might also want to consider the type of input equations. There are quite a few innocuous non-linear equations that will not solve with fsolve (it uses MINPACK hybrdj). You probably also need a way to input initial guesses. </p> <p>I'd be interested to hear if there are any other alternative ways of doing this.</p>
2
2009-07-25T06:17:07Z
[ "python", "equation", "solver" ]
Comparing MD5s in Python
1,169,717
<p>For a programming exercise I designed for myself, and for use in a pretty non-secure system later on, I'm trying to compare MD5 hashes. The one that is stored in a plain text file and is pulled out by the <code>check_pw()</code> function and the one that is created from the submitted password from a CGI form. <code>md5_pw(</code>) is used to create all the hashes in the program. </p> <p>For some reason, <em>if <code>(pair[1] == md5_pw(pw))</code></em> <strong>always fails</strong>, even though my program prints out identical hashes in my error checking lines:</p> <blockquote> <pre><code> print "this is the pw from the file: ", pair[1], "&lt;br /&gt;" print "this is the md5 pw you entered: ", md5_pw(pw), "&lt;br /&gt;" </code></pre> </blockquote> <p><em>Where am I messing up?</em> </p> <p>Code:</p> <pre><code>def md5_pw(pw): """Returns the MD5 hex digest of the pw with addition.""" m = md5.new() m.update("4hJ2Yq7qdHd9sdjFASh9"+pw) return m.hexdigest() def check_pw(user, pw, pwfile): """Returns True if the username and password match, False otherwise. pwfile is a xxx.txt format.""" f = open(pwfile) for line in f: pair = line.split(":") print "this is the pw from the file: ", pair[1], "&lt;br /&gt;" print "this is the md5 pw you entered: ", md5_pw(pw), "&lt;br /&gt;" if (pair[0] == user): print "user matched &lt;br /&gt;" if (pair[1] == md5_pw(pw)): f.close() return True else: f.close() print "passmatch a failure" return False </code></pre>
0
2009-07-23T05:14:31Z
1,169,734
<p>Your <code>pair[1]</code> probably has a trailing newline. Try:</p> <pre><code>for line in f: line = line.rstrip() pair = line.split(":") # ...etc </code></pre>
2
2009-07-23T05:19:10Z
[ "python", "md5" ]
Comparing MD5s in Python
1,169,717
<p>For a programming exercise I designed for myself, and for use in a pretty non-secure system later on, I'm trying to compare MD5 hashes. The one that is stored in a plain text file and is pulled out by the <code>check_pw()</code> function and the one that is created from the submitted password from a CGI form. <code>md5_pw(</code>) is used to create all the hashes in the program. </p> <p>For some reason, <em>if <code>(pair[1] == md5_pw(pw))</code></em> <strong>always fails</strong>, even though my program prints out identical hashes in my error checking lines:</p> <blockquote> <pre><code> print "this is the pw from the file: ", pair[1], "&lt;br /&gt;" print "this is the md5 pw you entered: ", md5_pw(pw), "&lt;br /&gt;" </code></pre> </blockquote> <p><em>Where am I messing up?</em> </p> <p>Code:</p> <pre><code>def md5_pw(pw): """Returns the MD5 hex digest of the pw with addition.""" m = md5.new() m.update("4hJ2Yq7qdHd9sdjFASh9"+pw) return m.hexdigest() def check_pw(user, pw, pwfile): """Returns True if the username and password match, False otherwise. pwfile is a xxx.txt format.""" f = open(pwfile) for line in f: pair = line.split(":") print "this is the pw from the file: ", pair[1], "&lt;br /&gt;" print "this is the md5 pw you entered: ", md5_pw(pw), "&lt;br /&gt;" if (pair[0] == user): print "user matched &lt;br /&gt;" if (pair[1] == md5_pw(pw)): f.close() return True else: f.close() print "passmatch a failure" return False </code></pre>
0
2009-07-23T05:14:31Z
1,169,776
<p>My guess is that there's an problem with the file loading/parsing, most likely caused by a newline character. By paring your code down, I was able to find that your logic was sound:</p> <pre><code>def md5_pw(pw): m = md5.new() m.update("4hJ2Yq7qdHd9sdjFASh9"+pw) return m.hexdigest() def check_pw(pw): pair = ("c317db7d54073ef5d345d6dd8b2c51e6") if (pair == md5_pw(pw)): return True else: return False &gt;&gt;&gt; import md5 &gt;&gt;&gt; check_pw('fakepw') False &gt;&gt;&gt; check_pw('testpw') True </code></pre> <p>("c317db7d54073ef5d345d6dd8b2c51e6" is the md5 hash for "4hJ2Yq7qdHd9sdjFASh9testpw")</p>
1
2009-07-23T05:31:55Z
[ "python", "md5" ]
Adding Values From Tuples of Same Length
1,169,725
<p>In a graphical program I'm writing using pygame I use a tuple representing a coordinate like this: (50, 50).</p> <p>Sometimes, I call a function which returns another tuple such as (3, -5), which represents the change in coordinate.</p> <p>What is the best way to add the change value to the coordinate value. It would be nice if I could do something like coordinate += change, but it appears that would simply concatenate the two tuples to something like (50, 50, 3, -5). Rather than adding the 1st value to the 1st value and the 2nd to the 2nd, and returning a resulting tuple.</p> <p>Until now I've been using this rather tiresome method: coord = (coord[0] + change[0], coord[1] + change[1])</p> <p>What is a better, more concise method to add together the values of two tuples of the same length. It seems especially important to know how to do it if the tuples are of an arbitrary length or a particularly long length that would make the previous method even more tiresome.</p>
10
2009-07-23T05:15:44Z
1,169,738
<p>My two cents, hope this helps</p> <pre><code>&gt;&gt;&gt; coord = (50, 50) &gt;&gt;&gt; change = (3, -5) &gt;&gt;&gt; tuple(sum(item) for item in zip(coord, change)) (53, 45) </code></pre>
1
2009-07-23T05:20:34Z
[ "python" ]
Adding Values From Tuples of Same Length
1,169,725
<p>In a graphical program I'm writing using pygame I use a tuple representing a coordinate like this: (50, 50).</p> <p>Sometimes, I call a function which returns another tuple such as (3, -5), which represents the change in coordinate.</p> <p>What is the best way to add the change value to the coordinate value. It would be nice if I could do something like coordinate += change, but it appears that would simply concatenate the two tuples to something like (50, 50, 3, -5). Rather than adding the 1st value to the 1st value and the 2nd to the 2nd, and returning a resulting tuple.</p> <p>Until now I've been using this rather tiresome method: coord = (coord[0] + change[0], coord[1] + change[1])</p> <p>What is a better, more concise method to add together the values of two tuples of the same length. It seems especially important to know how to do it if the tuples are of an arbitrary length or a particularly long length that would make the previous method even more tiresome.</p>
10
2009-07-23T05:15:44Z
1,169,760
<p>List comprehension is probably more readable, but here's another way:</p> <pre><code>&gt;&gt;&gt; a = (1,2) &gt;&gt;&gt; b = (3,4) &gt;&gt;&gt; tuple(map(sum,zip(a,b))) (4,6) </code></pre>
10
2009-07-23T05:26:00Z
[ "python" ]
Adding Values From Tuples of Same Length
1,169,725
<p>In a graphical program I'm writing using pygame I use a tuple representing a coordinate like this: (50, 50).</p> <p>Sometimes, I call a function which returns another tuple such as (3, -5), which represents the change in coordinate.</p> <p>What is the best way to add the change value to the coordinate value. It would be nice if I could do something like coordinate += change, but it appears that would simply concatenate the two tuples to something like (50, 50, 3, -5). Rather than adding the 1st value to the 1st value and the 2nd to the 2nd, and returning a resulting tuple.</p> <p>Until now I've been using this rather tiresome method: coord = (coord[0] + change[0], coord[1] + change[1])</p> <p>What is a better, more concise method to add together the values of two tuples of the same length. It seems especially important to know how to do it if the tuples are of an arbitrary length or a particularly long length that would make the previous method even more tiresome.</p>
10
2009-07-23T05:15:44Z
1,169,769
<p>Well, one way would be</p> <pre><code>coord = tuple(sum(x) for x in zip(coord, change)) </code></pre> <p>If you are doing a lot of math, you may want to investigate using <a href="http://numpy.scipy.org/">NumPy</a>, which has much more powerful array support and better performance.</p>
13
2009-07-23T05:29:15Z
[ "python" ]
Adding Values From Tuples of Same Length
1,169,725
<p>In a graphical program I'm writing using pygame I use a tuple representing a coordinate like this: (50, 50).</p> <p>Sometimes, I call a function which returns another tuple such as (3, -5), which represents the change in coordinate.</p> <p>What is the best way to add the change value to the coordinate value. It would be nice if I could do something like coordinate += change, but it appears that would simply concatenate the two tuples to something like (50, 50, 3, -5). Rather than adding the 1st value to the 1st value and the 2nd to the 2nd, and returning a resulting tuple.</p> <p>Until now I've been using this rather tiresome method: coord = (coord[0] + change[0], coord[1] + change[1])</p> <p>What is a better, more concise method to add together the values of two tuples of the same length. It seems especially important to know how to do it if the tuples are of an arbitrary length or a particularly long length that would make the previous method even more tiresome.</p>
10
2009-07-23T05:15:44Z
1,169,959
<p>This is a work in progress as I am learning Python myself. Can we use classes here, could simplify some operations later. I propose to use a coord class to store the coordinates. It would override add and sub so you could do addition and subtraction by simply using operators + and -. You could get the tuple representation with a function built into it.</p> <p><strong>Class</strong></p> <pre><code>class coord(object): def __init__(self,x,y): self.x = x self.y = y def __add__(self,c): return coord(self.x + c.x, self.y + c.y) def __sub__(self,c): return coord(self.x - c.x, self.y - c.y) def __eq__(self,c): #compares two coords return self.x == c.x and self.y == c.y def t(self): #return a tuple representation. return (self.x,self.y) </code></pre> <p><strong>Usage</strong></p> <pre><code>c1 = coord(4,3) #init coords c2 = coord(3,4) c3 = c1 + c2 #summing two coordinates. calls the overload __add__ print c3.t() #prints (7, 7) c3 = c3 - c1 print c3.t() #prints (3, 4) print c3 == c2 #prints True </code></pre> <p>you could improve coord to extend other operators as well (less than, greater than ..).</p> <p>In this version after doing your calculations you can call the pygame methods expecting tuples by just saying coord.t(). There might be a better way than have a function to return the tuple form though. </p>
3
2009-07-23T06:29:15Z
[ "python" ]
Adding Values From Tuples of Same Length
1,169,725
<p>In a graphical program I'm writing using pygame I use a tuple representing a coordinate like this: (50, 50).</p> <p>Sometimes, I call a function which returns another tuple such as (3, -5), which represents the change in coordinate.</p> <p>What is the best way to add the change value to the coordinate value. It would be nice if I could do something like coordinate += change, but it appears that would simply concatenate the two tuples to something like (50, 50, 3, -5). Rather than adding the 1st value to the 1st value and the 2nd to the 2nd, and returning a resulting tuple.</p> <p>Until now I've been using this rather tiresome method: coord = (coord[0] + change[0], coord[1] + change[1])</p> <p>What is a better, more concise method to add together the values of two tuples of the same length. It seems especially important to know how to do it if the tuples are of an arbitrary length or a particularly long length that would make the previous method even more tiresome.</p>
10
2009-07-23T05:15:44Z
1,170,017
<p>To get your "+" and "+=" behaviour you can define your own class and implement the <code>__add__()</code> method. The following is an incomplete sample:</p> <pre><code># T.py class T(object): def __init__(self, *args): self._t = args def __add__(self, other): return T(*([sum(x) for x in zip(self._t, other._t)])) def __str__(self): return str(self._t) def __repr__(self): return repr(self._t) &gt;&gt;&gt; from T import T &gt;&gt;&gt; a = T(50, 50) &gt;&gt;&gt; b = T(3, -5) &gt;&gt;&gt; a (50, 50) &gt;&gt;&gt; b (3, -5) &gt;&gt;&gt; a+b (53, 45) &gt;&gt;&gt; a+=b &gt;&gt;&gt; a (53, 45) &gt;&gt;&gt; a = T(50, 50, 50) &gt;&gt;&gt; b = T(10, -10, 10) &gt;&gt;&gt; a+b (60, 40, 60) &gt;&gt;&gt; a+b+b (70, 30, 70) </code></pre> <p><strong>EDIT: I've found a better way...</strong></p> <p>Define class T as a subclass of tuple and override the <code>__new__</code> and <code>__add__</code> methods. This provides the same interface as class <code>tuple</code> (but with different behaviour for <code>__add__</code>), so instances of class T can be passed to anything that expects a tuple.</p> <pre><code>class T(tuple): def __new__(cls, *args): return tuple.__new__(cls, args) def __add__(self, other): return T(*([sum(x) for x in zip(self, other)])) def __sub__(self, other): return self.__add__(-i for i in other) &gt;&gt;&gt; a = T(50, 50) &gt;&gt;&gt; b = T(3, -5) &gt;&gt;&gt; a (50, 50) &gt;&gt;&gt; b (3, -5) &gt;&gt;&gt; a+b (53, 45) &gt;&gt;&gt; a+=b &gt;&gt;&gt; a (53, 45) &gt;&gt;&gt; a = T(50, 50, 50) &gt;&gt;&gt; b = T(10, -10, 10) &gt;&gt;&gt; a+b (60, 40, 60) &gt;&gt;&gt; a+b+b (70, 30, 70) &gt;&gt;&gt; &gt;&gt;&gt; c = a + b &gt;&gt;&gt; c[0] 60 &gt;&gt;&gt; c[-1] 60 &gt;&gt;&gt; for x in c: ... print x ... 60 40 60 </code></pre>
3
2009-07-23T06:41:13Z
[ "python" ]
Bug with Python UTF-16 output and Windows line endings?
1,169,742
<p>With this code:</p> <p><strong>test.py</strong></p> <pre><code>import sys import codecs sys.stdout = codecs.getwriter('utf-16')(sys.stdout) print "test1" print "test2" </code></pre> <p>Then I run it as:</p> <pre><code>test.py &gt; test.txt </code></pre> <p>In Python 2.6 on Windows 2000, I'm finding that the newline characters are being output as the byte sequence <strong><code>\x0D\x0A\x00</code></strong> which of course is wrong for UTF-16.</p> <p>Am I missing something, or is this a bug?</p>
2
2009-07-23T05:21:50Z
1,169,911
<p>The newline translation is happening inside the stdout file. You're writing "test1\n" to sys.stdout (a StreamWriter). StreamWriter translates this to "t\x00e\x00s\x00t\x001\x00\n\x00", and sends it to the real file, the original sys.stderr.</p> <p>That file doesn't know that you've converted the data to UTF-16; all it knows is that any \n values in the output stream need to be converted to \x0D\x0A, which results in the output you're seeing.</p>
3
2009-07-23T06:15:35Z
[ "python", "windows", "utf-16" ]
Bug with Python UTF-16 output and Windows line endings?
1,169,742
<p>With this code:</p> <p><strong>test.py</strong></p> <pre><code>import sys import codecs sys.stdout = codecs.getwriter('utf-16')(sys.stdout) print "test1" print "test2" </code></pre> <p>Then I run it as:</p> <pre><code>test.py &gt; test.txt </code></pre> <p>In Python 2.6 on Windows 2000, I'm finding that the newline characters are being output as the byte sequence <strong><code>\x0D\x0A\x00</code></strong> which of course is wrong for UTF-16.</p> <p>Am I missing something, or is this a bug?</p>
2
2009-07-23T05:21:50Z
1,170,342
<p>I've found two solutions so far, but not one that gives output of UTF-16 <strong>with</strong> Windows-style line endings.</p> <p>First, to redirect Python <strong><code>print</code></strong> statements to a file with UTF-16 encoding (output Unix style line-endings):</p> <pre><code>import sys import codecs sys.stdout = codecs.open("outputfile.txt", "w", encoding="utf16") print "test1" print "test2" </code></pre> <p>Second, to redirect to <strong><code>stdout</code></strong> with UTF-16 encoding, without line-ending translation corruption (output Unix style line-endings) (thanks to <a href="http://code.activestate.com/recipes/65443/" rel="nofollow">this ActiveState recipe</a>):</p> <pre><code>import sys import codecs sys.stdout = codecs.getwriter('utf-16')(sys.stdout) if sys.platform == "win32": import os, msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) print "test1" print "test2" </code></pre>
0
2009-07-23T08:07:41Z
[ "python", "windows", "utf-16" ]
Bug with Python UTF-16 output and Windows line endings?
1,169,742
<p>With this code:</p> <p><strong>test.py</strong></p> <pre><code>import sys import codecs sys.stdout = codecs.getwriter('utf-16')(sys.stdout) print "test1" print "test2" </code></pre> <p>Then I run it as:</p> <pre><code>test.py &gt; test.txt </code></pre> <p>In Python 2.6 on Windows 2000, I'm finding that the newline characters are being output as the byte sequence <strong><code>\x0D\x0A\x00</code></strong> which of course is wrong for UTF-16.</p> <p>Am I missing something, or is this a bug?</p>
2
2009-07-23T05:21:50Z
1,170,469
<p>Try this:</p> <pre><code>import sys import codecs if sys.platform == "win32": import os, msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) class CRLFWrapper(object): def __init__(self, output): self.output = output def write(self, s): self.output.write(s.replace("\n", "\r\n")) def __getattr__(self, key): return getattr(self.output, key) sys.stdout = CRLFWrapper(codecs.getwriter('utf-16')(sys.stdout)) print "test1" print "test2" </code></pre>
3
2009-07-23T08:44:36Z
[ "python", "windows", "utf-16" ]
Profiling Python Scripts running on Mod_wsgi
1,169,833
<p>How can I profile a python script running on mod_wsgi on apache</p> <p>I would like to use cProfile but it seems it requires me to invoke a function manually. Is there a way to enable cProfile globally and have it keep on logging results. </p>
5
2009-07-23T05:52:07Z
1,169,914
<p>You need to wrap you wsgi application function inside another function that just calls your function using cProfile and use that as the application. Or you can reuse existing WSGI middleware to do that for you, for example <a href="http://repoze.org/repoze%5Fcomponents.html">repoze.profile</a> does pretty much what you seem to want.</p>
9
2009-07-23T06:16:45Z
[ "python", "profiling", "wsgi" ]
Profiling Python Scripts running on Mod_wsgi
1,169,833
<p>How can I profile a python script running on mod_wsgi on apache</p> <p>I would like to use cProfile but it seems it requires me to invoke a function manually. Is there a way to enable cProfile globally and have it keep on logging results. </p>
5
2009-07-23T05:52:07Z
1,177,812
<p>Here is the WSGI profile middleware for <a href="http://whiff.sourceforge.net" rel="nofollow">WHIFF</a> (currently only available from the mercurial repository): <a href="http://aaron.oirt.rutgers.edu/cgi-bin/whiffRepo.cgi/file/3929e9c62c84/whiff/middleware/profile.py" rel="nofollow">profile.py</a>. That should get you started. If you want to modify it to run outside of the WHIFF context change the line</p> <pre><code> gateway.putResource(env, resourcePath, report) </code></pre> <p>to something like</p> <pre><code> file("/tmp/profile.txt", "w").write(report) </code></pre>
0
2009-07-24T13:49:57Z
[ "python", "profiling", "wsgi" ]
Python 2 CSV writer produces wrong line terminator on Windows
1,170,214
<p>According to the <a href="http://docs.python.org/library/csv.html#csv.Dialect.lineterminator">its documentation</a> csv.writer should use '\r\n' as lineterminator by default.</p> <pre><code>import csv with open("test.csv", "w") as f: writer = csv.writer(f) rows = [(0,1,2,3,4), (-0,-1,-2,-3,-4), ("a","b","c","d","e"), ("A","B","C","D","E")] print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n") writer.writerows(rows) print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n") </code></pre> <p>This prints</p> <pre><code>\r\n \r\n </code></pre> <p>as expected. But, the created csv-file uses the lineterminator '\r\r\n'</p> <pre><code>0,1,2,3,4 0,-1,-2,-3,-4 a,b,c,d,e A,B,C,D,E </code></pre> <p>Is this a bug or is there something wrong in my usage of csv.writer?</p> <p>Python version:</p> <blockquote> <p>ActivePython 2.6.2.2 (ActiveState Software Inc.) based on Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on win32</p> </blockquote> <p>on Windows Vista</p>
31
2009-07-23T07:34:11Z
1,170,297
<p>In Python 2.x, always open your file in <strong>binary</strong> mode, as documented. <code>csv</code> writes <code>\r\n</code> as you expected, but then the underlying Windows text file mechanism cuts in and changes that <code>\n</code> to <code>\r\n</code> ... total effect: <code>\r\r\n</code></p> <p>From the <a href="http://docs.python.org/library/csv.html#csv.writer"><code>csv.writer</code></a> documentation:</p> <blockquote> <p>If <em>csvfile</em> is a file object, it must be opened with the <code>'b'</code> flag on platforms where that makes a difference.</p> </blockquote> <p>There seems to be some reticence about actually uttering the name of the main culprit :-)</p>
53
2009-07-23T07:53:18Z
[ "python", "windows", "csv", "python-2.x", "line-endings" ]
Python 2 CSV writer produces wrong line terminator on Windows
1,170,214
<p>According to the <a href="http://docs.python.org/library/csv.html#csv.Dialect.lineterminator">its documentation</a> csv.writer should use '\r\n' as lineterminator by default.</p> <pre><code>import csv with open("test.csv", "w") as f: writer = csv.writer(f) rows = [(0,1,2,3,4), (-0,-1,-2,-3,-4), ("a","b","c","d","e"), ("A","B","C","D","E")] print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n") writer.writerows(rows) print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n") </code></pre> <p>This prints</p> <pre><code>\r\n \r\n </code></pre> <p>as expected. But, the created csv-file uses the lineterminator '\r\r\n'</p> <pre><code>0,1,2,3,4 0,-1,-2,-3,-4 a,b,c,d,e A,B,C,D,E </code></pre> <p>Is this a bug or is there something wrong in my usage of csv.writer?</p> <p>Python version:</p> <blockquote> <p>ActivePython 2.6.2.2 (ActiveState Software Inc.) based on Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on win32</p> </blockquote> <p>on Windows Vista</p>
31
2009-07-23T07:34:11Z
11,235,483
<p>Unfortunately, it's a bit different with the csv module for Python 3, but this code will work on both Python 2 and Python 3:</p> <pre><code>if sys.version_info &gt;= (3,0,0): f = open(filename, 'w', newline='') else: f = open(filename, 'wb') </code></pre>
12
2012-06-27T22:08:27Z
[ "python", "windows", "csv", "python-2.x", "line-endings" ]
Python 2 CSV writer produces wrong line terminator on Windows
1,170,214
<p>According to the <a href="http://docs.python.org/library/csv.html#csv.Dialect.lineterminator">its documentation</a> csv.writer should use '\r\n' as lineterminator by default.</p> <pre><code>import csv with open("test.csv", "w") as f: writer = csv.writer(f) rows = [(0,1,2,3,4), (-0,-1,-2,-3,-4), ("a","b","c","d","e"), ("A","B","C","D","E")] print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n") writer.writerows(rows) print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n") </code></pre> <p>This prints</p> <pre><code>\r\n \r\n </code></pre> <p>as expected. But, the created csv-file uses the lineterminator '\r\r\n'</p> <pre><code>0,1,2,3,4 0,-1,-2,-3,-4 a,b,c,d,e A,B,C,D,E </code></pre> <p>Is this a bug or is there something wrong in my usage of csv.writer?</p> <p>Python version:</p> <blockquote> <p>ActivePython 2.6.2.2 (ActiveState Software Inc.) based on Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on win32</p> </blockquote> <p>on Windows Vista</p>
31
2009-07-23T07:34:11Z
31,418,457
<p>To change the line terminator in Python 2.7 csv writer use </p> <p><code>writer = csv.writer(f, delimiter = '|', lineterminator='\n')</code></p> <p>This is a much simpler way to change the default delimiter from \r\n.</p>
11
2015-07-14T22:24:24Z
[ "python", "windows", "csv", "python-2.x", "line-endings" ]
Duplicate django query set?
1,170,235
<p>I have a simple django's query set like:</p> <pre><code>qs = AModel.objects.exclude(state="F").order_by("order") </code></pre> <p>I'd like to use it as follows:</p> <pre><code>qs[0:3].update(state='F') expected = qs[3] # throws error here </code></pre> <p>But last statement throws: "Cannot update a query once a slice has been taken."</p> <p>How can I duplicate the query set?</p>
1
2009-07-23T07:37:58Z
1,170,288
<p>It's the first line throwing the error: you can't do qs[0:3].update(). qs[0:3] is taking a slice; update() is updating the query.</p> <p>update() is meant for bulk updates, resulting in SQL queries like</p> <pre><code>UPDATE app_model SET state = 'F' WHERE state &lt;&gt; 'F'; </code></pre> <p>You're trying to update the first three items according to "order", but that can't be done with this type of UPDATE--you can't order or limit an SQL UPDATE. It needs to be written differently, eg.</p> <pre><code>UPDATE app_model SET state = 'F' WHERE id IN ( SELECT id FROM app_model WHERE state &lt;&gt; 'F' ORDER BY order LIMIT 3 ) AS sub; </code></pre> <p>but Django can't do that for you.</p>
2
2009-07-23T07:51:07Z
[ "python", "django", "django-models" ]
Duplicate django query set?
1,170,235
<p>I have a simple django's query set like:</p> <pre><code>qs = AModel.objects.exclude(state="F").order_by("order") </code></pre> <p>I'd like to use it as follows:</p> <pre><code>qs[0:3].update(state='F') expected = qs[3] # throws error here </code></pre> <p>But last statement throws: "Cannot update a query once a slice has been taken."</p> <p>How can I duplicate the query set?</p>
1
2009-07-23T07:37:58Z
1,170,363
<p>There have been some talks about making it possible to do slices of a queryset and then be able to use update on them before, but AFAIK there have never been made anything. I don't think you can copy a slice of a queryset, but in this case you wont need to. If your order is an unique integer, you would be able to do this:</p> <pre><code>qs = AModel.objects.exclude(state="F").order_by("order") if len(qs) &gt; 3: slice = qs.exclude(order__gt=qs[3]) else: slice = qs slice.update(state='F') </code></pre> <p>I use exclude to remove the unwanted elements, but this will only work if the order is unique, else you wont be able to know how many you update. In case order is not unique it will still be possible using a second and unique arg in order:</p> <pre><code>qs = AModel.objects.exclude(state="F").order_by("order", "pk") if len(qs) &gt; 3: slice = qs.exclude(order__gt=qs[3]).exclude(order=qs[3], pk__gt=qs[3]) ... </code></pre>
0
2009-07-23T08:12:57Z
[ "python", "django", "django-models" ]
Duplicate django query set?
1,170,235
<p>I have a simple django's query set like:</p> <pre><code>qs = AModel.objects.exclude(state="F").order_by("order") </code></pre> <p>I'd like to use it as follows:</p> <pre><code>qs[0:3].update(state='F') expected = qs[3] # throws error here </code></pre> <p>But last statement throws: "Cannot update a query once a slice has been taken."</p> <p>How can I duplicate the query set?</p>
1
2009-07-23T07:37:58Z
2,529,522
<p>You can do this:</p> <p><code>qs = AModel.objects.filter(id__in= AModel.objects.exclude(state="F").order_by("order")[10]).update()</code></p>
1
2010-03-27T13:58:50Z
[ "python", "django", "django-models" ]
Problem running functions from a DLL file using ctypes in Object-oriented Python
1,170,372
<p>I sure hope this won't be an already answered question or a stupid one. Recently I've been programming with several instruments. Trying to communicate between them in order to create a testing program. However I've encoutered some problems with one specific instrument when I'm trying to call functions that I've "masked" out from the instruments DLL file. When I use the interactive python shell it works perfectly (although its alot of word clobbering). But when I implement the functions in a object-oriented manner the program fails, well actually it doesn't fail it just doesn't do anything. This is the first method that's called: (ctypes and ctypes.util is imported)</p> <pre><code> def init_hardware(self): """ Inits the instrument """ self.write_log("Initialising the automatic tuner") version_string = create_string_buffer(80) self.error_string = create_string_buffer(80) self.name = "Maury MT982EU" self.write_log("Tuner DLL path: %s", find_library('MLibTuners')) self.maury = WinDLL('MlibTuners') self.maury.get_tuner_driver_version(version_string) if (version_string.value == ""): self.write_log("IMPORTANT: Error obtaining the driver version") else: self.write_log("Version number of the DLL: %s" % version_string.value) self.ThreeTypeLong = c_long * 3 </code></pre> <p>Now that works swell, everything is perfect and I get perfect log-entries. But when I try to run a method further into the program called:</p> <pre><code>def add_tuner_and_controller(self, name, serial_number, tuner_number=0): """ Adds the tuner to the driver object, controller is inside the tuner """ self.write_log("Adding tuner %d and the built-in controller" % tuner_number) TempType = self.ThreeTypeLong() self.maury.add_controller(c_short(tuner_number), c_char_p(self.file_path), c_char_p(name), c_int(0), c_int(0), c_long(0), c_short(serial_number), self.error_string) self.maury.add_tuner(c_short(tuner_number), c_char_p(name), c_short(serial_number), c_short(0), c_short(1), pointer(c_double()), TempType, pointer(c_double()), pointer(c_double()), pointer(c_double()), self.error_string) </code></pre> <p>The program suddenly stops working/keeps running , nothing happenes when the "self.maury"-line is called. When I place everything in the init_hardware method it works perfectly so I'm guessing there's a slight memory "error" or something with the objective oriented structure. I really want it to remain this way, is there anyway to isolate the functions in this manner? or do I have to restrict myself to a big chunk of code?</p> <p><hr /></p> <p><strong>EDIT:</strong><br> <em>Documentation info</em>:<br> [Legend: The stars indicate pointers and the brackets indicate arrays]</p> <p><strong>The add_tuner function adds or updates one tuner in the tuner driver object.</strong></p> <pre><code>short add_tuner(short tuner_number, char model[ ], short serial_number, short ctlr_num, short ctlr_port, short *no_of_motors, long max_range[ ], double *fmin, double *fmax, double *fcrossover, char error_string[ ]) </code></pre> <p><strong>Output</strong>: <code>no_motors, max_range (array of three numbers), fmin, fmax, fcrossover,error_string (80+ characters long), function-return-&gt;Error flag</code></p> <p><br> <br> <strong>The add_controller function adds or updates one controller in the tuner driver object</strong></p> <pre><code>short add_controller(short controller_number, char driver[ ], char model[ ], int timeout, int address, long delay_ms, char error_string[ ]) </code></pre> <p><strong>Output</strong>: <code>error_string, function-return-&gt;Error flag</code></p>
2
2009-07-23T08:16:38Z
1,171,141
<p>I'm not sure about your exact problem, but here's a couple general tips:</p> <p>For those functions that you are calling outside of the constructor, I would strongly recommend setting their <a href="http://docs.python.org/library/ctypes.html#specifying-the-required-argument-types-function-prototypes" rel="nofollow"><code>argtypes</code></a> in the constructor as well. Once you've declared the <code>argtypes</code>, you shouldn't need to cast all the arguments as <code>c_short</code>, <code>c_double</code>, etc. Moreover, if you do accidentally pass an incorrect argument to a C function, Python will raise a runtime error instead of crashing within the DLL.</p> <p>Another minor detail, but you should be using <code>x = 0;</code> <a href="http://docs.python.org/library/ctypes.html#passing-pointers-or-passing-parameters-by-reference" rel="nofollow"><code>byref(x)</code></a> or maybe <a href="http://docs.python.org/library/ctypes.html#pointers" rel="nofollow"><code>POINTER</code></a><code>(c_double)()</code> instead of pointer(c_double()) in the tuner and controller.</p> <p>I've been writing some ctypes classes in Python 2.6 recently as well, and I haven't seen any issues like what you're describing. Since there apparently aren't any Python bug reports on that either, I strongly believe that there's just a minute detail that we are both overlooking in your method that is having a problem.</p>
1
2009-07-23T11:29:01Z
[ "python", "dll", "oop", "automation", "ctypes" ]
Problem running functions from a DLL file using ctypes in Object-oriented Python
1,170,372
<p>I sure hope this won't be an already answered question or a stupid one. Recently I've been programming with several instruments. Trying to communicate between them in order to create a testing program. However I've encoutered some problems with one specific instrument when I'm trying to call functions that I've "masked" out from the instruments DLL file. When I use the interactive python shell it works perfectly (although its alot of word clobbering). But when I implement the functions in a object-oriented manner the program fails, well actually it doesn't fail it just doesn't do anything. This is the first method that's called: (ctypes and ctypes.util is imported)</p> <pre><code> def init_hardware(self): """ Inits the instrument """ self.write_log("Initialising the automatic tuner") version_string = create_string_buffer(80) self.error_string = create_string_buffer(80) self.name = "Maury MT982EU" self.write_log("Tuner DLL path: %s", find_library('MLibTuners')) self.maury = WinDLL('MlibTuners') self.maury.get_tuner_driver_version(version_string) if (version_string.value == ""): self.write_log("IMPORTANT: Error obtaining the driver version") else: self.write_log("Version number of the DLL: %s" % version_string.value) self.ThreeTypeLong = c_long * 3 </code></pre> <p>Now that works swell, everything is perfect and I get perfect log-entries. But when I try to run a method further into the program called:</p> <pre><code>def add_tuner_and_controller(self, name, serial_number, tuner_number=0): """ Adds the tuner to the driver object, controller is inside the tuner """ self.write_log("Adding tuner %d and the built-in controller" % tuner_number) TempType = self.ThreeTypeLong() self.maury.add_controller(c_short(tuner_number), c_char_p(self.file_path), c_char_p(name), c_int(0), c_int(0), c_long(0), c_short(serial_number), self.error_string) self.maury.add_tuner(c_short(tuner_number), c_char_p(name), c_short(serial_number), c_short(0), c_short(1), pointer(c_double()), TempType, pointer(c_double()), pointer(c_double()), pointer(c_double()), self.error_string) </code></pre> <p>The program suddenly stops working/keeps running , nothing happenes when the "self.maury"-line is called. When I place everything in the init_hardware method it works perfectly so I'm guessing there's a slight memory "error" or something with the objective oriented structure. I really want it to remain this way, is there anyway to isolate the functions in this manner? or do I have to restrict myself to a big chunk of code?</p> <p><hr /></p> <p><strong>EDIT:</strong><br> <em>Documentation info</em>:<br> [Legend: The stars indicate pointers and the brackets indicate arrays]</p> <p><strong>The add_tuner function adds or updates one tuner in the tuner driver object.</strong></p> <pre><code>short add_tuner(short tuner_number, char model[ ], short serial_number, short ctlr_num, short ctlr_port, short *no_of_motors, long max_range[ ], double *fmin, double *fmax, double *fcrossover, char error_string[ ]) </code></pre> <p><strong>Output</strong>: <code>no_motors, max_range (array of three numbers), fmin, fmax, fcrossover,error_string (80+ characters long), function-return-&gt;Error flag</code></p> <p><br> <br> <strong>The add_controller function adds or updates one controller in the tuner driver object</strong></p> <pre><code>short add_controller(short controller_number, char driver[ ], char model[ ], int timeout, int address, long delay_ms, char error_string[ ]) </code></pre> <p><strong>Output</strong>: <code>error_string, function-return-&gt;Error flag</code></p>
2
2009-07-23T08:16:38Z
1,171,533
<p>Are any of the parameters in add-controller or add-tuner actually return values?</p> <p>Strongly recommend that you define prototypes of your functions, rather than calling them direct with casts of all the parameters.</p> <p><a href="http://docs.python.org/library/ctypes.html" rel="nofollow">I'm sure you've read this page already</a>, but the section you want to look at is Function Prototypes. Makes the code much cleaner and easier to trace/debug.</p> <p>Also -- as Mark Rushakoff mentions too -- using pointer(c_double()) and like in your call is pretty icky. I have much better luck w/ POINTER(), and recommend again that you predeclare the value as a variable, and pass the variable in your function call. Then at least you can examine its value afterward for strange behavior.</p> <p>EDIT: So your prototype and call will look something like this:</p> <pre><code>prototype = WINFUNCTYPE( c_int, # Return value (correct? Guess) c_short, # tuner_number c_char_p, # file_path c_char_p, # name c_int, # 0? c_int, # 0? c_long, # 0? c_short, # serial_number c_char_p, # error_string ) # 1 input, 2 output, 4 input default to zero (I think; check doc page) paramflags = (1, 'TunerNumber' ), (1, 'FilePath' ), (1, 'Name' ), ... AddController = prototype(('add_controller', WinDLL.MlibTuners), paramflags) </code></pre> <p>Then your call is much cleaner:</p> <pre><code>arg1 = 0 arg2 = 0 arg3 = 0 AddController(tuner_number, self.file_path, name, arg1, arg2, arg3, serial_number, self.error_string) </code></pre>
0
2009-07-23T12:55:15Z
[ "python", "dll", "oop", "automation", "ctypes" ]
Problem running functions from a DLL file using ctypes in Object-oriented Python
1,170,372
<p>I sure hope this won't be an already answered question or a stupid one. Recently I've been programming with several instruments. Trying to communicate between them in order to create a testing program. However I've encoutered some problems with one specific instrument when I'm trying to call functions that I've "masked" out from the instruments DLL file. When I use the interactive python shell it works perfectly (although its alot of word clobbering). But when I implement the functions in a object-oriented manner the program fails, well actually it doesn't fail it just doesn't do anything. This is the first method that's called: (ctypes and ctypes.util is imported)</p> <pre><code> def init_hardware(self): """ Inits the instrument """ self.write_log("Initialising the automatic tuner") version_string = create_string_buffer(80) self.error_string = create_string_buffer(80) self.name = "Maury MT982EU" self.write_log("Tuner DLL path: %s", find_library('MLibTuners')) self.maury = WinDLL('MlibTuners') self.maury.get_tuner_driver_version(version_string) if (version_string.value == ""): self.write_log("IMPORTANT: Error obtaining the driver version") else: self.write_log("Version number of the DLL: %s" % version_string.value) self.ThreeTypeLong = c_long * 3 </code></pre> <p>Now that works swell, everything is perfect and I get perfect log-entries. But when I try to run a method further into the program called:</p> <pre><code>def add_tuner_and_controller(self, name, serial_number, tuner_number=0): """ Adds the tuner to the driver object, controller is inside the tuner """ self.write_log("Adding tuner %d and the built-in controller" % tuner_number) TempType = self.ThreeTypeLong() self.maury.add_controller(c_short(tuner_number), c_char_p(self.file_path), c_char_p(name), c_int(0), c_int(0), c_long(0), c_short(serial_number), self.error_string) self.maury.add_tuner(c_short(tuner_number), c_char_p(name), c_short(serial_number), c_short(0), c_short(1), pointer(c_double()), TempType, pointer(c_double()), pointer(c_double()), pointer(c_double()), self.error_string) </code></pre> <p>The program suddenly stops working/keeps running , nothing happenes when the "self.maury"-line is called. When I place everything in the init_hardware method it works perfectly so I'm guessing there's a slight memory "error" or something with the objective oriented structure. I really want it to remain this way, is there anyway to isolate the functions in this manner? or do I have to restrict myself to a big chunk of code?</p> <p><hr /></p> <p><strong>EDIT:</strong><br> <em>Documentation info</em>:<br> [Legend: The stars indicate pointers and the brackets indicate arrays]</p> <p><strong>The add_tuner function adds or updates one tuner in the tuner driver object.</strong></p> <pre><code>short add_tuner(short tuner_number, char model[ ], short serial_number, short ctlr_num, short ctlr_port, short *no_of_motors, long max_range[ ], double *fmin, double *fmax, double *fcrossover, char error_string[ ]) </code></pre> <p><strong>Output</strong>: <code>no_motors, max_range (array of three numbers), fmin, fmax, fcrossover,error_string (80+ characters long), function-return-&gt;Error flag</code></p> <p><br> <br> <strong>The add_controller function adds or updates one controller in the tuner driver object</strong></p> <pre><code>short add_controller(short controller_number, char driver[ ], char model[ ], int timeout, int address, long delay_ms, char error_string[ ]) </code></pre> <p><strong>Output</strong>: <code>error_string, function-return-&gt;Error flag</code></p>
2
2009-07-23T08:16:38Z
1,226,235
<p>I found out that the only way to call the functions in the exported DLL was to use the DLL through a parameter in each method. (the program exports the dll and in each method called it will send it as a parameter). It looks pretty ugly but that's the only way I found to be working for me. I even tried exporting the DLL as an class attribute. The system I'm working with is pretty hefty so I guess there is some boboo-code somewhere that makes it fail. Thanks for all the feedback and tips!</p> <p>/Mazdak</p>
0
2009-08-04T08:08:56Z
[ "python", "dll", "oop", "automation", "ctypes" ]
How to create an optimized packing function in python?
1,170,478
<p>So I have been given the task to create a shipping module for a webshop system. It may be a bit overkill, but I would really like to create one that can figure out how to pack parcels in the most optimized way. Having learned programming simply by doing it, this is an area where I have no knowledge - yet! Anyways I can just give short description of the actual problem.</p> <p>So when users by stuff at webshops they will have x products in their cart with possibly varying sizes and weight. So I want to give that list of products to the function and let it figure out how these products should be packed in parcel(s).</p> <ul> <li>max length of parcel: 100</li> <li>max width of parcel: 50</li> <li>max height of parcel: 50</li> <li>max weight of parcel: 20</li> </ul> <p>Every product has a weight, length, width and height as well.</p> <p>Since parcels and products is basically boxes, I'm guessing this would be rather complex, as there are different ways of putting the products inside the parcel. My goal is not to make the perfect packaging function, but I would like to do something better than just putting products inside the parcel until a limit has been reached.</p> <p>Now, I don't expect you guys to make this for me, but what I would like to ask is three things.</p> <ol> <li>Where can I find good online resources that will teach me the basics needed?</li> <li>Are there some native python tools that would be good to use?</li> <li>Some pointers of what I need to be aware of, pitfalls etc</li> </ol> <p>Like I said, I don't plan for this to be perfect and 100% optimized, but I would like to end up with something that will come close. I would hate if users feel that the sending fee will be a lot higher than it actual is.</p>
15
2009-07-23T08:47:06Z
1,170,498
<p>That’s your typical <a href="http://en.wikipedia.org/wiki/Knapsack%5Fproblem">knapsack problem</a>. Many solutions for different languages can be found at <a href="http://www.rosettacode.org/wiki/Knapsack%5FProblem">Rosetta Code</a>.</p>
6
2009-07-23T08:53:19Z
[ "python", "algorithm", "optimization" ]
How to create an optimized packing function in python?
1,170,478
<p>So I have been given the task to create a shipping module for a webshop system. It may be a bit overkill, but I would really like to create one that can figure out how to pack parcels in the most optimized way. Having learned programming simply by doing it, this is an area where I have no knowledge - yet! Anyways I can just give short description of the actual problem.</p> <p>So when users by stuff at webshops they will have x products in their cart with possibly varying sizes and weight. So I want to give that list of products to the function and let it figure out how these products should be packed in parcel(s).</p> <ul> <li>max length of parcel: 100</li> <li>max width of parcel: 50</li> <li>max height of parcel: 50</li> <li>max weight of parcel: 20</li> </ul> <p>Every product has a weight, length, width and height as well.</p> <p>Since parcels and products is basically boxes, I'm guessing this would be rather complex, as there are different ways of putting the products inside the parcel. My goal is not to make the perfect packaging function, but I would like to do something better than just putting products inside the parcel until a limit has been reached.</p> <p>Now, I don't expect you guys to make this for me, but what I would like to ask is three things.</p> <ol> <li>Where can I find good online resources that will teach me the basics needed?</li> <li>Are there some native python tools that would be good to use?</li> <li>Some pointers of what I need to be aware of, pitfalls etc</li> </ol> <p>Like I said, I don't plan for this to be perfect and 100% optimized, but I would like to end up with something that will come close. I would hate if users feel that the sending fee will be a lot higher than it actual is.</p>
15
2009-07-23T08:47:06Z
1,170,541
<p>This seems a good problem to which to apply <a href="http://en.wikipedia.org/wiki/Simplex%5Falgorithm" rel="nofollow">the simplex algorithm</a> or some sort of <a href="http://en.wikipedia.org/wiki/Genetic%5Falgorithm" rel="nofollow">genetic algorithm</a>. If you never heard of the latter, I highly recommend you to read about them. As I can see from your question, you're doing this enhancement because you like to make things work optimally, and not because you were told to do so. Imagine when you tell them you applied an Artificial Intelligence technique for solving their problem! </p> <p>There are many straight-forward algorithms that solve your problem, but this can be a great opportunity to learn some evolutionary computation. Some interesting links about genetic algorithms [everyone, feel free to edit and add]: </p> <ol> <li><a href="http://i.t4z.com.ar/6co" rel="nofollow">These pages introduce some fundamentals of genetic algorithms.</a></li> <li><a href="http://i.t4z.com.ar/5VN" rel="nofollow">Genetic Algorithms in Plain English</a></li> </ol> <p>Luck with that!<br /> Manuel</p>
2
2009-07-23T09:04:43Z
[ "python", "algorithm", "optimization" ]
How to create an optimized packing function in python?
1,170,478
<p>So I have been given the task to create a shipping module for a webshop system. It may be a bit overkill, but I would really like to create one that can figure out how to pack parcels in the most optimized way. Having learned programming simply by doing it, this is an area where I have no knowledge - yet! Anyways I can just give short description of the actual problem.</p> <p>So when users by stuff at webshops they will have x products in their cart with possibly varying sizes and weight. So I want to give that list of products to the function and let it figure out how these products should be packed in parcel(s).</p> <ul> <li>max length of parcel: 100</li> <li>max width of parcel: 50</li> <li>max height of parcel: 50</li> <li>max weight of parcel: 20</li> </ul> <p>Every product has a weight, length, width and height as well.</p> <p>Since parcels and products is basically boxes, I'm guessing this would be rather complex, as there are different ways of putting the products inside the parcel. My goal is not to make the perfect packaging function, but I would like to do something better than just putting products inside the parcel until a limit has been reached.</p> <p>Now, I don't expect you guys to make this for me, but what I would like to ask is three things.</p> <ol> <li>Where can I find good online resources that will teach me the basics needed?</li> <li>Are there some native python tools that would be good to use?</li> <li>Some pointers of what I need to be aware of, pitfalls etc</li> </ol> <p>Like I said, I don't plan for this to be perfect and 100% optimized, but I would like to end up with something that will come close. I would hate if users feel that the sending fee will be a lot higher than it actual is.</p>
15
2009-07-23T08:47:06Z
1,177,246
<p>The fact that you have height, length and width makes it harder than a simple knapsack problem. Here's an interesting discussion of a <a href="http://www.cirm.univ-mrs.fr/videos/2006/exposes/14/Thursday%20Morning/Diedrich.pdf">3D knapsack problem</a>.</p> <p>Here's a <a href="http://books.google.com/books?id=mhrOkx-xyJIC&amp;lpg=PA34&amp;ots=1XEOcysErv&amp;pg=PA34">paper on the topic</a> by the same guys.</p>
5
2009-07-24T12:05:02Z
[ "python", "algorithm", "optimization" ]
need to create a .pem file
1,170,700
<p>What the <code>.pem</code> file contain? simply a key or a function which generate the key.</p> <p>I need to create a <code>.pem</code> file and also need to call this file in a function.</p> <p>here is code to which I have to proceed:</p> <pre><code>pk = open( 'public_key.pem', 'rb' ).read() rsa = M2Crypto.RSA.load_pub_key(pk) </code></pre>
2
2009-07-23T09:48:31Z
1,170,768
<p>You can use <a href="http://www.openssl.org/" rel="nofollow">openssl</a> to create a pem file. You will need to supply it the correct parameters to get the correct type of key. The <a href="http://www.openssl.org/docs/apps/genpkey.html#" rel="nofollow">genkey</a> command of openssl looks like what you want to use.</p>
1
2009-07-23T10:01:47Z
[ "python" ]
need to create a .pem file
1,170,700
<p>What the <code>.pem</code> file contain? simply a key or a function which generate the key.</p> <p>I need to create a <code>.pem</code> file and also need to call this file in a function.</p> <p>here is code to which I have to proceed:</p> <pre><code>pk = open( 'public_key.pem', 'rb' ).read() rsa = M2Crypto.RSA.load_pub_key(pk) </code></pre>
2
2009-07-23T09:48:31Z
6,878,312
<p>You can use this code to create a public key pair, then save them unencrypted to two files. </p> <pre><code> from M2Crypto import RSA key=RSA.gen_key(2048, 65537) key.save_pem('./privkey',cipher=None) key.save_pub_key('./pubkey') </code></pre> <p>To read it, do:</p> <pre><code>rsa=RSA.load_pub_key('./pubkey') </code></pre> <p>And similar if you want to load the private key as well. Good luck!</p>
1
2011-07-29T19:52:15Z
[ "python" ]
How can I run telnet command in the python GUI?
1,170,713
<p>How can I run telnet command in the python GUI?</p>
0
2009-07-23T09:51:56Z
1,170,750
<p>Sounds like you need <a href="http://docs.python.org/library/telnetlib.html" rel="nofollow">telnetlib</a> </p>
2
2009-07-23T09:57:21Z
[ "python" ]
How can I run telnet command in the python GUI?
1,170,713
<p>How can I run telnet command in the python GUI?</p>
0
2009-07-23T09:51:56Z
1,172,218
<p>You may also be interested in <a href="http://www.secdev.org/projects/scapy/" rel="nofollow">Scapy</a>, though it may be too low-level for what you want.</p>
0
2009-07-23T14:37:49Z
[ "python" ]
Error when using a Python constructor
1,170,731
<pre><code>class fileDetails : def __init__(self,host,usr,pwd,database): self.host=host self.usr.usr self.pwd=pwd self.database=database def __init__(self,connection,sql,path): self.connection=mysql_connection() self.sql=sql self.path=path </code></pre> <p>If I use the constructor then it gives an error:</p> <pre><code>onnetction = fileDetails('localhost',"root","",'bulsorbit') TypeError: __init__() takes exactly 4 arguments (5 given) </code></pre>
1
2009-07-23T09:54:47Z
1,170,758
<p>The overloading of the constructor (or any other function) is not allowed in python. So you cannot define two <code>__init__</code> functions for your class.</p> <p>You can have a look to <a href="http://stackoverflow.com/questions/312695/python-problem-with-overloaded-constructors">this post</a> or <a href="http://stackoverflow.com/questions/141545/overloading-init-in-python">this one</a></p> <p>The main ideas are to use default values <em>or</em> to create 'alternate constructors' <em>or</em> to check the number and the type of your args in order to choose which method to apply.</p> <pre><code>def __init__(self, **args): </code></pre> <p>Then <code>args</code> will be a dictionary containing all the parameters. So you will be able to make the difference between</p> <pre><code>connection = fileDetails(host='localhost',usr="root",pwd="",database='bulsorbit') </code></pre> <p>and</p> <pre><code>connection = fileDetails(connection="...",sql="...",path="...") </code></pre>
11
2009-07-23T09:58:54Z
[ "python", "constructor" ]
Error when using a Python constructor
1,170,731
<pre><code>class fileDetails : def __init__(self,host,usr,pwd,database): self.host=host self.usr.usr self.pwd=pwd self.database=database def __init__(self,connection,sql,path): self.connection=mysql_connection() self.sql=sql self.path=path </code></pre> <p>If I use the constructor then it gives an error:</p> <pre><code>onnetction = fileDetails('localhost',"root","",'bulsorbit') TypeError: __init__() takes exactly 4 arguments (5 given) </code></pre>
1
2009-07-23T09:54:47Z
1,170,759
<p>Define a single constructor with optional arguments.</p> <pre><code>def __init__(self,host='host',usr='user',pwd='pwd',database='db',connection=None,sql=None,path=None): if connection: # however you want to store your connection self.sql=sql self.path=path else: self.host=host self.usr.usr self.pwd=pwd self.database=database </code></pre> <p>Or something of the sort.</p>
4
2009-07-23T09:59:19Z
[ "python", "constructor" ]
Error when using a Python constructor
1,170,731
<pre><code>class fileDetails : def __init__(self,host,usr,pwd,database): self.host=host self.usr.usr self.pwd=pwd self.database=database def __init__(self,connection,sql,path): self.connection=mysql_connection() self.sql=sql self.path=path </code></pre> <p>If I use the constructor then it gives an error:</p> <pre><code>onnetction = fileDetails('localhost',"root","",'bulsorbit') TypeError: __init__() takes exactly 4 arguments (5 given) </code></pre>
1
2009-07-23T09:54:47Z
1,170,767
<p>In Python the functions in a class are stored internally in a dictionary (remember that constructors are just regular functions), and so only one function of the same name can exist. Therefore, when defining more than one functions with the same name the last one will overwrite all the previously defined ones and you'll end up with only one function.</p> <p>I suggest you look into <a href="http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions" rel="nofollow">keyword and default arguments</a> to see the proper way of achieving what you want.</p>
1
2009-07-23T10:01:44Z
[ "python", "constructor" ]
Error when using a Python constructor
1,170,731
<pre><code>class fileDetails : def __init__(self,host,usr,pwd,database): self.host=host self.usr.usr self.pwd=pwd self.database=database def __init__(self,connection,sql,path): self.connection=mysql_connection() self.sql=sql self.path=path </code></pre> <p>If I use the constructor then it gives an error:</p> <pre><code>onnetction = fileDetails('localhost',"root","",'bulsorbit') TypeError: __init__() takes exactly 4 arguments (5 given) </code></pre>
1
2009-07-23T09:54:47Z
1,170,803
<p>maybe you can use len() to choose the right branch:</p> <pre><code>class Foo(object): def __init__(self, *args): if len(args) == 4: # network self.host = args[0] self.user = args[1] self.pwd = args[2] self.database = args[3] elif len(args) == 3: # database self.connection = mysql_connection() # maybe it's args[0]? self.sql = args[1] self.path = args[2] def main(): foo = Foo('localhost',"root","",'bulsorbit') print foo.host if __name__ == "__main__": main() # output # localhost </code></pre> <p>but, sine Explicit is better than implicit. maybe this is workable too:</p> <pre><code>class Foo(object): def __init__(self, initdata): if initdata['style'] == 'network': self.host = initdata['host'] self.usr = initdata['usr'] self.pwd = initdata['pwd'] self.database = initdata['database'] elif initdata[style] == 'database': self.connection = mysql_connection() self.sql = initdata['sql'] self.path = initdata['path'] def main(): data = dict({'style': 'network', 'host': 'localhost', 'usr': 'root', 'pwd': '', 'database': 'database'}) foo = Foo(data) print foo.host if __name__ == "__main__": main() # output # localhost </code></pre>
1
2009-07-23T10:10:15Z
[ "python", "constructor" ]
Error when using a Python constructor
1,170,731
<pre><code>class fileDetails : def __init__(self,host,usr,pwd,database): self.host=host self.usr.usr self.pwd=pwd self.database=database def __init__(self,connection,sql,path): self.connection=mysql_connection() self.sql=sql self.path=path </code></pre> <p>If I use the constructor then it gives an error:</p> <pre><code>onnetction = fileDetails('localhost',"root","",'bulsorbit') TypeError: __init__() takes exactly 4 arguments (5 given) </code></pre>
1
2009-07-23T09:54:47Z
1,170,819
<p>Here's one way to achieve this:</p> <pre><code>class FileDetails: def __init__(self, *args, **kwargs): if len(args) == 3: self.conn, self.sql, self.path = args elif len(args) == 4: self.host, self.usr, self.pw, self.db = args else: # handle appropriately fd1 = FileDetail('connstring', 'select * from foo', '/some/path') print fd1.conn, fd1.sql, fd1.path fd2 = FileDetail('host', 'user', 'pass', 'somedb') print fd2.conn, fd2.usr, fd2.pw, fd2.db </code></pre> <p>Of course, you should do the appropriate type checking and error handling in the constructor.</p>
0
2009-07-23T10:13:41Z
[ "python", "constructor" ]
Error when using a Python constructor
1,170,731
<pre><code>class fileDetails : def __init__(self,host,usr,pwd,database): self.host=host self.usr.usr self.pwd=pwd self.database=database def __init__(self,connection,sql,path): self.connection=mysql_connection() self.sql=sql self.path=path </code></pre> <p>If I use the constructor then it gives an error:</p> <pre><code>onnetction = fileDetails('localhost',"root","",'bulsorbit') TypeError: __init__() takes exactly 4 arguments (5 given) </code></pre>
1
2009-07-23T09:54:47Z
1,170,820
<p>On the side note: if you really, really, reallllllyyy must do JiP (Java in Python) then multiple dispatch methods <strong>are</strong> possible with some additional code eg. <a href="http://www.ibm.com/developerworks/library/l-pydisp.html" rel="nofollow">here</a> and even beter: <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=101605" rel="nofollow">here by <em>BDFL</em></a>.</p> <p>Personally I try to avoid using them. </p>
0
2009-07-23T10:13:46Z
[ "python", "constructor" ]
How do I get urllib2 to log ALL transferred bytes
1,170,744
<p>I'm writing a web-app that uses several 3rd party web APIs, and I want to keep track of the low level request and responses for ad-hock analysis. So I'm looking for a recipe that will get Python's urllib2 to log all bytes transferred via HTTP. Maybe a sub-classed Handler?</p>
18
2009-07-23T09:56:43Z
1,181,585
<p>Well, I've found how to setup the built-in debugging mechanism of the library:</p> <pre><code>import logging, urllib2, sys hh = urllib2.HTTPHandler() hsh = urllib2.HTTPSHandler() hh.set_http_debuglevel(1) hsh.set_http_debuglevel(1) opener = urllib2.build_opener(hh, hsh) logger = logging.getLogger() logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.NOTSET) </code></pre> <p>But I'm still looking for a way to dump all the information transferred.</p>
11
2009-07-25T08:22:36Z
[ "python", "http", "logging", "urllib2" ]
How do I get urllib2 to log ALL transferred bytes
1,170,744
<p>I'm writing a web-app that uses several 3rd party web APIs, and I want to keep track of the low level request and responses for ad-hock analysis. So I'm looking for a recipe that will get Python's urllib2 to log all bytes transferred via HTTP. Maybe a sub-classed Handler?</p>
18
2009-07-23T09:56:43Z
1,844,608
<p>This looks pretty tricky to do. There are no hooks in urllib2, urllib, or httplib (which this builds on) for intercepting either input or output data.</p> <p>The only thing that occurs to me, other than switching tactics to use an external tool (of which there are many, and most people use such things), would be to write a subclass of socket.socket in your own new module (say, "capture_socket") and then insert that into httplib using "import capture_socket; import httplib; httplib.socket = capture_socket". You'd have to copy all the necessary references (anything of the form "socket.foo" that is used in httplib) into your own module, but then you could override things like recv() and sendall() in your subclass to do what you like with the data.</p> <p>Complications would likely arise if you were using SSL, and I'm not sure whether this would be sufficient or if you'd also have to make your own socket._fileobject as well. It appears doable though, and perusing the source in httplib.py and socket.py in the standard library would tell you more.</p>
2
2009-12-04T03:11:00Z
[ "python", "http", "logging", "urllib2" ]
Unable to find the Python PIL library.Google App Engine
1,170,898
<p>Installed the Google App Engine SDK.Python 2.6 perfect. Wanted to go into images, and test locally.Installed PIL</p> <p>Installed Python, then ran the PIL install, worked this time.</p> <p>Things seemed good, but trying to do localhost image manipulation gives: "NotImplementedError: Unable to find the Python PIL library. Please view the SDK documentation for details about installing PIL on your system."</p> <p>System : winxp</p>
9
2009-07-23T10:31:42Z
1,170,930
<p>We're probably going to need more information, so here are some questions and things to try.</p> <p>How are you trying to access the PIL? Are you trying to use the google.appengine.api.images module, or PIL directly? It sounds like the former, but it's not clear.</p> <p>Did you follow <a href="http://code.google.com/appengine/docs/python/images/" rel="nofollow">the App Engine instructions</a>?</p> <p>Post code, if you can.</p> <p>Perhaps the most important thing to try: see if you can use PIL from a non-App Engine script. Just write a quick Python script that accesses it and see how that goes. Something like:</p> <pre><code>import Image im = Image.open('filename.png') im.show() </code></pre> <p>If that doesn't work, it's not surprising that Google App Engine wouldn't work with PIL.</p>
2
2009-07-23T10:40:21Z
[ "python", "google-app-engine", "python-imaging-library" ]
Unable to find the Python PIL library.Google App Engine
1,170,898
<p>Installed the Google App Engine SDK.Python 2.6 perfect. Wanted to go into images, and test locally.Installed PIL</p> <p>Installed Python, then ran the PIL install, worked this time.</p> <p>Things seemed good, but trying to do localhost image manipulation gives: "NotImplementedError: Unable to find the Python PIL library. Please view the SDK documentation for details about installing PIL on your system."</p> <p>System : winxp</p>
9
2009-07-23T10:31:42Z
1,971,095
<p>As far as I know Google AppEngine does not allow to use PIL directly, but instead provides a limited <a href="http://code.google.com/appengine/docs/python/images/overview.html" rel="nofollow">Images API</a>.</p> <p>It can resize/rotate/crop and flip images. More or less what Picasaweb can do. But it cannot create new images or do complex things like adding text, drawing etc.</p>
4
2009-12-28T19:25:21Z
[ "python", "google-app-engine", "python-imaging-library" ]
Unable to find the Python PIL library.Google App Engine
1,170,898
<p>Installed the Google App Engine SDK.Python 2.6 perfect. Wanted to go into images, and test locally.Installed PIL</p> <p>Installed Python, then ran the PIL install, worked this time.</p> <p>Things seemed good, but trying to do localhost image manipulation gives: "NotImplementedError: Unable to find the Python PIL library. Please view the SDK documentation for details about installing PIL on your system."</p> <p>System : winxp</p>
9
2009-07-23T10:31:42Z
4,237,803
<p>On Ubuntu with python2.5 the following helps:</p> <p>new repo: ppa.launchpad.net/fkrull/deadsnakes/ubuntu</p> <p>sudo apt-get install python2.5 python2.5-dev libjpeg62 libjpeg62-dev</p> <p>untar: <a href="http://effbot.org/media/downloads/Imaging-1.1.6.tar.gz" rel="nofollow">http://effbot.org/media/downloads/Imaging-1.1.6.tar.gz</a></p> <p>cd Imaging-1.1.6</p> <p>edit setup.py line 38: JPEG_ROOT = libinclude("/usr/lib")</p> <p>sudo python2.5 setup.py install</p> <p>Done</p>
3
2010-11-21T12:28:37Z
[ "python", "google-app-engine", "python-imaging-library" ]
Unable to find the Python PIL library.Google App Engine
1,170,898
<p>Installed the Google App Engine SDK.Python 2.6 perfect. Wanted to go into images, and test locally.Installed PIL</p> <p>Installed Python, then ran the PIL install, worked this time.</p> <p>Things seemed good, but trying to do localhost image manipulation gives: "NotImplementedError: Unable to find the Python PIL library. Please view the SDK documentation for details about installing PIL on your system."</p> <p>System : winxp</p>
9
2009-07-23T10:31:42Z
4,821,894
<p>If you clear your GAE log window (assuming you're using the launcher) then restart your server, you might see something in the log. In my case I got</p> <p><PRE> WARNING 2011-01-27 21:04:11,856 dev_appserver.py:3698] Could not initialize images API; you are likely missing the Python "PIL" module. ImportError: dlopen(/Library/Python/2.6/site-packages/PIL/_imaging.so, 2): Symbol not found: _jpeg_resync_to_restart Referenced from: /Library/Python/2.6/site-packages/PIL/_imaging.so </PRE></p> <p>So I could tell that I didn't link well enough with the JPEG library.</p>
1
2011-01-27T21:08:13Z
[ "python", "google-app-engine", "python-imaging-library" ]
Unable to find the Python PIL library.Google App Engine
1,170,898
<p>Installed the Google App Engine SDK.Python 2.6 perfect. Wanted to go into images, and test locally.Installed PIL</p> <p>Installed Python, then ran the PIL install, worked this time.</p> <p>Things seemed good, but trying to do localhost image manipulation gives: "NotImplementedError: Unable to find the Python PIL library. Please view the SDK documentation for details about installing PIL on your system."</p> <p>System : winxp</p>
9
2009-07-23T10:31:42Z
14,057,571
<p>I took a while to get PIL working. Mainly because I forgot to tell app engine to load it in the yaml file:</p> <pre><code> libraries: - name: PIL version: 1.1.7 </code></pre> <p>Maybe this step is obvious, but I did not see it documented well on google documentation and I found all kinds of messages here stating that PIL was not available on app engine. I want to confirm that PIL is running on app engine.</p>
5
2012-12-27T16:06:17Z
[ "python", "google-app-engine", "python-imaging-library" ]
Fit algorithm does not accept my data
1,170,962
<p>I'm using the algorithm described <a href="http://www.scipy.org/Cookbook/FittingData" rel="nofollow">here</a> to fit Gaussian bell curves to my data.</p> <p>If I generate my data array with:</p> <pre><code>x=linspace(1.,100.,100) data= 17*exp(-((x-10)/3)**2) </code></pre> <p>everything works fine.</p> <p>But if I read the data from a text file using</p> <pre><code>file = open("d:\\test7.txt") arr=[] data=[] def column(matrix,i): return [row[i] for row in matrix] for line in file.readlines(): numbers=map(float, line.split()) arr.append(numbers) data = column(arr,300) x=linspace(1.,115.,115) </code></pre> <p>I get the error message:</p> <pre><code>Traceback (most recent call last): File "readmatrix.py", line 60, in &lt;module&gt; fit(f, [mu, sigma, height], data) File "readmatrix.py", line 42, in fit if x is None: x = arange(y.shape[0]) AttributeError: 'list' object has no attribute 'shape' </code></pre> <p>As far as I can see, the values included in data are correct, it looks like:</p> <pre><code>[0.108032, 0.86181600000000003, 1.386169, 3.2790530000000002, ... ] </code></pre> <p>Has someone a clue what I am doing wrong?</p> <p>Thanks!</p>
0
2009-07-23T10:48:38Z
1,171,090
<p>The fit function expects the data as a numpy Array (which has a shape attribute) and not a list (which does not), hence the AttributeError.</p> <p>Convert your data:</p> <pre><code>def column(matrix,i): return numpy.asarray([row[i] for row in matrix]) </code></pre>
4
2009-07-23T11:16:13Z
[ "python", "arrays", "file-io" ]
Fit algorithm does not accept my data
1,170,962
<p>I'm using the algorithm described <a href="http://www.scipy.org/Cookbook/FittingData" rel="nofollow">here</a> to fit Gaussian bell curves to my data.</p> <p>If I generate my data array with:</p> <pre><code>x=linspace(1.,100.,100) data= 17*exp(-((x-10)/3)**2) </code></pre> <p>everything works fine.</p> <p>But if I read the data from a text file using</p> <pre><code>file = open("d:\\test7.txt") arr=[] data=[] def column(matrix,i): return [row[i] for row in matrix] for line in file.readlines(): numbers=map(float, line.split()) arr.append(numbers) data = column(arr,300) x=linspace(1.,115.,115) </code></pre> <p>I get the error message:</p> <pre><code>Traceback (most recent call last): File "readmatrix.py", line 60, in &lt;module&gt; fit(f, [mu, sigma, height], data) File "readmatrix.py", line 42, in fit if x is None: x = arange(y.shape[0]) AttributeError: 'list' object has no attribute 'shape' </code></pre> <p>As far as I can see, the values included in data are correct, it looks like:</p> <pre><code>[0.108032, 0.86181600000000003, 1.386169, 3.2790530000000002, ... ] </code></pre> <p>Has someone a clue what I am doing wrong?</p> <p>Thanks!</p>
0
2009-07-23T10:48:38Z
1,171,270
<p>The solution of balpha is not correct; the solution is simply to convert my list to a numpy array via numpy.array.</p> <p>Thanks for giving me a hint!</p>
4
2009-07-23T11:57:40Z
[ "python", "arrays", "file-io" ]
How can I profile a SQLAlchemy powered application?
1,171,166
<p>Does anyone have experience profiling a Python/SQLAlchemy app? And what are the best way to find bottlenecks and design flaws?</p> <p>We have a Python application where the database layer is handled by SQLAlchemy. The application uses a batch design, so a lot of database requests is done sequentially and in a limited timespan. It currently takes a bit too long to run, so some optimization is needed. We don't use the ORM functionality, and the database is PostgreSQL.</p>
38
2009-07-23T11:33:39Z
1,171,280
<p>I have had some success in using cprofile and looking at the results in runsnakerun. This at least told me what functions and calls where taking a long time and if the database was the issue. The documentation is <a href="http://www.vrplumber.com/programming/runsnakerun/" rel="nofollow">here</a>. You need wxpython. The <a href="http://us.pycon.org/2009/conference/schedule/event/15/" rel="nofollow">presentation</a> on it is good to get you started.<br /> Its as easy as</p> <pre><code>import cProfile command = """foo.run()""" cProfile.runctx( command, globals(), locals(), filename="output.profile" ) </code></pre> <p>Then</p> <p>python runsnake.py output.profile</p> <p>If you are looking to optimise your queries you will need <a href="http://stackoverflow.com/questions/365103/how-to-profile-postgresql-database">postgrsql profiling</a>.</p> <p>It is also worth putting logging on to record the queries, but there is no parser for this that I know of to get the long running queries (and it wont be useful for concurrent requests).</p> <pre><code>sqlhandler = logging.FileHandler("sql.log") sqllogger = logging.getLogger('sqlalchemy.engine') sqllogger.setLevel(logging.info) sqllogger.addHandler(sqlhandler) </code></pre> <p>and making sure your create engine statement has echo = True.</p> <p>When I did it is was actually my code that was the main issue, so the cprofile thing helped.</p>
3
2009-07-23T12:00:32Z
[ "python", "sqlalchemy", "profiler" ]
How can I profile a SQLAlchemy powered application?
1,171,166
<p>Does anyone have experience profiling a Python/SQLAlchemy app? And what are the best way to find bottlenecks and design flaws?</p> <p>We have a Python application where the database layer is handled by SQLAlchemy. The application uses a batch design, so a lot of database requests is done sequentially and in a limited timespan. It currently takes a bit too long to run, so some optimization is needed. We don't use the ORM functionality, and the database is PostgreSQL.</p>
38
2009-07-23T11:33:39Z
1,175,677
<p>Sometimes just plain SQL logging (enabled via python's logging module or via the <code>echo=True</code> argument on <code>create_engine()</code>) can give you an idea how long things are taking. For example if you log something right after a SQL operation, you'd see something like this in your log:</p> <pre><code>17:37:48,325 INFO [sqlalchemy.engine.base.Engine.0x...048c] SELECT ... 17:37:48,326 INFO [sqlalchemy.engine.base.Engine.0x...048c] {&lt;params&gt;} 17:37:48,660 DEBUG [myapp.somemessage] </code></pre> <p>if you logged <code>myapp.somemessage</code> right after the operation, you know it took 334ms to complete the SQL part of things. </p> <p>Logging SQL will also illustrate if dozens/hundreds of queries are being issued which could be better organized into much fewer queries via joins. When using the SQLAlchemy ORM, the "eager loading" feature is provided to partially (<code>contains_eager()</code>) or fully (<code>eagerload()</code>, <code>eagerload_all()</code>) automate this activity, but without the ORM it just means to use joins so that results across multiple tables can be loaded in one result set instead of multiplying numbers of queries as more depth is added (i.e. <code>r + r*r2 + r*r2*r3</code> ...)</p> <p>If logging reveals that individual queries are taking too long, you'd need a breakdown of how much time was spent within the database processing the query, sending results over the network, being handled by the DBAPI, and finally being received by SQLAlchemy's result set and/or ORM layer. Each of these stages can present their own individual bottlenecks, depending on specifics.</p> <p>For that you need to use profiling, such as cProfile or hotshot. Here is a decorator I use:</p> <pre><code>import cProfile as profiler import gc, pstats, time def profile(fn): def wrapper(*args, **kw): elapsed, stat_loader, result = _profile("foo.txt", fn, *args, **kw) stats = stat_loader() stats.sort_stats('cumulative') stats.print_stats() # uncomment this to see who's calling what # stats.print_callers() return result return wrapper def _profile(filename, fn, *args, **kw): load_stats = lambda: pstats.Stats(filename) gc.collect() began = time.time() profiler.runctx('result = fn(*args, **kw)', globals(), locals(), filename=filename) ended = time.time() return ended - began, load_stats, locals()['result'] </code></pre> <p>To profile a section of code, place it in a function with the decorator:</p> <pre><code>@profile def go(): return Session.query(FooClass).filter(FooClass.somevalue==8).all() myfoos = go() </code></pre> <p>The output of profiling can be used to give an idea where time is being spent. If for example you see all the time being spent within <code>cursor.execute()</code>, that's the low level DBAPI call to the database, and it means your query should be optimized, either by adding indexes or restructuring the query and/or underlying schema. For that task I would recommend using pgadmin along with its graphical EXPLAIN utility to see what kind of work the query is doing.</p> <p>If you see many thousands of calls related to fetching rows, it may mean your query is returning more rows than expected - a cartesian product as a result of an incomplete join can cause this issue. Yet another issue is time spent within type handling - a SQLAlchemy type such as <code>Unicode</code> will perform string encoding/decoding on bind parameters and result columns, which may not be needed in all cases.</p> <p>The output of a profile can be a little daunting but after some practice they are very easy to read. There was once someone on the mailing list claiming slowness, and after having him post the results of profile, I was able to demonstrate that the speed problems were due to network latency - the time spent within cursor.execute() as well as all Python methods was very fast, whereas the majority of time was spent on socket.receive().</p> <p>If you're feeling ambitious, there's also a more involved example of SQLAlchemy profiling within the SQLAlchemy unit tests, if you poke around <a href="http://www.sqlalchemy.org/trac/browser/sqlalchemy/trunk/test/aaa_profiling">http://www.sqlalchemy.org/trac/browser/sqlalchemy/trunk/test/aaa_profiling</a> . There, we have tests using decorators that assert a maximum number of method calls being used for particular operations, so that if something inefficient gets checked in, the tests will reveal it (it is important to note that in Python, function calls have the highest overhead of any operation, and the count of calls is more often than not nearly proportional to time spent). Of note are the the "zoomark" tests which use a fancy "SQL capturing" scheme which cuts out the overhead of the DBAPI from the equation - although that technique isn't really necessary for garden-variety profiling.</p>
59
2009-07-24T03:54:46Z
[ "python", "sqlalchemy", "profiler" ]
How can I profile a SQLAlchemy powered application?
1,171,166
<p>Does anyone have experience profiling a Python/SQLAlchemy app? And what are the best way to find bottlenecks and design flaws?</p> <p>We have a Python application where the database layer is handled by SQLAlchemy. The application uses a batch design, so a lot of database requests is done sequentially and in a limited timespan. It currently takes a bit too long to run, so some optimization is needed. We don't use the ORM functionality, and the database is PostgreSQL.</p>
38
2009-07-23T11:33:39Z
8,428,546
<p>There's an extremely useful profiling recipe on the <a href="http://www.sqlalchemy.org/trac/wiki/UsageRecipes/Profiling">SQLAlchemy wiki</a></p> <p>With a couple of minor modifications,</p> <pre><code>from sqlalchemy import event from sqlalchemy.engine import Engine import time import logging logging.basicConfig() logger = logging.getLogger("myapp.sqltime") logger.setLevel(logging.DEBUG) @event.listens_for(Engine, "before_cursor_execute") def before_cursor_execute(conn, cursor, statement, parameters, context, executemany): context._query_start_time = time.time() logger.debug("Start Query:\n%s" % statement) # Modification for StackOverflow answer: # Show parameters, which might be too verbose, depending on usage.. logger.debug("Parameters:\n%r" % (parameters,)) @event.listens_for(Engine, "after_cursor_execute") def after_cursor_execute(conn, cursor, statement, parameters, context, executemany): total = time.time() - context._query_start_time logger.debug("Query Complete!") # Modification for StackOverflow: times in milliseconds logger.debug("Total Time: %.02fms" % (total*1000)) if __name__ == '__main__': from sqlalchemy import * engine = create_engine('sqlite://') m1 = MetaData(engine) t1 = Table("sometable", m1, Column("id", Integer, primary_key=True), Column("data", String(255), nullable=False), ) conn = engine.connect() m1.create_all(conn) conn.execute( t1.insert(), [{"data":"entry %d" % x} for x in xrange(100000)] ) conn.execute( t1.select().where(t1.c.data.between("entry 25", "entry 7800")).order_by(desc(t1.c.data)) ) </code></pre> <p>Output is something like:</p> <pre><code>DEBUG:myapp.sqltime:Start Query: SELECT sometable.id, sometable.data FROM sometable WHERE sometable.data BETWEEN ? AND ? ORDER BY sometable.data DESC DEBUG:myapp.sqltime:Parameters: ('entry 25', 'entry 7800') DEBUG:myapp.sqltime:Query Complete! DEBUG:myapp.sqltime:Total Time: 410.46ms </code></pre> <p>Then if you find an oddly slow query, you could take the query string, format in the parameters (can be done the <code>%</code> string-formatting operator, for psycopg2 at least), prefix it with "EXPLAIN ANALYZE" and shove the query plan output into <a href="http://explain.depesz.com/">http://explain.depesz.com/</a> (found via <a href="http://robots.thoughtbot.com/post/2638538135/postgresql-performance-considerations">this good article on PostgreSQL performance</a>)</p>
34
2011-12-08T09:06:54Z
[ "python", "sqlalchemy", "profiler" ]
Change Flash source by Python
1,171,170
<p>I have flash with big image library inside, is there way to manipulate this content by python?</p>
1
2009-07-23T11:34:03Z
1,171,291
<p>Python Flash Tools intended to be a level up from the Ming SWF library and a step down from a Flash GUI see <a href="http://pyswftools.sourceforge.net/" rel="nofollow">http://pyswftools.sourceforge.net/</a></p>
0
2009-07-23T12:02:38Z
[ "python", "flash" ]
How to increase connection pool size for Twisted?
1,171,519
<p>I'm using Twisted 8.1.0 as socket server engine. Reactor - epoll. Database server is MySQL 5.0.67. OS - Ubuntu Linux 8.10 32-bit </p> <p>in <code>/etc/mysql/my.cnf</code> :</p> <pre><code>max_connections = 1000 </code></pre> <p>in source code:</p> <pre><code>adbapi.ConnectionPool("MySQLdb", ..., use_unicode=True, charset='utf8', cp_min=3, cp_max=700, cp_noisy=False) </code></pre> <p>But in reality I can see only 200 (or less) open connections (<code>SHOW PROCESSLIST</code>) when application is running under heavy load. It is not enough for my app :( </p> <p>As I see this is limit for the thread pool. Any ideas?</p>
3
2009-07-23T12:52:37Z
1,175,408
<p>As you suspect, this is probably a threading issue. <code>cp_max</code> sets an upper limit for the number of threads in the thread pool, however, your process is very likely running out of memory well below this limit, in your case around 200 threads. Because each thread has its own stack, the total memory being used by your process hits the system limit and no more threads can be created.</p> <p>You can check this by adjusting the stack size ulimit setting (I'm using <code>bash</code>) prior to running your program, i.e.</p> <pre><code>$ ulimit -a core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited max nice (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 32750 max locked memory (kbytes, -l) 32 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 max rt priority (-r) 0 stack size (kbytes, -s) 10240 cpu time (seconds, -t) unlimited max user processes (-u) 32750 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited </code></pre> <p>You can see that the default stack size is 10240K on my machine and I have found that I can create about 300 threads with this setting. Adjusting the stack size down to 1024K (using <code>ulimit -s 1024</code>) I can create about 3000 threads.</p> <p>You can get some idea about the thread creation limits on you system using this script:</p> <pre><code>from thread import start_new_thread from time import sleep def sleeper(): try: while 1: sleep(10000) except: if running: raise def test(): global running n = 0 running = True try: while 1: start_new_thread(sleeper, ()) n += 1 except Exception, e: running = False print 'Exception raised:', e print 'Biggest number of threads:', n if __name__ == '__main__': test() </code></pre> <p>Whether this solves your problem will depend on the memory requirements of the <code>ConnectionPool</code> threads.</p>
7
2009-07-24T01:38:48Z
[ "python", "connection-pooling", "twisted" ]
How can I parse JSON in Google App Engine?
1,171,584
<p>I'd like to parse a JSON string into an object under Google App Engine (python). What do you recommend? Something to encode/stringify would be nice too. Is what you recommend built in, or a library that I have to include in my app? Is it secure? Thanks.</p>
77
2009-07-23T13:09:20Z
1,171,620
<p>Include the <a href="http://www.undefined.org/python/" rel="nofollow">simplejson</a> library with your app? </p>
6
2009-07-23T13:13:50Z
[ "python", "json", "google-app-engine" ]
How can I parse JSON in Google App Engine?
1,171,584
<p>I'd like to parse a JSON string into an object under Google App Engine (python). What do you recommend? Something to encode/stringify would be nice too. Is what you recommend built in, or a library that I have to include in my app? Is it secure? Thanks.</p>
77
2009-07-23T13:09:20Z
1,171,625
<p>Look at the python section of <a href="http://json.org/" rel="nofollow">json.org</a>. The standard library support for JSON started at python 2.6, which I believe is newer than what the app engine provides. Maybe one of the other options listed?</p>
0
2009-07-23T13:14:54Z
[ "python", "json", "google-app-engine" ]
How can I parse JSON in Google App Engine?
1,171,584
<p>I'd like to parse a JSON string into an object under Google App Engine (python). What do you recommend? Something to encode/stringify would be nice too. Is what you recommend built in, or a library that I have to include in my app? Is it secure? Thanks.</p>
77
2009-07-23T13:09:20Z
1,171,631
<p>If you're using Python2.6 or greater, I've used with success the built-in <a href="http://docs.python.org/library/json.html" rel="nofollow">json</a>.load function. Otherwise, <a href="http://code.google.com/p/simplejson/" rel="nofollow">simplejson</a> works on 2.4 without dependencies. </p>
1
2009-07-23T13:15:38Z
[ "python", "json", "google-app-engine" ]
How can I parse JSON in Google App Engine?
1,171,584
<p>I'd like to parse a JSON string into an object under Google App Engine (python). What do you recommend? Something to encode/stringify would be nice too. Is what you recommend built in, or a library that I have to include in my app? Is it secure? Thanks.</p>
77
2009-07-23T13:09:20Z
1,171,730
<p>Consider using <a href="http://docs.djangoproject.com/en/dev/topics/serialization/">Django's json lib</a>, which is included with GAE.</p> <pre><code>from django.utils import simplejson as json # load the object from a string obj = json.loads( string ) </code></pre> <p>The link above has examples of Django's serializer, and here's the link for <a href="http://simplejson.googlecode.com/svn/tags/simplejson-2.0.9/docs/index.html">simplejson's documentation</a>.</p> <p>If you're looking at storing Python class instances or objects (as opposed to compositions of lists, strings, numbers, and dictionaries), you probably want to look at <a href="http://docs.python.org/library/pickle.html">pickle</a>.</p> <p>I hope that helps.</p> <p>Incidentally, to get Django 1.0 (instead of Django 0.96) running on GAE, you can use the following call in your main.py, per <a href="http://code.google.com/appengine/docs/python/tools/libraries.html#Django">this article</a>:</p> <pre><code>from google.appengine.dist import use_library use_library('django', '1.0') </code></pre> <hr> <h2>Edit: Native JSON support in Google App Engine 1.6.0 with Python 2.7</h2> <p>As of Google App Engine 1.6.0, you can <a href="http://code.google.com/appengine/docs/python/python27/using27.html">use the Python 2.7 runtime</a> by adding <code>runtime: python27</code> in <code>app.yaml</code>, and then you can import the native JSON library with <code>import json</code>.</p>
111
2009-07-23T13:29:33Z
[ "python", "json", "google-app-engine" ]
How can I parse JSON in Google App Engine?
1,171,584
<p>I'd like to parse a JSON string into an object under Google App Engine (python). What do you recommend? Something to encode/stringify would be nice too. Is what you recommend built in, or a library that I have to include in my app? Is it secure? Thanks.</p>
77
2009-07-23T13:09:20Z
3,948,103
<p>Google App Engine now supports python 2.7. If using python 2.7, you can do the following:</p> <pre><code>import json structured_dictionary = json.loads(string_received) </code></pre>
18
2010-10-16T07:58:42Z
[ "python", "json", "google-app-engine" ]
Trying to understand Django's sorl-thumbnail
1,171,680
<p>I have been playing around with <code>sorl-thumbnail</code> for Django. And trying to understand how it works better. </p> <p>I've read the guide for it, installed it in my site-packages, made sure PIL is installed correctly, put <code>sorl.thumbnail</code> in the <code>INSTALLED APPS</code> in my <strong>settings.py</strong>, put <code>from sorl.thumbnail.fields import ImageWithThumbnailsField</code> at the top in my <strong>models.py</strong>, added <code>image = ImageWithThumbnailsField(upload to="images/", thumbnail={'size':(80, 80)})</code> as one of my model fields, passed the model through my view to the template, and in the template added <code>{% load thumbnail %}</code> at the top and put in the variable <code>{{ mymodel.image.thumbnail_tag }}</code> in there too.</p> <p>But from what I understood is that when I upload an image through the admin, it would create the thumbnail straight away, but it only actually creates in when I see my template in the browser? Is this correct? The thumbnail shows fine, it looks great in fact, but I thought that adding the model field part of it would create the thumbnail instantly once the image has uploaded? ...Why not just use the <code>models.ImageField</code> in my model instead?</p> <p>...or have I done this all OK and I've just got the way it works wrong?</p>
6
2009-07-23T13:22:30Z
1,232,375
<p>I'm one of the sorl-thumbnail developers.</p> <p>Firstly, you don't need to <code>{% load thumbnail %}</code> unless you're just using the thumbnail tag rather than a thumbnail field.</p> <p>Currently, a thumbnail is only ever created the first time it is used - even if you use the field [I'll get around to changing that one day if no-one else does first]. The advantage of the field is that you can specify the sizing rather than giving the freedom to the designer in the template level [and making it easier for an admin thumbnail].</p> <p>Both ways work, you get to decide which works best for you.</p>
2
2009-08-05T10:29:15Z
[ "python", "django", "image-processing" ]
Trying to understand Django's sorl-thumbnail
1,171,680
<p>I have been playing around with <code>sorl-thumbnail</code> for Django. And trying to understand how it works better. </p> <p>I've read the guide for it, installed it in my site-packages, made sure PIL is installed correctly, put <code>sorl.thumbnail</code> in the <code>INSTALLED APPS</code> in my <strong>settings.py</strong>, put <code>from sorl.thumbnail.fields import ImageWithThumbnailsField</code> at the top in my <strong>models.py</strong>, added <code>image = ImageWithThumbnailsField(upload to="images/", thumbnail={'size':(80, 80)})</code> as one of my model fields, passed the model through my view to the template, and in the template added <code>{% load thumbnail %}</code> at the top and put in the variable <code>{{ mymodel.image.thumbnail_tag }}</code> in there too.</p> <p>But from what I understood is that when I upload an image through the admin, it would create the thumbnail straight away, but it only actually creates in when I see my template in the browser? Is this correct? The thumbnail shows fine, it looks great in fact, but I thought that adding the model field part of it would create the thumbnail instantly once the image has uploaded? ...Why not just use the <code>models.ImageField</code> in my model instead?</p> <p>...or have I done this all OK and I've just got the way it works wrong?</p>
6
2009-07-23T13:22:30Z
2,178,420
<p>how about adding some jCrop in the admin to specify area of thumbnail ? Woul be pretty cool :) </p>
0
2010-02-01T16:51:31Z
[ "python", "django", "image-processing" ]
Comparison of the multiprocessing module and pyro?
1,171,767
<p>I use <a href="http://pyro.sourceforge.net/">pyro</a> for basic management of parallel jobs on a compute cluster. I just moved to a cluster where I will be responsible for using all the cores on each compute node. (On previous clusters, each core has been a separate node.) The python <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> module seems like a good fit for this. I notice it can also be used for <a href="http://docs.python.org/library/multiprocessing.html#using-a-remote-manager">remote-process communication</a>. If anyone has used both frameworks for remote-process communication, I'd be grateful to hear how they stack up against each other. The obvious benefit of the multiprocessing module is that it's built-in from 2.6. Apart from that, it's hard for me to tell which is better.</p>
8
2009-07-23T13:34:07Z
1,955,757
<p>EDIT: I'm changing my answer so you avoid pain. multiprocessing is immature, the docs on BaseManager are <strong>INCORRECT</strong>, and if you're an object-oriented thinker that wants to create shared objects on the fly at run-time, <strong>USE PYRO OR YOU WILL SERIOUSLY REGRET IT!</strong> If you are just doing functional programming using a shared queue that you register up front like all the stupid examples GOOD FOR YOU.</p> <h2>Short Answer</h2> <p>Multiprocessing:</p> <ul> <li>Feels awkward doing object-oriented remote objects</li> <li>Easy breezy crypto (authkey)</li> <li>Over a network or just inter-process communication</li> <li>No nameserver extra hassle like in Pyro (there are ways to get around this)</li> <li><strong>Edit:</strong> Can't "register" objects once the manager is instantiated!!??</li> <li><strong>Edit:</strong> If a server isn't not started, the client throws some "Invalid argument" exception instead of just saying "Failed to connect" WTF!?</li> <li><strong>Edit:</strong> BaseManager documentation is incorrect! There is no "start" method!?!</li> <li><strong>Edit:</strong> Very little examples as to how to use it.</li> </ul> <p>Pyro:</p> <ul> <li>Simple remote objects</li> <li>Network comms only (loopback if local only)</li> <li><strong>Edit:</strong> This thing just WORKS, and it likes object-oriented object sharing, which makes me LIKE it</li> <li><strong>Edit:</strong> Why isn't THIS a part of the standard library instead of that multiprocessing piece of crap that tried to copy it and failed miserably?</li> </ul> <p><strong>Edit:</strong> The first time I answered this I had just dived into 2.6 multiprocessing. In the code I show below, the Texture class is registered and shared as a proxy, however the "data" attribute inside of it is NOT. So guess what happens, each process has a separate copy of the "data" attribute inside of the Texture proxy, despite what you might expect. I just spent untold amount of hours trying to figure out how a good pattern to create shared objects during run-time and I kept running in to brick walls. It has been quite confusing and frustrating. Maybe it's just me, but looking around at the scant examples people have attempted it doesn't look like it.</p> <p>I'm having to make the painful decision of dropping multiprocessing library and preferring Pyro until multiprocessing is more mature. While initially I was excited to learn multiprocessing being built into python, I am now thoroughly disgusted with it and would rather install the Pyro package many many times with glee that such a beautiful library exists for python.</p> <h2>Long Answer</h2> <p>I have used Pyro in past projects and have been very happy with it. I have also started to work with multiprocessing new in 2.6. </p> <p>With multiprocessing I found it a bit awkward to allow shared objects to be created as needed. It seems like, in its youth, the multiprocessing module has been more geared for functional programming as opposed to object-oriented. However this is not entirely true because it is possible to do, I'm just feeling constrained by the "register" calls.</p> <p>For example:</p> <p>manager.py:</p> <pre><code>from multiprocessing import Process from multiprocessing.managers import BaseManager class Texture(object): def __init__(self, data): self.data = data def setData(self, data): print "Calling set data %s" % (data) self.data = data def getData(self): return self.data class TextureManager(BaseManager): def __init__(self, address=None, authkey=''): BaseManager.__init__(self, address, authkey) self.textures = {} def addTexture(self, name, texture): self.textures[name] = texture def hasTexture(self, name): return name in self.textures </code></pre> <p>server.py:</p> <pre><code>from multiprocessing import Process from multiprocessing.managers import BaseManager from manager import Texture, TextureManager manager = TextureManager(address=('', 50000), authkey='hello') def getTexture(name): if manager.hasTexture(name): return manager.textures[name] else: texture = Texture([0]*100) manager.addTexture(name, texture) manager.register(name, lambda: texture) TextureManager.register("getTexture", getTexture) if __name__ == "__main__": server = manager.get_server() server.serve_forever() </code></pre> <p>client.py:</p> <pre><code>from multiprocessing import Process from multiprocessing.managers import BaseManager from manager import Texture, TextureManager if __name__ == "__main__": manager = TextureManager(address=('127.0.0.1', 50000), authkey='hello') manager.connect() TextureManager.register("getTexture") texture = manager.getTexture("texture2") data = [2] * 100 texture.setData(data) print "data = %s" % (texture.getData()) </code></pre> <p>The awkwardness I'm describing comes from server.py where I register a getTexture function to retrieve a function of a certain name from the TextureManager. As I'm going over this the awkwardness could probably be removed if I made the TextureManager a shareable object which creates/retrieves shareable textures. Meh I'm still playing, but you get the idea. I don't remember encountering this awkwardness using pyro, but there probably is a solution that's cleaner than the example above.</p>
14
2009-12-23T22:51:01Z
[ "python", "rpc", "multiprocessing", "pyro" ]
How to solve this complex recursive problem, pyramid point system
1,171,926
<p>I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.</p> <p>The issue here is not the point calculation, I've gotten that right with some good help from you guys, but if a user gets more point that it parent, they should switch places in the ladder. So that a users parent becomes it's child and so on.</p> <p>The python code I have now doesnt work proper, and I dont really know why.</p> <pre><code>def verify_parents(user): """ This is a recursive function that checks to see if any of the parents should bump up because they got more points than its parent. """ from rottenetter.accounts.models import get_score try: parent = user.parent except: return False else: # If this players score is greater than its parent if get_score(user) &gt; get_score(parent): # change parent user.parent = parent.parent user.save() # change parent's parent to current profile parent.parent = user parent.save() verify_parents(parent) </code></pre> <p>In my mind this should work, if a user has a parent, check to see if the user got more points than its parent, if so, set the users parent to be the parents parent, and set the parents parent to be the user, and then they have switched places. And after that, call the same function with the parent as a target so that it can check it self, and then continue up the ladder.</p> <p>But this doesnt always work, in some cases people aren't bumbed to the right position of some reason.</p> <p>Edit:</p> <p>When one users steps up or down a step in the ladder, it's childs move with him so they still relate to the same parent, unless they to get more points and step up. So it should be unecessary to anything with the parents shouldn't it?</p>
1
2009-07-23T13:55:35Z
1,171,993
<p>I think your problem could be that you aren't setting the child(s) of <code>profile</code> to now have <code>parent</code> as it's/their parent, unless children with parents can't also be parents in your system (which I do not believe to be the case).</p> <p>Alternatively (or possibly together with the previous), you may want to just do <code>parent = profile.parent</code> rather than <code>parent = profile.parent.get_profile()</code>.</p> <p>EDIT: And I see that you did indeed switch to something of that second form, though using <code>user</code> instead of <code>profile</code>.</p> <p>Anyway, since each user can have multiple children (as you stated in a comment on another answer), you might want to keep track of each user's child from within that user's object. Something like...</p> <pre><code>parent = user.parent user.parent = parent.parent parent.parent = user children = user.children for child in children: child.parent = parent user.children = parent.children for child in user.children: if child is user: child = parent child.parent = user parent.children = children for child in user.parent.children: if child is parent: child = user </code></pre> <p>This probably needs refactoring, though, and I may have missed something.</p>
1
2009-07-23T14:04:13Z
[ "python", "django", "recursion" ]
How to solve this complex recursive problem, pyramid point system
1,171,926
<p>I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.</p> <p>The issue here is not the point calculation, I've gotten that right with some good help from you guys, but if a user gets more point that it parent, they should switch places in the ladder. So that a users parent becomes it's child and so on.</p> <p>The python code I have now doesnt work proper, and I dont really know why.</p> <pre><code>def verify_parents(user): """ This is a recursive function that checks to see if any of the parents should bump up because they got more points than its parent. """ from rottenetter.accounts.models import get_score try: parent = user.parent except: return False else: # If this players score is greater than its parent if get_score(user) &gt; get_score(parent): # change parent user.parent = parent.parent user.save() # change parent's parent to current profile parent.parent = user parent.save() verify_parents(parent) </code></pre> <p>In my mind this should work, if a user has a parent, check to see if the user got more points than its parent, if so, set the users parent to be the parents parent, and set the parents parent to be the user, and then they have switched places. And after that, call the same function with the parent as a target so that it can check it self, and then continue up the ladder.</p> <p>But this doesnt always work, in some cases people aren't bumbed to the right position of some reason.</p> <p>Edit:</p> <p>When one users steps up or down a step in the ladder, it's childs move with him so they still relate to the same parent, unless they to get more points and step up. So it should be unecessary to anything with the parents shouldn't it?</p>
1
2009-07-23T13:55:35Z
1,172,115
<p>[correction according to your comment]</p> <p>If the result of the "move" never intends to change the topology of the tree(i.e. when X becomes the parent of its old parent Y, it gives all its children to Y), then the simplest might be to decouple the notion "pyramid nodes" from the "users", with one-to-one relationship. Then if the 'swap' operation does not change the topology of the tree, you would only need to swap the mapping between 'nodeA &lt;=> userA' and 'nodeB &lt;=> userB' so they become 'nodeA &lt;=> userB' and 'nodeB &lt;=> userA'.</p> <p>Since the topology of the tree does not change, this would automagically take care of the children having a correct parent. The downside, of course, is that you no longer can directly find out the 'parent' from a user record and would need to go via the nodes. </p> <p>No code as I am not sure of your application details - but hopefully if this is applicable it should be easy enough to turn into code.</p>
1
2009-07-23T14:23:13Z
[ "python", "django", "recursion" ]
django - circular import problem when executing a command
1,172,386
<p>I'm developing a django application. Modules of importance to my problem are given below:</p> <p><strong>globals.py</strong> --> contains constants that are used throughout the application. <code>SITE_NAME</code> and <code>SITE_DOMAIN</code> are two of those and are used to fill some strings. Here is how I define them:</p> <pre><code>from django.contrib.sites.models import Site ... SITE_DOMAIN = Site.objects.get_current().domain SITE_NAME = Site.objects.get_current().name </code></pre> <p><strong>models.py</strong> --> models live inside this module. imports some constants from globals.py</p> <p><strong>some_command.py</strong> --> a command that imports some constants from globals also.</p> <p>when executed, the command imports a constant from <strong>globals.py</strong> and runs into a circular import problem: inside <strong>globals.py</strong>, <strong>get_current()</strong> from <strong>sites</strong> app is called, and <strong>sites</strong> app in turn imports <strong>models.py</strong> which has imports from <strong>globals.py</strong> as well.</p> <p><strong>EDIT:</strong></p> <p>The application runs flawlessly, without encountering this circular import issue. Importing <strong>globals.py</strong> from shell brings no problems. Even the command can be executed from the shell without calling <strong>manage.py</strong>.</p> <p>So why does <strong>manage.py some_command</strong> fail due to a circular import?</p> <p>Thanks in advance.</p>
2
2009-07-23T15:00:34Z
1,172,453
<p>Is there any particular reason you need to store SITE_DOMAIN and SITE_NAME in globals.py? These are already available directly from the sites framework.</p> <p>According to <a href="http://docs.djangoproject.com/en/dev/ref/contrib/sites/?from=olddocs#caching-the-current-site-object" rel="nofollow">the docs</a>, the site object is cached the first time you access it, so importing it and using it there directly doesn't hurt.</p>
1
2009-07-23T15:10:39Z
[ "python", "django", "import", "circular-reference" ]
Django-admin : How to display link to object info page instead of edit form , in records change list?
1,172,584
<p>I am customizing Django-admin for an application am working on . so far the customization is working file , added some views . but I am wondering how to change the records link in change_list display to display an info page instead of change form ?!</p> <p>in this blog post :<a href="http://www.theotherblog.com/Articles/2009/06/02/">http://www.theotherblog.com/Articles/2009/06/02/</a> extending-the-django-admin-interface/ Tom said :</p> <p>" You can add images or links in the listings view by defining a function then adding my_func.allow_tags = True "</p> <p>which i didn't fully understand !!</p> <p>right now i have profile function , which i need when i click on a member in the records list i can display it ( or adding another button called - Profile - ) , also how to add link for every member ( Edit : redirect me to edit form for this member ) .</p> <p>How i can achieve that ?!</p> <p>Regards Hamza</p>
7
2009-07-23T15:26:41Z
1,172,814
<p>If I understand your question right you want to add your own link to the listing view, and you want that link to point to some info page you have created.</p> <p>To do that, create a function to return the link HTML in your Admin object. Then use that function in your list. Like this:</p> <pre><code>class ModelAdmin(admin.ModelAdmin): def view_link(self, obj): return u"&lt;a href='view/%d/'&gt;View&lt;/a&gt;" % obj.id view_link.short_description = '' view_link.allow_tags = True list_display = ('id', view_link) </code></pre>
19
2009-07-23T16:04:54Z
[ "python", "django", "django-admin", "admin" ]
Django-admin : How to display link to object info page instead of edit form , in records change list?
1,172,584
<p>I am customizing Django-admin for an application am working on . so far the customization is working file , added some views . but I am wondering how to change the records link in change_list display to display an info page instead of change form ?!</p> <p>in this blog post :<a href="http://www.theotherblog.com/Articles/2009/06/02/">http://www.theotherblog.com/Articles/2009/06/02/</a> extending-the-django-admin-interface/ Tom said :</p> <p>" You can add images or links in the listings view by defining a function then adding my_func.allow_tags = True "</p> <p>which i didn't fully understand !!</p> <p>right now i have profile function , which i need when i click on a member in the records list i can display it ( or adding another button called - Profile - ) , also how to add link for every member ( Edit : redirect me to edit form for this member ) .</p> <p>How i can achieve that ?!</p> <p>Regards Hamza</p>
7
2009-07-23T15:26:41Z
1,172,841
<p>Take a look at: <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/">http://docs.djangoproject.com/en/dev/ref/contrib/admin/</a>, ModelAdmin.list_display part, it says: A string representing an attribute on the model. This behaves almost the same as the callable, but self in this context is the model instance. Here's a full model example:</p> <pre><code>class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) color_code = models.CharField(max_length=6) def colored_name(self): return '&lt;span style="color: #%s;"&gt;%s %s&lt;/span&gt;' % (self.color_code, self.first_name, self.last_name) colored_name.allow_tags = True class PersonAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name', 'colored_name') </code></pre> <p>So I guess, if you add these two methods to Person</p> <pre><code>def get_absolute_url(self): return '/profiles/%s/' % (self.id) def profile_link(self): return '&lt;a href="%s"&gt;%s&lt;/a&gt;' % (self.get_absolute_url(), self.username) profile_link.allow_tags = True </code></pre> <p>and changes PersonAdmin to</p> <pre><code>class PersonAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name', 'colored_name', 'profile_link') </code></pre> <p>Then you done</p>
7
2009-07-23T16:08:31Z
[ "python", "django", "django-admin", "admin" ]
Python file at GAE
1,172,725
<p>I have added a python file at google app engine. how to send a request to this file. Is this file needed to b executed explicitly?</p>
0
2009-07-23T15:49:49Z
1,173,195
<p>Your app.yaml file decides which python script to run, depending on the request URL.</p> <p>See examples at the <a href="http://code.google.com/appengine/docs/python/config/appconfig.html" rel="nofollow">Google Docs</a>. You can even use regexp.</p>
2
2009-07-23T17:11:52Z
[ "python", "google-app-engine" ]
Tokenizing blocks of code in Python
1,172,738
<p>I have this string: </p> <pre><code>[a [a b] [c e f] d] </code></pre> <p>and I want a list like this</p> <pre><code>lst[0] = "a" lst[1] = "a b" lst[2] = "c e f" lst[3] = "d" </code></pre> <p>My current implementation that I don't think is elegant/pythonic is two recursive functions (one splitting with '[' and the other with ']' ) but I am sure it can be done using list comprehensions or regular expressions (but I can't figure out a sane way to do it).</p> <p>Any ideas?</p>
1
2009-07-23T15:51:24Z
1,172,764
<p>Well, if it's a recursive data structure you're going to need a recursive function to cleanly navigate it.</p> <p>But Python does have a tokenizer library which might be useful: <a href="http://docs.python.org/library/tokenize.html" rel="nofollow">http://docs.python.org/library/tokenize.html</a></p>
1
2009-07-23T15:56:43Z
[ "python", "regex", "list-comprehension", "tokenize" ]
Tokenizing blocks of code in Python
1,172,738
<p>I have this string: </p> <pre><code>[a [a b] [c e f] d] </code></pre> <p>and I want a list like this</p> <pre><code>lst[0] = "a" lst[1] = "a b" lst[2] = "c e f" lst[3] = "d" </code></pre> <p>My current implementation that I don't think is elegant/pythonic is two recursive functions (one splitting with '[' and the other with ']' ) but I am sure it can be done using list comprehensions or regular expressions (but I can't figure out a sane way to do it).</p> <p>Any ideas?</p>
1
2009-07-23T15:51:24Z
1,172,898
<p>Actually this really isn't a recursive data structure, note that <code>a</code> and <code>d</code> are in separate lists. You're just splitting the string over the bracket characters and getting rid of some white space.</p> <p>I'm sure somebody can find something cleaner, but if you want a one-liner something like the following should get you close:</p> <pre><code>parse_str = '[a [a b] [c e f] d]' lst = [s.strip() for s in re.split('[\[\]]', parse_str) if s.strip()] &gt;&gt;&gt;lst ['a', 'a b', 'c e f', 'd'] </code></pre>
4
2009-07-23T16:20:25Z
[ "python", "regex", "list-comprehension", "tokenize" ]
Tokenizing blocks of code in Python
1,172,738
<p>I have this string: </p> <pre><code>[a [a b] [c e f] d] </code></pre> <p>and I want a list like this</p> <pre><code>lst[0] = "a" lst[1] = "a b" lst[2] = "c e f" lst[3] = "d" </code></pre> <p>My current implementation that I don't think is elegant/pythonic is two recursive functions (one splitting with '[' and the other with ']' ) but I am sure it can be done using list comprehensions or regular expressions (but I can't figure out a sane way to do it).</p> <p>Any ideas?</p>
1
2009-07-23T15:51:24Z
1,173,033
<p>If it's a recursive data structure, then recursion is good to traverse it. <em>However</em>, parsing the string to create the structure does not need to be recursive. One alternative way I would do it is iterative:</p> <pre><code>origString = "[a [a b] [c [x z] d e] f]".split(" ") stack = [] for element in origString: if element[0] == "[": newLevel = [ element[1:] ] stack.append(newLevel) elif element[-1] == "]": stack[-1].append(element[0:-1]) finished = stack.pop() if len(stack) != 0: stack[-1].append(finished) else: root = finished else: stack[-1].append(element) print root </code></pre> <p>Of course, this can probably be improved, and it will create lists of lists of lists of ... of strings, which isn't exactly what your example wanted. However, it does handle arbitrary depth of the tree.</p>
1
2009-07-23T16:45:24Z
[ "python", "regex", "list-comprehension", "tokenize" ]
Connecting to APNS for iPhone Using Python
1,172,769
<p>I'm trying to send push notifications to an iPhone using Python. I've exported my <strong>certificate and private key</strong> into a p12 file from keychain access and then converted it into pem file using the following command:</p> <pre><code>openssl pkcs12 -in cred.p12 -out cert.pem -nodes -clcerts </code></pre> <p>I'm using <a href="http://code.google.com/p/apns-python-wrapper/wiki/APNSWrapperOverview">APNSWrapper</a> in Python for the connection. </p> <p>I run the following code:</p> <pre> deviceToken = 'Qun\xaa\xd ... c0\x9c\xf6\xca' # create wrapper wrapper = APNSNotificationWrapper('/path/to/cert/cert.pem', True) # create message message = APNSNotification() message.token(deviceToken) message.badge(5) # add message to tuple and send it to APNS server wrapper.append(message) wrapper.notify() </pre> <p>And then I get the error message:</p> <pre> ssl.SSLError: (1, '_ssl.c:485: error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown') </pre> <p>Can anyone help me out on this? </p>
12
2009-07-23T15:57:29Z
1,173,457
<p>Have you considered the <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> package? The below code is taken from <a href="http://blog.nuclearbunny.org/2009/05/11/connecting-to-apple-push-notification-services-using-python-twisted/" rel="nofollow">here</a>:</p> <pre><code>from struct import pack from OpenSSL import SSL from twisted.internet import reactor from twisted.internet.protocol import ClientFactory, Protocol from twisted.internet.ssl import ClientContextFactory APNS_SERVER_HOSTNAME = "&lt;insert the push hostname from your iPhone developer portal&gt;" APNS_SERVER_PORT = 2195 APNS_SSL_CERTIFICATE_FILE = "&lt;your ssl certificate.pem&gt;" APNS_SSL_PRIVATE_KEY_FILE = "&lt;your ssl private key.pem&gt;" class APNSClientContextFactory(ClientContextFactory): def __init__(self): self.ctx = SSL.Context(SSL.SSLv3_METHOD) self.ctx.use_certificate_file(APNS_SSL_CERTIFICATE_FILE) self.ctx.use_privatekey_file(APNS_SSL_PRIVATE_KEY_FILE) def getContext(self): return self.ctx class APNSProtocol(Protocol): def sendMessage(self, deviceToken, payload): # notification messages are binary messages in network order # using the following format: # &lt;1 byte command&gt; &lt;2 bytes length&gt;&lt;token&gt; &lt;2 bytes length&gt;&lt;payload&gt; fmt = "!cH32cH%dc" % len(payload) command = 0 msg = struct.pack(fmt, command, deviceToken, len(payload), payload) self.transport.write(msg) class APNSClientFactory(ClientFactory): def buildProtocol(self, addr): print "Connected to APNS Server %s:%u" % (addr.host, addr.port) return APNSProtocol() def clientConnectionLost(self, connector, reason): print "Lost connection. Reason: %s" % reason def clientConnectionFailed(self, connector, reason): print "Connection failed. Reason: %s" % reason if __name__ == '__main__': reactor.connectSSL(APNS_SERVER_HOSTNAME, APNS_SERVER_PORT, APNSClientFactory(), APNSClientContextFactory()) reactor.run() </code></pre>
2
2009-07-23T18:00:23Z
[ "iphone", "python", "ssl", "push-notification" ]
Connecting to APNS for iPhone Using Python
1,172,769
<p>I'm trying to send push notifications to an iPhone using Python. I've exported my <strong>certificate and private key</strong> into a p12 file from keychain access and then converted it into pem file using the following command:</p> <pre><code>openssl pkcs12 -in cred.p12 -out cert.pem -nodes -clcerts </code></pre> <p>I'm using <a href="http://code.google.com/p/apns-python-wrapper/wiki/APNSWrapperOverview">APNSWrapper</a> in Python for the connection. </p> <p>I run the following code:</p> <pre> deviceToken = 'Qun\xaa\xd ... c0\x9c\xf6\xca' # create wrapper wrapper = APNSNotificationWrapper('/path/to/cert/cert.pem', True) # create message message = APNSNotification() message.token(deviceToken) message.badge(5) # add message to tuple and send it to APNS server wrapper.append(message) wrapper.notify() </pre> <p>And then I get the error message:</p> <pre> ssl.SSLError: (1, '_ssl.c:485: error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown') </pre> <p>Can anyone help me out on this? </p>
12
2009-07-23T15:57:29Z
1,254,027
<p>I recently did this using Django - <a href="http://leecutsco.de/2009/07/14/push-on-the-iphone/" rel="nofollow">http://leecutsco.de/2009/07/14/push-on-the-iphone/</a></p> <p>May be useful? It's making use of no extra libraries other than those included with Python already. Wouldn't take much to extract the send_message() method out.</p>
8
2009-08-10T09:58:26Z
[ "iphone", "python", "ssl", "push-notification" ]
Connecting to APNS for iPhone Using Python
1,172,769
<p>I'm trying to send push notifications to an iPhone using Python. I've exported my <strong>certificate and private key</strong> into a p12 file from keychain access and then converted it into pem file using the following command:</p> <pre><code>openssl pkcs12 -in cred.p12 -out cert.pem -nodes -clcerts </code></pre> <p>I'm using <a href="http://code.google.com/p/apns-python-wrapper/wiki/APNSWrapperOverview">APNSWrapper</a> in Python for the connection. </p> <p>I run the following code:</p> <pre> deviceToken = 'Qun\xaa\xd ... c0\x9c\xf6\xca' # create wrapper wrapper = APNSNotificationWrapper('/path/to/cert/cert.pem', True) # create message message = APNSNotification() message.token(deviceToken) message.badge(5) # add message to tuple and send it to APNS server wrapper.append(message) wrapper.notify() </pre> <p>And then I get the error message:</p> <pre> ssl.SSLError: (1, '_ssl.c:485: error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown') </pre> <p>Can anyone help me out on this? </p>
12
2009-07-23T15:57:29Z
1,282,565
<p>there were a few bugs in the originally posted code, so here's a corrected version that works for me.</p> <pre><code>from struct import pack from OpenSSL import SSL from twisted.internet import reactor from twisted.internet.protocol import ClientFactory, Protocol from twisted.internet.ssl import ClientContextFactory import binascii import struct APNS_SERVER_HOSTNAME = "gateway.sandbox.push.apple.com" APNS_SERVER_PORT = 2195 APNS_SSL_CERTIFICATE_FILE = "&lt;your ssl certificate.pem&gt;" APNS_SSL_PRIVATE_KEY_FILE = "&lt;your ssl private key.pem&gt;" DEVICE_TOKEN = "&lt;hexlified device token&gt;" MESSAGE = '{"aps":{"alert":"twisted test"}}' class APNSClientContextFactory(ClientContextFactory): def __init__(self): self.ctx = SSL.Context(SSL.SSLv3_METHOD) self.ctx.use_certificate_file(APNS_SSL_CERTIFICATE_FILE) self.ctx.use_privatekey_file(APNS_SSL_PRIVATE_KEY_FILE) def getContext(self): return self.ctx class APNSProtocol(Protocol): def connectionMade(self): print "connection made" self.sendMessage(binascii.unhexlify(DEVICE_TOKEN), MESSAGE) self.transport.loseConnection() def sendMessage(self, deviceToken, payload): # notification messages are binary messages in network order # using the following format: # &lt;1 byte command&gt; &lt;2 bytes length&gt;&lt;token&gt; &lt;2 bytes length&gt;&lt;payload&gt; fmt = "!cH32sH%ds" % len(payload) command = '\x00' msg = struct.pack(fmt, command, 32, deviceToken, len(payload), payload) print "%s: %s" %(binascii.hexlify(deviceToken), binascii.hexlify(msg)) self.transport.write(msg) class APNSClientFactory(ClientFactory): def buildProtocol(self, addr): print "Connected to APNS Server %s:%u" % (addr.host, addr.port) return APNSProtocol() def clientConnectionLost(self, connector, reason): print "Lost connection. Reason: %s" % reason def clientConnectionFailed(self, connector, reason): print "Connection failed. Reason: %s" % reason if __name__ == '__main__': reactor.connectSSL(APNS_SERVER_HOSTNAME, APNS_SERVER_PORT, APNSClientFactory(), APNSClientContextFactory()) reactor.run() </code></pre>
1
2009-08-15T18:59:00Z
[ "iphone", "python", "ssl", "push-notification" ]
Connecting to APNS for iPhone Using Python
1,172,769
<p>I'm trying to send push notifications to an iPhone using Python. I've exported my <strong>certificate and private key</strong> into a p12 file from keychain access and then converted it into pem file using the following command:</p> <pre><code>openssl pkcs12 -in cred.p12 -out cert.pem -nodes -clcerts </code></pre> <p>I'm using <a href="http://code.google.com/p/apns-python-wrapper/wiki/APNSWrapperOverview">APNSWrapper</a> in Python for the connection. </p> <p>I run the following code:</p> <pre> deviceToken = 'Qun\xaa\xd ... c0\x9c\xf6\xca' # create wrapper wrapper = APNSNotificationWrapper('/path/to/cert/cert.pem', True) # create message message = APNSNotification() message.token(deviceToken) message.badge(5) # add message to tuple and send it to APNS server wrapper.append(message) wrapper.notify() </pre> <p>And then I get the error message:</p> <pre> ssl.SSLError: (1, '_ssl.c:485: error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown') </pre> <p>Can anyone help me out on this? </p>
12
2009-07-23T15:57:29Z
1,398,617
<p>I tried both <code>APNSWrapper</code> and Lee Peckham's code and couldn't get it to work under Snow Leopard with Python 2.6. After a lot of trial and error it finally worked with <code>pyOpenSSL</code>. </p> <p>I already did a post with details and code snippets <a href="http://ramin.firoozye.com/2009/09/09/push-notification-and-python-django/" rel="nofollow">here</a> so I'll just refer you there.</p>
0
2009-09-09T09:44:32Z
[ "iphone", "python", "ssl", "push-notification" ]
Connecting to APNS for iPhone Using Python
1,172,769
<p>I'm trying to send push notifications to an iPhone using Python. I've exported my <strong>certificate and private key</strong> into a p12 file from keychain access and then converted it into pem file using the following command:</p> <pre><code>openssl pkcs12 -in cred.p12 -out cert.pem -nodes -clcerts </code></pre> <p>I'm using <a href="http://code.google.com/p/apns-python-wrapper/wiki/APNSWrapperOverview">APNSWrapper</a> in Python for the connection. </p> <p>I run the following code:</p> <pre> deviceToken = 'Qun\xaa\xd ... c0\x9c\xf6\xca' # create wrapper wrapper = APNSNotificationWrapper('/path/to/cert/cert.pem', True) # create message message = APNSNotification() message.token(deviceToken) message.badge(5) # add message to tuple and send it to APNS server wrapper.append(message) wrapper.notify() </pre> <p>And then I get the error message:</p> <pre> ssl.SSLError: (1, '_ssl.c:485: error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown') </pre> <p>Can anyone help me out on this? </p>
12
2009-07-23T15:57:29Z
1,745,843
<p>Try to update to latest APNSWrapper version (0.4). There is build-in support of openssl command line tool (openssl s_client) now.</p>
1
2009-11-17T00:33:04Z
[ "iphone", "python", "ssl", "push-notification" ]
Python Graphing Utility for GUI with Animations
1,172,776
<p>I am trying to create a GUI interface in VB to track... oh, nevermind.</p> <p>Basically, I want to create a GUI in python to display data, but I am finding that mathplotlib is not suiting my needs. I would like to be able to highlight certain datapoints, have more freedom in the text drawn to the screen, have animations on data movement, and have dropdown menus for data points. From what I have seen, I do not believe that mathplotlib can do these things. What utility can I look into to better suit my needs?</p>
4
2009-07-23T15:58:15Z
1,172,978
<p>QGraphicsScene/View from PyQt4 is a fantastic piece of code. Although your description makes me think that some upfront work will be necessary to make things work. </p> <p>...don 't trust me, I'm biased ;) Get the library <a href="http://www.riverbankcomputing.co.uk/software/pyqt/download" rel="nofollow">here</a> and check the demos. </p>
0
2009-07-23T16:35:41Z
[ "python" ]
Python Graphing Utility for GUI with Animations
1,172,776
<p>I am trying to create a GUI interface in VB to track... oh, nevermind.</p> <p>Basically, I want to create a GUI in python to display data, but I am finding that mathplotlib is not suiting my needs. I would like to be able to highlight certain datapoints, have more freedom in the text drawn to the screen, have animations on data movement, and have dropdown menus for data points. From what I have seen, I do not believe that mathplotlib can do these things. What utility can I look into to better suit my needs?</p>
4
2009-07-23T15:58:15Z
1,173,117
<p>The equivalent of matplotlib in the PyQt world is PyQwt (matplotlib integrates with PyQt also, but with PyQwt the integration is smoother). Take a look at this comparison between matplotlib and PyQwt:</p> <p><a href="http://eli.thegreenplace.net/2009/06/05/plotting-in-python-matplotlib-vs-pyqwt/" rel="nofollow">http://eli.thegreenplace.net/2009/06/05/plotting-in-python-matplotlib-vs-pyqwt/</a></p>
0
2009-07-23T16:58:50Z
[ "python" ]
Python Graphing Utility for GUI with Animations
1,172,776
<p>I am trying to create a GUI interface in VB to track... oh, nevermind.</p> <p>Basically, I want to create a GUI in python to display data, but I am finding that mathplotlib is not suiting my needs. I would like to be able to highlight certain datapoints, have more freedom in the text drawn to the screen, have animations on data movement, and have dropdown menus for data points. From what I have seen, I do not believe that mathplotlib can do these things. What utility can I look into to better suit my needs?</p>
4
2009-07-23T15:58:15Z
1,173,870
<p>I haven't used it myself but <a href="http://code.enthought.com/projects/chaco/" rel="nofollow">Chaco</a> seems to fit some of your needs. It is more interactive than matplotlib and can be used to make quite interactive applications. </p> <blockquote> <p>Chaco is a Python plotting application toolkit that facilitates writing plotting applications at all levels of complexity, from simple scripts with hard-coded data to large plotting programs with complex data interrelationships and a multitude of interactive tools. While Chaco generates attractive static plots for publication and presentation, it also works well for interactive data visualization and exploration.</p> </blockquote> <p><img src="http://code.enthought.com/projects/chaco/docs/html/_images/vanderwaals.png" width="400"></p>
2
2009-07-23T19:11:28Z
[ "python" ]
Python Graphing Utility for GUI with Animations
1,172,776
<p>I am trying to create a GUI interface in VB to track... oh, nevermind.</p> <p>Basically, I want to create a GUI in python to display data, but I am finding that mathplotlib is not suiting my needs. I would like to be able to highlight certain datapoints, have more freedom in the text drawn to the screen, have animations on data movement, and have dropdown menus for data points. From what I have seen, I do not believe that mathplotlib can do these things. What utility can I look into to better suit my needs?</p>
4
2009-07-23T15:58:15Z
6,274,686
<p>PyQt + <a href="http://mathgl.sf.net/" rel="nofollow">MathGL</a> can do it easily. See this <a href="http://mathgl.sourceforge.net/mathgl_en/mathgl_en_15.html#MathGL-and-PyQt" rel="nofollow">sample</a>.</p>
0
2011-06-08T05:49:17Z
[ "python" ]
Mismatch between MySQL and Python
1,172,790
<p><em>I know the mismatch between Object Oriented Technology and the Relational Technology, <a href="http://www.lalitbhatt.com/tiki-index.php?page=Introduction+to+ORM" rel="nofollow">generally here</a>.</em> </p> <p>But I do not know the mismatch between MySQL and Python, and other tools, not just ORMs, to deal with the issue, missing in the latter article.</p> <p>Questions:</p> <ol> <li>How is the problem dealt between MySQL and Python? </li> <li>Does <a href="http://code.google.com/appengine/kb/commontasks.html" rel="nofollow">App Engine's non-SQL</a> makes Python work better together?</li> <li>Are there some general tools, perhaps ORM, to deal with mismatches?</li> <li>What are non-standard ways to deal with the problem? </li> <li>Could you say that the nonSQL is a tool to make the object-oriented world of Python match the Relational world? Or does the new design totally avoid the problem?</li> </ol>
-1
2009-07-23T16:00:53Z
1,173,052
<p>ORM is the standard solution for making the object-oriented world of Python match the Relational world of MySQL.</p> <p>There are at least 3 popular ORM components.</p> <ul> <li><p><a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a></p></li> <li><p><a href="http://www.sqlobject.org/" rel="nofollow">SQLObject</a></p></li> <li><p><a href="http://docs.djangoproject.com/en/dev/ref/models/instances/" rel="nofollow">Django's ORM</a>.</p></li> </ul>
3
2009-07-23T16:48:23Z
[ "python", "mysql", "google-app-engine", "mismatch" ]
Mismatch between MySQL and Python
1,172,790
<p><em>I know the mismatch between Object Oriented Technology and the Relational Technology, <a href="http://www.lalitbhatt.com/tiki-index.php?page=Introduction+to+ORM" rel="nofollow">generally here</a>.</em> </p> <p>But I do not know the mismatch between MySQL and Python, and other tools, not just ORMs, to deal with the issue, missing in the latter article.</p> <p>Questions:</p> <ol> <li>How is the problem dealt between MySQL and Python? </li> <li>Does <a href="http://code.google.com/appengine/kb/commontasks.html" rel="nofollow">App Engine's non-SQL</a> makes Python work better together?</li> <li>Are there some general tools, perhaps ORM, to deal with mismatches?</li> <li>What are non-standard ways to deal with the problem? </li> <li>Could you say that the nonSQL is a tool to make the object-oriented world of Python match the Relational world? Or does the new design totally avoid the problem?</li> </ol>
-1
2009-07-23T16:00:53Z
1,177,910
<p>As was once said on comp.lang.python ORM's are like morphine -- it can save you pain if you are really hurting, but if you use it regularly you will end up with really big problems.</p> <p>It's not hard to build relatively low level interfaces between a relational database and an object model. It's extremely hard to migrate an automated ORM mapping to a new design after the fact. Only immature programmers try to simplify things that are not hard without looking ahead to the possible consequences that are extremely hard.</p> <p>The google app engine mini-rdb-with-some-restrictions-removed is nice because it only automates extremely simple stuff and forces you to think about the table layout without pretending that it can all be done automatically.</p>
1
2009-07-24T14:04:49Z
[ "python", "mysql", "google-app-engine", "mismatch" ]
Python Server Pages Implementations
1,173,184
<p>I've been a PHP developer for quite awhile, and I've heard good things about using Python for web scripting. After a bit of research, I found mod_python, which integrates with Apache to allow Python Server Pages, which seem very similar to the PHP pages I'm used to. I also found a mod_wsgi which looks similar.</p> <p>I was wondering which implementation the good people of Stack Overflow would recommend for someone who wants good integration with Apache and MySQL and similar functionality to PHP.</p>
3
2009-07-23T17:09:22Z
1,173,209
<p>I believe <strong>mod_wsgi</strong> is the preferred option to mod_python:</p> <p><a href="http://code.google.com/p/modwsgi/" rel="nofollow">http://code.google.com/p/modwsgi/</a></p> <p>Some performance benchmarks seem to suggest that mod_wsgi performs much better also. </p> <p><a href="http://code.google.com/p/modwsgi/wiki/PerformanceEstimates" rel="nofollow">http://code.google.com/p/modwsgi/wiki/PerformanceEstimates</a></p>
3
2009-07-23T17:13:52Z
[ "php", "python", "apache", "mod-python" ]
Does Python unittest report errors immediately?
1,173,310
<p>Does Python's unittest module always report errors in strict correspondence to the execution order of the lines in the code tested? Do errors create the possibility of unexpected changes into the code's variables?</p> <p>I was baffled by a KeyError reported by unittest. The line itself looks okay. On the last line before execution halted, debugging prints of the key requested and the dictionary showed the key was in the dictionary. The key referenced in the KeyError was a different key, but that too seemed to be in the dictionary.</p> <p>I inserted a counter variable into the outer loop to print the number of outer iterations just before the error line (inside an inner loop), and these do not output in the expected sequence. They come out something like 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 2, 2, 2 -- when I would expect something like 0, 0, 0, 1, 1, 1, 2, 2, 2. And debugging prints of internal data show unexpected changes from one loop to the next.</p> <p>Code (with many debugging lines):</p> <pre><code>def onSave(screen_data): counter = 0 for table, flds_dct in self.target_tables.items(): print 'TABLE %s' % table print 'FIELDS: %s' % flds_dct['fields'] tbl_screen_data = {} for fld in flds_dct['fields']: print 'LOOP TOP' print 'FIELD: %' % fld print 'SCREEN DATA: %s' % screen_data print 'COUNTER: %s' % counter print 'SCREEN DATA OUTPUT: %s' % screen_data[fld] tbl_screen_data[fld] = screen_data[fld] print 'LOOP BOTTOM' self.tables[table].addEntry(tbl_screen_data) counter =+ 1 print 'OUTER LOOP BOTTOM' </code></pre> <p>Just before the error, this outputs:</p> <pre><code>TABLE: questions FIELDS: ['whatIsYourQuest', 'whatIsYourName', 'whatIsTheAirSpeedOfSwallow'] LOOP TOP FIELD: whatIsYourQuest SCREEN DATA: {'whatIsYourQuest': 'grail', 'whatIsYourName': 'arthur', 'whatIsYourFavouriteColour': 'blue', 'whatIsTheAirSpeedOfSwallow': 'african or european?', 'whatIsCapitalOfAssyria': 'Nineveh'} COUNTER: 1 SCREEN DATA OUTPUT: grail LOOP BOTTOM OUTER LOOP BOTTOM </code></pre> <p>But then execution stops and I get this error message:</p> <pre><code>line 100, in writeData print 'SCREEN DATA OUTPUT: %s screen_data[fld] KeyError: 'whatIsCapitalOfAssyria' </code></pre> <p>But the error is attributed to a line that has already printed its output, and stops execution after the output of several lines after the line with the error. </p> <p>As I mentioned above, further debugging shows that the contents of screen_data are changed over the iterations of the loop. Crucially, the dictionary passed in has no key 'whatIsCapitalOfAssyria'.</p> <p>The absence of that key was the cause of the error. At some point the code asked the screen_data dictionary 'whatIsCapitalOfAssyria', which it couldn't answer, and so of course it was thrown from the Bridge of Death, err, failed. BUT it was kind of hard to see that when the screen_data object output in debugging lines <em>does</em> have the key; and the error condition reported isn't raised until after execution of many more lines, which confuses inspection of the values local to the error.</p> <p>So how does unittest handle code errors? What am I doing wrong here? How should I be using it to avoid this sort of thing?</p> <p>EDIT: It might help if I added that the method tested triggers calls on a number of other methods, which triggers calls themselves. I think all of those are reasonably well tested, but perhaps the number of interconnected calls matters.</p>
1
2009-07-23T17:33:52Z
1,173,664
<p>I think you're seeing the error at the NEXT leg of your for loop, compared to the one with which you see all the output -- try changing the plain <code>print</code> to <code>print&gt;&gt;stderr,</code> statements so that buffering and possible suppression of output is not a risk.</p>
1
2009-07-23T18:33:36Z
[ "python", "unit-testing", "testing" ]
python namespace hierarchy above object
1,173,401
<p>For example, if this code were contained in a module called some_module</p> <pre><code>class C: class C2: def g(self): @printNamespaceAbove def f(): pass </code></pre> <p>then printNamespaceAbove would be defined so that this code would output something like</p> <pre><code>[some_module,C,C2,g] </code></pre>
0
2009-07-23T17:50:57Z
1,173,815
<p>There is no way to make this code, as presented, have any output -- the body of g (including the decorator you'd like to do the printing) simply <em>DOESN'T</em> execute until g is called. I assume you do not literally intend for "this code" on its own to output anything, but rather intend to add a call such as C.C2().g() [which will actually do the output].</p> <p>There's not really a very efficient way to do this -- you (well, the decorator;-) must start at the module level (which you can identify through the globals of <code>f</code>, the decorator's argument: its name is <code>f.func_globals['__name__']</code> and via its name you can look it up in <code>sys.modules</code>), then you must walk down every possible chain of names until you locate your calling function (e.g. via the <a href="http://docs.python.org/library/inspect.html" rel="nofollow">inspect</a> module in the standard library). Note also that nested functions are a particular headache in several corner cases.</p>
2
2009-07-23T19:00:41Z
[ "python", "namespaces" ]
Randomness in Jython
1,173,520
<p>When using (pseudo) random numbers in Jython, would it be more efficient to use the Python random module or Java's random class?</p>
8
2009-07-23T18:10:07Z
1,173,613
<p>Python's version is much faster in a simple test on my Mac:</p> <pre><code>jython -m timeit -s "import random" "random.random()" </code></pre> <p>1000000 loops, best of 3: 0.266 usec per loop</p> <p>vs</p> <pre><code> jython -m timeit -s "import java.util.Random; random=java.util.Random()" "random.nextDouble()" </code></pre> <p>1000000 loops, best of 3: 1.65 usec per loop</p> <p>Jython version 2.5b3 and Java version 1.5.0_19.</p>
9
2009-07-23T18:26:53Z
[ "java", "python", "random", "jython" ]
Randomness in Jython
1,173,520
<p>When using (pseudo) random numbers in Jython, would it be more efficient to use the Python random module or Java's random class?</p>
8
2009-07-23T18:10:07Z
1,173,628
<p>Java's Random class uses (and indeed must use by Java's specs) a linear congruential algorithm, while Python's uses Mersenne Twister. Mersenne guarantees extremely high quality (though not <em>crypto</em> quality!) random numbers and a ridiculously long period (53-bit precision floats, period 2**19937-1); linear congruential generators have well-known <a href="http://en.wikipedia.org/wiki/Linear%5Fcongruential%5Fgenerator#Advantages%5Fand%5Fdisadvantages%5Fof%5FLCGs" rel="nofollow">issues</a>. If you don't really care about the random numbers' quality, and only care about speed, LCG is however likely to be faster exactly because it's less sophisticated.</p>
4
2009-07-23T18:28:41Z
[ "java", "python", "random", "jython" ]
Wxpython: Positioning a menu under a toolbar button
1,173,642
<p>I have a CheckLabelTool in a wx.ToolBar and I want a menu to popup directly beneath it on mouse click. I'm trying to get the location of the tool so I can set the position of the menu, but everything I've tried (GetEventObject, GetPosition, etc) gives me the position of the toolbar, so consequently the menu pops under the toolbar, but very far from the associated tool. Any suggestions? I need the tool to have toggle and bitmap capability, but I'm not fixed on CheckLabelTool if there's something else that would work better.</p> <p>Thanks!</p>
4
2009-07-23T18:30:38Z
1,175,271
<p>Read the section on the <a href="http://www.wxpython.org/docs/api/wx.Window-class.html#PopupMenu">PopupMenu</a> method on wxpython.org:</p> <blockquote> <p>"Pops up the given menu at the specified coordinates, relative to this window, and returns control when the user has dismissed the menu. If a menu item is selected, the corresponding menu event is generated and will be processed as usual. If the default position is given then the current position of the mouse cursor will be used."</p> </blockquote> <p>You need to bind to the EVT_MENU event of your check tool. Once the tool button is checked, you can pop the menu up. If you don't specify the location of the popup, it will use the current position of the mouse, which is what you want.</p> <p>If you want the menu to pop up at a pre-determined location that is independent of the mouse, you can get the screen location of the toolbar and add an offset </p> <p>Let's look at code:</p> <p>[<strong>Edit</strong>: To show how to compute the position of any point on a tool, I have modified the code to compute and display various points on the tool bar once you click a tool. The menu appears on the lower right corner of the clicked button. It works for me on Windows. I'm curious to know if it doesn't behave on other platforms.] </p> <pre><code>import wx class ViewApp(wx.App): def OnInit(self): self.frame = ToolFrame(None, -1, "Test App") self.frame.Show(True) return True class MyPopupMenu(wx.Menu): def __init__(self, parent): wx.Menu.__init__(self) self.parent = parent minimize = wx.MenuItem(self, wx.NewId(), 'Minimize') self.AppendItem(minimize) self.Bind(wx.EVT_MENU, self.OnMinimize, id=minimize.GetId()) def OnMinimize(self, event): self.parent.Iconize() class ToolFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(350, 250)) self.toolbar = self.CreateToolBar() self.tool_id = wx.NewId() for i in range(3): tool_id = wx.NewId() self.toolbar.AddCheckLabelTool(tool_id, 'Tool', wx.EmptyBitmap(10,10)) self.toolbar.Bind(wx.EVT_MENU, self.OnTool, id=tool_id) self.toolbar.Realize() self.Centre() self.Show() def OnTool(self, event): if event.IsChecked(): # Get the position of the toolbar relative to # the frame. This will be the upper left corner of the first tool bar_pos = self.toolbar.GetScreenPosition()-self.GetScreenPosition() # This is the position of the tool along the tool bar (1st, 2nd, 3rd, etc...) tool_index = self.toolbar.GetToolPos(event.GetId()) # Get the size of the tool tool_size = self.toolbar.GetToolSize() # This is the upper left corner of the clicked tool upper_left_pos = (bar_pos[0]+tool_size[0]*tool_index, bar_pos[1]) # Menu position will be in the lower right corner lower_right_pos = (bar_pos[0]+tool_size[0]*(tool_index+1), bar_pos[1]+tool_size[1]) # Show upper left corner of first tool in black dc = wx.WindowDC(self) dc.SetPen(wx.Pen("BLACK", 4)) dc.DrawCircle(bar_pos[0], bar_pos[1], 4) # Show upper left corner of this tool in blue dc.SetPen(wx.Pen("BLUE", 4)) dc.DrawCircle(upper_left_pos[0], upper_left_pos[1], 4) # Show lower right corner of this tool in green dc.SetPen(wx.Pen("GREEN", 4)) dc.DrawCircle(lower_right_pos[0], lower_right_pos[1], 4) # Correct for the position of the tool bar menu_pos = (lower_right_pos[0]-bar_pos[0],lower_right_pos[1]-bar_pos[1]) # Pop up the menu self.PopupMenu(MyPopupMenu(self), menu_pos) if __name__ == "__main__": app = ViewApp(0) app.MainLoop() </code></pre> <p>Parts of this code come from <a href="http://zetcode.com/wxpython/menustoolbars/">here</a>.</p>
6
2009-07-24T00:43:28Z
[ "python", "menu", "toolbar", "wx" ]
using pyunit on a network thread
1,173,767
<p>I am tasked with writing unit tests for a suite of networked software written in python. Writing units for message builders and other static methods is very simple, but I've hit a wall when it comes to writing a tests for network looped threads.</p> <p>For example: The server it connects to could be on any port, and I want to be able to test the ability to connect to numerous ports (in sequence, not parallel) without actually having to run numerous servers. What is a good way to approach this? Perhaps make server construction and destruction part of the test? Something tells me there must a simpler answer that evades me.</p> <p>I have to imagine there are methods for unit testing networked threads, but I can't seem to find any.</p>
2
2009-07-23T18:52:24Z
1,173,880
<p>It depends on how your network software is layered and how detailed you want your tests to be, but it's certainly feasible in some scenarios to make server setup and tear-down part of the test. For example, when I was working on the Python logging package (before it became part of Python), I had a test (I didn't use <code>pyunit</code>/<code>unittest</code> - it was just an ad-hoc script) which fired up (in one test) four servers to listen on TCP, UDP, HTTP and HTTP/SOAP ports, and then sent network traffic to them. If you're interested, the distribution is <a href="http://www.red-dove.com/logging-0.4.9.6.tar.gz" rel="nofollow">here</a> and the relevant test script in the archive to look at is <code>log_test.py</code>. The Python logging package has of course come some way since then, but the old package is still around for use with versions of Python &lt; 2.3 and >= 1.5.2.</p>
0
2009-07-23T19:13:46Z
[ "python", "unit-testing", "networking", "pyunit" ]
using pyunit on a network thread
1,173,767
<p>I am tasked with writing unit tests for a suite of networked software written in python. Writing units for message builders and other static methods is very simple, but I've hit a wall when it comes to writing a tests for network looped threads.</p> <p>For example: The server it connects to could be on any port, and I want to be able to test the ability to connect to numerous ports (in sequence, not parallel) without actually having to run numerous servers. What is a good way to approach this? Perhaps make server construction and destruction part of the test? Something tells me there must a simpler answer that evades me.</p> <p>I have to imagine there are methods for unit testing networked threads, but I can't seem to find any.</p>
2
2009-07-23T18:52:24Z
1,174,306
<p>I've some test cases that run a server in the setUp and close it in the tearDown. I don't know if it is very elegant way to do it but it works of for me.</p> <p>I am happy to have it and it helps me a lot. </p> <p>If the server init is very long, an alternative would be to automate it with ant. ant would run/stop the server before/after executing the tests.</p> <p>See <a href="http://www.ibm.com/developerworks/opensource/library/os-ecant/" rel="nofollow">here</a> for very interesting tutorial about ant and python </p>
0
2009-07-23T20:34:18Z
[ "python", "unit-testing", "networking", "pyunit" ]
using pyunit on a network thread
1,173,767
<p>I am tasked with writing unit tests for a suite of networked software written in python. Writing units for message builders and other static methods is very simple, but I've hit a wall when it comes to writing a tests for network looped threads.</p> <p>For example: The server it connects to could be on any port, and I want to be able to test the ability to connect to numerous ports (in sequence, not parallel) without actually having to run numerous servers. What is a good way to approach this? Perhaps make server construction and destruction part of the test? Something tells me there must a simpler answer that evades me.</p> <p>I have to imagine there are methods for unit testing networked threads, but I can't seem to find any.</p>
2
2009-07-23T18:52:24Z
1,174,498
<p>I would try to introduce a factory into your existing code that purports to create socket objects. Then in a test pass in a mock factory which creates mock sockets which just pretend they've connected to a server (or not for error cases, which you also want to test, don't you?) and log the message traffic to prove that your code has used the right ports to connect to the right types of servers.</p> <p>Try not to use threads just yet, to simplify testing.</p>
1
2009-07-23T21:09:50Z
[ "python", "unit-testing", "networking", "pyunit" ]
using pyunit on a network thread
1,173,767
<p>I am tasked with writing unit tests for a suite of networked software written in python. Writing units for message builders and other static methods is very simple, but I've hit a wall when it comes to writing a tests for network looped threads.</p> <p>For example: The server it connects to could be on any port, and I want to be able to test the ability to connect to numerous ports (in sequence, not parallel) without actually having to run numerous servers. What is a good way to approach this? Perhaps make server construction and destruction part of the test? Something tells me there must a simpler answer that evades me.</p> <p>I have to imagine there are methods for unit testing networked threads, but I can't seem to find any.</p>
2
2009-07-23T18:52:24Z
1,178,659
<p>You would need to create mock sockets. The exact way to do that would depend on how you create sockets and creating a socket generator would be a good idea. You can also use a mocking library like <a href="http://code.google.com/p/pymox/" rel="nofollow">pymox</a> to make your life easier. It can also possibly eliminate the need to create a socket generator just for the sole purpose of testing.</p> <p>Using pymox, you would do something like this:</p> <pre><code>def test_connect(self): m = mox.Mox() m.StubOutWithMock(socket, 'socket') socket_mock = m.MockAnything() m.socket.socket(socket.AF_INET, socket.SOCK_STREAM).AndReturn(socket_mock) socket_mock.connect(('test_server1', 80)) socket_mock.connect(('test_server2', 81)) socket_mock.connect(('test_server3', 82)) m.ReplayAll() code_to_be_tested() m.VerifyAll() m.UnsetStubs() </code></pre>
0
2009-07-24T16:10:50Z
[ "python", "unit-testing", "networking", "pyunit" ]
Django (?) really slow with large datasets after doing some python profiling
1,173,798
<p>I was comparing an old PHP script of mine versus the newer, fancier Django version and the PHP one, with full spitting out of HTML and all was functioning faster. MUCH faster to the point that something has to be wrong on the Django one.</p> <p>First, some context: I have a page that spits out reports of sales data. The data can be filtered by a number of things but is mostly filtered by date. This makes it a bit hard to cache it as the possibilities for results is nearly endless. There are a lot of numbers and calculations done but it was never much of a problem to handle within PHP.</p> <p>UPDATES:</p> <ul> <li><p>After some additional testing there is nothing within my view that is causing the slowdown. If I am simply number-crunching the data and spitting out 5 rows of rendered HTML, it's not that slow (still slower than PHP), but if I am rendering a lot of data, it's VERY slow.</p></li> <li><p>Whenever I ran a large report (e.g. all sales for the year), the CPU usage of the machine goes to 100%. Don't know if this means much. I am using mod_python and Apache. Perhaps switching to WSGI may help?</p></li> <li><p>My template tags that show the subtotals/totals process anywhere from 0.1 seconds to 1 second for really large sets. I call them about 6 times within the report so they don't seem like the biggest issue.</p></li> </ul> <p>Now, I ran a Python profiler and came back with these results:</p> <pre> Ordered by: internal time List reduced from 3074 to 20 due to restriction ncalls tottime percall cumtime percall filename:lineno(function) 2939417 26.290 0.000 44.857 0.000 /usr/lib/python2.5/tokenize.py:212(generate_tokens) 2822655 17.049 0.000 17.049 0.000 {built-in method match} 1689928 15.418 0.000 23.297 0.000 /usr/lib/python2.5/decimal.py:515(__new__) 12289605 11.464 0.000 11.464 0.000 {isinstance} 882618 9.614 0.000 25.518 0.000 /usr/lib/python2.5/decimal.py:1447(_fix) 17393 8.742 0.001 60.798 0.003 /usr/lib/python2.5/tokenize.py:158(tokenize_loop) 11 7.886 0.717 7.886 0.717 {method 'accept' of '_socket.socket' objects} 365577 7.854 0.000 30.233 0.000 /usr/lib/python2.5/decimal.py:954(__add__) 2922024 7.199 0.000 7.199 0.000 /usr/lib/python2.5/inspect.py:571(tokeneater) 438750 5.868 0.000 31.033 0.000 /usr/lib/python2.5/decimal.py:1064(__mul__) 60799 5.666 0.000 9.377 0.000 /usr/lib/python2.5/site-packages/django/db/models/base.py:241(__init__) 17393 4.734 0.000 4.734 0.000 {method 'query' of '_mysql.connection' objects} 1124348 4.631 0.000 8.469 0.000 /usr/lib/python2.5/site-packages/django/utils/encoding.py:44(force_unicode) 219076 4.139 0.000 156.618 0.001 /usr/lib/python2.5/site-packages/django/template/__init__.py:700(_resolve_lookup) 1074478 3.690 0.000 11.096 0.000 /usr/lib/python2.5/decimal.py:5065(_convert_other) 2973281 3.424 0.000 3.424 0.000 /usr/lib/python2.5/decimal.py:718(__nonzero__) 759014 2.962 0.000 3.371 0.000 /usr/lib/python2.5/decimal.py:4675(__init__) 381756 2.806 0.000 128.447 0.000 /usr/lib/python2.5/site-packages/django/db/models/fields/related.py:231(__get__) 842130 2.764 0.000 3.557 0.000 /usr/lib/python2.5/decimal.py:3339(_dec_from_triple) </pre> <p>tokenize.py comes out on top, which can make some sense as I am doing a lot of number formatting. Decimal.py makes sense since the report is essentially 90% numbers. I have no clue what the built-in method <code>match</code> is as I am not doing any Regex or similar in my own code (Something Django is doing?) The closest thing is I am using itertools ifilter.</p> <p>It seems those are the main culprits and if I could figure out how to reduce the processing time of those then I would have a much much faster page.</p> <p>Does anyone have any suggestions on how I could start on reducing this? I don't really know how I would fix this the tokenize/decimal issues without simply removing them.</p> <p>Update: I ran some tests with/without filters on most of the data and the result times pretty much came back the same, the latter being a bit faster but not much to be the cause of the issue. What is exactly going on in tokenize.py?</p>
5
2009-07-23T18:58:09Z
1,173,991
<p>There is a lot of things to assume about your problem as you don't have any type of code sample.</p> <p>Here are my assumptions: You are using Django's built-in ORM tools and models (i.e. sales-data = modelobj.objects().all() ) and on the PHP side you are dealing with direct SQL queries and working with a query_set.</p> <p>Django is doing a lot of type converting and casting to datatypes going from a database query into the ORM/Model object and the associated manager (objects() by default).</p> <p>In PHP you are controlling the conversions and know exactly how to cast from one data type to another, you are saving some execution time based on that issue alone.</p> <p>I would recommend trying to move some of that fancy number work into the database, especially if you are doing record-set based processing - databases eat that kind of processing from breakfast. In Django you can send RAW SQL over to the database: <a href="http://docs.djangoproject.com/en/dev/topics/db/sql/#topics-db-sql">http://docs.djangoproject.com/en/dev/topics/db/sql/#topics-db-sql</a></p> <p>I hope this at least can get you pointed in the right direction...</p>
6
2009-07-23T19:37:52Z
[ "python", "django", "optimization" ]
Django (?) really slow with large datasets after doing some python profiling
1,173,798
<p>I was comparing an old PHP script of mine versus the newer, fancier Django version and the PHP one, with full spitting out of HTML and all was functioning faster. MUCH faster to the point that something has to be wrong on the Django one.</p> <p>First, some context: I have a page that spits out reports of sales data. The data can be filtered by a number of things but is mostly filtered by date. This makes it a bit hard to cache it as the possibilities for results is nearly endless. There are a lot of numbers and calculations done but it was never much of a problem to handle within PHP.</p> <p>UPDATES:</p> <ul> <li><p>After some additional testing there is nothing within my view that is causing the slowdown. If I am simply number-crunching the data and spitting out 5 rows of rendered HTML, it's not that slow (still slower than PHP), but if I am rendering a lot of data, it's VERY slow.</p></li> <li><p>Whenever I ran a large report (e.g. all sales for the year), the CPU usage of the machine goes to 100%. Don't know if this means much. I am using mod_python and Apache. Perhaps switching to WSGI may help?</p></li> <li><p>My template tags that show the subtotals/totals process anywhere from 0.1 seconds to 1 second for really large sets. I call them about 6 times within the report so they don't seem like the biggest issue.</p></li> </ul> <p>Now, I ran a Python profiler and came back with these results:</p> <pre> Ordered by: internal time List reduced from 3074 to 20 due to restriction ncalls tottime percall cumtime percall filename:lineno(function) 2939417 26.290 0.000 44.857 0.000 /usr/lib/python2.5/tokenize.py:212(generate_tokens) 2822655 17.049 0.000 17.049 0.000 {built-in method match} 1689928 15.418 0.000 23.297 0.000 /usr/lib/python2.5/decimal.py:515(__new__) 12289605 11.464 0.000 11.464 0.000 {isinstance} 882618 9.614 0.000 25.518 0.000 /usr/lib/python2.5/decimal.py:1447(_fix) 17393 8.742 0.001 60.798 0.003 /usr/lib/python2.5/tokenize.py:158(tokenize_loop) 11 7.886 0.717 7.886 0.717 {method 'accept' of '_socket.socket' objects} 365577 7.854 0.000 30.233 0.000 /usr/lib/python2.5/decimal.py:954(__add__) 2922024 7.199 0.000 7.199 0.000 /usr/lib/python2.5/inspect.py:571(tokeneater) 438750 5.868 0.000 31.033 0.000 /usr/lib/python2.5/decimal.py:1064(__mul__) 60799 5.666 0.000 9.377 0.000 /usr/lib/python2.5/site-packages/django/db/models/base.py:241(__init__) 17393 4.734 0.000 4.734 0.000 {method 'query' of '_mysql.connection' objects} 1124348 4.631 0.000 8.469 0.000 /usr/lib/python2.5/site-packages/django/utils/encoding.py:44(force_unicode) 219076 4.139 0.000 156.618 0.001 /usr/lib/python2.5/site-packages/django/template/__init__.py:700(_resolve_lookup) 1074478 3.690 0.000 11.096 0.000 /usr/lib/python2.5/decimal.py:5065(_convert_other) 2973281 3.424 0.000 3.424 0.000 /usr/lib/python2.5/decimal.py:718(__nonzero__) 759014 2.962 0.000 3.371 0.000 /usr/lib/python2.5/decimal.py:4675(__init__) 381756 2.806 0.000 128.447 0.000 /usr/lib/python2.5/site-packages/django/db/models/fields/related.py:231(__get__) 842130 2.764 0.000 3.557 0.000 /usr/lib/python2.5/decimal.py:3339(_dec_from_triple) </pre> <p>tokenize.py comes out on top, which can make some sense as I am doing a lot of number formatting. Decimal.py makes sense since the report is essentially 90% numbers. I have no clue what the built-in method <code>match</code> is as I am not doing any Regex or similar in my own code (Something Django is doing?) The closest thing is I am using itertools ifilter.</p> <p>It seems those are the main culprits and if I could figure out how to reduce the processing time of those then I would have a much much faster page.</p> <p>Does anyone have any suggestions on how I could start on reducing this? I don't really know how I would fix this the tokenize/decimal issues without simply removing them.</p> <p>Update: I ran some tests with/without filters on most of the data and the result times pretty much came back the same, the latter being a bit faster but not much to be the cause of the issue. What is exactly going on in tokenize.py?</p>
5
2009-07-23T18:58:09Z
1,175,178
<p>"tokenize.py comes out on top, which can make some sense as I am doing a lot of number formatting. "</p> <p>Makes no sense at all.</p> <p>See <a href="http://docs.python.org/library/tokenize.html" rel="nofollow">http://docs.python.org/library/tokenize.html</a>.</p> <blockquote> <p>The tokenize module provides a lexical scanner for Python source code, implemented in Python</p> </blockquote> <p>Tokenize coming out on top means that you have dynamic code parsing going on.</p> <p>AFAIK (doing a search on the Django repository) Django does not use tokenize. So that leaves your program doing some kind of dynamic code instantiation. Or, you're only profiling the <strong>first</strong> time your program is loaded, parsed and run, leading to false assumptions about where the time is going.</p> <p>You should <strong>not</strong> ever do calculation in template tags -- it's slow. It involves a complex meta-evaluation of the template tag. You should do all calculations in the view in simple, low-overhead Python. Use the templates for presentation only.</p> <p>Also, if you're constantly doing queries, filters, sums, and what-not, you have a data warehouse. Get a book on data warehouse design, and follow the data warehouse design patterns.</p> <p>You must have a central fact table, surrounded by dimension tables. This is very, very efficient. </p> <p>Sums, group bys, etc., are can be done as <code>defaultdict</code> operations in Python. Bulk fetch all the rows, building the dictionary with the desired results. If this is too slow, then you have to use data warehousing techniques of saving persistent sums and groups separate from your fine-grained facts. Often this involves stepping outside the Django ORM and using RDBMS features like views or tables of derived data.</p>
2
2009-07-24T00:08:42Z
[ "python", "django", "optimization" ]
Django (?) really slow with large datasets after doing some python profiling
1,173,798
<p>I was comparing an old PHP script of mine versus the newer, fancier Django version and the PHP one, with full spitting out of HTML and all was functioning faster. MUCH faster to the point that something has to be wrong on the Django one.</p> <p>First, some context: I have a page that spits out reports of sales data. The data can be filtered by a number of things but is mostly filtered by date. This makes it a bit hard to cache it as the possibilities for results is nearly endless. There are a lot of numbers and calculations done but it was never much of a problem to handle within PHP.</p> <p>UPDATES:</p> <ul> <li><p>After some additional testing there is nothing within my view that is causing the slowdown. If I am simply number-crunching the data and spitting out 5 rows of rendered HTML, it's not that slow (still slower than PHP), but if I am rendering a lot of data, it's VERY slow.</p></li> <li><p>Whenever I ran a large report (e.g. all sales for the year), the CPU usage of the machine goes to 100%. Don't know if this means much. I am using mod_python and Apache. Perhaps switching to WSGI may help?</p></li> <li><p>My template tags that show the subtotals/totals process anywhere from 0.1 seconds to 1 second for really large sets. I call them about 6 times within the report so they don't seem like the biggest issue.</p></li> </ul> <p>Now, I ran a Python profiler and came back with these results:</p> <pre> Ordered by: internal time List reduced from 3074 to 20 due to restriction ncalls tottime percall cumtime percall filename:lineno(function) 2939417 26.290 0.000 44.857 0.000 /usr/lib/python2.5/tokenize.py:212(generate_tokens) 2822655 17.049 0.000 17.049 0.000 {built-in method match} 1689928 15.418 0.000 23.297 0.000 /usr/lib/python2.5/decimal.py:515(__new__) 12289605 11.464 0.000 11.464 0.000 {isinstance} 882618 9.614 0.000 25.518 0.000 /usr/lib/python2.5/decimal.py:1447(_fix) 17393 8.742 0.001 60.798 0.003 /usr/lib/python2.5/tokenize.py:158(tokenize_loop) 11 7.886 0.717 7.886 0.717 {method 'accept' of '_socket.socket' objects} 365577 7.854 0.000 30.233 0.000 /usr/lib/python2.5/decimal.py:954(__add__) 2922024 7.199 0.000 7.199 0.000 /usr/lib/python2.5/inspect.py:571(tokeneater) 438750 5.868 0.000 31.033 0.000 /usr/lib/python2.5/decimal.py:1064(__mul__) 60799 5.666 0.000 9.377 0.000 /usr/lib/python2.5/site-packages/django/db/models/base.py:241(__init__) 17393 4.734 0.000 4.734 0.000 {method 'query' of '_mysql.connection' objects} 1124348 4.631 0.000 8.469 0.000 /usr/lib/python2.5/site-packages/django/utils/encoding.py:44(force_unicode) 219076 4.139 0.000 156.618 0.001 /usr/lib/python2.5/site-packages/django/template/__init__.py:700(_resolve_lookup) 1074478 3.690 0.000 11.096 0.000 /usr/lib/python2.5/decimal.py:5065(_convert_other) 2973281 3.424 0.000 3.424 0.000 /usr/lib/python2.5/decimal.py:718(__nonzero__) 759014 2.962 0.000 3.371 0.000 /usr/lib/python2.5/decimal.py:4675(__init__) 381756 2.806 0.000 128.447 0.000 /usr/lib/python2.5/site-packages/django/db/models/fields/related.py:231(__get__) 842130 2.764 0.000 3.557 0.000 /usr/lib/python2.5/decimal.py:3339(_dec_from_triple) </pre> <p>tokenize.py comes out on top, which can make some sense as I am doing a lot of number formatting. Decimal.py makes sense since the report is essentially 90% numbers. I have no clue what the built-in method <code>match</code> is as I am not doing any Regex or similar in my own code (Something Django is doing?) The closest thing is I am using itertools ifilter.</p> <p>It seems those are the main culprits and if I could figure out how to reduce the processing time of those then I would have a much much faster page.</p> <p>Does anyone have any suggestions on how I could start on reducing this? I don't really know how I would fix this the tokenize/decimal issues without simply removing them.</p> <p>Update: I ran some tests with/without filters on most of the data and the result times pretty much came back the same, the latter being a bit faster but not much to be the cause of the issue. What is exactly going on in tokenize.py?</p>
5
2009-07-23T18:58:09Z
1,177,600
<p>When dealing with large sets of data, you can also save a lot of CPU and memory by using the <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#values-fields" rel="nofollow">ValuesQuerySet</a> that accesses the query results more directly instead of creating a model object instance for each row in the result.</p> <p>It's usage looks a bit like this:</p> <pre><code>Blog.objects.order_by('id').values() </code></pre>
2
2009-07-24T13:19:01Z
[ "python", "django", "optimization" ]
Django (?) really slow with large datasets after doing some python profiling
1,173,798
<p>I was comparing an old PHP script of mine versus the newer, fancier Django version and the PHP one, with full spitting out of HTML and all was functioning faster. MUCH faster to the point that something has to be wrong on the Django one.</p> <p>First, some context: I have a page that spits out reports of sales data. The data can be filtered by a number of things but is mostly filtered by date. This makes it a bit hard to cache it as the possibilities for results is nearly endless. There are a lot of numbers and calculations done but it was never much of a problem to handle within PHP.</p> <p>UPDATES:</p> <ul> <li><p>After some additional testing there is nothing within my view that is causing the slowdown. If I am simply number-crunching the data and spitting out 5 rows of rendered HTML, it's not that slow (still slower than PHP), but if I am rendering a lot of data, it's VERY slow.</p></li> <li><p>Whenever I ran a large report (e.g. all sales for the year), the CPU usage of the machine goes to 100%. Don't know if this means much. I am using mod_python and Apache. Perhaps switching to WSGI may help?</p></li> <li><p>My template tags that show the subtotals/totals process anywhere from 0.1 seconds to 1 second for really large sets. I call them about 6 times within the report so they don't seem like the biggest issue.</p></li> </ul> <p>Now, I ran a Python profiler and came back with these results:</p> <pre> Ordered by: internal time List reduced from 3074 to 20 due to restriction ncalls tottime percall cumtime percall filename:lineno(function) 2939417 26.290 0.000 44.857 0.000 /usr/lib/python2.5/tokenize.py:212(generate_tokens) 2822655 17.049 0.000 17.049 0.000 {built-in method match} 1689928 15.418 0.000 23.297 0.000 /usr/lib/python2.5/decimal.py:515(__new__) 12289605 11.464 0.000 11.464 0.000 {isinstance} 882618 9.614 0.000 25.518 0.000 /usr/lib/python2.5/decimal.py:1447(_fix) 17393 8.742 0.001 60.798 0.003 /usr/lib/python2.5/tokenize.py:158(tokenize_loop) 11 7.886 0.717 7.886 0.717 {method 'accept' of '_socket.socket' objects} 365577 7.854 0.000 30.233 0.000 /usr/lib/python2.5/decimal.py:954(__add__) 2922024 7.199 0.000 7.199 0.000 /usr/lib/python2.5/inspect.py:571(tokeneater) 438750 5.868 0.000 31.033 0.000 /usr/lib/python2.5/decimal.py:1064(__mul__) 60799 5.666 0.000 9.377 0.000 /usr/lib/python2.5/site-packages/django/db/models/base.py:241(__init__) 17393 4.734 0.000 4.734 0.000 {method 'query' of '_mysql.connection' objects} 1124348 4.631 0.000 8.469 0.000 /usr/lib/python2.5/site-packages/django/utils/encoding.py:44(force_unicode) 219076 4.139 0.000 156.618 0.001 /usr/lib/python2.5/site-packages/django/template/__init__.py:700(_resolve_lookup) 1074478 3.690 0.000 11.096 0.000 /usr/lib/python2.5/decimal.py:5065(_convert_other) 2973281 3.424 0.000 3.424 0.000 /usr/lib/python2.5/decimal.py:718(__nonzero__) 759014 2.962 0.000 3.371 0.000 /usr/lib/python2.5/decimal.py:4675(__init__) 381756 2.806 0.000 128.447 0.000 /usr/lib/python2.5/site-packages/django/db/models/fields/related.py:231(__get__) 842130 2.764 0.000 3.557 0.000 /usr/lib/python2.5/decimal.py:3339(_dec_from_triple) </pre> <p>tokenize.py comes out on top, which can make some sense as I am doing a lot of number formatting. Decimal.py makes sense since the report is essentially 90% numbers. I have no clue what the built-in method <code>match</code> is as I am not doing any Regex or similar in my own code (Something Django is doing?) The closest thing is I am using itertools ifilter.</p> <p>It seems those are the main culprits and if I could figure out how to reduce the processing time of those then I would have a much much faster page.</p> <p>Does anyone have any suggestions on how I could start on reducing this? I don't really know how I would fix this the tokenize/decimal issues without simply removing them.</p> <p>Update: I ran some tests with/without filters on most of the data and the result times pretty much came back the same, the latter being a bit faster but not much to be the cause of the issue. What is exactly going on in tokenize.py?</p>
5
2009-07-23T18:58:09Z
1,200,171
<p>In such a scenario the database is often the bottleneck. Also, using an ORM might result in sub-optimal SQL queries.</p> <p>As some pointed out it's not possible to tell what the probem really is, just with the information you provided.</p> <p>I just can give you some general advice:</p> <ul> <li>If your view is working with related model objects, consider using <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4" rel="nofollow">select_related()</a>. This simple method might speed up the queries generated by the ORM considerably.</li> <li>Use the <a href="http://www.djangosnippets.org/snippets/766/" rel="nofollow">Debug Footer Middleware</a> to see what SQL queries are generated by your views and what time they took to execute.</li> </ul> <p>PS: Just fyi, I had once a fairly simple view which was very slow. After installing the <a href="http://www.djangosnippets.org/snippets/766/" rel="nofollow">Debug Footer Middleware</a> I saw that around 500! sql queries were executed in that single view. Just using <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4" rel="nofollow">select_related()</a> brought that down to 5 queries and the view performed as expected.</p>
1
2009-07-29T13:14:55Z
[ "python", "django", "optimization" ]
What is a basic example of single inheritance using the super() keyword in Python?
1,173,992
<p>Let's say I have the following classes set up:</p> <pre><code>class Foo: def __init__(self, frob, frotz): self.frobnicate = frob self.frotz = frotz class Bar: def __init__(self, frob, frizzle): self.frobnicate = frob self.frotz = 34 self.frazzle = frizzle </code></pre> <p>How can I (if I can at all) use super() in this context to eliminate the duplicate code?</p>
22
2009-07-23T19:38:02Z
1,174,118
<p>Assuming you want class Bar to set the value 34 within its constructor, this would work:</p> <pre><code>class Foo(object): def __init__(self, frob, frotz): self.frobnicate = frob self.frotz = frotz class Bar(Foo): def __init__(self, frob, frizzle): super(Bar, self).__init__(frob, frizzle) self.frotz = 34 self.frazzle = frizzle bar = Bar(1,2) print "frobnicate:", bar.frobnicate print "frotz:", bar.frotz print "frazzle:", bar.frazzle </code></pre> <p>However, <code>super</code> introduces its own complications. See e.g. <a href="http://fuhm.net/super-harmful/" rel="nofollow">super considered harmful</a>. For completeness, here's the equivalent version without <code>super</code>.</p> <pre><code>class Foo(object): def __init__(self, frob, frotz): self.frobnicate = frob self.frotz = frotz class Bar(Foo): def __init__(self, frob, frizzle): Foo.__init__(self, frob, frizzle) self.frotz = 34 self.frazzle = frizzle bar = Bar(1,2) print "frobnicate:", bar.frobnicate print "frotz:", bar.frotz print "frazzle:", bar.frazzle </code></pre>
28
2009-07-23T19:57:25Z
[ "python", "inheritance", "constructor", "super" ]
What is a basic example of single inheritance using the super() keyword in Python?
1,173,992
<p>Let's say I have the following classes set up:</p> <pre><code>class Foo: def __init__(self, frob, frotz): self.frobnicate = frob self.frotz = frotz class Bar: def __init__(self, frob, frizzle): self.frobnicate = frob self.frotz = 34 self.frazzle = frizzle </code></pre> <p>How can I (if I can at all) use super() in this context to eliminate the duplicate code?</p>
22
2009-07-23T19:38:02Z
1,174,124
<p>In Python >=3.0, like this:</p> <pre><code>class Foo(): def __init__(self, frob, frotz) self.frobnicate = frob self.frotz = frotz class Bar(Foo): def __init__(self, frob, frizzle) super().__init__(frob, 34) self.frazzle = frizzle </code></pre> <p>Read more here: <a href="http://docs.python.org/3.1/library/functions.html#super" rel="nofollow">http://docs.python.org/3.1/library/functions.html#super</a></p> <p>EDIT: As said in another answer, sometimes just using <code>Foo.__init__(self, frob, 34)</code> can be the better solution. (For instance, when working with certain forms of multiple inheritance.)</p>
23
2009-07-23T19:58:31Z
[ "python", "inheritance", "constructor", "super" ]
appengine: cached reference property?
1,174,075
<p>How can I cache a Reference Property in Google App Engine?</p> <p>For example, let's say I have the following models:</p> <pre><code>class Many(db.Model): few = db.ReferenceProperty(Few) class Few(db.Model): year = db.IntegerProperty() </code></pre> <p>Then I create many <code>Many</code>'s that point to only one <code>Few</code>:</p> <pre><code>one_few = Few.get_or_insert(year=2009) Many.get_or_insert(few=one_few) Many.get_or_insert(few=one_few) Many.get_or_insert(few=one_few) Many.get_or_insert(few=one_few) Many.get_or_insert(few=one_few) Many.get_or_insert(few=one_few) </code></pre> <p>Now, if I want to iterate over all the <code>Many</code>'s, reading their <code>few</code> value, I would do this:</p> <pre><code>for many in Many.all().fetch(1000): print "%s" % many.few.year </code></pre> <p>The question is:</p> <ul> <li>Will each access to <code>many.few</code> trigger a database lookup?</li> <li>If yes, is it possible to cache somewhere, as only one lookup should be enough to bring the same entity every time?</li> </ul> <p><hr /></p> <p>As noted in one comment: I know about memcache, but I'm not sure how I can "inject it" when I'm calling the other entity through a reference. </p> <p>In any case memcache wouldn't be useful, as I need caching within an execution, not between them. Using memcache wouldn't help optimizing this call.</p>
2
2009-07-23T19:51:30Z
1,174,224
<p>The question is:</p> <ol> <li>Will each access to many.few trigger a database lookup? Yes. Not sure if its 1 or 2 calls</li> <li>If yes, is it possible to cache somewhere, as only one lookup should be enough to bring the same entity every time? You should be able to use the memcache repository to do this. This is in the google.appengine.api.memcache package.</li> </ol> <p>Details for memcache are in <a href="http://code.google.com/appengine/docs/python/memcache/usingmemcache.html" rel="nofollow">http://code.google.com/appengine/docs/python/memcache/usingmemcache.html</a></p>
1
2009-07-23T20:18:06Z
[ "python", "database", "performance", "google-app-engine", "gae-datastore" ]