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 |
|---|---|---|---|---|---|---|---|---|---|
Python UTF-16 WAVY DASH encoding question / issue | 2,269,171 | <p>I was doing some work today, and came across an issue where something "looked funny". I had been interpreting some string data as utf-8, and checking the encoded form. The data was coming from ldap (Specifically, Active Directory) via python-ldap. No surprises there.</p>
<p>So I came upon the byte sequence '\xe3\x8... | 4 | 2010-02-15T21:48:30Z | 2,269,279 | <p>But it decodes okay:</p>
<pre><code>>>> u"\u3030".encode("utf-16-le")
'00'
>>> '00'.decode("utf-16-le")
u'\u3030'
</code></pre>
<p>It's that the UTF-16 encoding of that character happens to coincide with the ASCII code for '0'. You could also represent it with '\x30\x30':</p>
<pre><code>>>... | 2 | 2010-02-15T22:10:24Z | [
"python",
"unicode",
"encoding",
"utf-8",
"utf-16"
] |
Python UTF-16 WAVY DASH encoding question / issue | 2,269,171 | <p>I was doing some work today, and came across an issue where something "looked funny". I had been interpreting some string data as utf-8, and checking the encoded form. The data was coming from ldap (Specifically, Active Directory) via python-ldap. No surprises there.</p>
<p>So I came upon the byte sequence '\xe3\x8... | 4 | 2010-02-15T21:48:30Z | 2,269,374 | <p>You are being confused by two things here (threw me off too):</p>
<ol>
<li>utf-16 and utf-32 encodings use a BOM unless you specify which byte order to use, via utf-16-be and such. This is the \xff\xfe in the second last line.</li>
<li><p>'00' is two of the characters <a href="http://www.fileformat.info/info/unico... | 1 | 2010-02-15T22:27:23Z | [
"python",
"unicode",
"encoding",
"utf-8",
"utf-16"
] |
Python UTF-16 WAVY DASH encoding question / issue | 2,269,171 | <p>I was doing some work today, and came across an issue where something "looked funny". I had been interpreting some string data as utf-8, and checking the encoded form. The data was coming from ldap (Specifically, Active Directory) via python-ldap. No surprises there.</p>
<p>So I came upon the byte sequence '\xe3\x8... | 4 | 2010-02-15T21:48:30Z | 2,395,790 | <p>There is a basic error in your sample code above. Remember, you <em>encode</em> Unicode to an <em>encoded string</em>, and you <em>decode</em> from an <em>encoded string</em> back to Unicode. So, you do:</p>
<pre><code>'\xe3\x80\xb0'.decode('utf-8').encode('utf-16-le').decode('utf-8')
</code></pre>
<p>which transl... | 0 | 2010-03-07T09:38:08Z | [
"python",
"unicode",
"encoding",
"utf-8",
"utf-16"
] |
How do I get my simple twisted proxy to work? | 2,269,380 | <p>I am attempting to make use of the <a href="http://twistedmatrix.com/trac/wiki/TwistedWeb" rel="nofollow">Twisted.Web</a> framework.</p>
<p>Notice the three line comments (#line1, #line2, #line3). I want to create a proxy (gateway?) that will forward a request to one of two servers depending on the url. If I uncomm... | 3 | 2010-02-15T22:28:01Z | 2,269,568 | <p>Since your <code>Simple</code> class implements the <code>getChild()</code> method, it is implied that this is not a leaf node, however, you are stating that it is a leaf node by setting <code>isLeaf = True</code>. (How can a leaf node have a child?).</p>
<p>Try changing <code>isLeaf = True</code> to <code>isLeaf =... | 4 | 2010-02-15T23:04:46Z | [
"python",
"proxy",
"twisted"
] |
How do I get my simple twisted proxy to work? | 2,269,380 | <p>I am attempting to make use of the <a href="http://twistedmatrix.com/trac/wiki/TwistedWeb" rel="nofollow">Twisted.Web</a> framework.</p>
<p>Notice the three line comments (#line1, #line2, #line3). I want to create a proxy (gateway?) that will forward a request to one of two servers depending on the url. If I uncomm... | 3 | 2010-02-15T22:28:01Z | 2,276,258 | <p>Here is the final working solution. Basically two resource request go to the GAE server, and all remaining request go to the GWT server.</p>
<p>Other than implementing mhawke's change, there is only one other change, and that was adding '"/" + name' to the proxy servers path. I assume this had to be done because th... | 2 | 2010-02-16T20:53:24Z | [
"python",
"proxy",
"twisted"
] |
Django: Template context processor request variable | 2,269,508 | <p>I am trying to implement <a href="http://code.google.com/p/django-facebookconnect/" rel="nofollow">django-facebookconnect</a>, for I need to check if a user logged in via Facebook or a regular user.</p>
<p>At the template, I can check if user logged in via facebook by checking <code>request.facebook.uid</code>
such... | 0 | 2010-02-15T22:52:28Z | 2,269,584 | <p>If you have access via the <code>request</code> object, why do you need to add a special <code>is_facebook</code> boolean at all? Just enable the built-in <code>django.core.context_processors.request</code> and this will ensure that <code>request</code> is present in all templates, then you can do this:</p>
<pre><c... | 1 | 2010-02-15T23:07:43Z | [
"python",
"django"
] |
Django: Template context processor request variable | 2,269,508 | <p>I am trying to implement <a href="http://code.google.com/p/django-facebookconnect/" rel="nofollow">django-facebookconnect</a>, for I need to check if a user logged in via Facebook or a regular user.</p>
<p>At the template, I can check if user logged in via facebook by checking <code>request.facebook.uid</code>
such... | 0 | 2010-02-15T22:52:28Z | 2,270,514 | <p>It could be a timing issue. Make sure that the Common middleware comes before the facebook middleware in your settings file. You can probably debug and see when the facebook middleware is modifying the request and when your context processor is invoked. That may give you some clue as to why this is happening. Bu... | 0 | 2010-02-16T03:51:31Z | [
"python",
"django"
] |
Package module not found in Python 2.5, but found in 2.6 | 2,269,697 | <p>I have package structure that looks like this: </p>
<ul>
<li>ae
<ul>
<li>util</li>
</ul></li>
</ul>
<p><strong>util</strong> contains a method <strong>mkdir(dir)</strong> that, given a path, creates a directory. If the directory exists, no error is thrown; the method fails silently. </p>
<p>The directory <strong>... | 0 | 2010-02-15T23:29:52Z | 2,269,711 | <p>It depends where You call this method, and what Your import is. If You write:</p>
<pre><code>from ae import util
util.mkdir(SOURCES)
</code></pre>
<p>everything should be ok. </p>
<p>The error occurs probably because of the difference in the import policy between Python 2.5 and 2.6.</p>
| 0 | 2010-02-15T23:34:01Z | [
"python",
"module",
"packages",
"package"
] |
Package module not found in Python 2.5, but found in 2.6 | 2,269,697 | <p>I have package structure that looks like this: </p>
<ul>
<li>ae
<ul>
<li>util</li>
</ul></li>
</ul>
<p><strong>util</strong> contains a method <strong>mkdir(dir)</strong> that, given a path, creates a directory. If the directory exists, no error is thrown; the method fails silently. </p>
<p>The directory <strong>... | 0 | 2010-02-15T23:29:52Z | 2,269,748 | <p>Maybe Python 2.5 is accessing a different version of <code>util</code> that does not have the <code>mkdir</code> method.</p>
| 2 | 2010-02-15T23:43:12Z | [
"python",
"module",
"packages",
"package"
] |
Package module not found in Python 2.5, but found in 2.6 | 2,269,697 | <p>I have package structure that looks like this: </p>
<ul>
<li>ae
<ul>
<li>util</li>
</ul></li>
</ul>
<p><strong>util</strong> contains a method <strong>mkdir(dir)</strong> that, given a path, creates a directory. If the directory exists, no error is thrown; the method fails silently. </p>
<p>The directory <strong>... | 0 | 2010-02-15T23:29:52Z | 2,269,765 | <ul>
<li>do you <code>import ae.util</code> or <code>import util</code>? Either <code>ae</code> or its parent dir should be in PYTHONPATH, but not both</li>
<li>verify you have the right <code>util</code> module by running <code>print util</code> (will print the module's source file)</li>
</ul>
| 1 | 2010-02-15T23:49:24Z | [
"python",
"module",
"packages",
"package"
] |
Why can't I do this INSERT in MYSQL? (Python MySQLdb) | 2,269,776 | <p>This is a follow up to this question I asked earlier:
<a href="http://stackoverflow.com/questions/2267034/why-cant-i-insert-into-mysql/2267076#2267076">http://stackoverflow.com/questions/2267034/why-cant-i-insert-into-mysql/2267076#2267076</a></p>
<p>That question solved it partly. Now I'm doing it in Python and it... | 1 | 2010-02-15T23:53:35Z | 2,269,805 | <p>This could depend on whatever API you use for SQL calls, but it could be that either:</p>
<p>a) values are in fact not strings and you need to replace %s with appropriate types (%d for integers, for example?), or </p>
<p>b) string values need to be quoted like this: <code>values('%s',PointFromWKB(point('%s','%s'))... | 1 | 2010-02-16T00:03:52Z | [
"python",
"mysql",
"database",
"insert"
] |
Why can't I do this INSERT in MYSQL? (Python MySQLdb) | 2,269,776 | <p>This is a follow up to this question I asked earlier:
<a href="http://stackoverflow.com/questions/2267034/why-cant-i-insert-into-mysql/2267076#2267076">http://stackoverflow.com/questions/2267034/why-cant-i-insert-into-mysql/2267076#2267076</a></p>
<p>That question solved it partly. Now I'm doing it in Python and it... | 1 | 2010-02-15T23:53:35Z | 2,269,809 | <p>Solved. Put parantheses around my variables.</p>
<pre><code>cursor.execute("INSERT INTO life(user_id, utm) values(%s,PointFromWKB(point(%s,%s)))",(the_user_id, utm_easting, utm_northing))
</code></pre>
| 1 | 2010-02-16T00:04:37Z | [
"python",
"mysql",
"database",
"insert"
] |
Why can't I do this INSERT in MYSQL? (Python MySQLdb) | 2,269,776 | <p>This is a follow up to this question I asked earlier:
<a href="http://stackoverflow.com/questions/2267034/why-cant-i-insert-into-mysql/2267076#2267076">http://stackoverflow.com/questions/2267034/why-cant-i-insert-into-mysql/2267076#2267076</a></p>
<p>That question solved it partly. Now I'm doing it in Python and it... | 1 | 2010-02-15T23:53:35Z | 2,269,816 | <p>From <a href="http://www.kitebird.com/articles/pydbapi.pdf" rel="nofollow">here (pdf)</a>:</p>
<blockquote>
<p>Following the statement string
argument to execute(), <strong>provide a tuple</strong>
containing the values to be bound to
the placeholders, in the order they
should appear within the string. If... | 4 | 2010-02-16T00:05:15Z | [
"python",
"mysql",
"database",
"insert"
] |
How to convert an int to a hex string? | 2,269,827 | <p>I want to take an integer (that will be <= 255), to a hex string representation</p>
<p>e.g.: I want to pass in <code>65</code> and get out <code>'\x41'</code>, or <code>255</code> and get <code>'\xff'</code>.</p>
<p>I've tried doing this with the <code>struct.pack('c',</code>65<code>)</code>, but that chokes on... | 83 | 2010-02-16T00:07:53Z | 2,269,836 | <p>You are looking for the <code>chr</code> function.</p>
<p>You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.</p>
<pre><code>>>> chr(0x... | 99 | 2010-02-16T00:10:13Z | [
"python",
"string",
"hex",
"int"
] |
How to convert an int to a hex string? | 2,269,827 | <p>I want to take an integer (that will be <= 255), to a hex string representation</p>
<p>e.g.: I want to pass in <code>65</code> and get out <code>'\x41'</code>, or <code>255</code> and get <code>'\xff'</code>.</p>
<p>I've tried doing this with the <code>struct.pack('c',</code>65<code>)</code>, but that chokes on... | 83 | 2010-02-16T00:07:53Z | 2,269,841 | <p>Try:</p>
<pre><code>"0x%x" % 255 # => 0xff
</code></pre>
<p>or</p>
<pre><code>"0x%X" % 255 # => 0xFF
</code></pre>
<p>Python Documentation says: "keep this under Your pillow: <a href="http://docs.python.org/library/index.html">http://docs.python.org/library/index.html</a>"</p>
| 29 | 2010-02-16T00:11:21Z | [
"python",
"string",
"hex",
"int"
] |
How to convert an int to a hex string? | 2,269,827 | <p>I want to take an integer (that will be <= 255), to a hex string representation</p>
<p>e.g.: I want to pass in <code>65</code> and get out <code>'\x41'</code>, or <code>255</code> and get <code>'\xff'</code>.</p>
<p>I've tried doing this with the <code>struct.pack('c',</code>65<code>)</code>, but that chokes on... | 83 | 2010-02-16T00:07:53Z | 2,269,848 | <p>What about <a href="http://docs.python.org/library/functions.html"><code>hex()</code></a>?</p>
<pre><code>hex(255) # 0xff
</code></pre>
<p>If you really want to have <code>\</code> in front you can do:</p>
<pre><code>print '\\' + hex(255)[1:]
</code></pre>
| 24 | 2010-02-16T00:12:47Z | [
"python",
"string",
"hex",
"int"
] |
How to convert an int to a hex string? | 2,269,827 | <p>I want to take an integer (that will be <= 255), to a hex string representation</p>
<p>e.g.: I want to pass in <code>65</code> and get out <code>'\x41'</code>, or <code>255</code> and get <code>'\xff'</code>.</p>
<p>I've tried doing this with the <code>struct.pack('c',</code>65<code>)</code>, but that chokes on... | 83 | 2010-02-16T00:07:53Z | 2,269,863 | <p>This will convert an integer to a 2 digit hex string with the 0x prefix:</p>
<pre><code>strHex = "0x%0.2X" % 255
</code></pre>
| 61 | 2010-02-16T00:17:09Z | [
"python",
"string",
"hex",
"int"
] |
How to convert an int to a hex string? | 2,269,827 | <p>I want to take an integer (that will be <= 255), to a hex string representation</p>
<p>e.g.: I want to pass in <code>65</code> and get out <code>'\x41'</code>, or <code>255</code> and get <code>'\xff'</code>.</p>
<p>I've tried doing this with the <code>struct.pack('c',</code>65<code>)</code>, but that chokes on... | 83 | 2010-02-16T00:07:53Z | 7,470,721 | <p>If you want to pack a struct with a value <255 (one byte unsigned, uint8_t) and end up with a string of one character, you're probably looking for the <a href="http://docs.python.org/library/struct.html#format-characters" rel="nofollow">format B instead of c</a>. C converts a character to a string (not too useful... | 7 | 2011-09-19T12:11:22Z | [
"python",
"string",
"hex",
"int"
] |
How to convert an int to a hex string? | 2,269,827 | <p>I want to take an integer (that will be <= 255), to a hex string representation</p>
<p>e.g.: I want to pass in <code>65</code> and get out <code>'\x41'</code>, or <code>255</code> and get <code>'\xff'</code>.</p>
<p>I've tried doing this with the <code>struct.pack('c',</code>65<code>)</code>, but that chokes on... | 83 | 2010-02-16T00:07:53Z | 8,965,218 | <p>I wanted a random integer converted into a six-digit hex string with a # at the beginning. To get this I used</p>
<pre><code>"#%6x" % random.randint(0xFFFFFF)
</code></pre>
| 1 | 2012-01-22T22:15:57Z | [
"python",
"string",
"hex",
"int"
] |
How to convert an int to a hex string? | 2,269,827 | <p>I want to take an integer (that will be <= 255), to a hex string representation</p>
<p>e.g.: I want to pass in <code>65</code> and get out <code>'\x41'</code>, or <code>255</code> and get <code>'\xff'</code>.</p>
<p>I've tried doing this with the <code>struct.pack('c',</code>65<code>)</code>, but that chokes on... | 83 | 2010-02-16T00:07:53Z | 39,884,007 | <p>Note that for large values, <code>hex()</code> still works (some other answers don't). For a decrypted RSA message, this worked great (python 2 and 3):</p>
<pre><code>import binascii
hexadecimals = hex(349593196107334030177678842158399357)
print(binascii.unhexlify(hexadecimals))
</code></pre>
| 0 | 2016-10-05T21:29:50Z | [
"python",
"string",
"hex",
"int"
] |
Low Autocorrelation Binary Sequence problem? Python troubleshooting | 2,269,831 | <p>I'm trying to model this problem (for details on it, <a href="http://www.mpi-hd.mpg.de/personalhomes/bauke/LABS/index.php" rel="nofollow">http://www.mpi-hd.mpg.de/personalhomes/bauke/LABS/index.php</a>)</p>
<p>I've seen that the proven minimum for a sequence of 10 digits is 13. However, my application seems to be ... | 0 | 2010-02-16T00:08:53Z | 2,270,020 | <p>I can't spot any obvious bug offhand, but you're making things really complicated, so maybe a bug's lurking and hiding somewhere. What about</p>
<pre><code>def evaluateHelper(self, g):
return sum(a*b for a, b in zip(self.chromosome, self.chomosome[g:]))
</code></pre>
<p>this should return the same values you're... | 2 | 2010-02-16T01:05:58Z | [
"python"
] |
Low Autocorrelation Binary Sequence problem? Python troubleshooting | 2,269,831 | <p>I'm trying to model this problem (for details on it, <a href="http://www.mpi-hd.mpg.de/personalhomes/bauke/LABS/index.php" rel="nofollow">http://www.mpi-hd.mpg.de/personalhomes/bauke/LABS/index.php</a>)</p>
<p>I've seen that the proven minimum for a sequence of 10 digits is 13. However, my application seems to be ... | 0 | 2010-02-16T00:08:53Z | 5,110,886 | <p>Your bug was here:</p>
<p><code>for i in range(len(self.chromosome) - g - 1):</code></p>
<p>The maximum value for i will be <code>len(self.chromosome) - g - 2</code>, because range is exclusive. Thus, you don't consider the last pair. It's basically the same as your other bug, just in a different place.</p>
| 1 | 2011-02-24T21:47:17Z | [
"python"
] |
Why does Sphinx generate json? | 2,269,895 | <p>I notice that <a href="http://sphinx.pocoo.org" rel="nofollow">Sphinx</a> has the ability to generate documentation in JSON. What are these files used for?</p>
| 2 | 2010-02-16T00:24:33Z | 2,269,999 | <p>I assume you're talking about the <a href="http://sphinx.pocoo.org/builders.html#sphinx.builders.html.SerializingHTMLBuilder" rel="nofollow">SerializingHTMLBuilder</a>, in which case I think the answer might be that there isn't necessarily a specific purpose in mind. Rather many things provide conversion routines o... | 0 | 2010-02-16T00:58:28Z | [
"python",
"json",
"python-sphinx"
] |
Why does Sphinx generate json? | 2,269,895 | <p>I notice that <a href="http://sphinx.pocoo.org" rel="nofollow">Sphinx</a> has the ability to generate documentation in JSON. What are these files used for?</p>
| 2 | 2010-02-16T00:24:33Z | 2,270,002 | <p>As <a href="http://sphinx.pocoo.org/builders.html#sphinx.builders.html.JSONHTMLBuilder" rel="nofollow">the docs</a> say, it's</p>
<blockquote>
<p>for use of a web application (or
custom postprocessing tool) that
doesnât use the standard HTML
templates.</p>
</blockquote>
<p>json's a good simple way for la... | 6 | 2010-02-16T01:00:00Z | [
"python",
"json",
"python-sphinx"
] |
Extracting numerical value from Python Decimal | 2,269,919 | <p>When I use the python Decimal object simply with something like:</p>
<pre><code>from decimal import *
dec = Decimal('3.432')
print dec
</code></pre>
<p>it will print 3.432, just like I want, but if i try to put that same value dec into a json object what I get in the json is Decimal("3.432"). How can I just get th... | 3 | 2010-02-16T00:31:59Z | 2,269,971 | <pre><code>>>> str(decimal.Decimal('3.1'))
'3.1'
</code></pre>
<p>Out-of-the-box JSON uses a few primitive types, like strings, heavily. </p>
<p>Your best bet is to convert your Decimals to strings when creating your JSON document from some Python object.</p>
<p>Convert the strings back to Decimal when conv... | 3 | 2010-02-16T00:50:09Z | [
"python",
"decimal"
] |
Extracting numerical value from Python Decimal | 2,269,919 | <p>When I use the python Decimal object simply with something like:</p>
<pre><code>from decimal import *
dec = Decimal('3.432')
print dec
</code></pre>
<p>it will print 3.432, just like I want, but if i try to put that same value dec into a json object what I get in the json is Decimal("3.432"). How can I just get th... | 3 | 2010-02-16T00:31:59Z | 2,269,978 | <p>You get a <code>Decimal('3.432')</code> in your JSON object? Weird... how?</p>
<pre><code>>>> from decimal import *
>>> import json
>>> json.dumps(Decimal('3.432'))
....
TypeError: Decimal('3.432') is not JSON serializable
</code></pre>
<p>In any case, if you are using a Decimal instead... | 3 | 2010-02-16T00:52:06Z | [
"python",
"decimal"
] |
Extracting numerical value from Python Decimal | 2,269,919 | <p>When I use the python Decimal object simply with something like:</p>
<pre><code>from decimal import *
dec = Decimal('3.432')
print dec
</code></pre>
<p>it will print 3.432, just like I want, but if i try to put that same value dec into a json object what I get in the json is Decimal("3.432"). How can I just get th... | 3 | 2010-02-16T00:31:59Z | 2,269,982 | <p>Interesting -- what I get is a <code>TypeError</code> exception (that's with Python 2.6's stock <code>json</code> module -- what are you using?).</p>
<p>The obvious alternative have obvious imperfections:</p>
<pre><code>>>> json.dumps(float(x))
'3.4319999999999999'
>>> json.dumps(str(x))
'"3.432"... | 1 | 2010-02-16T00:53:04Z | [
"python",
"decimal"
] |
Extracting numerical value from Python Decimal | 2,269,919 | <p>When I use the python Decimal object simply with something like:</p>
<pre><code>from decimal import *
dec = Decimal('3.432')
print dec
</code></pre>
<p>it will print 3.432, just like I want, but if i try to put that same value dec into a json object what I get in the json is Decimal("3.432"). How can I just get th... | 3 | 2010-02-16T00:31:59Z | 39,089,387 | <p>Simply convert the decimal string to <code>float</code>. There is no need to use <code>Decimal</code>.</p>
<pre><code>>>> dec = float('3.432')
>>> dec
3.432
</code></pre>
<p>Float object is JSON serializable. You don't have to make any work around.</p>
| 0 | 2016-08-22T22:00:31Z | [
"python",
"decimal"
] |
Syntax error after uploading GAE Python app | 2,269,941 | <p>I have created a GAE app that parses RSS feeds using cElementTree. Testing on my local installation of GAE works fine. When I uploaded this app and tried to test it, I get a SyntaxError.</p>
<p>The error is :</p>
<pre><code>Traceback (most recent call last): File "/base/python_lib/versions/1/google/appengine/ext... | 1 | 2010-02-16T00:40:44Z | 2,286,335 | <p>You may have run into one of the mysterious limits placed on GAE.</p>
<p>Urlopen has been overridden by google to it's urlfetch method, so there shouldn't be any difference in it. (though it might be worth trying, there are a lot of hidden things in GAE)</p>
<p>newline characters shouldn't effect cElementTree.</p>... | 0 | 2010-02-18T04:36:50Z | [
"python",
"rss",
"feeds"
] |
Cannot bind to address after socket program crashes | 2,270,343 | <p>If my program crashes before a socket is closed, the next time I run in, I get an error that looks like this;</p>
<pre><code>socket.error: [Errno 48] Address already in use
</code></pre>
<p>Changing the port fixes the problem.</p>
<p>Is there any way to avoid this, and why does this happen (when the program exits... | 14 | 2010-02-16T02:47:04Z | 2,270,357 | <p>Use <code>.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)</code> on your listening socket.</p>
<p>A search for those terms will net you many explanations for why this is necessary. Basically, after your first program closes down, the OS keeps the previous listening socket around in a shutdown state for <code>TIME_WAIT</c... | 22 | 2010-02-16T02:50:51Z | [
"python",
"sockets"
] |
Cannot bind to address after socket program crashes | 2,270,343 | <p>If my program crashes before a socket is closed, the next time I run in, I get an error that looks like this;</p>
<pre><code>socket.error: [Errno 48] Address already in use
</code></pre>
<p>Changing the port fixes the problem.</p>
<p>Is there any way to avoid this, and why does this happen (when the program exits... | 14 | 2010-02-16T02:47:04Z | 2,270,358 | <p>Most OSes take up to <em>2</em> minutes to close the socket when the program doesn't properly close it first. I've hit this many times with C programs that SEGFAULT (and I don't have it handled) or similar.<br/>
<br/>
Edit:<br/>
Thanks to <a href="http://stackoverflow.com/users/20713/ephemient">ephemient</a> for poi... | 3 | 2010-02-16T02:51:15Z | [
"python",
"sockets"
] |
Cannot bind to address after socket program crashes | 2,270,343 | <p>If my program crashes before a socket is closed, the next time I run in, I get an error that looks like this;</p>
<pre><code>socket.error: [Errno 48] Address already in use
</code></pre>
<p>Changing the port fixes the problem.</p>
<p>Is there any way to avoid this, and why does this happen (when the program exits... | 14 | 2010-02-16T02:47:04Z | 10,997,743 | <p>Other people who are getting this error may be getting it because the port is in use by another process. So check if the port is being used by any other processes and either run your program in another port or kill the blocking processes. </p>
| 2 | 2012-06-12T13:29:40Z | [
"python",
"sockets"
] |
Finding the version of an application from Python? | 2,270,345 | <p>Basically i am trying to find out what version of ArcGIS the user currently has installed, i looked through the registry and couldn't find anything related to a version string. However i know it is stored, within the .exe. </p>
<p>I've done a fair bit of googling, and can't find anything really worth it. I tried us... | 1 | 2010-02-16T02:47:52Z | 2,270,367 | <p>there's a gnu linux utility called 'strings' that prints the printable characters in any file(binary or non-binary), try using that and look for a version number like pattern</p>
<p>on windows, you can get strings here <a href="http://unxutils.sourceforge.net/" rel="nofollow">http://unxutils.sourceforge.net/</a></p... | 0 | 2010-02-16T02:54:16Z | [
"python",
"winapi"
] |
Finding the version of an application from Python? | 2,270,345 | <p>Basically i am trying to find out what version of ArcGIS the user currently has installed, i looked through the registry and couldn't find anything related to a version string. However i know it is stored, within the .exe. </p>
<p>I've done a fair bit of googling, and can't find anything really worth it. I tried us... | 1 | 2010-02-16T02:47:52Z | 2,469,304 | <p>If you prefer not to do this using pywin32, you would be able to do this with ctypes, for sure.</p>
<p>The trick will be decoding that silly file version structure that comes back.</p>
<p>There's one <a href="http://www.mail-archive.com/python-list@python.org/msg119364.html" rel="nofollow">old mailing list post</a... | 2 | 2010-03-18T11:12:30Z | [
"python",
"winapi"
] |
How to customize the auth.User Admin page in Django CRUD? | 2,270,537 | <p>I just want to add the subscription date in the User list in the Django CRUDÂ Administration site.
How can I do that ?</p>
<p>Thank you for your help</p>
| 33 | 2010-02-16T03:59:02Z | 2,270,596 | <p>Assuming that your user class is <code>User</code> and your subscription date field is <code>subscription_date</code>, this is what you need to add on your <code>admin.py</code></p>
<pre><code>class UserAdmin(admin.ModelAdmin):
list_display = ('subscription_date',)
admin.site.register(User, UserAdmin)
</code><... | -2 | 2010-02-16T04:17:17Z | [
"python",
"django",
"django-admin",
"django-users"
] |
How to customize the auth.User Admin page in Django CRUD? | 2,270,537 | <p>I just want to add the subscription date in the User list in the Django CRUDÂ Administration site.
How can I do that ?</p>
<p>Thank you for your help</p>
| 33 | 2010-02-16T03:59:02Z | 2,270,704 | <p>I finally did like this in my admin.py file :</p>
<pre><code>from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
UserAdmin.list_display = ('email', 'first_name', 'last_name', 'is_active', 'date_joined', 'is_staff')
admin.site.unregister(User)
admin.site.register(User, UserA... | 63 | 2010-02-16T04:45:58Z | [
"python",
"django",
"django-admin",
"django-users"
] |
How to customize the auth.User Admin page in Django CRUD? | 2,270,537 | <p>I just want to add the subscription date in the User list in the Django CRUDÂ Administration site.
How can I do that ?</p>
<p>Thank you for your help</p>
| 33 | 2010-02-16T03:59:02Z | 32,766,940 | <p>Another way to do this is extending the UserAdmin class.</p>
<p>You can also create a function to put on list_display</p>
<pre><code>from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class CustomUserAdmin(UserAdmin):
def __init__(self, *args, **kwargs):
super(... | 6 | 2015-09-24T16:54:53Z | [
"python",
"django",
"django-admin",
"django-users"
] |
Subscription web/desktop app [PYTHON] | 2,270,556 | <p>Firstly pardon me if i've yet again failed to title my question correctly.</p>
<p>I am required to build an app to manage magazine subscriptions. The client wants to enter subscriber data and then receive alerts at pre-set intervals such as when the subscription of a subscriber is about to expire and also the optio... | 3 | 2010-02-16T04:06:23Z | 2,277,530 | <p><strong>Payment gateway integration:</strong></p>
<ul>
<li><a href="http://uswaretech.com/blog/2009/03/exploring-authorizenet-payment-gateway-options-and-integrating-it-with-django/" rel="nofollow">Here is a detailed article</a> about how to integrate the <a href="http://www.authorize.net/" rel="nofollow">Authorize... | 2 | 2010-02-17T00:38:14Z | [
"python",
"django",
"sms",
"payment-gateway"
] |
Subscription web/desktop app [PYTHON] | 2,270,556 | <p>Firstly pardon me if i've yet again failed to title my question correctly.</p>
<p>I am required to build an app to manage magazine subscriptions. The client wants to enter subscriber data and then receive alerts at pre-set intervals such as when the subscription of a subscriber is about to expire and also the optio... | 3 | 2010-02-16T04:06:23Z | 2,277,634 | <p>I'd like to comment on the SMS alert part.</p>
<p>First, I have to admit that I'm not familiar with Django, but I assume it to be just like most other web frameworks: request based. This might be your first problem, as the alert service needs to run independently of requests. You could of course hack together som... | 0 | 2010-02-17T01:01:30Z | [
"python",
"django",
"sms",
"payment-gateway"
] |
Create a Reg Exp to search for __word__? | 2,270,634 | <p>In a program I'm making in python and I want all words formatted like <code>__word__</code> to stand out. How could I search for words like these using a regex?</p>
| 1 | 2010-02-16T04:28:39Z | 2,270,646 | <p>Take a squizz here: <a href="http://docs.python.org/library/re.html" rel="nofollow">http://docs.python.org/library/re.html</a></p>
<p>That should show you syntax and examples from which you can build a check for word(s) pre- and post-pended with 2 underscores.</p>
| 1 | 2010-02-16T04:31:02Z | [
"python",
"regex"
] |
Create a Reg Exp to search for __word__? | 2,270,634 | <p>In a program I'm making in python and I want all words formatted like <code>__word__</code> to stand out. How could I search for words like these using a regex?</p>
| 1 | 2010-02-16T04:28:39Z | 2,270,673 | <p>The simplest regex for this would be</p>
<pre><code>__.+__
</code></pre>
<p><BR>
If you want access to the word itself from your code, you should use</p>
<pre><code>__(.+)__
</code></pre>
| 0 | 2010-02-16T04:37:25Z | [
"python",
"regex"
] |
Create a Reg Exp to search for __word__? | 2,270,634 | <p>In a program I'm making in python and I want all words formatted like <code>__word__</code> to stand out. How could I search for words like these using a regex?</p>
| 1 | 2010-02-16T04:28:39Z | 2,270,675 | <p>Perhaps something like</p>
<pre><code>\b__(\S+)__\b
>>> import re
>>> re.findall(r"\b__(\S+)__\b","Here __is__ a __test__ sentence")
['is', 'test']
>>> re.findall(r"\b__(\S+)__\b","__Here__ is a test __sentence__")
['Here', 'sentence']
>>> re.findall(r"\b__(\S+)__\b","__Here... | 4 | 2010-02-16T04:37:34Z | [
"python",
"regex"
] |
Create a Reg Exp to search for __word__? | 2,270,634 | <p>In a program I'm making in python and I want all words formatted like <code>__word__</code> to stand out. How could I search for words like these using a regex?</p>
| 1 | 2010-02-16T04:28:39Z | 2,270,687 | <p>This will give you a list with all such words</p>
<pre><code>>>> import re
>>> m = re.findall("(__\w+__)", "What __word__ you search __for__")
>>> print m
['__word__', '__for__']
</code></pre>
| 0 | 2010-02-16T04:40:19Z | [
"python",
"regex"
] |
Create a Reg Exp to search for __word__? | 2,270,634 | <p>In a program I'm making in python and I want all words formatted like <code>__word__</code> to stand out. How could I search for words like these using a regex?</p>
| 1 | 2010-02-16T04:28:39Z | 2,270,689 | <pre><code>\b(__\w+__)\b
</code></pre>
<p><code>\b</code> word boundary<br>
<code>\w+</code> one or more word characters - <code>[a-zA-Z0-9_]</code></p>
| 0 | 2010-02-16T04:40:36Z | [
"python",
"regex"
] |
Create a Reg Exp to search for __word__? | 2,270,634 | <p>In a program I'm making in python and I want all words formatted like <code>__word__</code> to stand out. How could I search for words like these using a regex?</p>
| 1 | 2010-02-16T04:28:39Z | 2,270,691 | <p>simple string functions. no regex</p>
<pre><code>>>> mystring="blah __word__ blah __word2__"
>>> for item in mystring.split():
... if item.startswith("__") and item.endswith("__"):
... print item
...
__word__
__word2__
</code></pre>
| 0 | 2010-02-16T04:41:12Z | [
"python",
"regex"
] |
Hudson unable to navigate relative directories | 2,270,696 | <p>I have a <strong>Python</strong> project building with <strong>Hudson</strong>. Most unit tests work correctly, but any tests that require <em>writing to the file system</em> (I have a class that uses tarfiles, for example) can't find the <strong>tmp</strong> directory I have set up for intermediate processing (my t... | 1 | 2010-02-16T04:42:47Z | 2,270,741 | <p>I don't know anyhting about Hudson, but this is what I do to ensure, that relative path are working right:</p>
<pre><code>os.chdir(os.path.dirname(sys.argv[0]))
</code></pre>
| 0 | 2010-02-16T04:54:33Z | [
"python",
"unit-testing",
"continuous-integration",
"hudson"
] |
Hudson unable to navigate relative directories | 2,270,696 | <p>I have a <strong>Python</strong> project building with <strong>Hudson</strong>. Most unit tests work correctly, but any tests that require <em>writing to the file system</em> (I have a class that uses tarfiles, for example) can't find the <strong>tmp</strong> directory I have set up for intermediate processing (my t... | 1 | 2010-02-16T04:42:47Z | 2,270,782 | <p>Each job in Hudson has it's own working directory, at <code>/path/to/hudson/jobs/[job name]/workspace/</code></p>
<p>For individual jobs, you can set the "Use custom workspace" option (under "Advanced Project Options") to define where the workspace will be.</p>
<p>I guess it would depend on how your tests are bein... | 2 | 2010-02-16T05:03:48Z | [
"python",
"unit-testing",
"continuous-integration",
"hudson"
] |
Hudson unable to navigate relative directories | 2,270,696 | <p>I have a <strong>Python</strong> project building with <strong>Hudson</strong>. Most unit tests work correctly, but any tests that require <em>writing to the file system</em> (I have a class that uses tarfiles, for example) can't find the <strong>tmp</strong> directory I have set up for intermediate processing (my t... | 1 | 2010-02-16T04:42:47Z | 2,271,551 | <p>I don't know how you're initializing your workspace, but typically it's done by checking your project out of version control into the workspace. If this is true in your case, the easiest thing to do is to add your tmp directory to version control (say, with a README file in it, if your version control system doesn't... | 1 | 2010-02-16T08:48:28Z | [
"python",
"unit-testing",
"continuous-integration",
"hudson"
] |
Getting the name which is not defined from NameError in python | 2,270,795 | <p>As you know, if we simply do:</p>
<pre><code>>>> a > 0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
a > 0
NameError: name 'a' is not defined
</code></pre>
<p>Is there a way of catching the exception/error and extracting from it the value 'a'.
I need th... | 4 | 2010-02-16T05:07:13Z | 2,270,817 | <pre><code>>>> import exceptions
>>> try:
... a > 0
... except exceptions.NameError, e:
... print e
...
name 'a' is not defined
>>>
</code></pre>
<p>You can parse exceptions string for '' to extract value.</p>
| 1 | 2010-02-16T05:14:14Z | [
"python",
"exception-handling",
"dynamic-data",
"expression",
"nameerror"
] |
Getting the name which is not defined from NameError in python | 2,270,795 | <p>As you know, if we simply do:</p>
<pre><code>>>> a > 0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
a > 0
NameError: name 'a' is not defined
</code></pre>
<p>Is there a way of catching the exception/error and extracting from it the value 'a'.
I need th... | 4 | 2010-02-16T05:07:13Z | 2,270,822 | <pre><code>>>> import re
>>> try:
... a>0
... except (NameError,),e:
... print re.findall("name '(\w+)' is not defined",str(e))[0]
a
</code></pre>
<p>If you don't want to use regex, you could do something like this instead</p>
<pre><code>>>> str(e).split("'")[1]
'a'
</code></pre>... | 5 | 2010-02-16T05:15:32Z | [
"python",
"exception-handling",
"dynamic-data",
"expression",
"nameerror"
] |
Getting the name which is not defined from NameError in python | 2,270,795 | <p>As you know, if we simply do:</p>
<pre><code>>>> a > 0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
a > 0
NameError: name 'a' is not defined
</code></pre>
<p>Is there a way of catching the exception/error and extracting from it the value 'a'.
I need th... | 4 | 2010-02-16T05:07:13Z | 16,930,186 | <p>No <code>import exceptions</code> needed in Python 2.x</p>
<pre><code>>>> try:
... a > 0
... except NameError as e:
... print e.message.split("'")[1]
...
a
>>>
</code></pre>
<p>You assign the reference for 'a' as such:</p>
<pre><code>>>> try:
... a > 0
... except NameE... | 0 | 2013-06-05T01:35:28Z | [
"python",
"exception-handling",
"dynamic-data",
"expression",
"nameerror"
] |
Image color detection using python | 2,270,874 | <p>After downloading an image from the site i need to detect the color of the downloaded image.I successfully downloaded the image but i need to detect the color of the corresponding image and to be save it in the name of the corresponding color.Code used is given below.Tell me how can i achieve it from the current p... | 12 | 2010-02-16T05:31:48Z | 2,270,895 | <p><a href="http://effbot.org/imagingbook/image.htm" rel="nofollow">Use a PIL (Python Image Library) histogram.</a> Loop over the histogram and take the average of pixel color weighed by the pixel count.</p>
| 9 | 2010-02-16T05:37:46Z | [
"python"
] |
Image color detection using python | 2,270,874 | <p>After downloading an image from the site i need to detect the color of the downloaded image.I successfully downloaded the image but i need to detect the color of the corresponding image and to be save it in the name of the corresponding color.Code used is given below.Tell me how can i achieve it from the current p... | 12 | 2010-02-16T05:31:48Z | 2,270,898 | <p>You could use the PIL library's Image module to do this. See: <a href="http://effbot.org/imagingbook/image.htm" rel="nofollow">http://effbot.org/imagingbook/image.htm</a>.</p>
| 0 | 2010-02-16T05:37:55Z | [
"python"
] |
Image color detection using python | 2,270,874 | <p>After downloading an image from the site i need to detect the color of the downloaded image.I successfully downloaded the image but i need to detect the color of the corresponding image and to be save it in the name of the corresponding color.Code used is given below.Tell me how can i achieve it from the current p... | 12 | 2010-02-16T05:31:48Z | 2,271,013 | <p>As mentionned by others, PIL is the right library. Here is a function that open an image and look for the main color.</p>
<pre><code>def get_main_color(file):
img = Image.open(file)
colors = img.getcolors(256) #put a higher value if there are many colors in your image
max_occurence, most_present = 0, 0
... | 6 | 2010-02-16T06:17:27Z | [
"python"
] |
Image color detection using python | 2,270,874 | <p>After downloading an image from the site i need to detect the color of the downloaded image.I successfully downloaded the image but i need to detect the color of the corresponding image and to be save it in the name of the corresponding color.Code used is given below.Tell me how can i achieve it from the current p... | 12 | 2010-02-16T05:31:48Z | 2,271,015 | <p>You should use <a href="http://effbot.org/imagingbook/pil-index.htm" rel="nofollow">PIL</a>'s Parser from the ImageFile class to read the file in from the url. Then life is pretty easy because you said that the whole image is the same color. Here is some code that builds on your code:</p>
<pre><code>import urllib2
... | 4 | 2010-02-16T06:17:58Z | [
"python"
] |
Image color detection using python | 2,270,874 | <p>After downloading an image from the site i need to detect the color of the downloaded image.I successfully downloaded the image but i need to detect the color of the corresponding image and to be save it in the name of the corresponding color.Code used is given below.Tell me how can i achieve it from the current p... | 12 | 2010-02-16T05:31:48Z | 40,018,390 | <p>You could use K-means algorithm to get the K main colours of the image. Here is an example of how to do it: <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_ml/py_kmeans/py_kmeans_opencv/py_kmeans_opencv.html" rel="nofollow">K-means using OpenCV (Python)</a></p>
| 0 | 2016-10-13T10:25:07Z | [
"python"
] |
how to login to multiple website accounts concurrently with Python | 2,270,881 | <p>I am using urllib2 and <a href="http://docs.python.org/library/urllib2.html#httpcookieprocessor-objects" rel="nofollow">HTTPCookieProcessor</a> to login to a website. I want to login to multiple accounts concurrently and store the cookies to be reused later. </p>
<p>Can you recommend an approach or library to achie... | 0 | 2010-02-16T05:32:57Z | 2,271,256 | <p>How to achieve this really depends on you needs: what kind of login is it? Digest authentication? Is it a web form? Is JavaScript involved (you're pretty much screwed if this is the case)? A library like <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> can help you a lot with suc... | 1 | 2010-02-16T07:33:02Z | [
"python",
"cookies",
"concurrency",
"login",
"urllib2"
] |
how to login to multiple website accounts concurrently with Python | 2,270,881 | <p>I am using urllib2 and <a href="http://docs.python.org/library/urllib2.html#httpcookieprocessor-objects" rel="nofollow">HTTPCookieProcessor</a> to login to a website. I want to login to multiple accounts concurrently and store the cookies to be reused later. </p>
<p>Can you recommend an approach or library to achie... | 0 | 2010-02-16T05:32:57Z | 2,277,442 | <p>The OP clarified that this is not a concurrency issue. With sequential processing in mind, this is much simpler. I once used something like the following to update a bunch of SIP phone base stations (they had a web front-end which you could use to upload VCard files for the phone book). Note that I just cut away ... | 1 | 2010-02-17T00:21:43Z | [
"python",
"cookies",
"concurrency",
"login",
"urllib2"
] |
Encode East Asian languages using Python | 2,270,928 | <p>This may not really be a Python related question, but pertains to language encoding in general. I'm mining tweets from Twitter, and it appears that there is a large Japanese user community (with messages in Japanese). When I tried encoding the tweets for an XML file I used utf-8. e.g tweet=tweet.encode('utf-8') and ... | 1 | 2010-02-16T05:47:32Z | 2,270,935 | <p>Normally you would query the format for what encoding the data is in. Having said that, Shift-JIS is quite a popular encoding for Japanese text.</p>
<pre><code>>>> u'ããããã'.encode('shift-jis')
'\x82\xa0\x82\xa2\x82\xa4\x82\xa6\x82\xa8'
</code></pre>
| 3 | 2010-02-16T05:50:16Z | [
"python",
"xml",
"encoding",
"csv"
] |
Encode East Asian languages using Python | 2,270,928 | <p>This may not really be a Python related question, but pertains to language encoding in general. I'm mining tweets from Twitter, and it appears that there is a large Japanese user community (with messages in Japanese). When I tried encoding the tweets for an XML file I used utf-8. e.g tweet=tweet.encode('utf-8') and ... | 1 | 2010-02-16T05:47:32Z | 2,274,230 | <p>There should be a way to query the encoding of the tweets when read from Twitter. You then <em>decode</em> them to Unicode as you read them into your program, then <em>encode</em> them when you write them back out to an XML file. Chinese, for example, might be using <strong>gbk</strong> encoding:</p>
<pre><code>i... | 2 | 2010-02-16T16:04:34Z | [
"python",
"xml",
"encoding",
"csv"
] |
eagerly evaluating boolean expressions in Python | 2,271,017 | <p>Is there a way (using <code>eval</code> or whatever) to evaluate eagerly boolean expressions in python?</p>
<p>Let's see this:</p>
<pre><code>>>> x = 3
>>> 5 < x < y
False
</code></pre>
<p>Yikes! That's very nice, because this will be false regardless of <code>y</code>'s value. The thing i... | 3 | 2010-02-16T06:19:38Z | 2,271,021 | <pre><code>all([5 < x, x < y])
</code></pre>
| 5 | 2010-02-16T06:21:06Z | [
"python",
"exception-handling",
"lazy-evaluation",
"eager"
] |
eagerly evaluating boolean expressions in Python | 2,271,017 | <p>Is there a way (using <code>eval</code> or whatever) to evaluate eagerly boolean expressions in python?</p>
<p>Let's see this:</p>
<pre><code>>>> x = 3
>>> 5 < x < y
False
</code></pre>
<p>Yikes! That's very nice, because this will be false regardless of <code>y</code>'s value. The thing i... | 3 | 2010-02-16T06:19:38Z | 2,271,029 | <pre><code>(5 < x) & (x < y)
</code></pre>
<p>By using the bit-and operator, <code>&</code>, you get no short-circuiting behavior (as you get with <code>and</code>, <code>or</code>, chaining, <code>all</code>/<code>any</code>). Short-circuiting is normally deemed desirable (fast &c) but it's not har... | 6 | 2010-02-16T06:23:49Z | [
"python",
"exception-handling",
"lazy-evaluation",
"eager"
] |
eagerly evaluating boolean expressions in Python | 2,271,017 | <p>Is there a way (using <code>eval</code> or whatever) to evaluate eagerly boolean expressions in python?</p>
<p>Let's see this:</p>
<pre><code>>>> x = 3
>>> 5 < x < y
False
</code></pre>
<p>Yikes! That's very nice, because this will be false regardless of <code>y</code>'s value. The thing i... | 3 | 2010-02-16T06:19:38Z | 2,271,030 | <pre>
>>> x = 3
>>> y > x > 5
Traceback (most recent call last):
File "", line 1, in
NameError: name 'y' is not defined
</pre>
| 3 | 2010-02-16T06:23:59Z | [
"python",
"exception-handling",
"lazy-evaluation",
"eager"
] |
eagerly evaluating boolean expressions in Python | 2,271,017 | <p>Is there a way (using <code>eval</code> or whatever) to evaluate eagerly boolean expressions in python?</p>
<p>Let's see this:</p>
<pre><code>>>> x = 3
>>> 5 < x < y
False
</code></pre>
<p>Yikes! That's very nice, because this will be false regardless of <code>y</code>'s value. The thing i... | 3 | 2010-02-16T06:19:38Z | 2,271,056 | <p>The most natural way would probably be to evaluate the expressions on prior lines. </p>
<pre><code>a = foo()
b = bar()
if a and b:
...
</code></pre>
<p>as solutions like <code>all([5 < x, x < y])</code> hide that the side effects are important and solutions using bitwise and (<code>&</code>) seem sub... | 5 | 2010-02-16T06:33:34Z | [
"python",
"exception-handling",
"lazy-evaluation",
"eager"
] |
eagerly evaluating boolean expressions in Python | 2,271,017 | <p>Is there a way (using <code>eval</code> or whatever) to evaluate eagerly boolean expressions in python?</p>
<p>Let's see this:</p>
<pre><code>>>> x = 3
>>> 5 < x < y
False
</code></pre>
<p>Yikes! That's very nice, because this will be false regardless of <code>y</code>'s value. The thing i... | 3 | 2010-02-16T06:19:38Z | 2,271,099 | <p>If it's just the possibility of programmer-error you want to preclude, eagerly evaluating expressions won't do much. For instance, mistakenly doing <code>x or y()</code> instead of <code>x() or y()</code> won't be detected. Perhaps you're actually looking for tools like <a href="http://www.logilab.org/857" rel="nof... | 2 | 2010-02-16T06:51:44Z | [
"python",
"exception-handling",
"lazy-evaluation",
"eager"
] |
eagerly evaluating boolean expressions in Python | 2,271,017 | <p>Is there a way (using <code>eval</code> or whatever) to evaluate eagerly boolean expressions in python?</p>
<p>Let's see this:</p>
<pre><code>>>> x = 3
>>> 5 < x < y
False
</code></pre>
<p>Yikes! That's very nice, because this will be false regardless of <code>y</code>'s value. The thing i... | 3 | 2010-02-16T06:19:38Z | 2,275,011 | <p>If you are receiving the statement from the user and want to execute it with your own semantics, you should parse it yourself with a tool such as <code>pyparsing</code>. It is messy and insecure to evaluate someone else's code in the middle of yours, mixing their results with yours and it is confusing to evaluate w... | 1 | 2010-02-16T17:46:36Z | [
"python",
"exception-handling",
"lazy-evaluation",
"eager"
] |
django calendar free/busy/availabilitty | 2,271,190 | <p>I am trying to implement a calendar system with the ability to schedule other people for appointments. The system has to be able to prevent scheduling a person during another appointment or during their unavailable time.</p>
<p>I have looked at all the existing django calendar projects I have found on the internet ... | 7 | 2010-02-16T07:17:52Z | 2,271,279 | <p>What about using Django's <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#s-range">range test</a>.</p>
<p>For example:</p>
<pre><code>appoinment = Appointment()
appointment.start_time = datetime.datetime.now()
# 1 hour appointment
appointment.end_time = appointment.start_time + datetime.timedel... | 12 | 2010-02-16T07:36:58Z | [
"python",
"django",
"calendar"
] |
django calendar free/busy/availabilitty | 2,271,190 | <p>I am trying to implement a calendar system with the ability to schedule other people for appointments. The system has to be able to prevent scheduling a person during another appointment or during their unavailable time.</p>
<p>I have looked at all the existing django calendar projects I have found on the internet ... | 7 | 2010-02-16T07:17:52Z | 2,271,544 | <p>One caveat here is the different timezones of different users, and bring Daylight saving time into the mix things become very complicated.</p>
<p>You might want to take a look at <strong>pytz</strong> module for taking care of the timezone issue.</p>
| 0 | 2010-02-16T08:46:38Z | [
"python",
"django",
"calendar"
] |
Problem with replacing a word in a file, using Python | 2,271,199 | <p>I have a .txt file containing data like this:</p>
<pre><code>1,Rent1,Expense,16/02/2010,1,4000,4000
1,Car Loan1,Expense,16/02/2010,2,4500,9000
1,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Rent2,Expense,16/02/2010,1,4000,4000
0,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,400... | 1 | 2010-02-16T07:20:54Z | 2,271,219 | <p>Either use <code>rstrip</code> to remove the trailing new lines before printing or use <code>sys.stdout.write</code> instead of <code>print</code>.</p>
<p>Also, if you only need to modify the first element, there is no need to split the entire line and join it again. You only need to split on the first comma:</p>
... | 1 | 2010-02-16T07:23:57Z | [
"python",
"file",
"replace"
] |
Problem with replacing a word in a file, using Python | 2,271,199 | <p>I have a .txt file containing data like this:</p>
<pre><code>1,Rent1,Expense,16/02/2010,1,4000,4000
1,Car Loan1,Expense,16/02/2010,2,4500,9000
1,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Rent2,Expense,16/02/2010,1,4000,4000
0,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,400... | 1 | 2010-02-16T07:20:54Z | 2,271,221 | <p><code>print</code> adds an extra newline after the input and you already have one newline there. You should either strip the existing newline (<code>line.rstrip("\n")</code>) or use <code>sys.stdout.write()</code> instead.</p>
| 4 | 2010-02-16T07:24:37Z | [
"python",
"file",
"replace"
] |
Problem with replacing a word in a file, using Python | 2,271,199 | <p>I have a .txt file containing data like this:</p>
<pre><code>1,Rent1,Expense,16/02/2010,1,4000,4000
1,Car Loan1,Expense,16/02/2010,2,4500,9000
1,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Rent2,Expense,16/02/2010,1,4000,4000
0,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,400... | 1 | 2010-02-16T07:20:54Z | 2,271,229 | <pre><code>import fileinput
import re
p = re.compile(r'^0,')
for line in fileinput.FileInput("sample.txt",inplace=1):
print p.sub('1,', line.strip())
</code></pre>
<p>The existing code you have doesn't actually change the lines like you want; <code>print a</code> doesn't do anything if <code>a</code> isn't actuall... | 2 | 2010-02-16T07:26:37Z | [
"python",
"file",
"replace"
] |
Problem with replacing a word in a file, using Python | 2,271,199 | <p>I have a .txt file containing data like this:</p>
<pre><code>1,Rent1,Expense,16/02/2010,1,4000,4000
1,Car Loan1,Expense,16/02/2010,2,4500,9000
1,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Rent2,Expense,16/02/2010,1,4000,4000
0,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,400... | 1 | 2010-02-16T07:20:54Z | 2,271,232 | <pre><code>fixed = []
for l in file('sample.txt'):
parts = l.split(',',1)
if(parts[0] == '0'):
# not sure what you want to do here, but you want to "change this" number to 1?
parts[0] = 1
fixed.append(parts.join(','))
outp = file('sample.txt','w')
for f in fixed:
outp.write(f)
outp.close... | 0 | 2010-02-16T07:27:40Z | [
"python",
"file",
"replace"
] |
Problem with replacing a word in a file, using Python | 2,271,199 | <p>I have a .txt file containing data like this:</p>
<pre><code>1,Rent1,Expense,16/02/2010,1,4000,4000
1,Car Loan1,Expense,16/02/2010,2,4500,9000
1,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Rent2,Expense,16/02/2010,1,4000,4000
0,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,400... | 1 | 2010-02-16T07:20:54Z | 2,271,261 | <pre><code>import fileinput
for line in fileinput.FileInput("sample.txt",inplace=1):
s=line.rstrip().split(",")
print a
print ','.join(s)
</code></pre>
| 0 | 2010-02-16T07:33:56Z | [
"python",
"file",
"replace"
] |
Problem with replacing a word in a file, using Python | 2,271,199 | <p>I have a .txt file containing data like this:</p>
<pre><code>1,Rent1,Expense,16/02/2010,1,4000,4000
1,Car Loan1,Expense,16/02/2010,2,4500,9000
1,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Rent2,Expense,16/02/2010,1,4000,4000
0,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,400... | 1 | 2010-02-16T07:20:54Z | 2,271,293 | <p>You have to use a comma at the end of your <a href="http://www.rexx.com/~dkuhlman/python_101/python_101.html#SECTION004310000000000000000" rel="nofollow">print</a> so that it doesn't add a newline. Like so:</p>
<pre><code>print "Hello",
</code></pre>
<p>This is what I came up with:</p>
<pre><code>input = open('fi... | 0 | 2010-02-16T07:41:43Z | [
"python",
"file",
"replace"
] |
Problem with replacing a word in a file, using Python | 2,271,199 | <p>I have a .txt file containing data like this:</p>
<pre><code>1,Rent1,Expense,16/02/2010,1,4000,4000
1,Car Loan1,Expense,16/02/2010,2,4500,9000
1,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Rent2,Expense,16/02/2010,1,4000,4000
0,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,400... | 1 | 2010-02-16T07:20:54Z | 2,273,455 | <p>The cleanest way to do it is to use the CSV parser :</p>
<pre><code>import fileinput
import csv
f = fileinput.FileInput("test.txt",inplace=1)
fichiercsv = csv.reader(f, delimiter=',')
for line in fichiercsv:
line[0] = "1"
print ",".join(line)
</code></pre>
| 0 | 2010-02-16T14:13:05Z | [
"python",
"file",
"replace"
] |
How to access string value from new class that inherit string type | 2,271,216 | <p>I want to define a new class that inherit the build in str type, and create a method that duplicates the string contents.</p>
<p>How do I get access to the string value assigned to the object of my new class ?</p>
<pre><code> class str_usr(str):
def __new__(cls, arg):
return str.__new__(cls,... | 1 | 2010-02-16T07:23:36Z | 2,271,239 | <p>It doesn't look like you want to inherit from <code>str</code> at all (which is prettymuch never useful anyhow). Make a new class and have one of its attributes be a string you access, that is</p>
<pre><code>class MyString(object):
def __init__(self, string):
self.string = string
def dup(self):
... | 2 | 2010-02-16T07:29:32Z | [
"python",
"oop",
"class"
] |
How to access string value from new class that inherit string type | 2,271,216 | <p>I want to define a new class that inherit the build in str type, and create a method that duplicates the string contents.</p>
<p>How do I get access to the string value assigned to the object of my new class ?</p>
<pre><code> class str_usr(str):
def __new__(cls, arg):
return str.__new__(cls,... | 1 | 2010-02-16T07:23:36Z | 2,271,257 | <p>Strings in Python are immutable, so once you have one string, you can't change its value. It's almost the same as if you had a class derived from <code>int</code>, and then you added a method to change the value of the <code>int</code>.</p>
<p>You can of course return a new value:</p>
<pre><code>class str_usr(str... | 3 | 2010-02-16T07:33:19Z | [
"python",
"oop",
"class"
] |
How to access string value from new class that inherit string type | 2,271,216 | <p>I want to define a new class that inherit the build in str type, and create a method that duplicates the string contents.</p>
<p>How do I get access to the string value assigned to the object of my new class ?</p>
<pre><code> class str_usr(str):
def __new__(cls, arg):
return str.__new__(cls,... | 1 | 2010-02-16T07:23:36Z | 2,271,303 | <p>Note that in Python you could just use the multiplication operator on string:</p>
<pre><code>>>> s = "foo"
>>> s*2
'foofoo'
</code></pre>
| 0 | 2010-02-16T07:43:41Z | [
"python",
"oop",
"class"
] |
Is there any limitation in python when handling long file paths? | 2,271,437 | <p>I am writing a file copying utility in Python. But I am getting some error messages when processing files with very long file paths.</p>
<p>I suspect Python has some limitations when handling very long file paths.</p>
| 1 | 2010-02-16T08:22:25Z | 2,271,455 | <p>Many file systems don't support long filenames, so it's probably a limitation of the OS or your file system.</p>
<p>There are also OS-specific issues like API limitations (e.g. <a href="http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#maxpath" rel="nofollow">in the Windows API</a>).</p>
| 4 | 2010-02-16T08:28:17Z | [
"python"
] |
File deletion using rm command | 2,271,453 | <p>I want to make sure that I delete required files.
I have code something like</p>
<pre><code>dir="/some/path/"
file = "somefile.txt"
cmd_rm= "rm -rf "+dir + file
os.system(cmd_rm)
</code></pre>
<p>The <code>dir</code> and <code>file</code> values are fetched from a database. How can I make sure I never end up runni... | 7 | 2010-02-16T08:27:58Z | 2,271,469 | <p>You might consider using <a href="http://docs.python.org/library/os.html#files-and-directories"><code>os.remove()</code></a> instead since it's a great deal less dangerous than what you're attempting.</p>
| 15 | 2010-02-16T08:31:35Z | [
"python",
"file",
"delete-file"
] |
File deletion using rm command | 2,271,453 | <p>I want to make sure that I delete required files.
I have code something like</p>
<pre><code>dir="/some/path/"
file = "somefile.txt"
cmd_rm= "rm -rf "+dir + file
os.system(cmd_rm)
</code></pre>
<p>The <code>dir</code> and <code>file</code> values are fetched from a database. How can I make sure I never end up runni... | 7 | 2010-02-16T08:27:58Z | 2,271,496 | <p>First, I suggest you to use the <code>os.remove()</code> and <code>os.rmdir()</code> functions for working with things like that. You will end up with more portable code and less headache for checking command return.</p>
<p>To check what you are effectively attempting to remove (you may not want to just check "/"),... | 6 | 2010-02-16T08:37:15Z | [
"python",
"file",
"delete-file"
] |
File deletion using rm command | 2,271,453 | <p>I want to make sure that I delete required files.
I have code something like</p>
<pre><code>dir="/some/path/"
file = "somefile.txt"
cmd_rm= "rm -rf "+dir + file
os.system(cmd_rm)
</code></pre>
<p>The <code>dir</code> and <code>file</code> values are fetched from a database. How can I make sure I never end up runni... | 7 | 2010-02-16T08:27:58Z | 2,271,500 | <p>Don't use the <code>-r</code> switch if you just want to remove a single file. Also, there could be spaces in the file name.</p>
<p>Better use the functions in Python's <a href="http://docs.python.org/library/os.html"><code>os</code></a> module instead:</p>
<pre><code>dirname = "/some/path/"
filename = "somefile.t... | 21 | 2010-02-16T08:37:54Z | [
"python",
"file",
"delete-file"
] |
File deletion using rm command | 2,271,453 | <p>I want to make sure that I delete required files.
I have code something like</p>
<pre><code>dir="/some/path/"
file = "somefile.txt"
cmd_rm= "rm -rf "+dir + file
os.system(cmd_rm)
</code></pre>
<p>The <code>dir</code> and <code>file</code> values are fetched from a database. How can I make sure I never end up runni... | 7 | 2010-02-16T08:27:58Z | 2,271,516 | <p>There is a module called <code>shutil</code> that provides shell-like file manipulation. If you want to delete a directory and all files and directories in it then use <code>shutil.rmtree</code>.</p>
<p>However it is implemented in python so if you are deleting a huge number of files then spawning rm may be faster... | 2 | 2010-02-16T08:41:20Z | [
"python",
"file",
"delete-file"
] |
File deletion using rm command | 2,271,453 | <p>I want to make sure that I delete required files.
I have code something like</p>
<pre><code>dir="/some/path/"
file = "somefile.txt"
cmd_rm= "rm -rf "+dir + file
os.system(cmd_rm)
</code></pre>
<p>The <code>dir</code> and <code>file</code> values are fetched from a database. How can I make sure I never end up runni... | 7 | 2010-02-16T08:27:58Z | 2,271,617 | <p>Use <code>shutil.rmtree</code> as Dave Kirby says. If you want to delete the just the file use:</p>
<pre><code>dir = "/some/path/"
file = "somefile.txt"
cmd = os.path.join(dir, file)
shutil.rmtree(cmd)
</code></pre>
<p>If you want to delete the directory use:</p>
<pre><code>dir = "/some/path/"
file = "somefi... | 2 | 2010-02-16T09:03:36Z | [
"python",
"file",
"delete-file"
] |
File deletion using rm command | 2,271,453 | <p>I want to make sure that I delete required files.
I have code something like</p>
<pre><code>dir="/some/path/"
file = "somefile.txt"
cmd_rm= "rm -rf "+dir + file
os.system(cmd_rm)
</code></pre>
<p>The <code>dir</code> and <code>file</code> values are fetched from a database. How can I make sure I never end up runni... | 7 | 2010-02-16T08:27:58Z | 15,212,358 | <p>Assuming that your mentioning <em>rm -rf</em> is not just at random, but is exactly the command you need, why not just to call it? There is a lib allowing a greater integration with shell called <a href="https://github.com/amoffat/sh" rel="nofollow"><strong>sh</strong></a>.</p>
<pre><code>from sh import rm
path_to... | 0 | 2013-03-04T22:28:08Z | [
"python",
"file",
"delete-file"
] |
How to use numpy with cygwin | 2,271,565 | <p>I have a bash shell script which calls some python scripts. I am running windows with cygwin which has python in /usr/bin/python. I also have python and numpy installed as a windows package. When I execute the script from cygwin , I get an ImportError - no module named numpy. I have tried running from windows shell... | 1 | 2010-02-16T08:51:02Z | 2,271,593 | <p>The NumPy installed is for the Windows Python, not the cygwin Python. Install NumPy from source built against the cygwin Python, or install it from the cygwin setup if it exists there.</p>
| 0 | 2010-02-16T08:58:06Z | [
"python",
"cygwin",
"numpy"
] |
How to use numpy with cygwin | 2,271,565 | <p>I have a bash shell script which calls some python scripts. I am running windows with cygwin which has python in /usr/bin/python. I also have python and numpy installed as a windows package. When I execute the script from cygwin , I get an ImportError - no module named numpy. I have tried running from windows shell... | 1 | 2010-02-16T08:51:02Z | 2,271,606 | <p>Windows python and Cygwin Python are independent; if you're using Cygwin's Python, you need to have numpy installed in cygwin.</p>
<p>If you'd prefer to use the Windows python, you should be able to call it from a bash script by either:</p>
<ul>
<li>Calling the windows executable directly:<br> <code>c:/Python/pyth... | 2 | 2010-02-16T09:00:36Z | [
"python",
"cygwin",
"numpy"
] |
Psycopg2, Postgresql, Python: Fastest way to bulk-insert | 2,271,787 | <p>I'm looking for the most efficient way to bulk-insert some millions of tuples into a database. I'm using Python, PostgreSQL and <a href="http://www.devx.com/opensource/Article/29071">psycopg2</a>.</p>
<p>I have created a long list of tulpes that should be inserted to the database, sometimes with modifiers like geom... | 28 | 2010-02-16T09:36:50Z | 2,271,802 | <p>The first and the second would be used together, not separately. The third would be the most efficient server-wise though, since the server would do <em>all</em> the hard work.</p>
| 1 | 2010-02-16T09:39:15Z | [
"python",
"postgresql",
"psycopg2"
] |
Psycopg2, Postgresql, Python: Fastest way to bulk-insert | 2,271,787 | <p>I'm looking for the most efficient way to bulk-insert some millions of tuples into a database. I'm using Python, PostgreSQL and <a href="http://www.devx.com/opensource/Article/29071">psycopg2</a>.</p>
<p>I have created a long list of tulpes that should be inserted to the database, sometimes with modifiers like geom... | 28 | 2010-02-16T09:36:50Z | 2,271,806 | <p>Yeah, I would vote for COPY, providing you can write a file to the <em>server</em>'s hard drive (not the drive the app is running on) as COPY will only read off the server.</p>
| 12 | 2010-02-16T09:41:02Z | [
"python",
"postgresql",
"psycopg2"
] |
Psycopg2, Postgresql, Python: Fastest way to bulk-insert | 2,271,787 | <p>I'm looking for the most efficient way to bulk-insert some millions of tuples into a database. I'm using Python, PostgreSQL and <a href="http://www.devx.com/opensource/Article/29071">psycopg2</a>.</p>
<p>I have created a long list of tulpes that should be inserted to the database, sometimes with modifiers like geom... | 28 | 2010-02-16T09:36:50Z | 2,272,062 | <p>There is a new <a href="http://initd.org/psycopg/docs/">psycopg2 manual</a> containing examples for all the options.</p>
<p>The <a href="http://initd.org/psycopg/docs/usage.html#using-copy-to-and-copy-from">COPY</a> option is the most efficient. Then the executemany. Then the execute with pyformat.</p>
| 8 | 2010-02-16T10:18:57Z | [
"python",
"postgresql",
"psycopg2"
] |
Psycopg2, Postgresql, Python: Fastest way to bulk-insert | 2,271,787 | <p>I'm looking for the most efficient way to bulk-insert some millions of tuples into a database. I'm using Python, PostgreSQL and <a href="http://www.devx.com/opensource/Article/29071">psycopg2</a>.</p>
<p>I have created a long list of tulpes that should be inserted to the database, sometimes with modifiers like geom... | 28 | 2010-02-16T09:36:50Z | 12,612,802 | <p>You could use <a href="https://github.com/seamusabshere/py-upsert">a new upsert library</a>:</p>
<pre><code>$ pip install upsert
</code></pre>
<p>(you may have to <code>pip install decorator</code> first)</p>
<pre class="lang-py prettyprint-override"><code>conn = psycopg2.connect('dbname=mydatabase')
cur = conn.c... | 5 | 2012-09-27T01:27:02Z | [
"python",
"postgresql",
"psycopg2"
] |
Psycopg2, Postgresql, Python: Fastest way to bulk-insert | 2,271,787 | <p>I'm looking for the most efficient way to bulk-insert some millions of tuples into a database. I'm using Python, PostgreSQL and <a href="http://www.devx.com/opensource/Article/29071">psycopg2</a>.</p>
<p>I have created a long list of tulpes that should be inserted to the database, sometimes with modifiers like geom... | 28 | 2010-02-16T09:36:50Z | 21,510,454 | <p>in my experience <code>executemany</code> is not any faster than running many inserts yourself,
the fastest way is to format a single <code>INSERT</code> with many values yourself, maybe in the future <code>executemany</code> will improve but for now it is quite slow</p>
<p>i subclass a <code>list</code> and overlo... | 3 | 2014-02-02T12:14:24Z | [
"python",
"postgresql",
"psycopg2"
] |
Psycopg2, Postgresql, Python: Fastest way to bulk-insert | 2,271,787 | <p>I'm looking for the most efficient way to bulk-insert some millions of tuples into a database. I'm using Python, PostgreSQL and <a href="http://www.devx.com/opensource/Article/29071">psycopg2</a>.</p>
<p>I have created a long list of tulpes that should be inserted to the database, sometimes with modifiers like geom... | 28 | 2010-02-16T09:36:50Z | 34,544,028 | <p>After some testing, <a href="http://www.postgresql.org/docs/current/static/functions-array.html#ARRAY-FUNCTIONS-TABLE" rel="nofollow">unnest</a> often seems to be an extremely fast option, as I learned from <em>@Clodoaldo Neto</em>'s <a href="http://stackoverflow.com/a/33258295/2075003">answer</a> to a similar ques... | 0 | 2015-12-31T09:18:01Z | [
"python",
"postgresql",
"psycopg2"
] |
Why are these lists the same? | 2,272,119 | <p>I can't understand how x and y are the same list. I've been trying to debug it using print statements and <code>import code; code.interact(local=locals())</code> to drop into various points, but I can't figure out what on earth is going on :-(</p>
<pre><code>from collections import namedtuple, OrderedDict
coordina... | 1 | 2010-02-16T10:30:34Z | 2,272,189 | <p>I think the following line should look like this (but unfortunately I can't test because I don't have Python 3 available):</p>
<pre><code># Then functions to access them
d = dict((key, lambda self: self.__vals__[key]) for key in objects_type)
</code></pre>
| 0 | 2010-02-16T10:39:58Z | [
"python"
] |
Why are these lists the same? | 2,272,119 | <p>I can't understand how x and y are the same list. I've been trying to debug it using print statements and <code>import code; code.interact(local=locals())</code> to drop into various points, but I can't figure out what on earth is going on :-(</p>
<pre><code>from collections import namedtuple, OrderedDict
coordina... | 1 | 2010-02-16T10:30:34Z | 2,272,198 | <p>The problem is with this line:</p>
<pre><code>d={key: lambda self: self.__vals__[key] for key in objects_type}
</code></pre>
<p>The lambda uses the value of the variable <code>key</code>, but that value has changed by the time the lambda is called - so all lambdas will actually use the same value for the key.</p>
... | 7 | 2010-02-16T10:41:12Z | [
"python"
] |
Round to 5 (or other number) in python | 2,272,149 | <p>Is there a built-in function that can round like this:</p>
<pre><code>10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
</code></pre>
| 75 | 2010-02-16T10:35:04Z | 2,272,174 | <p>I don't know of a standard function in Python, but this works for me:</p>
<pre><code>def myround(x, base=5):
return int(base * round(float(x)/base))
</code></pre>
<p>It is easy to see why the above works. You want to make sure that your number divided by 5 is an integer, correctly rounded. So, we first do ex... | 141 | 2010-02-16T10:38:22Z | [
"python",
"rounding"
] |
Round to 5 (or other number) in python | 2,272,149 | <p>Is there a built-in function that can round like this:</p>
<pre><code>10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
</code></pre>
| 75 | 2010-02-16T10:35:04Z | 2,272,219 | <p>It's just a matter of scaling </p>
<pre><code>>>> a=[10,11,12,13,14,15,16,17,18,19,20]
>>> for b in a:
... int(round(b/5.0)*5.0)
...
10
10
10
15
15
15
15
15
20
20
20
</code></pre>
| 14 | 2010-02-16T10:44:38Z | [
"python",
"rounding"
] |
Round to 5 (or other number) in python | 2,272,149 | <p>Is there a built-in function that can round like this:</p>
<pre><code>10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
</code></pre>
| 75 | 2010-02-16T10:35:04Z | 2,272,849 | <p>round(x[, n]): values are rounded to the closest multiple of 10 to the power minus n. So if n is negative...</p>
<pre><code>def round5(x):
return int(round(x*2, -1)) / 2
</code></pre>
<p>Since 10 = 5 * 2, you can use integer division and multiplication with 2, rather than float division and multiplication with... | 4 | 2010-02-16T12:35:23Z | [
"python",
"rounding"
] |
Round to 5 (or other number) in python | 2,272,149 | <p>Is there a built-in function that can round like this:</p>
<pre><code>10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
</code></pre>
| 75 | 2010-02-16T10:35:04Z | 2,273,011 | <p>What about this:</p>
<pre><code> def divround(value, step):
return divmod(value, step)[0] * step
</code></pre>
| 0 | 2010-02-16T13:04:01Z | [
"python",
"rounding"
] |
Round to 5 (or other number) in python | 2,272,149 | <p>Is there a built-in function that can round like this:</p>
<pre><code>10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
</code></pre>
| 75 | 2010-02-16T10:35:04Z | 2,273,059 | <p>Modified version of divround :-)</p>
<pre><code>def divround(value, step, barrage):
result, rest = divmod(value, step)
return result*step if rest < barrage else (result+1)*step
</code></pre>
| 3 | 2010-02-16T13:11:17Z | [
"python",
"rounding"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.