title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python: default/common way to read png images
2,200,742
<p>I haven't found a standard way in Python to read images. Is there really none (because there are so many functions for so many custom stuff that I really wonder that there are no functions to read images)? Or what is it? (It should be available in the MacOSX standard installation and in most recent versions on Linux...
16
2010-02-04T15:15:26Z
16,388,379
<p>Coming late to the party, I would strongly suggest one of the <a href="http://www.imagemagick.org/script/api.php#python" rel="nofollow">Python interfaces to the ImageMagick</a> library (Wand worked well in my testing, I'll know more soon...)</p> <p>ImageMagick is a more powerful library and also pretty well a de-fa...
2
2013-05-05T19:39:13Z
[ "python", "image", "png" ]
How bad is it to override a method from a third-party module?
2,200,880
<p>How bad is it to redefine a class method from another, third-party module, in Python?</p> <p>In fact, users can create NumPy matrices that contain <a href="http://pypi.python.org/pypi/uncertainties/" rel="nofollow">numbers with uncertainty</a>; ideally, I would like their code to run unmodified (compared to when th...
9
2010-02-04T15:30:17Z
2,200,915
<p>In general, it's perfectly acceptable to override methods that are ...</p> <ul> <li>Intentionally permit overrides</li> <li>In a way they document (satisfying <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow">LSP</a> won't hurt)</li> </ul> <p>If both conditions are met, then overr...
1
2010-02-04T15:36:32Z
[ "python", "numpy", "override" ]
How bad is it to override a method from a third-party module?
2,200,880
<p>How bad is it to redefine a class method from another, third-party module, in Python?</p> <p>In fact, users can create NumPy matrices that contain <a href="http://pypi.python.org/pypi/uncertainties/" rel="nofollow">numbers with uncertainty</a>; ideally, I would like their code to run unmodified (compared to when th...
9
2010-02-04T15:30:17Z
2,201,098
<p>Depends on what you mean with "redefine". Obviously you can use your own version of it, no problem at all. Also you can redefine it by subclassing if it's a method.</p> <p>You can also make a new method, and patch it into the class, a practice known as monkey_patching. Like so:</p> <pre><code>from amodule import a...
1
2010-02-04T16:01:31Z
[ "python", "numpy", "override" ]
How bad is it to override a method from a third-party module?
2,200,880
<p>How bad is it to redefine a class method from another, third-party module, in Python?</p> <p>In fact, users can create NumPy matrices that contain <a href="http://pypi.python.org/pypi/uncertainties/" rel="nofollow">numbers with uncertainty</a>; ideally, I would like their code to run unmodified (compared to when th...
9
2010-02-04T15:30:17Z
2,201,106
<p>Subclassing (which does involve overriding, as the term is generally used) is generally much preferable to "monkey-patching" (stuffing altered methods into existing classes or modules), even when the latter is available (built-in types, meaning ones implemented in C, can protect themselves against monkey-patching, a...
11
2010-02-04T16:02:23Z
[ "python", "numpy", "override" ]
Inheritance in Python C++ extension
2,200,912
<p>I have c++ library that need communicate with Python plugged in modules. Communication supposes implementing by Python some callback c++ interface. </p> <p>I have read already about writing extensions, but no idea how to develop inheritance.</p> <p>So something about: C++:</p> <pre><code>class Broadcast { void...
2
2010-02-04T15:35:51Z
2,201,715
<p>Writing Python types in C that are inheritable is explained in <a href="http://www.python.org/dev/peps/pep-0253/" rel="nofollow">PEP 253</a>. It's not all that different from writing a normal builtin type as explained in <a href="http://docs.python.org/extending" rel="nofollow">the Extending/Embedding guide</a> but ...
4
2010-02-04T17:19:00Z
[ "c++", "python" ]
Need code to get all files in directory and past another local?
2,201,173
<p>i need code python to get all pic files in diretorie e paste another dir for ex. in "c:\capture" confirm exist pic files, if true get all and paste in c:\backup\paste.1 sleep 30 min and confirm new files in c:\capture if true get all and past in c:\backup\paste.2</p> <p>sorry my bad english tks</p>
0
2010-02-04T16:12:09Z
2,201,205
<p>I'm not sure what exactly you want to do, by are you looking for <a href="http://docs.python.org/library/os.html#os.listdir" rel="nofollow"><code>os.listdir()</code></a>, <a href="http://docs.python.org/library/os.html#os.rename" rel="nofollow"><code>os.rename()</code></a> and the other functions of the <a href="htt...
1
2010-02-04T16:15:11Z
[ "python" ]
How do I access my classes from the python console on MAC OSX?
2,201,461
<p>I'm trying to access my classes via </p> <pre><code>from project import * </code></pre> <p>But from the python console something seems to be off with the paths. How do I set the correct paths to my project so I can import classes? </p> <p>My models are stored in:</p> <pre><code>/Users/username/project/project/...
0
2010-02-04T16:48:56Z
2,201,499
<p>Most likely you will have to set the PYTHONPATH env variable, or change in the correct directory.</p> <p>I assume you do not start your console from: /Users/username/project</p> <p>You have several options now:</p> <ol> <li>Change to that directory</li> <li>Set the PYTHONPATH env variable to that directory (howev...
1
2010-02-04T16:52:38Z
[ "python", "osx", "pylons" ]
How do I access my classes from the python console on MAC OSX?
2,201,461
<p>I'm trying to access my classes via </p> <pre><code>from project import * </code></pre> <p>But from the python console something seems to be off with the paths. How do I set the correct paths to my project so I can import classes? </p> <p>My models are stored in:</p> <pre><code>/Users/username/project/project/...
0
2010-02-04T16:48:56Z
2,201,617
<p>You have the following choices</p> <ul> <li>Start your python session in the /User/username/project folder</li> <li>Change your import line to <code>from project.project import *</code></li> <li>Set the PYTHONPATH environment variable to /User/username/project (<code>setenv PYTHONPATH /User/username/project</code>)...
4
2010-02-04T17:06:51Z
[ "python", "osx", "pylons" ]
How do I access my classes from the python console on MAC OSX?
2,201,461
<p>I'm trying to access my classes via </p> <pre><code>from project import * </code></pre> <p>But from the python console something seems to be off with the paths. How do I set the correct paths to my project so I can import classes? </p> <p>My models are stored in:</p> <pre><code>/Users/username/project/project/...
0
2010-02-04T16:48:56Z
2,201,627
<p>This might be a silly suggestion, but do you have a <code>__init__.py</code> file in the module you're importing? if not, then create an empty one. You're also going to need to run <code>from project import *</code> from the <code>/Users/name/project/</code> directory. ie: you'll need to start the python CLI from <c...
1
2010-02-04T17:08:02Z
[ "python", "osx", "pylons" ]
How do you execute a server-side Python script using jQuery?
2,201,561
<p>I have a very simple Python file, called python1.py, whose contents are:</p> <pre><code>f = open('C:\\Temp\\test.txt', 'w') f.write('Succeeded') f.close() </code></pre> <p>I wish to execute this from JavaScript, like so:</p> <pre><code>jQuery.ajax({ type: "POST", url: "/cgi-bin/python1.py", success: func...
7
2010-02-04T16:59:38Z
2,201,586
<p>Are you able to execute the script directly from the browser. This looks more like a webserver config issue than jquery's</p>
4
2010-02-04T17:03:34Z
[ "javascript", "jquery", "python", "ajax" ]
How do you execute a server-side Python script using jQuery?
2,201,561
<p>I have a very simple Python file, called python1.py, whose contents are:</p> <pre><code>f = open('C:\\Temp\\test.txt', 'w') f.write('Succeeded') f.close() </code></pre> <p>I wish to execute this from JavaScript, like so:</p> <pre><code>jQuery.ajax({ type: "POST", url: "/cgi-bin/python1.py", success: func...
7
2010-02-04T16:59:38Z
2,201,614
<p>You simply need to configure your web server to execute your *.py scripts, instead of serving them as plain text.</p> <p>If you are using Apache as a web server, you need to enable <a href="http://www.modpython.org/">mod_python</a> or <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a>.</p> <hr> <p><strong>E...
7
2010-02-04T17:06:39Z
[ "javascript", "jquery", "python", "ajax" ]
How do you execute a server-side Python script using jQuery?
2,201,561
<p>I have a very simple Python file, called python1.py, whose contents are:</p> <pre><code>f = open('C:\\Temp\\test.txt', 'w') f.write('Succeeded') f.close() </code></pre> <p>I wish to execute this from JavaScript, like so:</p> <pre><code>jQuery.ajax({ type: "POST", url: "/cgi-bin/python1.py", success: func...
7
2010-02-04T16:59:38Z
2,204,473
<p>If your script is that simple, you would be best off using CGI on the server side rather than mod_python or mod_wsgi as suggested by others. For details on how to set up Apache for CGI with Python and simple script examples see:</p> <p><a href="http://webpython.codepoint.net/cgi_tutorial" rel="nofollow">http://webp...
1
2010-02-05T01:20:24Z
[ "javascript", "jquery", "python", "ajax" ]
How do you execute a server-side Python script using jQuery?
2,201,561
<p>I have a very simple Python file, called python1.py, whose contents are:</p> <pre><code>f = open('C:\\Temp\\test.txt', 'w') f.write('Succeeded') f.close() </code></pre> <p>I wish to execute this from JavaScript, like so:</p> <pre><code>jQuery.ajax({ type: "POST", url: "/cgi-bin/python1.py", success: func...
7
2010-02-04T16:59:38Z
7,085,301
<p>You could also use the opensource project Pico. It's a really elegant way of calling server side Python code from client side Javascript. </p> <p>The author has provided some simple examples here <a href="https://github.com/fergalwalsh/pico/wiki/Example-1:-Hello-World">https://github.com/fergalwalsh/pico/wiki/Examp...
7
2011-08-16T21:32:58Z
[ "javascript", "jquery", "python", "ajax" ]
Need a way to count entities in GAE datastore that meet a certain condition? (over 1000 entities)
2,201,580
<p>I'm building an app on GAE that needs to report on events occurring. An event has a type and I also need to report by event type.</p> <p>For example, say there is an event A, B and C. They occur periodically at random. User logs in and creates a set of entities to which those events can be attributed. When the user...
4
2010-02-04T17:02:37Z
2,202,017
<p>My approach would be to have an aggregate model or models to keep track of event types, dates and counts. I'm not 100% how you should model this given your requirements, though.</p> <p>Then, I'd fire off deferred tasks to asynchronously update the appropriate aggregate models whenever a user does something that tr...
0
2010-02-04T18:06:26Z
[ "python", "google-app-engine", "gae-datastore" ]
Need a way to count entities in GAE datastore that meet a certain condition? (over 1000 entities)
2,201,580
<p>I'm building an app on GAE that needs to report on events occurring. An event has a type and I also need to report by event type.</p> <p>For example, say there is an event A, B and C. They occur periodically at random. User logs in and creates a set of entities to which those events can be attributed. When the user...
4
2010-02-04T17:02:37Z
2,202,059
<p>App Engine is not a relational database and you won't be able to quickly do counts on the fly like this. The best approach is to update the counts at write time, not generate them at read time.</p> <p>When generating counts, there are two general approaches that scale well with App Engine to minimize write contenti...
7
2010-02-04T18:12:27Z
[ "python", "google-app-engine", "gae-datastore" ]
Need a way to count entities in GAE datastore that meet a certain condition? (over 1000 entities)
2,201,580
<p>I'm building an app on GAE that needs to report on events occurring. An event has a type and I also need to report by event type.</p> <p>For example, say there is an event A, B and C. They occur periodically at random. User logs in and creates a set of entities to which those events can be attributed. When the user...
4
2010-02-04T17:02:37Z
2,202,358
<p>This sounds very similar to a question that I posed on StackOverflow.</p> <p><a href="http://stackoverflow.com/questions/1183102/how-to-get-the-distinct-value-of-one-of-my-models-in-google-app-engine">http://stackoverflow.com/questions/1183102/how-to-get-the-distinct-value-of-one-of-my-models-in-google-app-engine</...
-1
2010-02-04T18:59:50Z
[ "python", "google-app-engine", "gae-datastore" ]
Need a way to count entities in GAE datastore that meet a certain condition? (over 1000 entities)
2,201,580
<p>I'm building an app on GAE that needs to report on events occurring. An event has a type and I also need to report by event type.</p> <p>For example, say there is an event A, B and C. They occur periodically at random. User logs in and creates a set of entities to which those events can be attributed. When the user...
4
2010-02-04T17:02:37Z
4,058,895
<p>Would a <a href="http://groups.google.com/group/google-appengine/browse_thread/thread/80d0c2351fe2fdf8" rel="nofollow">solution</a> using cursors (like the one below) work for you? I personally use this method to count the number of entries in a scenario similar to yours, and haven't seen yet any problems with it (a...
0
2010-10-30T13:31:26Z
[ "python", "google-app-engine", "gae-datastore" ]
Need a way to count entities in GAE datastore that meet a certain condition? (over 1000 entities)
2,201,580
<p>I'm building an app on GAE that needs to report on events occurring. An event has a type and I also need to report by event type.</p> <p>For example, say there is an event A, B and C. They occur periodically at random. User logs in and creates a set of entities to which those events can be attributed. When the user...
4
2010-02-04T17:02:37Z
4,088,516
<blockquote> <p>Results of datastore count() queries and offsets for all datastore queries are no longer capped at 1000.</p> </blockquote> <p>Since Version 1.3.6 </p>
3
2010-11-03T15:11:07Z
[ "python", "google-app-engine", "gae-datastore" ]
Need a way to count entities in GAE datastore that meet a certain condition? (over 1000 entities)
2,201,580
<p>I'm building an app on GAE that needs to report on events occurring. An event has a type and I also need to report by event type.</p> <p>For example, say there is an event A, B and C. They occur periodically at random. User logs in and creates a set of entities to which those events can be attributed. When the user...
4
2010-02-04T17:02:37Z
24,156,338
<p>This post is quite old, but I would like to provide a useful reference. App Engine now offers a built-in API to access datastore statistics:</p> <p>For Python,</p> <pre><code>from google.appengine.ext.db import stats global_stat = stats.GlobalStat.all().get() print 'Total bytes stored: %d' % global_stat.bytes pri...
0
2014-06-11T06:48:18Z
[ "python", "google-app-engine", "gae-datastore" ]
How to define two fields "unique" as couple
2,201,598
<p>Is there a way to define a couple of fields as unique in Django?</p> <p>I have a table of volumes (of journals) and I don't want more then one volume number for the same journal.</p> <pre><code>class Volume(models.Model): id = models.AutoField(primary_key=True) journal_id = models.ForeignKey(Journals, db_c...
174
2010-02-04T17:04:30Z
2,201,687
<p>There is a simple solution for you called <a href="https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together">unique_together</a> which does exactly what you want.</p> <p><strong>For example:</strong></p> <pre><code>class MyModel(models.Model): field1 = models.CharField(max_length=50) field2 = ...
304
2010-02-04T17:16:34Z
[ "python", "django", "django-models" ]
Replace newlines in a Unicode string
2,201,633
<p>I am trying to replace newline characters in a unicode string and seem to be missing some magic codes.</p> <p>My particular example is that I am working on AppEngine and trying to put titles from HTML pages into a <code>db.StringProperty()</code> in my model.</p> <p>So I do something like:</p> <pre><code>link.tit...
11
2010-02-04T17:08:39Z
2,201,651
<p>It would be useful to print the <code>repr()</code> of the page_title that is seen to be multiline, but the obvious candidate would be <code>'\r'</code>.</p>
-1
2010-02-04T17:11:10Z
[ "python", "google-app-engine", "unicode" ]
Replace newlines in a Unicode string
2,201,633
<p>I am trying to replace newline characters in a unicode string and seem to be missing some magic codes.</p> <p>My particular example is that I am working on AppEngine and trying to put titles from HTML pages into a <code>db.StringProperty()</code> in my model.</p> <p>So I do something like:</p> <pre><code>link.tit...
11
2010-02-04T17:08:39Z
2,201,785
<p>Try <code>''.join(unicode(page_title, 'utf-8').splitlines())</code>. <a href="http://docs.python.org/library/stdtypes.html#str.splitlines"><code>splitlines()</code></a> should let the standard library take care of all the possible crazy Unicode line breaks, and then you just join them all back together with the empt...
14
2010-02-04T17:28:33Z
[ "python", "google-app-engine", "unicode" ]
Replace newlines in a Unicode string
2,201,633
<p>I am trying to replace newline characters in a unicode string and seem to be missing some magic codes.</p> <p>My particular example is that I am working on AppEngine and trying to put titles from HTML pages into a <code>db.StringProperty()</code> in my model.</p> <p>So I do something like:</p> <pre><code>link.tit...
11
2010-02-04T17:08:39Z
2,202,029
<p>Python uses these characters for splitting in <code>unicode.splitlines()</code>:</p> <ul> <li>U+000A LINE FEED (\n)</li> <li>U+000D CARRIAGE RETURN (\r)</li> <li>U+001C FILE SEPARATOR</li> <li>U+001D GROUP SEPARATOR</li> <li>U+001E RECORD SEPARATOR</li> <li>U+0085 NEXT LINE</li> <li>U+2028 LINE SEPARATOR</li> <li>U...
8
2010-02-04T18:08:35Z
[ "python", "google-app-engine", "unicode" ]
Problem installing OpenERP server with buildout !
2,201,806
<p>I'm trying to deploy OpenERP with a buildout and my own piece of code. In fact I would like to build a complete deployement structure allowing me to use OpenERP with custom modules and patch.</p> <p>First of all, before adding any personnal configuration, I was trying to create a buildout which will have the respon...
8
2010-02-04T17:30:44Z
2,223,642
<p>I'm not familiar with buildout, but if I were going to try building an OpenERP installer, I'd start by looking at the nice one from <a href="http://opensourceconsulting.wordpress.com/2009/09/15/openerp-all-in-one-installer-update-for-dummies/" rel="nofollow">Open Source Consulting</a>. I've used it and been pretty h...
0
2010-02-08T17:46:56Z
[ "python", "setuptools", "distutils", "buildout", "openerp" ]
Problem installing OpenERP server with buildout !
2,201,806
<p>I'm trying to deploy OpenERP with a buildout and my own piece of code. In fact I would like to build a complete deployement structure allowing me to use OpenERP with custom modules and patch.</p> <p>First of all, before adding any personnal configuration, I was trying to create a buildout which will have the respon...
8
2010-02-04T17:30:44Z
2,277,980
<p>Ok I did this recently: </p> <p>Don't try to install the egg, openerp is not really standard. </p> <p>I used this buildout snippet:</p> <pre><code># get the openerp-stuff as a distutils package [openerp-server] recipe = zerokspot.recipe.distutils urls = http://www.openerp.com/download/stable/source/openerp-serve...
2
2010-02-17T02:44:17Z
[ "python", "setuptools", "distutils", "buildout", "openerp" ]
Problem installing OpenERP server with buildout !
2,201,806
<p>I'm trying to deploy OpenERP with a buildout and my own piece of code. In fact I would like to build a complete deployement structure allowing me to use OpenERP with custom modules and patch.</p> <p>First of all, before adding any personnal configuration, I was trying to create a buildout which will have the respon...
8
2010-02-04T17:30:44Z
14,138,156
<p>Just for the record: there is a <a href="http://pypi.python.org/pypi/anybox.recipe.openerp" rel="nofollow">buildout recipe for OpenERP</a> available in Pypi.</p>
1
2013-01-03T11:35:33Z
[ "python", "setuptools", "distutils", "buildout", "openerp" ]
Capturing **vars() pattern in string formatting
2,201,867
<p>I frequently find myself using the following pattern for string formatting.</p> <pre><code>a = 3 b = 'foo' c = dict(mykey='myval') #prints a is 3, b is foo, mykey is myval print('a is {a}, b is {b}, mykey is {c[mykey]}'.format(**vars())) </code></pre> <p>That is, I often have the values I need to print in the loc...
2
2010-02-04T17:43:16Z
2,202,025
<p>You have to inspect the variables from the calling frames.</p> <p>This will get you started:</p> <pre><code>import inspect import pprint def lfmt(s): for frame in inspect.getouterframes(inspect.currentframe()): f = frame[0] print pprint.pformat(f.f_locals) return '???' if __name__ == '__m...
1
2010-02-04T18:07:54Z
[ "python", "scope", "string-formatting" ]
Capturing **vars() pattern in string formatting
2,201,867
<p>I frequently find myself using the following pattern for string formatting.</p> <pre><code>a = 3 b = 'foo' c = dict(mykey='myval') #prints a is 3, b is foo, mykey is myval print('a is {a}, b is {b}, mykey is {c[mykey]}'.format(**vars())) </code></pre> <p>That is, I often have the values I need to print in the loc...
2
2010-02-04T17:43:16Z
2,202,084
<p>Here you are:</p> <pre><code>import sys def lfmt(s): """ lfmt (local format) will format the string using variables in the caller's local namespace. """ if hasattr(sys, "tracebacklimit") and sys.tracebacklimit == 0: raise Exception, "failfailfail" try: raise ZeroDivisionEr...
0
2010-02-04T18:16:31Z
[ "python", "scope", "string-formatting" ]
Capturing **vars() pattern in string formatting
2,201,867
<p>I frequently find myself using the following pattern for string formatting.</p> <pre><code>a = 3 b = 'foo' c = dict(mykey='myval') #prints a is 3, b is foo, mykey is myval print('a is {a}, b is {b}, mykey is {c[mykey]}'.format(**vars())) </code></pre> <p>That is, I often have the values I need to print in the loc...
2
2010-02-04T17:43:16Z
2,202,119
<p><strong>Edit</strong>: In order for <code>lfmt</code> to work when called from different namespaces, you'll need the <code>inspect</code> module. Note, as <a href="http://docs.python.org/library/inspect.html#inspect.currentframe" rel="nofollow">the documentation warns</a>, the <code>inspect</code> module may not be ...
2
2010-02-04T18:22:49Z
[ "python", "scope", "string-formatting" ]
Capturing **vars() pattern in string formatting
2,201,867
<p>I frequently find myself using the following pattern for string formatting.</p> <pre><code>a = 3 b = 'foo' c = dict(mykey='myval') #prints a is 3, b is foo, mykey is myval print('a is {a}, b is {b}, mykey is {c[mykey]}'.format(**vars())) </code></pre> <p>That is, I often have the values I need to print in the loc...
2
2010-02-04T17:43:16Z
2,202,447
<p>Is it so bad to type <code>,vars</code> each time you call the function?</p> <pre><code>def lfmt(s,v): """ lfmt (local format) will format the string using variables from the dict returned by calling v()""" return s.format(**v()) print(lfmt('a is {a}, b is {b}, mykey is {c[mykey]}',vars)) </code></...
0
2010-02-04T19:10:22Z
[ "python", "scope", "string-formatting" ]
Capturing **vars() pattern in string formatting
2,201,867
<p>I frequently find myself using the following pattern for string formatting.</p> <pre><code>a = 3 b = 'foo' c = dict(mykey='myval') #prints a is 3, b is foo, mykey is myval print('a is {a}, b is {b}, mykey is {c[mykey]}'.format(**vars())) </code></pre> <p>That is, I often have the values I need to print in the loc...
2
2010-02-04T17:43:16Z
16,578,823
<p>You could also use <code>sys</code> instead of <code>inspect</code>, but I don't know if it has the same problem with different implementations as <code>inspect</code> has.</p> <pre><code>import sys def lfmt(s): caller = sys._getframe(1) return s.format(**caller.f_locals) </code></pre> <p>This is as far a...
0
2013-05-16T04:05:11Z
[ "python", "scope", "string-formatting" ]
How do I launch background jobs w/ paramiko?
2,202,228
<p>Here is my scenario: I am trying to automate some tasks using Paramiko. The tasks need to be started in this order (using the notation (host, task)): (A, 1), (B, 2), (C, 2), (A,3), (B,3) -- essentially starting servers and clients for some testing in the correct order. Further, because in the tests networking may ge...
4
2010-02-04T18:39:40Z
2,202,565
<p>I don't know anything about paramiko and it's exec_cmd, but maybe <code>bash</code>'s <code>disown</code> could help.</p> <pre><code>#!/bin/bash -l test_cmd &amp; disown test_cmd </code></pre>
-1
2010-02-04T19:32:57Z
[ "python", "screen", "paramiko", "nohup" ]
How do I launch background jobs w/ paramiko?
2,202,228
<p>Here is my scenario: I am trying to automate some tasks using Paramiko. The tasks need to be started in this order (using the notation (host, task)): (A, 1), (B, 2), (C, 2), (A,3), (B,3) -- essentially starting servers and clients for some testing in the correct order. Further, because in the tests networking may ge...
4
2010-02-04T18:39:40Z
6,691,724
<p>For this purpose I wrote a small shell script which I execute on the remote side: </p> <pre><code>#!/bin/bash # check for command line arguments if [ $# -lt 2 ]; then echo "usage: runcommand.sh EXECUTIONSTRING TASKNAME" exit -1 fi taskname=$2 execstr=$1 logfile=$taskname.log echo START $taskname ...
0
2011-07-14T10:25:04Z
[ "python", "screen", "paramiko", "nohup" ]
How do I launch background jobs w/ paramiko?
2,202,228
<p>Here is my scenario: I am trying to automate some tasks using Paramiko. The tasks need to be started in this order (using the notation (host, task)): (A, 1), (B, 2), (C, 2), (A,3), (B,3) -- essentially starting servers and clients for some testing in the correct order. Further, because in the tests networking may ge...
4
2010-02-04T18:39:40Z
8,142,947
<p>without using nohup or screen.</p> <pre><code>def command(channel, cmd): channel.exec_command(cmd + ' &gt; /dev/null 2&gt;&amp;1 &amp;') </code></pre> <p>this says "Redirect STDOUT from cmd into dev/null, then redirect STDERR back into STDOUT, which goes into /dev/null. Then push it into the background."</p> ...
3
2011-11-15T20:48:56Z
[ "python", "screen", "paramiko", "nohup" ]
Python: deferToThread XMLRPC Server - Twisted - Cherrypy?
2,202,231
<p>This question is related to others I have asked on here, mainly regarding sorting huge sets of data in memory.</p> <p>Basically this is what I want / have:</p> <p>Twisted XMLRPC server running. This server keeps several (32) instances of Foo class in memory. Each Foo class contains a list bar (which will contain...
-1
2010-02-04T18:40:16Z
2,202,414
<p>I don't know how long your processData method runs nor how you're setting up your twisted reactor. <a href="http://twistedmatrix.com/trac/browser/tags/releases/twisted-9.0.0/twisted/internet/base.py#L911" rel="nofollow">By default</a>, the twisted reactor has a thread pool of between 0 and 10 threads. You may be t...
0
2010-02-04T19:06:51Z
[ "python", "multithreading", "twisted", "cherrypy" ]
Python: deferToThread XMLRPC Server - Twisted - Cherrypy?
2,202,231
<p>This question is related to others I have asked on here, mainly regarding sorting huge sets of data in memory.</p> <p>Basically this is what I want / have:</p> <p>Twisted XMLRPC server running. This server keeps several (32) instances of Foo class in memory. Each Foo class contains a list bar (which will contain...
-1
2010-02-04T18:40:16Z
2,202,900
<p>The easiest way to get the app to be responsive is to break up the CPU-intensive processing in smaller chunks, while letting the twisted reactor run in between. For example by calling reactor.callLater(0, process_next_chunk) to advance to next chunk. Effectively implementing cooperative multitasking by yourself.</p>...
1
2010-02-04T20:23:33Z
[ "python", "multithreading", "twisted", "cherrypy" ]
Distinguishing parent model's children with Django inheritance
2,202,232
<p>Basically I have a Base class called "Program". I then have more specific program model types that use Program as a base class. For 99% of my needs, I don't care whether or not a Program is one of the specific child types. Of course there's that 1% of the time that I do want to know if it's one of the children.</p> ...
1
2010-02-04T18:40:24Z
2,202,394
<p><strong>// Update</strong></p> <p>As pointed out in the comments to this post I got the question wrong. The answer below will not solve the problem.</p> <hr> <p>Hi f4nt,</p> <p>the easiest way I can think of right now would be the following:</p> <pre><code>program = models.Program.objects.get(id=15) if program...
0
2010-02-04T19:04:34Z
[ "python", "django" ]
Distinguishing parent model's children with Django inheritance
2,202,232
<p>Basically I have a Base class called "Program". I then have more specific program model types that use Program as a base class. For 99% of my needs, I don't care whether or not a Program is one of the specific child types. Of course there's that 1% of the time that I do want to know if it's one of the children.</p> ...
1
2010-02-04T18:40:24Z
2,202,676
<p>Have you tried hasattr()? Something like this:</p> <pre><code>if hasattr(program, 'swimprogram'): # ... elif hasattr(program, 'campprogram'): # ... </code></pre> <p>If you are unsure about this approach, try it out in a simple test app first. Here are two simple models that should show if it will work fo...
4
2010-02-04T19:50:45Z
[ "python", "django" ]
Distinguishing parent model's children with Django inheritance
2,202,232
<p>Basically I have a Base class called "Program". I then have more specific program model types that use Program as a base class. For 99% of my needs, I don't care whether or not a Program is one of the specific child types. Of course there's that 1% of the time that I do want to know if it's one of the children.</p> ...
1
2010-02-04T18:40:24Z
2,203,499
<p>A couple of weeks ago, someone on the django-developers mailing list introduced a very interesting extension to Django's ORM that makes QuerySets return subclassed objects instead of objects of the parent class. You can read all about it here:</p> <p><a href="http://bserve.webhop.org/wiki/django_polymorphic" rel="n...
1
2010-02-04T21:50:59Z
[ "python", "django" ]
Implementing preg_match_all in Python
2,202,360
<p>I basically want the same functionality of <code>preg_match_all()</code>from PHP in a Python way.</p> <p>If I have a regex pattern and a string, is there a way to search the string and get back a dictionary of each occurrence of a vowel, along with its position in the string?</p> <p>Example:</p> <pre><code>s = "s...
2
2010-02-04T19:00:20Z
2,202,424
<p>Like this, for example:</p> <pre><code>import re def findall(pattern, string): res = {} for match in re.finditer(pattern, string): res[match.group(0)] = match.start() return res print findall("[aeiou]", "Test this thang") </code></pre> <p>Note that <code>re.finditer</code> only finds non-over...
0
2010-02-04T19:07:57Z
[ "php", "python", "regex" ]
Implementing preg_match_all in Python
2,202,360
<p>I basically want the same functionality of <code>preg_match_all()</code>from PHP in a Python way.</p> <p>If I have a regex pattern and a string, is there a way to search the string and get back a dictionary of each occurrence of a vowel, along with its position in the string?</p> <p>Example:</p> <pre><code>s = "s...
2
2010-02-04T19:00:20Z
2,202,438
<p>What you ask for can't be a dictionary, since it has multiple identical keys. However, you can put it in a list of tuples like this:</p> <pre><code>&gt;&gt;&gt; [(m.group(0), m.start()) for m in re.finditer('[aeiou]',s)] [('u', 1), ('e', 3), ('a', 6), ('i', 8), ('a', 11), ('i', 13), ('i', 15), ('i', 18), ('e', 20),...
5
2010-02-04T19:09:24Z
[ "php", "python", "regex" ]
Implementing preg_match_all in Python
2,202,360
<p>I basically want the same functionality of <code>preg_match_all()</code>from PHP in a Python way.</p> <p>If I have a regex pattern and a string, is there a way to search the string and get back a dictionary of each occurrence of a vowel, along with its position in the string?</p> <p>Example:</p> <pre><code>s = "s...
2
2010-02-04T19:00:20Z
2,202,541
<p>You can do this <em>faster</em> without regexp</p> <pre><code>[(x,i) for i,x in enumerate(s) if x in "aeiou"] </code></pre> <p>Here are some timings:<br> For <code>s = "supercalifragilisticexpialidocious"</code></p> <pre><code>timeit [(m.group(0), m.start()) for m in re.finditer('[aeiou]',s)] 10000 loops, best of...
6
2010-02-04T19:29:24Z
[ "php", "python", "regex" ]
Yield multiple objects at a time from an iterable object?
2,202,461
<p>How can I yield multiple items at a time from an iterable object?</p> <p>For example, with a sequence of arbitrary length, how can I iterate through the items in the sequence, in groups of X consecutive items per iteration?</p>
3
2010-02-04T19:12:19Z
2,202,485
<p>Your question is a bit vague, but check out the <code>grouper</code> recipe in the <code>itertools</code> documentation.</p> <pre><code>def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --&gt; ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) </...
6
2010-02-04T19:17:22Z
[ "python", "iterator", "grouping", "yield" ]
Yield multiple objects at a time from an iterable object?
2,202,461
<p>How can I yield multiple items at a time from an iterable object?</p> <p>For example, with a sequence of arbitrary length, how can I iterate through the items in the sequence, in groups of X consecutive items per iteration?</p>
3
2010-02-04T19:12:19Z
2,202,783
<p>Just use <a href="http://docs.python.org/library/itertools.html#itertools.groupby" rel="nofollow">itertools.groupby</a></p>
-4
2010-02-04T20:06:00Z
[ "python", "iterator", "grouping", "yield" ]
Yield multiple objects at a time from an iterable object?
2,202,461
<p>How can I yield multiple items at a time from an iterable object?</p> <p>For example, with a sequence of arbitrary length, how can I iterate through the items in the sequence, in groups of X consecutive items per iteration?</p>
3
2010-02-04T19:12:19Z
2,202,971
<p>Here's another approach that works on older version of Python that don't have izip_longest:</p> <pre><code>def grouper(n, seq): result = [] for x in seq: result.append(x) if len(result) &gt;= n: yield tuple(result) del result[:] if result: yield tuple(result) </code></pre> <p>No fille...
2
2010-02-04T20:32:21Z
[ "python", "iterator", "grouping", "yield" ]
I Keep receiving an "The MetaData is not bound to an Engine or Connection." when trying to create my SQL tables with pylons
2,202,927
<p>Here is my current code:</p> <pre><code>def init_model(engine): global t_user t_user = sa.Table("User", meta.metadata, sa.Column("id", sa.types.Integer, primary_key=True), sa.Column("name", sa.types.String(100), nullable=False), sa.Column("first_name", sa.types.String(100), nullable=False), ...
0
2010-02-04T20:26:37Z
2,204,656
<p>This issue was resolved. I didn't know that when using pylons from the CLI, I have to include the entire environment:</p> <pre><code>from paste.deploy import appconfig from pylons import config from project.config.environment import load_environment conf = appconfig('config:development.ini', relative_to='.') loa...
1
2010-02-05T02:15:17Z
[ "python", "pylons" ]
S60 camera focusing
2,202,991
<p>In my project I have to use mobile camera from my own program. I use python with S60 platform under NOKIA 6220 Classic. It has 5mp-camera.</p> <p>The problem is that photos quality are very-very low. Seems that auto-focusing doesn't work. I'd like to know maybe anyone from you made something before. I can buy new t...
0
2010-02-04T20:34:42Z
2,203,194
<p>This is just a guess. Are you maybe getting low-res images that are suitable for sending via MMS? I would look at the API.</p>
0
2010-02-04T21:02:18Z
[ "python", "camera", "s60" ]
Creating custom Field Lookups in Django
2,203,179
<p>How do you create custom <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups">field lookups</a> in Django? </p> <p>When filtering querysets, django provides a set of lookups that you can use: <code>__contains</code>, <code>__iexact</code>, <code>__in</code>, and so forth. I want to be ab...
11
2010-02-04T20:59:29Z
2,203,613
<p>Rather than creating a field lookup, best practice would be to create a manager method, that might look a little bit like this:</p> <pre><code>class PersonManger(models.Manager): def in_age_range(self, min, max): return self.filter(age__gte=min, age__lt=max) class Person(models.Model): age = #... ...
6
2010-02-04T22:08:33Z
[ "python", "django", "django-queryset" ]
Creating custom Field Lookups in Django
2,203,179
<p>How do you create custom <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups">field lookups</a> in Django? </p> <p>When filtering querysets, django provides a set of lookups that you can use: <code>__contains</code>, <code>__iexact</code>, <code>__in</code>, and so forth. I want to be ab...
11
2010-02-04T20:59:29Z
2,210,784
<p>A more flexible way to do this is to write a custom QuerySet as well as a custom manager. Working from ozan's code:</p> <pre><code>class PersonQuerySet(models.query.QuerySet): def in_age_range(self, min, max): return self.filter(age__gte=min, age__lt=max) class PersonManager(models.Manager): def ge...
12
2010-02-05T22:04:29Z
[ "python", "django", "django-queryset" ]
Creating custom Field Lookups in Django
2,203,179
<p>How do you create custom <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups">field lookups</a> in Django? </p> <p>When filtering querysets, django provides a set of lookups that you can use: <code>__contains</code>, <code>__iexact</code>, <code>__in</code>, and so forth. I want to be ab...
11
2010-02-04T20:59:29Z
8,282,171
<p>First, let me say that there is no Django machinery in place that's meant to publicly facilitate what you'd like.</p> <p><em>(Edit - actually since Django 1.7 there is: <a href="https://docs.djangoproject.com/en/1.7/howto/custom-lookups/" rel="nofollow">https://docs.djangoproject.com/en/1.7/howto/custom-lookups/</a...
6
2011-11-26T22:38:50Z
[ "python", "django", "django-queryset" ]
Creating custom Field Lookups in Django
2,203,179
<p>How do you create custom <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups">field lookups</a> in Django? </p> <p>When filtering querysets, django provides a set of lookups that you can use: <code>__contains</code>, <code>__iexact</code>, <code>__in</code>, and so forth. I want to be ab...
11
2010-02-04T20:59:29Z
29,680,477
<p>As of Django 1.7, there is a simple way to implement it. Your example is actually very similar to the one from <a href="https://docs.djangoproject.com/en/1.7/howto/custom-lookups/" rel="nofollow">the documentation</a>:</p> <pre><code>from django.db.models import Lookup class AbsoluteValueLessThan(Lookup): look...
1
2015-04-16T16:16:01Z
[ "python", "django", "django-queryset" ]
SVG to black-and-white
2,203,241
<p>I would like to be able to convert SVG documents to black and white. My try is the following Makefile script using 'sed' :</p> <pre><code>%.bw.svg: %.svg sed '/stroke:none/!s/stroke:[^;\"]*/stroke:black/g' $&lt; &gt; $@ </code></pre> <p>This works for lines etc but not for fillings. Basically if the stroke is ...
1
2010-02-04T21:07:49Z
2,203,273
<p>My first thought is that it can be dangerous to manipulate XML (in this case SVG) via <code>sed</code> etc. since it won't escape XML chars properly or respect character encodings. </p> <p>Having said that, your dataset may be sufficiently constrained and limited such that this isn't a particular problem.</p> <p>C...
0
2010-02-04T21:13:46Z
[ "python", "xslt", "sed", "awk", "svg" ]
SVG to black-and-white
2,203,241
<p>I would like to be able to convert SVG documents to black and white. My try is the following Makefile script using 'sed' :</p> <pre><code>%.bw.svg: %.svg sed '/stroke:none/!s/stroke:[^;\"]*/stroke:black/g' $&lt; &gt; $@ </code></pre> <p>This works for lines etc but not for fillings. Basically if the stroke is ...
1
2010-02-04T21:07:49Z
2,203,287
<p>I think you need a full CSS parser to do this job for all of SVG; but for "SVG as generated by some particular vector editing application", XSLT containing string editing of the style attributes (as you're doing now, except that it will properly stick to the styles and avoid e.g. &lt;text>) might be adequate.</p> <...
0
2010-02-04T21:16:17Z
[ "python", "xslt", "sed", "awk", "svg" ]
SVG to black-and-white
2,203,241
<p>I would like to be able to convert SVG documents to black and white. My try is the following Makefile script using 'sed' :</p> <pre><code>%.bw.svg: %.svg sed '/stroke:none/!s/stroke:[^;\"]*/stroke:black/g' $&lt; &gt; $@ </code></pre> <p>This works for lines etc but not for fillings. Basically if the stroke is ...
1
2010-02-04T21:07:49Z
2,203,365
<p>Two options that I would try:</p> <p>1- Inkscape appears to be able to do it - <a href="http://www.commandlinefu.com/commands/view/2009/convert-a-svg-file-to-grayscale" rel="nofollow">Inkscape Convert</a><br> 2- SVG supports a ColorProfile attribute on the SVG element that can reference an ICC Color Profile. I wou...
2
2010-02-04T21:30:18Z
[ "python", "xslt", "sed", "awk", "svg" ]
SVG to black-and-white
2,203,241
<p>I would like to be able to convert SVG documents to black and white. My try is the following Makefile script using 'sed' :</p> <pre><code>%.bw.svg: %.svg sed '/stroke:none/!s/stroke:[^;\"]*/stroke:black/g' $&lt; &gt; $@ </code></pre> <p>This works for lines etc but not for fillings. Basically if the stroke is ...
1
2010-02-04T21:07:49Z
2,649,724
<p>First of all: Don't try doing this with <code>sed</code>. Editing XML is a little more complex than that.</p> <p>You can use an SVG <a href="http://www.w3.org/TR/SVG11/filters.html" rel="nofollow">filter effect</a> on the image. The ColorMatrix filter primitive can desaturate an image.</p>
0
2010-04-15T23:44:16Z
[ "python", "xslt", "sed", "awk", "svg" ]
Loading Google App Engine app from one file for all the URLs or one file per URL for loading speed
2,203,348
<p>I have a small web app running on AppEngine and have all my URL processing in one file and the other processing done in another file that is imported at the top of the main python.</p> <p>e.g.</p> <pre><code>import wsgiref.handlers from wsgiref.handlers import format_date_time import logging import os import cgi ...
0
2010-02-04T21:27:26Z
2,204,211
<p>There's no need to split your handlers into separate files. However, if you're importing something that's going to use a lot of CPU when it's imported and won't be used by many of your handlers, it's best to move your imports inside your handler classes so you can take advantage of lazy loading.</p>
1
2010-02-05T00:15:02Z
[ "python", "performance", "google-app-engine" ]
Python: How to retrieve class information from a 'frame' object?
2,203,424
<p>Is it possible to retrieve any class information from a frame object? I know how to get the file (frame.f_code.co_filename), function (frame.f_code.co_name) and line number (frame.f_lineno), but would like to be able to also get the name of the class of the active object instance of the frame (or None if not in an i...
10
2010-02-04T21:38:09Z
2,220,759
<p>I don't believe that, at the frame object level, there's any way to find the actual python function object that has been called.</p> <p>However, if your code rely on the common convention : naming the instance parameter of a method <code>self</code>, then you could do the following :</p> <pre><code>def get_class_f...
11
2010-02-08T10:07:51Z
[ "python", "introspection" ]
Python: How to retrieve class information from a 'frame' object?
2,203,424
<p>Is it possible to retrieve any class information from a frame object? I know how to get the file (frame.f_code.co_filename), function (frame.f_code.co_name) and line number (frame.f_lineno), but would like to be able to also get the name of the class of the active object instance of the frame (or None if not in an i...
10
2010-02-04T21:38:09Z
2,544,639
<p>This is a bit shorter, but does about the same. Returns None if class name not available.</p> <pre><code>def get_class_name(): f = sys._getframe(1) try: class_name = f.f_locals['self'].__class__.__name__ except KeyError: class_name = None return class_name </code></pre>
4
2010-03-30T11:14:08Z
[ "python", "introspection" ]
Python: How to retrieve class information from a 'frame' object?
2,203,424
<p>Is it possible to retrieve any class information from a frame object? I know how to get the file (frame.f_code.co_filename), function (frame.f_code.co_name) and line number (frame.f_lineno), but would like to be able to also get the name of the class of the active object instance of the frame (or None if not in an i...
10
2010-02-04T21:38:09Z
15,704,609
<p>I just came across this post as I was faced with the same problem. I did not consider the 'self' method an acceptable solution, however, for all the reasons already listed.</p> <p>The following code demonstrates a different approach: given a frame object it searches the globals for an object with matching member na...
1
2013-03-29T13:49:04Z
[ "python", "introspection" ]
Python: How to retrieve class information from a 'frame' object?
2,203,424
<p>Is it possible to retrieve any class information from a frame object? I know how to get the file (frame.f_code.co_filename), function (frame.f_code.co_name) and line number (frame.f_lineno), but would like to be able to also get the name of the class of the active object instance of the frame (or None if not in an i...
10
2010-02-04T21:38:09Z
39,799,473
<p>If a method is a class method, the class will be the first argument. This prints out the type of the first arg if present for each calling stack frame:</p> <pre><code> def some_method(self): for f in inspect.getouterframes(inspect.currentframe() ): args, _,_, local_dict = inspect.getargvalues...
0
2016-09-30T20:18:51Z
[ "python", "introspection" ]
Python: How do you call a method when you only have the string name of the method?
2,203,438
<p>This is for use in a JSON API. I don't want to have:</p> <pre><code>if method_str == 'method_1': method_1() if method_str == 'method_2': method_2() </code></pre> <p>For obvious reasons this is not optimal. How would I use map strings to methods like this in a reusable way (also note that I need to pass in...
9
2010-02-04T21:39:16Z
2,203,465
<p>Assuming the functions are all global variables (they are, unless they were defined inside another functions), they can be accessed with the <code>globals()</code> function. <code>globals()</code> returns a dictionary of all global variables, including functions.</p> <p>For example:</p> <pre><code>$ python Python ...
1
2010-02-04T21:43:07Z
[ "python", "json", "api", "serialization" ]
Python: How do you call a method when you only have the string name of the method?
2,203,438
<p>This is for use in a JSON API. I don't want to have:</p> <pre><code>if method_str == 'method_1': method_1() if method_str == 'method_2': method_2() </code></pre> <p>For obvious reasons this is not optimal. How would I use map strings to methods like this in a reusable way (also note that I need to pass in...
9
2010-02-04T21:39:16Z
2,203,479
<p>For methods of instances, use <code>getattr</code></p> <pre><code>&gt;&gt;&gt; class MyClass(object): ... def sayhello(self): ... print "Hello World!" ... &gt;&gt;&gt; m=MyClass() &gt;&gt;&gt; getattr(m,"sayhello")() Hello World! &gt;&gt;&gt; </code></pre> <p>For functions you can look in the global dict</p> ...
22
2010-02-04T21:46:08Z
[ "python", "json", "api", "serialization" ]
Python: How do you call a method when you only have the string name of the method?
2,203,438
<p>This is for use in a JSON API. I don't want to have:</p> <pre><code>if method_str == 'method_1': method_1() if method_str == 'method_2': method_2() </code></pre> <p>For obvious reasons this is not optimal. How would I use map strings to methods like this in a reusable way (also note that I need to pass in...
9
2010-02-04T21:39:16Z
2,203,480
<p>Use getattr. For example:</p> <pre><code>class Test(object): def say_hello(self): print 'Hell no, world!!111' def test(self): getattr(self, 'say_hello')() </code></pre>
6
2010-02-04T21:46:23Z
[ "python", "json", "api", "serialization" ]
Python: How do you call a method when you only have the string name of the method?
2,203,438
<p>This is for use in a JSON API. I don't want to have:</p> <pre><code>if method_str == 'method_1': method_1() if method_str == 'method_2': method_2() </code></pre> <p>For obvious reasons this is not optimal. How would I use map strings to methods like this in a reusable way (also note that I need to pass in...
9
2010-02-04T21:39:16Z
2,203,482
<p>The clean, safe way to do this is to make a dict mapping names to functions. If these are actually methods, the best way is still to make such a dict, though <code>getattr</code> is also available. Using <code>globals</code> or <code>eval</code> is unsafe and dirty.</p>
6
2010-02-04T21:46:53Z
[ "python", "json", "api", "serialization" ]
Code Changes While Keeping Large Objects In Memory in Python
2,203,492
<p>I have an application that starts by loading a large pickled trie (173M) from disk and then uses it to do some processing. I'm making frequent changes to the processing part, which is inconvenient because loading the trie takes 15 minutes or so. I'm looking for a way to eliminate the repeated loading during testin...
2
2010-02-04T21:49:43Z
2,203,524
<p>You could try using Pythons built-in <a href="http://docs.python.org/library/functions.html#reload" rel="nofollow"><code>reload</code></a> method or the <a href="http://code.google.com/p/livecoding/" rel="nofollow">livecoding</a> project.</p>
2
2010-02-04T21:54:01Z
[ "python" ]
Code Changes While Keeping Large Objects In Memory in Python
2,203,492
<p>I have an application that starts by loading a large pickled trie (173M) from disk and then uses it to do some processing. I'm making frequent changes to the processing part, which is inconvenient because loading the trie takes 15 minutes or so. I'm looking for a way to eliminate the repeated loading during testin...
2
2010-02-04T21:49:43Z
2,203,707
<p>The usual problem with <code>reload</code> is that instances stay bound to the old version of the class. If you are not keeping old instances around, <code>reload</code> is simple and works very well.</p>
0
2010-02-04T22:26:39Z
[ "python" ]
Error "Could not locate a bind configured on mapper" for SQLAlchemy and pylons
2,203,496
<p>I'm not sure what I'm doing wrong here to warrant this message. Any help with my configuration would be appreciated.</p> <pre><code>"""The application's model objects""" import sqlalchemy as sa from sqlalchemy import orm from project.model import meta def now(): return datetime.datetime.now() def init_model...
3
2010-02-04T21:50:26Z
2,204,650
<p>This issue was resolved. I didn't know that when using pylons from the CLI, I have to include the entire environment:</p> <pre><code>from paste.deploy import appconfig from pylons import config from project.config.environment import load_environment conf = appconfig('config:development.ini', relative_to='.') loa...
3
2010-02-05T02:13:26Z
[ "python", "sqlalchemy", "pylons" ]
Translate a python dict into a Solr query string
2,203,514
<p>I'm just getting started with Python, and I'm stuck on the syntax that I need to convert a set of request.POST parameters to Solr's query syntax. </p> <p>The use case is a form defined like this:</p> <pre><code>class SearchForm(forms.Form): text = forms.CharField() metadata = forms.CharField() figures ...
0
2010-02-04T21:53:08Z
2,203,567
<p>Isn't <code>u'\u003A'</code> simply the same as <code>u':'</code>, which is escaped in URLs as <code>%3A</code> ?</p> <pre><code>qstring = '+AND+'.join( [ u'%s%%3A%s'%(f,v) for f,v in request.POST.iteritems() if f] ) </code></pre>
0
2010-02-04T22:01:35Z
[ "python", "django", "solr" ]
Translate a python dict into a Solr query string
2,203,514
<p>I'm just getting started with Python, and I'm stuck on the syntax that I need to convert a set of request.POST parameters to Solr's query syntax. </p> <p>The use case is a form defined like this:</p> <pre><code>class SearchForm(forms.Form): text = forms.CharField() metadata = forms.CharField() figures ...
0
2010-02-04T21:53:08Z
2,204,630
<p>I would recommend creating a function in the form to handle this rather than in the view. So after you call form.isValid() to ensure the data is acceptable. You can invoke a form.generateSolrQuery() (or whatever name you would like).</p> <pre><code>class SearchForm(forms.Form): text = forms.CharField() metada...
1
2010-02-05T02:07:10Z
[ "python", "django", "solr" ]
Translate a python dict into a Solr query string
2,203,514
<p>I'm just getting started with Python, and I'm stuck on the syntax that I need to convert a set of request.POST parameters to Solr's query syntax. </p> <p>The use case is a form defined like this:</p> <pre><code>class SearchForm(forms.Form): text = forms.CharField() metadata = forms.CharField() figures ...
0
2010-02-04T21:53:08Z
2,205,582
<p>Use <a href="http://haystacksearch.org/" rel="nofollow">django-haystack</a>. It takes care of all the interfacing with Solr - both indexing and querying.</p>
0
2010-02-05T07:15:20Z
[ "python", "django", "solr" ]
Is this a bug in Django or what? Logging out of the Django Authentication system...will remove all sessiosn?
2,203,604
<p>I'm using sessions across my application. And using logins.</p> <p>When I do a simple:</p> <pre><code>#log out the user. logout(request) </code></pre> <p>...the request.sessions get erased.</p> <p>What is this??!</p>
1
2010-02-04T22:07:06Z
2,203,631
<p>I believe the correct syntax is:</p> <pre><code>logout(request.user) </code></pre>
2
2010-02-04T22:12:57Z
[ "python", "django", "session" ]
Is this a bug in Django or what? Logging out of the Django Authentication system...will remove all sessiosn?
2,203,604
<p>I'm using sessions across my application. And using logins.</p> <p>When I do a simple:</p> <pre><code>#log out the user. logout(request) </code></pre> <p>...the request.sessions get erased.</p> <p>What is this??!</p>
1
2010-02-04T22:07:06Z
2,203,731
<p>If by <code>request.sessions</code> you mean <code>request.session</code>, then it's a documented feature:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.logout" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.logout</a></p>
4
2010-02-04T22:30:28Z
[ "python", "django", "session" ]
Efficient way to convert numpy record array to a list of dictionary
2,203,673
<p>How do I convert the numpy record array below:</p> <pre><code>recs = [('Bill', 31, 260.0), ('Fred', 15, 145.0)] r = rec.fromrecords(recs, names='name, age, weight', formats='S30, i2, f4') </code></pre> <p>to a list of dictionary like:</p> <pre><code>[{'name': 'Bill', 'age': 31, 'weight': 260.0}, 'name': 'Fred', ...
7
2010-02-04T22:21:15Z
2,204,485
<p>I am not sure there is built-in function for that or not, but following could do the work.</p> <pre><code>&gt;&gt;&gt; [dict(zip(r.dtype.names,x)) for x in r] [{'age': 31, 'name': 'Bill', 'weight': 260.0}, {'age': 15, 'name': 'Fred', 'weight': 145.0}] </code></pre>
12
2010-02-05T01:26:43Z
[ "python", "numpy" ]
Efficient way to convert numpy record array to a list of dictionary
2,203,673
<p>How do I convert the numpy record array below:</p> <pre><code>recs = [('Bill', 31, 260.0), ('Fred', 15, 145.0)] r = rec.fromrecords(recs, names='name, age, weight', formats='S30, i2, f4') </code></pre> <p>to a list of dictionary like:</p> <pre><code>[{'name': 'Bill', 'age': 31, 'weight': 260.0}, 'name': 'Fred', ...
7
2010-02-04T22:21:15Z
2,204,590
<p>Answered at <a href="http://mail.scipy.org/pipermail/numpy-discussion/2010-February/048288.html" rel="nofollow">Numpy-discussion</a> by Robert Kern</p> <p><hr> Copy of concluding email from that discussion:</p> <blockquote> <blockquote> <p>How do I convert the numpy record array below: recs = [('Bill', 3...
-1
2010-02-05T01:55:44Z
[ "python", "numpy" ]
Efficient way to convert numpy record array to a list of dictionary
2,203,673
<p>How do I convert the numpy record array below:</p> <pre><code>recs = [('Bill', 31, 260.0), ('Fred', 15, 145.0)] r = rec.fromrecords(recs, names='name, age, weight', formats='S30, i2, f4') </code></pre> <p>to a list of dictionary like:</p> <pre><code>[{'name': 'Bill', 'age': 31, 'weight': 260.0}, 'name': 'Fred', ...
7
2010-02-04T22:21:15Z
23,500,570
<p>This depends on the final structure required. This example shows a numpy recarray composed of several 1D subsets. To have a python dictionary instead, a possible conversion is:</p> <pre><code>import numpy as np a = np.rec.array([np.array([1,3,6]), np.array([3.4,4.2,-1.2])], names=['t', 'x']) b = {name:a[name] for...
0
2014-05-06T16:54:38Z
[ "python", "numpy" ]
How can I optimize multiple nested SELECTs in SQLite (w/Python)?
2,203,709
<p>I'm building a CGI script that polls a SQLite database and builds a table of statistics. The source database table is described below, as is the chunk of pertinent code. Everything works (functionally), but the CGI itself is very slow as I have multiple nested <code>SELECT COUNT(id)</code> calls. I figure my best sh...
4
2010-02-04T22:26:47Z
2,204,258
<p>For starters, create an index:</p> <p>CREATE INDEX messages_sender_by_day ON messages (sender, day);</p> <p>(You probably don't need to include "hour" in there.)</p> <p>If that doesn't help or you've already tried it, then please fix up your question a bit: give us some code to generate test data and SQL for all ...
1
2010-02-05T00:25:41Z
[ "python", "perl", "optimization", "sqlite", "query-optimization" ]
How can I optimize multiple nested SELECTs in SQLite (w/Python)?
2,203,709
<p>I'm building a CGI script that polls a SQLite database and builds a table of statistics. The source database table is described below, as is the chunk of pertinent code. Everything works (functionally), but the CGI itself is very slow as I have multiple nested <code>SELECT COUNT(id)</code> calls. I figure my best sh...
4
2010-02-04T22:26:47Z
2,204,284
<p>first of all you can use the group by clause:</p> <pre><code>select count(*), sender from messages group by sender; </code></pre> <p>and with this you execute one query for all senders instead of on query for each sender. Another possibility could be:</p> <pre><code>select count(*), sender, day, hour from mes...
3
2010-02-05T00:33:24Z
[ "python", "perl", "optimization", "sqlite", "query-optimization" ]
Possible to use GCJ to produce library callable from Python?
2,203,728
<p>Is it possible to compile a library intended for Java with GCJ, get a dll and call from python ctypes?</p> <p>I'm interested in toxilibs for now, but if anybody knows a toy example that would be great !</p>
4
2010-02-04T22:30:24Z
2,217,719
<p>If you want Java-Python hooks, you'd be far better off using Jython and then calling across the boundary that way. </p> <p>However, yes, it's possible to call an external library from Java; but you don't need GCJ to do that. Rather, you can just bring up a JVM instance inside your Python runtime and then invoke you...
1
2010-02-07T18:18:11Z
[ "java", "python", "ctypes", "gcj" ]
Python: Problem with metaclasses in conjunction multiple inheritance
2,203,947
<p>i have two questions converning metaclasses and multiple inheritance. The first is: Why do i get a TypeError for the class <code>Derived</code> but not for <code>Derived2</code>?</p> <pre><code>class Metaclass(type): pass class Klass(object): __metaclass__ = Metaclass #class Derived(object, Klass): pass # ...
3
2010-02-04T23:13:45Z
2,203,997
<p>For the first question, have a look at <a href="http://www.python.org/download/releases/2.3/mro/" rel="nofollow">the description of MRO in python</a> - specifically, the "bad Method Resolution order" section. Essentially, it's to do with the fact that python doesn't know whether to use object or Klass's methods. (It...
3
2010-02-04T23:26:02Z
[ "python", "multiple-inheritance", "metaclass" ]
Python: Problem with metaclasses in conjunction multiple inheritance
2,203,947
<p>i have two questions converning metaclasses and multiple inheritance. The first is: Why do i get a TypeError for the class <code>Derived</code> but not for <code>Derived2</code>?</p> <pre><code>class Metaclass(type): pass class Klass(object): __metaclass__ = Metaclass #class Derived(object, Klass): pass # ...
3
2010-02-04T23:13:45Z
2,204,007
<p>For the second question, you need to pass self to <code>__new__</code> like this:</p> <pre><code>class Metaclass(type): def __new__(self, name, bases, dict_): return super(Metaclass, self).__new__(self, name, bases, dict_) class Klass(object): __metaclass__ = Metaclass </code></pre> <p>I can't re...
0
2010-02-04T23:28:44Z
[ "python", "multiple-inheritance", "metaclass" ]
Python: Problem with metaclasses in conjunction multiple inheritance
2,203,947
<p>i have two questions converning metaclasses and multiple inheritance. The first is: Why do i get a TypeError for the class <code>Derived</code> but not for <code>Derived2</code>?</p> <pre><code>class Metaclass(type): pass class Klass(object): __metaclass__ = Metaclass #class Derived(object, Klass): pass # ...
3
2010-02-04T23:13:45Z
2,204,741
<p>The second question has already been well answered twice, though <code>__new__</code> is actually a staticmethod, not a classmethod as erroneously claimed in a comment...:</p> <pre><code>&gt;&gt;&gt; class sic(object): ... def __new__(cls, *x): return object.__new__(cls, *x) ... &gt;&gt;&gt; type(sic.__dict__['_...
6
2010-02-05T02:53:12Z
[ "python", "multiple-inheritance", "metaclass" ]
Python: Problem with metaclasses in conjunction multiple inheritance
2,203,947
<p>i have two questions converning metaclasses and multiple inheritance. The first is: Why do i get a TypeError for the class <code>Derived</code> but not for <code>Derived2</code>?</p> <pre><code>class Metaclass(type): pass class Klass(object): __metaclass__ = Metaclass #class Derived(object, Klass): pass # ...
3
2010-02-04T23:13:45Z
2,205,604
<p>Why would you do?</p> <pre><code>class Derived(object, Klass): </code></pre> <p>Klass already derives from object. </p> <pre><code>class Derived(Klass): </code></pre> <p>Is the reasonable thing here.</p>
0
2010-02-05T07:23:01Z
[ "python", "multiple-inheritance", "metaclass" ]
Python win32com: Excel set chart type to Line
2,204,069
<p>This VBA macro works:</p> <pre><code>Sub Draw_Graph() Columns("A:B").Select ActiveSheet.Shapes.AddChart.Select ActiveChart.SetSourceData Source:=ActiveSheet.Range("$A:$B") ActiveChart.ChartType = xlLine End Sub </code></pre> <p>This Python (near) Equivalent almost works:</p> <pre><code>from win32c...
1
2010-02-04T23:41:16Z
2,204,159
<p>Needed to run the 'makepy.py' to get it to work.</p> <p><a href="http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/QuickStartClientCom.html#UsingComConstants" rel="nofollow">http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/QuickStartClientCom.html#UsingComConstan...
1
2010-02-05T00:02:57Z
[ "python", "excel", "charts", "python-2.6", "win32com" ]
Minimal linear regression program
2,204,087
<p>I am running some calculations in an external machine and at the end I get X, Y pairs. I want to apply linear regression and obtain A, B, and R2. In this machine I can not install anything (it runs Linux) and has basic stuff installed on it, python, bash (of course), etc.</p> <p>I wonder what would be the best appr...
2
2010-02-04T23:45:24Z
2,204,122
<p>How about extracting the coeffs into a file, import to another machine and then use Excel/Matlab/whatever other program that does this for you?</p>
1
2010-02-04T23:53:00Z
[ "c++", "python", "bash", "linear-algebra" ]
Minimal linear regression program
2,204,087
<p>I am running some calculations in an external machine and at the end I get X, Y pairs. I want to apply linear regression and obtain A, B, and R2. In this machine I can not install anything (it runs Linux) and has basic stuff installed on it, python, bash (of course), etc.</p> <p>I wonder what would be the best appr...
2
2010-02-04T23:45:24Z
2,204,124
<p>For a single, simple, known function (as in your case: a line) it is not hard to simply code a basic least square routine from scratch (but does require some attention to detail). It is a very common assignment in introductory numeric analysis classes.</p> <p>So, look up least squares on wikipedia or mathworld or i...
3
2010-02-04T23:53:46Z
[ "c++", "python", "bash", "linear-algebra" ]
Why am I getting an error about my class defining __slots__ when trying to pickle an object?
2,204,155
<p>I'm trying to pickle an object of a (new-style) class I defined. But I'm getting the following error:</p> <pre><code>&gt;&gt;&gt; with open('temp/connection.pickle','w') as f: ... pickle.dump(c,f) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; File "/usr/lib/python2.5...
20
2010-02-05T00:00:58Z
2,204,168
<p>From <a href="http://www.python.org/dev/peps/pep-0307/" rel="nofollow">PEP 307</a>:</p> <blockquote> <p>The <code>__getstate__</code> method should return a picklable value representing the object's state without referencing the object itself. If no <code>__getstate__</code> method exists, a defa...
0
2010-02-05T00:04:26Z
[ "python", "pickle", "slots" ]
Why am I getting an error about my class defining __slots__ when trying to pickle an object?
2,204,155
<p>I'm trying to pickle an object of a (new-style) class I defined. But I'm getting the following error:</p> <pre><code>&gt;&gt;&gt; with open('temp/connection.pickle','w') as f: ... pickle.dump(c,f) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; File "/usr/lib/python2.5...
20
2010-02-05T00:00:58Z
2,204,177
<p>Perhaps an attribute of your instance is using <code>__slots__</code></p> <p>For example, <code>socket</code> has <code>__slots__</code> so it can't be pickled</p> <p>You need to identify which attribute is causing the error and write your own <code>__getstate__</code> and <code>__setstate__</code> to ignore that ...
6
2010-02-05T00:06:34Z
[ "python", "pickle", "slots" ]
Why am I getting an error about my class defining __slots__ when trying to pickle an object?
2,204,155
<p>I'm trying to pickle an object of a (new-style) class I defined. But I'm getting the following error:</p> <pre><code>&gt;&gt;&gt; with open('temp/connection.pickle','w') as f: ... pickle.dump(c,f) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; File "/usr/lib/python2.5...
20
2010-02-05T00:00:58Z
2,204,702
<p>The class defining <a href="https://docs.python.org/2/reference/datamodel.html#__slots__" rel="nofollow"><code>__slots__</code></a> (and not <a href="https://docs.python.org/2/library/pickle.html#object.__getstate__" rel="nofollow"><code>__getstate__</code></a>) can be either an ancestor class of yours, or a class (...
20
2010-02-05T02:35:10Z
[ "python", "pickle", "slots" ]
Using a PFX Certificate to connect to an HTTP site
2,204,252
<p>Here's the scenario: I need to connect to a web site to retrieve electronic lab results formatted in XML. In order to connect, I need to use a digital certificate.</p> <p>I've been able to get a version of this working in Perl. It looks like this:</p> <pre><code>#!/usr/bin/env perl use strict; use WWW::Mechaniz...
0
2010-02-05T00:24:34Z
2,204,339
<p>I have no idea what is going on with your perl issues. However, mechanize for Python can be found <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">here</a>.</p>
0
2010-02-05T00:45:51Z
[ "python", "perl", "ssl", "certificate" ]
Everything is ok, but my 127.0.0.1:8000 can't show anything, why ? I used django-sphinx
2,204,686
<pre><code>from djangosphinx.models import SphinxSearch def xx(request): queryset =File.search.query('test') #return HttpResponse(queryset)#&lt;------1 return render_to_response('a.html',{'a':queryset})#&lt;--------2 </code></pre> <p>and </p> <pre><code>class File(models.Model): name = models.CharFiel...
0
2010-02-05T02:26:35Z
8,601,772
<p>Since you are not giving a lot of info, I will make a educated guess. You probably didn't build you search index. Try building it before quering, sphynx search in the sindex, not in the DB.</p>
0
2011-12-22T09:25:18Z
[ "python", "django", "sphinx", "django-sphinx" ]
setting help_text for each choice in a RadioSelect
2,204,696
<p>I can set the help_text attribute on any form field, but is it possible to set help_text on the choices used for a RadioSelect()?</p> <p>I'd looking for a clean way to show some help information under each radio button.</p> <p>Below is the code for the model and the form, I can render the name attribute in a templ...
4
2010-02-05T02:31:52Z
2,204,814
<p>Assuming you're using <code>RadioSelect</code> as a widget for <code>forms.ChoiceField</code>, you can do something like:</p> <pre><code>choices = (('1', 'First help_text here'), ('2', 'Second help_text here'), ('3', 'Third help_text here'), ) class MyForm(forms.Form): ... c...
0
2010-02-05T03:18:41Z
[ "python", "django" ]
setting help_text for each choice in a RadioSelect
2,204,696
<p>I can set the help_text attribute on any form field, but is it possible to set help_text on the choices used for a RadioSelect()?</p> <p>I'd looking for a clean way to show some help information under each radio button.</p> <p>Below is the code for the model and the form, I can render the name attribute in a templ...
4
2010-02-05T02:31:52Z
4,184,157
<p><strong>@Rishabh is correct</strong> but I'll elaborate further as, at first glance, it doesn't appear to be the solution, although it is; or, at least, it can be kludged to get a useful effect without having to dive too deep into django forms.</p> <p>The second element of the tuple is presented inside the "label" ...
5
2010-11-15T12:08:16Z
[ "python", "django" ]
Transform items from iterable with a sequence of unary functions
2,204,733
<p>I frequently find myself needing to apply a sequence of unary functions to a sequence of of the same length. My first thought is to go with <code>map()</code>, however this only takes a single function to be applied to all items in the sequence.</p> <p>In the following code for example, I wish to apply <code>str.up...
0
2010-02-05T02:50:48Z
2,204,754
<pre><code>&gt;&gt;&gt; s="pid,5 user,8 program,28 dev,10 sent,9 received,15".split() &gt;&gt;&gt; [ ( m.upper(),int(n)) for m, n in [i.split(",") for i in s ] ] [('PID', 5), ('USER', 8), ('PROGRAM', 28), ('DEV', 10), ('SENT', 9), ('RECEIVED', 15)] </code></pre>
1
2010-02-05T02:56:03Z
[ "python", "map", "transform", "predicate", "unary-function" ]
Transform items from iterable with a sequence of unary functions
2,204,733
<p>I frequently find myself needing to apply a sequence of unary functions to a sequence of of the same length. My first thought is to go with <code>map()</code>, however this only takes a single function to be applied to all items in the sequence.</p> <p>In the following code for example, I wish to apply <code>str.up...
0
2010-02-05T02:50:48Z
2,204,761
<p>What about...:</p> <pre><code>def transform(functions, arguments): return [f(a) for f, a in zip(functions, arguments)] </code></pre>
3
2010-02-05T02:57:35Z
[ "python", "map", "transform", "predicate", "unary-function" ]
Transform items from iterable with a sequence of unary functions
2,204,733
<p>I frequently find myself needing to apply a sequence of unary functions to a sequence of of the same length. My first thought is to go with <code>map()</code>, however this only takes a single function to be applied to all items in the sequence.</p> <p>In the following code for example, I wish to apply <code>str.up...
0
2010-02-05T02:50:48Z
2,204,801
<p>I'm currently using this:</p> <pre><code>def transform(unaries, iterable): return map(lambda a, b: a(b), unaries, iterable) </code></pre>
1
2010-02-05T03:15:33Z
[ "python", "map", "transform", "predicate", "unary-function" ]
PIP install a Python Package without a setup.py file?
2,204,811
<p>I'm trying to figure out how I can install a python package that doesn't have a <code>setup.py</code> file with <a href="http://pip.openplans.org/">pip</a>. (package in question is <a href="http://code.google.com/p/django-google-analytics/">http://code.google.com/p/django-google-analytics/</a>)</p> <p>Normally I wo...
12
2010-02-05T03:18:27Z
2,205,586
<p>You can't. PIP installs Python packages. That's not a Python package. I've heard that the Django community in general doesn't make much packages, which makes things like what you are trying to do tricky. But that could be wrong.</p> <p>If you want to freeze your environment you might want to look into <a href="http...
6
2010-02-05T07:16:49Z
[ "python", "setuptools", "easy-install", "pip" ]
PIP install a Python Package without a setup.py file?
2,204,811
<p>I'm trying to figure out how I can install a python package that doesn't have a <code>setup.py</code> file with <a href="http://pip.openplans.org/">pip</a>. (package in question is <a href="http://code.google.com/p/django-google-analytics/">http://code.google.com/p/django-google-analytics/</a>)</p> <p>Normally I wo...
12
2010-02-05T03:18:27Z
2,210,050
<p>Fork the repo and add a working setup.py. Then send a pull request to the author.</p> <p>Oh, it's on Google Code. Well then, file a bug and post a patch.</p> <p>If the author refuses to make their code into an installable Python distribution (never happened to me), just host your fork somewhere and put that in you...
15
2010-02-05T20:04:15Z
[ "python", "setuptools", "easy-install", "pip" ]
Write timestamp to file every hour in Python
2,204,856
<p>I have a python script that is constantly grabbing data from Twitter and writing the messages to a file. The question that I have is every hour, I want my program to write the current time to the file. Below is my script. Currently, it gets into the timestamp function and just keeps printing out the time every 10 se...
3
2010-02-05T03:29:12Z
2,204,884
<p>your code</p> <pre><code>sc.enter(10, 1, t.timestamp, (sc,) </code></pre> <p>is asking to be scheduled again in 10 seconds. If you want to be scheduled once an hour,</p> <pre><code>sc.enter(3600, 1, t.timestamp, (sc,) </code></pre> <p>seems better, since an hour is 3600 seconds, not 10!</p> <p>Also, the line</...
4
2010-02-05T03:36:13Z
[ "python", "file-io" ]
Restricting RSS elements by date with feedparser. [Python]
2,204,858
<p>I iterate a RSS feed like so where _file is the feed</p> <pre><code>d = feedparser.parse(_file) for element in d.entries: print repr(element.date) </code></pre> <p>The date output comes out like so</p> <pre><code>u'Thu, 16 Jul 2009 15:18:22 EDT' </code></pre> <p>I cant seem to understand how to actually qua...
3
2010-02-05T03:29:42Z
2,204,949
<p>one way</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; t=time.strptime("Thu, 16 Jul 2009 15:18:22 EDT","%a, %d %b %Y %H:%M:%S %Z") &gt;&gt;&gt; sevendays=86400*7 &gt;&gt;&gt; current=time.strftime ("%s",time.localtime()) &gt;&gt;&gt; if int(current) - time.mktime(t) &gt; sevendays: print "more than 7 ...
1
2010-02-05T03:56:17Z
[ "python", "feedparser" ]
Restricting RSS elements by date with feedparser. [Python]
2,204,858
<p>I iterate a RSS feed like so where _file is the feed</p> <pre><code>d = feedparser.parse(_file) for element in d.entries: print repr(element.date) </code></pre> <p>The date output comes out like so</p> <pre><code>u'Thu, 16 Jul 2009 15:18:22 EDT' </code></pre> <p>I cant seem to understand how to actually qua...
3
2010-02-05T03:29:42Z
2,205,094
<p>If you install the <a href="http://labix.org/python-dateutil" rel="nofollow">dateutil</a> module:</p> <pre><code>import dateutil.parser as dp import dateutil.tz as dtz import datetime date_string=u'Thu, 16 Jul 2009 15:18:22 EDT' adatetime=dp.parse(date_string) print(adatetime) # 2009-07-16 15:18:22-04:00 now=dat...
0
2010-02-05T04:41:50Z
[ "python", "feedparser" ]