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 |
|---|---|---|---|---|---|---|---|---|---|
Timeout for xmlrpclib client requests | 2,425,799 | <p>I am using Python's xmlrpclib to make requests to an xml-rpc service.</p>
<p>Is there a way to set a client timeout, so my requests don't hang forever when the server is not available?</p>
<p>I know I can globally set a socket timeout with <code>socket.setdefaulttimeout()</code>, but that is not preferable.</p>
| 3 | 2010-03-11T14:40:35Z | 6,014,897 | <p>doh, to make this work in python2.6+ do this:</p>
<pre><code>class HTTP_with_timeout(httplib.HTTP):
def __init__(self, host='', port=None, strict=None, timeout=5.0):
if port == 0: port = None
self._setup(self._connection_class(host, port, strict, timeout=timeout))
def getresponse(self, *arg... | 8 | 2011-05-16T08:42:05Z | [
"python",
"xmlrpclib"
] |
Timeout for xmlrpclib client requests | 2,425,799 | <p>I am using Python's xmlrpclib to make requests to an xml-rpc service.</p>
<p>Is there a way to set a client timeout, so my requests don't hang forever when the server is not available?</p>
<p>I know I can globally set a socket timeout with <code>socket.setdefaulttimeout()</code>, but that is not preferable.</p>
| 3 | 2010-03-11T14:40:35Z | 6,509,975 | <p>Why not:</p>
<pre><code>class TimeoutTransport(xmlrpclib.Transport):
def setTimeout(self, timeout):
self._timeout = timeout
def make_connection(self, host):
return httplib.HTTPConnection(host, timeout=self._timeout)
</code></pre>
<p>?</p>
<p>After all, <code>HTTP</code> and <code>HTTPS</code> seem to be... | 3 | 2011-06-28T16:40:19Z | [
"python",
"xmlrpclib"
] |
Timeout for xmlrpclib client requests | 2,425,799 | <p>I am using Python's xmlrpclib to make requests to an xml-rpc service.</p>
<p>Is there a way to set a client timeout, so my requests don't hang forever when the server is not available?</p>
<p>I know I can globally set a socket timeout with <code>socket.setdefaulttimeout()</code>, but that is not preferable.</p>
| 3 | 2010-03-11T14:40:35Z | 16,971,426 | <p>An alternative implementation that would be compatible with python 2.7 would be as follows (with a comment containing what you would want if you're using python 2.6):</p>
<pre><code>import socket
import xmlrpclib
class TimeoutTransport (xmlrpclib.Transport):
"""
Custom XML-RPC transport class for HTTP conn... | 3 | 2013-06-06T20:19:49Z | [
"python",
"xmlrpclib"
] |
Requesting a JavaScript property in Python (GAE) | 2,426,232 | <p>I'm currently making an iphone web app based on Google App Engine (python). I need to check if the user is browsing not trough safari but by the home screen. I can check this with an read-only 'window.navigator.standalone' Boolean JavaScript property as read on :http://developer.apple.com/safari/library/documentatio... | 0 | 2010-03-11T15:31:34Z | 2,426,429 | <p>According to <a href="http://kosmaczewski.net/2009/10/30/http-headers-web-apps-and-mobile-safari/" rel="nofollow">this page on HTTP headers and MobileSafari</a>, you can tell if the user has launched your site from their home screen by testing to see whether the string <code>Safari</code> is found in the <code>HTTP_... | 2 | 2010-03-11T15:52:40Z | [
"javascript",
"python",
"google-app-engine",
"iphone"
] |
Compare DB row values efficiently | 2,426,246 | <p>I want to loop through a database of documents and calculate a pairwise comparison score. </p>
<p>A simplistic, naive method would nest a loop within another loop. This would result in the program comparing documents twice and also comparing each document to itself.</p>
<p>Is there a name for the algorithm for doi... | 3 | 2010-03-11T15:32:54Z | 2,426,284 | <p>You can keep track of which documents you have already compared, e.g. (with numbers ;))</p>
<pre><code>compared = set()
for i in [1,2,3]:
for j in [1,2,3]:
pair = frozenset((i,j))
if i != k and pair not in compared:
compare.add(pair)
compare(i,j)
</code></pre>
<p>Anoth... | 0 | 2010-03-11T15:37:19Z | [
"python",
"mysql",
"database",
"logic"
] |
Compare DB row values efficiently | 2,426,246 | <p>I want to loop through a database of documents and calculate a pairwise comparison score. </p>
<p>A simplistic, naive method would nest a loop within another loop. This would result in the program comparing documents twice and also comparing each document to itself.</p>
<p>Is there a name for the algorithm for doi... | 3 | 2010-03-11T15:32:54Z | 2,426,328 | <p>I don't think its complicated enough to qualify for a name.</p>
<p>You can avoid duplicate pairs just by forcing a comparison on any value which might be different between different rows - the primary key is an obvious choice, e.g.</p>
<p>Unique pairings:</p>
<pre><code>SELECT a.item as a_item, b.item as b_item
F... | 2 | 2010-03-11T15:41:03Z | [
"python",
"mysql",
"database",
"logic"
] |
Compare DB row values efficiently | 2,426,246 | <p>I want to loop through a database of documents and calculate a pairwise comparison score. </p>
<p>A simplistic, naive method would nest a loop within another loop. This would result in the program comparing documents twice and also comparing each document to itself.</p>
<p>Is there a name for the algorithm for doi... | 3 | 2010-03-11T15:32:54Z | 2,426,358 | <p>Assume all items have a number ItemNumber</p>
<p>Simple solution -- always have the 2nd element's ItemNumber greater than the first item.</p>
<p>eg</p>
<pre><code>for (firstitem = 1 to maxitemnumber)
for (seconditem = firstitemnumber+1 to maxitemnumber)
compare(firstitem, seconditem)
</code></pre>
<p>visua... | 3 | 2010-03-11T15:44:27Z | [
"python",
"mysql",
"database",
"logic"
] |
Compare DB row values efficiently | 2,426,246 | <p>I want to loop through a database of documents and calculate a pairwise comparison score. </p>
<p>A simplistic, naive method would nest a loop within another loop. This would result in the program comparing documents twice and also comparing each document to itself.</p>
<p>Is there a name for the algorithm for doi... | 3 | 2010-03-11T15:32:54Z | 2,427,237 | <p>Something like this?</p>
<pre><code>src = [1,2,3]
for i, x in enumerate(src):
for y in src[i:]:
compare(x, y)
</code></pre>
<p>Or you might wish to generate a list of pairs instead:</p>
<pre><code>pairs = [(x, y) for i, x in enumerate(src) for y in src[i:]]
</code></pre>
| 0 | 2010-03-11T17:32:47Z | [
"python",
"mysql",
"database",
"logic"
] |
Install TurboGears on windows xp | 2,426,262 | <p>I've been trying to get TurboGears installed on Windows by following <a href="http://www.stuartellis.eu/articles/python-development-windows/" rel="nofollow">this</a> site.
I've installed virtualenv but when I execute the command "virtualenv --no-site-packages testproj", I get the following message:</p>
<pre>
New py... | 0 | 2010-03-11T15:34:13Z | 2,439,485 | <p>I figured out the error. Apparently, virtualenv does not like it if folder names have spaces (eg Documents and Settings). It worked fine when my folder names had no spaces.</p>
| 1 | 2010-03-13T18:30:08Z | [
"python",
"windows-xp",
"turbogears"
] |
Python server pages, tables and lists | 2,426,401 | <p>I am using MySQL and python server pages to show the data in a database. In the db I have selected this data: a list <code>x =[1, 61, 121, 181, 241, 301]</code> and a list of lists <code>z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l'])</code> and I would like to put these in a table to look like:</p... | 0 | 2010-03-11T15:50:30Z | 2,426,464 | <pre><code>for index, (a, b) in zip(x, z):
print(index, a, b) # format as appropriate
</code></pre>
<p>Also, your creation of <code>z</code> list might be improved upon:</p>
<pre><code>z = [dic[row[1]] for row in rows] # calling variable dict shadows built-in
</code></pre>
<p><code>x</code> can e... | 1 | 2010-03-11T15:55:16Z | [
"python",
"table",
"python-server-pages"
] |
Python server pages, tables and lists | 2,426,401 | <p>I am using MySQL and python server pages to show the data in a database. In the db I have selected this data: a list <code>x =[1, 61, 121, 181, 241, 301]</code> and a list of lists <code>z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l'])</code> and I would like to put these in a table to look like:</p... | 0 | 2010-03-11T15:50:30Z | 2,426,477 | <p>You're doing the "step by 60" twice on <code>x</code> -- you're building <code>x</code> to have exactly the list you see, already stepped by 60 at a time, and then getting its first 60 items (it doesn't have that many, so you're getting <em>all</em> items in fact) with the <code>str(x[i:i+60])</code> in the second l... | 1 | 2010-03-11T15:56:21Z | [
"python",
"table",
"python-server-pages"
] |
Python server pages, tables and lists | 2,426,401 | <p>I am using MySQL and python server pages to show the data in a database. In the db I have selected this data: a list <code>x =[1, 61, 121, 181, 241, 301]</code> and a list of lists <code>z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l'])</code> and I would like to put these in a table to look like:</p... | 0 | 2010-03-11T15:50:30Z | 2,426,544 | <pre><code>#Following code will work in Python 3.x
x =[1, 61, 121, 181, 241, 301]
z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l'])
for i in zip(x, z):
print("{0:03} {1} {2}".format(i[0], i[1][0], i[1][1]))
</code></pre>
| 0 | 2010-03-11T16:04:22Z | [
"python",
"table",
"python-server-pages"
] |
Python server pages, tables and lists | 2,426,401 | <p>I am using MySQL and python server pages to show the data in a database. In the db I have selected this data: a list <code>x =[1, 61, 121, 181, 241, 301]</code> and a list of lists <code>z = (['a','b'],['c','d'],['e','f'],['g','h'],['i','j'],['k','l'])</code> and I would like to put these in a table to look like:</p... | 0 | 2010-03-11T15:50:30Z | 2,426,548 | <ol>
<li><p>Try to use iterators instead of arrays + indekses. Foe example use <code>xrange</code> instead of <code>range</code> etc. It might be beneficial (I don't know MySQL capabilities) to use 2 cursors instead of caching everything in table.</p></li>
<li><p>There is <code>zip</code> function which takes two itera... | 0 | 2010-03-11T16:04:52Z | [
"python",
"table",
"python-server-pages"
] |
Dynamic mass hosting using mod_wsgi | 2,426,637 | <p>I am trying to configure an apache server using mod_wsgi for dynamic mass hosting. Each user will have it's own instance of a python application located in /mnt/data/www/domains/[user_name] and there will be a vhost.map telling me which domain maps to each user's directory (the directory will have the same name as t... | 0 | 2010-03-11T16:17:39Z | 2,444,761 | <p>Discussion thread about this at:</p>
<p><a href="http://groups.google.com/group/modwsgi/browse_frm/thread/2a9905f24c10a967" rel="nofollow">http://groups.google.com/group/modwsgi/browse_frm/thread/2a9905f24c10a967</a></p>
| 1 | 2010-03-15T02:31:47Z | [
"python",
"django",
"apache2",
"mod-wsgi"
] |
How to create instances of a class from a static method? | 2,426,690 | <p>Here is my problem. I have created a pretty heavy readonly class making many database calls with a static "factory" method. The goal of this method is to avoid killing the database by looking in a pool of already-created objects if an identical instance of the same object (same type, same init parameters) already ex... | 0 | 2010-03-11T16:24:05Z | 2,426,745 | <p>One usual approach is this.</p>
<pre><code>class SomeClass( object ):
# Something that is precious and needs to be pooled.
class SomeClassPool( object ):
def __init__( self ):
self.pool= [ SomeClass() ]
def getInstance( self ):
if len(self.pool) == 0:
self.pool.append( SomeC... | 1 | 2010-03-11T16:29:00Z | [
"python"
] |
How to create instances of a class from a static method? | 2,426,690 | <p>Here is my problem. I have created a pretty heavy readonly class making many database calls with a static "factory" method. The goal of this method is to avoid killing the database by looking in a pool of already-created objects if an identical instance of the same object (same type, same init parameters) already ex... | 0 | 2010-03-11T16:24:05Z | 2,426,973 | <pre><code>import weakref
class A(object):
_get_obj_cache = weakref.WeakValueDictionary()
@classmethod
def get_obj(cls, identifier):
cache = cls._get_obj_cache
obj = cache.get((cls, identifier))
if obj is None:
obj = cache[(cls, identifier)] = cls(identifier)
return obj
class B(A):
pass
... | 4 | 2010-03-11T16:56:43Z | [
"python"
] |
How to create instances of a class from a static method? | 2,426,690 | <p>Here is my problem. I have created a pretty heavy readonly class making many database calls with a static "factory" method. The goal of this method is to avoid killing the database by looking in a pool of already-created objects if an identical instance of the same object (same type, same init parameters) already ex... | 0 | 2010-03-11T16:24:05Z | 2,428,492 | <p>Expanding on S.Lott's comment:</p>
<blockquote>
<p>"I want to return the correct instance
each time, without removing it from
the pool". You mean you want a
dictionary of objects? -S.Lott</p>
</blockquote>
<pre><code>the_cache = {}
def get_obj(cls, identifier):
key = (cls, identifier)
if key not i... | 0 | 2010-03-11T20:36:51Z | [
"python"
] |
Python: For loop problem | 2,426,719 | <p>I have a simple for loop problem, when i run the code below it prints out series of 'blue green' sequences then a series of 'green' sequences. I want the output to be; if row[4] is equal to 1 to print blue else print green. </p>
<pre><code> for row in rows:
for i in `row[4]`:
if i ==`1`:
... | 0 | 2010-03-11T16:26:50Z | 2,426,732 | <p>Try something like this:</p>
<pre><code>for i in xrange(len(rows)):
if rows[i] == '1':
print "blue"
else:
print "green"
</code></pre>
<p>Or, since you don't actually seem to care about the index, you can of course do it more cleanly:</p>
<pre><code>for r in rows:
if r == "1":
print "blue"
else... | 3 | 2010-03-11T16:28:06Z | [
"python",
"loops",
"for-loop"
] |
Python: For loop problem | 2,426,719 | <p>I have a simple for loop problem, when i run the code below it prints out series of 'blue green' sequences then a series of 'green' sequences. I want the output to be; if row[4] is equal to 1 to print blue else print green. </p>
<pre><code> for row in rows:
for i in `row[4]`:
if i ==`1`:
... | 0 | 2010-03-11T16:26:50Z | 2,426,754 | <pre><code>if rows[4] == 1:
print 'blue'
else:
print 'green'
</code></pre>
| 1 | 2010-03-11T16:30:16Z | [
"python",
"loops",
"for-loop"
] |
Python: For loop problem | 2,426,719 | <p>I have a simple for loop problem, when i run the code below it prints out series of 'blue green' sequences then a series of 'green' sequences. I want the output to be; if row[4] is equal to 1 to print blue else print green. </p>
<pre><code> for row in rows:
for i in `row[4]`:
if i ==`1`:
... | 0 | 2010-03-11T16:26:50Z | 2,426,769 | <p>the <code>enumerate()</code> function will iterate and give you the index as well as the value:</p>
<pre><code>for i, v in enumerate(rows):
if i == 4:
print "blue"
else:
print "green"
</code></pre>
<p>if you want to print blue on every fourth line else green do this:</p>
<pre><code>for i, ... | 2 | 2010-03-11T16:31:42Z | [
"python",
"loops",
"for-loop"
] |
How to join list of strings? | 2,426,988 | <p>This is probably seriously easy to solve for most of you but I cannot solve this simply putting <code>str()</code> around it can I?</p>
<p>I would like to convert this list: <code>['A','B','C']</code> into <code>'A B C'</code>.</p>
<p>Thanks in advance!!</p>
| 5 | 2010-03-11T16:58:48Z | 2,427,007 | <pre><code>In [1]: L = ['A', 'B', 'C']
In [2]: " ".join(L)
Out[2]: 'A B C'
</code></pre>
| 13 | 2010-03-11T17:01:03Z | [
"python",
"string"
] |
How to join list of strings? | 2,426,988 | <p>This is probably seriously easy to solve for most of you but I cannot solve this simply putting <code>str()</code> around it can I?</p>
<p>I would like to convert this list: <code>['A','B','C']</code> into <code>'A B C'</code>.</p>
<p>Thanks in advance!!</p>
| 5 | 2010-03-11T16:58:48Z | 10,956,433 | <p>I do not like Python's syntax for joining a list of items, so I prefer to call my own function to perform that task, rather than using Python's syntax in line.</p>
<p>Here is my function:</p>
<pre><code>def joinList(l, c):
return c.join(l)
myList = ['a', 'b', 'c']
myStrg = joinList(myList, "-")
print myStrg... | 0 | 2012-06-08T21:50:08Z | [
"python",
"string"
] |
How to do Python's zip in C#? | 2,427,015 | <p>Python's <code>zip</code> function does the following:</p>
<pre><code>a = [1, 2, 3]
b = [6, 7, 8]
zipped = zip(a, b)
</code></pre>
<p>result</p>
<pre><code>[[1, 6], [2, 7], [3, 8]]
</code></pre>
| 10 | 2010-03-11T17:02:04Z | 2,427,054 | <p>Solution 1:</p>
<pre><code>IEnumerable<KeyValuePair<T1, T2>> Zip<T1, T2>(
IEnumerable<T1> a, IEnumerable<T2> b)
{
var enumeratorA = a.GetEnumerator();
var enumeratorB = b.GetEnumerator();
while (enumeratorA.MoveNext())
{
enumeratorB.MoveNext();
yield... | 2 | 2010-03-11T17:06:09Z | [
"c#",
".net",
"python",
"linq",
"zip"
] |
How to do Python's zip in C#? | 2,427,015 | <p>Python's <code>zip</code> function does the following:</p>
<pre><code>a = [1, 2, 3]
b = [6, 7, 8]
zipped = zip(a, b)
</code></pre>
<p>result</p>
<pre><code>[[1, 6], [2, 7], [3, 8]]
</code></pre>
| 10 | 2010-03-11T17:02:04Z | 2,427,055 | <p>How about <a href="http://bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx">this</a>?</p>
<p>C# 4.0 LINQ'S NEW ZIP OPERATOR </p>
<pre><code>public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
this IEnumerable<TFirs... | 7 | 2010-03-11T17:06:16Z | [
"c#",
".net",
"python",
"linq",
"zip"
] |
How to do Python's zip in C#? | 2,427,015 | <p>Python's <code>zip</code> function does the following:</p>
<pre><code>a = [1, 2, 3]
b = [6, 7, 8]
zipped = zip(a, b)
</code></pre>
<p>result</p>
<pre><code>[[1, 6], [2, 7], [3, 8]]
</code></pre>
| 10 | 2010-03-11T17:02:04Z | 2,427,087 | <p>Solution 2: Similar to C# 4.0 Zip, but you can use it in C# 3.0</p>
<pre><code> public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> func)
{
u... | 5 | 2010-03-11T17:10:40Z | [
"c#",
".net",
"python",
"linq",
"zip"
] |
How to do Python's zip in C#? | 2,427,015 | <p>Python's <code>zip</code> function does the following:</p>
<pre><code>a = [1, 2, 3]
b = [6, 7, 8]
zipped = zip(a, b)
</code></pre>
<p>result</p>
<pre><code>[[1, 6], [2, 7], [3, 8]]
</code></pre>
| 10 | 2010-03-11T17:02:04Z | 2,427,098 | <p>Also take a look at <a href="http://gitorious.org/cadenza" rel="nofollow">Cadenza</a> which has all sorts of nifty utility methods. </p>
<p>Specifically look at the Zip extension methods here:
<a href="http://gitorious.org/cadenza/cadenza/blobs/master/src/Cadenza/Cadenza.Collections/Enumerable.cs#line1303" rel="nof... | 1 | 2010-03-11T17:12:17Z | [
"c#",
".net",
"python",
"linq",
"zip"
] |
How to do Python's zip in C#? | 2,427,015 | <p>Python's <code>zip</code> function does the following:</p>
<pre><code>a = [1, 2, 3]
b = [6, 7, 8]
zipped = zip(a, b)
</code></pre>
<p>result</p>
<pre><code>[[1, 6], [2, 7], [3, 8]]
</code></pre>
| 10 | 2010-03-11T17:02:04Z | 24,768,812 | <p>I just have come across the same problem. .NET library does not offer the solution, so I made it by myself. Here is my solution.</p>
<p>The <code>Pivot</code> method is made as extension to <code>IEnumerable<IEnumerable<T>></code>.
It requires all the sequences' elements to be of the same type <code>T<... | 0 | 2014-07-15T21:51:11Z | [
"c#",
".net",
"python",
"linq",
"zip"
] |
easy hex/float conversion | 2,427,034 | <p>I am doing some input/output between a c++ and a python program (only floating point values) python has a nice feature of converting floating point values to hex-numbers and back as you can see in this link:</p>
<p><a href="http://docs.python.org/library/stdtypes.html#additional-methods-on-float" rel="nofollow">htt... | 2 | 2010-03-11T17:03:58Z | 2,427,079 | <p>The docs there say that <code>%a</code> does this in C. </p>
| 1 | 2010-03-11T17:09:45Z | [
"c++",
"python",
"formatting",
"floating-point",
"hex"
] |
easy hex/float conversion | 2,427,034 | <p>I am doing some input/output between a c++ and a python program (only floating point values) python has a nice feature of converting floating point values to hex-numbers and back as you can see in this link:</p>
<p><a href="http://docs.python.org/library/stdtypes.html#additional-methods-on-float" rel="nofollow">htt... | 2 | 2010-03-11T17:03:58Z | 2,427,081 | <p>You're sorely mistaken if you believe that this will solve all your problems. The hex notation is exactly equivalent to the original float. It just uses a different representation.</p>
| 1 | 2010-03-11T17:09:52Z | [
"c++",
"python",
"formatting",
"floating-point",
"hex"
] |
easy hex/float conversion | 2,427,034 | <p>I am doing some input/output between a c++ and a python program (only floating point values) python has a nice feature of converting floating point values to hex-numbers and back as you can see in this link:</p>
<p><a href="http://docs.python.org/library/stdtypes.html#additional-methods-on-float" rel="nofollow">htt... | 2 | 2010-03-11T17:03:58Z | 2,427,092 | <p>C++ does not have any library routines for converting hex to floating point. One reason is that the internal representation of floating point is not standardized (although many compilers do use an IEEE standard). </p>
<p>I recommend storing in ASCII format, which is portable across platforms. You could write you... | 1 | 2010-03-11T17:11:13Z | [
"c++",
"python",
"formatting",
"floating-point",
"hex"
] |
easy hex/float conversion | 2,427,034 | <p>I am doing some input/output between a c++ and a python program (only floating point values) python has a nice feature of converting floating point values to hex-numbers and back as you can see in this link:</p>
<p><a href="http://docs.python.org/library/stdtypes.html#additional-methods-on-float" rel="nofollow">htt... | 2 | 2010-03-11T17:03:58Z | 2,427,844 | <p>Can you send raw binary data between the two instead of strings? The <a href="http://docs.python.org/library/struct.html" rel="nofollow">struct</a> package of Python's standard library can unpack the raw data into a Python float object.</p>
| 2 | 2010-03-11T19:01:44Z | [
"c++",
"python",
"formatting",
"floating-point",
"hex"
] |
easy hex/float conversion | 2,427,034 | <p>I am doing some input/output between a c++ and a python program (only floating point values) python has a nice feature of converting floating point values to hex-numbers and back as you can see in this link:</p>
<p><a href="http://docs.python.org/library/stdtypes.html#additional-methods-on-float" rel="nofollow">htt... | 2 | 2010-03-11T17:03:58Z | 2,427,871 | <p>From the link you provided in your question (<a href="http://docs.python.org/library/stdtypes.html#additional-methods-on-float">Additional Methods on Float</a>):</p>
<blockquote>
<p>This syntax is similar to the syntax
specified in section 6.4.4.2 of the
C99 standard, and also to the syntax
used in Java 1.5... | 5 | 2010-03-11T19:06:39Z | [
"c++",
"python",
"formatting",
"floating-point",
"hex"
] |
easy hex/float conversion | 2,427,034 | <p>I am doing some input/output between a c++ and a python program (only floating point values) python has a nice feature of converting floating point values to hex-numbers and back as you can see in this link:</p>
<p><a href="http://docs.python.org/library/stdtypes.html#additional-methods-on-float" rel="nofollow">htt... | 2 | 2010-03-11T17:03:58Z | 2,428,030 | <p>If you're on a platform whose system C library supports C99, you can just use <code>printf( )</code> and <code>scanf( )</code> with the <code>%a</code> format specifier. For reading in such values, you can also use the C99 <code>strtod( )</code>, <code>strtof( )</code>, and <code>strtold( )</code> functions:</p>
<... | 1 | 2010-03-11T19:32:04Z | [
"c++",
"python",
"formatting",
"floating-point",
"hex"
] |
easy hex/float conversion | 2,427,034 | <p>I am doing some input/output between a c++ and a python program (only floating point values) python has a nice feature of converting floating point values to hex-numbers and back as you can see in this link:</p>
<p><a href="http://docs.python.org/library/stdtypes.html#additional-methods-on-float" rel="nofollow">htt... | 2 | 2010-03-11T17:03:58Z | 19,894,670 | <p>C++11 offers std::hexfloat: <a href="http://en.cppreference.com/w/cpp/io/manip/fixed" rel="nofollow">IO manipulators including hexfloat</a></p>
<p>If you can use C++11 then hexfloat is pretty easy to use.</p>
| 0 | 2013-11-10T20:19:38Z | [
"c++",
"python",
"formatting",
"floating-point",
"hex"
] |
How do I delete a foreign key constraint in SQLAlchemy? | 2,427,199 | <p>I'm using SQLAlchemy Migrate to keep track of database changes and I'm running into an issue with removing a foreign key. I have two tables, t_new is a new table, and t_exists is an existing table. I need to add t_new, then add a foreign key to t_exists. Then I need to be able to reverse the operation (which is w... | 7 | 2010-03-11T17:25:59Z | 2,427,980 | <p>I was able to accomplish this by creating a separate metadata instance and using Session.execute() to run raw SQL. Ideally, there would be a solution that uses sqlalchemy exclusively, so I wouldn't have to use MySQL-specific solutions. But as of now, I am not aware of such a solution.</p>
| 2 | 2010-03-11T19:23:44Z | [
"python",
"mysql",
"foreign-keys",
"sqlalchemy",
"mysql-error-1025"
] |
How do I delete a foreign key constraint in SQLAlchemy? | 2,427,199 | <p>I'm using SQLAlchemy Migrate to keep track of database changes and I'm running into an issue with removing a foreign key. I have two tables, t_new is a new table, and t_exists is an existing table. I need to add t_new, then add a foreign key to t_exists. Then I need to be able to reverse the operation (which is w... | 7 | 2010-03-11T17:25:59Z | 2,450,144 | <p>Well, you can achieve this in sqlalchemy: just <code>drop()</code> the all the constraints before you <code>drop()</code> the column (theoretically, you might have multiple constraints):</p>
<pre><code>def drop_column(column):
for fk in column.table.foreign_keys:
if fk.column == column:
prin... | -1 | 2010-03-15T20:12:48Z | [
"python",
"mysql",
"foreign-keys",
"sqlalchemy",
"mysql-error-1025"
] |
How do I delete a foreign key constraint in SQLAlchemy? | 2,427,199 | <p>I'm using SQLAlchemy Migrate to keep track of database changes and I'm running into an issue with removing a foreign key. I have two tables, t_new is a new table, and t_exists is an existing table. I need to add t_new, then add a foreign key to t_exists. Then I need to be able to reverse the operation (which is w... | 7 | 2010-03-11T17:25:59Z | 5,081,040 | <p>I believe you can achieve this with SQLAlchemy-Migrate. Note that a ForeignKey is on an isolated column. A ForeignKeyConstraint is at the table level and relates the columns together. If you look at the ForeignKey object on the column you will see that it references a ForeignKeyConstraint.</p>
<p>I would unable ... | 0 | 2011-02-22T16:38:35Z | [
"python",
"mysql",
"foreign-keys",
"sqlalchemy",
"mysql-error-1025"
] |
How do I delete a foreign key constraint in SQLAlchemy? | 2,427,199 | <p>I'm using SQLAlchemy Migrate to keep track of database changes and I'm running into an issue with removing a foreign key. I have two tables, t_new is a new table, and t_exists is an existing table. I need to add t_new, then add a foreign key to t_exists. Then I need to be able to reverse the operation (which is w... | 7 | 2010-03-11T17:25:59Z | 5,462,453 | <p>You can do it with sqlalchemy.migrate.</p>
<p>In order to make it work, I have had to create the foreign key constraint explicitly rather than implicitely with Column('fk', ForeignKey('fk_table.field')):</p>
<p>Alas, instead of doing this:</p>
<pre><code>p2 = Table('tablename',
metadata,
C... | 5 | 2011-03-28T17:01:19Z | [
"python",
"mysql",
"foreign-keys",
"sqlalchemy",
"mysql-error-1025"
] |
Thread-safe equivalent to python's time.strptime()? | 2,427,240 | <p>Something I wrote throws a lot of <code>AttributeError</code> exceptions when using time.strptime() inside a thread. This only seems to happen on Windows (not on Linux) but whatever- upon a'Googling, it seems that time.strptime() isn't considered thread-safe.</p>
<p>Is there a better way to create a datetime object... | 15 | 2010-03-11T17:33:30Z | 2,427,267 | <p>Have you tried manually synchronizing it yourself? Possibly using the synchronization decorator from <a href="http://code.activestate.com/recipes/465057-basic-synchronization-decorator/" rel="nofollow">this recipe</a>.</p>
| 0 | 2010-03-11T17:39:34Z | [
"python"
] |
Thread-safe equivalent to python's time.strptime()? | 2,427,240 | <p>Something I wrote throws a lot of <code>AttributeError</code> exceptions when using time.strptime() inside a thread. This only seems to happen on Windows (not on Linux) but whatever- upon a'Googling, it seems that time.strptime() isn't considered thread-safe.</p>
<p>Is there a better way to create a datetime object... | 15 | 2010-03-11T17:33:30Z | 2,427,308 | <p>According to the <a href="http://bugs.python.org/issue7980">bug report</a>, this doesn't happen if you call <code>strptime</code> once before creating your threads. I've done a little testing which seems to confirm this. So just make any call to <code>strptime</code> during initialization as a workaround.</p>
| 21 | 2010-03-11T17:46:01Z | [
"python"
] |
Thread-safe equivalent to python's time.strptime()? | 2,427,240 | <p>Something I wrote throws a lot of <code>AttributeError</code> exceptions when using time.strptime() inside a thread. This only seems to happen on Windows (not on Linux) but whatever- upon a'Googling, it seems that time.strptime() isn't considered thread-safe.</p>
<p>Is there a better way to create a datetime object... | 15 | 2010-03-11T17:33:30Z | 22,476,843 | <p>Just another workaround for this bug, you can simply import <code>_strptime</code> manually, along with datetime</p>
<pre><code>import _strptime
from datetime import datetime
# then, in threaded block
datetime.strptime(date, format)
</code></pre>
| 9 | 2014-03-18T10:38:54Z | [
"python"
] |
Thread-safe equivalent to python's time.strptime()? | 2,427,240 | <p>Something I wrote throws a lot of <code>AttributeError</code> exceptions when using time.strptime() inside a thread. This only seems to happen on Windows (not on Linux) but whatever- upon a'Googling, it seems that time.strptime() isn't considered thread-safe.</p>
<p>Is there a better way to create a datetime object... | 15 | 2010-03-11T17:33:30Z | 26,283,915 | <p>When I use <code>import datetime</code> the <code>datetime.datetime.strptime()</code> does not throw the exception anymore.</p>
| -2 | 2014-10-09T16:54:28Z | [
"python"
] |
Python Question: Year and Day of Year to date? | 2,427,555 | <p>I have a year value and a day of year and would like to convert to a date (day/month/year). </p>
<p>Thanks in advance. :) </p>
| 27 | 2010-03-11T18:21:43Z | 2,427,578 | <pre><code>>>> import datetime
>>> datetime.datetime.strptime('2010 120', '%Y %j')
datetime.datetime(2010, 4, 30, 0, 0)
>>> _.strftime('%d/%m/%Y')
'30/04/2010'
</code></pre>
| 15 | 2010-03-11T18:25:30Z | [
"python",
"date",
"julian-date"
] |
Python Question: Year and Day of Year to date? | 2,427,555 | <p>I have a year value and a day of year and would like to convert to a date (day/month/year). </p>
<p>Thanks in advance. :) </p>
| 27 | 2010-03-11T18:21:43Z | 2,427,581 | <pre><code>datetime.datetime(year, 1, 1) + datetime.timedelta(days - 1)
</code></pre>
| 40 | 2010-03-11T18:26:01Z | [
"python",
"date",
"julian-date"
] |
Python Question: Year and Day of Year to date? | 2,427,555 | <p>I have a year value and a day of year and would like to convert to a date (day/month/year). </p>
<p>Thanks in advance. :) </p>
| 27 | 2010-03-11T18:21:43Z | 2,427,612 | <p>The <a href="http://docs.python.org/library/datetime.html#datetime.date.toordinal"><code>toordinal()</code></a> and <a href="http://docs.python.org/library/datetime.html#datetime.date.fromordinal"><code>fromordinal()</code></a> functions of the <code>date</code> class could be used:</p>
<pre><code>from datetime im... | 6 | 2010-03-11T18:29:14Z | [
"python",
"date",
"julian-date"
] |
pyOpenSSL and the WantReadError | 2,427,947 | <p>I have a socket server that I am trying to move over to SSL on python 2.5, but I've run into a snag with pyOpenSSL. I can't find any good tutorials on using it, so I'm operating largely on guesses.</p>
<p>Here is how my server sets up the socket:</p>
<pre><code>ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.use_privatek... | 2 | 2010-03-11T19:19:25Z | 5,133,568 | <p>Sometimes in order to send application bytes of an SSL connection, you need to be able to read more bytes from the connection first. <code>WantReadError</code> is how this case is indicated. The only thing you're doing wrong is that you're not handling the <code>WantReadError</code> and then waiting until <code>se... | 4 | 2011-02-27T13:53:05Z | [
"python",
"ssl",
"pyopenssl"
] |
Python appengine Query does not work when using a variable | 2,428,047 | <p>I am trying to use a fetcher method to retrieve items from my datastore. If I use the following</p>
<pre><code>def getItem(item_id):
q = Item.all()
q.filter("itemid = ", item_id)
</code></pre>
<p>It fails because nothing is returned. If I hard code in an item like </p>
<pre><code>def getItem(item_id):
... | 3 | 2010-03-11T19:34:25Z | 2,428,251 | <p>Does it make any difference if you do this:</p>
<pre><code>def getItem(item_id):
q = Item.all()
q.filter("itemid = ", int(item_id))
</code></pre>
<p>The most likely cause of the problem that I can see is that the item_id parameter may be a string even though it is holding a numerical value. Coerce it to an... | 2 | 2010-03-11T20:02:17Z | [
"python",
"google-app-engine",
"gae-datastore"
] |
Old desktop programmer wants to create S+S project | 2,428,077 | <p>I have an idea for a product that I want to be web-based. But because I live in a part of the world where the internet is not always available, there needs to be a client desktop component that is available for when the internet is down. Also, I have been a SQL programmer, a desktop application programmer using dBas... | 1 | 2010-03-11T19:38:35Z | 2,428,452 | <p>If you want a 'desktop component' that is available for you to do development on whenever your internet is out, you could really choose any of those technologies. You can always have a local server (like apache) running on your machine, as well as a local sql database, though if your database contains a large amount... | 0 | 2010-03-11T20:29:27Z | [
"php",
"python",
"ruby-on-rails",
"programming-languages",
"saas"
] |
Old desktop programmer wants to create S+S project | 2,428,077 | <p>I have an idea for a product that I want to be web-based. But because I live in a part of the world where the internet is not always available, there needs to be a client desktop component that is available for when the internet is down. Also, I have been a SQL programmer, a desktop application programmer using dBas... | 1 | 2010-03-11T19:38:35Z | 2,429,484 | <p>The languages you list are all serverside components. The big question is whether you can sensibly build a thick client - effectively you could develop a multi-tier application where the webserver sits on the client and uses a webservice as a datafeed if/when its available but the solution is not very portable.</p>
... | 0 | 2010-03-11T23:43:06Z | [
"php",
"python",
"ruby-on-rails",
"programming-languages",
"saas"
] |
Old desktop programmer wants to create S+S project | 2,428,077 | <p>I have an idea for a product that I want to be web-based. But because I live in a part of the world where the internet is not always available, there needs to be a client desktop component that is available for when the internet is down. Also, I have been a SQL programmer, a desktop application programmer using dBas... | 1 | 2010-03-11T19:38:35Z | 2,430,572 | <p>If you wan't to run a version of the server on desktops, your best options would be Python, Rails, or Java servlets, all of which can be easily packaged into small self contained servers with no dependencies.</p>
<p>My recommendation for the desktop would be HTML 5 local storage. The standard hasn't been finalized... | 0 | 2010-03-12T04:49:57Z | [
"php",
"python",
"ruby-on-rails",
"programming-languages",
"saas"
] |
Creating a JSON response using Django and Python | 2,428,092 | <p>I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.</p>
<p>This is the server-side script:</p>
<pre><code>/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETUR... | 249 | 2010-03-11T19:40:35Z | 2,428,119 | <p>I usually use a dictionary, not a list to return JSON content. </p>
<pre><code>import json
from django.http import HttpResponse
response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'
</code></pre>
<p>Pre-Django 1.7 you'd return it like this:</p>
<pre><code>return Ht... | 559 | 2010-03-11T19:44:55Z | [
"python",
"django",
"json"
] |
Creating a JSON response using Django and Python | 2,428,092 | <p>I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.</p>
<p>This is the server-side script:</p>
<pre><code>/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETUR... | 249 | 2010-03-11T19:40:35Z | 2,428,192 | <p>I use this, it works fine.</p>
<pre><code>from django.utils import simplejson
from django.http import HttpResponse
def some_view(request):
to_json = {
"key1": "value1",
"key2": "value2"
}
return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
</code></pre>
<p>Alter... | 121 | 2010-03-11T19:55:29Z | [
"python",
"django",
"json"
] |
Creating a JSON response using Django and Python | 2,428,092 | <p>I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.</p>
<p>This is the server-side script:</p>
<pre><code>/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETUR... | 249 | 2010-03-11T19:40:35Z | 11,470,298 | <p>You'll want to use the django serializer to help with unicode stuff:</p>
<pre><code>from django.core import serializers
json_serializer = serializers.get_serializer("json")()
response = json_serializer.serialize(list, ensure_ascii=False, indent=2, use_natural_keys=True)
return HttpResponse(response, mimet... | 9 | 2012-07-13T12:14:10Z | [
"python",
"django",
"json"
] |
Creating a JSON response using Django and Python | 2,428,092 | <p>I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.</p>
<p>This is the server-side script:</p>
<pre><code>/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETUR... | 249 | 2010-03-11T19:40:35Z | 12,832,214 | <p><a href="http://stackoverflow.com/questions/5106306/how-to-use-google-app-engine-with-ajax-json">How to use google app engine with ajax (json)?</a></p>
<p>Code Javascript with JQuery:</p>
<pre><code>$.ajax({
url: '/ajax',
dataType : 'json',
cache: false,
success: function(data) {
alert('Loa... | 4 | 2012-10-11T04:27:56Z | [
"python",
"django",
"json"
] |
Creating a JSON response using Django and Python | 2,428,092 | <p>I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.</p>
<p>This is the server-side script:</p>
<pre><code>/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETUR... | 249 | 2010-03-11T19:40:35Z | 12,865,351 | <p>This is my preferred version using a class based view.
Simply subclass the basic View and override the get()-method.</p>
<pre><code>import json
class MyJsonView(View):
def get(self, *args, **kwargs):
resp = {'my_key': 'my value',}
return HttpResponse(json.dumps(resp), mimetype="application/jso... | 2 | 2012-10-12T18:53:25Z | [
"python",
"django",
"json"
] |
Creating a JSON response using Django and Python | 2,428,092 | <p>I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.</p>
<p>This is the server-side script:</p>
<pre><code>/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETUR... | 249 | 2010-03-11T19:40:35Z | 16,360,219 | <pre><code>from django.http import HttpResponse
import json
class JsonResponse(HttpResponse):
def __init__(self, content={}, mimetype=None, status=None,
content_type='application/json'):
super(JsonResponse, self).__init__(json.dumps(content), mimetype=mimetype,
... | 13 | 2013-05-03T13:35:45Z | [
"python",
"django",
"json"
] |
Creating a JSON response using Django and Python | 2,428,092 | <p>I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.</p>
<p>This is the server-side script:</p>
<pre><code>/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETUR... | 249 | 2010-03-11T19:40:35Z | 24,411,716 | <p>New in django 1.7</p>
<p>you could use <a href="https://docs.djangoproject.com/en/dev/ref/request-response/#jsonresponse-objects">JsonResponse</a> objects. </p>
<p>from the docs:</p>
<pre><code>from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
</code></pre>
| 110 | 2014-06-25T14:41:22Z | [
"python",
"django",
"json"
] |
Creating a JSON response using Django and Python | 2,428,092 | <p>I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.</p>
<p>This is the server-side script:</p>
<pre><code>/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETUR... | 249 | 2010-03-11T19:40:35Z | 26,653,011 | <p>Since Django 1.7 you have a standard <a href="https://docs.djangoproject.com/en/1.7/ref/request-response/#jsonresponse-objects">JsonResponse</a> that's exactly what you need:</p>
<pre><code>from django.http import JsonResponse
...
return JsonResponse(array_to_js, safe=False)
</code></pre>
<p>You don't even need to... | 16 | 2014-10-30T12:29:12Z | [
"python",
"django",
"json"
] |
Creating a JSON response using Django and Python | 2,428,092 | <p>I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.</p>
<p>This is the server-side script:</p>
<pre><code>/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETUR... | 249 | 2010-03-11T19:40:35Z | 27,599,604 | <pre><code>Django code(views.py):
def view(request):
if request.method == 'POST':
print request.body
data = request.body
return HttpResponse(json.dumps(data))
</code></pre>
<p>HTML code(view.html):</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<script src="http://ajax... | 1 | 2014-12-22T09:10:55Z | [
"python",
"django",
"json"
] |
Creating a JSON response using Django and Python | 2,428,092 | <p>I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.</p>
<p>This is the server-side script:</p>
<pre><code>/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETUR... | 249 | 2010-03-11T19:40:35Z | 32,466,453 | <p>For those who use Django 1.7+</p>
<pre><code>from django.http import JsonResponse
def your_view(request):
json_object = {'key': "value"}
return JsonResponse(json_object)
</code></pre>
<p><a href="https://docs.djangoproject.com/en/1.8/ref/request-response/#jsonresponse-objects">official docs</a></p>
| 10 | 2015-09-08T20:12:30Z | [
"python",
"django",
"json"
] |
casting raw strings python | 2,428,117 | <p>in python, given a variable which holds a string is there a quick way to cast that into another raw string variable?</p>
<p>the following code should illustrate what im after...</p>
<pre><code>def checkEqual(x, y):
print True if x==y else False
line1 = "hurr..\n..durr"
line2 = r"hurr..\n..durr"
line3 = "%r"%l... | 26 | 2010-03-11T19:44:30Z | 2,428,132 | <pre><code>"hurr..\n..durr".encode('string-escape')
</code></pre>
| 54 | 2010-03-11T19:46:50Z | [
"python",
"string",
"python-2.x"
] |
casting raw strings python | 2,428,117 | <p>in python, given a variable which holds a string is there a quick way to cast that into another raw string variable?</p>
<p>the following code should illustrate what im after...</p>
<pre><code>def checkEqual(x, y):
print True if x==y else False
line1 = "hurr..\n..durr"
line2 = r"hurr..\n..durr"
line3 = "%r"%l... | 26 | 2010-03-11T19:44:30Z | 2,428,189 | <p>Yet another way:</p>
<pre><code>>>> s = "hurr..\n..durr"
>>> print repr(s).strip("'")
hurr..\n..durr
</code></pre>
| 2 | 2010-03-11T19:55:06Z | [
"python",
"string",
"python-2.x"
] |
casting raw strings python | 2,428,117 | <p>in python, given a variable which holds a string is there a quick way to cast that into another raw string variable?</p>
<p>the following code should illustrate what im after...</p>
<pre><code>def checkEqual(x, y):
print True if x==y else False
line1 = "hurr..\n..durr"
line2 = r"hurr..\n..durr"
line3 = "%r"%l... | 26 | 2010-03-11T19:44:30Z | 4,172,713 | <pre><code>>>> v1 = 'aa\1.js'
>>> re.sub(r'(.*)\.js', repr(v1).strip("'"), 'my.js', 1)
'aa\\x01.js
</code></pre>
<p>But</p>
<pre><code>>>> re.sub(r'(.*)\.js', r'aa\1.js', 'my.js', 1)
'aamy.js'
</code></pre>
<p>And</p>
<pre><code>>>> re.sub(r'(.*)\.js', raw(v1), 'my.js', 1)
'aamy.... | 0 | 2010-11-13T13:25:01Z | [
"python",
"string",
"python-2.x"
] |
casting raw strings python | 2,428,117 | <p>in python, given a variable which holds a string is there a quick way to cast that into another raw string variable?</p>
<p>the following code should illustrate what im after...</p>
<pre><code>def checkEqual(x, y):
print True if x==y else False
line1 = "hurr..\n..durr"
line2 = r"hurr..\n..durr"
line3 = "%r"%l... | 26 | 2010-03-11T19:44:30Z | 27,449,976 | <p>Above it was shown how to encode.</p>
<pre><code>'hurr..\n..durr'.encode('string-escape')
</code></pre>
<p>This way will decode.</p>
<pre><code>r'hurr..\n..durr'.decode('string-escape')
</code></pre>
<p>Ex.</p>
<pre><code>In [12]: print 'hurr..\n..durr'.encode('string-escape')
hurr..\n..durr
In [13]: print r'h... | 1 | 2014-12-12T18:38:25Z | [
"python",
"string",
"python-2.x"
] |
Should I worry about circular references in Python? | 2,428,301 | <p>Suppose I have code that maintains a parent/children structure. In such a structure I get circular references, where a child points to a parent and a parent points to a child. Should I worry about them? I'm using Python 2.5.</p>
<p>I am concerned that they will not be garbage collected and the application will even... | 27 | 2010-03-11T20:11:28Z | 2,428,360 | <p>Python will detect the cycle and release the memory when there are no outside references.</p>
| 9 | 2010-03-11T20:17:49Z | [
"python"
] |
Should I worry about circular references in Python? | 2,428,301 | <p>Suppose I have code that maintains a parent/children structure. In such a structure I get circular references, where a child points to a parent and a parent points to a child. Should I worry about them? I'm using Python 2.5.</p>
<p>I am concerned that they will not be garbage collected and the application will even... | 27 | 2010-03-11T20:11:28Z | 2,428,361 | <p>Experimentally: you're fine:</p>
<pre><code>import itertools
for i in itertools.count():
a = {}
b = {"a":a}
a["b"] = b
</code></pre>
<p>It consistently stays at using 3.6 MB of RAM.</p>
| 13 | 2010-03-11T20:18:00Z | [
"python"
] |
Should I worry about circular references in Python? | 2,428,301 | <p>Suppose I have code that maintains a parent/children structure. In such a structure I get circular references, where a child points to a parent and a parent points to a child. Should I worry about them? I'm using Python 2.5.</p>
<p>I am concerned that they will not be garbage collected and the application will even... | 27 | 2010-03-11T20:11:28Z | 2,428,363 | <p>Circular references are a normal thing to do, so I don't see a reason to be worried about them. Many tree algorithms require that each node have links to its children and its parent. They're also required to implement something like a doubly linked list.</p>
| 5 | 2010-03-11T20:18:07Z | [
"python"
] |
Should I worry about circular references in Python? | 2,428,301 | <p>Suppose I have code that maintains a parent/children structure. In such a structure I get circular references, where a child points to a parent and a parent points to a child. Should I worry about them? I'm using Python 2.5.</p>
<p>I am concerned that they will not be garbage collected and the application will even... | 27 | 2010-03-11T20:11:28Z | 2,428,392 | <p>I don't think you should worry. Try the following program and will you see that it won't consume all memory:</p>
<pre><code>while True:
a=range(100)
b=range(100)
a.append(b)
b.append(a)
a.append(a)
b.append(b)
</code></pre>
| 3 | 2010-03-11T20:20:47Z | [
"python"
] |
Should I worry about circular references in Python? | 2,428,301 | <p>Suppose I have code that maintains a parent/children structure. In such a structure I get circular references, where a child points to a parent and a parent points to a child. Should I worry about them? I'm using Python 2.5.</p>
<p>I am concerned that they will not be garbage collected and the application will even... | 27 | 2010-03-11T20:11:28Z | 2,428,888 | <p>"Worry" is misplaced, but if your program turns out to be slow, consume more memory than expected, or have strange inexplicable pauses, the cause is indeed likely to be in those garbage reference loops -- they need to be garbage collected by a different procedure than "normal" (acyclic) reference graphs, and that co... | 22 | 2010-03-11T21:37:46Z | [
"python"
] |
Should I worry about circular references in Python? | 2,428,301 | <p>Suppose I have code that maintains a parent/children structure. In such a structure I get circular references, where a child points to a parent and a parent points to a child. Should I worry about them? I'm using Python 2.5.</p>
<p>I am concerned that they will not be garbage collected and the application will even... | 27 | 2010-03-11T20:11:28Z | 13,511,342 | <p>There seems to be a issue with references to methods in lists in a variable. Here are two examples. The first one does not call <code>__del__</code>. The second one with weakref is ok for <code>__del__</code>. However, in this later case the problem is that you cannot weakly reference methods: <a href="http://docs.p... | 1 | 2012-11-22T11:04:18Z | [
"python"
] |
When to use Python special methods? | 2,428,391 | <p>I know that classes can implement various special methods, such as <code>__iter__</code>, <code>__setitem__</code>, <code>__len__</code>, <code>__setattr__</code>, and many others. But when should I use them? Can anyone describe typical scenarios when I would want to implement them and they would simplify programmin... | 1 | 2010-03-11T20:20:36Z | 2,428,430 | <p>If you're creating a class that should act sort of like an array or dictionary, these are very useful so that your syntax looks familiar. For example, if you wanted to create an ordered dictionary, you could use all of the functions you mentioned so that you could interchange that with a regular dictionary.</p>
| 0 | 2010-03-11T20:26:24Z | [
"python"
] |
When to use Python special methods? | 2,428,391 | <p>I know that classes can implement various special methods, such as <code>__iter__</code>, <code>__setitem__</code>, <code>__len__</code>, <code>__setattr__</code>, and many others. But when should I use them? Can anyone describe typical scenarios when I would want to implement them and they would simplify programmin... | 1 | 2010-03-11T20:20:36Z | 2,428,433 | <p>Well, the short answer is: <em>when you need them</em>.</p>
<p>Since there are a lot of built in functions I can't answer for all of them. However, you can almost all the time manage without ever overriding a builtin Python function.</p>
<p>Usually when you <em>do</em> need them is when you'd like your object to b... | 3 | 2010-03-11T20:26:54Z | [
"python"
] |
When to use Python special methods? | 2,428,391 | <p>I know that classes can implement various special methods, such as <code>__iter__</code>, <code>__setitem__</code>, <code>__len__</code>, <code>__setattr__</code>, and many others. But when should I use them? Can anyone describe typical scenarios when I would want to implement them and they would simplify programmin... | 1 | 2010-03-11T20:20:36Z | 2,428,460 | <p>I think you basically answered your question.</p>
<p>Become familiar with the special methods. If you find that using one will make your program simpler, use it. If you don't understand what one is for, or feel like it is a more complex solution - you have answered the question. Don't use it.</p>
<p>The typical ... | 3 | 2010-03-11T20:31:34Z | [
"python"
] |
When to use Python special methods? | 2,428,391 | <p>I know that classes can implement various special methods, such as <code>__iter__</code>, <code>__setitem__</code>, <code>__len__</code>, <code>__setattr__</code>, and many others. But when should I use them? Can anyone describe typical scenarios when I would want to implement them and they would simplify programmin... | 1 | 2010-03-11T20:20:36Z | 12,573,111 | <p><code>getattr</code> and <code>setattr</code> are useful when you want to implement an interface by delegating to an instance member instead of straight inheritance. You map them to the <code>getattr</code> and <code>setattr</code> of the member.</p>
| 0 | 2012-09-24T21:21:42Z | [
"python"
] |
os.path.getmtime() doesn't return fraction of a second | 2,428,556 | <p>I compiled python 2.6.4 for centos 5.3 and find this issue that os.path.getmtime() or os.stat().m_time doesn't have the fraction part. As per docs, if os.stat_float_times() returns True, then it should return float value. In my case, I do see it as float, but no fraction part (it is 0).</p>
<pre><code>In [3]: os.pa... | 3 | 2010-03-11T20:50:37Z | 2,428,823 | <p>This is a filesystem limitation, rather than a Python one. Centos is still on ext3, which provides integer mtimes. You can see this if you display the mtimes with <code>ls</code>. Try</p>
<pre><code>ls -ld --full-time /tmp
</code></pre>
<p>On my ext3 Centos box, I get</p>
<pre><code>drwxrwxrwt 11 root root 69632 ... | 6 | 2010-03-11T21:28:41Z | [
"python",
"linux",
"centos"
] |
Concise way to getattr() and use it if not None in Python | 2,428,557 | <p>I am finding myself doing the following a bit too often:</p>
<pre><code>attr = getattr(obj, 'attr', None)
if attr is not None:
attr()
# Do something, either attr(), or func(attr), or whatever
else:
# Do something else
</code></pre>
<p>Is there a more pythonic way of writing that? Is this better? (At le... | 18 | 2010-03-11T20:50:42Z | 2,428,625 | <p>There is another nice idiom:</p>
<pre><code>if hasattr(obj, 'attr'):
...something...
else:
...something else...
</code></pre>
<p>From the two options you posted I prefer the first one. The notion of throwing exceptions when accessing members just do not seem the thing the exceptions were meant to be used f... | 4 | 2010-03-11T20:59:44Z | [
"python"
] |
Concise way to getattr() and use it if not None in Python | 2,428,557 | <p>I am finding myself doing the following a bit too often:</p>
<pre><code>attr = getattr(obj, 'attr', None)
if attr is not None:
attr()
# Do something, either attr(), or func(attr), or whatever
else:
# Do something else
</code></pre>
<p>Is there a more pythonic way of writing that? Is this better? (At le... | 18 | 2010-03-11T20:50:42Z | 2,428,702 | <p>Using try/except is generally considered more pythonic. It is also more efficient if obj does have the attribute, since it eliminates the test - try blocks have no overhead if the exception is not thrown. On the other hand it is less efficient if obj does not have the attribute since it will have the overhead of t... | 1 | 2010-03-11T21:10:37Z | [
"python"
] |
Concise way to getattr() and use it if not None in Python | 2,428,557 | <p>I am finding myself doing the following a bit too often:</p>
<pre><code>attr = getattr(obj, 'attr', None)
if attr is not None:
attr()
# Do something, either attr(), or func(attr), or whatever
else:
# Do something else
</code></pre>
<p>Is there a more pythonic way of writing that? Is this better? (At le... | 18 | 2010-03-11T20:50:42Z | 2,428,819 | <p>The <code>try</code>/<code>except</code> alternative, as you code it, might accidentally cause an <code>AttributeError</code> caused by problems in anything that <code>attr()</code> is calling, to be caught. If you want to code with <code>try</code>/<code>except</code>, which is reasonable and quite well performing... | 6 | 2010-03-11T21:28:23Z | [
"python"
] |
Concise way to getattr() and use it if not None in Python | 2,428,557 | <p>I am finding myself doing the following a bit too often:</p>
<pre><code>attr = getattr(obj, 'attr', None)
if attr is not None:
attr()
# Do something, either attr(), or func(attr), or whatever
else:
# Do something else
</code></pre>
<p>Is there a more pythonic way of writing that? Is this better? (At le... | 18 | 2010-03-11T20:50:42Z | 2,428,866 | <p>Ah, it depends on the exact code. Your two tools:</p>
<ul>
<li>hasattr(obj, 'attr') return True if and only if obj.attr exists.</li>
<li>getattr(obj, 'attr', other_value) returns obj.attr if it exists, else other_value</li>
<li>try a = obj.attr/except failure()/else do_something(a) when performance beats readabili... | 0 | 2010-03-11T21:35:07Z | [
"python"
] |
Concise way to getattr() and use it if not None in Python | 2,428,557 | <p>I am finding myself doing the following a bit too often:</p>
<pre><code>attr = getattr(obj, 'attr', None)
if attr is not None:
attr()
# Do something, either attr(), or func(attr), or whatever
else:
# Do something else
</code></pre>
<p>Is there a more pythonic way of writing that? Is this better? (At le... | 18 | 2010-03-11T20:50:42Z | 2,428,876 | <p>Since you are calling the <code>attr</code>, you could just do:</p>
<pre><code>def default_action():
# do something else
action = getattr(obj, 'attr', default_action)
action()
</code></pre>
| 22 | 2010-03-11T21:36:00Z | [
"python"
] |
Concise way to getattr() and use it if not None in Python | 2,428,557 | <p>I am finding myself doing the following a bit too often:</p>
<pre><code>attr = getattr(obj, 'attr', None)
if attr is not None:
attr()
# Do something, either attr(), or func(attr), or whatever
else:
# Do something else
</code></pre>
<p>Is there a more pythonic way of writing that? Is this better? (At le... | 18 | 2010-03-11T20:50:42Z | 25,343,529 | <p>Similar to Joe's answer, but shorter:</p>
<pre><code>getattr(obj, 'attr', lambda: None)()
</code></pre>
| 2 | 2014-08-16T20:11:06Z | [
"python"
] |
How to test floats results with doctest? | 2,428,618 | <p>I'm developing a program that makes some floating points calculations.
Is there any way to test my functions (which deliver floats) with doctests? </p>
| 10 | 2010-03-11T20:58:47Z | 2,428,747 | <p>Sure, just format the floats with a reasonable format, based on your knowledge of what precision you expect them to exhibit -- e.g, if you expect accuracy to 2 digits after the decimal point, you could use:</p>
<pre><code>''' Rest of your docstring and then...
>>> '%.2f' % funcreturningfloat()
'12... | 6 | 2010-03-11T21:16:14Z | [
"python",
"unit-testing",
"floating-point",
"doctest"
] |
How to test floats results with doctest? | 2,428,618 | <p>I'm developing a program that makes some floating points calculations.
Is there any way to test my functions (which deliver floats) with doctests? </p>
| 10 | 2010-03-11T20:58:47Z | 2,428,921 | <p><a href="http://docs.python.org/library/doctest.html#warnings">The documentation</a> has a suggestion</p>
<blockquote>
<p>Floating-point numbers are also
subject to small output variations
across platforms, because Python
defers to the platform C library for
float formatting, and C libraries vary
widely... | 6 | 2010-03-11T21:42:49Z | [
"python",
"unit-testing",
"floating-point",
"doctest"
] |
How to test floats results with doctest? | 2,428,618 | <p>I'm developing a program that makes some floating points calculations.
Is there any way to test my functions (which deliver floats) with doctests? </p>
| 10 | 2010-03-11T20:58:47Z | 5,235,834 | <p>String format allows use test tuples.</p>
<pre><code>>>> funcreturningfloattuple(1.0)
(1.0, 1.0)
>>> '%.2f, %.2f' % funcreturningfloattuple(1.0)
'1.00, 1.00'
>>> funcreturningfloattuple(1.4)
(1.3999999999999999, 1.3999999999999999)
>>> '%.2f, %.2f' % funcreturningfloattuple(1.4)... | 1 | 2011-03-08T17:11:43Z | [
"python",
"unit-testing",
"floating-point",
"doctest"
] |
How to test floats results with doctest? | 2,428,618 | <p>I'm developing a program that makes some floating points calculations.
Is there any way to test my functions (which deliver floats) with doctests? </p>
| 10 | 2010-03-11T20:58:47Z | 17,401,831 | <p>The following works for nosetests:</p>
<pre><code>>>> 1/3. # doctest: +ELLIPSIS
0.333...
</code></pre>
| 3 | 2013-07-01T10:05:23Z | [
"python",
"unit-testing",
"floating-point",
"doctest"
] |
How to test floats results with doctest? | 2,428,618 | <p>I'm developing a program that makes some floating points calculations.
Is there any way to test my functions (which deliver floats) with doctests? </p>
| 10 | 2010-03-11T20:58:47Z | 27,187,084 | <p>You can use numtest - a doctest extension that simplifies the test of numerical results.
<a href="https://pypi.python.org/pypi/numtest" rel="nofollow">https://pypi.python.org/pypi/numtest</a></p>
<pre><code>>>> 1.0/3
0.333
</code></pre>
<blockquote>
<p>Failed example:
1.0/3
Expected:
0.33... | 0 | 2014-11-28T10:50:14Z | [
"python",
"unit-testing",
"floating-point",
"doctest"
] |
datetime command line argument in python 2.4 | 2,428,746 | <p>I want to pass a datetime value into my python script on the command line. My first idea was to use optparse and pass the value in as a string, then use datetime.strptime to convert it to a datetime. This works fine on my machine (python 2.6), but I also need to run this script on machines that are running python 2.... | 7 | 2010-03-11T21:16:13Z | 2,428,785 | <p>Go by way of the <code>time</code> module, which did already have <code>strptime</code> in 2.4:</p>
<pre><code>>>> import time
>>> t = time.strptime("2010-02-02 7:31", "%Y-%m-%d %H:%M")
>>> t
(2010, 2, 2, 7, 31, 0, 1, 33, -1)
>>> import datetime
>>> datetime.datetime(*t[... | 14 | 2010-03-11T21:23:10Z | [
"python",
"datetime"
] |
How to detect an 'image area' percentage inside an image? | 2,428,916 | <p>Mhh, kinda hard to explain with my poor english ;)</p>
<p>So, lets say I have an image, doesnt matter what kind of (gif, jpg, png) with 200x200 pixel size (total area 40000 pixels)</p>
<p>This image have a background, that can be trasparent, or every color (but i know the background-color in advance).</p>
<p>Lets... | 2 | 2010-03-11T21:41:30Z | 2,428,942 | <p>I am assuming the surrounding area has only one colour and the object in the image can have any shape (so you need to find out its coordinates first, right?)</p>
<p>If you can use ImageMagick, it's easy. </p>
<ol>
<li><p>Store size of image (40000 Pixels)</p></li>
<li><p>Send image to ImageMagick and trim the surr... | 0 | 2010-03-11T21:47:41Z | [
"php",
"python",
"web-applications",
"image-processing",
"image-manipulation"
] |
How to detect an 'image area' percentage inside an image? | 2,428,916 | <p>Mhh, kinda hard to explain with my poor english ;)</p>
<p>So, lets say I have an image, doesnt matter what kind of (gif, jpg, png) with 200x200 pixel size (total area 40000 pixels)</p>
<p>This image have a background, that can be trasparent, or every color (but i know the background-color in advance).</p>
<p>Lets... | 2 | 2010-03-11T21:41:30Z | 2,428,961 | <p>Using Python and PIL (Python Imaging Library) you could try the following (untested - credit goes to the <a href="http://mail.python.org/pipermail/image-sig/2008-July/005092.html" rel="nofollow">original thread</a> here):</p>
<pre><code> from PIL import ImageChops
def trim(im, border):
bg = Image.new(im.mode... | 0 | 2010-03-11T21:51:07Z | [
"php",
"python",
"web-applications",
"image-processing",
"image-manipulation"
] |
How to detect an 'image area' percentage inside an image? | 2,428,916 | <p>Mhh, kinda hard to explain with my poor english ;)</p>
<p>So, lets say I have an image, doesnt matter what kind of (gif, jpg, png) with 200x200 pixel size (total area 40000 pixels)</p>
<p>This image have a background, that can be trasparent, or every color (but i know the background-color in advance).</p>
<p>Lets... | 2 | 2010-03-11T21:41:30Z | 2,429,706 | <pre><code>from PIL import Image
image = Image.open("pepper.png")
bg = image.getpixel((0,0))
width, height = image.size
bg_count = next(n for n,c in image.getcolors(width*height) if c==bg)
img_count = width*height - bg_count
img_percent = img_count*100.0/width/height
</code></pre>
<p>gives 7.361875 for both images</p>... | 4 | 2010-03-12T00:28:53Z | [
"php",
"python",
"web-applications",
"image-processing",
"image-manipulation"
] |
How to detect an 'image area' percentage inside an image? | 2,428,916 | <p>Mhh, kinda hard to explain with my poor english ;)</p>
<p>So, lets say I have an image, doesnt matter what kind of (gif, jpg, png) with 200x200 pixel size (total area 40000 pixels)</p>
<p>This image have a background, that can be trasparent, or every color (but i know the background-color in advance).</p>
<p>Lets... | 2 | 2010-03-11T21:41:30Z | 2,429,938 | <p>It depends a bit on your accuracy requirements and on the presence of the background color in the image. Consider this annoying test case:</p>
<ul>
<li>Make a 400 pt large "G". </li>
<li>Make the text white. Hit "Shadow" or "Outline" so it surrounded by black.</li>
<li>Put it on a white background.</li>
</ul>
... | 0 | 2010-03-12T01:35:47Z | [
"php",
"python",
"web-applications",
"image-processing",
"image-manipulation"
] |
Mimic Haskell with Python | 2,429,039 | <p>Haskell provides the feature something like f = f1 . f2</p>
<p>How can I mimic that with Python?</p>
<p>For example, if I have to do the 'map' operation two times, is there any way to do something like map . map in Python?</p>
<pre>
x = ['1','2','3']
x = map(int,x)
x = map(lambda i:i+1, x)
</pre>
| 2 | 2010-03-11T22:07:00Z | 2,429,057 | <p>There have been several proposals for a <code>compose</code> operation, but none have been formalized. In the meantime it is possible to use a list comprehension or a generator expression to apply complex transformations to a sequence.</p>
| 1 | 2010-03-11T22:10:26Z | [
"python"
] |
Mimic Haskell with Python | 2,429,039 | <p>Haskell provides the feature something like f = f1 . f2</p>
<p>How can I mimic that with Python?</p>
<p>For example, if I have to do the 'map' operation two times, is there any way to do something like map . map in Python?</p>
<pre>
x = ['1','2','3']
x = map(int,x)
x = map(lambda i:i+1, x)
</pre>
| 2 | 2010-03-11T22:07:00Z | 2,429,060 | <p>There's a good recipe for this <a href="http://code.activestate.com/recipes/52902-function-composition/" rel="nofollow">here</a>.</p>
| 0 | 2010-03-11T22:11:02Z | [
"python"
] |
Mimic Haskell with Python | 2,429,039 | <p>Haskell provides the feature something like f = f1 . f2</p>
<p>How can I mimic that with Python?</p>
<p>For example, if I have to do the 'map' operation two times, is there any way to do something like map . map in Python?</p>
<pre>
x = ['1','2','3']
x = map(int,x)
x = map(lambda i:i+1, x)
</pre>
| 2 | 2010-03-11T22:07:00Z | 2,429,063 | <p>I think you are looking for <a href="http://en.wikipedia.org/wiki/Function_composition_%28computer_science%29#First-class_composition" rel="nofollow">function composition</a> in Python.</p>
<p>You can do this:</p>
<pre><code>f = lambda x: f1(f2(x))
</code></pre>
| 2 | 2010-03-11T22:11:18Z | [
"python"
] |
Mimic Haskell with Python | 2,429,039 | <p>Haskell provides the feature something like f = f1 . f2</p>
<p>How can I mimic that with Python?</p>
<p>For example, if I have to do the 'map' operation two times, is there any way to do something like map . map in Python?</p>
<pre>
x = ['1','2','3']
x = map(int,x)
x = map(lambda i:i+1, x)
</pre>
| 2 | 2010-03-11T22:07:00Z | 2,429,064 | <pre><code>def compose(f,g):
return lambda x: f(g(x))
def inc(x): return x+1
map(compose(inc, int), ['1', '2', '3'])
# [2, 3, 4]
</code></pre>
| 1 | 2010-03-11T22:11:29Z | [
"python"
] |
Mimic Haskell with Python | 2,429,039 | <p>Haskell provides the feature something like f = f1 . f2</p>
<p>How can I mimic that with Python?</p>
<p>For example, if I have to do the 'map' operation two times, is there any way to do something like map . map in Python?</p>
<pre>
x = ['1','2','3']
x = map(int,x)
x = map(lambda i:i+1, x)
</pre>
| 2 | 2010-03-11T22:07:00Z | 2,429,090 | <pre>
>>> import <a href="http://oakwinter.com/code/functional/" rel="nofollow">functional</a>, <a href="http://docs.python.org/library/functools.html" rel="nofollow">functools</a>, <a href="http://docs.python.org/library/operator.html" rel="nofollow">operator</a>
>>> f1 = int
>>> f2 = functools.partial(operator.add, 1... | 1 | 2010-03-11T22:13:45Z | [
"python"
] |
Check if the integer in a list is not duplicated, and sequential | 2,429,073 | <p>testGroupList is a list of integer.
I need to check the numbers in testGroupList is sequential and not duplicate numbers. Ignore the negative integer. </p>
<p>For example, [1,2,-1,2,3,4] is an error as 2 is duplicated, but [-1,3,2,4,1,5] is OK. </p>
<p>I implemented it as follows, and it's pretty ugly. Is there an... | 1 | 2010-03-11T22:11:56Z | 2,429,100 | <p>For Python2.7 or 3.1 you can use Counter, although the print needs to be changed in the case of Python3</p>
<pre><code>from collections import Counter
counter = Counter(x for x in testGroupList if x>=0)
minval = min(Counter)
maxval = max(Counter)
messages={0:"(Test Group %(id)d missing)",
1:"%(id)d",
... | 1 | 2010-03-11T22:15:22Z | [
"python"
] |
Check if the integer in a list is not duplicated, and sequential | 2,429,073 | <p>testGroupList is a list of integer.
I need to check the numbers in testGroupList is sequential and not duplicate numbers. Ignore the negative integer. </p>
<p>For example, [1,2,-1,2,3,4] is an error as 2 is duplicated, but [-1,3,2,4,1,5] is OK. </p>
<p>I implemented it as follows, and it's pretty ugly. Is there an... | 1 | 2010-03-11T22:11:56Z | 2,429,139 | <pre>
for i, v in enumerate(buff):
if i != v - 1:
print "MISSING OR DUPLICATE"
</pre>
| 0 | 2010-03-11T22:19:39Z | [
"python"
] |
Check if the integer in a list is not duplicated, and sequential | 2,429,073 | <p>testGroupList is a list of integer.
I need to check the numbers in testGroupList is sequential and not duplicate numbers. Ignore the negative integer. </p>
<p>For example, [1,2,-1,2,3,4] is an error as 2 is duplicated, but [-1,3,2,4,1,5] is OK. </p>
<p>I implemented it as follows, and it's pretty ugly. Is there an... | 1 | 2010-03-11T22:11:56Z | 2,429,286 | <p>If you don't need fancy error reporting, then you can implement it as two simple checks:</p>
<pre><code>positiveValues = [x for x in testGroupList if x > 0]
if len(positiveValues) != len(set(positiveValues)):
print("Input has duplicate values")
elif len(positiveValues) != max(positiveValues):
print("Inpu... | 0 | 2010-03-11T22:40:54Z | [
"python"
] |
Check if the integer in a list is not duplicated, and sequential | 2,429,073 | <p>testGroupList is a list of integer.
I need to check the numbers in testGroupList is sequential and not duplicate numbers. Ignore the negative integer. </p>
<p>For example, [1,2,-1,2,3,4] is an error as 2 is duplicated, but [-1,3,2,4,1,5] is OK. </p>
<p>I implemented it as follows, and it's pretty ugly. Is there an... | 1 | 2010-03-11T22:11:56Z | 2,429,741 | <p>If you're looking for more elegant as in smaller code, then you can just do this:</p>
<pre><code>buff = [x for x in testGroupList if x > 0]
for i, val in enumerate([buff.count(x) for x in xrange(1,max(buff))]):
if val == 1: print i+1,
elif val > 1: print "(Test Group %d duplicated %d times)" % (i+1, ... | 1 | 2010-03-12T00:39:45Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.