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
How to match search strings to content in python
1,103,685
<p>Usually when we search, we have a list of stories, we provide a search string, and expect back a list of results where the given search strings matches the story.</p> <p>What I am looking to do, is the opposite. Give a list of search strings, and one story and find out which search strings match to that story.</p> ...
0
2009-07-09T12:54:23Z
1,104,172
<p>Here's a suggestion in pseudocode. I'm assuming you store a story identifier with the search terms in the index, so that you can retrieve it with the search results.</p> <pre><code>def search_strings_matching(story_id_to_match, search_strings): result = set() for s in search_strings: result_story_id...
0
2009-07-09T14:15:58Z
[ "python", "search", "lucene", "solr" ]
How to match search strings to content in python
1,103,685
<p>Usually when we search, we have a list of stories, we provide a search string, and expect back a list of results where the given search strings matches the story.</p> <p>What I am looking to do, is the opposite. Give a list of search strings, and one story and find out which search strings match to that story.</p> ...
0
2009-07-09T12:54:23Z
1,105,551
<p>After extensive googling, i realized what i am looking to do is a Boolean search.</p> <p>Found the code that makes regex boolean aware : <a href="http://code.activestate.com/recipes/252526/" rel="nofollow">http://code.activestate.com/recipes/252526/</a></p> <p>Issue looks solved for now.</p>
1
2009-07-09T18:01:33Z
[ "python", "search", "lucene", "solr" ]
How to match search strings to content in python
1,103,685
<p>Usually when we search, we have a list of stories, we provide a search string, and expect back a list of results where the given search strings matches the story.</p> <p>What I am looking to do, is the opposite. Give a list of search strings, and one story and find out which search strings match to that story.</p> ...
0
2009-07-09T12:54:23Z
1,109,852
<p>This is probably less interesting to you now, since you've already solved your problem, but what you're describing sounds like <a href="http://en.wikipedia.org/wiki/Prospective%5Fsearch" rel="nofollow">Prospective Search</a>, which is what you call it when you have the query first and you want to match it against do...
0
2009-07-10T14:25:31Z
[ "python", "search", "lucene", "solr" ]
How to match search strings to content in python
1,103,685
<p>Usually when we search, we have a list of stories, we provide a search string, and expect back a list of results where the given search strings matches the story.</p> <p>What I am looking to do, is the opposite. Give a list of search strings, and one story and find out which search strings match to that story.</p> ...
0
2009-07-09T12:54:23Z
7,152,733
<p>If you are writing Python on AppEngine, you can use the AppEngine Prospective Search Service to achieve exactly what you are trying to do here. See: <a href="http://code.google.com/appengine/docs/python/prospectivesearch/overview.html" rel="nofollow">http://code.google.com/appengine/docs/python/prospectivesearch/ove...
0
2011-08-22T19:44:27Z
[ "python", "search", "lucene", "solr" ]
Upload a potentially huge textfile to a plain WSGI-server in Python
1,103,940
<p>I need to upload a potentially huge plain-text file to a very simple wsgi-app without eating up all available memory on the server. How do I accomplish that? I want to use standard python modules and avoid third-party modules if possible.</p>
1
2009-07-09T13:36:57Z
1,104,001
<p>Has python know how to <a href="http://docs.python.org/library/archiving.html" rel="nofollow">deal with gzip annd zip file</a> I would suggest you to compress your file (using a zip or gzip compliant application like 7-zip) on your client and then upload it to your server.</p> <p>Even better : write a script that a...
0
2009-07-09T13:47:35Z
[ "python", "file", "upload", "wsgi" ]
Upload a potentially huge textfile to a plain WSGI-server in Python
1,103,940
<p>I need to upload a potentially huge plain-text file to a very simple wsgi-app without eating up all available memory on the server. How do I accomplish that? I want to use standard python modules and avoid third-party modules if possible.</p>
1
2009-07-09T13:36:57Z
1,104,012
<p>wsgi.input should be a file like stream object. You can read from that in blocks, and write those blocks directly to disk. That shouldn't use up any significant memory.</p> <p>Or maybe I misunderstood the question?</p>
3
2009-07-09T13:49:23Z
[ "python", "file", "upload", "wsgi" ]
Upload a potentially huge textfile to a plain WSGI-server in Python
1,103,940
<p>I need to upload a potentially huge plain-text file to a very simple wsgi-app without eating up all available memory on the server. How do I accomplish that? I want to use standard python modules and avoid third-party modules if possible.</p>
1
2009-07-09T13:36:57Z
1,209,507
<p>If you use the cgi module to parse the input (which most frameworks use, e.g., Pylons, WebOb, CherryPy) then it will automatically save the uploaded file to a temporary file, and not load it into memory.</p>
2
2009-07-30T21:32:04Z
[ "python", "file", "upload", "wsgi" ]
Run (remote) php script from (local) python script
1,104,064
<p>How do I make python (local) run php script <strong>on a remote server</strong>? </p> <p>I don't want to process its output with python script or anything, just execute it and meanwhile quit python (while php script will be already working and doing its job).</p> <p>edit: What I'm trying to achieve:</p> <ul> <li>...
5
2009-07-09T13:58:59Z
1,104,084
<pre><code>os.system("php yourscript.php") </code></pre> <p>Another alternative would be:</p> <pre><code># will return new process' id os.spawnl(os.P_NOWAIT, "php yourscript.php") </code></pre> <p>You can check all os module documentation <a href="http://docs.python.org/library/os.html" rel="nofollow">here</a>.</p>
5
2009-07-09T14:01:03Z
[ "php", "python" ]
Run (remote) php script from (local) python script
1,104,064
<p>How do I make python (local) run php script <strong>on a remote server</strong>? </p> <p>I don't want to process its output with python script or anything, just execute it and meanwhile quit python (while php script will be already working and doing its job).</p> <p>edit: What I'm trying to achieve:</p> <ul> <li>...
5
2009-07-09T13:58:59Z
1,104,391
<p>I'll paraphrase the answer to <a href="http://stackoverflow.com/questions/1060436/how-do-i-include-a-php-script-in-python">http://stackoverflow.com/questions/1060436/how-do-i-include-a-php-script-in-python</a>.</p> <pre><code>import subprocess def php(script_path): p = subprocess.Popen(['php', script_path] ) <...
0
2009-07-09T14:50:31Z
[ "php", "python" ]
Run (remote) php script from (local) python script
1,104,064
<p>How do I make python (local) run php script <strong>on a remote server</strong>? </p> <p>I don't want to process its output with python script or anything, just execute it and meanwhile quit python (while php script will be already working and doing its job).</p> <p>edit: What I'm trying to achieve:</p> <ul> <li>...
5
2009-07-09T13:58:59Z
1,105,790
<p>If python is on a different physical machine than the PHP script, I'd make sure the PHP script is web-accessible and use <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> to call to that url</p> <pre><code>import urllib2 urllib2.urlopen("http://remotehost.com/myscript.php") </code></...
4
2009-07-09T18:46:36Z
[ "php", "python" ]
Combining module files in Python
1,104,066
<p>Is there a way to put together Python files, akin to JAR in Java? I need a way of packaging set of Python classes and functions, but unlike a standard module, I'd like it to be in one file.</p>
6
2009-07-09T13:59:06Z
1,104,080
<p>Take a look at Python Eggs: <a href="http://peak.telecommunity.com/DevCenter/PythonEggs">http://peak.telecommunity.com/DevCenter/PythonEggs</a></p> <p>Or, you can use regular zips: <a href="http://docs.python.org/library/zipimport.html">http://docs.python.org/library/zipimport.html</a></p>
7
2009-07-09T14:00:31Z
[ "python", "packaging" ]
Combining module files in Python
1,104,066
<p>Is there a way to put together Python files, akin to JAR in Java? I need a way of packaging set of Python classes and functions, but unlike a standard module, I'd like it to be in one file.</p>
6
2009-07-09T13:59:06Z
1,104,081
<p>The simplest approach is to just use <code>zip</code>. A <code>jar</code> file in Java is a zipfile containing some metadata such as a manifest; but you don't necessarily need the metatada -- Python can import from inside a zipfile as long as you place that zipfile on sys.path, just as you would do for any directory...
3
2009-07-09T14:00:55Z
[ "python", "packaging" ]
Combining module files in Python
1,104,066
<p>Is there a way to put together Python files, akin to JAR in Java? I need a way of packaging set of Python classes and functions, but unlike a standard module, I'd like it to be in one file.</p>
6
2009-07-09T13:59:06Z
1,104,089
<p>You can create zip files containing Python code and import from zip files using <a href="http://docs.python.org/library/zipimport.html" rel="nofollow">zipimport</a>. A system such as <a href="http://www.pyinstaller.org/" rel="nofollow">PyInstaller</a> (cross-platform) or <a href="http://www.py2exe.org/" rel="nofollo...
2
2009-07-09T14:01:42Z
[ "python", "packaging" ]
Combining module files in Python
1,104,066
<p>Is there a way to put together Python files, akin to JAR in Java? I need a way of packaging set of Python classes and functions, but unlike a standard module, I'd like it to be in one file.</p>
6
2009-07-09T13:59:06Z
1,104,102
<p>Read this <a href="http://www.python.org/dev/peps/pep-0273/" rel="nofollow">PEP</a> for informations.<br> Also, <a href="http://docs.python.org/library/zipimport.html" rel="nofollow">Import modules from Zip</a>.</p>
0
2009-07-09T14:03:32Z
[ "python", "packaging" ]
Combining module files in Python
1,104,066
<p>Is there a way to put together Python files, akin to JAR in Java? I need a way of packaging set of Python classes and functions, but unlike a standard module, I'd like it to be in one file.</p>
6
2009-07-09T13:59:06Z
6,611,335
<p>After looking for a solution to the same problem, I ended up writing a simple tool which combines multiple .py files into one: <a href="http://pagekite.net/wiki/Floss/PyBreeder/">PyBreeder</a></p> <p>It will only work with pure-Python modules and may require some trial-and-error to get the order of modules right, b...
8
2011-07-07T13:27:07Z
[ "python", "packaging" ]
Scrolling QGraphicsView programmatically
1,104,304
<p>I've want to implement a scroll/pan-feature on a QGraphicsView in my (Py)Qt application. It's supposed to work like this: The user presses the middle mouse button, and the view scrolls as the user moves the mouse (this is quite a common feature).<br /> I tried using the scroll() method inherited from QWidget. Howeve...
1
2009-07-09T14:39:07Z
1,105,111
<p>I haven't done this myself but this is from the <a href="http://doc.trolltech.com/4.5/qgraphicsview.html" rel="nofollow"><code>QGraphicsView</code></a> documentation</p> <blockquote> <p>... When the scene is larger than the scroll bars' values, you can choose to use translate() to navigate the scene instead...
3
2009-07-09T16:45:58Z
[ "python", "qt" ]
Scrolling QGraphicsView programmatically
1,104,304
<p>I've want to implement a scroll/pan-feature on a QGraphicsView in my (Py)Qt application. It's supposed to work like this: The user presses the middle mouse button, and the view scrolls as the user moves the mouse (this is quite a common feature).<br /> I tried using the scroll() method inherited from QWidget. Howeve...
1
2009-07-09T14:39:07Z
1,108,477
<p>You can set the QGraphicsScene's area that will be displayed by the QGraphicsView with the method <a href="http://doc.trolltech.com/4.5/qgraphicsview.html#sceneRect-prop" rel="nofollow">QGraphicsView::setSceneRect()</a>. So when you press the button and move the mouse, you can change the center of the displayed part...
0
2009-07-10T08:54:08Z
[ "python", "qt" ]
Scrolling QGraphicsView programmatically
1,104,304
<p>I've want to implement a scroll/pan-feature on a QGraphicsView in my (Py)Qt application. It's supposed to work like this: The user presses the middle mouse button, and the view scrolls as the user moves the mouse (this is quite a common feature).<br /> I tried using the scroll() method inherited from QWidget. Howeve...
1
2009-07-09T14:39:07Z
3,697,290
<p>My addition to translate() method. It works great unless you scale the scene. If you do this, you'll notice, that the image is not in sync with your mouse movements. That's when mapToScene() comes to help. You should map your points from mouse events to scene coordinates. Then the mapped difference goes to translate...
4
2010-09-13T00:39:29Z
[ "python", "qt" ]
Scrolling QGraphicsView programmatically
1,104,304
<p>I've want to implement a scroll/pan-feature on a QGraphicsView in my (Py)Qt application. It's supposed to work like this: The user presses the middle mouse button, and the view scrolls as the user moves the mouse (this is quite a common feature).<br /> I tried using the scroll() method inherited from QWidget. Howeve...
1
2009-07-09T14:39:07Z
28,180,049
<p>Answer given by denis is correct to get translate to work. The comment by PF4Public is also valid: this can screw up scaling. My workaround is different than P4FPublc's -- instead of mapToScene I preserve the anchor and restore it after a translation:</p> <pre><code>previousAnchor = view.transformationAnchor() #h...
0
2015-01-27T21:09:45Z
[ "python", "qt" ]
Twisted sometimes throws (seemingly incomplete) 'maximum recursion depth exceeded' RuntimeError
1,104,587
<p>Because the Twisted <code>getPage</code> function doesn't give me access to headers, I had to write my own <code>getPageWithHeaders</code> function.</p> <pre><code>def getPageWithHeaders(contextFactory=None, *args, **kwargs): try: return _makeGetterFactory(url, HTTPClientFactory, ...
2
2009-07-09T15:21:58Z
1,104,617
<p>You should look at the traceback you're getting together with the exception -- that will tell you what function(s) is/are recursing too deeply, "below" <code>_makeGetterFactory</code>. Most likely you'll find that your own <code>getPageWithHeaders</code> is involved in the recursion, exactly because instead of prope...
1
2009-07-09T15:25:59Z
[ "python", "twisted" ]
Twisted sometimes throws (seemingly incomplete) 'maximum recursion depth exceeded' RuntimeError
1,104,587
<p>Because the Twisted <code>getPage</code> function doesn't give me access to headers, I had to write my own <code>getPageWithHeaders</code> function.</p> <pre><code>def getPageWithHeaders(contextFactory=None, *args, **kwargs): try: return _makeGetterFactory(url, HTTPClientFactory, ...
2
2009-07-09T15:21:58Z
1,104,648
<p>The URL opener is likely following an un-ending series of 301 or 302 redirects.</p>
-1
2009-07-09T15:29:49Z
[ "python", "twisted" ]
Twisted sometimes throws (seemingly incomplete) 'maximum recursion depth exceeded' RuntimeError
1,104,587
<p>Because the Twisted <code>getPage</code> function doesn't give me access to headers, I had to write my own <code>getPageWithHeaders</code> function.</p> <pre><code>def getPageWithHeaders(contextFactory=None, *args, **kwargs): try: return _makeGetterFactory(url, HTTPClientFactory, ...
2
2009-07-09T15:21:58Z
1,108,849
<p>The specific traceback that you're looking at is a bit mystifying. You could try <code>traceback.print_stack</code> rather than <code>traceback.print_exc</code> to get a look at the <em>entire</em> stack above the problematic code, rather than just the stack going back to where the exception is caught.</p> <p>With...
2
2009-07-10T10:38:43Z
[ "python", "twisted" ]
Lengthy single line strings in Python without going over maximum line length
1,104,762
<p>How can I break a long one liner string in my code and keep the string indented with the rest of the code? <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow" title="PEP-8">PEP 8</a> doesn't have any example for this case.</p> <p>Correct ouptut but strangely indented:</p> <pre><code>if True: prin...
1
2009-07-09T15:46:39Z
1,104,789
<p>Adjacent strings are concatenated at compile time:</p> <pre><code>if True: print ("this is the first line of a very long string" " this is the second line") </code></pre> <p>Output:</p> <pre><code>this is the first line of a very long string this is the second line </code></pre>
27
2009-07-09T15:49:47Z
[ "python", "string" ]
Lengthy single line strings in Python without going over maximum line length
1,104,762
<p>How can I break a long one liner string in my code and keep the string indented with the rest of the code? <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow" title="PEP-8">PEP 8</a> doesn't have any example for this case.</p> <p>Correct ouptut but strangely indented:</p> <pre><code>if True: prin...
1
2009-07-09T15:46:39Z
1,104,790
<p>You can use a trailing backslash to join separate strings like this:</p> <pre><code>if True: print "long test long test long test long test long " \ "test long test long test long test long test long test" </code></pre>
2
2009-07-09T15:49:56Z
[ "python", "string" ]
Lengthy single line strings in Python without going over maximum line length
1,104,762
<p>How can I break a long one liner string in my code and keep the string indented with the rest of the code? <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow" title="PEP-8">PEP 8</a> doesn't have any example for this case.</p> <p>Correct ouptut but strangely indented:</p> <pre><code>if True: prin...
1
2009-07-09T15:46:39Z
1,104,793
<pre><code>if True: print "long test long test long test long test long"\ "test long test long test long test long test long test" </code></pre>
6
2009-07-09T15:50:07Z
[ "python", "string" ]
Lengthy single line strings in Python without going over maximum line length
1,104,762
<p>How can I break a long one liner string in my code and keep the string indented with the rest of the code? <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow" title="PEP-8">PEP 8</a> doesn't have any example for this case.</p> <p>Correct ouptut but strangely indented:</p> <pre><code>if True: prin...
1
2009-07-09T15:46:39Z
1,104,796
<pre><code>if True: print "long test long test long test "+ "long test long test long test "+ "long test long test long test " </code></pre> <p>And so on.</p>
-6
2009-07-09T15:50:54Z
[ "python", "string" ]
Lengthy single line strings in Python without going over maximum line length
1,104,762
<p>How can I break a long one liner string in my code and keep the string indented with the rest of the code? <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow" title="PEP-8">PEP 8</a> doesn't have any example for this case.</p> <p>Correct ouptut but strangely indented:</p> <pre><code>if True: prin...
1
2009-07-09T15:46:39Z
1,107,873
<p>Why isn't anyone recommending triple quotes?</p> <pre><code>print """ blah blah blah ..............""" </code></pre>
0
2009-07-10T05:34:02Z
[ "python", "string" ]
Python tell when an ftp transfer sits on completion
1,105,014
<p>I have to download some files from an FTP server. Seems prosaic enough. However, the way this server behaves is if the file is very large, the connection will just hang when the download ostensibly completes.</p> <p>How can I handle this gracefully using ftplib in python?</p> <p>Sample python code:</p> <pre><code...
2
2009-07-09T16:30:56Z
1,106,842
<p>I've never used ftplib, but perhaps you could do:</p> <ol> <li>Get the name and size of the file you want.</li> <li>Start a new daemonic thread to download the file.</li> <li>In the main thread, check every few seconds whether the file size on disk equals the target size.</li> <li>When it does, wait a few seconds t...
0
2009-07-09T22:49:44Z
[ "python", "ftp", "network-programming" ]
Python tell when an ftp transfer sits on completion
1,105,014
<p>I have to download some files from an FTP server. Seems prosaic enough. However, the way this server behaves is if the file is very large, the connection will just hang when the download ostensibly completes.</p> <p>How can I handle this gracefully using ftplib in python?</p> <p>Sample python code:</p> <pre><code...
2
2009-07-09T16:30:56Z
1,940,568
<p>I think some debugging could be useful. Could you fold the class below into your code? (I didn't do it myself because I know this version works, and didn't want to risk making an error. You should be able to just put the class at the top of your file and replace the body of the loop with what I've written after #...
0
2009-12-21T14:58:02Z
[ "python", "ftp", "network-programming" ]
Pythonic way to get some rows of a matrix
1,105,101
<p>I was thinking about a code that I wrote a few years ago in Python, at some point it had to get just some elements, by index, of a list of lists.</p> <p>I remember I did something like this:</p> <pre><code>def getRows(m, row_indices): tmp = [] for i in row_indices: tmp.append(m[i]) return tmp <...
1
2009-07-09T16:44:37Z
1,105,120
<p>It's the clean an obvious way. So, I'd say it doesn't get more Pythonic than that.</p>
4
2009-07-09T16:47:34Z
[ "list", "coding-style", "filtering", "python" ]
Pythonic way to get some rows of a matrix
1,105,101
<p>I was thinking about a code that I wrote a few years ago in Python, at some point it had to get just some elements, by index, of a list of lists.</p> <p>I remember I did something like this:</p> <pre><code>def getRows(m, row_indices): tmp = [] for i in row_indices: tmp.append(m[i]) return tmp <...
1
2009-07-09T16:44:37Z
1,105,177
<p>It's worth looking at <a href="http://www.scipy.org/Tentative%5FNumPy%5FTutorial" rel="nofollow">NumPy</a> for its slicing syntax. Scroll down in the linked page until you get to "Indexing, Slicing and Iterating".</p>
4
2009-07-09T16:58:03Z
[ "list", "coding-style", "filtering", "python" ]
Pythonic way to get some rows of a matrix
1,105,101
<p>I was thinking about a code that I wrote a few years ago in Python, at some point it had to get just some elements, by index, of a list of lists.</p> <p>I remember I did something like this:</p> <pre><code>def getRows(m, row_indices): tmp = [] for i in row_indices: tmp.append(m[i]) return tmp <...
1
2009-07-09T16:44:37Z
1,106,175
<p>As Curt said, it seems that Numpy is a good tool for this. Here's an example,</p> <pre><code>from numpy import * a = arange(16).reshape((4,4)) b = a[:, [1,2]] c = a[[1,2], :] print a print b print c </code></pre> <p>gives</p> <pre><code>[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] [[ 1 2] [ ...
2
2009-07-09T20:06:33Z
[ "list", "coding-style", "filtering", "python" ]
How to exclude U+2028 from line separators in Python when reading file?
1,105,106
<p>I have a file in UTF-8, where some lines contain the U+2028 Line Separator character (<a href="http://www.fileformat.info/info/unicode/char/2028/index.htm" rel="nofollow">http://www.fileformat.info/info/unicode/char/2028/index.htm</a>). I don't want it to be treated as a line break when I read lines from the file. I...
3
2009-07-09T16:44:49Z
1,105,207
<p>If you use Python 3.0 (note that I don't, so I can't test), according to the <a href="http://docs.python.org/3.0/library/functions.html#open" rel="nofollow">documentation</a> you can pass an optional <code>newline</code> parameter to <code>open</code> to specifify which line seperator to use. However, the documentat...
0
2009-07-09T17:03:54Z
[ "python", "utf-8", "readline", "separator" ]
How to exclude U+2028 from line separators in Python when reading file?
1,105,106
<p>I have a file in UTF-8, where some lines contain the U+2028 Line Separator character (<a href="http://www.fileformat.info/info/unicode/char/2028/index.htm" rel="nofollow">http://www.fileformat.info/info/unicode/char/2028/index.htm</a>). I don't want it to be treated as a line break when I read lines from the file. I...
3
2009-07-09T16:44:49Z
1,105,563
<p>I couldn't reproduce that behavior but here's a naive solution that just merges readline results until they don't end with U+2028.</p> <pre><code>#!/usr/bin/env python from __future__ import with_statement def my_readlines(f): buf = u"" for line in f.readlines(): uline = line.decode('utf8') buf += uli...
2
2009-07-09T18:04:17Z
[ "python", "utf-8", "readline", "separator" ]
How to exclude U+2028 from line separators in Python when reading file?
1,105,106
<p>I have a file in UTF-8, where some lines contain the U+2028 Line Separator character (<a href="http://www.fileformat.info/info/unicode/char/2028/index.htm" rel="nofollow">http://www.fileformat.info/info/unicode/char/2028/index.htm</a>). I don't want it to be treated as a line break when I read lines from the file. I...
3
2009-07-09T16:44:49Z
1,106,449
<p>I can't duplicate this behaviour in python 2.5, 2.6 or 3.0 on mac os x - U+2028 is always treated as non-endline. Could you go into more detail about where you see this error?</p> <p>That said, here is a subclass of the "file" class that might do what you want:</p> <pre><code>#/usr/bin/python # -*- coding: utf-8 -...
1
2009-07-09T21:04:52Z
[ "python", "utf-8", "readline", "separator" ]
How to exclude U+2028 from line separators in Python when reading file?
1,105,106
<p>I have a file in UTF-8, where some lines contain the U+2028 Line Separator character (<a href="http://www.fileformat.info/info/unicode/char/2028/index.htm" rel="nofollow">http://www.fileformat.info/info/unicode/char/2028/index.htm</a>). I don't want it to be treated as a line break when I read lines from the file. I...
3
2009-07-09T16:44:49Z
1,106,760
<p>Thanks to everyone for answering. I think I know why you might not have been able to replicate this.I just realized that it happens if I decode the file when opening, as in:</p> <pre><code>f = codecs.open(filename, encoding='utf-8') for line in f: print line </code></pre> <p>The lines are not separated on u20...
1
2009-07-09T22:24:58Z
[ "python", "utf-8", "readline", "separator" ]
How to exclude U+2028 from line separators in Python when reading file?
1,105,106
<p>I have a file in UTF-8, where some lines contain the U+2028 Line Separator character (<a href="http://www.fileformat.info/info/unicode/char/2028/index.htm" rel="nofollow">http://www.fileformat.info/info/unicode/char/2028/index.htm</a>). I don't want it to be treated as a line break when I read lines from the file. I...
3
2009-07-09T16:44:49Z
1,107,249
<p>The codecs module is doing the RIGHT thing. U+2028 is named "LINE SEPARATOR" with the comment "may be used to represent this semantic unambiguously". So treating it as a line separator is sensible.</p> <p>Presumably the creator would not have put the U+2028 characters there without good reason ... does the file hav...
0
2009-07-10T01:15:31Z
[ "python", "utf-8", "readline", "separator" ]
storing uploaded photos and documents - filesystem vs database blob
1,105,429
<p><strong>My specific situation</strong></p> <p>Property management web site where users can upload photos and lease documents. For every apartment unit, there might be 4 photos, so there won't be an overwhelming number of photo in the system. </p> <p>For photos, there will be thumbnails of each.</p> <p><strong>M...
10
2009-07-09T17:39:58Z
1,105,444
<p>File system. No contest. The data has to go through a lot more layers when you store it in the db.</p> <p>Edit on caching: If you want to cache the file while the user uploads it to ensure the operation finishes as soon as possible, dumping it straight to disk (i.e. file system) is about as quick as it gets. As lon...
9
2009-07-09T17:42:19Z
[ "python", "postgresql", "storage", "photos", "photo-management" ]
storing uploaded photos and documents - filesystem vs database blob
1,105,429
<p><strong>My specific situation</strong></p> <p>Property management web site where users can upload photos and lease documents. For every apartment unit, there might be 4 photos, so there won't be an overwhelming number of photo in the system. </p> <p>For photos, there will be thumbnails of each.</p> <p><strong>M...
10
2009-07-09T17:39:58Z
1,105,453
<p>While there are exceptions to everything, the general case is that storing images in the file system is your best bet. You can easily provide caching services to the images, you don't need to worry about additional code to handle image processing, and you can easily do maintenance on the images if needed through sta...
10
2009-07-09T17:43:25Z
[ "python", "postgresql", "storage", "photos", "photo-management" ]
storing uploaded photos and documents - filesystem vs database blob
1,105,429
<p><strong>My specific situation</strong></p> <p>Property management web site where users can upload photos and lease documents. For every apartment unit, there might be 4 photos, so there won't be an overwhelming number of photo in the system. </p> <p>For photos, there will be thumbnails of each.</p> <p><strong>M...
10
2009-07-09T17:39:58Z
1,105,479
<p>Definitely store your images on the filesystem. One concern that folks don't consider enough when considering these types of things is bloat; cramming images as binary blobs into your database is a really quick way to bloat your DB way up. With a large database comes higher hardware requirements, more difficult re...
3
2009-07-09T17:48:56Z
[ "python", "postgresql", "storage", "photos", "photo-management" ]
storing uploaded photos and documents - filesystem vs database blob
1,105,429
<p><strong>My specific situation</strong></p> <p>Property management web site where users can upload photos and lease documents. For every apartment unit, there might be 4 photos, so there won't be an overwhelming number of photo in the system. </p> <p>For photos, there will be thumbnails of each.</p> <p><strong>M...
10
2009-07-09T17:39:58Z
1,105,534
<p>a DB <em>might</em> be faster than a filesystem on some operations, but loading a well-identified chunk of data 100s of KB is not one of them.</p> <p>also, a good frontend webserver (like nginx) is way faster than any webapp layer you'd have to write to read the blob from the DB. in some tests nginx is roughly on ...
1
2009-07-09T17:58:11Z
[ "python", "postgresql", "storage", "photos", "photo-management" ]
storing uploaded photos and documents - filesystem vs database blob
1,105,429
<p><strong>My specific situation</strong></p> <p>Property management web site where users can upload photos and lease documents. For every apartment unit, there might be 4 photos, so there won't be an overwhelming number of photo in the system. </p> <p>For photos, there will be thumbnails of each.</p> <p><strong>M...
10
2009-07-09T17:39:58Z
1,106,705
<p>Maybe on a slight tangent, but in <a href="http://www.mysqlconf.com/mysql2009/public/schedule/detail/8232" rel="nofollow">this</a> video from the MySQL Conference, the presenter talks about how the website <a href="http://www.smugmug.com/" rel="nofollow">smugmug</a> uses MySQL and various other technologies for supe...
1
2009-07-09T22:12:14Z
[ "python", "postgresql", "storage", "photos", "photo-management" ]
storing uploaded photos and documents - filesystem vs database blob
1,105,429
<p><strong>My specific situation</strong></p> <p>Property management web site where users can upload photos and lease documents. For every apartment unit, there might be 4 photos, so there won't be an overwhelming number of photo in the system. </p> <p>For photos, there will be thumbnails of each.</p> <p><strong>M...
10
2009-07-09T17:39:58Z
14,577,062
<p><em>Comment to the Sheepy's answer.</em></p> <p>In common storing files in SQL is better when file size less than 256 kilobytes, and worth when it greater 1 megabyte. So between 256-1024 kilobytes it depends on several factors. Read <a href="http://research.microsoft.com/apps/pubs/default.aspx?id=64525" rel="nofoll...
2
2013-01-29T06:40:03Z
[ "python", "postgresql", "storage", "photos", "photo-management" ]
Starting an INDIVIDUAL instance of a subclass from asynchat
1,105,814
<p>So the situation I have is that I have loaded more than one class that I've made that subclasses from <code>asynchat</code>, but I only want one of them to run. Of course, this doesn't work out when I call <code>asyncore.loop()</code> as they all begin. Is there any way to make only one of them begin running?</p> <...
0
2009-07-09T18:51:53Z
1,319,238
<p>For all who were curious, I figured it out. If you pass your instance's <code>_map</code> to <code>loop()</code> it seems to only start the single instance.</p> <p>Example:</p> <pre><code>my_asyncore_obj = SomeAsyncoreObj() asyncore.loop(map=my_asyncore_obj._map) </code></pre>
0
2009-08-23T18:42:45Z
[ "python", "asyncore" ]
Parse annotations from a pdf
1,106,098
<p>I want a python function that takes a pdf and returns a list of the text of the note annotations in the document. I have looked at python-poppler (<a href="https://code.launchpad.net/~poppler-python/poppler-python/trunk">https://code.launchpad.net/~poppler-python/poppler-python/trunk</a>) but I can not figure out ho...
16
2009-07-09T19:52:08Z
1,107,909
<p>I didn't ever used this, nor I wanted this kind of features, but I found <a href="http://www.unixuser.org/~euske/python/pdfminer/index.html" rel="nofollow">PDFMiner</a> - this link has information about basic usage, maybe this is what You are looking for?</p>
1
2009-07-10T05:50:55Z
[ "python", "pdf" ]
Parse annotations from a pdf
1,106,098
<p>I want a python function that takes a pdf and returns a list of the text of the note annotations in the document. I have looked at python-poppler (<a href="https://code.launchpad.net/~poppler-python/poppler-python/trunk">https://code.launchpad.net/~poppler-python/poppler-python/trunk</a>) but I can not figure out ho...
16
2009-07-09T19:52:08Z
1,116,901
<p>Turns out the bindings were incomplete. It is now fixed. <a href="https://bugs.launchpad.net/poppler-python/+bug/397850" rel="nofollow">https://bugs.launchpad.net/poppler-python/+bug/397850</a></p>
3
2009-07-12T20:57:11Z
[ "python", "pdf" ]
Parse annotations from a pdf
1,106,098
<p>I want a python function that takes a pdf and returns a list of the text of the note annotations in the document. I have looked at python-poppler (<a href="https://code.launchpad.net/~poppler-python/poppler-python/trunk">https://code.launchpad.net/~poppler-python/poppler-python/trunk</a>) but I can not figure out ho...
16
2009-07-09T19:52:08Z
12,502,560
<p>Just in case somebody is looking for some working code. Here is a script I use.</p> <pre><code>import poppler import sys import urllib import os def main(): input_filename = sys.argv[1] # http://blog.hartwork.org/?p=612 document = poppler.document_new_from_file('file://%s' % \ urllib.pathname2url(os.pa...
10
2012-09-19T20:40:13Z
[ "python", "pdf" ]
improving Boyer-Moore string search
1,106,112
<p>I've been playing around with the Boyer-Moore sting search algorithm and starting with a base code set from Shriphani Palakodety I created 2 additional versions (v2 and v3) - each making some modifications such as removing len() function from the loop and than refactoring the while/if conditions. From v1 to v2 I se...
2
2009-07-09T19:54:07Z
1,107,298
<p>Using "in bcs.keys()" is creating a list and then doing an O(N) search of the list -- just use "in bcs". </p> <p>Do the goodSuffixShift(key) thing inside the search function. Two benefits: the caller has only one API to use, and you avoid having bcs as a global (horrid ** 2). </p> <p>Your indentation is incorrec...
3
2009-07-10T01:37:30Z
[ "python", "performance" ]
How are these type of python decorators written?
1,106,223
<p>I'd like to write a decorator that would limit the number of times a function can be executed, something along the following syntax :</p> <pre><code> @max_execs(5) def my_method(*a,**k): # do something here pass </code></pre> <p>I think it's possible to write this type of decorator, but I don't know how. I t...
6
2009-07-09T20:16:56Z
1,106,242
<p>I know you said you didn't want a class, but unfortunately that's the only way I can think of how to do it off the top of my head.</p> <pre><code>class mymethodwrapper: def __init__(self): self.maxcalls = 0 def mymethod(self): self.maxcalls += 1 if self.maxcalls &gt; 5: r...
0
2009-07-09T20:24:46Z
[ "python", "language-features", "decorator" ]
How are these type of python decorators written?
1,106,223
<p>I'd like to write a decorator that would limit the number of times a function can be executed, something along the following syntax :</p> <pre><code> @max_execs(5) def my_method(*a,**k): # do something here pass </code></pre> <p>I think it's possible to write this type of decorator, but I don't know how. I t...
6
2009-07-09T20:16:56Z
1,106,244
<p>Decorator is merely a callable that transforms a function into something else. In your case, <code>max_execs(5)</code> must be a callable that transforms a function into another callable object that will count and forward the calls.</p> <pre><code>class helper: def __init__(self, i, fn): self.i = i ...
4
2009-07-09T20:24:53Z
[ "python", "language-features", "decorator" ]
How are these type of python decorators written?
1,106,223
<p>I'd like to write a decorator that would limit the number of times a function can be executed, something along the following syntax :</p> <pre><code> @max_execs(5) def my_method(*a,**k): # do something here pass </code></pre> <p>I think it's possible to write this type of decorator, but I don't know how. I t...
6
2009-07-09T20:16:56Z
1,106,255
<p>There are two ways of doing it. The object-oriented way is to make a class:</p> <pre><code>class max_execs: def __init__(self, max_executions): self.max_executions = max_executions self.executions = 0 def __call__(self, func): @wraps(func) def maybe(*args, **kwargs): ...
3
2009-07-09T20:27:09Z
[ "python", "language-features", "decorator" ]
How are these type of python decorators written?
1,106,223
<p>I'd like to write a decorator that would limit the number of times a function can be executed, something along the following syntax :</p> <pre><code> @max_execs(5) def my_method(*a,**k): # do something here pass </code></pre> <p>I think it's possible to write this type of decorator, but I don't know how. I t...
6
2009-07-09T20:16:56Z
1,106,289
<p>This is what I whipped up. It doesn't use a class, but it does use function attributes:</p> <pre><code>def max_execs(n=5): def decorator(fn): fn.max = n fn.called = 0 def wrapped(*args, **kwargs): fn.called += 1 if fn.called &lt;= fn.max: return fn...
12
2009-07-09T20:32:25Z
[ "python", "language-features", "decorator" ]
How are these type of python decorators written?
1,106,223
<p>I'd like to write a decorator that would limit the number of times a function can be executed, something along the following syntax :</p> <pre><code> @max_execs(5) def my_method(*a,**k): # do something here pass </code></pre> <p>I think it's possible to write this type of decorator, but I don't know how. I t...
6
2009-07-09T20:16:56Z
1,106,349
<p>Without relying to a state in a class, you have to save the state (count) in the function itself:</p> <pre><code>def max_execs(count): def new_meth(meth): meth.count = count def new(*a,**k): meth.count -= 1 print meth.count if meth.count&gt;=0: ...
2
2009-07-09T20:46:08Z
[ "python", "language-features", "decorator" ]
How are these type of python decorators written?
1,106,223
<p>I'd like to write a decorator that would limit the number of times a function can be executed, something along the following syntax :</p> <pre><code> @max_execs(5) def my_method(*a,**k): # do something here pass </code></pre> <p>I think it's possible to write this type of decorator, but I don't know how. I t...
6
2009-07-09T20:16:56Z
1,106,423
<p>This method does not modify function internals, instead wraps it into a callable object.</p> <p>Using class slows down execution by ~20% vs using the patched function!</p> <pre><code>def max_execs(n=1): class limit_wrapper: def __init__(self, fn, max): self.calls_left = max self...
1
2009-07-09T21:01:00Z
[ "python", "language-features", "decorator" ]
Python: better way to open lots of sockets
1,106,433
<p>I have the following program to open lot's of sockets, and hold them open to stress test one of our servers. There are several problem's with this. I think it could be a lot more efficient than a recursive call, and it's really still opening sockets in a serial fashion rather than parallel fashion. I realize ther...
1
2009-07-09T21:02:03Z
1,106,504
<p>Well it's already multi process - put a sleep in before calling open_socket, and run , say , 500 of them from a shell:</p> <pre><code>for i in `seq 500`; do ./yourprogram &amp; done </code></pre> <p>You're not a actually connecting to something though - seems you're setting up server sockets ? If you need to conne...
0
2009-07-09T21:16:24Z
[ "python", "sockets" ]
Python: better way to open lots of sockets
1,106,433
<p>I have the following program to open lot's of sockets, and hold them open to stress test one of our servers. There are several problem's with this. I think it could be a lot more efficient than a recursive call, and it's really still opening sockets in a serial fashion rather than parallel fashion. I realize ther...
1
2009-07-09T21:02:03Z
1,106,521
<p>You can try using Twisted for this. It greatly simplifies networking on Python. Their site has <a href="http://twistedmatrix.com/projects/core/documentation/howto/index.html" rel="nofollow">some tutorials</a> to get you started.</p> <p>However, you could easily see using Python an overkill for this task. A faster o...
2
2009-07-09T21:18:44Z
[ "python", "sockets" ]
Python: better way to open lots of sockets
1,106,433
<p>I have the following program to open lot's of sockets, and hold them open to stress test one of our servers. There are several problem's with this. I think it could be a lot more efficient than a recursive call, and it's really still opening sockets in a serial fashion rather than parallel fashion. I realize ther...
1
2009-07-09T21:02:03Z
1,106,537
<p>I was puzzled why you would use recursion instead of a simple loop. My guess is that with a simple loop, you would have overwritten the variable sockname again and again, so that Python's garbage collection would actually close the previous socket after you created the next one. The solution is to store them all in ...
4
2009-07-09T21:22:30Z
[ "python", "sockets" ]
How does os.path map to posixpath.pyc and not os/path.py?
1,106,455
<p>What is the underlying mechanism in Python that handles such "aliases"?</p> <pre><code>&gt;&gt;&gt; import os.path &gt;&gt;&gt; os.path.__file__ '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/posixpath.pyc' </code></pre>
3
2009-07-09T21:05:59Z
1,106,464
<p>Perhaps os uses import as?</p> <pre><code>import posixpath as path </code></pre>
0
2009-07-09T21:08:31Z
[ "python", "import", "path", "module", "alias" ]
How does os.path map to posixpath.pyc and not os/path.py?
1,106,455
<p>What is the underlying mechanism in Python that handles such "aliases"?</p> <pre><code>&gt;&gt;&gt; import os.path &gt;&gt;&gt; os.path.__file__ '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/posixpath.pyc' </code></pre>
3
2009-07-09T21:05:59Z
1,106,498
<p>Taken from os.py on CPython 2.6:</p> <pre><code>sys.modules['os.path'] = path from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, devnull) </code></pre> <p><code>path</code> is defined earlier as the platform-specific module:</p> <pre><code>if 'posix' in _names: name = 'posix' ...
6
2009-07-09T21:15:30Z
[ "python", "import", "path", "module", "alias" ]
installing easy_install for Python 2.6.2 (missing?)
1,106,574
<p>I am not a python user, I'm just trying to get couchdb-dump up and running and it's in an "egg" file which I guess needs easy_install. I have Python 2.6.2 running on my computer but it seems to know nothing about easy_install or setuptools... help! What can I do to fix this??? </p> <p><strong>edit:</strong> you may...
0
2009-07-09T21:31:36Z
1,106,613
<p>I don't like the whole easy_install thing either.</p> <p>But the solution is to download the source, untar it, and type </p> <pre><code>python setup.py install </code></pre>
7
2009-07-09T21:43:29Z
[ "python", "easy-install" ]
installing easy_install for Python 2.6.2 (missing?)
1,106,574
<p>I am not a python user, I'm just trying to get couchdb-dump up and running and it's in an "egg" file which I guess needs easy_install. I have Python 2.6.2 running on my computer but it seems to know nothing about easy_install or setuptools... help! What can I do to fix this??? </p> <p><strong>edit:</strong> you may...
0
2009-07-09T21:31:36Z
1,107,267
<p>For installing setuptools for 2.6 download "ez_setup.py" from:</p> <p><a href="http://svn.python.org/projects/sandbox/branches/setuptools-0.6/#egg=setuptools-dev06" rel="nofollow">http://svn.python.org/projects/sandbox/branches/setuptools-0.6/#egg=setuptools-dev06</a></p> <p>And run it. setuptools should be insta...
0
2009-07-10T01:22:34Z
[ "python", "easy-install" ]
installing easy_install for Python 2.6.2 (missing?)
1,106,574
<p>I am not a python user, I'm just trying to get couchdb-dump up and running and it's in an "egg" file which I guess needs easy_install. I have Python 2.6.2 running on my computer but it seems to know nothing about easy_install or setuptools... help! What can I do to fix this??? </p> <p><strong>edit:</strong> you may...
0
2009-07-09T21:31:36Z
6,418,280
<p><a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">http://pypi.python.org/pypi/setuptools</a><br> ... has been updated and has windows installers for Python 2.6 and 2.7</p> <p>(note: if you need 64-bit windows installer: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd...
1
2011-06-20T22:23:00Z
[ "python", "easy-install" ]
Do I have any obligations if I upload an egg to the CheeseShop?
1,106,759
<p>Suppose I'd like to upload some eggs on the Cheese Shop. Do I have any obligation? Am I required to provide a license? Am I required to provide tests? Will I have any obligations to the users of this egg ( if any ) ?</p> <p>I haven't really released anything as open source 'till now, and I'd like to know the proces...
14
2009-07-09T22:24:51Z
1,106,782
<p>You will need to license the code. Despite what some people may think, the authors of content actually need to grant the license on their own. The Cheese Shop can't grant a license to other people to use the content until you've granted it as the copyright owner.</p>
3
2009-07-09T22:31:20Z
[ "python", "egg", "pypi" ]
Do I have any obligations if I upload an egg to the CheeseShop?
1,106,759
<p>Suppose I'd like to upload some eggs on the Cheese Shop. Do I have any obligation? Am I required to provide a license? Am I required to provide tests? Will I have any obligations to the users of this egg ( if any ) ?</p> <p>I haven't really released anything as open source 'till now, and I'd like to know the proces...
14
2009-07-09T22:24:51Z
1,106,807
<p>See <a href="http://wiki.python.org/moin/CheeseShopTutorial" rel="nofollow">CheeseShopTutorial</a> and <a href="http://docs.python.org/distutils/setupscript.html" rel="nofollow">Writing the Setup Script</a>.</p>
4
2009-07-09T22:38:10Z
[ "python", "egg", "pypi" ]
Do I have any obligations if I upload an egg to the CheeseShop?
1,106,759
<p>Suppose I'd like to upload some eggs on the Cheese Shop. Do I have any obligation? Am I required to provide a license? Am I required to provide tests? Will I have any obligations to the users of this egg ( if any ) ?</p> <p>I haven't really released anything as open source 'till now, and I'd like to know the proces...
14
2009-07-09T22:24:51Z
1,108,038
<ol> <li><p>You have an obligation to register the package with a useful description. Nothing is more frustrating than finding a Package that <em>may</em> be good, but you don't know, because there is no description.</p> <p>Typical example of Lazy developer: <a href="http://pypi.python.org/pypi/gevent/0.9.1">http://py...
9
2009-07-10T06:43:17Z
[ "python", "egg", "pypi" ]
Find functions explicitly defined in a module (python)
1,106,840
<p>Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume my module looks like this:</p> <pre><code>from datetime import date, datetime def test(): return "This is a real method" </code></pre> <p>...
18
2009-07-09T22:49:03Z
1,106,856
<p>Every class in python has a <code>__module__</code> attribute. You can use its value to perform filtering. Take a look at <a href="http://diveintopython.net/file_handling/more_on_modules.html" rel="nofollow">example 6.14 in dive into python</a></p>
1
2009-07-09T22:53:53Z
[ "python", "introspection" ]
Find functions explicitly defined in a module (python)
1,106,840
<p>Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume my module looks like this:</p> <pre><code>from datetime import date, datetime def test(): return "This is a real method" </code></pre> <p>...
18
2009-07-09T22:49:03Z
1,106,871
<p>the python <a href="http://docs.python.org/3.0/library/inspect.html" rel="nofollow">inspect</a> module is probably what you're looking for here.</p> <pre><code>import inspect if inspect.ismethod(methodInQuestion): pass # It's a method </code></pre>
0
2009-07-09T22:56:42Z
[ "python", "introspection" ]
Find functions explicitly defined in a module (python)
1,106,840
<p>Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume my module looks like this:</p> <pre><code>from datetime import date, datetime def test(): return "This is a real method" </code></pre> <p>...
18
2009-07-09T22:49:03Z
1,106,875
<p>How about the following:</p> <pre><code>grep ^def my_module.py </code></pre>
4
2009-07-09T22:59:22Z
[ "python", "introspection" ]
Find functions explicitly defined in a module (python)
1,106,840
<p>Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume my module looks like this:</p> <pre><code>from datetime import date, datetime def test(): return "This is a real method" </code></pre> <p>...
18
2009-07-09T22:49:03Z
1,107,010
<p>You can check <code>__module__</code> attribute of the function in question. I say "function" because a method belongs to a class usually ;-).</p> <p>BTW, a class actually also has <code>__module__</code> attribute.</p>
2
2009-07-09T23:47:26Z
[ "python", "introspection" ]
Find functions explicitly defined in a module (python)
1,106,840
<p>Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume my module looks like this:</p> <pre><code>from datetime import date, datetime def test(): return "This is a real method" </code></pre> <p>...
18
2009-07-09T22:49:03Z
1,107,150
<p>Are you looking for something like this?</p> <pre><code>import sys, inspect def is_mod_function(mod, func): return inspect.isfunction(func) and inspect.getmodule(func) == mod def list_functions(mod): return [func.__name__ for func in mod.__dict__.itervalues() if is_mod_function(mod, func)] ...
21
2009-07-10T00:36:47Z
[ "python", "introspection" ]
Is 'if element in aList' possible with Django templates?
1,106,849
<p>Does something like the python</p> <pre><code>if "a" in ["a", "b", "c"]: pass </code></pre> <p>exist in Django templates? </p> <p>If not, is there an easy way to implement it?</p>
2
2009-07-09T22:50:54Z
1,106,928
<p>This is something you usually do in your view functions.</p> <pre><code>aList = ["a", "b", "c"] listAndFlags = [ (item,item in aList) for item in someQuerySet ] </code></pre> <p>Now you have a simple two-element list that you can display</p> <pre><code>{% for item, flag in someList %} &lt;tr&gt;&lt;td class="...
2
2009-07-09T23:17:23Z
[ "python", "django", "django-templates" ]
Is 'if element in aList' possible with Django templates?
1,106,849
<p>Does something like the python</p> <pre><code>if "a" in ["a", "b", "c"]: pass </code></pre> <p>exist in Django templates? </p> <p>If not, is there an easy way to implement it?</p>
2
2009-07-09T22:50:54Z
1,106,960
<p>Not directly, there is no if x in iterable template tag included.</p> <p>This is not typically something needed inside the templates themselves. Without more context about the surrounding problem a good answer cannot be given. We can guess and say that you want to either pass a nested list like the above commen...
1
2009-07-09T23:28:56Z
[ "python", "django", "django-templates" ]
Python: StopIteration exception and list comprehensions
1,106,903
<p>I'd like to read at most 20 lines from a csv file:</p> <pre><code>rows = [csvreader.next() for i in range(20)] </code></pre> <p>Works fine if the file has 20 or more rows, fails with a StopIteration exception otherwise.</p> <p>Is there an elegant way to deal with an iterator that could throw a StopIteration excep...
8
2009-07-09T23:09:56Z
1,106,921
<p>You can use <a href="http://docs.python.org/library/itertools.html#itertools.islice"><code>itertools.islice</code></a>. It is the iterator version of list slicing. If the iterator has less than 20 elements, it will return all elements.</p> <pre><code>import itertools rows = list(itertools.islice(csvreader, 20)) </c...
10
2009-07-09T23:15:50Z
[ "python", "iterator", "list-comprehension", "stopiteration" ]
Python: StopIteration exception and list comprehensions
1,106,903
<p>I'd like to read at most 20 lines from a csv file:</p> <pre><code>rows = [csvreader.next() for i in range(20)] </code></pre> <p>Works fine if the file has 20 or more rows, fails with a StopIteration exception otherwise.</p> <p>Is there an elegant way to deal with an iterator that could throw a StopIteration excep...
8
2009-07-09T23:09:56Z
1,106,952
<p>If for whatever reason you need also to keep track of the line number, I'd recommend you:</p> <pre><code>rows = zip(xrange(20), csvreader) </code></pre> <p>If not, you can strip it out after or... well, you'd better try other option more optimal from the beginning :-)</p>
-1
2009-07-09T23:26:24Z
[ "python", "iterator", "list-comprehension", "stopiteration" ]
Python: StopIteration exception and list comprehensions
1,106,903
<p>I'd like to read at most 20 lines from a csv file:</p> <pre><code>rows = [csvreader.next() for i in range(20)] </code></pre> <p>Works fine if the file has 20 or more rows, fails with a StopIteration exception otherwise.</p> <p>Is there an elegant way to deal with an iterator that could throw a StopIteration excep...
8
2009-07-09T23:09:56Z
1,247,653
<p><a href="http://docs.python.org/library/itertools.html#itertools.izip" rel="nofollow"><code>itertools.izip</code></a> (<a href="http://doc.astro-wise.org/itertools.html#islice" rel="nofollow">2</a>) provides a way to easily make list comprehensions work, but <code>islice</code> looks to be the way to go in this case...
0
2009-08-08T01:00:55Z
[ "python", "iterator", "list-comprehension", "stopiteration" ]
How to model an object with references to arbitrary number of arbitrary field types? (django orm)
1,107,024
<p>I'd like to define a set of model/objects which allow for one to represent the relationship: field_set has many fields where fields are django.db.model field objects (IPAddressField, FilePathField etc). </p> <p>My goals is to have a ORM model which supports the following type of 'api'.</p> <p>From a controller vie...
2
2009-07-09T23:52:39Z
1,107,105
<p>In SQL there is no such thing as a table with variable number of columns or variable type columns. Also, Django does not modify database layout at run time - i.e. does not call <code>ALTER TABLE</code> statements - as far as I know.</p> <p>In django data models must be completely defined before you run your applica...
0
2009-07-10T00:21:06Z
[ "python", "django", "orm" ]
How to model an object with references to arbitrary number of arbitrary field types? (django orm)
1,107,024
<p>I'd like to define a set of model/objects which allow for one to represent the relationship: field_set has many fields where fields are django.db.model field objects (IPAddressField, FilePathField etc). </p> <p>My goals is to have a ORM model which supports the following type of 'api'.</p> <p>From a controller vie...
2
2009-07-09T23:52:39Z
1,107,166
<p>I see several problems with the code. First, with this class definition:</p> <pre><code>class Field(models.Model): f = models.Field() fieldset = models.ForeignKey(FieldSet) </code></pre> <p>The class models.Field is not supposed to be used directly for a field definition. It is a base class for all field types...
1
2009-07-10T00:42:12Z
[ "python", "django", "orm" ]
How to model an object with references to arbitrary number of arbitrary field types? (django orm)
1,107,024
<p>I'd like to define a set of model/objects which allow for one to represent the relationship: field_set has many fields where fields are django.db.model field objects (IPAddressField, FilePathField etc). </p> <p>My goals is to have a ORM model which supports the following type of 'api'.</p> <p>From a controller vie...
2
2009-07-09T23:52:39Z
23,850,110
<p>Why not to make sth like this?</p> <pre><code>class Info(models.Model): info_type = models.ForeignKey('InfoType', blank=False, null=False, default='') info_int = models.IntegerField(null=True, blank=True) info_img = models.ImageField(upload_to='info',null=True, blank=True) info_date = models.DateTim...
0
2014-05-24T22:07:16Z
[ "python", "django", "orm" ]
Python Lambda Problems
1,107,210
<p>What's going on here? I'm trying to create a list of functions:</p> <pre><code>def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(lambda x:f(i,x)) </code></pre> <p>This isn't doing what I expect. I would expect the list to act like this:</p> <pre><code>funcs[3](3) = 9 funcs[0](5) = 0...
12
2009-07-10T01:01:25Z
1,107,232
<p>All the lambdas end up being bound to the last one. See this question for a longer answer:</p> <p><a href="http://stackoverflow.com/questions/452610/how-do-i-create-a-list-of-python-lambdas-in-a-list-comprehension-for-loop">http://stackoverflow.com/questions/452610/how-do-i-create-a-list-of-python-lambdas-in-a-list...
1
2009-07-10T01:10:21Z
[ "python", "lambda" ]
Python Lambda Problems
1,107,210
<p>What's going on here? I'm trying to create a list of functions:</p> <pre><code>def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(lambda x:f(i,x)) </code></pre> <p>This isn't doing what I expect. I would expect the list to act like this:</p> <pre><code>funcs[3](3) = 9 funcs[0](5) = 0...
12
2009-07-10T01:01:25Z
1,107,234
<p>Considering the final value of <code>i == 9</code></p> <p>Like any good python function, it's going to use the value of the variable in the scope it was defined. Perhaps <code>lambda: varname</code> (being that it is a language construct) binds to the name, not the value, and evaluates that name at runtime?</p> <...
1
2009-07-10T01:10:41Z
[ "python", "lambda" ]
Python Lambda Problems
1,107,210
<p>What's going on here? I'm trying to create a list of functions:</p> <pre><code>def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(lambda x:f(i,x)) </code></pre> <p>This isn't doing what I expect. I would expect the list to act like this:</p> <pre><code>funcs[3](3) = 9 funcs[0](5) = 0...
12
2009-07-10T01:01:25Z
1,107,243
<p>lambdas in python are closures.... the arguments you give it aren't going to be evaluated until the lambda is evaluated. At that time, i=9 regardless, because your iteration is finished.</p> <p>The behavior you're looking for can be achieved with functools.partial</p> <pre><code>import functools def f(a,b): ...
15
2009-07-10T01:13:24Z
[ "python", "lambda" ]
Python Lambda Problems
1,107,210
<p>What's going on here? I'm trying to create a list of functions:</p> <pre><code>def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(lambda x:f(i,x)) </code></pre> <p>This isn't doing what I expect. I would expect the list to act like this:</p> <pre><code>funcs[3](3) = 9 funcs[0](5) = 0...
12
2009-07-10T01:01:25Z
1,107,260
<p>There's only one <code>i</code> which is bound to each lambda, contrary to what you think. This is a common mistake. </p> <p>One way to get what you want is:</p> <pre><code>for i in range(0,10): funcs.append(lambda x, i=i: f(i, x)) </code></pre> <p>Now you're creating a default parameter <code>i</code> in e...
8
2009-07-10T01:18:54Z
[ "python", "lambda" ]
Python Lambda Problems
1,107,210
<p>What's going on here? I'm trying to create a list of functions:</p> <pre><code>def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(lambda x:f(i,x)) </code></pre> <p>This isn't doing what I expect. I would expect the list to act like this:</p> <pre><code>funcs[3](3) = 9 funcs[0](5) = 0...
12
2009-07-10T01:01:25Z
1,107,333
<p>Yep, the usual "scoping problem" (actually a binding-later-than-you want problem, but it's often called by that name). You've already gotten the two best (because simplest) answers -- the "fake default" <code>i=i</code> solution, and <code>functools.partial</code>, so I'm only giving the third one of the classic thr...
11
2009-07-10T01:56:49Z
[ "python", "lambda" ]
Platform-independent version of /var/lib and ~/.config
1,107,213
<p>We see that programs like <code>apt-get</code> store information in several places:</p> <pre><code>/var/cache/apt &lt;- cache /var/lib/apt &lt;- keyrings, package db, states, locks, mirrors /etc/apt &lt;- configuration file ~/.aptitude/config &lt;- user configuration file </code></pre> <p>S...
1
2009-07-10T01:02:05Z
1,107,869
<p>Do you mean something like <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a>?</p>
-1
2009-07-10T05:32:31Z
[ "python", "configuration", "path", "cross-platform" ]
Platform-independent version of /var/lib and ~/.config
1,107,213
<p>We see that programs like <code>apt-get</code> store information in several places:</p> <pre><code>/var/cache/apt &lt;- cache /var/lib/apt &lt;- keyrings, package db, states, locks, mirrors /etc/apt &lt;- configuration file ~/.aptitude/config &lt;- user configuration file </code></pre> <p>S...
1
2009-07-10T01:02:05Z
1,127,382
<p>For Linux, check out the <a href="http://www.pathname.com/fhs/" rel="nofollow">Filesystem Hierarchy Standard</a> (but be aware that these standards are for software being part of distribution, software installed locally should not interfere with distribution's package management and stay in /usr/local/ and /var/loca...
1
2009-07-14T19:09:03Z
[ "python", "configuration", "path", "cross-platform" ]
looking for a more pythonic way to access the database
1,107,297
<p>I have a bunch of python methods that follow this pattern:</p> <pre><code>def delete_session(guid): conn = get_conn() cur = conn.cursor() cur.execute("delete from sessions where guid=%s", guid) conn.commit() conn.close() </code></pre> <p>Is there a more pythonic way to execute raw sql. The 2 ...
4
2009-07-10T01:37:14Z
1,107,303
<p>You could write a context manager and use the with statement. For example, see this blog post:</p> <p><a href="http://jessenoller.com/2009/02/03/get-with-the-program-as-contextmanager-completely-different/" rel="nofollow">http://jessenoller.com/2009/02/03/get-with-the-program-as-contextmanager-completely-different...
8
2009-07-10T01:42:16Z
[ "python", "mysql" ]
looking for a more pythonic way to access the database
1,107,297
<p>I have a bunch of python methods that follow this pattern:</p> <pre><code>def delete_session(guid): conn = get_conn() cur = conn.cursor() cur.execute("delete from sessions where guid=%s", guid) conn.commit() conn.close() </code></pre> <p>Is there a more pythonic way to execute raw sql. The 2 ...
4
2009-07-10T01:37:14Z
1,107,314
<p>Careful about that <code>execute</code>, the second argument needs to be [guid] (a list with just one item). As for your question, I normally just use a class encapsulating connection and cursor, but it looks like you may prefer to use an <em>execution context</em> object whose <code>__enter__</code> method gives y...
3
2009-07-10T01:46:46Z
[ "python", "mysql" ]
looking for a more pythonic way to access the database
1,107,297
<p>I have a bunch of python methods that follow this pattern:</p> <pre><code>def delete_session(guid): conn = get_conn() cur = conn.cursor() cur.execute("delete from sessions where guid=%s", guid) conn.commit() conn.close() </code></pre> <p>Is there a more pythonic way to execute raw sql. The 2 ...
4
2009-07-10T01:37:14Z
1,107,315
<p>It doesn't have to be more pythonic, just more structured:</p> <pre><code>def execSql(statement): conn = get_conn() cur = conn.cursor() cur.execute(statement) conn.commit() conn.close() def delete_session(guid): execSql("delete from sessions where guid=%s"%(guid)) </code></pre>
0
2009-07-10T01:47:48Z
[ "python", "mysql" ]
looking for a more pythonic way to access the database
1,107,297
<p>I have a bunch of python methods that follow this pattern:</p> <pre><code>def delete_session(guid): conn = get_conn() cur = conn.cursor() cur.execute("delete from sessions where guid=%s", guid) conn.commit() conn.close() </code></pre> <p>Is there a more pythonic way to execute raw sql. The 2 ...
4
2009-07-10T01:37:14Z
1,107,316
<p>A decorator?</p> <pre><code>class SqlExec: def __init__ (self, f): self.f = f def __call__ (self, *args): conn = get_conn() cur = conn.cursor() cur.execute(self.f (*args)) conn.commit() conn.close() @SqlExec def delete_session(guid): return "delete from sessions whe...
0
2009-07-10T01:48:22Z
[ "python", "mysql" ]
looking for a more pythonic way to access the database
1,107,297
<p>I have a bunch of python methods that follow this pattern:</p> <pre><code>def delete_session(guid): conn = get_conn() cur = conn.cursor() cur.execute("delete from sessions where guid=%s", guid) conn.commit() conn.close() </code></pre> <p>Is there a more pythonic way to execute raw sql. The 2 ...
4
2009-07-10T01:37:14Z
1,107,440
<p>"I have a bunch of python methods that follow this pattern:"</p> <p>This is confusing.</p> <p>Either you have a bunch of functions, or you have a bunch of methods of a class.</p> <p><strong>Bunch of Functions</strong>.</p> <p>Do this instead.</p> <pre><code>class SQLFunction( object ): def __init__( self, c...
3
2009-07-10T02:47:12Z
[ "python", "mysql" ]
looking for a more pythonic way to access the database
1,107,297
<p>I have a bunch of python methods that follow this pattern:</p> <pre><code>def delete_session(guid): conn = get_conn() cur = conn.cursor() cur.execute("delete from sessions where guid=%s", guid) conn.commit() conn.close() </code></pre> <p>Is there a more pythonic way to execute raw sql. The 2 ...
4
2009-07-10T01:37:14Z
39,772,336
<p>According to the <a href="https://docs.python.org/2/library/sqlite3.html#using-shortcut-methods" rel="nofollow">docs</a>, if you were using SQLite3, you wouldn't even <em>need</em> a <code>Cursor</code> which, as the docs say, is "often superfluous".</p> <p>Instead you can use the shortcut methods <code>execute</co...
0
2016-09-29T13:55:34Z
[ "python", "mysql" ]
hex to string formatting conversion in python
1,107,331
<p>I used to generate random string in the following way (now I've switched to <a href="http://stackoverflow.com/questions/785058/random-strings-in-python-2-6-is-this-ok/785086#785086" rel="nofollow" title="this method">this method</a>).</p> <pre><code>key = '%016x' % random.getrandbits(128) </code></pre> <p>The key ...
2
2009-07-10T01:56:20Z
1,107,341
<p>Yes, but the format you're using doesn't truncate -- you generate 128 random bits, which require (usually) 32 hex digits to show, and the <code>%016</code> means AT LEAST 16 hex digits, but doesn't just throw away the extra ones you need to show all of that 128-bit number. Why not generate just 64 random bits if th...
5
2009-07-10T01:59:50Z
[ "python", "string" ]
hex to string formatting conversion in python
1,107,331
<p>I used to generate random string in the following way (now I've switched to <a href="http://stackoverflow.com/questions/785058/random-strings-in-python-2-6-is-this-ok/785086#785086" rel="nofollow" title="this method">this method</a>).</p> <pre><code>key = '%016x' % random.getrandbits(128) </code></pre> <p>The key ...
2
2009-07-10T01:56:20Z
1,107,348
<p>Each hex characters from 0 to F contains 4 bits of information, or half a byte. 128 bits is 16 bytes, and since it takes two hex characters to print a byte you get 32 characters. Your format string should thus be <code>'%032x'</code> which will always generate a 32-character string, never shorter.</p> <pre><code>jk...
3
2009-07-10T02:01:41Z
[ "python", "string" ]
Noob components design question
1,107,368
<p><strong>Updated question, see below</strong></p> <p>I'm starting a new project and I would like to experiment with components based architecture (I chose <a href="http://peak.telecommunity.com/PyProtocols.html" rel="nofollow">PyProtocols</a>). It's a little program to display and interract with realtime graphics.</...
3
2009-07-10T02:11:05Z
1,107,971
<p>I haven't used PyProtocols, only the Zope Component Architecture, but they are similar enough for these principles to be the same.</p> <p>Your error is that you have two adapters that can adapt the same thing. You both have an averaging filter and an inversion filter. When you then ask for the filter, both are foun...
1
2009-07-10T06:21:25Z
[ "python", "interface", "protocols" ]
Manually logging out a user, after a site update in Django
1,107,598
<p>I have a website, which will be frequently updated. Sometimes changes happen to User specific models and are linked to sessions.</p> <p>After I update my site, I want the user to log out and log back in. So I would log out the user right then. If he logs back in, he will see the latest updates to the site.</p> <p>...
1
2009-07-10T03:52:15Z
1,107,640
<p>You could just reset your session table. This would logout every user. Of course, depending on what your doing with sessions, it could have other implications (like emptying a shopping cart, for example).</p> <pre><code>python manage.py reset sessions </code></pre> <p>Or in raw SQL:</p> <pre><code>DELETE FROM dja...
10
2009-07-10T04:04:59Z
[ "python", "django", "authentication", "logout" ]
Manually logging out a user, after a site update in Django
1,107,598
<p>I have a website, which will be frequently updated. Sometimes changes happen to User specific models and are linked to sessions.</p> <p>After I update my site, I want the user to log out and log back in. So I would log out the user right then. If he logs back in, he will see the latest updates to the site.</p> <p>...
1
2009-07-10T03:52:15Z
1,108,781
<p>See this: <a href="http://docs.djangoproject.com/en/dev/topics/auth/#how-to-log-a-user-out" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/auth/#how-to-log-a-user-out</a></p> <p>That seems to cover it.</p>
-1
2009-07-10T10:18:27Z
[ "python", "django", "authentication", "logout" ]
Assigning a Iron Python list to .NET array
1,107,789
<p>I have a list comprehension operating on elements of an .NET array like</p> <pre><code>obj.arr = [f(x) for x in obj.arr] </code></pre> <p>However the assignment back to obj.arr fails.</p> <p>Is it possible to convert a list to a .NET array in IronPython?</p>
3
2009-07-10T05:05:16Z
1,107,828
<p>Try this:</p> <pre><code>obj.arr = Array[T]([f(x) for x in obj.arr]) </code></pre> <p>replacing <code>T</code> with type of array elements.</p> <p>Alternatively:</p> <pre><code>obj.arr = tuple([f(x) for x in obj.arr]) </code></pre>
5
2009-07-10T05:17:39Z
[ "python", "ironpython" ]
Assigning a Iron Python list to .NET array
1,107,789
<p>I have a list comprehension operating on elements of an .NET array like</p> <pre><code>obj.arr = [f(x) for x in obj.arr] </code></pre> <p>However the assignment back to obj.arr fails.</p> <p>Is it possible to convert a list to a .NET array in IronPython?</p>
3
2009-07-10T05:05:16Z
1,107,830
<p>Arrays have to be typed as far as I know. This works for me:</p> <pre><code>num_list = [n for n in range(10)] from System import Array num_arr = Array[int](num_list) </code></pre> <p>Similarly for strings and other types. </p>
2
2009-07-10T05:18:28Z
[ "python", "ironpython" ]
python long running daemon job processor
1,107,826
<p>I want to write a long running process (linux daemon) that serves two purposes:</p> <ul> <li>responds to REST web requests</li> <li>executes jobs which can be scheduled </li> </ul> <p>I originally had it working as a simple program that would run through runs and do the updates which I then cron’d, but now I hav...
2
2009-07-10T05:16:44Z
1,107,859
<p>I usually use <code>cron</code> for scheduling. As for REST you can use one of the many, many web frameworks out there. But just running SimpleHTTPServer should be enough.</p> <p>You can schedule the REST service startup with <code>cron</code> @reboot</p> <pre><code>@reboot (cd /path/to/my/app &amp;&amp; nohup pyt...
0
2009-07-10T05:29:23Z
[ "python", "web-services", "scheduling", "long-running-processes" ]
python long running daemon job processor
1,107,826
<p>I want to write a long running process (linux daemon) that serves two purposes:</p> <ul> <li>responds to REST web requests</li> <li>executes jobs which can be scheduled </li> </ul> <p>I originally had it working as a simple program that would run through runs and do the updates which I then cron’d, but now I hav...
2
2009-07-10T05:16:44Z
1,107,871
<p>One option is to simply choose a lightweight WSGI server from this list:</p> <ul> <li><a href="http://wsgi.org/wsgi/Servers" rel="nofollow">http://wsgi.org/wsgi/Servers</a></li> </ul> <p>and let it do the work of a long-running process that serves requests. (I would recommend <a href="http://pypi.python.org/pypi/...
1
2009-07-10T05:33:28Z
[ "python", "web-services", "scheduling", "long-running-processes" ]