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/python2.4/site-packages/sqlite/main.py", line 280, in close if self.con and self.con.closed: ReferenceError: weakly-referenced object no longer exists </code></pre> <p>However, if I modify the code in the following way:</p> <pre><code>import sqlite x1 = sqlite.connect('tmp.db') x2 = x1.cursor() x3 = x2.close() </code></pre> <p>everything is fine. Why? </p>
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, your connection has been destructed.</p> <p>The second form avoids this by keeping a strong reference to your connection around the whole time.</p>
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 or the other.</p>
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 do. I suspect both languages will work for you.</p>
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 or the other.</p>
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 these days, so if you feel like you'd develop better with Python, have at it!</p> <hr> <p>In reply to comment (how can java be faster than Python):</p> <p>All languages are processed differently. Java is about the fastest after C &amp; C++ (which can be as fast or up to 5x faster than java, but seems to average around 2x faster). The rest are from 2-5+ times slower. Python is one of the faster ones after Java. I'm guessing that C# is about as fast as Java or maybe faster, but the benchmarksgame only had Mono (which was a tad slower) because they don't run it on windows.</p> <p>Most of these claims are based on the <a href="http://benchmarksgame.alioth.debian.org/" rel="nofollow">computer language benchmarks game</a> which tends to be pretty fair because advocates of/experts in each language tweak the test written in their specific language to ensure the code is well-targeted.</p> <p>For example, <a href="http://benchmarksgame.alioth.debian.org/u64q/compare.php?lang=java&amp;lang2=gpp" rel="nofollow">this</a> shows all tests with Java vs c++ and you can see the speed ranges from about equal to java being 3x slower (first column is between 1 and 3), and java uses much more memory!</p> <p>Now <a href="http://benchmarksgame.alioth.debian.org/u64q/python.html" rel="nofollow">this page</a> shows java vs python (from the point of view of Python). So the speeds range from python being 2x slower than Java to 174x slower, python generally beats java in code size and memory usage though.</p> <p>Another interesting point here--tests that allocated a lot of memory, Java actually performed significantly better than Python in memory size as well. I'm pretty sure java usually loses memory because of the overhead of the VM, but once that factors out, java is probably more efficient than most (again, except the C's).</p> <p>This is Python 3 by the way, the other python platform tested (Just called Python) faired much worse.</p> <p>If you really wanted to know <em>how</em> it is faster, the VM is amazingly intelligent. It compiles to machine language AFTER running the code, so it knows what the most likely code paths are and optimizes for them. Memory allocation is an art--really useful in an OO language. It can perform some amazing run-time optimizations which no non-VM language can do. It can run in a pretty small memory footprint when forced to, and is a language of choice for embedded devices along with C/C++.</p> <p>I worked on a Signal Analyzer for Agilent (think expensive o-scope) where nearly the entire thing (aside from the sampling) was done in Java. This includes drawing the screen including the trace (AWT) and interacting with the controls.</p> <p>Currently I'm working on a project for all future cable boxes. The Guide along with most other apps will be written in Java. </p> <p>Why wouldn't it be faster than Python? </p>
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 or the other.</p>
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 stream text - not binary - to your processes. Therefore your files needed to be text files, unless you do some funky encoding transformations yourself. But now it appears a <a href="https://issues.apache.org/jira/browse/HADOOP-1722">patch</a> has been added that now allows the use of binary formats with hadoop streaming.</p> <p>If you use a "custom jar" (i.e. you wrote your mapreduce code in Java or Scala using the hadoop libraries), then you will have access to functions that allow you to input and output binary (serialize in binary) from your streaming processes (and save the results to disk). So future runs will be much faster (depending on how much your binary format is smaller than your text format).</p> <p>So if your hadoop job is going to be I/O bound, then the "custom jar" approach will be faster (since both Java is faster as previous posters have shown and reading from disk will also be faster).</p> <p>But you have to ask yourself how valuable is your time. I find myself far more productive with python, and writing map-reduce that reads STDIN and writes to STDOUT is really straightforward. So I personally would recommend going the python route - even if you have to figure the binary encoding stuff out yourself. Since hadoop 0.21 handles non-utf8 byte arrays, and since there is a binary (byte array) alternative to use for python (<a href="http://dumbotics.com/2009/02/24/hadoop-1722-and-typed-bytes/">http://dumbotics.com/2009/02/24/hadoop-1722-and-typed-bytes/</a>), which shows the python code only being about 25% slower than the "custom jar" java code, I would definitely go the python route.</p>
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.from_iterable(combinations(s, r) for r in range(len(s)+1)) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; list(powerset("abcd")) [(), ('a',), ('b',), ('c',), ('d',), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd'), ('a', 'b', 'c', 'd')] </code></pre> <p>If you don't like that empty tuple at the beginning, you can just change the <code>range</code> statement to <code>range(1, len(s)+1)</code> to avoid a 0-length combination.</p>
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] </code></pre> <p>Mark Rushakoff's comment is applicable here: "If you don't like that empty tuple at the beginning, on."you can just change the range statement to range(1, len(s)+1) to avoid a 0-length combination", except in my case you change "for i in range(1 &lt;&lt; x)" to "for i in range(1, 1 &lt;&lt; x)".</p> <hr> <p>Returning to this years later, I'd now write it like this:</p> <pre><code>def powerset(s): x = len(s) masks = [1 &lt;&lt; i for i in range(x)] for i in range(1 &lt;&lt; x): yield [ss for mask, ss in zip(masks, s) if i &amp; mask] </code></pre> <p>And then the test code would look like this, say:</p> <pre><code>print(list(powerset([4, 5, 6]))) </code></pre> <p>Using <code>yield</code> means that you do not need to calculate all results in a single piece of memory. Precalculating the masks outside the main loop is assumed to be a worthwhile optimization.</p>
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): """ Returns all the subsets of this set. This is a generator. """ if len(seq) &lt;= 1: yield seq yield [] else: for item in powerset(seq[1:]): yield [seq[0]]+item yield item </code></pre> <p>This can be used like this:</p> <pre><code> l = [1, 2, 3, 4] r = [x for x in powerset(l)] </code></pre> <p>Now r is a list of all the elements you wanted, and can be sorted and printed:</p> <pre><code>r.sort() print r [[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 4], [1, 3], [1, 3, 4], [1, 4], [2], [2, 3], [2, 3, 4], [2, 4], [3], [3, 4], [4]] </code></pre>
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 combo.append(list(combinations(items,r))) return combo l_powerset = powerset(l) for i, item in enumerate(l_powerset): print "All sets of length ", i print item </code></pre> <hr> <p><strong>The results</strong></p> <p>All sets of length 0</p> <p><code>[()]</code></p> <p>All sets of length 1</p> <p><code>[('x',), ('y',), ('z',)]</code></p> <p>All sets of length 2</p> <p><code>[('x', 'y'), ('x', 'z'), ('y', 'z')]</code></p> <p>All sets of length 3</p> <p><code>[('x', 'y', 'z')]</code></p> <p>For more <a href="http://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow">see the itertools docs</a>, also the wikipedia entry on <a href="http://en.wikipedia.org/wiki/Power_set#Example" rel="nofollow">power sets</a></p>
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 itertools recipe shown above""" from itertools import chain, combinations base_list = list( base_set ) combo_list = [ combinations(base_list, r) for r in range(len(base_set)+1) ] powerset = set([]) for ll in combo_list: list_of_frozensets = list( map( frozenset, map( list, ll ) ) ) set_of_frozensets = set( list_of_frozensets ) powerset = powerset.union( set_of_frozensets ) return powerset print powerset( test_set ) # &gt;&gt;&gt; set([ frozenset(['money','whatup']), frozenset(['money','whatup','yo']), # frozenset(['whatup']), frozenset(['whatup','yo']), frozenset(['yo']), # frozenset(['money','yo']), frozenset(['money']), frozenset([]) ]) </code></pre> <p>I'd love to see a better implementation, though.</p>
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>get_power_set([1,2,3]) </code></pre> <p>yield</p> <pre><code>[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] </code></pre>
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() currentSet = [] for combo in combinations: for i,val in enumerate(combo): if val=='1': currentSet.append(array[i]) sets.add(tuple(sorted(currentSet))) currentSet = [] return sets </code></pre>
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> <pre><code>for id in request.POST['id']: </code></pre> <p>even possible? </p> <p>I'm looking for the best accepted way.</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> <pre><code>for id in request.POST['id']: </code></pre> <p>even possible? </p> <p>I'm looking for the best accepted way.</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: // Logic here </code></pre>
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> <pre><code>for id in request.POST['id']: </code></pre> <p>even possible? </p> <p>I'm looking for the best accepted way.</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 formset to read the results.</p>
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> <pre><code>for id in request.POST['id']: </code></pre> <p>even possible? </p> <p>I'm looking for the best accepted way.</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 of the fields in the POST which start with 'uid' in a list.</p>
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> <pre><code>for id in request.POST['id']: </code></pre> <p>even possible? </p> <p>I'm looking for the best accepted way.</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;&gt;&gt; q.getlist('a') ['1', '2'] </code></pre>
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 remote serial access to the boxes.)</p> <p>Basically, a client established a Telnet or SSH connection to the daemon. The daemon passes the client's input out (for example) /dev/ttyS0, and passes input from ttyS0 back out to the client. However, I want to be able to blacklist certain strings coming from the client. For instance, the command 'delete foo' should not be allowed.</p> <p>I'm not sure how best to approach this. Communication must be asynchronous; I can't simply wait for a carriage return to allow the buffer to be fed out the serial interface. Matching regular expressions against the stream seems tricky too, as all of the following must be intercepted:</p> <pre><code>delete foo(enter) del foo(enter) el foo(ctrl+a)d(enter) dl(left)e(right) foo(enter) </code></pre> <p>...and so forth. The only solid delimiter is the CR/LF.</p> <p>I'm hoping someone can point me in the right direction. I've been looking through Python modules but so far haven't come up with anything.</p>
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 malicious possibilities and guarding against all of them. </p>
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 remote serial access to the boxes.)</p> <p>Basically, a client established a Telnet or SSH connection to the daemon. The daemon passes the client's input out (for example) /dev/ttyS0, and passes input from ttyS0 back out to the client. However, I want to be able to blacklist certain strings coming from the client. For instance, the command 'delete foo' should not be allowed.</p> <p>I'm not sure how best to approach this. Communication must be asynchronous; I can't simply wait for a carriage return to allow the buffer to be fed out the serial interface. Matching regular expressions against the stream seems tricky too, as all of the following must be intercepted:</p> <pre><code>delete foo(enter) del foo(enter) el foo(ctrl+a)d(enter) dl(left)e(right) foo(enter) </code></pre> <p>...and so forth. The only solid delimiter is the CR/LF.</p> <p>I'm hoping someone can point me in the right direction. I've been looking through Python modules but so far haven't come up with anything.</p>
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", and apply the "edit" requests (such as the ctrl-a, left, right in your examples) to the data you're collecting, then you're left with the "completed command about to be sent" in memory where it can be matched and rejected or sent on.</p> <p>If you <strong>must</strong> do it character by character, <code>.read(1)</code> on the (unbuffered) input will allow you to, but the vetting becomes potentially more problematic; again you can keep an in-memory image of the edited command that you've sent so far (as you apply the edit requests even while sending them), but what happens when the "enter" arrives and your vetting shows you that the command thus composed must NOT be allowed -- can you e.g. send a number of "delete"s to the device to wipe away said command? Or is there a single "toss the complete line" edit request that would serve?</p> <p>If you must send every character as you receive it (not allowed to accumulate them until decision point) AND there is no way to delete/erase characters already sent, then the task appears to be impossible (though I don't understand the "can't wait for the enter" condition AT ALL, so maybe there's hope).</p>
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 remote serial access to the boxes.)</p> <p>Basically, a client established a Telnet or SSH connection to the daemon. The daemon passes the client's input out (for example) /dev/ttyS0, and passes input from ttyS0 back out to the client. However, I want to be able to blacklist certain strings coming from the client. For instance, the command 'delete foo' should not be allowed.</p> <p>I'm not sure how best to approach this. Communication must be asynchronous; I can't simply wait for a carriage return to allow the buffer to be fed out the serial interface. Matching regular expressions against the stream seems tricky too, as all of the following must be intercepted:</p> <pre><code>delete foo(enter) del foo(enter) el foo(ctrl+a)d(enter) dl(left)e(right) foo(enter) </code></pre> <p>...and so forth. The only solid delimiter is the CR/LF.</p> <p>I'm hoping someone can point me in the right direction. I've been looking through Python modules but so far haven't come up with anything.</p>
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 reliably. Thanks anyway for the input!</p>
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 remote serial access to the boxes.)</p> <p>Basically, a client established a Telnet or SSH connection to the daemon. The daemon passes the client's input out (for example) /dev/ttyS0, and passes input from ttyS0 back out to the client. However, I want to be able to blacklist certain strings coming from the client. For instance, the command 'delete foo' should not be allowed.</p> <p>I'm not sure how best to approach this. Communication must be asynchronous; I can't simply wait for a carriage return to allow the buffer to be fed out the serial interface. Matching regular expressions against the stream seems tricky too, as all of the following must be intercepted:</p> <pre><code>delete foo(enter) del foo(enter) el foo(ctrl+a)d(enter) dl(left)e(right) foo(enter) </code></pre> <p>...and so forth. The only solid delimiter is the CR/LF.</p> <p>I'm hoping someone can point me in the right direction. I've been looking through Python modules but so far haven't come up with anything.</p>
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 def fromstr(self, s): return float(s)/self.scale </code></pre> <p>The part that confuses me is this part</p> <pre><code>FormatFormatStr.__init__(self, '%%1.%df'%precision) </code></pre> <p>does this mean that the precision gets entered twice before the 1 and once before df? Does df stand for anything that you know of? I don't see it elsewhere even in its ancestors as can be seen here:</p> <pre><code>class FormatFormatStr(FormatObj): def __init__(self, fmt): self.fmt = fmt def tostr(self, x): if x is None: return 'None' return self.fmt%self.toval(x) class FormatObj: def tostr(self, x): return self.toval(x) def toval(self, x): return str(x) def fromstr(self, s): return s </code></pre> <p>also, I put this into my Ipython and get this:</p> <pre><code>In [53]: x = FormatFloat(.234324234325435) In [54]: x Out[54]: &lt;matplotlib.mlab.FormatFloat instance at 0x939d4ec&gt; </code></pre> <p>I figured that it would reduce precision to 4 and scale to 1. But instead it gets stored somewhere in my memory. Can I retrieve it to see what it does to the number?</p> <p>Thanks everyone you're very helpful!</p>
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 href="http://docs.python.org/library/string.html#formatstrings" rel="nofollow">More about string formatting in Python</a></p> <p>In order to use the <code>FormatFloat</code> class you might try something like this:</p> <pre><code>formatter = FormatFloat(precision = 4) print formatter.tostr(0.2345678) </code></pre>
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 def fromstr(self, s): return float(s)/self.scale </code></pre> <p>The part that confuses me is this part</p> <pre><code>FormatFormatStr.__init__(self, '%%1.%df'%precision) </code></pre> <p>does this mean that the precision gets entered twice before the 1 and once before df? Does df stand for anything that you know of? I don't see it elsewhere even in its ancestors as can be seen here:</p> <pre><code>class FormatFormatStr(FormatObj): def __init__(self, fmt): self.fmt = fmt def tostr(self, x): if x is None: return 'None' return self.fmt%self.toval(x) class FormatObj: def tostr(self, x): return self.toval(x) def toval(self, x): return str(x) def fromstr(self, s): return s </code></pre> <p>also, I put this into my Ipython and get this:</p> <pre><code>In [53]: x = FormatFloat(.234324234325435) In [54]: x Out[54]: &lt;matplotlib.mlab.FormatFloat instance at 0x939d4ec&gt; </code></pre> <p>I figured that it would reduce precision to 4 and scale to 1. But instead it gets stored somewhere in my memory. Can I retrieve it to see what it does to the number?</p> <p>Thanks everyone you're very helpful!</p>
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 prompt:</p> <pre><code>&gt;&gt;&gt; print "%%1.%df" % 5 '%1.5f' </code></pre> <p>The class <code>FormatFloat</code> doesn't define <code>__repr__</code>, <code>__str__</code>, or <code>__unicode__</code> (the "magic" methods used for type coercion) so when you just print the value in an interactive console, you get the standard representation of instances. To get the string value, you would call the <code>tostr()</code> method (defined on the parent class):</p> <pre><code>&gt;&gt;&gt; ff = FormatFloat(.234324234325435) &gt;&gt;&gt; ff.tostr() 0.234 </code></pre>
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 def fromstr(self, s): return float(s)/self.scale </code></pre> <p>The part that confuses me is this part</p> <pre><code>FormatFormatStr.__init__(self, '%%1.%df'%precision) </code></pre> <p>does this mean that the precision gets entered twice before the 1 and once before df? Does df stand for anything that you know of? I don't see it elsewhere even in its ancestors as can be seen here:</p> <pre><code>class FormatFormatStr(FormatObj): def __init__(self, fmt): self.fmt = fmt def tostr(self, x): if x is None: return 'None' return self.fmt%self.toval(x) class FormatObj: def tostr(self, x): return self.toval(x) def toval(self, x): return str(x) def fromstr(self, s): return s </code></pre> <p>also, I put this into my Ipython and get this:</p> <pre><code>In [53]: x = FormatFloat(.234324234325435) In [54]: x Out[54]: &lt;matplotlib.mlab.FormatFloat instance at 0x939d4ec&gt; </code></pre> <p>I figured that it would reduce precision to 4 and scale to 1. But instead it gets stored somewhere in my memory. Can I retrieve it to see what it does to the number?</p> <p>Thanks everyone you're very helpful!</p>
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 def who_referred(cls): for referer in Referer.all(): obj = referer.target </code></pre> <p>This last line is giving an error likeso:</p> <pre><code>No implementation for kind 'Base' </code></pre> <p>Traceback is likeso:</p> <pre><code>&gt;&gt;&gt; object = referer.target /usr/local/google_appengine/google/appengine/ext/db/__init__.py in __get__:2804 /usr/local/google_appengine/google/appengine/ext/db/__init__.py in get:1179 /usr/local/google_appengine/google/appengine/ext/db/__init__.py in class_for_kind:220 </code></pre> <p>Does anyone have any idea what's going on here? The expected behavior would be, obviously, that no error be thrown.</p> <p>It may be relevant that Base and Referer are in separate files (and not imported). </p> <p>This problem may be somewhat related to <a href="http://stackoverflow.com/questions/1412210/python-decorate-a-class-to-change-parent-object-type">Python decorate a class to change parent object type</a>, which is a question which still lurks in the back of my mind.</p> <p>Thank you for reading.</p>
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 large to convert to int </code></pre> <p>Python 3.x:</p> <pre><code>&gt;&gt;&gt; N = 10**100 &gt;&gt;&gt; r = range(N) &gt;&gt;&gt; r = range(N, N+10) &gt;&gt;&gt; len(r) 10 </code></pre> <p>Is there a backport of py3k builtin <code>range()</code> function for Python 2.x?</p> <h3>Edit</h3> <p>I'm looking for a complete implementation of "lazy" <code>range()</code>, not just a partial implementation of some of its functionality. </p>
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 in functions written in C, depending on how they're written.</p>
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 large to convert to int </code></pre> <p>Python 3.x:</p> <pre><code>&gt;&gt;&gt; N = 10**100 &gt;&gt;&gt; r = range(N) &gt;&gt;&gt; r = range(N, N+10) &gt;&gt;&gt; len(r) 10 </code></pre> <p>Is there a backport of py3k builtin <code>range()</code> function for Python 2.x?</p> <h3>Edit</h3> <p>I'm looking for a complete implementation of "lazy" <code>range()</code>, not just a partial implementation of some of its functionality. </p>
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 native C long. If a larger range is needed, an alternate version can be crafted using the itertools module: islice(count(start, step), (stop-start+step-1)//step).</p> </blockquote> <p>Alternatively reimplement xrange using generators:</p> <pre><code>def myxrange(a1, a2=None, step=1): if a2 is None: start, last = 0, a1 else: start, last = a1, a2 while cmp(start, last) == cmp(0, step): yield start start += step </code></pre> <p>and</p> <pre><code>N = 10**100 len(list(myxrange(N, N+10))) </code></pre>
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 large to convert to int </code></pre> <p>Python 3.x:</p> <pre><code>&gt;&gt;&gt; N = 10**100 &gt;&gt;&gt; r = range(N) &gt;&gt;&gt; r = range(N, N+10) &gt;&gt;&gt; len(r) 10 </code></pre> <p>Is there a backport of py3k builtin <code>range()</code> function for Python 2.x?</p> <h3>Edit</h3> <p>I'm looking for a complete implementation of "lazy" <code>range()</code>, not just a partial implementation of some of its functionality. </p>
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: proceed = operator.gt else: proceed = operator.lt while proceed(start, stop): yield start start += step </code></pre> <p><strong>Edit</strong> it appears the OP doesn't just want looping (the normal purpose of xrange, and range in Py3), but also <code>len</code> and the <code>in</code> operator (the latter does work on the above generator, but slowly -- optimizations are possible). For such richness a class is better...:</p> <pre><code>import operator class wowrange(object): def __init__(self, start, stop=None, step=1): if step == 0: raise ValueError('step must be != 0') if stop is None: start, stop = 0, start if step &lt; 0: self.proceed = operator.gt self.l = (stop-start+step+1)//step else: self.proceed = operator.lt self.l = (stop-start+step-1)//step self.lo = min(start, stop) self.start, self.stop, self.step = start, stop, step def __iter__(self): start = self.start while self.proceed(start, self.stop): yield start start += self.step def __len__(self): return self.l def __contains__(self, x): if x == self.stop: return False if self.proceed(x, self.start): return False if self.proceed(self.stop, x): return False return (x-self.lo) % self.step == 0 </code></pre> <p>I wouldn't be surprised if there's an off-by-one or similar glitch lurking here, but, I hope this helps!</p> <p><strong>Edit</strong> again: I see indexing is ALSO required. Is it just too hard to write your own <code>__getitem__</code>? I guess it is, so here it, too, is, served on a silver plate...:</p> <pre><code> def __getitem__(self, i): if i &lt; 0: i += self.l if i &lt; 0: raise IndexError elif if i &gt;= self.l: raise IndexError return self.start + i * self.step </code></pre> <p>I don't know if 3.0 <code>range</code> supports slicing (<code>xrange</code> in recent <code>2.*</code> releases doesn't -- it used to, but that was removed because the complication was ridiculous and prone to bugs), but I guess I do have to draw a line in the sand somewhere, so I'm not going to add it;-).</p>
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 large to convert to int </code></pre> <p>Python 3.x:</p> <pre><code>&gt;&gt;&gt; N = 10**100 &gt;&gt;&gt; r = range(N) &gt;&gt;&gt; r = range(N, N+10) &gt;&gt;&gt; len(r) 10 </code></pre> <p>Is there a backport of py3k builtin <code>range()</code> function for Python 2.x?</p> <h3>Edit</h3> <p>I'm looking for a complete implementation of "lazy" <code>range()</code>, not just a partial implementation of some of its functionality. </p>
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 - (a2 - a1) % step if cmp(a1, a2) != cmp(0, step): a2 = a1 self.start, self.stop, self.step = a1, a2, step def __iter__(self): n = self.start while cmp(n, self.stop) == cmp(0, self.step): yield n n += self.step def __repr__(self): return "MyXRange(%d,%d,%d)" % (self.start, self.stop, self.step) # NB: len(self) will convert this to an int, and may fail def __len__(self): return (self.stop - self.start)//(self.step) def __getitem__(self, key): if key &lt; 0: key = self.__len__() + key if key &lt; 0: raise IndexError("list index out of range") return self[key] n = self.start + self.step*key if cmp(n, self.stop) != cmp(0, self.step): raise IndexError("list index out of range") return n def __reversed__(self): return MyXRange(self.stop-self.step, self.start-self.step, -self.step) def __contains__(self, val): if val == self.start: return cmp(0, self.step) == cmp(self.start, self.stop) if cmp(self.start, val) != cmp(0, self.step): return False if cmp(val, self.stop) != cmp(0, self.step): return False return (val - self.start) % self.step == 0 </code></pre> <p>And some testing:</p> <pre><code>def testMyXRange(testsize=10): def normexcept(f,args): try: r = [f(args)] except Exception, e: r = type(e) return r for i in range(-testsize,testsize+1): for j in range(-testsize,testsize+1): print i, j for k in range(-9, 10, 2): r, mr = range(i,j,k), MyXRange(i,j,k) if r != list(mr): print "iter fail: %d, %d, %d" % (i,j,k) if list(reversed(r)) != list(reversed(mr)): print "reversed fail: %d, %d, %d" % (i,j,k) if len(r) != len(mr): print "len fail: %d, %d, %d" % (i,j,k) z = [m for m in range(-testsize*2,testsize*2+1) if (m in r) != (m in mr)] if z != []: print "contains fail: %d, %d, %d, %s" % (i,j,k,(z+["..."])[:10]) z = [m for m in range(-testsize*2, testsize*2+1) if normexcept(r.__getitem__, m) != normexcept(mr.__getitem__, m)] if z != []: print "getitem fail: %d, %d, %d, %s" % (i,j,k,(z+["..."])[:10]) </code></pre>
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 large to convert to int </code></pre> <p>Python 3.x:</p> <pre><code>&gt;&gt;&gt; N = 10**100 &gt;&gt;&gt; r = range(N) &gt;&gt;&gt; r = range(N, N+10) &gt;&gt;&gt; len(r) 10 </code></pre> <p>Is there a backport of py3k builtin <code>range()</code> function for Python 2.x?</p> <h3>Edit</h3> <p>I'm looking for a complete implementation of "lazy" <code>range()</code>, not just a partial implementation of some of its functionality. </p>
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" rel="nofollow">xrange.py</a></p> <h3>Edit</h3> <p>The latest version of <code>irange</code> (renamed as <code>lrange</code>) is at <a href="http://github.com/zed/lrange/" rel="nofollow">github</a>.</p> <p><hr /></p> <p>Implementation based on py3k's <a href="http://svn.python.org/view/python/branches/py3k/Objects/rangeobject.c?view=markup" rel="nofollow">rangeobject.c</a></p> <h3>irange.py</h3> <pre><code>"""Define `irange.irange` class `xrange`, py3k's `range` analog for large integers See help(irange.irange) &gt;&gt;&gt; r = irange(2**100, 2**101, 2**100) &gt;&gt;&gt; len(r) 1 &gt;&gt;&gt; for i in r: ... print i, 1267650600228229401496703205376 &gt;&gt;&gt; for i in r: ... print i, 1267650600228229401496703205376 &gt;&gt;&gt; 2**100 in r True &gt;&gt;&gt; r[0], r[-1] (1267650600228229401496703205376L, 1267650600228229401496703205376L) &gt;&gt;&gt; L = list(r) &gt;&gt;&gt; L2 = [1, 2, 3] &gt;&gt;&gt; L2[:] = r &gt;&gt;&gt; L == L2 == [2**100] True """ def toindex(arg): """Convert `arg` to integer type that could be used as an index. """ if not any(isinstance(arg, cls) for cls in (long, int, bool)): raise TypeError("'%s' object cannot be interpreted as an integer" % ( type(arg).__name__,)) return int(arg) class irange(object): """irange([start,] stop[, step]) -&gt; irange object Return an iterator that generates the numbers in the range on demand. Return `xrange` for small integers Pure Python implementation of py3k's `range()`. (I.e. it supports large integers) If `xrange` and py3k `range()` differ then prefer `xrange`'s behaviour Based on `[1]`_ .. [1] http://svn.python.org/view/python/branches/py3k/Objects/rangeobject.c?view=markup &gt;&gt;&gt; # on Python 2.6 &gt;&gt;&gt; N = 10**80 &gt;&gt;&gt; len(range(N, N+3)) 3 &gt;&gt;&gt; len(xrange(N, N+3)) Traceback (most recent call last): ... OverflowError: long int too large to convert to int &gt;&gt;&gt; len(irange(N, N+3)) 3 &gt;&gt;&gt; xrange(N) Traceback (most recent call last): ... OverflowError: long int too large to convert to int &gt;&gt;&gt; irange(N).length() == N True """ def __new__(cls, *args): try: return xrange(*args) # use `xrange` for small integers except OverflowError: pass nargs = len(args) if nargs == 1: stop = toindex(args[0]) start = 0 step = 1 elif nargs in (2, 3): start = toindex(args[0]) stop = toindex(args[1]) if nargs == 3: step = args[2] if step is None: step = 1 step = toindex(step) if step == 0: raise ValueError("irange() arg 3 must not be zero") else: step = 1 else: raise ValueError("irange(): wrong number of arguments," + " got %s" % args) r = super(irange, cls).__new__(cls) r._start, r._stop, r._step = start, stop, step return r def length(self): """len(self) might throw OverflowError, this method shouldn't.""" if self._step &gt; 0: lo, hi = self._start, self._stop step = self._step else: hi, lo = self._start, self._stop step = -self._step assert step if lo &gt;= hi: return 0 else: return (hi - lo - 1) // step + 1 __len__ = length def __getitem__(self, i): # for L[:] = irange(..) if i &lt; 0: i = i + self.length() if i &lt; 0 or i &gt;= self.length(): raise IndexError("irange object index out of range") return self._start + i * self._step def __repr__(self): if self._step == 1: return "irange(%r, %r)" % (self._start, self._stop) else: return "irange(%r, %r, %r)" % ( self._start, self._stop, self._step) def __contains__(self, ob): if type(ob) not in (int, long, bool): # mimic py3k # perform iterative search return any(i == ob for i in self) # if long or bool if self._step &gt; 0: inrange = self._start &lt;= ob &lt; self._stop else: assert self._step inrange = self._stop &lt; ob &lt;= self._start if not inrange: return False else: return ((ob - self._start) % self._step) == 0 def __iter__(self): len_ = self.length() i = 0 while i &lt; len_: yield self._start + i * self._step i += 1 def __reversed__(self): len_ = self.length() new_start = self._start + (len_ - 1) * self._step new_stop = self._start if self._step &gt; 0: new_stop -= 1 else: new_stop += 1 return irange(new_start, new_stop, -self._step) </code></pre> <h3>test_irange.py</h3> <pre><code>"""Unit-tests for irange.irange class. Usage: $ python -W error test_irange.py --with-doctest --doctest-tests """ import sys from nose.tools import raises from irange import irange def eq_irange(a, b): """Assert that `a` equals `b`. Where `a`, `b` are `irange` objects """ try: assert a.length() == b.length() assert a._start == b._start assert a._stop == b._stop assert a._step == b._step if a.length() &lt; 100: assert list(a) == list(b) try: assert list(a) == range(a._start, a._stop, a._step) except OverflowError: pass except AttributeError: if type(a) == xrange: assert len(a) == len(b) if len(a) == 0: # empty xrange return if len(a) &gt; 0: assert a[0] == b[0] if len(a) &gt; 1: a = irange(a[0], a[-1], a[1] - a[0]) b = irange(b[0], b[-1], b[1] - b[0]) eq_irange(a, b) else: raise def _get_short_iranges_args(): # perl -E'local $,= q/ /; $n=100; for (1..20) # &gt; { say map {int(-$n + 2*$n*rand)} 0..int(3*rand) }' input_args = """\ 67 -11 51 -36 -15 38 19 43 -58 79 -91 -71 -56 3 51 -23 -63 -80 13 -30 24 -14 49 10 73 31 38 66 -22 20 -81 79 5 84 44 40 49 """ return [[int(arg) for arg in line.split()] for line in input_args.splitlines() if line.strip()] def _get_iranges_args(): N = 2**100 return [(start, stop, step) for start in range(-2*N, 2*N, N//2+1) for stop in range(-4*N, 10*N, N+1) for step in range(-N//2, N, N//8+1)] def _get_short_iranges(): return [irange(*args) for args in _get_short_iranges_args()] def _get_iranges(): return (_get_short_iranges() + [irange(*args) for args in _get_iranges_args()]) @raises(TypeError) def test_kwarg(): irange(stop=10) @raises(TypeError, DeprecationWarning) def test_float_stop(): irange(1.0) @raises(TypeError, DeprecationWarning) def test_float_step2(): irange(-1, 2, 1.0) @raises(TypeError, DeprecationWarning) def test_float_start(): irange(1.0, 2) @raises(TypeError, DeprecationWarning) def test_float_step(): irange(1, 2, 1.0) @raises(TypeError) def test_empty_args(): irange() def test_empty_range(): for args in ( "-3", "1 3 -1", "1 1", "1 1 1", "-3 -4", "-3 -2 -1", "-3 -3 -1", "-3 -3", ): r = irange(*[int(a) for a in args.split()]) assert len(r) == 0 L = list(r) assert len(L) == 0 def test_small_ints(): for args in _get_short_iranges_args(): ir, r = irange(*args), xrange(*args) assert len(ir) == len(r) assert list(ir) == list(r) def test_big_ints(): N = 10**100 for args, len_ in [ [(N,), N], [(N, N+10), 10], [(N, N-10, -2), 5], ]: try: xrange(*args) assert 0 except OverflowError: pass ir = irange(*args) assert ir.length() == len_ try: assert ir.length() == len(ir) except OverflowError: pass # ir[ir.length()-1] # if len(args) &gt;= 2: r = range(*args) assert list(ir) == r assert ir[ir.length()-1] == r[-1] assert list(reversed(ir)) == list(reversed(r)) # def test_negative_index(): assert irange(10)[-1] == 9 assert irange(2**100+1)[-1] == 2**100 def test_reversed(): for r in _get_iranges(): if type(r) == xrange: continue # known not to work for xrange if r.length() &gt; 1000: continue # skip long assert list(reversed(reversed(r))) == list(r) assert list(r) == range(r._start, r._stop, r._step) def test_pickle(): import pickle for r in _get_iranges(): rp = pickle.loads(pickle.dumps(r)) eq_irange(rp, r) def test_equility(): for args in _get_iranges_args(): a, b = irange(*args), irange(*args) assert a is not b assert a != b eq_irange(a, b) def test_contains(): class IntSubclass(int): pass r10 = irange(10) for i in range(10): assert i in r10 assert IntSubclass(i) in r10 assert 10 not in r10 assert -1 not in r10 assert IntSubclass(10) not in r10 assert IntSubclass(-1) not in r10 def test_repr(): for r in _get_iranges(): eq_irange(eval(repr(r)), r) def test_new(): assert repr(irange(True)) == repr(irange(1)) def test_overflow(): lo, hi = sys.maxint-2, sys.maxint+3 assert list(irange(lo, hi)) == list(range(lo, hi)) def test_getitem(): r = irange(sys.maxint-2, sys.maxint+3) L = [] L[:] = r assert len(L) == len(r) assert L == list(r) if __name__ == "__main__": import nose nose.main() </code></pre>
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 with Pygame 1.9.1 in Eclipse on Vista 64-bit. Thus, this is for windows systems. The <code>SetWindowPos</code> function is documented <a href="http://msdn.microsoft.com/en-us/library/ms633545%28VS.85%29.aspx">Here</a>. I will refer to this in my explanation.</p> <p>Imports:</p> <pre><code>from ctypes import windll </code></pre> <p>Then I set up a variable that calls the "SetWindowPos" in user32:</p> <pre><code>SetWindowPos = windll.user32.SetWindowPos </code></pre> <p>Now, let's say I just made a window:</p> <pre><code>screen = pygame.display.set_mode((100,100), pygame.NOFRAME) </code></pre> <p>The next line is the key. This sets the window to be on top of other windows.</p> <pre><code>SetWindowPos(pygame.display.get_wm_info()['window'], -1, x, y, 0, 0, 0x0001) </code></pre> <p>Basically, You supply the <code>hWnd</code>(Window Handle) with the window ID returned from a call to <code>display.get_wm_info()</code>. Now the function can edit the window you just initialized.</p> <p>The <code>-1</code> is our <code>hWndInsertAfter</code>.</p> <p>The MSDN site says:</p> <blockquote> <p>A window can be made a topmost window either by setting the hWndInsertAfter parameter to HWND_TOPMOST and ensuring that the SWP_NOZORDER flag is not set, or by setting a window's position in the Z order so that it is above any existing topmost windows. When a non-topmost window is made topmost, its owned windows are also made topmost. Its owners, however, are not changed.</p> </blockquote> <p>So, the <code>-1</code> makes sure the window is above any other existing topmost windows, but this may not work in all cases. Maybe a -2 beats a -1? It currently works for me. :)</p> <p>The <code>x</code> and <code>y</code> specify the new coordinates for the window being set. I wanted the window to stay at its current position when the <code>SetWindowPos</code> function was called on it. Alas, I couldn't find a way to easily pass the current window (x,y) position into the function. I was able to find a work around, but assume I shouldn't introduce a new topic into this question.</p> <p>The <code>0, 0,</code> are supposed to specify the new width and height of the window, in pixels. Well, that functionality is already in your <code>pygame.display.set_mode()</code> function, so I left them at 0. The <code>0x0001</code> ignores these parameters. </p> <p><code>0x0001</code> corresponds to SWP_NOSIZE and is my only uFlag. A list of all the available uFlags are on the provided documentation page. Some of their Hex representations are as follows:</p> <ul> <li>SWP_NOSIZE = 0x0001</li> <li>SWP_NOMOVE = 0x0002 </li> <li>SWP_NOZORDER = 0x0004</li> <li>SWP_NOREDRAW = 0x0008</li> <li>SWP_NOACTIVATE = 0x0010</li> <li>SWP_FRAMECHANGED = 0x0020</li> <li>SWP_SHOWWINDOW = 0x0040</li> <li>SWP_HIDEWINDOW = 0x0080</li> <li>SWP_NOCOPYBITS = 0x0100</li> <li>SWP_NOOWNERZORDER = 0x0200</li> <li>SWP_NOSENDCHANGING = 0x0400</li> </ul> <p>That should be it! Hope it works for you! </p> <p>Credit to John Popplewell at john@johnnypops.demon.co.uk for his help.</p>
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_transient_for(main_window) </code></pre> <p>You might also want to search things like "x11 always on top". The underlying concept seems to be that you're giving the window manager a "hint" that it should keep the window above the others. The window manager, however, has free reign and can do whatever it wants.</p> <p>I've also seen the concept of layers when using window managers like Fluxbox, so maybe there's a way to change the layer on which the window appears.</p>
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 with Pygame 1.9.1 in Eclipse on Vista 64-bit. Thus, this is for windows systems. The <code>SetWindowPos</code> function is documented <a href="http://msdn.microsoft.com/en-us/library/ms633545%28VS.85%29.aspx">Here</a>. I will refer to this in my explanation.</p> <p>Imports:</p> <pre><code>from ctypes import windll </code></pre> <p>Then I set up a variable that calls the "SetWindowPos" in user32:</p> <pre><code>SetWindowPos = windll.user32.SetWindowPos </code></pre> <p>Now, let's say I just made a window:</p> <pre><code>screen = pygame.display.set_mode((100,100), pygame.NOFRAME) </code></pre> <p>The next line is the key. This sets the window to be on top of other windows.</p> <pre><code>SetWindowPos(pygame.display.get_wm_info()['window'], -1, x, y, 0, 0, 0x0001) </code></pre> <p>Basically, You supply the <code>hWnd</code>(Window Handle) with the window ID returned from a call to <code>display.get_wm_info()</code>. Now the function can edit the window you just initialized.</p> <p>The <code>-1</code> is our <code>hWndInsertAfter</code>.</p> <p>The MSDN site says:</p> <blockquote> <p>A window can be made a topmost window either by setting the hWndInsertAfter parameter to HWND_TOPMOST and ensuring that the SWP_NOZORDER flag is not set, or by setting a window's position in the Z order so that it is above any existing topmost windows. When a non-topmost window is made topmost, its owned windows are also made topmost. Its owners, however, are not changed.</p> </blockquote> <p>So, the <code>-1</code> makes sure the window is above any other existing topmost windows, but this may not work in all cases. Maybe a -2 beats a -1? It currently works for me. :)</p> <p>The <code>x</code> and <code>y</code> specify the new coordinates for the window being set. I wanted the window to stay at its current position when the <code>SetWindowPos</code> function was called on it. Alas, I couldn't find a way to easily pass the current window (x,y) position into the function. I was able to find a work around, but assume I shouldn't introduce a new topic into this question.</p> <p>The <code>0, 0,</code> are supposed to specify the new width and height of the window, in pixels. Well, that functionality is already in your <code>pygame.display.set_mode()</code> function, so I left them at 0. The <code>0x0001</code> ignores these parameters. </p> <p><code>0x0001</code> corresponds to SWP_NOSIZE and is my only uFlag. A list of all the available uFlags are on the provided documentation page. Some of their Hex representations are as follows:</p> <ul> <li>SWP_NOSIZE = 0x0001</li> <li>SWP_NOMOVE = 0x0002 </li> <li>SWP_NOZORDER = 0x0004</li> <li>SWP_NOREDRAW = 0x0008</li> <li>SWP_NOACTIVATE = 0x0010</li> <li>SWP_FRAMECHANGED = 0x0020</li> <li>SWP_SHOWWINDOW = 0x0040</li> <li>SWP_HIDEWINDOW = 0x0080</li> <li>SWP_NOCOPYBITS = 0x0100</li> <li>SWP_NOOWNERZORDER = 0x0200</li> <li>SWP_NOSENDCHANGING = 0x0400</li> </ul> <p>That should be it! Hope it works for you! </p> <p>Credit to John Popplewell at john@johnnypops.demon.co.uk for his help.</p>
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 is upto the window manager to respect this setting or not.</p> <p><strong>Edited to include SDL specific stuff</strong> Pygame uses SDL to do display work and apprently does not play nice with <a href="http://www.pygame.org/wiki/gui">Windowing toolkits</a>. SDL Window can be put on top is discussed <a href="http://www.linuxquestions.org/questions/programming-9/how-to-make-a-sdl-window-always-on-top-188371/">here</a>.</p>
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 with Pygame 1.9.1 in Eclipse on Vista 64-bit. Thus, this is for windows systems. The <code>SetWindowPos</code> function is documented <a href="http://msdn.microsoft.com/en-us/library/ms633545%28VS.85%29.aspx">Here</a>. I will refer to this in my explanation.</p> <p>Imports:</p> <pre><code>from ctypes import windll </code></pre> <p>Then I set up a variable that calls the "SetWindowPos" in user32:</p> <pre><code>SetWindowPos = windll.user32.SetWindowPos </code></pre> <p>Now, let's say I just made a window:</p> <pre><code>screen = pygame.display.set_mode((100,100), pygame.NOFRAME) </code></pre> <p>The next line is the key. This sets the window to be on top of other windows.</p> <pre><code>SetWindowPos(pygame.display.get_wm_info()['window'], -1, x, y, 0, 0, 0x0001) </code></pre> <p>Basically, You supply the <code>hWnd</code>(Window Handle) with the window ID returned from a call to <code>display.get_wm_info()</code>. Now the function can edit the window you just initialized.</p> <p>The <code>-1</code> is our <code>hWndInsertAfter</code>.</p> <p>The MSDN site says:</p> <blockquote> <p>A window can be made a topmost window either by setting the hWndInsertAfter parameter to HWND_TOPMOST and ensuring that the SWP_NOZORDER flag is not set, or by setting a window's position in the Z order so that it is above any existing topmost windows. When a non-topmost window is made topmost, its owned windows are also made topmost. Its owners, however, are not changed.</p> </blockquote> <p>So, the <code>-1</code> makes sure the window is above any other existing topmost windows, but this may not work in all cases. Maybe a -2 beats a -1? It currently works for me. :)</p> <p>The <code>x</code> and <code>y</code> specify the new coordinates for the window being set. I wanted the window to stay at its current position when the <code>SetWindowPos</code> function was called on it. Alas, I couldn't find a way to easily pass the current window (x,y) position into the function. I was able to find a work around, but assume I shouldn't introduce a new topic into this question.</p> <p>The <code>0, 0,</code> are supposed to specify the new width and height of the window, in pixels. Well, that functionality is already in your <code>pygame.display.set_mode()</code> function, so I left them at 0. The <code>0x0001</code> ignores these parameters. </p> <p><code>0x0001</code> corresponds to SWP_NOSIZE and is my only uFlag. A list of all the available uFlags are on the provided documentation page. Some of their Hex representations are as follows:</p> <ul> <li>SWP_NOSIZE = 0x0001</li> <li>SWP_NOMOVE = 0x0002 </li> <li>SWP_NOZORDER = 0x0004</li> <li>SWP_NOREDRAW = 0x0008</li> <li>SWP_NOACTIVATE = 0x0010</li> <li>SWP_FRAMECHANGED = 0x0020</li> <li>SWP_SHOWWINDOW = 0x0040</li> <li>SWP_HIDEWINDOW = 0x0080</li> <li>SWP_NOCOPYBITS = 0x0100</li> <li>SWP_NOOWNERZORDER = 0x0200</li> <li>SWP_NOSENDCHANGING = 0x0400</li> </ul> <p>That should be it! Hope it works for you! </p> <p>Credit to John Popplewell at john@johnnypops.demon.co.uk for his help.</p>
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's done with (versus downloading the image to a local drive, and then working with it). Any help is much appreciated.</p>
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's done with (versus downloading the image to a local drive, and then working with it). Any help is much appreciated.</p>
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 are both part of Python's standard library. urllib is simple, urllib2 is more powerful but also more complicated.</p> <p>urllib example:</p> <pre><code>import urllib image = urllib.URLopener() image.urlretrieve("http://sstatic.net/so/img/logo.png") </code></pre> <p>In this case, the file is not stored in local memory, but rather as a temp file with a generated name.</p>
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's done with (versus downloading the image to a local drive, and then working with it). Any help is much appreciated.</p>
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 memory or to disk). For simple-enough needs, <code>x=urllib.urlopen(theurl)</code> will give you an object that lets you access the response headers (e.g. to find out the image's content-type) and data (as <code>x.read()</code>); <code>urllib2</code> works similarly but lets you control proxying, user agent, coockies, https, authentication, etc, etc, much more than simple <code>urllib</code> does.</p>
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's done with (versus downloading the image to a local drive, and then working with it). Any help is much appreciated.</p>
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</code> seems to be what you're looking for.</p>
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 create the tables I run: </p> <p>paster setup-app development.ini</p> <p>But my problem is that the tables that I have defined in /model/__init__.py are created properly but the table definitions found in /model/profile.py are not created. How can I execute the table definitions found in the /model/profile.py so that all my tables can be created?</p> <p>Thanks for the help!</p>
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 create the tables I run: </p> <p>paster setup-app development.ini</p> <p>But my problem is that the tables that I have defined in /model/__init__.py are created properly but the table definitions found in /model/profile.py are not created. How can I execute the table definitions found in the /model/profile.py so that all my tables can be created?</p> <p>Thanks for the help!</p>
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 create the tables I run: </p> <p>paster setup-app development.ini</p> <p>But my problem is that the tables that I have defined in /model/__init__.py are created properly but the table definitions found in /model/profile.py are not created. How can I execute the table definitions found in the /model/profile.py so that all my tables can be created?</p> <p>Thanks for the help!</p>
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 of my mapper definitions afterwards. Keeping them all in the init file solved some problems I was having relating between tables defined in different files.</li> </ol> <p>Also, I've since created projects using the declarative method and didn't need to define the mapping in the init file.</p>
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 expected for key, tuple found"</p> <p>Any suggestions? </p>
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 expected for key, tuple found"</p> <p>Any suggestions? </p>
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 turn your tuple into a str; depending on what you'll have in the tuple, <code>repr</code>, some <code>separator.join</code>, pickling, marshaling, etc, may be fruitfully employed for that purpose.</p>
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 expected for key, tuple found"</p> <p>Any suggestions? </p>
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 href="http://en.wikipedia.org/wiki/Dewey%5Fdecimal" rel="nofollow">Dewey decimal</a> and the <strong>str</strong> creates a concatenated complete representation.</p>
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 number, so no quotes 1 &gt;&gt;&gt; "hi" # just a string, displayed with quotes 'hi' &gt;&gt;&gt; print("hi") # being *printed* to the screen, so do not show quotes hi &gt;&gt;&gt; "'hello'" # string with embedded single quotes "'hello'" &gt;&gt;&gt; print("'hello'") # *printing* a string with embedded single quotes 'hello' </code></pre> <p>If you actually <em>do</em> need to <em>remove</em> leading/trailing quotation marks, use the <code>.strip</code> method of the string to remove single and/or double quotes:</p> <pre><code>&gt;&gt;&gt; print("""'"hello"'""") '"hello"' &gt;&gt;&gt; print("""'"hello"'""".strip('"\'')) hello </code></pre>
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 range(irt(n))] </code></pre>
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;&gt;&gt; for i in [1,3,6,10,15]: ... print i, foo(i) ... 1 [[1]] 3 [[1], [2, 3]] 6 [[1], [2, 3], [4, 5, 6]] 10 [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]] 15 [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14, 15]] &gt;&gt;&gt; </code></pre> <p>The calculation of x relies on solution of the quadratic equation with positive roots for</p> <pre><code>0 = y*y + y - 2*n </code></pre>
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 connect to the server. But now I have to first install a server on the client in order to connect to another server?</p>
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 connect to the server. But now I have to first install a server on the client in order to connect to another server?</p>
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 connect to the server. But now I have to first install a server on the client in order to connect to another server?</p>
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 other database managers. Using the common API makes it much easier to write database-independent code in Python; the adapters handle (much of) the messy differences among the various database client libraries. Thus, you do need to install MySQL client libraries; there are several ways to do this: the easiest options are probably downloading prebuilt libraries from mysql.com or you can use a package manager, like MacPorts, to install them and other dependencies.</p>
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 connect to the server. But now I have to first install a server on the client in order to connect to another server?</p>
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 connect to the server. But now I have to first install a server on the client in order to connect to another server?</p>
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 stackoverflow, can only add one).</p> <ul> <li>Download MySQL MacOS X 10.5 (x86_64) tar ball. For v10.5 currently, until there is one for MacOS X v10.6.</li> <li>Get a copy of MySQL-python (MySQLdb).</li> <li>Install the latest XCode tools found on the Snow Leopard CD under option installs or download it. You need it to compile.</li> </ul> <p>I'm not covering the installation of MySQL, but when you've done so, here's how you install MySQLdb.</p> <pre><code>shell&gt; PATH="/usr/local/mysql/bin:$PATH" shell&gt; tar xzf MySQL-python-1.2.3c1.tar.gz shell&gt; cd MySQL-python-1.2.3c1 shell&gt; ARCHFLAGS="-arch x86_64" /usr/bin/python setup.py build shell&gt; /usr/bin/python setup.py install </code></pre> <p>There is currently work done on MySQL Connector/Python. The is a pure Python implementation of the MySQL protocol so you don't need to install any MySQL software or compile to get you going.</p>
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</code> from <code>$arr[1]['Letter']</code>, etc.</p> <p>Is there a way to do same with python?</p>
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</code> from <code>$arr[1]['Letter']</code>, etc.</p> <p>Is there a way to do same with python?</p>
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 understand what real problem you're trying to solve that, e.g. a <code>collections.defaultdict</code> wouldn't address.</p>
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</code> from <code>$arr[1]['Letter']</code>, etc.</p> <p>Is there a way to do same with python?</p>
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['letter'][len(arr['letter'])+1] = 'c' &gt;&gt;&gt; arr['letter'][len(arr['letter'])+1] = 'd' &gt;&gt;&gt; arr {'letter': {1: 'a', 2: 'b', 3: 'c', 4: 'd'}} &gt;&gt;&gt; </code></pre>
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</code> from <code>$arr[1]['Letter']</code>, etc.</p> <p>Is there a way to do same with python?</p>
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 you try this in the interpreter</p> <pre><code>&gt;&gt;&gt; x = [ dict(Letter=chr(i)) for i in range(ord('a'),ord('f')) ] &gt;&gt;&gt; x [{'Letter': 'a'}, {'Letter': 'b'}, {'Letter': 'c'}, {'Letter': 'd'}, {'Letter': 'e'}] &gt;&gt;&gt; x[0] {'Letter': 'a'} &gt;&gt;&gt; x[1] {'Letter': 'b'} &gt;&gt;&gt; x[1]['Letter'] 'b' &gt;&gt;&gt; </code></pre> <p>Or if you prefer it written out in full without a list comprehension</p> <pre><code>x = [] for c in range(ord('a'),ord('f')): d = { 'Letter': chr(c) } x.append(d) </code></pre>
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, factor=1): self.__factor = factor @property def factor(self): return getattr(self, '_%s__factor' % self.__class__.__name__) def __call__(self, factor=None): if not factor is not None is True: factor = self.factor class Multiplier(object): def __init__(self, factor=None): self.__factor = factor @property def factor(self): return getattr(self, '_%s__factor' % self.__class__.__name__) def __call__(self, n): return self.factor*n Multiplier.__init__.im_func.func_defaults = (factor,) return Multiplier(factor) twice = MultiplierFactory(2)() </code></pre> <p>We know that <code>twice</code> is an equivalent to the answer:</p> <pre><code>def twice(x): return 2*x </code></pre> <p>From the names <code>Multiplier</code> and <code>MultiplierFactory</code> we get an idea of what's the code doing, but we're not sure of the exact internals. Let's simplify it first.</p> <h2>Logic</h2> <pre><code>if not factor is not None is True: factor = self.factor </code></pre> <p><code>not factor is not None is True</code> is equivalent to <code>not factor is not None</code>, which is also <code>factor is None</code>. Result:</p> <pre><code>if factor is None: factor = self.factor </code></pre> <p>Until now, that was easy :)</p> <h2>Attribute access</h2> <p>Another interesting point is the curious <code>factor</code> accessor.</p> <pre><code>def factor(self): return getattr(self, '_%s__factor' % self.__class__.__name__) </code></pre> <p>During initialization of <code>MultiplierFactory</code>, <code>self.__factor</code> is set. But later on, the code accesses <code>self.factor</code>.</p> <p>It then seems that:</p> <pre><code>getattr(self, '_%s__factor' % self.__class__.__name__) </code></pre> <p>Is doing exactly "<code>self.__factor</code>". </p> <p><strong><em>Can we always access attributes in this fashion?</em></strong></p> <pre><code>def mygetattr(self, attr): return getattr(self, '_%s%s' % (self.__class__.__name__, attr)) </code></pre> <h2>Dynamically changing function signatures</h2> <p>Anyway, at this point, here is the simplified code:</p> <pre><code>class MultiplierFactory(object): def __init__(self, factor=1): self.factor = factor def __call__(self, factor=None): if factor is None: factor = self.factor class Multiplier(object): def __init__(self, factor=None): self.factor = factor def __call__(self, n): return self.factor*n Multiplier.__init__.im_func.func_defaults = (factor,) return Multiplier(factor) twice = MultiplierFactory(2)() </code></pre> <p>Code is almost clean now. The only puzzling line, maybe, would be:</p> <pre><code>Multiplier.__init__.im_func.func_defaults = (factor,) </code></pre> <p>What's in there? I looked at the <a href="http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy" rel="nofollow">datamodel doc</a>, and found that <code>func_defaults</code> was "<em>A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value</em>". <strong><em>Are we just changing the default value for</em> <code>factor</code> <em>argument in</em> <code>__init__</code> <em>here?</em></strong> Resulting code would then be:</p> <pre><code>class MultiplierFactory(object): def __init__(self, factor=1): self.factor = factor def __call__(self, factor=None): if factor is None: factor = self.factor class Multiplier(object): def __init__(self, innerfactor=factor): self.factor = innerfactor def __call__(self, n): return self.factor*n return Multiplier(factor) twice = MultiplierFactory(2)() </code></pre> <p>Which means that dynamically setting the default value was just useless noise, since <code>Multiplier</code> is never called without a default parameter, <strong><em>right</em></strong>?</p> <p>And we could probably simplify it to:</p> <pre><code>class MultiplierFactory(object): def __init__(self, factor=1): self.factor = factor def __call__(self, factor=None): if factor is None: factor = self.factor def my_multiplier(n): return factor*n return my_multiplier twice = MultiplierFactory(2)() # similar to MultiplierFactory()(2) </code></pre> <p>Correct?</p> <p><em>And for those hurrying to "this is not a real question"... read again, my questions are in bold+italic</em></p>
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__</code> here?</p> <p>A: Yes.</p> <p>Q2: right?</p> <p>Right.</p>
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 &gt;&gt;&gt; </code></pre> <p><strong>Edit</strong>:</p> <p>If you consider only integers and decimals, it's even easier:</p> <pre><code>def valid(s): return re.match('[0-9]+(\.[0-9]*)?$', s) is not None assert valid("42") assert valid("13.37") assert valid("1.") assert not valid("1.2.3.4") assert not valid("abcd") </code></pre>
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 or one times.)</p>
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> <li><code>\.?</code> matches the period character (must be escaped with <code>\</code> as it's a reserved char) exactly 0 or 1 times</li> <li><code>[^.]*</code> is the same pattern used in 2 above</li> <li><code>$</code> matches the end of the string</li> </ol> <p>As an aside, personally I wouldn't use a regular expression for this (unless I was checking other aspects of the string for validity too). I would just use the count function.</p>
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 arguments start and end are interpreted as in slice notation.</p> </blockquote> <pre><code>&gt;&gt;&gt; "A.B.C.D".count(".") 3 &gt;&gt;&gt; "A/B.C/D".count(".") 1 &gt;&gt;&gt; "A/B.C/D".count(".") == 1 True &gt;&gt;&gt; </code></pre>
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 not fixed because length consumed by different no of digits is different e.g. I am writing header for packetNo=1 as <code>PACKET_NO=1</code> , its length will be different for packetNo 10, 100,.. etc</p> <p>I am currently not including no of packets in header. I am just including packet number, I want to include it, but how can I know no of packets prior to computing header size as header should now contain no of packets and NO_OF_PACKETS=--- can be of any length. </p> <p>I can pass it through some function which will compute no of packets but that will be something like brute force and will consume unnecessary time and processing power. Is there any intelligent way to do it? </p>
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 documentation</a> for <code>struct</code> module.</p>
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 not fixed because length consumed by different no of digits is different e.g. I am writing header for packetNo=1 as <code>PACKET_NO=1</code> , its length will be different for packetNo 10, 100,.. etc</p> <p>I am currently not including no of packets in header. I am just including packet number, I want to include it, but how can I know no of packets prior to computing header size as header should now contain no of packets and NO_OF_PACKETS=--- can be of any length. </p> <p>I can pass it through some function which will compute no of packets but that will be something like brute force and will consume unnecessary time and processing power. Is there any intelligent way to do it? </p>
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 possible number of packets, but there has to be <em>some</em> upper limit, no?</p>
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 look in <a href="http://stackoverflow.com/questions/260165/whats-the-best-way-to-generate-a-uml-diagram-from-python-source-code">Python UML tools</a> yet.</p>
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 look in <a href="http://stackoverflow.com/questions/260165/whats-the-best-way-to-generate-a-uml-diagram-from-python-source-code">Python UML tools</a> yet.</p>
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;&lt;instantiate&gt;&gt;</code>.</p>
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 look in <a href="http://stackoverflow.com/questions/260165/whats-the-best-way-to-generate-a-uml-diagram-from-python-source-code">Python UML tools</a> yet.</p>
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 to label a Usage dependency between two Classes to indicate that one Class creates instances of the other." (Pg 690[706-AdobeReader], Appendix B, Unnumbered 4th paragraph, 1st on the page) I think this would apply to meta-classes.</p> <p>Stereotype answer: This is kind of an answer, but does not infer "create" which is the word you used in your post, but might have just been an ambiguous word choice. The notation is an normal line with a filled triangle. I have also seen the keyword of <code>&lt;&lt;extend&gt;&gt;</code> used in tools like Rational Software Modeler. (Pg 657[673-AdobeReader] Figure 18.3 and 659 Figure 18.5, Profile Section)</p> <p>You might also want to clarify if you mean meta-class in the MOF/Model definition sense or in some language or other context.</p> <p>Let me know if you refine your question.</p>
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> <p>edit: The reason I would like to check for syntax errors, is because 12a is a command line parameter.</p> <p>Thanks.</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> <p>edit: The reason I would like to check for syntax errors, is because 12a is a command line parameter.</p> <p>Thanks.</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: date = eval('datetime(2009, 12a, 31)') except SyntaxError: print 'error' </code></pre> <p>But that's still a horrible solution. Maybe you can tell us why you have to catch such syntax errors.</p>
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> <p>edit: The reason I would like to check for syntax errors, is because 12a is a command line parameter.</p> <p>Thanks.</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> <pre><code>month = '12' try: month = int(month) except ValueError: print('bad argument for month') raise else: if not 1&lt;= month &lt;= 12: raise ValueError('month should be between 1 to 12') </code></pre>
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 debug ATM.</p>
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 debug ATM.</p>
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 Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from PIL import Image &gt;&gt;&gt; f = open("happy.jpg") &gt;&gt;&gt; im = Image.open(f) &gt;&gt;&gt; box = (0,0,100,100) &gt;&gt;&gt; kay = im.crop(box) &gt;&gt;&gt; kay &lt;PIL.Image._ImageCrop instance at 0xb1ea80&gt; &gt;&gt;&gt; bad_box = ("0","0","100","100") &gt;&gt;&gt; nkay = im.crop(bad_box) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/PIL/Image.py", line 742, in crop return _ImageCrop(self, box) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/PIL/Image.py", line 1657, in __init__ self.size = x1-x0, y1-y0 TypeError: unsupported operand type(s) for -: 'str' and 'str' &gt;&gt;&gt; </code></pre>
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 debug ATM.</p>
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 ... print inst.args # arguments stored in .args ... print inst # __str__ allows args to printed directly ... x, y = inst # __getitem__ allows args to be unpacked directly ... print 'x =', x ... print 'y =', y ... &lt;type 'exceptions.Exception'&gt; ('spam', 'eggs') ('spam', 'eggs') x = spam y = eggs </code></pre>
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 = GENDER_CHOICES) city = models.CharField(max_length = 50) personalInfo = models.TextField() user = models.OneToOneField(User,unique=True) </code></pre> <p>Then, I have a ModelForm for that model</p> <pre><code>class StudentForm (forms.ModelForm): class Meta: model = Student </code></pre> <p>Using the fields attribute in class Meta, i've managed to show only some fields in a template. However, can I indicate which user fields to show?</p> <p>Something as:</p> <pre><code> fields =('personalInfo','user.username') </code></pre> <p>is currently not showing anything. Works with only StudentFields though/</p> <p>Thanks in advance.</p>
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 = GENDER_CHOICES) city = models.CharField(max_length = 50) personalInfo = models.TextField() user = models.OneToOneField(User,unique=True) </code></pre> <p>Then, I have a ModelForm for that model</p> <pre><code>class StudentForm (forms.ModelForm): class Meta: model = Student </code></pre> <p>Using the fields attribute in class Meta, i've managed to show only some fields in a template. However, can I indicate which user fields to show?</p> <p>Something as:</p> <pre><code> fields =('personalInfo','user.username') </code></pre> <p>is currently not showing anything. Works with only StudentFields though/</p> <p>Thanks in advance.</p>
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 related_to model.</p> <p>For instance, if you have a UserProfile class, and want to be able to have these, when shown, have the User object that is related shown as in inline, you will be out of luck.</p> <p>You can have custom fields on a ModelForm, and use this as a more flexible way, but be aware that it is no longer 'automatic' like a standard ModelForm/inline formset.</p>
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/zone/python-compile.htm" rel="nofollow">Python can be compiled.</a></li> <li>And no not all hosts support python + django.</li> </ul>
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 web host" that question doesn't matter. There are many good hosts that support python and django.</p>
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>And if your server's security has been breached, then you have other things to worry about...</p>
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 them are typically compiled to some form of bytecode, also known as intermediate code. The compilation from source to bytecode may take place as and when needed, but you can also do it in advance if you prefer; however Google App Engine, which lets you run small Python web apps, including Django, for free, as one of its limitations requires you to upload source and not compiled code (I know of no other host imposing the same limitation, but then I know of none giving you so many resources for free in exchange;-).</p> <p>You might be most at home with IronPython, which is a Microsoft product (albeit, I believe, the first Microsoft product to be entirely open-source): in that case you can be certain that it <strong>is</strong> "compiled like .net", because it <strong>is</strong> (part of) .net (more precisely, .net and silverlight). Therefore it cannot be neither more nor less obfuscated and/or secure than .net (meaning, any other .net language).</p> <p>Jython works on JVM, the Java Virtual Machine, much like IronPython works on Microsoft's Common Language Runtime, aka CLR. CPython has its own dedicated virtual machine.</p> <p>For completeness, other implementations (not yet recommended for production use) include <a href="http://codespeak.net/pypy/dist/pypy/doc/">pypy</a>, a highly flexible implementation that supports many possible back-ends (including but not limited to .net); <a href="http://code.google.com/p/unladen-swallow/">unladen swallow</a>, focused on evolving CPython to make it faster; <a href="http://code.google.com/p/pynie/">pynie</a>, a Python compiler to the Parrot virtual machine; <a href="http://code.google.com/p/wpython/">wpython</a>, a reimplementation based on "wordcode" instead of "bytecode"; and no doubt many, many others.</p> <p>CPython, IronPython, Jython and pypy can all run Django (other implementations might also be complete enough for that, but I'm not certain).</p>
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 does not prevent anybody from stealing your software.</p>
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 scripting, but it uses lines and columns rather than a general offset. </p> <p>Would i have to calculate the amount of all preceding line lengths + the current row, or is there a simpler method ?</p>
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 offset from start of file of the cursor position, and similarly for other marks. More generally, if you have a line/column pair this (assuming <code>+byte_offset</code> is how your vim was compiled with) is the way to get a byte offset (there's also a <code>byte2line</code> function to go the other way).</p> <p>While the vim module does make a lot of functionality available directly to Python scripts in vim, I've found that <code>vim.eval</code> and <code>vim.command</code> are often the handiest (and sometimes the only;-) way to get in just as deep as needed;-). Oh, and I always try to have a vim compiled with +justabouteverything whenever I can;-).</p>
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 scripting, but it uses lines and columns rather than a general offset. </p> <p>Would i have to calculate the amount of all preceding line lengths + the current row, or is there a simpler method ?</p>
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 defaults.</p>
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 using Windows Vista and Python 2.6.2.</p>
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 using Windows Vista and Python 2.6.2.</p>
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 using Windows Vista and Python 2.6.2.</p>
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 larger and has evolved. As such a lot of these strings are probably not used anymore. I want to eliminate the ones that have gone and tidy up the file. </p> <p>I want to write a python script, using regular expressions I can get all of the string aliases but how can I search all files in a Java package hierarchy for an instance of a string? If there is a reason I use use perl or bash then let me know as I can but I'd prefer to stick to one scripting language.</p> <p>Please ask for clarification if this doesn't make sense, hopefully this is straightforward, I just haven't used python much.</p> <p>Thanks in advance,</p> <p>Gav</p>
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 larger and has evolved. As such a lot of these strings are probably not used anymore. I want to eliminate the ones that have gone and tidy up the file. </p> <p>I want to write a python script, using regular expressions I can get all of the string aliases but how can I search all files in a Java package hierarchy for an instance of a string? If there is a reason I use use perl or bash then let me know as I can but I'd prefer to stick to one scripting language.</p> <p>Please ask for clarification if this doesn't make sense, hopefully this is straightforward, I just haven't used python much.</p> <p>Thanks in advance,</p> <p>Gav</p>
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 in f: text = line.split('=', 1)[1] text = text.strip().replace('"', '') thestrings.append(text) import os for root, dirs, files in os.walk('/top/dir/of/interest'): for name in files: path = os.path.join(root, name) with open(path) as f: data = f.read() for text in thestrings: if text in data: files_by_str[text].append(path) break </code></pre> <p>This gives you a dict with the texts (those that are present in 1+ files, only), as keys, and lists of the paths to the files containing them as values. If you care only about a yes/no answer to the question "is this text present somewhere", and don't care where, you can save some memory by keeping only a set instead of the defaultdict; but I think that often knowing what files contained each text will be useful, so I suggest this more complete version.</p>
4
2009-09-27T16:13:23Z
[ "python", "find", "internationalization" ]