title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
How do I validate a Django form containing a file on App Engine with google-app-engine-django?
1,573,913
<p>I have a model and form like so:</p> <pre><code>class Image(BaseModel): original = db.BlobProperty() class ImageForm(ModelForm): class Meta: model = Image </code></pre> <p>I do the following in my view:</p> <pre><code>form = ImageForm(request.POST, request.FILES, instance=image) if form.is_valid(): </code></pre> <p>And I get:</p> <blockquote> <p>AttributeError at /image/add/</p> <p>'NoneType' object has no attribute 'validate'</p> </blockquote> <p>Traced to:</p> <blockquote> <p>/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/djangoforms.py in property_clean</p> <ol> <li>value: The value to validate. 606.</li> <li>Raises:</li> <li>forms.ValidationError if the value cannot be validated.</li> <li>"""</li> <li>if value is not None:</li> <li><p>try:</p></li> <li><p>prop.validate(prop.make_value_from_form(value)) ...</p></li> <li><p>except (db.BadValueError, ValueError), e:</p></li> <li>raise forms.ValidationError(unicode(e)) 615. 616.</li> <li>class ModelFormOptions(object):</li> <li>"""A simple class to hold internal options for a ModelForm class.</li> </ol> <p>▼ Local vars</p> <p>prop None</p> <p>value InMemoryUploadedFile: Nearby.jpg (image/jpeg)</p> </blockquote> <p>Any ideas how to get it to validate? It looks like FileField does not have a validate method, which Django expects...</p>
1
2009-10-15T17:32:13Z
1,574,192
<p>The docs for the constructor say:</p> <blockquote> <p>files: dict of file upload values; Django 0.97 or later only</p> </blockquote> <p>Are you using Django 0.97? The bundled Django is 0.96, unless you explicitly select 1.0 or 1.1. Have you tried validating the form without the files parameter?</p>
0
2009-10-15T18:25:45Z
[ "python", "django", "google-app-engine", "django-forms", "validation" ]
How do I validate a Django form containing a file on App Engine with google-app-engine-django?
1,573,913
<p>I have a model and form like so:</p> <pre><code>class Image(BaseModel): original = db.BlobProperty() class ImageForm(ModelForm): class Meta: model = Image </code></pre> <p>I do the following in my view:</p> <pre><code>form = ImageForm(request.POST, request.FILES, instance=image) if form.is_valid(): </code></pre> <p>And I get:</p> <blockquote> <p>AttributeError at /image/add/</p> <p>'NoneType' object has no attribute 'validate'</p> </blockquote> <p>Traced to:</p> <blockquote> <p>/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/djangoforms.py in property_clean</p> <ol> <li>value: The value to validate. 606.</li> <li>Raises:</li> <li>forms.ValidationError if the value cannot be validated.</li> <li>"""</li> <li>if value is not None:</li> <li><p>try:</p></li> <li><p>prop.validate(prop.make_value_from_form(value)) ...</p></li> <li><p>except (db.BadValueError, ValueError), e:</p></li> <li>raise forms.ValidationError(unicode(e)) 615. 616.</li> <li>class ModelFormOptions(object):</li> <li>"""A simple class to hold internal options for a ModelForm class.</li> </ol> <p>▼ Local vars</p> <p>prop None</p> <p>value InMemoryUploadedFile: Nearby.jpg (image/jpeg)</p> </blockquote> <p>Any ideas how to get it to validate? It looks like FileField does not have a validate method, which Django expects...</p>
1
2009-10-15T17:32:13Z
1,618,697
<p>It doesn't work with default django version. And bug is <a href="http://code.google.com/p/googleappengine/issues/detail?id=920" rel="nofollow">reported</a>. </p> <p>BTW, default installation raise other exeption. So possible problem with other part of your code.</p>
4
2009-10-24T18:31:37Z
[ "python", "django", "google-app-engine", "django-forms", "validation" ]
How to find duplicates in MySQL
1,574,064
<p>Suppose I have many columns. If 2 columns match and are exactly the same, then they are duplicates.</p> <pre><code>ID | title | link | size | author </code></pre> <p>Suppose if link and size are similar for 2 rows or more, then those rows are duplicates. How do I get those duplicates into a list and process them?</p>
2
2009-10-15T18:02:15Z
1,574,082
<p>Will return all records that have dups:</p> <pre><code>SELECT theTable.* FROM theTable INNER JOIN ( SELECT link, size FROM theTable GROUP BY link, size HAVING count(ID) &gt; 1 ) dups ON theTable.link = dups.link AND theTable.size = dups.size </code></pre> <p>I like the subquery b/c I can do things like select all but the first or last. (very easy to turn into a delete query then).</p> <p>Example: select all duplicate records EXCEPT the one with the max ID: </p> <pre><code>SELECT theTable.* FROM theTable INNER JOIN ( SELECT link, size, max(ID) as maxID FROM theTable GROUP BY link, size HAVING count(ID) &gt; 1 ) dups ON theTable.link = dups.link AND theTable.size = dups.size AND theTable.ID &lt;&gt; dups.maxID </code></pre>
7
2009-10-15T18:05:46Z
[ "python", "mysql" ]
How to find duplicates in MySQL
1,574,064
<p>Suppose I have many columns. If 2 columns match and are exactly the same, then they are duplicates.</p> <pre><code>ID | title | link | size | author </code></pre> <p>Suppose if link and size are similar for 2 rows or more, then those rows are duplicates. How do I get those duplicates into a list and process them?</p>
2
2009-10-15T18:02:15Z
1,574,092
<p>Assuming that none of <em>id</em>, <em>link</em> or <em>size</em> can be NULL, and <em>id</em> field is the primary key. This gives you the id's of duplicate rows. Beware that same id can be in the results several times, if there are three or more rows with identical link and size values.</p> <pre><code>select a.id, b.id from tbl a, tbl b where a.id &lt; b.id and a.link = b.link and a.size = b.size </code></pre>
1
2009-10-15T18:07:48Z
[ "python", "mysql" ]
How to find duplicates in MySQL
1,574,064
<p>Suppose I have many columns. If 2 columns match and are exactly the same, then they are duplicates.</p> <pre><code>ID | title | link | size | author </code></pre> <p>Suppose if link and size are similar for 2 rows or more, then those rows are duplicates. How do I get those duplicates into a list and process them?</p>
2
2009-10-15T18:02:15Z
1,574,103
<p>If you want to do it exclusively in <code>SQL</code>, some kind of self-join of the table (on equality of <code>link</code> and <code>size</code>) is required, and can be accompanied by different kinds of elaboration. Since you mention Python as well, I assume you want to do the processing in Python; in that case, simplest is to build an iterator on a 'SELECT * FROM thetable ORDER BY link, size<code>, and process with </code>itertools.groupby<code> using, as key, the </code>operator.itemgetter` for those two fields; this will present natural groupings of each bunch of 1+ rows with identical values for the fields in question.</p> <p>I can elaborate on either option if you clarify where you want to do your processing and ideally provide an example of the kind of processing you DO want to perform!</p>
0
2009-10-15T18:09:11Z
[ "python", "mysql" ]
How to find duplicates in MySQL
1,574,064
<p>Suppose I have many columns. If 2 columns match and are exactly the same, then they are duplicates.</p> <pre><code>ID | title | link | size | author </code></pre> <p>Suppose if link and size are similar for 2 rows or more, then those rows are duplicates. How do I get those duplicates into a list and process them?</p>
2
2009-10-15T18:02:15Z
1,574,362
<p>After you remove the duplicates from the MySQL table, you can add a unique index to the table so no more duplicates can be inserted:</p> <pre><code>create unique index theTable_index on theTable (link,size); </code></pre>
1
2009-10-15T19:02:04Z
[ "python", "mysql" ]
Plotting time in Python with Matplotlib
1,574,088
<p>I have an array of timestamps in the format (HH:MM:SS.mmmmmm) and another array of floating point numbers, each corresponding to a value in the timestamp array.</p> <p>Can I plot time on the x axis and the numbers on the y-axis using Matplotlib?</p> <p>I was trying to, but somehow it was only accepting arrays of floats. How can I get it to plot the time? Do I have to modify the format in any way?</p>
63
2009-10-15T18:07:10Z
1,574,146
<p>You must first convert your timestamps to Python <code>datetime</code> objects (use <code>datetime.strptime</code>). Then use <code>date2num</code> to convert the dates to matplotlib format.</p> <p>Plot the dates and values using <a href="http://matplotlib.org/api/pyplot_api.html?highlight=plot_date#matplotlib.pyplot.plot_date" rel="nofollow"><code>plot_date</code></a>:</p> <pre><code>dates = matplotlib.dates.date2num(list_of_datetimes) plot_date(dates, values) </code></pre>
77
2009-10-15T18:18:26Z
[ "python", "graph", "plot", "matplotlib" ]
Plotting time in Python with Matplotlib
1,574,088
<p>I have an array of timestamps in the format (HH:MM:SS.mmmmmm) and another array of floating point numbers, each corresponding to a value in the timestamp array.</p> <p>Can I plot time on the x axis and the numbers on the y-axis using Matplotlib?</p> <p>I was trying to, but somehow it was only accepting arrays of floats. How can I get it to plot the time? Do I have to modify the format in any way?</p>
63
2009-10-15T18:07:10Z
16,428,019
<p>You can also plot the timestamp, value pairs using <a href="http://matplotlib.org/api/pyplot_api.html?highlight=plot_date#matplotlib.pyplot.plot" rel="nofollow">pyplot.plot</a> (after parsing them from their string representation). (Tested with matplotlib versions 1.2.0 and 1.3.1.)</p> <p>Example:</p> <pre><code>import datetime import random import matplotlib.pyplot as plt # make up some data x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)] y = [i+random.gauss(0,1) for i,_ in enumerate(x)] # plot plt.plot(x,y) # beautify the x-labels plt.gcf().autofmt_xdate() plt.show() </code></pre> <p>Resulting image:</p> <p><img src="http://i.stack.imgur.com/QduOf.png" alt="Line Plot"></p> <hr> <p>Here's the same as a scatter plot:</p> <pre><code>import datetime import random import matplotlib.pyplot as plt # make up some data x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)] y = [i+random.gauss(0,1) for i,_ in enumerate(x)] # plot plt.scatter(x,y) # beautify the x-labels plt.gcf().autofmt_xdate() plt.show() </code></pre> <p>Produces an image similar to this:</p> <p><a href="http://i.stack.imgur.com/Px62M.png" rel="nofollow"><img src="http://i.stack.imgur.com/Px62M.png" alt="Scatter Plot"></a></p>
29
2013-05-07T20:30:05Z
[ "python", "graph", "plot", "matplotlib" ]
How to match columns in MySQL
1,574,418
<p>Everyone knows the "=" sign.</p> <pre><code>SELECT * FROM mytable WHERE column1 = column2; </code></pre> <p>However, what if I have different contents in column1 and column2...but they are VERY similar? (maybe off by a space, or have a word that's different).</p> <p>Is it possible to:</p> <pre><code>SELECT * FROM mytable WHERE ....column matches column2 with .4523423 "Score"... </code></pre> <p>I believe this is called fuzzy matching? Or pattern matching? That's the technical term for it.</p> <p>EDIT: I know about Soundex and Levenstein disatance. IS that what you recommend?</p>
3
2009-10-15T19:11:03Z
1,574,473
<p>What you are looking for is called <a href="http://en.wikipedia.org/wiki/Levenshtein%5Fdistance">Levenstein distance</a>. It gives you the number value which discribes the difference between two strings. </p> <p>In MySQL you have to write stored procedure for that. <a href="http://codejanitor.com/wp/2007/02/10/levenshtein-distance-as-a-mysql-stored-function/">Here</a> is the articla that may help.</p>
5
2009-10-15T19:18:34Z
[ "python", "sql", "mysql", "string", "pattern-matching" ]
How to match columns in MySQL
1,574,418
<p>Everyone knows the "=" sign.</p> <pre><code>SELECT * FROM mytable WHERE column1 = column2; </code></pre> <p>However, what if I have different contents in column1 and column2...but they are VERY similar? (maybe off by a space, or have a word that's different).</p> <p>Is it possible to:</p> <pre><code>SELECT * FROM mytable WHERE ....column matches column2 with .4523423 "Score"... </code></pre> <p>I believe this is called fuzzy matching? Or pattern matching? That's the technical term for it.</p> <p>EDIT: I know about Soundex and Levenstein disatance. IS that what you recommend?</p>
3
2009-10-15T19:11:03Z
1,574,523
<p>Lukasz Lysik posted a reference to a stored procedure that can do the fuzzy match from inside the database. If you will want to do this as an ongoing task, that is your best bet.</p> <p>But if you want to do this as a one-off task, and if you might want to do complicated checks, or if you want to do something complicated to clean up the fuzzy matches, you might want to do the fuzzy matching from within Python. (One of your tags is "python" so I assume you are open to a Python solution...)</p> <p>Using a Python ORM, you can get a Python list with one object per database row, and then use the full power of Python to analyze your data. You could use regular expressions, Python Levenstein functions, or anything else.</p> <p>The all-around best ORM for Python is probably <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>. I actually like the ORM from <a href="http://www.djangoproject.com/" rel="nofollow">Django</a> a little better; it's a little simpler, and I value simplicity. If your ORM needs are not complicated, the Django ORM may be a good choice. If in doubt, just go to SQLAlchemy.</p> <p>Good luck!</p>
0
2009-10-15T19:28:19Z
[ "python", "sql", "mysql", "string", "pattern-matching" ]
Python object that monitors changes in objects
1,574,458
<p>I want a Python object that will monitor whether other objects have changed since the last time they were checked in, probably by storing their hash and comparing. It should behave sort of like this:</p> <pre><code>&gt;&gt;&gt; library = Library() &gt;&gt;&gt; library.is_changed(object1) False &gt;&gt;&gt; object1.change_somehow() &gt;&gt;&gt; library.is_changed(object1) True &gt;&gt;&gt; library.is_changed(object1) False </code></pre> <p>Do you know of anything like that?</p>
3
2009-10-15T19:16:52Z
1,574,538
<p>I haven't heard of anything like this... but you could write it pretty easily. Use a dictionary to store a name:hash pair for each object, then use the <code>pickle</code> module to save the dictionary.</p>
0
2009-10-15T19:30:54Z
[ "python", "hash" ]
Python object that monitors changes in objects
1,574,458
<p>I want a Python object that will monitor whether other objects have changed since the last time they were checked in, probably by storing their hash and comparing. It should behave sort of like this:</p> <pre><code>&gt;&gt;&gt; library = Library() &gt;&gt;&gt; library.is_changed(object1) False &gt;&gt;&gt; object1.change_somehow() &gt;&gt;&gt; library.is_changed(object1) True &gt;&gt;&gt; library.is_changed(object1) False </code></pre> <p>Do you know of anything like that?</p>
3
2009-10-15T19:16:52Z
1,574,556
<p>It sounds like you're describing the <a href="http://en.wikipedia.org/wiki/Observer%5Fpattern" rel="nofollow">observer pattern</a>. Check here:</p> <ul> <li><a href="http://rudd-o.com/projects/python-observable/" rel="nofollow">http://rudd-o.com/projects/python-observable/</a> </li> <li><a href="http://twistedmatrix.com/trac/browser/trunk/twisted/python/observable.py?rev=1" rel="nofollow">Twisted observable</a> </li> <li><a href="http://radio.weblogs.com/0124960/2004/06/15.html#a30" rel="nofollow">http://radio.weblogs.com/0124960/2004/06/15.html#a30</a> - includes explanation</li> </ul>
2
2009-10-15T19:33:28Z
[ "python", "hash" ]
Python object that monitors changes in objects
1,574,458
<p>I want a Python object that will monitor whether other objects have changed since the last time they were checked in, probably by storing their hash and comparing. It should behave sort of like this:</p> <pre><code>&gt;&gt;&gt; library = Library() &gt;&gt;&gt; library.is_changed(object1) False &gt;&gt;&gt; object1.change_somehow() &gt;&gt;&gt; library.is_changed(object1) True &gt;&gt;&gt; library.is_changed(object1) False </code></pre> <p>Do you know of anything like that?</p>
3
2009-10-15T19:16:52Z
1,574,755
<p>Here is an implementation for you. Note that the objects you monitor must be hashable and picklable. Note also the use of a <code>WeakKeyDictionary</code> which means that the <code>Monitor</code> won't stop the monitored objects from being deleted.</p> <pre><code>from weakref import WeakKeyDictionary from cPickle import dumps class Monitor(): def __init__(self): self.objects = WeakKeyDictionary() def is_changed(self, obj): current_pickle = dumps(obj, -1) changed = False if obj in self.objects: changed = current_pickle != self.objects[obj] self.objects[obj] = current_pickle return changed class MyObject(): def __init__(self): self.i = 1 def change_somehow(self): self.i += 1 </code></pre> <p>If you test it like this</p> <pre><code>object1 = MyObject() monitor = Monitor() print monitor.is_changed(object1) object1.change_somehow() print monitor.is_changed(object1) print monitor.is_changed(object1) </code></pre> <p>It prints</p> <pre><code>False True False </code></pre>
5
2009-10-15T20:12:01Z
[ "python", "hash" ]
Python object that monitors changes in objects
1,574,458
<p>I want a Python object that will monitor whether other objects have changed since the last time they were checked in, probably by storing their hash and comparing. It should behave sort of like this:</p> <pre><code>&gt;&gt;&gt; library = Library() &gt;&gt;&gt; library.is_changed(object1) False &gt;&gt;&gt; object1.change_somehow() &gt;&gt;&gt; library.is_changed(object1) True &gt;&gt;&gt; library.is_changed(object1) False </code></pre> <p>Do you know of anything like that?</p>
3
2009-10-15T19:16:52Z
1,575,197
<p>I am stole idea from Nick Craig-Wood, and change it to Mix-Class. Come out more easyly using, as for me</p> <pre><code>from cPickle import dumps #base class for monitoring changes class ChangesMonitor: _cm_last_dump = None def is_chaged(self): prev_dump = self._cm_last_dump self._cm_last_dump = None cur_dump = dumps(self, -1) self._cm_last_dump = cur_dump return ( ( prev_dump is not None ) and ( prev_dump != cur_dump ) ) if __name__ == '__main__': print 'Test Example' #mix monitoring class with your common class class MyGreateObject(ChangesMonitor,object): one_val = 5 second_val = 7 def some_changes(self): self.second_val += 5 #and testing my_obj = MyGreateObject() print my_obj.is_chaged() print my_obj.is_chaged() my_obj.some_changes() print my_obj.is_chaged() print my_obj.is_chaged() </code></pre>
1
2009-10-15T21:29:05Z
[ "python", "hash" ]
Building Django app using Comet/Orbited on Apache, use mod_wsgi or mod_python?
1,574,513
<p>Building a Django app on a VPS. I am not very experienced with setting up my own server, but I decided to try a VPS this time around. </p> <p>I have been doing a bunch of research to learn how to "properly" setup a LAMPython server using the Apache worker MPM. Naturally, the mod_python vs mod_wsgi debate came up. </p> <p>Reading Graham Dumpleton's blog and his various mailinglist responses, I've learned quite a bit. Particularly, that the performance of mod_python could be greatly improved by using worker MPM - as described at <a href="http://blog.dscpl.com.au/2009/03/load-spikes-and-excessive-memory-usage.html" rel="nofollow">Load spikes and excessive memory usage in mod_python</a></p> <p>Regardless, I had decided to go with mod_wsgi(daemon mode) + worker MPM, but then I started looking into implementing Comet and I got a bit confused.</p> <p>I was considering implementing comet using the technique described by Dark Porter ( <a href="http://darkporter.com/?p=7" rel="nofollow">http://darkporter.com/?p=7</a>) because it looks like it optimizes the django setup a bit more by having it all in one process, but he specifically says that he uses mod_python and makes no mention of mod_wsgi.</p> <p>So my questions:</p> <p>1) Is it possible to implement Dark Porter's method using mod_wsgi? </p> <p>2) If you were setting a server to support Django+Comet, what components would you use and why? (mod_python vs mod_wsgi / DarkPortersMethod vs MorbidQ vs RabbitMQ)</p> <p>Thanks</p>
0
2009-10-15T19:26:32Z
1,574,586
<ol> <li><p>Yes, absolutely.</p></li> <li><p>I would probably use Orbited as implemented by Dark Porter - It's the simplest solution to get your code running, and implemented in pure python. Not to mention, based on Twisted and thus <em>very</em> scalable, and has a well-established community of Django users.</p></li> </ol>
3
2009-10-15T19:39:19Z
[ "python", "django", "apache", "comet" ]
syntax error on `If` line
1,574,530
<p>My code:</p> <pre><code>#!/usr/bin/env python def Runaaall(aaa): Objects9(1.0, 2.0) def Objects9(aaa1, aaa2): If aaa2 != 0: print aaa1 / aaa2 </code></pre> <p>The error I receive:</p> <pre><code>$ python test2.py File "test2.py", line 7 If aaa2 != 0: print aaa1 / aaa2 ^ SyntaxError: invalid syntax </code></pre> <p>I'm at a loss to why this error is happening.</p>
1
2009-10-15T19:29:15Z
1,574,542
<p><code>if</code> must be written in lower case.</p> <p>Furthermore,</p> <ul> <li>Write function names in lower case (see <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a>, the Python style guide).</li> <li>Write the body of an <code>if</code>-clause on a separate line.</li> <li>Though in this case you'll probably not run into trouble, be careful with <a href="http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm" rel="nofollow">comparing floats for equality</a>.</li> <li><p>Since you've just started learning Python, you may want to get acquainted with writing parentheses around the arguments to <code>print</code>, since from Python 3 onwards, <a href="http://docs.python.org/dev/3.0/whatsnew/3.0.html" rel="nofollow">print is a function</a>, not a keyword.<br /> To enforce this syntax in Python 2.6, you can put this at the top of your file:</p> <pre><code>from __future__ import print_function </code></pre> <p>Demonstration:</p> <pre><code>&gt;&gt;&gt; print 'test' test &gt;&gt;&gt; from __future__ import print_function &gt;&gt;&gt; print 'test' File "&lt;stdin&gt;", line 1 print 'test' ^ SyntaxError: invalid syntax &gt;&gt;&gt; print('test') test </code></pre> <p>For more on <code>__future__</code> imports, see the <a href="http://docs.python.org/3.1/library/%5F%5Ffuture%5F%5F.html" rel="nofollow">documentation</a>.</p></li> </ul>
16
2009-10-15T19:31:14Z
[ "python", "syntax" ]
syntax error on `If` line
1,574,530
<p>My code:</p> <pre><code>#!/usr/bin/env python def Runaaall(aaa): Objects9(1.0, 2.0) def Objects9(aaa1, aaa2): If aaa2 != 0: print aaa1 / aaa2 </code></pre> <p>The error I receive:</p> <pre><code>$ python test2.py File "test2.py", line 7 If aaa2 != 0: print aaa1 / aaa2 ^ SyntaxError: invalid syntax </code></pre> <p>I'm at a loss to why this error is happening.</p>
1
2009-10-15T19:29:15Z
1,574,546
<p>How about</p> <pre><code>def Objects9(aaa1, aaa2): if aaa2 != 0: print aaa1 / aaa2 </code></pre> <p>Python keywords are case sensitive, so you must write 'if' instead of 'If', 'for' instead of 'fOR', et cetera.</p>
3
2009-10-15T19:31:45Z
[ "python", "syntax" ]
syntax error on `If` line
1,574,530
<p>My code:</p> <pre><code>#!/usr/bin/env python def Runaaall(aaa): Objects9(1.0, 2.0) def Objects9(aaa1, aaa2): If aaa2 != 0: print aaa1 / aaa2 </code></pre> <p>The error I receive:</p> <pre><code>$ python test2.py File "test2.py", line 7 If aaa2 != 0: print aaa1 / aaa2 ^ SyntaxError: invalid syntax </code></pre> <p>I'm at a loss to why this error is happening.</p>
1
2009-10-15T19:29:15Z
1,574,548
<p>It's the capital 'I' on "If". Change it to "if" and it will work.</p>
4
2009-10-15T19:32:11Z
[ "python", "syntax" ]
Efficient way to convert strings from split function to ints in Python
1,574,678
<p>I have a string of data with the following format: xpos-ypos-zoom (i.e. 8743-12083-15) that I want to split up and store in the variables xpos, ypos, and zoom. Since I need to do some calculations with these number I'd like to convert them to integers right from the beginning. Currently, the way I'm doing this is with the following code:</p> <pre><code>file = '8743-12083-15' xval, yval, zoom = file.split("-") xval = int(xval) yval = int(yval) </code></pre> <p>It seems to me there should be a more efficient way of doing this. Any ideas?</p>
7
2009-10-15T19:59:54Z
1,574,700
<p>You can <a href="http://docs.python.org/3.0/library/functions.html#map" rel="nofollow"><code>map</code></a> the function <a href="http://docs.python.org/3.0/library/functions.html#int" rel="nofollow"><code>int</code></a> on each substring, or use a <a href="http://www.python.org/dev/peps/pep-0202/" rel="nofollow">list comprehension</a>:</p> <pre><code>&gt;&gt;&gt; file = '8743-12083-15' &gt;&gt;&gt; list(map(int, file.split('-'))) [8743, 12083, 15] &gt;&gt;&gt; [int(d) for d in file.split('-')] [8743, 12083, 15] </code></pre> <p>In the above the call to <a href="http://docs.python.org/3.0/library/functions.html#list" rel="nofollow"><code>list</code></a> is not required, unless working with Python 3.x. (In Python 2.x <code>map</code> returns a list, in Python 3.x it returns a generator.)</p> <p>Directly assigning to the three variables is also possible (in this case a <a href="http://www.python.org/dev/peps/pep-0289/" rel="nofollow">generator expression</a> instead of a list comprehension will do):</p> <pre><code>&gt;&gt;&gt; xval, yval, zval = (int(d) for d in file.split('-')) &gt;&gt;&gt; xval, yval, zval (8743, 12083, 15) </code></pre>
4
2009-10-15T20:02:45Z
[ "python", "variables", "casting" ]
Efficient way to convert strings from split function to ints in Python
1,574,678
<p>I have a string of data with the following format: xpos-ypos-zoom (i.e. 8743-12083-15) that I want to split up and store in the variables xpos, ypos, and zoom. Since I need to do some calculations with these number I'd like to convert them to integers right from the beginning. Currently, the way I'm doing this is with the following code:</p> <pre><code>file = '8743-12083-15' xval, yval, zoom = file.split("-") xval = int(xval) yval = int(yval) </code></pre> <p>It seems to me there should be a more efficient way of doing this. Any ideas?</p>
7
2009-10-15T19:59:54Z
1,574,703
<p>efficient as in fewer lines of code?</p> <pre><code>(xval,yval,zval) = [int(s) for s in file.split('-')] </code></pre>
9
2009-10-15T20:03:06Z
[ "python", "variables", "casting" ]
Efficient way to convert strings from split function to ints in Python
1,574,678
<p>I have a string of data with the following format: xpos-ypos-zoom (i.e. 8743-12083-15) that I want to split up and store in the variables xpos, ypos, and zoom. Since I need to do some calculations with these number I'd like to convert them to integers right from the beginning. Currently, the way I'm doing this is with the following code:</p> <pre><code>file = '8743-12083-15' xval, yval, zoom = file.split("-") xval = int(xval) yval = int(yval) </code></pre> <p>It seems to me there should be a more efficient way of doing this. Any ideas?</p>
7
2009-10-15T19:59:54Z
1,574,718
<p>My original suggestion with a list comprehension.</p> <pre><code>test = '8743-12083-15' lst_int = [int(x) for x in test.split("-")] </code></pre> <p><strong>EDIT:</strong></p> <p>As to which is most efficient (cpu-cyclewise) is something that should always be tested. Some quick testing on my Python 2.6 install indicates <strong>map</strong> is probably the most efficient candidate here (building a list of integers from a value-splitted string). Note that the difference is so small that this does not really matter until you are doing this millions of times (and it is a proven bottleneck)...</p> <pre><code>def v1(): return [int(x) for x in '8743-12083-15'.split('-')] def v2(): return map(int, '8743-12083-15'.split('-')) import timeit print "v1", timeit.Timer('v1()', 'from __main__ import v1').timeit(500000) print "v2", timeit.Timer('v2()', 'from __main__ import v2').timeit(500000) &gt; output v1 3.73336911201 &gt; output v2 3.44717001915 </code></pre>
24
2009-10-15T20:04:31Z
[ "python", "variables", "casting" ]
Efficient way to convert strings from split function to ints in Python
1,574,678
<p>I have a string of data with the following format: xpos-ypos-zoom (i.e. 8743-12083-15) that I want to split up and store in the variables xpos, ypos, and zoom. Since I need to do some calculations with these number I'd like to convert them to integers right from the beginning. Currently, the way I'm doing this is with the following code:</p> <pre><code>file = '8743-12083-15' xval, yval, zoom = file.split("-") xval = int(xval) yval = int(yval) </code></pre> <p>It seems to me there should be a more efficient way of doing this. Any ideas?</p>
7
2009-10-15T19:59:54Z
1,574,802
<p>note: you might want to pick a different name for <code>file</code> as it shadows the buildtin</p> <p>this works in Python 2 and 3</p> <pre><code> xval,yval,zval = map(int,file.split('-')) </code></pre>
3
2009-10-15T20:22:16Z
[ "python", "variables", "casting" ]
Python multiprocessing: restrict number of cores used
1,575,067
<p>I want to know how to distribute N independent tasks to exactly M processors on a machine that has L cores, where L>M. I don't want to use all the processors because I still want to have I/O available. The solutions I've tried seem to get distributed to all processors, bogging down the system.</p> <p>I assume the multiprocessing module is the way to go.</p> <p>I do numerical simulations. My background is in physics, not computer science, so unfortunately, I often don't fully understand discussions involving standard tasking models like server/client, producer/consumer, etc.</p> <p>Here are some simplified models that I've tried:</p> <p>Suppose I have a function <code>run_sim(**kwargs)</code> (see that further below) that runs a simulation, and a long list of kwargs for the simulations, and I have an 8 core machine.</p> <pre><code>from multiprocessing import Pool, Process #using pool p = Pool(4) p.map(run_sim, kwargs) # using process number_of_live_jobs=0 all_jobs=[] sim_index=0 while sim_index &lt; len(kwargs)+1: number_of_live_jobs = len([1 for job in all_jobs if job.is_alive()]) if number_of_live_jobs &lt;= 4: p = Process(target=run_sim, args=[], kwargs=kwargs[sim_index]) print "starting job", kwargs[sim_index]["data_file_name"] print "number of live jobs: ", number_of_live_jobs p.start() p.join() all_jobs.append(p) sim_index += 1 </code></pre> <p>When I look at the processor usage with "top" and then "1", All processors seem to get used anyway in either case. It is not out of the question that I am misinterpreting the output of "top", but if the <code>run_simulation()</code> is processor intensive, the machine bogs down heavily.</p> <p>Hypothetical simulation and data:</p> <pre><code># simulation kwargs numbers_of_steps = range(0,10000000, 1000000) sigmas = [x for x in range(11)] kwargs = [] for number_of_steps in numbers_of_steps: for sigma in sigmas: kwargs.append( dict( number_of_steps=number_of_steps, sigma=sigma, # why do I need to cast to int? data_file_name="walk_steps=%i_sigma=%i" % (number_of_steps, sigma), ) ) import random, time random.seed(time.time()) # simulation of random walk def run_sim(kwargs): number_of_steps = kwargs["number_of_steps"] sigma = kwargs["sigma"] data_file_name = kwargs["data_file_name"] data_file = open(data_file_name+".dat", "w") current_position = 0 print "running simulation", data_file_name for n in range(int(number_of_steps)+1): data_file.write("step number %i position=%f\n" % (n, current_position)) random_step = random.gauss(0,sigma) current_position += random_step data_file.close() </code></pre>
6
2009-10-15T21:04:33Z
1,575,133
<p>You might want to look into the following package:</p> <p><a href="http://pypi.python.org/pypi/affinity" rel="nofollow">http://pypi.python.org/pypi/affinity</a></p> <p>It is a package that uses sched_setaffinity and sched _getaffinity.</p> <p>The drawback is that it is highly Linux-specific.</p>
3
2009-10-15T21:16:49Z
[ "python", "multiprocessing" ]
Python multiprocessing: restrict number of cores used
1,575,067
<p>I want to know how to distribute N independent tasks to exactly M processors on a machine that has L cores, where L>M. I don't want to use all the processors because I still want to have I/O available. The solutions I've tried seem to get distributed to all processors, bogging down the system.</p> <p>I assume the multiprocessing module is the way to go.</p> <p>I do numerical simulations. My background is in physics, not computer science, so unfortunately, I often don't fully understand discussions involving standard tasking models like server/client, producer/consumer, etc.</p> <p>Here are some simplified models that I've tried:</p> <p>Suppose I have a function <code>run_sim(**kwargs)</code> (see that further below) that runs a simulation, and a long list of kwargs for the simulations, and I have an 8 core machine.</p> <pre><code>from multiprocessing import Pool, Process #using pool p = Pool(4) p.map(run_sim, kwargs) # using process number_of_live_jobs=0 all_jobs=[] sim_index=0 while sim_index &lt; len(kwargs)+1: number_of_live_jobs = len([1 for job in all_jobs if job.is_alive()]) if number_of_live_jobs &lt;= 4: p = Process(target=run_sim, args=[], kwargs=kwargs[sim_index]) print "starting job", kwargs[sim_index]["data_file_name"] print "number of live jobs: ", number_of_live_jobs p.start() p.join() all_jobs.append(p) sim_index += 1 </code></pre> <p>When I look at the processor usage with "top" and then "1", All processors seem to get used anyway in either case. It is not out of the question that I am misinterpreting the output of "top", but if the <code>run_simulation()</code> is processor intensive, the machine bogs down heavily.</p> <p>Hypothetical simulation and data:</p> <pre><code># simulation kwargs numbers_of_steps = range(0,10000000, 1000000) sigmas = [x for x in range(11)] kwargs = [] for number_of_steps in numbers_of_steps: for sigma in sigmas: kwargs.append( dict( number_of_steps=number_of_steps, sigma=sigma, # why do I need to cast to int? data_file_name="walk_steps=%i_sigma=%i" % (number_of_steps, sigma), ) ) import random, time random.seed(time.time()) # simulation of random walk def run_sim(kwargs): number_of_steps = kwargs["number_of_steps"] sigma = kwargs["sigma"] data_file_name = kwargs["data_file_name"] data_file = open(data_file_name+".dat", "w") current_position = 0 print "running simulation", data_file_name for n in range(int(number_of_steps)+1): data_file.write("step number %i position=%f\n" % (n, current_position)) random_step = random.gauss(0,sigma) current_position += random_step data_file.close() </code></pre>
6
2009-10-15T21:04:33Z
1,575,304
<p>If you are on linux, use taskset when you launch the program</p> <p>A child created via fork(2) inherits its parent’s CPU affinity mask. The affinity mask is preserved across an execve(2).</p> <blockquote> <p>TASKSET(1)<br /> Linux User’s Manual<br /> TASKSET(1)</p> <p>NAME taskset - retrieve or set a process’s CPU affinity</p> <p>SYNOPSIS taskset [options] mask command [arg]... taskset [options] -p [mask] pid</p> <p>DESCRIPTION taskset is used to set or retrieve the CPU affinity of a running process given its PID or to launch a new COMMAND with a given CPU affinity. CPU affinity is a scheduler property that "bonds" a process to a given set of CPUs on the system. The Linux scheduler will honor the given CPU affinity and the process will not run on any other CPUs. Note that the Linux scheduler also supports natural CPU affinity: the scheduler attempts to keep processes on the same CPU as long as practical for performance reasons. Therefore, forcing a specific CPU affinity is useful only in certain applications.</p> <p>The CPU affinity is represented as a bitmask, with the lowest order bit corresponding to the first logical CPU and the highest order bit corresponding to the last logical CPU. Not all CPUs may exist on a given sys‐ tem but a mask may specify more CPUs than are present. A retrieved mask will reflect only the bits that cor‐ respond to CPUs physically on the system. If an invalid mask is given (i.e., one that corresponds to no valid CPUs on the current system) an error is returned. The masks are typically given in hexadecimal.</p> </blockquote>
2
2009-10-15T21:50:24Z
[ "python", "multiprocessing" ]
Python multiprocessing: restrict number of cores used
1,575,067
<p>I want to know how to distribute N independent tasks to exactly M processors on a machine that has L cores, where L>M. I don't want to use all the processors because I still want to have I/O available. The solutions I've tried seem to get distributed to all processors, bogging down the system.</p> <p>I assume the multiprocessing module is the way to go.</p> <p>I do numerical simulations. My background is in physics, not computer science, so unfortunately, I often don't fully understand discussions involving standard tasking models like server/client, producer/consumer, etc.</p> <p>Here are some simplified models that I've tried:</p> <p>Suppose I have a function <code>run_sim(**kwargs)</code> (see that further below) that runs a simulation, and a long list of kwargs for the simulations, and I have an 8 core machine.</p> <pre><code>from multiprocessing import Pool, Process #using pool p = Pool(4) p.map(run_sim, kwargs) # using process number_of_live_jobs=0 all_jobs=[] sim_index=0 while sim_index &lt; len(kwargs)+1: number_of_live_jobs = len([1 for job in all_jobs if job.is_alive()]) if number_of_live_jobs &lt;= 4: p = Process(target=run_sim, args=[], kwargs=kwargs[sim_index]) print "starting job", kwargs[sim_index]["data_file_name"] print "number of live jobs: ", number_of_live_jobs p.start() p.join() all_jobs.append(p) sim_index += 1 </code></pre> <p>When I look at the processor usage with "top" and then "1", All processors seem to get used anyway in either case. It is not out of the question that I am misinterpreting the output of "top", but if the <code>run_simulation()</code> is processor intensive, the machine bogs down heavily.</p> <p>Hypothetical simulation and data:</p> <pre><code># simulation kwargs numbers_of_steps = range(0,10000000, 1000000) sigmas = [x for x in range(11)] kwargs = [] for number_of_steps in numbers_of_steps: for sigma in sigmas: kwargs.append( dict( number_of_steps=number_of_steps, sigma=sigma, # why do I need to cast to int? data_file_name="walk_steps=%i_sigma=%i" % (number_of_steps, sigma), ) ) import random, time random.seed(time.time()) # simulation of random walk def run_sim(kwargs): number_of_steps = kwargs["number_of_steps"] sigma = kwargs["sigma"] data_file_name = kwargs["data_file_name"] data_file = open(data_file_name+".dat", "w") current_position = 0 print "running simulation", data_file_name for n in range(int(number_of_steps)+1): data_file.write("step number %i position=%f\n" % (n, current_position)) random_step = random.gauss(0,sigma) current_position += random_step data_file.close() </code></pre>
6
2009-10-15T21:04:33Z
1,575,395
<p>On my dual-core machine the total number of processes is honoured, i.e. if I do</p> <pre><code>p = Pool(1) </code></pre> <p>Then I only see one CPU in use at any given time. The process is free to migrate to a different <em>processor</em>, but then the other processor is idle. I don't see how all your processors can be in use at the same time, so I don't follow how this can be related to your I/O issues. Of course, if your simulation is I/O bound, then you will see sluggish I/O regardless of core usage...</p>
2
2009-10-15T22:06:38Z
[ "python", "multiprocessing" ]
Python multiprocessing: restrict number of cores used
1,575,067
<p>I want to know how to distribute N independent tasks to exactly M processors on a machine that has L cores, where L>M. I don't want to use all the processors because I still want to have I/O available. The solutions I've tried seem to get distributed to all processors, bogging down the system.</p> <p>I assume the multiprocessing module is the way to go.</p> <p>I do numerical simulations. My background is in physics, not computer science, so unfortunately, I often don't fully understand discussions involving standard tasking models like server/client, producer/consumer, etc.</p> <p>Here are some simplified models that I've tried:</p> <p>Suppose I have a function <code>run_sim(**kwargs)</code> (see that further below) that runs a simulation, and a long list of kwargs for the simulations, and I have an 8 core machine.</p> <pre><code>from multiprocessing import Pool, Process #using pool p = Pool(4) p.map(run_sim, kwargs) # using process number_of_live_jobs=0 all_jobs=[] sim_index=0 while sim_index &lt; len(kwargs)+1: number_of_live_jobs = len([1 for job in all_jobs if job.is_alive()]) if number_of_live_jobs &lt;= 4: p = Process(target=run_sim, args=[], kwargs=kwargs[sim_index]) print "starting job", kwargs[sim_index]["data_file_name"] print "number of live jobs: ", number_of_live_jobs p.start() p.join() all_jobs.append(p) sim_index += 1 </code></pre> <p>When I look at the processor usage with "top" and then "1", All processors seem to get used anyway in either case. It is not out of the question that I am misinterpreting the output of "top", but if the <code>run_simulation()</code> is processor intensive, the machine bogs down heavily.</p> <p>Hypothetical simulation and data:</p> <pre><code># simulation kwargs numbers_of_steps = range(0,10000000, 1000000) sigmas = [x for x in range(11)] kwargs = [] for number_of_steps in numbers_of_steps: for sigma in sigmas: kwargs.append( dict( number_of_steps=number_of_steps, sigma=sigma, # why do I need to cast to int? data_file_name="walk_steps=%i_sigma=%i" % (number_of_steps, sigma), ) ) import random, time random.seed(time.time()) # simulation of random walk def run_sim(kwargs): number_of_steps = kwargs["number_of_steps"] sigma = kwargs["sigma"] data_file_name = kwargs["data_file_name"] data_file = open(data_file_name+".dat", "w") current_position = 0 print "running simulation", data_file_name for n in range(int(number_of_steps)+1): data_file.write("step number %i position=%f\n" % (n, current_position)) random_step = random.gauss(0,sigma) current_position += random_step data_file.close() </code></pre>
6
2009-10-15T21:04:33Z
1,575,735
<p>Probably a dumb observation, pls forgive my inexperience in Python.</p> <p>But your while loop polling for the finished tasks is not going to sleep and is consuming one core all time, isn't it?</p> <p>The other thing to notice is that if your tasks are I/O bound, you M should be adjusted to the number of parallel disks(?) you have ... if they are NFS mounted in different machine you could potentially have M>L.</p> <p>g'luck!</p>
1
2009-10-15T23:50:03Z
[ "python", "multiprocessing" ]
Python multiprocessing: restrict number of cores used
1,575,067
<p>I want to know how to distribute N independent tasks to exactly M processors on a machine that has L cores, where L>M. I don't want to use all the processors because I still want to have I/O available. The solutions I've tried seem to get distributed to all processors, bogging down the system.</p> <p>I assume the multiprocessing module is the way to go.</p> <p>I do numerical simulations. My background is in physics, not computer science, so unfortunately, I often don't fully understand discussions involving standard tasking models like server/client, producer/consumer, etc.</p> <p>Here are some simplified models that I've tried:</p> <p>Suppose I have a function <code>run_sim(**kwargs)</code> (see that further below) that runs a simulation, and a long list of kwargs for the simulations, and I have an 8 core machine.</p> <pre><code>from multiprocessing import Pool, Process #using pool p = Pool(4) p.map(run_sim, kwargs) # using process number_of_live_jobs=0 all_jobs=[] sim_index=0 while sim_index &lt; len(kwargs)+1: number_of_live_jobs = len([1 for job in all_jobs if job.is_alive()]) if number_of_live_jobs &lt;= 4: p = Process(target=run_sim, args=[], kwargs=kwargs[sim_index]) print "starting job", kwargs[sim_index]["data_file_name"] print "number of live jobs: ", number_of_live_jobs p.start() p.join() all_jobs.append(p) sim_index += 1 </code></pre> <p>When I look at the processor usage with "top" and then "1", All processors seem to get used anyway in either case. It is not out of the question that I am misinterpreting the output of "top", but if the <code>run_simulation()</code> is processor intensive, the machine bogs down heavily.</p> <p>Hypothetical simulation and data:</p> <pre><code># simulation kwargs numbers_of_steps = range(0,10000000, 1000000) sigmas = [x for x in range(11)] kwargs = [] for number_of_steps in numbers_of_steps: for sigma in sigmas: kwargs.append( dict( number_of_steps=number_of_steps, sigma=sigma, # why do I need to cast to int? data_file_name="walk_steps=%i_sigma=%i" % (number_of_steps, sigma), ) ) import random, time random.seed(time.time()) # simulation of random walk def run_sim(kwargs): number_of_steps = kwargs["number_of_steps"] sigma = kwargs["sigma"] data_file_name = kwargs["data_file_name"] data_file = open(data_file_name+".dat", "w") current_position = 0 print "running simulation", data_file_name for n in range(int(number_of_steps)+1): data_file.write("step number %i position=%f\n" % (n, current_position)) random_step = random.gauss(0,sigma) current_position += random_step data_file.close() </code></pre>
6
2009-10-15T21:04:33Z
5,444,316
<p>you might try using pypar module. I am not sure how to use affinity to set cpu affinity of to a certain core using affinity</p>
1
2011-03-26T18:25:00Z
[ "python", "multiprocessing" ]
How to read .ARC files from the Heritrix crawler using Python?
1,575,442
<p>I looked at the Heritrix documentation website, and they listed a Python .ARC file reader. However, it is 404 not found when I clicked on it. <a href="http://crawler.archive.org/articles/developer%5Fmanual/arcs.html" rel="nofollow">http://crawler.archive.org/articles/developer%5Fmanual/arcs.html</a></p> <p>Does anyone else know any Heritrix ARC reader that uses Python?</p> <p>(I asked this question before, but closed it due to inaccuracy)</p>
1
2009-10-15T22:17:46Z
1,575,561
<p>Nothing a little Googling can't find: <a href="http://archive-access.cvs.sourceforge.net/viewvc/archive-access/archive-access/projects/hedaern/" rel="nofollow">http://archive-access.cvs.sourceforge.net/viewvc/archive-access/archive-access/projects/hedaern/</a></p>
0
2009-10-15T22:51:50Z
[ "python", "web-crawler" ]
Preempting __del__ hmmm
1,575,567
<p>I need to preempt <code>__del__</code> and I want to know what is the right way to do this. Basically my question in code is this..</p> <pre><code>class A: def __init__(self): self.log = logging.getLogger() self.log.debug("In init") self.closed = False def close(self): self.log.debug("Doing some magic") self.closed = True def __del__(self): if not self.closed: self.close() self.log.debug("In closing") # What should go here to properly do GC?? </code></pre> <p>Is there any way to now call the standard GC features?</p> <p>Thanks for reading!!</p> <p>Steve</p>
0
2009-10-15T22:52:42Z
1,575,581
<p><code>__del__</code> isn't a true destructor. It is called before an object is destroyed to free any resources it is holding. It need not worry about freeing memory itself.</p> <p>You can always call the parent class' <code>__del__</code>, too, if you are inheriting a class which may also have open resources.</p>
4
2009-10-15T22:56:30Z
[ "python", "class" ]
Preempting __del__ hmmm
1,575,567
<p>I need to preempt <code>__del__</code> and I want to know what is the right way to do this. Basically my question in code is this..</p> <pre><code>class A: def __init__(self): self.log = logging.getLogger() self.log.debug("In init") self.closed = False def close(self): self.log.debug("Doing some magic") self.closed = True def __del__(self): if not self.closed: self.close() self.log.debug("In closing") # What should go here to properly do GC?? </code></pre> <p>Is there any way to now call the standard GC features?</p> <p>Thanks for reading!!</p> <p>Steve</p>
0
2009-10-15T22:52:42Z
1,575,590
<p>If you're looking to call the GC manually then call gc.collect().</p>
1
2009-10-15T22:59:37Z
[ "python", "class" ]
Preempting __del__ hmmm
1,575,567
<p>I need to preempt <code>__del__</code> and I want to know what is the right way to do this. Basically my question in code is this..</p> <pre><code>class A: def __init__(self): self.log = logging.getLogger() self.log.debug("In init") self.closed = False def close(self): self.log.debug("Doing some magic") self.closed = True def __del__(self): if not self.closed: self.close() self.log.debug("In closing") # What should go here to properly do GC?? </code></pre> <p>Is there any way to now call the standard GC features?</p> <p>Thanks for reading!!</p> <p>Steve</p>
0
2009-10-15T22:52:42Z
1,575,623
<p>Please use the <code>with</code> statement for this.</p> <p>See <a href="http://docs.python.org/reference/compound%5Fstmts.html#the-with-statement" rel="nofollow">http://docs.python.org/reference/compound%5Fstmts.html#the-with-statement</a></p> <blockquote> <p>The with statement guarantees that if the <strong>enter</strong>() method returns without an error, then <strong>exit</strong>() will always be called.</p> </blockquote> <p>Rather than fool around with <code>__del__</code>, use <code>__exit__</code> of a context manager object.</p>
3
2009-10-15T23:10:11Z
[ "python", "class" ]
Ensure that only one instance of a class gets run
1,575,680
<p>I have an underlying class which I want to place in some code. I only want it to be instantiated or started once for a given app although it might be called many times.. The problem with the code below is that LowClass is started over and over again. I only want it to start once per test..</p> <pre><code>import logging class LowClass: active = False def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) if self.active: return else: self.active = True self.log.debug("Now active!") class A: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = LowClass() class B: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = LowClass() class C: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.a = A() self.b = B() class ATests(unittest.TestCase): def setUp(self): pass def testOne(self): a = A() b = B() def testTwo(self): c = C() </code></pre> <p>Thanks for pointing out my problem!! </p>
2
2009-10-15T23:33:01Z
1,575,702
<p>Look up "singleton pattern". It looks like Python you are dealing with, so you might have to search a bit harder. I now there are plenty of examples in C++.</p>
1
2009-10-15T23:41:41Z
[ "python", "singleton" ]
Ensure that only one instance of a class gets run
1,575,680
<p>I have an underlying class which I want to place in some code. I only want it to be instantiated or started once for a given app although it might be called many times.. The problem with the code below is that LowClass is started over and over again. I only want it to start once per test..</p> <pre><code>import logging class LowClass: active = False def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) if self.active: return else: self.active = True self.log.debug("Now active!") class A: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = LowClass() class B: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = LowClass() class C: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.a = A() self.b = B() class ATests(unittest.TestCase): def setUp(self): pass def testOne(self): a = A() b = B() def testTwo(self): c = C() </code></pre> <p>Thanks for pointing out my problem!! </p>
2
2009-10-15T23:33:01Z
1,575,704
<p>What you need is to implement the <a href="http://en.wikipedia.org/wiki/Singleton%5Fpattern" rel="nofollow">Singleton</a> Design pattern in python</p> <p>I've found this <a href="http://code.activestate.com/recipes/52558/" rel="nofollow">implementation</a> I hope it helps</p>
1
2009-10-15T23:42:33Z
[ "python", "singleton" ]
Ensure that only one instance of a class gets run
1,575,680
<p>I have an underlying class which I want to place in some code. I only want it to be instantiated or started once for a given app although it might be called many times.. The problem with the code below is that LowClass is started over and over again. I only want it to start once per test..</p> <pre><code>import logging class LowClass: active = False def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) if self.active: return else: self.active = True self.log.debug("Now active!") class A: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = LowClass() class B: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = LowClass() class C: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.a = A() self.b = B() class ATests(unittest.TestCase): def setUp(self): pass def testOne(self): a = A() b = B() def testTwo(self): c = C() </code></pre> <p>Thanks for pointing out my problem!! </p>
2
2009-10-15T23:33:01Z
1,575,713
<p>See <a href="http://code.activestate.com/recipes/52558/">singleton in python</a>.</p>
5
2009-10-15T23:44:13Z
[ "python", "singleton" ]
Ensure that only one instance of a class gets run
1,575,680
<p>I have an underlying class which I want to place in some code. I only want it to be instantiated or started once for a given app although it might be called many times.. The problem with the code below is that LowClass is started over and over again. I only want it to start once per test..</p> <pre><code>import logging class LowClass: active = False def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) if self.active: return else: self.active = True self.log.debug("Now active!") class A: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = LowClass() class B: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = LowClass() class C: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.a = A() self.b = B() class ATests(unittest.TestCase): def setUp(self): pass def testOne(self): a = A() b = B() def testTwo(self): c = C() </code></pre> <p>Thanks for pointing out my problem!! </p>
2
2009-10-15T23:33:01Z
1,576,188
<p>I believe that the problem with the code shown is that you set <code>self.active=True</code>. This will create an attribute for the instance and set that to <code>True</code>, whereas I believe that you want to set the active of the class itself to <code>True</code>. So, instead of <code>self.active=True</code>, try <code>self.__class__.active=True</code>.</p>
0
2009-10-16T05:11:48Z
[ "python", "singleton" ]
Ensure that only one instance of a class gets run
1,575,680
<p>I have an underlying class which I want to place in some code. I only want it to be instantiated or started once for a given app although it might be called many times.. The problem with the code below is that LowClass is started over and over again. I only want it to start once per test..</p> <pre><code>import logging class LowClass: active = False def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) if self.active: return else: self.active = True self.log.debug("Now active!") class A: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = LowClass() class B: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = LowClass() class C: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.a = A() self.b = B() class ATests(unittest.TestCase): def setUp(self): pass def testOne(self): a = A() b = B() def testTwo(self): c = C() </code></pre> <p>Thanks for pointing out my problem!! </p>
2
2009-10-15T23:33:01Z
15,541,090
<p>When you import a module in python, it is natural singleton. For example, in util.py, you have:</p> <pre><code> class MyClass(object): ...... g_my_obj = MyClass() </code></pre> <p>in a.py, you import g_my_obj:</p> <pre><code>from util import g_my_obj </code></pre> <p>in b.py, you import g_my_obj again:</p> <pre><code>from util import g_my_obj </code></pre> <p>Safely, there is only one g_my_obj created no matter how many times you import it.</p>
1
2013-03-21T06:44:47Z
[ "python", "singleton" ]
Python datetime subtraction - wrong results?
1,575,779
<p>I must be doing something wrong here, any ideas?</p> <pre><code>&gt;&gt;&gt; (datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)).seconds 2098 </code></pre> <p>It should be getting more than that many seconds.</p>
1
2009-10-16T00:04:46Z
1,575,787
<p><code>timedelta.seconds</code> isn't the total number of seconds, it's the remainder in seconds after days have been accounted for. Using your example:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; (datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)) datetime.timedelta(1, 2098) </code></pre> <p>That <code>datetime.timedelta(1, 2098)</code> means that your timedelta is <em>1 day</em>, <strong>plus</strong> <em>2098 seconds</em>.</p> <p>What you want is something like:</p> <pre><code>&gt;&gt;&gt; delta = (datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)) &gt;&gt;&gt; (delta.days * 86400) + delta.seconds 88498 </code></pre>
1
2009-10-16T00:09:05Z
[ "python", "datetime" ]
Python datetime subtraction - wrong results?
1,575,779
<p>I must be doing something wrong here, any ideas?</p> <pre><code>&gt;&gt;&gt; (datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)).seconds 2098 </code></pre> <p>It should be getting more than that many seconds.</p>
1
2009-10-16T00:04:46Z
1,575,790
<p><code>timedelta.seconds</code> gives you the <code>seconds</code> field of the timedelta. But it also has a <code>days</code> field (and a <code>milliseconds</code> field).</p> <p>So you would want something like </p> <pre><code>delta = datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16) delta.seconds + delta.days*86400 </code></pre>
9
2009-10-16T00:10:05Z
[ "python", "datetime" ]
Python datetime subtraction - wrong results?
1,575,779
<p>I must be doing something wrong here, any ideas?</p> <pre><code>&gt;&gt;&gt; (datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)).seconds 2098 </code></pre> <p>It should be getting more than that many seconds.</p>
1
2009-10-16T00:04:46Z
1,575,792
<p>It's actually returning a timedelta which has a day field also i.e.</p> <p><code>c.seconds = 2098</code></p> <p>but </p> <p><code>c.days = 1</code></p>
2
2009-10-16T00:10:16Z
[ "python", "datetime" ]
Python datetime subtraction - wrong results?
1,575,779
<p>I must be doing something wrong here, any ideas?</p> <pre><code>&gt;&gt;&gt; (datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)).seconds 2098 </code></pre> <p>It should be getting more than that many seconds.</p>
1
2009-10-16T00:04:46Z
1,575,796
<p><code>datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)</code> returns a <code>datetime.timedelta</code> object which has a <code>days</code> attribute. The difference that you are calculating is actually 1 day and 2098 seconds. </p>
1
2009-10-16T00:11:05Z
[ "python", "datetime" ]
Python callback with SWIG wrapped type
1,575,802
<p>I'm trying to add a python callback to a C++ library as illustrated:</p> <pre><code>template&lt;typename T&gt; void doCallback(shared_ptr&lt;T&gt; data) { PyObject* pyfunc; //I have this already PyObject* args = Py_BuildValue("(O)", data); PyEval_CallObject(pyfunc,args); } </code></pre> <p>This fails because data hasn't gone through swig, and isn't a PyObject.</p> <p>I tried using:</p> <pre><code>swigData = SWIG_NewPointerObj((void*)data, NULL, 0); </code></pre> <p>But because its a template, I don't really know what to use for the second parameter. Even if I do hard code the 'correct' SWIGTYPE, it usually segfaults on PyEval_CallObject.</p> <p>So my questions are:</p> <ol> <li><p>Whats the best way to invoke swig type wrapping?</p></li> <li><p>Am I even going in the right direction here? Directors looked promising for implementing a callback, but I couldn't find an example of directors with python.</p></li> </ol> <p><strong>Update:</strong> The proper wrapping is getting generated. I have other functions that return shared_ptrs and can call those correctly.</p>
2
2009-10-16T00:13:39Z
1,580,899
<p><code>shared_ptr&lt;T&gt;</code> for unknown <code>T</code> isn't a type, so SWIG can't hope to wrap it. What you need to do is provide a SWIG wrapping for each instance of <code>shared_ptr</code> that you intend to use. So if for example you want to be able to <code>doCallback()</code> with both <code>shared_ptr&lt;Foo&gt;</code> and <code>shared_ptr&lt;Bar&gt;</code>, you will need:</p> <ul> <li>A wrapper for <code>Foo</code></li> <li>A wrapper for <code>Bar</code></li> <li>Wrappers for <code>shared_ptr&lt;Foo&gt;</code> and <code>shared_ptr&lt;Bar&gt;</code>.</li> </ul> <p>You make those like so:</p> <pre><code>namespace boost { template&lt;class T&gt; class shared_ptr { public: T * operator-&gt; () const; }; } %template(FooSharedPtr) boost::shared_ptr&lt;Foo&gt;; %template(BarSharedPtr) boost::shared_ptr&lt;Bar&gt;; </code></pre>
0
2009-10-16T23:31:33Z
[ "c++", "python", "swig" ]
Python callback with SWIG wrapped type
1,575,802
<p>I'm trying to add a python callback to a C++ library as illustrated:</p> <pre><code>template&lt;typename T&gt; void doCallback(shared_ptr&lt;T&gt; data) { PyObject* pyfunc; //I have this already PyObject* args = Py_BuildValue("(O)", data); PyEval_CallObject(pyfunc,args); } </code></pre> <p>This fails because data hasn't gone through swig, and isn't a PyObject.</p> <p>I tried using:</p> <pre><code>swigData = SWIG_NewPointerObj((void*)data, NULL, 0); </code></pre> <p>But because its a template, I don't really know what to use for the second parameter. Even if I do hard code the 'correct' SWIGTYPE, it usually segfaults on PyEval_CallObject.</p> <p>So my questions are:</p> <ol> <li><p>Whats the best way to invoke swig type wrapping?</p></li> <li><p>Am I even going in the right direction here? Directors looked promising for implementing a callback, but I couldn't find an example of directors with python.</p></li> </ol> <p><strong>Update:</strong> The proper wrapping is getting generated. I have other functions that return shared_ptrs and can call those correctly.</p>
2
2009-10-16T00:13:39Z
1,597,811
<p>My first answer misunderstood the question completely, so let's try this again.</p> <p>Your central problem is the free type parameter <code>T</code> in the definition of <code>doCallback</code>. As you point out in your question, there's no way to make a SWIG object out of a <code>shared_ptr&lt;T&gt;</code> without a concrete value for <code>T</code>: <code>shared_ptr&lt;T&gt;</code> isn't really a type.</p> <p>Thus I think that you have to specialize: for each concrete instantiation of <code>doCallback</code> that the host system uses, provide a template specialization for the target type. With that done, you can generate a Python-friendly wrapping of <code>data</code>, and pass it to your python function. The simplest technique for that is probably:</p> <pre><code>swigData = SWIG_NewPointerObj((void*)(data.get()), SWIGType_Whatever, 0); </code></pre> <p>...though this can only work if your Python function doesn't save its argument anywhere, as the <code>shared_ptr</code> itself is not copied.</p> <p>If you do need to retain a reference to <code>data</code>, you'll need to use whatever mechanism SWIG usually uses to wrap <code>shared_ptr</code>. If there's no special-case smart-pointer magic going on, it's probably something like:</p> <pre><code>pythonData = new shared_ptr&lt;Whatever&gt;(data); swigData = SWIG_NewPointerObj(pythonData, SWIGType_shared_ptr_to_Whatever, 1); </code></pre> <p>Regardless, you then you have a Python-friendly SWIG object that's amenable to <code>Py_BuildValue()</code>.</p> <p>Hope this helps.</p>
0
2009-10-20T23:11:22Z
[ "c++", "python", "swig" ]
How can I check that a column in a tab-delimited file has valid values?
1,575,936
<p>I have a large file named CHECKME which is tab delimited. There are 8 columns in each row. Column 4 is integers.</p> <p>By using Perl or Python, is it possible to verify that each row in CHECKME has 8 columns and that column 4 is an integer?</p>
1
2009-10-16T00:56:11Z
1,575,953
<p>In Python:</p> <pre><code>def isfileok(filename): f = open(filename) for line in f: pieces = line.split('\t') if len(pieces) != 8: return False if not pieces[3].isdigit(): return False return True </code></pre> <p>I assume that by "column no. 4" you mean the 4th one, hence the <code>[3]</code> since Python (like most computer languages) indices from 0.</p> <p>Here I'm just returning a boolean result, but I split up the code so it's easy to give good diagnostics about what line is wrong, and how, if you so desire.</p>
4
2009-10-16T01:00:07Z
[ "python", "perl" ]
How can I check that a column in a tab-delimited file has valid values?
1,575,936
<p>I have a large file named CHECKME which is tab delimited. There are 8 columns in each row. Column 4 is integers.</p> <p>By using Perl or Python, is it possible to verify that each row in CHECKME has 8 columns and that column 4 is an integer?</p>
1
2009-10-16T00:56:11Z
1,576,031
<p>In Perl:</p> <pre><code>while (&lt;&gt;) { if (! /^[^\t]+\t[^\t]+\t[^\t]+\t\d+\t[^\t]+\t[^\t]+\t[^\t]+\t[^\t]+$/) { die "Line $. is bad: $_"; } } </code></pre> <p>Checks to see that the line starts with one or more non-tabs, followed by a tab, followed by one or more non-tabs, followed by a tab, followed by one or more non-tabs, followed by a tab, followed by one or more digits, etc. until the eighth set of non-tab(s), which must be at the end of the line.</p> <p>Thats the quick and dirty solution, but in the long run, it'd probably be better to use a "split /\t/" and count the number of fields it gets and then check to make sure field 3 (zero origin) is just digits. That way when (not if) the requirements change and you now need 9 fields, with the 9th field being a prime number, it's easy to make the change.</p>
2
2009-10-16T01:32:48Z
[ "python", "perl" ]
How can I check that a column in a tab-delimited file has valid values?
1,575,936
<p>I have a large file named CHECKME which is tab delimited. There are 8 columns in each row. Column 4 is integers.</p> <p>By using Perl or Python, is it possible to verify that each row in CHECKME has 8 columns and that column 4 is an integer?</p>
1
2009-10-16T00:56:11Z
1,576,033
<p>The following Python code should display the line as you have indicated:</p> <pre><code>for n,line in enumerate(open("filename")): line=line.split() if len(line)!=8: print "line %d error" % n+1 if not line[3].isdigit(): print "line %d error" % n+1 </code></pre>
0
2009-10-16T01:34:22Z
[ "python", "perl" ]
How can I check that a column in a tab-delimited file has valid values?
1,575,936
<p>I have a large file named CHECKME which is tab delimited. There are 8 columns in each row. Column 4 is integers.</p> <p>By using Perl or Python, is it possible to verify that each row in CHECKME has 8 columns and that column 4 is an integer?</p>
1
2009-10-16T00:56:11Z
1,576,121
<p>In Perl</p> <pre><code>while(&lt;&gt;) { my @F=split/\t/; die "Invalid line: $_" if @F!=8 or $F[3]!~/^-?\d+$/; } </code></pre>
8
2009-10-16T04:46:05Z
[ "python", "perl" ]
How can I check that a column in a tab-delimited file has valid values?
1,575,936
<p>I have a large file named CHECKME which is tab delimited. There are 8 columns in each row. Column 4 is integers.</p> <p>By using Perl or Python, is it possible to verify that each row in CHECKME has 8 columns and that column 4 is an integer?</p>
1
2009-10-16T00:56:11Z
1,579,866
<p>It's very easy work for Perl:</p> <pre><code>perl -F\\t -ane'die"Invalid!"if@F!=8||$F[3]!~/^-?\d+$/' CHECKME </code></pre>
4
2009-10-16T19:13:23Z
[ "python", "perl" ]
How can I check that a column in a tab-delimited file has valid values?
1,575,936
<p>I have a large file named CHECKME which is tab delimited. There are 8 columns in each row. Column 4 is integers.</p> <p>By using Perl or Python, is it possible to verify that each row in CHECKME has 8 columns and that column 4 is an integer?</p>
1
2009-10-16T00:56:11Z
1,580,440
<h3>validate-input.py</h3> <p>Read files given on the command-line or stdin. Print invalid lines. Return code is zero if there are no errors or one otherwise.</p> <pre><code>import fileinput, sys def error(msg, line): print &gt;&gt; sys.stderr, "%s:%d:%s\terror: %s" % ( fileinput.filename(), fileinput.filelineno(), line, msg) error.count += 1 error.count = 0 ncol, icol = 8, 3 for row in (line.split('\t') for line in fileinput.input()): if len(row) == ncol: try: int(row[icol]) except ValueError: error("%dth field '%s' is not integer" % ( (icol + 1), row[icol]), '\t'.join(row)) else: error('wrong number of columns (want: %d, got: %d)' % ( ncol, len(row)), '\t'.join(row)) sys.exit(error.count != 0) </code></pre> <h3>Example</h3> <pre> $ echo 1 2 3 | python validate-input.py *.txt - not_integer.txt:2:a b c 1.1 e f g h error: 4th field '1.1' is not integer wrong_cols.txt:3:a b error: wrong number of columns (want: 8, got: 3) &lt;stdin>:1:1 2 3 error: wrong number of columns (want: 8, got: 1) </pre>
1
2009-10-16T21:08:58Z
[ "python", "perl" ]
Python - Twisted and Unit Tests
1,575,966
<p>I'm writing unit tests for a portion of an application that runs as an HTTP server. The approach I have been trying to take is to import the module that contains the HTTP server, start it. Then, the unit tests will use urllib2 to connect, send data, and check the response.</p> <p>Our HTTP server is using Twisted. One problem here is that I'm just not that familiar with Twisted :)</p> <p>Now, I instantiate our HTTP server and start it in the setUp() method and then I stop it in the tearDown() method.</p> <p>Problem is, Twisted doesn't appear to like this, and it will only run one unit test. After the first one, the reactor won't start anymore.</p> <p>I've searched and searched and searched, and I just can't seem to find an answer that makes sense.</p> <p>Am I taking the wrong approach entirely, or just missing something obvious?</p>
16
2009-10-16T01:03:08Z
1,575,983
<p>I believe that for unit testing within Twisted you're supposed to use <a href="http://twistedmatrix.com/trac/wiki/TwistedTrial">TwistedTrial</a> (it's a core component, i.e., comes with the Twisted tarball in the twisted/trial directory). However, as the URL I've pointed to says, the doc is mostly by having a look through the source (including sources of various Twisted projects, as they're tested with Trial too).</p>
7
2009-10-16T01:09:02Z
[ "python", "unit-testing", "twisted" ]
Python - Twisted and Unit Tests
1,575,966
<p>I'm writing unit tests for a portion of an application that runs as an HTTP server. The approach I have been trying to take is to import the module that contains the HTTP server, start it. Then, the unit tests will use urllib2 to connect, send data, and check the response.</p> <p>Our HTTP server is using Twisted. One problem here is that I'm just not that familiar with Twisted :)</p> <p>Now, I instantiate our HTTP server and start it in the setUp() method and then I stop it in the tearDown() method.</p> <p>Problem is, Twisted doesn't appear to like this, and it will only run one unit test. After the first one, the reactor won't start anymore.</p> <p>I've searched and searched and searched, and I just can't seem to find an answer that makes sense.</p> <p>Am I taking the wrong approach entirely, or just missing something obvious?</p>
16
2009-10-16T01:03:08Z
1,575,992
<p>Here's some info: <a href="http://twistedmatrix.com/projects/core/documentation/howto/testing.html">Writing tests for Twisted code using Trial</a></p> <p>You should also look at the -help of the trial command. There'a lot of good stuff in trial! But it's not always easy to do testing in a async application. Good luck!</p>
17
2009-10-16T01:12:36Z
[ "python", "unit-testing", "twisted" ]
Python - Twisted and Unit Tests
1,575,966
<p>I'm writing unit tests for a portion of an application that runs as an HTTP server. The approach I have been trying to take is to import the module that contains the HTTP server, start it. Then, the unit tests will use urllib2 to connect, send data, and check the response.</p> <p>Our HTTP server is using Twisted. One problem here is that I'm just not that familiar with Twisted :)</p> <p>Now, I instantiate our HTTP server and start it in the setUp() method and then I stop it in the tearDown() method.</p> <p>Problem is, Twisted doesn't appear to like this, and it will only run one unit test. After the first one, the reactor won't start anymore.</p> <p>I've searched and searched and searched, and I just can't seem to find an answer that makes sense.</p> <p>Am I taking the wrong approach entirely, or just missing something obvious?</p>
16
2009-10-16T01:03:08Z
1,576,026
<p>There is a <a href="http://twistedmatrix.com/trac/ticket/2066" rel="nofollow">known bug</a> with Twisted (that probably won't get fixed) where re-starting the reactor causes a crash.</p> <p>This is why your unit tests don't work. </p> <p>As well as using <a href="http://twistedmatrix.com/projects/core/documentation/howto/testing.html" rel="nofollow">Trial</a> you might want to consider seperate testing systems that talk to your HTTP server like a client will.</p> <ul> <li><a href="http://code.google.com/p/webdriver/" rel="nofollow">Webdriver</a> - an API to drive a browser session around your site.</li> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/1385" rel="nofollow">TestGen4Web</a> - Firefox plugin that records interactions with site and can replay.</li> </ul>
3
2009-10-16T01:30:33Z
[ "python", "unit-testing", "twisted" ]
Python - Twisted and Unit Tests
1,575,966
<p>I'm writing unit tests for a portion of an application that runs as an HTTP server. The approach I have been trying to take is to import the module that contains the HTTP server, start it. Then, the unit tests will use urllib2 to connect, send data, and check the response.</p> <p>Our HTTP server is using Twisted. One problem here is that I'm just not that familiar with Twisted :)</p> <p>Now, I instantiate our HTTP server and start it in the setUp() method and then I stop it in the tearDown() method.</p> <p>Problem is, Twisted doesn't appear to like this, and it will only run one unit test. After the first one, the reactor won't start anymore.</p> <p>I've searched and searched and searched, and I just can't seem to find an answer that makes sense.</p> <p>Am I taking the wrong approach entirely, or just missing something obvious?</p>
16
2009-10-16T01:03:08Z
1,580,776
<p>As others mentioned, you should be using Trial for unit tests in Twisted.</p> <p>You also should be unit testing from the bottom up - that's what the "unit" in unit testing implies. Test your data and logic before you test your interface. For a HTTP interface, you should be calling processGET, processPOST, etc with a mock request, but you should only be doing this after you've tested what these methods are calling. Each test should assume that the units tested elsewhere are working as designed.</p> <p>If you're speaking HTTP, or you need a running server or other state, you're probably making higher level tests such as functional or integration tests. This isn't a bad thing, but you might want to rephrase your question.</p>
4
2009-10-16T22:45:23Z
[ "python", "unit-testing", "twisted" ]
Sorting strings with integers and text in Python
1,575,971
<p>I'm making a stupid little game that saves your score in a highscores.txt file. </p> <p>My problem is sorting the lines. Here's what I have so far. </p> <p>Maybe an alphanumeric sorter for python would help? Thanks.</p> <pre><code>import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highscores.txt") score = 500 name = "Nicholas" #If the file doesn't exist, create one with the high scores format. if file_exists == False: f = open("highscores.txt", "w") f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name') new_score = str(score) + ".........." + name f = open("highscores.txt", "r+") words = f.readlines() print words main() </code></pre>
0
2009-10-16T01:05:07Z
1,575,993
<p>after <code>words = f.readlines()</code>, try something like:</p> <pre><code>headers = words.pop(0) def myway(aline): i = 0 while aline[i].isdigit(): i += 1 score = int(aline[:i]) return score words.sort(key=myway, reverse=True) words.insert(0, headers) </code></pre> <p>The key (;-) idea is to make a function that returns the "sorting key" from each item (here, a line). I'm trying to write it in the simplest possible way: see how many leading digits there are, then turn them all into an int, and return that.</p>
4
2009-10-16T01:12:40Z
[ "python", "string", "alphanumeric" ]
Sorting strings with integers and text in Python
1,575,971
<p>I'm making a stupid little game that saves your score in a highscores.txt file. </p> <p>My problem is sorting the lines. Here's what I have so far. </p> <p>Maybe an alphanumeric sorter for python would help? Thanks.</p> <pre><code>import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highscores.txt") score = 500 name = "Nicholas" #If the file doesn't exist, create one with the high scores format. if file_exists == False: f = open("highscores.txt", "w") f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name') new_score = str(score) + ".........." + name f = open("highscores.txt", "r+") words = f.readlines() print words main() </code></pre>
0
2009-10-16T01:05:07Z
1,576,151
<p>Doing a simple string sort on your </p> <pre><code>new_score = str(score) + ".........." + name </code></pre> <p>items isn't going to work since, for example str(1000) &lt; str(500). In other words, 1000 will come before 500 in an alphanumeric sort.</p> <p>Alex's answer is good in that it demonstrates the use of a sort key function, but here is another solution which is a bit simpler and has the added advantage of visuallaly aligning the high score displays.</p> <p>What you need to do is right align your numbers in a fixed field of the maximum size of the scores, thus (assuming 5 digits max and ver &lt; 3.0):</p> <pre><code>new_score = "%5d........%s" % (score, name) </code></pre> <p>or for Python ver 3.x:</p> <pre><code>new_score = "{0:5d}........{1}".format(score, name) </code></pre> <p>For each new_score append it to the words list (you could use a better name here) and sort it reversed before printing. Or you could use the bisect.insort library function rather than doing a list.append.</p> <p>Also, a more Pythonic form than</p> <pre><code>if file_exists == False: </code></pre> <p>is:</p> <pre><code>if not file_exists: </code></pre>
0
2009-10-16T04:57:44Z
[ "python", "string", "alphanumeric" ]
Sorting strings with integers and text in Python
1,575,971
<p>I'm making a stupid little game that saves your score in a highscores.txt file. </p> <p>My problem is sorting the lines. Here's what I have so far. </p> <p>Maybe an alphanumeric sorter for python would help? Thanks.</p> <pre><code>import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highscores.txt") score = 500 name = "Nicholas" #If the file doesn't exist, create one with the high scores format. if file_exists == False: f = open("highscores.txt", "w") f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name') new_score = str(score) + ".........." + name f = open("highscores.txt", "r+") words = f.readlines() print words main() </code></pre>
0
2009-10-16T01:05:07Z
1,576,203
<p>I guess something went wrong when you pasted from Alex's answer, so here is your code with a sort in there</p> <pre><code> import os.path def main(): #Check if the file exists file_exists = os.path.exists("highscores.txt") score = 500 name = "Nicholas" #If the file doesn't exist, create one with the high scores format. if file_exists == False: f = open("highscores.txt", "w") f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name') new_score = str(score) + ".........." + name +"\n" f = open("highscores.txt", "r+") words = f.readlines() headers = words.pop(0) def anotherway(aline): score="" for c in aline: if c.isdigit(): score+=c else: break return int(score) words.append(new_score) words.sort(key=anotherway, reverse=True) words.insert(0, headers) print "".join(words) main() </code></pre>
0
2009-10-16T05:19:03Z
[ "python", "string", "alphanumeric" ]
Sorting strings with integers and text in Python
1,575,971
<p>I'm making a stupid little game that saves your score in a highscores.txt file. </p> <p>My problem is sorting the lines. Here's what I have so far. </p> <p>Maybe an alphanumeric sorter for python would help? Thanks.</p> <pre><code>import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highscores.txt") score = 500 name = "Nicholas" #If the file doesn't exist, create one with the high scores format. if file_exists == False: f = open("highscores.txt", "w") f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name') new_score = str(score) + ".........." + name f = open("highscores.txt", "r+") words = f.readlines() print words main() </code></pre>
0
2009-10-16T01:05:07Z
1,576,226
<p>I'd like to encourage you to store your high scores in a more robust format. In particular I suggest JSON.</p> <pre><code>import simplejson as json # Python 2.x # import json # Python 3.x d = {} d["version"] = 1 d["highscores"] = [[100, "Steve"], [200, "Ken"], [400, "Denise"]] s = json.dumps(d) print s # prints: # {"version": 1, "highscores": [[100, "Steve"], [200, "Ken"], [400, "Denise"]]} d2 = json.loads(s) for score, name in sorted(d2["highscores"], reverse=True): print "%5d\t%s" % (score, name) # prints: # 400 Denise # 200 Ken # 100 Steve </code></pre> <p>Using JSON will keep you from having to write your own parser to recover data from saved files such as high score tables. You can just tuck everything into a dictionary and trivially get it all back.</p> <p>Note that I tucked in a version number, the version number of your high score save format. If you ever change the save format of your data, having a version number in there will be a very good thing.</p>
1
2009-10-16T05:26:06Z
[ "python", "string", "alphanumeric" ]
Sorting strings with integers and text in Python
1,575,971
<p>I'm making a stupid little game that saves your score in a highscores.txt file. </p> <p>My problem is sorting the lines. Here's what I have so far. </p> <p>Maybe an alphanumeric sorter for python would help? Thanks.</p> <pre><code>import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highscores.txt") score = 500 name = "Nicholas" #If the file doesn't exist, create one with the high scores format. if file_exists == False: f = open("highscores.txt", "w") f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name') new_score = str(score) + ".........." + name f = open("highscores.txt", "r+") words = f.readlines() print words main() </code></pre>
0
2009-10-16T01:05:07Z
1,576,309
<p>What you want is probably what's generally known as a "Natural Sort". Searching for "natural sort python" gives many results, but there's some good discussion on <a href="http://code.activestate.com/recipes/285264/" rel="nofollow">ASPN</a>.</p>
0
2009-10-16T05:49:38Z
[ "python", "string", "alphanumeric" ]
Python on multiprocessor machines: multiprocessing or a non-GIL interpreter
1,575,985
<p>This is more a style question. For CPU bound processes that really benefit for having multiple cores, do you typically use the multiprocessing module or use threads with an interpreter that doesn't have the GIL? I've used the multiprocessing library only lightly, but also have no experience with anything besides CPython. I'm curious what the preferred approach is and if it is to use a different interpreter, which one.</p>
1
2009-10-16T01:10:27Z
1,576,107
<p>Take a look at Parallel Python (<a href="http://www.parallelpython.com" rel="nofollow">www.parallelpython.com</a>) -- I've used to to nicely split up work among the processors on my quad-core box. It even supports clusters!</p>
1
2009-10-16T02:07:05Z
[ "python", "multiprocessing" ]
Python on multiprocessor machines: multiprocessing or a non-GIL interpreter
1,575,985
<p>This is more a style question. For CPU bound processes that really benefit for having multiple cores, do you typically use the multiprocessing module or use threads with an interpreter that doesn't have the GIL? I've used the multiprocessing library only lightly, but also have no experience with anything besides CPython. I'm curious what the preferred approach is and if it is to use a different interpreter, which one.</p>
1
2009-10-16T01:10:27Z
1,576,115
<p>I don't really see a "style" argument to be made here, either way -- both <code>multiprocessing</code> in CPython 2.6, and <code>threading</code> in (e.g.) the current versions of Jython and IronPython, let you code in extremely similar ways (and styles;-). So, I'd choose on the basis of very "hard-nosed" considerations -- what is performance like with each choice (if I'm <em>so</em> CPU-bound as to benefit from multiple cores, then performance is <em>obviously</em> of paramount importance), could I use with serious benefit any library that's CPython-only (like <code>numpy</code>) or maybe something else that's JVM- or .NET- only, and so forth.</p>
3
2009-10-16T02:09:34Z
[ "python", "multiprocessing" ]
Python pdb not breaking in files properly?
1,576,266
<p>I wish I could provide a simple sample case that occurs using standard library code, but unfortunately it only happens when using one of our in-house libraries that in turn is built on top of sql alchemy.</p> <p>Basically, the problem is that this <code>break</code> command:</p> <pre><code>(Pdb) print sqlalchemy.engine.base.__file__ /prod/eggs/SQLAlchemy-0.5.5-py2.5.egg/sqlalchemy/engine/base.py (Pdb) break /prod/eggs/SQLAlchemy-0.5.5-py2.5.egg/sqlalchemy/engine/base.py:946 </code></pre> <p>Is just being totally ignored, it seems, by <code>pdb</code>. As in, even though I am <em>positive</em> the code is being hit (both because I can see log messages, and because I've used <code>sys.settrace</code> to check which lines in which files are being hit), <code>pdb</code> is just not breaking there.</p> <p>I suspect that somehow the use of an egg is confusing <code>pdb</code> as to what files are being used (I can't reproduce the error if I use a non-egg'ed library, like <code>pickle</code>; there everything works fine).</p> <p>It's a shot in the dark, but has anyone come across this before?</p>
0
2009-10-16T05:39:53Z
1,580,988
<p>I wonder if somehow there's an old .pyc that can't be deleted because of permissions being messed up. Nuke all of the .pycs in your python-path, and see if that helps.</p> <p><a href="http://rpatterson.net/blog/emacs-pdb-and-eggs" rel="nofollow">This blog post</a> might be related to your trouble.</p>
0
2009-10-17T00:11:11Z
[ "python", "pdb" ]
Python pdb not breaking in files properly?
1,576,266
<p>I wish I could provide a simple sample case that occurs using standard library code, but unfortunately it only happens when using one of our in-house libraries that in turn is built on top of sql alchemy.</p> <p>Basically, the problem is that this <code>break</code> command:</p> <pre><code>(Pdb) print sqlalchemy.engine.base.__file__ /prod/eggs/SQLAlchemy-0.5.5-py2.5.egg/sqlalchemy/engine/base.py (Pdb) break /prod/eggs/SQLAlchemy-0.5.5-py2.5.egg/sqlalchemy/engine/base.py:946 </code></pre> <p>Is just being totally ignored, it seems, by <code>pdb</code>. As in, even though I am <em>positive</em> the code is being hit (both because I can see log messages, and because I've used <code>sys.settrace</code> to check which lines in which files are being hit), <code>pdb</code> is just not breaking there.</p> <p>I suspect that somehow the use of an egg is confusing <code>pdb</code> as to what files are being used (I can't reproduce the error if I use a non-egg'ed library, like <code>pickle</code>; there everything works fine).</p> <p>It's a shot in the dark, but has anyone come across this before?</p>
0
2009-10-16T05:39:53Z
2,634,056
<p>I don't suppose this is yet another problem caused by setuptools? I ask because I notice the ".egg" in that path...</p>
0
2010-04-14T00:06:24Z
[ "python", "pdb" ]
Python pdb not breaking in files properly?
1,576,266
<p>I wish I could provide a simple sample case that occurs using standard library code, but unfortunately it only happens when using one of our in-house libraries that in turn is built on top of sql alchemy.</p> <p>Basically, the problem is that this <code>break</code> command:</p> <pre><code>(Pdb) print sqlalchemy.engine.base.__file__ /prod/eggs/SQLAlchemy-0.5.5-py2.5.egg/sqlalchemy/engine/base.py (Pdb) break /prod/eggs/SQLAlchemy-0.5.5-py2.5.egg/sqlalchemy/engine/base.py:946 </code></pre> <p>Is just being totally ignored, it seems, by <code>pdb</code>. As in, even though I am <em>positive</em> the code is being hit (both because I can see log messages, and because I've used <code>sys.settrace</code> to check which lines in which files are being hit), <code>pdb</code> is just not breaking there.</p> <p>I suspect that somehow the use of an egg is confusing <code>pdb</code> as to what files are being used (I can't reproduce the error if I use a non-egg'ed library, like <code>pickle</code>; there everything works fine).</p> <p>It's a shot in the dark, but has anyone come across this before?</p>
0
2009-10-16T05:39:53Z
14,806,375
<p>What version of python are running? I observe similar behavior on python 2.7.3. Curiously, I do <em>not</em> see the same behavior on ipython 0.12.1.</p> <p>In python 2.7.3, the debugger and the stack trace get the point where an exception occurred wrong.</p> <p>In ipython 0.12.1, the debugger and the stack trace get the point where the exception occurs is correct, but once the exception occurs, then the program exits, which makes post mortem debugging difficult.</p>
0
2013-02-11T05:25:00Z
[ "python", "pdb" ]
Using Sphinx to write personal websites and blogs
1,576,340
<p><a href="http://sphinx.pocoo.org/">Sphinx</a> is a Python library to generate nice documentation from a set of <a href="http://docutils.sourceforge.net/rst.html">ReST</a> formatted text files.</p> <p>I wonder if any one has written Sphinx plugins to make it <strong>generate personal websites and blogs</strong>.</p> <p>Especially for blogs, there needs to be a way to automatically list posts chronologically and generate a RSS feed. One needs to write a Sphinx plugin to do such special page/xml generation.</p> <p>Has anyone tried this before?</p>
31
2009-10-16T05:56:08Z
1,576,372
<p>Not Sphinx, but several of the sites at <a href="http://codespeak.net/" rel="nofollow">http://codespeak.net/</a> are done with scripts that take ReST text, generates HTML and uploads them to the site. I didn't write those scripts though, but I've used them.</p> <p>It's a reasonable way to generate sites if the sites need to contain a lot of ReST files anyway, like when generating documentation for python modules, which of course these sites are all about. It's also good if you need the site to be version controlled, because you can keep the source code in svn or hg, or something.</p> <p>But if you start writing a lot of automatic menues and other extensions, what you will end up with in the end is a content management system. And there is plenty of those around already, so you might want to look at them first.</p> <p>Another example is the new packages.python.org. There you can generate your documentation in anyway you want it, and then through PyPI upload a zip-file with the docs. Distribute has done this with Sphinx: <a href="http://packages.python.org/distribute" rel="nofollow">http://packages.python.org/distribute</a> . But there no particular script is needed, that's just generating HTML from Sphinx documentation.</p> <p>However...</p> <p>I must say that I find the idea of writing a blogging software as Sphinx extension a bit funny, especially since there is so much excellent blogging software out there already. And nothing is going to beat Wordpress anyway, and wordpress.com has been a great blogging experience for me. But as an exercise in how much you can abuse Sphinx, why not! :-)</p>
2
2009-10-16T06:06:14Z
[ "python", "plugins", "website", "blogs", "python-sphinx" ]
Using Sphinx to write personal websites and blogs
1,576,340
<p><a href="http://sphinx.pocoo.org/">Sphinx</a> is a Python library to generate nice documentation from a set of <a href="http://docutils.sourceforge.net/rst.html">ReST</a> formatted text files.</p> <p>I wonder if any one has written Sphinx plugins to make it <strong>generate personal websites and blogs</strong>.</p> <p>Especially for blogs, there needs to be a way to automatically list posts chronologically and generate a RSS feed. One needs to write a Sphinx plugin to do such special page/xml generation.</p> <p>Has anyone tried this before?</p>
31
2009-10-16T05:56:08Z
1,576,635
<p>Doug hellmann, author of the 'Python Module of the Week' does his site using Sphinx.</p> <p><a href="http://www.doughellmann.com/PyMOTW/" rel="nofollow">http://www.doughellmann.com/PyMOTW/</a></p> <p>He has several posts which cover sphinx topics that can probably help you on your way:</p> <p><a href="http://doughellmann.com/?s=sphinx" rel="nofollow">http://blog.doughellmann.com</a></p>
11
2009-10-16T07:30:40Z
[ "python", "plugins", "website", "blogs", "python-sphinx" ]
Using Sphinx to write personal websites and blogs
1,576,340
<p><a href="http://sphinx.pocoo.org/">Sphinx</a> is a Python library to generate nice documentation from a set of <a href="http://docutils.sourceforge.net/rst.html">ReST</a> formatted text files.</p> <p>I wonder if any one has written Sphinx plugins to make it <strong>generate personal websites and blogs</strong>.</p> <p>Especially for blogs, there needs to be a way to automatically list posts chronologically and generate a RSS feed. One needs to write a Sphinx plugin to do such special page/xml generation.</p> <p>Has anyone tried this before?</p>
31
2009-10-16T05:56:08Z
1,577,278
<p>I redid my personal website (<a href="http://homepage.mac.com/s_lott/steve/" rel="nofollow">http://homepage.mac.com/s_lott/steve/</a>) in Sphinx. It works nicely. <em>Sadly, the SO markup mangles the <code>_</code> in my URL.</em></p> <p>I also rewrote the entire <em>Introduction to Programming for Non-Programmers</em> (<a href="http://homepage.mac.com/s_lott/books/nonprog/html/index.html" rel="nofollow">http://homepage.mac.com/s_lott/books/nonprog/html/index.html</a>) book in Sphinx. I'm in the process of rewriting Introduction to Python in Sphinx.</p> <p>I do not use Sphinx for blogs -- it's not perfectly convenient, but it would work. I use <a href="http://slott-softwarearchitect.blogspot.com/" rel="nofollow">blogspot</a> for low-graphics/high-text and relatively high-velocity blogging. I use iWeb (<a href="http://web.me.com/s_lott/Travel/Welcome.html" rel="nofollow">http://web.me.com/s_lott/Travel/Welcome.html</a>) for high graphic and relatively low-velocity blogging.</p>
1
2009-10-16T10:21:02Z
[ "python", "plugins", "website", "blogs", "python-sphinx" ]
Using Sphinx to write personal websites and blogs
1,576,340
<p><a href="http://sphinx.pocoo.org/">Sphinx</a> is a Python library to generate nice documentation from a set of <a href="http://docutils.sourceforge.net/rst.html">ReST</a> formatted text files.</p> <p>I wonder if any one has written Sphinx plugins to make it <strong>generate personal websites and blogs</strong>.</p> <p>Especially for blogs, there needs to be a way to automatically list posts chronologically and generate a RSS feed. One needs to write a Sphinx plugin to do such special page/xml generation.</p> <p>Has anyone tried this before?</p>
31
2009-10-16T05:56:08Z
1,588,720
<p>I've done it at <a href="http://reinout.vanrees.org/weblog" rel="nofollow">http://reinout.vanrees.org/weblog</a>. The key trick is to add a preprocessor step. I've got my blog entries in a <code>weblog/yyyy/mm/dd/</code> folder structure.</p> <p>A script iterates through that folder structure, creating <code>index.txt</code> files in every directory, listing the sub-items. The normal Sphinx process then renders those <code>index.txt</code> files.</p> <p>I added a custom Sphinx processor for tags. So ".. tags:: python, buildout" somewhere at the top of my weblog entry generates the tags. And the preprocessor again collects those entries and writes out a <code>weblog/tags/TAGNAME.txt</code> file which Sphinx again renders normally.</p> <p>The preprocessor also creates the root <code>weblog/index.txt</code> with the latest 10 entries. And an <code>weblog/atom.xml</code> in (hardcoded) the output directory for the rss feed.</p> <p>So: you need some custom stuff, but it is pretty much plain text, so for me it was a nice exercise. And you get to write some helper scripts to make life easy, for instance one that copies a textfile from somewhere to today's weblog directory (including creation of missing directories and an "svn add").</p>
15
2009-10-19T13:39:15Z
[ "python", "plugins", "website", "blogs", "python-sphinx" ]
Using Sphinx to write personal websites and blogs
1,576,340
<p><a href="http://sphinx.pocoo.org/">Sphinx</a> is a Python library to generate nice documentation from a set of <a href="http://docutils.sourceforge.net/rst.html">ReST</a> formatted text files.</p> <p>I wonder if any one has written Sphinx plugins to make it <strong>generate personal websites and blogs</strong>.</p> <p>Especially for blogs, there needs to be a way to automatically list posts chronologically and generate a RSS feed. One needs to write a Sphinx plugin to do such special page/xml generation.</p> <p>Has anyone tried this before?</p>
31
2009-10-16T05:56:08Z
3,218,401
<p>It's worth knowing that there is an RSS extension for sphinx in the sphinx-contrib extensions, called <code>sphinxcontrib.feed</code> It and many other fun Sphinx things live at <a href="http://bitbucket.org/birkenfeld/sphinx-contrib/">http://bitbucket.org/birkenfeld/sphinx-contrib/</a></p> <p>(Disclaimer: I wrote the feed extension.)</p>
6
2010-07-10T08:03:58Z
[ "python", "plugins", "website", "blogs", "python-sphinx" ]
Using Sphinx to write personal websites and blogs
1,576,340
<p><a href="http://sphinx.pocoo.org/">Sphinx</a> is a Python library to generate nice documentation from a set of <a href="http://docutils.sourceforge.net/rst.html">ReST</a> formatted text files.</p> <p>I wonder if any one has written Sphinx plugins to make it <strong>generate personal websites and blogs</strong>.</p> <p>Especially for blogs, there needs to be a way to automatically list posts chronologically and generate a RSS feed. One needs to write a Sphinx plugin to do such special page/xml generation.</p> <p>Has anyone tried this before?</p>
31
2009-10-16T05:56:08Z
9,238,379
<p>As of now (February, 2012), there are different resources available to do what you want:</p> <p>A blog engine based on sphinx: <a href="http://tinkerer.me/">http://tinkerer.me/</a></p> <p>Reinout Van Rees' blog: <a href="https://github.com/reinout/reinout.vanrees.org">https://github.com/reinout/reinout.vanrees.org</a></p> <p>The feed contrib extension: <a href="https://bitbucket.org/birkenfeld/sphinx-contrib/src/tip/feed/README">https://bitbucket.org/birkenfeld/sphinx-contrib/src/tip/feed/README</a></p>
13
2012-02-11T06:41:23Z
[ "python", "plugins", "website", "blogs", "python-sphinx" ]
Using Sphinx to write personal websites and blogs
1,576,340
<p><a href="http://sphinx.pocoo.org/">Sphinx</a> is a Python library to generate nice documentation from a set of <a href="http://docutils.sourceforge.net/rst.html">ReST</a> formatted text files.</p> <p>I wonder if any one has written Sphinx plugins to make it <strong>generate personal websites and blogs</strong>.</p> <p>Especially for blogs, there needs to be a way to automatically list posts chronologically and generate a RSS feed. One needs to write a Sphinx plugin to do such special page/xml generation.</p> <p>Has anyone tried this before?</p>
31
2009-10-16T05:56:08Z
13,031,104
<p>If you need to write in <a href="http://docutils.sourceforge.net/rst.html">reStructuredText </a>, you should try <a href="http://docs.getpelican.com/">Pelican</a>. </p> <p>Pelican is a static site generator, written in Python. You'll be able to write your blog entries directly in reStructuredText or Markdown.</p>
10
2012-10-23T13:05:57Z
[ "python", "plugins", "website", "blogs", "python-sphinx" ]
Using Sphinx to write personal websites and blogs
1,576,340
<p><a href="http://sphinx.pocoo.org/">Sphinx</a> is a Python library to generate nice documentation from a set of <a href="http://docutils.sourceforge.net/rst.html">ReST</a> formatted text files.</p> <p>I wonder if any one has written Sphinx plugins to make it <strong>generate personal websites and blogs</strong>.</p> <p>Especially for blogs, there needs to be a way to automatically list posts chronologically and generate a RSS feed. One needs to write a Sphinx plugin to do such special page/xml generation.</p> <p>Has anyone tried this before?</p>
31
2009-10-16T05:56:08Z
29,449,180
<p>Check out <a href="http://ablog.readthedocs.org/" rel="nofollow">ABlog for Sphinx</a></p> <p>I am in the process of starting a blog myself using it.</p> <p>I stumbled across it while I was going through my feeds in feedly. I searched about it and found it interesting. It also has Disqus integration, and can generat Atom feeds (not very sure what that is at the moment, I am new to the web)</p> <p>I have not yet figured out how to deploy my test blog, will update when i find out something.</p>
3
2015-04-04T17:08:40Z
[ "python", "plugins", "website", "blogs", "python-sphinx" ]
Generate pretty diff html in Python
1,576,459
<p>I have two chunks of text that I would like to compare and see which words/lines have been added/removed/modified in Python (similar to a Wiki's Diff Output). </p> <p>I have tried difflib.HtmlDiff but it's output is less than pretty. </p> <p>Is there a way in Python (or external library) that would generate clean looking HTML of the diff of two sets of text chunks? (not just line level, but also word/character modifications within a line)</p>
20
2009-10-16T06:39:20Z
1,576,663
<p>try first of all clean up both of HTML by lxml.html, and the check the difference by difflib</p>
0
2009-10-16T07:41:41Z
[ "python", "html", "diff", "prettify" ]
Generate pretty diff html in Python
1,576,459
<p>I have two chunks of text that I would like to compare and see which words/lines have been added/removed/modified in Python (similar to a Wiki's Diff Output). </p> <p>I have tried difflib.HtmlDiff but it's output is less than pretty. </p> <p>Is there a way in Python (or external library) that would generate clean looking HTML of the diff of two sets of text chunks? (not just line level, but also word/character modifications within a line)</p>
20
2009-10-16T06:39:20Z
1,576,759
<p>There's <code>diff_prettyHtml()</code> in the <a href="https://code.google.com/p/google-diff-match-patch/" rel="nofollow">diff-match-patch</a> library from Google.</p>
20
2009-10-16T08:15:22Z
[ "python", "html", "diff", "prettify" ]
Generate pretty diff html in Python
1,576,459
<p>I have two chunks of text that I would like to compare and see which words/lines have been added/removed/modified in Python (similar to a Wiki's Diff Output). </p> <p>I have tried difflib.HtmlDiff but it's output is less than pretty. </p> <p>Is there a way in Python (or external library) that would generate clean looking HTML of the diff of two sets of text chunks? (not just line level, but also word/character modifications within a line)</p>
20
2009-10-16T06:39:20Z
1,579,110
<p>Generally, if you want some HTML to render in a prettier way, you do it by adding CSS.</p> <p>For instance, if you generate the HTML like this:</p> <pre><code>import difflib import sys fromfile = "xxx" tofile = "zzz" fromlines = open(fromfile, 'U').readlines() tolines = open(tofile, 'U').readlines() diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile) sys.stdout.writelines(diff) </code></pre> <p>then you get green backgrounds on added lines, yellow on changed lines and red on deleted. If I were doing this I would take take the generated HTML, extract the body, and prefix it with my own handwritten block of HTML with lots of CSS to make it look good. I'd also probably strip out the legend table and move it to the top or put it in a div so that CSS can do that. </p> <p>Actually, I would give serious consideration to just fixing up the difflib module (which is written in python) to generate better HTML and contribute it back to the project. If you have a CSS expert to help you or are one yourself, please consider doing this.</p>
12
2009-10-16T16:40:35Z
[ "python", "html", "diff", "prettify" ]
Generate pretty diff html in Python
1,576,459
<p>I have two chunks of text that I would like to compare and see which words/lines have been added/removed/modified in Python (similar to a Wiki's Diff Output). </p> <p>I have tried difflib.HtmlDiff but it's output is less than pretty. </p> <p>Is there a way in Python (or external library) that would generate clean looking HTML of the diff of two sets of text chunks? (not just line level, but also word/character modifications within a line)</p>
20
2009-10-16T06:39:20Z
1,593,316
<p>A copy of my own answer from <a href="http://stackoverflow.com/questions/31722/anyone-have-a-diff-algorithm-for-rendered-html/1593296#1593296">here</a>.</p> <p><hr /></p> <p>What about <a href="http://code.google.com/p/daisydiff/" rel="nofollow">DaisyDiff</a> (<a href="http://code.google.com/p/daisydiff/" rel="nofollow">Java</a> and <a href="http://www.mediawiki.org/wiki/Visual%5FDiff" rel="nofollow">PHP</a> vesions available).</p> <p>Following features are really nice:</p> <ul> <li>Works with badly formed HTML that can be found "in the wild".</li> <li>The diffing is more specialized in HTML than XML tree differs. Changing part of a text node will not cause the entire node to be changed.</li> <li>In addition to the default visual diff, HTML source can be diffed coherently.</li> <li>Provides easy to understand descriptions of the changes.</li> <li>The default GUI allows easy browsing of the modifications through keyboard shortcuts and links. </li> </ul>
1
2009-10-20T08:58:22Z
[ "python", "html", "diff", "prettify" ]
Generate pretty diff html in Python
1,576,459
<p>I have two chunks of text that I would like to compare and see which words/lines have been added/removed/modified in Python (similar to a Wiki's Diff Output). </p> <p>I have tried difflib.HtmlDiff but it's output is less than pretty. </p> <p>Is there a way in Python (or external library) that would generate clean looking HTML of the diff of two sets of text chunks? (not just line level, but also word/character modifications within a line)</p>
20
2009-10-16T06:39:20Z
29,867,928
<p>I recently posted a python script that does just this: <a href="https://github.com/wagoodman/diff2HtmlCompare" rel="nofollow">diff2HtmlCompare</a> (follow the link for a screenshot). Under the hood it wraps difflib and uses pygments for syntax highlighting.</p>
1
2015-04-25T16:42:34Z
[ "python", "html", "diff", "prettify" ]
Generate pretty diff html in Python
1,576,459
<p>I have two chunks of text that I would like to compare and see which words/lines have been added/removed/modified in Python (similar to a Wiki's Diff Output). </p> <p>I have tried difflib.HtmlDiff but it's output is less than pretty. </p> <p>Is there a way in Python (or external library) that would generate clean looking HTML of the diff of two sets of text chunks? (not just line level, but also word/character modifications within a line)</p>
20
2009-10-16T06:39:20Z
35,338,425
<p>Since the .. library from google seams to have no active development any more, I suggest to use <a href="https://github.com/askeing/diff_py" rel="nofollow">diff_py</a></p> <p>From the github page:</p> <blockquote> <p>The simple diff tool which is written by Python. The diff result can be printed in console or to html file.</p> </blockquote>
0
2016-02-11T11:42:31Z
[ "python", "html", "diff", "prettify" ]
Why does else behave differently in for/while statements as opposed to if/try statements?
1,576,537
<p>I have recently stumbled over a seeming inconsistency in Python's way of dealing with else clauses in different compound statements. Since Python is so well designed, I'm sure that there is a good explanation, but I can't think of it.</p> <p>Consider the following:</p> <pre><code>if condition: do_something() else: do_something_else() </code></pre> <p>Here, <code>do_something_else()</code> is only executed if <code>condition</code> is false, as expected. </p> <p>Similarly, in</p> <pre><code>try: do_something() except someException: pass: else: do_something_else() finally: cleanup() </code></pre> <p><code>do_something_else()</code> is only executed if no exception occurred.</p> <p>But in for or while loops, an else clause is always executed, whether the contents of the <code>for/while block</code> have been executed or not.</p> <pre><code>for i in some_iterator: print(i) else: print("Iterator is empty!") </code></pre> <p>will always print "Iterator is empty!", whether I say <code>some_iterator = []</code> or <code>some_iterator = [1,2,3]</code>. Same behavior in <code>while-else</code> clauses. It seems to me that <code>else</code> behaves more like <code>finally</code> in these cases. What am I overlooking?</p>
6
2009-10-16T06:58:27Z
1,576,552
<p>The <code>for else</code> construct executes the <code>else</code> clause if no <code>break</code> statement was executed for the loop, <a href="http://docs.python.org/reference/compound_stmts.html#the-for-statement" rel="nofollow">as described here</a> For example, this else clause is never evaluated</p> <pre><code>for i in range(1,10): if i % 5 == 0: print i break else: print "nothing divisible by 5" </code></pre>
13
2009-10-16T07:03:50Z
[ "python", "flow-control" ]
Why does else behave differently in for/while statements as opposed to if/try statements?
1,576,537
<p>I have recently stumbled over a seeming inconsistency in Python's way of dealing with else clauses in different compound statements. Since Python is so well designed, I'm sure that there is a good explanation, but I can't think of it.</p> <p>Consider the following:</p> <pre><code>if condition: do_something() else: do_something_else() </code></pre> <p>Here, <code>do_something_else()</code> is only executed if <code>condition</code> is false, as expected. </p> <p>Similarly, in</p> <pre><code>try: do_something() except someException: pass: else: do_something_else() finally: cleanup() </code></pre> <p><code>do_something_else()</code> is only executed if no exception occurred.</p> <p>But in for or while loops, an else clause is always executed, whether the contents of the <code>for/while block</code> have been executed or not.</p> <pre><code>for i in some_iterator: print(i) else: print("Iterator is empty!") </code></pre> <p>will always print "Iterator is empty!", whether I say <code>some_iterator = []</code> or <code>some_iterator = [1,2,3]</code>. Same behavior in <code>while-else</code> clauses. It seems to me that <code>else</code> behaves more like <code>finally</code> in these cases. What am I overlooking?</p>
6
2009-10-16T06:58:27Z
1,576,579
<p>Yes, as Eli mentioned, the else clause is executed only if you don't break. It stops you from implementing code like this:</p> <pre><code>for i in range(1,10): if i % 5 == 0: print i break if i % 5 != 0: print "nothing divisible by 5" </code></pre> <p>Which is roughly equivalent here, but handy if the conditions for quitting are a bit more complicated (like checking various possible conditions or combinations of conditions).</p>
4
2009-10-16T07:10:47Z
[ "python", "flow-control" ]
Why does else behave differently in for/while statements as opposed to if/try statements?
1,576,537
<p>I have recently stumbled over a seeming inconsistency in Python's way of dealing with else clauses in different compound statements. Since Python is so well designed, I'm sure that there is a good explanation, but I can't think of it.</p> <p>Consider the following:</p> <pre><code>if condition: do_something() else: do_something_else() </code></pre> <p>Here, <code>do_something_else()</code> is only executed if <code>condition</code> is false, as expected. </p> <p>Similarly, in</p> <pre><code>try: do_something() except someException: pass: else: do_something_else() finally: cleanup() </code></pre> <p><code>do_something_else()</code> is only executed if no exception occurred.</p> <p>But in for or while loops, an else clause is always executed, whether the contents of the <code>for/while block</code> have been executed or not.</p> <pre><code>for i in some_iterator: print(i) else: print("Iterator is empty!") </code></pre> <p>will always print "Iterator is empty!", whether I say <code>some_iterator = []</code> or <code>some_iterator = [1,2,3]</code>. Same behavior in <code>while-else</code> clauses. It seems to me that <code>else</code> behaves more like <code>finally</code> in these cases. What am I overlooking?</p>
6
2009-10-16T06:58:27Z
1,576,622
<p>Well, it depends how you see it. You can look at the elses like this (excuse the screaming, its the only way to make emphasis in code):</p> <pre><code>if condition: do_something() IF THE PREVIOUS CONDITION WAS FALSE: do_something_else() </code></pre> <p>Now, there is an obvious similarity between if/else and try/except/else, if you see the else statement as an else to the except statement. Like this.</p> <pre><code>try: do_something() IF THERE WAS AN EXCEPTION: pass: IF THE PREVIOUS CONDITION WAS FALSE: do_something_else() finally: cleanup() </code></pre> <p>Same goes for the else/for:</p> <pre><code>IF some_iterator IS NOT EMPTY: i = next(some_iterator) print(i) IF THE PREVIOUS CONDITION WAS FALSE: print("Iterator is empty!") </code></pre> <p>So here we see that the else in some fundamental way <em>do</em> work exactly the same in all three cases. </p> <p>But you can also see the else in this way:</p> <pre><code>try: do_something() except someException: pass: IF NO EXCEPTION: do_something_else() finally: cleanup() </code></pre> <p>And then it's not the same anymore, but the else because a sort of "if nothing else". You can see for/else in the same way:</p> <pre><code>for i in some_iterator: print(i) IF NO MORE ITERATING: print("Iterator is empty!") </code></pre> <p>But then again, considering the elif, then this way of seeing it works for if/else as well:</p> <pre><code>if condition: do_something() elif otherconditaion: do_anotherthing() IF NO CONDITION WAS TRUE: do_something_else() </code></pre> <p>Which way you want to look at the else is up to you, but in both ways of viewing, else do have similarities in all three cases.</p>
5
2009-10-16T07:28:03Z
[ "python", "flow-control" ]
How can I capture iSight frames with Python in Snow Leopard?
1,576,593
<p>I have the following PyObjC script:</p> <pre><code>from Foundation import NSObject import QTKit error = None capture_session = QTKit.QTCaptureSession.alloc().init() print 'capture_session', capture_session device = QTKit.QTCaptureDevice.defaultInputDeviceWithMediaType_(QTKit.QTMediaTypeVideo) print 'device', device, type(device) success = device.open_(error) print 'device open success', success, error if not success: raise Exception(error) capture_device_input = QTKit.QTCaptureDeviceInput.alloc().initWithDevice_(device) print 'capture_device_input', capture_device_input, capture_device_input.device() success = capture_session.addInput_error_(capture_device_input, error) print 'session add input success', success, error if not success: raise Exception(error) capture_decompressed_video_output = QTKit.QTCaptureDecompressedVideoOutput.alloc().init() print 'capture_decompressed_video_output', capture_decompressed_video_output class Delegate(NSObject): def captureOutput_didOutputVideoFrame_withSampleBuffer_fromConnection_(self, captureOutput, videoFrame, sampleBuffer, connection): print videoFrame, sampleBuffer, connection delegate = Delegate.alloc().init() print 'delegate', delegate capture_decompressed_video_output.setDelegate_(delegate) print 'output delegate:', capture_decompressed_video_output.delegate() success = capture_session.addOutput_error_(capture_decompressed_video_output, error) print 'capture session add output success', success, error if not success: raise Exception(error) print 'about to run session', capture_session, 'with inputs', capture_session.inputs(), 'and outputs', capture_session.outputs() capture_session.startRunning() print 'capture session is running?', capture_session.isRunning() import time time.sleep(10) </code></pre> <p>The program reports no errors, but iSight's green light is never activated and the delegate's frame capture callback is never called. Here's the output I get:</p> <pre><code>$ python prueba.py capture_session &lt;QTCaptureSession: 0x1006c16f0&gt; device Built-in iSight &lt;objective-c class QTCaptureDALDevice at 0x7fff70366aa8&gt; device open success (True, None) None capture_device_input &lt;QTCaptureDeviceInput: 0x1002ae010&gt; Built-in iSight session add input success (True, None) None capture_decompressed_video_output &lt;QTCaptureDecompressedVideoOutput: 0x104239f10&gt; delegate &lt;Delegate: 0x10423af50&gt; output delegate: &lt;Delegate: 0x10423af50&gt; capture session add output success (True, None) None about to run session &lt;QTCaptureSession: 0x1006c16f0&gt; with inputs ( "&lt;QTCaptureDeviceInput: 0x1002ae010&gt;" ) and outputs ( "&lt;QTCaptureDecompressedVideoOutput: 0x104239f10&gt;" ) capture session is running? True </code></pre> <p>PS: Please don't answer I should try PySight, I have but it won't work because Xcode can't compile CocoaSequenceGrabber in 64bit.</p>
5
2009-10-16T07:16:44Z
1,578,283
<p>Your problem here is that you don't have an event loop. If you want to do this as a standalone script, you'll have to figure out how to create one. The PyObjC XCode templates automatically set that up for you with:</p> <pre><code>from PyObjCTools import AppHelper AppHelper.runEventLoop() </code></pre> <p>Trying to insert that at the top of your script, however, shows that something inside <code>AppHelper</code> (probably <code>NSApplicationMain</code>) expects a plist file to extract the main class from. You can get that by creating a <code>setup.py</code> file and using <code>py2app</code>, something like this example from a <a href="http://svn.red-bean.com/bob/pycon/2005/trunk/dist/PyObjC-Hacking.pdf" rel="nofollow" title="PyObjC talk">PyObjc talk</a>:</p> <pre><code>from distutils.core import setup import py2app plist = dict( NSPrincipalClass='SillyBalls', ) setup( plugin=['SillyBalls.py'], data_files=['English.lproj'], options=dict(py2app=dict( extension='.saver', plist=plist, )), ) </code></pre>
3
2009-10-16T14:08:43Z
[ "python", "osx-snow-leopard", "pyobjc", "qtkit", "isight" ]
How can I capture iSight frames with Python in Snow Leopard?
1,576,593
<p>I have the following PyObjC script:</p> <pre><code>from Foundation import NSObject import QTKit error = None capture_session = QTKit.QTCaptureSession.alloc().init() print 'capture_session', capture_session device = QTKit.QTCaptureDevice.defaultInputDeviceWithMediaType_(QTKit.QTMediaTypeVideo) print 'device', device, type(device) success = device.open_(error) print 'device open success', success, error if not success: raise Exception(error) capture_device_input = QTKit.QTCaptureDeviceInput.alloc().initWithDevice_(device) print 'capture_device_input', capture_device_input, capture_device_input.device() success = capture_session.addInput_error_(capture_device_input, error) print 'session add input success', success, error if not success: raise Exception(error) capture_decompressed_video_output = QTKit.QTCaptureDecompressedVideoOutput.alloc().init() print 'capture_decompressed_video_output', capture_decompressed_video_output class Delegate(NSObject): def captureOutput_didOutputVideoFrame_withSampleBuffer_fromConnection_(self, captureOutput, videoFrame, sampleBuffer, connection): print videoFrame, sampleBuffer, connection delegate = Delegate.alloc().init() print 'delegate', delegate capture_decompressed_video_output.setDelegate_(delegate) print 'output delegate:', capture_decompressed_video_output.delegate() success = capture_session.addOutput_error_(capture_decompressed_video_output, error) print 'capture session add output success', success, error if not success: raise Exception(error) print 'about to run session', capture_session, 'with inputs', capture_session.inputs(), 'and outputs', capture_session.outputs() capture_session.startRunning() print 'capture session is running?', capture_session.isRunning() import time time.sleep(10) </code></pre> <p>The program reports no errors, but iSight's green light is never activated and the delegate's frame capture callback is never called. Here's the output I get:</p> <pre><code>$ python prueba.py capture_session &lt;QTCaptureSession: 0x1006c16f0&gt; device Built-in iSight &lt;objective-c class QTCaptureDALDevice at 0x7fff70366aa8&gt; device open success (True, None) None capture_device_input &lt;QTCaptureDeviceInput: 0x1002ae010&gt; Built-in iSight session add input success (True, None) None capture_decompressed_video_output &lt;QTCaptureDecompressedVideoOutput: 0x104239f10&gt; delegate &lt;Delegate: 0x10423af50&gt; output delegate: &lt;Delegate: 0x10423af50&gt; capture session add output success (True, None) None about to run session &lt;QTCaptureSession: 0x1006c16f0&gt; with inputs ( "&lt;QTCaptureDeviceInput: 0x1002ae010&gt;" ) and outputs ( "&lt;QTCaptureDecompressedVideoOutput: 0x104239f10&gt;" ) capture session is running? True </code></pre> <p>PS: Please don't answer I should try PySight, I have but it won't work because Xcode can't compile CocoaSequenceGrabber in 64bit.</p>
5
2009-10-16T07:16:44Z
2,192,651
<p>You should give a try to <a href="http://github.com/motmot/pycamiface" rel="nofollow">motmot's camiface</a> library from Andrew Straw. It also works with firewire cameras, but it works also with the isight, which is what you are looking for.</p> <p>From the tutorial:</p> <pre><code>import motmot.cam_iface.cam_iface_ctypes as cam_iface import numpy as np mode_num = 0 device_num = 0 num_buffers = 32 cam = cam_iface.Camera(device_num,num_buffers,mode_num) cam.start_camera() frame = np.asarray(cam.grab_next_frame_blocking()) print 'grabbed frame with shape %s'%(frame.shape,) </code></pre>
2
2010-02-03T14:35:57Z
[ "python", "osx-snow-leopard", "pyobjc", "qtkit", "isight" ]
pyqt installation problem in mac osx snow leopard
1,576,629
<p>I'm following a tutorial of making desktop apps. with python and qt4, I downloaded and installed qt creator ide, created the .ui file and then I had to convert it using pyuic4, I've been trying a lot of things and still can't do it.</p> <p>I thought that pyuic4 would be installed with Qt creator IDE, but it seems that's not the case, so I installed pyqt through macports:</p> <pre><code>sudo port install py26-pyqt4 </code></pre> <p>I didn't know but that came with qt, so it was about 3 hours building it.</p> <p>after installing it I tried to convert the .ui again:</p> <pre><code>$ pyuic4-2.6 principal.ui -o prin.py Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PyQt4/uic/pyuic.py", line 4, in &lt;module&gt; from PyQt4 import QtCore ImportError: No module named PyQt4 </code></pre> <p>No module named PyQt4? wasn't that what I just installed?</p> <p>Thanks, and excuse me if my english isn't 100% good.</p>
4
2009-10-16T07:29:28Z
1,583,091
<p>I've solved it, you have to use the python of macports instead of the default that comes with OS X, to do that install python_select through macports:</p> <pre><code>sudo port install python_select sudo python_select python26 </code></pre>
8
2009-10-17T20:09:25Z
[ "python", "osx", "qt", "macports" ]
pyqt installation problem in mac osx snow leopard
1,576,629
<p>I'm following a tutorial of making desktop apps. with python and qt4, I downloaded and installed qt creator ide, created the .ui file and then I had to convert it using pyuic4, I've been trying a lot of things and still can't do it.</p> <p>I thought that pyuic4 would be installed with Qt creator IDE, but it seems that's not the case, so I installed pyqt through macports:</p> <pre><code>sudo port install py26-pyqt4 </code></pre> <p>I didn't know but that came with qt, so it was about 3 hours building it.</p> <p>after installing it I tried to convert the .ui again:</p> <pre><code>$ pyuic4-2.6 principal.ui -o prin.py Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PyQt4/uic/pyuic.py", line 4, in &lt;module&gt; from PyQt4 import QtCore ImportError: No module named PyQt4 </code></pre> <p>No module named PyQt4? wasn't that what I just installed?</p> <p>Thanks, and excuse me if my english isn't 100% good.</p>
4
2009-10-16T07:29:28Z
2,085,719
<p>I made <a href="http://chinbilly.blogspot.com/2010/01/building-pyqt4-on-snow-leopard.html" rel="nofollow">some notes on building and install PyQt4 on Mac Snow Leopard</a>.</p> <p>The order is important, and there are some quirks with 64-bit libraries. The default Mac Qt libs are Carbon (32 bit), whereas Mac system Python is 64 bit and needs the Cocoa libs.</p>
3
2010-01-18T11:45:56Z
[ "python", "osx", "qt", "macports" ]
pyqt installation problem in mac osx snow leopard
1,576,629
<p>I'm following a tutorial of making desktop apps. with python and qt4, I downloaded and installed qt creator ide, created the .ui file and then I had to convert it using pyuic4, I've been trying a lot of things and still can't do it.</p> <p>I thought that pyuic4 would be installed with Qt creator IDE, but it seems that's not the case, so I installed pyqt through macports:</p> <pre><code>sudo port install py26-pyqt4 </code></pre> <p>I didn't know but that came with qt, so it was about 3 hours building it.</p> <p>after installing it I tried to convert the .ui again:</p> <pre><code>$ pyuic4-2.6 principal.ui -o prin.py Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PyQt4/uic/pyuic.py", line 4, in &lt;module&gt; from PyQt4 import QtCore ImportError: No module named PyQt4 </code></pre> <p>No module named PyQt4? wasn't that what I just installed?</p> <p>Thanks, and excuse me if my english isn't 100% good.</p>
4
2009-10-16T07:29:28Z
9,559,996
<p>I spent a while finding the package name in Homebrew. It seems to be:</p> <pre><code>brew install pyqt </code></pre>
0
2012-03-04T23:45:10Z
[ "python", "osx", "qt", "macports" ]
Releasing Python GIL while in C++ code
1,576,737
<p>I've got a library written in C++ which I wrap using SWIG and use in python. Generally there is one class with few methods. The problem is that calling these methods may be time consuming - they may hang my application (GIL is not released when calling these methods). So my question is: </p> <p>What is the simplest way to release GIL for these method calls? </p> <p>(I understand that if I used a C library I could wrap this with some additional C code, but here I use C++ and classes)</p>
6
2009-10-16T08:07:48Z
1,576,959
<p>You can use the same API call as for C. No difference. Include "python.h" and call the appoproate function.</p> <p>Also, see if SWIG doesn't have a typemap or something to indicate that the GIL shuold not be held for a specific function.</p>
1
2009-10-16T09:01:03Z
[ "c++", "python", "swig", "gil" ]
Releasing Python GIL while in C++ code
1,576,737
<p>I've got a library written in C++ which I wrap using SWIG and use in python. Generally there is one class with few methods. The problem is that calling these methods may be time consuming - they may hang my application (GIL is not released when calling these methods). So my question is: </p> <p>What is the simplest way to release GIL for these method calls? </p> <p>(I understand that if I used a C library I could wrap this with some additional C code, but here I use C++ and classes)</p>
6
2009-10-16T08:07:48Z
1,577,009
<p>Not having any idea what SWIG is I'll attempt an answer anyway :)</p> <p>Use something like this to release/acquire the GIL:</p> <pre><code>class GILReleaser { GILReleaser() : save(PyEval_SaveThread()) {} ~GILReleaser() { PyEval_RestoreThread(save); } PyThreadState* save; }; </code></pre> <p>And in the code-block of your choosing, utilize RAII to release/acquire GIL:</p> <pre><code>{ GILReleaser releaser; // ... Do stuff ... } </code></pre>
4
2009-10-16T09:12:03Z
[ "c++", "python", "swig", "gil" ]
Releasing Python GIL while in C++ code
1,576,737
<p>I've got a library written in C++ which I wrap using SWIG and use in python. Generally there is one class with few methods. The problem is that calling these methods may be time consuming - they may hang my application (GIL is not released when calling these methods). So my question is: </p> <p>What is the simplest way to release GIL for these method calls? </p> <p>(I understand that if I used a C library I could wrap this with some additional C code, but here I use C++ and classes)</p>
6
2009-10-16T08:07:48Z
1,578,357
<p>The real problem is that SWIG is not documented well (I saw hints to use changelog for searching ;) ). </p> <p>Ok, I found out that I can do inline functions in SWIG and use macros to release/acquire GIL, it looks like this:</p> <pre><code>%inline %{ void wrappedFunction(OriginalObject *o, &lt;parameters&gt;) { Py_BEGIN_ALLOW_THREADS o-&gt;originalFunction(&lt;parameters&gt;); Py_END_ALLOW_THREADS } %} </code></pre> <p>This function is not present in original C++, but available in python module. This is (almost) exactly what I wanted. (what I would like is to wrap original method like python decorator does)</p>
5
2009-10-16T14:21:01Z
[ "c++", "python", "swig", "gil" ]
SVN hook environment issues with Python script
1,576,784
<p>I am experiencing issues with my SVN post-commit hook and the fact that it is executed with an empty environment. Everything was working fine till about two weeks ago when my systems administrator upgraded a few things on the server.</p> <p>My post-commit hook executes a Python script that uses a SVN module to email information about the commit to me. After the recent upgrades, however, Python cannot find the SVN module when executed via the hook. When executed by hand (ie with all environment variables intact) everything works fine.</p> <p>I have tried setting the PYTHONPATH variable in my post-commit hook directly (PYTHONPATH=/usr/local/lib/svn-python), but that makes no difference.</p> <p>How can I tell Python where the module is located?</p>
1
2009-10-16T08:21:49Z
1,576,956
<p>Your system administrator might have forgotten to execute this command.</p> <pre><code>echo /usr/local/lib/svn-python \ &gt; /usr/local/lib/python2.x/site-packages/subversion.pth </code></pre> <p>This is written in subversion/bindings/swig/INSTALL in the source distribution.</p>
1
2009-10-16T09:00:25Z
[ "python", "svn" ]
SVN hook environment issues with Python script
1,576,784
<p>I am experiencing issues with my SVN post-commit hook and the fact that it is executed with an empty environment. Everything was working fine till about two weeks ago when my systems administrator upgraded a few things on the server.</p> <p>My post-commit hook executes a Python script that uses a SVN module to email information about the commit to me. After the recent upgrades, however, Python cannot find the SVN module when executed via the hook. When executed by hand (ie with all environment variables intact) everything works fine.</p> <p>I have tried setting the PYTHONPATH variable in my post-commit hook directly (PYTHONPATH=/usr/local/lib/svn-python), but that makes no difference.</p> <p>How can I tell Python where the module is located?</p>
1
2009-10-16T08:21:49Z
1,593,977
<p>Got it! I missed the <strong>export</strong> in my post-commit hook script! It should have been:</p> <p>export PYTHONPATH=/usr/local/lib/svn-python</p> <p>Problem solved :)</p>
1
2009-10-20T11:33:08Z
[ "python", "svn" ]
In regex, what does \w* mean?
1,576,789
<p>In Python. r^[\w*]$</p> <p>whats that mean?</p>
6
2009-10-16T08:23:41Z
1,576,800
<p>From the beginning of this line, <a href="http://rubular.com" rel="nofollow">"Any number of word characters (letter, number, underscore)"</a> until the end of the line.</p> <p>I am unsure as to why it's in square brackets, as circle brackets (e.g. "(" and ")") are correct if you want the matched text returned.</p>
0
2009-10-16T08:26:14Z
[ "python", "regex", "syntax" ]
In regex, what does \w* mean?
1,576,789
<p>In Python. r^[\w*]$</p> <p>whats that mean?</p>
6
2009-10-16T08:23:41Z
1,576,801
<p>\w refers to 0 or more alphanumeric characters and the underscore. the * in your case is also inside the character class, so [\w*] would match all of [a-zA-Z0-9_*] (the * is interpreted literally)</p> <p>See <a href="http://www.regular-expressions.info/reference.html" rel="nofollow">http://www.regular-expressions.info/reference.html</a></p> <p>To quote:</p> <blockquote> <p>\d, \w and \s --- Shorthand character classes matching digits, word characters, and whitespace. Can be used inside and outside character classes.</p> </blockquote> <p><strong>Edit</strong> corrected in response to comment</p>
0
2009-10-16T08:26:20Z
[ "python", "regex", "syntax" ]
In regex, what does \w* mean?
1,576,789
<p>In Python. r^[\w*]$</p> <p>whats that mean?</p>
6
2009-10-16T08:23:41Z
1,576,806
<p>\w is equivalent to [a-zA-Z0-9_] I don't understand the * after it or the [] around it, because \w already is a class and * in class definitions makes no sense. </p>
0
2009-10-16T08:27:00Z
[ "python", "regex", "syntax" ]
In regex, what does \w* mean?
1,576,789
<p>In Python. r^[\w*]$</p> <p>whats that mean?</p>
6
2009-10-16T08:23:41Z
1,576,812
<p><strong>Quick answer:</strong> Match a string consisting of a single character, where that character is alphanumeric (letters, numbers) an underscore (<code>_</code>) or an asterisk (<code>*</code>).</p> <p><strong>Details:</strong></p> <ul> <li>The "<code>\w</code>" means "any word character" which usually means alphanumeric (letters, numbers, regardless of case) plus underscore (_)</li> <li>The "<code>^</code>" "anchors" to the beginning of a string, and the "<code>$</code>" "anchors" To the end of a string, which means that, in this case, the match must start at the beginning of a string and end at the end of the string.</li> <li>The <code>[]</code> means a character class, which means "match any character contained in the character class".</li> </ul> <p>It is also worth mentioning that normal quoting and escaping rules for strings make it very difficult to enter regular expressions (all the backslashes would need to be escaped with additional backslashes), so in Python there is a special notation which has its own special quoting rules that allow for all of the backslashes to be interpreted properly, and that is what the "<code>r</code>" at the beginning is for.</p> <p><strong>Note:</strong> Normally an asterisk (<code>*</code>) means "0 or more of the previous thing" but in the example above, it does <em>not</em> have that meaning, since the asterisk is <em>inside</em> of the character class, so it loses its "special-ness".</p> <p>For more information on regular expressions in Python, the two official references are the <a href="http://docs.python.org/library/re.html">re module</a>, the Regular Expression <a href="http://docs.python.org/dev/howto/regex.html">HOWTO</a>.</p>
28
2009-10-16T08:27:57Z
[ "python", "regex", "syntax" ]
In regex, what does \w* mean?
1,576,789
<p>In Python. r^[\w*]$</p> <p>whats that mean?</p>
6
2009-10-16T08:23:41Z
1,576,824
<p>As exhuma said, \w is any word-class character (alphanumeric as Jonathan clarifies).</p> <p>However because it is in square brackets it will match:</p> <ol> <li>a single alphanumeric character OR</li> <li>an asterisk (*)</li> </ol> <p>So the whole regular expression matches:</p> <ul> <li>the beginning of a line (^)</li> <li>followed by either a single alphanumeric character or an asterisk</li> <li>followed by the end of a line ($)</li> </ul> <p>so the following would match:</p> <pre><code>blah z &lt;- matches this line blah </code></pre> <p>or</p> <pre><code>blah * &lt;- matches this line blah </code></pre>
1
2009-10-16T08:31:06Z
[ "python", "regex", "syntax" ]
In regex, what does \w* mean?
1,576,789
<p>In Python. r^[\w*]$</p> <p>whats that mean?</p>
6
2009-10-16T08:23:41Z
1,576,845
<p>As said above \w means any word. so you could use this in the context of below</p> <pre><code>view.aspx?url=[\w] </code></pre> <p>which means you can have any word as the value of the "url=" parameter</p>
0
2009-10-16T08:36:28Z
[ "python", "regex", "syntax" ]
How to use ? and ?: and : in REGEX for Python?
1,576,957
<p>I understand that </p> <pre><code>* = "zero or more" ? = "zero or more" ...what's the difference? </code></pre> <p>Also, ?: &lt;&lt; my book uses this, it says its a "subtlety" but I don't know what exactly these do!</p>
2
2009-10-16T09:00:34Z
1,576,962
<p>? = zero or one</p> <p>you use (?:) for grouping w/o saving the group in a temporary variable as you would with ()</p>
2
2009-10-16T09:02:01Z
[ "python", "regex", "syntax" ]
How to use ? and ?: and : in REGEX for Python?
1,576,957
<p>I understand that </p> <pre><code>* = "zero or more" ? = "zero or more" ...what's the difference? </code></pre> <p>Also, ?: &lt;&lt; my book uses this, it says its a "subtlety" but I don't know what exactly these do!</p>
2
2009-10-16T09:00:34Z
1,576,963
<p><code>?</code> does not mean "zero or more", it means "zero or one".</p>
1
2009-10-16T09:02:04Z
[ "python", "regex", "syntax" ]
How to use ? and ?: and : in REGEX for Python?
1,576,957
<p>I understand that </p> <pre><code>* = "zero or more" ? = "zero or more" ...what's the difference? </code></pre> <p>Also, ?: &lt;&lt; my book uses this, it says its a "subtlety" but I don't know what exactly these do!</p>
2
2009-10-16T09:00:34Z
1,576,991
<blockquote> <p>?: &lt;&lt; my book uses this, it says its a "subtlety" but I don't know what exactly these do!</p> </blockquote> <p>If that’s indeed what your book says, then I advise getting a better book.</p> <p>Inside parentheses (more precisely: right after an opening parenthesis), <code>?</code> has another meaning. It starts a group of <em>options</em> which count only for the scope of the parentheses. <code>?:</code> is a special case of these options. To understand this special case, you must first know that parentheses create capture groups:</p> <pre><code>a(.)c </code></pre> <p>This is a regular expression that matches any three-letter string starting with <code>a</code> and ending with <code>c</code>. The middle character is (more or less) aribtrary. Since you put it in parentheses, you can <em>capture</em> it:</p> <pre><code>m = re.search('a(.)c', 'abcdef') print m.group(1) </code></pre> <p>This will print <code>b</code>, since <code>m.group(1)</code> captures the content of the first parentheses (<code>group(0)</code> captures the whole hit, here <code>abc</code>).</p> <p>Now, consider this regular expression:</p> <pre><code>a(?:.)c </code></pre> <p>No capture is made here – this is what <code>?:</code> after an opening parenthesis means. That is, the following code will fail:</p> <pre><code>print m.group(1) </code></pre> <p>Because there is no group 1!</p>
4
2009-10-16T09:06:53Z
[ "python", "regex", "syntax" ]
How to use ? and ?: and : in REGEX for Python?
1,576,957
<p>I understand that </p> <pre><code>* = "zero or more" ? = "zero or more" ...what's the difference? </code></pre> <p>Also, ?: &lt;&lt; my book uses this, it says its a "subtlety" but I don't know what exactly these do!</p>
2
2009-10-16T09:00:34Z
1,577,001
<p>As Manu already said, <code>?</code> means "zero or one time". It is the same as <code>{0,1}</code>.</p> <p>And by <code>?:</code>, you probably meant <code>(?:X)</code>, where X is some other string. This is called a "non-capturing group". Normally when you wrap parenthesis around something, you group what is matched by those parenthesis. For example, the regex <code>.(.).(.)</code> matches any 4 characters (except line breaks) and stores the second character in group 1 and the fourth character in group 2. However, when you do: <code>.(?:.).(.)</code> only the fourth character is stored in group 1, everything bewteen <code>(?:.)</code> is matched, but not "remembered".</p> <p>A little demo:</p> <pre><code>import re m = re.search('.(.).(.)', '1234') print m.group(1) print m.group(2) # output: # 2 # 4 m = re.search('.(?:.).(.)', '1234') print m.group(1) # output: # 4 </code></pre> <p>You might ask yourself: "why use this non-capturing group at all?". Well, sometimes, you want to make an OR between two strings, for example, you want to match the string "www.google.com" or "www.yahoo.com", you could then do: <code>www\.google\.com|www\.yahoo\.com</code>, but shorter would be: <code>www\.(google|yahoo)\.com</code> of course. But if you're not going to do something useful with what is being captured by this group (the string "google", or "yahoo"), you mind as well use a non-capturing group: <code>www\.(?:google|yahoo)\.com</code>. When the regex engine does not need to "remember" the substring "google" or "yahoo" then your app/script will run faster. Of course, it wouldn't make much difference with relatively small strings, but when your regex and string(s) gets larger, it probably will.</p> <p>And for a better example to use non-capturing groups, see Chris Lutz's comment below.</p>
3
2009-10-16T09:10:14Z
[ "python", "regex", "syntax" ]
What does this function do?
1,577,031
<pre><code>def fun1(a): for i in range(len(a)): a[i] = a[i] * a[i] return a </code></pre>
-4
2009-10-16T09:16:10Z
1,577,038
<p>It takes an array as parameter and returns the same array with each member squared.</p> <p>EDIT:</p> <p>Since you modified your question from 'What does this function do' to 'What is some code to execute this function', here is an example:</p> <pre><code>def fun1(a): for i in range(len(a)): a[i] = a[i] * a[i] return a test1 = [1,2,3,4,5] print 'Original list', test1 test2 = fun1(test1) print 'Result', test2 print 'Original list', test1 </code></pre> <p>The output will be:</p> <pre><code>Original list [1, 2, 3, 4, 5] Result [1, 4, 9, 16, 25] Original list [1, 4, 9, 16, 25] </code></pre> <p>Because the function modifies the list in place, test1 is also modified.</p>
12
2009-10-16T09:18:37Z
[ "python" ]