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
What's the most efficient way to find one of several substrings in Python?
842,856
<p>I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. </p> <p>I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings.</p> <p>To clarify, for '012cat' the result is 3, and for '0123dog789ca...
21
2009-05-09T07:20:49Z
842,860
<pre><code>subs = ['cat', 'fish', 'dog'] sentences = ['0123dog789cat'] import re subs = re.compile("|".join(subs)) def search(): for sentence in sentences: result = subs.search(sentence) if result != None: return (result.group(), result.span()[0]) # ('dog', 4) </code></pre>
4
2009-05-09T07:24:07Z
[ "python", "regex", "string", "substring" ]
What's the most efficient way to find one of several substrings in Python?
842,856
<p>I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. </p> <p>I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings.</p> <p>To clarify, for '012cat' the result is 3, and for '0123dog789ca...
21
2009-05-09T07:20:49Z
842,871
<p>I would assume a regex is better than checking for each substring individually because <em>conceptually</em> the regular expression is modeled as a DFA, and so as the input is consumed all matches are being tested for at the same time (resulting in one scan of the input string).</p> <p>So, here is an example:</p> ...
30
2009-05-09T07:34:52Z
[ "python", "regex", "string", "substring" ]
What's the most efficient way to find one of several substrings in Python?
842,856
<p>I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. </p> <p>I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings.</p> <p>To clarify, for '012cat' the result is 3, and for '0123dog789ca...
21
2009-05-09T07:20:49Z
842,878
<p>This is a vague, theoretical answer with no code provided, but I hope it can point you in the right direction.</p> <p>First, you will need a more efficient lookup for your substring list. I would recommend some sort of tree structure. Start with a root, then add an <code>'a'</code> node if any substrings start with...
2
2009-05-09T07:40:42Z
[ "python", "regex", "string", "substring" ]
What's the most efficient way to find one of several substrings in Python?
842,856
<p>I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. </p> <p>I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings.</p> <p>To clarify, for '012cat' the result is 3, and for '0123dog789ca...
21
2009-05-09T07:20:49Z
842,904
<p>First of all, I would suggest you to sort the initial list in ascending order. Because scanning for a shorter substring is faster that scanning for a longer substring.</p>
0
2009-05-09T08:02:09Z
[ "python", "regex", "string", "substring" ]
What's the most efficient way to find one of several substrings in Python?
842,856
<p>I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. </p> <p>I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings.</p> <p>To clarify, for '012cat' the result is 3, and for '0123dog789ca...
21
2009-05-09T07:20:49Z
842,955
<p>How about this one.</p> <pre><code>&gt;&gt;&gt; substrings = ['cat', 'fish', 'dog'] &gt;&gt;&gt; _string = '0123dog789cat' &gt;&gt;&gt; found = map(lambda x: (_string.index(x), x), filter(lambda x: x in _string, substrings)) [(10, 'cat'), (4, 'dog')] &gt;&gt;&gt; if found: &gt;&gt;&gt; min(found, key=lambda x: ...
0
2009-05-09T08:31:56Z
[ "python", "regex", "string", "substring" ]
What's the most efficient way to find one of several substrings in Python?
842,856
<p>I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. </p> <p>I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings.</p> <p>To clarify, for '012cat' the result is 3, and for '0123dog789ca...
21
2009-05-09T07:20:49Z
844,156
<p>I just want to point out the time difference between DisplacedAussie's answer and Tom's answer. Both were fast when used once, so you shouldn't have any noticeable wait for either, but when you time them:</p> <pre><code>import random import re import string words = [] letters_and_digits = "%s%s" % (string.letters,...
3
2009-05-09T21:54:58Z
[ "python", "regex", "string", "substring" ]
How can I use Django admin list and filterering in my own views?
843,182
<p>I’m just beginning to learn Django and I like the automatic listing in Django admin and the way you can configure filters and what columns to show. Is it possible to use it in my own applications?</p> <p>I’ve looked in the source for the admin and figured out that I probably want to subclass the “ChangeListâ€...
1
2009-05-09T12:05:13Z
843,222
<p>You're better off doing the following.</p> <ol> <li><p>Define a regular old Django query for your various kinds of filters. These are very easy to write.</p></li> <li><p>Use the supplied <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#list-detail-generic-views" rel="nofollow">generic</a> view fun...
1
2009-05-09T12:32:50Z
[ "python", "django", "filter", "django-views", "django-queryset" ]
How to render contents of a tag in unicode in BeautifulSoup?
843,227
<p>This is a soup from a WordPress post detail page:</p> <pre><code>content = soup.body.find('div', id=re.compile('post')) title = content.h2.extract() item['title'] = unicode(title.string) item['content'] = u''.join(map(unicode, content.contents)) </code></pre> <p>I want to omit the enclosing <code>div</code> tag wh...
2
2009-05-09T12:38:38Z
843,239
<p>Have you tried:</p> <pre><code>unicode(content) </code></pre> <p>It converts <code>content</code>'s markup to a single Unicode string.</p> <p>Edit: If you don't want the enclosing tag, try:</p> <pre><code>content.renderContents() </code></pre>
6
2009-05-09T12:44:51Z
[ "python", "xml", "web-applications", "screen-scraping", "beautifulsoup" ]
Logout or switch user in Windows using Python
843,268
<p>I want to write a small program that given a time (in minutes) as input, sleeps in the background for that time, and then forces a return to the "switch user screen" (equivalent to the Winkey+L combination) or logs off a user (may be another user logged in on the same machine).</p> <p>What functions or libraries in...
1
2009-05-09T13:05:48Z
843,280
<p>Maybe you can use os.popen or <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> to run windows command line for logout. I think logoff is the command. (According to this <a href="http://www.simplehelp.net/2006/09/12/windows-run-commands/" rel="nofollow">page</a>)</p>
1
2009-05-09T13:10:56Z
[ "python", "windows" ]
Logout or switch user in Windows using Python
843,268
<p>I want to write a small program that given a time (in minutes) as input, sleeps in the background for that time, and then forces a return to the "switch user screen" (equivalent to the Winkey+L combination) or logs off a user (may be another user logged in on the same machine).</p> <p>What functions or libraries in...
1
2009-05-09T13:05:48Z
843,294
<p>I think you must use windows API, and run by python. use os.system('logoff'); (or logout, I forget) it is not tested, because I am using ubuntu now...</p>
0
2009-05-09T13:16:07Z
[ "python", "windows" ]
Logout or switch user in Windows using Python
843,268
<p>I want to write a small program that given a time (in minutes) as input, sleeps in the background for that time, and then forces a return to the "switch user screen" (equivalent to the Winkey+L combination) or logs off a user (may be another user logged in on the same machine).</p> <p>What functions or libraries in...
1
2009-05-09T13:05:48Z
843,298
<p>There seems to be a simple way of locking a computer using no Python libraries except for ctypes:</p> <pre><code>import ctypes ctypes.windll.user32.LockWorkStation () </code></pre> <p>Source: <a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/lock%5Fmy%5Fworkstation.html" rel="nofollow">Tim Golden's Pytho...
7
2009-05-09T13:18:10Z
[ "python", "windows" ]
Logout or switch user in Windows using Python
843,268
<p>I want to write a small program that given a time (in minutes) as input, sleeps in the background for that time, and then forces a return to the "switch user screen" (equivalent to the Winkey+L combination) or logs off a user (may be another user logged in on the same machine).</p> <p>What functions or libraries in...
1
2009-05-09T13:05:48Z
9,589,872
<p>To switch users, you can use this <strong>Win32 API</strong> function <code>WTSDisconnectSession(HANDLE hServer, DWORD SessionId, BOOL bWait)</code></p> <pre><code>#include "WtsApi32.h" BOOL OsofemSwitchUser() { //Switch User return WTSDisconnectSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, TRUE); } </co...
1
2012-03-06T18:41:27Z
[ "python", "windows" ]
How do I check if a variable exists?
843,277
<p>I want to check if a variable exists. Now I'm doing something like this:</p> <pre><code>try: myVar except NameError: # Do something. </code></pre> <p>Are there other ways without exceptions?</p>
402
2009-05-09T13:10:31Z
843,286
<p><code>catch</code> is called <a href="http://docs.python.org/reference/compound%5Fstmts.html#the-try-statement" rel="nofollow"><code>except</code></a> in Python. other than that it's fine for such simple cases. There's the <a href="http://docs.python.org/library/exceptions.html#exceptions.AttributeError" rel="nofoll...
4
2009-05-09T13:12:59Z
[ "python", "exception", "variables" ]
How do I check if a variable exists?
843,277
<p>I want to check if a variable exists. Now I'm doing something like this:</p> <pre><code>try: myVar except NameError: # Do something. </code></pre> <p>Are there other ways without exceptions?</p>
402
2009-05-09T13:10:31Z
843,293
<p>To check the existence of a local variable:</p> <pre><code>if 'myVar' in locals(): # myVar exists. </code></pre> <p>To check the existence of a global variable:</p> <pre><code>if 'myVar' in globals(): # myVar exists. </code></pre> <p>To check if an object has an attribute:</p> <pre><code>if hasattr(obj, 'at...
735
2009-05-09T13:16:05Z
[ "python", "exception", "variables" ]
How do I check if a variable exists?
843,277
<p>I want to check if a variable exists. Now I'm doing something like this:</p> <pre><code>try: myVar except NameError: # Do something. </code></pre> <p>Are there other ways without exceptions?</p>
402
2009-05-09T13:10:31Z
843,306
<p>The use of variables that haven't been defined is actually a bad thing in any language since it indicates that the logic of the program hasn't been thought through properly.</p> <p>Python will assume you know what you're doing, otherwise you'd be using VB :-).</p> <p>The following trick, which is similar to yours,...
50
2009-05-09T13:19:28Z
[ "python", "exception", "variables" ]
How do I check if a variable exists?
843,277
<p>I want to check if a variable exists. Now I'm doing something like this:</p> <pre><code>try: myVar except NameError: # Do something. </code></pre> <p>Are there other ways without exceptions?</p>
402
2009-05-09T13:10:31Z
843,326
<p>Using try/except is the best way to test for a variable's existence. But there's almost certainly a better way of doing whatever it is you're doing than setting/testing global variables.</p> <p>For example, if you want to initialize a module-level variable the first time you call some function, you're better off wi...
9
2009-05-09T13:27:55Z
[ "python", "exception", "variables" ]
How do I check if a variable exists?
843,277
<p>I want to check if a variable exists. Now I'm doing something like this:</p> <pre><code>try: myVar except NameError: # Do something. </code></pre> <p>Are there other ways without exceptions?</p>
402
2009-05-09T13:10:31Z
3,664,379
<p>A way that often works well for handling this kind of situation is to not explicitly check if the variable exists but just go ahead and wrap the first usage of the possibly non-existing variable in a try/except NameError:</p> <pre><code># Search for entry. for x in y: if x == 3: found = x # Work with found e...
3
2010-09-08T03:05:58Z
[ "python", "exception", "variables" ]
How do I check if a variable exists?
843,277
<p>I want to check if a variable exists. Now I'm doing something like this:</p> <pre><code>try: myVar except NameError: # Do something. </code></pre> <p>Are there other ways without exceptions?</p>
402
2009-05-09T13:10:31Z
22,645,635
<p>I will assume that the test is going to be used in a function, similar to user97370's answer. I don't like that answer because it pollutes the global namespace. One way to fix it is to use a class instead:</p> <pre><code>class InitMyVariable(object): my_variable = None def __call__(self): if self.my_variable...
1
2014-03-25T20:31:42Z
[ "python", "exception", "variables" ]
How do I check if a variable exists?
843,277
<p>I want to check if a variable exists. Now I'm doing something like this:</p> <pre><code>try: myVar except NameError: # Do something. </code></pre> <p>Are there other ways without exceptions?</p>
402
2009-05-09T13:10:31Z
26,616,037
<p>for objects/modules, you can also </p> <pre><code>'var' in dir(obj) </code></pre> <p>For example, </p> <pre><code>&gt;&gt;&gt; class Something(object): ... pass ... &gt;&gt;&gt; c = Something() &gt;&gt;&gt; c.a = 1 &gt;&gt;&gt; 'a' in dir(c) True &gt;&gt;&gt; 'b' in dir(c) False </code></pre>
5
2014-10-28T18:39:57Z
[ "python", "exception", "variables" ]
How do I check if a variable exists?
843,277
<p>I want to check if a variable exists. Now I'm doing something like this:</p> <pre><code>try: myVar except NameError: # Do something. </code></pre> <p>Are there other ways without exceptions?</p>
402
2009-05-09T13:10:31Z
30,651,757
<p>A simple way is to initialize it at first saying <code>myVar = none;</code></p> <p>Then later on: </p> <pre><code>if myVar: #Do something </code></pre>
2
2015-06-04T18:46:22Z
[ "python", "exception", "variables" ]
How do I check if a variable exists?
843,277
<p>I want to check if a variable exists. Now I'm doing something like this:</p> <pre><code>try: myVar except NameError: # Do something. </code></pre> <p>Are there other ways without exceptions?</p>
402
2009-05-09T13:10:31Z
38,813,771
<p>try:`</p> <pre><code>Myvariable = ['v', 'a', 'r'] try: print(Myvariable) except Nameerror: print('variable \"Myvariable\" not found') </code></pre> <p>hope this helps!</p>
-2
2016-08-07T11:43:52Z
[ "python", "exception", "variables" ]
Why is django giving error: no module named django.core?
843,383
<p>I get the error in question when I attempt to create a project. I followed the instructions found at <a href="http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/" rel="nofollow">how to install python an django in windows vista</a>.</p>
5
2009-05-09T14:06:16Z
843,492
<p>Most likely you don't have Django on your Python path. To test, quickly fire up Python and run:</p> <pre><code>&gt;&gt;&gt; import django </code></pre> <p>If that fails, it's just a matter of getting Django onto your Python path. Either you set the environment variable, or you move django into your <code>python2x/...
1
2009-05-09T15:26:58Z
[ "python", "windows", "django", "django-admin" ]
Why is django giving error: no module named django.core?
843,383
<p>I get the error in question when I attempt to create a project. I followed the instructions found at <a href="http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/" rel="nofollow">how to install python an django in windows vista</a>.</p>
5
2009-05-09T14:06:16Z
843,530
<p>Also make sure that you have permission to access all of django's files. I've seen these kinds of errors happen because of permissions issues before.</p> <p><strong>EDIT</strong>: I haven't tried it out, but there's a link on that page to <a href="http://www.instantdjango.com/" rel="nofollow">Instant Django</a>, ...
3
2009-05-09T15:52:07Z
[ "python", "windows", "django", "django-admin" ]
Why is django giving error: no module named django.core?
843,383
<p>I get the error in question when I attempt to create a project. I followed the instructions found at <a href="http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/" rel="nofollow">how to install python an django in windows vista</a>.</p>
5
2009-05-09T14:06:16Z
2,172,331
<p>You can get around this problem by providing the full path to your django-admin.py file</p> <pre><code>python c:\python25\scripts\django-admin.py startproject mysite </code></pre>
1
2010-01-31T16:09:14Z
[ "python", "windows", "django", "django-admin" ]
Why is django giving error: no module named django.core?
843,383
<p>I get the error in question when I attempt to create a project. I followed the instructions found at <a href="http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/" rel="nofollow">how to install python an django in windows vista</a>.</p>
5
2009-05-09T14:06:16Z
12,980,351
<p>From your command line (<code>cmd</code>) run "ftype Python.File" and make sure that your .py files are being executed by the correct version/installation of Python. </p> <p>It's possible another application has surreptitiously changed this under the hood.</p>
1
2012-10-19T18:32:36Z
[ "python", "windows", "django", "django-admin" ]
Python: get http headers from urllib call?
843,392
<p>does urllib fetch the whole page? when a urlopen call is made? </p> <p>I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call?</p> <pre...
36
2009-05-09T14:11:51Z
843,401
<p>What about sending a HEAD request instead of a normal GET request. The following snipped (copied from a similar <a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">question</a>) does exactly that. </p> <pre><code>&gt;&gt;&gt; import httplib &gt;&gt;&gt; conn = httplib.H...
37
2009-05-09T14:17:34Z
[ "python", "urllib", "forwarding" ]
Python: get http headers from urllib call?
843,392
<p>does urllib fetch the whole page? when a urlopen call is made? </p> <p>I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call?</p> <pre...
36
2009-05-09T14:11:51Z
843,403
<p>urllib2.urlopen does an HTTP GET (or POST if you supply a data argument), not an HTTP HEAD (if it did the latter, you couldn't do readlines or other accesses to the page body, of course).</p>
7
2009-05-09T14:18:33Z
[ "python", "urllib", "forwarding" ]
Python: get http headers from urllib call?
843,392
<p>does urllib fetch the whole page? when a urlopen call is made? </p> <p>I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call?</p> <pre...
36
2009-05-09T14:11:51Z
1,640,946
<p>Use the <code>response.info()</code> method to get the headers.</p> <p>From the <a href="http://docs.python.org/library/urllib2.html?highlight=urllib2#module-urllib2">urllib2 docs</a>:</p> <blockquote> <p>urllib2.urlopen(url[, data][, timeout])</p> <p>...</p> <p>This function returns a file-like object...
36
2009-10-29T00:17:31Z
[ "python", "urllib", "forwarding" ]
Python: get http headers from urllib call?
843,392
<p>does urllib fetch the whole page? when a urlopen call is made? </p> <p>I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call?</p> <pre...
36
2009-05-09T14:11:51Z
9,350,032
<p>Actually, it appears that urllib2 can do an HTTP HEAD request.</p> <p>The <a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">question</a> that @reto linked to, above, shows how to get urllib2 to do a HEAD request.</p> <p>Here's my take on it:</p> <pre><code>import ur...
15
2012-02-19T14:27:46Z
[ "python", "urllib", "forwarding" ]
Python: get http headers from urllib call?
843,392
<p>does urllib fetch the whole page? when a urlopen call is made? </p> <p>I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call?</p> <pre...
36
2009-05-09T14:11:51Z
9,939,222
<p>One-liner:</p> <pre><code>$ python -c "import urllib2; print urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)).open(urllib2.Request('http://google.com'))" </code></pre>
3
2012-03-30T08:11:23Z
[ "python", "urllib", "forwarding" ]
Python: get http headers from urllib call?
843,392
<p>does urllib fetch the whole page? when a urlopen call is made? </p> <p>I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call?</p> <pre...
36
2009-05-09T14:11:51Z
24,992,147
<pre><code>def _GetHtmlPage(self, addr): headers = { 'User-Agent' : self.userAgent, ' Cookie' : self.cookies} req = urllib2.Request(addr) response = urllib2.urlopen(req) print "ResponseInfo=" print response.info() resultsHtml = unicode(response.read(), self.encoding) return resultsHtml <...
-1
2014-07-28T09:25:02Z
[ "python", "urllib", "forwarding" ]
Barchart (o plot) 3D in Python
843,449
<p>I need to plot some data in various forms. Currently I'm using <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> and I'm fairly happy with the plots I'm able to produce.</p> <p>This question is on how to plot the last one. The data is similar to the "distance table", like <a href="http...
6
2009-05-09T14:53:16Z
843,561
<p><a href="http://code.enthought.com/projects/mayavi/" rel="nofollow">MyavaVi2</a> can make <a href="http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html#d-data" rel="nofollow">3D barcharts</a> (scroll down a bit). Once you have <a href="http://en.wikipedia.org/wiki/MayaVi" rel="nofollow">...
5
2009-05-09T16:10:51Z
[ "python", "matplotlib", "plot", "3d" ]
Barchart (o plot) 3D in Python
843,449
<p>I need to plot some data in various forms. Currently I'm using <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> and I'm fairly happy with the plots I'm able to produce.</p> <p>This question is on how to plot the last one. The data is similar to the "distance table", like <a href="http...
6
2009-05-09T14:53:16Z
843,640
<p>For some time now, matplotlib had no 3D support, but it has been added back <a href="http://thread.gmane.org/gmane.comp.python.matplotlib.devel/6762/focus=6820" rel="nofollow">recently</a>. You will need to use the svn version, since no release has been made since, and the documentation is a little sparse (see examp...
7
2009-05-09T16:56:07Z
[ "python", "matplotlib", "plot", "3d" ]
Barchart (o plot) 3D in Python
843,449
<p>I need to plot some data in various forms. Currently I'm using <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> and I'm fairly happy with the plots I'm able to produce.</p> <p>This question is on how to plot the last one. The data is similar to the "distance table", like <a href="http...
6
2009-05-09T14:53:16Z
846,214
<p>You might check out Chart Director:</p> <blockquote> <p><a href="http://www.advsofteng.com" rel="nofollow">http://www.advsofteng.com</a></p> </blockquote> <p>It has a pretty wide variety of charts and graphs and has a nice Python (and several other languages) API.</p> <p>There are two editions: The free version...
0
2009-05-10T22:09:16Z
[ "python", "matplotlib", "plot", "3d" ]
Barchart (o plot) 3D in Python
843,449
<p>I need to plot some data in various forms. Currently I'm using <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> and I'm fairly happy with the plots I'm able to produce.</p> <p>This question is on how to plot the last one. The data is similar to the "distance table", like <a href="http...
6
2009-05-09T14:53:16Z
852,343
<p>One more possibility is Gnuplot, which can draw some kind of <a href="http://t16web.lanl.gov/Kawano/gnuplot/plotpm3d-e.html#6.9" rel="nofollow">pseudo 3D bar charts</a>, and <a href="http://gnuplot-py.sourceforge.net/" rel="nofollow">gnuplot.py</a> allows interfacing to Gnuplot from Python. I have not tried it mysel...
5
2009-05-12T11:50:19Z
[ "python", "matplotlib", "plot", "3d" ]
Barchart (o plot) 3D in Python
843,449
<p>I need to plot some data in various forms. Currently I'm using <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> and I'm fairly happy with the plots I'm able to produce.</p> <p>This question is on how to plot the last one. The data is similar to the "distance table", like <a href="http...
6
2009-05-09T14:53:16Z
34,894,803
<p>This is my code for a simple Bar-3d using matplotlib. </p> <pre><code>import mpl_toolkits from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt %matplotlib inline ## The value you want to plot zval=[0.020752244,0.078514652,0.170302899,0.29543857,0.45358061,0.021255922,0.079022499,\ 0.17...
1
2016-01-20T08:19:08Z
[ "python", "matplotlib", "plot", "3d" ]
How does garbage collection in Python work with class methods?
843,459
<pre><code>class example: def exampleMethod(self): aVar = 'some string' return aVar </code></pre> <p>In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?</p>
3
2009-05-09T15:03:38Z
843,489
<p>The variable is never deallocated.</p> <p>The object (in this case a string, with a value of <code>'some string'</code> is reused again and again, so that object can never be deallocated.</p> <p>Objects are deallocated when no variable refers to the object. Think of this.</p> <pre><code>a = 'hi mom' a = 'next va...
6
2009-05-09T15:22:55Z
[ "python", "garbage-collection" ]
How does garbage collection in Python work with class methods?
843,459
<pre><code>class example: def exampleMethod(self): aVar = 'some string' return aVar </code></pre> <p>In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?</p>
3
2009-05-09T15:03:38Z
843,498
<p>Every time You assign an object to a variable, You increase this object's reference counter.</p> <pre><code>a = MyObject() # +1, so it's at 1 b = a # +1, so it's now 2 a = 'something else' # -1, so it's 1 b = 'something else' # -1, so it's 0 </code></pre> <p>Noone can access this the MyObject object We have create...
4
2009-05-09T15:31:25Z
[ "python", "garbage-collection" ]
How does garbage collection in Python work with class methods?
843,459
<pre><code>class example: def exampleMethod(self): aVar = 'some string' return aVar </code></pre> <p>In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?</p>
3
2009-05-09T15:03:38Z
843,525
<p>From your example, if you call example.exampleMethod() , without assigning the results (eg. <code>a = example.exampleMethod()</code>) then it will be deallocated straight away (in CPython), as CPython uses a reference counting mechanism. Strings aren't a very good example to use, because they also have a number of ...
3
2009-05-09T15:50:36Z
[ "python", "garbage-collection" ]
How does garbage collection in Python work with class methods?
843,459
<pre><code>class example: def exampleMethod(self): aVar = 'some string' return aVar </code></pre> <p>In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?</p>
3
2009-05-09T15:03:38Z
843,579
<p>As in Nico's answer, it depends on what you do with the result returned by exampleMethod. Python (or CPython anyway) uses reference counting. During the method, aVar references the string, while after that the variable aVar is deleted, which may leave no references, in which case, it is deleted.</p> <p>Below is an ...
0
2009-05-09T16:23:19Z
[ "python", "garbage-collection" ]
Using virtualenv on Mac OS X
843,531
<p>I've been using virtualenv on Ubuntu and it rocks, so I'm trying to use it on my Mac and I'm having trouble.</p> <p>The <code>virtualenv</code> command successfully creates the directory, and <code>easy_install</code> gladly installs packages in it, but I can't import anything I install. It seems like <code>sys.pat...
2
2009-05-09T15:53:02Z
843,539
<p>I've not had any problems with the same OS X/Python/virtualenv version (OS X 10.5.6, Python 2.5.1, virtualenv 1.3.1)</p> <pre><code>$ virtualenv test New python executable in test/bin/python Installing setuptools............done. $ source test/bin/activate (test)$ which python /Users/dbr/test/bin/python $ echo $PAT...
5
2009-05-09T16:00:13Z
[ "python", "osx", "virtualenv" ]
Using virtualenv on Mac OS X
843,531
<p>I've been using virtualenv on Ubuntu and it rocks, so I'm trying to use it on my Mac and I'm having trouble.</p> <p>The <code>virtualenv</code> command successfully creates the directory, and <code>easy_install</code> gladly installs packages in it, but I can't import anything I install. It seems like <code>sys.pat...
2
2009-05-09T15:53:02Z
895,855
<p>It turns out that my problems with virtualenv were my own fault: I had configured my <code>.bash_profile</code> to muck with the <code>PYTHONPATH</code> environment variable, which caused the import problems.</p> <p>Thank you to everyone who took the time to answer; sorry for not investigating the problem further o...
1
2009-05-21T23:54:38Z
[ "python", "osx", "virtualenv" ]
Parse JavaScript to instrument code
843,546
<p>I need to split a JavaScript file into single instructions. For example</p> <pre><code>a = 2; foo() function bar() { b = 5; print("spam"); } </code></pre> <p>has to be separated into three instructions. (assignment, function call and function definition).</p> <p>Basically I need to instrument the code, in...
7
2009-05-09T16:05:33Z
843,591
<p>Why not use a JavaScript parser? There are lots, including a Python API for ANTLR and a Python wrapper around SpiderMonkey.</p>
4
2009-05-09T16:28:39Z
[ "javascript", "python", "parsing", "spidermonkey" ]
Parse JavaScript to instrument code
843,546
<p>I need to split a JavaScript file into single instructions. For example</p> <pre><code>a = 2; foo() function bar() { b = 5; print("spam"); } </code></pre> <p>has to be separated into three instructions. (assignment, function call and function definition).</p> <p>Basically I need to instrument the code, in...
7
2009-05-09T16:05:33Z
843,593
<p>Why not use an existing JavaScript interpreter like <a href="http://www.mozilla.org/rhino/" rel="nofollow">Rhino</a> (Java) or <a href="http://pypi.python.org/pypi/python-spidermonkey" rel="nofollow">python-spidermonkey</a> (not sure whether this one is still alive)? It will parse the JS and then you can examine the...
0
2009-05-09T16:29:54Z
[ "javascript", "python", "parsing", "spidermonkey" ]
Parse JavaScript to instrument code
843,546
<p>I need to split a JavaScript file into single instructions. For example</p> <pre><code>a = 2; foo() function bar() { b = 5; print("spam"); } </code></pre> <p>has to be separated into three instructions. (assignment, function call and function definition).</p> <p>Basically I need to instrument the code, in...
7
2009-05-09T16:05:33Z
843,805
<p>Why not try a javascript beautifier?</p> <p>For example <a href="http://jsbeautifier.org/" rel="nofollow">http://jsbeautifier.org/</a></p> <p>Or see <a href="http://stackoverflow.com/questions/18985/javascript-beautifier">http://stackoverflow.com/questions/18985/javascript-beautifier</a></p>
0
2009-05-09T18:28:34Z
[ "javascript", "python", "parsing", "spidermonkey" ]
Parse JavaScript to instrument code
843,546
<p>I need to split a JavaScript file into single instructions. For example</p> <pre><code>a = 2; foo() function bar() { b = 5; print("spam"); } </code></pre> <p>has to be separated into three instructions. (assignment, function call and function definition).</p> <p>Basically I need to instrument the code, in...
7
2009-05-09T16:05:33Z
1,338,857
<p>JavaScript is tricky to parse; you need a full JavaScript parser. The <a href="http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html" rel="nofollow">DMS Software Reengineering Toolkit</a> can parse full JavaScript and build a corresponding <a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree" rel="nofoll...
2
2009-08-27T04:32:51Z
[ "javascript", "python", "parsing", "spidermonkey" ]
Parse JavaScript to instrument code
843,546
<p>I need to split a JavaScript file into single instructions. For example</p> <pre><code>a = 2; foo() function bar() { b = 5; print("spam"); } </code></pre> <p>has to be separated into three instructions. (assignment, function call and function definition).</p> <p>Basically I need to instrument the code, in...
7
2009-05-09T16:05:33Z
7,461,246
<p>Forget my parser. <a href="https://bitbucket.org/mvantellingen/pyjsparser" rel="nofollow">https://bitbucket.org/mvantellingen/pyjsparser</a> is great and complete parser. I've fixed a couple of it's bugs here: <a href="https://bitbucket.org/nullie/pyjsparser" rel="nofollow">https://bitbucket.org/nullie/pyjsparser</a...
0
2011-09-18T11:44:45Z
[ "javascript", "python", "parsing", "spidermonkey" ]
Writing a __init__ function to be used in django model
843,580
<p>I'm trying to write an <code>__init__</code> function for one of my models so that I can create an object by doing</p> <pre><code>p = User('name','email') </code></pre> <p>When I write the model, I have </p> <pre><code> def __init__(self, name, email, house_id, password): models.Model.__init__(self...
40
2009-05-09T16:23:35Z
843,669
<p>Django expects the signature of a model's constructor to be <code>(self, *args, **kwargs)</code>, or some reasonable facsimile. Your changing the signature to something completely incompatible has broken it.</p>
34
2009-05-09T17:10:33Z
[ "python", "django" ]
Writing a __init__ function to be used in django model
843,580
<p>I'm trying to write an <code>__init__</code> function for one of my models so that I can create an object by doing</p> <pre><code>p = User('name','email') </code></pre> <p>When I write the model, I have </p> <pre><code> def __init__(self, name, email, house_id, password): models.Model.__init__(self...
40
2009-05-09T16:23:35Z
843,740
<p>Relying on Django's built-in functionality and passing named parameters would be the simplest way to go.</p> <pre><code>p = User(name="Fred", email="fred@example.com") </code></pre> <p>But if you're set on saving some keystrokes, I'd suggest adding a static convenience method to the class instead of messing with t...
65
2009-05-09T17:55:47Z
[ "python", "django" ]
Writing a __init__ function to be used in django model
843,580
<p>I'm trying to write an <code>__init__</code> function for one of my models so that I can create an object by doing</p> <pre><code>p = User('name','email') </code></pre> <p>When I write the model, I have </p> <pre><code> def __init__(self, name, email, house_id, password): models.Model.__init__(self...
40
2009-05-09T16:23:35Z
28,050,067
<p>Don't create models with args parameters. If you make a model like so:</p> <pre><code> User('name','email') </code></pre> <p>It becomes very unreadable very quickly as most models require more than that for initialization. You could very easily end up with:</p> <pre><code>User('Bert', 'Reynolds', 'me@bertreynold...
1
2015-01-20T16:13:03Z
[ "python", "django" ]
Writing a __init__ function to be used in django model
843,580
<p>I'm trying to write an <code>__init__</code> function for one of my models so that I can create an object by doing</p> <pre><code>p = User('name','email') </code></pre> <p>When I write the model, I have </p> <pre><code> def __init__(self, name, email, house_id, password): models.Model.__init__(self...
40
2009-05-09T16:23:35Z
28,218,753
<p>The correct answer is to avoid overriding <code>__init__</code> and write a classmethod as described in the <a href="https://docs.djangoproject.com/en/1.7/ref/models/instances/#creating-objects">Django docs</a>.</p> <p>But this could be done like you're trying, you just need to add in <code>*args, **kwargs</code> t...
5
2015-01-29T15:45:04Z
[ "python", "django" ]
call function between time intervals
843,614
<p>In app engine I would like to call a function if the current time is between a particular interval. This is what I am doing now. </p> <pre><code>ist_time = datetime.utcnow() + timedelta(hours=5, minutes = 30) ist_midnight = ist_time.replace(hour=0, minute=0, second=0, microsecond=0) market_open = ist_midnight + tim...
0
2009-05-09T16:42:36Z
843,644
<p>This is more compact, but not so obvious:</p> <pre><code>if '09:55' &lt;= time.strftime( '%H:%M', time.gmtime((time.time() + 60 * (5 * 60 + 30)))) &lt;= '16:01': check_for_updates() </code></pre> <p>Depending on how important it is for you to do the calculations absolutely properly, you may want to consider d...
1
2009-05-09T16:58:09Z
[ "python", "datetime", "time", "timezone" ]
call function between time intervals
843,614
<p>In app engine I would like to call a function if the current time is between a particular interval. This is what I am doing now. </p> <pre><code>ist_time = datetime.utcnow() + timedelta(hours=5, minutes = 30) ist_midnight = ist_time.replace(hour=0, minute=0, second=0, microsecond=0) market_open = ist_midnight + tim...
0
2009-05-09T16:42:36Z
843,984
<p>It seems like you might want datetime's "time" type, which doesn't care about date.</p> <pre><code>import datetime ist_time = datetime.utcnow() + datetime.timedelta(hours=5, minutes = 30) # Turn this into a time object (no day information). ist_time = ist_time.time() if datetime.time(9, 55) &lt;= ist_time &lt;= dat...
0
2009-05-09T20:23:33Z
[ "python", "datetime", "time", "timezone" ]
Profiling in Python: Who called the function?
843,671
<p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p> <p><strong>EDIT:</strong></p> <p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the...
40
2009-05-09T17:10:52Z
843,690
<p>That may not answer your question directly, but will definitely help. If use the profiler with option --sort cumulative it will sort the functions by cumulative time. Which is helpful to detect not only heavy functions but the functions that call them.</p> <pre><code>python -m cProfile --sort cumulative myScript.py...
32
2009-05-09T17:18:58Z
[ "python", "profiling" ]
Profiling in Python: Who called the function?
843,671
<p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p> <p><strong>EDIT:</strong></p> <p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the...
40
2009-05-09T17:10:52Z
843,692
<p>I have not used cProfile myself, but most profilers give you a call hierarchy.<br /> Googling I found this <a href="http://us.pycon.org/media/2009/talkdata/PyCon2009/015/fletcher-profiling-2009.pdf" rel="nofollow">slides</a> about cProfile. Maybe that helps. Page 6 looks like cProfile does provide a hierarchy.</p>
1
2009-05-09T17:20:00Z
[ "python", "profiling" ]
Profiling in Python: Who called the function?
843,671
<p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p> <p><strong>EDIT:</strong></p> <p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the...
40
2009-05-09T17:10:52Z
843,703
<p><a href="http://docs.python.org/library/inspect.html#inspect.stack">inspect.stack()</a> will give you the current caller stack.</p>
10
2009-05-09T17:25:37Z
[ "python", "profiling" ]
Profiling in Python: Who called the function?
843,671
<p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p> <p><strong>EDIT:</strong></p> <p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the...
40
2009-05-09T17:10:52Z
843,725
<p>I almost always view the output of the cProfile module using <a href="http://code.google.com/p/jrfonseca/wiki/Gprof2Dot">Gprof2dot</a>, basically it converts the output into a graphvis graph (a <code>.dot</code> file), for example:</p> <p><a href="http://jrfonseca.googlecode.com/svn/wiki/gprof2dot.png"><img src="ht...
92
2009-05-09T17:41:25Z
[ "python", "profiling" ]
Profiling in Python: Who called the function?
843,671
<p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p> <p><strong>EDIT:</strong></p> <p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the...
40
2009-05-09T17:10:52Z
845,850
<p>Sorry I'm not familiar with Python, but there's a <a href="http://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux/378024#378024">general method</a> that works, assuming you can manually interrupt execution at a random time.</p> <p>Just do so, and display the call stack. It will tell you...
0
2009-05-10T18:45:34Z
[ "python", "profiling" ]
Profiling in Python: Who called the function?
843,671
<p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p> <p><strong>EDIT:</strong></p> <p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the...
40
2009-05-09T17:10:52Z
845,905
<p>You might want to take a look at <a href="http://pycallgraph.slowchop.com/" rel="nofollow">pycallgraph</a>.</p>
3
2009-05-10T19:16:22Z
[ "python", "profiling" ]
Profiling in Python: Who called the function?
843,671
<p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p> <p><strong>EDIT:</strong></p> <p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the...
40
2009-05-09T17:10:52Z
18,358,552
<p>Pycscope does this. I just found it today, so I can't speak to how good it is, but the few examples I've tried have been pretty good (though not perfect).</p> <p><a href="https://pypi.python.org/pypi/pycscope/" rel="nofollow">https://pypi.python.org/pypi/pycscope/</a></p> <p>You would use this to generate a cscope...
0
2013-08-21T13:18:29Z
[ "python", "profiling" ]
Profiling in Python: Who called the function?
843,671
<p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p> <p><strong>EDIT:</strong></p> <p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the...
40
2009-05-09T17:10:52Z
33,163,091
<p>It is possible to do it using profiler <code>cProfile</code> in standard library. <br/> In <code>pstats.Stats</code> (the profiler result) there is method <code>print_callees</code> (or alternatively <code>print_callers</code>).</p> <p><br/>Example code:</p> <pre><code>import cProfile, pstats pr = cProfile.Profile...
0
2015-10-16T05:22:07Z
[ "python", "profiling" ]
How do I choose which Python installation to run in a PyObjC program?
843,698
<p>I use Python 2.6 more than I use Leopard's default python installation, so I have it set as my main Python installation. But I'd rather use the default Python for a PyObjC program I'm working on. Is there any way to specify to only use it instead of Python 2.6?</p>
1
2009-05-09T17:22:14Z
843,701
<p>Try specifying the full path to the Python interpreter in the command line, something like:</p> <pre><code>/foo/bar/python2.6 script.py /baz/python objcscript.py </code></pre> <p>You can also add a shebang to the beginning of your script (first line):</p> <pre><code>#! /foo/bar/python2.6 script.py </code></pre> ...
2
2009-05-09T17:25:05Z
[ "python", "objective-c", "osx", "pyobjc" ]
How do I choose which Python installation to run in a PyObjC program?
843,698
<p>I use Python 2.6 more than I use Leopard's default python installation, so I have it set as my main Python installation. But I'd rather use the default Python for a PyObjC program I'm working on. Is there any way to specify to only use it instead of Python 2.6?</p>
1
2009-05-09T17:22:14Z
845,044
<p>AFAIR this helped me (in main.m):</p> <pre><code> NSArray *pythonPathArray = [NSArray arrayWithObjects: resourcePath, [resourcePath stringByAppendingPathComponent:@"PyObjC"], @"/System/Library/Frameworks/Python.framework/Versions/Current/Extras/lib/python/", @"/Library/Python/2.5/site-packages", nil]; </code></p...
2
2009-05-10T10:07:34Z
[ "python", "objective-c", "osx", "pyobjc" ]
How do I choose which Python installation to run in a PyObjC program?
843,698
<p>I use Python 2.6 more than I use Leopard's default python installation, so I have it set as my main Python installation. But I'd rather use the default Python for a PyObjC program I'm working on. Is there any way to specify to only use it instead of Python 2.6?</p>
1
2009-05-09T17:22:14Z
845,560
<p>Finally figured this one out myself. The key to this is to make the final executable link with /System/Library/Frameworks/Python.framework instead of /Library/Frameworks/Python.framework.</p>
3
2009-05-10T15:57:20Z
[ "python", "objective-c", "osx", "pyobjc" ]
list.append or list +=?
843,751
<p>Which is more pythonic?</p> <pre><code>list.append(1) </code></pre> <p>or</p> <pre><code>list += [1] </code></pre>
25
2009-05-09T17:59:10Z
843,761
<p>From the <a href="http://www.python.org/dev/peps/pep-0020/">Zen of Python</a>:</p> <blockquote> <p>Explicit is better than implicit.</p> </blockquote> <p>So: <code>list.append(1)</code></p>
54
2009-05-09T18:05:09Z
[ "python" ]
list.append or list +=?
843,751
<p>Which is more pythonic?</p> <pre><code>list.append(1) </code></pre> <p>or</p> <pre><code>list += [1] </code></pre>
25
2009-05-09T17:59:10Z
843,762
<p><code>list.append(1)</code> is faster, because it doesn't create a temporary list object.</p>
57
2009-05-09T18:05:12Z
[ "python" ]
list.append or list +=?
843,751
<p>Which is more pythonic?</p> <pre><code>list.append(1) </code></pre> <p>or</p> <pre><code>list += [1] </code></pre>
25
2009-05-09T17:59:10Z
843,781
<p>list.append(1) more readable and to consistent with the context</p>
3
2009-05-09T18:13:40Z
[ "python" ]
list.append or list +=?
843,751
<p>Which is more pythonic?</p> <pre><code>list.append(1) </code></pre> <p>or</p> <pre><code>list += [1] </code></pre>
25
2009-05-09T17:59:10Z
843,908
<p>Since there's also</p> <pre><code>list.extend(l) </code></pre> <p>which appends all elements of the given list, I would use</p> <pre><code>list.append(1) </code></pre> <p>for symmetry and readability's sake.</p>
6
2009-05-09T19:50:50Z
[ "python" ]
list.append or list +=?
843,751
<p>Which is more pythonic?</p> <pre><code>list.append(1) </code></pre> <p>or</p> <pre><code>list += [1] </code></pre>
25
2009-05-09T17:59:10Z
843,936
<p>These are two different operations, what you are doing with += is the extend operation. Here is what Python documents have to say about this:</p> <blockquote> <p>list.append(x): Add an item to the end of the list; equivalent to a[len(a):] = [x].</p> <p>list.extend(L): Extend the list by appending all the ite...
16
2009-05-09T20:02:44Z
[ "python" ]
list.append or list +=?
843,751
<p>Which is more pythonic?</p> <pre><code>list.append(1) </code></pre> <p>or</p> <pre><code>list += [1] </code></pre>
25
2009-05-09T17:59:10Z
844,287
<p>While most people here are preferring the append option, I personally prefer the other one because it looks nicer even though it may be slower (or maybe its optimized).</p> <blockquote> <p>Beautiful is better than ugly.</p> </blockquote> <p>When you write lots of Python code, I don't usually see something like t...
5
2009-05-09T23:12:50Z
[ "python" ]
list.append or list +=?
843,751
<p>Which is more pythonic?</p> <pre><code>list.append(1) </code></pre> <p>or</p> <pre><code>list += [1] </code></pre>
25
2009-05-09T17:59:10Z
844,354
<p>If you've got a single element, <code>a</code>, that you want to add to your list <code>l</code>, then putting <code>a</code> into its own list and extending <code>l</code> with it seems like adding unnecessary complexity. I would thus prefer </p> <pre><code>l.append(a) </code></pre> <p>over</p> <pre><code>l += [...
3
2009-05-09T23:47:43Z
[ "python" ]
list.append or list +=?
843,751
<p>Which is more pythonic?</p> <pre><code>list.append(1) </code></pre> <p>or</p> <pre><code>list += [1] </code></pre>
25
2009-05-09T17:59:10Z
28,676,064
<h2>Beware of fundamentalism</h2> <p>Have you noticed the term "more pythonic" in your question? I think it implies that you are asking a not-so-helpful question.</p> <p>If one is merely <em>more</em> pythonic than the other (rather than being pythonic while the other is not) it could be said that you have violated ...
0
2015-02-23T14:29:53Z
[ "python" ]
FastCgi crashes -- Want to catch all exceptions but how?
843,753
<p>I have a django app running on apache with fastcgi (uses Flup's WSGIServer).</p> <p>This gets setup via dispatch.fcgi, concatenated below:</p> <pre><code>#!/usr/bin/python import sys, os sys.path.insert(0, os.path.realpath('/usr/local/django_src/django')) PROJECT_PATH=os.environ['PROJECT_PATH'] sys.path.insert...
0
2009-05-09T18:00:25Z
843,811
<p>This is probably a Flup <a href="http://trac.saddi.com/flup/ticket/18" rel="nofollow">bug</a>. When a flup-based server's client connection is closed before flup is done sending data, it raises a socket.error: (32, 'Broken pipe') exception.</p> <p>Trying to catch the exception by a try catch around runfastcgi will ...
2
2009-05-09T18:37:04Z
[ "python", "django", "fastcgi", "wsgi", "flup" ]
FastCgi crashes -- Want to catch all exceptions but how?
843,753
<p>I have a django app running on apache with fastcgi (uses Flup's WSGIServer).</p> <p>This gets setup via dispatch.fcgi, concatenated below:</p> <pre><code>#!/usr/bin/python import sys, os sys.path.insert(0, os.path.realpath('/usr/local/django_src/django')) PROJECT_PATH=os.environ['PROJECT_PATH'] sys.path.insert...
0
2009-05-09T18:00:25Z
844,131
<p><em>Broken pipe</em> usually doesn't come deterministically. You get a <em>Broken pipe</em> if a write operation on a pipe or socket fails because the other end has closed the connection. So if your FastCGI gets a <em>Broken pipe</em>, it means that the webserver has closed to connection too early. In some cases thi...
0
2009-05-09T21:36:13Z
[ "python", "django", "fastcgi", "wsgi", "flup" ]
How can I check Hamming Weight without converting to binary?
843,828
<p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p> <p>e.g.</p> <pre><code> def number_of_ones(n): # do something # I want to MAKE this FASTER (computationally less complex). c = 0 while n: c += n%2 ...
8
2009-05-09T18:54:53Z
843,846
<p>I'm not a python programmer, but hopefully it will be enough for you to follow.</p> <pre><code>c = 0 while n: c += 1 n &amp;= n - 1 return c </code></pre> <p>While a little obscure, it's primary advantage is speed and simplicity. The while loop is only iterated once for every bit set to 1 in n.</p>
7
2009-05-09T19:05:58Z
[ "python", "algorithm", "discrete-mathematics" ]
How can I check Hamming Weight without converting to binary?
843,828
<p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p> <p>e.g.</p> <pre><code> def number_of_ones(n): # do something # I want to MAKE this FASTER (computationally less complex). c = 0 while n: c += n%2 ...
8
2009-05-09T18:54:53Z
843,854
<p>If you're actually concerned about speed, code it up in C (see <a href="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer">this question</a> for how), and interface with the C implementation using something like <a href="http://docs.python.org/library/ctypes...
1
2009-05-09T19:12:23Z
[ "python", "algorithm", "discrete-mathematics" ]
How can I check Hamming Weight without converting to binary?
843,828
<p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p> <p>e.g.</p> <pre><code> def number_of_ones(n): # do something # I want to MAKE this FASTER (computationally less complex). c = 0 while n: c += n%2 ...
8
2009-05-09T18:54:53Z
843,899
<p>IMO, a good approach would be to use a look-up table - create a dictionary which converts bytes to number of 1's (you can use the code you posted to generate it, it would only need to run once), and then use something like this:</p> <pre><code>def number_of_ones(n): sum = 0 while n != 0: sum += look...
5
2009-05-09T19:46:52Z
[ "python", "algorithm", "discrete-mathematics" ]
How can I check Hamming Weight without converting to binary?
843,828
<p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p> <p>e.g.</p> <pre><code> def number_of_ones(n): # do something # I want to MAKE this FASTER (computationally less complex). c = 0 while n: c += n%2 ...
8
2009-05-09T18:54:53Z
843,940
<p>If you want to do it in a single line, you could use:</p> <pre><code>sum( [x&amp;(1&lt;&lt;i)&gt;0 for i in range(32)] ) </code></pre>
4
2009-05-09T20:03:13Z
[ "python", "algorithm", "discrete-mathematics" ]
How can I check Hamming Weight without converting to binary?
843,828
<p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p> <p>e.g.</p> <pre><code> def number_of_ones(n): # do something # I want to MAKE this FASTER (computationally less complex). c = 0 while n: c += n%2 ...
8
2009-05-09T18:54:53Z
843,957
<p>You cannot make this computationally less complex. It will be O(n) the number of bits, or, as the answer with the &amp; trick showed, O(n) the number of bits set to 1; but unless all of the numbers you are using are a special case, the latter should on average be n/2, so both of those O(n) numbers are the same.</p>...
6
2009-05-09T20:12:20Z
[ "python", "algorithm", "discrete-mathematics" ]
How can I check Hamming Weight without converting to binary?
843,828
<p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p> <p>e.g.</p> <pre><code> def number_of_ones(n): # do something # I want to MAKE this FASTER (computationally less complex). c = 0 while n: c += n%2 ...
8
2009-05-09T18:54:53Z
36,503,001
<p>p= lambda n:n and 1+p(n&amp;(n-1))</p> <p>This uses short-circuiting and recursion, when n is greater than 0, it switches to calculate 1+p(n&amp;(n-1)) where p(n&amp;(n-1)) is called and so on, when n is 0 it returns 0. Complexity being O(n) since it runs the number of times the number of ones exist in the binary.<...
0
2016-04-08T15:03:25Z
[ "python", "algorithm", "discrete-mathematics" ]
How can I check Hamming Weight without converting to binary?
843,828
<p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p> <p>e.g.</p> <pre><code> def number_of_ones(n): # do something # I want to MAKE this FASTER (computationally less complex). c = 0 while n: c += n%2 ...
8
2009-05-09T18:54:53Z
36,555,670
<p>Here:</p> <p>def bitCount(int_no):</p> <pre><code>c = 0 while(int_no): int_no &amp;= (int_no - 1) c += 1 return c </code></pre> <p>This might be an old and efficient way to do this... originally implementated in C (Algo has a name I can't remember). It works fine for me hope it does for any other person</...
0
2016-04-11T17:47:35Z
[ "python", "algorithm", "discrete-mathematics" ]
wxPython: Drawing a vector-based image from file
844,110
<p>How can I draw a vector-based image from a file in wxPython? I know nothing of image formats for such a thing, so please recommend.</p>
3
2009-05-09T21:26:37Z
844,139
<p>You can do this with using cairo &amp; librsvg python bindings. There is a small example <a href="http://www.daa.com.au/pipermail/pygtk/2007-April/013778.html" rel="nofollow">here</a>.</p>
3
2009-05-09T21:43:13Z
[ "python", "wxpython", "vector-graphics" ]
wxPython: Drawing a vector-based image from file
844,110
<p>How can I draw a vector-based image from a file in wxPython? I know nothing of image formats for such a thing, so please recommend.</p>
3
2009-05-09T21:26:37Z
884,997
<p>I have done something similar, I had a custom vector image format that I needed to render in a wxPython window. In order to accomplish this I used the GDI interface for drawing commands and I wrote my own parser module. There is a great GDI tutorial at this site that should help you out: <a href="http://www.zetcode...
1
2009-05-19T20:59:49Z
[ "python", "wxpython", "vector-graphics" ]
Downloading a web page and all of its resource files in Python
844,115
<p>I want to be able to download a page and all of its associated resources (images, style sheets, script files, etc) using Python. I am (somewhat) familiar with urllib2 and know how to download individual urls, but before I go and start hacking at BeautifulSoup + urllib2 I wanted to be sure that there wasn't already ...
8
2009-05-09T21:28:26Z
844,121
<p>Websucker? See <a href="http://effbot.org/zone/websucker.htm" rel="nofollow">http://effbot.org/zone/websucker.htm</a></p>
2
2009-05-09T21:31:08Z
[ "python", "urllib2", "wget" ]
Downloading a web page and all of its resource files in Python
844,115
<p>I want to be able to download a page and all of its associated resources (images, style sheets, script files, etc) using Python. I am (somewhat) familiar with urllib2 and know how to download individual urls, but before I go and start hacking at BeautifulSoup + urllib2 I wanted to be sure that there wasn't already ...
8
2009-05-09T21:28:26Z
2,837,722
<p>websucker.py doesn't import css links. HTTrack.com is not python, it's C/C++, but it's a good, maintained, utility for downloading a website for offline browsing.</p> <p><a href="http://www.mail-archive.com/python-bugs-list@python.org/msg13523.html" rel="nofollow">http://www.mail-archive.com/python-bugs-list@python...
2
2010-05-14T21:22:34Z
[ "python", "urllib2", "wget" ]
where to put method that works on a model
844,142
<p>I'm working with Django.</p> <p>I have a model called Agrument. Arguments have sides and owners. I have a function that returns back the side of the most recent argument of a certain user.</p> <p>like obj.get_current_side(username)</p> <p>I've added this to the actual Argument model like this</p> <pre><code> ...
1
2009-05-09T21:47:00Z
844,168
<p>I think what you are looking for are model managers. </p> <p><a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#topics-db-managers" rel="nofollow">Django docs on managers</a> with managers you can add a function to the model class instead of a model instance. </p>
0
2009-05-09T22:03:16Z
[ "python", "django" ]
where to put method that works on a model
844,142
<p>I'm working with Django.</p> <p>I have a model called Agrument. Arguments have sides and owners. I have a function that returns back the side of the most recent argument of a certain user.</p> <p>like obj.get_current_side(username)</p> <p>I've added this to the actual Argument model like this</p> <pre><code> ...
1
2009-05-09T21:47:00Z
844,176
<p>It would make more sense to have instance methods on the <code>User</code> model:</p> <pre><code>def get_current_side(self): try: return self.arguments.latest('pub_date').side except User.DoesNotExist, e: return None </code></pre> <p>You can do this by extending the <code>User</code> model ...
2
2009-05-09T22:08:19Z
[ "python", "django" ]
where to put method that works on a model
844,142
<p>I'm working with Django.</p> <p>I have a model called Agrument. Arguments have sides and owners. I have a function that returns back the side of the most recent argument of a certain user.</p> <p>like obj.get_current_side(username)</p> <p>I've added this to the actual Argument model like this</p> <pre><code> ...
1
2009-05-09T21:47:00Z
844,998
<p>This should be a method on a custom model manager:</p> <pre><code># in models.py class ArgumentManager(models.manager.Manager): def get_current_side(self, user): try: return self.filter(user=user).latest('pub_date').side except Argument.DoesNotExist: return None class Ar...
1
2009-05-10T09:22:00Z
[ "python", "django" ]
Regular expression implementation details
844,183
<p>A <a href="http://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python">question that I answered</a> got me wondering:</p> <p>How are regular expressions implemented in Python? What sort of efficiency guarantees are there? Is the implementation "standard", or i...
11
2009-05-09T22:12:50Z
844,267
<p>Python's re module was based on <a href="http://en.wikipedia.org/wiki/PCRE" rel="nofollow">PCRE</a>, but has moved on to their own implementation.</p> <p>Here is the link to the <a href="http://hg.python.org/cpython/file/a82fc1f366b4/Modules/_sre.c" rel="nofollow">C code</a>.</p> <p>It appears as though the librar...
16
2009-05-09T23:03:17Z
[ "python", "regex" ]
Regular expression implementation details
844,183
<p>A <a href="http://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python">question that I answered</a> got me wondering:</p> <p>How are regular expressions implemented in Python? What sort of efficiency guarantees are there? Is the implementation "standard", or i...
11
2009-05-09T22:12:50Z
846,095
<p>There are no "efficiency guarantees" on Python REs any more than on any other part of the language (C++'s standard library is the only widespread language standard I know that tries to establish such standards -- but there are no standards, even in C++, specifying that, say, multiplying two ints must take constant t...
5
2009-05-10T21:01:56Z
[ "python", "regex" ]
Regular expression implementation details
844,183
<p>A <a href="http://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python">question that I answered</a> got me wondering:</p> <p>How are regular expressions implemented in Python? What sort of efficiency guarantees are there? Is the implementation "standard", or i...
11
2009-05-09T22:12:50Z
1,635,192
<p><a href="http://perl.plover.com/NPC/" rel="nofollow">Matching regular expressions with backreferences is NP-hard</a>, which is at least as hard as <a href="http://en.wikipedia.org/wiki/NP-complete" rel="nofollow">NP-Complete</a>. That basically means that it's as hard as any problem you're likely to encounter, and ...
1
2009-10-28T04:24:21Z
[ "python", "regex" ]
Is a graph library (eg NetworkX) the right solution for my Python problem?
844,505
<p>I'm rewriting a data-driven legacy application in Python. One of the primary tables is referred to as a "graph table", and does appear to be a directed graph, so I was exploring the NetworkX package to see whether it would make sense to use it for the graph table manipulations, and really implement it as a graph rat...
2
2009-05-10T01:34:33Z
845,659
<p>Definitely not suitable for general purpose graph libraries (whatever you're supposed to do if more than one of the words meaningful in a node is in the input string -- is that an error? -- or if none does and there is no default for the node, as for node 30 in the example you supply). Just write the table as a dic...
2
2009-05-10T16:57:30Z
[ "python", "graph" ]
Is a graph library (eg NetworkX) the right solution for my Python problem?
844,505
<p>I'm rewriting a data-driven legacy application in Python. One of the primary tables is referred to as a "graph table", and does appear to be a directed graph, so I was exploring the NetworkX package to see whether it would make sense to use it for the graph table manipulations, and really implement it as a graph rat...
2
2009-05-10T01:34:33Z
851,532
<p>Adding an answer to respond to the further requirements newly edited in...: I still wouldn't go for a general-purpose library. For "all nodes can be reached and there are no loops", simply reasoning in terms of sets (ignoring the triggering keywords) should do: (again untested code, but the general outline should he...
0
2009-05-12T07:13:35Z
[ "python", "graph" ]
Python regex question: stripping multi-line comments but maintaining a line break
844,681
<p>I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /<em>....</em>/). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.</p> <p>For example, the code:</p> <pr...
3
2009-05-10T04:20:41Z
844,688
<p>Is this what you're looking for?</p> <pre><code>&gt;&gt;&gt; print(s) qwe /* 123 456 789 */ asd &gt;&gt;&gt; print(re.sub(r'\s*/\*.*\n.*\*/\s*', '\n', s, flags=re.S)) qwe asd </code></pre> <p>This will work only for those comments that are more than one line, but will leave others alone. </p>
1
2009-05-10T04:30:47Z
[ "python", "regex", "parsing", "comments" ]
Python regex question: stripping multi-line comments but maintaining a line break
844,681
<p>I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /<em>....</em>/). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.</p> <p>For example, the code:</p> <pr...
3
2009-05-10T04:20:41Z
844,716
<p>How about this:</p> <pre><code>re.sub(r'\s*/\*(.|\n)*?\*/\s*', '\n', s, re.DOTALL).strip() </code></pre> <p>It attacks leading whitespace, <code>/*</code>, any text and newline up until the first <code>*\</code>, then any whitespace after that.</p> <p>Its a little twist on sykora's example but it is also non-gree...
1
2009-05-10T04:56:47Z
[ "python", "regex", "parsing", "comments" ]
Python regex question: stripping multi-line comments but maintaining a line break
844,681
<p>I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /<em>....</em>/). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.</p> <p>For example, the code:</p> <pr...
3
2009-05-10T04:20:41Z
844,717
<p>See <a href="http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns">can-regular-expressions-be-used-to-match-nested-patterns</a> - if you consider nested comments, regular expressions are not the solution.</p>
0
2009-05-10T04:57:04Z
[ "python", "regex", "parsing", "comments" ]
Python regex question: stripping multi-line comments but maintaining a line break
844,681
<p>I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /<em>....</em>/). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.</p> <p>For example, the code:</p> <pr...
3
2009-05-10T04:20:41Z
844,721
<pre><code>comment_re = re.compile( r'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?', re.DOTALL | re.MULTILINE ) def comment_replacer(match): start,mid,end = match.group(1,2,3) if mid is None: # single line comment return '' elif start is not None or end is not None: # mul...
9
2009-05-10T05:01:02Z
[ "python", "regex", "parsing", "comments" ]
Python regex question: stripping multi-line comments but maintaining a line break
844,681
<p>I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /<em>....</em>/). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.</p> <p>For example, the code:</p> <pr...
3
2009-05-10T04:20:41Z
844,731
<p>The fact that you have to even ask this question, and that the solutions given are, shall we say, less than perfectly readable :-) should be a good indication that REs are not the real answer to this question.</p> <p>You would be far better, from a readability viewpoint, to actually code this up as a relatively sim...
5
2009-05-10T05:07:18Z
[ "python", "regex", "parsing", "comments" ]
Performing a getattr() style lookup in a django template
844,746
<p>Python's getattr() method is useful when you don't know the name of a certain attribute in advance.</p> <p>This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? </p>
31
2009-05-10T05:15:16Z
844,764
<p>There isn't a built-in tag, but it shouldn't be too difficult to <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags" rel="nofollow">write your own</a>.</p>
0
2009-05-10T05:29:51Z
[ "python", "django", "django-templates" ]
Performing a getattr() style lookup in a django template
844,746
<p>Python's getattr() method is useful when you don't know the name of a certain attribute in advance.</p> <p>This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? </p>
31
2009-05-10T05:15:16Z
844,774
<p>I don't think so. But it wouldn't be too hard to write a <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/" rel="nofollow">custom template tag</a> to return an attribute in the context dict. If you're simply trying to return a string, try something like this:</p> <pre><code>class GetAttrNo...
2
2009-05-10T05:35:31Z
[ "python", "django", "django-templates" ]