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
list
Django: testing get query
2,525,026
<p>Okay, so I am sick of writing this...</p> <pre><code>res = Something.objects.filter(asdf=something) if res: single = res[0] else: single = None if single: # do some stuff </code></pre> <p>I would much rather be able to do something like this:</p> <pre><code>single = Something.objects.filter(asdf=something...
0
2010-03-26T16:43:44Z
2,525,117
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#id2" rel="nofollow">Create a custom <code>Manager</code></a> which encapsulates the bit you're sick of repeating as a method (with a better name than the one below) or just write a utility function which does the same without the hit to model definiti...
2
2010-03-26T16:57:51Z
[ "python", "django", "django-models", "django-queryset" ]
Django: testing get query
2,525,026
<p>Okay, so I am sick of writing this...</p> <pre><code>res = Something.objects.filter(asdf=something) if res: single = res[0] else: single = None if single: # do some stuff </code></pre> <p>I would much rather be able to do something like this:</p> <pre><code>single = Something.objects.filter(asdf=something...
0
2010-03-26T16:43:44Z
2,525,122
<p>The <a href="http://bitbucket.org/offline/django-annoying/" rel="nofollow">django-annoying</a> project includes a <code>get_object_or_None</code> shortcut which does this, although it's trivial to write it yourself.</p>
3
2010-03-26T16:58:28Z
[ "python", "django", "django-models", "django-queryset" ]
GQL how to select by UserProperty
2,525,180
<p>Hey I have this code but it doesn't work because it is expecting a string. How can I make it work?</p> <pre><code>class Atable(BaseModel): owner = db.UserProperty() (...) --------- // -------------- query = "SELECT * FROM Atable WHERE owner=", users.get_current_user() results = db.GqlQuery(query) </cod...
1
2010-03-26T17:08:34Z
2,525,746
<pre><code>query = GqlQuery("SELECT * FROM Atable WHERE owner = :1", users.get_current_user()) </code></pre>
2
2010-03-26T18:28:39Z
[ "python", "django", "google-app-engine" ]
GQL how to select by UserProperty
2,525,180
<p>Hey I have this code but it doesn't work because it is expecting a string. How can I make it work?</p> <pre><code>class Atable(BaseModel): owner = db.UserProperty() (...) --------- // -------------- query = "SELECT * FROM Atable WHERE owner=", users.get_current_user() results = db.GqlQuery(query) </cod...
1
2010-03-26T17:08:34Z
2,526,334
<p>You could try the GQL way:</p> <pre><code>results = db.GqlQuery("SELECT * FROM Atable WHERE owner = :1", users.get_current_user().key()) </code></pre> <p>or the Python Query way:</p> <pre><code>query = db.Query(Atable) results = query.filter('owner =', users.get_current_user()) </code></pre>
3
2010-03-26T19:59:24Z
[ "python", "django", "google-app-engine" ]
GQL how to select by UserProperty
2,525,180
<p>Hey I have this code but it doesn't work because it is expecting a string. How can I make it work?</p> <pre><code>class Atable(BaseModel): owner = db.UserProperty() (...) --------- // -------------- query = "SELECT * FROM Atable WHERE owner=", users.get_current_user() results = db.GqlQuery(query) </cod...
1
2010-03-26T17:08:34Z
2,526,460
<p>The python query way is probably easier if you just need to get some data for that user.</p> <p>For example in your class Something(db.Model), you can define: </p> <pre><code>@staticmethod def get_something_by_user(user): query = db.Query(Something).filter('users =', user) result = query.fetch(lim...
0
2010-03-26T20:18:14Z
[ "python", "django", "google-app-engine" ]
How can I make mock-0.6 return a sequence of values?
2,525,233
<p>I'm using the mock-0.6 library from <a href="http://www.voidspace.org.uk/python/mock/mock.html" rel="nofollow">http://www.voidspace.org.uk/python/mock/mock.html</a> to mock out a framework for testing, and I want to have a mock method return a series of values, each time it's called.</p> <p>Right now, this is what ...
2
2010-03-26T17:16:20Z
2,525,506
<p>Here's the solution, found by trial and error:</p> <p>The returnList function must create a generator and use its <code>next</code> method to provide the responses:</p> <pre><code>def returnList(items): log.debug("Creating side effect function for %s", items) def func(): for item in items: log.debug(...
2
2010-03-26T17:49:25Z
[ "python", "mocking" ]
How can I make mock-0.6 return a sequence of values?
2,525,233
<p>I'm using the mock-0.6 library from <a href="http://www.voidspace.org.uk/python/mock/mock.html" rel="nofollow">http://www.voidspace.org.uk/python/mock/mock.html</a> to mock out a framework for testing, and I want to have a mock method return a series of values, each time it's called.</p> <p>Right now, this is what ...
2
2010-03-26T17:16:20Z
11,910,285
<p>If you just want to return a list of values, the answer is easy if you're using mock==0.8.0 or later: </p> <pre><code>import mock m = mock.Mock() m = side_effect = [ ['a', 'b', 'c'], ['d', 'e', 'f'], ] print "First: %s" % m() print "Second: %s" % m() </code></pre> <p>The output is: </p> <pre><c...
5
2012-08-10T22:59:06Z
[ "python", "mocking" ]
Measuring ping latency of a server - Python
2,525,312
<p>I have a list of server <strong>IP addresses</strong>, I need to check if each one is online and how long the <strong>latency</strong> is.</p> <p>I haven't found any straight forward ways of implementing this, and there seems to be a few problems in calculating latency accurately.</p> <hr> <p>Any ideas?</p>
3
2010-03-26T17:26:19Z
2,525,471
<p>If you want to avoid implementing all the network communication details you could probably try to build something on top of <a href="http://www.fping.com/">fping</a>:</p> <blockquote> <p>fping is a like program which uses the Internet Control Message Protocol (ICMP) echo request to determine if a target hos...
5
2010-03-26T17:44:55Z
[ "python", "networking", "tcp", "latency" ]
Measuring ping latency of a server - Python
2,525,312
<p>I have a list of server <strong>IP addresses</strong>, I need to check if each one is online and how long the <strong>latency</strong> is.</p> <p>I haven't found any straight forward ways of implementing this, and there seems to be a few problems in calculating latency accurately.</p> <hr> <p>Any ideas?</p>
3
2010-03-26T17:26:19Z
2,525,473
<p>If you are already comfortable with parsing strings, you can use the subprocess module to get the data you are looking for into a string, like this:</p> <pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; p = subprocess.Popen(["ping.exe","www.google.com"], stdout = subprocess.PIPE) &gt;&gt;&gt; print p.communica...
4
2010-03-26T17:45:11Z
[ "python", "networking", "tcp", "latency" ]
Measuring ping latency of a server - Python
2,525,312
<p>I have a list of server <strong>IP addresses</strong>, I need to check if each one is online and how long the <strong>latency</strong> is.</p> <p>I haven't found any straight forward ways of implementing this, and there seems to be a few problems in calculating latency accurately.</p> <hr> <p>Any ideas?</p>
3
2010-03-26T17:26:19Z
14,054,961
<p>Following hlovdal's suggestion to work with fping, here is my solution that I use for testing proxies. I only tried it under Linux. If no ping time could be measured, a big value is returned. Usage: <code>print get_ping_time('&lt;ip&gt;:&lt;port&gt;')</code>.</p> <pre><code>import shlex from subprocess import Pop...
3
2012-12-27T12:46:07Z
[ "python", "networking", "tcp", "latency" ]
Measuring ping latency of a server - Python
2,525,312
<p>I have a list of server <strong>IP addresses</strong>, I need to check if each one is online and how long the <strong>latency</strong> is.</p> <p>I haven't found any straight forward ways of implementing this, and there seems to be a few problems in calculating latency accurately.</p> <hr> <p>Any ideas?</p>
3
2010-03-26T17:26:19Z
28,174,547
<p><a href="https://github.com/matthieu-lapeyre/network-benchmarkMy" rel="nofollow">https://github.com/matthieu-lapeyre/network-benchmarkMy</a> solution based on the work of FlipperPA: <a href="https://github.com/FlipperPA/latency-tester" rel="nofollow">https://github.com/FlipperPA/latency-tester</a></p> <pre><code>im...
1
2015-01-27T15:52:56Z
[ "python", "networking", "tcp", "latency" ]
Regex for [a-zA-Z0-9\-] with dashes allowed in between but not at the start or end
2,525,327
<h1>Update:</h1> <p>This question was an epic failure, but here's the working solution. It's based on Gumbo's answer (Gumbo's was close to working so I chose it as the accepted answer):</p> <h3>Solution:</h3> <pre><code>r'(?=[a-zA-Z0-9\-]{4,25}$)^[a-zA-Z0-9]+(\-[a-zA-Z0-9]+)*$' </code></pre> <h1>Original Question (...
5
2010-03-26T17:27:31Z
2,525,339
<p>Try this regular expression:</p> <pre><code>^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$ </code></pre> <p>This regular expression does only allow hyphens to separate sequences of one or more characters of <code>[a-zA-Z0-9]</code>.</p> <hr> <p><strong>Edit</strong>    Following up your comment: The expression <code>(…)*<...
14
2010-03-26T17:29:07Z
[ "python", "regex" ]
Regex for [a-zA-Z0-9\-] with dashes allowed in between but not at the start or end
2,525,327
<h1>Update:</h1> <p>This question was an epic failure, but here's the working solution. It's based on Gumbo's answer (Gumbo's was close to working so I chose it as the accepted answer):</p> <h3>Solution:</h3> <pre><code>r'(?=[a-zA-Z0-9\-]{4,25}$)^[a-zA-Z0-9]+(\-[a-zA-Z0-9]+)*$' </code></pre> <h1>Original Question (...
5
2010-03-26T17:27:31Z
2,525,348
<p>It should be something like this:</p> <pre><code>^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$ </code></pre> <p>You are telling it to look for only one char, either a-z, A-Z, 0-9 or -, that is what [] does.</p> <p>So if you do <code>[abc]</code> you will match only "a", or "b" or "c". not "abc"</p> <p>Have fun.</p>
1
2010-03-26T17:29:40Z
[ "python", "regex" ]
Regex for [a-zA-Z0-9\-] with dashes allowed in between but not at the start or end
2,525,327
<h1>Update:</h1> <p>This question was an epic failure, but here's the working solution. It's based on Gumbo's answer (Gumbo's was close to working so I chose it as the accepted answer):</p> <h3>Solution:</h3> <pre><code>r'(?=[a-zA-Z0-9\-]{4,25}$)^[a-zA-Z0-9]+(\-[a-zA-Z0-9]+)*$' </code></pre> <h1>Original Question (...
5
2010-03-26T17:27:31Z
2,525,357
<p>If you simply don't want a dash at the end and beginning, try <code>^[^-].*?[^-]$</code></p> <p><b>Edit:</b> Bah, you keep changing it. </p>
0
2010-03-26T17:30:45Z
[ "python", "regex" ]
Regex for [a-zA-Z0-9\-] with dashes allowed in between but not at the start or end
2,525,327
<h1>Update:</h1> <p>This question was an epic failure, but here's the working solution. It's based on Gumbo's answer (Gumbo's was close to working so I chose it as the accepted answer):</p> <h3>Solution:</h3> <pre><code>r'(?=[a-zA-Z0-9\-]{4,25}$)^[a-zA-Z0-9]+(\-[a-zA-Z0-9]+)*$' </code></pre> <h1>Original Question (...
5
2010-03-26T17:27:31Z
2,525,643
<p>The current regex is simple and fairly readable. Rather than making it long and complicated, have you considered applying the other constraints with normal Python string processing tools?</p> <pre><code>import re def fits_pattern(string): if (4 &lt;= len(string) &lt;= 25 and "--" not in string and ...
3
2010-03-26T18:08:28Z
[ "python", "regex" ]
Speex in Python
2,525,494
<p>How can I use <a href="http://www.speex.org/" rel="nofollow">Speex</a> to encode/decode from within python? Are there any wrappers? I found an old project <a href="http://www.freenet.org.nz/python/pySpeex/" rel="nofollow">pySpeex</a> but it is obsolete now (requires Python 2.2).</p>
1
2010-03-26T17:48:02Z
2,527,625
<p>I think starting from pySpeex (and tweaking any issue that may arise if you're using Python 2.6, say, in lieu of 2.2) is by far the path of least resistance -- there aren't <em>that</em> many backward incompatibilities between 2.2 and 2.6, after all, so the amount of work should be pretty limited (and then you can c...
1
2010-03-27T00:17:26Z
[ "python", "wrapper", "speex" ]
Matching first set of elements with xpath
2,525,627
<p>I have an xml document that looks like this.</p> <pre><code>&lt;foo&gt; &lt;bar type="artist"/&gt; Bob Marley &lt;/bar&gt; &lt;bar type="artist"/&gt; Peter Tosh &lt;/bar&gt; &lt;bar type="artist"/&gt; Marlon Wayans &lt;/bar&gt; &lt;/foo&gt; &lt;foo&gt; &lt;bar type="artist"/&gt; Bob Marley &lt;/bar&...
1
2010-03-26T18:05:30Z
2,525,653
<p>In order to get only sub elements of some "indexed" node:</p> <pre><code>//foo[1]/bar[@type='artist'] </code></pre> <p>Exmaple in C#:</p> <pre><code>string xml = @"&lt;root&gt; &lt;foo&gt; &lt;bar type='artist'&gt; Artist 1 &lt;/bar&gt; &lt;bar type='artist'&gt; Artist 2 &lt;/b...
2
2010-03-26T18:09:28Z
[ "python", "xpath", "lxml" ]
Twisted - how to create multi protocol process and send the data between the protocols
2,525,644
<p>Im trying to write a program that would be listening for data (simple text messages) on some port (say tcp 6666) and then pass them to one or more different protocols - irc, xmpp and so on. I've tried many approaches and digged the Internet, but I cant find easy and working solution for such task.</p> <p>The code I...
1
2010-03-26T18:08:28Z
2,525,765
<p>See <a href="http://twistedmatrix.com/trac/browser/trunk/doc/core/examples/chatserver.py" rel="nofollow"><code>doc/core/examples/chatserver.py</code></a>. There they've added hooks to the <code>Protocol</code>'s <code>connectionMade</code> and <code>connectionLost</code> methods to maintain a list of connected clie...
1
2010-03-26T18:31:11Z
[ "python", "xmpp", "twisted", "irc" ]
Twisted - how to create multi protocol process and send the data between the protocols
2,525,644
<p>Im trying to write a program that would be listening for data (simple text messages) on some port (say tcp 6666) and then pass them to one or more different protocols - irc, xmpp and so on. I've tried many approaches and digged the Internet, but I cant find easy and working solution for such task.</p> <p>The code I...
1
2010-03-26T18:08:28Z
2,528,764
<p>This is answered in the FAQ.</p> <p><a href="http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#HowdoImakeinputononeconnectionresultinoutputonanother" rel="nofollow">http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#HowdoImakeinputononeconnectionresultinoutputonanother</a></p>
2
2010-03-27T09:33:25Z
[ "python", "xmpp", "twisted", "irc" ]
Twisted - how to create multi protocol process and send the data between the protocols
2,525,644
<p>Im trying to write a program that would be listening for data (simple text messages) on some port (say tcp 6666) and then pass them to one or more different protocols - irc, xmpp and so on. I've tried many approaches and digged the Internet, but I cant find easy and working solution for such task.</p> <p>The code I...
1
2010-03-26T18:08:28Z
5,864,672
<p>Here is sample code to read from multiple connections to port 9001 and write out to a connection on port 9000. You would need multiple "PutLine" implementations, one for XMPP, IRC, MSN, etc.</p> <p>I used a global to store the output connection PutLine but you would want to create a more complex Factory object tha...
5
2011-05-03T03:15:53Z
[ "python", "xmpp", "twisted", "irc" ]
How to write the Visitor Pattern for Abstract Syntax Tree in Python?
2,525,677
<p>My collegue suggested me to write a visitor pattern to navigate the AST. Can anyone tell me more how would I start writing it?</p> <p>As far as I understand, each Node in AST would have <code>visit()</code> method (?) that would somehow get called (from where?). That about concludes my understanding.</p> <p>To sim...
17
2010-03-26T18:14:07Z
2,525,771
<p>See <a href="http://docs.python.org/library/ast.html?highlight=ast#ast.NodeVisitor">the docs</a> for <code>ast.NodeVisitor</code>, e.g. a crude possibility might be:</p> <pre><code>import ast class MyVisitor(ast.NodeVisitor): def visit_BinaryOp(self, node): self.visit(node.left) print node.op, self.v...
10
2010-03-26T18:32:54Z
[ "python", "parsing", "compiler-construction", "abstract-syntax-tree", "visitor" ]
How to write the Visitor Pattern for Abstract Syntax Tree in Python?
2,525,677
<p>My collegue suggested me to write a visitor pattern to navigate the AST. Can anyone tell me more how would I start writing it?</p> <p>As far as I understand, each Node in AST would have <code>visit()</code> method (?) that would somehow get called (from where?). That about concludes my understanding.</p> <p>To sim...
17
2010-03-26T18:14:07Z
2,526,397
<p>Wikipedia has a great overview of <a href="http://en.wikipedia.org/wiki/Visitor_pattern#Example">how the Visitor pattern works</a>, although the sample implementation that they use is in Java. You can easily port that to Python, though, no?</p> <p>Basically, you want to implement a mechanism for <a href="http://en....
8
2010-03-26T20:09:28Z
[ "python", "parsing", "compiler-construction", "abstract-syntax-tree", "visitor" ]
How to best design a date/geographic proximity query on GAE?
2,525,747
<p>I'm building a directory for finding athletic tournaments on GAE with web2py and a Flex front end. The user selects a location, a radius, and a maximum date from a set of choices. I have a basic version of this query implemented, but it's inefficient and slow. One way I know I can improve it is by condensing the man...
1
2010-03-26T18:28:42Z
2,534,712
<p><a href="http://code.google.com/p/geomodel/" rel="nofollow">GeoModel</a> is the best I found. You may look how my GAE <a href="http://www.koolbusiness.com" rel="nofollow">app</a> return geospatial queries. For instance India http query is with optional cc (country code) using geomodel library <code>lat=20.2095231&am...
2
2010-03-28T21:48:47Z
[ "python", "google-app-engine", "caching", "gae-datastore", "web2py" ]
How to best design a date/geographic proximity query on GAE?
2,525,747
<p>I'm building a directory for finding athletic tournaments on GAE with web2py and a Flex front end. The user selects a location, a radius, and a maximum date from a set of choices. I have a basic version of this query implemented, but it's inefficient and slow. One way I know I can improve it is by condensing the man...
1
2010-03-26T18:28:42Z
2,537,798
<p>You might be interested by <code>geohash</code>, which enables you to do an inequality query like this:</p> <blockquote> <p>SELECT latitude, longitude, title FROM myMarkers WHERE geohash >= :sw_geohash AND geohash &lt;= :ne_geohash</p> </blockquote> <p>Have a look at <a href="http://hitching.net/2009/11/10/s...
1
2010-03-29T12:29:08Z
[ "python", "google-app-engine", "caching", "gae-datastore", "web2py" ]
Proper way in Python to raise errors while setting variables
2,525,845
<p>What is the proper way to do error-checking in a class? Raising exceptions? Setting an instance variable dictionary "errors" that contains all the errors and returning it? </p> <p>Is it bad to print errors from a class? Do I have to return False if I'm raising an exception?</p> <p>Just want to make sure that I'...
11
2010-03-26T18:45:02Z
2,525,936
<p>The standard way of signalling an error in python is to raise an exception and let the calling code handle it. Either let the NameError &amp; TypeError carry on upwards, or catch them and raise an InvalidPassword exception that you define. </p> <p>While it is possible to return a success/fail flag or error code f...
9
2010-03-26T18:57:32Z
[ "python", "error-handling" ]
Proper way in Python to raise errors while setting variables
2,525,845
<p>What is the proper way to do error-checking in a class? Raising exceptions? Setting an instance variable dictionary "errors" that contains all the errors and returning it? </p> <p>Is it bad to print errors from a class? Do I have to return False if I'm raising an exception?</p> <p>Just want to make sure that I'...
11
2010-03-26T18:45:02Z
2,525,988
<p>Generally, you should indicate errors that propagate by using exceptions. If you discover an error by something you just checked and you can deal with it immediately, there is no need to raise an exception. </p> <p>In the particular case of a setter, of example, returning <code>False</code> or anything else won't h...
4
2010-03-26T19:07:50Z
[ "python", "error-handling" ]
Proper way in Python to raise errors while setting variables
2,525,845
<p>What is the proper way to do error-checking in a class? Raising exceptions? Setting an instance variable dictionary "errors" that contains all the errors and returning it? </p> <p>Is it bad to print errors from a class? Do I have to return False if I'm raising an exception?</p> <p>Just want to make sure that I'...
11
2010-03-26T18:45:02Z
2,526,154
<p>Your code is out of a context so is not obvious the right choice. Following some tips:</p> <ul> <li><p>Don't use <code>NameError</code> exception, it is only used when a name, as the exception itself said, is not found in the local or global scope, use <code>ValueError</code> or <code>TypeError</code> if the except...
17
2010-03-26T19:30:22Z
[ "python", "error-handling" ]
Game login authentication and security
2,526,110
<p>First off I will say I am completely new to security in coding. I am currently helping a friend develop a small game (in Python) which will have a login server. I don't have much knowledge regarding security, but I know many games do have issues with this. Everything from 3rd party applications (bots) to WPE packet ...
4
2010-03-26T19:25:11Z
2,526,148
<p>This is a tough problem, because the code runs on the client. The replay problem can be solved by using a challenge by letting the server sending a random token which the client adds to the string to be encrypted. This way, the password string will be different each time, and replaying the encrypted string doesn't w...
1
2010-03-26T19:29:59Z
[ "python", "security", "authentication", "login" ]
Game login authentication and security
2,526,110
<p>First off I will say I am completely new to security in coding. I am currently helping a friend develop a small game (in Python) which will have a login server. I don't have much knowledge regarding security, but I know many games do have issues with this. Everything from 3rd party applications (bots) to WPE packet ...
4
2010-03-26T19:25:11Z
2,526,281
<p>Although it might conceivably be overkill for this specific application (small game, limited user base), you should seriously consider using <a href="http://oauth.net/" rel="nofollow">oAuth</a>, since this application gives you a great chance to learn this technology (which is really solid and widespread, and spread...
1
2010-03-26T19:49:00Z
[ "python", "security", "authentication", "login" ]
Game login authentication and security
2,526,110
<p>First off I will say I am completely new to security in coding. I am currently helping a friend develop a small game (in Python) which will have a login server. I don't have much knowledge regarding security, but I know many games do have issues with this. Everything from 3rd party applications (bots) to WPE packet ...
4
2010-03-26T19:25:11Z
2,526,532
<p>The simple answer to how to protect the password going over the wire, replay attacks, and message tampering is: use SSL. Yes, there are other things you can do with challenge-response authentication schemes for the login part of it, but it sounds like you really want the whole channel protected anyway. Use SSL at ...
1
2010-03-26T20:30:52Z
[ "python", "security", "authentication", "login" ]
Game login authentication and security
2,526,110
<p>First off I will say I am completely new to security in coding. I am currently helping a friend develop a small game (in Python) which will have a login server. I don't have much knowledge regarding security, but I know many games do have issues with this. Everything from 3rd party applications (bots) to WPE packet ...
4
2010-03-26T19:25:11Z
2,526,606
<p>As for how to protect the client... The most realistic thing is to say that you don't. When you're writing the server code, never trust any data that the client sends you. Never give the client any information you don't want the player to have.</p> <p>In some games, like chess (or really anything turn-based), th...
1
2010-03-26T20:42:10Z
[ "python", "security", "authentication", "login" ]
Settings module not found deploying django on a shared server
2,526,172
<p>I'm trying to deploy my django project on a shared hosting as describe <a href="http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/#running-django-on-a-shared-hosting-provider-with-apache" rel="nofollow">here</a></p> <p>I have my project on /home/user/www/testa</p> <p>I'm using this script</p> <pre><co...
0
2010-03-26T19:33:32Z
2,526,400
<p>The line</p> <pre><code>os.environ['DJANGO_SETTINGS_MODULE'] = "settings.py" </code></pre> <p>should be more like</p> <pre><code>os.environ['DJANGO_SETTINGS_MODULE'] = "settings" </code></pre> <p>based on how you're setting up <code>sys.path</code>. That environment variable is supposed to contain the path to t...
3
2010-03-26T20:09:56Z
[ "python", "django", "fastcgi" ]
pyInotify performance
2,526,273
<p>I have a very large directory tree I am wanting pyInotify to watch. Is it better to have pyInotify watch the entire tree or is it better to have a number of watches reporting changes to specific files ? Thanks </p>
0
2010-03-26T19:48:31Z
2,526,820
<p>If you're going to watch only a few files in a huge tree, it makes sense to watch individual files. On the other hand, if you're going to watch almost all files in the tree, watching the entire tree instead makes sense. To know the point of turn exactly, you must benchmark both to see which one performs better.</p>
0
2010-03-26T21:18:02Z
[ "python", "pyinotify" ]
Django ModelFormSet with Google app engine
2,526,394
<p>I'm using Django with google app engine. I'm using the google furnished django app engine helper project.</p> <p>I'm attempting to create a Django modelformset like this:</p> <pre><code>#MyModel inherits from BaseModel MyFormSet = modelformset_factory(models.MyModel) </code></pre> <p>However, it's failing wit...
1
2010-03-26T20:08:36Z
2,721,549
<p>It is a fundamental incompatibility between Django and GAE, because they do not share the same interface for their models. The django helper does not include a patch for the modelformsets, but django-nonrel probably does, or will eventually.</p> <p>Since the google team does not spend much time on the django helpe...
0
2010-04-27T13:24:44Z
[ "python", "django", "google-app-engine", "django-forms" ]
Error handling with Python + Pylons
2,526,458
<p>What is the proper way to handle errors with Python + Pylons?</p> <p>Say a user sets a password via a form that, when passed to a model class via the controller, throws an error because it's too short. How should that error be handled so that an error message gets displayed on the web page rather than the entire s...
3
2010-03-26T20:17:49Z
2,526,549
<p>What are you using to validate your forms? I'm using <a href="http://formalchemy.org" rel="nofollow">formalchemy</a>. It validates the input data using built-in and custom validators, and feeds a list with the errors it finds. You can then display that list in any way you want in your template.</p> <p>Documentation...
2
2010-03-26T20:33:47Z
[ "python", "error-handling", "pylons" ]
Error handling with Python + Pylons
2,526,458
<p>What is the proper way to handle errors with Python + Pylons?</p> <p>Say a user sets a password via a form that, when passed to a model class via the controller, throws an error because it's too short. How should that error be handled so that an error message gets displayed on the web page rather than the entire s...
3
2010-03-26T20:17:49Z
2,526,649
<p>I use formencode @validate decorator. It is possible to write custom validator for it but the problem with handling exceptions that occur in the model after validation still exists.</p> <p>You could write custom action decorator similar to formencode one which will handle your model exceptions and populate c.form_e...
1
2010-03-26T20:49:58Z
[ "python", "error-handling", "pylons" ]
Error handling with Python + Pylons
2,526,458
<p>What is the proper way to handle errors with Python + Pylons?</p> <p>Say a user sets a password via a form that, when passed to a model class via the controller, throws an error because it's too short. How should that error be handled so that an error message gets displayed on the web page rather than the entire s...
3
2010-03-26T20:17:49Z
2,527,503
<p>Not pretending to be production-ready solution, just as an example. Actually I've copied most of decorator code from pylons.decorators:</p> <pre><code>from decorator import decorator from webob import UnicodeMultiDict class ModelException(Exception): pass def handle_exceptions(form): def wrapper(fn, self,...
1
2010-03-26T23:44:12Z
[ "python", "error-handling", "pylons" ]
Python Permutation Program Flow help
2,526,540
<p>i found this code at activestate, it takes a string and prints permutations of the string. I understand that its a recursive function but i dont really understand how it works, it'd be great if someone could walk me through the program flow, thanks a bunch!</p> <pre><code>import sys def printList(alist, blist=[]):...
2
2010-03-26T20:32:00Z
2,526,665
<p>To understand it clearly remove the loop with alist=love and blist initialized to []: The 4 printlist calls in the for loop will now be(at first level of recursion):</p> <pre><code> printList("ove","l"); printList("lve","o"); printList("loe","v"); printList("lov","e"); </code></pre> <p>Each of these pri...
3
2010-03-26T20:52:09Z
[ "python", "workflow", "recursion" ]
Python Permutation Program Flow help
2,526,540
<p>i found this code at activestate, it takes a string and prints permutations of the string. I understand that its a recursive function but i dont really understand how it works, it'd be great if someone could walk me through the program flow, thanks a bunch!</p> <pre><code>import sys def printList(alist, blist=[]):...
2
2010-03-26T20:32:00Z
2,526,770
<p>You can figure out how <code>printList</code> behaves by drawing a recursion tree. Each node consists of two elements: an <code>alist</code> and a <code>blist</code>. The root has the <code>alist</code> with the initial sequence of items you want to permute, and an empty <code>blist</code>. Each node of the tree has...
6
2010-03-26T21:09:52Z
[ "python", "workflow", "recursion" ]
Python Permutation Program Flow help
2,526,540
<p>i found this code at activestate, it takes a string and prints permutations of the string. I understand that its a recursive function but i dont really understand how it works, it'd be great if someone could walk me through the program flow, thanks a bunch!</p> <pre><code>import sys def printList(alist, blist=[]):...
2
2010-03-26T20:32:00Z
2,527,043
<p>Shameless plug - Here is an elementary permutation code in python along with explanation from my blog. <a href="http://devconvert.blogspot.com/2009/09/playing-with-recursion-string.html" rel="nofollow">Playing with recursion - string permutation</a></p>
0
2010-03-26T22:02:12Z
[ "python", "workflow", "recursion" ]
Forwarding keypresses in GTK
2,526,589
<p>I'm writing a bit of code for a Gedit plugin. I'm using Python and the interface (obviously) is GTK.</p> <p>So, the issue I'm having is quite simple: I have a search box (a gtk.Entry) and right below I have a results box (a gtk.TreeView). Right after you type something in the search box you are presented a bunch of...
0
2010-03-26T20:39:29Z
2,539,108
<p>Did you include the <code>key-press-event</code> in the list of events the widget is allowed to receive? You can do that by calling</p> <pre><code>browser.add_events(gtk.gdk.KEY_PRESS_MASK) </code></pre>
0
2010-03-29T15:24:54Z
[ "python", "gtk", "keypress", "forwarding" ]
Forwarding keypresses in GTK
2,526,589
<p>I'm writing a bit of code for a Gedit plugin. I'm using Python and the interface (obviously) is GTK.</p> <p>So, the issue I'm having is quite simple: I have a search box (a gtk.Entry) and right below I have a results box (a gtk.TreeView). Right after you type something in the search box you are presented a bunch of...
0
2010-03-26T20:39:29Z
2,556,400
<p>Not a proper answer to the question (I don't know how to forward key presses), but there's an alternative solution to your problem.</p> <p>Manipulate the TreeView cursor/selection directly, for example:</p> <pre><code>path, column = browser.get_cursor() browser.set_cursor((path[0] + 1,)) # Down </code></pre>
1
2010-03-31T20:57:57Z
[ "python", "gtk", "keypress", "forwarding" ]
Compiling a Python binding on Linux
2,526,632
<p>I'm trying to compile a Python binding, but I'm unable to find the python.h header on debian. Which package should I install?</p>
3
2010-03-26T20:46:54Z
2,526,641
<p>you should install <a href="http://packages.debian.org/search?keywords=python-dev"><code>python-dev</code></a></p>
5
2010-03-26T20:48:38Z
[ "python", "debian", "binding" ]
Compiling a Python binding on Linux
2,526,632
<p>I'm trying to compile a Python binding, but I'm unable to find the python.h header on debian. Which package should I install?</p>
3
2010-03-26T20:46:54Z
2,526,648
<p>The python-dev package needs to be installed.</p>
1
2010-03-26T20:49:31Z
[ "python", "debian", "binding" ]
Compiling a Python binding on Linux
2,526,632
<p>I'm trying to compile a Python binding, but I'm unable to find the python.h header on debian. Which package should I install?</p>
3
2010-03-26T20:46:54Z
2,526,652
<p>You are missing the development header. try</p> <pre><code>sudo apt-get install python-dev </code></pre>
0
2010-03-26T20:50:14Z
[ "python", "debian", "binding" ]
Compiling a Python binding on Linux
2,526,632
<p>I'm trying to compile a Python binding, but I'm unable to find the python.h header on debian. Which package should I install?</p>
3
2010-03-26T20:46:54Z
2,526,781
<p>First of all, the header file for embedding or extending python is <code>Python.h</code>, with an uppercase P. Linux is case sensitive, and python.h won't work.</p> <p>On debian and debian deriviatives like ubuntu, you can use apt-file to find out what package to install, given a filename:</p> <pre><code>$ apt-fi...
1
2010-03-26T21:11:20Z
[ "python", "debian", "binding" ]
Compiling a Python binding on Linux
2,526,632
<p>I'm trying to compile a Python binding, but I'm unable to find the python.h header on debian. Which package should I install?</p>
3
2010-03-26T20:46:54Z
15,634,881
<pre><code>sudo apt-get install python2.6-dev </code></pre> <p>or</p> <pre><code>sudo apt-get install python2.7-dev </code></pre> <p>According to virtualenv option</p>
0
2013-03-26T10:35:02Z
[ "python", "debian", "binding" ]
I need a simple command line program to transform XML using an XSL Stylesheet
2,526,681
<p>I am on OSX Snow Leopard (10.6.2) I can install anything I need to. I would preferably like a Python or Java solution. I have searched on Google and found lots of information on writing my own program to do this, but this is a just a quick and dirty experiment so I don't want to invest a lot of time on writing a bun...
15
2010-03-26T20:55:22Z
2,526,695
<p><a href="http://xml.apache.org/xalan-j/" rel="nofollow">http://xml.apache.org/xalan-j/</a></p>
2
2010-03-26T20:57:48Z
[ "java", "python", "xml", "osx", "xslt" ]
I need a simple command line program to transform XML using an XSL Stylesheet
2,526,681
<p>I am on OSX Snow Leopard (10.6.2) I can install anything I need to. I would preferably like a Python or Java solution. I have searched on Google and found lots of information on writing my own program to do this, but this is a just a quick and dirty experiment so I don't want to invest a lot of time on writing a bun...
15
2010-03-26T20:55:22Z
2,526,698
<p>Use <a href="http://codespeak.net/lxml/" rel="nofollow"><code>lxml</code></a>. It is very easy to use and very fast. It can work with XPath and includes a <a href="http://codespeak.net/lxml/xpathxslt.html#xslt" rel="nofollow">XSLT transformer</a>.</p>
4
2010-03-26T20:58:30Z
[ "java", "python", "xml", "osx", "xslt" ]
I need a simple command line program to transform XML using an XSL Stylesheet
2,526,681
<p>I am on OSX Snow Leopard (10.6.2) I can install anything I need to. I would preferably like a Python or Java solution. I have searched on Google and found lots of information on writing my own program to do this, but this is a just a quick and dirty experiment so I don't want to invest a lot of time on writing a bun...
15
2010-03-26T20:55:22Z
2,526,707
<p>If I assume correctly that you want to supply a stylesheet and an XML document then Xalan-J has a command line feature you can use to do this:</p> <p><a href="http://xml.apache.org/xalan-j/commandline.html" rel="nofollow">http://xml.apache.org/xalan-j/commandline.html</a></p> <p>which can be invoked with:</p> <pr...
3
2010-03-26T20:59:52Z
[ "java", "python", "xml", "osx", "xslt" ]
I need a simple command line program to transform XML using an XSL Stylesheet
2,526,681
<p>I am on OSX Snow Leopard (10.6.2) I can install anything I need to. I would preferably like a Python or Java solution. I have searched on Google and found lots of information on writing my own program to do this, but this is a just a quick and dirty experiment so I don't want to invest a lot of time on writing a bun...
15
2010-03-26T20:55:22Z
2,526,720
<p>Have you seen <a href="http://xmlstar.sourceforge.net/" rel="nofollow">XMLStarlet</a> (an XML command line toolset) ? It does lots of XML-related querying transformation, and in particular:</p> <pre><code>xml tr --help XMLStarlet Toolkit: Transform XML document(s) using XSLT Usage: xml tr [&lt;options&gt;] &lt;xsl-...
2
2010-03-26T21:01:42Z
[ "java", "python", "xml", "osx", "xslt" ]
I need a simple command line program to transform XML using an XSL Stylesheet
2,526,681
<p>I am on OSX Snow Leopard (10.6.2) I can install anything I need to. I would preferably like a Python or Java solution. I have searched on Google and found lots of information on writing my own program to do this, but this is a just a quick and dirty experiment so I don't want to invest a lot of time on writing a bun...
15
2010-03-26T20:55:22Z
2,526,724
<p>I'd recommend <a href="http://sourceforge.net/projects/saxon/">Saxon</a>, which can be run from the command line like so:</p> <pre><code>java -jar /path/to/saxon.jar xmlfile xslfile </code></pre>
13
2010-03-26T21:02:38Z
[ "java", "python", "xml", "osx", "xslt" ]
I need a simple command line program to transform XML using an XSL Stylesheet
2,526,681
<p>I am on OSX Snow Leopard (10.6.2) I can install anything I need to. I would preferably like a Python or Java solution. I have searched on Google and found lots of information on writing my own program to do this, but this is a just a quick and dirty experiment so I don't want to invest a lot of time on writing a bun...
15
2010-03-26T20:55:22Z
2,528,244
<p>Have you tried '<em>xsltproc</em>'? It's probably already installed.</p> <p><a href="http://xmlsoft.org/XSLT/xsltproc2.html">http://xmlsoft.org/XSLT/xsltproc2.html</a></p>
18
2010-03-27T05:23:42Z
[ "java", "python", "xml", "osx", "xslt" ]
I need a simple command line program to transform XML using an XSL Stylesheet
2,526,681
<p>I am on OSX Snow Leopard (10.6.2) I can install anything I need to. I would preferably like a Python or Java solution. I have searched on Google and found lots of information on writing my own program to do this, but this is a just a quick and dirty experiment so I don't want to invest a lot of time on writing a bun...
15
2010-03-26T20:55:22Z
2,541,765
<p>I have used Saxon 6.5 for years for command line transformations. (Java, XSLT 1)</p> <p>An excellent fallback if a native solution is not available.</p>
0
2010-03-29T22:46:30Z
[ "java", "python", "xml", "osx", "xslt" ]
I need a simple command line program to transform XML using an XSL Stylesheet
2,526,681
<p>I am on OSX Snow Leopard (10.6.2) I can install anything I need to. I would preferably like a Python or Java solution. I have searched on Google and found lots of information on writing my own program to do this, but this is a just a quick and dirty experiment so I don't want to invest a lot of time on writing a bun...
15
2010-03-26T20:55:22Z
13,917,435
<p>see <a href="http://stackoverflow.com/q/9756520/520567">this question</a> for another solution with com.sun.org.apache.xalan.internal.xsltc.cmdline.Transform. But I noticed some weirdness with namespaces compared to xalan processing. Be aware behavior might be non standard.</p> <p>Also you know, internal java class...
0
2012-12-17T15:51:49Z
[ "java", "python", "xml", "osx", "xslt" ]
Moon / Lunar Phase Algorithm
2,526,815
<p>Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year?</p> <p>Googling tells me the answer is in some Astronomy book, but I don't really want to buy a whole book when I only need a single page.</p> <p><strong>Update:</strong></p...
24
2010-03-26T21:16:21Z
2,526,824
<p>I think you searched on wrong google:</p> <ul> <li><a href="http://home.att.net/~srschmitt/zenosamples/zs_lunarphasecalc.html">http://home.att.net/~srschmitt/zenosamples/zs_lunarphasecalc.html</a></li> <li><a href="http://www.voidware.com/moon_phase.htm">http://www.voidware.com/moon_phase.htm</a></li> <li><a href="...
12
2010-03-26T21:18:51Z
[ "python", "c", "algorithm", "calendar", "astronomy" ]
Moon / Lunar Phase Algorithm
2,526,815
<p>Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year?</p> <p>Googling tells me the answer is in some Astronomy book, but I don't really want to buy a whole book when I only need a single page.</p> <p><strong>Update:</strong></p...
24
2010-03-26T21:16:21Z
2,526,829
<p>A quick google revealed <a href="http://www.daniweb.com/code/post968407.html" rel="nofollow">this</a>.</p>
-1
2010-03-26T21:19:38Z
[ "python", "c", "algorithm", "calendar", "astronomy" ]
Moon / Lunar Phase Algorithm
2,526,815
<p>Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year?</p> <p>Googling tells me the answer is in some Astronomy book, but I don't really want to buy a whole book when I only need a single page.</p> <p><strong>Update:</strong></p...
24
2010-03-26T21:16:21Z
2,531,541
<p>I ported some code to Python for this a while back. I was going to just link to it, but it turns out that it fell off the web in the meantime, so I had to go dust it off and upload it again. See <a href="http://bazaar.launchpad.net/~keturn/py-moon-phase/trunk/annotate/head:/moon.py">moon.py</a> which is derived fr...
14
2010-03-28T01:03:41Z
[ "python", "c", "algorithm", "calendar", "astronomy" ]
Moon / Lunar Phase Algorithm
2,526,815
<p>Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year?</p> <p>Googling tells me the answer is in some Astronomy book, but I don't really want to buy a whole book when I only need a single page.</p> <p><strong>Update:</strong></p...
24
2010-03-26T21:16:21Z
2,531,563
<p>Also, <a href="http://rhodesmill.org/pyephem/">pyephem — scientific-grade astronomy routines</a> [<a href="http://pypi.python.org/pypi/pyephem/">PyPI</a>], which is a Python package but has the <a href="http://bitbucket.org/brandon/pyephem/src/tip/libastro-3.7.4/moon.c">computational guts in C</a>, and that <em>do...
6
2010-03-28T01:16:50Z
[ "python", "c", "algorithm", "calendar", "astronomy" ]
Moon / Lunar Phase Algorithm
2,526,815
<p>Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year?</p> <p>Googling tells me the answer is in some Astronomy book, but I don't really want to buy a whole book when I only need a single page.</p> <p><strong>Update:</strong></p...
24
2010-03-26T21:16:21Z
2,555,160
<p>I know that you're looking for Python but if you can understand C# there's an open source project out there called <a href="http://chronosxp.sourceforge.net/" rel="nofollow">Chronos XP</a> which does this very well.</p>
0
2010-03-31T17:41:08Z
[ "python", "c", "algorithm", "calendar", "astronomy" ]
Moon / Lunar Phase Algorithm
2,526,815
<p>Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year?</p> <p>Googling tells me the answer is in some Astronomy book, but I don't really want to buy a whole book when I only need a single page.</p> <p><strong>Update:</strong></p...
24
2010-03-26T21:16:21Z
2,597,088
<p>If you don't need high accuracy, you can always (ab)use a lunar (or lunisolar) calendar class (e.g., <code>HijriCalendar</code> or <code>ChineseLunisolarCalendar</code> in Microsoft .NET) to calculate the (approximate) moon phase of any date, as the calendar's "day-of-month" property, being a lunar (or lunisolar) ca...
-1
2010-04-08T02:01:46Z
[ "python", "c", "algorithm", "calendar", "astronomy" ]
Moon / Lunar Phase Algorithm
2,526,815
<p>Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year?</p> <p>Googling tells me the answer is in some Astronomy book, but I don't really want to buy a whole book when I only need a single page.</p> <p><strong>Update:</strong></p...
24
2010-03-26T21:16:21Z
18,667,709
<p>If you're like me, you try to be a careful programmer. So it makes you nervous when you see random code scattered across the internet that purports to solve a complex astronomical problem, but doesn't explain why the solution is correct.</p> <p>You believe that there must be authoritative sources such as <em>books<...
6
2013-09-06T22:48:50Z
[ "python", "c", "algorithm", "calendar", "astronomy" ]
Moon / Lunar Phase Algorithm
2,526,815
<p>Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year?</p> <p>Googling tells me the answer is in some Astronomy book, but I don't really want to buy a whole book when I only need a single page.</p> <p><strong>Update:</strong></p...
24
2010-03-26T21:16:21Z
32,169,397
<p>Pyephem by default uses coordinated universal (UTC) time. I wanted a program that would generate a list of full moons that would be accurate in the pacific time zone. The code below will calculate the full moons for a given year and then adjust that using the ephem.localtime() method to calibrate to the desired time...
1
2015-08-23T17:24:04Z
[ "python", "c", "algorithm", "calendar", "astronomy" ]
Is Using Python to MapReduce for Cassandra Dumb?
2,527,173
<p>Since Cassandra doesn't have MapReduce built in yet (I think it's coming in 0.7), is it dumb to try and MapReduce with my Python client or should I just use CouchDB or Mongo or something?</p> <p>The application is stats collection, so I need to be able to sum values with grouping to increment counters. I'm not, but...
4
2010-03-26T22:28:32Z
2,528,683
<p>Cassandra supports map reduce since version 0.6. (Current stable release is 0.5.1, but go ahead and try the new map reduce functionality in 0.6.0-beta3) To get started I recommend to take a look at the word count map reduce example in 'contrib/word_count'.</p>
6
2010-03-27T08:54:33Z
[ "python", "couchdb", "mongodb", "nosql", "cassandra" ]
Is Using Python to MapReduce for Cassandra Dumb?
2,527,173
<p>Since Cassandra doesn't have MapReduce built in yet (I think it's coming in 0.7), is it dumb to try and MapReduce with my Python client or should I just use CouchDB or Mongo or something?</p> <p>The application is stats collection, so I need to be able to sum values with grouping to increment counters. I'm not, but...
4
2010-03-26T22:28:32Z
2,528,749
<p>MongoDB has update-in-place, so MongoDB should be very good with counters. <a href="http://blog.mongodb.org/post/171353301/using-mongodb-for-real-time-analytics" rel="nofollow">http://blog.mongodb.org/post/171353301/using-mongodb-for-real-time-analytics</a></p>
3
2010-03-27T09:27:26Z
[ "python", "couchdb", "mongodb", "nosql", "cassandra" ]
How do I make a dialog box that waits for user response?
2,527,247
<p>When you tkSimpleDialog.askinteger, the program stalls and waits for user input. What are the basics of writing my own method that would have the same effect? I want to make the same kind of dialog box, I just want to be able to request more information. The problem that I'm having is that when I open the new windo...
2
2010-03-26T22:43:19Z
2,527,303
<p>First off, if you can use some other widget system like PyGtk or PyQt, you should seriously consider it. Tkinter is ancient, and the newer libraries have a lot more functionality (read: more things you don't have to reinvent). I've used PyGtk and like it a lot more than Tkinter, which I used in the old Python 1.x ...
0
2010-03-26T22:55:49Z
[ "python", "tkinter" ]
Fastest way to uniqify a list in Python
2,527,405
<p>Fastest way to uniqify a list in Python without preserving order? I saw many complicated solutions on the Internet - could they be faster than simply:</p> <pre><code>list(set([a,b,c,a])) </code></pre>
18
2010-03-26T23:17:37Z
2,527,511
<pre><code>set([a, b, c, a]) </code></pre> <p>Leave it in that form if possible.</p>
21
2010-03-26T23:45:22Z
[ "python", "performance", "list" ]
Fastest way to uniqify a list in Python
2,527,405
<p>Fastest way to uniqify a list in Python without preserving order? I saw many complicated solutions on the Internet - could they be faster than simply:</p> <pre><code>list(set([a,b,c,a])) </code></pre>
18
2010-03-26T23:17:37Z
2,527,518
<p>Check out <a href="http://www.peterbe.com/plog/uniqifiers-benchmark" rel="nofollow">this post</a> with many different results. What you proposed above seems to be one of the fastest (and simplest ones)</p>
0
2010-03-26T23:47:43Z
[ "python", "performance", "list" ]
Fastest way to uniqify a list in Python
2,527,405
<p>Fastest way to uniqify a list in Python without preserving order? I saw many complicated solutions on the Internet - could they be faster than simply:</p> <pre><code>list(set([a,b,c,a])) </code></pre>
18
2010-03-26T23:17:37Z
2,527,608
<p>Going to a set only works for lists such that all their items are <em>hashable</em> -- so e.g. in your example if <code>c = []</code>, the code you give will raise an exception. For non-hashable, but comparable items, sorting the list, then using <code>itertools.groupby</code> to extract the unique items from it, i...
25
2010-03-27T00:11:40Z
[ "python", "performance", "list" ]
Fastest way to uniqify a list in Python
2,527,405
<p>Fastest way to uniqify a list in Python without preserving order? I saw many complicated solutions on the Internet - could they be faster than simply:</p> <pre><code>list(set([a,b,c,a])) </code></pre>
18
2010-03-26T23:17:37Z
2,527,652
<p>Tim Peters wrote a classic <strong>general</strong> <a href="http://code.activestate.com/recipes/52560/" rel="nofollow">cookbook recipe</a> for this problem back in 2001 (before sets were introduced). Comments by Alex Martelli, Raymond Hettinger et alia are informative and include updating to use sets etc.</p>
2
2010-03-27T00:25:57Z
[ "python", "performance", "list" ]
Replace a whole line in a txt file
2,527,435
<p>I'am new to Python 3 and could really use a little help. I have a txt file containing:</p> <pre><code>InstallPrompt= DisplayLicense= FinishMessage= TargetName=D:\somewhere FriendlyName=something </code></pre> <p>I have a python script that in the end, should change just two lines to:</p> <pre><code>TargetName...
4
2010-03-26T23:27:20Z
2,527,513
<p>A very simple solution for what you're doing:</p> <pre><code>#!/usr/bin/python import re import sys for line in open(sys.argv[1],'r').readlines(): line = re.sub(r'TargetName=.+',r'TargetName=D:\\new', line) line = re.sub(r'FriendlyName=.+',r'FriendlyName=big', line) print line, </code></pre> <p>You would inv...
2
2010-03-26T23:46:10Z
[ "python", "text", "replace", "python-3.x" ]
Replace a whole line in a txt file
2,527,435
<p>I'am new to Python 3 and could really use a little help. I have a txt file containing:</p> <pre><code>InstallPrompt= DisplayLicense= FinishMessage= TargetName=D:\somewhere FriendlyName=something </code></pre> <p>I have a python script that in the end, should change just two lines to:</p> <pre><code>TargetName...
4
2010-03-26T23:27:20Z
2,527,537
<pre><code>import fileinput for line in fileinput.FileInput("file",inplace=1): sline=line.strip().split("=") if sline[0].startswith("TargetName"): sline[1]="new.txt" elif sline[0].startswith("FriendlyName"): sline[1]="big" line='='.join(sline) print(line) </code></pre>
2
2010-03-26T23:54:13Z
[ "python", "text", "replace", "python-3.x" ]
Replace a whole line in a txt file
2,527,435
<p>I'am new to Python 3 and could really use a little help. I have a txt file containing:</p> <pre><code>InstallPrompt= DisplayLicense= FinishMessage= TargetName=D:\somewhere FriendlyName=something </code></pre> <p>I have a python script that in the end, should change just two lines to:</p> <pre><code>TargetName...
4
2010-03-26T23:27:20Z
2,527,618
<p>Writing to a temporary file and the renaming is the best way to make sure you won't get a damaged file if something goes wrong</p> <pre><code>import os from tempfile import NamedTemporaryFile fname = "lines.txt" with open(fname) as fin, NamedTemporaryFile(dir='.', delete=False) as fout: for line in fin: ...
1
2010-03-27T00:14:40Z
[ "python", "text", "replace", "python-3.x" ]
Replace a whole line in a txt file
2,527,435
<p>I'am new to Python 3 and could really use a little help. I have a txt file containing:</p> <pre><code>InstallPrompt= DisplayLicense= FinishMessage= TargetName=D:\somewhere FriendlyName=something </code></pre> <p>I have a python script that in the end, should change just two lines to:</p> <pre><code>TargetName...
4
2010-03-26T23:27:20Z
2,527,715
<p><code>subs_names.py</code> script works both Python 2.6+ and Python 3.x:</p> <pre><code>#!/usr/bin/env python from __future__ import print_function import sys, fileinput # here goes new values substitions = dict(TargetName=r"D:\new", FriendlyName="Big") inplace = '-i' in sys.argv # make substitions inplace if inp...
0
2010-03-27T00:48:12Z
[ "python", "text", "replace", "python-3.x" ]
Replace a whole line in a txt file
2,527,435
<p>I'am new to Python 3 and could really use a little help. I have a txt file containing:</p> <pre><code>InstallPrompt= DisplayLicense= FinishMessage= TargetName=D:\somewhere FriendlyName=something </code></pre> <p>I have a python script that in the end, should change just two lines to:</p> <pre><code>TargetName...
4
2010-03-26T23:27:20Z
2,528,049
<p>Is this a config (.ini) file you're trying to parse? The format looks suspiciously similar, except without a header section. You can use <a href="http://docs.python.org/py3k/library/configparser.html?highlight=configparser#module-configparser" rel="nofollow"><code>configparser</code></a>, though it may add extra s...
1
2010-03-27T03:31:59Z
[ "python", "text", "replace", "python-3.x" ]
How do I install a python package
2,527,461
<p>I want to install this python package: <a href="http://pypi.python.org/pypi/netifaces/0.5" rel="nofollow">http://pypi.python.org/pypi/netifaces/0.5</a></p> <p>But I don't know how and I know nothing about python. Still, I guess there is a standardized way to install it. Am I right?</p> <p>Thanks in advance</p>
-1
2010-03-26T23:34:01Z
2,527,480
<p>Check easy_install : <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install" rel="nofollow">http://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install</a></p>
0
2010-03-26T23:38:16Z
[ "python", "linux", "installation", "packages" ]
How do I install a python package
2,527,461
<p>I want to install this python package: <a href="http://pypi.python.org/pypi/netifaces/0.5" rel="nofollow">http://pypi.python.org/pypi/netifaces/0.5</a></p> <p>But I don't know how and I know nothing about python. Still, I guess there is a standardized way to install it. Am I right?</p> <p>Thanks in advance</p>
-1
2010-03-26T23:34:01Z
2,527,481
<p>From <a href="http://pypi.python.org/pypi" rel="nofollow">http://pypi.python.org/pypi</a>:</p> <blockquote> <p>to use a package from this index either "pip install package" or download, unpack and "python setup.py install" it.</p> </blockquote> <p>That said, often distributions of Linux package a lot in th...
2
2010-03-26T23:38:30Z
[ "python", "linux", "installation", "packages" ]
How do I install a python package
2,527,461
<p>I want to install this python package: <a href="http://pypi.python.org/pypi/netifaces/0.5" rel="nofollow">http://pypi.python.org/pypi/netifaces/0.5</a></p> <p>But I don't know how and I know nothing about python. Still, I guess there is a standardized way to install it. Am I right?</p> <p>Thanks in advance</p>
-1
2010-03-26T23:34:01Z
2,527,498
<p>You can download the binary for windows from here or use easy_install as the above poster said <a href="http://alastairs-place.net/2007/03/netifaces/netifaces-0.4-py2.4-win32.egg" rel="nofollow">http://alastairs-place.net/2007/03/netifaces/netifaces-0.4-py2.4-win32.egg</a> </p>
0
2010-03-26T23:43:00Z
[ "python", "linux", "installation", "packages" ]
PHP's form bracket trick is to Django's ___?
2,527,476
<p>In PHP you can create form elements with names like:</p> <pre><code>category[1] category[2] </code></pre> <p>or even</p> <pre><code>category[junk] category[test] </code></pre> <p>When the form is posted, <code>category</code> is automatically turned into a nice dictionary like:</p> <pre><code>category[1] =&gt; ...
4
2010-03-26T23:37:15Z
2,527,497
<p>You can do <code>request.POST['namefromform']</code> - I take it this isn't what you're looking for?</p>
0
2010-03-26T23:42:54Z
[ "php", "python", "django" ]
PHP's form bracket trick is to Django's ___?
2,527,476
<p>In PHP you can create form elements with names like:</p> <pre><code>category[1] category[2] </code></pre> <p>or even</p> <pre><code>category[junk] category[test] </code></pre> <p>When the form is posted, <code>category</code> is automatically turned into a nice dictionary like:</p> <pre><code>category[1] =&gt; ...
4
2010-03-26T23:37:15Z
2,527,560
<p>Use <code>request.POST.keys()</code></p>
0
2010-03-26T23:59:18Z
[ "php", "python", "django" ]
PHP's form bracket trick is to Django's ___?
2,527,476
<p>In PHP you can create form elements with names like:</p> <pre><code>category[1] category[2] </code></pre> <p>or even</p> <pre><code>category[junk] category[test] </code></pre> <p>When the form is posted, <code>category</code> is automatically turned into a nice dictionary like:</p> <pre><code>category[1] =&gt; ...
4
2010-03-26T23:37:15Z
2,527,574
<p>Sorry, as far as I've found, getlist is all there is for what you want, but you could easily parse the request using <code>request.POST.keys()</code> and turn them into dictionaries.</p>
0
2010-03-27T00:02:21Z
[ "php", "python", "django" ]
PHP's form bracket trick is to Django's ___?
2,527,476
<p>In PHP you can create form elements with names like:</p> <pre><code>category[1] category[2] </code></pre> <p>or even</p> <pre><code>category[junk] category[test] </code></pre> <p>When the form is posted, <code>category</code> is automatically turned into a nice dictionary like:</p> <pre><code>category[1] =&gt; ...
4
2010-03-26T23:37:15Z
2,527,580
<p>I'm not a python expert but you might try</p> <pre><code>for key,value in request.POST.iteritems() doSomething.... </code></pre>
0
2010-03-27T00:03:18Z
[ "php", "python", "django" ]
PHP's form bracket trick is to Django's ___?
2,527,476
<p>In PHP you can create form elements with names like:</p> <pre><code>category[1] category[2] </code></pre> <p>or even</p> <pre><code>category[junk] category[test] </code></pre> <p>When the form is posted, <code>category</code> is automatically turned into a nice dictionary like:</p> <pre><code>category[1] =&gt; ...
4
2010-03-26T23:37:15Z
2,528,085
<p>Hardly pretty, but it should get the job done:</p> <pre><code>import re def getdict(d, pref): r = re.compile(r'^%s\[(.*)\]$' % pref) return dict((r.sub(r'\1', k), v) for (k, v) in d.iteritems() if r.match(k)) D = { 'foo[bar]': '123', 'foo[baz]': '456', 'quux': '789', } print getdict(D, 'foo') # Returns...
1
2010-03-27T03:50:25Z
[ "php", "python", "django" ]
PHP's form bracket trick is to Django's ___?
2,527,476
<p>In PHP you can create form elements with names like:</p> <pre><code>category[1] category[2] </code></pre> <p>or even</p> <pre><code>category[junk] category[test] </code></pre> <p>When the form is posted, <code>category</code> is automatically turned into a nice dictionary like:</p> <pre><code>category[1] =&gt; ...
4
2010-03-26T23:37:15Z
2,528,916
<p>You could use <a href="http://code.djangoproject.com/browser/django/trunk/django/utils/datastructures.py#L365" rel="nofollow"><code>django.utils.datastructures.DotExpandedDict</code></a> with inputs named category.1, category.2 etc. to do something similar, but I don't really see why you would if you ever have to va...
2
2010-03-27T10:34:53Z
[ "php", "python", "django" ]
PHP's form bracket trick is to Django's ___?
2,527,476
<p>In PHP you can create form elements with names like:</p> <pre><code>category[1] category[2] </code></pre> <p>or even</p> <pre><code>category[junk] category[test] </code></pre> <p>When the form is posted, <code>category</code> is automatically turned into a nice dictionary like:</p> <pre><code>category[1] =&gt; ...
4
2010-03-26T23:37:15Z
5,284,276
<p>django.utils.datastrctures has DotExpandedDict</p> <p>I have written fork of it, that parses dictionary by brackets.. </p> <pre><code>class BrExpandedDict(dict): """ A special dictionary constructor that takes a dictionary in which the keys may contain brackets to specify inner dictionaries. It's confu...
0
2011-03-12T17:49:30Z
[ "php", "python", "django" ]
Python c_types .dll functions (pari library)
2,527,705
<p>Alright, so <a href="http://stackoverflow.com/questions/2506087/python-pari-library">a couple days ago</a> I decided to try and write a primitive wrapper for the PARI library. Ever since then I've been playing with <code>ctypes</code> library in loading the dll and accessing the functions contained using code simila...
2
2010-03-27T00:44:14Z
2,529,944
<p>You have two problems here, one give fibo the correct return type and two convert the GEN return type to the value you are looking for.</p> <p>Poking around the source code a bit, you'll find that GEN is defined as a pointer to a long. Also, at looks like the library provides some converting/printing GENs. I focu...
2
2010-03-27T16:10:58Z
[ "python", "ctypes", "pari" ]
Standardizing a Release/Tools group on a specific language
2,527,867
<p>I'm part of a six-member build and release team for an embedded software company. We also support a lot of developer tools, such as Atlassian's Fisheye, Jira, etc., Perforce, Bugzilla, AnthillPro, and a couple of homebrew tools (like my Django release notes generator).</p> <p>Most of the time, our team just writes ...
4
2010-03-27T02:10:11Z
2,527,917
<p>Google standardized on Python for such tasks (and many more) a bit before I joined the company; as far as I know, huge advantages such as Python's great implementations on the JVM and .NET didn't even play a role in the decision -- it was all about readability. At the time (and to some extent, even now) the theory ...
4
2010-03-27T02:36:29Z
[ "python", "perl", "groovy" ]
Standardizing a Release/Tools group on a specific language
2,527,867
<p>I'm part of a six-member build and release team for an embedded software company. We also support a lot of developer tools, such as Atlassian's Fisheye, Jira, etc., Perforce, Bugzilla, AnthillPro, and a couple of homebrew tools (like my Django release notes generator).</p> <p>Most of the time, our team just writes ...
4
2010-03-27T02:10:11Z
2,528,064
<p>Two points:</p> <ul> <li><p>"Eww Perl gross" is somewhat of an urban legend. You can write great clean self-documenting code in Perl, and your can write write-only code in pretty much any language. It's a property of a developer, not a language. </p> <p>Just because you're writing glue code, doesn't mean the code ...
6
2010-03-27T03:41:23Z
[ "python", "perl", "groovy" ]
Standardizing a Release/Tools group on a specific language
2,527,867
<p>I'm part of a six-member build and release team for an embedded software company. We also support a lot of developer tools, such as Atlassian's Fisheye, Jira, etc., Perforce, Bugzilla, AnthillPro, and a couple of homebrew tools (like my Django release notes generator).</p> <p>Most of the time, our team just writes ...
4
2010-03-27T02:10:11Z
2,529,182
<p>First, it's important to note that it is very hard to convince someone they're wrong.</p> <blockquote> <p>He's advocating bash scripts and Perl, due to their universality and simplicity</p> </blockquote> <p>Bash scripts are not simple. The bash programming model is really complex and unfriendly. <code>if</...
-1
2010-03-27T12:05:46Z
[ "python", "perl", "groovy" ]
Standardizing a Release/Tools group on a specific language
2,527,867
<p>I'm part of a six-member build and release team for an embedded software company. We also support a lot of developer tools, such as Atlassian's Fisheye, Jira, etc., Perforce, Bugzilla, AnthillPro, and a couple of homebrew tools (like my Django release notes generator).</p> <p>Most of the time, our team just writes ...
4
2010-03-27T02:10:11Z
2,534,316
<p>I don't think anyone is going to be able to solve your problem on Stackoverflow. Your choice of tools, methods, and process are much more affected by social constraints, e.g. what your boss wants and what you want, then technical merits. That's not necessarily bad. </p> <p>The short answer is "Use what is going to ...
1
2010-03-28T20:00:22Z
[ "python", "perl", "groovy" ]
Parsing a tweet to extract hashtags into an array in Python
2,527,892
<p>I am having a heck of a time taking the information in a tweet including hashtags, and pulling each hashtag into an array using Python. I am embarrassed to even put what I have been trying thus far.</p> <p>For example, "I love #stackoverflow because #people are very #helpful!"</p> <p>This should pull the 3 hashta...
9
2010-03-27T02:25:09Z
2,527,902
<pre><code>hashtags = [word for word in tweet.split() if word[0] == "#"] </code></pre>
1
2010-03-27T02:28:14Z
[ "python", "arrays" ]
Parsing a tweet to extract hashtags into an array in Python
2,527,892
<p>I am having a heck of a time taking the information in a tweet including hashtags, and pulling each hashtag into an array using Python. I am embarrassed to even put what I have been trying thus far.</p> <p>For example, "I love #stackoverflow because #people are very #helpful!"</p> <p>This should pull the 3 hashta...
9
2010-03-27T02:25:09Z
2,527,903
<p>A simple regex should do the job:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = "I love #stackoverflow because #people are very #helpful!" &gt;&gt;&gt; re.findall(r"#(\w+)", s) ['stackoverflow', 'people', 'helpful'] </code></pre> <p>Note though, that as suggested in other answers, this may also find non-h...
36
2010-03-27T02:30:27Z
[ "python", "arrays" ]
Parsing a tweet to extract hashtags into an array in Python
2,527,892
<p>I am having a heck of a time taking the information in a tweet including hashtags, and pulling each hashtag into an array using Python. I am embarrassed to even put what I have been trying thus far.</p> <p>For example, "I love #stackoverflow because #people are very #helpful!"</p> <p>This should pull the 3 hashta...
9
2010-03-27T02:25:09Z
2,527,954
<pre><code>&gt;&gt;&gt; s="I love #stackoverflow because #people are very #helpful!" &gt;&gt;&gt; [i for i in s.split() if i.startswith("#") ] ['#stackoverflow', '#people', '#helpful!'] </code></pre>
11
2010-03-27T02:51:37Z
[ "python", "arrays" ]
Parsing a tweet to extract hashtags into an array in Python
2,527,892
<p>I am having a heck of a time taking the information in a tweet including hashtags, and pulling each hashtag into an array using Python. I am embarrassed to even put what I have been trying thus far.</p> <p>For example, "I love #stackoverflow because #people are very #helpful!"</p> <p>This should pull the 3 hashta...
9
2010-03-27T02:25:09Z
2,528,131
<p>AndiDogs answer will screw up with links and other stuff, you may want to filter them out first. After that use this code:</p> <pre><code>UTF_CHARS = ur'a-z0-9_\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff' TAG_EXP = ur'(^|[^0-9A-Z&amp;/]+)(#|\uff03)([0-9A-Z_]*[A-Z_]+[%s]*)' % UTF_CHARS TAG_REGEX = re.compile(TAG_EXP, re...
3
2010-03-27T04:17:26Z
[ "python", "arrays" ]
Parsing a tweet to extract hashtags into an array in Python
2,527,892
<p>I am having a heck of a time taking the information in a tweet including hashtags, and pulling each hashtag into an array using Python. I am embarrassed to even put what I have been trying thus far.</p> <p>For example, "I love #stackoverflow because #people are very #helpful!"</p> <p>This should pull the 3 hashta...
9
2010-03-27T02:25:09Z
20,614,981
<p>Suppose that you have to retrieve your <code>#Hashtags</code> from a sentence full of punctuation symbols. Let's say that <code>#stackoverflow #people</code> and <code>#helpful</code>are terminated with different symbols, you want to retrieve them from <code>text</code> but you may want to avoid repetitions:</p> <p...
3
2013-12-16T15:49:53Z
[ "python", "arrays" ]
Parsing a tweet to extract hashtags into an array in Python
2,527,892
<p>I am having a heck of a time taking the information in a tweet including hashtags, and pulling each hashtag into an array using Python. I am embarrassed to even put what I have been trying thus far.</p> <p>For example, "I love #stackoverflow because #people are very #helpful!"</p> <p>This should pull the 3 hashta...
9
2010-03-27T02:25:09Z
32,498,784
<p>i had a lot of issues with unicode languages.</p> <p>i had seen many ways to extract hashtag, but found non of them answering on all cases</p> <p>so i wrote some small python code to handle most of the cases. it works for me.</p> <pre><code>def get_hashtagslist(string): ret = [] s='' hashtag = False ...
0
2015-09-10T10:02:10Z
[ "python", "arrays" ]
Parsing a tweet to extract hashtags into an array in Python
2,527,892
<p>I am having a heck of a time taking the information in a tweet including hashtags, and pulling each hashtag into an array using Python. I am embarrassed to even put what I have been trying thus far.</p> <p>For example, "I love #stackoverflow because #people are very #helpful!"</p> <p>This should pull the 3 hashta...
9
2010-03-27T02:25:09Z
37,598,957
<p>simple gist (better than chosen answer) <a href="https://gist.github.com/mahmoud/237eb20108b5805aed5f" rel="nofollow">https://gist.github.com/mahmoud/237eb20108b5805aed5f</a> also work with unicode hashtags</p>
0
2016-06-02T17:55:25Z
[ "python", "arrays" ]
Python MySQLdb placeholders syntax
2,527,941
<p>I'd like to use placeholders as seen in this example:</p> <pre><code>cursor.execute (""" UPDATE animal SET name = %s WHERE name = %s """, ("snake", "turtle")) </code></pre> <p>Except I'd like to have the query be its own variable as I need to insert a query into multiple databases, as in:</p> <pre><co...
2
2010-03-27T02:47:01Z
2,527,950
<pre><code>query = """UPDATE animal SET name = %s WHERE name = %s """ values = ("snake", "turtle") cursor.execute(query, values) cursor2.execute(query, values) </code></pre> <p>or if you want group them together...</p> <pre><code>arglist = [query, values] cursor.execute(*arglist) cursor2.execut...
3
2010-03-27T02:49:48Z
[ "python", "mysql", "pylons" ]
Simplest way to handle and display errors in a Python Pylons controller without a helper class
2,527,992
<p>I have a class User() that throw exceptions when attributes are incorrectly set. I am currently passing the exceptions from the models through the controller to the templates by essentially catching exceptions two times for each variable. </p> <p>Is this a correct way of doing it? Is there a better (but still si...
2
2010-03-27T03:07:32Z
2,528,139
<p>You could remove repetition from the code as a semi-measure:</p> <pre><code>class RegisterController(BaseController): def index(self): if request.POST: c.errors = {} u = User() for key in "name email password".split(): try: value =...
0
2010-03-27T04:24:21Z
[ "python", "forms", "pylons" ]
Can SQLAlchemy DateTime Objects Only Be Naive?
2,528,189
<p>I am working with SQLAlchemy, and I'm not yet sure which database I'll use under it, so I want to remain as DB-agnostic as possible. How can I store a timezone-aware datetime object in the DB without tying myself to a specific database? Right now, I'm making sure that times are UTC before I store them in the DB, a...
22
2010-03-27T05:01:00Z
2,528,453
<p>There is a <code>timezone</code> parameter to <a href="http://docs.sqlalchemy.org/en/latest/core/types.html#sqlalchemy.types.DateTime"><code>DateTime</code></a> column time, so there is no problem with storing timezone-aware <code>datetime</code> objects. However I found convenient to convert stored <code>datetime</...
36
2010-03-27T07:01:27Z
[ "python", "datetime", "sqlalchemy" ]