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
Character Translation using Python (like the tr command)
555,705
<p>Is there a way to do character translation (kind of like the tr command) using python</p>
28
2009-02-17T06:33:06Z
23,159,267
<p>In Python 2, <code>unicode.translate()</code> accepts ordinary mappings, ie. there's no need to import anything either:</p> <pre><code>&gt;&gt;&gt; u'abc+-'.translate({ord('+'): u'-', ord('-'): u'+', ord('b'): None}) u'ac-+' </code></pre> <p>The <code>translate()</code> method is especially useful for swapping characters (as '+' and '-' above), which can't be done with <code>replace()</code>, and using <code>re.sub()</code> isn't very straightforward for that purpose either.</p> <p>I have to admit, however, that the repeated use of <code>ord()</code> doesn't make the code look like nice and tidy.</p>
1
2014-04-18T17:41:42Z
[ "python" ]
Character Translation using Python (like the tr command)
555,705
<p>Is there a way to do character translation (kind of like the tr command) using python</p>
28
2009-02-17T06:33:06Z
27,964,244
<p>I has developed python-tr, implemented tr algorithm. Let's try it.</p> <p>Install:</p> <pre><code>$ pip install python-tr </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; from tr import tr &gt;&gt;&gt; tr('bn', 'cr', 'bunny') 'curry' &gt;&gt;&gt; tr('n', '', 'bunny', 'd') 'buy' &gt;&gt;&gt; tr('n', 'u', 'bunny', 'c') 'uunnu' &gt;&gt;&gt; tr('n', '', 'bunny', 's') 'buny' &gt;&gt;&gt; tr('bn', '', 'bunny', 'cd') 'bnn' &gt;&gt;&gt; tr('bn', 'cr', 'bunny', 'cs') 'brnnr' &gt;&gt;&gt; tr('bn', 'cr', 'bunny', 'ds') 'uy' </code></pre> <ul> <li><a href="https://pypi.python.org/pypi/python-tr" rel="nofollow">https://pypi.python.org/pypi/python-tr</a></li> <li><a href="https://github.com/ikegami-yukino/python-tr" rel="nofollow">https://github.com/ikegami-yukino/python-tr</a></li> </ul>
3
2015-01-15T13:11:18Z
[ "python" ]
Character Translation using Python (like the tr command)
555,705
<p>Is there a way to do character translation (kind of like the tr command) using python</p>
28
2009-02-17T06:33:06Z
37,368,639
<p>This one works for Python 3</p> <p><code>-int('(1200)'.translate(str.maketrans('','','()')))</code></p>
-1
2016-05-21T22:31:54Z
[ "python" ]
ImportError: No module named copy_reg pickle
556,269
<p>I'm trying to unpickle an object stored as a blob in a MySQL database. I've manually generated and stored the pickled object in the database, but when I try to unpickle the object, I get the following rather cryptic exception:</p> <p>ImportError: No module named copy_reg</p> <p>Any ideas as to why this happens?</p> <p><strong>Method of Reproduction</strong></p> <p>Note: Must do step 1 on a Windows PC and steps 3 and 4 on a Linux PC.</p> <p>1) On a Windows PC:</p> <pre><code>file = open("test.txt", "w") thing = {'a': 1, 'b':2} cPickle.dump(thing, file) </code></pre> <p>2) Manually insert contents of text.txt into blob field of MySQL database running on linux</p> <p>3) In Python running on a linux machine, fetch the contents of column from MySQL</p> <p>4) Assuming that you put the contents of the blob column into a variable called data, try this:</p> <pre><code>cPickle.loads(rawString) </code></pre>
13
2009-02-17T10:42:58Z
556,295
<p>It seems this might be caused by my method of exporting the pickled object.</p> <p><a href="http://www.archivum.info/python-bugs-list@python.org/2007-04/msg00222.html">This bug report</a> seens to suggest that my issue can be resolved by exporting to a file writen in binary mode. I'm going to give this a go now and see if this solves my issue.</p> <p>UPDATE: This works. The solution is to make sure you export your pickled object to a file open in binary mode, even if you are using the default protocol 0 (commonly referred to as being "text")</p> <p>Correct code based on orignal example in question:</p> <pre><code>file = open("test.txt", 'wb') thing = {'a': 1, 'b':2} cPickle.dump(thing, file) </code></pre>
17
2009-02-17T10:52:36Z
[ "python", "pickle" ]
ImportError: No module named copy_reg pickle
556,269
<p>I'm trying to unpickle an object stored as a blob in a MySQL database. I've manually generated and stored the pickled object in the database, but when I try to unpickle the object, I get the following rather cryptic exception:</p> <p>ImportError: No module named copy_reg</p> <p>Any ideas as to why this happens?</p> <p><strong>Method of Reproduction</strong></p> <p>Note: Must do step 1 on a Windows PC and steps 3 and 4 on a Linux PC.</p> <p>1) On a Windows PC:</p> <pre><code>file = open("test.txt", "w") thing = {'a': 1, 'b':2} cPickle.dump(thing, file) </code></pre> <p>2) Manually insert contents of text.txt into blob field of MySQL database running on linux</p> <p>3) In Python running on a linux machine, fetch the contents of column from MySQL</p> <p>4) Assuming that you put the contents of the blob column into a variable called data, try this:</p> <pre><code>cPickle.loads(rawString) </code></pre>
13
2009-02-17T10:42:58Z
760,499
<p>Also, simply running dos2unix (under linux) over the (windows-created) pickle file solved the problem for me. (Haven't tried the open mode 'wb' thing.) Dan</p>
9
2009-04-17T13:50:01Z
[ "python", "pickle" ]
ImportError: No module named copy_reg pickle
556,269
<p>I'm trying to unpickle an object stored as a blob in a MySQL database. I've manually generated and stored the pickled object in the database, but when I try to unpickle the object, I get the following rather cryptic exception:</p> <p>ImportError: No module named copy_reg</p> <p>Any ideas as to why this happens?</p> <p><strong>Method of Reproduction</strong></p> <p>Note: Must do step 1 on a Windows PC and steps 3 and 4 on a Linux PC.</p> <p>1) On a Windows PC:</p> <pre><code>file = open("test.txt", "w") thing = {'a': 1, 'b':2} cPickle.dump(thing, file) </code></pre> <p>2) Manually insert contents of text.txt into blob field of MySQL database running on linux</p> <p>3) In Python running on a linux machine, fetch the contents of column from MySQL</p> <p>4) Assuming that you put the contents of the blob column into a variable called data, try this:</p> <pre><code>cPickle.loads(rawString) </code></pre>
13
2009-02-17T10:42:58Z
1,245,146
<p>just an interactive python session to show that you don't need any particular code to have this problem:</p> <p>do something like this on a windows machine</p> <pre><code>Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pickle, re &gt;&gt;&gt; empty_string = re.compile("^$") &gt;&gt;&gt; pickle.dump([empty_string,1,1.23,'abc'], file('m:/mario/test-b.dump','wb')) &gt;&gt;&gt; pickle.dump([empty_string,1,1.23,'abc'], file('m:/mario/test-t.dump','wt')) &gt;&gt;&gt; </code></pre> <p>and then try to retrieve the data from a linux box</p> <pre><code>Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pickle &gt;&gt;&gt; pickle.load(file('/home/mario/.gvfs/transfer on 192.168.0.4/mario/test-b.dump')) /usr/lib/python2.6/pickle.py:1124: DeprecationWarning: The sre module is deprecated, please import re. __import__(module) [&lt;_sre.SRE_Pattern object at 0xb7d42420&gt;, 1, 1.23, 'abc'] &gt;&gt;&gt; pickle.load(file('/home/mario/.gvfs/transfer on 192.168.0.4/mario/test-t.dump')) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.6/pickle.py", line 1370, in load return Unpickler(file).load() File "/usr/lib/python2.6/pickle.py", line 858, in load dispatch[key](self) File "/usr/lib/python2.6/pickle.py", line 1090, in load_global klass = self.find_class(module, name) File "/usr/lib/python2.6/pickle.py", line 1124, in find_class __import__(module) ImportError: No module named sre &gt;&gt;&gt; </code></pre> <p>the error message can be even more confusing if you are just pickling base types. this is what I get with the list <code>[12, 1.2, '']</code>:</p> <pre><code>ValueError: insecure string pickle </code></pre>
3
2009-08-07T14:42:46Z
[ "python", "pickle" ]
ImportError: No module named copy_reg pickle
556,269
<p>I'm trying to unpickle an object stored as a blob in a MySQL database. I've manually generated and stored the pickled object in the database, but when I try to unpickle the object, I get the following rather cryptic exception:</p> <p>ImportError: No module named copy_reg</p> <p>Any ideas as to why this happens?</p> <p><strong>Method of Reproduction</strong></p> <p>Note: Must do step 1 on a Windows PC and steps 3 and 4 on a Linux PC.</p> <p>1) On a Windows PC:</p> <pre><code>file = open("test.txt", "w") thing = {'a': 1, 'b':2} cPickle.dump(thing, file) </code></pre> <p>2) Manually insert contents of text.txt into blob field of MySQL database running on linux</p> <p>3) In Python running on a linux machine, fetch the contents of column from MySQL</p> <p>4) Assuming that you put the contents of the blob column into a variable called data, try this:</p> <pre><code>cPickle.loads(rawString) </code></pre>
13
2009-02-17T10:42:58Z
26,446,582
<p>Another thing going on here is that you don't seem to have closed the file after dumping the pickle to it. the error reported here can sometimes be caused (whether on a windows machine or otherwise) by not closing the file. </p>
0
2014-10-19T02:09:30Z
[ "python", "pickle" ]
ImportError: No module named copy_reg pickle
556,269
<p>I'm trying to unpickle an object stored as a blob in a MySQL database. I've manually generated and stored the pickled object in the database, but when I try to unpickle the object, I get the following rather cryptic exception:</p> <p>ImportError: No module named copy_reg</p> <p>Any ideas as to why this happens?</p> <p><strong>Method of Reproduction</strong></p> <p>Note: Must do step 1 on a Windows PC and steps 3 and 4 on a Linux PC.</p> <p>1) On a Windows PC:</p> <pre><code>file = open("test.txt", "w") thing = {'a': 1, 'b':2} cPickle.dump(thing, file) </code></pre> <p>2) Manually insert contents of text.txt into blob field of MySQL database running on linux</p> <p>3) In Python running on a linux machine, fetch the contents of column from MySQL</p> <p>4) Assuming that you put the contents of the blob column into a variable called data, try this:</p> <pre><code>cPickle.loads(rawString) </code></pre>
13
2009-02-17T10:42:58Z
33,434,146
<p>As mentioned in the other answer use </p> <pre><code>dos2unix originalPickle.file outputPickle.file </code></pre> <p>OR use the tr command like below (removes carriage returns and ctrl-z)</p> <pre><code> tr -d '\15\32' &lt; originalPickle.file &gt; outputPickle.file </code></pre> <p>OR use <code>awk</code> (<code>gawk</code> or <code>nawk</code> if its old versions)</p> <pre><code> awk '{ sub("\r$", ""); print }' originalPickle.file &gt; outputPickle.file </code></pre> <p>OR if you can recreate a pickle file in linux, use that.</p>
0
2015-10-30T10:47:23Z
[ "python", "pickle" ]
ImportError: No module named copy_reg pickle
556,269
<p>I'm trying to unpickle an object stored as a blob in a MySQL database. I've manually generated and stored the pickled object in the database, but when I try to unpickle the object, I get the following rather cryptic exception:</p> <p>ImportError: No module named copy_reg</p> <p>Any ideas as to why this happens?</p> <p><strong>Method of Reproduction</strong></p> <p>Note: Must do step 1 on a Windows PC and steps 3 and 4 on a Linux PC.</p> <p>1) On a Windows PC:</p> <pre><code>file = open("test.txt", "w") thing = {'a': 1, 'b':2} cPickle.dump(thing, file) </code></pre> <p>2) Manually insert contents of text.txt into blob field of MySQL database running on linux</p> <p>3) In Python running on a linux machine, fetch the contents of column from MySQL</p> <p>4) Assuming that you put the contents of the blob column into a variable called data, try this:</p> <pre><code>cPickle.loads(rawString) </code></pre>
13
2009-02-17T10:42:58Z
35,439,754
<p>The pickle load may not be looking in the same location as your python script. Sometimes the directory changes on the basis of your application. Just before you load the pickle, print a os.getcwd() to work out a solution.</p>
0
2016-02-16T17:55:58Z
[ "python", "pickle" ]
Python code to find if x is following y on twitter. More Pythonic way please
556,342
<p>I wrote a twitter application in Python. Following is the code I used for a module where I find if x is following y. This code can be obviously improved upon. A pythonic way to do that?</p> <pre><code>import urllib2 import sys import re import base64 from urlparse import urlparse import simplejson def is_follows(follower, following): theurl = 'http://twitter.com/friendships/exists.json?user_a='+follower+'&amp;user_b='+following username = 'uname1' password = 'pwd1' handle = urllib2.Request(theurl) base64string = base64.encodestring('%s:%s' % (username, password)) authheader = "Basic %s" % base64string handle.add_header("Authorization", authheader) fol=True try: fol = simplejson.load(urllib2.urlopen(handle)) except IOError, e: # here we shouldn't fail if the username/password is right print "It looks like the username or password is wrong." return fol </code></pre> <p>Update: Indentation fixed.</p>
1
2009-02-17T11:11:11Z
556,352
<p>Three things:</p> <ul> <li>Fix the indentation (but then I guess this was not done on purpose).</li> <li>Use formatting instead of concatenation in constructing <code>theurl</code>.</li> <li>Remove the <code>fol</code> variable. Rather, do the following:</li> </ul> <p><hr /></p> <pre><code>try: return simplejson.load(urllib2.urlopen(handle)) except IOError, e: # here we shouldn't fail if the username/password is right print "It looks like the username or password is wrong." return False </code></pre>
2
2009-02-17T11:17:05Z
[ "authentication", "twitter", "python" ]
Python code to find if x is following y on twitter. More Pythonic way please
556,342
<p>I wrote a twitter application in Python. Following is the code I used for a module where I find if x is following y. This code can be obviously improved upon. A pythonic way to do that?</p> <pre><code>import urllib2 import sys import re import base64 from urlparse import urlparse import simplejson def is_follows(follower, following): theurl = 'http://twitter.com/friendships/exists.json?user_a='+follower+'&amp;user_b='+following username = 'uname1' password = 'pwd1' handle = urllib2.Request(theurl) base64string = base64.encodestring('%s:%s' % (username, password)) authheader = "Basic %s" % base64string handle.add_header("Authorization", authheader) fol=True try: fol = simplejson.load(urllib2.urlopen(handle)) except IOError, e: # here we shouldn't fail if the username/password is right print "It looks like the username or password is wrong." return fol </code></pre> <p>Update: Indentation fixed.</p>
1
2009-02-17T11:11:11Z
556,361
<p>Google threw this library with an <a href="http://static.unto.net/python-twitter/0.5/doc/twitter.html" rel="nofollow">Twitter API for Python</a> at me. I think such an library would simplify this task alot. It has a GetFollowers() method that lets you look up if someone is following you.</p> <p>Edit: It looks like you can't look up followers of arbitrary users.</p>
0
2009-02-17T11:21:13Z
[ "authentication", "twitter", "python" ]
Python code to find if x is following y on twitter. More Pythonic way please
556,342
<p>I wrote a twitter application in Python. Following is the code I used for a module where I find if x is following y. This code can be obviously improved upon. A pythonic way to do that?</p> <pre><code>import urllib2 import sys import re import base64 from urlparse import urlparse import simplejson def is_follows(follower, following): theurl = 'http://twitter.com/friendships/exists.json?user_a='+follower+'&amp;user_b='+following username = 'uname1' password = 'pwd1' handle = urllib2.Request(theurl) base64string = base64.encodestring('%s:%s' % (username, password)) authheader = "Basic %s" % base64string handle.add_header("Authorization", authheader) fol=True try: fol = simplejson.load(urllib2.urlopen(handle)) except IOError, e: # here we shouldn't fail if the username/password is right print "It looks like the username or password is wrong." return fol </code></pre> <p>Update: Indentation fixed.</p>
1
2009-02-17T11:11:11Z
556,498
<p>Konrad gave you a good answer with changes you can make to make your code more Pythonic. All I want to add is if you are interested in seeing some <strong>advanced</strong> code to do this same thing check out <a href="http://mike.verdone.ca/twitter/" rel="nofollow">The Minimalist Twitter API for Python</a>.</p> <p>It can show you a Pythonic way to write an API that doesn't repeat itself (in other words follows DRY [don't repeat yourself] principles) by using dynamic class method construction using __getattr__() and __call__(). Your example would be something like:</p> <pre><code>fol = twitter.friendships.exists(user_a="X", user_b="Y") </code></pre> <p>even though the twitter class doesn't have "friendships" or "exists" methods/properties.</p> <p>(Warning: I didn't test the code above so it might not be quite right, but should be pretty close)</p>
2
2009-02-17T11:58:36Z
[ "authentication", "twitter", "python" ]
Python code to find if x is following y on twitter. More Pythonic way please
556,342
<p>I wrote a twitter application in Python. Following is the code I used for a module where I find if x is following y. This code can be obviously improved upon. A pythonic way to do that?</p> <pre><code>import urllib2 import sys import re import base64 from urlparse import urlparse import simplejson def is_follows(follower, following): theurl = 'http://twitter.com/friendships/exists.json?user_a='+follower+'&amp;user_b='+following username = 'uname1' password = 'pwd1' handle = urllib2.Request(theurl) base64string = base64.encodestring('%s:%s' % (username, password)) authheader = "Basic %s" % base64string handle.add_header("Authorization", authheader) fol=True try: fol = simplejson.load(urllib2.urlopen(handle)) except IOError, e: # here we shouldn't fail if the username/password is right print "It looks like the username or password is wrong." return fol </code></pre> <p>Update: Indentation fixed.</p>
1
2009-02-17T11:11:11Z
556,574
<p>From your code it looks like you are trying to do a Basic HTTP Authentication. Is this right? Then you shouldn't create the HTTP headers by hand. Instead use the urllib2.HTTPBasicAuthHandler. An example from the <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">docs</a>:</p> <pre><code>import urllib2 # Create an OpenerDirector with support for Basic HTTP Authentication... auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='PDQ Application', uri='https://mahler:8092/site-updates.py', user='klem', passwd='kadidd!ehopper') opener = urllib2.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. urllib2.install_opener(opener) urllib2.urlopen('http://www.example.com/login.html') </code></pre>
2
2009-02-17T12:23:11Z
[ "authentication", "twitter", "python" ]
Python list serialization - fastest method
556,730
<p>I need to load (de-serialize) a pre-computed list of integers from a file in a Python script (into a Python list). The list is large (upto millions of items), and I can choose the format I store it in, as long as loading is fastest.</p> <p>Which is the fastest method, and why?</p> <ol> <li>Using <code>import</code> on a .py file that just contains the list assigned to a variable</li> <li>Using <code>cPickle</code>'s <code>load</code></li> <li>Some other method (perhaps <code>numpy</code>?)</li> </ol> <p>Also, how can one benchmark such things reliably?</p> <p><strong>Addendum:</strong> measuring this reliably is difficult, because <code>import</code> is cached so it can't be executed multiple times in a test. The loading with pickle also gets faster after the first time probably because page-precaching by the OS. Loading 1 million numbers with <code>cPickle</code> takes 1.1 sec the first time run, and 0.2 sec on subsequent executions of the script.</p> <p>Intuitively I feel <code>cPickle</code> should be faster, but I'd appreciate numbers (this is quite a challenge to measure, I think). </p> <p>And yes, it's important for me that this performs quickly.</p> <p>Thanks</p>
11
2009-02-17T13:16:25Z
556,843
<p>"how can one benchmark such things reliably?" </p> <p>I don't get the question.</p> <p>You write a bunch of little functions to create and save your list in various forms.</p> <p>You write a bunch of little functions to load your lists in their various forms.</p> <p>You write a little timer function to get start time, execute the load procedure a few dozen times (to get a solid average that's long enough that OS scheduling noise doesn't dominate your measurements).</p> <p>You summarize your data in a little report. </p> <p>What's unreliable about this?</p> <p>Here are some unrelated questions that shows how to measure and compare performance. </p> <p><a href="http://stackoverflow.com/questions/489999/python-convert-list-of-ints-to-one-number">http://stackoverflow.com/questions/489999/python-convert-list-of-ints-to-one-number</a></p> <p><a href="http://stackoverflow.com/questions/376461/string-concatenation-vs-string-substitution-in-python">http://stackoverflow.com/questions/376461/string-concatenation-vs-string-substitution-in-python</a></p>
2
2009-02-17T13:43:57Z
[ "python", "serialization", "caching" ]
Python list serialization - fastest method
556,730
<p>I need to load (de-serialize) a pre-computed list of integers from a file in a Python script (into a Python list). The list is large (upto millions of items), and I can choose the format I store it in, as long as loading is fastest.</p> <p>Which is the fastest method, and why?</p> <ol> <li>Using <code>import</code> on a .py file that just contains the list assigned to a variable</li> <li>Using <code>cPickle</code>'s <code>load</code></li> <li>Some other method (perhaps <code>numpy</code>?)</li> </ol> <p>Also, how can one benchmark such things reliably?</p> <p><strong>Addendum:</strong> measuring this reliably is difficult, because <code>import</code> is cached so it can't be executed multiple times in a test. The loading with pickle also gets faster after the first time probably because page-precaching by the OS. Loading 1 million numbers with <code>cPickle</code> takes 1.1 sec the first time run, and 0.2 sec on subsequent executions of the script.</p> <p>Intuitively I feel <code>cPickle</code> should be faster, but I'd appreciate numbers (this is quite a challenge to measure, I think). </p> <p>And yes, it's important for me that this performs quickly.</p> <p>Thanks</p>
11
2009-02-17T13:16:25Z
556,867
<p>For benchmarking, see the timeit module in the Python standard library. To see what is the fastest way, implement all the ways you can think of and measure them with timeit.</p> <p>Random thought: depending on what you're doing exactly, you may find it fastest to store "sets of integers" in the style used in <strong>.newsrc</strong> files:</p> <pre><code>1, 3-1024, 11000-1200000 </code></pre> <p>If you need to check whether something is in that set, then loading and matching with such a representation should be among the fastest ways. This assumes your sets of integers are reasonably dense, with long consecutive sequences of adjacent values.</p>
3
2009-02-17T13:50:14Z
[ "python", "serialization", "caching" ]
Python list serialization - fastest method
556,730
<p>I need to load (de-serialize) a pre-computed list of integers from a file in a Python script (into a Python list). The list is large (upto millions of items), and I can choose the format I store it in, as long as loading is fastest.</p> <p>Which is the fastest method, and why?</p> <ol> <li>Using <code>import</code> on a .py file that just contains the list assigned to a variable</li> <li>Using <code>cPickle</code>'s <code>load</code></li> <li>Some other method (perhaps <code>numpy</code>?)</li> </ol> <p>Also, how can one benchmark such things reliably?</p> <p><strong>Addendum:</strong> measuring this reliably is difficult, because <code>import</code> is cached so it can't be executed multiple times in a test. The loading with pickle also gets faster after the first time probably because page-precaching by the OS. Loading 1 million numbers with <code>cPickle</code> takes 1.1 sec the first time run, and 0.2 sec on subsequent executions of the script.</p> <p>Intuitively I feel <code>cPickle</code> should be faster, but I'd appreciate numbers (this is quite a challenge to measure, I think). </p> <p>And yes, it's important for me that this performs quickly.</p> <p>Thanks</p>
11
2009-02-17T13:16:25Z
556,902
<p>To help you with timing, the Python Library provides the <a href="http://docs.python.org/library/timeit.html#module-timeit" rel="nofollow"><code>timeit</code></a> module:</p> <blockquote> <p>This module provides a simple way to time small bits of Python code. It has both command line as well as callable interfaces. It avoids a number of common traps for measuring execution times.</p> </blockquote> <p>An example (from the manual) that compares the cost of using <code>hasattr()</code> vs. <code>try/except</code> to test for missing and present object attributes:</p> <pre><code>% timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass' 100000 loops, best of 3: 15.7 usec per loop % timeit.py 'if hasattr(str, "__nonzero__"): pass' 100000 loops, best of 3: 4.26 usec per loop % timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass' 1000000 loops, best of 3: 1.43 usec per loop % timeit.py 'if hasattr(int, "__nonzero__"): pass' 100000 loops, best of 3: 2.23 usec per loop </code></pre>
2
2009-02-17T13:57:14Z
[ "python", "serialization", "caching" ]
Python list serialization - fastest method
556,730
<p>I need to load (de-serialize) a pre-computed list of integers from a file in a Python script (into a Python list). The list is large (upto millions of items), and I can choose the format I store it in, as long as loading is fastest.</p> <p>Which is the fastest method, and why?</p> <ol> <li>Using <code>import</code> on a .py file that just contains the list assigned to a variable</li> <li>Using <code>cPickle</code>'s <code>load</code></li> <li>Some other method (perhaps <code>numpy</code>?)</li> </ol> <p>Also, how can one benchmark such things reliably?</p> <p><strong>Addendum:</strong> measuring this reliably is difficult, because <code>import</code> is cached so it can't be executed multiple times in a test. The loading with pickle also gets faster after the first time probably because page-precaching by the OS. Loading 1 million numbers with <code>cPickle</code> takes 1.1 sec the first time run, and 0.2 sec on subsequent executions of the script.</p> <p>Intuitively I feel <code>cPickle</code> should be faster, but I'd appreciate numbers (this is quite a challenge to measure, I think). </p> <p>And yes, it's important for me that this performs quickly.</p> <p>Thanks</p>
11
2009-02-17T13:16:25Z
556,946
<p>I would guess <a href="http://docs.python.org/library/pickle.html#module-cPickle" rel="nofollow">cPickle</a> will be fastest if you really need the thing in a list.</p> <p>If you can use an <a href="http://docs.python.org/library/array.html" rel="nofollow">array</a>, which is a built-in sequence type, I timed this at a quarter of a second for 1 million integers:</p> <pre><code>from array import array from datetime import datetime def WriteInts(theArray,filename): f = file(filename,"wb") theArray.tofile(f) f.close() def ReadInts(filename): d = datetime.utcnow() theArray = array('i') f = file(filename,"rb") try: theArray.fromfile(f,1000000000) except EOFError: pass print "Read %d ints in %s" % (len(theArray),datetime.utcnow() - d) return theArray if __name__ == "__main__": a = array('i') a.extend(range(0,1000000)) filename = "a_million_ints.dat" WriteInts(a,filename) r = ReadInts(filename) print "The 5th element is %d" % (r[4]) </code></pre>
7
2009-02-17T14:07:06Z
[ "python", "serialization", "caching" ]
Python list serialization - fastest method
556,730
<p>I need to load (de-serialize) a pre-computed list of integers from a file in a Python script (into a Python list). The list is large (upto millions of items), and I can choose the format I store it in, as long as loading is fastest.</p> <p>Which is the fastest method, and why?</p> <ol> <li>Using <code>import</code> on a .py file that just contains the list assigned to a variable</li> <li>Using <code>cPickle</code>'s <code>load</code></li> <li>Some other method (perhaps <code>numpy</code>?)</li> </ol> <p>Also, how can one benchmark such things reliably?</p> <p><strong>Addendum:</strong> measuring this reliably is difficult, because <code>import</code> is cached so it can't be executed multiple times in a test. The loading with pickle also gets faster after the first time probably because page-precaching by the OS. Loading 1 million numbers with <code>cPickle</code> takes 1.1 sec the first time run, and 0.2 sec on subsequent executions of the script.</p> <p>Intuitively I feel <code>cPickle</code> should be faster, but I'd appreciate numbers (this is quite a challenge to measure, I think). </p> <p>And yes, it's important for me that this performs quickly.</p> <p>Thanks</p>
11
2009-02-17T13:16:25Z
556,961
<p>cPickle will be the fastest since it is saved in binary and no real python code has to be parsed.</p> <p>Other advantates are that it is more secure (since it does not execute commands) and you have no problems with setting <code>$PYTHONPATH</code> correctly.</p>
1
2009-02-17T14:11:21Z
[ "python", "serialization", "caching" ]
Python list serialization - fastest method
556,730
<p>I need to load (de-serialize) a pre-computed list of integers from a file in a Python script (into a Python list). The list is large (upto millions of items), and I can choose the format I store it in, as long as loading is fastest.</p> <p>Which is the fastest method, and why?</p> <ol> <li>Using <code>import</code> on a .py file that just contains the list assigned to a variable</li> <li>Using <code>cPickle</code>'s <code>load</code></li> <li>Some other method (perhaps <code>numpy</code>?)</li> </ol> <p>Also, how can one benchmark such things reliably?</p> <p><strong>Addendum:</strong> measuring this reliably is difficult, because <code>import</code> is cached so it can't be executed multiple times in a test. The loading with pickle also gets faster after the first time probably because page-precaching by the OS. Loading 1 million numbers with <code>cPickle</code> takes 1.1 sec the first time run, and 0.2 sec on subsequent executions of the script.</p> <p>Intuitively I feel <code>cPickle</code> should be faster, but I'd appreciate numbers (this is quite a challenge to measure, I think). </p> <p>And yes, it's important for me that this performs quickly.</p> <p>Thanks</p>
11
2009-02-17T13:16:25Z
581,566
<p>Do you need to always load the whole file? If not, <a href="http://docs.python.org/library/struct.html" rel="nofollow">upack_from()</a> might be the best solution. Suppose, that you have 1000000 integers, but you'd like to load just the ones from 50000 to 50099, you'd do:</p> <pre><code>import struct intSize = struct.calcsize('i') #this value would be constant for a given arch intFile = open('/your/file.of.integers') intTuple5K100 = struct.unpack_from('i'*100,intFile,50000*intSize) </code></pre>
2
2009-02-24T12:25:20Z
[ "python", "serialization", "caching" ]
WingIDE no autocompletion for my modules
556,785
<p>If anyone using WingIDE for their python dev needs: For some reason I get auto-completion on all the standard python libraries (like datetime....) but not on my own modules. So if I create my own class and then import it from another class, I get no auto-completion on it.</p> <p>Does anyone know why this is?</p>
0
2009-02-17T13:28:35Z
557,053
<p>Just found an answer, it has to do with pythonpath: <a href="http://www.wingware.com/doc/edit/how-analysis-works" rel="nofollow">http://www.wingware.com/doc/edit/how-analysis-works</a></p>
0
2009-02-17T14:28:17Z
[ "python", "ide" ]
How to get distinct Django apps on same subdomain to share session cookie?
556,907
<p>We have a couple of Django applications deployed on the same subdomain. A few power users need to jump between these applications. I noticed that each time they bounce between applications their session cookie receives a new session ID from Django. </p> <p>I don't use the Django session table much except in one complex workflow. If the user bounces between applications while in this workflow they lose their session and have to start over.</p> <p>I dug through the Django session code and discovered that the:</p> <blockquote> <p>django.conf.settings.SECRET_KEY</p> </blockquote> <p>is used to perform an integrity check on the sessions on each request. If the integrity check fails, a new session is created. Realizing this, I changed the secret key in each of these applications to use the same value, thinking this would allow the integrity check to pass and allow them to share Django sessions. However, it didn't seem to work. </p> <p>Is there a way to do this? Am I missing something else?</p> <p>Thanks in advance</p>
7
2009-02-17T13:58:41Z
557,020
<p>I would instead advise you to set <code>SESSION_COOKIE_NAME</code> to <em>different</em> values for the two apps. Your users will still have to log in twice initially, but their sessions won't conflict - if they log in to app A, then app B, and return to A, they'll still have their A session.</p> <p>Sharing sessions between Django instances is probably not a good idea. If you want some kind of single-sign-on, look into something like django-cas. You'll still have 2 sessions (as you should), but the user will only log in once.</p>
12
2009-02-17T14:21:11Z
[ "python", "django", "deployment", "session", "cookies" ]
How to get distinct Django apps on same subdomain to share session cookie?
556,907
<p>We have a couple of Django applications deployed on the same subdomain. A few power users need to jump between these applications. I noticed that each time they bounce between applications their session cookie receives a new session ID from Django. </p> <p>I don't use the Django session table much except in one complex workflow. If the user bounces between applications while in this workflow they lose their session and have to start over.</p> <p>I dug through the Django session code and discovered that the:</p> <blockquote> <p>django.conf.settings.SECRET_KEY</p> </blockquote> <p>is used to perform an integrity check on the sessions on each request. If the integrity check fails, a new session is created. Realizing this, I changed the secret key in each of these applications to use the same value, thinking this would allow the integrity check to pass and allow them to share Django sessions. However, it didn't seem to work. </p> <p>Is there a way to do this? Am I missing something else?</p> <p>Thanks in advance</p>
7
2009-02-17T13:58:41Z
659,606
<p>I agree that sharing sessions between Django instances is probably not a good idea. If you really wanted to, you could:</p> <ul> <li>make sure the two django applications share the same SECRET_KEY</li> <li>make sure the two django applications share the same SeSSON_COOKIE_NAME</li> <li>make sure the SESSION_COOKIE_DOMAIN is set to something that lets the two instances share cookies. (If they really share the same subdomain, your current setting is probably fine.)</li> <li>make sure both Django instances use the same session backend (the same database, the same file directory, the same memcached config, etc.)</li> <li>make sure that anything put into the session makes sense in both Django databases: at the very least, that'll include the user id, since Django auth uses that to remember which user is logged in.</li> </ul> <p>All that said, I haven't actually tried all this, so you may still have trouble! </p>
8
2009-03-18T18:44:25Z
[ "python", "django", "deployment", "session", "cookies" ]
Where should I post my python code?
556,967
<p>Today I needed to parse some data out from an xlsx file (Office open XML Spreadsheet). I could have just opened the files in openoffice and exported to csv. However I will need to reimport data from this spreadsheet later, and I wanted to eliminate the manual operation.</p> <p>I searched on the net for xlsx parser, and all I found was a stackoverflow question asking the same thing: <a href="http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx">http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx</a></p> <p>So I rolled my own. </p> <p>It's 134 lines of code for the parsing and accessing off a spreadsheet, and 54 lines of code of unit tests. This of course is only tested on the 1 file I needed it, and aside from how it's used in the unit tests there are is no documentation as off now. It uses zipfile, minidom, re and unittest, so perfectly portable and platform independent.</p> <p>Since I don't blog, and I don't have any desire to turn this into a python library for OfficeOpen XML, I am stuck wondering where I should post this code. I have solved a problem that I am sure others will get in the future. So I want to post my code under public domain somewhere for anyone to copy and paste into their app and adjust to fix their problem.</p> <p>The implementation is simple, and here is a quick overview off the features:</p> <pre><code>workbook = Workbook(filename) # open a file for sheet in workbook: pass # iterate over the worksheets workbook["sheetname"] # access a sheet by name, also possible to do by index from 0 sheet["A1"] # Access cell sheet["A"] # Access column sheet["1"] # Access row cell.value # Cell value - only tested with ints and strings. </code></pre> <p>Thanks for all the replies. I was going to hoste it on activestate, but the page kept crashing when sending me the activation mail. So I can't activate my code to post it.</p> <p>My second choice was codeproject, and I wrote up a nice article about the file. Sadly that page crashes when I try to submit my post.</p> <p>So I put it on github for any to see and branch off: <a href="http://github.com/staale/python-xlsx/tree/master" rel="nofollow">http://github.com/staale/python-xlsx/tree/master</a></p> <p>I don't want to do all the work for the python project hosting, so that's out.</p> <p>Accepting the git answer, as that was the only thing that worked for me. And git rocks.</p> <p>Edit: Gah, lost my entire post at codeproject, and I did such a nice writeup. Screw it, I have spent more time trying to share this than it took coding it. So I am calling it done for my part as off now. Unless I decide to tweak it more later.</p>
4
2009-02-17T14:12:24Z
556,993
<p>You should post it <a href="http://code.activestate.com/recipes/langs/python/" rel="nofollow">here</a>. There are plenty of recipes here and yours would fit in perfectly.</p> <p>Stack Overflow is meant to be a wiki, where people search for questions and find answers. That being said, if you want to post it here, what you would do is open a question relevant to your answer, then respond to your own question with your answer.</p>
5
2009-02-17T14:17:01Z
[ "python", "excel-2007" ]
Where should I post my python code?
556,967
<p>Today I needed to parse some data out from an xlsx file (Office open XML Spreadsheet). I could have just opened the files in openoffice and exported to csv. However I will need to reimport data from this spreadsheet later, and I wanted to eliminate the manual operation.</p> <p>I searched on the net for xlsx parser, and all I found was a stackoverflow question asking the same thing: <a href="http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx">http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx</a></p> <p>So I rolled my own. </p> <p>It's 134 lines of code for the parsing and accessing off a spreadsheet, and 54 lines of code of unit tests. This of course is only tested on the 1 file I needed it, and aside from how it's used in the unit tests there are is no documentation as off now. It uses zipfile, minidom, re and unittest, so perfectly portable and platform independent.</p> <p>Since I don't blog, and I don't have any desire to turn this into a python library for OfficeOpen XML, I am stuck wondering where I should post this code. I have solved a problem that I am sure others will get in the future. So I want to post my code under public domain somewhere for anyone to copy and paste into their app and adjust to fix their problem.</p> <p>The implementation is simple, and here is a quick overview off the features:</p> <pre><code>workbook = Workbook(filename) # open a file for sheet in workbook: pass # iterate over the worksheets workbook["sheetname"] # access a sheet by name, also possible to do by index from 0 sheet["A1"] # Access cell sheet["A"] # Access column sheet["1"] # Access row cell.value # Cell value - only tested with ints and strings. </code></pre> <p>Thanks for all the replies. I was going to hoste it on activestate, but the page kept crashing when sending me the activation mail. So I can't activate my code to post it.</p> <p>My second choice was codeproject, and I wrote up a nice article about the file. Sadly that page crashes when I try to submit my post.</p> <p>So I put it on github for any to see and branch off: <a href="http://github.com/staale/python-xlsx/tree/master" rel="nofollow">http://github.com/staale/python-xlsx/tree/master</a></p> <p>I don't want to do all the work for the python project hosting, so that's out.</p> <p>Accepting the git answer, as that was the only thing that worked for me. And git rocks.</p> <p>Edit: Gah, lost my entire post at codeproject, and I did such a nice writeup. Screw it, I have spent more time trying to share this than it took coding it. So I am calling it done for my part as off now. Unless I decide to tweak it more later.</p>
4
2009-02-17T14:12:24Z
557,004
<p>err, with a more descriptive title, i am sure many people would have found it here itself.(but i wasn't aware of the not-a-question tag).</p> <p>Hence, you can get a free blog, and just put in the bits you want to share, that way you would also have a steady online reference whenever you need it.</p>
1
2009-02-17T14:18:13Z
[ "python", "excel-2007" ]
Where should I post my python code?
556,967
<p>Today I needed to parse some data out from an xlsx file (Office open XML Spreadsheet). I could have just opened the files in openoffice and exported to csv. However I will need to reimport data from this spreadsheet later, and I wanted to eliminate the manual operation.</p> <p>I searched on the net for xlsx parser, and all I found was a stackoverflow question asking the same thing: <a href="http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx">http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx</a></p> <p>So I rolled my own. </p> <p>It's 134 lines of code for the parsing and accessing off a spreadsheet, and 54 lines of code of unit tests. This of course is only tested on the 1 file I needed it, and aside from how it's used in the unit tests there are is no documentation as off now. It uses zipfile, minidom, re and unittest, so perfectly portable and platform independent.</p> <p>Since I don't blog, and I don't have any desire to turn this into a python library for OfficeOpen XML, I am stuck wondering where I should post this code. I have solved a problem that I am sure others will get in the future. So I want to post my code under public domain somewhere for anyone to copy and paste into their app and adjust to fix their problem.</p> <p>The implementation is simple, and here is a quick overview off the features:</p> <pre><code>workbook = Workbook(filename) # open a file for sheet in workbook: pass # iterate over the worksheets workbook["sheetname"] # access a sheet by name, also possible to do by index from 0 sheet["A1"] # Access cell sheet["A"] # Access column sheet["1"] # Access row cell.value # Cell value - only tested with ints and strings. </code></pre> <p>Thanks for all the replies. I was going to hoste it on activestate, but the page kept crashing when sending me the activation mail. So I can't activate my code to post it.</p> <p>My second choice was codeproject, and I wrote up a nice article about the file. Sadly that page crashes when I try to submit my post.</p> <p>So I put it on github for any to see and branch off: <a href="http://github.com/staale/python-xlsx/tree/master" rel="nofollow">http://github.com/staale/python-xlsx/tree/master</a></p> <p>I don't want to do all the work for the python project hosting, so that's out.</p> <p>Accepting the git answer, as that was the only thing that worked for me. And git rocks.</p> <p>Edit: Gah, lost my entire post at codeproject, and I did such a nice writeup. Screw it, I have spent more time trying to share this than it took coding it. So I am calling it done for my part as off now. Unless I decide to tweak it more later.</p>
4
2009-02-17T14:12:24Z
557,059
<p>It seems to me that <a href="http://pypi.python.org/pypi" rel="nofollow">Python Package Index</a> is the right place for you</p>
0
2009-02-17T14:28:50Z
[ "python", "excel-2007" ]
Where should I post my python code?
556,967
<p>Today I needed to parse some data out from an xlsx file (Office open XML Spreadsheet). I could have just opened the files in openoffice and exported to csv. However I will need to reimport data from this spreadsheet later, and I wanted to eliminate the manual operation.</p> <p>I searched on the net for xlsx parser, and all I found was a stackoverflow question asking the same thing: <a href="http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx">http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx</a></p> <p>So I rolled my own. </p> <p>It's 134 lines of code for the parsing and accessing off a spreadsheet, and 54 lines of code of unit tests. This of course is only tested on the 1 file I needed it, and aside from how it's used in the unit tests there are is no documentation as off now. It uses zipfile, minidom, re and unittest, so perfectly portable and platform independent.</p> <p>Since I don't blog, and I don't have any desire to turn this into a python library for OfficeOpen XML, I am stuck wondering where I should post this code. I have solved a problem that I am sure others will get in the future. So I want to post my code under public domain somewhere for anyone to copy and paste into their app and adjust to fix their problem.</p> <p>The implementation is simple, and here is a quick overview off the features:</p> <pre><code>workbook = Workbook(filename) # open a file for sheet in workbook: pass # iterate over the worksheets workbook["sheetname"] # access a sheet by name, also possible to do by index from 0 sheet["A1"] # Access cell sheet["A"] # Access column sheet["1"] # Access row cell.value # Cell value - only tested with ints and strings. </code></pre> <p>Thanks for all the replies. I was going to hoste it on activestate, but the page kept crashing when sending me the activation mail. So I can't activate my code to post it.</p> <p>My second choice was codeproject, and I wrote up a nice article about the file. Sadly that page crashes when I try to submit my post.</p> <p>So I put it on github for any to see and branch off: <a href="http://github.com/staale/python-xlsx/tree/master" rel="nofollow">http://github.com/staale/python-xlsx/tree/master</a></p> <p>I don't want to do all the work for the python project hosting, so that's out.</p> <p>Accepting the git answer, as that was the only thing that worked for me. And git rocks.</p> <p>Edit: Gah, lost my entire post at codeproject, and I did such a nice writeup. Screw it, I have spent more time trying to share this than it took coding it. So I am calling it done for my part as off now. Unless I decide to tweak it more later.</p>
4
2009-02-17T14:12:24Z
557,148
<p><a href="http://github.com/" rel="nofollow">GitHub</a> would also be a great place to post this. Especially as that would allow others to quickly fork their own copies and make any improvements or modifications they need. These changes would then also be available to anyone else who wants them.</p>
5
2009-02-17T14:46:36Z
[ "python", "excel-2007" ]
Where should I post my python code?
556,967
<p>Today I needed to parse some data out from an xlsx file (Office open XML Spreadsheet). I could have just opened the files in openoffice and exported to csv. However I will need to reimport data from this spreadsheet later, and I wanted to eliminate the manual operation.</p> <p>I searched on the net for xlsx parser, and all I found was a stackoverflow question asking the same thing: <a href="http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx">http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx</a></p> <p>So I rolled my own. </p> <p>It's 134 lines of code for the parsing and accessing off a spreadsheet, and 54 lines of code of unit tests. This of course is only tested on the 1 file I needed it, and aside from how it's used in the unit tests there are is no documentation as off now. It uses zipfile, minidom, re and unittest, so perfectly portable and platform independent.</p> <p>Since I don't blog, and I don't have any desire to turn this into a python library for OfficeOpen XML, I am stuck wondering where I should post this code. I have solved a problem that I am sure others will get in the future. So I want to post my code under public domain somewhere for anyone to copy and paste into their app and adjust to fix their problem.</p> <p>The implementation is simple, and here is a quick overview off the features:</p> <pre><code>workbook = Workbook(filename) # open a file for sheet in workbook: pass # iterate over the worksheets workbook["sheetname"] # access a sheet by name, also possible to do by index from 0 sheet["A1"] # Access cell sheet["A"] # Access column sheet["1"] # Access row cell.value # Cell value - only tested with ints and strings. </code></pre> <p>Thanks for all the replies. I was going to hoste it on activestate, but the page kept crashing when sending me the activation mail. So I can't activate my code to post it.</p> <p>My second choice was codeproject, and I wrote up a nice article about the file. Sadly that page crashes when I try to submit my post.</p> <p>So I put it on github for any to see and branch off: <a href="http://github.com/staale/python-xlsx/tree/master" rel="nofollow">http://github.com/staale/python-xlsx/tree/master</a></p> <p>I don't want to do all the work for the python project hosting, so that's out.</p> <p>Accepting the git answer, as that was the only thing that worked for me. And git rocks.</p> <p>Edit: Gah, lost my entire post at codeproject, and I did such a nice writeup. Screw it, I have spent more time trying to share this than it took coding it. So I am calling it done for my part as off now. Unless I decide to tweak it more later.</p>
4
2009-02-17T14:12:24Z
557,160
<p>If your code is short enough to copy and paste, you might want to post it as a <a href="http://code.activestate.com/recipes/langs/python/" rel="nofollow">Python recipe</a>. That site is a great resource for learning Python techniques and its best contents have been <a href="http://www.oreilly.com/catalog/9780596007973" rel="nofollow">compiled into a book</a>.</p> <p>If your code is reusable as-is then you should post your Python code in the <a href="http://python.org/pypi" rel="nofollow">Python Package Index</a> (pypi). Organize your source code, <a href="http://www.python.org/~jeremy/weblog/030924.html" rel="nofollow">read this tutorial</a> on how to write a <code>setup.py</code> for your package. Once you have your free pypi account and have written <code>setup.py</code>, run <code>python setup.py register</code> to claim your package's name and post its metadata to the index. <code>setup.py</code> can also <a href="http://docs.python.org/distutils/uploading.html" rel="nofollow" title="upload">upload</a> your package's source or binaries to pypi, for example <code>python setup.py sdist upload</code> would build and upload the <strong>s</strong>ource <strong>dist</strong>ribution.</p> <p>Once your package is a part of the Python Package Index, other Python programmers can download and install it automatically with a number of tools including <code>easy_install your_package</code>.</p>
2
2009-02-17T14:48:14Z
[ "python", "excel-2007" ]
Where should I post my python code?
556,967
<p>Today I needed to parse some data out from an xlsx file (Office open XML Spreadsheet). I could have just opened the files in openoffice and exported to csv. However I will need to reimport data from this spreadsheet later, and I wanted to eliminate the manual operation.</p> <p>I searched on the net for xlsx parser, and all I found was a stackoverflow question asking the same thing: <a href="http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx">http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx</a></p> <p>So I rolled my own. </p> <p>It's 134 lines of code for the parsing and accessing off a spreadsheet, and 54 lines of code of unit tests. This of course is only tested on the 1 file I needed it, and aside from how it's used in the unit tests there are is no documentation as off now. It uses zipfile, minidom, re and unittest, so perfectly portable and platform independent.</p> <p>Since I don't blog, and I don't have any desire to turn this into a python library for OfficeOpen XML, I am stuck wondering where I should post this code. I have solved a problem that I am sure others will get in the future. So I want to post my code under public domain somewhere for anyone to copy and paste into their app and adjust to fix their problem.</p> <p>The implementation is simple, and here is a quick overview off the features:</p> <pre><code>workbook = Workbook(filename) # open a file for sheet in workbook: pass # iterate over the worksheets workbook["sheetname"] # access a sheet by name, also possible to do by index from 0 sheet["A1"] # Access cell sheet["A"] # Access column sheet["1"] # Access row cell.value # Cell value - only tested with ints and strings. </code></pre> <p>Thanks for all the replies. I was going to hoste it on activestate, but the page kept crashing when sending me the activation mail. So I can't activate my code to post it.</p> <p>My second choice was codeproject, and I wrote up a nice article about the file. Sadly that page crashes when I try to submit my post.</p> <p>So I put it on github for any to see and branch off: <a href="http://github.com/staale/python-xlsx/tree/master" rel="nofollow">http://github.com/staale/python-xlsx/tree/master</a></p> <p>I don't want to do all the work for the python project hosting, so that's out.</p> <p>Accepting the git answer, as that was the only thing that worked for me. And git rocks.</p> <p>Edit: Gah, lost my entire post at codeproject, and I did such a nice writeup. Screw it, I have spent more time trying to share this than it took coding it. So I am calling it done for my part as off now. Unless I decide to tweak it more later.</p>
4
2009-02-17T14:12:24Z
557,727
<p>In general, <a href="http://www.codeproject.com/" rel="nofollow">CodeProject</a> is a great place to post code as long as you're willing to write a small article about the code. (One of the good things about CodeProject is that they do require some verbiage about the code.) The site gets an extraordinary amount of traffic, so anything you post there will be seen.</p>
1
2009-02-17T17:00:06Z
[ "python", "excel-2007" ]
Where should I post my python code?
556,967
<p>Today I needed to parse some data out from an xlsx file (Office open XML Spreadsheet). I could have just opened the files in openoffice and exported to csv. However I will need to reimport data from this spreadsheet later, and I wanted to eliminate the manual operation.</p> <p>I searched on the net for xlsx parser, and all I found was a stackoverflow question asking the same thing: <a href="http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx">http://stackoverflow.com/questions/173246/parsing-and-generating-microsoft-office-2007-files-docx-xlsx-pptx</a></p> <p>So I rolled my own. </p> <p>It's 134 lines of code for the parsing and accessing off a spreadsheet, and 54 lines of code of unit tests. This of course is only tested on the 1 file I needed it, and aside from how it's used in the unit tests there are is no documentation as off now. It uses zipfile, minidom, re and unittest, so perfectly portable and platform independent.</p> <p>Since I don't blog, and I don't have any desire to turn this into a python library for OfficeOpen XML, I am stuck wondering where I should post this code. I have solved a problem that I am sure others will get in the future. So I want to post my code under public domain somewhere for anyone to copy and paste into their app and adjust to fix their problem.</p> <p>The implementation is simple, and here is a quick overview off the features:</p> <pre><code>workbook = Workbook(filename) # open a file for sheet in workbook: pass # iterate over the worksheets workbook["sheetname"] # access a sheet by name, also possible to do by index from 0 sheet["A1"] # Access cell sheet["A"] # Access column sheet["1"] # Access row cell.value # Cell value - only tested with ints and strings. </code></pre> <p>Thanks for all the replies. I was going to hoste it on activestate, but the page kept crashing when sending me the activation mail. So I can't activate my code to post it.</p> <p>My second choice was codeproject, and I wrote up a nice article about the file. Sadly that page crashes when I try to submit my post.</p> <p>So I put it on github for any to see and branch off: <a href="http://github.com/staale/python-xlsx/tree/master" rel="nofollow">http://github.com/staale/python-xlsx/tree/master</a></p> <p>I don't want to do all the work for the python project hosting, so that's out.</p> <p>Accepting the git answer, as that was the only thing that worked for me. And git rocks.</p> <p>Edit: Gah, lost my entire post at codeproject, and I did such a nice writeup. Screw it, I have spent more time trying to share this than it took coding it. So I am calling it done for my part as off now. Unless I decide to tweak it more later.</p>
4
2009-02-17T14:12:24Z
562,280
<p>May I humbly suggest my site; <a href="http://utilitymill.com" rel="nofollow">http://utilitymill.com</a>. It lets you not only post your Python code, but also makes it into a runnable web utility. </p> <p>Users can collaberate on the code and write-ups, and it even gives you an automatic RESTful API for the utility for free.</p>
0
2009-02-18T18:28:00Z
[ "python", "excel-2007" ]
Quick and dirty stripchart in python?
557,069
<p>I have some python code that receives a message every so often containing a timestamp and an edge transition, either low-to-high, or high-to-low. I'd like to graph each transition on a stripchart for a quick and dirty visualization of the digital waveform with the minimal amount of effort.</p> <p>Can you recommend any methods or packages that would make this easy?</p> <p>I'm also not opposed to exporting the data in, for instance, csv format and loading it into another program if that would be easier.</p> <p>Edit:</p> <p>Tried CairoPlot:</p> <pre><code>&gt;&gt;&gt; data = [(10, 0), (11, 1), (12.5, 0), (15, 1)] &gt;&gt;&gt; def fn(t): ... for d in data: ... if t &gt; d[0]: ... return d[1] ... return data[-1][1] ... &gt;&gt;&gt; CairoPlot.function_plot( 'tester.png', data, 500, 300, discrete = True, h_bounds=( data[0][0],data[-1][0]), step = 1 ) </code></pre> <p>This pinned my CPU at 100% for more than 10 minutes and was steadily eating memory. I killed it before it used up all of swap. Am I doing something wrong or is CairoPlot just broken?</p> <p>Further edit:</p> <p>I now have something more workable using CairoPlot, based loosely on the above code. However, it's not perfect because of the resolution: I may need up to tens of nanoseconds (1e-8) resolution in order to catch some of the shorter pulses. For a multi-second graph, this takes a <em>very</em> long time with this method.</p>
1
2009-02-17T14:30:39Z
557,091
<p>I haven't use it myself, but perhaps <a href="http://linil.wordpress.com/2008/06/14/cairoplot-plotting-graphics-using-python-and-cairo/" rel="nofollow">Cairo Plot</a> is worth taking a look at.</p>
2
2009-02-17T14:35:19Z
[ "python", "graphing", "stripchart" ]
Quick and dirty stripchart in python?
557,069
<p>I have some python code that receives a message every so often containing a timestamp and an edge transition, either low-to-high, or high-to-low. I'd like to graph each transition on a stripchart for a quick and dirty visualization of the digital waveform with the minimal amount of effort.</p> <p>Can you recommend any methods or packages that would make this easy?</p> <p>I'm also not opposed to exporting the data in, for instance, csv format and loading it into another program if that would be easier.</p> <p>Edit:</p> <p>Tried CairoPlot:</p> <pre><code>&gt;&gt;&gt; data = [(10, 0), (11, 1), (12.5, 0), (15, 1)] &gt;&gt;&gt; def fn(t): ... for d in data: ... if t &gt; d[0]: ... return d[1] ... return data[-1][1] ... &gt;&gt;&gt; CairoPlot.function_plot( 'tester.png', data, 500, 300, discrete = True, h_bounds=( data[0][0],data[-1][0]), step = 1 ) </code></pre> <p>This pinned my CPU at 100% for more than 10 minutes and was steadily eating memory. I killed it before it used up all of swap. Am I doing something wrong or is CairoPlot just broken?</p> <p>Further edit:</p> <p>I now have something more workable using CairoPlot, based loosely on the above code. However, it's not perfect because of the resolution: I may need up to tens of nanoseconds (1e-8) resolution in order to catch some of the shorter pulses. For a multi-second graph, this takes a <em>very</em> long time with this method.</p>
1
2009-02-17T14:30:39Z
557,181
<p>you may try using CairoPlot:</p> <pre><code>import CairoPlot #the data list stands for your low-to-high (1) and high-to-low (0) data data = lambda x : [0,0,1,1,0,0,1][x] CairoPlot.function_plot( 'Up_and_Down', data, 500, 300, discrete = True, x_bounds=( 0,len(data) - 1 ), step = 1 ) </code></pre> <p>For more information, check <a href="http://linil.wordpress.com/2008/09/16/cairoplot-11/" rel="nofollow">CairoPlot</a></p> <p>Edit:</p> <p>I didn't understand your function fn(t) here. The idea of the function_plot is to plot a function not a vector.</p> <p>To plot those points, you could use function_plot on this way:</p> <pre><code>#notice I have split your data into two different vectors, #one for x axis and the other one for y axis x_data = [10, 11, 12.5, 15] y_data = [0, 1, 0, 1] def get_data( i ): if i in x_data : return y_data[x_data.index(i)] else : return 0 CairoPlot.function_plot( 'Up_and_Down', get_data, 500, 300, discrete = True, x_bounds=( 0,20 ), step = 0.5 ) </code></pre> <p>I guess that will work</p> <p>For the 100% pinning CPU, that shouldn't happen... I'll take a look at it later today. Thanks for pointing it \o_</p>
1
2009-02-17T14:52:53Z
[ "python", "graphing", "stripchart" ]
Quick and dirty stripchart in python?
557,069
<p>I have some python code that receives a message every so often containing a timestamp and an edge transition, either low-to-high, or high-to-low. I'd like to graph each transition on a stripchart for a quick and dirty visualization of the digital waveform with the minimal amount of effort.</p> <p>Can you recommend any methods or packages that would make this easy?</p> <p>I'm also not opposed to exporting the data in, for instance, csv format and loading it into another program if that would be easier.</p> <p>Edit:</p> <p>Tried CairoPlot:</p> <pre><code>&gt;&gt;&gt; data = [(10, 0), (11, 1), (12.5, 0), (15, 1)] &gt;&gt;&gt; def fn(t): ... for d in data: ... if t &gt; d[0]: ... return d[1] ... return data[-1][1] ... &gt;&gt;&gt; CairoPlot.function_plot( 'tester.png', data, 500, 300, discrete = True, h_bounds=( data[0][0],data[-1][0]), step = 1 ) </code></pre> <p>This pinned my CPU at 100% for more than 10 minutes and was steadily eating memory. I killed it before it used up all of swap. Am I doing something wrong or is CairoPlot just broken?</p> <p>Further edit:</p> <p>I now have something more workable using CairoPlot, based loosely on the above code. However, it's not perfect because of the resolution: I may need up to tens of nanoseconds (1e-8) resolution in order to catch some of the shorter pulses. For a multi-second graph, this takes a <em>very</em> long time with this method.</p>
1
2009-02-17T14:30:39Z
557,542
<p><a href="http://bitworking.org/projects/sparklines/" rel="nofollow">http://bitworking.org/projects/sparklines/</a> provides a tiny graph for you.</p>
0
2009-02-17T16:07:12Z
[ "python", "graphing", "stripchart" ]
Quick and dirty stripchart in python?
557,069
<p>I have some python code that receives a message every so often containing a timestamp and an edge transition, either low-to-high, or high-to-low. I'd like to graph each transition on a stripchart for a quick and dirty visualization of the digital waveform with the minimal amount of effort.</p> <p>Can you recommend any methods or packages that would make this easy?</p> <p>I'm also not opposed to exporting the data in, for instance, csv format and loading it into another program if that would be easier.</p> <p>Edit:</p> <p>Tried CairoPlot:</p> <pre><code>&gt;&gt;&gt; data = [(10, 0), (11, 1), (12.5, 0), (15, 1)] &gt;&gt;&gt; def fn(t): ... for d in data: ... if t &gt; d[0]: ... return d[1] ... return data[-1][1] ... &gt;&gt;&gt; CairoPlot.function_plot( 'tester.png', data, 500, 300, discrete = True, h_bounds=( data[0][0],data[-1][0]), step = 1 ) </code></pre> <p>This pinned my CPU at 100% for more than 10 minutes and was steadily eating memory. I killed it before it used up all of swap. Am I doing something wrong or is CairoPlot just broken?</p> <p>Further edit:</p> <p>I now have something more workable using CairoPlot, based loosely on the above code. However, it's not perfect because of the resolution: I may need up to tens of nanoseconds (1e-8) resolution in order to catch some of the shorter pulses. For a multi-second graph, this takes a <em>very</em> long time with this method.</p>
1
2009-02-17T14:30:39Z
557,593
<p><a href="http://www.gnuplot.info/" rel="nofollow">GnuPlot</a> is a the old reliable answer here, easy graphing with lots of options. I believe there are python bindings but it's probably easier to export your data and run it through regular gnuplot. Here's an ancient <a href="http://parand.com/docs/gnuplot.html" rel="nofollow">quick start doc</a> for it.</p> <p>I'm also using <a href="http://matplotlib.sourceforge.net/" rel="nofollow">matplotlib</a> with great success for larger data sizes.</p>
0
2009-02-17T16:17:38Z
[ "python", "graphing", "stripchart" ]
Quick and dirty stripchart in python?
557,069
<p>I have some python code that receives a message every so often containing a timestamp and an edge transition, either low-to-high, or high-to-low. I'd like to graph each transition on a stripchart for a quick and dirty visualization of the digital waveform with the minimal amount of effort.</p> <p>Can you recommend any methods or packages that would make this easy?</p> <p>I'm also not opposed to exporting the data in, for instance, csv format and loading it into another program if that would be easier.</p> <p>Edit:</p> <p>Tried CairoPlot:</p> <pre><code>&gt;&gt;&gt; data = [(10, 0), (11, 1), (12.5, 0), (15, 1)] &gt;&gt;&gt; def fn(t): ... for d in data: ... if t &gt; d[0]: ... return d[1] ... return data[-1][1] ... &gt;&gt;&gt; CairoPlot.function_plot( 'tester.png', data, 500, 300, discrete = True, h_bounds=( data[0][0],data[-1][0]), step = 1 ) </code></pre> <p>This pinned my CPU at 100% for more than 10 minutes and was steadily eating memory. I killed it before it used up all of swap. Am I doing something wrong or is CairoPlot just broken?</p> <p>Further edit:</p> <p>I now have something more workable using CairoPlot, based loosely on the above code. However, it's not perfect because of the resolution: I may need up to tens of nanoseconds (1e-8) resolution in order to catch some of the shorter pulses. For a multi-second graph, this takes a <em>very</em> long time with this method.</p>
1
2009-02-17T14:30:39Z
558,281
<p><a href="http://matplotlib.sourceforge.net" rel="nofollow">Matplotlib</a> might work. Take a look at this <a href="http://matplotlib.sourceforge.net/examples/animation/strip_chart_demo.html" rel="nofollow">strip chart demo</a>.</p>
2
2009-02-17T19:04:22Z
[ "python", "graphing", "stripchart" ]
Quick and dirty stripchart in python?
557,069
<p>I have some python code that receives a message every so often containing a timestamp and an edge transition, either low-to-high, or high-to-low. I'd like to graph each transition on a stripchart for a quick and dirty visualization of the digital waveform with the minimal amount of effort.</p> <p>Can you recommend any methods or packages that would make this easy?</p> <p>I'm also not opposed to exporting the data in, for instance, csv format and loading it into another program if that would be easier.</p> <p>Edit:</p> <p>Tried CairoPlot:</p> <pre><code>&gt;&gt;&gt; data = [(10, 0), (11, 1), (12.5, 0), (15, 1)] &gt;&gt;&gt; def fn(t): ... for d in data: ... if t &gt; d[0]: ... return d[1] ... return data[-1][1] ... &gt;&gt;&gt; CairoPlot.function_plot( 'tester.png', data, 500, 300, discrete = True, h_bounds=( data[0][0],data[-1][0]), step = 1 ) </code></pre> <p>This pinned my CPU at 100% for more than 10 minutes and was steadily eating memory. I killed it before it used up all of swap. Am I doing something wrong or is CairoPlot just broken?</p> <p>Further edit:</p> <p>I now have something more workable using CairoPlot, based loosely on the above code. However, it's not perfect because of the resolution: I may need up to tens of nanoseconds (1e-8) resolution in order to catch some of the shorter pulses. For a multi-second graph, this takes a <em>very</em> long time with this method.</p>
1
2009-02-17T14:30:39Z
7,605,445
<p>For a realtime stripchart application using only tkinter (no external packages required), see <a href="http://stackoverflow.com/questions/457246/what-is-the-best-real-time-plotting-widget-for-wxpython/7605072#7605072">What is the best real time plotting widget for wxPython?</a>.</p> <p>If I understand your question, you are receiving messages in realtime with nanosecond resolution timestamps, but you don't expect to see 10^9 messages per second. If the average message rate is low (100 messages per second or fewer), I'd just ignore the timestamp and plot the transitions one message at a time. If the graph timescale is 10ms per pixel, 4 transitions would be drawn over 40ms, but at least you wouldn't miss seeing that something happened.</p>
0
2011-09-30T02:44:04Z
[ "python", "graphing", "stripchart" ]
Quick and dirty stripchart in python?
557,069
<p>I have some python code that receives a message every so often containing a timestamp and an edge transition, either low-to-high, or high-to-low. I'd like to graph each transition on a stripchart for a quick and dirty visualization of the digital waveform with the minimal amount of effort.</p> <p>Can you recommend any methods or packages that would make this easy?</p> <p>I'm also not opposed to exporting the data in, for instance, csv format and loading it into another program if that would be easier.</p> <p>Edit:</p> <p>Tried CairoPlot:</p> <pre><code>&gt;&gt;&gt; data = [(10, 0), (11, 1), (12.5, 0), (15, 1)] &gt;&gt;&gt; def fn(t): ... for d in data: ... if t &gt; d[0]: ... return d[1] ... return data[-1][1] ... &gt;&gt;&gt; CairoPlot.function_plot( 'tester.png', data, 500, 300, discrete = True, h_bounds=( data[0][0],data[-1][0]), step = 1 ) </code></pre> <p>This pinned my CPU at 100% for more than 10 minutes and was steadily eating memory. I killed it before it used up all of swap. Am I doing something wrong or is CairoPlot just broken?</p> <p>Further edit:</p> <p>I now have something more workable using CairoPlot, based loosely on the above code. However, it's not perfect because of the resolution: I may need up to tens of nanoseconds (1e-8) resolution in order to catch some of the shorter pulses. For a multi-second graph, this takes a <em>very</em> long time with this method.</p>
1
2009-02-17T14:30:39Z
34,702,512
<pre><code>#simple stripchart using pygame import pygame, math, random white=(255,255,255) #define colors red=(255,0,0) pygame.init() #initialize pygame width=1000 height=200 size=[width,height] #select window size screen=pygame.display.set_mode(size) #create screen pygame.display.set_caption("Python Strip Chart") clock=pygame.time.Clock() data=[] for x in range (0,width+1): data.append([x,100]) # -------- Event Loop ----------- while (not pygame.event.peek(pygame.QUIT)): #user closed window for x in range (0,width): data[x][1]=data[x+1][1] #move points to the left t=pygame.time.get_ticks() #run time in milliseconds noise=random.randint(-10,10) #create random noise data[width][1]=100.-50.*math.sin(t/200.) +noise #new value screen.fill(white) #erase the old line pygame.draw.lines(screen, red, 0,data,3) #draw a new line clock.tick(150) #regulate speed pygame.display.flip() #display the new screen pygame.quit () #exit if event loop ends </code></pre>
1
2016-01-10T05:49:55Z
[ "python", "graphing", "stripchart" ]
Which Version of TurboGears should I use for a new project?
557,101
<p>I'm planing a new project and I want to use <a href="http://www.turbogears.org" rel="nofollow">TurboGears</a>. The problem is: I'm not sure which version to choose. There are three choices: Turbogears 1.0.8 (stable) Turbogears 1.1 (beta 3) Turbogears 2.0 (beta 4)</p> <p>As this is a new project I dont want to choose the wrong framework. So where are the differeneces, how "beta" is 2.0?</p> <p>Thanks for any help!</p>
0
2009-02-17T14:38:19Z
557,178
<p>I personally would go with TG2 (but would also look at other frameworks such as Pylons or repoze.bfg) esp. if it's a new project. Remember that you might need to upgrade at some point (or want to at least). TG2 also is offers full WSGI support which gains more and more traction and is IMHO also something you really want. </p> <p>For me the most important thing these days is always how good the code of that framework looks like because you never know when you need to dig into it to try to understand some misbehaviour or even fix a bug (regardless of what version).</p> <p>Another important aspect is IMHO the community, so hanging around in IRC channels or on mailing lists for a bit might help you to make better decision. </p> <p>Maybe <a href="http://compoundthinking.com/blog/index.php/2008/07/31/10-reasons-why-the-new-turbogears-2-alpha-is-worth-a-look/" rel="nofollow">these 10 reasons to use TG2</a> also help. </p>
5
2009-02-17T14:52:16Z
[ "python", "project", "turbogears" ]
Which Version of TurboGears should I use for a new project?
557,101
<p>I'm planing a new project and I want to use <a href="http://www.turbogears.org" rel="nofollow">TurboGears</a>. The problem is: I'm not sure which version to choose. There are three choices: Turbogears 1.0.8 (stable) Turbogears 1.1 (beta 3) Turbogears 2.0 (beta 4)</p> <p>As this is a new project I dont want to choose the wrong framework. So where are the differeneces, how "beta" is 2.0?</p> <p>Thanks for any help!</p>
0
2009-02-17T14:38:19Z
557,498
<p>Yes, TG2. TG1.0.x is legacy, and TG1.1 is meant as a stepping stone to TG2 for legacy apps.</p> <p>I'd look very seriously at Pylons and Django too.</p>
1
2009-02-17T15:56:43Z
[ "python", "project", "turbogears" ]
How to re-use a reusable app in Django
557,171
<h2>Hello Django experts</h2> <p>I am trying to create my first site in Django and as I'm looking for example apps out there to draw inspiration from, I constantly stumble upon a term called <em>"reusable apps"</em>.</p> <p>I understand the <em>concept</em> of an app that is reusable easy enough, but the means of reusing an app in Django are quite lost for me. Few questions that are bugging me in the whole business are:</p> <p>What is the preferred way to re-use an existing Django app? Where do I put it and how do I reference it?</p> <p>From what I understand, the recommendation is to put it on your "PYTHONPATH", but that breaks as soon as I need to deploy my app to a remote location that I have limited access to (e.g. on a hosting service).</p> <p>So, if I develop my site on my local computer and intend to deploy it on an ISP where I only have ftp access, how do I re-use 3rd party Django apps so that if I deploy my site, the site keeps working (e.g. the only thing I can count on is that the service provider has Python 2.5 and Django 1.x installed)?</p> <p>How do I organize my Django project so that I could easily deploy it along with all of the reusable apps I want to use?</p>
17
2009-02-17T14:50:22Z
557,509
<p>In general, the only thing required to use a reusable app is to make sure it's on <code>sys.path</code>, so that you can import it from Python code. In most cases (if the author follows best practice), the reusable app tarball or bundle will contain a top-level directory with docs, a README, a <code>setup.py</code>, and then a subdirectory containing the actual app (see <a href="http://code.google.com/p/django-voting/source/browse/#svn/trunk" rel="nofollow">django-voting</a> for an example; the app itself is in the "voting" subdirectory). This subdirectory is what needs to be placed in your Python path. Possible methods for doing that include:</p> <ul> <li>running <code>pip install appname</code>, if the app has been uploaded to <a href="https://pypi.python.org/pypi" rel="nofollow">PyPI</a> (these days most are)</li> <li>installing the app with <code>setup.py install</code> (this has the same result as <code>pip install appname</code>, but requires that you first download and unpack the code yourself; pip will do that for you)</li> <li>manually symlinking the code directory to your Python site-packages directory</li> <li>using software like <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a> to create a "virtual Python environment" that has its own site-packages directory, and then running <code>setup.py install</code> or <code>pip install appname</code> with that virtualenv active, or placing or symlinking the app in the virtualenv's site-packages (highly recommended over all the "global installation" options, if you value your future sanity)</li> <li>placing the application in some directory where you intend to place various apps, and then adding that directory to the PYTHONPATH environment variable</li> </ul> <p>You'll know you've got it in the right place if you can fire up a Python interpreter and "import voting" (for example) without getting an ImportError.</p> <p>On a server where you have FTP access only, your only option is really the last one, and they have to set it up for you. If they claim to support Django they must provide <em>some</em> place where you can upload packages and they will be available for importing in Python. Without knowing details of your webhost, it's impossible to say how they structure that for you.</p>
25
2009-02-17T15:59:50Z
[ "python", "django", "code-reuse" ]
How to re-use a reusable app in Django
557,171
<h2>Hello Django experts</h2> <p>I am trying to create my first site in Django and as I'm looking for example apps out there to draw inspiration from, I constantly stumble upon a term called <em>"reusable apps"</em>.</p> <p>I understand the <em>concept</em> of an app that is reusable easy enough, but the means of reusing an app in Django are quite lost for me. Few questions that are bugging me in the whole business are:</p> <p>What is the preferred way to re-use an existing Django app? Where do I put it and how do I reference it?</p> <p>From what I understand, the recommendation is to put it on your "PYTHONPATH", but that breaks as soon as I need to deploy my app to a remote location that I have limited access to (e.g. on a hosting service).</p> <p>So, if I develop my site on my local computer and intend to deploy it on an ISP where I only have ftp access, how do I re-use 3rd party Django apps so that if I deploy my site, the site keeps working (e.g. the only thing I can count on is that the service provider has Python 2.5 and Django 1.x installed)?</p> <p>How do I organize my Django project so that I could easily deploy it along with all of the reusable apps I want to use?</p>
17
2009-02-17T14:50:22Z
3,710,136
<p>An old question, but here's what I do:</p> <p>If you're using a version control system (VCS), I suggest putting all of the reusable apps and libraries (including django) that your software needs in the VCS. If you don't want to put them directly under your project root, you can modify settings.py to add their location to sys.path.</p> <p>After that deployment is as simple as cloning or checking out the VCS repository to wherever you want to use it.</p> <p>This has two added benefits:</p> <ul> <li>Version mismatches; your software always uses the version that you tested it with, and not the version that was available at the time of deployment.</li> <li>If multiple people work on the project, nobody else has to deal with installing the dependencies.</li> </ul> <p>When it's time to update a component's version, update it in your VCS and then propagate the update to your deployments via it.</p>
2
2010-09-14T15:01:39Z
[ "python", "django", "code-reuse" ]
Converting a database-driven (non-OO) python script into a non-database driven, OO-script
557,199
<p>I have some software that is heavily dependent on MySQL, and is written in python without any class definitions. For performance reasons, and because the database is really just being used to store and retrieve large amounts of data, I'd like to convert this to an object-oriented python script that does not use the database at all.</p> <p>So my plan is to export the database tables to a set of files (not many -- it's a pretty simple database; it's big in that it has a lot of rows, but only a few tables, each of which has just two or three columns).</p> <p>Then I plan to read the data in, and have a set of functions which provide access to and operations on the data.</p> <p>My question is this:</p> <p>is there a preferred way to convert a set of database tables to classes and objects? For example, if I have a table which contains fruit, where each fruit has an id and a name, would I have a "CollectionOfFruit" class which contains a list of "Fruit" objects, or would I just have a "CollectionOfFruit" class which contains a list of tuples? Or would I just have a list of Fruit objects?</p> <p>I don't want to add any extra frameworks, because I want this code to be easy to transfer to different machines. So I'm really just looking for general advice on how to represent data that might more naturally be stored in database tables, in objects in Python.</p> <p>Alternatively, is there a good book I should read that would point me in the right direction on this?</p>
0
2009-02-17T14:56:13Z
557,241
<p>There's no "one size fits all" answer for this -- it'll depend a lot on the data and how it's used in the application. If the data and usage are simple enough you might want to store your fruit in a dict with id as key and the rest of the data as tuples. Or not. It totally depends. If there's a guiding principle out there then it's to extract the underlying requirements of the app and then write code against those requirements.</p>
1
2009-02-17T15:06:14Z
[ "python", "object" ]
Converting a database-driven (non-OO) python script into a non-database driven, OO-script
557,199
<p>I have some software that is heavily dependent on MySQL, and is written in python without any class definitions. For performance reasons, and because the database is really just being used to store and retrieve large amounts of data, I'd like to convert this to an object-oriented python script that does not use the database at all.</p> <p>So my plan is to export the database tables to a set of files (not many -- it's a pretty simple database; it's big in that it has a lot of rows, but only a few tables, each of which has just two or three columns).</p> <p>Then I plan to read the data in, and have a set of functions which provide access to and operations on the data.</p> <p>My question is this:</p> <p>is there a preferred way to convert a set of database tables to classes and objects? For example, if I have a table which contains fruit, where each fruit has an id and a name, would I have a "CollectionOfFruit" class which contains a list of "Fruit" objects, or would I just have a "CollectionOfFruit" class which contains a list of tuples? Or would I just have a list of Fruit objects?</p> <p>I don't want to add any extra frameworks, because I want this code to be easy to transfer to different machines. So I'm really just looking for general advice on how to represent data that might more naturally be stored in database tables, in objects in Python.</p> <p>Alternatively, is there a good book I should read that would point me in the right direction on this?</p>
0
2009-02-17T14:56:13Z
557,279
<p>you could have a fruit class with id and name instance variables. and a function to read/write the information from a file, and maybe a class variable to keep track of the number of fruits (objects) created</p>
1
2009-02-17T15:14:45Z
[ "python", "object" ]
Converting a database-driven (non-OO) python script into a non-database driven, OO-script
557,199
<p>I have some software that is heavily dependent on MySQL, and is written in python without any class definitions. For performance reasons, and because the database is really just being used to store and retrieve large amounts of data, I'd like to convert this to an object-oriented python script that does not use the database at all.</p> <p>So my plan is to export the database tables to a set of files (not many -- it's a pretty simple database; it's big in that it has a lot of rows, but only a few tables, each of which has just two or three columns).</p> <p>Then I plan to read the data in, and have a set of functions which provide access to and operations on the data.</p> <p>My question is this:</p> <p>is there a preferred way to convert a set of database tables to classes and objects? For example, if I have a table which contains fruit, where each fruit has an id and a name, would I have a "CollectionOfFruit" class which contains a list of "Fruit" objects, or would I just have a "CollectionOfFruit" class which contains a list of tuples? Or would I just have a list of Fruit objects?</p> <p>I don't want to add any extra frameworks, because I want this code to be easy to transfer to different machines. So I'm really just looking for general advice on how to represent data that might more naturally be stored in database tables, in objects in Python.</p> <p>Alternatively, is there a good book I should read that would point me in the right direction on this?</p>
0
2009-02-17T14:56:13Z
557,291
<p>Generally you want your Objects to absolutely match your "real world entities".</p> <p>Since you're starting from a database, it's not always the case that the database has any real-world fidelity, either. Some database designs are simply awful.</p> <p>If your database has reasonable models for Fruit, that's where you start. Get that right first.</p> <p>A "collection" may -- or may not -- be an artificial construct that's part of the solution algorithm, not really a proper part of the problem. Usually collections <em>are</em> part of the problem, and you should design those classes, also.</p> <p>Other times, however, the collection is an artifact of having used a database, and a simple Python list is all you need.</p> <p>Still other times, the collection is actually a proper mapping from some unique key value to an entity, in which case, it's a Python dictionary.</p> <p>And sometimes, the collection is a proper mapping from some non-unique key value to some collection of entities, in which case it's a Python <code>collections.defaultdict(list)</code>.</p> <p>Start with the fundamental, real-world-like entities. Those get class definitions.</p> <p>Collections may use built-in Python collections or may require their own classes.</p>
2
2009-02-17T15:17:01Z
[ "python", "object" ]
Converting a database-driven (non-OO) python script into a non-database driven, OO-script
557,199
<p>I have some software that is heavily dependent on MySQL, and is written in python without any class definitions. For performance reasons, and because the database is really just being used to store and retrieve large amounts of data, I'd like to convert this to an object-oriented python script that does not use the database at all.</p> <p>So my plan is to export the database tables to a set of files (not many -- it's a pretty simple database; it's big in that it has a lot of rows, but only a few tables, each of which has just two or three columns).</p> <p>Then I plan to read the data in, and have a set of functions which provide access to and operations on the data.</p> <p>My question is this:</p> <p>is there a preferred way to convert a set of database tables to classes and objects? For example, if I have a table which contains fruit, where each fruit has an id and a name, would I have a "CollectionOfFruit" class which contains a list of "Fruit" objects, or would I just have a "CollectionOfFruit" class which contains a list of tuples? Or would I just have a list of Fruit objects?</p> <p>I don't want to add any extra frameworks, because I want this code to be easy to transfer to different machines. So I'm really just looking for general advice on how to represent data that might more naturally be stored in database tables, in objects in Python.</p> <p>Alternatively, is there a good book I should read that would point me in the right direction on this?</p>
0
2009-02-17T14:56:13Z
557,403
<p>In the simple case <a href="http://docs.python.org/dev/library/collections.html#collections.namedtuple" rel="nofollow">namedtuples</a> let get you started:</p> <pre><code>&gt;&gt;&gt; from collections import namedtuple &gt;&gt;&gt; Fruit = namedtuple("Fruit", "name weight color") &gt;&gt;&gt; fruits = [Fruit(*row) for row in cursor.execute('select * from fruits')] </code></pre> <p><code>Fruit</code> is equivalent to the following class:</p> <pre><code>&gt;&gt;&gt; Fruit = namedtuple("Fruit", "name weight color", verbose=True) class Fruit(tuple): 'Fruit(name, weight, color)' __slots__ = () _fields = ('name', 'weight', 'color') def __new__(cls, name, weight, color): return tuple.__new__(cls, (name, weight, color)) @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new Fruit object from a sequence or iterable' result = new(cls, iterable) if len(result) != 3: raise TypeError('Expected 3 arguments, got %d' % len(result)) return result def __repr__(self): return 'Fruit(name=%r, weight=%r, color=%r)' % self def _asdict(t): 'Return a new dict which maps field names to their values' return {'name': t[0], 'weight': t[1], 'color': t[2]} def _replace(self, **kwds): 'Return a new Fruit object replacing specified fields with new values' result = self._make(map(kwds.pop, ('name', 'weight', 'color'), self)) if kwds: raise ValueError('Got unexpected field names: %r' % kwds.keys()) return result def __getnewargs__(self): return tuple(self) name = property(itemgetter(0)) weight = property(itemgetter(1)) color = property(itemgetter(2)) </code></pre>
1
2009-02-17T15:36:39Z
[ "python", "object" ]
Converting a database-driven (non-OO) python script into a non-database driven, OO-script
557,199
<p>I have some software that is heavily dependent on MySQL, and is written in python without any class definitions. For performance reasons, and because the database is really just being used to store and retrieve large amounts of data, I'd like to convert this to an object-oriented python script that does not use the database at all.</p> <p>So my plan is to export the database tables to a set of files (not many -- it's a pretty simple database; it's big in that it has a lot of rows, but only a few tables, each of which has just two or three columns).</p> <p>Then I plan to read the data in, and have a set of functions which provide access to and operations on the data.</p> <p>My question is this:</p> <p>is there a preferred way to convert a set of database tables to classes and objects? For example, if I have a table which contains fruit, where each fruit has an id and a name, would I have a "CollectionOfFruit" class which contains a list of "Fruit" objects, or would I just have a "CollectionOfFruit" class which contains a list of tuples? Or would I just have a list of Fruit objects?</p> <p>I don't want to add any extra frameworks, because I want this code to be easy to transfer to different machines. So I'm really just looking for general advice on how to represent data that might more naturally be stored in database tables, in objects in Python.</p> <p>Alternatively, is there a good book I should read that would point me in the right direction on this?</p>
0
2009-02-17T14:56:13Z
557,473
<p>If the data is a natural fit for database tables ("rectangular data"), why not convert it to sqlite? It's portable -- just one file to move the db around, and sqlite is available anywhere you have python (2.5 and above anyway).</p>
5
2009-02-17T15:51:38Z
[ "python", "object" ]
Converting a database-driven (non-OO) python script into a non-database driven, OO-script
557,199
<p>I have some software that is heavily dependent on MySQL, and is written in python without any class definitions. For performance reasons, and because the database is really just being used to store and retrieve large amounts of data, I'd like to convert this to an object-oriented python script that does not use the database at all.</p> <p>So my plan is to export the database tables to a set of files (not many -- it's a pretty simple database; it's big in that it has a lot of rows, but only a few tables, each of which has just two or three columns).</p> <p>Then I plan to read the data in, and have a set of functions which provide access to and operations on the data.</p> <p>My question is this:</p> <p>is there a preferred way to convert a set of database tables to classes and objects? For example, if I have a table which contains fruit, where each fruit has an id and a name, would I have a "CollectionOfFruit" class which contains a list of "Fruit" objects, or would I just have a "CollectionOfFruit" class which contains a list of tuples? Or would I just have a list of Fruit objects?</p> <p>I don't want to add any extra frameworks, because I want this code to be easy to transfer to different machines. So I'm really just looking for general advice on how to represent data that might more naturally be stored in database tables, in objects in Python.</p> <p>Alternatively, is there a good book I should read that would point me in the right direction on this?</p>
0
2009-02-17T14:56:13Z
558,619
<p>Another way would be to use the ZODB to directly store objects persistently. The only thing you have to do is to derive your classes from Peristent and everything from the root object up is then automatically stored in that database as an object. The root object comes from the ZODB connection. There are many backends available and the default is simple a file.</p> <p>A class could then look like this:</p> <pre><code>class Collection(persistent.Persistent): def __init__(self, fruit = []): self.fruit = fruit class Fruit(peristent.Persistent): def __init__(self, name): self.name = name </code></pre> <p>Assuming you have the root object you can then do:</p> <pre><code>fruit = Fruit("apple") root.collection = Collection([fruit]) </code></pre> <p>and it's stored in the database automatically. You can find it again by simply looking accessing 'collection' from the root object:</p> <pre><code>print root.collection.fruit </code></pre> <p>You can also derive subclasses from e.g. Fruit as usual.</p> <p>Useful links with more information:</p> <ul> <li><a href="http://new.zope.org/projects/zodb" rel="nofollow">The new ZODB homepage</a> </li> <li><a href="http://new.zope.org/projects/zodb/tutorial" rel="nofollow">a ZODB tutorial</a></li> </ul> <p>That way you still are able to use the full power of Python objects and there is no need to serialize something e.g. via an ORM but you still have an easy way to store your data.</p>
1
2009-02-17T20:38:29Z
[ "python", "object" ]
Converting a database-driven (non-OO) python script into a non-database driven, OO-script
557,199
<p>I have some software that is heavily dependent on MySQL, and is written in python without any class definitions. For performance reasons, and because the database is really just being used to store and retrieve large amounts of data, I'd like to convert this to an object-oriented python script that does not use the database at all.</p> <p>So my plan is to export the database tables to a set of files (not many -- it's a pretty simple database; it's big in that it has a lot of rows, but only a few tables, each of which has just two or three columns).</p> <p>Then I plan to read the data in, and have a set of functions which provide access to and operations on the data.</p> <p>My question is this:</p> <p>is there a preferred way to convert a set of database tables to classes and objects? For example, if I have a table which contains fruit, where each fruit has an id and a name, would I have a "CollectionOfFruit" class which contains a list of "Fruit" objects, or would I just have a "CollectionOfFruit" class which contains a list of tuples? Or would I just have a list of Fruit objects?</p> <p>I don't want to add any extra frameworks, because I want this code to be easy to transfer to different machines. So I'm really just looking for general advice on how to represent data that might more naturally be stored in database tables, in objects in Python.</p> <p>Alternatively, is there a good book I should read that would point me in the right direction on this?</p>
0
2009-02-17T14:56:13Z
558,822
<p>Here are a couple points for you to consider. If your data is large reading it all into memory may be wasteful. If you need random access and not just sequential access to your data then you'll either have to scan the at most the entire file each time or read that table into an indexed memory structure like a dictionary. A list will still require some kind of scan (straight iteration or binary search if sorted). With that said, if you don't require some of the features of a DB then don't use one but if you just think MySQL is too heavy then +1 on the Sqlite suggestion from earlier. It gives you most of the features you'd want while using a database without the concurrency overhead.</p>
1
2009-02-17T21:32:03Z
[ "python", "object" ]
Converting a database-driven (non-OO) python script into a non-database driven, OO-script
557,199
<p>I have some software that is heavily dependent on MySQL, and is written in python without any class definitions. For performance reasons, and because the database is really just being used to store and retrieve large amounts of data, I'd like to convert this to an object-oriented python script that does not use the database at all.</p> <p>So my plan is to export the database tables to a set of files (not many -- it's a pretty simple database; it's big in that it has a lot of rows, but only a few tables, each of which has just two or three columns).</p> <p>Then I plan to read the data in, and have a set of functions which provide access to and operations on the data.</p> <p>My question is this:</p> <p>is there a preferred way to convert a set of database tables to classes and objects? For example, if I have a table which contains fruit, where each fruit has an id and a name, would I have a "CollectionOfFruit" class which contains a list of "Fruit" objects, or would I just have a "CollectionOfFruit" class which contains a list of tuples? Or would I just have a list of Fruit objects?</p> <p>I don't want to add any extra frameworks, because I want this code to be easy to transfer to different machines. So I'm really just looking for general advice on how to represent data that might more naturally be stored in database tables, in objects in Python.</p> <p>Alternatively, is there a good book I should read that would point me in the right direction on this?</p>
0
2009-02-17T14:56:13Z
558,830
<p>Abstract persistence from the object class. Put all of the persistence logic in an adapter class, and assign the adapter to the object class. Something like:</p> <pre><code>class Fruit(Object): @classmethod def get(cls, id): return cls.adapter.get(id) def put(self): cls.adapter.put(self) def __init__(self, id, name, weight, color): self.id = id self.name = name self.weight = weight self.color = color class FruitAdapter(Object): def get(id): # retrieve attributes from persistent storage here return Fruit(id, name, weight, color) def put(fruit): # insert/update fruit in persistent storage here Fruit.adapter = FruitAdapter() f = Fruit.get(1) f.name = "lemon" f.put() # and so on... </code></pre> <p>Now you can build different FruitAdapter objects that interoperate with whatever persistence format you settle on (database, flat file, in-memory collection, whatever) and the basic Fruit class will be completely unaffected.</p>
1
2009-02-17T21:35:15Z
[ "python", "object" ]
Make pyunit show output for every assertion
557,213
<p>How can I make python's unittest module show output for every assertion, rather than failing at the first one per test case? It would be much easier to debug if I could see the complete pattern of failures rather than just the first one.</p> <p>In my case the assertions are based on a couple loops over an array containing an object plus some function names and the expected output (see below), so there isn't an obvious way (at least to me) to just separate every assertion into a separate TestCase:</p> <pre><code>import unittest import get_nodes class mytest2(unittest.TestCase): def testfoo(self): root = get_nodes.mmnode_plus.factory('mytree.xml') tests = [ (root, {'skip_traversal': False, 'skip_as_child': True, 'skip_as_parent': False, 'is_leaf': False}), (root[0], {'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': False, 'is_leaf': False}), (root[1], {'skip_traversal': True, 'skip_as_child': True, 'skip_as_parent': True}), (root[1][0], {'skip_traversal': True}), (root[0][0], {'is_leaf': False, 'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': False}), (root[0][0][0], {'is_leaf': True, 'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': True}), (root[0][4], {'skip_traversal': True, 'skip_as_child': True, 'skip_as_parent': True}), (root[0][7], {'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': True}), ] for (node, states) in tests: for test_state, exp_result in states.iteritems(): self.assertEqual(node.__getattribute__(test_state)(), exp_result, "unexpected %s for state %s of node %s %s" % (not exp_result, test_state, repr(node), repr(node.__dict__))) unittest.main() </code></pre> <p><code>obj.__getattribute__('hello')</code> returns <code>obj.hello</code> so <code>node.__getattribute__(test_state)()</code> is my way of calling the member function of node whose name is stored in the test_state variable.</p>
1
2009-02-17T14:58:21Z
557,386
<pre><code>import unittest import get_nodes class TestSuper(unittest.TestCase): def setUp( self ): self.root = get_nodes.mmnode_plus.factory('mytree.xml') def condition( self, aNode, skip_traversal, skip_as_child, skip_as_parent, is_leaf ): self.assertEquals( skip_traversal, aNode.skip_traversal ) self.assertEquals( skip_as_child, aNode. skip_as_child) self.assertEquals( skip_as_parent, aNode. skip_as_parent) self.assertEquals( is_leaf , aNode. is_leaf ) class TestRoot( TestSuper ): def testRoot( self ): self.condition( self.root, **{'skip_traversal': False, 'skip_as_child': True, 'skip_as_parent': False, 'is_leaf': False} ) class TestRoot0( TestSuper ): def testRoot0( self ): self.condition( self.root[0], **{'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': False, 'is_leaf': False} ) class TestRoot1( TestSuper ): def testRoot1( self ): self.condition( self.root[1], **{'skip_traversal': True, 'skip_as_child': True, 'skip_as_parent': True}) class TestRoot10( TestSuper ): def testRoot10( self ): self.condition( self.root[1][0], **{'skip_traversal': True}) class TestRoot00( TestSuper ): def testRoot00( self ): self.condition( self.root[0][0], **{'is_leaf': False, 'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': False}) class TestRoot0( TestSuper ): def testRoot000( self ): self.condition( root[0][0][0], **{'is_leaf': True, 'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': True}) class TestRoot04( TestSuper ): def testRoot04( self ): self.condition( self.root[0][4], **{'skip_traversal': True, 'skip_as_child': True, 'skip_as_parent': True}) class TestRoot07( TestSuper ): def testRoot07( self ): self.condition( self.root[0][7], **{'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': True}) unittest.main() </code></pre>
2
2009-02-17T15:32:58Z
[ "python", "unit-testing", "pyunit" ]
Make pyunit show output for every assertion
557,213
<p>How can I make python's unittest module show output for every assertion, rather than failing at the first one per test case? It would be much easier to debug if I could see the complete pattern of failures rather than just the first one.</p> <p>In my case the assertions are based on a couple loops over an array containing an object plus some function names and the expected output (see below), so there isn't an obvious way (at least to me) to just separate every assertion into a separate TestCase:</p> <pre><code>import unittest import get_nodes class mytest2(unittest.TestCase): def testfoo(self): root = get_nodes.mmnode_plus.factory('mytree.xml') tests = [ (root, {'skip_traversal': False, 'skip_as_child': True, 'skip_as_parent': False, 'is_leaf': False}), (root[0], {'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': False, 'is_leaf': False}), (root[1], {'skip_traversal': True, 'skip_as_child': True, 'skip_as_parent': True}), (root[1][0], {'skip_traversal': True}), (root[0][0], {'is_leaf': False, 'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': False}), (root[0][0][0], {'is_leaf': True, 'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': True}), (root[0][4], {'skip_traversal': True, 'skip_as_child': True, 'skip_as_parent': True}), (root[0][7], {'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': True}), ] for (node, states) in tests: for test_state, exp_result in states.iteritems(): self.assertEqual(node.__getattribute__(test_state)(), exp_result, "unexpected %s for state %s of node %s %s" % (not exp_result, test_state, repr(node), repr(node.__dict__))) unittest.main() </code></pre> <p><code>obj.__getattribute__('hello')</code> returns <code>obj.hello</code> so <code>node.__getattribute__(test_state)()</code> is my way of calling the member function of node whose name is stored in the test_state variable.</p>
1
2009-02-17T14:58:21Z
559,006
<p>I was able to do it by making new TestCase classes dynamically using the builtin type() factory:</p> <pre><code>root = get_nodes.mmnode_plus.factory('somenodes.xml') tests = [ (root, {'skip_traversal': False, 'skip_as_child': True, 'skip_as_parent': False, 'is_leaf': False}), (root[0], {'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': False, 'is_leaf': False}), (root[1], {'skip_traversal': True, 'skip_as_child': True, 'skip_as_parent': True}), (root[1][0], {'skip_traversal': True}), (root[0][0], {'is_leaf': False, 'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': False}), (root[0][0][0], {'is_leaf': True, 'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': True}), (root[0][4], {'skip_traversal': True, 'skip_as_child': True, 'skip_as_parent': True}), (root[0][7], {'skip_traversal': False, 'skip_as_child': False, 'skip_as_parent': True}), ] i = 0 for (node, states) in tests: for test_state, exp_result in states.iteritems(): input = node.__getattribute__(test_state)() errstr = "expected %s, not %s for state %s of node %s" % (input, exp_result, test_state, repr(node)) locals()['foo' + str(i)] = type('foo' + str(i), (unittest.TestCase,), {'input': input, 'exp_result': exp_result, 'errstr': errstr, 'testme': lambda self: self.assertEqual(self.input, self.exp_result, self.errstr)}) i += 1 </code></pre>
1
2009-02-17T22:27:41Z
[ "python", "unit-testing", "pyunit" ]
Django - having middleware communicate with views/templates
557,460
<p>Alright, this is probably a really silly question but I am new to Python/Django so I can't really wrap my head around its scoping concepts just yet. Right now I am writing a <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/#topics-http-middleware">middleware</a> class to handle some stuff, and I want to set 'global' variables that my views and templates can access. What is the "right" way of doing this? I considered doing something like this:</p> <h2>middleware.py</h2> <pre><code>from django.conf import settings class BeforeFilter(object): def process_request(self, request): settings.my_var = 'Hello World' return None </code></pre> <h2>views.py</h2> <pre><code>from django.conf import settings from django.http import HttpResponse def myview(request): return HttpResponse(settings.my_var) </code></pre> <p>Although this works, I am not sure if it is the "Django way" or the "Python way" of doing this.</p> <p>So, my questions are:<br /> 1. Is this the right way?<br /> 2. If it is the right way, what is the right way of adding variables that can be used in the actual template from the middleware? Say I want to evaluate something and I want to set a variable <code>headername</code> as 'My Site Name' in the middleware, and I want to be able to do <code>{{ headername }}</code> in all templates. Doing it the way I have it now I'd have to add <code>headername</code> to the context inside every view. Is there anyway to bypass this? I am thinking something along the lines of CakePHP's <code>$this-&gt;set('headername','My Site Name');</code><br /> 3. I am using the middleware class as an equivalent of CakePHP's <code>beforeFilter</code> that runs before every view (or controller in CakePHP) is called. Is this the right way of doing this?<br /> 4. Completely unrelated but it is a small question, what is a nice way of printing out the contents of a variable to the browser ala <code>print_r</code>? Say I want to see all the stuff inside the <code>request</code> that is passed into the view? Is <code>pprint</code> the answer?</p>
7
2009-02-17T15:47:49Z
557,524
<p>1) If you modify 'settings', this is truly going to be global even across requests. In other words, concurrent requests are going to stomp each other if you need each request to have its own value. It's safer to modify the request object itself, which is what some of the common Django middleware does (e.g. django.contrib.auth.middleware.AuthenticationMiddleware adds a reference to 'user' on the request object)</p> <p>2) (EDIT 2) See #4, getting a common set of variables into each template is probably better suited for a custom context processor</p> <p>3) I'm not familiar with CakePHP, but adding a process_request middleware is definitely a good Django way of preprocessing each request.</p> <p>4) Take a look at the doc for <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#id1" rel="nofollow">template context processors</a>. If you use RequestContext each template will have a context variable called 'request' that you can dump to your template. You can also use the debug context processor and do something like this so it only dumps when settings.DEBUG=True:</p> <pre><code>{% if debug %} &lt;!-- {{ request.REQUEST }} --&gt; {% endif %} </code></pre> <p>This will work for both GET and POST, but you can modify accordingly if you only need one or the other.</p> <p><strong>EDIT</strong></p> <p>Also, I just looked closer at your views.py. Not sure I fully understand what you are trying to do there by just returning the variable in the response. If you really have that use case, you'll probably also want to set the mimetype like this:</p> <pre><code>return HttpResponse (..., mimetype='text/plain') </code></pre> <p>That's just to be explicit that you're not returning HTML, XML or some other structured content type.</p> <p><strong>EDIT 2</strong> </p> <p>Just saw the question was updated with a new subquestion, renumbered answers</p>
4
2009-02-17T16:02:01Z
[ "python", "django" ]
Django - having middleware communicate with views/templates
557,460
<p>Alright, this is probably a really silly question but I am new to Python/Django so I can't really wrap my head around its scoping concepts just yet. Right now I am writing a <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/#topics-http-middleware">middleware</a> class to handle some stuff, and I want to set 'global' variables that my views and templates can access. What is the "right" way of doing this? I considered doing something like this:</p> <h2>middleware.py</h2> <pre><code>from django.conf import settings class BeforeFilter(object): def process_request(self, request): settings.my_var = 'Hello World' return None </code></pre> <h2>views.py</h2> <pre><code>from django.conf import settings from django.http import HttpResponse def myview(request): return HttpResponse(settings.my_var) </code></pre> <p>Although this works, I am not sure if it is the "Django way" or the "Python way" of doing this.</p> <p>So, my questions are:<br /> 1. Is this the right way?<br /> 2. If it is the right way, what is the right way of adding variables that can be used in the actual template from the middleware? Say I want to evaluate something and I want to set a variable <code>headername</code> as 'My Site Name' in the middleware, and I want to be able to do <code>{{ headername }}</code> in all templates. Doing it the way I have it now I'd have to add <code>headername</code> to the context inside every view. Is there anyway to bypass this? I am thinking something along the lines of CakePHP's <code>$this-&gt;set('headername','My Site Name');</code><br /> 3. I am using the middleware class as an equivalent of CakePHP's <code>beforeFilter</code> that runs before every view (or controller in CakePHP) is called. Is this the right way of doing this?<br /> 4. Completely unrelated but it is a small question, what is a nice way of printing out the contents of a variable to the browser ala <code>print_r</code>? Say I want to see all the stuff inside the <code>request</code> that is passed into the view? Is <code>pprint</code> the answer?</p>
7
2009-02-17T15:47:49Z
557,538
<p>Here's what we do. We use a context processor like this...</p> <pre><code>def context_myApp_settings(request): """Insert some additional information into the template context from the settings. Specifically, the LOGOUT_URL, MEDIA_URL and BADGES settings. """ from django.conf import settings additions = { 'MEDIA_URL': settings.MEDIA_URL, 'LOGOUT_URL': settings.LOGOUT_URL, 'BADGES': settings.BADGES, 'DJANGO_ROOT': request.META['SCRIPT_NAME'], } return additions </code></pre> <p>Here the setting that activates this.</p> <pre><code>TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.request", "myapp. context_myApp_settings", ) </code></pre> <p>This provides "global" information in the context of each template that gets rendered. This is the standard Django solution. See <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#ref-templates-api">http://docs.djangoproject.com/en/dev/ref/templates/api/#ref-templates-api</a> for more information on context processors.</p> <p><hr /></p> <p>"what is a nice way of printing out the contents of a variable to the browser ala print_r?"</p> <p>In the view? You can provide a <code>pprint.pformat</code> string to a template to be rendered for debugging purposes.</p> <p>In the log? You have to use Python's <code>logging</code> module and send stuff to a separate log file. The use of simple print statements to write stuff to the log doesn't work wonderfully consistently for all Django implementations (mod_python, for example, loses all the stdout and stderr stuff.)</p>
12
2009-02-17T16:06:36Z
[ "python", "django" ]
Django - having middleware communicate with views/templates
557,460
<p>Alright, this is probably a really silly question but I am new to Python/Django so I can't really wrap my head around its scoping concepts just yet. Right now I am writing a <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/#topics-http-middleware">middleware</a> class to handle some stuff, and I want to set 'global' variables that my views and templates can access. What is the "right" way of doing this? I considered doing something like this:</p> <h2>middleware.py</h2> <pre><code>from django.conf import settings class BeforeFilter(object): def process_request(self, request): settings.my_var = 'Hello World' return None </code></pre> <h2>views.py</h2> <pre><code>from django.conf import settings from django.http import HttpResponse def myview(request): return HttpResponse(settings.my_var) </code></pre> <p>Although this works, I am not sure if it is the "Django way" or the "Python way" of doing this.</p> <p>So, my questions are:<br /> 1. Is this the right way?<br /> 2. If it is the right way, what is the right way of adding variables that can be used in the actual template from the middleware? Say I want to evaluate something and I want to set a variable <code>headername</code> as 'My Site Name' in the middleware, and I want to be able to do <code>{{ headername }}</code> in all templates. Doing it the way I have it now I'd have to add <code>headername</code> to the context inside every view. Is there anyway to bypass this? I am thinking something along the lines of CakePHP's <code>$this-&gt;set('headername','My Site Name');</code><br /> 3. I am using the middleware class as an equivalent of CakePHP's <code>beforeFilter</code> that runs before every view (or controller in CakePHP) is called. Is this the right way of doing this?<br /> 4. Completely unrelated but it is a small question, what is a nice way of printing out the contents of a variable to the browser ala <code>print_r</code>? Say I want to see all the stuff inside the <code>request</code> that is passed into the view? Is <code>pprint</code> the answer?</p>
7
2009-02-17T15:47:49Z
557,540
<ol> <li><p>It's not the best way. You could set my_var on the request rather than on the settings. Settings are global and apply to the whole site. You don't want to modify it for every request. There could be concurrency issues with multiple request updating/reading the variable at the same time.</p></li> <li><p>To access request.my_var in your templates you could do <strong>{{ request.my_var }}</strong>. To get access to the request variable in your template you will have to add <strong>django.core.context_processors.request</strong> to your <strong>TEMPLATE_CONTEXT_PROCESSORS</strong> setting.</p></li> <li><p>Yes. Other terminology to describe request middleware would be request pre-processor/filter/interceptor. </p></li> </ol> <p>Also, if you want to use a common Site name for the header in your templates, you might want to check out the Django Sites application which provides a site name variable for your use.</p>
19
2009-02-17T16:06:49Z
[ "python", "django" ]
How do I use easy_install and buildout when pypi is down?
557,462
<p>I am using <a href="http://pypi.python.org/pypi/zc.buildout">buildout</a> to automatically download and setup the many dependencies of my Plone installation. buildout more or less uses easy_install to download and install a bunch of Python eggs. This usually works, but it doesn't work if any of the dependencies cannot be downloaded or if I want buildout to find an internal package not appropriate for pypi. How can I set up my own local version of pypi to automatically mirror the packages I need? Will it still depend on third-party servers for packages that use pypi for their metadata but not their code?</p>
13
2009-02-17T15:48:23Z
557,832
<p>Here are <a href="http://www.zopyx.de/blog/creating-a-local-pypi-mirror">instructions on how to setup your own PyPi mirror</a>. The homepage of this project is <a href="http://www.openplans.org/projects/pypi-mirroring/project-home">here</a>. There also seems to be a growing number of mirrors out there.</p> <p>For instructions on how to setup your own package index, check out <a href="http://plope.com/Members/chrism/distribution_links_considered_harmful">this blog post</a> where one solution is explained at the end. Then you can also host your own internal packages in there. The advantage is also that the versions are fixed that way. (For a way to pin the versions directly in buildout, check out <a href="http://maurits.vanrees.org/weblog/archive/2008/01/easily-creating-repeatable-buildouts">this post</a>).</p> <p>If there is only metadata on PyPI and the archive is stored somewhere else you might of course copy that over to your index as well. If you just use a PyPI mirror I assume that you still need access to these servers.</p>
12
2009-02-17T17:22:44Z
[ "python", "plone", "easy-install", "buildout" ]
How do I use easy_install and buildout when pypi is down?
557,462
<p>I am using <a href="http://pypi.python.org/pypi/zc.buildout">buildout</a> to automatically download and setup the many dependencies of my Plone installation. buildout more or less uses easy_install to download and install a bunch of Python eggs. This usually works, but it doesn't work if any of the dependencies cannot be downloaded or if I want buildout to find an internal package not appropriate for pypi. How can I set up my own local version of pypi to automatically mirror the packages I need? Will it still depend on third-party servers for packages that use pypi for their metadata but not their code?</p>
13
2009-02-17T15:48:23Z
3,292,240
<p>You can also use a mirror. Put this in the "[global]" section of "~/.pip/pip.conf":</p> <pre><code>index-url = http://d.pypi.python.org/simple/ </code></pre> <p>This is a recent feature as announced <a href="http://mail.python.org/pipermail/catalog-sig/2010-July/003132.html">here</a>.</p>
8
2010-07-20T16:36:12Z
[ "python", "plone", "easy-install", "buildout" ]
How do I use easy_install and buildout when pypi is down?
557,462
<p>I am using <a href="http://pypi.python.org/pypi/zc.buildout">buildout</a> to automatically download and setup the many dependencies of my Plone installation. buildout more or less uses easy_install to download and install a bunch of Python eggs. This usually works, but it doesn't work if any of the dependencies cannot be downloaded or if I want buildout to find an internal package not appropriate for pypi. How can I set up my own local version of pypi to automatically mirror the packages I need? Will it still depend on third-party servers for packages that use pypi for their metadata but not their code?</p>
13
2009-02-17T15:48:23Z
3,393,628
<p>This page shows how to use the alternate mirror mentioned in @moraes post, but for easy_install, buildout and virtualenv as well as pip:</p> <p><a href="http://jacobian.org/writing/when-pypi-goes-down/">http://jacobian.org/writing/when-pypi-goes-down/</a></p>
5
2010-08-03T04:44:42Z
[ "python", "plone", "easy-install", "buildout" ]
How do I use easy_install and buildout when pypi is down?
557,462
<p>I am using <a href="http://pypi.python.org/pypi/zc.buildout">buildout</a> to automatically download and setup the many dependencies of my Plone installation. buildout more or less uses easy_install to download and install a bunch of Python eggs. This usually works, but it doesn't work if any of the dependencies cannot be downloaded or if I want buildout to find an internal package not appropriate for pypi. How can I set up my own local version of pypi to automatically mirror the packages I need? Will it still depend on third-party servers for packages that use pypi for their metadata but not their code?</p>
13
2009-02-17T15:48:23Z
5,589,821
<p>PyPI has had mirroring since mid 2010 <a href="http://pypi.python.org/mirrors" rel="nofollow">http://pypi.python.org/mirrors</a></p>
0
2011-04-08T02:37:06Z
[ "python", "plone", "easy-install", "buildout" ]
How do I use easy_install and buildout when pypi is down?
557,462
<p>I am using <a href="http://pypi.python.org/pypi/zc.buildout">buildout</a> to automatically download and setup the many dependencies of my Plone installation. buildout more or less uses easy_install to download and install a bunch of Python eggs. This usually works, but it doesn't work if any of the dependencies cannot be downloaded or if I want buildout to find an internal package not appropriate for pypi. How can I set up my own local version of pypi to automatically mirror the packages I need? Will it still depend on third-party servers for packages that use pypi for their metadata but not their code?</p>
13
2009-02-17T15:48:23Z
6,147,959
<p>Configure <code>index</code> in <code>buildout.cfg</code>, e.g.</p> <pre><code>[buildout] index = http://a.pypi.python.org/ find-links = </code></pre> <p>More mirrors on : <a href="http://www.pypi-mirrors.org/" rel="nofollow">http://www.pypi-mirrors.org/</a></p>
2
2011-05-27T04:51:34Z
[ "python", "plone", "easy-install", "buildout" ]
How do I use easy_install and buildout when pypi is down?
557,462
<p>I am using <a href="http://pypi.python.org/pypi/zc.buildout">buildout</a> to automatically download and setup the many dependencies of my Plone installation. buildout more or less uses easy_install to download and install a bunch of Python eggs. This usually works, but it doesn't work if any of the dependencies cannot be downloaded or if I want buildout to find an internal package not appropriate for pypi. How can I set up my own local version of pypi to automatically mirror the packages I need? Will it still depend on third-party servers for packages that use pypi for their metadata but not their code?</p>
13
2009-02-17T15:48:23Z
8,333,271
<p>In case of zc.buildout: use its local download caching features. There are mostly three things to cache: </p> <ul> <li>external extends, i.e. <a href="http://dist.plone.org/release/4.1.2/versions.cfg" rel="nofollow">http://dist.plone.org/release/4.1.2/versions.cfg</a></li> <li>eggs from some distserver, i.e. pypi</li> <li>downloads from zc.recipe.cmmi or similar recipes using the download infrastructure provided by zc.buildout</li> </ul> <p>For all three we need to tweak the global configuration and set a cache folder for the extends and one for eggs and other downloads.</p> <p>In your home folder create a <code>.buildout</code> folder.</p> <p>In this folder create the folders <code>extends-cache</code> and <code>downloads</code> </p> <p>In <code>.buildout</code> create a file default.cfg with:</p> <pre><code>[buildout] extends-cache = /home/USERNAME/.buildout/extends-cache download-cache = /home/USERNAME/.buildout/downloads </code></pre> <p>so you have:</p> <pre><code>.buildout/ ├── default.cfg ├── downloads └── extends-cache </code></pre> <p>Thats it. Make sure to not override these two variables from default.cfg in your specific buildout. After first successful run of buildout subsequent runs are running in offline mode <code>./bin/buildout -o</code>.</p> <p>As a side effect buildout is much faster if used in offline mode, i.e. when no new downloads are expected but some configuration changed</p> <p>Beside this it makes sense to run your own pypi-mirror. As another source of information you might be interested in the article I wrote some time ago about this topic: <a href="http://bluedynamics.com/articles/jens/setup-z3c.pypimirror" rel="nofollow">http://bluedynamics.com/articles/jens/setup-z3c.pypimirror</a></p>
3
2011-11-30T21:36:37Z
[ "python", "plone", "easy-install", "buildout" ]
How do I suppress python-mode's output buffer?
557,555
<p>In python-mode (for emacs), hitting Control-C\Control-C will execute the current buffer. However, when execution is finished, the output buffer springs up and splits my editing window in half. This is a <em>complete</em> pain, especially given that there's generally no output in the buffer anyway!</p> <p>Is there a way to stop the buffer from appearing? Also, how can I send painful electric shocks to the programmer who thought unexpectedly interrupting my train of thought with an empty buffer was a good idea?</p> <p><strong>Edit:</strong> Apparently, there are uses for this behavior, most notably in seeing the output of a program. That's fine, but if there's no output (as in the program with which I'm tinkering), it is <em>really</em> dumb to cut my buffer in half with a blank window.</p>
5
2009-02-17T16:10:51Z
557,605
<p>Sorry that I can't help you with emacs, but as for your second question, a modified aluminum keyboard from Apple may be a solution:</p> <p><a href="http://www.apple.com/keyboard/" rel="nofollow">http://www.apple.com/keyboard/</a></p>
2
2009-02-17T16:20:54Z
[ "python", "emacs" ]
How do I suppress python-mode's output buffer?
557,555
<p>In python-mode (for emacs), hitting Control-C\Control-C will execute the current buffer. However, when execution is finished, the output buffer springs up and splits my editing window in half. This is a <em>complete</em> pain, especially given that there's generally no output in the buffer anyway!</p> <p>Is there a way to stop the buffer from appearing? Also, how can I send painful electric shocks to the programmer who thought unexpectedly interrupting my train of thought with an empty buffer was a good idea?</p> <p><strong>Edit:</strong> Apparently, there are uses for this behavior, most notably in seeing the output of a program. That's fine, but if there's no output (as in the program with which I'm tinkering), it is <em>really</em> dumb to cut my buffer in half with a blank window.</p>
5
2009-02-17T16:10:51Z
557,779
<p>You might want to customize the <code>pop-up-windows</code> variable; that controls the splitting functionality.</p>
1
2009-02-17T17:12:38Z
[ "python", "emacs" ]
How do I suppress python-mode's output buffer?
557,555
<p>In python-mode (for emacs), hitting Control-C\Control-C will execute the current buffer. However, when execution is finished, the output buffer springs up and splits my editing window in half. This is a <em>complete</em> pain, especially given that there's generally no output in the buffer anyway!</p> <p>Is there a way to stop the buffer from appearing? Also, how can I send painful electric shocks to the programmer who thought unexpectedly interrupting my train of thought with an empty buffer was a good idea?</p> <p><strong>Edit:</strong> Apparently, there are uses for this behavior, most notably in seeing the output of a program. That's fine, but if there's no output (as in the program with which I'm tinkering), it is <em>really</em> dumb to cut my buffer in half with a blank window.</p>
5
2009-02-17T16:10:51Z
557,820
<p>Don't know how to stop it from popping up, but <em>C-x, 1</em> will close the window.</p>
0
2009-02-17T17:20:00Z
[ "python", "emacs" ]
How do I suppress python-mode's output buffer?
557,555
<p>In python-mode (for emacs), hitting Control-C\Control-C will execute the current buffer. However, when execution is finished, the output buffer springs up and splits my editing window in half. This is a <em>complete</em> pain, especially given that there's generally no output in the buffer anyway!</p> <p>Is there a way to stop the buffer from appearing? Also, how can I send painful electric shocks to the programmer who thought unexpectedly interrupting my train of thought with an empty buffer was a good idea?</p> <p><strong>Edit:</strong> Apparently, there are uses for this behavior, most notably in seeing the output of a program. That's fine, but if there's no output (as in the program with which I'm tinkering), it is <em>really</em> dumb to cut my buffer in half with a blank window.</p>
5
2009-02-17T16:10:51Z
559,238
<p>What python-mode are you using? Unfortunately, there are <em>several</em>.</p> <p>Type C-h k and then C-c C-c .. what does it say in the modeline? Does it say "py-execute-buffer" or does it say "python-send-buffer", the first kind indicates you're using Tim Peters' python-mode, while the second indicates you're using Dave Love's python-mode.</p> <p>I myself prefer Dave Love's python mode, and it's the version that ships with Emacs 23 (and maybe earlier too?). Dave Love's does not pop up the buffer when you run C-c C-c, you have to explicitly switch to the *Python* buffer if you want to see it.</p> <p>If you're really intent on sticking with Tim Peters' version, you could always put something like the following in your .emacs and you'll never see the output buffer again unless explicitly moved to.</p> <pre><code>(defadvice py-execute-buffer (after advice-delete-output-window activate) (delete-windows-on "*Python Output*")) </code></pre>
5
2009-02-17T23:42:02Z
[ "python", "emacs" ]
How do I suppress python-mode's output buffer?
557,555
<p>In python-mode (for emacs), hitting Control-C\Control-C will execute the current buffer. However, when execution is finished, the output buffer springs up and splits my editing window in half. This is a <em>complete</em> pain, especially given that there's generally no output in the buffer anyway!</p> <p>Is there a way to stop the buffer from appearing? Also, how can I send painful electric shocks to the programmer who thought unexpectedly interrupting my train of thought with an empty buffer was a good idea?</p> <p><strong>Edit:</strong> Apparently, there are uses for this behavior, most notably in seeing the output of a program. That's fine, but if there's no output (as in the program with which I'm tinkering), it is <em>really</em> dumb to cut my buffer in half with a blank window.</p>
5
2009-02-17T16:10:51Z
8,940,489
<p>In recent <code>python-mode.el</code> that behavior is controlled by a customizable variable:</p> <pre><code>py-shell-switch-buffers-on-execute </code></pre> <p>See these links:</p> <ul> <li><p><a href="http://launchpad.net/python-mode" rel="nofollow">An Emacs mode for editing Python code</a></p></li> <li><p><a href="http://launchpad.net/python-mode/trunk/6.0.4/+download/python-mode.el-6.0.4.tar.gz" rel="nofollow">Link to direct download</a></p></li> </ul>
2
2012-01-20T11:08:59Z
[ "python", "emacs" ]
Want procmail to run a custom python script, everytime a new mail shows up
557,906
<p>I have a pretty usual requirement with procmail but I am unable to get the results somehow. I have procmailrc file with this content:</p> <pre><code>:0 * ^To.*@myhost | /usr/bin/python /work/scripts/privilege_emails_forward.py </code></pre> <p>Wherein my custom python script(privilege_emails_forward.py) will be scanning through the email currently received and do some operations on the mail content. But I am unable to get the script getting executed at the first shot(let alone scanning through the mail content).</p> <ul> <li>Is this a correct way of invoking an external program(python) as soon as new mail arrives? </li> <li>And how does my python program(privilege_emails_forward.py) will receive the mail as input? I mean as sys.argv or stdin????</li> </ul>
9
2009-02-17T17:37:23Z
557,932
<p>That is just fine, just put <code>fw</code> after <code>:0</code> (<code>:0 fw</code>). Your python program will receive the mail on <code>stdin</code>. You have to 'echo' the possibly transformed mail on <code>stdout</code>.</p> <p><code>fw</code> means:</p> <ul> <li><code>f</code> Consider the pipe as a filter.</li> <li><code>w</code> Wait for the filter or program to finish and check its exitcode (normally ignored); if the filter is unsuccessful, then the text will not have been filtered.</li> </ul> <p>My SPAM checker (bogofilter) just works like that. It adds headers and later procmail-rules do something depending on these headers.</p>
11
2009-02-17T17:45:04Z
[ "python", "email", "procmail" ]
Want procmail to run a custom python script, everytime a new mail shows up
557,906
<p>I have a pretty usual requirement with procmail but I am unable to get the results somehow. I have procmailrc file with this content:</p> <pre><code>:0 * ^To.*@myhost | /usr/bin/python /work/scripts/privilege_emails_forward.py </code></pre> <p>Wherein my custom python script(privilege_emails_forward.py) will be scanning through the email currently received and do some operations on the mail content. But I am unable to get the script getting executed at the first shot(let alone scanning through the mail content).</p> <ul> <li>Is this a correct way of invoking an external program(python) as soon as new mail arrives? </li> <li>And how does my python program(privilege_emails_forward.py) will receive the mail as input? I mean as sys.argv or stdin????</li> </ul>
9
2009-02-17T17:37:23Z
561,142
<p>The <a href="http://stackoverflow.com/questions/557906/want-procmail-to-run-a-custom-python-script-everytime-a-new-mail-shows-up/561028#561028">log excerpt</a> clearly states that your script is executed, even if it doesn't show the desired effect. I'd expect procmail to log an error if the execution failed.</p> <p>Anyway, make sure that the user (uid) that procmail is executed with has the correct permissions to execute your script. Wire the script into procmail only if you succeeded testing with something like this (replace 'procmail' with the correct uid):</p> <pre> # sudo -u procmail /bin/sh -c '/bin/cat /work/scripts/mail.txt | /usr/bin/python /work/scripts/privilege_emails_forward.py' </pre> <p>Depending on your sudo configuration, you'd have to run this as root. Oh, and make sure you use absolute file paths.</p>
4
2009-02-18T14:01:22Z
[ "python", "email", "procmail" ]
Debugging web apps
557,927
<p>I've gotten pretty used to step-through debuggers over the years, both in builder, and using the pydev debugger in Eclipse. </p> <p>Currently, I'm making something in Python and running it on Google App Engine, and I should add that I'm pretty new to developing any real web app; I've never really done much beyond editing HTML code.</p> <p>So, I'm running Google's dev_appserver and viewing my work at <a href="http://localhost">http://localhost</a>, dig, and right now, the only tool I'm using to identify issues is PMD (poor man's debugger). . .basically writing things to the html pages to see the value of local variables. </p> <p>Is there a better technique for dealing with this? </p>
8
2009-02-17T17:43:59Z
557,938
<p>The dev_appserver is just a python script, you can simply use the pydev debugger on that script with the proper arguments as far as I know.</p> <p>Here is a very detailed guide on how to do that:</p> <p><a href="http://www.ibm.com/developerworks/opensource/library/os-eclipse-mashup-google-pt1/index.html" rel="nofollow">http://www.ibm.com/developerworks/opensource/library/os-eclipse-mashup-google-pt1/index.html</a></p>
7
2009-02-17T17:47:05Z
[ "python", "eclipse", "debugging", "google-app-engine" ]
Debugging web apps
557,927
<p>I've gotten pretty used to step-through debuggers over the years, both in builder, and using the pydev debugger in Eclipse. </p> <p>Currently, I'm making something in Python and running it on Google App Engine, and I should add that I'm pretty new to developing any real web app; I've never really done much beyond editing HTML code.</p> <p>So, I'm running Google's dev_appserver and viewing my work at <a href="http://localhost">http://localhost</a>, dig, and right now, the only tool I'm using to identify issues is PMD (poor man's debugger). . .basically writing things to the html pages to see the value of local variables. </p> <p>Is there a better technique for dealing with this? </p>
8
2009-02-17T17:43:59Z
558,065
<p>"Is there a better technique for dealing with this?" Not really.</p> <p>"step-through debuggers" are their own problem. They're a kind of mental crutch that make it easy to get something that looks like it works.</p> <p>First, look at <a href="http://code.google.com/appengine/docs/python/tools/devserver.html#The_Development_Console" rel="nofollow">http://code.google.com/appengine/docs/python/tools/devserver.html#The_Development_Console</a> for something that might be helpful.</p> <p>Second, note that <code>--debug</code> Prints verbose debugging messages to the console while running.</p> <p>Finally, note that you'll need plenty of Python experience and Google AppEngine experience to write things like web applications. To get that experience, the <code>print</code> statement is really quite good. It shows you what's going on, and it encourages you to really understand what you <em>expect</em> or <em>intend</em> to happen. </p> <p>Debuggers are passive. It devolves to writing random code, seeing what happens, making changes until it works. I've watched people do this.</p> <p>Print statement is active. You have to plan what should happen, write code, and consider the results carefully to see if the plans worked out. If it doesn't do what you intended, you have to hypothesize and test your hypothesis. If it works, then you "understood" what was going on. Once you get the semantics of Python and the Google AppEngine, your understanding grows and this becomes really easy.</p>
2
2009-02-17T18:13:26Z
[ "python", "eclipse", "debugging", "google-app-engine" ]
Debugging web apps
557,927
<p>I've gotten pretty used to step-through debuggers over the years, both in builder, and using the pydev debugger in Eclipse. </p> <p>Currently, I'm making something in Python and running it on Google App Engine, and I should add that I'm pretty new to developing any real web app; I've never really done much beyond editing HTML code.</p> <p>So, I'm running Google's dev_appserver and viewing my work at <a href="http://localhost">http://localhost</a>, dig, and right now, the only tool I'm using to identify issues is PMD (poor man's debugger). . .basically writing things to the html pages to see the value of local variables. </p> <p>Is there a better technique for dealing with this? </p>
8
2009-02-17T17:43:59Z
558,165
<p>I would suggest to use logging statements instead of prints though as you can control them better. Python has a quite good logging library included.</p> <p>For logging from Google App Engine to e.g. Firebug there is also some handy tool called <a href="http://appengine-cookbook.appspot.com/recipe/firepython-logger-console-inside-firebug/" rel="nofollow">FirePython</a>. This allows to log to the firebug console from within your Django or WSGI app (it's middleware).</p>
4
2009-02-17T18:33:49Z
[ "python", "eclipse", "debugging", "google-app-engine" ]
Debugging web apps
557,927
<p>I've gotten pretty used to step-through debuggers over the years, both in builder, and using the pydev debugger in Eclipse. </p> <p>Currently, I'm making something in Python and running it on Google App Engine, and I should add that I'm pretty new to developing any real web app; I've never really done much beyond editing HTML code.</p> <p>So, I'm running Google's dev_appserver and viewing my work at <a href="http://localhost">http://localhost</a>, dig, and right now, the only tool I'm using to identify issues is PMD (poor man's debugger). . .basically writing things to the html pages to see the value of local variables. </p> <p>Is there a better technique for dealing with this? </p>
8
2009-02-17T17:43:59Z
560,779
<p>My debugging toolbox for GAE:</p> <ul> <li>standard Python logging as a substitute for <code>print</code> statements</li> <li><a href="http://dev.pocoo.org/projects/werkzeug/wiki/UsingDebuggerWithAppEngine" rel="nofollow">Werkzeug debugger</a> if I do not want to go to the console log on each error (not everything works, most notably interactive interpreter session)</li> <li>interactive console at <a href="http://localhost:8080/_ah/admin/interactive" rel="nofollow">http://localhost:8080/_ah/admin/interactive</a> (not as good as Django's <code>python manage.py shell</code> but still...)</li> </ul> <p>Symbolic debuggers are not so valued as elsewhere, possibly because Python's superior introspection and reflection mechanisms.</p>
1
2009-02-18T12:01:10Z
[ "python", "eclipse", "debugging", "google-app-engine" ]
String separation in required format, Pythonic way? (with or w/o Regex)
558,105
<p>I have a string in the format:</p> <pre><code>t='@abc @def Hello this part is text' </code></pre> <p>I want to get this:</p> <pre><code>l=["abc", "def"] s='Hello this part is text' </code></pre> <p>I did this:</p> <pre><code>a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l=[i.strip() for i in b][1:] </code></pre> <p>It works for the most part, but it fails when the text part has the '@'. Eg, when: </p> <pre><code>t='@abc @def My email is red@hjk.com' </code></pre> <p>it fails. The @names are there in the beginning and there can be text after @names, which may possibly contain @.</p> <p>Clearly I can append initally with a space and find out first word without '@'. But that doesn't seem an elegant solution.</p> <p>What is a pythonic way of solving this?</p>
6
2009-02-17T18:22:07Z
558,181
<pre><code> [i.strip('@') for i in t.split(' ', 2)[:2]] # for a fixed number of @def a = [i.strip('@') for i in t.split(' ') if i.startswith('@')] s = ' '.join(i for i in t.split(' ') if not i.startwith('@')) </code></pre>
3
2009-02-17T18:37:22Z
[ "regex", "string", "format", "python" ]
String separation in required format, Pythonic way? (with or w/o Regex)
558,105
<p>I have a string in the format:</p> <pre><code>t='@abc @def Hello this part is text' </code></pre> <p>I want to get this:</p> <pre><code>l=["abc", "def"] s='Hello this part is text' </code></pre> <p>I did this:</p> <pre><code>a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l=[i.strip() for i in b][1:] </code></pre> <p>It works for the most part, but it fails when the text part has the '@'. Eg, when: </p> <pre><code>t='@abc @def My email is red@hjk.com' </code></pre> <p>it fails. The @names are there in the beginning and there can be text after @names, which may possibly contain @.</p> <p>Clearly I can append initally with a space and find out first word without '@'. But that doesn't seem an elegant solution.</p> <p>What is a pythonic way of solving this?</p>
6
2009-02-17T18:22:07Z
558,189
<p>You might also use regular expressions:</p> <pre><code>import re rx = re.compile("@([\w]+) @([\w]+) (.*)") t='@abc @def Hello this part is text and my email is foo@ba.r' a,b,s = rx.match(t).groups() </code></pre> <p>But this all depends on how your data can look like. So you might need to adjust it. What it does is basically creating group via () and checking for what's allowed in them.</p>
3
2009-02-17T18:40:23Z
[ "regex", "string", "format", "python" ]
String separation in required format, Pythonic way? (with or w/o Regex)
558,105
<p>I have a string in the format:</p> <pre><code>t='@abc @def Hello this part is text' </code></pre> <p>I want to get this:</p> <pre><code>l=["abc", "def"] s='Hello this part is text' </code></pre> <p>I did this:</p> <pre><code>a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l=[i.strip() for i in b][1:] </code></pre> <p>It works for the most part, but it fails when the text part has the '@'. Eg, when: </p> <pre><code>t='@abc @def My email is red@hjk.com' </code></pre> <p>it fails. The @names are there in the beginning and there can be text after @names, which may possibly contain @.</p> <p>Clearly I can append initally with a space and find out first word without '@'. But that doesn't seem an elegant solution.</p> <p>What is a pythonic way of solving this?</p>
6
2009-02-17T18:22:07Z
558,278
<p>How about this:</p> <ol> <li>Splitting by space.</li> <li><p>foreach word, check </p> <p>2.1. if word starts with @ then Push to first list</p> <p>2.2. otherwise just join the remaining words by spaces.</p></li> </ol>
5
2009-02-17T19:03:38Z
[ "regex", "string", "format", "python" ]
String separation in required format, Pythonic way? (with or w/o Regex)
558,105
<p>I have a string in the format:</p> <pre><code>t='@abc @def Hello this part is text' </code></pre> <p>I want to get this:</p> <pre><code>l=["abc", "def"] s='Hello this part is text' </code></pre> <p>I did this:</p> <pre><code>a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l=[i.strip() for i in b][1:] </code></pre> <p>It works for the most part, but it fails when the text part has the '@'. Eg, when: </p> <pre><code>t='@abc @def My email is red@hjk.com' </code></pre> <p>it fails. The @names are there in the beginning and there can be text after @names, which may possibly contain @.</p> <p>Clearly I can append initally with a space and find out first word without '@'. But that doesn't seem an elegant solution.</p> <p>What is a pythonic way of solving this?</p>
6
2009-02-17T18:22:07Z
558,345
<p>[<strong>edit</strong>: this is implementing what was suggested by Osama above]</p> <p>This will create L based on the @ variables from the beginning of the string, and then once a non @ var is found, just grab the rest of the string.</p> <pre><code>t = '@one @two @three some text afterward with @ symbols@ meow@meow' words = t.split(' ') # split into list of words based on spaces L = [] s = '' for i in range(len(words)): # go through each word word = words[i] if word[0] == '@': # grab @'s from beginning of string L.append(word[1:]) continue s = ' '.join(words[i:]) # put spaces back in break # you can ignore the rest of the words </code></pre> <p>You can refactor this to be less code, but I'm trying to make what is going on obvious.</p>
3
2009-02-17T19:21:39Z
[ "regex", "string", "format", "python" ]
String separation in required format, Pythonic way? (with or w/o Regex)
558,105
<p>I have a string in the format:</p> <pre><code>t='@abc @def Hello this part is text' </code></pre> <p>I want to get this:</p> <pre><code>l=["abc", "def"] s='Hello this part is text' </code></pre> <p>I did this:</p> <pre><code>a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l=[i.strip() for i in b][1:] </code></pre> <p>It works for the most part, but it fails when the text part has the '@'. Eg, when: </p> <pre><code>t='@abc @def My email is red@hjk.com' </code></pre> <p>it fails. The @names are there in the beginning and there can be text after @names, which may possibly contain @.</p> <p>Clearly I can append initally with a space and find out first word without '@'. But that doesn't seem an elegant solution.</p> <p>What is a pythonic way of solving this?</p>
6
2009-02-17T18:22:07Z
558,392
<p>Building unashamedly on MrTopf's effort:</p> <pre><code>import re rx = re.compile("((?:@\w+ +)+)(.*)") t='@abc @def @xyz Hello this part is text and my email is foo@ba.r' a,s = rx.match(t).groups() l = re.split('[@ ]+',a)[1:-1] print l print s </code></pre> <p>prints:</p> <blockquote> <p>['abc', 'def', 'xyz']<br /> Hello this part is text and my email is foo@ba.r</p> </blockquote> <p><hr /></p> <p>Justly called to account by <a href="http://stackoverflow.com/users/35364/hasen-j">hasen j</a>, let me clarify how this works:</p> <pre><code>/@\w+ +/ </code></pre> <p>matches a single tag - @ followed by at least one alphanumeric or _ followed by at least one space character. + is greedy, so if there is more than one space, it will grab them all.</p> <p>To match any number of these tags, we need to add a plus (one or more things) to the pattern for tag; so we need to group it with parentheses:</p> <pre><code>/(@\w+ +)+/ </code></pre> <p>which matches one-or-more tags, and, being greedy, matches all of them. However, those parentheses now fiddle around with our capture groups, so we undo that by making them into an anonymous group:</p> <pre><code>/(?:@\w+ +)+/ </code></pre> <p>Finally, we make that into a capture group and add another to sweep up the rest:</p> <pre><code>/((?:@\w+ +)+)(.*)/ </code></pre> <p>A last breakdown to sum up:</p> <pre><code>((?:@\w+ +)+)(.*) (?:@\w+ +)+ ( @\w+ +) @\w+ + </code></pre> <p><hr /></p> <p>Note that in reviewing this, I've improved it - \w didn't need to be in a set, and it now allows for multiple spaces between tags. Thanks, hasen-j!</p>
13
2009-02-17T19:32:42Z
[ "regex", "string", "format", "python" ]
String separation in required format, Pythonic way? (with or w/o Regex)
558,105
<p>I have a string in the format:</p> <pre><code>t='@abc @def Hello this part is text' </code></pre> <p>I want to get this:</p> <pre><code>l=["abc", "def"] s='Hello this part is text' </code></pre> <p>I did this:</p> <pre><code>a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l=[i.strip() for i in b][1:] </code></pre> <p>It works for the most part, but it fails when the text part has the '@'. Eg, when: </p> <pre><code>t='@abc @def My email is red@hjk.com' </code></pre> <p>it fails. The @names are there in the beginning and there can be text after @names, which may possibly contain @.</p> <p>Clearly I can append initally with a space and find out first word without '@'. But that doesn't seem an elegant solution.</p> <p>What is a pythonic way of solving this?</p>
6
2009-02-17T18:22:07Z
558,393
<pre><code>t='@abc @def Hello this part is text' words = t.split(' ') names = [] while words: w = words.pop(0) if w.startswith('@'): names.append(w[1:]) else: break text = ' '.join(words) print names print text </code></pre>
7
2009-02-17T19:32:42Z
[ "regex", "string", "format", "python" ]
String separation in required format, Pythonic way? (with or w/o Regex)
558,105
<p>I have a string in the format:</p> <pre><code>t='@abc @def Hello this part is text' </code></pre> <p>I want to get this:</p> <pre><code>l=["abc", "def"] s='Hello this part is text' </code></pre> <p>I did this:</p> <pre><code>a=t[t.find(' ',t.rfind('@')):].strip() s=t[:t.find(' ',t.rfind('@'))].strip() b=a.split('@') l=[i.strip() for i in b][1:] </code></pre> <p>It works for the most part, but it fails when the text part has the '@'. Eg, when: </p> <pre><code>t='@abc @def My email is red@hjk.com' </code></pre> <p>it fails. The @names are there in the beginning and there can be text after @names, which may possibly contain @.</p> <p>Clearly I can append initally with a space and find out first word without '@'. But that doesn't seem an elegant solution.</p> <p>What is a pythonic way of solving this?</p>
6
2009-02-17T18:22:07Z
563,299
<p>Here's just another variation that uses split() and no regexpes:</p> <pre><code>t='@abc @def My email is red@hjk.com' tags = [] words = iter(t.split()) # iterate over words until first non-tag word for w in words: if not w.startswith("@"): # join this word and all the following s = w + " " + (" ".join(words)) break tags.append(w[1:]) else: s = "" # handle string with only tags print tags, s </code></pre> <p>Here's a shorter but perhaps a bit cryptic version that uses a regexp to find the first space followed by a non-@ character:</p> <pre><code>import re t = '@abc @def My email is red@hjk.com @extra bye' m = re.search(r"\s([^@].*)$", t) tags = [tag[1:] for tag in t[:m.start()].split()] s = m.group(1) print tags, s # ['abc', 'def'] My email is red@hjk.com @extra bye </code></pre> <p>This doesn't work properly if there are no tags or no text. The format is underspecified. You'll need to provide more test cases to validate.</p>
1
2009-02-18T23:14:31Z
[ "regex", "string", "format", "python" ]
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
558,216
<p>I have been asked to test a library provided by a 3rd party. The library is known to be accurate to <em>n</em> significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:</p> <pre><code>def nearlyequal( a, b, sigfig=5 ): </code></pre> <p>The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to <strong>sigfig</strong> significant-figures when written in decimal. </p> <p>Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:</p> <pre><code>assert nearlyequal(1, 1, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(-1e-9, 1e-9, 5) assert nearlyequal(1e9, 1e9 + 1 , 5) assert not nearlyequal( 1e4, 1e4 + 1, 5) assert nearlyequal( 0.0, 1e-15, 5 ) assert not nearlyequal( 0.0, 1e-4, 6 ) </code></pre> <p>Additional notes:</p> <ol> <li>Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.</li> <li>Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.</li> <li>Speed... I've got to compare a lot of numbers so the faster the better.</li> <li>I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.</li> </ol>
13
2009-02-17T18:49:20Z
558,289
<p>Here's a take.</p> <pre><code>def nearly_equal(a,b,sig_fig=5): return ( a==b or int(a*10**sig_fig) == int(b*10**sig_fig) ) </code></pre>
8
2009-02-17T19:07:04Z
[ "python", "math", "floating-point", "numpy" ]
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
558,216
<p>I have been asked to test a library provided by a 3rd party. The library is known to be accurate to <em>n</em> significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:</p> <pre><code>def nearlyequal( a, b, sigfig=5 ): </code></pre> <p>The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to <strong>sigfig</strong> significant-figures when written in decimal. </p> <p>Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:</p> <pre><code>assert nearlyequal(1, 1, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(-1e-9, 1e-9, 5) assert nearlyequal(1e9, 1e9 + 1 , 5) assert not nearlyequal( 1e4, 1e4 + 1, 5) assert nearlyequal( 0.0, 1e-15, 5 ) assert not nearlyequal( 0.0, 1e-4, 6 ) </code></pre> <p>Additional notes:</p> <ol> <li>Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.</li> <li>Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.</li> <li>Speed... I've got to compare a lot of numbers so the faster the better.</li> <li>I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.</li> </ol>
13
2009-02-17T18:49:20Z
558,298
<p>"Significant figures" in decimal is a matter of adjusting the decimal point and truncating to an integer. </p> <pre><code>&gt;&gt;&gt; int(3.1415926 * 10**3) 3141 &gt;&gt;&gt; int(1234567 * 10**-3) 1234 &gt;&gt;&gt; </code></pre>
2
2009-02-17T19:10:06Z
[ "python", "math", "floating-point", "numpy" ]
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
558,216
<p>I have been asked to test a library provided by a 3rd party. The library is known to be accurate to <em>n</em> significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:</p> <pre><code>def nearlyequal( a, b, sigfig=5 ): </code></pre> <p>The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to <strong>sigfig</strong> significant-figures when written in decimal. </p> <p>Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:</p> <pre><code>assert nearlyequal(1, 1, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(-1e-9, 1e-9, 5) assert nearlyequal(1e9, 1e9 + 1 , 5) assert not nearlyequal( 1e4, 1e4 + 1, 5) assert nearlyequal( 0.0, 1e-15, 5 ) assert not nearlyequal( 0.0, 1e-4, 6 ) </code></pre> <p>Additional notes:</p> <ol> <li>Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.</li> <li>Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.</li> <li>Speed... I've got to compare a lot of numbers so the faster the better.</li> <li>I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.</li> </ol>
13
2009-02-17T18:49:20Z
558,322
<p>There is a function <code>assert_approx_equal</code> in <code>numpy.testing</code> (source <a href="https://github.com/numpy/numpy/blob/1225aef37298ec82048d0828f6cb7e0be8ed58cc/numpy/testing/utils.py#L513" rel="nofollow">here) </a>which may be a good starting point. </p> <pre><code>def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True): """ Raise an assertion if two items are not equal up to significant digits. .. note:: It is recommended to use one of `assert_allclose`, `assert_array_almost_equal_nulp` or `assert_array_max_ulp` instead of this function for more consistent floating point comparisons. Given two numbers, check that they are approximately equal. Approximately equal is defined as the number of significant digits that agree. </code></pre>
16
2009-02-17T19:16:25Z
[ "python", "math", "floating-point", "numpy" ]
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
558,216
<p>I have been asked to test a library provided by a 3rd party. The library is known to be accurate to <em>n</em> significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:</p> <pre><code>def nearlyequal( a, b, sigfig=5 ): </code></pre> <p>The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to <strong>sigfig</strong> significant-figures when written in decimal. </p> <p>Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:</p> <pre><code>assert nearlyequal(1, 1, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(-1e-9, 1e-9, 5) assert nearlyequal(1e9, 1e9 + 1 , 5) assert not nearlyequal( 1e4, 1e4 + 1, 5) assert nearlyequal( 0.0, 1e-15, 5 ) assert not nearlyequal( 0.0, 1e-4, 6 ) </code></pre> <p>Additional notes:</p> <ol> <li>Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.</li> <li>Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.</li> <li>Speed... I've got to compare a lot of numbers so the faster the better.</li> <li>I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.</li> </ol>
13
2009-02-17T18:49:20Z
558,359
<p>I believe your question is not defined well enough, and the unit-tests you present prove it:</p> <p>If by 'round to N sig-fig decimal places' you mean 'N decimal places to the right of the decimal point', then the test <code>assert nearlyequal(1e9, 1e9 + 1 , 5)</code> should fail, because even when you round 1000000000 and 1000000001 to 0.00001 accuracy, they are still different.</p> <p>And if by 'round to N sig-fig decimal places' you mean 'The N most significant digits, regardless of the decimal point', then the test <code>assert nearlyequal(-1e-9, 1e-9, 5)</code> should fail, because 0.000000001 and -0.000000001 are totally different when viewed this way.</p> <p>If you meant the first definition, then the first answer on this page (by Triptych) is good. If you meant the second definition, please say it, I promise to think about it :-)</p>
4
2009-02-17T19:24:29Z
[ "python", "math", "floating-point", "numpy" ]
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
558,216
<p>I have been asked to test a library provided by a 3rd party. The library is known to be accurate to <em>n</em> significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:</p> <pre><code>def nearlyequal( a, b, sigfig=5 ): </code></pre> <p>The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to <strong>sigfig</strong> significant-figures when written in decimal. </p> <p>Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:</p> <pre><code>assert nearlyequal(1, 1, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(-1e-9, 1e-9, 5) assert nearlyequal(1e9, 1e9 + 1 , 5) assert not nearlyequal( 1e4, 1e4 + 1, 5) assert nearlyequal( 0.0, 1e-15, 5 ) assert not nearlyequal( 0.0, 1e-4, 6 ) </code></pre> <p>Additional notes:</p> <ol> <li>Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.</li> <li>Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.</li> <li>Speed... I've got to compare a lot of numbers so the faster the better.</li> <li>I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.</li> </ol>
13
2009-02-17T18:49:20Z
563,955
<p>This is a fairly common issue with floating point numbers. I solve it based on the discussion in Section 1.5 of Demmel[1]. (1) Calculate the roundoff error. (2) Check that the roundoff error is less than some epsilon. I haven't used python in some time and only have version 2.4.3, but I'll try to get this correct.</p> <p>Step 1. Roundoff error</p> <pre><code>def roundoff_error(exact, approximate): return abs(approximate/exact - 1.0) </code></pre> <p>Step 2. Floating point equality</p> <pre><code>def float_equal(float1, float2, epsilon=2.0e-9): return (roundoff_error(float1, float2) &lt; epsilon) </code></pre> <p>There are a couple obvious deficiencies with this code.</p> <ol> <li>Division by zero error if the exact value is Zero.</li> <li>Does not verify that the arguments are floating point values.</li> </ol> <p>Revision 1.</p> <pre><code>def roundoff_error(exact, approximate): if (exact == 0.0 or approximate == 0.0): return abs(exact + approximate) else: return abs(approximate/exact - 1.0) def float_equal(float1, float2, epsilon=2.0e-9): if not isinstance(float1,float): raise TypeError,"First argument is not a float." elif not isinstance(float2,float): raise TypeError,"Second argument is not a float." else: return (roundoff_error(float1, float2) &lt; epsilon) </code></pre> <p>That's a little better. If either the exact or the approximate value is zero, than the error is equal to the value of the other. If something besides a floating point value is provided, a TypeError is raised.</p> <p>At this point, the only difficult thing is setting the correct value for epsilon. I noticed in the documentation for version 2.6.1 that there is an epsilon attribute in sys.float_info, so I would use twice that value as the default epsilon. But the correct value depends on both your application and your algorithm.</p> <p>[1] James W. Demmel, <em>Applied Numerical Linear Algebra</em>, SIAM, 1997.</p>
1
2009-02-19T04:30:15Z
[ "python", "math", "floating-point", "numpy" ]
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
558,216
<p>I have been asked to test a library provided by a 3rd party. The library is known to be accurate to <em>n</em> significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:</p> <pre><code>def nearlyequal( a, b, sigfig=5 ): </code></pre> <p>The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to <strong>sigfig</strong> significant-figures when written in decimal. </p> <p>Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:</p> <pre><code>assert nearlyequal(1, 1, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(-1e-9, 1e-9, 5) assert nearlyequal(1e9, 1e9 + 1 , 5) assert not nearlyequal( 1e4, 1e4 + 1, 5) assert nearlyequal( 0.0, 1e-15, 5 ) assert not nearlyequal( 0.0, 1e-4, 6 ) </code></pre> <p>Additional notes:</p> <ol> <li>Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.</li> <li>Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.</li> <li>Speed... I've got to compare a lot of numbers so the faster the better.</li> <li>I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.</li> </ol>
13
2009-02-17T18:49:20Z
563,993
<p>Oren Shemesh got part of the problem with the problem as stated but there's more:</p> <p>assert nearlyequal( 0.0, 1e-15, 5 ) </p> <p>also fails the second definition (and that's the definition I learned in school.)</p> <p>No matter how many digits you are looking at, 0 will not equal a not-zero. This could prove to be a headache for such tests if you have a case whose correct answer is zero.</p>
1
2009-02-19T04:55:15Z
[ "python", "math", "floating-point", "numpy" ]
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
558,216
<p>I have been asked to test a library provided by a 3rd party. The library is known to be accurate to <em>n</em> significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:</p> <pre><code>def nearlyequal( a, b, sigfig=5 ): </code></pre> <p>The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to <strong>sigfig</strong> significant-figures when written in decimal. </p> <p>Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:</p> <pre><code>assert nearlyequal(1, 1, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(-1e-9, 1e-9, 5) assert nearlyequal(1e9, 1e9 + 1 , 5) assert not nearlyequal( 1e4, 1e4 + 1, 5) assert nearlyequal( 0.0, 1e-15, 5 ) assert not nearlyequal( 0.0, 1e-4, 6 ) </code></pre> <p>Additional notes:</p> <ol> <li>Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.</li> <li>Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.</li> <li>Speed... I've got to compare a lot of numbers so the faster the better.</li> <li>I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.</li> </ol>
13
2009-02-17T18:49:20Z
564,086
<p>There are already plenty of great answers, but here's a think:</p> <pre><code>def closeness(a, b): """Returns measure of equality (for two floats), in unit of decimal significant figures.""" if a == b: return float("infinity") difference = abs(a - b) avg = (a + b)/2 return math.log10( avg / difference ) if closeness(1000, 1000.1) &gt; 3: print "Joy!" </code></pre>
3
2009-02-19T05:50:20Z
[ "python", "math", "floating-point", "numpy" ]
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
558,216
<p>I have been asked to test a library provided by a 3rd party. The library is known to be accurate to <em>n</em> significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:</p> <pre><code>def nearlyequal( a, b, sigfig=5 ): </code></pre> <p>The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to <strong>sigfig</strong> significant-figures when written in decimal. </p> <p>Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:</p> <pre><code>assert nearlyequal(1, 1, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(-1e-9, 1e-9, 5) assert nearlyequal(1e9, 1e9 + 1 , 5) assert not nearlyequal( 1e4, 1e4 + 1, 5) assert nearlyequal( 0.0, 1e-15, 5 ) assert not nearlyequal( 0.0, 1e-4, 6 ) </code></pre> <p>Additional notes:</p> <ol> <li>Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.</li> <li>Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.</li> <li>Speed... I've got to compare a lot of numbers so the faster the better.</li> <li>I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.</li> </ol>
13
2009-02-17T18:49:20Z
1,595,078
<p>There is a interesting solution to this by B. Dawson (with C++ code) at <a href="http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm" rel="nofollow">"Comparing Floating Point Numbers"</a>. His approach relies on strict IEEE representation of two numbers and the enforced lexicographical ordering when said numbers are represented as unsigned integers.</p>
1
2009-10-20T14:36:50Z
[ "python", "math", "floating-point", "numpy" ]
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
558,216
<p>I have been asked to test a library provided by a 3rd party. The library is known to be accurate to <em>n</em> significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:</p> <pre><code>def nearlyequal( a, b, sigfig=5 ): </code></pre> <p>The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to <strong>sigfig</strong> significant-figures when written in decimal. </p> <p>Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:</p> <pre><code>assert nearlyequal(1, 1, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(-1e-9, 1e-9, 5) assert nearlyequal(1e9, 1e9 + 1 , 5) assert not nearlyequal( 1e4, 1e4 + 1, 5) assert nearlyequal( 0.0, 1e-15, 5 ) assert not nearlyequal( 0.0, 1e-4, 6 ) </code></pre> <p>Additional notes:</p> <ol> <li>Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.</li> <li>Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.</li> <li>Speed... I've got to compare a lot of numbers so the faster the better.</li> <li>I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.</li> </ol>
13
2009-02-17T18:49:20Z
20,585,965
<p>There are lots of ways of comparing two numbers to see if they agree to N significant digits. Roughly speaking you just want to make sure that their difference is less than 10^-N times the largest of the two numbers being compared. That's easy enough.</p> <p>But, what if one of the numbers is zero? The whole concept of relative-differences or significant-digits falls down when comparing against zero. To handle that case you need to have an absolute-difference as well, which should be specified differently from the relative-difference.</p> <p>I discuss the problems of comparing floating-point numbers -- including a specific case of handling zero -- in this blog post:</p> <p><a href="http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/" rel="nofollow">http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/</a></p>
0
2013-12-14T17:11:49Z
[ "python", "math", "floating-point", "numpy" ]
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
558,216
<p>I have been asked to test a library provided by a 3rd party. The library is known to be accurate to <em>n</em> significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:</p> <pre><code>def nearlyequal( a, b, sigfig=5 ): </code></pre> <p>The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to <strong>sigfig</strong> significant-figures when written in decimal. </p> <p>Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:</p> <pre><code>assert nearlyequal(1, 1, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(1.0, 1.0, 5) assert nearlyequal(-1e-9, 1e-9, 5) assert nearlyequal(1e9, 1e9 + 1 , 5) assert not nearlyequal( 1e4, 1e4 + 1, 5) assert nearlyequal( 0.0, 1e-15, 5 ) assert not nearlyequal( 0.0, 1e-4, 6 ) </code></pre> <p>Additional notes:</p> <ol> <li>Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.</li> <li>Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.</li> <li>Speed... I've got to compare a lot of numbers so the faster the better.</li> <li>I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.</li> </ol>
13
2009-02-17T18:49:20Z
36,407,955
<p>As of Python 3.5, the standard way to do this (using the standard library) is with the <a href="https://docs.python.org/3/library/math.html#math.isclose" rel="nofollow"><code>math.isclose</code></a> function.</p> <p>It has the following signature:</p> <pre><code>isclose(a, b, rel_tol=1e-9, abs_tol=0.0) </code></pre> <p>An example of usage with absolute error tolerance:</p> <pre><code>from math import isclose a = 1.0 b = 1.00000001 assert isclose(a, b, abs_tol=1e-8) </code></pre> <p>If you want it with precision of <strong><em>n</em></strong> significant digits, simply replace the last line with:</p> <pre><code>assert isclose(a, b, abs_tol=10**-n) </code></pre>
5
2016-04-04T16:24:31Z
[ "python", "math", "floating-point", "numpy" ]
Bayesian spam filtering library for Python
558,219
<p>I am looking for a Python library which does Bayesian Spam Filtering. I looked at SpamBayes and OpenBayes, but both seem to be unmaintained (I might be wrong).</p> <p>Can anyone suggest a good Python (or Clojure, Common Lisp, even Ruby) library which implements Bayesian Spam Filtering?</p> <p>Thanks in advance.</p> <p><strong>Clarification</strong>: I am actually looking for a <em>Bayesian Spam Classifier</em> and not necessarily a spam filter. I just want to train it using some data and later tell me whether some given data is spam. Sorry for any confusion.</p>
19
2009-02-17T18:50:18Z
558,299
<p>Try to use <a href="http://bogofilter.sourceforge.net/" rel="nofollow">bogofilter</a>, I'm not sure how it can be used from Python. Bogofilter is integrated with many mail systems, which means a relative ease of interfacing.</p>
3
2009-02-17T19:10:11Z
[ "python", "spam-prevention", "bayesian", "bayesian-networks" ]
Bayesian spam filtering library for Python
558,219
<p>I am looking for a Python library which does Bayesian Spam Filtering. I looked at SpamBayes and OpenBayes, but both seem to be unmaintained (I might be wrong).</p> <p>Can anyone suggest a good Python (or Clojure, Common Lisp, even Ruby) library which implements Bayesian Spam Filtering?</p> <p>Thanks in advance.</p> <p><strong>Clarification</strong>: I am actually looking for a <em>Bayesian Spam Classifier</em> and not necessarily a spam filter. I just want to train it using some data and later tell me whether some given data is spam. Sorry for any confusion.</p>
19
2009-02-17T18:50:18Z
558,405
<p>Do you want spam filtering or Bayesian classification?</p> <p>For Bayesian classification there are a number of Python modules. I was just recently reviewing <a href="http://www.ailab.si/orange/">Orange</a> which looks very impressive. R has a number of Bayesian modules. You can use <a href="http://rpy.sourceforge.net/">Rpy</a> to hook into R.</p>
11
2009-02-17T19:35:52Z
[ "python", "spam-prevention", "bayesian", "bayesian-networks" ]
Bayesian spam filtering library for Python
558,219
<p>I am looking for a Python library which does Bayesian Spam Filtering. I looked at SpamBayes and OpenBayes, but both seem to be unmaintained (I might be wrong).</p> <p>Can anyone suggest a good Python (or Clojure, Common Lisp, even Ruby) library which implements Bayesian Spam Filtering?</p> <p>Thanks in advance.</p> <p><strong>Clarification</strong>: I am actually looking for a <em>Bayesian Spam Classifier</em> and not necessarily a spam filter. I just want to train it using some data and later tell me whether some given data is spam. Sorry for any confusion.</p>
19
2009-02-17T18:50:18Z
561,654
<p>Try <a href="http://bazaar.launchpad.net/~divmod-dev/divmod.org/trunk/files/head:/Reverend/" rel="nofollow">Reverend</a>. It's a spam filtering module.</p>
12
2009-02-18T15:50:37Z
[ "python", "spam-prevention", "bayesian", "bayesian-networks" ]
Bayesian spam filtering library for Python
558,219
<p>I am looking for a Python library which does Bayesian Spam Filtering. I looked at SpamBayes and OpenBayes, but both seem to be unmaintained (I might be wrong).</p> <p>Can anyone suggest a good Python (or Clojure, Common Lisp, even Ruby) library which implements Bayesian Spam Filtering?</p> <p>Thanks in advance.</p> <p><strong>Clarification</strong>: I am actually looking for a <em>Bayesian Spam Classifier</em> and not necessarily a spam filter. I just want to train it using some data and later tell me whether some given data is spam. Sorry for any confusion.</p>
19
2009-02-17T18:50:18Z
806,101
<p><a href="http://spambayes.org" rel="nofollow">SpamBayes</a> <strong>is</strong> maintained, and is mature (i.e. it works without having to have new releases all the time). It will easily do what you want. Note that SpamBayes is only loosely Bayesian (it uses chi-squared combining), but presumably you're after any sort of statistical token-based classification, rather than something specifically Bayesian.</p>
3
2009-04-30T09:31:01Z
[ "python", "spam-prevention", "bayesian", "bayesian-networks" ]
Bayesian spam filtering library for Python
558,219
<p>I am looking for a Python library which does Bayesian Spam Filtering. I looked at SpamBayes and OpenBayes, but both seem to be unmaintained (I might be wrong).</p> <p>Can anyone suggest a good Python (or Clojure, Common Lisp, even Ruby) library which implements Bayesian Spam Filtering?</p> <p>Thanks in advance.</p> <p><strong>Clarification</strong>: I am actually looking for a <em>Bayesian Spam Classifier</em> and not necessarily a spam filter. I just want to train it using some data and later tell me whether some given data is spam. Sorry for any confusion.</p>
19
2009-02-17T18:50:18Z
978,043
<p>A module in the Python natural language toolkit (nltk) does naïve Bayesian classification: <a href="http://nltk.googlecode.com/svn/trunk/doc/api/nltk.classify.naivebayes-module.html" rel="nofollow"><code>nltk.classify.naivebayes</code></a>.</p> <p><em>Disclaimer:</em> I know crap all about Bayesian classification, naïve or worldly.</p>
1
2009-06-10T20:44:01Z
[ "python", "spam-prevention", "bayesian", "bayesian-networks" ]
Bayesian spam filtering library for Python
558,219
<p>I am looking for a Python library which does Bayesian Spam Filtering. I looked at SpamBayes and OpenBayes, but both seem to be unmaintained (I might be wrong).</p> <p>Can anyone suggest a good Python (or Clojure, Common Lisp, even Ruby) library which implements Bayesian Spam Filtering?</p> <p>Thanks in advance.</p> <p><strong>Clarification</strong>: I am actually looking for a <em>Bayesian Spam Classifier</em> and not necessarily a spam filter. I just want to train it using some data and later tell me whether some given data is spam. Sorry for any confusion.</p>
19
2009-02-17T18:50:18Z
11,917,279
<p>RedisBayes looks good to me:</p> <p><a href="http://pypi.python.org/pypi/redisbayes/0.1.3">http://pypi.python.org/pypi/redisbayes/0.1.3</a></p> <p>In my experience Redis is an awesome addition to your stack and can help process data at blazing fast speeds compared to MySQL, PostgreSQL or any other RDBMS.</p> <pre><code>import redis, redisbayes rb = redisbayes.RedisBayes(redis=redis.Redis()) rb.train('good', 'sunshine drugs love sex lobster sloth') rb.train('bad', 'fear death horror government zombie god') assert rb.classify('sloths are so cute i love them') == 'good' assert rb.classify('i fear god and love the government') == 'bad' print rb.score('i fear god and love the government') rb.untrain('good', 'sunshine drugs love sex lobster sloth') rb.untrain('bad', 'fear death horror government zombie god') </code></pre> <p>Hope that helps a bit.</p>
8
2012-08-11T20:11:51Z
[ "python", "spam-prevention", "bayesian", "bayesian-networks" ]
What is wrong with my nested loops in Python?
558,539
<p>How do I make nested loops in Python (version 3.0)?</p> <p>I am trying to get the following loops to show me the products of two numbers:</p> <pre><code>def PrintProductsBelowNumber(number): number1 = 1 number2 = 1 while number1 &lt;= number: while number2 &lt;= number: print(number1, "*", number2, "=", number1 * number2) number2 += 1 number1 += 1 PrintProductsBelowNumber(2) </code></pre> <p>As a result I get:</p> <pre><code>1 * 1 = 1 1 * 2 = 2 </code></pre> <p>So it seems the outer loop over number1 does not run.</p> <p>How do I get the loop over number1 to run, and thus obtain:</p> <pre><code>1 * 1 = 1 1 * 2 = 2 2 * 1 = 2 2 * 2 = 4 </code></pre>
0
2009-02-17T20:19:26Z
558,552
<p>Because you aren't setting number2 back to 1 after the inner loop completes the first time. number1 then increments, but since number2 is still too high the inner loop doesn't run again. </p> <pre><code>def PrintProductsBelowNumber(number): number1 = 1 while number1 &lt;= number: number2 = 1 while number2 &lt;= number: print(number1, "*", number2, "=", number1 * number2) number2 += 1 number1 += 1 PrintProductsBelowNumber(2) </code></pre> <p><strong>EDIT</strong>: Adam's solution is much better in general, but this is to show why your's wasn't working the way you thought it should in the first place.</p>
8
2009-02-17T20:22:32Z
[ "python", "loops", "nested" ]
What is wrong with my nested loops in Python?
558,539
<p>How do I make nested loops in Python (version 3.0)?</p> <p>I am trying to get the following loops to show me the products of two numbers:</p> <pre><code>def PrintProductsBelowNumber(number): number1 = 1 number2 = 1 while number1 &lt;= number: while number2 &lt;= number: print(number1, "*", number2, "=", number1 * number2) number2 += 1 number1 += 1 PrintProductsBelowNumber(2) </code></pre> <p>As a result I get:</p> <pre><code>1 * 1 = 1 1 * 2 = 2 </code></pre> <p>So it seems the outer loop over number1 does not run.</p> <p>How do I get the loop over number1 to run, and thus obtain:</p> <pre><code>1 * 1 = 1 1 * 2 = 2 2 * 1 = 2 2 * 2 = 4 </code></pre>
0
2009-02-17T20:19:26Z
558,554
<p><code>number2</code> only gets initialized once, you need to re-initialize it for each iteration of the inner loop. However, this code is very C-like and not very Pythonic. The better way to do it would be to use the <code>for number in range(n)</code> construct:</p> <pre><code>def PrintProductsBelowNumber(number): for number1 in range(1, number+1): for number2 in range(1, number+1): print(number1, "*", number2, "=", number1 * number2) </code></pre>
14
2009-02-17T20:22:58Z
[ "python", "loops", "nested" ]
What is wrong with my nested loops in Python?
558,539
<p>How do I make nested loops in Python (version 3.0)?</p> <p>I am trying to get the following loops to show me the products of two numbers:</p> <pre><code>def PrintProductsBelowNumber(number): number1 = 1 number2 = 1 while number1 &lt;= number: while number2 &lt;= number: print(number1, "*", number2, "=", number1 * number2) number2 += 1 number1 += 1 PrintProductsBelowNumber(2) </code></pre> <p>As a result I get:</p> <pre><code>1 * 1 = 1 1 * 2 = 2 </code></pre> <p>So it seems the outer loop over number1 does not run.</p> <p>How do I get the loop over number1 to run, and thus obtain:</p> <pre><code>1 * 1 = 1 1 * 2 = 2 2 * 1 = 2 2 * 2 = 4 </code></pre>
0
2009-02-17T20:19:26Z
558,891
<p>You could modify Adam's solution with a list comprehension:</p> <pre><code>def PrintProductsBelowNumber(number): results = [(i, j, i * j) for i in range(1, number + 1) for j in range(1, number + 1)] for number1, number2, result in results: print(number1, "*", number2, "=", result) </code></pre> <p>or some variation thereof.</p>
0
2009-02-17T21:54:59Z
[ "python", "loops", "nested" ]
Detect script start up from command prompt or "double click" on Windows
558,776
<p>Is is possible to detect if a Python script was started from the command prompt or by a user "double clicking" a .py file in the file explorer on Windows?</p>
4
2009-02-17T21:20:24Z
558,804
<p>The command-prompt started script has a parent process named <code>cmd.exe</code> (or a non-existent process, in case the console has been closed in the mean time). </p> <p>The doubleclick-started script should have a parent process named <code>explorer.exe</code>.</p>
3
2009-02-17T21:26:13Z
[ "python", "windows" ]
Detect script start up from command prompt or "double click" on Windows
558,776
<p>Is is possible to detect if a Python script was started from the command prompt or by a user "double clicking" a .py file in the file explorer on Windows?</p>
4
2009-02-17T21:20:24Z
558,808
<p>Good question. One thing you could do is create a shortcut to the script in Windows, and pass arguments (using the shortcut's Target property) that would denote the script was launched by double-clicking (in this case, a shortcut).</p>
2
2009-02-17T21:26:57Z
[ "python", "windows" ]
Detect script start up from command prompt or "double click" on Windows
558,776
<p>Is is possible to detect if a Python script was started from the command prompt or by a user "double clicking" a .py file in the file explorer on Windows?</p>
4
2009-02-17T21:20:24Z
573,426
<p>Here is an example of how to obtain the parent process id and name of the current running script. As suggested by <a href="http://stackoverflow.com/users/18771/tomalak">Tomalak</a> this can be used to detect if the script was started from the command prompt or by double clicking in explorer.</p> <pre><code>import win32pdh import os def getPIDInfo(): """ Return a dictionary with keys the PID of all running processes. The values are dictionaries with the following key-value pairs: - name: &lt;Name of the process PID&gt; - parent_id: &lt;PID of this process parent&gt; """ # get the names and occurences of all running process names items, instances = win32pdh.EnumObjectItems(None, None, 'Process', win32pdh.PERF_DETAIL_WIZARD) instance_dict = {} for instance in instances: instance_dict[instance] = instance_dict.get(instance, 0) + 1 # define the info to obtain counter_items = ['ID Process', 'Creating Process ID'] # output dict pid_dict = {} # loop over each program (multiple instances might be running) for instance, max_instances in instance_dict.items(): for inum in xrange(max_instances): # define the counters for the query hq = win32pdh.OpenQuery() hcs = {} for item in counter_items: path = win32pdh.MakeCounterPath((None,'Process',instance, None,inum,item)) hcs[item] = win32pdh.AddCounter(hq,path) win32pdh.CollectQueryData(hq) # store the values in a temporary dict hc_dict = {} for item, hc in hcs.items(): type,val=win32pdh.GetFormattedCounterValue(hc,win32pdh.PDH_FMT_LONG) hc_dict[item] = val win32pdh.RemoveCounter(hc) win32pdh.CloseQuery(hq) # obtain the pid and ppid of the current instance # and store it in the output dict pid, ppid = (hc_dict[item] for item in counter_items) pid_dict[pid] = {'name': instance, 'parent_id': ppid} return pid_dict def getParentInfo(pid): """ Returns a PID, Name tuple of the parent process for the argument pid process. """ pid_info = getPIDInfo() ppid = pid_info[pid]['parent_id'] return ppid, pid_info[ppid]['name'] if __name__ == "__main__": """ Print the current PID and information of the parent process. """ pid = os.getpid() ppid, ppname = getParentInfo(pid) print "This PID: %s. Parent PID: %s, Parent process name: %s" % (pid, ppid, ppname) dummy = raw_input() </code></pre> <p>When run from the command prompt this outputs:</p> <blockquote> <p>This PID: 148. Parent PID: 4660, Parent process name: cmd</p> </blockquote> <p>When started by double clicking in explorer this outputs:</p> <blockquote> <p>This PID: 1896. Parent PID: 3788, Parent process name: explorer</p> </blockquote>
3
2009-02-21T17:27:56Z
[ "python", "windows" ]
Detect script start up from command prompt or "double click" on Windows
558,776
<p>Is is possible to detect if a Python script was started from the command prompt or by a user "double clicking" a .py file in the file explorer on Windows?</p>
4
2009-02-17T21:20:24Z
14,394,730
<p>If running from the command line there is an extra environment variable 'PROMPT' defined.</p> <p>This script will pause if clicked from the explorer and not pause if run from the command line: </p> <pre><code>import os print 'Hello, world!' if not 'PROMPT' in os.environ: raw_input() </code></pre> <p>Tested on Windows 7 with Python 2.7</p>
4
2013-01-18T08:05:45Z
[ "python", "windows" ]