title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Asynchronous File Upload to Amazon S3 with Django
670,442
<p>I am using this file storage engine to store files to Amazon S3 when they are uploaded:</p> <p><a href="http://code.welldev.org/django-storages/wiki/Home">http://code.welldev.org/django-storages/wiki/Home</a></p> <p>It takes quite a long time to upload because the file must first be uploaded from client to web server, and then web server to Amazon S3 before a response is returned to the client.</p> <p>I would like to make the process of sending the file to S3 asynchronous, so the response can be returned to the user much faster. What is the best way to do this with the file storage engine?</p> <p>Thanks for your advice!</p>
32
2009-03-22T02:29:32Z
848,251
<p>It's possible to have your users upload files directly to S3 from their browser using a special form (with an encrypted policy document in a hidden field). They will be redirected back to your application once the upload completes.</p> <p>More information here: <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1434">http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1434</a></p>
22
2009-05-11T14:01:49Z
[ "python", "django", "amazon-s3" ]
Asynchronous File Upload to Amazon S3 with Django
670,442
<p>I am using this file storage engine to store files to Amazon S3 when they are uploaded:</p> <p><a href="http://code.welldev.org/django-storages/wiki/Home">http://code.welldev.org/django-storages/wiki/Home</a></p> <p>It takes quite a long time to upload because the file must first be uploaded from client to web server, and then web server to Amazon S3 before a response is returned to the client.</p> <p>I would like to make the process of sending the file to S3 asynchronous, so the response can be returned to the user much faster. What is the best way to do this with the file storage engine?</p> <p>Thanks for your advice!</p>
32
2009-03-22T02:29:32Z
5,684,245
<p>You can directly upload media to the s3 server without using your web application server. </p> <p>See the following references: </p> <p>Amazon API Reference : <a href="http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?UsingHTTPPOST.html" rel="nofollow">http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?UsingHTTPPOST.html</a></p> <p>A django implementation : <a href="https://github.com/sbc/django-uploadify-s3" rel="nofollow">https://github.com/sbc/django-uploadify-s3</a></p>
3
2011-04-16T03:11:57Z
[ "python", "django", "amazon-s3" ]
Asynchronous File Upload to Amazon S3 with Django
670,442
<p>I am using this file storage engine to store files to Amazon S3 when they are uploaded:</p> <p><a href="http://code.welldev.org/django-storages/wiki/Home">http://code.welldev.org/django-storages/wiki/Home</a></p> <p>It takes quite a long time to upload because the file must first be uploaded from client to web server, and then web server to Amazon S3 before a response is returned to the client.</p> <p>I would like to make the process of sending the file to S3 asynchronous, so the response can be returned to the user much faster. What is the best way to do this with the file storage engine?</p> <p>Thanks for your advice!</p>
32
2009-03-22T02:29:32Z
7,305,558
<p>As some of the answers here suggest uploading directly to S3, here's a Django S3 Mixin using plupload: <a href="https://github.com/burgalon/plupload-s3mixin" rel="nofollow">https://github.com/burgalon/plupload-s3mixin</a></p>
0
2011-09-05T08:28:12Z
[ "python", "django", "amazon-s3" ]
Asynchronous File Upload to Amazon S3 with Django
670,442
<p>I am using this file storage engine to store files to Amazon S3 when they are uploaded:</p> <p><a href="http://code.welldev.org/django-storages/wiki/Home">http://code.welldev.org/django-storages/wiki/Home</a></p> <p>It takes quite a long time to upload because the file must first be uploaded from client to web server, and then web server to Amazon S3 before a response is returned to the client.</p> <p>I would like to make the process of sending the file to S3 asynchronous, so the response can be returned to the user much faster. What is the best way to do this with the file storage engine?</p> <p>Thanks for your advice!</p>
32
2009-03-22T02:29:32Z
9,799,520
<p>There is an app for that :-)</p> <p><a href="https://github.com/jezdez/django-queued-storage">https://github.com/jezdez/django-queued-storage</a></p> <p>It does exactly what you need - and much more, because you can set any "local" storage and any "remote" storage. This app will store your file in fast "local" storage (for example MogileFS storage) and then using <a href="http://celeryproject.org/">Celery</a> (django-celery), will attempt asynchronous uploading to the "remote" storage.</p> <p>Few remarks:</p> <ol> <li><p>The tricky thing is - you can setup it to copy&amp;upload, or to upload&amp;delete strategy, that will delete local file once it is uploaded.</p></li> <li><p>Second tricky thing - it will serve file from "local" storage until it is not uploaded.</p></li> <li><p>It also can be configured to make number of retries on uploads failures.</p></li> </ol> <p>Installation &amp; usage is also very simple and straightforward:</p> <pre><code>pip install django-queued-storage </code></pre> <p>append to <code>INSTALLED_APPS</code>:</p> <pre><code>INSTALLED_APPS += ('queued_storage',) </code></pre> <p>in <code>models.py</code>:</p> <pre><code>from queued_storage.backends import QueuedStorage queued_s3storage = QueuedStorage( 'django.core.files.storage.FileSystemStorage', 'storages.backends.s3boto.S3BotoStorage', task='queued_storage.tasks.TransferAndDelete') class MyModel(models.Model): my_file = models.FileField(upload_to='files', storage=queued_s3storage) </code></pre>
18
2012-03-21T06:18:09Z
[ "python", "django", "amazon-s3" ]
Asynchronous File Upload to Amazon S3 with Django
670,442
<p>I am using this file storage engine to store files to Amazon S3 when they are uploaded:</p> <p><a href="http://code.welldev.org/django-storages/wiki/Home">http://code.welldev.org/django-storages/wiki/Home</a></p> <p>It takes quite a long time to upload because the file must first be uploaded from client to web server, and then web server to Amazon S3 before a response is returned to the client.</p> <p>I would like to make the process of sending the file to S3 asynchronous, so the response can be returned to the user much faster. What is the best way to do this with the file storage engine?</p> <p>Thanks for your advice!</p>
32
2009-03-22T02:29:32Z
14,830,782
<p>I encountered the same issue with uploaded images. You cannot pass along files to a Celery worker because Celery needs to be able to pickle the arguments to a task. My solution was to deconstruct the image data into a string and get all other info from the file, passing this data and info to the task, where I reconstructed the image. After that you can save it, which will send it to your storage backend (such as S3). If you want to associate the image with a model, just pass along the id of the instance to the task and retrieve it there, bind the image to the instance and save the instance. </p> <p>When a file has been uploaded via a form, it is available in your view as a UploadedFile file-like object. You can get it directly out of request.FILES, or better first bind it to your form, run is_valid and retrieve the file-like object from form.cleaned_data. At that point at least you know it is the kind of file you want it to be. After that you can get the data using read(), and get the other info using other methods/attributes. See <a href="https://docs.djangoproject.com/en/1.4/topics/http/file-uploads/" rel="nofollow">https://docs.djangoproject.com/en/1.4/topics/http/file-uploads/</a></p> <p>I actually ended up writing and distributing a little package to save an image asyncly. Have a look at <a href="https://github.com/gterzian/django_async" rel="nofollow">https://github.com/gterzian/django_async</a> Right it's just for images and you could fork it and add functionalities for your situation. I'm using it with <a href="https://github.com/duointeractive/django-athumb" rel="nofollow">https://github.com/duointeractive/django-athumb</a> and S3</p>
0
2013-02-12T10:50:19Z
[ "python", "django", "amazon-s3" ]
Line-wrapping problems with IPython shell
670,764
<p>If I have run a long line in IPython, and try and recall it (using the up-arrow) or backspace beyond the start of the current line, it displays incorrectly (all smushed into one line)</p> <p>For example, in the following session I wrote a long line <code>[1]</code>, entered a somewhat-blank line <code>[2]</code>, then up-arrowed twice to get the <code>print</code> statement on line <code>[3]</code>, and the following happened:</p> <p><img src="http://i.stack.imgur.com/jUjhy.png" alt="Line wrap issue"></p> <p>Happens in both iTerm and Terminal.app.. I had a similar problem with regular terminal sessions, which was fixed by properly terminating colour codes, but I'm not sure how to fix it with IPython</p>
10
2009-03-22T09:40:21Z
671,274
<p>I can't reproduce it:</p> <p><img src="http://i403.photobucket.com/albums/pp111/uber%5Fulrich/misc/so-misc.png" alt="up-arrow works for long lines in ipython" title="ipython up-arrow long line" /></p>
1
2009-03-22T16:49:32Z
[ "python", "terminal", "ipython" ]
Line-wrapping problems with IPython shell
670,764
<p>If I have run a long line in IPython, and try and recall it (using the up-arrow) or backspace beyond the start of the current line, it displays incorrectly (all smushed into one line)</p> <p>For example, in the following session I wrote a long line <code>[1]</code>, entered a somewhat-blank line <code>[2]</code>, then up-arrowed twice to get the <code>print</code> statement on line <code>[3]</code>, and the following happened:</p> <p><img src="http://i.stack.imgur.com/jUjhy.png" alt="Line wrap issue"></p> <p>Happens in both iTerm and Terminal.app.. I had a similar problem with regular terminal sessions, which was fixed by properly terminating colour codes, but I'm not sure how to fix it with IPython</p>
10
2009-03-22T09:40:21Z
672,755
<p>Aha! I had an old version of the Python readline module - installing the latest from <a href="http://ipython.scipy.org/dist/">http://ipython.scipy.org/dist/</a> and it works perfectly!</p> <pre><code>sudo easy_install http://ipython.scipy.org/dist/readline-2.5.1-py2.5-macosx-10.5-i386.egg </code></pre>
9
2009-03-23T09:52:26Z
[ "python", "terminal", "ipython" ]
Line-wrapping problems with IPython shell
670,764
<p>If I have run a long line in IPython, and try and recall it (using the up-arrow) or backspace beyond the start of the current line, it displays incorrectly (all smushed into one line)</p> <p>For example, in the following session I wrote a long line <code>[1]</code>, entered a somewhat-blank line <code>[2]</code>, then up-arrowed twice to get the <code>print</code> statement on line <code>[3]</code>, and the following happened:</p> <p><img src="http://i.stack.imgur.com/jUjhy.png" alt="Line wrap issue"></p> <p>Happens in both iTerm and Terminal.app.. I had a similar problem with regular terminal sessions, which was fixed by properly terminating colour codes, but I'm not sure how to fix it with IPython</p>
10
2009-03-22T09:40:21Z
3,373,928
<p>Got this problem on Snow Leopard. Installing a new version of readline from <a href="http://pypi.python.org/pypi/readline/" rel="nofollow">http://pypi.python.org/pypi/readline/</a> fixes it:</p> <pre><code>sudo easy_install http://pypi.python.org/packages/2.6/r/readline/readline-2.6.4-py2.6-macosx-10.6-universal.egg </code></pre>
2
2010-07-30T17:25:41Z
[ "python", "terminal", "ipython" ]
Getting the value of href attributes in all <a> tags on a html file with Python
671,323
<p>I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines().</p> <p>Currently I have this code that uses regex (I'm not very good at it) to search for links in every line:</p> <pre><code>for line in lines: result = re.match ('/href="(.*)"/iU', line) print result </code></pre> <p>This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening.</p> <p>Can someone give me a hint on this?</p> <p>Thanks in advance</p>
1
2009-03-22T17:22:34Z
671,334
<p>There's an HTML parser that comes standard in Python. Checkout <code>htmllib</code>.</p>
4
2009-03-22T17:28:39Z
[ "python", "html", "regex", "parsing" ]
Getting the value of href attributes in all <a> tags on a html file with Python
671,323
<p>I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines().</p> <p>Currently I have this code that uses regex (I'm not very good at it) to search for links in every line:</p> <pre><code>for line in lines: result = re.match ('/href="(.*)"/iU', line) print result </code></pre> <p>This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening.</p> <p>Can someone give me a hint on this?</p> <p>Thanks in advance</p>
1
2009-03-22T17:22:34Z
671,349
<p><a href="http://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> can do this almost trivially:</p> <pre><code>from BeautifulSoup import BeautifulSoup as soup html = soup('&lt;body&gt;&lt;a href="123"&gt;qwe&lt;/a&gt;&lt;a href="456"&gt;asd&lt;/a&gt;&lt;/body&gt;') print [tag.attrMap['href'] for tag in html.findAll('a', {'href': True})] </code></pre>
11
2009-03-22T17:43:14Z
[ "python", "html", "regex", "parsing" ]
Getting the value of href attributes in all <a> tags on a html file with Python
671,323
<p>I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines().</p> <p>Currently I have this code that uses regex (I'm not very good at it) to search for links in every line:</p> <pre><code>for line in lines: result = re.match ('/href="(.*)"/iU', line) print result </code></pre> <p>This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening.</p> <p>Can someone give me a hint on this?</p> <p>Thanks in advance</p>
1
2009-03-22T17:22:34Z
671,365
<p>Don't divide the html content into lines, as there maybe multiple matches in a single line. Also don't assume there is always quotes around the url. </p> <p>Do something like this:</p> <pre><code>links = re.finditer(' href="?([^\s^"]+)', content) for link in links: print link </code></pre>
1
2009-03-22T17:57:58Z
[ "python", "html", "regex", "parsing" ]
Getting the value of href attributes in all <a> tags on a html file with Python
671,323
<p>I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines().</p> <p>Currently I have this code that uses regex (I'm not very good at it) to search for links in every line:</p> <pre><code>for line in lines: result = re.match ('/href="(.*)"/iU', line) print result </code></pre> <p>This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening.</p> <p>Can someone give me a hint on this?</p> <p>Thanks in advance</p>
1
2009-03-22T17:22:34Z
671,372
<p>Another alternative to BeautifulSoup is lxml (<a href="http://lxml.de/" rel="nofollow">http://lxml.de/</a>);</p> <pre><code>import lxml.html links = lxml.html.parse("http://stackoverflow.com/").xpath("//a/@href") for link in links: print link </code></pre>
8
2009-03-22T18:00:18Z
[ "python", "html", "regex", "parsing" ]
Getting the value of href attributes in all <a> tags on a html file with Python
671,323
<p>I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines().</p> <p>Currently I have this code that uses regex (I'm not very good at it) to search for links in every line:</p> <pre><code>for line in lines: result = re.match ('/href="(.*)"/iU', line) print result </code></pre> <p>This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening.</p> <p>Can someone give me a hint on this?</p> <p>Thanks in advance</p>
1
2009-03-22T17:22:34Z
671,410
<p>What others haven't told you is that using regular expressions for this is not a reliable solution.<br /> Using regular expression will give you wrong results on many situations: if there are &lt;A> tags that are commented out, or if there are text in the page which include the string "href=", or if there are &lt;textarea&gt; elements with html code in it, and many others. Plus, the href attribute may exist on tags other that the anchor tag.</p> <p>What you need for this is <a href="http://en.wikipedia.org/wiki/Xpath" rel="nofollow">XPath</a>, which is a query language for DOM trees, i.e. it lets you retrieve any set of nodes satisfying the conditions you specify (HTML attributes are nodes in the DOM).<br /> XPath is a well standarized language now a days (<a href="http://www.w3.org/TR/xpath" rel="nofollow">W3C</a>), and is well supported by all major languages. I strongly suggest you use XPath and not regexp for this.<br /> adw's answer shows one example of using XPath for your particular case.</p>
3
2009-03-22T18:31:56Z
[ "python", "html", "regex", "parsing" ]
Getting the value of href attributes in all <a> tags on a html file with Python
671,323
<p>I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines().</p> <p>Currently I have this code that uses regex (I'm not very good at it) to search for links in every line:</p> <pre><code>for line in lines: result = re.match ('/href="(.*)"/iU', line) print result </code></pre> <p>This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening.</p> <p>Can someone give me a hint on this?</p> <p>Thanks in advance</p>
1
2009-03-22T17:22:34Z
671,866
<p>As previously mentioned: regex does not have the power to parse HTML. Do not use regex for parsing HTML. Do not pass Go. Do not collect £200.</p> <p>Use an HTML parser.</p> <p>But for completeness, the primary problem is:</p> <pre><code>re.match ('/href="(.*)"/iU', line) </code></pre> <p>You don't use the “/.../flags” syntax for decorating regexes in Python. Instead put the flags in a separate argument:</p> <pre><code>re.match('href="(.*)"', line, re.I|re.U) </code></pre> <p>Another problem is the greedy ‘.*’ pattern. If you have two hrefs in a line, it'll happily suck up all the content between the opening " of the first match and the closing " of the second match. You can use the non-greedy ‘.*?’ or, more simply, ‘[^"]*’ to only match up to the first closing quote.</p> <p>But don't use regexes for parsing HTML. Really.</p>
3
2009-03-23T00:14:53Z
[ "python", "html", "regex", "parsing" ]
Getting the value of href attributes in all <a> tags on a html file with Python
671,323
<p>I'm building an app in python, and I need to get the URL of all links in one webpage. I already have a function that uses urllib to download the html file from the web, and transform it to a list of strings with readlines().</p> <p>Currently I have this code that uses regex (I'm not very good at it) to search for links in every line:</p> <pre><code>for line in lines: result = re.match ('/href="(.*)"/iU', line) print result </code></pre> <p>This is not working, as it only prints "None" for every line in the file, but I'm sure that at least there are 3 links on the file I'm opening.</p> <p>Can someone give me a hint on this?</p> <p>Thanks in advance</p>
1
2009-03-22T17:22:34Z
672,508
<p>Well, just for completeness I will add here what I found to be the best answer, and I found it on the book Dive Into Python, from Mark Pilgrim.</p> <p>Here follows the code to list all URL's from a webpage:</p> <pre><code>from sgmllib import SGMLParser class URLLister(SGMLParser): def reset(self): SGMLParser.reset(self) self.urls = [] def start_a(self, attrs): href = [v for k, v in attrs if k=='href'] if href: self.urls.extend(href) import urllib, urllister usock = urllib.urlopen("http://diveintopython.net/") parser = urllister.URLLister() parser.feed(usock.read()) usock.close() parser.close() for url in parser.urls: print url </code></pre> <p>Thanks for all the replies.</p>
1
2009-03-23T07:54:07Z
[ "python", "html", "regex", "parsing" ]
QSortFilterProxyModel.mapToSource crashes. No info why
671,340
<p>I have the following code:</p> <pre><code>proxy_index = self.log_list.filter_proxy_model.createIndex(index, COL_REV) model_index = self.log_list.filter_proxy_model.mapToSource(proxy_index) revno = self.log_list.model.data(model_index,QtCore.Qt.DisplayRole) self.setEditText(revno.toString()) </code></pre> <p>The code crashed on the second line. There is no exception raised. No trace back. No warnings. How do I fix this?</p>
1
2009-03-22T17:33:05Z
671,884
<p>It may be that you're using the proxy model's createIndex() method incorrectly. Usually, the createIndex() method is called as part of a model's index() method implementation.</p> <p>Have you tried calling the proxy model's index() method to get a proxy index then mapping that to the source?</p> <p>Perhaps you could show the code in context or explain what you are trying to do.</p>
1
2009-03-23T00:22:32Z
[ "python", "qt", "qt4", "pyqt", "pyqt4" ]
QSortFilterProxyModel.mapToSource crashes. No info why
671,340
<p>I have the following code:</p> <pre><code>proxy_index = self.log_list.filter_proxy_model.createIndex(index, COL_REV) model_index = self.log_list.filter_proxy_model.mapToSource(proxy_index) revno = self.log_list.model.data(model_index,QtCore.Qt.DisplayRole) self.setEditText(revno.toString()) </code></pre> <p>The code crashed on the second line. There is no exception raised. No trace back. No warnings. How do I fix this?</p>
1
2009-03-22T17:33:05Z
1,332,267
<p>I've run into the same problem, but fortunately using the index () method instead of createIndex () as David recommends does the magic. In general it's a bad idea to mess around with the internal pointer of QModelIndex outside the index () method. Even when using your own Model messing around the internal pointer leads often to unexpected bahavior since Qts View code is pretty obscure to the user.</p>
0
2009-08-26T04:05:42Z
[ "python", "qt", "qt4", "pyqt", "pyqt4" ]
unsubscriptable object
671,363
<pre><code> im = Image.open(teh_file) if im: colors = im.resize( (1,1), Image.ANTIALIAS).getpixel((0,0)) # simple way to get average color red = colors[0] # and so on, some operations on color data </code></pre> <p>The problem is, on a few (very few, particulary don't know why those exactly, simple jpegs) I get 'unsubscriptable object' on line "colors[0]". Tried:</p> <pre><code>if colors: </code></pre> <p>gets true and goes on. </p> <pre><code>if len(colors): </code></pre> <p>gives 'len() of unsized object'</p> <ol> <li>What condition should I apply not to get this exception?</li> <li>What's the cause of the problem?</li> </ol>
1
2009-03-22T17:57:45Z
671,373
<p>From the PIL docs:</p> <pre><code>getpixel im.getpixel(xy) =&gt; value or tuple Returns the pixel at the given position. If the image is a multi-layer image, this method returns a tuple. </code></pre> <p>So it seems that some of your images are multilayer, and some are single-layer.</p>
4
2009-03-22T18:00:57Z
[ "python", "image", "image-processing", "colors", "python-imaging-library" ]
unsubscriptable object
671,363
<pre><code> im = Image.open(teh_file) if im: colors = im.resize( (1,1), Image.ANTIALIAS).getpixel((0,0)) # simple way to get average color red = colors[0] # and so on, some operations on color data </code></pre> <p>The problem is, on a few (very few, particulary don't know why those exactly, simple jpegs) I get 'unsubscriptable object' on line "colors[0]". Tried:</p> <pre><code>if colors: </code></pre> <p>gets true and goes on. </p> <pre><code>if len(colors): </code></pre> <p>gives 'len() of unsized object'</p> <ol> <li>What condition should I apply not to get this exception?</li> <li>What's the cause of the problem?</li> </ol>
1
2009-03-22T17:57:45Z
671,377
<p>As noted in another answer, <code>getpixel</code> returns either a single value, or a tuple. You could check the type and do the appropriate action in the following ways:</p> <pre><code>if isinstance(colors, tuple): color = colors[0] else: color = colors # Do other stuff </code></pre> <p>or:</p> <pre><code>try: color = colors[0] except: # Whatever the exception is - IndexError or whatever color = colors # Do other stuff </code></pre> <p>The second way is probably more Pythonic.</p>
2
2009-03-22T18:06:25Z
[ "python", "image", "image-processing", "colors", "python-imaging-library" ]
unsubscriptable object
671,363
<pre><code> im = Image.open(teh_file) if im: colors = im.resize( (1,1), Image.ANTIALIAS).getpixel((0,0)) # simple way to get average color red = colors[0] # and so on, some operations on color data </code></pre> <p>The problem is, on a few (very few, particulary don't know why those exactly, simple jpegs) I get 'unsubscriptable object' on line "colors[0]". Tried:</p> <pre><code>if colors: </code></pre> <p>gets true and goes on. </p> <pre><code>if len(colors): </code></pre> <p>gives 'len() of unsized object'</p> <ol> <li>What condition should I apply not to get this exception?</li> <li>What's the cause of the problem?</li> </ol>
1
2009-03-22T17:57:45Z
671,523
<p>Ok the case was, that when B&amp;W images have no RGB band (L band), it returns an integer with the pixel color single value, not a list of rgb values. The solution is to check bands</p> <pre><code>im.getbands() </code></pre> <p>or the simpler for my needs was:</p> <pre><code> if isinstance(colors, tuple): values = {'r':colors[0], 'g':colors[1], 'b':colors[2]} else: values = {'r':colors, 'g':colors, 'b':colors} </code></pre>
2
2009-03-22T19:43:35Z
[ "python", "image", "image-processing", "colors", "python-imaging-library" ]
Django: specifying a base template by directory
671,369
<p>I'm working on a Django site that has multiple sections and subsections. I'd like to have several depths of template inheritance: a base template for the whole site, one base template for each section that inherits from the root base template, and so on. Here's a simplified version of my desired directory structure:</p> <pre><code>base.html section1/ base.html section2/ base.html section3/ base.html </code></pre> <p>What I would desire is for all the files under <code>section1/</code> to contain something like <code>{% extends "base.html" %}</code>, meaning they would extend <code>section1/base.html</code>. <code>section1/base.html</code> would contain something like <code>{% extends "../base.html" %}</code>, meaning that it would extend the root-level base file. However, I couldn't find anything in the documentation suggesting this was possible, and I couldn't get Django to distinguish between <code>"../base.html"</code> and <code>"base.html"</code>. (<code>{% extends "../base.html" %}</code> throws an error.) I suppose one workaround would be to rename all base files <code>base_SECTIONNAME.html</code>, and update all the files that inherit from them, but I am concerned that this might become difficult to maintain as my site becomes bigger and sections change names, etc. I would prefer a solution that takes advantage of the natural hierarchy specified by directories and subdirectories.</p> <p>Any ideas?</p>
10
2009-03-22T17:59:50Z
671,378
<p>May be I oversee something, but all you want can be accomplished with the django template system. All extends calls are relative to template directories.</p> <ol> <li><p>In order for all base.html files in subdirectories to extend base.html, you just have to put a <code>{% extends "base.html" %}</code> into the files. section1/base.html would would look like that.</p> <p><code>{% extends "base.html" %}</code></p> <p><code>{# ... rest of your code ...#}</code></p></li> <li><p>Now, to get the files from section1 to extend <em>section1/base.html</em> you just have to put <code>{% extends "section1/base.html" %}</code> at the top of them. Same for section2, section3 and so on.</p></li> </ol> <p>It is just that simple, but might not totally obvious in the documentation.</p> <p>I hope, I understood your question.</p>
17
2009-03-22T18:07:15Z
[ "python", "django", "django-templates" ]
Django: specifying a base template by directory
671,369
<p>I'm working on a Django site that has multiple sections and subsections. I'd like to have several depths of template inheritance: a base template for the whole site, one base template for each section that inherits from the root base template, and so on. Here's a simplified version of my desired directory structure:</p> <pre><code>base.html section1/ base.html section2/ base.html section3/ base.html </code></pre> <p>What I would desire is for all the files under <code>section1/</code> to contain something like <code>{% extends "base.html" %}</code>, meaning they would extend <code>section1/base.html</code>. <code>section1/base.html</code> would contain something like <code>{% extends "../base.html" %}</code>, meaning that it would extend the root-level base file. However, I couldn't find anything in the documentation suggesting this was possible, and I couldn't get Django to distinguish between <code>"../base.html"</code> and <code>"base.html"</code>. (<code>{% extends "../base.html" %}</code> throws an error.) I suppose one workaround would be to rename all base files <code>base_SECTIONNAME.html</code>, and update all the files that inherit from them, but I am concerned that this might become difficult to maintain as my site becomes bigger and sections change names, etc. I would prefer a solution that takes advantage of the natural hierarchy specified by directories and subdirectories.</p> <p>Any ideas?</p>
10
2009-03-22T17:59:50Z
672,282
<p>The accepted answer will work, but I do recommend using variable names to keep track of section structure. My personal preference would be a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#writing-your-own-context-processors">context processor</a>. If, for example, your site's section organization is transparently reflected in the url, try something like:</p> <pre><code># It may be convenient to make this function live in or near your url conf. def convert_url_path_to_folder_path(path): # fill in the magic here def sub_folder_available(request): folder = convert_url_path_to_folder_path(request.path) return {'subsection': folder, 'local_base':folder+'/base.html'} </code></pre> <p>Then in your template, just call</p> <pre><code>{% extends local_base %} </code></pre> <p>There are probably a dozen other ways to do this, but the main thing is to think about avoiding hard-coding the folder name into the template. This will get you a lot of mileage, especially since you can just drag and drop template between sections if they happen to be similar enough. Another thing you might add insert is:</p> <pre><code>def sub_folder_available(request): folder = convert_url_path_to_folder_path(request.path) # Check if local base exists: if os.access(folder+'/base.html',os.F_OK): base = folder+'/base.html' else: # revert to your global base base = 'base.html' return {'subsection': folder, 'base':base} </code></pre> <p>The nice advantage of this strategy is of course that you can get a fly-weight section up and running without any local base template at all.</p>
5
2009-03-23T05:00:58Z
[ "python", "django", "django-templates" ]
Django: specifying a base template by directory
671,369
<p>I'm working on a Django site that has multiple sections and subsections. I'd like to have several depths of template inheritance: a base template for the whole site, one base template for each section that inherits from the root base template, and so on. Here's a simplified version of my desired directory structure:</p> <pre><code>base.html section1/ base.html section2/ base.html section3/ base.html </code></pre> <p>What I would desire is for all the files under <code>section1/</code> to contain something like <code>{% extends "base.html" %}</code>, meaning they would extend <code>section1/base.html</code>. <code>section1/base.html</code> would contain something like <code>{% extends "../base.html" %}</code>, meaning that it would extend the root-level base file. However, I couldn't find anything in the documentation suggesting this was possible, and I couldn't get Django to distinguish between <code>"../base.html"</code> and <code>"base.html"</code>. (<code>{% extends "../base.html" %}</code> throws an error.) I suppose one workaround would be to rename all base files <code>base_SECTIONNAME.html</code>, and update all the files that inherit from them, but I am concerned that this might become difficult to maintain as my site becomes bigger and sections change names, etc. I would prefer a solution that takes advantage of the natural hierarchy specified by directories and subdirectories.</p> <p>Any ideas?</p>
10
2009-03-22T17:59:50Z
36,059,204
<p>You can use this library: <a href="https://github.com/vb64/django.templates.relative.path" rel="nofollow">https://github.com/vb64/django.templates.relative.path</a></p> <p>Just write in your templates as follows:</p> <p>{% load relative_path %} {% extends ".base.html" %}</p> <p>this will extend template "base.html", located in the same folder, where your template placed</p> <p>{% load relative_path %} {% extends "...base.html" %}</p> <p>extend template "base.html", located at two levels higher</p> <p>same things works with 'include' tag.</p>
0
2016-03-17T11:27:47Z
[ "python", "django", "django-templates" ]
Memory efficiency: One large dictionary or a dictionary of smaller dictionaries?
671,403
<p>I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store.</p> <p>I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the smaller dictionaries.</p> <p>I know there is a lot of overhead in general with lists and dictionaries. I read somewhere that python internally allocates enough space that the dictionary/list # of items to the power of 2.</p> <p>I'm new enough to python that I'm not sure if there are other unexpected internal complexities/suprises like that, that is not apparent to the average user that I should take into consideration.</p> <p>One of the difficulties is knowing how the power of 2 system counts "items"? Is each key:pair counted as 1 item? That's seems important to know because if you have a 100 item monolithic dictionary then space 100^2 items would be allocated. If you have 100 single item dictionaries (1 key:pair) then each dictionary would only be allocation 1^2 (aka no extra allocation)?</p> <p>Any clearly laid out information would be very helpful!</p>
25
2009-03-22T18:27:48Z
671,454
<p>Often times, dictionaries of dictionaries are useful for other than performance reasons. ie, they allow you to store context information about the data without having extra fields on the objects themselves, and make querying subsets of the data faster.</p> <p>In terms of memory usage, it would stand to reason that one large dictionary will use less ram than multiple smaller ones. Remember, if you're nesting dictionaries, each additional layer of nesting will roughly double the number of dictionaries you need to allocate.</p> <p>In terms of query speed, multiple dicts will take longer due to the increased number of lookups required.</p> <p>So I think the only way to answer this question is for you to profile your own code. However, my suggestion is to use the method that makes your code the cleanest and easiest to maintain. Of all the features of Python, dictionaries are probably the most heavily tweaked for optimal performance.</p>
1
2009-03-22T19:03:03Z
[ "python", "memory", "dictionary", "performance" ]
Memory efficiency: One large dictionary or a dictionary of smaller dictionaries?
671,403
<p>I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store.</p> <p>I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the smaller dictionaries.</p> <p>I know there is a lot of overhead in general with lists and dictionaries. I read somewhere that python internally allocates enough space that the dictionary/list # of items to the power of 2.</p> <p>I'm new enough to python that I'm not sure if there are other unexpected internal complexities/suprises like that, that is not apparent to the average user that I should take into consideration.</p> <p>One of the difficulties is knowing how the power of 2 system counts "items"? Is each key:pair counted as 1 item? That's seems important to know because if you have a 100 item monolithic dictionary then space 100^2 items would be allocated. If you have 100 single item dictionaries (1 key:pair) then each dictionary would only be allocation 1^2 (aka no extra allocation)?</p> <p>Any clearly laid out information would be very helpful!</p>
25
2009-03-22T18:27:48Z
671,463
<p>If you're using Python, you really shouldn't be worrying about this sort of thing in the first place. Just build your data structure the way it best suits <em>your</em> needs, not the computer's.</p> <p>This smacks of premature optimization, not performance improvement. Profile your code if something is actually bottlenecking, but until then, just let Python do what it does and focus on the actual programming task, and not the underlying mechanics.</p>
13
2009-03-22T19:12:25Z
[ "python", "memory", "dictionary", "performance" ]
Memory efficiency: One large dictionary or a dictionary of smaller dictionaries?
671,403
<p>I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store.</p> <p>I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the smaller dictionaries.</p> <p>I know there is a lot of overhead in general with lists and dictionaries. I read somewhere that python internally allocates enough space that the dictionary/list # of items to the power of 2.</p> <p>I'm new enough to python that I'm not sure if there are other unexpected internal complexities/suprises like that, that is not apparent to the average user that I should take into consideration.</p> <p>One of the difficulties is knowing how the power of 2 system counts "items"? Is each key:pair counted as 1 item? That's seems important to know because if you have a 100 item monolithic dictionary then space 100^2 items would be allocated. If you have 100 single item dictionaries (1 key:pair) then each dictionary would only be allocation 1^2 (aka no extra allocation)?</p> <p>Any clearly laid out information would be very helpful!</p>
25
2009-03-22T18:27:48Z
671,474
<p>"Simple" is generally better than "clever", especially if you have no tested reason to go beyond "simple". And anyway "Memory efficient" is an ambiguous term, and there are tradeoffs, when you consider persisting, serializing, cacheing, swapping, and a whole bunch of other stuff that someone else has already thought through so that in most cases you don't need to.</p> <p>Think "Simplest way to handle it properly" optimize much later.</p>
6
2009-03-22T19:19:15Z
[ "python", "memory", "dictionary", "performance" ]
Memory efficiency: One large dictionary or a dictionary of smaller dictionaries?
671,403
<p>I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store.</p> <p>I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the smaller dictionaries.</p> <p>I know there is a lot of overhead in general with lists and dictionaries. I read somewhere that python internally allocates enough space that the dictionary/list # of items to the power of 2.</p> <p>I'm new enough to python that I'm not sure if there are other unexpected internal complexities/suprises like that, that is not apparent to the average user that I should take into consideration.</p> <p>One of the difficulties is knowing how the power of 2 system counts "items"? Is each key:pair counted as 1 item? That's seems important to know because if you have a 100 item monolithic dictionary then space 100^2 items would be allocated. If you have 100 single item dictionaries (1 key:pair) then each dictionary would only be allocation 1^2 (aka no extra allocation)?</p> <p>Any clearly laid out information would be very helpful!</p>
25
2009-03-22T18:27:48Z
671,476
<p>Honestly, you won't be able to tell the difference either way, in terms of either performance or memory usage. Unless you're dealing with tens of millions of items or more, the performance or memory impact is just noise.</p> <p>From the way you worded your second sentence, it sounds like the one big dictionary is your first inclination, and matches more closely with the problem you're trying to solve. If that's true, go with that. What you'll find about Python is that the solutions that everyone considers 'right' nearly always turn out to be those that are as clear and simple as possible.</p>
1
2009-03-22T19:19:59Z
[ "python", "memory", "dictionary", "performance" ]
Memory efficiency: One large dictionary or a dictionary of smaller dictionaries?
671,403
<p>I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store.</p> <p>I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the smaller dictionaries.</p> <p>I know there is a lot of overhead in general with lists and dictionaries. I read somewhere that python internally allocates enough space that the dictionary/list # of items to the power of 2.</p> <p>I'm new enough to python that I'm not sure if there are other unexpected internal complexities/suprises like that, that is not apparent to the average user that I should take into consideration.</p> <p>One of the difficulties is knowing how the power of 2 system counts "items"? Is each key:pair counted as 1 item? That's seems important to know because if you have a 100 item monolithic dictionary then space 100^2 items would be allocated. If you have 100 single item dictionaries (1 key:pair) then each dictionary would only be allocation 1^2 (aka no extra allocation)?</p> <p>Any clearly laid out information would be very helpful!</p>
25
2009-03-22T18:27:48Z
671,502
<p>Premature optimization bla bla, don't do it bla bla.</p> <p>I think you're mistaken about the <em>power</em> of two extra allocation does. I think its just a <em>multiplier</em> of two. x*2, not x^2.</p> <p>I've seen this question a few times on various python mailing lists.</p> <p>With regards to memory, here's a paraphrased version of one such discussion (the post in question wanted to store hundreds of millions integers):</p> <ol> <li>A set() is more space efficient than a dict(), if you just want to test for membership</li> <li>gmpy has a bitvector type class for storing dense sets of integers</li> <li>Dicts are kept between 50% and 30% empty, and an entry is about ~12 bytes (though the true amount will vary by platform a bit).</li> </ol> <p>So, the fewer objects you have, the less memory you're going to be using, and the fewer lookups you're going to do (since you'll have to lookup in the index, then a second lookup in the actual value).</p> <p>Like others, said, profile to see your bottlenecks. Keeping an membership set() and value dict() might be faster, but you'll be using more memory.</p> <p>I'd also suggest reposting this to a python specific list, such as comp.lang.python, which is full of much more knowledgeable people than myself who would give you all sorts of useful information.</p>
3
2009-03-22T19:36:51Z
[ "python", "memory", "dictionary", "performance" ]
Memory efficiency: One large dictionary or a dictionary of smaller dictionaries?
671,403
<p>I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store.</p> <p>I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the smaller dictionaries.</p> <p>I know there is a lot of overhead in general with lists and dictionaries. I read somewhere that python internally allocates enough space that the dictionary/list # of items to the power of 2.</p> <p>I'm new enough to python that I'm not sure if there are other unexpected internal complexities/suprises like that, that is not apparent to the average user that I should take into consideration.</p> <p>One of the difficulties is knowing how the power of 2 system counts "items"? Is each key:pair counted as 1 item? That's seems important to know because if you have a 100 item monolithic dictionary then space 100^2 items would be allocated. If you have 100 single item dictionaries (1 key:pair) then each dictionary would only be allocation 1^2 (aka no extra allocation)?</p> <p>Any clearly laid out information would be very helpful!</p>
25
2009-03-22T18:27:48Z
671,522
<p>Three suggestions:</p> <ol> <li><p><strong>Use one dictionary.</strong><br> It's easier, it's more straightforward, and someone else has already optimized this problem for you. Until you've actually measured your code and traced a performance problem to this part of it, you have no reason not to do the simple, straightforward thing.</p></li> <li><p><strong>Optimize later.</strong><br> If you are <em>really</em> worried about performance, then abstract the problem make a class to wrap whatever lookup mechanism you end up using and write your code to use this class. You can change the implementation later if you find you need some other data structure for greater performance.</p></li> <li><p><strong>Read up on hash tables.</strong><br> Dictionaries are <a href="http://en.wikipedia.org/wiki/Hash_table">hash tables</a>, and if you are worried about their time or space overhead, you should read up on how they're implemented. This is basic computer science. The short of it is that hash tables are:</p> <ul> <li>average case <strong>O(1)</strong> lookup time</li> <li><strong>O(n)</strong> space (Expect about <strong>2n</strong>, depending on various parameters)</li> </ul> <p>I do not know where you read that they were <strong>O(n^2)</strong> space, but if they were, then they would not be in widespread, practical use as they are in most languages today. There are two advantages to these nice properties of hash tables:</p> <ol> <li><strong>O(1)</strong> lookup time implies that you will not pay a cost in lookup time for having a larger dictionary, as lookup time doesn't depend on size.</li> <li><strong>O(n)</strong> space implies that you don't gain much of anything from breaking your dictionary up into smaller pieces. Space scales linearly with number of elements, so lots of small dictionaries will not take up significantly less space than one large one or vice versa. This would not be true if they were <strong>O(n^2)</strong> space, but lucky for you, they're not.</li> </ol> <p>Here are some more resources that might help:</p> <ul> <li>The <a href="http://en.wikipedia.org/wiki/Hash_table">Wikipedia article on Hash Tables</a> gives a great listing of the various lookup and allocation schemes used in hashtables.</li> <li>The <a href="http://www.gnu.org/software/mit-scheme/documentation/mit-scheme-ref/Resizing-of-Hash-Tables.html">GNU Scheme documentation</a> has a nice discussion of how much space you can expect hashtables to take up, including a formal discussion of why <em>"the amount of space used by the hash table is proportional to the number of associations in the table"</em>. This might interest you.</li> </ul> <p>Here are some things you might consider if you find you actually need to optimize your dictionary implementation:</p> <ul> <li>Here is the C source code for Python's dictionaries, in case you want ALL the details. There's copious documentation in here: <ul> <li><a href="http://svn.python.org/view/python/trunk/Include/dictobject.h?revision=59564&amp;view=markup">dictobject.h</a></li> <li><a href="http://svn.python.org/view/python/trunk/Objects/dictobject.c?revision=68128&amp;view=markup">dicobject.c</a></li> </ul></li> <li>Here is a <a href="http://pybites.blogspot.com/2008/10/pure-python-dictionary-implementation.html">python implementation</a> of that, in case you don't like reading C.<br> (Thanks to <a href="http://stackoverflow.com/users/33795/benjamin-peterson">Ben Peterson</a>)</li> <li>The <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Hashtable.html">Java Hashtable class docs</a> talk a bit about how load factors work, and how they affect the space your hash takes up. Note there's a tradeoff between your load factor and how frequently you need to <em>rehash</em>. Rehashes can be costly.</li> </ul></li> </ol>
59
2009-03-22T19:43:19Z
[ "python", "memory", "dictionary", "performance" ]
Memory efficiency: One large dictionary or a dictionary of smaller dictionaries?
671,403
<p>I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store.</p> <p>I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the smaller dictionaries.</p> <p>I know there is a lot of overhead in general with lists and dictionaries. I read somewhere that python internally allocates enough space that the dictionary/list # of items to the power of 2.</p> <p>I'm new enough to python that I'm not sure if there are other unexpected internal complexities/suprises like that, that is not apparent to the average user that I should take into consideration.</p> <p>One of the difficulties is knowing how the power of 2 system counts "items"? Is each key:pair counted as 1 item? That's seems important to know because if you have a 100 item monolithic dictionary then space 100^2 items would be allocated. If you have 100 single item dictionaries (1 key:pair) then each dictionary would only be allocation 1^2 (aka no extra allocation)?</p> <p>Any clearly laid out information would be very helpful!</p>
25
2009-03-22T18:27:48Z
801,780
<p>If your dictionary is so big that it does not fit into memory, you might want to have a look at <a href="http://www.ibm.com/developerworks/aix/library/au-zodb/" rel="nofollow">ZODB</a>, a very mature object database for Python.</p> <p>The 'root' of the db has the same interface as a dictionary, and you don't need to load the whole data structure into memory at once e.g. you can iterate over only a portion of the structure by providing start and end keys.</p> <p>It also provides transactions and versioning.</p>
4
2009-04-29T10:37:13Z
[ "python", "memory", "dictionary", "performance" ]
How to do "performance-based" (benchmark) unit testing in Python
671,503
<p>Let's say that I've got my code base to as high a degree of unit test coverage as makes sense. (Beyond a certain point, increasing coverage doesn't have a good ROI.)</p> <p>Next I want to test performance. To benchmark code to make sure that new commits aren't slowing things down needlessly. I was very intrigued by Safari's <a href="http://webkit.org/projects/performance/index.html" rel="nofollow">zero tolerance policy</a> for slowdowns from commits. I'm not sure that level of commitment to speed has a good ROI for most projects, but I'd at least like to be alerted that a speed regression has happened, and be able to make a judgment call about it.</p> <p>Environment is Python on Linux, and a suggestion that was also workable for BASH scripts would make me very happy. (But Python is the main focus.)</p>
7
2009-03-22T19:36:55Z
671,517
<p>You will want to do performance testing at a system level if possible - test your application as a whole, in context, with data and behaviour as close to production use as possible.</p> <p>This is not easy, and it will be even harder to automate it and get consistent results.</p> <p>Moreover, you can't use a VM for performance testing (unless your production environment runs in VMs, and even then, you'd need to run the VM on a host with nothing else on).</p> <p>When you say doing performance unit-testing, that may be valuable, but only if it is being used to diagnose a problem which really exists at a system level (not just in the developer's head).</p> <p>Also, performance of units in unit testing sometimes fails to reflect their performance in-context, so it may not be useful at all.</p>
7
2009-03-22T19:40:24Z
[ "python", "linux", "unit-testing", "benchmarking" ]
How to do "performance-based" (benchmark) unit testing in Python
671,503
<p>Let's say that I've got my code base to as high a degree of unit test coverage as makes sense. (Beyond a certain point, increasing coverage doesn't have a good ROI.)</p> <p>Next I want to test performance. To benchmark code to make sure that new commits aren't slowing things down needlessly. I was very intrigued by Safari's <a href="http://webkit.org/projects/performance/index.html" rel="nofollow">zero tolerance policy</a> for slowdowns from commits. I'm not sure that level of commitment to speed has a good ROI for most projects, but I'd at least like to be alerted that a speed regression has happened, and be able to make a judgment call about it.</p> <p>Environment is Python on Linux, and a suggestion that was also workable for BASH scripts would make me very happy. (But Python is the main focus.)</p>
7
2009-03-22T19:36:55Z
671,524
<p>MarkR is right... doing real-world performance testing is key, and may be somewhat dodgey in unit tests. Having said that, have a look at the <code>cProfile</code> module in the standard library. It will at least be useful for giving you a relative sense from commit-to-commit of how fast things are running, and you can run it within a unit test, though of course you'll get results in the details that include the overhead of the unit test framework itself.</p> <p>In all, though, if your objective is zero-tolerance, you'll need something much more robust than this... cProfile in a unit test won't cut it at all, and may be misleading.</p>
2
2009-03-22T19:44:06Z
[ "python", "linux", "unit-testing", "benchmarking" ]
How to do "performance-based" (benchmark) unit testing in Python
671,503
<p>Let's say that I've got my code base to as high a degree of unit test coverage as makes sense. (Beyond a certain point, increasing coverage doesn't have a good ROI.)</p> <p>Next I want to test performance. To benchmark code to make sure that new commits aren't slowing things down needlessly. I was very intrigued by Safari's <a href="http://webkit.org/projects/performance/index.html" rel="nofollow">zero tolerance policy</a> for slowdowns from commits. I'm not sure that level of commitment to speed has a good ROI for most projects, but I'd at least like to be alerted that a speed regression has happened, and be able to make a judgment call about it.</p> <p>Environment is Python on Linux, and a suggestion that was also workable for BASH scripts would make me very happy. (But Python is the main focus.)</p>
7
2009-03-22T19:36:55Z
671,921
<p>When I do performance testing, I generally have a test suite of data inputs, and measure how long it takes the program to process each one.</p> <p>You can log the performance on a daily or weekly basis, but I don't find it particularly useful to worry about performance until all the functionality is implemented.</p> <p>If performance is too poor, then I break out <a href="http://docs.python.org/library/profile.html#module-pstats" rel="nofollow">cProfile</a>, run it with the same data inputs, and try to see where the bottlenecks are.</p>
2
2009-03-23T00:46:55Z
[ "python", "linux", "unit-testing", "benchmarking" ]
How to do "performance-based" (benchmark) unit testing in Python
671,503
<p>Let's say that I've got my code base to as high a degree of unit test coverage as makes sense. (Beyond a certain point, increasing coverage doesn't have a good ROI.)</p> <p>Next I want to test performance. To benchmark code to make sure that new commits aren't slowing things down needlessly. I was very intrigued by Safari's <a href="http://webkit.org/projects/performance/index.html" rel="nofollow">zero tolerance policy</a> for slowdowns from commits. I'm not sure that level of commitment to speed has a good ROI for most projects, but I'd at least like to be alerted that a speed regression has happened, and be able to make a judgment call about it.</p> <p>Environment is Python on Linux, and a suggestion that was also workable for BASH scripts would make me very happy. (But Python is the main focus.)</p>
7
2009-03-22T19:36:55Z
2,209,270
<p>While I agree that testing performance at a system level is ultimately more relevant, if you'd like to do UnitTest style load testing for Python, FunkLoad <a href="http://funkload.nuxeo.org/" rel="nofollow">http://funkload.nuxeo.org/</a> does exactly that.</p> <p>Micro benchmarks have their place when you're trying to speed up a specific action in your codebase. And getting subsequent performance unit tests done is a useful way to ensure that this action that you just optimized does not unintentionally regress in performance upon future commits.</p>
4
2010-02-05T18:03:46Z
[ "python", "linux", "unit-testing", "benchmarking" ]
Do you have a copy of Unipath-0.2.0.tar.gz?
671,542
<p>I need a copy of this library installed on my system because my software depends on this library.</p> <p>Unfortunately, at the moment, it's impossible install it trough easy_install:</p> <pre><code>andrea@puzzle:~$ sudo easy_install Unipath [sudo] password for andrea: Searching for Unipath Reading http://pypi.python.org/simple/Unipath/ Reading http://sluggo.scrapping.cc/python/unipath/ Download error: (-2, 'Name or service not known') -- Some packages may not be found! Reading http://sluggo.scrapping.cc/python/unipath/ Download error: (-2, 'Name or service not known') -- Some packages may not be found! Best match: Unipath 0.2.0 Downloading http://sluggo.scrapping.cc/python/unipath/Unipath-0.2.0.tar.gz error: Download error for http://sluggo.scrapping.cc/python/unipath/Unipath-0.2.0.tar.gz: (-2, 'Name or service not known') </code></pre> <p>I think that something weird happened on the DNS entry of <code>sluggo.scrapping.cc</code>. How can I get this library? </p> <p>I searched for a mirror on google but I didn't find it. Do you know if there is a another place from where I can download this library?</p> <p>Or ... do you have a copy of this library and you can send it to me?</p>
0
2009-03-22T20:07:01Z
671,630
<p>I found <a href="http://groups.google.com/group/python-file-system-discuss/browse%5Fthread/thread/a421d749eff8a230/4eacafbf70b6c04b?hl=en&amp;q=unipath%2Bpython#4eacafbf70b6c04b" rel="nofollow">this</a> newsgroup post written my Mike Orr (the creator of Unipath). In the last sentence he says that he's moving the project from the <a href="http://sluggo.scrapping.cc" rel="nofollow">old server</a> to Bitbucket. So may be that the problem will be fixed when the moving is finished.</p> <p>Mike Orr message is dated March 10 2009, at the time of writing March 29 2009 I can see yet the source code on <a href="http://bitbucket.org/sluggo/unipath" rel="nofollow">http://bitbucket.org/sluggo/unipath</a></p> <p><strong>Workaround</strong></p> <p>I found an .egg file in the backup archive of old system of mine. I uploaded the file on the internet.</p> <p>But I think it solve the problem only for those people who have python 2.5. To install it use:</p> <pre><code>easy_install http://trash-cli.googlecode.com/files/Unipath-0.2.1-py2.5.egg </code></pre> <p>I hope the problem on the sluggo.scrapping.cc server would be soon fixed.</p>
0
2009-03-22T21:19:08Z
[ "python" ]
Do you have a copy of Unipath-0.2.0.tar.gz?
671,542
<p>I need a copy of this library installed on my system because my software depends on this library.</p> <p>Unfortunately, at the moment, it's impossible install it trough easy_install:</p> <pre><code>andrea@puzzle:~$ sudo easy_install Unipath [sudo] password for andrea: Searching for Unipath Reading http://pypi.python.org/simple/Unipath/ Reading http://sluggo.scrapping.cc/python/unipath/ Download error: (-2, 'Name or service not known') -- Some packages may not be found! Reading http://sluggo.scrapping.cc/python/unipath/ Download error: (-2, 'Name or service not known') -- Some packages may not be found! Best match: Unipath 0.2.0 Downloading http://sluggo.scrapping.cc/python/unipath/Unipath-0.2.0.tar.gz error: Download error for http://sluggo.scrapping.cc/python/unipath/Unipath-0.2.0.tar.gz: (-2, 'Name or service not known') </code></pre> <p>I think that something weird happened on the DNS entry of <code>sluggo.scrapping.cc</code>. How can I get this library? </p> <p>I searched for a mirror on google but I didn't find it. Do you know if there is a another place from where I can download this library?</p> <p>Or ... do you have a copy of this library and you can send it to me?</p>
0
2009-03-22T20:07:01Z
694,714
<p>I contacted the original author who confirmed me that there was a problem with the DNS entry and he's going to solve it.</p> <p>He also uploaded the latest tarball to pypi, so now you can install it with <code>easy_install Unipath</code>.</p>
0
2009-03-29T14:37:52Z
[ "python" ]
CL-WHO-like HTML templating for other languages?
671,572
<p>Common Lisp guys have their <a href="http://www.weitz.de/cl-who/" rel="nofollow">CL-WHO</a>, which makes HTML templating integrated with the "main" language thus making the task easier. For those who don't know CL-WHO, it looks like this (example from CL-WHO's webpage):</p> <pre><code>(with-html-output (*http-stream*) (:table :border 0 :cellpadding 4 (loop for i below 25 by 5 do (htm (:tr :align "right" (loop for j from i below (+ i 5) do (htm (:td :bgcolor (if (oddp j) "pink" "green") (fmt "~@R" (1+ j)))))))))) </code></pre> <p>Do you know any libraries like this for other languages? The one I know about (that mimics CL-WHO) is <a href="http://breve.twisty-industries.com/" rel="nofollow">Brevé</a> for Python. I'm particularly interested in Perl flavour, but it's interesting how other languages handle integrating HTML into their syntax.</p>
10
2009-03-22T20:31:07Z
671,595
<p>Perl's CGI module has support for something like this.</p> <pre><code>use CGI ':standard'; use Lisp::Fmt print header(); print table( { -border =&gt; 1, -cellpading =&gt; 4}, loop({ below =&gt; 25, by=&gt; 5}, sub { my $i = shift; tr( {-align =&gt; 'right'} , loop({ from =&gt; $i, below $i + 5}, sub { my $j = shift; td({-bgcolor =&gt; ($oddp eq $j ? 'pink' : 'green')} fmt("~@R", 1+$j); }) ) }); </code></pre> <p>I tried to keep it lispy, so you'll have to implement a lispy <code>loop</code> function yourself. I don't really program Common List, so I hope I understood your code correctly.</p>
5
2009-03-22T20:51:03Z
[ "python", "html", "perl", "common-lisp", "templating" ]
CL-WHO-like HTML templating for other languages?
671,572
<p>Common Lisp guys have their <a href="http://www.weitz.de/cl-who/" rel="nofollow">CL-WHO</a>, which makes HTML templating integrated with the "main" language thus making the task easier. For those who don't know CL-WHO, it looks like this (example from CL-WHO's webpage):</p> <pre><code>(with-html-output (*http-stream*) (:table :border 0 :cellpadding 4 (loop for i below 25 by 5 do (htm (:tr :align "right" (loop for j from i below (+ i 5) do (htm (:td :bgcolor (if (oddp j) "pink" "green") (fmt "~@R" (1+ j)))))))))) </code></pre> <p>Do you know any libraries like this for other languages? The one I know about (that mimics CL-WHO) is <a href="http://breve.twisty-industries.com/" rel="nofollow">Brevé</a> for Python. I'm particularly interested in Perl flavour, but it's interesting how other languages handle integrating HTML into their syntax.</p>
10
2009-03-22T20:31:07Z
671,722
<p>Perl's standard <a href="http://search.cpan.org/dist/CGI.pm/CGI.pm" rel="nofollow">CGI</a> module can do something similar:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use CGI qw/:standard/; print start_html("An example"), h1( { -align =&gt; "left", -class =&gt; "headerinfo", }, 'this is an example' ), "The CGI module has functions that add HTML:", ul( map li($_), ("start_html", "h1, h2, h3, etc.", "ol, ul, li", "ol, ul, li", "table, tr, th, td") ), "and many more.", end_html(); </code></pre> <p>That produces:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US"&gt; &lt;head&gt; &lt;title&gt;An example&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt; &lt;/head&gt; &lt;body&gt; &lt;h1 class="headerinfo" align="left"&gt;this is an example&lt;/h1&gt;The CGI module has functions that add HTML:&lt;ul&gt;&lt;li&gt;start_html&lt;/li&gt; &lt;li&gt;h1, h2, h3, etc.&lt;/li&gt; &lt;li&gt;ol, ul, li&lt;/li&gt; &lt;li&gt;ol, ul, li&lt;/li&gt; &lt;li&gt;table, tr, th, td&lt;/li&gt;&lt;/ul&gt;and many more. &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The li section could be rewritten like this</p> <pre><code>print ol(map li($_), @list); </code></pre> <p>if you had a list or an array.</p>
3
2009-03-22T22:35:54Z
[ "python", "html", "perl", "common-lisp", "templating" ]
CL-WHO-like HTML templating for other languages?
671,572
<p>Common Lisp guys have their <a href="http://www.weitz.de/cl-who/" rel="nofollow">CL-WHO</a>, which makes HTML templating integrated with the "main" language thus making the task easier. For those who don't know CL-WHO, it looks like this (example from CL-WHO's webpage):</p> <pre><code>(with-html-output (*http-stream*) (:table :border 0 :cellpadding 4 (loop for i below 25 by 5 do (htm (:tr :align "right" (loop for j from i below (+ i 5) do (htm (:td :bgcolor (if (oddp j) "pink" "green") (fmt "~@R" (1+ j)))))))))) </code></pre> <p>Do you know any libraries like this for other languages? The one I know about (that mimics CL-WHO) is <a href="http://breve.twisty-industries.com/" rel="nofollow">Brevé</a> for Python. I'm particularly interested in Perl flavour, but it's interesting how other languages handle integrating HTML into their syntax.</p>
10
2009-03-22T20:31:07Z
671,836
<p>There is <a href="http://www.kieranholland.com/code/documentation/nevow-stan/" rel="nofollow">stan</a>: <em>An s-expression-like syntax for expressing xml in pure python</em>, from <a href="http://divmod.org/trac/wiki/DivmodNevow" rel="nofollow">Divmod's Nevow</a>. I think it's kind of what you want. An example from the tutorial linked:</p> <pre><code>t = T.table[ T.tr[ T.td[ "Name:" ], T.td[ original.name ] ], T.tr[ T.td[ "Email:" ], T.td[T.a(href='mailto:%s' % original.email)[ original.email ] ] ], T.tr[ T.td[ "Password:" ], T.td[ "******" ] ], ] </code></pre>
4
2009-03-22T23:57:23Z
[ "python", "html", "perl", "common-lisp", "templating" ]
CL-WHO-like HTML templating for other languages?
671,572
<p>Common Lisp guys have their <a href="http://www.weitz.de/cl-who/" rel="nofollow">CL-WHO</a>, which makes HTML templating integrated with the "main" language thus making the task easier. For those who don't know CL-WHO, it looks like this (example from CL-WHO's webpage):</p> <pre><code>(with-html-output (*http-stream*) (:table :border 0 :cellpadding 4 (loop for i below 25 by 5 do (htm (:tr :align "right" (loop for j from i below (+ i 5) do (htm (:td :bgcolor (if (oddp j) "pink" "green") (fmt "~@R" (1+ j)))))))))) </code></pre> <p>Do you know any libraries like this for other languages? The one I know about (that mimics CL-WHO) is <a href="http://breve.twisty-industries.com/" rel="nofollow">Brevé</a> for Python. I'm particularly interested in Perl flavour, but it's interesting how other languages handle integrating HTML into their syntax.</p>
10
2009-03-22T20:31:07Z
672,064
<p>One of <a href="http://www.perlfoundation.org/" rel="nofollow">The Perl Foundation</a>'s current grant-sponsored projects (a <a href="http://www.perlfoundation.org/ilya%5Fcarl%5Fand%5Fstephen%5Fa%5Flightweight%5Fweb%5Fframework%5Ffor%5Fperl%5F6" rel="nofollow">lightweight web framework for Perl 6</a>) has working Perl6 code that <a href="http://blogs.gurulabs.com/stephen/2009/03/tagspm-for-the-perl-6-web-proj.html" rel="nofollow">provides a similar interface</a>:</p> <pre><code>use Tags; say show { html { head { title { 'Tags Demo' } } body { outs "hi"; ul :id&lt;numberlist&gt; { outs "A list from one to ten:"; for 1..10 { li :class&lt;number&gt;, { $_ } } } } } } </code></pre> <p>Browse or clone the current code on <a href="http://github.com/masak/web/tree/master" rel="nofollow">github</a>.</p>
6
2009-03-23T02:28:38Z
[ "python", "html", "perl", "common-lisp", "templating" ]
CL-WHO-like HTML templating for other languages?
671,572
<p>Common Lisp guys have their <a href="http://www.weitz.de/cl-who/" rel="nofollow">CL-WHO</a>, which makes HTML templating integrated with the "main" language thus making the task easier. For those who don't know CL-WHO, it looks like this (example from CL-WHO's webpage):</p> <pre><code>(with-html-output (*http-stream*) (:table :border 0 :cellpadding 4 (loop for i below 25 by 5 do (htm (:tr :align "right" (loop for j from i below (+ i 5) do (htm (:td :bgcolor (if (oddp j) "pink" "green") (fmt "~@R" (1+ j)))))))))) </code></pre> <p>Do you know any libraries like this for other languages? The one I know about (that mimics CL-WHO) is <a href="http://breve.twisty-industries.com/" rel="nofollow">Brevé</a> for Python. I'm particularly interested in Perl flavour, but it's interesting how other languages handle integrating HTML into their syntax.</p>
10
2009-03-22T20:31:07Z
672,665
<p>For <a href="http://search.cpan.org" rel="nofollow">CPAN</a> offerings have a look at the following (in alphabetical order)...</p> <ul> <li><a href="http://search.cpan.org/dist/Builder/" rel="nofollow">Builder</a></li> <li><a href="http://search.cpan.org/dist/HTML-Tree/lib/HTML/AsSubs.pm" rel="nofollow">HTML::AsSubs</a></li> <li><a href="http://search.cpan.org/dist/HTML-Tiny/" rel="nofollow">HTML::Tiny</a></li> <li><a href="http://search.cpan.org/dist/Markapl/" rel="nofollow">Markapl</a></li> <li><a href="http://search.cpan.org/dist/Template-Declare/" rel="nofollow">Template::Declare</a></li> <li><a href="http://search.cpan.org/dist/XML-Generator/" rel="nofollow">XML::Generator</a></li> </ul> <p>Using the table part of the CL-WHO example provided (minus Roman numerals and s/background-color/color/ to squeeze code into screen width here!)....</p> <p><br /></p> <h2>Builder</h2> <pre><code>use Builder; my $builder = Builder-&gt;new; my $h = $builder-&gt;block( 'Builder::XML' ); $h-&gt;table( { border =&gt; 0, cellpadding =&gt; 4 }, sub { for ( my $i = 1; $i &lt; 25; $i += 5 ) { $h-&gt;tr( { align =&gt; 'right' }, sub { for my $j (0..4) { $h-&gt;td( { color =&gt; $j % 2 ? 'pink' : 'green' }, $i + $j ); } }); } }); say $builder-&gt;render; </code></pre> <p><br /></p> <h2>HTML::AsSubs</h2> <pre><code>use HTML::AsSubs; my $td = sub { my $i = shift; return map { td( { color =&gt; $_ % 2 ? 'pink' : 'green' }, $i + $_ ) } 0..4; }; say table( { border =&gt; 0, cellpadding =&gt; 4 }, map { &amp;tr( { align =&gt; 'right' }, $td-&gt;( $_ ) ) } loop( below =&gt; 25, by =&gt; 5 ) )-&gt;as_HTML; </code></pre> <p><br /></p> <h2>HTML::Tiny</h2> <pre><code>use HTML::Tiny; my $h = HTML::Tiny-&gt;new; my $td = sub { my $i = shift; return map { $h-&gt;td( { 'color' =&gt; $_ % 2 ? 'pink' : 'green' }, $i + $_ ) } 0..4; }; say $h-&gt;table( { border =&gt; 0, cellpadding =&gt; 4 }, [ map { $h-&gt;tr( { align =&gt; 'right' }, [ $td-&gt;( $_ ) ] ) } loop( below =&gt; 25, by =&gt; 5 ) ] ); </code></pre> <p><br /></p> <h2>Markapl</h2> <pre><code>use Markapl; template 'MyTable' =&gt; sub { table ( border =&gt; 0, cellpadding =&gt; 4 ) { for ( my $i = 1; $i &lt; 25; $i += 5 ) { row ( align =&gt; 'right' ) { for my $j ( 0.. 4 ) { td ( color =&gt; $j % 2 ? 'pink' : 'green' ) { $i + $j } } } } } }; print main-&gt;render( 'MyTable' ); </code></pre> <p><br /></p> <h2>Template::Declare</h2> <pre><code>package MyTemplates; use Template::Declare::Tags; use base 'Template::Declare'; template 'MyTable' =&gt; sub { table { attr { border =&gt; 0, cellpadding =&gt; 4 }; for ( my $i = 1; $i &lt; 25; $i += 5 ) { row { attr { align =&gt; 'right' }; for my $j ( 0..4 ) { cell { attr { color =&gt; $j % 2 ? 'pink' : 'green' } outs $i + $j; } } } } } }; package main; use Template::Declare; Template::Declare-&gt;init( roots =&gt; ['MyTemplates'] ); print Template::Declare-&gt;show( 'MyTable' ); </code></pre> <p><br /></p> <h2>XML::Generator</h2> <pre><code>use XML::Generator; my $x = XML::Generator-&gt;new( pretty =&gt; 2 ); my $td = sub { my $i = shift; return map { $x-&gt;td( { 'color' =&gt; $_ % 2 ? 'pink' : 'green' }, $i + $_ ) } 0..4; }; say $x-&gt;table( { border =&gt; 0, cellpadding =&gt; 4 }, map { $x-&gt;tr( { align =&gt; 'right' }, $td-&gt;( $_ ) ) } loop( below =&gt; 25, by =&gt; 5 ) ); </code></pre> <p><br /> <em>And the following can be used to produce the "loop" in HTML::AsSubs / HTML::Tiny / XML::Generator examples....</em></p> <pre><code>sub loop { my ( %p ) = @_; my @list; for ( my $i = $p{start} || 1; $i &lt; $p{below}; $i += $p{by} ) { push @list, $i; } return @list; } </code></pre> <p>/I3az/</p>
11
2009-03-23T09:21:02Z
[ "python", "html", "perl", "common-lisp", "templating" ]
CL-WHO-like HTML templating for other languages?
671,572
<p>Common Lisp guys have their <a href="http://www.weitz.de/cl-who/" rel="nofollow">CL-WHO</a>, which makes HTML templating integrated with the "main" language thus making the task easier. For those who don't know CL-WHO, it looks like this (example from CL-WHO's webpage):</p> <pre><code>(with-html-output (*http-stream*) (:table :border 0 :cellpadding 4 (loop for i below 25 by 5 do (htm (:tr :align "right" (loop for j from i below (+ i 5) do (htm (:td :bgcolor (if (oddp j) "pink" "green") (fmt "~@R" (1+ j)))))))))) </code></pre> <p>Do you know any libraries like this for other languages? The one I know about (that mimics CL-WHO) is <a href="http://breve.twisty-industries.com/" rel="nofollow">Brevé</a> for Python. I'm particularly interested in Perl flavour, but it's interesting how other languages handle integrating HTML into their syntax.</p>
10
2009-03-22T20:31:07Z
693,058
<p><a href="http://elzr.com/posts/hyperscript" rel="nofollow">Here</a> is such thing for JavaScript. It looks like the following:</p> <pre><code>T.div({ className: "content"}, T.p("Some ", T.u("paragraph")), T.p("Another paragraph")) </code></pre>
1
2009-03-28T16:32:44Z
[ "python", "html", "perl", "common-lisp", "templating" ]
CL-WHO-like HTML templating for other languages?
671,572
<p>Common Lisp guys have their <a href="http://www.weitz.de/cl-who/" rel="nofollow">CL-WHO</a>, which makes HTML templating integrated with the "main" language thus making the task easier. For those who don't know CL-WHO, it looks like this (example from CL-WHO's webpage):</p> <pre><code>(with-html-output (*http-stream*) (:table :border 0 :cellpadding 4 (loop for i below 25 by 5 do (htm (:tr :align "right" (loop for j from i below (+ i 5) do (htm (:td :bgcolor (if (oddp j) "pink" "green") (fmt "~@R" (1+ j)))))))))) </code></pre> <p>Do you know any libraries like this for other languages? The one I know about (that mimics CL-WHO) is <a href="http://breve.twisty-industries.com/" rel="nofollow">Brevé</a> for Python. I'm particularly interested in Perl flavour, but it's interesting how other languages handle integrating HTML into their syntax.</p>
10
2009-03-22T20:31:07Z
693,552
<h2>Clojure</h2> <p>There are a bunch of CL-WHO-inspired HTML-generating libraries available in Clojure (as one would expect, Clojure being a Lisp). Here's how you could do it using the HTML library that comes with <a href="http://github.com/weavejester/compojure/tree/master" rel="nofollow">Compojure</a>, and <a href="http://github.com/tomfaulhaber/cl-format/tree/master" rel="nofollow">cl-format</a>:</p> <pre><code>(use 'compojure.html 'com.infolace.format) (html [:table {:border 0 :cellpadding 4} (map (fn [tds] [:tr {:align "right"} tds]) (partition 5 (map (fn [num color] [:td {:bgcolor color} (cl-format nil "~@R" (inc num))]) (range 25) (cycle ["green" "pink"]))))]) </code></pre> <p>Compojure's HTML library makes good use of Clojure's literal hash-maps as attribute/value pairs, and using literal vectors for tags instead of lists for everything helps the tags stand out a bit and avoids some of the need for macro magic.</p> <p><code>partition</code> breaks up a collection into groups of some number of elements. <code>cycle</code> generates an infinitely repeating list of the elements of a collection. These plus <code>range</code> and <code>map</code> help you avoid explicit loops and counter variables.</p>
3
2009-03-28T21:23:22Z
[ "python", "html", "perl", "common-lisp", "templating" ]
CL-WHO-like HTML templating for other languages?
671,572
<p>Common Lisp guys have their <a href="http://www.weitz.de/cl-who/" rel="nofollow">CL-WHO</a>, which makes HTML templating integrated with the "main" language thus making the task easier. For those who don't know CL-WHO, it looks like this (example from CL-WHO's webpage):</p> <pre><code>(with-html-output (*http-stream*) (:table :border 0 :cellpadding 4 (loop for i below 25 by 5 do (htm (:tr :align "right" (loop for j from i below (+ i 5) do (htm (:td :bgcolor (if (oddp j) "pink" "green") (fmt "~@R" (1+ j)))))))))) </code></pre> <p>Do you know any libraries like this for other languages? The one I know about (that mimics CL-WHO) is <a href="http://breve.twisty-industries.com/" rel="nofollow">Brevé</a> for Python. I'm particularly interested in Perl flavour, but it's interesting how other languages handle integrating HTML into their syntax.</p>
10
2009-03-22T20:31:07Z
3,313,597
<h2>Haskell</h2> <p>Haskell has an HTML combinator library that is not all that different from CL-WHO. The lazy functional approach to programming, though, does result in a much different idiomatic iteration structure than the loop facilities in Common Lisp:</p> <pre><code>import Data.Char import Data.List import Text.Html -- from http://fawcett.blogspot.com/2007/08/roman-numerals-in-haskell.html import RomanNumerals -- Simple roman numeral conversion; returns "" if it cannot convert. rom :: Int -&gt; String rom r = let m = toRoman r in (map toUpper . maybe "" id) m -- Group a list N elements at a time. -- groupN 2 [1,2,3,4,5] == [[1,2],[3,4],[5]] groupN n [] = [] groupN n xs = let (a, b) = splitAt n xs in a : (groupN n b) pink = "pink" -- for convenience below; green is already covered by Text.Html rom_table = table ! [border 0, cellpadding 4] &lt;&lt; trs where -- a list of &lt;tr&gt; entries trs = map (rom_tr . map rom_td) rom_array -- generates a &lt;tr&gt; from a list of &lt;td&gt;s rom_tr tds = tr ! [align "right"] &lt;&lt; tds -- generates a &lt;td&gt; given a numeral and a color rom_td (r, c) = td ! [bgcolor c] &lt;&lt; r -- our 5 x 5 array (list x list) of numerals and colors rom_array = (groupN 5 . take 25) rom_colors -- a theoretically infinite list of pairs of roman numerals and colors -- (practically, though, the roman numeral library has limits!) rom_colors = zip (map rom [1..]) colors -- an infinite list of alternating green and pink colors colors = cycle [green, pink] main = let s = prettyHtml rom_table in putStrLn s </code></pre> <p>I should note there's also a little combinator library in Text.Html for composing tables using "above" and "beside" operators to calculate row/column spanning, but it's a little too simplistic in terms of applying attributes to duplicate this example exactly, and we don't need the fancy splitting of rows and columns.</p>
1
2010-07-22T21:20:44Z
[ "python", "html", "perl", "common-lisp", "templating" ]
CL-WHO-like HTML templating for other languages?
671,572
<p>Common Lisp guys have their <a href="http://www.weitz.de/cl-who/" rel="nofollow">CL-WHO</a>, which makes HTML templating integrated with the "main" language thus making the task easier. For those who don't know CL-WHO, it looks like this (example from CL-WHO's webpage):</p> <pre><code>(with-html-output (*http-stream*) (:table :border 0 :cellpadding 4 (loop for i below 25 by 5 do (htm (:tr :align "right" (loop for j from i below (+ i 5) do (htm (:td :bgcolor (if (oddp j) "pink" "green") (fmt "~@R" (1+ j)))))))))) </code></pre> <p>Do you know any libraries like this for other languages? The one I know about (that mimics CL-WHO) is <a href="http://breve.twisty-industries.com/" rel="nofollow">Brevé</a> for Python. I'm particularly interested in Perl flavour, but it's interesting how other languages handle integrating HTML into their syntax.</p>
10
2009-03-22T20:31:07Z
6,444,393
<p>There's <a href="http://wiki.call-cc.org/egg/html-tags" rel="nofollow">html-tags</a>, a <a href="http://call-cc.org" rel="nofollow">Chicken Scheme</a> extension. html-tags generates either [X]HTML or SXML.</p> <p>Here's an example (using the loop extension and considering string output):</p> <pre><code>(&lt;table&gt; border: 0 cellpadding: 4 (string-intersperse (loop for i below 25 by 5 collect (&lt;tr&gt; align: "right" (string-intersperse (loop for j from i below (+ i 5) collect (&lt;td&gt; bgcolor: (if (odd? j) "pink" "green") (+ 1 j)))))))) </code></pre> <p>I'd add links to the loop and html-utils extensions (which is built on top of html-tags), but stackoverflow is considering I'm a spammer and only allows me to post a maximum of two links.</p>
1
2011-06-22T18:02:55Z
[ "python", "html", "perl", "common-lisp", "templating" ]
Is there a Python library that allows to build user interfaces without writing much code?
671,741
<p>I am writing editing front ends in Python since several years now, and I am fed up with micromanaging every UI detail of a window or dialog every single time.</p> <p>Is there a technology that allows me to, say, specify the relations between a GTK+ Glade-designed interface and the tables and records of an SQLite database to do all the middle man work? It should spare me the work of manually writing event handlers, input evaluators and view updates.</p> <p>The technologies in question are just examples, but I want to stick with Python as far as possible.</p>
7
2009-03-22T22:49:11Z
671,752
<p>PyQt and its models can automate some of these tasks for you (to some amount off course, e.g. filling widgets with data from a database and handling most of the widgets behaviour, buffering etc.).</p> <p>If you want a more object-oriented approach to handling SQL you could look into an ORM-oriented solution (for example SQLAlchemy).</p>
4
2009-03-22T22:58:54Z
[ "python", "user-interface", "sqlite", "gtk", "glade" ]
Is there a Python library that allows to build user interfaces without writing much code?
671,741
<p>I am writing editing front ends in Python since several years now, and I am fed up with micromanaging every UI detail of a window or dialog every single time.</p> <p>Is there a technology that allows me to, say, specify the relations between a GTK+ Glade-designed interface and the tables and records of an SQLite database to do all the middle man work? It should spare me the work of manually writing event handlers, input evaluators and view updates.</p> <p>The technologies in question are just examples, but I want to stick with Python as far as possible.</p>
7
2009-03-22T22:49:11Z
671,849
<p><a href="http://en.wikipedia.org/wiki/WxGlade" rel="nofollow">wxGlade</a> may help, although I haven't used it myself so I don't speak from experience.</p> <p><a href="http://en.wikipedia.org/wiki/Boa%5Fconstructor" rel="nofollow">Boa Constructor</a> apparently has a wxPython GUI builder in it, and there is also <a href="http://pythoncard.sourceforge.net/" rel="nofollow">PythonCard</a>, though development on these two projects seems to have stalled.</p>
1
2009-03-23T00:04:16Z
[ "python", "user-interface", "sqlite", "gtk", "glade" ]
Is there a Python library that allows to build user interfaces without writing much code?
671,741
<p>I am writing editing front ends in Python since several years now, and I am fed up with micromanaging every UI detail of a window or dialog every single time.</p> <p>Is there a technology that allows me to, say, specify the relations between a GTK+ Glade-designed interface and the tables and records of an SQLite database to do all the middle man work? It should spare me the work of manually writing event handlers, input evaluators and view updates.</p> <p>The technologies in question are just examples, but I want to stick with Python as far as possible.</p>
7
2009-03-22T22:49:11Z
671,911
<p><a href="http://dabodev.com/" rel="nofollow">Dabo</a> is built on top of wxPython, so you may not prefer it, but it's designed to make it easy to tie a GUI to a database, so I'd recommend you check it out if you haven't already. In particular, it's got good facilities for tying widgets to data, and handling a lot of the common cases of GUI development.</p>
4
2009-03-23T00:37:12Z
[ "python", "user-interface", "sqlite", "gtk", "glade" ]
Is there a Python library that allows to build user interfaces without writing much code?
671,741
<p>I am writing editing front ends in Python since several years now, and I am fed up with micromanaging every UI detail of a window or dialog every single time.</p> <p>Is there a technology that allows me to, say, specify the relations between a GTK+ Glade-designed interface and the tables and records of an SQLite database to do all the middle man work? It should spare me the work of manually writing event handlers, input evaluators and view updates.</p> <p>The technologies in question are just examples, but I want to stick with Python as far as possible.</p>
7
2009-03-22T22:49:11Z
672,093
<p>Besides the ones already mentioned I can add:</p> <ul> <li><a href="http://www.async.com.br/projects/kiwi/api/kiwi.html" rel="nofollow">Kiwi</a></li> <li><a href="http://www.uxpython.com/" rel="nofollow">uxpython</a></li> <li><a href="http://www.pygtk.org/" rel="nofollow">pygtk</a></li> <li><a href="http://code.google.com/p/treethon/" rel="nofollow">treethon</a></li> </ul> <p>I've never used any of them so have no recommendations but, for what it's worth, I have used at least 2 complex programs built directly on pygtk that worked in both Windows and Linux.</p> <p>I think Kiwi is the only one of these with baked in support for db (through interface with SQLAlchemy, SQLObject, or Storm) but I would be surprised if you couldn't use one of those ORM's inside any of the other frameworks.</p>
5
2009-03-23T02:53:13Z
[ "python", "user-interface", "sqlite", "gtk", "glade" ]
Is there a Python library that allows to build user interfaces without writing much code?
671,741
<p>I am writing editing front ends in Python since several years now, and I am fed up with micromanaging every UI detail of a window or dialog every single time.</p> <p>Is there a technology that allows me to, say, specify the relations between a GTK+ Glade-designed interface and the tables and records of an SQLite database to do all the middle man work? It should spare me the work of manually writing event handlers, input evaluators and view updates.</p> <p>The technologies in question are just examples, but I want to stick with Python as far as possible.</p>
7
2009-03-22T22:49:11Z
677,952
<p>Traits might be a good option for you. <a href="http://code.enthought.com/projects/traits/docs/html/TUIUG/index.html" rel="nofollow">http://code.enthought.com/projects/traits/docs/html/TUIUG/index.html</a></p> <p>AS simple as it is to map a UI to an object, it doesn't seem too far fetched to incorporate SQLAlchemy for persistence. </p>
1
2009-03-24T15:34:32Z
[ "python", "user-interface", "sqlite", "gtk", "glade" ]
Is there a Python library that allows to build user interfaces without writing much code?
671,741
<p>I am writing editing front ends in Python since several years now, and I am fed up with micromanaging every UI detail of a window or dialog every single time.</p> <p>Is there a technology that allows me to, say, specify the relations between a GTK+ Glade-designed interface and the tables and records of an SQLite database to do all the middle man work? It should spare me the work of manually writing event handlers, input evaluators and view updates.</p> <p>The technologies in question are just examples, but I want to stick with Python as far as possible.</p>
7
2009-03-22T22:49:11Z
678,000
<p>I had lots of success with wxPython, but that was some years ago now and there may be better new solutions...</p>
0
2009-03-24T15:43:44Z
[ "python", "user-interface", "sqlite", "gtk", "glade" ]
Is there a Python library that allows to build user interfaces without writing much code?
671,741
<p>I am writing editing front ends in Python since several years now, and I am fed up with micromanaging every UI detail of a window or dialog every single time.</p> <p>Is there a technology that allows me to, say, specify the relations between a GTK+ Glade-designed interface and the tables and records of an SQLite database to do all the middle man work? It should spare me the work of manually writing event handlers, input evaluators and view updates.</p> <p>The technologies in question are just examples, but I want to stick with Python as far as possible.</p>
7
2009-03-22T22:49:11Z
691,567
<p>There is a good book on wxPython, "wxPython in Action", which can't be said for some of the other solutions. No knock on the others. I've had success developing with wxPython in the past and it comes with a great set of demo applications with source code from which you can borrow liberally.</p> <p>The best UI designer I found for wxPython applications is a commercial one, Anthemion DialogBlocks. It's by one of the wxPython programmers and is worth the money. Other solutions for UI design include wxGlade (I found it usable but not featureful) and Boa Constructor (haven't used it). Wing IDE might also have one. Stani's Python Editor bundles wxGlade, I believe. There are a lot of other projects that don't really work or are fairly old.</p> <p>As far as SQL automation goes, as another answerer says, I'd look at SQL alchemy, but the learning curve for a small application might be too much and you'd be better off just going straight to odbc. The best odbc api is the one used by Django, pyodbc.</p> <p>It's been a while since I developed with these tools, so there may be something newer for each, but at the time these were definitely the best of breed in my opinion.</p>
1
2009-03-27T21:41:51Z
[ "python", "user-interface", "sqlite", "gtk", "glade" ]
Is there a Python library that allows to build user interfaces without writing much code?
671,741
<p>I am writing editing front ends in Python since several years now, and I am fed up with micromanaging every UI detail of a window or dialog every single time.</p> <p>Is there a technology that allows me to, say, specify the relations between a GTK+ Glade-designed interface and the tables and records of an SQLite database to do all the middle man work? It should spare me the work of manually writing event handlers, input evaluators and view updates.</p> <p>The technologies in question are just examples, but I want to stick with Python as far as possible.</p>
7
2009-03-22T22:49:11Z
765,138
<p>Ok this is an unconventional solution but write yourself a code generator. I have done this several times using <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a>. So in my case I auto inspect a table which columns it contains and types and generate classes from that. It's more work upfront but does exactly what you want and is reusable in subsequent projects.</p>
0
2009-04-19T09:39:09Z
[ "python", "user-interface", "sqlite", "gtk", "glade" ]
Using python map and other functional tools
672,172
<p>This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:</p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars) </code></pre> <p>produces:</p> <pre><code>1.0 1 2.0 2 3.0 3 4.0 None 5.0 None </code></pre> <p><strong>Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc.</strong></p> <pre><code>1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3] </code></pre> <p><strong>Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g.</strong></p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5] </code></pre> <p><strong>and print:</strong></p> <pre><code>1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ... </code></pre> <p><strong>P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?</strong></p>
119
2009-03-23T03:46:29Z
672,176
<p>Would this do it?</p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest2(bar): print bar def maptest(foo): print foo map(maptest2, bars) map(maptest, foos) </code></pre>
0
2009-03-23T03:51:03Z
[ "python", "dictionary", "functional-programming" ]
Using python map and other functional tools
672,172
<p>This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:</p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars) </code></pre> <p>produces:</p> <pre><code>1.0 1 2.0 2 3.0 3 4.0 None 5.0 None </code></pre> <p><strong>Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc.</strong></p> <pre><code>1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3] </code></pre> <p><strong>Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g.</strong></p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5] </code></pre> <p><strong>and print:</strong></p> <pre><code>1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ... </code></pre> <p><strong>P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?</strong></p>
119
2009-03-23T03:46:29Z
672,197
<p>Here's the solution you're looking for:</p> <pre><code>&gt;&gt;&gt; foos = [1.0, 2.0, 3.0, 4.0, 5.0] &gt;&gt;&gt; bars = [1, 2, 3] &gt;&gt;&gt; [(x, bars) for x in foos] [(1.0, [1, 2, 3]), (2.0, [1, 2, 3]), (3.0, [1, 2, 3]), (4.0, [1, 2, 3]), (5.0, [ 1, 2, 3])] </code></pre> <p>I'd recommend using a list comprehension (the <code>[(x, bars) for x in foos]</code> part) over using map as it avoids the overhead of a function call on every iteration (which can be very significant). If you're just going to use it in a for loop, you'll get better speeds by using a generator comprehension:</p> <pre><code>&gt;&gt;&gt; y = ((x, bars) for x in foos) &gt;&gt;&gt; for z in y: ... print z ... (1.0, [1, 2, 3]) (2.0, [1, 2, 3]) (3.0, [1, 2, 3]) (4.0, [1, 2, 3]) (5.0, [1, 2, 3]) </code></pre> <p>The difference is that the generator comprehension is <a href="http://en.wikipedia.org/wiki/Lazy%5Floading">lazily loaded</a>.</p> <p><strong>UPDATE</strong> In response to this comment:</p> <blockquote> <p>Of course you know, that you don't copy bars, all entries are the same bars list. So if you modify any one of them (including original bars), you modify all of them.</p> </blockquote> <p>I suppose this is a valid point. There are two solutions to this that I can think of. The most efficient is probably something like this:</p> <pre><code>tbars = tuple(bars) [(x, tbars) for x in foos] </code></pre> <p>Since tuples are immutable, this will prevent bars from being modified through the results of this list comprehension (or generator comprehension if you go that route). If you really need to modify each and every one of the results, you can do this:</p> <pre><code>from copy import copy [(x, copy(bars)) for x in foos] </code></pre> <p>However, this can be a bit expensive both in terms of memory usage and in speed, so I'd recommend against it unless you really need to add to each one of them.</p>
30
2009-03-23T04:00:28Z
[ "python", "dictionary", "functional-programming" ]
Using python map and other functional tools
672,172
<p>This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:</p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars) </code></pre> <p>produces:</p> <pre><code>1.0 1 2.0 2 3.0 3 4.0 None 5.0 None </code></pre> <p><strong>Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc.</strong></p> <pre><code>1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3] </code></pre> <p><strong>Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g.</strong></p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5] </code></pre> <p><strong>and print:</strong></p> <pre><code>1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ... </code></pre> <p><strong>P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?</strong></p>
119
2009-03-23T03:46:29Z
672,198
<p>The easiest way would be not to pass <code>bars</code> through the different functions, but to access it directly from <code>maptest</code>:</p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo): print foo, bars map(maptest, foos) </code></pre> <p>With your original <code>maptest</code> function you could also use a lambda function in <code>map</code>:</p> <pre><code>map((lambda foo: maptest(foo, bars)), foos) </code></pre>
52
2009-03-23T04:00:28Z
[ "python", "dictionary", "functional-programming" ]
Using python map and other functional tools
672,172
<p>This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:</p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars) </code></pre> <p>produces:</p> <pre><code>1.0 1 2.0 2 3.0 3 4.0 None 5.0 None </code></pre> <p><strong>Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc.</strong></p> <pre><code>1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3] </code></pre> <p><strong>Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g.</strong></p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5] </code></pre> <p><strong>and print:</strong></p> <pre><code>1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ... </code></pre> <p><strong>P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?</strong></p>
119
2009-03-23T03:46:29Z
672,216
<pre><code>import itertools foos=[1.0, 2.0, 3.0, 4.0, 5.0] bars=[1, 2, 3] print zip(foos, itertools.cycle([bars])) </code></pre>
11
2009-03-23T04:17:28Z
[ "python", "dictionary", "functional-programming" ]
Using python map and other functional tools
672,172
<p>This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:</p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars) </code></pre> <p>produces:</p> <pre><code>1.0 1 2.0 2 3.0 3 4.0 None 5.0 None </code></pre> <p><strong>Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc.</strong></p> <pre><code>1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3] </code></pre> <p><strong>Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g.</strong></p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5] </code></pre> <p><strong>and print:</strong></p> <pre><code>1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ... </code></pre> <p><strong>P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?</strong></p>
119
2009-03-23T03:46:29Z
672,222
<pre><code>&gt;&gt;&gt; from itertools import repeat &gt;&gt;&gt; for foo, bars in zip(foos, repeat(bars)): ... print foo, bars ... 1.0 [1, 2, 3] 2.0 [1, 2, 3] 3.0 [1, 2, 3] 4.0 [1, 2, 3] 5.0 [1, 2, 3] </code></pre>
12
2009-03-23T04:21:19Z
[ "python", "dictionary", "functional-programming" ]
Using python map and other functional tools
672,172
<p>This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:</p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars) </code></pre> <p>produces:</p> <pre><code>1.0 1 2.0 2 3.0 3 4.0 None 5.0 None </code></pre> <p><strong>Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc.</strong></p> <pre><code>1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3] </code></pre> <p><strong>Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g.</strong></p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5] </code></pre> <p><strong>and print:</strong></p> <pre><code>1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ... </code></pre> <p><strong>P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?</strong></p>
119
2009-03-23T03:46:29Z
672,230
<p>Here's an overview of the parameters to the <code>map(function, *sequences)</code> function:</p> <ul> <li><code>function</code> is the name of your function.</li> <li><code>sequences</code> is any number of sequences, which are usually lists or tuples. <code>map</code> will iterate over them <em>simultaneously</em> and give the current values to <code>function</code>. That's why the number of sequences should equal the number of parameters to your function.</li> </ul> <p>It sounds like you're trying to iterate for some of <code>function</code>'s parameters but keep others constant, and unfortunately <code>map</code> doesn't support that. I found <a href="http://mail.python.org/pipermail/python-dev/2003-February/033486.html">an old proposal</a> to add such a feature to Python, but the map construct is so clean and well-established that I doubt something like that will ever be implemented.</p> <p>Use a workaround like global variables or list comprehensions, as others have suggested.</p>
6
2009-03-23T04:24:48Z
[ "python", "dictionary", "functional-programming" ]
Using python map and other functional tools
672,172
<p>This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:</p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars) </code></pre> <p>produces:</p> <pre><code>1.0 1 2.0 2 3.0 3 4.0 None 5.0 None </code></pre> <p><strong>Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc.</strong></p> <pre><code>1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3] </code></pre> <p><strong>Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g.</strong></p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5] </code></pre> <p><strong>and print:</strong></p> <pre><code>1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ... </code></pre> <p><strong>P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?</strong></p>
119
2009-03-23T03:46:29Z
672,296
<p>Are you familiar with other functional languages? i.e. are you trying to learn how python does functional programming, or are you trying to learn about functional programming and using python as the vehicle?</p> <p>Also, do you understand list comprehensions?</p> <pre><code>map(f, sequence) </code></pre> <p>is directly equivalent (*) to:</p> <pre><code>[f(x) for x in sequence] </code></pre> <p>In fact, I think <code>map()</code> was once slated for removal from python 3.0 as being redundant (that didn't happen).</p> <pre><code>map(f, sequence1, sequence2) </code></pre> <p>is mostly equivalent to:</p> <pre><code>[f(x1, x2) for x1, x2 in zip(sequence1, sequence2)] </code></pre> <p>(there is a difference in how it handles the case where the sequences are of different length. As you saw, <code>map()</code> fills in None when one of the sequences runs out, whereas <code>zip()</code> stops when the shortest sequence stops)</p> <p>So, to address your specific question, you're trying to produce the result:</p> <pre><code>foos[0], bars foos[1], bars foos[2], bars # etc. </code></pre> <p>You could do this by writing a function that takes a single argument and prints it, followed by bars:</p> <pre><code>def maptest(x): print x, bars map(maptest, foos) </code></pre> <p>Alternatively, you could create a list that looks like this:</p> <pre><code>[bars, bars, bars, ] # etc. </code></pre> <p>and use your original maptest:</p> <pre><code>def maptest(x, y): print x, y </code></pre> <p>One way to do this would be to explicitely build the list beforehand:</p> <pre><code>barses = [bars] * len(foos) map(maptest, foos, barses) </code></pre> <p>Alternatively, you could pull in the <code>itertools</code> module. <code>itertools</code> contains many clever functions that help you do functional-style lazy-evaluation programming in python. In this case, we want <code>itertools.repeat</code>, which will output its argument indefinitely as you iterate over it. This last fact means that if you do:</p> <pre><code>map(maptest, foos, itertools.repeat(bars)) </code></pre> <p>you will get endless output, since <code>map()</code> keeps going as long as one of the arguments is still producing output. However, <code>itertools.imap</code> is just like <code>map()</code>, but stops as soon as the shortest iterable stops.</p> <pre><code>itertools.imap(maptest, foos, itertools.repeat(bars)) </code></pre> <p>Hope this helps :-)</p> <p>(*) It's a little different in python 3.0. There, map() essentially returns a generator expression.</p>
188
2009-03-23T05:11:47Z
[ "python", "dictionary", "functional-programming" ]
Using python map and other functional tools
672,172
<p>This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:</p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars) </code></pre> <p>produces:</p> <pre><code>1.0 1 2.0 2 3.0 3 4.0 None 5.0 None </code></pre> <p><strong>Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc.</strong></p> <pre><code>1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3] </code></pre> <p><strong>Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g.</strong></p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5] </code></pre> <p><strong>and print:</strong></p> <pre><code>1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ... </code></pre> <p><strong>P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?</strong></p>
119
2009-03-23T03:46:29Z
672,469
<p>Functional programming is about creating side-effect-free code.</p> <p>map is a functional list transformation abstraction. You use it to take a sequence of something and turn it into a sequence of something else.</p> <p>You are trying to use it as an iterator. Don't do that. :)</p> <p>Here is an example of how you might use map to build the list you want. There are shorter solutions (I'd just use comprehensions), but this will help you understand what map does a bit better:</p> <pre><code>def my_transform_function(input): return [input, [1, 2, 3]] new_list = map(my_transform, input_list) </code></pre> <p>Notice at this point, you've only done a data manipulation. Now you can print it:</p> <pre><code>for n,l in new_list: print n, ll </code></pre> <p>-- I'm not sure what you mean by 'without loops.' fp isn't about avoiding loops (you can't examine every item in a list without visiting each one). It's about avoiding side-effects, thus writing fewer bugs.</p>
18
2009-03-23T07:28:29Z
[ "python", "dictionary", "functional-programming" ]
Using python map and other functional tools
672,172
<p>This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:</p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars) </code></pre> <p>produces:</p> <pre><code>1.0 1 2.0 2 3.0 3 4.0 None 5.0 None </code></pre> <p><strong>Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc.</strong></p> <pre><code>1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3] </code></pre> <p><strong>Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g.</strong></p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5] </code></pre> <p><strong>and print:</strong></p> <pre><code>1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ... </code></pre> <p><strong>P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?</strong></p>
119
2009-03-23T03:46:29Z
18,649,750
<p>How about this:</p> <pre><code>foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, [bars]*len(foos)) </code></pre>
0
2013-09-06T04:11:41Z
[ "python", "dictionary", "functional-programming" ]
Django Custom Queryset filters
672,182
<p>Is there, in Django, a standard way to write complex, custom filters for QuerySets?</p> <p>Just as I can write </p> <pre><code>MyClass.objects.all().filter(field=val) </code></pre> <p>I'd like to do something like this :</p> <pre><code>MyClass.objects.all().filter(customFilter) </code></pre> <p>I could use a generator expression </p> <pre><code>(x for x in MyClass.objects.all() if customFilter(x)) </code></pre> <p>but that would lose the chainability and whatever other functions the QuerySets provide.</p>
6
2009-03-23T03:53:41Z
672,193
<p>I think you may need custom <a href="https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers" rel="nofollow">managers</a>.</p>
5
2009-03-23T03:58:12Z
[ "python", "django", "django-queryset", "generator-expression" ]
Django Custom Queryset filters
672,182
<p>Is there, in Django, a standard way to write complex, custom filters for QuerySets?</p> <p>Just as I can write </p> <pre><code>MyClass.objects.all().filter(field=val) </code></pre> <p>I'd like to do something like this :</p> <pre><code>MyClass.objects.all().filter(customFilter) </code></pre> <p>I could use a generator expression </p> <pre><code>(x for x in MyClass.objects.all() if customFilter(x)) </code></pre> <p>but that would lose the chainability and whatever other functions the QuerySets provide.</p>
6
2009-03-23T03:53:41Z
673,180
<p>The recommendation to start using manager methods is a good one, but to answer your question more directly: yes, use <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects">Q objects</a>. For example:</p> <pre><code>from django.db.models import Q complexQuery = Q(name__startswith='Xa') | ~Q(birthdate__year=2000) MyModel.objects.filter(complexQuery) </code></pre> <p>Q objects can be combined with | (OR), &amp; (AND), and ~ (NOT).</p>
12
2009-03-23T12:21:14Z
[ "python", "django", "django-queryset", "generator-expression" ]
How do you send AT GSM commands using python?
672,366
<p>How do i send AT GSM commands using python?</p> <p>Am able to do this quite easily using Delphi and some comport component (TComport), but how do i talk to my modem using python?</p> <p>Gath</p>
9
2009-03-23T06:11:02Z
672,434
<p>I don't know if there is an AT module, but you can use <a href="http://pyserial.sourceforge.net/" rel="nofollow">pyserial</a> to communicate with a serial port.</p>
4
2009-03-23T06:59:32Z
[ "python", "modem" ]
How do you send AT GSM commands using python?
672,366
<p>How do i send AT GSM commands using python?</p> <p>Am able to do this quite easily using Delphi and some comport component (TComport), but how do i talk to my modem using python?</p> <p>Gath</p>
9
2009-03-23T06:11:02Z
672,448
<p>I do it like this with pyserial:</p> <pre><code>import serial serialPort = serial.Serial(port=1,baudrate=115200,timeout=0,rtscts=0,xonxoff=0) def sendatcmd(cmd): serialPort.write('at'+cmd+'\r') print 'Loading profile...', sendatcmd('+npsda=0,2') </code></pre> <p>Then I listen for an answer...</p>
16
2009-03-23T07:08:33Z
[ "python", "modem" ]
Python Programming - Rules/Advice for developing enterprise-level software in Python?
672,781
<p>I'm a somewhat advanced C++/Java Developer who recently became interested in Python and I enjoy its dynamic typing and efficient coding style very much. I currently use it on my small programming needs like solving programming riddles and scripting, but I'm curious if anyone out there has successfully used Python in an enterprise-quality project? (Preferably using modern programming concepts such as OOP and some type of Design Pattern)</p> <p>If so, would you please explain <strong>why</strong> you chose Python <em>(specifically)</em> and give us some of the <strong>lessons</strong> you learned from this project? (Feel free to compare the use of Python in the project vs Java or etc)</p>
7
2009-03-23T09:59:44Z
672,806
<p>I've been using Python as distributed computing framework in one of the worlds largest banks. It was chosen because:</p> <ul> <li>It had to be extremely fast for developing and deploying new functionalities;</li> <li>It had to be easily integrable with C and C++; </li> <li>Some parts of the code were to be written by people whose area of expertise was mathematical modeling, not software development.</li> </ul>
3
2009-03-23T10:06:25Z
[ "java", "python", "design-patterns", "programming-languages", "dynamic-typing" ]
Python Programming - Rules/Advice for developing enterprise-level software in Python?
672,781
<p>I'm a somewhat advanced C++/Java Developer who recently became interested in Python and I enjoy its dynamic typing and efficient coding style very much. I currently use it on my small programming needs like solving programming riddles and scripting, but I'm curious if anyone out there has successfully used Python in an enterprise-quality project? (Preferably using modern programming concepts such as OOP and some type of Design Pattern)</p> <p>If so, would you please explain <strong>why</strong> you chose Python <em>(specifically)</em> and give us some of the <strong>lessons</strong> you learned from this project? (Feel free to compare the use of Python in the project vs Java or etc)</p>
7
2009-03-23T09:59:44Z
672,975
<p>I'm using Python for developing a complex insurance underwriting application.</p> <p>Our application software essentially repackages our actuarial model in a form that companies can subscribe to it. This business is based on our actuaries and their deep thinking. We're not packaging a clever algorithm that's relatively fixed. We're renting our actuarial brains to customers via a web service.</p> <ol> <li><p>The actuaries must be free to make changes as they gain deeper insight into the various factors that lead to claims.</p> <ul> <li><p>Static languages (Java, C++, C#) lead to early lock-in to a data model.</p></li> <li><p>Python allows us to have a very flexible data model. They're free to add, change or delete factors or information sources without a lot of development cost and complexity. Duck typing allows us to introduce new pieces without a lot rework.</p></li> </ul></li> <li><p>Our software is a service (not a package) so we have an endless integration problem.</p> <ul> <li><p>Static languages need complex mapping components. Often some kind of configurable, XML-driven mapping from customer messages to our ever-changing internal structures.</p></li> <li><p>Python allows us to have the mappings as a simple Python class definition that we simply tweak, test and put into production. There are no limitations on this module -- it's first-class Python code.</p></li> </ul></li> <li><p>We have to do extensive, long-running proof-of-concept. These involve numerous "what-if" scenarios with different data feeds and customized features.</p> <ul> <li><p>Static languages require a lot of careful planning and thinking to create yet another demo, yet another mapping from yet another customer-supplied file to the current version of our actuarial models.</p></li> <li><p>Python requires much less planning. Duck typing (and Django) let us knock out a demo without very much pain. The data mappings are simple python class definitions; our actuarial models are in a fairly constant state of flux.</p></li> </ul></li> <li><p>Our business model is subject to a certain amount of negotiation. We have rather complex contracts with information providers; these don't change as often as the actuarial model, but changes here require customization.</p> <ul> <li><p>Static languages bind in assumptions about the contracts, and require fairly complex designs (or workarounds) to handle the brain-farts of the business folks negotiating the deals.</p></li> <li><p>In Python, we use an extensive test suite and do a lot of refactoring as the various contract terms and conditions trickle down to us. </p></li> </ul> <p>Every week we get a question like "Can we handle a provision like X?" Our standard answer is "Absolutely." Followed by an hour of refactoring to be sure we <em>could</em> handle it if the deal was struck in that form.</p></li> <li><p>We're mostly a RESTful web service. Django does a lot of this out of the box. We had to write some extensions because our security model is a bit more strict than the one provided by Django. </p> <ul> <li><p>Static languages don't have to ship source. Don't like the security model? Pay the vendor $$$.</p></li> <li><p>Dynamic languages must ship as source. In our case, we spend time reading the source of Django carefully to make sure that our security model fits cleanly with the rest of Django. We don't <em>need</em> HIPAA compliance, but we're building it in anyway. </p></li> </ul></li> <li><p>We use web services from information providers. urllib2 does this for us nicely. We can prototype an interface rapidly. </p> <ul> <li><p>With a static language, you have API's, you write, you run, and you hope it worked. The development cycle is Edit, Compile, Build, Run, Crash, Look at Logs; and this is just to spike the interface and be sure we have the protocol, credentials and configuration right.</p></li> <li><p>We exercise the interface in interactive Python. Since we're executing it interactively, we can examine the responses immediately. The development cycle is reduced to Run, Edit. We can spike a web services API in an afternoon.</p></li> </ul></li> </ol>
16
2009-03-23T11:11:11Z
[ "java", "python", "design-patterns", "programming-languages", "dynamic-typing" ]
File dialogs of Tkinter in Python 3?
673,174
<p>I want to select a file from a dialog box. <a href="http://www.java2s.com/Code/Python/GUI-Tk/Fileopendialog.htm">Here</a> is code that does all I need, but when I run it: </p> <p><code>ImportError: No module named 'tkMessageBox'</code> </p> <p>How can I make this example work with Python 3?</p>
13
2009-03-23T12:20:01Z
673,309
<p>The package <code>Tkinter</code> has been renamed to <code>tkinter</code> in Python 3, as well as other modules related to it. Here are the name changes:</p> <ul> <li><code>Tkinter</code> → <code>tkinter</code></li> <li><code>tkMessageBox</code> → <code>tkinter.messagebox</code></li> <li><code>tkColorChooser</code> → <code>tkinter.colorchooser</code></li> <li><code>tkFileDialog</code> → <code>tkinter.filedialog</code> </li> <li><code>tkCommonDialog</code> → <code>tkinter.commondialog</code></li> <li><code>tkSimpleDialog</code> → <code>tkinter.simpledialog</code></li> <li><code>tkFont</code> → <code>tkinter.font</code></li> <li><code>Tkdnd</code> → <code>tkinter.dnd</code></li> <li><code>ScrolledText</code> → <code>tkinter.scrolledtext</code></li> <li><code>Tix</code> → <code>tkinter.tix</code></li> <li><code>ttk</code> → <code>tkinter.ttk</code></li> </ul> <p>I advise you to learn how to dynamically browse the modules with the <a href="http://docs.python.org/library/functions.html#dir"><code>dir</code></a> command. If you are under windows, configure Python to use <a href="http://ipython.scipy.org/moin/PyReadline/Intro">readline</a> module to get auto-completion and make it much easier to list available classes in a module.</p>
36
2009-03-23T13:11:44Z
[ "python", "python-2.7", "python-3.x", "tkinter", "dialog" ]
How to include page in PDF in PDF document in Python
673,288
<p>I am using reportlab toolkit in Python to generate some reports in PDF format. I want to use some predefined parts of documents already published in PDF format to be included in generated PDF file. Is it possible (and how) to accomplish this in reportlab or in python library?</p> <p>I know I can use some other tools like PDF Toolkit (pdftk) but I am looking for Python-based solution.</p>
5
2009-03-23T13:03:12Z
673,322
<p>There is an add-on for ReportLab &mdash; <a href="http://www.reportlab.com/docs/PageCatchIntro.pdf" rel="nofollow">PageCatcher</a>. </p>
1
2009-03-23T13:17:53Z
[ "python", "pdf", "pdf-generation", "reportlab" ]
How to include page in PDF in PDF document in Python
673,288
<p>I am using reportlab toolkit in Python to generate some reports in PDF format. I want to use some predefined parts of documents already published in PDF format to be included in generated PDF file. Is it possible (and how) to accomplish this in reportlab or in python library?</p> <p>I know I can use some other tools like PDF Toolkit (pdftk) but I am looking for Python-based solution.</p>
5
2009-03-23T13:03:12Z
673,515
<p>I'm currently using <a href="http://pybrary.net/pyPdf/">PyPDF</a> to read, write, and combine existing PDF's and ReportLab to generate new content. Using the two package seemed to work better than any single package I was able to find.</p>
6
2009-03-23T14:10:39Z
[ "python", "pdf", "pdf-generation", "reportlab" ]
How to include page in PDF in PDF document in Python
673,288
<p>I am using reportlab toolkit in Python to generate some reports in PDF format. I want to use some predefined parts of documents already published in PDF format to be included in generated PDF file. Is it possible (and how) to accomplish this in reportlab or in python library?</p> <p>I know I can use some other tools like PDF Toolkit (pdftk) but I am looking for Python-based solution.</p>
5
2009-03-23T13:03:12Z
7,154,867
<p>If you want to place existing PDF pages in your Reportlab documents I recommend <a href="http://code.google.com/p/pdfrw/" rel="nofollow">pdfrw</a>. Unlike PageCatcher it is free.</p> <p>I've used it for several projects where I need to add barcodes etc to existing documents and it works very well. There are a couple of <a href="http://code.google.com/p/pdfrw/wiki/ExampleTools" rel="nofollow">examples</a> on the project page of how to use it with Reportlab.</p> <p>A couple of things to note though:</p> <p>If the source PDF contains errors (due to the originating program following the PDF spec imperfectly for example), pdfrw may fail even though something like Adobe Reader has no apparent problems reading the PDF. pdfrw is currently not very fault tolerant.</p> <p>Also, pdfrw works by being completely agnostic to the actual content of the PDF page you are placing. So for example, you wouldn't be able to use pdfrw inspect a page to see if it contains a certain string of text in the lower right-hand corner. However if you <em>don't</em> need to do anything like that you should be fine.</p>
2
2011-08-22T23:46:43Z
[ "python", "pdf", "pdf-generation", "reportlab" ]
Is there a Python library for easily writing zoomable UI's?
673,434
<p>My next work is going to be heavily focused on working with data that is best understood when organized on a two-dimensional zoomable plane or canvas, instead of using lists and property forms.</p> <p>The library can be based on OpenGL, GTK+ or Cairo. It should allow me to:</p> <ul> <li>build widgets out of vector shapes and text (perhaps even SVG based?)</li> <li>arrange these widgets on a 2D plane</li> <li>catch widget-related events</li> <li>zoom deeply into a widget to reveal additional data</li> <li>arrange widgets in a tree</li> <li>animate widgets fluidly</li> </ul> <p>It wouldn't hurt if it would also allow for some databinding or model/view concept.</p>
3
2009-03-23T13:51:13Z
673,447
<p>Qt has this covered... check PyQt</p>
3
2009-03-23T13:54:34Z
[ "python", "user-interface", "opengl", "gtk", "cairo" ]
Is there a Python library for easily writing zoomable UI's?
673,434
<p>My next work is going to be heavily focused on working with data that is best understood when organized on a two-dimensional zoomable plane or canvas, instead of using lists and property forms.</p> <p>The library can be based on OpenGL, GTK+ or Cairo. It should allow me to:</p> <ul> <li>build widgets out of vector shapes and text (perhaps even SVG based?)</li> <li>arrange these widgets on a 2D plane</li> <li>catch widget-related events</li> <li>zoom deeply into a widget to reveal additional data</li> <li>arrange widgets in a tree</li> <li>animate widgets fluidly</li> </ul> <p>It wouldn't hurt if it would also allow for some databinding or model/view concept.</p>
3
2009-03-23T13:51:13Z
675,971
<p>I think <a href="http://www.clutter-project.org/" rel="nofollow">Clutter</a> is perfect for you.</p> <p>From the web site:</p> <blockquote> <p>Clutter is an open source software library for creating fast, visually rich and animated graphical user interfaces.</p> </blockquote> <p>Clutter is written in C, but it has great <a href="http://clutter-project.org/sources/pyclutter/" rel="nofollow">Python bindings</a>.</p> <p>A very similar project is <a href="https://code.fluendo.com/pigment/trac" rel="nofollow">Pigment</a>:</p> <blockquote> <p>Pigment is a 3D scene graph library designed to easily create rich application user interfaces.</p> </blockquote>
2
2009-03-24T02:32:42Z
[ "python", "user-interface", "opengl", "gtk", "cairo" ]
What signals should I catch for clipboard pasting and character insertion in GTK?
673,605
<p>I have a Window with a TextView, and I would like to perform some actions when the user pastes some text. </p> <p>I would also like to know what signal(s) should I catch in order to perform something when the user presses a key inside the TextView. </p> <p>Can you tell me what are the signals I must connect?</p>
1
2009-03-23T14:37:30Z
673,643
<p>For paste: Take a look at the <a href="http://library.gnome.org/devel/gtk/stable/GtkTextBuffer.html#GtkTextBuffer-paste-done" rel="nofollow">paste-done</a> signal of the <code><a href="http://library.gnome.org/devel/gtk/stable/GtkTextBuffer.html" rel="nofollow">GtkTextBuffer</a></code> class, it sounds about right.</p> <p>For regular character insert: <a href="http://library.gnome.org/devel/gtk/stable/GtkTextBuffer.html#GtkTextBuffer-insert-text" rel="nofollow">insert-text</a>.</p>
2
2009-03-23T14:44:47Z
[ "python", "gtk", "clipboard", "pygtk", "signals" ]
Using PiL to take a screenshot of HTML/CSS
673,725
<p>I want to enable a user on a website to upload an image, and write some text over it. Also, they should be able to crop/scale/move the image and text. For that stuff, I can do it in jQuery.</p> <p>After they've made the image the way they want it, is there a way i can take a screenshot of that image (using PiL) and save it on the server?</p> <p>What is the best/proper way to do this?</p>
1
2009-03-23T15:00:51Z
673,958
<p>I assume you got Python on the server side.</p> <p>The best way imo is to somehow 'get' all the editing parameters from the client, then re-render it using PIL.</p> <p>Update: How I will do it On the server side, you need an url to handle posts. On the client side, (after each edit, )send a post to that url, with the editing parameters. I think there is not an easy solution to this.</p> <p>Maybe if you don't use PIL to render the final image, but only remember the parameters, each view from clients can render itself?</p>
1
2009-03-23T15:58:28Z
[ "jquery", "python", "css", "xhtml", "python-imaging-library" ]
Using PiL to take a screenshot of HTML/CSS
673,725
<p>I want to enable a user on a website to upload an image, and write some text over it. Also, they should be able to crop/scale/move the image and text. For that stuff, I can do it in jQuery.</p> <p>After they've made the image the way they want it, is there a way i can take a screenshot of that image (using PiL) and save it on the server?</p> <p>What is the best/proper way to do this?</p>
1
2009-03-23T15:00:51Z
673,961
<p>Taking a "screenshot" of the picture is neither the best, nor the proper way to do it. To take a screenshot, you need to execute code on the client machine, which is "not possible" in a website scenario.</p> <p>Have a look at <a href="http://mine.icanhascheezburger.com/" rel="nofollow">lolcat builder</a> (I can't think of a more serious example right now ;). Everytime you click the "Preview" button, the image src is updated with an url containing the text, its style and position. The request is handled by the server which will generate a new picture to display.</p>
2
2009-03-23T15:59:10Z
[ "jquery", "python", "css", "xhtml", "python-imaging-library" ]
Using PiL to take a screenshot of HTML/CSS
673,725
<p>I want to enable a user on a website to upload an image, and write some text over it. Also, they should be able to crop/scale/move the image and text. For that stuff, I can do it in jQuery.</p> <p>After they've made the image the way they want it, is there a way i can take a screenshot of that image (using PiL) and save it on the server?</p> <p>What is the best/proper way to do this?</p>
1
2009-03-23T15:00:51Z
674,221
<p>PIL isn't available on the client side.. so unless, as Jack Ha suggests, you intend to upload all the instructions of your image editing to the server and re-execute them, it's not an option. I would shy away from this because you'd need to implement the same editing routines on both the client and the server, doubling the size of your code base. (Perhaps if your server-side code was written in Javascript it would make sense, so the drawing code could be reused.)</p> <p>Instead, look into finding a Javascript library that does complete image manipulation client-side, and have the browser upload the final, edited image. I'm not familiar with the options in that area, but a quick Google search <a href="http://www.pixastic.com/" rel="nofollow">turned this up</a>, which uses the canvas element to store the pixel data.</p>
0
2009-03-23T16:55:34Z
[ "jquery", "python", "css", "xhtml", "python-imaging-library" ]
Using PiL to take a screenshot of HTML/CSS
673,725
<p>I want to enable a user on a website to upload an image, and write some text over it. Also, they should be able to crop/scale/move the image and text. For that stuff, I can do it in jQuery.</p> <p>After they've made the image the way they want it, is there a way i can take a screenshot of that image (using PiL) and save it on the server?</p> <p>What is the best/proper way to do this?</p>
1
2009-03-23T15:00:51Z
674,283
<p>Well, even if others are trying to discourage you from doing this, it would probably not be that hard.</p> <p>On the client-side, you, you define a div that is floated/resizable over the image, with transparency, that can be scaled for the crop.</p> <p>Move, I assume it applies only to the text, so you dynamically create draggable spans on the client side, still easy.</p> <p>Scale, I have no Idea of a simple UI to do it.</p> <p>When you want to update your Image, you serialize your data (position of your cropping div and position of your text spans / scaling, relative to the position to the image.) Then, using json or anything similar you'd like, you transfer the data to the server. </p> <p>Then, on the server, using python/PIL, you reproduce the transformations that you have serialized.</p>
0
2009-03-23T17:08:06Z
[ "jquery", "python", "css", "xhtml", "python-imaging-library" ]
How to read from an os.pipe() without getting blocked?
673,844
<p>I'm trying to read from an open <code>os.pipe()</code> to see if it's empty at the moment of the reading. The problem is that calling <code>read()</code> causes the program to block there until there is actually something to read there however there won't be any, if the test I'm doing succeeded. </p> <p>I know I can use <code>select.select()</code> with a timeout however I wanted to know if there is another solution to the problem.</p>
7
2009-03-23T15:27:53Z
674,508
<p>You might try this. </p> <pre><code>import os, fcntl fcntl.fcntl(thePipe, fcntl.F_SETFL, os.O_NONBLOCK) </code></pre> <p>With this <code>thePipe.read()</code> should be non-blocking. </p> <p>From <a href="http://man7.org/linux/man-pages/man7/pipe.7.html">pipe(7)</a> man page:</p> <blockquote> <p>If a process attempts to read from an empty pipe, then read(2) will block until data is available. (...) Non-blocking I/O is possible by using the fcntl(2) <code>F_SETFL</code> operation to enable the <code>O_NONBLOCK</code> open file status flag.</p> </blockquote>
13
2009-03-23T17:54:55Z
[ "python", "file", "pipe" ]
python: arbitrary order by
673,867
<p>In Oracle sql there is a feature to order as follow:</p> <pre><code>order by decode("carrot" = 2 ,"banana" = 1 ,"apple" = 3) </code></pre> <p>What will be the best way to implement this in python?</p> <p>I want to be able to order a dict on its keys. And that order isn't alphabetically or anything, I determine the order.</p>
3
2009-03-23T15:33:24Z
673,882
<p>Python's dict is a hashmap, so it has no order. But you can sort the keys separately, extracting them from the dictionary with <a href="http://docs.python.org/library/stdtypes.html#dict.keys" rel="nofollow">keys()</a> method.</p> <p><a href="http://docs.python.org/library/functions.html#sorted" rel="nofollow"><code>sorted()</code></a> takes comparison and key functions as arguments.</p> <p>You can do exact copy of your decode with</p> <pre><code>sortedKeys = sorted(dictionary, {"carrot": 2 ,"banana": 1 ,"apple": 3}.get); </code></pre>
1
2009-03-23T15:37:47Z
[ "python", "order" ]
python: arbitrary order by
673,867
<p>In Oracle sql there is a feature to order as follow:</p> <pre><code>order by decode("carrot" = 2 ,"banana" = 1 ,"apple" = 3) </code></pre> <p>What will be the best way to implement this in python?</p> <p>I want to be able to order a dict on its keys. And that order isn't alphabetically or anything, I determine the order.</p>
3
2009-03-23T15:33:24Z
673,888
<p>You can't sort a dictionary; a dictionary is a mapping and a mapping has no ordering.</p> <p>You could extract the keys and sort those, however:</p> <pre><code>keys = myDict.keys() sorted_keys = sorted(keys, myCompare) </code></pre>
1
2009-03-23T15:39:42Z
[ "python", "order" ]
python: arbitrary order by
673,867
<p>In Oracle sql there is a feature to order as follow:</p> <pre><code>order by decode("carrot" = 2 ,"banana" = 1 ,"apple" = 3) </code></pre> <p>What will be the best way to implement this in python?</p> <p>I want to be able to order a dict on its keys. And that order isn't alphabetically or anything, I determine the order.</p>
3
2009-03-23T15:33:24Z
673,890
<p>A dict is not ordered. You will need to keep a list of keys.</p> <p>You can pass your own comparison function to list.sort() or sorted().</p> <p>If you need to sort on multiple keys, just concatenate them in a tuple, and sort on the tuple.</p>
0
2009-03-23T15:39:58Z
[ "python", "order" ]
python: arbitrary order by
673,867
<p>In Oracle sql there is a feature to order as follow:</p> <pre><code>order by decode("carrot" = 2 ,"banana" = 1 ,"apple" = 3) </code></pre> <p>What will be the best way to implement this in python?</p> <p>I want to be able to order a dict on its keys. And that order isn't alphabetically or anything, I determine the order.</p>
3
2009-03-23T15:33:24Z
673,892
<p>Use the <code>key</code> named keyword argument of <code>sorted()</code>.</p> <pre><code>#set up the order you want the keys to appear here order = ["banana", "carrot", "apple"] # this uses the order list to sort the actual keys. sorted(keys, key=order.index) </code></pre> <p>For higher performance than <code>list.index</code>, you could use <code>dict.get</code> instead.</p> <pre><code>#this builds a dictionary to lookup the desired ordering order = dict((key, idx) for idx, key in enumerate(["banana", "carrot", "apple"])) # this uses the order dict to sort the actual keys. sorted(keys, key=order.get) </code></pre>
13
2009-03-23T15:40:10Z
[ "python", "order" ]
python: arbitrary order by
673,867
<p>In Oracle sql there is a feature to order as follow:</p> <pre><code>order by decode("carrot" = 2 ,"banana" = 1 ,"apple" = 3) </code></pre> <p>What will be the best way to implement this in python?</p> <p>I want to be able to order a dict on its keys. And that order isn't alphabetically or anything, I determine the order.</p>
3
2009-03-23T15:33:24Z
673,897
<p>There will be <code>OrderedDict</code> in new Python versions: <a href="http://www.python.org/dev/peps/pep-0372/" rel="nofollow">http://www.python.org/dev/peps/pep-0372/</a>.</p> <p>Meanwhile, you can try one of the alternative implementations: <a href="http://code.activestate.com/recipes/496761/" rel="nofollow">http://code.activestate.com/recipes/496761/</a>, <a href="http://pypi.python.org/pypi/Ordered%20Dictionary/" rel="nofollow">Ordered Dictionary</a>.</p>
1
2009-03-23T15:41:25Z
[ "python", "order" ]
python: arbitrary order by
673,867
<p>In Oracle sql there is a feature to order as follow:</p> <pre><code>order by decode("carrot" = 2 ,"banana" = 1 ,"apple" = 3) </code></pre> <p>What will be the best way to implement this in python?</p> <p>I want to be able to order a dict on its keys. And that order isn't alphabetically or anything, I determine the order.</p>
3
2009-03-23T15:33:24Z
673,910
<p>You can't order a dict per se, but you can convert it to a list of (key, value) tuples, and you can sort that.</p> <p>You use the .items() method to do that. For example,</p> <pre><code>&gt;&gt;&gt; {'a': 1, 'b': 2} {'a': 1, 'b': 2} &gt;&gt;&gt; {'a': 1, 'b': 2}.items() [('a', 1), ('b', 2)] </code></pre> <p>Most efficient way to sort that is to use a key function. using cmp is less efficient because it has to be called for every pair of items, where using key it only needs to be called once for every item. Just specify a callable that will transform the item according to how it should be sorted:</p> <pre><code>sorted(somedict.items(), key=lambda x: {'carrot': 2, 'banana': 1, 'apple':3}[x[0]]) </code></pre> <p>The above defines a dict that specifies the custom order of the keys that you want, and the lambda returns that value for each key in the old dict.</p>
4
2009-03-23T15:47:08Z
[ "python", "order" ]
Error while deploying Django on Apache
673,936
<p>I have a small Django website which I am trying to run on an Apache 2.2 HTTP-Server. The application is running fine using "python manage.py runserver".</p> <p>Django Version: 1.0.2 final <br /> Python: 2.5<br /> OS: Windows 2000<br /></p> <p>I wen't through the steps described in the <a href="http://docs.djangoproject.com/en/dev//howto/deployment/modpython/" rel="nofollow">documentation</a> and after some fiddling, came out with the following in my httpd.conf.</p> <pre><code>&lt;Location "/therap/"&gt; SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE settings PythonOption django.root /therap PythonDebug On PythonPath "['D:/therap/therap'] + sys.path" &lt;/Location&gt; MaxRequestsPerChild 1 </code></pre> <p>D:\therap\therap beeing the place where my manage.py is.</p> <p>When I try to open in my browser, I see an error in the style used by Django (as opposed to black courier on white background.)</p> <pre><code>ImportError at / No module named therap.urls Request Method: GET Request URL: http://****:8080/ Exception Type: ImportError Exception Value: No module named therap.urls Exception Location: C:\python25\lib\site-packages\django\core\urlresolvers.py in _get_urlconf_module, line 200 Python Executable: C:\Programme\Apache Software Foundation\Apache2.2\bin\httpd.exe Python Version: 2.5.1 Python Path: ['D:/therap/therap', 'C:\\WINNT\\system32\\python25.zip', 'C:\\Python25\\Lib', 'C:\\Python25\\DLLs', 'C:\\Python25\\Lib\\lib-tk', 'C:\\Programme\\Apache Software Foundation\\Apache2.2', 'C:\\Programme\\Apache Software Foundation\\Apache2.2\\bin', 'C:\\Python25', 'C:\\Python25\\lib\\site-packages', 'C:\\Python25\\lib\\site-packages\\pyserial-2.2', 'C:\\Python25\\lib\\site-packages\\win32', 'C:\\Python25\\lib\\site-packages\\win32\\lib', 'C:\\Python25\\lib\\site-packages\\Pythonwin', 'C:\\Python25\\lib\\site-packages\\wx-2.8-msw-unicode'] Server time: Mo, 23 Mär 2009 16:27:03 +0100 </code></pre> <p>There is a urls.py in D:\therap\therap. However there is none in D:\therap\therap\main where most of my code is.</p> <p>I then tried using the parent folder</p> <pre><code>&lt;Location "/therap/"&gt; SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE therap.settings PythonOption django.root /therap PythonDebug On PythonPath "['D:/therap'] + sys.path" &lt;/Location&gt; MaxRequestsPerChild 1 </code></pre> <p>Which gave me a different error:</p> <pre><code>MOD_PYTHON ERROR ProcessId: 2424 Interpreter: '***' ServerName: '****' DocumentRoot: 'C:/Programme/Apache Software Foundation/Apache2.2/htdocs' URI: '/therap/' Location: '/therap/' Directory: None Filename: 'C:/Programme/Apache Software Foundation/Apache2.2/htdocs/therap' PathInfo: '/' Phase: 'PythonHandler' Handler: 'django.core.handlers.modpython' Traceback (most recent call last): File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1229, in _process_target result = _execute_target(config, req, object, arg) File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1128, in _execute_target result = object(arg) File "C:\Python25\lib\site-packages\django\core\handlers\modpython.py", line 228, in handler return ModPythonHandler()(req) File "C:\Python25\lib\site-packages\django\core\handlers\modpython.py", line 201, in __call__ response = self.get_response(request) File "C:\python25\Lib\site-packages\django\core\handlers\base.py", line 67, in get_response response = middleware_method(request) File "C:\python25\Lib\site-packages\django\middleware\locale.py", line 17, in process_request translation.activate(language) File "C:\python25\Lib\site-packages\django\utils\translation\__init__.py", line 73, in activate return real_activate(language) File "C:\python25\Lib\site-packages\django\utils\translation\trans_real.py", line 209, in activate _active[currentThread()] = translation(language) File "C:\python25\Lib\site-packages\django\utils\translation\trans_real.py", line 198, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "C:\python25\Lib\site-packages\django\utils\translation\trans_real.py", line 183, in _fetch app = __import__(appname, {}, {}, []) ImportError: No module named main </code></pre> <p>I do use the internationalization module, but I do not see why it causes a problem at this point.</p> <p>"main" is the name of the only Django app (containing views, models, forms and such). The full path is D:\therap\therap\main.</p> <p>I put <code>__init__.py</code>-files everywhere from the main folder to d:\therap.</p> <p>Now I don't know what else I could do. Any ideas?</p>
1
2009-03-23T15:52:46Z
674,237
<p>Have you installed gettext? Or a maybe different version of it...</p>
0
2009-03-23T17:00:04Z
[ "python", "windows", "django", "apache", "mod-python" ]
Error while deploying Django on Apache
673,936
<p>I have a small Django website which I am trying to run on an Apache 2.2 HTTP-Server. The application is running fine using "python manage.py runserver".</p> <p>Django Version: 1.0.2 final <br /> Python: 2.5<br /> OS: Windows 2000<br /></p> <p>I wen't through the steps described in the <a href="http://docs.djangoproject.com/en/dev//howto/deployment/modpython/" rel="nofollow">documentation</a> and after some fiddling, came out with the following in my httpd.conf.</p> <pre><code>&lt;Location "/therap/"&gt; SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE settings PythonOption django.root /therap PythonDebug On PythonPath "['D:/therap/therap'] + sys.path" &lt;/Location&gt; MaxRequestsPerChild 1 </code></pre> <p>D:\therap\therap beeing the place where my manage.py is.</p> <p>When I try to open in my browser, I see an error in the style used by Django (as opposed to black courier on white background.)</p> <pre><code>ImportError at / No module named therap.urls Request Method: GET Request URL: http://****:8080/ Exception Type: ImportError Exception Value: No module named therap.urls Exception Location: C:\python25\lib\site-packages\django\core\urlresolvers.py in _get_urlconf_module, line 200 Python Executable: C:\Programme\Apache Software Foundation\Apache2.2\bin\httpd.exe Python Version: 2.5.1 Python Path: ['D:/therap/therap', 'C:\\WINNT\\system32\\python25.zip', 'C:\\Python25\\Lib', 'C:\\Python25\\DLLs', 'C:\\Python25\\Lib\\lib-tk', 'C:\\Programme\\Apache Software Foundation\\Apache2.2', 'C:\\Programme\\Apache Software Foundation\\Apache2.2\\bin', 'C:\\Python25', 'C:\\Python25\\lib\\site-packages', 'C:\\Python25\\lib\\site-packages\\pyserial-2.2', 'C:\\Python25\\lib\\site-packages\\win32', 'C:\\Python25\\lib\\site-packages\\win32\\lib', 'C:\\Python25\\lib\\site-packages\\Pythonwin', 'C:\\Python25\\lib\\site-packages\\wx-2.8-msw-unicode'] Server time: Mo, 23 Mär 2009 16:27:03 +0100 </code></pre> <p>There is a urls.py in D:\therap\therap. However there is none in D:\therap\therap\main where most of my code is.</p> <p>I then tried using the parent folder</p> <pre><code>&lt;Location "/therap/"&gt; SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE therap.settings PythonOption django.root /therap PythonDebug On PythonPath "['D:/therap'] + sys.path" &lt;/Location&gt; MaxRequestsPerChild 1 </code></pre> <p>Which gave me a different error:</p> <pre><code>MOD_PYTHON ERROR ProcessId: 2424 Interpreter: '***' ServerName: '****' DocumentRoot: 'C:/Programme/Apache Software Foundation/Apache2.2/htdocs' URI: '/therap/' Location: '/therap/' Directory: None Filename: 'C:/Programme/Apache Software Foundation/Apache2.2/htdocs/therap' PathInfo: '/' Phase: 'PythonHandler' Handler: 'django.core.handlers.modpython' Traceback (most recent call last): File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1537, in HandlerDispatch default=default_handler, arg=req, silent=hlist.silent) File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1229, in _process_target result = _execute_target(config, req, object, arg) File "C:\Python25\Lib\site-packages\mod_python\importer.py", line 1128, in _execute_target result = object(arg) File "C:\Python25\lib\site-packages\django\core\handlers\modpython.py", line 228, in handler return ModPythonHandler()(req) File "C:\Python25\lib\site-packages\django\core\handlers\modpython.py", line 201, in __call__ response = self.get_response(request) File "C:\python25\Lib\site-packages\django\core\handlers\base.py", line 67, in get_response response = middleware_method(request) File "C:\python25\Lib\site-packages\django\middleware\locale.py", line 17, in process_request translation.activate(language) File "C:\python25\Lib\site-packages\django\utils\translation\__init__.py", line 73, in activate return real_activate(language) File "C:\python25\Lib\site-packages\django\utils\translation\trans_real.py", line 209, in activate _active[currentThread()] = translation(language) File "C:\python25\Lib\site-packages\django\utils\translation\trans_real.py", line 198, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "C:\python25\Lib\site-packages\django\utils\translation\trans_real.py", line 183, in _fetch app = __import__(appname, {}, {}, []) ImportError: No module named main </code></pre> <p>I do use the internationalization module, but I do not see why it causes a problem at this point.</p> <p>"main" is the name of the only Django app (containing views, models, forms and such). The full path is D:\therap\therap\main.</p> <p>I put <code>__init__.py</code>-files everywhere from the main folder to d:\therap.</p> <p>Now I don't know what else I could do. Any ideas?</p>
1
2009-03-23T15:52:46Z
675,981
<p>The problem is that you are importing your app ("main") as if it lives directly on the Python path, and your URLconf ("therap.urls") as if it lives within a "therap" module on the Python path. This can only work if both "D:/therap" and "D:/therap/therap" are BOTH on the Python path (which runserver does for you automatically to "make things easy"; though it ends up just delaying the confusion until deployment time). You can emulate runserver's behavior by using the following line in your Apache config:</p> <pre><code>PythonPath "['D:/therap', 'D:/therap/therap'] + sys.path" </code></pre> <p>It probably makes more sense to standardize your references so your Python path only need include one or the other. The usual way (at least the way I see referenced more often) would be to put "D:\therap" on the Python path and qualify your app as "therap.main" instead of just "main". Personally, I take the opposite approach and it works just fine: put "D:\therap\therap" on your Python path and set ROOT_URLCONF to "urls" instead of "therap.urls". The advantage of this is that if in future you want to make your "main" app reusable and move it out of the particular project, your references to it aren't tied to the project name "therap" (though with an app named "main" it doesn't sound like you're thinking in terms of reusable apps anyway).</p>
3
2009-03-24T02:38:00Z
[ "python", "windows", "django", "apache", "mod-python" ]
How can I make the Django contrib Admin change list for a particular model class editable with drop downs for related items displayed in the listing?
673,970
<p>Basically I want to have an editable form for related entries instead of a static listing. </p>
1
2009-03-23T16:00:39Z
680,830
<p>Try Django 1.1 beta. It's got the option to make items in the changelist editable (as well as incorporating the django-batchadmin project) </p>
1
2009-03-25T09:24:43Z
[ "python", "django", "django-admin", "django-templates", "django-forms" ]
Django syncdb locking up on table creation
674,030
<p>I've added new models and pushed to our staging server, run syncdb to create their tables, and it locks up. It gets as far as 'Create table photos_photousertag' and postgres output shows the notice for creation of 'photos_photousertag_id_seq', but otherwise i get nothing on either said. I can't ctrl+c the syncdb process and I have no indication of what route to take from here. Has anyone else ran into this?</p>
3
2009-03-23T16:16:18Z
674,105
<p>We use postgres, and while we've not run into this particular issue, there are some steps you may find helpful in debugging:</p> <p>a. What version of postgres and psycopg2 are you using? For that matter, what version of django?</p> <p>b. Try running the syncdb command with the "--verbosity=2" option to show all output.</p> <p>c. Find the SQL that django is generating by running the "manage.py sql " command. Run the CREATE TABLE statements for your new models in the postgres shell and see what develops.</p> <p>d. Turn the error logging, statement logging, and server status logging on postgres way up to see if you can catch any particular messages.</p> <p>In the past, we've usually found that either option b or option c points out the problem.</p>
1
2009-03-23T16:30:12Z
[ "python", "django", "django-syncdb" ]
Django syncdb locking up on table creation
674,030
<p>I've added new models and pushed to our staging server, run syncdb to create their tables, and it locks up. It gets as far as 'Create table photos_photousertag' and postgres output shows the notice for creation of 'photos_photousertag_id_seq', but otherwise i get nothing on either said. I can't ctrl+c the syncdb process and I have no indication of what route to take from here. Has anyone else ran into this?</p>
3
2009-03-23T16:16:18Z
10,438,955
<p>I just experienced this as well, and it turned out to just be a plain old lock on that particular table, unrelated to Django. Once that cleared the sync went through just fine.</p> <p>Try querying the table that the sync is getting stuck on and make sure that's working correctly first.</p>
1
2012-05-03T20:35:57Z
[ "python", "django", "django-syncdb" ]
Django syncdb locking up on table creation
674,030
<p>I've added new models and pushed to our staging server, run syncdb to create their tables, and it locks up. It gets as far as 'Create table photos_photousertag' and postgres output shows the notice for creation of 'photos_photousertag_id_seq', but otherwise i get nothing on either said. I can't ctrl+c the syncdb process and I have no indication of what route to take from here. Has anyone else ran into this?</p>
3
2009-03-23T16:16:18Z
21,254,637
<p>Strange here too, but <strong>simply restarting the PostgreSQL service (or server)</strong> solved it. I'd tried manually pasting the table creation code in psql too, but that wasn't solving it either (well, no way it could if it was a lock thing) - so I just used the restart:</p> <blockquote> <p>systemctl restart postgresql.service </p> </blockquote> <p>that's on my Suse box.</p> <p>Am not sure whether <em>reloading</em> the service/server might lift existing table locks too?</p>
0
2014-01-21T09:53:51Z
[ "python", "django", "django-syncdb" ]
How to display errors to the user while still logging it?
674,067
<p>I'm using a PyQt4 user interface. I've redirected stderr to a log file for easy debugging and trouble-shooting, but now I need to display error messages to the user when an error occurs.</p> <p>My issue is that I need to catch an exception when it happens and let the user know that it happened, but still let the traceback propagate to stderr (i.e. the log file).</p> <p>If I do something like this:</p> <pre><code>def updateResults(self): try: #code that updates the results except: #display error message box </code></pre> <p>This will catch the exception and not propogate to the error log.</p> <p>Is there some way to show the user the message and then continue to propogate the error?</p> <p>Would this work? </p> <pre><code>except, e: #display error message box raise e </code></pre> <p>Is there a better way to accomplish my goal?</p>
2
2009-03-23T16:22:51Z
674,073
<p>Exactly, but you can just</p> <pre><code>raise </code></pre> <p>which will re-raise the currently handled exception.</p>
3
2009-03-23T16:24:38Z
[ "python", "exception-handling", "error-handling", "pyqt4", "error-logging" ]
How to display errors to the user while still logging it?
674,067
<p>I'm using a PyQt4 user interface. I've redirected stderr to a log file for easy debugging and trouble-shooting, but now I need to display error messages to the user when an error occurs.</p> <p>My issue is that I need to catch an exception when it happens and let the user know that it happened, but still let the traceback propagate to stderr (i.e. the log file).</p> <p>If I do something like this:</p> <pre><code>def updateResults(self): try: #code that updates the results except: #display error message box </code></pre> <p>This will catch the exception and not propogate to the error log.</p> <p>Is there some way to show the user the message and then continue to propogate the error?</p> <p>Would this work? </p> <pre><code>except, e: #display error message box raise e </code></pre> <p>Is there a better way to accomplish my goal?</p>
2
2009-03-23T16:22:51Z
674,149
<p>I think you are thinking about this in the wrong way. You shouldn't be re-raising the error simply to log it further down the line. The cannonical way of doing this in Python is to use the logging module. Adapted from the docs:</p> <pre><code>import logging LOG_FILENAME = '/tmp/logging_example.out' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,) ... try: # code except: logging.debug('Something bad happened', exc_info=True) # display message box # raise (if necessary) </code></pre> <p>This gives a far more flexible logging system than relying on errors produced on sys.stdout. You may not need to re-raise the exception if you can recover from the exception in some way. </p>
6
2009-03-23T16:41:55Z
[ "python", "exception-handling", "error-handling", "pyqt4", "error-logging" ]
How to display errors to the user while still logging it?
674,067
<p>I'm using a PyQt4 user interface. I've redirected stderr to a log file for easy debugging and trouble-shooting, but now I need to display error messages to the user when an error occurs.</p> <p>My issue is that I need to catch an exception when it happens and let the user know that it happened, but still let the traceback propagate to stderr (i.e. the log file).</p> <p>If I do something like this:</p> <pre><code>def updateResults(self): try: #code that updates the results except: #display error message box </code></pre> <p>This will catch the exception and not propogate to the error log.</p> <p>Is there some way to show the user the message and then continue to propogate the error?</p> <p>Would this work? </p> <pre><code>except, e: #display error message box raise e </code></pre> <p>Is there a better way to accomplish my goal?</p>
2
2009-03-23T16:22:51Z
674,884
<p>Some additional information:</p> <p>(With PyQt4) you will also need to rebind sys.excepthook to your own function to catch all <em>uncaught</em> exceptions. Otherwise PyQt will just print them to the console, which may not be what you need...</p> <pre><code>import sys def excepthook(exc_type, exc_val, tracebackobj): # do something useful with the uncaught exception ... def main(): # rebind excepthook sys.excepthook = excepthook ... </code></pre>
1
2009-03-23T19:27:35Z
[ "python", "exception-handling", "error-handling", "pyqt4", "error-logging" ]
Python list.index throws exception when index not found
674,229
<p>Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this?</p> <p>To me it looks cleaner to deal with special values, etc than exceptions.</p> <p>EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None?</p>
9
2009-03-23T16:58:07Z
674,250
<p>Because <code>-1</code> is itself a valid index. It could use a different value, such as <code>None</code>, but that wouldn't be useful, which <code>-1</code> can be in other situations (thus <code>str.find()</code>), and would amount simply to error-checking, which is exactly what exceptions are for.</p>
10
2009-03-23T17:02:18Z
[ "python", "indexing", "list" ]
Python list.index throws exception when index not found
674,229
<p>Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this?</p> <p>To me it looks cleaner to deal with special values, etc than exceptions.</p> <p>EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None?</p>
9
2009-03-23T16:58:07Z
674,258
<p>In Python, -1 is a valid index, meaning a number from the end of the list (instead of the beginning), so if you were to do</p> <pre><code>idx = mylist.index(someval) nextval = mylist[idx+1] </code></pre> <p>then you would get the first value of the array, instead of realising there was an error. This way you can catch the exception and deal with it. If you don't want exceptions, then just check beforehand:</p> <pre><code>if someval in mylist: idx = mylist.index(someval) </code></pre> <p>Edit: There's not really any point in returning None, because if you're going to test for None, you might as well test whether the value is in the list as above!</p>
3
2009-03-23T17:04:00Z
[ "python", "indexing", "list" ]
Python list.index throws exception when index not found
674,229
<p>Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this?</p> <p>To me it looks cleaner to deal with special values, etc than exceptions.</p> <p>EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None?</p>
9
2009-03-23T16:58:07Z
674,259
<p>Well, the special value would actually have to be <strong><code>None</code></strong>, because -1 is a valid index (meaning the last element of a list). </p> <p>You can emulate this behavior by:</p> <pre><code>idx = l.index(x) if x in l else None </code></pre>
5
2009-03-23T17:04:10Z
[ "python", "indexing", "list" ]
Python list.index throws exception when index not found
674,229
<p>Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this?</p> <p>To me it looks cleaner to deal with special values, etc than exceptions.</p> <p>EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None?</p>
9
2009-03-23T16:58:07Z
674,262
<p>One simple idea: <code>-1</code> is perfectly usable as an index (as are other negative values).</p>
1
2009-03-23T17:04:17Z
[ "python", "indexing", "list" ]
Python list.index throws exception when index not found
674,229
<p>Why does list.index throws an exception instead of returning a value like say -1? What's the idea behind this?</p> <p>To me it looks cleaner to deal with special values, etc than exceptions.</p> <p>EDIT: I didn't realize -1 to be usable, but in that case, how about a value of None?</p>
9
2009-03-23T16:58:07Z
674,268
<p>To add to Devin's response: This is an old debate between special return values versus exceptions. Many programming gurus prefer an exception because on an exception, I get to see the whole stacktrace and immediate infer what is wrong. </p>
7
2009-03-23T17:05:02Z
[ "python", "indexing", "list" ]