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
Is there a way to check whether function output is assigned to a variable in Python?
813,882
<p>In Python, I'd like to write a function that would pretty-print its results to the console if called by itself (mostly for use interactively or for debugging). For the purpose of this question, let's say it checks the status of something. If I call just</p> <pre><code>check_status() </code></pre> <p>I would like to see something like:</p> <pre><code>Pretty printer status check 0.02v NOTE: This is so totally not written for giant robots ================================= System operational: ... ok Time to ion canon charge is 9m 21s Booster rocket in AFTERBURNER state Range check is optimal Rocket fuel is 10h 19m 40s to depletion Beer served is type WICKSE LAGER, chill optimal Suggested catchphrase is 01_FIGHTING_SPIRIT_GOGOGO Virtual ... on </code></pre> <p>However, I would also like it to pass the output as a list if I call it in the context of a variable assignment:</p> <pre><code>not_robot_stat = check_status() print not_robot_stat &gt;&gt;&gt; {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5, 'range_est_sigma': 0.023, 'fuel_est': 32557154, 'beer_type': 31007, 'beer_temp': 2, 'catchphrase_suggestion': 1023, 'virtual_on': 'hell yes'} </code></pre> <p>So... is there a way to dynamically know, within a function, whether its output is being assigned? I'd like to be able to do this without resorting param passing, or writing another function dedicated for this. I've Googled for a bit, and from what little I can tell it looks like I'd have to resort to playing wth the bytecode. Is that really necessary?</p>
2
2009-05-02T01:08:18Z
814,177
<p>Even if there is a way to do this, it's a bad idea. Imagine trying to debug something that behaves differently depending on the context it's called from. Now try to imagine that it's six months from now and this is buried in part of some system that's too big to keep in your head all at once.</p> <p>Keep it simple. Explicit is better than implicit. Just make a pretty-print function (or use the pprint module) and call that on the result. In an interactive Pythn session you can use _ to get the value of the last expression.</p>
1
2009-05-02T05:01:11Z
[ "python", "functional-programming", "bytecode" ]
If I want to use a pylons app with Apache, should I use mod_wsgi or proxy to paste?
813,943
<p>Or should I be using a totally different server?</p>
4
2009-05-02T01:37:39Z
814,005
<p>Nginx with mod_wsgi requires the use of a non-blocking asynchronous framework and setup and isn't likely to work out of box with Pylons.</p> <p>I usually go with the proxy route to a stand-alone Pylons process using the PasteScript#cherrypy WSGI server (as its higher performing than the Paste#http one, though it won't recycle threads if you have leaks...).</p> <p>If you're set on using Apache and its <em>your</em> server (so you can compile and run Apache mod_wsgi), I'd suggest using that setup as its less maintenance to effectively utilize multiple cores. With a proxy setup, you'd have to use the mod_proxy_balancer with multiple paste processes to effectively utilize multiple cores/cpus.</p> <p>If you're deploying to someone else's Apache (shared hosting), mod_proxy is generally the easier solution as its stock in Apache 2.2 and above.</p> <p>Personally, I usually deploy with nginx + proxy to multiple paster processes.</p>
8
2009-05-02T02:26:56Z
[ "python", "apache2", "pylons", "mod-wsgi" ]
If I want to use a pylons app with Apache, should I use mod_wsgi or proxy to paste?
813,943
<p>Or should I be using a totally different server?</p>
4
2009-05-02T01:37:39Z
817,350
<p>I've also used mod_fastcgi + flup to great success several times now. There are a couple of recipes floating around for setting this up, but unfortunately it will probably still require some tweaking on your part to get everything working:</p> <p><a href="http://wiki.pylonshq.com/display/pylonscookbook/Production+Deployment+Using+Apache,+FastCGI+and+mod_rewrite" rel="nofollow">http://wiki.pylonshq.com/display/pylonscookbook/Production+Deployment+Using+Apache,+FastCGI+and+mod_rewrite</a></p>
0
2009-05-03T15:47:43Z
[ "python", "apache2", "pylons", "mod-wsgi" ]
How to Fix the Broken BSDDB Install in the Default Python Package on Mac OS X 10.5 Leopard?
814,041
<p>Do the following on the default Python install on Mac OS X 10.5 (Leopard) w/ Developer Tools:</p> <pre><code>noel ~ : python Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import bsddb Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/bsddb/__init__.py", line 51, in &lt;module&gt; import _bsddb ImportError: No module named _bsddb </code></pre> <p>nice, huh? How do I fix this without giving up and installing/configuring/maintaining my own Python package as per <a href="http://blogs.23.nu/c0re/2007/12/antville-16716/" rel="nofollow">TMNC's suggestion</a> or using MacPorts etc?</p> <h3>Edit</h3> <p>I've gone around the problem by installing Python2.4 and BSDDB via MacPorts.</p> <p>My question still stands: why is the default install broken and is it possible to fix it.</p>
4
2009-05-02T03:08:07Z
814,105
<p>Follow the instructions at <a href="http://marc-abramowitz.com/archives/2007/11/28/hacking-os-xs-python-dbhash-and-bsddb-modules-to-work/">http://marc-abramowitz.com/archives/2007/11/28/hacking-os-xs-python-dbhash-and-bsddb-modules-to-work/</a> .</p>
6
2009-05-02T03:59:58Z
[ "python", "osx", "osx-leopard", "berkeley-db", "bsddb" ]
How to Fix the Broken BSDDB Install in the Default Python Package on Mac OS X 10.5 Leopard?
814,041
<p>Do the following on the default Python install on Mac OS X 10.5 (Leopard) w/ Developer Tools:</p> <pre><code>noel ~ : python Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import bsddb Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/bsddb/__init__.py", line 51, in &lt;module&gt; import _bsddb ImportError: No module named _bsddb </code></pre> <p>nice, huh? How do I fix this without giving up and installing/configuring/maintaining my own Python package as per <a href="http://blogs.23.nu/c0re/2007/12/antville-16716/" rel="nofollow">TMNC's suggestion</a> or using MacPorts etc?</p> <h3>Edit</h3> <p>I've gone around the problem by installing Python2.4 and BSDDB via MacPorts.</p> <p>My question still stands: why is the default install broken and is it possible to fix it.</p>
4
2009-05-02T03:08:07Z
5,687,452
<p>A solution I found was to install ActivePython, dig into its library (located in /Library/Frameworks/Python.framework/Versions/....your version here..../lib) and copy and paste the <strong>_bsddb.so</strong> file into my OS X 10.6 native python 2.6 install directory (/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/).</p> <p>That fixed the missing _bsddb issue leaving me with a working version of bsddb in my native python install. Then, I just uninstalled ActivePython (<a href="http://docs.activestate.com/activepython/2.6/installnotes.html#osxpkg_uninstall" rel="nofollow">instructions here</a>)</p>
1
2011-04-16T15:18:45Z
[ "python", "osx", "osx-leopard", "berkeley-db", "bsddb" ]
How to Fix the Broken BSDDB Install in the Default Python Package on Mac OS X 10.5 Leopard?
814,041
<p>Do the following on the default Python install on Mac OS X 10.5 (Leopard) w/ Developer Tools:</p> <pre><code>noel ~ : python Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import bsddb Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/bsddb/__init__.py", line 51, in &lt;module&gt; import _bsddb ImportError: No module named _bsddb </code></pre> <p>nice, huh? How do I fix this without giving up and installing/configuring/maintaining my own Python package as per <a href="http://blogs.23.nu/c0re/2007/12/antville-16716/" rel="nofollow">TMNC's suggestion</a> or using MacPorts etc?</p> <h3>Edit</h3> <p>I've gone around the problem by installing Python2.4 and BSDDB via MacPorts.</p> <p>My question still stands: why is the default install broken and is it possible to fix it.</p>
4
2009-05-02T03:08:07Z
17,073,693
<p>The error I had was "No module named _bsddb". It turn out I didn't need to upgrade my bsddb. I wasusing the .pkl file created in windows. After renaming the pkl file to get it out the way Mac OSX Python recreated a new .pkl.db file and now it works perfectly.</p>
0
2013-06-12T19:28:54Z
[ "python", "osx", "osx-leopard", "berkeley-db", "bsddb" ]
How to Fix the Broken BSDDB Install in the Default Python Package on Mac OS X 10.5 Leopard?
814,041
<p>Do the following on the default Python install on Mac OS X 10.5 (Leopard) w/ Developer Tools:</p> <pre><code>noel ~ : python Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import bsddb Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/bsddb/__init__.py", line 51, in &lt;module&gt; import _bsddb ImportError: No module named _bsddb </code></pre> <p>nice, huh? How do I fix this without giving up and installing/configuring/maintaining my own Python package as per <a href="http://blogs.23.nu/c0re/2007/12/antville-16716/" rel="nofollow">TMNC's suggestion</a> or using MacPorts etc?</p> <h3>Edit</h3> <p>I've gone around the problem by installing Python2.4 and BSDDB via MacPorts.</p> <p>My question still stands: why is the default install broken and is it possible to fix it.</p>
4
2009-05-02T03:08:07Z
24,358,389
<p>The patch did not work for me and I had to replace the bsddb folder in /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7</p> <p>with the bsddb3 in:</p> <p>/usr/local/lib/python2.7/site-packages/bsddb3</p> <p>Make sure you backup the bsddb folder just in case.</p>
1
2014-06-23T04:28:28Z
[ "python", "osx", "osx-leopard", "berkeley-db", "bsddb" ]
How to Fix the Broken BSDDB Install in the Default Python Package on Mac OS X 10.5 Leopard?
814,041
<p>Do the following on the default Python install on Mac OS X 10.5 (Leopard) w/ Developer Tools:</p> <pre><code>noel ~ : python Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import bsddb Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/bsddb/__init__.py", line 51, in &lt;module&gt; import _bsddb ImportError: No module named _bsddb </code></pre> <p>nice, huh? How do I fix this without giving up and installing/configuring/maintaining my own Python package as per <a href="http://blogs.23.nu/c0re/2007/12/antville-16716/" rel="nofollow">TMNC's suggestion</a> or using MacPorts etc?</p> <h3>Edit</h3> <p>I've gone around the problem by installing Python2.4 and BSDDB via MacPorts.</p> <p>My question still stands: why is the default install broken and is it possible to fix it.</p>
4
2009-05-02T03:08:07Z
25,348,662
<p>This pain persists on OSX 10.8. I could not install bsddb3 using macports py-bsddb3 into a virtualenv. What was very simple and did work is:</p> <ul> <li>install db53 from macports</li> <li>download and unpack bsddb3 source (<a href="https://pypi.python.org/pypi/bsddb3/6.1.0" rel="nofollow">https://pypi.python.org/pypi/bsddb3/6.1.0</a>)</li> <li>sudo python setup.py –berkeley-db-incdir=/opt/local/include/db53 –berkeley-db-libdir=/opt/local/lib/db53 install</li> </ul>
2
2014-08-17T11:10:12Z
[ "python", "osx", "osx-leopard", "berkeley-db", "bsddb" ]
PY2EXE: How to output "*_D.PYD" file (debug) and use MSVCR80D.DLL?
814,078
<p>The debug configuration of my app is built against:</p> <pre><code> PYTHON25_D.DLL MSVCR80D.DLL </code></pre> <p>We use Python .PYD files in our application. Some of these .PYD are .PY converted by PY2EXE to .PYD.</p> <p>When I run PY2EXE on MYSCRIPT.PY, I get the following .PYD and dependencies:</p> <pre><code>MYSCRIPT.PYD PYTHON25.DLL MSVCR71.DLL KERNEL32.DLL </code></pre> <p>What I <em>want</em> is the debug version, built against the same C runtime library my app uses (MSVCR80D.DLL). </p> <p>How can I convert MYSCRIPT.PY into:</p> <pre><code>MYSCRIPT_D.PYD &lt;-- debug version of .PYD end with "_D" PYTHON25_D.DLL &lt;-- debug version of Python MSVCR80D.DLL &lt;-- ver 8.0, Debug KERNEL32.DLL </code></pre> <p>How can this be done?</p>
0
2009-05-02T03:40:31Z
814,189
<p>it won't work, beacuse MSVCR80D is a side by side runtime</p> <p>You will need to either tell user to directly install MS runtime or manually also copy the manifest files. Also the MSVCR71.DLL is not selected for you. It's for Python, so you may still need to keep it.</p>
0
2009-05-02T05:12:00Z
[ "python", "windows", "py2exe" ]
PY2EXE: How to output "*_D.PYD" file (debug) and use MSVCR80D.DLL?
814,078
<p>The debug configuration of my app is built against:</p> <pre><code> PYTHON25_D.DLL MSVCR80D.DLL </code></pre> <p>We use Python .PYD files in our application. Some of these .PYD are .PY converted by PY2EXE to .PYD.</p> <p>When I run PY2EXE on MYSCRIPT.PY, I get the following .PYD and dependencies:</p> <pre><code>MYSCRIPT.PYD PYTHON25.DLL MSVCR71.DLL KERNEL32.DLL </code></pre> <p>What I <em>want</em> is the debug version, built against the same C runtime library my app uses (MSVCR80D.DLL). </p> <p>How can I convert MYSCRIPT.PY into:</p> <pre><code>MYSCRIPT_D.PYD &lt;-- debug version of .PYD end with "_D" PYTHON25_D.DLL &lt;-- debug version of Python MSVCR80D.DLL &lt;-- ver 8.0, Debug KERNEL32.DLL </code></pre> <p>How can this be done?</p>
0
2009-05-02T03:40:31Z
814,473
<p>Note that the MS debug dlls are nondistributable - you must not give them avay. However, py2exe will collect the debug versions of all dlls correctly if you run a debug version of Python, and a debug compiled version of py2exe.</p>
0
2009-05-02T09:09:38Z
[ "python", "windows", "py2exe" ]
Easiest way to rm -rf in Python
814,167
<p>What is the easiest way to do the equivalent of <code>rm -rf</code> in Python?</p>
42
2009-05-02T04:52:24Z
814,170
<pre><code>import shutil shutil.rmtree("dir-you-want-to-remove") </code></pre>
51
2009-05-02T04:54:34Z
[ "python" ]
Easiest way to rm -rf in Python
814,167
<p>What is the easiest way to do the equivalent of <code>rm -rf</code> in Python?</p>
42
2009-05-02T04:52:24Z
814,535
<p>shutil.rmtree() is right answer, but just look at another useful function - os.walk()</p>
1
2009-05-02T09:38:05Z
[ "python" ]
Easiest way to rm -rf in Python
814,167
<p>What is the easiest way to do the equivalent of <code>rm -rf</code> in Python?</p>
42
2009-05-02T04:52:24Z
9,559,881
<p>While useful, rmtree isn't equivalent: it errors out if you try to remove a single file, which <code>rm -f</code> does not (see example below).</p> <p>To get around this, you'll need to check whether your path is a file or a directory, and act accordingly. Something like this should do the trick:</p> <pre><code>import os import shutil def rm_r(path): if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) </code></pre> <p>Note: this function will not handle character or block devices (that would require using the <code>stat</code> module).</p> <p>Example in difference of between <code>rm -f</code> and Python's <code>shutils.rmtree</code></p> <pre><code>$ mkdir rmtest $ cd rmtest/ $ echo "stuff" &gt; myfile $ ls myfile $ rm -rf myfile $ ls $ echo "stuff" &gt; myfile $ ls myfile $ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import shutil &gt;&gt;&gt; shutil.rmtree('myfile') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/shutil.py", line 236, in rmtree onerror(os.listdir, path, sys.exc_info()) File "/usr/lib/python2.7/shutil.py", line 234, in rmtree names = os.listdir(path) OSError: [Errno 20] Not a directory: 'myfile' </code></pre> <p><em>Edit:</em> handle symlinks; note limitations as per @pevik's comment</p>
24
2012-03-04T23:28:12Z
[ "python" ]
Easiest way to rm -rf in Python
814,167
<p>What is the easiest way to do the equivalent of <code>rm -rf</code> in Python?</p>
42
2009-05-02T04:52:24Z
32,881,474
<pre><code>import os import shutil def rm_r(path): if not os.path.exists(path): return if os.path.isfile(path) or os.path.islink(path): os.unlink(path) else: shutil.rmtree(path) </code></pre> <p>Slightly improved Gabriel Grant's version. This works also on symlinks to directories. Note: function does <em>not</em> handle Un*x character and block devices (it would require to use <a href="https://docs.python.org/3.0/library/stat.html" rel="nofollow">stat</a> module).</p>
1
2015-10-01T07:11:52Z
[ "python" ]
Easiest way to rm -rf in Python
814,167
<p>What is the easiest way to do the equivalent of <code>rm -rf</code> in Python?</p>
42
2009-05-02T04:52:24Z
33,421,144
<p>Just do this:</p> <pre><code>import os dirname = "path_to_directory_to_remove" os.system("rm -rf %s" % dirname) </code></pre>
-5
2015-10-29T17:42:14Z
[ "python" ]
Python lxml screen scraping?
814,227
<p>I need to do some HTML parsing with python. After some research lxml seems to be my best choice but I am having a hard time finding examples that help me with what I am trying to do. this is why i am hear. I need to scrape a page for all of its viewable text.. strip out all tags and javascript.. I need it to leave me with what text is viewable. sounds simple enough.. i did it with the HTMLParser but its not handling javascript well</p> <pre><code>class HTML2Text(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.output = cStringIO.StringIO() def get_text(self): return self.output.getvalue() def handle_data(self, data): self.output.write(data) def ParseHTML(source): p = HTML2Text() p.feed(source) text = p.get_text() return text </code></pre> <p>Any Ideas for a way to do this with lxml or a better way to do it HTMLParser.. HTMLParser would be best because no additional libs are needed.. thanks everyone</p> <p>Scott F.</p>
1
2009-05-02T05:44:05Z
814,233
<p>No screen-scraping library I know "does well with Javascript" -- it's just too hard to anticipate all ways in which JS could alter the HTML DOM dynamically, conditionally &amp;c.</p>
4
2009-05-02T05:47:06Z
[ "python", "html", "parsing", "screen-scraping", "lxml" ]
Python lxml screen scraping?
814,227
<p>I need to do some HTML parsing with python. After some research lxml seems to be my best choice but I am having a hard time finding examples that help me with what I am trying to do. this is why i am hear. I need to scrape a page for all of its viewable text.. strip out all tags and javascript.. I need it to leave me with what text is viewable. sounds simple enough.. i did it with the HTMLParser but its not handling javascript well</p> <pre><code>class HTML2Text(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.output = cStringIO.StringIO() def get_text(self): return self.output.getvalue() def handle_data(self, data): self.output.write(data) def ParseHTML(source): p = HTML2Text() p.feed(source) text = p.get_text() return text </code></pre> <p>Any Ideas for a way to do this with lxml or a better way to do it HTMLParser.. HTMLParser would be best because no additional libs are needed.. thanks everyone</p> <p>Scott F.</p>
1
2009-05-02T05:44:05Z
814,430
<p>BeautifulSoup (<a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/</a>) is often the right answer to python html scraping questions.</p>
0
2009-05-02T08:33:29Z
[ "python", "html", "parsing", "screen-scraping", "lxml" ]
Python lxml screen scraping?
814,227
<p>I need to do some HTML parsing with python. After some research lxml seems to be my best choice but I am having a hard time finding examples that help me with what I am trying to do. this is why i am hear. I need to scrape a page for all of its viewable text.. strip out all tags and javascript.. I need it to leave me with what text is viewable. sounds simple enough.. i did it with the HTMLParser but its not handling javascript well</p> <pre><code>class HTML2Text(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.output = cStringIO.StringIO() def get_text(self): return self.output.getvalue() def handle_data(self, data): self.output.write(data) def ParseHTML(source): p = HTML2Text() p.feed(source) text = p.get_text() return text </code></pre> <p>Any Ideas for a way to do this with lxml or a better way to do it HTMLParser.. HTMLParser would be best because no additional libs are needed.. thanks everyone</p> <p>Scott F.</p>
1
2009-05-02T05:44:05Z
814,538
<p>I know of no Python HTML parsing libraries that handle running javascript in the page being parsed. It's not "simple enough" for the reasons given by Alex Martelli and more.</p> <p>For this task you may need to think about going to a higher level than just parsing HTML and look at web application testing frameworks.</p> <p>Two that can execute javascript and are either Python based or can interface with Python:</p> <ul> <li><a href="http://pamie.sourceforge.net/" rel="nofollow">PAMIE</a></li> <li><a href="http://seleniumhq.org/" rel="nofollow">Selenium</a></li> </ul> <p>Unfortunately I'm not sure if the "unit testing" orientation of these frameworks will actually let you scrape out visible text.</p> <p>So the only other solution would be to do it yourself, say by integrating <a href="http://github.com/davisp/python-spidermonkey/tree/master" rel="nofollow">python-spidermonkey</a> into your app.</p>
0
2009-05-02T09:40:04Z
[ "python", "html", "parsing", "screen-scraping", "lxml" ]
Python lxml screen scraping?
814,227
<p>I need to do some HTML parsing with python. After some research lxml seems to be my best choice but I am having a hard time finding examples that help me with what I am trying to do. this is why i am hear. I need to scrape a page for all of its viewable text.. strip out all tags and javascript.. I need it to leave me with what text is viewable. sounds simple enough.. i did it with the HTMLParser but its not handling javascript well</p> <pre><code>class HTML2Text(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.output = cStringIO.StringIO() def get_text(self): return self.output.getvalue() def handle_data(self, data): self.output.write(data) def ParseHTML(source): p = HTML2Text() p.feed(source) text = p.get_text() return text </code></pre> <p>Any Ideas for a way to do this with lxml or a better way to do it HTMLParser.. HTMLParser would be best because no additional libs are needed.. thanks everyone</p> <p>Scott F.</p>
1
2009-05-02T05:44:05Z
1,383,491
<p>Your code is smart and very flexible to extent, I think.</p> <p>How about simply adding handle_starttag() and handle_endtag() to supress the &lt;script&gt; blocks?</p> <pre><code>class HTML2Text(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.output = cStringIO.StringIO() self.is_in_script = False def get_text(self): return self.output.getvalue() def handle_data(self, data): if not self.is_in_script: self.output.write(data) def handle_starttag(self, tag, attrs): if tag == "script": self.is_in_script = True def handle_endtag(self, tag): if tag == "script": self.is_in_script = False def ParseHTML(source): p = HTML2Text() p.feed(source) text = p.get_text() return text </code></pre>
0
2009-09-05T14:47:08Z
[ "python", "html", "parsing", "screen-scraping", "lxml" ]
Python lxml screen scraping?
814,227
<p>I need to do some HTML parsing with python. After some research lxml seems to be my best choice but I am having a hard time finding examples that help me with what I am trying to do. this is why i am hear. I need to scrape a page for all of its viewable text.. strip out all tags and javascript.. I need it to leave me with what text is viewable. sounds simple enough.. i did it with the HTMLParser but its not handling javascript well</p> <pre><code>class HTML2Text(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.output = cStringIO.StringIO() def get_text(self): return self.output.getvalue() def handle_data(self, data): self.output.write(data) def ParseHTML(source): p = HTML2Text() p.feed(source) text = p.get_text() return text </code></pre> <p>Any Ideas for a way to do this with lxml or a better way to do it HTMLParser.. HTMLParser would be best because no additional libs are needed.. thanks everyone</p> <p>Scott F.</p>
1
2009-05-02T05:44:05Z
2,603,442
<p><a href="http://zesty.ca/scrape/" rel="nofollow">scrape.py</a> can do this for you.</p> <p>It's as simple as:</p> <pre><code>import scrape s = scrape.Session() s.go('yoursite.com') print s.doc.text </code></pre> <p>Jump to about 2:40 in this video for an awesome overview from the creator of scrape.py: <a href="http://pycon.blip.tv/file/3261277" rel="nofollow">pycon.blip.tv/file/3261277</a></p>
2
2010-04-08T21:02:24Z
[ "python", "html", "parsing", "screen-scraping", "lxml" ]
Python regex parsing
814,786
<p>I have an array of strings in python which each string in the array looking something like this:</p> <pre><code>&lt;r n="Foo Bar" t="5" s="10" l="25"/&gt; </code></pre> <p>I have been searching around for a while and the best thing I could find is attempting to modify a HTML hyperlink regex into something that will fit my needs.</p> <p>But not really knowing much regex stuff I havent had anything work yet. This is what I have so far.</p> <pre><code>string = '&lt;r n="Foo Bar" t="5" s="10" l="25"/&gt;' print re.split("&lt;r\s+n=(?:\"(^\"]+)\").*?/&gt;", string) </code></pre> <p>What would be the best way to extract the values of n, t, s, and l from that string?</p>
2
2009-05-02T12:28:13Z
814,797
<p>This will get you most of the way there:</p> <pre><code>&gt;&gt;&gt; print re.findall(r'(\w+)="(.*?)"', string) [('n', 'Foo Bar'), ('t', '5'), ('s', '10'), ('l', '25')] </code></pre> <p><a href="http://docs.python.org/library/re.html#re.split" rel="nofollow">re.split</a> and <a href="http://docs.python.org/library/re.html#re.findall" rel="nofollow">re.findall</a> are complementary.</p> <p>Every time your thought process begins with "I want each item that looks like X", then you should use <code>re.findall</code>. When it starts with "I want the data between and surrounding each X", use <code>re.split</code>.</p>
7
2009-05-02T12:34:08Z
[ "python", "regex" ]
Python regex parsing
814,786
<p>I have an array of strings in python which each string in the array looking something like this:</p> <pre><code>&lt;r n="Foo Bar" t="5" s="10" l="25"/&gt; </code></pre> <p>I have been searching around for a while and the best thing I could find is attempting to modify a HTML hyperlink regex into something that will fit my needs.</p> <p>But not really knowing much regex stuff I havent had anything work yet. This is what I have so far.</p> <pre><code>string = '&lt;r n="Foo Bar" t="5" s="10" l="25"/&gt;' print re.split("&lt;r\s+n=(?:\"(^\"]+)\").*?/&gt;", string) </code></pre> <p>What would be the best way to extract the values of n, t, s, and l from that string?</p>
2
2009-05-02T12:28:13Z
814,872
<blockquote> <pre><code>&lt;r n="Foo Bar" t="5" s="10" l="25"/&gt; </code></pre> </blockquote> <p>That source looks like XML, so the "the best way" would be to use an XML parsing module.. If it's not exactly XML, BeautifulSoup (or rather, the <code>BeautifulSoup.BeautifulStoneSoup</code> module) may work best, as it's good at dealing with possibly-invalid XML (or things that "aren't <em>quite</em> XML"):</p> <pre><code>&gt;&gt;&gt; from BeautifulSoup import BeautifulStoneSoup &gt;&gt;&gt; soup = BeautifulStoneSoup("""&lt;r n="Foo Bar" t="5" s="10" l="25"/&gt;""") # grab the "r" element (You could also use soup.findAll("r") if there are multiple &gt;&gt;&gt; soup.find("r") &lt;r n="Foo Bar" t="5" s="10" l="25"&gt;&lt;/r&gt; # get a specific attribute &gt;&gt;&gt; soup.find("r")['n'] u'Foo Bar' &gt;&gt;&gt; soup.find("r")['t'] u'5' # Get all attributes, or turn them into a regular dictionary &gt;&gt;&gt; soup.find("r").attrs [(u'n', u'Foo Bar'), (u't', u'5'), (u's', u'10'), (u'l', u'25')] &gt;&gt;&gt; dict(soup.find("r").attrs) {u's': u'10', u'l': u'25', u't': u'5', u'n': u'Foo Bar'} </code></pre>
6
2009-05-02T13:32:54Z
[ "python", "regex" ]
google app engine - design considerations about cron tasks
814,896
<p>I'm developing software using the google app engine. </p> <p>I have some considerations about the optimal design regarding the following issue: I need to create and save snapshots of some entities at regular intervals.</p> <p>in the conventional relational db world, I would create db jobs which would insert new summary records.</p> <p>for example, a job would insert a record for every active user that would contain his current score to the "userrank" table, say, every hour.</p> <p>I'd like to know what's the best method to achieve this in google app engine. I know that there is the Cron service, but does it allow us to execute jobs which will insert/update thousands of records?</p>
1
2009-05-02T13:54:04Z
814,932
<p>Have you considered using the <a href="http://code.google.com/appengine/articles/remote%5Fapi.html" rel="nofollow">remote api</a> instead? This way you could get a shell to your datastore and avoid the timeouts. The Mapper class they demonstrate in that link is quite useful and I've used it successfully to do batch operations on ~1500 objects.</p> <p>That said, cron should work fine too. You do have a limit on the time of each individual request so you can't just chew through them all at once, but you can use redirection to loop over as many users as you want, processing one user at a time. There should be an example of this in the docs somewhere if you need help with this approach.</p>
2
2009-05-02T14:23:21Z
[ "python", "database", "design", "google-app-engine", "cron" ]
google app engine - design considerations about cron tasks
814,896
<p>I'm developing software using the google app engine. </p> <p>I have some considerations about the optimal design regarding the following issue: I need to create and save snapshots of some entities at regular intervals.</p> <p>in the conventional relational db world, I would create db jobs which would insert new summary records.</p> <p>for example, a job would insert a record for every active user that would contain his current score to the "userrank" table, say, every hour.</p> <p>I'd like to know what's the best method to achieve this in google app engine. I know that there is the Cron service, but does it allow us to execute jobs which will insert/update thousands of records?</p>
1
2009-05-02T13:54:04Z
815,113
<p>I think you'll find that snapshotting every user's state every hour isn't something that will scale well no matter what your framework. A more ordinary environment will disguise this by letting you have longer running tasks, but you'll still reach the point where it's not practical to take a snapshot of every user's data, every hour.</p> <p>My suggestion would be this: Add a 'last snapshot' field, and subclass the put() function of your model (assuming you're using Python; the same is possible in Java, but I don't know the syntax), such that whenever you update a record, it checks if it's been more than an hour since the last snapshot, and if so, creates and writes a snapshot record.</p> <p>In order to prevent concurrent updates creating two identical snapshots, you'll want to give the snapshots a key name derived from the time at which the snapshot was taken. That way, if two concurrent updates try to write a snapshot, one will harmlessly overwrite the other.</p> <p>To get the snapshot for a given hour, simply query for the oldest snapshot newer than the requested period. As an added bonus, since inactive records aren't snapshotted, you're saving a lot of space, too.</p>
3
2009-05-02T16:17:30Z
[ "python", "database", "design", "google-app-engine", "cron" ]
google app engine - design considerations about cron tasks
814,896
<p>I'm developing software using the google app engine. </p> <p>I have some considerations about the optimal design regarding the following issue: I need to create and save snapshots of some entities at regular intervals.</p> <p>in the conventional relational db world, I would create db jobs which would insert new summary records.</p> <p>for example, a job would insert a record for every active user that would contain his current score to the "userrank" table, say, every hour.</p> <p>I'd like to know what's the best method to achieve this in google app engine. I know that there is the Cron service, but does it allow us to execute jobs which will insert/update thousands of records?</p>
1
2009-05-02T13:54:04Z
1,758,489
<p>I would use a combination of Cron jobs and a looping url fetch method detailed here: <a href="http://stage.vambenepe.com/archives/549" rel="nofollow">http://stage.vambenepe.com/archives/549</a>. In this way you can catch your timeouts and begin another request.</p> <p>To summarize the article, the cron job calls your initial process, you catch the timeout error and call the process again, masked as a second url. You have to ping between two URLs to keep app engine from thinking you are in a accidental loop. You also need to be careful that you do not loop infinitely. Make sure that there is an end state for your updating loop, since this would put you over your quotas pretty quickly if it never ended.</p>
0
2009-11-18T19:35:02Z
[ "python", "database", "design", "google-app-engine", "cron" ]
python regular exp. with a unicode char
814,933
<p>I need a reg exp that will parse something like-</p> <pre><code>"2 * 240pin" </code></pre> <p>where the * can be either the regular star or unicode char \u00d7 or just an x. This is what I have but its not working:</p> <pre><code>multiple= r'^(\d+)\s?x|*|\\u00d7\s?(\d+)(\w{2,4})$' multiplepat= re.compile(multiple, re.I) print multiplepat.search(u'1 X 240pin').groups() </code></pre> <p>returns</p> <pre><code>multiplepat= re.compile(multiple, re.I) File "C:\Python26\lib\re.py", line 188, in compile return _compile(pattern, flags) File "C:\Python26\lib\re.py", line 243, in _compile raise error, v # invalid expression error: nothing to repeat </code></pre>
3
2009-05-02T14:26:05Z
814,947
<pre><code>multiple= r'^(\d+)\s[xX\*\\u00d7]\s?(\d+)(\w{2,4})$' </code></pre>
2
2009-05-02T14:39:06Z
[ "python", "regex" ]
python regular exp. with a unicode char
814,933
<p>I need a reg exp that will parse something like-</p> <pre><code>"2 * 240pin" </code></pre> <p>where the * can be either the regular star or unicode char \u00d7 or just an x. This is what I have but its not working:</p> <pre><code>multiple= r'^(\d+)\s?x|*|\\u00d7\s?(\d+)(\w{2,4})$' multiplepat= re.compile(multiple, re.I) print multiplepat.search(u'1 X 240pin').groups() </code></pre> <p>returns</p> <pre><code>multiplepat= re.compile(multiple, re.I) File "C:\Python26\lib\re.py", line 188, in compile return _compile(pattern, flags) File "C:\Python26\lib\re.py", line 243, in _compile raise error, v # invalid expression error: nothing to repeat </code></pre>
3
2009-05-02T14:26:05Z
814,950
<p>You need to escape the <code>*</code> as it is a quantifier in the context you use it. But you could also use a character class. So try this: </p> <pre><code>ur'^(\d+)\s?[x*\u00d7]\s?(\d+)(\w{2,4})$' </code></pre>
2
2009-05-02T14:41:06Z
[ "python", "regex" ]
python regular exp. with a unicode char
814,933
<p>I need a reg exp that will parse something like-</p> <pre><code>"2 * 240pin" </code></pre> <p>where the * can be either the regular star or unicode char \u00d7 or just an x. This is what I have but its not working:</p> <pre><code>multiple= r'^(\d+)\s?x|*|\\u00d7\s?(\d+)(\w{2,4})$' multiplepat= re.compile(multiple, re.I) print multiplepat.search(u'1 X 240pin').groups() </code></pre> <p>returns</p> <pre><code>multiplepat= re.compile(multiple, re.I) File "C:\Python26\lib\re.py", line 188, in compile return _compile(pattern, flags) File "C:\Python26\lib\re.py", line 243, in _compile raise error, v # invalid expression error: nothing to repeat </code></pre>
3
2009-05-02T14:26:05Z
814,957
<p>Use <a href="http://docs.python.org/library/re.html#regular-expression-syntax" rel="nofollow">character sets (<code>[]</code>)</a> :</p> <blockquote> <p>[]</p> <p>Used to indicate a set of characters. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a '-'. <strong>Special characters are not active inside sets</strong>. </p> </blockquote> <pre><code>&gt;&gt;&gt; m= u'^(\\d+)\\s?[x*\u00d7]\\s?(\\d+)(\\w{2,4})$' &gt;&gt;&gt; mpat=re.compile(m) &gt;&gt;&gt; mpat.search(u'1 * 240pin').groups() (u'1', u'240', u'pin') &gt;&gt;&gt; </code></pre>
2
2009-05-02T14:44:35Z
[ "python", "regex" ]
Is there a decorator to simply cache function return values?
815,110
<p>Consider the following:</p> <pre><code>@property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name </code></pre> <p>I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)</p> <p>PS the real calculation doesn't depend on mutable values</p>
67
2009-05-02T16:15:40Z
815,160
<p>It sounds like you're <strong>not</strong> asking for a general-purpose memoization decorator (i.e., you're not interested in the general case where you want to cache return values for different argument values). That is, you'd like to have this:</p> <pre><code>x = obj.name # expensive y = obj.name # cheap </code></pre> <p>while a general-purpose memoization decorator would give you this:</p> <pre><code>x = obj.name() # expensive y = obj.name() # cheap </code></pre> <p>I submit that the method-call syntax is better style, because it suggests the possibility of expensive computation while the property syntax suggests a quick lookup.</p> <p>[Update: The class-based memoization decorator I had linked to and quoted here previously doesn't work for methods. I've replaced it with a decorator function.] If you're willing to use a general-purpose memoization decorator, here's a simple one:</p> <pre><code>def memoize(function): memo = {} def wrapper(*args): if args in memo: return memo[args] else: rv = function(*args) memo[args] = rv return rv return wrapper </code></pre> <p>Example usage:</p> <pre><code>@memoize def fibonacci(n): if n &lt; 2: return n return fibonacci(n - 1) + fibonacci(n - 2) </code></pre> <p>Another memoization decorator with a limit on the cache size can be found <a href="http://code.activestate.com/recipes/496879/">here</a>.</p>
22
2009-05-02T16:42:33Z
[ "python", "caching", "decorator" ]
Is there a decorator to simply cache function return values?
815,110
<p>Consider the following:</p> <pre><code>@property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name </code></pre> <p>I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)</p> <p>PS the real calculation doesn't depend on mutable values</p>
67
2009-05-02T16:15:40Z
816,245
<p>Ah, just needed to find the right name for this: "<a href="http://code.activestate.com/recipes/363602/" rel="nofollow">Lazy property evaluation</a>".</p> <p>I do this a lot too; maybe I'll use that recipe in my code sometime.</p>
4
2009-05-03T03:25:54Z
[ "python", "caching", "decorator" ]
Is there a decorator to simply cache function return values?
815,110
<p>Consider the following:</p> <pre><code>@property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name </code></pre> <p>I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)</p> <p>PS the real calculation doesn't depend on mutable values</p>
67
2009-05-02T16:15:40Z
2,061,438
<p>There is yet another example of a <em>memoize</em> decorator at Python Wiki:</p> <p><a href="http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize" rel="nofollow">http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize</a></p> <p>That example is a bit smart, because it won't cache the results if the parameters are mutable. (check that code, it's very simple and interesting!)</p>
3
2010-01-14T00:40:44Z
[ "python", "caching", "decorator" ]
Is there a decorator to simply cache function return values?
815,110
<p>Consider the following:</p> <pre><code>@property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name </code></pre> <p>I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)</p> <p>PS the real calculation doesn't depend on mutable values</p>
67
2009-05-02T16:15:40Z
5,295,190
<p>Werkzeug has a <code>cached_property</code> decorator (<a href="http://werkzeug.pocoo.org/docs/utils/#werkzeug.utils.cached_property">docs</a>, <a href="https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/utils.py">source</a>)</p>
8
2011-03-14T05:48:16Z
[ "python", "caching", "decorator" ]
Is there a decorator to simply cache function return values?
815,110
<p>Consider the following:</p> <pre><code>@property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name </code></pre> <p>I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)</p> <p>PS the real calculation doesn't depend on mutable values</p>
67
2009-05-02T16:15:40Z
9,674,327
<p>Starting from Python 3.2 there is a built-in decorator:</p> <p><a href="http://docs.python.org/dev/library/functools.html#functools.lru_cache"><code>@functools.lru_cache(maxsize=100, typed=False)</code></a></p> <blockquote> Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments. </blockquote> <p>Example of an LRU cache for computing <a href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci numbers</a>:</p> <pre><code>@lru_cache(maxsize=None) def fib(n): if n &lt; 2: return n return fib(n-1) + fib(n-2) &gt;&gt;&gt; print([fib(n) for n in range(16)]) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] &gt;&gt;&gt; print(fib.cache_info()) CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) </code></pre> <hr> <p>If you are stuck with Python 2.x, here's a list of other compatible memoization libraries:</p> <ul> <li><code>functools32</code> | <a href="https://pypi.python.org/pypi/functools32">PyPI</a> | <a href="https://github.com/MiCHiLU/python-functools32">Source code</a></li> <li><code>repoze.lru</code> | <a href="https://pypi.python.org/pypi/repoze.lru/">PyPI</a> | <a href="https://github.com/repoze/repoze.lru">Source code</a></li> <li><code>pylru</code> | <a href="https://pypi.python.org/pypi/pylru/">PyPI</a> | <a href="https://github.com/jlhutch/pylru">Source code</a></li> <li><code>backports.functools_lru_cache</code> | <a href="https://pypi.python.org/pypi/backports.functools_lru_cache">PyPI</a> | <a href="https://github.com/jaraco/backports.functools_lru_cache">Source code</a></li> </ul>
81
2012-03-12T20:28:46Z
[ "python", "caching", "decorator" ]
Is there a decorator to simply cache function return values?
815,110
<p>Consider the following:</p> <pre><code>@property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name </code></pre> <p>I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)</p> <p>PS the real calculation doesn't depend on mutable values</p>
67
2009-05-02T16:15:40Z
16,459,127
<p>If you are using Django Framework, it has such a property to cache a view or response of API's using @cache_page(time) and there can be other options as well.</p> <pre><code>@cache_page(60 * 15, cache="special_cache") def my_view(request): ... </code></pre> <p>More details can be found <a href="https://docs.djangoproject.com/en/dev/topics/cache/" rel="nofollow">here</a>.</p>
2
2013-05-09T10:00:02Z
[ "python", "caching", "decorator" ]
Is there a decorator to simply cache function return values?
815,110
<p>Consider the following:</p> <pre><code>@property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name </code></pre> <p>I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)</p> <p>PS the real calculation doesn't depend on mutable values</p>
67
2009-05-02T16:15:40Z
18,774,264
<p>I implemented something like this, using pickle for persistance and using sha1 for short almost-certainly-unique IDs. Basically the cache hashed the code of the function and the hist of arguments to get a sha1 then looked for a file with that sha1 in the name. If it existed, it opened it and returned the result; if not, it calls the function and saves the result (optionally only saving if it took a certain amount of time to process).</p> <p>That said, I'd swear I found an existing module that did this and find myself here trying to find that module... The closest I can find is this, which looks about right: <a href="http://chase-seibert.github.io/blog/2011/11/23/pythondjango-disk-based-caching-decorator.html" rel="nofollow">http://chase-seibert.github.io/blog/2011/11/23/pythondjango-disk-based-caching-decorator.html</a></p> <p>The only problem I see with that is it wouldn't work well for large inputs since it hashes str(arg), which isn't unique for giant arrays.</p> <p>It would be nice if there were a <strong>unique_hash</strong>() protocol that had a class return a secure hash of its contents. I basically manually implemented that for the types I cared about.</p>
1
2013-09-12T21:01:43Z
[ "python", "caching", "decorator" ]
Is there a decorator to simply cache function return values?
815,110
<p>Consider the following:</p> <pre><code>@property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name </code></pre> <p>I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)</p> <p>PS the real calculation doesn't depend on mutable values</p>
67
2009-05-02T16:15:40Z
22,552,713
<pre><code>class memorize(dict): def __init__(self, func): self.func = func def __call__(self, *args): return self[args] def __missing__(self, key): result = self[key] = self.func(*key) return result </code></pre> <p>Sample uses:</p> <pre><code>&gt;&gt;&gt; @memorize ... def foo(a, b): ... return a * b &gt;&gt;&gt; foo(2, 4) 8 &gt;&gt;&gt; foo {(2, 4): 8} &gt;&gt;&gt; foo('hi', 3) 'hihihi' &gt;&gt;&gt; foo {(2, 4): 8, ('hi', 3): 'hihihi'} </code></pre>
11
2014-03-21T07:27:09Z
[ "python", "caching", "decorator" ]
Is there a decorator to simply cache function return values?
815,110
<p>Consider the following:</p> <pre><code>@property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name </code></pre> <p>I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)</p> <p>PS the real calculation doesn't depend on mutable values</p>
67
2009-05-02T16:15:40Z
29,891,043
<p><strong>DISCLAIMER:</strong> I'm the author of <a href="https://github.com/0k/kids.cache" rel="nofollow">kids.cache</a>.</p> <p>You should check <code>kids.cache</code>, it provides a <code>@cache</code> decorator that works on python 2 and python 3. No dependencies, ~100 lines of code. It's very straightforward to use, for instance, with your code in mind, you could use it like this:</p> <pre><code>pip install kids.cache </code></pre> <p>Then</p> <pre><code>from kids.cache import cache ... class MyClass(object): ... @cache # &lt;-- That's all you need to do @property def name(self): return 1 + 1 # supposedly expensive calculation </code></pre> <p>Or you could put the <code>@cache</code> decorator after the <code>@property</code> (same result).</p> <p>Using cache on a property is called <em>lazy evaluation</em>, <code>kids.cache</code> can do much more (it works on function with any arguments, properties, any type of methods, and even classes...). For advanced users, <code>kids.cache</code> supports <code>cachetools</code> which provides fancy cache stores to python 2 and python 3 (LRU, LFU, TTL, RR cache).</p>
3
2015-04-27T08:46:35Z
[ "python", "caching", "decorator" ]
Is there a decorator to simply cache function return values?
815,110
<p>Consider the following:</p> <pre><code>@property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name </code></pre> <p>I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)</p> <p>PS the real calculation doesn't depend on mutable values</p>
67
2009-05-02T16:15:40Z
30,698,822
<p>I coded this simple decorator class to cache function responses. I find it VERY useful for my projects:</p> <pre><code>from datetime import datetime, timedelta class cached(object): def __init__(self, *args, **kwargs): self.cached_function_responses = {} self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=0)) def __call__(self, func): def inner(*args, **kwargs): max_age = kwargs.get('max_age', self.default_max_age) if not max_age or func not in self.cached_function_responses or (datetime.now() - self.cached_function_responses[func]['fetch_time'] &gt; max_age): if 'max_age' in kwargs: del kwargs['max_age'] res = func(*args, **kwargs) self.cached_function_responses[func] = {'data': res, 'fetch_time': datetime.now()} return self.cached_function_responses[func]['data'] return inner </code></pre> <p>The usage is straightforward:</p> <pre><code>import time @cached def myfunc(a): print "in func" return (a, datetime.now()) @cached(default_max_age = timedelta(seconds=6)) def cacheable_test(a): print "in cacheable test: " return (a, datetime.now()) print cacheable_test(1,max_age=timedelta(seconds=5)) print cacheable_test(2,max_age=timedelta(seconds=5)) time.sleep(7) print cacheable_test(3,max_age=timedelta(seconds=5)) </code></pre>
6
2015-06-07T21:53:33Z
[ "python", "caching", "decorator" ]
Is there a decorator to simply cache function return values?
815,110
<p>Consider the following:</p> <pre><code>@property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name </code></pre> <p>I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)</p> <p>PS the real calculation doesn't depend on mutable values</p>
67
2009-05-02T16:15:40Z
36,857,036
<p>Along with the <a href="http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize" rel="nofollow">Memoize Example</a> I found the following python packages:</p> <ul> <li><a href="https://pypi.python.org/pypi/cachepy/" rel="nofollow">cachepy</a>; It allows to set up ttl and\or the number of calls for cached functions; Also, one can use encrypted file-based cache...</li> <li><a href="https://pypi.python.org/pypi/percache" rel="nofollow">percache</a> </li> </ul>
0
2016-04-26T06:36:31Z
[ "python", "caching", "decorator" ]
How to designate unreachable python code
815,310
<p>What's the pythonic way to designate unreachable code in python as in:</p> <pre><code>gender = readFromDB(...) # either 'm' or 'f' if gender == 'm': greeting = 'Mr.' elif gender == 'f': greeting = 'Ms.' else: # What should this line say? </code></pre>
8
2009-05-02T18:16:06Z
815,320
<pre><code>raise ValueError('invalid gender %r' % gender) </code></pre>
23
2009-05-02T18:22:36Z
[ "python" ]
How to designate unreachable python code
815,310
<p>What's the pythonic way to designate unreachable code in python as in:</p> <pre><code>gender = readFromDB(...) # either 'm' or 'f' if gender == 'm': greeting = 'Mr.' elif gender == 'f': greeting = 'Ms.' else: # What should this line say? </code></pre>
8
2009-05-02T18:16:06Z
815,324
<p>This depends on how sure you are of the gender being either <code>'m'</code> or <code>'f'</code>.</p> <p>If you're absolutely certain, use <code>if...else</code> instead of <code>if...elif...else</code>. Just makes it easier for everyone.</p> <p>If there's any chance of malformed data, however, you should probably raise an exception to make testing and bug-fixing easier. You <em>could</em> use a gender-neutral greeting in this case, but for anything bigger, special values just make bugs harder to find.</p>
7
2009-05-02T18:23:00Z
[ "python" ]
How to designate unreachable python code
815,310
<p>What's the pythonic way to designate unreachable code in python as in:</p> <pre><code>gender = readFromDB(...) # either 'm' or 'f' if gender == 'm': greeting = 'Mr.' elif gender == 'f': greeting = 'Ms.' else: # What should this line say? </code></pre>
8
2009-05-02T18:16:06Z
815,327
<p>You could raise an exception:</p> <pre><code>raise ValueError("Unexpected gender; expected 'm' or 'f', got %s" % gender) </code></pre> <p>or use an assert False if you expect the database to return only 'm' or 'f':</p> <pre><code>assert False, "Unexpected gender; expected 'm' or 'f', got %s" % gender </code></pre>
7
2009-05-02T18:24:22Z
[ "python" ]
How to designate unreachable python code
815,310
<p>What's the pythonic way to designate unreachable code in python as in:</p> <pre><code>gender = readFromDB(...) # either 'm' or 'f' if gender == 'm': greeting = 'Mr.' elif gender == 'f': greeting = 'Ms.' else: # What should this line say? </code></pre>
8
2009-05-02T18:16:06Z
815,518
<p>I actually think that there's a place for this.</p> <pre><code>class SeriousDesignError( Exception ): pass </code></pre> <p>So you can do this</p> <pre><code>if number % 2 == 0: result = "Even" elif number % 2 == 1: result = "Odd" else: raise SeriousDesignError() </code></pre> <p>I think this is the most meaningful error message. This kind of thing can only arise through design errors (or bad maintenance, which is the same thing.)</p>
4
2009-05-02T20:11:43Z
[ "python" ]
How to designate unreachable python code
815,310
<p>What's the pythonic way to designate unreachable code in python as in:</p> <pre><code>gender = readFromDB(...) # either 'm' or 'f' if gender == 'm': greeting = 'Mr.' elif gender == 'f': greeting = 'Ms.' else: # What should this line say? </code></pre>
8
2009-05-02T18:16:06Z
815,886
<p>I sometimes do:</p> <pre><code>if gender == 'm': greeting = 'Mr.' else: assert gender == 'f' greeting = 'Ms.' </code></pre> <p>I think this does a good job of telling a reader of the code that there are only (in this case) two possibilities, and what they are. Although you could make a case for raising a more descriptive error than AssertionError.</p>
2
2009-05-02T23:26:18Z
[ "python" ]
How to designate unreachable python code
815,310
<p>What's the pythonic way to designate unreachable code in python as in:</p> <pre><code>gender = readFromDB(...) # either 'm' or 'f' if gender == 'm': greeting = 'Mr.' elif gender == 'f': greeting = 'Ms.' else: # What should this line say? </code></pre>
8
2009-05-02T18:16:06Z
815,935
<p>It depends exactly what you want the error to signal, but I would use a dictionary in this case:</p> <pre><code>greetings={'m':'Mr.', 'f':'Ms.'} gender = readFromDB(...) # either 'm' or 'f' greeting=greetings[gender] </code></pre> <p>If gender is neither m nor f, this will raise a KeyError containing the unexpected value:</p> <pre><code>greetings={'m':'Mr.', 'f':'Ms.'} &gt;&gt;&gt; greetings['W'] Traceback (most recent call last): File "&lt;pyshell#4&gt;", line 1, in &lt;module&gt; greetings['W'] KeyError: 'W' </code></pre> <p>If you want more detail in the message, you can catch &amp; reraise it:</p> <pre><code>try: greeting = greetings[gender] except KeyError,e: raise ValueError('Unrecognized gender %s'%gender) </code></pre>
3
2009-05-02T23:51:45Z
[ "python" ]
How to designate unreachable python code
815,310
<p>What's the pythonic way to designate unreachable code in python as in:</p> <pre><code>gender = readFromDB(...) # either 'm' or 'f' if gender == 'm': greeting = 'Mr.' elif gender == 'f': greeting = 'Ms.' else: # What should this line say? </code></pre>
8
2009-05-02T18:16:06Z
10,038,699
<p>Until now, I've usually used a variation on John Fouhy's answer -- but this is not exactly correct, as Ethan points out:</p> <pre><code>assert gender in ('m', 'f') if gender == 'm': greeting = 'Mr.' else: greeting = 'Ms.' </code></pre> <p>The main problem with using an assert is that if anyone runs your code with the -O or -OO flags, the asserts get optimized away. As Ethan points out below, that means you now have no data checks at all. Asserts are a development aid and shouldn't be used for production logic. I'm going to get into the habit of using a check() function instead -- this allows for clean calling syntax like an assert:</p> <pre><code>def check(condition, msg=None): if not condition: raise ValueError(msg or '') check(gender in ('m', 'f')) if gender == 'm': greeting = 'Mr.' else: greeting = 'Ms.' </code></pre> <p>Going back to the original question, I'd claim that using an assert() or check() prior to the if/else logic is easier to read, safer, and more explicit:</p> <ul> <li>it tests the data quality first before starting to act on it -- this might be important if there are operators other than '==' in the if/else chain</li> <li>it separates the assertion test from the branching logic, rather than interleaving them -- this makes reading and refactoring easier</li> </ul>
3
2012-04-06T03:11:54Z
[ "python" ]
Detecting Retweets using computationally inexpensive Python hashing algorithms
815,313
<p>In order to be able to detect RT of a particular tweet, I plan to store hashes of each formatted tweet in the database.</p> <p>What hashing algorithm should I use. Cryptic is of course not essential. Just a minimal way of storing a data as something which can then be compared if it is the same, in an efficient way.</p> <p>My first attempt at this was by using md5 hashes. But I figured there can be hashing algorithms that are much more efficient, as security is not required.</p>
2
2009-05-02T18:17:58Z
815,315
<p>Python's shelve module? <a href="http://docs.python.org/library/shelve.html" rel="nofollow">http://docs.python.org/library/shelve.html</a></p>
0
2009-05-02T18:20:51Z
[ "python", "hash", "twitter", "md5" ]
Detecting Retweets using computationally inexpensive Python hashing algorithms
815,313
<p>In order to be able to detect RT of a particular tweet, I plan to store hashes of each formatted tweet in the database.</p> <p>What hashing algorithm should I use. Cryptic is of course not essential. Just a minimal way of storing a data as something which can then be compared if it is the same, in an efficient way.</p> <p>My first attempt at this was by using md5 hashes. But I figured there can be hashing algorithms that are much more efficient, as security is not required.</p>
2
2009-05-02T18:17:58Z
815,317
<p>Do you really need to hash at all? Twitter messages are short enough (and disk space cheap enough) that it may be better to just store the whole message, rather than eating up clock cycles to hash it.</p>
6
2009-05-02T18:21:12Z
[ "python", "hash", "twitter", "md5" ]
Detecting Retweets using computationally inexpensive Python hashing algorithms
815,313
<p>In order to be able to detect RT of a particular tweet, I plan to store hashes of each formatted tweet in the database.</p> <p>What hashing algorithm should I use. Cryptic is of course not essential. Just a minimal way of storing a data as something which can then be compared if it is the same, in an efficient way.</p> <p>My first attempt at this was by using md5 hashes. But I figured there can be hashing algorithms that are much more efficient, as security is not required.</p>
2
2009-05-02T18:17:58Z
815,321
<p>Well, tweets are only 140 characters long, so you could even store the entire tweet in the database...</p> <p>but if you really want to "hash" them somehow, a simple way would be to just take the sum of the ASCII values of all the characters in the tweet:</p> <pre><code>sum(ord(c) for c in tweet) </code></pre> <p>Of course, whenever you have a match of hashes, you should check the tweets themselves for sameness, because the probability of finding two tweets that give the same "sum-hash" is probably non-negligible.</p>
1
2009-05-02T18:22:41Z
[ "python", "hash", "twitter", "md5" ]
Detecting Retweets using computationally inexpensive Python hashing algorithms
815,313
<p>In order to be able to detect RT of a particular tweet, I plan to store hashes of each formatted tweet in the database.</p> <p>What hashing algorithm should I use. Cryptic is of course not essential. Just a minimal way of storing a data as something which can then be compared if it is the same, in an efficient way.</p> <p>My first attempt at this was by using md5 hashes. But I figured there can be hashing algorithms that are much more efficient, as security is not required.</p>
2
2009-05-02T18:17:58Z
815,381
<p>I echo Chris' comment about not using a hash at all (your database engine can hopefully index 140-character fields efficiently).</p> <p>If you did want to use a hash, MD5 would be my first choice as well (16 bytes), followed by SHA-1 (20 bytes).</p> <p>Whatever you do, don't use sum-of-characters. I can't immediately come up with a function that would have more collisions (all anagrams hash the same), plus it's slower!</p> <pre><code>$ python -m timeit -s 'from hashlib import md5' 'd=md5("There once was a man named Michael Finnegan.").digest()' 100000 loops, best of 3: 2.47 usec per loop $ python -m timeit 'd=sum(ord(c) for c in "There once was a man named Michael Finnegan.")' 100000 loops, best of 3: 13.9 usec per loop </code></pre>
2
2009-05-02T18:52:58Z
[ "python", "hash", "twitter", "md5" ]
Detecting Retweets using computationally inexpensive Python hashing algorithms
815,313
<p>In order to be able to detect RT of a particular tweet, I plan to store hashes of each formatted tweet in the database.</p> <p>What hashing algorithm should I use. Cryptic is of course not essential. Just a minimal way of storing a data as something which can then be compared if it is the same, in an efficient way.</p> <p>My first attempt at this was by using md5 hashes. But I figured there can be hashing algorithms that are much more efficient, as security is not required.</p>
2
2009-05-02T18:17:58Z
815,390
<p>I am not familiar with Python (sorry, Ruby guy typing here) however you could try a few things. </p> <p><strong>Assumptions:</strong> You will likely be storing hundreds of thousands of Tweets over time, so comparing one hash against "every record" in the table will be inefficient. Also, RTs are not always carbon copies of the original tweet. After all, the original author's name is usually included and takes up some of the 140 character limit. So perhaps you could use a solution that matches more accurately than a "dumb" hash?</p> <ol> <li><p><strong>Tagging &amp; Indexing</strong></p> <p>Tag and index the component parts of the message in a standard way. This could include treating hashed #...., at-marked @.... and URL strings as "tags". After removing noise words and punctuation, you could also treat the remaining words as tags too.</p></li> <li><p><strong>Fast Searching</strong></p> <p>Databases are terrible at finding multiple group membership very quickly (I'll assume your using either Mysql or Postgresql, which are terrible at this). Instead try one of the free text engines like <a href="http://www.sphinxsearch.com/" rel="nofollow">Sphinx Search</a>. They are very very fast at resolving multiple group membership (i.e. checking if keywords are present).</p> <p>Using Sphinx or similar, we search on all of the "tags" we extracted. This will probably return a smallish result set of "potential original Tweets". Then compare them one by one using similarity matching algorithm (here is one in Python <a href="http://code.google.com/p/pylevenshtein/" rel="nofollow">http://code.google.com/p/pylevenshtein/</a>)</p></li> </ol> <p>Now let me warmly welcome you to the world of <em>text mining</em>. </p> <p>Good luck!</p>
4
2009-05-02T18:57:56Z
[ "python", "hash", "twitter", "md5" ]
Detecting Retweets using computationally inexpensive Python hashing algorithms
815,313
<p>In order to be able to detect RT of a particular tweet, I plan to store hashes of each formatted tweet in the database.</p> <p>What hashing algorithm should I use. Cryptic is of course not essential. Just a minimal way of storing a data as something which can then be compared if it is the same, in an efficient way.</p> <p>My first attempt at this was by using md5 hashes. But I figured there can be hashing algorithms that are much more efficient, as security is not required.</p>
2
2009-05-02T18:17:58Z
817,731
<p>You are trying to hash a string right? Builtin types can be hashed right away, just do <code>hash("some string")</code> and you get some int. Its the same function python uses for dictonarys, so it is probably the best choice.</p>
0
2009-05-03T18:59:30Z
[ "python", "hash", "twitter", "md5" ]
Detecting Retweets using computationally inexpensive Python hashing algorithms
815,313
<p>In order to be able to detect RT of a particular tweet, I plan to store hashes of each formatted tweet in the database.</p> <p>What hashing algorithm should I use. Cryptic is of course not essential. Just a minimal way of storing a data as something which can then be compared if it is the same, in an efficient way.</p> <p>My first attempt at this was by using md5 hashes. But I figured there can be hashing algorithms that are much more efficient, as security is not required.</p>
2
2009-05-02T18:17:58Z
1,139,680
<p>There are a few issues here. First, RT's are not always identical. Some people add a comment. Others change the URL for tracking. Others add in the person that they are RT'ing (which may or may not be the originator).</p> <p>So if you are going to hash the tweet, you need to boil it down to the meat of the tweet, and only hash that. Good luck.</p> <p>Above, someone mentioned that with 32-bits, you will start having collisions at about 65K tweets. Of course, you could have collisions on tweet #2. But I think the author of that comment was confused, since 2^16 = ~65K, but 2^32 = ~4 Trillion. So you have a little more room there.</p> <p>A better algorithm might be to try to derive the "unique" parts of the tweet, and fingerprint it. It's not a hash, it's a fingerprint of a few key words that define uniqueness.</p>
2
2009-07-16T19:07:47Z
[ "python", "hash", "twitter", "md5" ]
Python imports from crossreferencing packages
815,367
<p>Currently I'm trying to write my first Python library and I've encountered the following problem:</p> <p>I have the following import in my package myapp.factories:</p> <pre><code>from myapp.models import * </code></pre> <p>And the following in my package myapp.models:</p> <pre><code>from myapp.factories import * </code></pre> <p>I need the models in my factories package but inside one model I also need one of the factories. If I now call the code that needs the factory I get the following error:</p> <pre><code>NameError: global name 'MyModelFactory' is not defined </code></pre> <p>I'm pretty sure it has something to do with the order in which the scripts are loaded but I can't seem to figure out how to get these crossreferences to work.</p>
0
2009-05-02T18:46:15Z
815,374
<p>"inside one model I also need one of the factories" - just import that factory where you need it:</p> <pre><code>class SomeModel: def some_method(self): from myapp.factories import SomeFactory SomeFactory().do_something() </code></pre>
5
2009-05-02T18:49:18Z
[ "python" ]
C# Web Server: Implementing a Dynamic Language
815,446
<p>I've just finished writing a web server in C#. Its pretty basic and only serves static content like html, xml, and images at the moment. I would like to implement a dynamic language, however. I'm trying to choose between one of the following:</p> <ul> <li>ASP.NET</li> <li>PHP</li> <li>Python</li> </ul> <p>I'd prefer to implement PHP or Python because I am much more familiar with those, however I would like to implement whichever might be easiest. How would I go about adding this functionality to my server, and which of the three languages would be the easiest to implement?</p> <p>EDIT: this is not about what language i want to do web programing in, this is about what language i want to let people who use the server program in. I would like to be able for the server to serve applications written in either asp.net, PHP or Python.</p>
0
2009-05-02T19:25:41Z
815,449
<p>ASP.NET will surely be the easiest as you can use all the built in classes. Essentially you don't need to build it, you just hook it up to the Web server (I don't know if we can count it as <em>writing</em> ASP.NET though ;) )</p> <p>You might want to look at <a href="http://blogs.msdn.com/dmitryr/archive/2006/03/09/548131.aspx" rel="nofollow">Cassini source code</a></p>
1
2009-05-02T19:26:54Z
[ "php", "asp.net", "python", "webserver" ]
C# Web Server: Implementing a Dynamic Language
815,446
<p>I've just finished writing a web server in C#. Its pretty basic and only serves static content like html, xml, and images at the moment. I would like to implement a dynamic language, however. I'm trying to choose between one of the following:</p> <ul> <li>ASP.NET</li> <li>PHP</li> <li>Python</li> </ul> <p>I'd prefer to implement PHP or Python because I am much more familiar with those, however I would like to implement whichever might be easiest. How would I go about adding this functionality to my server, and which of the three languages would be the easiest to implement?</p> <p>EDIT: this is not about what language i want to do web programing in, this is about what language i want to let people who use the server program in. I would like to be able for the server to serve applications written in either asp.net, PHP or Python.</p>
0
2009-05-02T19:25:41Z
815,457
<p>Have you considered boo? It has a very configurable compiler and there are some good OSS examples out there (for example the brail view engine for Monorail &amp; ASP.NET MVC).</p>
1
2009-05-02T19:31:51Z
[ "php", "asp.net", "python", "webserver" ]
C# Web Server: Implementing a Dynamic Language
815,446
<p>I've just finished writing a web server in C#. Its pretty basic and only serves static content like html, xml, and images at the moment. I would like to implement a dynamic language, however. I'm trying to choose between one of the following:</p> <ul> <li>ASP.NET</li> <li>PHP</li> <li>Python</li> </ul> <p>I'd prefer to implement PHP or Python because I am much more familiar with those, however I would like to implement whichever might be easiest. How would I go about adding this functionality to my server, and which of the three languages would be the easiest to implement?</p> <p>EDIT: this is not about what language i want to do web programing in, this is about what language i want to let people who use the server program in. I would like to be able for the server to serve applications written in either asp.net, PHP or Python.</p>
0
2009-05-02T19:25:41Z
815,491
<p>Perhaps you should take a look at <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython" rel="nofollow">IronPython</a>.</p>
0
2009-05-02T19:56:27Z
[ "php", "asp.net", "python", "webserver" ]
C# Web Server: Implementing a Dynamic Language
815,446
<p>I've just finished writing a web server in C#. Its pretty basic and only serves static content like html, xml, and images at the moment. I would like to implement a dynamic language, however. I'm trying to choose between one of the following:</p> <ul> <li>ASP.NET</li> <li>PHP</li> <li>Python</li> </ul> <p>I'd prefer to implement PHP or Python because I am much more familiar with those, however I would like to implement whichever might be easiest. How would I go about adding this functionality to my server, and which of the three languages would be the easiest to implement?</p> <p>EDIT: this is not about what language i want to do web programing in, this is about what language i want to let people who use the server program in. I would like to be able for the server to serve applications written in either asp.net, PHP or Python.</p>
0
2009-05-02T19:25:41Z
815,511
<p>Well it would appear you are doing this as a learning experience, after all Microsoft already provides a web server for Windows (IIS).</p> <p>Similary PHP has already been ported to <a href="http://www.php.net/downloads.php" rel="nofollow">Windows</a>, you could use that port directly. SImilary you could use it as a "reference implimentation" and write your own implimentation of PHP for windows.</p> <p>Either way, it would then permit your web server to host lots of existing applications such as Wordpress etc.</p>
0
2009-05-02T20:09:30Z
[ "php", "asp.net", "python", "webserver" ]
C# Web Server: Implementing a Dynamic Language
815,446
<p>I've just finished writing a web server in C#. Its pretty basic and only serves static content like html, xml, and images at the moment. I would like to implement a dynamic language, however. I'm trying to choose between one of the following:</p> <ul> <li>ASP.NET</li> <li>PHP</li> <li>Python</li> </ul> <p>I'd prefer to implement PHP or Python because I am much more familiar with those, however I would like to implement whichever might be easiest. How would I go about adding this functionality to my server, and which of the three languages would be the easiest to implement?</p> <p>EDIT: this is not about what language i want to do web programing in, this is about what language i want to let people who use the server program in. I would like to be able for the server to serve applications written in either asp.net, PHP or Python.</p>
0
2009-05-02T19:25:41Z
815,550
<p>If you implement a cgi interface, you could use any kind of backend language. If you want to get fancy, you could consider looking into fastcgi.</p>
1
2009-05-02T20:28:46Z
[ "php", "asp.net", "python", "webserver" ]
How to use subversion Ctypes Python Bindings?
815,530
<p>Subversion 1.6 introduce something that is called 'Ctypes Python Binding', but it is not documented. Is it any information available what this bindings are and how to use it? For example, i have a fresh windows XP and want to control SVN repository using subversiion 1.6 and this mysterious python bindings. What exactly i need to download/install/compile in order to do something like</p> <pre><code>import svn from almighty_ctype_subversion_bindings svn.get( "\\rep\\project" ) </code></pre> <p>And how is this connected to pysvn project? Is this a same technology, or different technologies?</p>
4
2009-05-02T20:18:33Z
815,568
<p>The whole point of ctypes is that you shouldn't need to have to compile anything anywhere. That said, the readme for the bindings mentions some dependencies and a build step.</p> <p>The bindings can be found in the Subversion source distribution at least, in <code>subversion/bindings/ctypes-python/</code>, with a distutils setup.py.</p> <p>They seem to be a successor / alternative of sorts to pysvn.</p>
0
2009-05-02T20:41:22Z
[ "python", "svn" ]
How to use subversion Ctypes Python Bindings?
815,530
<p>Subversion 1.6 introduce something that is called 'Ctypes Python Binding', but it is not documented. Is it any information available what this bindings are and how to use it? For example, i have a fresh windows XP and want to control SVN repository using subversiion 1.6 and this mysterious python bindings. What exactly i need to download/install/compile in order to do something like</p> <pre><code>import svn from almighty_ctype_subversion_bindings svn.get( "\\rep\\project" ) </code></pre> <p>And how is this connected to pysvn project? Is this a same technology, or different technologies?</p>
4
2009-05-02T20:18:33Z
815,711
<p>I looked into the python binding for subversion, but in the end I found it to be simpler to just invoke svn.exe like this:</p> <pre><code>(stdout, stderr, err) = execute('svn export "%s" "%s"' \ % (exportURL, workingCopyFolder)) </code></pre> <p>where <code>execute</code> is a function like this:</p> <pre><code>def execute(cmd): import subprocess proc = subprocess.Popen(\ cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = proc.communicate() return (stdout, stderr, proc.returncode) </code></pre> <p>The output of svn.exe is designed to be easily parsed if necessary. There is even a --xml output option.</p>
-1
2009-05-02T21:54:00Z
[ "python", "svn" ]
How to use subversion Ctypes Python Bindings?
815,530
<p>Subversion 1.6 introduce something that is called 'Ctypes Python Binding', but it is not documented. Is it any information available what this bindings are and how to use it? For example, i have a fresh windows XP and want to control SVN repository using subversiion 1.6 and this mysterious python bindings. What exactly i need to download/install/compile in order to do something like</p> <pre><code>import svn from almighty_ctype_subversion_bindings svn.get( "\\rep\\project" ) </code></pre> <p>And how is this connected to pysvn project? Is this a same technology, or different technologies?</p>
4
2009-05-02T20:18:33Z
841,995
<p>You need the Subversion source distribution, Python (>= 2.5), and <a href="http://code.google.com/p/ctypesgen/" rel="nofollow">ctypesgen</a>.</p> <p>Instructions for building the ctypes bindings are <a href="http://svn.apache.org/repos/asf/subversion/trunk/subversion/bindings/ctypes-python/README" rel="nofollow">here</a>.</p> <p>You will end up with a package called <code>csvn</code>, examples of it's use are <a href="http://svn.apache.org/repos/asf/subversion/trunk/subversion/bindings/ctypes-python/examples/" rel="nofollow">here</a>.</p>
1
2009-05-08T21:54:54Z
[ "python", "svn" ]
How do you remove html tags using Universal Feed Parser?
815,606
<p>The documentation lists the tags that are allowed/removed by default:</p> <p><a href="http://www.feedparser.org/docs/html-sanitization.html" rel="nofollow">http://www.feedparser.org/docs/html-sanitization.html</a></p> <p>But it doesn't say anything about how you can specify which additional tags you want removed.</p> <p>Is there a way to do this using Universal Feed Parser or do you have to do further processing using your own regex and/or something like Beautiful Soup?</p>
3
2009-05-02T21:01:15Z
815,681
<p>i took a quick look over the code and i don't think there is a way to overwrite them directly. But you can overwrite <code>feedparser._HTMLSanitizer.acceptable_elements</code>, the list of tags that wont get removed before doing <code>feedparser.parse</code></p>
5
2009-05-02T21:34:41Z
[ "python", "django", "feeds", "parsing" ]
callable as instancemethod?
815,947
<p>Let's say we've got a metaclass <code>CallableWrappingMeta</code> which walks the body of a new class, wrapping its methods with a class, <code>InstanceMethodWrapper</code>:</p> <pre><code>import types class CallableWrappingMeta(type): def __new__(mcls, name, bases, cls_dict): for k, v in cls_dict.iteritems(): if isinstance(v, types.FunctionType): cls_dict[k] = InstanceMethodWrapper(v) return type.__new__(mcls, name, bases, cls_dict) class InstanceMethodWrapper(object): def __init__(self, method): self.method = method def __call__(self, *args, **kw): print "InstanceMethodWrapper.__call__( %s, *%r, **%r )" % (self, args, kw) return self.method(*args, **kw) class Bar(object): __metaclass__ = CallableWrappingMeta def __init__(self): print 'bar!' </code></pre> <p>Our dummy wrapper just prints the arguments as they come in. But you'll notice something conspicuous: the method isn't passed the instance-object receiver, because even though <code>InstanceMethodWrapper</code> is callable, it is not treated as a function for the purpose of being converted to an instance method during class creation (after our metaclass is done with it).</p> <p>A potential solution is to use a decorator instead of a class to wrap the methods -- that function will become an instance method. But in the real world, <code>InstanceMethodWrapper</code> is much more complex: it provides an API and publishes method-call events. A class is more convenient (and more performant, not that this matters much).</p> <p>I also tried some dead-ends. Subclassing <code>types.MethodType</code> and <code>types.UnboundMethodType</code> didn't go anywhere. A little introspection, and it appears they decend from <code>type</code>. So I tried using both as a metaclass, but no luck there either. It might be the case that they have special demands as a metaclass, but it seems we're in undocumented territory at this point.</p> <p>Any ideas?</p>
2
2009-05-02T23:58:32Z
815,982
<p><strong>Edit</strong>: I lie yet again. The <code>__?attr__</code> attributes on functions are readonly, but apparently do not always throw an <code>AttributeException</code> exception when you assign? I dunno. Back to square one!</p> <p><strong>Edit</strong>: This doesn't actually solve the problem, as the wrapping function won't proxy attribute requests to the <code>InstanceMethodWrapper</code>. I could, of course, duck-punch the <code>__?attr__</code> attributes in the decorator--and it is what I'm doing now--but that's ugly. Better ideas are very welcome.</p> <p><hr /></p> <p>Of course, I immediately realized that combining a simple decorator with our classes will do the trick:</p> <pre><code>def methodize(method, callable): "Circumvents the fact that callables are not converted to instance methods." @wraps(method) def wrapper(*args, **kw): return wrapper._callable(*args, **kw) wrapper._callable = callable return wrapper </code></pre> <p>Then you add the decorator to the call to <code>InstanceMethodWrapper</code> in the metaclass:</p> <pre><code>cls_dict[k] = methodize(v, InstanceMethodWrapper(v)) </code></pre> <p>Poof. A little oblique, but it works.</p>
0
2009-05-03T00:26:02Z
[ "python", "metaclass" ]
callable as instancemethod?
815,947
<p>Let's say we've got a metaclass <code>CallableWrappingMeta</code> which walks the body of a new class, wrapping its methods with a class, <code>InstanceMethodWrapper</code>:</p> <pre><code>import types class CallableWrappingMeta(type): def __new__(mcls, name, bases, cls_dict): for k, v in cls_dict.iteritems(): if isinstance(v, types.FunctionType): cls_dict[k] = InstanceMethodWrapper(v) return type.__new__(mcls, name, bases, cls_dict) class InstanceMethodWrapper(object): def __init__(self, method): self.method = method def __call__(self, *args, **kw): print "InstanceMethodWrapper.__call__( %s, *%r, **%r )" % (self, args, kw) return self.method(*args, **kw) class Bar(object): __metaclass__ = CallableWrappingMeta def __init__(self): print 'bar!' </code></pre> <p>Our dummy wrapper just prints the arguments as they come in. But you'll notice something conspicuous: the method isn't passed the instance-object receiver, because even though <code>InstanceMethodWrapper</code> is callable, it is not treated as a function for the purpose of being converted to an instance method during class creation (after our metaclass is done with it).</p> <p>A potential solution is to use a decorator instead of a class to wrap the methods -- that function will become an instance method. But in the real world, <code>InstanceMethodWrapper</code> is much more complex: it provides an API and publishes method-call events. A class is more convenient (and more performant, not that this matters much).</p> <p>I also tried some dead-ends. Subclassing <code>types.MethodType</code> and <code>types.UnboundMethodType</code> didn't go anywhere. A little introspection, and it appears they decend from <code>type</code>. So I tried using both as a metaclass, but no luck there either. It might be the case that they have special demands as a metaclass, but it seems we're in undocumented territory at this point.</p> <p>Any ideas?</p>
2
2009-05-02T23:58:32Z
816,072
<p>I'm guessing you are trying to make a metaclass that wraps every method in the class with a custom function.</p> <p>Here is my version which I think is a little bit less oblique.</p> <pre><code>import types class CallableWrappingMeta(type): def __new__(mcls, name, bases, cls_dict): instance = type.__new__(mcls, name, bases, cls_dict) for k in dir(instance): v = getattr(instance, k) if isinstance(v, types.MethodType): setattr(instance, k, instanceMethodWrapper(v)) return instance def instanceMethodWrapper(function): def customfunc(*args, **kw): print "instanceMethodWrapper(*%r, **%r )" % (args, kw) return function(*args, **kw) return customfunc class Bar(object): __metaclass__ = CallableWrappingMeta def method(self, a, b): print a,b a = Bar() a.method("foo","bar") </code></pre>
0
2009-05-03T01:41:18Z
[ "python", "metaclass" ]
callable as instancemethod?
815,947
<p>Let's say we've got a metaclass <code>CallableWrappingMeta</code> which walks the body of a new class, wrapping its methods with a class, <code>InstanceMethodWrapper</code>:</p> <pre><code>import types class CallableWrappingMeta(type): def __new__(mcls, name, bases, cls_dict): for k, v in cls_dict.iteritems(): if isinstance(v, types.FunctionType): cls_dict[k] = InstanceMethodWrapper(v) return type.__new__(mcls, name, bases, cls_dict) class InstanceMethodWrapper(object): def __init__(self, method): self.method = method def __call__(self, *args, **kw): print "InstanceMethodWrapper.__call__( %s, *%r, **%r )" % (self, args, kw) return self.method(*args, **kw) class Bar(object): __metaclass__ = CallableWrappingMeta def __init__(self): print 'bar!' </code></pre> <p>Our dummy wrapper just prints the arguments as they come in. But you'll notice something conspicuous: the method isn't passed the instance-object receiver, because even though <code>InstanceMethodWrapper</code> is callable, it is not treated as a function for the purpose of being converted to an instance method during class creation (after our metaclass is done with it).</p> <p>A potential solution is to use a decorator instead of a class to wrap the methods -- that function will become an instance method. But in the real world, <code>InstanceMethodWrapper</code> is much more complex: it provides an API and publishes method-call events. A class is more convenient (and more performant, not that this matters much).</p> <p>I also tried some dead-ends. Subclassing <code>types.MethodType</code> and <code>types.UnboundMethodType</code> didn't go anywhere. A little introspection, and it appears they decend from <code>type</code>. So I tried using both as a metaclass, but no luck there either. It might be the case that they have special demands as a metaclass, but it seems we're in undocumented territory at this point.</p> <p>Any ideas?</p>
2
2009-05-02T23:58:32Z
817,108
<p>I think you need to be more specific about your problem. The original question talks about wrapping a function, but your subsequent answer seems to talk about preserving function attributes, which seems to be a new factor. If you spelled out your design goals more clearly, it might be easier to answer your question.</p>
0
2009-05-03T13:53:23Z
[ "python", "metaclass" ]
callable as instancemethod?
815,947
<p>Let's say we've got a metaclass <code>CallableWrappingMeta</code> which walks the body of a new class, wrapping its methods with a class, <code>InstanceMethodWrapper</code>:</p> <pre><code>import types class CallableWrappingMeta(type): def __new__(mcls, name, bases, cls_dict): for k, v in cls_dict.iteritems(): if isinstance(v, types.FunctionType): cls_dict[k] = InstanceMethodWrapper(v) return type.__new__(mcls, name, bases, cls_dict) class InstanceMethodWrapper(object): def __init__(self, method): self.method = method def __call__(self, *args, **kw): print "InstanceMethodWrapper.__call__( %s, *%r, **%r )" % (self, args, kw) return self.method(*args, **kw) class Bar(object): __metaclass__ = CallableWrappingMeta def __init__(self): print 'bar!' </code></pre> <p>Our dummy wrapper just prints the arguments as they come in. But you'll notice something conspicuous: the method isn't passed the instance-object receiver, because even though <code>InstanceMethodWrapper</code> is callable, it is not treated as a function for the purpose of being converted to an instance method during class creation (after our metaclass is done with it).</p> <p>A potential solution is to use a decorator instead of a class to wrap the methods -- that function will become an instance method. But in the real world, <code>InstanceMethodWrapper</code> is much more complex: it provides an API and publishes method-call events. A class is more convenient (and more performant, not that this matters much).</p> <p>I also tried some dead-ends. Subclassing <code>types.MethodType</code> and <code>types.UnboundMethodType</code> didn't go anywhere. A little introspection, and it appears they decend from <code>type</code>. So I tried using both as a metaclass, but no luck there either. It might be the case that they have special demands as a metaclass, but it seems we're in undocumented territory at this point.</p> <p>Any ideas?</p>
2
2009-05-02T23:58:32Z
817,815
<p>Just enrich you <code>InstanceMethodWrapper</code> class with a <code>__get__</code> (which can perfectly well just <code>return self</code>) -- that is, make that class into a <em>descriptor</em> type, so that its instances are descriptor objects. See <a href="http://users.rcn.com/python/download/Descriptor.htm" rel="nofollow">http://users.rcn.com/python/download/Descriptor.htm</a> for background and details.</p> <p>BTW, if you're on Python 2.6 or better, consider using a class-decorator instead of that metaclass -- we added class decorators exactly because so many metaclasses were being used just for such decoration purposes, and decorators are really much simpler to use.</p>
3
2009-05-03T19:37:57Z
[ "python", "metaclass" ]
Python, SimPy: How to generate a value from a triangular probability distribution?
815,969
<p>I want to run a simulation that uses as parameter a value generated from a triangular probability distribution with lower limit A, mode B and and upper limit C. How can I generate this value in Python? Is there something as simple as expovariate(lambda) (from random) for this distribution or do I have to code this thing?</p>
6
2009-05-03T00:14:53Z
815,994
<p>If you download the NumPy package, it has a function numpy.random.triangular(left, mode, right[, size]) that does exactly what you are looking for.</p>
6
2009-05-03T00:30:52Z
[ "python", "distribution", "probability", "simpy" ]
Python, SimPy: How to generate a value from a triangular probability distribution?
815,969
<p>I want to run a simulation that uses as parameter a value generated from a triangular probability distribution with lower limit A, mode B and and upper limit C. How can I generate this value in Python? Is there something as simple as expovariate(lambda) (from random) for this distribution or do I have to code this thing?</p>
6
2009-05-03T00:14:53Z
816,185
<p>Since, I was checking random's documentation from Python 2.4 I missed this:</p> <p><strong><em>random.triangular(low, high, mode)</strong>¶ Return a random floating point number N such that low &lt;= N &lt;= high and with the specified mode between those bounds. The low and high bounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution. <strong>New in version 2.6</strong>.</em></p>
3
2009-05-03T02:55:44Z
[ "python", "distribution", "probability", "simpy" ]
Python, SimPy: How to generate a value from a triangular probability distribution?
815,969
<p>I want to run a simulation that uses as parameter a value generated from a triangular probability distribution with lower limit A, mode B and and upper limit C. How can I generate this value in Python? Is there something as simple as expovariate(lambda) (from random) for this distribution or do I have to code this thing?</p>
6
2009-05-03T00:14:53Z
923,105
<p>Let's say that your distribution wasn't handled by NumPy or the Python Standard Library.</p> <p>In situations where performance is not very important, rejection sampling is a useful hack for getting draws from a distribution you don't have using one you do have.</p> <p>For your triangular distribution, you could do something like</p> <pre><code>from random import random, uniform def random_triangular(low, high, mode): while True: proposal = uniform(low, high) if proposal &lt; mode: acceptance_prob = (proposal - low) / (mode - low) else: acceptance_prob = (high - proposal) / (high - mode) if random() &lt; acceptance_prob: break return proposal </code></pre> <p>You can plot some samples</p> <pre><code>pylab.hist([random_triangular(1, 6, 5) for t in range(10000)]) </code></pre> <p>to make sure that everything looks okay.</p>
2
2009-05-28T20:49:34Z
[ "python", "distribution", "probability", "simpy" ]
Scientific Plotting in Python
816,086
<p>I have a large data set of tuples containing (time of event, latitude, longitude) that I need to visualize. I was hoping to generate a 'movie'-like xy-plot, but was wondering if anyone has a better idea or if there is an easy way to do this in Python?</p> <p>Thanks in advance for the help, --Leo</p>
8
2009-05-03T01:53:32Z
816,115
<p>get <a href="http://matplotlib.sourceforge.net" rel="nofollow">matplotlib</a></p>
16
2009-05-03T02:14:07Z
[ "python", "visualization", "plot", "scientific-computing" ]
Scientific Plotting in Python
816,086
<p>I have a large data set of tuples containing (time of event, latitude, longitude) that I need to visualize. I was hoping to generate a 'movie'-like xy-plot, but was wondering if anyone has a better idea or if there is an easy way to do this in Python?</p> <p>Thanks in advance for the help, --Leo</p>
8
2009-05-03T01:53:32Z
816,325
<p>I have had reasonable success with Python applications generating SVG with animation features embedded, but this was with a smaller set of elements than what you probably have. For example, if your data is about a seismic event, show a circle that shows up when the event happened and grows in size matching the magnitude of the event. A moving indicator over a timeline is really simple to add.</p> <p><a href="http://www.kevlindev.com/samples/kaleidoscope/kaleidoscope.svg" rel="nofollow">Kaleidoscope</a> (Opera, others maybe, Safari not) shows lots of pieces moving around and I found inspirational. Lots of other good SVG tutorial content on the site too.</p>
0
2009-05-03T04:23:53Z
[ "python", "visualization", "plot", "scientific-computing" ]
Scientific Plotting in Python
816,086
<p>I have a large data set of tuples containing (time of event, latitude, longitude) that I need to visualize. I was hoping to generate a 'movie'-like xy-plot, but was wondering if anyone has a better idea or if there is an easy way to do this in Python?</p> <p>Thanks in advance for the help, --Leo</p>
8
2009-05-03T01:53:32Z
816,381
<p>You might want to look at <a href="http://pyqwt.sourceforge.net/" rel="nofollow">PyQwt</a>. It's a plotting library which works with Qt/PyQt. </p> <p>Several of the PyQwt examples (in the qt4examples directory) show how to create "moving" / dynamically changing plots -- look at <code>CPUplot.py</code>, <code>MapDemo.py</code>, <code>DataDemo.py</code>. </p>
0
2009-05-03T05:06:05Z
[ "python", "visualization", "plot", "scientific-computing" ]
Scientific Plotting in Python
816,086
<p>I have a large data set of tuples containing (time of event, latitude, longitude) that I need to visualize. I was hoping to generate a 'movie'-like xy-plot, but was wondering if anyone has a better idea or if there is an easy way to do this in Python?</p> <p>Thanks in advance for the help, --Leo</p>
8
2009-05-03T01:53:32Z
817,418
<p>I'd try rpy. All the power of R, from within python. <a href="http://rpy.sourceforge.net/" rel="nofollow">http://rpy.sourceforge.net/</a></p> <p>rpy is awesome.</p> <p>Check out the CRAN library for animations, <a href="http://cran.r-project.org/web/packages/animation/index.html" rel="nofollow">http://cran.r-project.org/web/packages/animation/index.html</a></p> <p>Of course, you have to learn a bit about R to do this, but if you're planning to do this kind of thing routinely in future it will be well worth your while to learn.</p>
4
2009-05-03T16:18:16Z
[ "python", "visualization", "plot", "scientific-computing" ]
Scientific Plotting in Python
816,086
<p>I have a large data set of tuples containing (time of event, latitude, longitude) that I need to visualize. I was hoping to generate a 'movie'-like xy-plot, but was wondering if anyone has a better idea or if there is an easy way to do this in Python?</p> <p>Thanks in advance for the help, --Leo</p>
8
2009-05-03T01:53:32Z
817,465
<p>Enthought's <a href="http://code.enthought.com/chaco/" rel="nofollow">Chaco</a> is designed for interactive/updating plots. the api and such takes a little while to get use to, but once you're there it's a fantastic framework to work with.</p>
2
2009-05-03T16:46:34Z
[ "python", "visualization", "plot", "scientific-computing" ]
Scientific Plotting in Python
816,086
<p>I have a large data set of tuples containing (time of event, latitude, longitude) that I need to visualize. I was hoping to generate a 'movie'-like xy-plot, but was wondering if anyone has a better idea or if there is an easy way to do this in Python?</p> <p>Thanks in advance for the help, --Leo</p>
8
2009-05-03T01:53:32Z
936,193
<p>If you are interested in scientific plotting using Python then have a look at Mlab: <a href="http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html" rel="nofollow">http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html</a></p> <p>It allows you to plot 2d / 3d and animate your data and the quality of the charts is really high. </p>
3
2009-06-01T18:56:25Z
[ "python", "visualization", "plot", "scientific-computing" ]
Scientific Plotting in Python
816,086
<p>I have a large data set of tuples containing (time of event, latitude, longitude) that I need to visualize. I was hoping to generate a 'movie'-like xy-plot, but was wondering if anyone has a better idea or if there is an easy way to do this in Python?</p> <p>Thanks in advance for the help, --Leo</p>
8
2009-05-03T01:53:32Z
936,552
<p>The easiest option is matplotlib. Two particular solutions that might work for you are:</p> <p>1) You can generate a series of plots, each a snapshot at a given time. These can either be displayed as a dynamic plot in matplotlib, where the axes stay the same and the data moves around; or you can save the series of plots to separate files and later combine them to make a movie (using a separate application). There a number of examples in the official examples for doing these things.</p> <p>2) A simple scatter plot, where the colors of the circles changes with time might work well for your data. This is super easy. See <a href="http://matplotlib.sourceforge.net/examples/pylab_examples/ellipse_collection.html" rel="nofollow">this</a>, for example, which produces this figure <img src="http://matplotlib.sourceforge.net/plot_directive/mpl_examples/pylab_examples/ellipse_collection.hires.png" alt="alt text"></p>
8
2009-06-01T20:17:06Z
[ "python", "visualization", "plot", "scientific-computing" ]
What's a good way to mix RSS feeds using Python?
816,118
<p>SimplePie lets you merge feeds together:</p> <p><a href="http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date" rel="nofollow">http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date</a></p> <p>Is there anything like this in the Python world? The Universal Feed Parser documentation doesn't say anything about merging multiple feeds together.</p>
1
2009-05-03T02:15:47Z
816,216
<p><a href="http://github.com/dustin/snippets/blob/master/python/net/http/combiner.py" rel="nofollow">This</a> may be a good start for you. I wrote it a long time ago for one very specific combination, but I don't think I wrote it <em>too</em> specifically for my needs.</p>
2
2009-05-03T03:12:42Z
[ "python", "django", "rss", "feeds", "parsing" ]
What's a good way to mix RSS feeds using Python?
816,118
<p>SimplePie lets you merge feeds together:</p> <p><a href="http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date" rel="nofollow">http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date</a></p> <p>Is there anything like this in the Python world? The Universal Feed Parser documentation doesn't say anything about merging multiple feeds together.</p>
1
2009-05-03T02:15:47Z
816,268
<p>&nbsp;<a href="http://www.planetplanet.org/" rel="nofollow">Planet is a feed aggregator written in Python. Its development is basically dead, but the code lives on in several forks, including Planet Venus</a>.</p>
1
2009-05-03T03:34:07Z
[ "python", "django", "rss", "feeds", "parsing" ]
What's a good way to mix RSS feeds using Python?
816,118
<p>SimplePie lets you merge feeds together:</p> <p><a href="http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date" rel="nofollow">http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date</a></p> <p>Is there anything like this in the Python world? The Universal Feed Parser documentation doesn't say anything about merging multiple feeds together.</p>
1
2009-05-03T02:15:47Z
816,553
<p>I'm using Yahoo pipes for that task. It's a set a very powerful tools. I havo pipes join feeds based on certain criteria, and have it generate a compliant rss feed that i then process with universal feed parser.</p>
0
2009-05-03T08:04:19Z
[ "python", "django", "rss", "feeds", "parsing" ]
What's a good way to mix RSS feeds using Python?
816,118
<p>SimplePie lets you merge feeds together:</p> <p><a href="http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date" rel="nofollow">http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date</a></p> <p>Is there anything like this in the Python world? The Universal Feed Parser documentation doesn't say anything about merging multiple feeds together.</p>
1
2009-05-03T02:15:47Z
817,637
<p><strong><a href="http://atomisator.ziade.org/" rel="nofollow">Atomisator</a></strong> is a data aggregator framework. Its purpose is to provide an engine to build any kind of data by merging several sources of data. It was developed as an example application in the book Expert Python Programming. You can use different In- and Output Formats. An RSS aggregartor is part of the examples.</p>
1
2009-05-03T18:08:20Z
[ "python", "django", "rss", "feeds", "parsing" ]
What is wrong with this SimPy installation?
816,156
<p>Alright, I have tried a bunch of times the </p> <pre><code>python setup.py install </code></pre> <p>command from my command prompt, and this is what I'm getting:</p> <p><a href="http://yfrog.com/5ofallasimpyp" rel="nofollow">SCREEN</a></p> <p>And when trying this:</p> <pre><code>from SimPy.Simulation import * </code></pre> <p>on Idle, I get this:</p> <pre><code>Traceback (most recent call last): File "C:/Python30/pruebas/prueba1", line 1, in &lt;module&gt; from SimPy.Simulation import * File "C:\Python30\SimPy\Simulation.py", line 320 print 'SimPy.Simulation %s' %__version__, ^ SyntaxError: invalid syntax &gt;&gt;&gt; </code></pre>
0
2009-05-03T02:36:53Z
816,167
<p>Not every module supports python 3 - in fact, 90% or more of the modules are for 2.x now.</p> <p>you should use 2.5 or 2.6 for this module, or find a simpy that is compatible with 3.0.</p> <p>you can also run the 2->3 upgrade script to modify your simpy source, but I don't suggest doing that.</p>
2
2009-05-03T02:41:19Z
[ "python", "windows", "installation", "simpy" ]
What is wrong with this SimPy installation?
816,156
<p>Alright, I have tried a bunch of times the </p> <pre><code>python setup.py install </code></pre> <p>command from my command prompt, and this is what I'm getting:</p> <p><a href="http://yfrog.com/5ofallasimpyp" rel="nofollow">SCREEN</a></p> <p>And when trying this:</p> <pre><code>from SimPy.Simulation import * </code></pre> <p>on Idle, I get this:</p> <pre><code>Traceback (most recent call last): File "C:/Python30/pruebas/prueba1", line 1, in &lt;module&gt; from SimPy.Simulation import * File "C:\Python30\SimPy\Simulation.py", line 320 print 'SimPy.Simulation %s' %__version__, ^ SyntaxError: invalid syntax &gt;&gt;&gt; </code></pre>
0
2009-05-03T02:36:53Z
2,946,419
<p>I have a similar error, and I Installed python 2.6.4, so I don't think you can solve your problem using an older version of python.</p> <pre><code>alumno@ubuntu:/usr/local/SimPy/SimPy$ python carro.py Traceback (most recent call last): File "carro.py", line 2, in &lt;module&gt; from SimPy.Simulation import * ImportError: No module named SimPy.Simulation </code></pre> <p>Python 2.6.4rc2 (r264rc2:75497, Oct 20 2009, 02:55:11) [GCC 4.4.1] on linux2</p>
0
2010-05-31T23:18:22Z
[ "python", "windows", "installation", "simpy" ]
What is wrong with this SimPy installation?
816,156
<p>Alright, I have tried a bunch of times the </p> <pre><code>python setup.py install </code></pre> <p>command from my command prompt, and this is what I'm getting:</p> <p><a href="http://yfrog.com/5ofallasimpyp" rel="nofollow">SCREEN</a></p> <p>And when trying this:</p> <pre><code>from SimPy.Simulation import * </code></pre> <p>on Idle, I get this:</p> <pre><code>Traceback (most recent call last): File "C:/Python30/pruebas/prueba1", line 1, in &lt;module&gt; from SimPy.Simulation import * File "C:\Python30\SimPy\Simulation.py", line 320 print 'SimPy.Simulation %s' %__version__, ^ SyntaxError: invalid syntax &gt;&gt;&gt; </code></pre>
0
2009-05-03T02:36:53Z
22,529,526
<p>Refer point 4 of: <a href="http://pythonhosted.org/SimPy/Manuals/INSTALLATION.html" rel="nofollow">http://pythonhosted.org/SimPy/Manuals/INSTALLATION.html</a> for a workaround. It worked for me.</p> <p>simpy package does not seem to have same classes as SimPy by using pip install SimPy command, simpy gets installed.</p> <p>Hence, just download the SimPy package from the link and copy it to your classpath for python. </p>
0
2014-03-20T10:07:02Z
[ "python", "windows", "installation", "simpy" ]
What is wrong with this SimPy installation?
816,156
<p>Alright, I have tried a bunch of times the </p> <pre><code>python setup.py install </code></pre> <p>command from my command prompt, and this is what I'm getting:</p> <p><a href="http://yfrog.com/5ofallasimpyp" rel="nofollow">SCREEN</a></p> <p>And when trying this:</p> <pre><code>from SimPy.Simulation import * </code></pre> <p>on Idle, I get this:</p> <pre><code>Traceback (most recent call last): File "C:/Python30/pruebas/prueba1", line 1, in &lt;module&gt; from SimPy.Simulation import * File "C:\Python30\SimPy\Simulation.py", line 320 print 'SimPy.Simulation %s' %__version__, ^ SyntaxError: invalid syntax &gt;&gt;&gt; </code></pre>
0
2009-05-03T02:36:53Z
25,465,903
<p>There is nothing wrong with your Python installation. SimPy 1 and SimPy 2 use remarkably different syntax from SimPy 3, which is the version that you have installed - and the one which is widely available. The old tutorials are all written in view of the old SimPy versions. Checkout this page...</p> <p><a href="http://simpy.readthedocs.org/en/latest/simpy_intro/installation.html" rel="nofollow">http://simpy.readthedocs.org/en/latest/simpy_intro/installation.html</a></p>
0
2014-08-23T20:07:07Z
[ "python", "windows", "installation", "simpy" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
816,217
<p>I suspect the basic reason is a combination of security and reliability. You don't want someone to be easily able to hack the phone, and you want to have some control over what's being installed.</p>
0
2009-05-03T03:13:13Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
816,219
<p>Jailbroken iPhones can have python installed, and I actually use python very frequently on mine. </p>
1
2009-05-03T03:15:14Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
816,225
<p>I think that performance concerns may be part of, but not all of, the reason. Mobile devices do not have very powerful hardware to work with.</p> <p>I am partly unsure about this, though.</p>
1
2009-05-03T03:17:37Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
816,228
<p>Memory is also a significant factor. It's easy to eat memory in Python, unfortunately.</p>
0
2009-05-03T03:20:08Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
816,233
<p>One of the most pressing matters is garbage collection. Garbage collection often times introduce unpredictable pauses in embedded machines which sometimes need real time performance.</p> <p>This is why there is a Java Micro Edition which has a different garbage collector which reduces pauses in exchange for a slower program.</p> <p>Refcounting garbage collectors (like the one in CPython) are also less prone to pauses but can explode when data with many nested pointers (like a linked list) get deleted.</p>
1
2009-05-03T03:21:07Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
816,248
<p>In general it's all of these things. Memory, speed, and probably most importantly programmer familiarity. Apple has a huge investment in Objective C, Java is known by basically everyone, and C# is very popular as well. If you're trying for mass programmer appeal it makes sense to start with something popular, even if it's sort of boring.</p> <p>There aren't really any technical requirements stopping it. We could write a whole Ruby stack and let the programmer re-implement the slow bits in C and it wouldn't be that big of a deal. It would be an investment for whatever company is making the mobile OS, and at the end of the day I'm not sure they gain as much from this.</p> <p>Finally, it's the very beginning of mobile devices. In 5 years I wouldn't be at all surprised to see a much wider mobile stack.</p>
13
2009-05-03T03:26:56Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
816,266
<p>There are many reasons. Among them:</p> <ul> <li>business reasons, such as software lock-in strategies,</li> <li>efficiency: dynamic languages are usually perceived to be slower (and in some cases really are slower, or at least provide a limit to the amount of optimsation you can do. On a mobile device, optimising code is necessary much more often than on a PC), and tend to use more memory, which is a significant issue on portable devices with limited memory and little cache,,</li> <li>keeping development simple: a platform that supports say Python and Ruby and Java out of the box: <ul> <li>means thrice the work to write documentation and provide support,</li> <li>divides development effort into three; it takes longer for helpful material to appear on the web and there are less developers who use the same language as you on your platform,</li> <li>requires more storage on the device to support all these languages,</li> </ul></li> <li>management need to be convinced. I've always felt that the merits of Java are easily explained to a non-technical audience. .Net and Obj-C also seem a very natural choice for a Microsoft and Apple platform, respectively.</li> </ul>
0
2009-05-03T03:33:22Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
817,365
<p>Contrary to the premise of the question: One of the first mainstream mobile devices was the <a href="http://en.wikipedia.org/wiki/Apple%5FNewton" rel="nofollow">Newton</a>, which was designed to use a specialized dynamic language called <a href="http://en.wikipedia.org/wiki/NewtonScript" rel="nofollow">NewtonScript</a> for application development. The Newton development environment and language made it especially easy for applications to work together and share information - almost the polar opposite of the current iPhone experience. Although many developers writing new Newton applications from scratch liked it a lot - NewtonScript "feels" a lot like Ruby - the Newton had some performance issues and porting of existing code was not easy, even after Apple later added the ability to incorporate C code into a NewtonScript program. Also, it was very hard to protect one's intellectual property on the Newton - other developers could in most cases look inside your code and even override bits of it at a whim - a security nightmare.</p> <p><strong>The Newton was a commercial failure.</strong></p> <p>Palm took a few of Apple's best ideas - and improved upon them - but tossed dynamic language support as part of an overall simplification that eventually led to PalmOS gaining a majority of the mobile market share (for many years) as independent mobile software developers flocked to the new platform.</p> <p>There were many reasons <em>why</em> the Newton was a failure, but some probably blame NewtonScript. Apple is "thinking different" with the iPhone, and one of the early decisions they seem to have made is to leverage as much as possible off their existing core developer base and make it easy for people to develop in Objective C. If iPhone gets official support for dynamic languages, that will be a later addition after long and careful consideration about how best to do it while still providing a secure and high-performance platform.</p> <p>And 5 minutes after they do, others will follow. :-)</p>
2
2009-05-03T15:54:28Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
817,560
<p>webOS -- the new OS from Palm, which will debut on the Pre -- has you write apps against a webkit runtime in JavaScript. Time will tell how successful it is, but I suspect it will not be the first to go down this path. As mobile devices become more powerful, you'll see dynamic languages become more prevalent.</p>
0
2009-05-03T17:35:38Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
817,612
<p>The situation for multiple languages on mobile devices is better than the question implies. Java (in its J2ME incarnation) is available these days even in fairly cheap phones. Symbian S60 officially supports <a href="http://opensource.nokia.com/projects/pythonfors60/" rel="nofollow">Python</a>, and <a href="http://www.forum.nokia.com/Resources%5Fand%5FInformation/Explore/Web%5FTechnologies/Web%5FRuntime/" rel="nofollow">Javascript for widgets</a>, and there's a Ruby port although it's still fairly experimental. Charles Nutter has experimented with <a href="http://blog.headius.com/2009/02/domo-arigato-mr-ruboto.html" rel="nofollow">getting JRuby running on Android</a>. <a href="http://rhomobile.com/home" rel="nofollow">rhomobile</a> claims to allow developing an app in Ruby which will then run on <em>all</em> the major smartphone OSes, although that kind of portability claim implies restrictions on what those apps can achieve.</p> <p>It's important to distinguish between the mobile OS (which does operating system stuff like sharing and protecting resources) and the runtime platform (which provides a working environment and a set of APIs to user-written applications). An OS can support multiple runtimes, such as how you can run both C++ and Java apps in Windows, even though Windows itself is written in C++.</p> <p>Runtimes will have different performance characteristics, and expose the capabilities of the OS and hardware to a greater or lesser degree. For example, J2ME is available on tons of devices, but on many devices the J2ME runtime doesn't provide access to the camera or the ability to make calls. The "native" runtime (i.e. the one where apps are written in the same language as the OS) is no different in this respect: what "native" apps can do depends on what the runtime allows.</p>
2
2009-05-03T17:59:39Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
1,077,282
<p>My Palm has a <a href="http://en.wikipedia.org/wiki/Plua" rel="nofollow">Lua implementation</a> that allows you to do reasonable GUIs, a fairly useless old Python 1.5, a <a href="http://www.quartus.net/products/forth/" rel="nofollow">superb Forth</a> (which allows you to produce compiled apps) and a <a href="http://www.lispme.de/lispme/" rel="nofollow">Scheme</a> that allows for copmlete GUI dev.</p> <p>At the recent Apple WWDC 2009, the Symbian alliance hosted an event the first day in an adjacent building with the teaser of a free <a href="http://europe.nokia.com/find-products/devices/nokia-5800-xpressmusic" rel="nofollow">Nokia 5800</a> for <em>everyone coming even just for the lunch with marketing pitch</em> - a US$350 phone. The event was to pitch developing for the <a href="http://store.ovi.com/" rel="nofollow">Ovi Store</a> and they had developers there and a programming competition on the afternoon.</p> <p>The three languages they were emphasizing for development for Symbian were Java, Flash (lite) and <a href="http://www.forum.nokia.com/Tools%5FDocs%5Fand%5FCode/Tools/Runtimes/Python%5Ffor%5FS60/" rel="nofollow">Python</a>. Python is the only option that allows you to work on the device <a href="http://people.csail.mit.edu/kapu/symbian/python.html" rel="nofollow">or a PC</a> and includes samples with OpenGL ES and other phone features.</p> <p>With a utility to bundle Python apps into standalones that can be hosted on the store, I'd say Python on S60 is right up there as a contender for <em>serious dynamic language</em> on the (still) dominant platform.</p>
0
2009-07-02T23:59:40Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
1,077,315
<p>There is a linux distribution for OpenMoko Freerunner called SHR. Most of its settings and framework code is written in python and... well, it isn't very fast. It is bearable, but it was planned from the beginning to rewrite it in Vala.</p> <p>On the other side, my few smallish apps work fast enough (with the only drawback having big startup time) to consider python to develop user applications.</p> <p>For the record: Freerunner has ARM-something 400MHz and 128MB of RAM. I guess that once mobile devices cross 1GHz, languages like Python will be fast enough for middle-level stuff too (the low-level being the kernel).</p>
0
2009-07-03T00:12:49Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
Python/Ruby as mobile OS
816,212
<p>I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language.</p> <p>What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython.</p> <p>I was just wondering why we do not see more dynamic language support in today's mobile OS's.</p>
10
2009-05-03T03:09:58Z
1,512,031
<p>Rhomobile's open source <a href="http://rhomobile.com/products/rhodes" rel="nofollow">Rhodes</a> framework offers this today. The world's first Ruby implementations for all smartphones.</p>
0
2009-10-02T22:08:35Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
How to unescape apostrophes and such in Python?
816,272
<p>I have a string with symbols like this:</p> <pre><code>&amp;#39; </code></pre> <p>That's an apostrophe apparently.</p> <p>I tried saxutils.unescape() without any luck and tried urllib.unquote()</p> <p>How can I decode this? Thanks!</p>
7
2009-05-03T03:37:49Z
816,281
<p>I am not sure about the &amp; or the #, but here is some code for decoding:</p> <pre><code>&gt;&gt;&gt;chr(39) "'" &gt;&gt;&gt;ord("'") 39 </code></pre>
-2
2009-05-03T03:45:19Z
[ "python", "html", "django", "html-entities" ]
How to unescape apostrophes and such in Python?
816,272
<p>I have a string with symbols like this:</p> <pre><code>&amp;#39; </code></pre> <p>That's an apostrophe apparently.</p> <p>I tried saxutils.unescape() without any luck and tried urllib.unquote()</p> <p>How can I decode this? Thanks!</p>
7
2009-05-03T03:37:49Z
816,297
<p>Check out <a href="http://stackoverflow.com/questions/275174/">this question</a>. What you're looking for is "html entity decoding". Typically, you'll find a function named something like "htmldecode" that will do what you want. Both Django and Cheetah provide such functions as does BeautifulSoup.</p> <p>The other answer will work just great if you don't want to use a library and all the entities are numeric.</p>
2
2009-05-03T03:54:01Z
[ "python", "html", "django", "html-entities" ]