title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Why I cannot build a chain of methods? (method1.method2.method3)
1,482,270
<p>If I have the following code:</p> <pre><code>import sqlite sqlite.connect('tmp.db').cursor().close() </code></pre> <p>I get the following error message:</p> <pre><code>Traceback (most recent call last): File "searchengine2.py", line 13, in ? sqlite.connect('tmp.db').cursor().close() File "/usr/lib64/pytho...
0
2009-09-26T21:46:49Z
1,482,291
<p>It looks like <code>cursor()</code> returns (and keeps) a weak reference to the connection, so that then, when the strong reference to your connection is off the call stack, your connection (the result of <code>connect()</code>) is left without any strong references. So by the time <code>close()</code> is called, y...
1
2009-09-26T22:01:00Z
[ "python", "sqlite", "methods" ]
Java vs Python on Hadoop
1,482,282
<p>I am working on a project using Hadoop and it seems to natively incorporate Java and provide streaming support for Python. Is there is a significant performance impact to choosing one over the other? I am early enough in the process where I can go either way if there is a significant performance difference one way ...
46
2009-09-26T21:55:05Z
1,482,294
<p>Java is less dynamic than Python and more effort has been put into its VM, making it a faster language. Python is also held back by its Global Interpreter Lock, meaning it cannot push threads of a single process onto different core.</p> <p>Whether this makes any significant difference depends on what you intend to ...
13
2009-09-26T22:03:11Z
[ "java", "python", "hadoop" ]
Java vs Python on Hadoop
1,482,282
<p>I am working on a project using Hadoop and it seems to natively incorporate Java and provide streaming support for Python. Is there is a significant performance impact to choosing one over the other? I am early enough in the process where I can go either way if there is a significant performance difference one way ...
46
2009-09-26T21:55:05Z
1,482,440
<p>With Python you'll probably develop faster and with Java will definitely run faster.</p> <p>Google "benchmarksgame" if you want to see some very accurate speed comparisons between all popular languages, but if I recall correctly you're talking about 3-5x faster.</p> <p>That said, few things are processor bound the...
23
2009-09-26T23:51:13Z
[ "java", "python", "hadoop" ]
Java vs Python on Hadoop
1,482,282
<p>I am working on a project using Hadoop and it seems to natively incorporate Java and provide streaming support for Python. Is there is a significant performance impact to choosing one over the other? I am early enough in the process where I can go either way if there is a significant performance difference one way ...
46
2009-09-26T21:55:05Z
6,700,580
<p>You can write Hadoop mapreduce transformations either as "streaming" or as a "custom jar". If you use streaming, you can write your code in any language you like, including Python or C++. Your code will just read from STDIN and output to STDOUT. However, on hadoop versions before 0.21, hadoop streaming used to only...
14
2011-07-14T22:15:15Z
[ "java", "python", "hadoop" ]
what's a good way to combinate through a set?
1,482,308
<p>Given a set <code>{a,b,c,d}</code>, what's a good way to produce <code>{a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,abcd}</code>?</p>
15
2009-09-26T22:11:20Z
1,482,316
<p>The Python <a href="http://docs.python.org/library/itertools.html#recipes"><code>itertools</code> page</a> has exactly a <code>powerset</code> recipe for this:</p> <pre><code>def powerset(iterable): "powerset([1,2,3]) --&gt; () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.fr...
34
2009-09-26T22:18:15Z
[ "python", "factorial" ]
what's a good way to combinate through a set?
1,482,308
<p>Given a set <code>{a,b,c,d}</code>, what's a good way to produce <code>{a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,abcd}</code>?</p>
15
2009-09-26T22:11:20Z
1,482,320
<p>Here is more code for a powerset. This is written from scratch:</p> <pre><code>&gt;&gt;&gt; def powerset(s): ... x = len(s) ... for i in range(1 &lt;&lt; x): ... print [s[j] for j in range(x) if (i &amp; (1 &lt;&lt; j))] ... &gt;&gt;&gt; powerset([4,5,6]) [] [4] [5] [4, 5] [6] [4, 6] [5, 6] [4, 5, 6...
11
2009-09-26T22:20:22Z
[ "python", "factorial" ]
what's a good way to combinate through a set?
1,482,308
<p>Given a set <code>{a,b,c,d}</code>, what's a good way to produce <code>{a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,abcd}</code>?</p>
15
2009-09-26T22:11:20Z
1,482,322
<p>If you're looking for a quick answer, I just searched "python power set" on google and came up with this: <a href="http://blog.technomancy.org/2009/3/17/a-powerset-generator-in-python">Python Power Set Generator</a></p> <p>Here's a copy-paste from the code in that page:</p> <pre><code>def powerset(seq): """ ...
10
2009-09-26T22:21:05Z
[ "python", "factorial" ]
what's a good way to combinate through a set?
1,482,308
<p>Given a set <code>{a,b,c,d}</code>, what's a good way to produce <code>{a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,abcd}</code>?</p>
15
2009-09-26T22:11:20Z
1,482,359
<pre><code>def powerset(lst): return reduce(lambda result, x: result + [subset + [x] for subset in result], lst, [[]]) </code></pre>
6
2009-09-26T22:54:12Z
[ "python", "factorial" ]
what's a good way to combinate through a set?
1,482,308
<p>Given a set <code>{a,b,c,d}</code>, what's a good way to produce <code>{a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,abcd}</code>?</p>
15
2009-09-26T22:11:20Z
14,906,761
<p>I just wanted to provide the most comprehensible solution, the anti code-golf version.</p> <pre><code>from itertools import combinations l = ["x", "y", "z", ] def powerset(items): combo = [] for r in range(len(items) + 1): #use a list to coerce a actual list from the combinations generator ...
0
2013-02-16T03:56:58Z
[ "python", "factorial" ]
what's a good way to combinate through a set?
1,482,308
<p>Given a set <code>{a,b,c,d}</code>, what's a good way to produce <code>{a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,abcd}</code>?</p>
15
2009-09-26T22:11:20Z
15,942,290
<p>This is wild because none of these answers actually provide the return of an actual Python set. Here is a messy implementation that will give a powerset that actually is a Python <code>set</code>. </p> <pre><code>test_set = set(['yo', 'whatup', 'money']) def powerset( base_set ): """ modified from pydoc's itert...
0
2013-04-11T06:43:45Z
[ "python", "factorial" ]
what's a good way to combinate through a set?
1,482,308
<p>Given a set <code>{a,b,c,d}</code>, what's a good way to produce <code>{a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,abcd}</code>?</p>
15
2009-09-26T22:11:20Z
17,700,015
<pre><code>def get_power_set(s): power_set=[[]] for elem in s: # iterate over the sub sets so far for sub_set in power_set: # add a new subset consisting of the subset at hand added elem power_set=power_set+[list(sub_set)+[elem]] return power_set </code></pre> <p>For example:</p> <pre><code>...
1
2013-07-17T12:40:08Z
[ "python", "factorial" ]
what's a good way to combinate through a set?
1,482,308
<p>Given a set <code>{a,b,c,d}</code>, what's a good way to produce <code>{a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,abcd}</code>?</p>
15
2009-09-26T22:11:20Z
18,927,108
<p>Here is my quick implementation utilizing combinations but using only built-ins.</p> <pre><code>def powerSet(array): length = str(len(array)) formatter = '{:0' + length + 'b}' combinations = [] for i in xrange(2**int(length)): combinations.append(formatter.format(i)) sets = set() cur...
0
2013-09-20T23:06:30Z
[ "python", "factorial" ]
what's a good way to combinate through a set?
1,482,308
<p>Given a set <code>{a,b,c,d}</code>, what's a good way to produce <code>{a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,abcd}</code>?</p>
15
2009-09-26T22:11:20Z
19,078,726
<p>There is a refinement of powerset:</p> <pre><code>def powerset(seq): """ Returns all the subsets of this set. This is a generator. """ if len(seq) &lt;= 0: yield [] else: for item in powerset(seq[1:]): yield [seq[0]]+item yield item </code></pre>
1
2013-09-29T13:43:39Z
[ "python", "factorial" ]
django. Can a view receive a list as parameter?
1,482,362
<p>I want to submit a form (by POST) that will submit N (unknown) user_id's. Can I make a view receive those ids as a list?</p> <p>For example</p> <pre><code>def getids(request,list): for id in list: usr = User.objects.get(pk=id); //do something with it. usr.save() </code></pre> <p>Is </p> ...
1
2009-09-26T22:56:51Z
1,482,365
<p>You should read about <a href="http://docs.djangoproject.com/en/dev/ref/request-response/#querydict-objects" rel="nofollow">QueryDict objects</a>:</p> <pre><code>&gt;&gt;&gt; q = QueryDict('a=1&amp;a=2&amp;a=3') &gt;&gt;&gt; q.lists() [('a', ['1', '2', '3'])] </code></pre>
5
2009-09-26T23:02:33Z
[ "python", "django", "django-views" ]
django. Can a view receive a list as parameter?
1,482,362
<p>I want to submit a form (by POST) that will submit N (unknown) user_id's. Can I make a view receive those ids as a list?</p> <p>For example</p> <pre><code>def getids(request,list): for id in list: usr = User.objects.get(pk=id); //do something with it. usr.save() </code></pre> <p>Is </p> ...
1
2009-09-26T22:56:51Z
1,482,368
<p>Very close. The POST parameters are actually contained in a <a href="http://docs.djangoproject.com/en/dev/ref/request-response/#querydict-objects" rel="nofollow">QueryDict object</a> in the request.</p> <pre><code>def getids(request): if request.method == 'POST': for field in HttpRequest.POST: ...
2
2009-09-26T23:03:37Z
[ "python", "django", "django-views" ]
django. Can a view receive a list as parameter?
1,482,362
<p>I want to submit a form (by POST) that will submit N (unknown) user_id's. Can I make a view receive those ids as a list?</p> <p>For example</p> <pre><code>def getids(request,list): for id in list: usr = User.objects.get(pk=id); //do something with it. usr.save() </code></pre> <p>Is </p> ...
1
2009-09-26T22:56:51Z
1,483,162
<p>If you are submitting lots of identical forms in one page you might find <a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/" rel="nofollow">Formsets</a> to be the thing you want.</p> <p>You can then make one Form for the userid and then repeat it in a Formset. You can then iterate over the formse...
2
2009-09-27T09:06:51Z
[ "python", "django", "django-views" ]
django. Can a view receive a list as parameter?
1,482,362
<p>I want to submit a form (by POST) that will submit N (unknown) user_id's. Can I make a view receive those ids as a list?</p> <p>For example</p> <pre><code>def getids(request,list): for id in list: usr = User.objects.get(pk=id); //do something with it. usr.save() </code></pre> <p>Is </p> ...
1
2009-09-26T22:56:51Z
1,494,319
<p>You can create the form fields with some prefix you could filter later.</p> <p>Say you use form fields with names like uid-1, uid-2, ... uid-n</p> <p>Then, when you process the POST you can do:</p> <pre><code>uids = [POST[x] for x in POST.keys() if x[:3] == 'uid'] </code></pre> <p>That would give you the values ...
0
2009-09-29T18:57:57Z
[ "python", "django", "django-views" ]
django. Can a view receive a list as parameter?
1,482,362
<p>I want to submit a form (by POST) that will submit N (unknown) user_id's. Can I make a view receive those ids as a list?</p> <p>For example</p> <pre><code>def getids(request,list): for id in list: usr = User.objects.get(pk=id); //do something with it. usr.save() </code></pre> <p>Is </p> ...
1
2009-09-26T22:56:51Z
33,487,400
<p><code>QueryDict</code>'s <a href="https://docs.djangoproject.com/en/1.8/ref/request-response/#django.http.QueryDict.getlist" rel="nofollow"><code>getlist</code></a> is what you're looking for.</p> <p>From the docs:</p> <pre><code>&gt;&gt;&gt; q = QueryDict('a=1', mutable=True) &gt;&gt;&gt; q.update({'a': '2'}) &gt...
0
2015-11-02T21:34:42Z
[ "python", "django", "django-views" ]
Best approach to a command line proxy?
1,482,367
<p>I'd like to write a simple command line proxy in Python to sit between a Telnet/SSH connection and a local serial interface. The application should simply bridge I/O between the two, but filter out certain unallowed strings (matched by regular expressions). (This for a router/switch lab in which the user is given re...
0
2009-09-26T23:03:33Z
1,482,374
<p>Python is not my primary language, so I'll leave that part of the answer for others. I do alot of security work, though, and I would urge a "white list" approach, not a "black list" approach. In other words, pick a set of safe commands and forbid all others. This is much much easier than trying to think of all the m...
6
2009-09-26T23:08:08Z
[ "python", "regex", "command-line" ]
Best approach to a command line proxy?
1,482,367
<p>I'd like to write a simple command line proxy in Python to sit between a Telnet/SSH connection and a local serial interface. The application should simply bridge I/O between the two, but filter out certain unallowed strings (matched by regular expressions). (This for a router/switch lab in which the user is given re...
0
2009-09-26T23:03:33Z
1,482,448
<p>As all the examples you show finish with <code>(enter)</code>, why is it that...:</p> <blockquote> <p>Communication must be asynchronous; I can't simply wait for a carriage return to allow the buffer to be fed out the serial interface</p> </blockquote> <p>if you can collect incoming data until the "enter",...
0
2009-09-26T23:57:56Z
[ "python", "regex", "command-line" ]
Best approach to a command line proxy?
1,482,367
<p>I'd like to write a simple command line proxy in Python to sit between a Telnet/SSH connection and a local serial interface. The application should simply bridge I/O between the two, but filter out certain unallowed strings (matched by regular expressions). (This for a router/switch lab in which the user is given re...
0
2009-09-26T23:03:33Z
1,484,002
<p>After thinking about this for a while, it doesn't seem like there's any practical, reliable method to filter on client input. I'm going to attempt this from another angle: if I can identify persistent patterns in warning messages coming from the serial devices (e.g. confirmation prompts) I may be able to abort relia...
0
2009-09-27T17:23:17Z
[ "python", "regex", "command-line" ]
Best approach to a command line proxy?
1,482,367
<p>I'd like to write a simple command line proxy in Python to sit between a Telnet/SSH connection and a local serial interface. The application should simply bridge I/O between the two, but filter out certain unallowed strings (matched by regular expressions). (This for a router/switch lab in which the user is given re...
0
2009-09-26T23:03:33Z
1,485,711
<p><a href="http://docs.fabfile.org/0.9/" rel="nofollow">Fabric</a> is doing a similar thing.</p> <p>For SSH api you should check <a href="http://www.lag.net/paramiko/" rel="nofollow">paramiko</a>.</p>
0
2009-09-28T06:38:53Z
[ "python", "regex", "command-line" ]
Understanding this class in python. The operator % and formatting a float
1,482,383
<pre><code>class FormatFloat(FormatFormatStr): def __init__(self, precision=4, scale=1.): FormatFormatStr.__init__(self, '%%1.%df'%precision) self.precision = precision self.scale = scale def toval(self, x): if x is not None: x = x * self.scale return x ...
1
2009-09-26T23:17:55Z
1,482,421
<p>In <code>('%%1.%df' % precision)</code>, the first <code>%%</code> yields a literal <code>%</code>, <code>%d</code> is substituted with <code>precision</code>, and <code>f</code> is inserted literally. Here's an example of how it might turn out:</p> <pre><code>&gt;&gt;&gt; '%%1.%df' % 4 '%1.4f' </code></pre> <p><a...
0
2009-09-26T23:37:08Z
[ "python", "class", "operators" ]
Understanding this class in python. The operator % and formatting a float
1,482,383
<pre><code>class FormatFloat(FormatFormatStr): def __init__(self, precision=4, scale=1.): FormatFormatStr.__init__(self, '%%1.%df'%precision) self.precision = precision self.scale = scale def toval(self, x): if x is not None: x = x * self.scale return x ...
1
2009-09-26T23:17:55Z
1,482,423
<p>In python format strings, "%%" means "insert a literal percent sign" -- the first % 'escapes' the second, in the jargon. The string in question, <code>"%%1.%df" % precision</code> is using a format string to generate a format string, and the only thing that gets substituted is the "%d". Try it at the interactive pro...
0
2009-09-26T23:39:36Z
[ "python", "class", "operators" ]
Understanding this class in python. The operator % and formatting a float
1,482,383
<pre><code>class FormatFloat(FormatFormatStr): def __init__(self, precision=4, scale=1.): FormatFormatStr.__init__(self, '%%1.%df'%precision) self.precision = precision self.scale = scale def toval(self, x): if x is not None: x = x * self.scale return x ...
1
2009-09-26T23:17:55Z
1,482,424
<pre><code>&gt;&gt;&gt; precision=4 &gt;&gt;&gt; '%%1.%df'%precision '%1.4f' </code></pre> <p>%% gets translated to %</p> <p>1 is printed as is</p> <p>%d prints precision as a decimal number</p> <p>f is printed literally</p>
2
2009-09-26T23:39:59Z
[ "python", "class", "operators" ]
Google App Engine - ReferenceProperty() gives error - Generic reference - Polymodel
1,482,435
<p>Given a Polymodel in Google App Engine, likeso:</p> <pre><code>from google.appengine.ext import db from google.appengine.ext.db import polymodel class Base(polymodel.PolyModel): def add_to_referer(self): Referer(target=self).put() class Referer(db.Model): target = db.ReferenceProperty() @classmethod ...
0
2009-09-26T23:47:53Z
1,482,439
<p>Ah. I answered this immediately after I posted:</p> <p>The file with Referer needs to <strong>import Base</strong>.</p> <p>Perhaps someone else will happen upon this quirk, so I'll leave this question open.</p>
0
2009-09-26T23:50:23Z
[ "python", "google-app-engine", "referenceproperty" ]
`xrange(2**100)` -> OverflowError: long int too large to convert to int
1,482,480
<p><code>xrange</code> function doesn't work for large integers:</p> <pre><code>&gt;&gt;&gt; N = 10**100 &gt;&gt;&gt; xrange(N) Traceback (most recent call last): ... OverflowError: long int too large to convert to int &gt;&gt;&gt; xrange(N, N+10) Traceback (most recent call last): ... OverflowError: long int too larg...
16
2009-09-27T00:28:45Z
1,482,496
<p>Even if there was a backport, it would probably have to be modified. The underlying problem here is that in Python 2.x <code>int</code> and <code>long</code> are separate data types, even though <code>int</code>s get automatically upcast to <code>long</code>s as necessary. However, this doesn't necessarily happen ...
1
2009-09-27T00:37:30Z
[ "python", "python-3.x", "range", "biginteger", "xrange" ]
`xrange(2**100)` -> OverflowError: long int too large to convert to int
1,482,480
<p><code>xrange</code> function doesn't work for large integers:</p> <pre><code>&gt;&gt;&gt; N = 10**100 &gt;&gt;&gt; xrange(N) Traceback (most recent call last): ... OverflowError: long int too large to convert to int &gt;&gt;&gt; xrange(N, N+10) Traceback (most recent call last): ... OverflowError: long int too larg...
16
2009-09-27T00:28:45Z
1,482,497
<p>From the docs:</p> <blockquote> <p>Note</p> <p>xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (“short” Python integers), and also requires that the number of elements fit in a na...
9
2009-09-27T00:38:54Z
[ "python", "python-3.x", "range", "biginteger", "xrange" ]
`xrange(2**100)` -> OverflowError: long int too large to convert to int
1,482,480
<p><code>xrange</code> function doesn't work for large integers:</p> <pre><code>&gt;&gt;&gt; N = 10**100 &gt;&gt;&gt; xrange(N) Traceback (most recent call last): ... OverflowError: long int too large to convert to int &gt;&gt;&gt; xrange(N, N+10) Traceback (most recent call last): ... OverflowError: long int too larg...
16
2009-09-27T00:28:45Z
1,482,502
<p>I believe there is no backport (Py 3's completely removed the int/long distinction, after all, but in 2.* it's here to stay;-) but it's not hard to hack your own, e.g....:</p> <pre><code>import operator def wowrange(start, stop, step=1): if step == 0: raise ValueError('step must be != 0') elif step &lt; 0:...
19
2009-09-27T00:41:55Z
[ "python", "python-3.x", "range", "biginteger", "xrange" ]
`xrange(2**100)` -> OverflowError: long int too large to convert to int
1,482,480
<p><code>xrange</code> function doesn't work for large integers:</p> <pre><code>&gt;&gt;&gt; N = 10**100 &gt;&gt;&gt; xrange(N) Traceback (most recent call last): ... OverflowError: long int too large to convert to int &gt;&gt;&gt; xrange(N, N+10) Traceback (most recent call last): ... OverflowError: long int too larg...
16
2009-09-27T00:28:45Z
1,482,695
<p>Okay, here's a go at a fuller reimplementation.</p> <pre><code>class MyXRange(object): def __init__(self, a1, a2=None, step=1): if step == 0: raise ValueError("arg 3 must not be 0") if a2 is None: a1, a2 = 0, a1 if (a2 - a1) % step != 0: a2 += step - (...
10
2009-09-27T03:05:09Z
[ "python", "python-3.x", "range", "biginteger", "xrange" ]
`xrange(2**100)` -> OverflowError: long int too large to convert to int
1,482,480
<p><code>xrange</code> function doesn't work for large integers:</p> <pre><code>&gt;&gt;&gt; N = 10**100 &gt;&gt;&gt; xrange(N) Traceback (most recent call last): ... OverflowError: long int too large to convert to int &gt;&gt;&gt; xrange(N, N+10) Traceback (most recent call last): ... OverflowError: long int too larg...
16
2009-09-27T00:28:45Z
1,482,801
<h3>Edit</h3> <p><a href="http://bugs.python.org/issue1546078" rel="nofollow">Issue 1546078: "xrange that supports longs, etc"</a> on the Python issue tracker contains C patch and pure Python implementation of unlimited xrange written by Neal Norwitz (nnorwitz). See <a href="http://bugs.python.org/file7500/xrange.py" ...
3
2009-09-27T04:34:41Z
[ "python", "python-3.x", "range", "biginteger", "xrange" ]
How to make python window run as "Always On Top"?
1,482,565
<p>I am running a little program in python that launches a small window that needs to stay on top of all the other windows. I believe this is OS specific, how is it done in GNU-Linux with GNOME?</p> <p>[<strong>Update - Solution for Windows</strong>]</p> <p>Lovely, I think I got it working. I am using Python 2.5.4 wi...
6
2009-09-27T01:25:09Z
1,482,574
<p>I really don't know much Python at all, but Googling "pygtk always on top" gave me this:</p> <p><a href="http://www.mail-archive.com/pygtk@daa.com.au/msg01370.html" rel="nofollow">http://www.mail-archive.com/pygtk@daa.com.au/msg01370.html</a></p> <p>The solution posted there was:</p> <pre><code>transient.set_tran...
0
2009-09-27T01:34:26Z
[ "python", "linux", "gnome", "pygame", "always-on-top" ]
How to make python window run as "Always On Top"?
1,482,565
<p>I am running a little program in python that launches a small window that needs to stay on top of all the other windows. I believe this is OS specific, how is it done in GNU-Linux with GNOME?</p> <p>[<strong>Update - Solution for Windows</strong>]</p> <p>Lovely, I think I got it working. I am using Python 2.5.4 wi...
6
2009-09-27T01:25:09Z
1,482,733
<p>The question is more like which windowing toolkit are you using ? PyGTK and similar educated googling gave me <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkwindow.html#method-gtkwindow--set-keep-above">this</a>:</p> <pre><code> gtk.Window.set_keep_above </code></pre> <p>As mentioned previously it i...
8
2009-09-27T03:39:33Z
[ "python", "linux", "gnome", "pygame", "always-on-top" ]
How to make python window run as "Always On Top"?
1,482,565
<p>I am running a little program in python that launches a small window that needs to stay on top of all the other windows. I believe this is OS specific, how is it done in GNU-Linux with GNOME?</p> <p>[<strong>Update - Solution for Windows</strong>]</p> <p>Lovely, I think I got it working. I am using Python 2.5.4 wi...
6
2009-09-27T01:25:09Z
3,406,597
<p>I was trying to figure out a similar issue and found this solution using the Pmw module</p> <p><a href="http://www.java2s.com/Code/Python/GUI-Pmw/Showglobalmodaldialog.htm" rel="nofollow">http://www.java2s.com/Code/Python/GUI-Pmw/Showglobalmodaldialog.htm</a></p>
0
2010-08-04T14:36:41Z
[ "python", "linux", "gnome", "pygame", "always-on-top" ]
Grab an image via the web and save it with Python
1,482,600
<p>I want to be able to download an image (to my computer or to a web server) resize it, and upload it to S3. The piece concerned here is:</p> <p>What would be a recommended way to do the downloading portion within Python (i.e., don't want to use external tools, bash, etc). I want it to be stored into memory until it'...
1
2009-09-27T02:00:00Z
1,482,611
<p>Consider:</p> <pre><code>import urllib f = urllib.urlopen(url_of_image) image = f.read() </code></pre> <p><a href="http://docs.python.org/library/urllib.html" rel="nofollow">http://docs.python.org/library/urllib.html</a></p>
0
2009-09-27T02:06:16Z
[ "python", "image" ]
Grab an image via the web and save it with Python
1,482,600
<p>I want to be able to download an image (to my computer or to a web server) resize it, and upload it to S3. The piece concerned here is:</p> <p>What would be a recommended way to do the downloading portion within Python (i.e., don't want to use external tools, bash, etc). I want it to be stored into memory until it'...
1
2009-09-27T02:00:00Z
1,482,615
<p><a href="http://pycurl.sourceforge.net/" rel="nofollow">Pycurl</a>, <a href="http://docs.python.org/library/urllib.html" rel="nofollow">urllib</a>, and <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> are all options. Pycurl is a Python interface for libcurl, and urllib and urllib2 ar...
1
2009-09-27T02:07:28Z
[ "python", "image" ]
Grab an image via the web and save it with Python
1,482,600
<p>I want to be able to download an image (to my computer or to a web server) resize it, and upload it to S3. The piece concerned here is:</p> <p>What would be a recommended way to do the downloading portion within Python (i.e., don't want to use external tools, bash, etc). I want it to be stored into memory until it'...
1
2009-09-27T02:00:00Z
1,482,616
<p><a href="http://docs.python.org/library/urllib.html" rel="nofollow">urllib</a> (simple but a bit rough) and <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> (powerful but a bit more complicated) are the recommended standard library modules for grabbing data from a URL (either to memor...
3
2009-09-27T02:08:05Z
[ "python", "image" ]
Grab an image via the web and save it with Python
1,482,600
<p>I want to be able to download an image (to my computer or to a web server) resize it, and upload it to S3. The piece concerned here is:</p> <p>What would be a recommended way to do the downloading portion within Python (i.e., don't want to use external tools, bash, etc). I want it to be stored into memory until it'...
1
2009-09-27T02:00:00Z
1,483,826
<p><del>You could always have a look at <a href="http://code.google.com/p/hand/" rel="nofollow">hand</a>.</del></p> <p><del>If I remember correctly, it was written to grab cartoons from sites that don't have feeds</del></p> <p>This project seems to have died, so it's no longer an option. Anyway, using <code>urllib</c...
0
2009-09-27T15:59:14Z
[ "python", "image" ]
Creating tables with pylons and SQLAlchemy
1,482,627
<p>I'm using SQLAlchemy and I can create tables that I have defined in /model/__init__.py but I have defined my classes, tables and their mappings in other files found in the /model directory. </p> <p>For example I have a profile class and a profile table which are defined and mapped in /model/profile.py</p> <p>To cr...
3
2009-09-27T02:19:52Z
1,483,061
<p>Just import your other table's modules in your <strong>init</strong>.py, and use metadata object from models.meta in other files. Pylons default setup_app function creates all tables found in metadata object from model.meta after importing it.</p>
0
2009-09-27T07:53:32Z
[ "python", "sqlalchemy", "pylons" ]
Creating tables with pylons and SQLAlchemy
1,482,627
<p>I'm using SQLAlchemy and I can create tables that I have defined in /model/__init__.py but I have defined my classes, tables and their mappings in other files found in the /model directory. </p> <p>For example I have a profile class and a profile table which are defined and mapped in /model/profile.py</p> <p>To cr...
3
2009-09-27T02:19:52Z
1,485,719
<p>If you are using declarative style, be sure to use Base.meta for tables generation.</p>
0
2009-09-28T06:41:27Z
[ "python", "sqlalchemy", "pylons" ]
Creating tables with pylons and SQLAlchemy
1,482,627
<p>I'm using SQLAlchemy and I can create tables that I have defined in /model/__init__.py but I have defined my classes, tables and their mappings in other files found in the /model directory. </p> <p>For example I have a profile class and a profile table which are defined and mapped in /model/profile.py</p> <p>To cr...
3
2009-09-27T02:19:52Z
1,528,312
<p>I ran into the same problem with my first real Pylons project. The solution that worked for me was this:</p> <ol> <li>Define tables and classes in your profile.py file</li> <li>In your <code>__init__.py</code> add <code>from profile import *</code> after your <code>def init_model</code></li> <li>I then added all o...
4
2009-10-06T21:55:48Z
[ "python", "sqlalchemy", "pylons" ]
Any way to use a tuple as key in a shelf? (Python)
1,482,631
<p>I want to use a tuple (1,2,3) as a key using the shelve module in Python. I can do this with dictionaries:</p> <pre><code>d = {} d[(1,2,3)] = 4 </code></pre> <p>But if i try it with shelve:</p> <pre><code>s = shelve.open('myshelf') s[(1,2,3)] = 4 </code></pre> <p>I get: "TypeError: String or Integer object expe...
4
2009-09-27T02:24:31Z
1,482,642
<p>How about using the repr() of the tuple:</p> <pre><code>s[repr((1,2,3))] = 4 </code></pre>
5
2009-09-27T02:30:28Z
[ "python", "shelve" ]
Any way to use a tuple as key in a shelf? (Python)
1,482,631
<p>I want to use a tuple (1,2,3) as a key using the shelve module in Python. I can do this with dictionaries:</p> <pre><code>d = {} d[(1,2,3)] = 4 </code></pre> <p>But if i try it with shelve:</p> <pre><code>s = shelve.open('myshelf') s[(1,2,3)] = 4 </code></pre> <p>I get: "TypeError: String or Integer object expe...
4
2009-09-27T02:24:31Z
1,482,658
<p>As per the <a href="http://docs.python.org/library/shelve.html?highlight=shelf#shelve.Shelf">docs</a>, </p> <blockquote> <p>the values <strong>(not the keys!)</strong> in a shelf can be essentially arbitrary Python objects</p> </blockquote> <p>My emphasis: shelf keys must be strings, period. So, you need to ...
6
2009-09-27T02:41:22Z
[ "python", "shelve" ]
Any way to use a tuple as key in a shelf? (Python)
1,482,631
<p>I want to use a tuple (1,2,3) as a key using the shelve module in Python. I can do this with dictionaries:</p> <pre><code>d = {} d[(1,2,3)] = 4 </code></pre> <p>But if i try it with shelve:</p> <pre><code>s = shelve.open('myshelf') s[(1,2,3)] = 4 </code></pre> <p>I get: "TypeError: String or Integer object expe...
4
2009-09-27T02:24:31Z
1,482,718
<p>Why not stick with dictionaries if you want to have arbitray keys ? The other option is to build a wrapper class around your tuple with a <strong>repr</strong> or <strong>str</strong> method to change it to a string. I am thinking of a library(natural response to shelves) - your tuple can be the elements in the <a h...
1
2009-09-27T03:24:21Z
[ "python", "shelve" ]
Python return without " ' "
1,482,649
<p>In Python, how do you return a variable like:</p> <pre><code>function(x): return x </code></pre> <p>Without the <code>'x'</code> (<code>'</code>) being around the <code>x</code>? </p>
4
2009-09-27T02:37:26Z
1,482,660
<p>In the Python interactive prompt, if you return a string, it will be <em>displayed</em> with quotes around it, mainly so that you know it's a string.</p> <p>If you just <em>print</em> the string, it will not be shown with quotes (unless the string <em>has</em> quotes in it).</p> <pre><code>&gt;&gt;&gt; 1 # just a ...
16
2009-09-27T02:42:29Z
[ "python" ]
Python return without " ' "
1,482,649
<p>In Python, how do you return a variable like:</p> <pre><code>function(x): return x </code></pre> <p>Without the <code>'x'</code> (<code>'</code>) being around the <code>x</code>? </p>
4
2009-09-27T02:37:26Z
1,482,661
<p>Here's one way that will remove all the single quotes in a string.</p> <pre><code>def remove(x): return x.replace("'", "") </code></pre> <p>Here's another alternative that will remove the first and last character.</p> <pre><code>def remove2(x): return x[1:-1] </code></pre>
-2
2009-09-27T02:42:40Z
[ "python" ]
Python return without " ' "
1,482,649
<p>In Python, how do you return a variable like:</p> <pre><code>function(x): return x </code></pre> <p>Without the <code>'x'</code> (<code>'</code>) being around the <code>x</code>? </p>
4
2009-09-27T02:37:26Z
33,089,740
<p>Remove single quotes around a string. </p> <pre><code> print str(x) </code></pre>
0
2015-10-12T20:33:51Z
[ "python" ]
List of Lists in python?
1,482,967
<p>I need a good function to do this in python.</p> <pre><code>def foo(n): # do somthing return list_of_lists &gt;&gt; foo(6) [[1], [2,3], [4,5,6]] &gt;&gt; foot(10) [[1], [2,3], [4,5,6] [7,8,9,10]] </code></pre>
1
2009-09-27T07:01:18Z
1,482,982
<pre><code>def foo(n): lol = [ [] ] i = 1 for x in range(n): if len(lol[-1]) &gt;= i: i += 1 lol.append([]) lol[-1].append(x) return lol </code></pre>
9
2009-09-27T07:10:17Z
[ "python", "list", "list-comprehension" ]
List of Lists in python?
1,482,967
<p>I need a good function to do this in python.</p> <pre><code>def foo(n): # do somthing return list_of_lists &gt;&gt; foo(6) [[1], [2,3], [4,5,6]] &gt;&gt; foot(10) [[1], [2,3], [4,5,6] [7,8,9,10]] </code></pre>
1
2009-09-27T07:01:18Z
1,483,006
<pre><code>def foo(n): i = 1 while i &lt;= n: last = int(i * 1.5 + 1) yield range(i, last) i = last list(foo(3)) </code></pre> <p>What behavior do you expect when you use a number for <code>n</code> that doesn't work, like 9?</p>
8
2009-09-27T07:20:57Z
[ "python", "list", "list-comprehension" ]
List of Lists in python?
1,482,967
<p>I need a good function to do this in python.</p> <pre><code>def foo(n): # do somthing return list_of_lists &gt;&gt; foo(6) [[1], [2,3], [4,5,6]] &gt;&gt; foot(10) [[1], [2,3], [4,5,6] [7,8,9,10]] </code></pre>
1
2009-09-27T07:01:18Z
1,483,052
<p>One more, just for fun:</p> <pre><code>def lol(n): entries = range(1,n+1) i, out = 1, [] while len(entries) &gt; i: out.append( [entries.pop(0) for x in xrange(i)] ) i += 1 return out + [entries] </code></pre> <p>(This doesn't rely on the underlying list having the numbers 1..n)</p>...
1
2009-09-27T07:47:59Z
[ "python", "list", "list-comprehension" ]
List of Lists in python?
1,482,967
<p>I need a good function to do this in python.</p> <pre><code>def foo(n): # do somthing return list_of_lists &gt;&gt; foo(6) [[1], [2,3], [4,5,6]] &gt;&gt; foot(10) [[1], [2,3], [4,5,6] [7,8,9,10]] </code></pre>
1
2009-09-27T07:01:18Z
1,483,130
<p>Adapted from gs's answer but without the mysterious "1.5".</p> <pre><code>def foo(n): i = c = 1 while i &lt;= n: yield range(i, i + c) i += c c += 1 list(foo(10)) </code></pre>
5
2009-09-27T08:46:45Z
[ "python", "list", "list-comprehension" ]
List of Lists in python?
1,482,967
<p>I need a good function to do this in python.</p> <pre><code>def foo(n): # do somthing return list_of_lists &gt;&gt; foo(6) [[1], [2,3], [4,5,6]] &gt;&gt; foot(10) [[1], [2,3], [4,5,6] [7,8,9,10]] </code></pre>
1
2009-09-27T07:01:18Z
1,483,150
<p>This is probably not a case where list comprehensions are appropriate, but I don't care!</p> <pre><code>from math import ceil, sqrt, max def tri(n): return n*(n+1) // 2 def irt(x): return int(ceil((-1 + sqrt(1 + 8*x)) / 2)) def foo(n): return [list(range(tri(i)+1, min(tri(i+1)+1, n+1))) for i in rang...
3
2009-09-27T09:01:23Z
[ "python", "list", "list-comprehension" ]
List of Lists in python?
1,482,967
<p>I need a good function to do this in python.</p> <pre><code>def foo(n): # do somthing return list_of_lists &gt;&gt; foo(6) [[1], [2,3], [4,5,6]] &gt;&gt; foot(10) [[1], [2,3], [4,5,6] [7,8,9,10]] </code></pre>
1
2009-09-27T07:01:18Z
1,483,931
<p>Here's my python golf entry:</p> <pre><code>&gt;&gt;&gt; def foo(n): ... def lower(i): return 1 + (i*(i-1)) // 2 ... def upper(i): return i + lower(i) ... import math ... x = (math.sqrt(1 + 8*n) - 1) // 2 ... return [list(range(lower(i), upper(i))) for i in range(1, x+1)] ... &gt;&gt;&gt; &gt;&...
1
2009-09-27T16:53:02Z
[ "python", "list", "list-comprehension" ]
Why MySQLdb for Mac has to have MySQL installed to install?
1,483,024
<p>I been working on finding out how to install MySQLdb module for Python on Mac. And all pathes finally come cross to have MySQL installed since there is a mysql_config needed for the module. But I don't understand why it has to be needed? </p> <p>MySQLdb suppose to be a client module for the client who wants to conn...
1
2009-09-27T07:31:28Z
1,483,030
<p>I'm not sure about the specifics of MySQLdb, but most likely it needs header information to compile/install. It uses the location of mysql_config to know where the appropriate headers would be. The MySQL Gem for Ruby on Rails requires the same thing, even though it simply connects to the MySQL server.</p>
1
2009-09-27T07:34:28Z
[ "python", "mysql" ]
Why MySQLdb for Mac has to have MySQL installed to install?
1,483,024
<p>I been working on finding out how to install MySQLdb module for Python on Mac. And all pathes finally come cross to have MySQL installed since there is a mysql_config needed for the module. But I don't understand why it has to be needed? </p> <p>MySQLdb suppose to be a client module for the client who wants to conn...
1
2009-09-27T07:31:28Z
1,483,154
<p>What it needs is the client library and headers that come with the server, since it just a Python wrapper (which sits in <code>_mysql.c</code>; and DB-API interface to that wrapper in <code>MySQLdb</code> package) over original C MySQL API.</p>
1
2009-09-27T09:03:10Z
[ "python", "mysql" ]
Why MySQLdb for Mac has to have MySQL installed to install?
1,483,024
<p>I been working on finding out how to install MySQLdb module for Python on Mac. And all pathes finally come cross to have MySQL installed since there is a mysql_config needed for the module. But I don't understand why it has to be needed? </p> <p>MySQLdb suppose to be a client module for the client who wants to conn...
1
2009-09-27T07:31:28Z
1,483,157
<p>MySQLdb is <em>not</em> a client module per se. It is a wrapper or interface between Python programs and the standard MySQL client libraries. MySQLdb conforms to the <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">Python standard DB API</a>. There are other conforming adapters implemented for othe...
1
2009-09-27T09:04:33Z
[ "python", "mysql" ]
Why MySQLdb for Mac has to have MySQL installed to install?
1,483,024
<p>I been working on finding out how to install MySQLdb module for Python on Mac. And all pathes finally come cross to have MySQL installed since there is a mysql_config needed for the module. But I don't understand why it has to be needed? </p> <p>MySQLdb suppose to be a client module for the client who wants to conn...
1
2009-09-27T07:31:28Z
1,483,305
<p>Just to clarify what the other answerers have said: you don't need to install a MySQL <em>server</em>, but you <strong>do</strong> need to install the MySQL <em>client</em> libraries. However, for whatever reasons, MySQL don't make a separate download available for just the client libraries, as they do for Linux.</p...
1
2009-09-27T10:41:04Z
[ "python", "mysql" ]
Why MySQLdb for Mac has to have MySQL installed to install?
1,483,024
<p>I been working on finding out how to install MySQLdb module for Python on Mac. And all pathes finally come cross to have MySQL installed since there is a mysql_config needed for the module. But I don't understand why it has to be needed? </p> <p>MySQLdb suppose to be a client module for the client who wants to conn...
1
2009-09-27T07:31:28Z
1,514,131
<p>Just to complete the fine answers, here's a small how-to for installing MySQLdb on MacOS X 10.6. This was posted <a href="http://blog.some-abstract-type.com/2009/09/mysql-python-and-mac-os-x-106-snow.html" rel="nofollow">on my blog</a> and you might check that out for maybe more info (and links as I'm a new user on ...
3
2009-10-03T15:58:52Z
[ "python", "mysql" ]
Auto create next Key in python dictionary
1,483,058
<p>Is there an easy way to create dictionary like associative array in php? in php i can do:</p> <pre><code>&gt; $x='a'; &gt; while($x&lt;d){ &gt; $arr[]['Letter']=$x; &gt; $x++ &gt; } </code></pre> <p>The interpreter adds automatically a new number into empty brackets "[]" so i can access letter <code>b...
0
2009-09-27T07:50:56Z
1,483,082
<p>Edit: I'm stupid. Of course there is a way of doing this in Python. Like so:</p> <pre><code>result = [{'Letter': chr(i+97)} for i in range(26)] </code></pre> <p>That will give you a List. Which can be indexed with a number. So <code>result[1]['Letter']</code> will give you <code>'b'</code>.</p>
3
2009-09-27T08:09:53Z
[ "python" ]
Auto create next Key in python dictionary
1,483,058
<p>Is there an easy way to create dictionary like associative array in php? in php i can do:</p> <pre><code>&gt; $x='a'; &gt; while($x&lt;d){ &gt; $arr[]['Letter']=$x; &gt; $x++ &gt; } </code></pre> <p>The interpreter adds automatically a new number into empty brackets "[]" so i can access letter <code>b...
0
2009-09-27T07:50:56Z
1,483,084
<p>Empty-brackets indexing is syntactically invalid in Python, but you could conceivably program a class that takes e.g. <code>[None]</code> as a signal to add one more key with a dict as its value and an incremented integer as the key. Before I make the substantial effort to program such a class, I'd love to understa...
3
2009-09-27T08:10:56Z
[ "python" ]
Auto create next Key in python dictionary
1,483,058
<p>Is there an easy way to create dictionary like associative array in php? in php i can do:</p> <pre><code>&gt; $x='a'; &gt; while($x&lt;d){ &gt; $arr[]['Letter']=$x; &gt; $x++ &gt; } </code></pre> <p>The interpreter adds automatically a new number into empty brackets "[]" so i can access letter <code>b...
0
2009-09-27T07:50:56Z
1,483,124
<p>Already mentioned that Python doesn't support it by default. </p> <p>You can achieve that effect by using the length of the dictionary, like this:</p> <pre><code>&gt;&gt;&gt; arr = {'letter':{1:'a'}} &gt;&gt;&gt; arr {'letter': {1: 'a'}} &gt;&gt;&gt; arr['letter'][len(arr['letter'])+1] = 'b' &gt;&gt;&gt; arr['let...
0
2009-09-27T08:42:16Z
[ "python" ]
Auto create next Key in python dictionary
1,483,058
<p>Is there an easy way to create dictionary like associative array in php? in php i can do:</p> <pre><code>&gt; $x='a'; &gt; while($x&lt;d){ &gt; $arr[]['Letter']=$x; &gt; $x++ &gt; } </code></pre> <p>The interpreter adds automatically a new number into empty brackets "[]" so i can access letter <code>b...
0
2009-09-27T07:50:56Z
1,483,126
<p>In python lists and dictionaries are distinct types. PHP has the one type to rule them all the associative array.</p> <p>I think what you want to do above translates into a list of dictionaries in python, like this</p> <pre><code>x = [ dict(Letter=chr(i)) for i in range(ord('a'),ord('f')) ] </code></pre> <p>If y...
2
2009-09-27T08:44:03Z
[ "python" ]
decypher with me that obfuscated MultiplierFactory
1,483,085
<p>This week on comp.lang.python, an "interesting" piece of code was <a href="http://groups.google.com/group/comp.lang.python/msg/fbd486398fcff81b" rel="nofollow">posted</a> by Steven D'Aprano as a joke answer to an homework question. Here it is:</p> <pre><code>class MultiplierFactory(object): def __init__(self, f...
2
2009-09-27T08:11:24Z
1,483,137
<p>Q1. Can we always access attributes in this fashion?</p> <p>A: No. It's only those attributes who start with double underscores. They get obfuscated in that way, to prevent accidental access/overriding from outside the class.</p> <p>Q2: Are we just changing the default value for factor argument in <code>__init__</...
1
2009-09-27T08:49:53Z
[ "python", "obfuscation", "python-datamodel" ]
regex for character appearing at most once
1,483,108
<p>I want to check a string that contains the period, ".", at most once in python. </p>
2
2009-09-27T08:34:58Z
1,483,116
<p>While period is special char it must be escaped. So "\.+" should work.</p> <p>EDIT:</p> <p>Use '?' instead of '+' to match one or zero repetitions. Have a look at: <a href="http://docs.python.org/library/re.html" rel="nofollow">re — Regular expression operations</a></p>
0
2009-09-27T08:37:32Z
[ "python", "regex" ]
regex for character appearing at most once
1,483,108
<p>I want to check a string that contains the period, ".", at most once in python. </p>
2
2009-09-27T08:34:58Z
1,483,117
<pre><code>[^.]*\.?[^.]*$ </code></pre> <p>And be sure to <code>match</code>, don't <code>search</code></p> <pre><code>&gt;&gt;&gt; dot = re.compile("[^.]*\.[^.]*$") &gt;&gt;&gt; dot.match("fooooooooooooo.bar") &lt;_sre.SRE_Match object at 0xb7651838&gt; &gt;&gt;&gt; dot.match("fooooooooooooo.bar.sad") is None True &...
7
2009-09-27T08:37:37Z
[ "python", "regex" ]
regex for character appearing at most once
1,483,108
<p>I want to check a string that contains the period, ".", at most once in python. </p>
2
2009-09-27T08:34:58Z
1,483,120
<p>You can use:</p> <pre><code>re.search('^[^.]*\.?[^.]*$', 'this.is') != None &gt;&gt;&gt; re.search('^[^.]*\.?[^.]*$', 'thisis') != None True &gt;&gt;&gt; re.search('^[^.]*\.?[^.]*$', 'this.is') != None True &gt;&gt;&gt; re.search('^[^.]*\.?[^.]*$', 'this..is') != None False </code></pre> <p>(Matches period zero o...
2
2009-09-27T08:38:44Z
[ "python", "regex" ]
regex for character appearing at most once
1,483,108
<p>I want to check a string that contains the period, ".", at most once in python. </p>
2
2009-09-27T08:34:58Z
1,483,122
<p>If the period should exist only once in the entire string, then use the <code>?</code> operator:</p> <pre><code>^[^.]*\.?[^.]*$ </code></pre> <p>Breaking this down:</p> <ol> <li><code>^</code> matches the beginning of the string</li> <li><code>[^.]</code> matches zero or more characters that are not periods</li> ...
0
2009-09-27T08:39:49Z
[ "python", "regex" ]
regex for character appearing at most once
1,483,108
<p>I want to check a string that contains the period, ".", at most once in python. </p>
2
2009-09-27T08:34:58Z
1,483,156
<p>No regexp is needed, see <a href="http://docs.python.org/library/stdtypes.html#str.count" rel="nofollow"><code>str.count()</code></a>:</p> <blockquote> <p><code>str.count(sub[, start[, end]])</code></p> <p>Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional a...
5
2009-09-27T09:03:58Z
[ "python", "regex" ]
regex for character appearing at most once
1,483,108
<p>I want to check a string that contains the period, ".", at most once in python. </p>
2
2009-09-27T08:34:58Z
1,483,236
<p>Why do you need to check? If you have a number in a string, I now guess you will want to handle it as a number soon. Perhaps you can do this without <em>Looking Before You Leap</em>:</p> <pre><code>try: value = float(input_str) except ValueError: ... else: ... </code></pre>
0
2009-09-27T10:05:10Z
[ "python", "regex" ]
How to split data into equal size packets having variable header size..
1,483,243
<p>I am building peer to peer application in python. Its going to work over UDP. I have function called <code>getHeader(packetNo,totalPackets)</code> which returns me the header for that packet.Depending on size of header I am chopping data, attaching data to header and getting same packet size.</p> <p>Header size is ...
0
2009-09-27T10:06:57Z
1,483,258
<p>Don't use plain-text. Make packet's header a two packed 4-byte (or 8-byte, depending on how many packets you expect) integers, e.g.</p> <pre><code>import struct header = struct.pack('!II', packetNo, totalPackets) </code></pre> <p><a href="http://docs.python.org/library/struct.html" rel="nofollow">Here's documentat...
2
2009-09-27T10:14:06Z
[ "python", "sockets", "udp", "packets" ]
How to split data into equal size packets having variable header size..
1,483,243
<p>I am building peer to peer application in python. Its going to work over UDP. I have function called <code>getHeader(packetNo,totalPackets)</code> which returns me the header for that packet.Depending on size of header I am chopping data, attaching data to header and getting same packet size.</p> <p>Header size is ...
0
2009-09-27T10:06:57Z
1,483,359
<p>Why not zero-pad your number of packets, so that the header becomes fixed. Say you want to support 1 billion packets in a message:</p> <pre><code>PACKET_NO=0000000001 </code></pre> <p>is the same length as:</p> <pre><code>PACKET_NO=1000000000 </code></pre> <p>Of course, this will create an upper bound on the po...
0
2009-09-27T11:13:41Z
[ "python", "sockets", "udp", "packets" ]
How to draw a class's metaclass in UML?
1,483,273
<p>If class A is created by its __metaclass M, how does the arrow look in UML?</p> <p>The <a href="http://etutorials.org/Programming/Learning+uml/Part+IV+Beyond+the+Unified+Modeling+Language/Chapter+9.+Extension+Mechanisms/9.2+Stereotypes/" rel="nofollow">stereotype</a> syntax seems to be related.</p> <p>I didn't loo...
1
2009-09-27T10:22:26Z
1,483,312
<p>I would draw a dependency with the stereotype «metaclass». This is not a predefined stereotype, but should make it clear to the read what kind of dependency this is.</p>
0
2009-09-27T10:43:17Z
[ "python", "uml", "metadata" ]
How to draw a class's metaclass in UML?
1,483,273
<p>If class A is created by its __metaclass M, how does the arrow look in UML?</p> <p>The <a href="http://etutorials.org/Programming/Learning+uml/Part+IV+Beyond+the+Unified+Modeling+Language/Chapter+9.+Extension+Mechanisms/9.2+Stereotypes/" rel="nofollow">stereotype</a> syntax seems to be related.</p> <p>I didn't loo...
1
2009-09-27T10:22:26Z
1,483,637
<p>A metaclass is drawn using the class notation plus the <code>&lt;&lt;metaclass&gt;&gt;</code> stereotype. The relationship between a class and its metaclass can be defined using a dependency relationship between the two (dashed line with the arrow pointing to the metaclass) annotated with the stereotype <code>&lt;&l...
2
2009-09-27T14:06:00Z
[ "python", "uml", "metadata" ]
How to draw a class's metaclass in UML?
1,483,273
<p>If class A is created by its __metaclass M, how does the arrow look in UML?</p> <p>The <a href="http://etutorials.org/Programming/Learning+uml/Part+IV+Beyond+the+Unified+Modeling+Language/Chapter+9.+Extension+Mechanisms/9.2+Stereotypes/" rel="nofollow">stereotype</a> syntax seems to be related.</p> <p>I didn't loo...
1
2009-09-27T10:22:26Z
1,489,804
<p>This answer is from the <a href="http://www.omg.org/cgi-bin/doc?formal/2009-02-02.pdf" rel="nofollow">UML 2.2 Superstructure Specification</a>:</p> <p>More class answer: "For instance, the «create» keyword can appear next to an operation name to indicate that it is a constructor operation, and it can also be used...
1
2009-09-28T23:07:53Z
[ "python", "uml", "metadata" ]
How to except SyntaxError?
1,483,343
<p>I would like to except the error the following code produces, but I don't know how.</p> <pre><code>from datetime import datetime try: date = datetime(2009, 12a, 31) except: print "error" </code></pre> <p>The code above is not printing <code>"error"</code>. That's what I would like to be able to do.</p> <...
2
2009-09-27T11:04:20Z
1,483,367
<p>If you want to check command-line parameters, you could also use <a href="http://code.google.com/p/argparse/" rel="nofollow"><code>argparse</code></a> or <a href="http://docs.python.org/library/optparse.html" rel="nofollow"><code>optparse</code></a>, they will handle the syntax check for you.</p>
3
2009-09-27T11:16:03Z
[ "python", "exception-handling" ]
How to except SyntaxError?
1,483,343
<p>I would like to except the error the following code produces, but I don't know how.</p> <pre><code>from datetime import datetime try: date = datetime(2009, 12a, 31) except: print "error" </code></pre> <p>The code above is not printing <code>"error"</code>. That's what I would like to be able to do.</p> <...
2
2009-09-27T11:04:20Z
1,483,373
<p>You can't catch syntax errors because the source must be valid before it can be executed. I am not quite sure, why you can't simple fix the syntax error, but if the line with the datetime is generated automatically from user input (?) and you must be able to catch those errors, you might try:</p> <pre><code>try: ...
2
2009-09-27T11:19:15Z
[ "python", "exception-handling" ]
How to except SyntaxError?
1,483,343
<p>I would like to except the error the following code produces, but I don't know how.</p> <pre><code>from datetime import datetime try: date = datetime(2009, 12a, 31) except: print "error" </code></pre> <p>The code above is not printing <code>"error"</code>. That's what I would like to be able to do.</p> <...
2
2009-09-27T11:04:20Z
1,483,450
<p>command-line "parameters" are strings. if your code is:</p> <pre><code>datetime(2009, '12a', 31) </code></pre> <p>it won't produce <code>SyntaxError</code>. It raises <code>TypeError</code>.</p> <p>All command-line parameters are needed to be cleaned up first, before use in your code. for example like this:</p> ...
9
2009-09-27T11:57:05Z
[ "python", "exception-handling" ]
Why can't I crop this image in Python PIL? (simple syntax problem?)
1,483,393
<pre><code>from PIL import Image im = Image.open(f) #the size is 500x350 box = (0,0,100,100) kay = im.crop(box) </code></pre> <p>It seems like there's nothing wrong with this, right?</p> <p>That last line will result in an error and won't continue, but I don't know what the error is because it's AJAX and I can't de...
1
2009-09-27T11:27:55Z
1,483,406
<p>Try using integer coordinates instead of strings:</p> <pre><code>from PIL import Image im = Image.open(f) #the size is 500x350 box = (0,0,100,100) kay = im.crop(box) </code></pre>
0
2009-09-27T11:39:50Z
[ "python", "image", "python-imaging-library" ]
Why can't I crop this image in Python PIL? (simple syntax problem?)
1,483,393
<pre><code>from PIL import Image im = Image.open(f) #the size is 500x350 box = (0,0,100,100) kay = im.crop(box) </code></pre> <p>It seems like there's nothing wrong with this, right?</p> <p>That last line will result in an error and won't continue, but I don't know what the error is because it's AJAX and I can't de...
1
2009-09-27T11:27:55Z
1,483,540
<p>If your controller is dealing with strings because the crop data is coming in via an ajax GET, it might be worth trying to make them into integers before applying the crop. Example from my terminal...</p> <pre><code>Trinity:~ kelvin$ python Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Compute...
4
2009-09-27T13:02:59Z
[ "python", "image", "python-imaging-library" ]
Why can't I crop this image in Python PIL? (simple syntax problem?)
1,483,393
<pre><code>from PIL import Image im = Image.open(f) #the size is 500x350 box = (0,0,100,100) kay = im.crop(box) </code></pre> <p>It seems like there's nothing wrong with this, right?</p> <p>That last line will result in an error and won't continue, but I don't know what the error is because it's AJAX and I can't de...
1
2009-09-27T11:27:55Z
1,483,679
<p>When you pick up the co-ordinates from the AJAX get request they are strings, you have to parse them to Int for the crop to succeed.</p>
1
2009-09-27T14:27:47Z
[ "python", "image", "python-imaging-library" ]
How to print an error in Python?
1,483,429
<pre><code>try: something here except: print 'the whatever error occurred.' </code></pre> <p>How can I print the error in my <code>except:</code> block?</p>
118
2009-09-27T11:48:19Z
1,483,447
<p>In case you want to pass error strings, here is an example from <a href="http://docs.python.org/tutorial/errors.html">Errors and Exceptions</a> (Python 2.6)</p> <pre><code>&gt;&gt;&gt; try: ... raise Exception('spam', 'eggs') ... except Exception as inst: ... print type(inst) # the exception instance ... ...
23
2009-09-27T11:56:30Z
[ "python", "error-handling", "exception-handling" ]
How to print an error in Python?
1,483,429
<pre><code>try: something here except: print 'the whatever error occurred.' </code></pre> <p>How can I print the error in my <code>except:</code> block?</p>
118
2009-09-27T11:48:19Z
1,483,488
<pre><code>except Exception,e: print str(e) </code></pre>
191
2009-09-27T12:19:27Z
[ "python", "error-handling", "exception-handling" ]
How to print an error in Python?
1,483,429
<pre><code>try: something here except: print 'the whatever error occurred.' </code></pre> <p>How can I print the error in my <code>except:</code> block?</p>
118
2009-09-27T11:48:19Z
1,483,494
<p><a href="http://docs.python.org/library/traceback.html"><code>traceback</code></a> module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:</p> <pre><code>except: traceback.print_exc() </code></pre>
56
2009-09-27T12:25:48Z
[ "python", "error-handling", "exception-handling" ]
How to print an error in Python?
1,483,429
<pre><code>try: something here except: print 'the whatever error occurred.' </code></pre> <p>How can I print the error in my <code>except:</code> block?</p>
118
2009-09-27T11:48:19Z
1,483,798
<p>One liner error raising can be done with assert statements if that's what you want to do. This will help you write statically fixable code and check errors early.</p> <pre><code> assert type(A) is type(""), "requires a string" </code></pre>
2
2009-09-27T15:38:09Z
[ "python", "error-handling", "exception-handling" ]
How to print an error in Python?
1,483,429
<pre><code>try: something here except: print 'the whatever error occurred.' </code></pre> <p>How can I print the error in my <code>except:</code> block?</p>
118
2009-09-27T11:48:19Z
1,483,909
<p>In <strong>Python 2.6 or greater</strong> it's a bit cleaner:</p> <pre><code>except Exception as e: print(e) </code></pre> <p>In older versions it's still quite readable:</p> <pre><code>except Exception, e: print e </code></pre>
74
2009-09-27T16:42:53Z
[ "python", "error-handling", "exception-handling" ]
django model Form. Include fields from related models
1,483,647
<p>I have a model, called Student, which has some fields, and a OneToOne relationship with user (django.contrib.auth.User).</p> <pre><code>class Student(models.Model): phone = models.CharField(max_length = 25 ) birthdate = models.DateField(null=True) gender = models.CharField(max_length=1,choices = GENDE...
10
2009-09-27T14:12:12Z
1,483,958
<p>I'm not sure this is what you want, but you can take a look at the <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets" rel="nofollow">documentation for Inline Formsets</a></p>
2
2009-09-27T17:04:09Z
[ "python", "django", "django-forms" ]
django model Form. Include fields from related models
1,483,647
<p>I have a model, called Student, which has some fields, and a OneToOne relationship with user (django.contrib.auth.User).</p> <pre><code>class Student(models.Model): phone = models.CharField(max_length = 25 ) birthdate = models.DateField(null=True) gender = models.CharField(max_length=1,choices = GENDE...
10
2009-09-27T14:12:12Z
1,486,758
<p>Both answers are correct: Inline Formsets make doing this easy.</p> <p>Be aware, however, that the inline can only go one way: from the model that has the foreign key in it. Without having primary keys in both (bad, since you could then have A -> B and then B -> A2), you cannot have the inline formset in the relat...
5
2009-09-28T12:27:22Z
[ "python", "django", "django-forms" ]
python _+ django, is it compiled code?
1,483,685
<p>Just looking into python from a .net background.</p> <p>Is python compiled like .net? If yes, can it be obfuscated and is it more or less secure than .net compiled code that is obfuscated?</p> <p>does pretty much every web host (unix) support django and python?</p>
1
2009-09-27T14:31:51Z
1,483,713
<p>I don't know about the security part but.</p> <ul> <li>Python is interpreted. Like PHP. (It's turned into bytecode which CPython reads)</li> <li>Django is just a <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29" rel="nofollow">framework</a> on top of Python.</li> <li><a href="http://effbot.org/z...
2
2009-09-27T14:46:16Z
[ "python" ]
python _+ django, is it compiled code?
1,483,685
<p>Just looking into python from a .net background.</p> <p>Is python compiled like .net? If yes, can it be obfuscated and is it more or less secure than .net compiled code that is obfuscated?</p> <p>does pretty much every web host (unix) support django and python?</p>
1
2009-09-27T14:31:51Z
1,483,720
<p>Obfuscation is false security. And the only thing worse than no security is false security. Why would you obfuscate a web app anyways?</p> <p>Python is compiled to bytecode and run on a virtual machine, but usually distributed as source code.</p> <p>Unless you really plan to run your webapp on "pretty much every w...
1
2009-09-27T14:48:45Z
[ "python" ]
python _+ django, is it compiled code?
1,483,685
<p>Just looking into python from a .net background.</p> <p>Is python compiled like .net? If yes, can it be obfuscated and is it more or less secure than .net compiled code that is obfuscated?</p> <p>does pretty much every web host (unix) support django and python?</p>
1
2009-09-27T14:31:51Z
1,483,789
<p>The Python is interpreted language. But you can compile the python program into a Unix executable using <a href="http://wiki.python.org/moin/Freeze" rel="nofollow">Freeze</a>.</p>
-1
2009-09-27T15:30:44Z
[ "python" ]
python _+ django, is it compiled code?
1,483,685
<p>Just looking into python from a .net background.</p> <p>Is python compiled like .net? If yes, can it be obfuscated and is it more or less secure than .net compiled code that is obfuscated?</p> <p>does pretty much every web host (unix) support django and python?</p>
1
2009-09-27T14:31:51Z
1,483,820
<p>You shouldn't have to worry about obfuscating your code, specially since it's going to run on your server.</p> <p>You are not supposed to put your code in a public directory anyway. The right thing to do with django (as oposed to PHP) is to make the code accessible by the webserver, but not by the public.</p> <p>A...
2
2009-09-27T15:55:20Z
[ "python" ]
python _+ django, is it compiled code?
1,483,685
<p>Just looking into python from a .net background.</p> <p>Is python compiled like .net? If yes, can it be obfuscated and is it more or less secure than .net compiled code that is obfuscated?</p> <p>does pretty much every web host (unix) support django and python?</p>
1
2009-09-27T14:31:51Z
1,483,828
<p>There are many implementations of the Python language; the three that are certainly solid, mature and complete enough for production use are <a href="http://en.wikipedia.org/wiki/CPython">CPython</a>, <a href="http://www.codeplex.com/IronPython">IronPython</a>, and <a href="http://www.jython.org/">Jython</a>. All of...
8
2009-09-27T16:00:39Z
[ "python" ]
python _+ django, is it compiled code?
1,483,685
<p>Just looking into python from a .net background.</p> <p>Is python compiled like .net? If yes, can it be obfuscated and is it more or less secure than .net compiled code that is obfuscated?</p> <p>does pretty much every web host (unix) support django and python?</p>
1
2009-09-27T14:31:51Z
1,483,846
<p>Code obfuscation in .NET are mostly a question of changing variable names to make it harder to understand the disassembled code. Yes, you can do those techniques with CPython too.</p> <p>Now, why ever you would <em>want</em> to is another question completely. It doesn't actually provide you with any security, and d...
0
2009-09-27T16:13:01Z
[ "python" ]
Get offset of current buffer in vim (in particular, via python scripting)
1,483,796
<p>i want to get the offset of </p> <ol> <li>the current cursor position</li> <li>the current selection range</li> </ol> <p>in vim, beginning from the start of the file. I do this in python, so hints how to do it with vim's python scripting would be very helpful. </p> <p>I have used vim.current.. before for doing sc...
11
2009-09-27T15:36:59Z
1,483,948
<p>If your vim is compiled with the <a href="http://www.vim.org/htmldoc/various.html#+byte%5Foffset"><code>+byte_offset</code></a> option, then in a Python script after the usual <code>import vim</code>, you can use, e.g.:</p> <pre><code>vim.eval('line2byte(line("."))+col(".")') </code></pre> <p>to get the byte offse...
13
2009-09-27T16:59:18Z
[ "python", "offset", "vim" ]
Get offset of current buffer in vim (in particular, via python scripting)
1,483,796
<p>i want to get the offset of </p> <ol> <li>the current cursor position</li> <li>the current selection range</li> </ol> <p>in vim, beginning from the start of the file. I do this in python, so hints how to do it with vim's python scripting would be very helpful. </p> <p>I have used vim.current.. before for doing sc...
11
2009-09-27T15:36:59Z
1,484,076
<p>You may also want to look at the <code>statusline</code> setting. This will add the bye offset to the statusline:</p> <pre><code>set statusline+=%o </code></pre> <p>See <code>:h statusline</code></p> <p>Just be careful because the default statusline is blank, and by appending the %o to it, you loose all the defa...
10
2009-09-27T18:01:40Z
[ "python", "offset", "vim" ]
Path to current file depends on how I execute the program
1,483,827
<p>This is my Python program:</p> <pre><code>#!/usr/bin/env python import os BASE_PATH = os.path.dirname(__file__) print BASE_PATH </code></pre> <p>If I run this using <code>python myfile.py</code> it prints an empty string. If I run it using <code>myfile.py</code>, it prints the correct path. Why is this? I'm usin...
5
2009-09-27T15:59:43Z
1,483,832
<p>It's just a harmless windows quirk; you can compensate by using <code>os.path.abspath(__file__)</code>, see <a href="http://docs.python.org/library/os.path.html?highlight=os.path#os.path.abspath">the docs</a></p>
8
2009-09-27T16:03:30Z
[ "python", "path" ]
Path to current file depends on how I execute the program
1,483,827
<p>This is my Python program:</p> <pre><code>#!/usr/bin/env python import os BASE_PATH = os.path.dirname(__file__) print BASE_PATH </code></pre> <p>If I run this using <code>python myfile.py</code> it prints an empty string. If I run it using <code>myfile.py</code>, it prints the correct path. Why is this? I'm usin...
5
2009-09-27T15:59:43Z
1,485,986
<pre><code>os.path.normpath(os.path.join(os.getcwd(),os.path.dirname(__file__))) </code></pre>
0
2009-09-28T08:32:20Z
[ "python", "path" ]
Path to current file depends on how I execute the program
1,483,827
<p>This is my Python program:</p> <pre><code>#!/usr/bin/env python import os BASE_PATH = os.path.dirname(__file__) print BASE_PATH </code></pre> <p>If I run this using <code>python myfile.py</code> it prints an empty string. If I run it using <code>myfile.py</code>, it prints the correct path. Why is this? I'm usin...
5
2009-09-27T15:59:43Z
19,599,167
<p>In many cases it's better to use:</p> <pre><code>os.path.dirname(sys.argv[0]) </code></pre>
0
2013-10-25T20:46:46Z
[ "python", "path" ]
Python Script to find instances of a set of strings in a set of files
1,483,830
<p>I have a file which I use to centralize all strings used in my application. Lets call it Strings.txt;</p> <pre><code>TITLE="Title" T_AND_C="Accept my terms and conditions please" START_BUTTON="Start" BACK_BUTTON="Back" ... </code></pre> <p>This helps me with I18n, the issue is that my application is now a lot larg...
1
2009-09-27T16:02:19Z
1,483,841
<p>You might consider using <a href="http://github.com/petdance/ack" rel="nofollow">ack</a>.</p> <pre><code>% ack --java 'search_string' </code></pre> <p>This will search under the current directory.</p>
0
2009-09-27T16:09:20Z
[ "python", "find", "internationalization" ]
Python Script to find instances of a set of strings in a set of files
1,483,830
<p>I have a file which I use to centralize all strings used in my application. Lets call it Strings.txt;</p> <pre><code>TITLE="Title" T_AND_C="Accept my terms and conditions please" START_BUTTON="Start" BACK_BUTTON="Back" ... </code></pre> <p>This helps me with I18n, the issue is that my application is now a lot larg...
1
2009-09-27T16:02:19Z
1,483,848
<p>Assuming the files are of reasonable size (as source files will be) so you can easily read them in memory, and that you're looking for the parts in quotes right of the = signs:</p> <pre><code>import collections files_by_str = collections.defaultdict(list) thestrings = [] with open('Strings.txt') as f: for line i...
4
2009-09-27T16:13:23Z
[ "python", "find", "internationalization" ]