title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python dictionary simple way to add a new key value pair
1,721,795
<p>Say you have,</p> <pre><code>foo = 'bar' d = {'a-key':'a-value'} </code></pre> <p>And you want</p> <pre><code>d = {'a-key':'a-value','foo':'bar'} e = {'foo':foo} </code></pre> <p>I know you can do,</p> <pre><code>d['foo'] = foo #Either of the following for e e = {'foo':foo} e = dict(foo=foo) </code></pre> <p>...
1
2009-11-12T12:18:56Z
5,181,691
<p>It seems to me what you are talking about is an enhancement to parameter passing functionality:</p> <pre><code>def func(*vars): </code></pre> <p>provides a tuple of ordered values without keys</p> <pre><code>def func(**vars): </code></pre> <p>provides a dict of key value pairs, that MUST be passed as <strong...
0
2011-03-03T14:01:41Z
[ "python", "dictionary" ]
What is the equivalent of MATLAB's repmat in NumPy
1,721,802
<p>I would like to execute the equivalent of the following MATLAB code using NumPy: <code>repmat([1; 1], [1 1 1])</code>. How would I accomplish this?</p>
60
2009-11-12T12:20:32Z
1,722,075
<p>See <a href="http://www.scipy.org/NumPy_for_Matlab_Users" rel="nofollow">NumPy for Matlab users</a>.</p> <p>Matlab:</p> <pre><code>repmat(a, 2, 3) </code></pre> <p>Numpy:</p> <pre><code>numpy.kron(numpy.ones((2,3)), a) </code></pre>
7
2009-11-12T13:09:50Z
[ "python", "matlab", "numpy" ]
What is the equivalent of MATLAB's repmat in NumPy
1,721,802
<p>I would like to execute the equivalent of the following MATLAB code using NumPy: <code>repmat([1; 1], [1 1 1])</code>. How would I accomplish this?</p>
60
2009-11-12T12:20:32Z
1,722,154
<p>Note that some of the reasons you'd need to use MATLAB's repmat are taken care of by NumPy's <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html">broadcasting</a> mechanism, which allows you to do various types of math with arrays of similar shape. So if you had, say, a 1600x1400x3 array represent...
11
2009-11-12T13:24:02Z
[ "python", "matlab", "numpy" ]
What is the equivalent of MATLAB's repmat in NumPy
1,721,802
<p>I would like to execute the equivalent of the following MATLAB code using NumPy: <code>repmat([1; 1], [1 1 1])</code>. How would I accomplish this?</p>
60
2009-11-12T12:20:32Z
1,724,410
<p>Here is a much better (official) <a href="http://www.scipy.org/NumPy%5Ffor%5FMatlab%5FUsers">NumPy for Matlab Users</a> link - I'm afraid the mathesaurus one is quite out of date.</p> <p>The numpy equivalent of <code>repmat(a, m, n)</code> is <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.h...
69
2009-11-12T18:36:56Z
[ "python", "matlab", "numpy" ]
What is the equivalent of MATLAB's repmat in NumPy
1,721,802
<p>I would like to execute the equivalent of the following MATLAB code using NumPy: <code>repmat([1; 1], [1 1 1])</code>. How would I accomplish this?</p>
60
2009-11-12T12:20:32Z
2,098,102
<p>Know both <code>tile</code> and <code>repeat</code>.</p> <pre><code>x = numpy.arange(5) print numpy.tile(x, 2) print x.repeat(2) </code></pre>
2
2010-01-19T23:52:13Z
[ "python", "matlab", "numpy" ]
What is the equivalent of MATLAB's repmat in NumPy
1,721,802
<p>I would like to execute the equivalent of the following MATLAB code using NumPy: <code>repmat([1; 1], [1 1 1])</code>. How would I accomplish this?</p>
60
2009-11-12T12:20:32Z
36,251,855
<p>This is how I understood it out of a bit of fiddling around. Happy to be corrected and hope this helps.</p> <p>Say you have a matrix <strong>M</strong> of 2x3 elements. This has two dimensions, obviously.</p> <p>I could see no difference between Matlab and Python while asking to manipulate the input matrix along t...
1
2016-03-27T19:48:47Z
[ "python", "matlab", "numpy" ]
django datefield filter
1,722,111
<p>I'd like to use an object filter similar to the following</p> <pre><code>Shipment.objects.filter(date__gte=datetime.date(2005,1,1)) </code></pre> <p>However there doesn't seem to be support for comparison operators on datetime objects. Is there a method I'm unaware of or should I look into writing a custom filter....
0
2009-11-12T13:16:17Z
1,722,141
<p>I use date comparison in my code a lot and they work e.g copied a snippet from my calendar code</p> <pre><code>q.filter(start_date__gt=pay_period.start_date).order_by("start_date") </code></pre>
3
2009-11-12T13:21:54Z
[ "python", "django", "datetime", "filter" ]
How to write the output of this code to HTML file?
1,722,239
<pre><code>from HTMLParser import HTMLParser from urllib import urlopen class Spider(HTMLParser): def __init__(self, url): HTMLParser.__init__(self) req = urlopen(url) self.feed(req.read()) def handle_starttag(self, tag, attrs): if tag ...
1
2009-11-12T13:40:34Z
1,722,333
<pre><code>python spider.py &gt; output.html </code></pre>
3
2009-11-12T13:54:20Z
[ "python" ]
How to write the output of this code to HTML file?
1,722,239
<pre><code>from HTMLParser import HTMLParser from urllib import urlopen class Spider(HTMLParser): def __init__(self, url): HTMLParser.__init__(self) req = urlopen(url) self.feed(req.read()) def handle_starttag(self, tag, attrs): if tag ...
1
2009-11-12T13:40:34Z
1,723,382
<p>I haven't messed with Spider at all, but is it printing html, or are you just printing the "Found link..." lines? If you are just printing those, you can do something like <code>outfl = open('output.txt')</code></p> <p>And then, instead of <code>print</code>, call <code>outfl.write("Found link =&gt; %s" % attrs[0][...
0
2009-11-12T16:11:26Z
[ "python" ]
How to write the output of this code to HTML file?
1,722,239
<pre><code>from HTMLParser import HTMLParser from urllib import urlopen class Spider(HTMLParser): def __init__(self, url): HTMLParser.__init__(self) req = urlopen(url) self.feed(req.read()) def handle_starttag(self, tag, attrs): if tag ...
1
2009-11-12T13:40:34Z
1,723,423
<p>Put this at the top of your script:</p> <pre><code>import sys sys.stdout = file('output.html', 'w') </code></pre> <p>This will redirect everything your script writes to the standard output (which includes <code>print</code> statements) to the file 'output.html'.</p>
1
2009-11-12T16:16:10Z
[ "python" ]
Finding the MAC address of the sender of a multicast UDP message in Python?
1,722,254
<p>I have some code that listens for "announcements" via UDP multicast. I can get the IP address of the sender, but what I really need is the MAC address of the sender (since the IP address can and will change).</p> <p>Is there an easy way to do this in Python?</p> <p>A code snippet is included for reference, but lik...
2
2009-11-12T13:42:02Z
1,722,318
<p>The protocol you need is <a href="http://en.wikipedia.org/wiki/Address%5FResolution%5FProtocol" rel="nofollow">ARP</a>. Check this <a href="http://stackoverflow.com/questions/85577/search-for-host-with-mac-address-using-python">question/answer</a> for details</p>
1
2009-11-12T13:52:14Z
[ "python", "sockets", "udp", "multicast", "mac-address" ]
Finding the MAC address of the sender of a multicast UDP message in Python?
1,722,254
<p>I have some code that listens for "announcements" via UDP multicast. I can get the IP address of the sender, but what I really need is the MAC address of the sender (since the IP address can and will change).</p> <p>Is there an easy way to do this in Python?</p> <p>A code snippet is included for reference, but lik...
2
2009-11-12T13:42:02Z
1,722,329
<p>You cannot, in general, get the mac address. You might succeed using ARP on a LAN, but across the Internet it's not possible.</p> <p>Consider the case where the packet you receive has the IP address of the sender's <a href="http://en.wikipedia.org/wiki/Network%5Faddress%5Ftranslation" rel="nofollow">NATting</a> rou...
7
2009-11-12T13:53:48Z
[ "python", "sockets", "udp", "multicast", "mac-address" ]
Finding the MAC address of the sender of a multicast UDP message in Python?
1,722,254
<p>I have some code that listens for "announcements" via UDP multicast. I can get the IP address of the sender, but what I really need is the MAC address of the sender (since the IP address can and will change).</p> <p>Is there an easy way to do this in Python?</p> <p>A code snippet is included for reference, but lik...
2
2009-11-12T13:42:02Z
1,722,332
<p>I'm not sure that it is possible to get the sender's MAC address since the MAC address is a link level address and not a network level address like IP. The MAC address will change at each hop in the network as the packet containing the UDP message is routed from the sender to the receiver.</p>
1
2009-11-12T13:54:18Z
[ "python", "sockets", "udp", "multicast", "mac-address" ]
403 error in Google App Engine with staticdir
1,722,441
<p>For some reason I can't get static_dir to work. In my app.ymal I have:</p> <pre><code>- url: /ui static_dir: ui - url: /dump static_dir: dump </code></pre> <p>Loading static files from /ui works (i.e /ui/images/logo.png). But when I try to access something from /dumo I just get:</p> <pre><code>INFO ...
1
2009-11-12T14:09:16Z
1,722,572
<p>HTTP 403 code is usually returned by GAE for quota problems, read <a href="http://code.google.com/appengine/docs/quotas.html" rel="nofollow">http://code.google.com/appengine/docs/quotas.html</a></p> <p>I think your zip file is more than 1 MB, and I have read it doesn't allow such big zip files. Try with a smaller f...
5
2009-11-12T14:33:18Z
[ "python", "linux", "google-app-engine", "http-status-codes", "http-status-code-403" ]
Which CAS implementation to use in django?
1,722,664
<p>Which CAS implementation should i use to enable CAS single sign on to my django app (trusing a specified CAS server, I'm not interested in creating a CAS provider) ? What I can find are the following:</p> <ul> <li><a href="http://code.google.com/p/django-cas/">http://code.google.com/p/django-cas/</a></li> <li><a h...
23
2009-11-12T14:44:10Z
4,592,274
<p>Low activity does not necessarily mean that product is not good enough. It might be the case that the product has reached a stable state. Probably, you should confirm it with the developer. Personally, I would go for a stable system over one which shows lot of activity (especially if the activity is bug-fixing )</p>...
3
2011-01-04T09:48:40Z
[ "python", "django", "authentication", "single-sign-on", "cas" ]
Which CAS implementation to use in django?
1,722,664
<p>Which CAS implementation should i use to enable CAS single sign on to my django app (trusing a specified CAS server, I'm not interested in creating a CAS provider) ? What I can find are the following:</p> <ul> <li><a href="http://code.google.com/p/django-cas/">http://code.google.com/p/django-cas/</a></li> <li><a h...
23
2009-11-12T14:44:10Z
6,512,247
<p>I've been using an older version of django-cas for a long time now, and it works as expected. I've never used django-cas-consumer, but I've looked into it.</p> <p>Comparing the code between the two projects, it looks like django-cas-consumer is a stripped-down version of django-cas.</p> <p>The two most glaring dif...
8
2011-06-28T19:46:48Z
[ "python", "django", "authentication", "single-sign-on", "cas" ]
Which CAS implementation to use in django?
1,722,664
<p>Which CAS implementation should i use to enable CAS single sign on to my django app (trusing a specified CAS server, I'm not interested in creating a CAS provider) ? What I can find are the following:</p> <ul> <li><a href="http://code.google.com/p/django-cas/">http://code.google.com/p/django-cas/</a></li> <li><a h...
23
2009-11-12T14:44:10Z
13,566,412
<p>Django-cas was missing features we needed, so we rolled our own: <a href="http://github.com/KTHse/django-cas2">http://github.com/KTHse/django-cas2</a></p>
8
2012-11-26T14:00:54Z
[ "python", "django", "authentication", "single-sign-on", "cas" ]
Which CAS implementation to use in django?
1,722,664
<p>Which CAS implementation should i use to enable CAS single sign on to my django app (trusing a specified CAS server, I'm not interested in creating a CAS provider) ? What I can find are the following:</p> <ul> <li><a href="http://code.google.com/p/django-cas/">http://code.google.com/p/django-cas/</a></li> <li><a h...
23
2009-11-12T14:44:10Z
26,823,750
<p>If someone still interesting CAS on django. Please try the most latest and active maintained version of django cas: <a href="https://github.com/mingchen/django-cas-ng" rel="nofollow">django-cas-ng</a>:</p> <pre><code>pip install django-cas-ng </code></pre> <p>django-cas-ng is CAS (Central Authentication Service) c...
3
2014-11-09T00:49:00Z
[ "python", "django", "authentication", "single-sign-on", "cas" ]
Which CAS implementation to use in django?
1,722,664
<p>Which CAS implementation should i use to enable CAS single sign on to my django app (trusing a specified CAS server, I'm not interested in creating a CAS provider) ? What I can find are the following:</p> <ul> <li><a href="http://code.google.com/p/django-cas/">http://code.google.com/p/django-cas/</a></li> <li><a h...
23
2009-11-12T14:44:10Z
30,322,764
<p>The <a href="https://github.com/kstateome/django-cas" rel="nofollow">kstateome/django-cas</a> repo is more <strong>active recently</strong> (2015) with following details.</p> <h3>Requirements</h3> <ul> <li>Current version: 1.1.1</li> <li>Django <code>1.5</code> or above, </li> <li>Python <code>2.6</code>, <code>2....
2
2015-05-19T10:15:51Z
[ "python", "django", "authentication", "single-sign-on", "cas" ]
Twisted/tkinter program crashes on exit
1,722,865
<p>I am running an app using twisted and tkinter that sends the result to the server, waits for the server to send back a confirmation, and then exits. So, the function I use to exit is this:</p> <pre><code>def term(): '''To end the program''' reactor.stop() root.quit() root.destroy() </code></pre> <p...
1
2009-11-12T15:08:47Z
1,723,169
<p>You only need to call <code>reactor.stop</code> to exit: the <code>root.quit()</code> and <code>root.destroy()</code> calls are superfluous. Consider this short example which runs Twisted and Tk for three seconds and then exits:</p> <pre><code>import Tkinter from twisted.internet import tksupport root = Tkinter.T...
1
2009-11-12T15:42:48Z
[ "python", "twisted", "tkinter" ]
Is the first entry in sys.path supposed to represent the current working directory?
1,722,901
<p>I had always assumed that the first entry in <code>sys.path</code> by default was the current working directory. But as it turns out, on my system the first entry is the path on which the script resides. So if I'm executing a script that's in <code>/usr/bin</code> from <code>/some/directory</code>, the first entry...
0
2009-11-12T15:12:40Z
1,722,915
<p>This is by design:</p> <blockquote> <p>As initialized upon program startup, the first item of this list, <code>path[0]</code>, is the directory containing the script that was used to invoke the Python interpreter.</p> </blockquote> <p><em>source: <a href="http://docs.python.org/library/sys.html#sys.path"...
5
2009-11-12T15:14:25Z
[ "python", "pythonpath", "sys.path" ]
Is the first entry in sys.path supposed to represent the current working directory?
1,722,901
<p>I had always assumed that the first entry in <code>sys.path</code> by default was the current working directory. But as it turns out, on my system the first entry is the path on which the script resides. So if I'm executing a script that's in <code>/usr/bin</code> from <code>/some/directory</code>, the first entry...
0
2009-11-12T15:12:40Z
1,722,943
<p>You can get the current directory with <code>os.getcwd()</code>.</p>
1
2009-11-12T15:17:27Z
[ "python", "pythonpath", "sys.path" ]
Multiple programs using the same UDP port? Possible?
1,722,993
<p>I currently have a small Python script that I'm using to spawn multiple executables, (voice chat servers), and in the next version of the software, the servers have the ability to receive heartbeat signals on the UDP port. (There will be possibly thousands of servers on one machine, ranging from ports 7878 and up)</...
0
2009-11-12T15:22:37Z
1,723,017
<p>This isn't possible. What you'll have to do is have one UDP master program that handles all UDP communication over the one port, and communicates with your servers in another way (UDP on different ports, named pipes, ...)</p>
2
2009-11-12T15:26:37Z
[ "python", "udp", "communication", "daemon", "ports" ]
Multiple programs using the same UDP port? Possible?
1,722,993
<p>I currently have a small Python script that I'm using to spawn multiple executables, (voice chat servers), and in the next version of the software, the servers have the ability to receive heartbeat signals on the UDP port. (There will be possibly thousands of servers on one machine, ranging from ports 7878 and up)</...
0
2009-11-12T15:22:37Z
1,723,643
<p>I'm pretty sure this is possible on Linux; I don't know about other UNIXes.</p> <p>There are two ways to propagate a file descriptor from one process to another:</p> <ul> <li>When a process fork()s, the child inherits all the file descriptors of the parent.</li> <li>A process can send a file descriptor to another ...
1
2009-11-12T16:47:22Z
[ "python", "udp", "communication", "daemon", "ports" ]
Find (and keep) duplicates of sublist in python
1,723,072
<p>I have a list of lists (sublist) that contains numbers and I only want to keep those exists in all (sub)lists.</p> <p>Example:</p> <pre><code>x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]] output =&gt; [3, 4] </code></pre> <p>How can I do this?</p>
4
2009-11-12T15:32:11Z
1,723,086
<pre><code>common = set(x[0]) for l in x[1:]: common &amp;= set(l) print list(common) </code></pre> <p>or:</p> <pre><code>import operator print reduce(operator.iand, map(set, x)) </code></pre>
8
2009-11-12T15:33:42Z
[ "python", "list", "duplicates", "sublist" ]
Find (and keep) duplicates of sublist in python
1,723,072
<p>I have a list of lists (sublist) that contains numbers and I only want to keep those exists in all (sub)lists.</p> <p>Example:</p> <pre><code>x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]] output =&gt; [3, 4] </code></pre> <p>How can I do this?</p>
4
2009-11-12T15:32:11Z
1,723,102
<p>In one liner:</p> <pre><code>&gt;&gt;&gt; reduce(set.intersection, x[1:], set(x[0])) set([3, 4]) </code></pre>
6
2009-11-12T15:35:23Z
[ "python", "list", "duplicates", "sublist" ]
Find (and keep) duplicates of sublist in python
1,723,072
<p>I have a list of lists (sublist) that contains numbers and I only want to keep those exists in all (sub)lists.</p> <p>Example:</p> <pre><code>x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]] output =&gt; [3, 4] </code></pre> <p>How can I do this?</p>
4
2009-11-12T15:32:11Z
13,931,861
<pre><code>def f(a, b): return list(set(a).intersection(set(b))) reduce(f, x) </code></pre>
1
2012-12-18T11:21:46Z
[ "python", "list", "duplicates", "sublist" ]
Find (and keep) duplicates of sublist in python
1,723,072
<p>I have a list of lists (sublist) that contains numbers and I only want to keep those exists in all (sub)lists.</p> <p>Example:</p> <pre><code>x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]] output =&gt; [3, 4] </code></pre> <p>How can I do this?</p>
4
2009-11-12T15:32:11Z
21,448,535
<p>Just another way of solving, almost same as nadia but without using reduce, and i use map:</p> <pre><code>&gt;&gt;&gt; x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]] &gt;&gt;&gt; set.intersection(*map(set,x)) set([3, 4]) &gt;&gt;&gt; </code></pre>
0
2014-01-30T05:29:02Z
[ "python", "list", "duplicates", "sublist" ]
python function slowing down for no apparent reason
1,723,494
<p>I have a python function defined as follows which i use to delete from list1 the items which are already in list2. I am using python 2.6.2 on windows XP</p> <pre><code>def compareLists(list1, list2): curIndex = 0 while curIndex &lt; len(list1): if list1[curIndex] in list2: list1.pop(curI...
2
2009-11-12T16:26:16Z
1,723,529
<p>EDIT: I've updated my answer to account for lists being unhashable, as well as some other feedback. This one is even tested.</p> <p>It probably relates to the cost of poping an item out of a middle of a list.</p> <p>Alternatively have you tried using sets to handle this?</p> <pre><code>def difference(list1, list...
1
2009-11-12T16:30:10Z
[ "python" ]
python function slowing down for no apparent reason
1,723,494
<p>I have a python function defined as follows which i use to delete from list1 the items which are already in list2. I am using python 2.6.2 on windows XP</p> <pre><code>def compareLists(list1, list2): curIndex = 0 while curIndex &lt; len(list1): if list1[curIndex] in list2: list1.pop(curI...
2
2009-11-12T16:26:16Z
1,723,530
<p>If we rule the data structure itself out, look at your memory usage next. If you end up asking the OS to swap in for you (i.e., the list takes up more memory than you have), Python's going to sit in <em>iowait</em> waiting on the OS to get the pages from disk, which makes sense given your description.</p> <p>Is Pyt...
2
2009-11-12T16:30:14Z
[ "python" ]
python function slowing down for no apparent reason
1,723,494
<p>I have a python function defined as follows which i use to delete from list1 the items which are already in list2. I am using python 2.6.2 on windows XP</p> <pre><code>def compareLists(list1, list2): curIndex = 0 while curIndex &lt; len(list1): if list1[curIndex] in list2: list1.pop(curI...
2
2009-11-12T16:26:16Z
1,723,560
<p>Try a more pythonic approach to the filtering, something like</p> <pre><code>[x for x in list1 if x not in set(list2)] </code></pre> <p>Converting both lists to sets is unnessescary, and will be very slow and memory hungry on large amounts of data.</p> <p>Since your data is a list of lists, you need to do somethi...
12
2009-11-12T16:34:59Z
[ "python" ]
python function slowing down for no apparent reason
1,723,494
<p>I have a python function defined as follows which i use to delete from list1 the items which are already in list2. I am using python 2.6.2 on windows XP</p> <pre><code>def compareLists(list1, list2): curIndex = 0 while curIndex &lt; len(list1): if list1[curIndex] in list2: list1.pop(curI...
2
2009-11-12T16:26:16Z
1,723,564
<p>The only reason why the code can become slower is that you have big elements in both lists which share a lot of common elements (so the <code>list1[curIndex] in list2</code> takes more time).</p> <p>Here are a couple of ways to fix this:</p> <ul> <li><p>If you don't care about the order, convert both lists into <c...
2
2009-11-12T16:35:16Z
[ "python" ]
python function slowing down for no apparent reason
1,723,494
<p>I have a python function defined as follows which i use to delete from list1 the items which are already in list2. I am using python 2.6.2 on windows XP</p> <pre><code>def compareLists(list1, list2): curIndex = 0 while curIndex &lt; len(list1): if list1[curIndex] in list2: list1.pop(curI...
2
2009-11-12T16:26:16Z
1,723,594
<p>There are 2 issues that cause your algorithm to scale poorly:</p> <ol> <li><code>x in list</code> is an O(n) operation.</li> <li><code>pop(n)</code> where n is in the middle of the array is an O(n) operation.</li> </ol> <p>Both situations cause it to scale poorly O(n^2) for large amounts of data. gnud's implement...
3
2009-11-12T16:39:56Z
[ "python" ]
python function slowing down for no apparent reason
1,723,494
<p>I have a python function defined as follows which i use to delete from list1 the items which are already in list2. I am using python 2.6.2 on windows XP</p> <pre><code>def compareLists(list1, list2): curIndex = 0 while curIndex &lt; len(list1): if list1[curIndex] in list2: list1.pop(curI...
2
2009-11-12T16:26:16Z
1,723,766
<p>The often suggested <code>set</code> wont work here, because the two lists contain lists, which are unhashable. You need to change your data structure first.</p> <p>You can</p> <ul> <li>convert the sublists into tuples or class instances to make them hashable, then use sets.</li> <li>Keep both lists sorted, then y...
0
2009-11-12T17:02:48Z
[ "python" ]
aspect-oriented techniques in python?
1,723,849
<p>So I have an interesting problem in Python, that could possibly be solved with aspect-oriented techniques. Here's the situation:</p> <ol> <li>I have a bunch of modules, each of which has a bunch of functions.</li> <li>I have an executable that calls some set of functions in those modules.</li> <li>When the executab...
4
2009-11-12T17:13:39Z
1,723,949
<p>The simplest and first solution that comes to mind, is using a proxy module.</p> <pre><code>#fooproxy.py import foo import logger #not implemented here - use your imagination :) def bar(baz): logger.method("foo.bar") return foo.bar(baz) #foo.py def bar(baz): print "The real McCoy" #main.py import fo...
0
2009-11-12T17:26:10Z
[ "python" ]
aspect-oriented techniques in python?
1,723,849
<p>So I have an interesting problem in Python, that could possibly be solved with aspect-oriented techniques. Here's the situation:</p> <ol> <li>I have a bunch of modules, each of which has a bunch of functions.</li> <li>I have an executable that calls some set of functions in those modules.</li> <li>When the executab...
4
2009-11-12T17:13:39Z
1,723,953
<p>I don't know the right way to do this in a general case, but what comes to mind is just hacking the executable a little. Something like:</p> <pre><code>class DebugCallWrapper(object): def __init__(self, callable): self.callable = callable def __call__(*args,**kwargs): log.debug(str(callabl...
0
2009-11-12T17:26:42Z
[ "python" ]
aspect-oriented techniques in python?
1,723,849
<p>So I have an interesting problem in Python, that could possibly be solved with aspect-oriented techniques. Here's the situation:</p> <ol> <li>I have a bunch of modules, each of which has a bunch of functions.</li> <li>I have an executable that calls some set of functions in those modules.</li> <li>When the executab...
4
2009-11-12T17:13:39Z
1,724,358
<p>Modify the behavior of the functions in the executable can be done using a decorator:</p> <pre><code>#!/usr/bin/env python from module1 import foo from module2 import bar def trace(f): def tracewrapper(*arg, **kw): arg_str=','.join(['%r'%a for a in arg]+['%s=%s'%(key,kw[key]) for key in kw]) pr...
5
2009-11-12T18:29:31Z
[ "python" ]
How to split the file content by space and end-of-line character?
1,724,080
<p>When I do the following list comprehension I end up with nested lists:</p> <pre><code>channel_values = [x for x in [ y.split(' ') for y in open(channel_output_file).readlines() ] if x and not x == '\n'] </code></pre> <p>Basically I have a file composed of this:</p> <pre><code>7656 7653 7649 7646 7643 7640 763...
1
2009-11-12T17:46:19Z
1,724,104
<p>You don't need list comprehensions for this:</p> <pre><code>channel_values = open(channel_output_file).read().split() </code></pre>
11
2009-11-12T17:49:51Z
[ "python", "list-comprehension" ]
How to split the file content by space and end-of-line character?
1,724,080
<p>When I do the following list comprehension I end up with nested lists:</p> <pre><code>channel_values = [x for x in [ y.split(' ') for y in open(channel_output_file).readlines() ] if x and not x == '\n'] </code></pre> <p>Basically I have a file composed of this:</p> <pre><code>7656 7653 7649 7646 7643 7640 763...
1
2009-11-12T17:46:19Z
1,724,111
<p>Just do this:</p> <pre><code>channel_values = open(channel_output_file).read().split() </code></pre> <p><a href="http://docs.python.org/library/stdtypes.html#str.split">split()</a> will split according to whitespace that includes <code>' ' '\t' and '\n'</code>. It will split all the values into one list.</p> <p>I...
5
2009-11-12T17:50:20Z
[ "python", "list-comprehension" ]
How to split the file content by space and end-of-line character?
1,724,080
<p>When I do the following list comprehension I end up with nested lists:</p> <pre><code>channel_values = [x for x in [ y.split(' ') for y in open(channel_output_file).readlines() ] if x and not x == '\n'] </code></pre> <p>Basically I have a file composed of this:</p> <pre><code>7656 7653 7649 7646 7643 7640 763...
1
2009-11-12T17:46:19Z
1,724,162
<p>Well another problem is that you're leaving the file open. Note that <code>open</code> is an alias for <code>file</code>.</p> <p>try this:</p> <pre><code>f = file(channel_output_file) channel_values = f.read().split() f.close() </code></pre> <p>Note they'll be string values so if you want integer ones change the...
0
2009-11-12T17:56:12Z
[ "python", "list-comprehension" ]
How to split the file content by space and end-of-line character?
1,724,080
<p>When I do the following list comprehension I end up with nested lists:</p> <pre><code>channel_values = [x for x in [ y.split(' ') for y in open(channel_output_file).readlines() ] if x and not x == '\n'] </code></pre> <p>Basically I have a file composed of this:</p> <pre><code>7656 7653 7649 7646 7643 7640 763...
1
2009-11-12T17:46:19Z
1,724,214
<p>Also, the reason the original list comprehension had nested lists is because you added an extra level of list comprehension with the inner set of square brackets. You meant this:</p> <pre><code>channel_values = [x for x in y.split(' ') for y in open(channel_output_file) if x and not x == '\n'] </code></pre> <...
2
2009-11-12T18:03:37Z
[ "python", "list-comprehension" ]
How to split the file content by space and end-of-line character?
1,724,080
<p>When I do the following list comprehension I end up with nested lists:</p> <pre><code>channel_values = [x for x in [ y.split(' ') for y in open(channel_output_file).readlines() ] if x and not x == '\n'] </code></pre> <p>Basically I have a file composed of this:</p> <pre><code>7656 7653 7649 7646 7643 7640 763...
1
2009-11-12T17:46:19Z
1,724,275
<blockquote> <p>Is there a better way to do this via list comprehension?</p> </blockquote> <p>Sort of..</p> <p>Instead of reading each line as an array, with the <code>.readlines()</code> methods, you can just use <code>.read()</code>:</p> <pre><code>channel_values = [x for x in open(channel_output_file).readlines...
0
2009-11-12T18:12:48Z
[ "python", "list-comprehension" ]
How to split the file content by space and end-of-line character?
1,724,080
<p>When I do the following list comprehension I end up with nested lists:</p> <pre><code>channel_values = [x for x in [ y.split(' ') for y in open(channel_output_file).readlines() ] if x and not x == '\n'] </code></pre> <p>Basically I have a file composed of this:</p> <pre><code>7656 7653 7649 7646 7643 7640 763...
1
2009-11-12T17:46:19Z
1,726,790
<p>If you don't care about dangling file references, and you really must have a list read into memory all at once, the one-liner mentioned in other answers does work:</p> <pre><code>channel_values = open(channel_output_path).read().split() </code></pre> <p>In production code, I would probably use a generator, why rea...
0
2009-11-13T02:38:25Z
[ "python", "list-comprehension" ]
Referencing classes in Python
1,724,316
<p>I'm having a spot of bother with Python (using for app engine). I'm fairly new to it (more used to Java), but I had been enjoying....until now.</p> <p>The following won't work!</p> <pre><code>class SomeClass(db.Model): item = db.ReferenceProperty(AnotherClass) class AnotherClass(db.Model): otherItem = db.Refe...
2
2009-11-12T18:22:15Z
1,724,341
<p>If you mean it won't work because each class want to reference the other, try this:</p> <pre><code>class SomeClass(db.Model): item = None class AnotherClass(db.Model): otherItem = db.ReferenceProperty(SomeClass) SomeClass.item = db.ReferenceProperty(AnotherClass) </code></pre> <p>It conflicts with some metac...
1
2009-11-12T18:26:08Z
[ "python", "google-app-engine", "class", "definition" ]
Referencing classes in Python
1,724,316
<p>I'm having a spot of bother with Python (using for app engine). I'm fairly new to it (more used to Java), but I had been enjoying....until now.</p> <p>The following won't work!</p> <pre><code>class SomeClass(db.Model): item = db.ReferenceProperty(AnotherClass) class AnotherClass(db.Model): otherItem = db.Refe...
2
2009-11-12T18:22:15Z
1,724,402
<p>One way to view the "class" keyword in Python is as simply creating a new named scope during the initial execution of your script. So your code throws a <em>NameError: name 'AnotherClass' is not defined</em> exception because Python hasn't executed the <code>class AnotherClass(db.Model):</code> line yet when it exe...
6
2009-11-12T18:35:36Z
[ "python", "google-app-engine", "class", "definition" ]
Exclude on a many-to-many relationship through a third table
1,724,317
<p>I have a problem making "exclude" querys on tables which have a many-to-many relationship through a third table. I have a table with projects, a table with people and a relationsship table with the flags "is_green, is_yellow, is_red", like:</p> <pre><code>class Project(models.Model): ... class Person(models.Mo...
3
2009-11-12T18:22:17Z
1,724,526
<p>If you have a list of Status objects called 'objects', you can use</p> <pre><code>[s.person for s in objects] </code></pre> <p>to make it into a list of the corresponding Persons.</p>
0
2009-11-12T18:56:10Z
[ "python", "django", "many-to-many" ]
Exclude on a many-to-many relationship through a third table
1,724,317
<p>I have a problem making "exclude" querys on tables which have a many-to-many relationship through a third table. I have a table with projects, a table with people and a relationsship table with the flags "is_green, is_yellow, is_red", like:</p> <pre><code>class Project(models.Model): ... class Person(models.Mo...
3
2009-11-12T18:22:17Z
1,724,689
<p>Maybe this? (untested)</p> <pre><code>Person.objects.exclude(id__in=Person.objects.filter(project=p, status__is_red=True).values(id)) </code></pre>
4
2009-11-12T19:21:29Z
[ "python", "django", "many-to-many" ]
How could I print out the nth letter of the alphabet in Python?
1,724,473
<p>ASCII math doesn't seem to work in Python:</p> <blockquote> <blockquote> <p>'a' + 5 DOESN'T WORK</p> </blockquote> </blockquote> <p>How could I quickly print out the nth letter of the alphabet without having an array of letters?</p> <p>My naive solution is this:</p> <pre> letters = ['A', 'B', 'C', 'D...
11
2009-11-12T18:47:18Z
1,724,482
<pre><code>chr(ord('a')+5) </code></pre> <p><sup>&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;&#8203;</sup></p>
2
2009-11-12T18:49:04Z
[ "python" ]
How could I print out the nth letter of the alphabet in Python?
1,724,473
<p>ASCII math doesn't seem to work in Python:</p> <blockquote> <blockquote> <p>'a' + 5 DOESN'T WORK</p> </blockquote> </blockquote> <p>How could I quickly print out the nth letter of the alphabet without having an array of letters?</p> <p>My naive solution is this:</p> <pre> letters = ['A', 'B', 'C', 'D...
11
2009-11-12T18:47:18Z
1,724,485
<p><code>chr</code> and <code>ord</code> convert characters from and to integers, respectively. So:</p> <pre><code>chr(ord('a') + 5) </code></pre> <p>is the letter <code>'f'</code>.</p>
32
2009-11-12T18:49:09Z
[ "python" ]
How could I print out the nth letter of the alphabet in Python?
1,724,473
<p>ASCII math doesn't seem to work in Python:</p> <blockquote> <blockquote> <p>'a' + 5 DOESN'T WORK</p> </blockquote> </blockquote> <p>How could I quickly print out the nth letter of the alphabet without having an array of letters?</p> <p>My naive solution is this:</p> <pre> letters = ['A', 'B', 'C', 'D...
11
2009-11-12T18:47:18Z
1,724,491
<p>You need to use the <code>ord</code> function, like</p> <pre><code>print(ord('a')-5) </code></pre> <p>Edit: gah, I was too slow :)</p>
1
2009-11-12T18:49:58Z
[ "python" ]
How could I print out the nth letter of the alphabet in Python?
1,724,473
<p>ASCII math doesn't seem to work in Python:</p> <blockquote> <blockquote> <p>'a' + 5 DOESN'T WORK</p> </blockquote> </blockquote> <p>How could I quickly print out the nth letter of the alphabet without having an array of letters?</p> <p>My naive solution is this:</p> <pre> letters = ['A', 'B', 'C', 'D...
11
2009-11-12T18:47:18Z
1,724,536
<p>ASCII math aside, you don't have to type your letters table by hand. The <a href="http://docs.python.org/library/string.html#string-constants">string constants</a> in the <code>string module</code> provide what you were looking for.</p> <pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; string.ascii_uppercase[5] 'F...
21
2009-11-12T18:57:28Z
[ "python" ]
How could I print out the nth letter of the alphabet in Python?
1,724,473
<p>ASCII math doesn't seem to work in Python:</p> <blockquote> <blockquote> <p>'a' + 5 DOESN'T WORK</p> </blockquote> </blockquote> <p>How could I quickly print out the nth letter of the alphabet without having an array of letters?</p> <p>My naive solution is this:</p> <pre> letters = ['A', 'B', 'C', 'D...
11
2009-11-12T18:47:18Z
1,724,625
<pre><code>import string print string.letters[n + is_upper*26] </code></pre> <p>For example:</p> <pre><code>&gt;&gt;&gt; n = 5 &gt;&gt;&gt; is_upper = False &gt;&gt;&gt; string.letters[n+is_upper*26] 'f' &gt;&gt;&gt; is_upper = True &gt;&gt;&gt; string.letters[n+is_upper*26] 'F' </code></pre>
0
2009-11-12T19:12:46Z
[ "python" ]
How could I print out the nth letter of the alphabet in Python?
1,724,473
<p>ASCII math doesn't seem to work in Python:</p> <blockquote> <blockquote> <p>'a' + 5 DOESN'T WORK</p> </blockquote> </blockquote> <p>How could I quickly print out the nth letter of the alphabet without having an array of letters?</p> <p>My naive solution is this:</p> <pre> letters = ['A', 'B', 'C', 'D...
11
2009-11-12T18:47:18Z
6,024,696
<p>if u want to go really out of the way (probably not very good) you could create a new class CharMath:</p> <pre><code>class CharMath: def __init__(self,char): if len(char) &gt; 1: raise IndexError("Not a single character provided") else: self.char = char def __add__(self,num): if type...
1
2011-05-16T23:45:50Z
[ "python" ]
Just curious about result from NumPy function!
1,724,504
<p>I have used NumPy for my Master thesis. I've converted parts of the code from MATLAB code, but I have doubts in NumPy/Python when I reference:</p> <pre><code>m = numpy.ones((10,2)) m[:,0] </code></pre> <p>which returns:</p> <pre><code>array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) </code></pre> <p>and...
2
2009-11-12T18:52:47Z
1,724,546
<p>I forget what numpy does, but Matlab indexes vectors from 1, not 0. So array(:,0) is an error in Matlab.</p>
0
2009-11-12T18:58:54Z
[ "python", "matlab", "numpy" ]
Just curious about result from NumPy function!
1,724,504
<p>I have used NumPy for my Master thesis. I've converted parts of the code from MATLAB code, but I have doubts in NumPy/Python when I reference:</p> <pre><code>m = numpy.ones((10,2)) m[:,0] </code></pre> <p>which returns:</p> <pre><code>array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) </code></pre> <p>and...
2
2009-11-12T18:52:47Z
1,724,837
<p>I'm still learning Python myself, but I think the way that <em>slicing</em> works is that indices point to in-between locations, therefore <code>0:1</code> only gets you the first column. Is this what you were asking about?</p> <p>This is what the <a href="http://docs.python.org/tutorial/introduction.html#strings" ...
3
2009-11-12T19:41:02Z
[ "python", "matlab", "numpy" ]
Just curious about result from NumPy function!
1,724,504
<p>I have used NumPy for my Master thesis. I've converted parts of the code from MATLAB code, but I have doubts in NumPy/Python when I reference:</p> <pre><code>m = numpy.ones((10,2)) m[:,0] </code></pre> <p>which returns:</p> <pre><code>array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) </code></pre> <p>and...
2
2009-11-12T18:52:47Z
1,724,985
<p>This is because numpy has the concept of 1d arrays which Matlab doesn't have. Coupled with numpys <a href="http://www.scipy.org/EricsBroadcastingDoc">broadcasting</a> this provides a powerful simplification (less worrying about inserting transposes everywhere) but does mean you have to think a little bit about trans...
5
2009-11-12T20:02:55Z
[ "python", "matlab", "numpy" ]
Dynamically Display field values in Django template (object.x)
1,724,569
<p>I am currently working on an app that uses custom annotate querysets. Currently i have 2 urls setup, but i would need one for each field that the users would like to summarize data for. This could be configured manually, but it would violate DRY! I would basically have +-8 urls that basically do the same thing. </p>...
1
2009-11-12T19:02:24Z
1,725,513
<p>It sounds like you want to do something along the lines of:</p> <pre><code># in the views.py: field = 'business' {# in the template: #} {{ object.field }} </code></pre> <p>and have the value of <code>object.business</code> appear in the output. This isn't possible with the Django template language out of the bo...
0
2009-11-12T21:23:32Z
[ "python", "django", "django-models", "django-templates" ]
Deleting duplicate dictionaries in a list in python
1,724,588
<p>I have two lists of dictionaries</p> <pre><code>list1 = [ {..}, {..}, ..] list2 = [ {..}, {..}, ..] </code></pre> <p>I want to remove the dictionaries in list1 which are in list2. I had a similar problem where I had a list of lists instead of a dictionary and it is solved here</p> <p><a href="http://stackoverflow...
1
2009-11-12T19:05:52Z
1,724,622
<p>You can't use <code>dict</code>s in <code>set</code>s because they're mutable and don't have stable identities. You can work around that by making a <code>tuple</code> out of their items. Note that simply wrapping a <code>dict</code> in a <code>tuple</code> doesn't get around the fact that distinct <code>dict</code>...
5
2009-11-12T19:11:55Z
[ "python" ]
How can I use PHP's gettext in conjunction with python's gettext?
1,724,629
<p>I have an app that I'm migrating portions of to Django, but Python and PHP have a different string format, e.g., <code>"Hello %1s"</code> in PHP vs. <code>"Hello {0}"</code> or <code>"Hello {name}"</code> in Python.</p> <p>We'll be maintaining both apps for a while, but is there a way to use the Python format in P...
0
2009-11-12T19:13:07Z
1,724,782
<p>PHP's gettext doesn't expand/substitute %s - this is done by output functions (e.g. <em>printf</em>). It also appears to be the case in Python.</p> <p>Most importantly, in Python you <strong>can</strong> use %s to represent strings, see <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="n...
0
2009-11-12T19:32:01Z
[ "php", "python", "gettext" ]
How can I use PHP's gettext in conjunction with python's gettext?
1,724,629
<p>I have an app that I'm migrating portions of to Django, but Python and PHP have a different string format, e.g., <code>"Hello %1s"</code> in PHP vs. <code>"Hello {0}"</code> or <code>"Hello {name}"</code> in Python.</p> <p>We'll be maintaining both apps for a while, but is there a way to use the Python format in P...
0
2009-11-12T19:13:07Z
1,724,876
<p>Would something like this php PECL extension help you?</p> <p><a href="http://pecl.php.net/package/python" rel="nofollow">http://pecl.php.net/package/python</a></p> <p>Regards.</p>
0
2009-11-12T19:46:20Z
[ "php", "python", "gettext" ]
Given a list of slices, how do I split a sequence by them?
1,724,675
<h3>Given a list of slices, how do I separate a sequence based on them?</h3> <p>I have long amino-acid strings that I would like to split based on start-stop values in a list. An example is probably the most clear way of explaining it:</p> <pre><code>str = "MSEPAGDVRQNPCGSKAC" split_points = [[1,3], [7,10], [12,13]] ...
11
2009-11-12T19:19:21Z
1,724,769
<p>Here's some code that will work.</p> <pre><code>result = [] last_end = 0 for sp in split_points: result.append(str[last_end:sp[0]]) result.append('(' + str[sp[0]:sp[1]+1] + ')') last_end = sp[1]+1 result.append(str[last_end:]) print result </code></pre> <p>If you just want the parts in the parenthesis it be...
0
2009-11-12T19:29:26Z
[ "python" ]
Given a list of slices, how do I split a sequence by them?
1,724,675
<h3>Given a list of slices, how do I separate a sequence based on them?</h3> <p>I have long amino-acid strings that I would like to split based on start-stop values in a list. An example is probably the most clear way of explaining it:</p> <pre><code>str = "MSEPAGDVRQNPCGSKAC" split_points = [[1,3], [7,10], [12,13]] ...
11
2009-11-12T19:19:21Z
1,724,806
<p>Here is a simple solution for you. to grab each of the sets specified by the point. </p> <pre><code>In[4]: str[p[0]:p[1]+1] for p in split_points] Out[4]: ['SEP', 'VRQN', 'CG'] </code></pre> <p>To get the parenthesis:</p> <pre><code>In[5]: ['(' + str[p[0]:p[1]+1] + ')' for p in split_points] Out[5]: ['(SEP)'...
2
2009-11-12T19:36:07Z
[ "python" ]
Given a list of slices, how do I split a sequence by them?
1,724,675
<h3>Given a list of slices, how do I separate a sequence based on them?</h3> <p>I have long amino-acid strings that I would like to split based on start-stop values in a list. An example is probably the most clear way of explaining it:</p> <pre><code>str = "MSEPAGDVRQNPCGSKAC" split_points = [[1,3], [7,10], [12,13]] ...
11
2009-11-12T19:19:21Z
1,724,900
<p>Strange way to split strings you have there:</p> <pre><code>def splitter( s, points ): c = 0 for x,y in points: yield s[c:x] yield "(%s)" % s[x:y+1] c=y+1 yield s[c:] print list(splitter(str, split_points)) # =&gt; ['M', '(SEP)', 'AGD', '(VRQN)', 'P', '(CG)', 'SKAC'] # if some ...
9
2009-11-12T19:49:33Z
[ "python" ]
Given a list of slices, how do I split a sequence by them?
1,724,675
<h3>Given a list of slices, how do I separate a sequence based on them?</h3> <p>I have long amino-acid strings that I would like to split based on start-stop values in a list. An example is probably the most clear way of explaining it:</p> <pre><code>str = "MSEPAGDVRQNPCGSKAC" split_points = [[1,3], [7,10], [12,13]] ...
11
2009-11-12T19:19:21Z
1,725,166
<p>Probably not for elegance, but just because I can do it in a oneliner :)</p> <pre><code>&gt;&gt;&gt; reduce(lambda a,ij:a[:-1]+[str[a[-1]:ij[0]],'('+str[ij[0]:ij[1]+1]+')', ij[1]], split_points, [0])[:-1] + [str[split_points[-1][-1]+1:]] ['M', '(SEP)', 'PAGD', '(VRQN)', 'NP', '(CG)', 'SKAC'] </code></p...
0
2009-11-12T20:32:35Z
[ "python" ]
Given a list of slices, how do I split a sequence by them?
1,724,675
<h3>Given a list of slices, how do I separate a sequence based on them?</h3> <p>I have long amino-acid strings that I would like to split based on start-stop values in a list. An example is probably the most clear way of explaining it:</p> <pre><code>str = "MSEPAGDVRQNPCGSKAC" split_points = [[1,3], [7,10], [12,13]] ...
11
2009-11-12T19:19:21Z
1,725,200
<p>Here's a solution that converts your split_points to regular string slices and then prints out the appropriate slices:</p> <pre><code>str = "MSEPAGDVRQNPCGSKAC" split_points = [[1, 3], [7, 10], [12, 13]] adjust = [s for sp in [[x, y + 1] for x, y in split_points] for s in sp] zipped = zip([None] + adjust, adjust +...
0
2009-11-12T20:37:08Z
[ "python" ]
Given a list of slices, how do I split a sequence by them?
1,724,675
<h3>Given a list of slices, how do I separate a sequence based on them?</h3> <p>I have long amino-acid strings that I would like to split based on start-stop values in a list. An example is probably the most clear way of explaining it:</p> <pre><code>str = "MSEPAGDVRQNPCGSKAC" split_points = [[1,3], [7,10], [12,13]] ...
11
2009-11-12T19:19:21Z
1,725,336
<pre> >>> str = "MSEPAGDVRQNPCGSKAC" >>> split_points = [[1,3], [7,10], [12,13]] >>> >>> all_points = sum(split_points, [0]) + [len(str)-1] >>> map(lambda i,j: str[i:j+1], all_points[:-1], all_points[1:]) ['MS', 'SEP', 'PAGDV', 'VRQN', 'NPC', 'CG', 'GSKAC'] >>> >>> str_out = map(lambda i,j: str[i:j+1], all_points[:-1:2...
0
2009-11-12T20:56:39Z
[ "python" ]
Find a file in python
1,724,693
<p>I have a file that may be in a different place on each user's machine. Is there a way to implement a search for the file? A way that I can pass the file's name and the directory tree to search in?</p>
34
2009-11-12T19:21:52Z
1,724,712
<p>See the <a href="http://docs.python.org/library/os.html#files-and-directories" rel="nofollow">os module</a> for os.walk or os.listdir</p> <p>See also this question <a href="http://stackoverflow.com/questions/229186/os-walk-without-digging-into-directories-below">http://stackoverflow.com/questions/229186/os-walk-wit...
1
2009-11-12T19:24:39Z
[ "python" ]
Find a file in python
1,724,693
<p>I have a file that may be in a different place on each user's machine. Is there a way to implement a search for the file? A way that I can pass the file's name and the directory tree to search in?</p>
34
2009-11-12T19:21:52Z
1,724,723
<p><a href="http://docs.python.org/library/os.html#os.walk">os.walk</a> is the answer, this will find the first match:</p> <pre><code>import os def find(name, path): for root, dirs, files in os.walk(path): if name in files: return os.path.join(root, name) </code></pre> <p>And this will find a...
84
2009-11-12T19:25:29Z
[ "python" ]
Find a file in python
1,724,693
<p>I have a file that may be in a different place on each user's machine. Is there a way to implement a search for the file? A way that I can pass the file's name and the directory tree to search in?</p>
34
2009-11-12T19:21:52Z
24,303,387
<p>For fast, OS-independent search, use <code>scandir</code></p> <p><a href="https://github.com/benhoyt/scandir/#readme" rel="nofollow">https://github.com/benhoyt/scandir/#readme</a></p> <p>Read <a href="http://bugs.python.org/issue11406" rel="nofollow">http://bugs.python.org/issue11406</a> for details why.</p>
0
2014-06-19T09:36:07Z
[ "python" ]
Find a file in python
1,724,693
<p>I have a file that may be in a different place on each user's machine. Is there a way to implement a search for the file? A way that I can pass the file's name and the directory tree to search in?</p>
34
2009-11-12T19:21:52Z
24,679,920
<p>I used a version of <code>os.walk</code> and on a larger directory got times around 3.5 sec. I tried two random solutions with no great improvement, then just did:</p> <pre><code>paths = [line[2:] for line in subprocess.check_output("find . -iname '*.txt'", shell=True).splitlines()] </code></pre> <p>While it's POS...
7
2014-07-10T15:00:13Z
[ "python" ]
How do I strip a character in Django admin after submission before sending value to dB?
1,725,175
<p>I'm more comfortable with PHP &amp; MySQL, don't know a lick of Python (yet) except for the teeny tiny bit I picked up using the Django admin recently...therefore please excuse this very stupid question that I'm embarrassed to ask. In PHP this would be trivial for me...</p> <p>I'm using a color picker (farbtastic) ...
0
2009-11-12T20:33:49Z
1,725,414
<p>Usually, you do a customized form to clean the data properly. It seems (at first) like overkill, but it's a very general solution.</p> <p>You have to (1) define the modified Form, and then (2) bind the modified Form into the Admin interface.</p> <p>On the other hand, you might be able to do this in the model's <c...
1
2009-11-12T21:07:14Z
[ "python", "django" ]
Lxml html xpath context
1,725,268
<p>I'm using lxml to parse a HTML file and I'd like to know how can I set the <code>context</code> of xpath search. What I mean I that I have a node element and want to make xpath search only inside this node as if it was the root one. For example, I have a form node and xpath search <code>//input</code> return only in...
8
2009-11-12T20:48:01Z
1,725,377
<p>XPath expression <code>//input</code> will match all input elements, anywhere in your document, while <code>.//input</code> will match all inside current context.</p> <p>Maybe if you improve your scenario description we can help you further.</p>
12
2009-11-12T21:02:37Z
[ "python", "xpath", "lxml" ]
Python Unit Tests - Am I using SetUp wrong?
1,725,366
<p>What am I doing wrong here?</p> <pre><code>import unittest class Test_1(unittest.TestCase): def SetUp(self): self.data = [] def test_data(self): self.assertEqual(len(self.data),0) if __name__=='__main__': unittest.main() </code></pre> <p>When I run it, it says:</p> <blockquote> <...
0
2009-11-12T21:01:39Z
1,725,397
<p>It must be named <code>setUp</code>, starting with a <strong>lowercase</strong> <code>s</code>.</p>
5
2009-11-12T21:04:12Z
[ "python", "unit-testing" ]
Can a python module have a __repr__?
1,725,515
<p>Can a python module have a __repr__? The idea would be to do something like:</p> <pre><code>import mymodule print mymodule </code></pre> <p>EDIT: precision: I mean a <strong>user-defined</strong> repr!</p>
4
2009-11-12T21:24:17Z
1,725,552
<p>As a matter of fact, many modules do [have a <code>__repr__</code>]!</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print(sys) &lt;module 'sys' (built-in)&gt; #read edit, however, this info didn't come from __repr__ ! </code></pre> <p>also try <code>dir(sys)</code> to see <code>__repr__</code> is there alo...
2
2009-11-12T21:30:08Z
[ "python", "module" ]
Can a python module have a __repr__?
1,725,515
<p>Can a python module have a __repr__? The idea would be to do something like:</p> <pre><code>import mymodule print mymodule </code></pre> <p>EDIT: precision: I mean a <strong>user-defined</strong> repr!</p>
4
2009-11-12T21:24:17Z
1,725,580
<p>Modules can have a <code>__repr__</code> function, but it isn't invoked when getting the representation of a module. </p> <p>So no, you can't do what you want.</p>
4
2009-11-12T21:34:37Z
[ "python", "module" ]
Can a python module have a __repr__?
1,725,515
<p>Can a python module have a __repr__? The idea would be to do something like:</p> <pre><code>import mymodule print mymodule </code></pre> <p>EDIT: precision: I mean a <strong>user-defined</strong> repr!</p>
4
2009-11-12T21:24:17Z
1,725,604
<p><strong>Short answer</strong>: basically the answer is no.</p> <p>But can't you find the functionality you are looking for using docstrings?</p> <pre>testmodule.py</pre> <pre><code>""" my module test does x and y """ class myclass(object): ... </code></pre> <pre>test.py</pre> <pre><code>import testmodule pr...
8
2009-11-12T21:39:04Z
[ "python", "module" ]
Can a python module have a __repr__?
1,725,515
<p>Can a python module have a __repr__? The idea would be to do something like:</p> <pre><code>import mymodule print mymodule </code></pre> <p>EDIT: precision: I mean a <strong>user-defined</strong> repr!</p>
4
2009-11-12T21:24:17Z
1,725,968
<p>No, because <code>__repr__</code> is a special method (I call it a <em>capability</em>), and it is only ever looked up on the class. Your module is just another instance of the module type, so however you would manage to define a <code>__repr__</code>, it would not be called!</p>
1
2009-11-12T22:51:30Z
[ "python", "module" ]
Can a python module have a __repr__?
1,725,515
<p>Can a python module have a __repr__? The idea would be to do something like:</p> <pre><code>import mymodule print mymodule </code></pre> <p>EDIT: precision: I mean a <strong>user-defined</strong> repr!</p>
4
2009-11-12T21:24:17Z
1,727,209
<p>You can achieve this effect--<em>if</em> you're willing to turn to the Dark Side of the Force.</p> <p>Add this to <strong>mymodule.py:</strong></p> <pre><code>import sys class MyReprModule(mymodule.__class__): def __init__(self, other): for attr in dir(other): setattr(self, attr, getattr(other, attr))...
4
2009-11-13T04:57:00Z
[ "python", "module" ]
Working with JSON in Python 2.6?
1,725,682
<p>I'm really new to Python, but I've picked a problem that actually pertains to work and I think as I figure out how to do it I'll learn along the way.</p> <p>I have a directory full of JSON-formatted files. I've gotten as far as importing everything in the directory into a list, and iterating through the list to do ...
2
2009-11-12T21:55:31Z
1,725,769
<p>What you get when you <code>json.load</code> a file containing the JSON form of a Javascript object such as <code>{'abc': 'def'}</code> is a Python <a href="http://docs.python.org/tutorial/datastructures.html#dictionaries">dictionary</a> (normally and affectionately called a <code>dict</code>) (which in this case ha...
11
2009-11-12T22:09:52Z
[ "python", "json" ]
Working with JSON in Python 2.6?
1,725,682
<p>I'm really new to Python, but I've picked a problem that actually pertains to work and I think as I figure out how to do it I'll learn along the way.</p> <p>I have a directory full of JSON-formatted files. I've gotten as far as importing everything in the directory into a list, and iterating through the list to do ...
2
2009-11-12T21:55:31Z
1,725,894
<p>To access all properties, try eval() statement before append a list.</p> <p>like:</p> <pre><code>import os #define path to reports reportspath = "reports/" # Gets all json files and imports them dir = os.listdir(reportspath) for fname in dir: json = eval(open(fname).read()) # now, json is a normal pyt...
-1
2009-11-12T22:35:40Z
[ "python", "json" ]
time.sleep and suspend (ie. standby and hibernate)
1,725,758
<p>For example, if I do time.sleep(100) and immediately hibernate my computer for 99 seconds, will the next statement be executed in 1 second or 100 seconds after waking up?</p> <p>If the answer is 1 second, how do you "sleep" 100 seconds, regardless of the length of hibernate/standby?</p>
1
2009-11-12T22:07:34Z
1,725,784
<p>Clearly, you must sleep according to real, elapsed time.</p> <p>The alternative (sleeping according to some other clock that "somehow" started and stopped) would be unmanageable. How would your application (which is sleeping) be notified of all this starting and stopping activity? Right, it would have to be woken...
1
2009-11-12T22:13:28Z
[ "python" ]
time.sleep and suspend (ie. standby and hibernate)
1,725,758
<p>For example, if I do time.sleep(100) and immediately hibernate my computer for 99 seconds, will the next statement be executed in 1 second or 100 seconds after waking up?</p> <p>If the answer is 1 second, how do you "sleep" 100 seconds, regardless of the length of hibernate/standby?</p>
1
2009-11-12T22:07:34Z
1,725,833
<p><code>time.sleep(N)</code> attempts to sleep <em>at least</em> N seconds of elapsed, AKA "wall-clock" time - of course there can be no guarantee that the sleep will last <em>exactly</em> N seconds; for example, the thread becomes ready to execute again at that time, but it cannot necessarily preempt whatever other t...
5
2009-11-12T22:23:18Z
[ "python" ]
time.sleep and suspend (ie. standby and hibernate)
1,725,758
<p>For example, if I do time.sleep(100) and immediately hibernate my computer for 99 seconds, will the next statement be executed in 1 second or 100 seconds after waking up?</p> <p>If the answer is 1 second, how do you "sleep" 100 seconds, regardless of the length of hibernate/standby?</p>
1
2009-11-12T22:07:34Z
1,725,912
<p>I don't know exactly what you are trying to achieve, but</p> <pre><code>for i in range(100):sleep(1) </code></pre> <p>might work, as the hibernate would only use up to 1 seconds worth of the sleep</p>
3
2009-11-12T22:38:35Z
[ "python" ]
Get functions called in a Python expression
1,726,251
<p>I have a database that holds the name of Python functions and a string for their code. I want the user to be able to enter a Python code and see the result. The problem is that I need to know the names of the functions they call in order to retrieve the code from the database. For instance, if they enter <code>cubic...
2
2009-11-12T23:54:51Z
1,726,293
<p>A quick example to you started. Note that you'll be expecting valid python semantics for this to work.</p> <p>You can extend this to also parse your arguments...</p> <pre><code>import token, tokenize, StringIO def extract_names(src): rawstr = StringIO.StringIO(unicode(src)) tokens = tokenize.generate_toke...
2
2009-11-13T00:05:12Z
[ "python" ]
Get functions called in a Python expression
1,726,251
<p>I have a database that holds the name of Python functions and a string for their code. I want the user to be able to enter a Python code and see the result. The problem is that I need to know the names of the functions they call in order to retrieve the code from the database. For instance, if they enter <code>cubic...
2
2009-11-12T23:54:51Z
1,726,372
<p>The built-in function <a href="http://docs.python.org/library/functions.html#compile">compile</a> will do that for you exactly:</p> <pre><code>&gt;&gt;&gt; compile("cubic_fit(1, 2, get_data())", '&lt;string&gt;', 'eval').co_names ('cubic_fit', 'get_data') </code></pre> <p>And it is safe to run. No code is actually...
11
2009-11-13T00:23:57Z
[ "python" ]
Get functions called in a Python expression
1,726,251
<p>I have a database that holds the name of Python functions and a string for their code. I want the user to be able to enter a Python code and see the result. The problem is that I need to know the names of the functions they call in order to retrieve the code from the database. For instance, if they enter <code>cubic...
2
2009-11-12T23:54:51Z
1,726,451
<p>If you just want the names, then the compile() and co_names method will work best.</p> <p>You also might take advantage of the capability of eval() to use any mapping object as its locals parameter. You could create a mapping object to look up and compile the objects from your database as needed by eval().</p> <p...
0
2009-11-13T00:52:11Z
[ "python" ]
Matplotlib: draw grid lines behind other graph elements
1,726,391
<p>In Matplotlib, I make dashed grid lines as follows:</p> <pre><code>fig = pylab.figure() ax = fig.add_subplot(1,1,1) ax.yaxis.grid(color='gray', linestyle='dashed') </code></pre> <p>however, I can't find out how (or even if it is possible) to make the grid lines be drawn behind other graph elements, such as bar...
49
2009-11-13T00:30:55Z
1,726,527
<p>According to this - <a href="http://old.nabble.com/axis-elements-and-zorder-td6119088.html">http://old.nabble.com/axis-elements-and-zorder-td6119088.html</a> - you can use Axis.set_axisbelow()</p> <p>(I am currently installing matplotlib for the first time, so have no idea if that's correct - I just found it by goo...
43
2009-11-13T01:13:26Z
[ "python", "matplotlib", "grid" ]
Matplotlib: draw grid lines behind other graph elements
1,726,391
<p>In Matplotlib, I make dashed grid lines as follows:</p> <pre><code>fig = pylab.figure() ax = fig.add_subplot(1,1,1) ax.yaxis.grid(color='gray', linestyle='dashed') </code></pre> <p>however, I can't find out how (or even if it is possible) to make the grid lines be drawn behind other graph elements, such as bar...
49
2009-11-13T00:30:55Z
15,612,303
<p>I had the same problem and the following worked:</p> <pre><code>[line.set_zorder(3) for line in ax.lines] fig.show() # to update </code></pre> <p>Increase <code>3</code>to a higher value if it does not work.</p>
6
2013-03-25T10:09:25Z
[ "python", "matplotlib", "grid" ]
Matplotlib: draw grid lines behind other graph elements
1,726,391
<p>In Matplotlib, I make dashed grid lines as follows:</p> <pre><code>fig = pylab.figure() ax = fig.add_subplot(1,1,1) ax.yaxis.grid(color='gray', linestyle='dashed') </code></pre> <p>however, I can't find out how (or even if it is possible) to make the grid lines be drawn behind other graph elements, such as bar...
49
2009-11-13T00:30:55Z
39,039,520
<p>To me, it was unclear how to apply andrew cooke's answer, so this is a complete solution based on that:</p> <pre><code>ax.set_axisbelow(True) ax.yaxis.grid(color='gray', linestyle='dashed') </code></pre>
5
2016-08-19T12:51:06Z
[ "python", "matplotlib", "grid" ]
In Python, how do I use urllib to see if a website is 404 or 200?
1,726,402
<p>How to get the code of the headers through urllib?</p>
78
2009-11-13T00:35:14Z
1,726,431
<p>The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.</p> <pre><code>&gt;&gt;&gt; a=urllib.urlopen('http://www.google.com/asdfsf') &gt;&gt;&gt; a.getcode() 404 &gt;&gt;&gt; a=urllib.urlopen('http://www.google.com/') &gt;&gt;&gt; a....
121
2009-11-13T00:45:14Z
[ "python", "urllib", "http-status-codes" ]
In Python, how do I use urllib to see if a website is 404 or 200?
1,726,402
<p>How to get the code of the headers through urllib?</p>
78
2009-11-13T00:35:14Z
1,726,434
<p>You can use <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml#urlerror">urllib2</a> as well:</p> <pre><code>import urllib2 req = urllib2.Request('http://www.python.org/fish.html') try: resp = urllib2.urlopen(req) except urllib2.HTTPError as e: if e.code == 404: # do something... ...
67
2009-11-13T00:46:01Z
[ "python", "urllib", "http-status-codes" ]
In Python, how do I use urllib to see if a website is 404 or 200?
1,726,402
<p>How to get the code of the headers through urllib?</p>
78
2009-11-13T00:35:14Z
6,629,421
<pre><code>import urllib2 try: fileHandle = urllib2.urlopen('http://www.python.org/fish.html') data = fileHandle.read() fileHandle.close() except urllib2.URLError, e: print 'you got an error with the code', e </code></pre>
5
2011-07-08T19:25:41Z
[ "python", "urllib", "http-status-codes" ]
In Python, how do I use urllib to see if a website is 404 or 200?
1,726,402
<p>How to get the code of the headers through urllib?</p>
78
2009-11-13T00:35:14Z
36,896,675
<p>For python 3:</p> <pre><code>import urllib.request, urllib.error url = 'http://www.google.com/asdfsf' try: conn = urllib.request.urlopen(url) except urllib.error.HTTPError as e: # Return code error (e.g. 404, 501, ...) # ... print(e.code) except urllib.error.URLError as e: # Not an HTTP-specifi...
6
2016-04-27T17:20:18Z
[ "python", "urllib", "http-status-codes" ]
python stdin eof
1,726,590
<p>How to pass python eof to stdin </p> <p>here is my code </p> <pre><code>p = Popen(commd,stdout=PIPE,stderr=PIPE,stdin=PIPE) o = p.communicate(inputstring)[0] </code></pre> <p>when i run the commd in command line after i input the inputstring windows still expecting a Ctrl+Z to finish accepting input.</p> <p>How...
3
2009-11-13T01:32:15Z
1,726,619
<pre><code>p.stdin.close() </code></pre> <p>after p.communicate, finishes the input and sends EOF to commd.</p>
8
2009-11-13T01:41:49Z
[ "python", "stdin", "eof" ]
How should unit tests be documented?
1,726,622
<p>I'm trying to improve the number and quality of tests in my Python projects. One of the the difficulties I've encountered as the number of tests increase is knowing what each test does and how it's supposed to help spot problems. I know that part of keeping track of tests is better unit test names (which has been ad...
16
2009-11-13T01:43:46Z
1,726,633
<p>I document most on my unit tests with the method name exclusively:</p> <pre><code>testInitializeSetsUpChessBoardCorrectly() testSuccessfulPromotionAddsCorrectPiece() </code></pre> <p>For almost 100% of my test cases, this clearly explains what the unit test is validating and that's all I use. However, in a few of...
11
2009-11-13T01:47:04Z
[ "python", "unit-testing", "documentation", "docstring" ]
How should unit tests be documented?
1,726,622
<p>I'm trying to improve the number and quality of tests in my Python projects. One of the the difficulties I've encountered as the number of tests increase is knowing what each test does and how it's supposed to help spot problems. I know that part of keeping track of tests is better unit test names (which has been ad...
16
2009-11-13T01:43:46Z
1,726,659
<p>The name of the test method should describe exactly what you are testing. The documentation should say what makes the test fail. </p>
3
2009-11-13T02:00:18Z
[ "python", "unit-testing", "documentation", "docstring" ]
How should unit tests be documented?
1,726,622
<p>I'm trying to improve the number and quality of tests in my Python projects. One of the the difficulties I've encountered as the number of tests increase is knowing what each test does and how it's supposed to help spot problems. I know that part of keeping track of tests is better unit test names (which has been ad...
16
2009-11-13T01:43:46Z
1,726,782
<p>You should use a combination of descriptive method names and comments in the doc string. A good way to do it is including a basic procedure and verification steps in the doc string. Then if you run these tests from some kind of testing framework that automates running the tests and collecting results, you can have...
1
2009-11-13T02:35:59Z
[ "python", "unit-testing", "documentation", "docstring" ]
How should unit tests be documented?
1,726,622
<p>I'm trying to improve the number and quality of tests in my Python projects. One of the the difficulties I've encountered as the number of tests increase is knowing what each test does and how it's supposed to help spot problems. I know that part of keeping track of tests is better unit test names (which has been ad...
16
2009-11-13T01:43:46Z
1,726,796
<p>Perhaps the issue isn't in how best to write test docstrings, but how to write the tests themselves? Refactoring tests in such a way that they're self documenting can go a long way, and your docstring won't go stale when the code changes.</p> <p>There's a few things you can do to make the tests clearer:</p> <ul> <...
5
2009-11-13T02:40:10Z
[ "python", "unit-testing", "documentation", "docstring" ]
How should unit tests be documented?
1,726,622
<p>I'm trying to improve the number and quality of tests in my Python projects. One of the the difficulties I've encountered as the number of tests increase is knowing what each test does and how it's supposed to help spot problems. I know that part of keeping track of tests is better unit test names (which has been ad...
16
2009-11-13T01:43:46Z
1,731,545
<p>When the test fails (which should be before it ever passes) you should see the error message and be able to tell what's up. That only happens if you plan it that way.</p> <p>It's entirely a matter of the naming of the test class, the test method, and the assert message. When a test fails, and you can't tell what i...
0
2009-11-13T20:01:28Z
[ "python", "unit-testing", "documentation", "docstring" ]
Using keys with spaces
1,726,640
<p>Is there a way to do something like the following in Django templates?</p> <pre><code> {% for hop in hops%} &lt;tr&gt; &lt;td&gt;{{ hop.name }}&lt;/td&gt; &lt;td&gt;{{ hop.mass }}&lt;/td&gt; &lt;td&gt;{{ hop."boil time" }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre> <p>The hop....
2
2009-11-13T01:50:47Z
1,726,679
<p>The best way to get at it is to sneak the property name into another variable, like so:</p> <pre><code>{% for key, value in hop.items %} {% ifequal key 'boil time' %} {{ value }} {% endifequal %} {% endfor %} </code></pre> <p>In Django 0.96 (the version used by Google AppEngine) the templating lang...
1
2009-11-13T02:06:27Z
[ "python", "django", "google-app-engine", "dictionary", "django-templates" ]