title
stringlengths
15
101
question
stringlengths
57
2.99k
answer
stringlengths
59
4.06k
title_question_fit
listlengths
1
1
title_question_fit-suggestion
stringclasses
0 values
title_question_fit-suggestion-metadata
dict
tags
listlengths
1
1
tags-suggestion
sequencelengths
tags-suggestion-metadata
dict
answer_quality
listlengths
1
1
answer_quality-suggestion
int32
answer_quality-suggestion-metadata
dict
new_answer
listlengths
1
1
new_answer-suggestion
stringclasses
0 values
new_answer-suggestion-metadata
dict
external_id
stringclasses
0 values
metadata
stringclasses
1 value
C-like structures in Python
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
<p>Use a <a href="https://docs.python.org/2/library/collections.html#collections.namedtuple">named tuple</a>, which was added to the <a href="http://docs.python.org/library/collections.html">collections module</a> in the standard library in Python 2.6. It's also possible to use Raymond Hettinger's <a href="http://code.activestate.com/recipes/500261/">named tuple</a> recipe if you need to support Python 2.4.</p> <p>It's nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as:</p> <pre><code>from collections import namedtuple MyStruct = namedtuple("MyStruct", "field1 field2 field3") </code></pre> <p>The newly created type can be used like this:</p> <pre><code>m = MyStruct("foo", "bar", "baz") </code></pre> <p>Or you can use named arguments:</p> <pre><code>m = MyStruct(field1 = "foo", field2 = "bar", field3 = "baz") </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "flask" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How do I sort a list of strings in Python?
<p>What is the best way of creating an alphabetically sorted list in Python?</p>
<p>Basic answer:</p> <pre><code>mylist = ["b", "C", "A"] mylist.sort() </code></pre> <p>This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the <a href="http://docs.python.org/library/functions.html#sorted"><code>sorted()</code></a> function:</p> <pre><code>for x in sorted(mylist): print x </code></pre> <p>However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter <code>key</code> to specify custom sorting order (the alternative, using <code>cmp</code>, is a deprecated solution, as it has to be evaluated multiple times - <code>key</code> is only computed once per element).</p> <p>So, to sort according to the current locale, taking language-specific rules into account (<a href="http://docs.python.org/library/functools.html#functools.cmp_to_key"><code>cmp_to_key</code></a> is a helper function from functools):</p> <pre><code>sorted(mylist, key=cmp_to_key(locale.strcoll)) </code></pre> <p>And finally, if you need, you can specify a <a href="http://docs.python.org/library/locale.html">custom locale</a> for sorting:</p> <pre><code>import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale assert sorted((u'Ab', u'ad', u'aa'), key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad'] </code></pre> <p>Last note: you will see examples of case-insensitive sorting which use the <code>lower()</code> method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:</p> <pre><code># this is incorrect! mylist.sort(key=lambda x: x.lower()) # alternative notation, a bit faster, but still wrong mylist.sort(key=str.lower) </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "tkinter" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
"The system cannot find the file specified" when invoking subprocess.Popen in python
<p>I'm trying to use svnmerge.py to merge some files. Under the hood it uses python, and when I use it I get an error - "The system cannot find the file specified". Colleagues at work are running the same version of svnmerge.py, and of python (2.5.2, specifically r252:60911) without an issue.</p> <p>I found <a href="http://www.nabble.com/problem-under-some-windows-desktop-td15868057.html" rel="nofollow">this link</a>, which describes my problem. Trying what was outlined there, I confirmed Python could find svn (it's in my path):</p> <pre> P:\>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> i,k = os.popen4("svn --version") >>> i.close() >>> k.readline() 'svn, version 1.4.2 (r22196)\n' </pre> <p>Looking at the svnmerge.py code, though, I noticed for python versions 2.4 and higher it was following a different execution path. Rather than invoking os.popen4() it uses subprocess.Popen(). Trying that reproduces the error:</p> <pre> C:\>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import subprocess >>> p = subprocess.Popen("svn --version", stdout=subprocess.PIPE, >>> close_fds=False, stderr=subprocess.PIPE) Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\subprocess.py", line 594, in __init__ errread, errwrite) File "C:\Python25\lib\subprocess.py", line 816, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified >>> </pre> <p>For now, I've commented out the 2.4-and-higher specific code, but I'd like to find a proper solution.</p> <p>If it's not obvious, I'm a complete python newbie, but google hasn't helped. Any pointers?</p>
<p>It's a bug, see the <a href="http://docs.python.org/lib/node528.html" rel="nofollow">documentation of <code>subprocess.Popen</code></a>. There either needs to be a <code>"shell=True</code>" option, or the first argument needs to be a sequence <code>['svn', '--version']</code>. As it is now, <code>Popen</code> is looking for an executable named, literally, "svn --version" which it doesn't find.</p> <p>I don't know why it would work for your colleagues though, if they are running the same OS and version of Python... FWIW it gives me the same error message on a mac, and either of the two ways I gave fixes it.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "regex" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Setup django with WSGI and apache
<p>I have been sold on mod_wsgi and apache rather than mod_python. I have all the parts installed (django, apache, mod_wsgi) but have run into a problem deploying.</p> <p>I am on osx 10.5 with apache 2.2 and django 1.0b2, mod_wsgi-2.3</p> <p>My application is called tred.</p> <p>Here are the relevant files: httpd-vhosts (included in httpd-conf)</p> <pre> NameVirtualHost tred:80 ServerName tred Alias /admin_media /usr/lib/python2.5/site-packages/django/contrib/admin/media Order allow,deny Allow from all Alias /media /Users/dmg/Sites/tred/media Order allow,deny Allow from all Alias / /Users/dmg/Sites/tred/ Order allow,deny Allow from all WSGIScriptAlias / /Users/dmg/Sites/tred/mod_wsgi-handler.wsgi WSGIDaemonProcess tred user=dmg group=staff processes=1 threads=10 WSGIProcessGroup tred </pre> <p>mod_wsgi-handle.wsgi</p> <pre> import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') os.environ['DJANGO_SETTINGS_MODULE'] = 'tred.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() </pre> <p>When I go to <a href="http://tred">http://tred</a> I get a directory listing rather than the rendered website. I think I have followed the tutorials correctly but it is obviously not right. What can I do to make this work?</p>
<p>Note that Alias and WSGIScriptAlias directives do not have the same precedence. Thus, they will not be processed in file order as written. Instead, all Alias directives get precedence over WSGIScriptAlias directives. Thus, it wouldn't have mattered if the Alias for '/' appeared after WSGIScriptAlias, it would still have taken precedence.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python-3.x", "pandas" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How do I add data to an existing model in Django?
<p>Currently, I am writing up a bit of a product-based CMS as my first project.</p> <p>Here is my question. How can I add additional data (products) to my Product model?</p> <p>I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in mind that I don't really know all that much Python, and i am very new to Django</p> <p>How can I do this all without using this existing django admin interface.</p>
<p>You will want to wire your URL to the Django <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object" rel="nofollow">create_object generic view</a>, and pass it either "model" (the model you want to create) or "form_class" (a customized <a href="https://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#topics-forms-modelforms" rel="nofollow">ModelForm</a> class). There are a number of <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object" rel="nofollow">other arguments</a> you can also pass to override default behaviors.</p> <p>Sample URLconf for the simplest case:</p> <pre><code>from django.conf.urls.defaults import * from django.views.generic.create_update import create_object from my_products_app.models import Product urlpatterns = patterns('', url(r'^admin/products/add/$', create_object, {'model': Product})) </code></pre> <p>Your template will get the context variable "form", which you just need to wrap in a &lt;form> tag and add a submit button. The simplest working template (by default should go in "my_products_app/product_form.html"):</p> <pre><code>&lt;form action="." method="POST"&gt; {{ form }} &lt;input type="submit" name="submit" value="add"&gt; &lt;/form&gt; </code></pre> <p>Note that your Product model must have a get_absolute_url method, or else you must pass in the post_save_redirect parameter to the view. Otherwise it won't know where to redirect to after save.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python-3.x" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
What does ** (double star) and * (star) do for Python parameters?
<p>In the following method definitions, what does the <code>*</code> and <code>**</code> do for <code>param2</code>?</p> <pre><code>def foo(param1, *param2): def bar(param1, **param2): </code></pre>
<p>The <code>*args</code> and <code>**kwargs</code> is a common idiom to allow arbitrary number of arguments to functions as described in the section <a href="http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions">more on defining functions</a> in the Python documentation.</p> <p>The <code>*args</code> will give you all function parameters <a href="https://docs.python.org/dev/tutorial/controlflow.html#arbitrary-argument-lists">as a tuple</a>:</p> <pre><code>In [1]: def foo(*args): ...: for a in args: ...: print a ...: ...: In [2]: foo(1) 1 In [4]: foo(1,2,3) 1 2 3 </code></pre> <p>The <code>**kwargs</code> will give you all <strong>keyword arguments</strong> except for those corresponding to a formal parameter as a dictionary.</p> <pre><code>In [5]: def bar(**kwargs): ...: for a in kwargs: ...: print a, kwargs[a] ...: ...: In [6]: bar(name='one', age=27) age 27 name one </code></pre> <p>Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments:</p> <pre><code>def foo(kind, *args, **kwargs): pass </code></pre> <p>Another usage of the <code>*l</code> idiom is to <strong>unpack argument lists</strong> when calling a function.</p> <pre><code>In [9]: def foo(bar, lee): ...: print bar, lee ...: ...: In [10]: l = [1,2] In [11]: foo(*l) 1 2 </code></pre> <p>In Python 3 it is possible to use <code>*l</code> on the left side of an assignment (<a href="http://www.python.org/dev/peps/pep-3132/">Extended Iterable Unpacking</a>):</p> <pre><code>first, *rest = [1,2,3,4] first, *l, last = [1,2,3,4] </code></pre> <p>Also Python 3 adds new semantic (refer <a href="https://www.python.org/dev/peps/pep-3102/">PEP 3102</a>):</p> <pre><code>def func(arg1, arg2, arg3='default', *, kwarg1='abc', kwarg2='xyz'): pass </code></pre> <p>Such function accepts only 2 positional arguments, and everything after <code>*</code> can only be passed as keyword argument, not positional one.</p> <p>In Python 2 similar was true for all parameters after <code>*args</code>.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "mysql" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How can I represent an 'Enum' in Python?
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
<p>Enums have been added to Python 3.4 as described in <a href="http://www.python.org/dev/peps/pep-0435/" rel="nofollow">PEP 435</a>. It has also been <a href="https://pypi.python.org/pypi/enum34" rel="nofollow">backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4</a> on pypi. </p> <p>For more advanced Enum techniques try the <a href="https://pypi.python.org/pypi/aenum" rel="nofollow">aenum library</a> (2.7, 3.3+, same author as <code>enum34</code>. Code is not perfectly compatible between py2 and py3, e.g. you'll need <a href="http://stackoverflow.com/a/25982264/57461"><code>__order__</code> in python 2</a>).</p> <ul> <li>To use <code>enum34</code>, do <code>$ pip install enum34</code></li> <li>To use <code>aenum</code>, do <code>$ pip install aenum</code></li> </ul> <p>Installing <code>enum</code> (no numbers) will install a completely different and incompatible version.</p> <hr> <pre><code>from enum import Enum # for enum34, or the stdlib version # from aenum import Enum # for the aenum version Animal = Enum('Animal', 'ant bee cat dog') Animal.ant # returns &lt;Animal.ant: 1&gt; Animal['ant'] # returns &lt;Animal.ant: 1&gt; (string lookup) Animal.ant.name # returns 'ant' (inverse lookup) </code></pre> <p>or equivalently:</p> <pre><code>class Animal(Enum): ant = 1 bee = 2 cat = 3 dog = 4 </code></pre> <hr> <p>In earlier versions, one way of accomplishing enums is:</p> <pre><code>def enum(**enums): return type('Enum', (), enums) </code></pre> <p>which is used like so:</p> <pre><code>&gt;&gt;&gt; Numbers = enum(ONE=1, TWO=2, THREE='three') &gt;&gt;&gt; Numbers.ONE 1 &gt;&gt;&gt; Numbers.TWO 2 &gt;&gt;&gt; Numbers.THREE 'three' </code></pre> <p>You can also easily support automatic enumeration with something like this:</p> <pre><code>def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) </code></pre> <p>and used like so:</p> <pre><code>&gt;&gt;&gt; Numbers = enum('ZERO', 'ONE', 'TWO') &gt;&gt;&gt; Numbers.ZERO 0 &gt;&gt;&gt; Numbers.ONE 1 </code></pre> <p>Support for converting the values back to names can be added this way:</p> <pre><code>def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) reverse = dict((value, key) for key, value in enums.iteritems()) enums['reverse_mapping'] = reverse return type('Enum', (), enums) </code></pre> <p>This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw KeyError if the reverse mapping doesn't exist. With the first example:</p> <pre><code>&gt;&gt;&gt; Numbers.reverse_mapping['three'] 'THREE' </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "html" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Resources for lexing, tokenising and parsing in python
<p>Can people point me to resources on lexing, parsing and tokenising with Python?</p> <p>I'm doing a little hacking on an open source project (<a href="http://www.hotwire-shell.org/">hotwire</a>) and wanted to do a few changes to the code that <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/externals/shlex.py">lexes</a>, <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/command.py">parses and tokenises</a> the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.</p> <p>I haven't worked on code to lex/parse/tokenise before, so I was thinking one approach would be to work through a tutorial or two on this aspect. I would hope to learn enough to navigate around the code I actually want to alter. Is there anything suitable out there? (Ideally it could be done in an afternoon without having to buy and read the dragon book first ...)</p> <p><strong>Edit:</strong> (7 Oct 2008) None of the below answers quite give what I want. With them I could generate parsers from scratch, but I want to learn how to write my own basic parser from scratch, not using lex and yacc or similar tools. Having done that I can then understand the existing code better. </p> <p>So could someone point me to a tutorial where I can build a basic parser from scratch, using just python?</p>
<p>I'm a happy user of <a href="http://www.dabeaz.com/ply/">PLY</a>. It is a pure-Python implementation of Lex &amp; Yacc, with lots of small niceties that make it quite Pythonic and easy to use. Since Lex &amp; Yacc are the most popular lexing &amp; parsing tools and are used for the most projects, PLY has the advantage of standing on giants' shoulders. A lot of knowledge exists online on Lex &amp; Yacc, and you can freely apply it to PLY.</p> <p>PLY also has a good <a href="http://www.dabeaz.com/ply/ply.html">documentation page</a> with some simple examples to get you started. </p> <p>For a listing of lots of Python parsing tools, see <a href="http://nedbatchelder.com/text/python-parsers.html">this</a>.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "django" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How to make Ruby or Python web sites to use multiple cores?
<p>Even though <a href="http://twistedmatrix.com/pipermail/twisted-python/2004-May/007896.html">Python</a> and <a href="http://www.reddit.com/comments/6wmum/thread_safe_ruby_on_rails_in_22_release/">Ruby</a> have one kernel thread per interpreter thread, they have a global interpreter lock (GIL) that is used to protect potentially shared data structures, so this inhibits multi-processor execution. Even though the portions in those languajes that are written in C or C++ can be free-threaded, that's not possible with pure interpreted code unless you use multiple processes. What's the best way to achieve this? <a href="http://blogs.codehaus.org/people/tirsen/archives/001041_ruby_on_rails_and_fastcgi_scaling_using_processes_instead_of_threads.html">Using FastCGI</a>? Creating a <a href="http://blog.innerewut.de/files/images/stage_2.png">cluster or a farm</a> of virtualized servers? Using their Java equivalents, JRuby and Jython?</p>
<p>I'm not totally sure which problem you want so solve, but if you deploy your python/django application via an apache prefork MPM using mod_python apache will start several worker processes for handling different requests.</p> <p>If one request needs so much resources, that you want to use multiple cores have a look at <a href="http://pyprocessing.berlios.de/" rel="nofollow">pyprocessing</a>. But I don't think that would be wise.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "html" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How can I simply inherit methods from an existing instance?
<p>below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.</p> <pre><code>import cgi class ClassX(object): pass # ... with own __repr__ class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("&lt;H1&gt;","&lt;/H1&gt;")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() </code></pre> <p>Output:</p> <pre>Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters</pre> <p>Is what I'm trying to do possible? If so, what am I doing wrong?</p>
<blockquote> <p>Very close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way.</p> </blockquote> <p>Looks like you're trying to set up some sort of proxy object scheme. That's doable, and there are better solutions than your colleague's, but first consider whether it would be easier to just patch in some extra methods. This won't work for built-in classes like <code>bool</code>, but it will for your user-defined classes:</p> <pre><code>def HTMLDecorator (obj): def html (): sep = cgi.escape (repr (obj)) return sep.join (("&lt;H1&gt;", "&lt;/H1&gt;")) obj.html = html return obj </code></pre> <p>And here is the proxy version:</p> <pre><code>class HTMLDecorator(object): def __init__ (self, wrapped): self.__wrapped = wrapped def html (self): sep = cgi.escape (repr (self.__wrapped)) return sep.join (("&lt;H1&gt;", "&lt;/H1&gt;")) def __getattr__ (self, name): return getattr (self.__wrapped, name) def __setattr__ (self, name, value): if not name.startswith ('_HTMLDecorator__'): setattr (self.__wrapped, name, value) return super (HTMLDecorator, self).__setattr__ (name, value) def __delattr__ (self, name): delattr (self.__wraped, name) </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python-3.x" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Filter out HTML tags and resolve entities in python
<p>Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python.</p>
<p>Use <a href="http://codespeak.net/lxml/lxmlhtml.html">lxml</a> which is the best xml/html library for python.</p> <pre><code>import lxml.html t = lxml.html.fromstring("...") t.text_content() </code></pre> <p>And if you just want to sanitize the html look at the lxml.html.clean <a href="http://codespeak.net/lxml/lxmlhtml.html#cleaning-up-html">module</a></p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "csv" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
What's the easiest way to read a FoxPro DBF file from Python?
<p>I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too.</p> <p><strong>Update</strong>: Thanks @cnu, I used Yusdi Santoso's <a href="http://www.physics.ox.ac.uk/users/santoso/dbf.py.src"><code>dbf.py</code></a> and it works nicely. One gotcha: The memo file name extension must be lower case, i.e. <code>.fpt</code>, not <code>.FPT</code> which was how the filename came over from Windows.</p>
<p>I prefer <a href="http://sourceforge.net/projects/dbfpy/">dbfpy</a>. It supports both reading and writing of <code>.DBF</code> files and can cope with most variations of the format. It's the only implementation I have found that could both read and write the legacy DBF files of some older systems I have worked with.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "csv" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
What are Class methods in Python for?
<p>I'm teaching myself Python and my most recent lesson was that <a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>, and so I've just spent a while turning all my Class methods into functions.</p> <p>I now realise that I don't need to use Class methods for what I would done with <code>static</code> methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.</p> <p>Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?</p>
<p>Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functions.</p> <p>If you have a class <code>MyClass</code>, and a module-level function that operates on MyClass (factory, dependency injection stub, etc), make it a <code>classmethod</code>. Then it'll be available to subclasses.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "mysql" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Retrieving an Oracle timestamp using Python's Win32 ODBC module
<p>Given an Oracle table created using the following:</p> <pre><code>CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE); </code></pre> <p>Using the Python ODBC module from its <a href="http://www.python.org/download/windows/" rel="nofollow">Win32 extensions</a> (from the win32all package), I tried the following:</p> <pre><code>import dbi, odbc connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD") cursor = connection.cursor() cursor.execute("SELECT WhenAdded FROM Log") results = cursor.fetchall() </code></pre> <p>When I run this, I get the following:</p> <pre><code>Traceback (most recent call last): ... results = cursor.fetchall() dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH </code></pre> <p>The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps?</p>
<p>I believe this is a bug in the Oracle ODBC driver. Basically, the Oracle ODBC driver does not support the <code>TIMESTAMP WITH (LOCAL) TIME ZONE</code> data types, only the <code>TIMESTAMP</code> data type. As you have discovered, one workaround is in fact to use the <code>TO_CHAR</code> method.</p> <p>In your example you are not actually reading the time zone information. If you have control of the table you could convert it to a straight <code>TIMESTAMP</code> column. If you don't have control over the table, another solution may be to create a view that converts from <code>TIMESTAMP WITH TIME ZONE</code> to <code>TIMESTAMP</code> via a string - sorry, I don't know if there is a way to convert directly from <code>TIMESTAMP WITH TIME ZONE</code> to <code>TIMESTAMP</code>.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "google-app-engine" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
What's the best way to return multiple values from a function in Python?
<p>I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. </p> <p>In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.</p> <p>Related question: <a href="http://stackoverflow.com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values">Is it pythonic for a function to return multiple values?</a></p>
<pre><code>def f(in_str): out_str = in_str.upper() return True, out_str # Creates tuple automatically succeeded, b = f("a") # Automatic tuple unpacking </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "tkinter" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Using Django time/date widgets in custom form
<p>How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?</p> <p>I have looked through <a href="https://docs.djangoproject.com/en/dev/topics/forms/">the Django forms documentation</a>, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?</p> <p>Here is my template that I want it applied on.</p> <pre><code>&lt;form action="." method="POST"&gt; &lt;table&gt; {% for f in form %} &lt;tr&gt; &lt;td&gt; {{ f.name }}&lt;/td&gt; &lt;td&gt;{{ f }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;input type="submit" name="submit" value="Add Product"&gt; &lt;/form&gt; </code></pre> <p>Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:</p> <pre><code>(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...</p>
<p>The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that.</p> <p>That said, here's what you have to do if you're determined to make this work:</p> <ol> <li><p>Define your own ModelForm subclass for your model (best to put it in forms.py in your app), and tell it to use the AdminDateWidget / AdminTimeWidget / AdminSplitDateTime (replace 'mydate' etc with the proper field names from your model):</p> <pre><code>from django import forms from my_app.models import Product from django.contrib.admin import widgets class ProductForm(forms.ModelForm): class Meta: model = Product def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['mydate'].widget = widgets.AdminDateWidget() self.fields['mytime'].widget = widgets.AdminTimeWidget() self.fields['mydatetime'].widget = widgets.AdminSplitDateTime() </code></pre></li> <li><p>Change your URLconf to pass 'form_class': ProductForm instead of 'model': Product to the generic create_object view (that'll mean "from my_app.forms import ProductForm" instead of "from my_app.models import Product", of course).</p></li> <li><p>In the head of your template, include {{ form.media }} to output the links to the Javascript files.</p></li> <li><p>And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically. So in your template above {{ form.media }} you'll need:</p> <pre><code>&lt;script type="text/javascript" src="/my_admin/jsi18n/"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/media/admin/js/core.js"&gt;&lt;/script&gt; </code></pre> <p>You may also wish to use the following admin CSS (thanks <a href="http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/719583#719583">Alex</a> for mentioning this):</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/&gt; &lt;link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/&gt; &lt;link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/&gt; &lt;link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/&gt; </code></pre></li> </ol> <p>This implies that Django's admin media (ADMIN_MEDIA_PREFIX) is at /media/admin/ - you can change that for your setup. Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question.</p> <p>This also requires that the URL /my_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript_catalog view (or null_javascript_catalog if you aren't using I18N). You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks <a href="http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/408230#408230">Jeremy</a> for pointing this out). Sample code for your URLconf:</p> <pre><code>(r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'), </code></pre> <p>Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media:</p> <pre><code>{% load adminmedia %} /* At the top of the template. */ /* In the head section of the template. */ &lt;script type="text/javascript"&gt; window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}"; &lt;/script&gt; </code></pre> <p>Thanks <a href="http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form/2818128#2818128">lupefiasco</a> for this addition.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python-2.7" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How to merge two Python dictionaries in a single expression?
<p>I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = x.update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1, 'b': 10, 'c': 11} </code></pre> <p>How can I get that final merged dict in z, not x?</p> <p>(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)</p>
<p>In your case, what you can do is:</p> <pre><code>z = dict(x.items() + y.items()) </code></pre> <p>This will, as you want it, put the final dict in <code>z</code>, and make the value for key <code>b</code> be properly overridden by the second (<code>y</code>) dict's value:</p> <pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2} &gt;&gt;&gt; y = {'b':10, 'c': 11} &gt;&gt;&gt; z = dict(x.items() + y.items()) &gt;&gt;&gt; z {'a': 1, 'c': 11, 'b': 10} </code></pre> <p>If you use Python 3, it is only a little more complicated. To create <code>z</code>:</p> <pre><code>&gt;&gt;&gt; z = dict(list(x.items()) + list(y.items())) &gt;&gt;&gt; z {'a': 1, 'c': 11, 'b': 10} </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "google-app-engine" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Search and replace a line in a file in Python
<p>I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.</p> <p>What is the best way to do this, within the following code?</p> <pre><code>f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file </code></pre>
<p>The shortest way would probably be to use the <a href="http://docs.python.org/2/library/fileinput.html?highlight=fileinput#fileinput">fileinput module</a>. For example, the following adds line numbers to a file, in-place:</p> <pre><code>import fileinput for line in fileinput.input("test.txt", inplace=True): print "%d: %s" % (fileinput.filelineno(), line), </code></pre> <p>What happens here is:</p> <ol> <li>The original file is moved to a backup file</li> <li>The standard output is redirected to the original file within the loop</li> <li>Thus any <code>print</code> statements write back into the original file</li> </ol> <p><code>fileinput</code> has more bells and whistles. For example, it can be used to automatically operate on all files in <code>sys.args[1:]</code>, without your having to iterate over them explicitly. Starting with Python 3.2 it also provides a convenient context manager for use in a <code>with</code> statement.</p> <hr> <p>While <code>fileinput</code> is great for throwaway scripts, I would be wary of using it in real code because admittedly it's not very readable or familiar. In real (production) code it's worthwhile to spend just a few more lines of code to make the process explicit and thus make the code readable.</p> <p>There are two options:</p> <ol> <li>The file is not overly large, and you can just read it wholly to memory. Then close the file, reopen it in writing mode and write the modified contents back.</li> <li>The file is too large to be stored in memory; you can move it over to a temporary file and open that, reading it line by line, writing back into the original file. Note that this requires twice the storage.</li> </ol>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "tkinter" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Finding a file in a Python module distribution
<p>I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypackage/).</p> <p>How do I store the final location of the database file so my code can access it? Right now, I'm using a hack based on the <code>__file__</code> variable in the module which accesses the database:</p> <pre> dbname = os.path.join(os.path.dirname(__file__), "database.dat") </pre> <p>It works, but it seems... hackish. Is there a better way to do this? I'd like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig.py" file that gets installed alongside the code that accesses the database.</p>
<p>Try using pkg_resources, which is part of setuptools (and available on all of the pythons I have access to right now):</p> <pre><code>&gt;&gt;&gt; import pkg_resources &gt;&gt;&gt; pkg_resources.resource_ filename(__name__, "foo.config") 'foo.config' &gt;&gt;&gt; pkg_resources.resource_filename('tempfile', "foo.config") '/usr/lib/python2.4/foo.config' </code></pre> <p>There's more discussion about using pkg_resources to get resources on the <a href="http://peak.telecommunity.com/DevCenter/PythonEggs#accessing-package-resources">eggs</a> page and the <a href="http://peak.telecommunity.com/DevCenter/PkgResources">pkg_resources</a> page.</p> <p>Also note, where possible it's probably advisable to use pkg_resources.resource_stream or pkg_resources.resource_string because if the package is part of an egg, resource_filename will copy the file to a temporary directory.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "regex" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
What is the best way to do Bit Field manipulation in Python?
<p>I'm reading some MPEG Transport Stream protocol over UDP and it has some funky bitfields in it (length 13 for example). I'm using the "struct" library to do the broad unpacking, but is there a simple way to say "Grab the next 13 bits" rather than have to hand-tweak the bit manipulation? I'd like something like the way C does bit fields (without having to revert to C).</p> <p>Suggestions?</p>
<p>The <a href="http://python-bitstring.googlecode.com">bitstring</a> module is designed to address just this problem. It will let you read, modify and construct data using bits as the basic building blocks. The latest versions are for Python 2.6 or later (including Python 3) but version 1.0 supported Python 2.4 and 2.5 as well.</p> <p>A relevant example for you might be this, which strips out all the null packets from a transport stream (and quite possibly uses your 13 bit field?):</p> <pre><code>from bitstring import Bits, BitStream # Opening from a file means that it won't be all read into memory s = Bits(filename='test.ts') outfile = open('test_nonull.ts', 'wb') # Cut the stream into 188 byte packets for packet in s.cut(188*8): # Take a 13 bit slice and interpret as an unsigned integer PID = packet[11:24].uint # Write out the packet if the PID doesn't indicate a 'null' packet if PID != 8191: # The 'bytes' property converts back to a string. outfile.write(packet.bytes) </code></pre> <p>Here's another example including reading from bitstreams: </p> <pre><code># You can create from hex, binary, integers, strings, floats, files... # This has a hex code followed by two 12 bit integers s = BitStream('0x000001b3, uint:12=352, uint:12=288') # Append some other bits s += '0b11001, 0xff, int:5=-3' # read back as 32 bits of hex, then two 12 bit unsigned integers start_code, width, height = s.readlist('hex:32, 2*uint:12') # Skip some bits then peek at next bit value s.pos += 4 if s.peek(1): flags = s.read(9) </code></pre> <p>You can use standard slice notation to slice, delete, reverse, overwrite, etc. at the bit level, and there are bit level find, replace, split etc. functions. Different endiannesses are also supported.</p> <pre><code># Replace every '1' bit by 3 bits s.replace('0b1', '0b001') # Find all occurrences of a bit sequence bitposlist = list(s.findall('0b01000')) # Reverse bits in place s.reverse() </code></pre> <p>The full documentation is <a href="http://packages.python.org/bitstring/">here</a>.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "google-app-engine" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Using C in a shared multi-platform POSIX environment
<p>I write tools that are used in a shared workspace. Since there are multiple OS's working in this space, we generally use Python and standardize the version that is installed across machines. However, if I wanted to write some things in C, I was wondering if maybe I could have the application wrapped in a Python script, that detected the operating system and fired off the correct version of the C application. Each platform has GCC available and uses the same shell.</p> <p>One idea was to have the C compiled to the users local ~/bin, with timestamp comparison with C code so it is not compiled each run, but only when code is updated. Another was to just compile it for each platform, and have the wrapper script select the proper executable.</p> <p>Is there an accepted/stable process for this? Are there any catches? Are there alternatives (assuming the absolute need to use native C code)?</p> <p><em>Clarification: Multiple OS's are involved that do not share ABI. Eg. OS X, various Linuxes, BSD etc. I need to be able to update the code in place in shared folders and have the new code working more or less instantaneously. Distributing binary or source packages is less than ideal.</em></p>
<p>Launching a Python interpreter instance just to select the right binary to run would be much heavier than you need. I'd distribute a shell .rc file which provides aliases.</p> <p>In /shared/bin, you put the various binaries: /shared/bin/toolname-mac, /shared/bin/toolname-debian-x86, /shared/bin/toolname-netbsd-dreamcast, etc. Then, in the common shared shell .rc file, you put the logic to set the aliases according to platform, so that on OSX, it gets alias toolname=/shared/bin/toolname-mac, and so forth.</p> <p>This won't work as well if you're adding new tools all the time, because the users will need to reload the aliases.</p> <p>I wouldn't recommend distributing tools this way, though. Testing and qualifying new builds of the tools should be taking up enough time and effort that the extra time required to distribute the tools to the users is trivial. You seem to be optimizing to reduce the distribution time. Replacing tools that quickly in a live environment is all too likely to result in lengthy and confusing downtime if anything goes wrong in writing and building the tools--especially when subtle cross-platform issues creep in.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "django" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
PGP signatures from Python?
<p>What is the easiest way to create and verify PGP/GPG signatures from within a Python application? </p> <p>I can call pgp or gpg using subprocess and parse the output, but I was looking for a way that didn't require an external program to be installed (my application is cross-platform mac/windows/unix).</p>
<p>I think <a href="http://www.gnupg.org/related_software/gpgme/" rel="nofollow">GPGME</a> and the <a href="http://pyme.sourceforge.net/" rel="nofollow">PyMe Python wrapper</a> should do what you need.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "google-app-engine" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
javascript locals()?
<p>In python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in javascript? For instance, I would like to do something like the following:</p> <pre><code>var foo = function(){ alert('foo'); }; var bar = function(){ alert('bar'); }; var s = 'foo'; locals()[s](); // alerts 'foo' </code></pre> <p>Is this at all possible, or should I just be using a local object for the lookup?</p>
<ul> <li><p>locals() - No. </p></li> <li><p>globals() - Yes.</p></li> </ul> <p><code>window</code> is a reference to the global scope, like <code>globals()</code> in python.</p> <pre><code>globals()["foo"] </code></pre> <p>is the same as:</p> <pre><code>window["foo"] </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "mysql" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
cx_Oracle: how do I get the ORA-xxxxx error number?
<p>In a try/except block, how do I extract the Oracle error number?</p>
<pre><code>try: cursor.execute("select 1 / 0 from dual") except cx_Oracle.DatabaseError, exc: error, = exc print "Code:", error.code print "Message:", error.message </code></pre> <p>This results in the following output:</p> <pre><code>Code: 1476 Message: ORA-01476: divisor is equal to zero </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python-2.7" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Python deployment and /usr/bin/env portability
<p>At the beginning of all my executable Python scripts I put the <a href="http://en.wikipedia.org/wiki/Shebang_(Unix)">shebang</a> line:</p> <pre><code>#!/usr/bin/env python </code></pre> <p>I'm running these scripts on a system where <code>env python</code> yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version:</p> <pre><code>if sys.version_info &lt; (2, 4): raise ImportError("Cannot run with Python version &lt; 2.4") </code></pre> <p>I don't want to have to change the shebang line on every executable file, if it's possible; however, I don't have administrative access to the machine to change the result of <code>env python</code> and I don't want to force a particular version, as in:</p> <pre><code>#!/usr/bin/env python2.4 </code></pre> <p>I'd like to avoid this because system may have a newer version than Python 2.4, or may have Python 2.5 but no Python 2.4.</p> <p>What's the elegant solution?</p> <p>[Edit:] I wasn't specific enough in posing the question -- I'd like to let users execute the scripts without manual configuration (e.g. path alteration or symlinking in <code>~/bin</code> and ensuring your PATH has <code>~/bin</code> before the Python 2.2 path). Maybe some distribution utility is required to prevent the manual tweaks?</p>
<p>"env" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "dictionary" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Always including the user in the django template context
<p>I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.</p> <p>In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?</p> <p>Or will I have to make my own custom shortcuts to setup the context properly?</p>
<p>There is <strong>no need</strong> to write a context processor for the user object if you already have the <a href="https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates"><code>"django.core.context_processors.auth"</code></a> in <a href="https://docs.djangoproject.com/en/dev/ref/settings/#std%3asetting-TEMPLATE_CONTEXT_PROCESSORS"><code>TEMPLATE_CONTEXT_PROCESSORS</code></a> <strong>and</strong> if you're using <a href="https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext"><code>RequestContext</code></a> in your views. </p> <p>if you are using django 1.4 or latest the module has been moved to <code>django.contrib.auth.context_processors.auth</code></p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How do I do monkeypatching in python?
<p>I've had to do some introspection in python and it wasn't pretty:</p> <pre><code>name = sys._getframe(1).f_code name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name) </code></pre> <p>To get something like</p> <pre><code>foo.py:22 bar() blah blah </code></pre> <p>In our debugging output.</p> <p>I'd ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python?</p>
<p>A print statement does its IO through "sys.stdout.write" so you can override sys.stdout if you want to manipulate the print stream.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "pandas" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Splitting tuples in Python - best practice?
<p>I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)</p> <p>For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this: (jobId, label, username) = job</p> <p>I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?</p> <p>Here are my two best guesses: (jobId, label, username) = (job[0], job[1], job[2]) ...but that doesn't scale nicely when you have 15...20 fields</p> <p>or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)</p>
<p>I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values.</p> <p>For example:</p> <pre><code>job={} job['jobid'], job['label'], job['username']=&lt;querycode&gt; </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "arrays" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Standard way to open a folder window in linux?
<p>I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application.</p> <p>On OSX, I can open a window in the finder with</p> <pre><code>os.system('open "%s"' % foldername) </code></pre> <p>and on Windows with</p> <pre><code>os.startfile(foldername) </code></pre> <p>What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)?</p> <p>This looks like something that could be specified by the <a href="http://freedesktop.org">freedesktop.org</a> folks (a python module, similar to <code>webbrowser</code>, would also be nice!).</p>
<pre><code>os.system('xdg-open "%s"' % foldername) </code></pre> <p><code>xdg-open</code> can be used for files/urls also</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "tkinter" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
What is a tuple useful for?
<p>I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this different from a list?</p>
<ul> <li>Tuples are used whenever you want to return multiple results from a function.</li> <li>Since they're immutable, they can be used as keys for a dictionary (lists can't).</li> </ul>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "pandas" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Best way to extract text from a Word doc without using COM/automation?
<p>Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.)</p> <p>Antiword seems like it might be a reasonable option, but it seems like it might be abandoned.</p> <p>A Python solution would be ideal, but doesn't appear to be available.</p>
<p>(Same answer as <a href="http://stackoverflow.com/questions/125222/extracting-text-from-ms-word-files-in-python">extracting text from MS word files in python</a>)</p> <p>Use the native Python docx module which I made this week. Here's how to extract all the text from a doc:</p> <pre><code>document = opendocx('Hello world.docx') # This location is where most document content lives docbody = document.xpath('/w:document/w:body', namespaces=wordnamespaces)[0] # Extract all text print getdocumenttext(document) </code></pre> <p>See <a href="https://python-docx.readthedocs.org/en/latest/">Python DocX site</a></p> <p>100% Python, no COM, no .net, no Java, no parsing serialized XML with regexs, no crap.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Python re.sub MULTILINE caret match
<p>The Python docs say:</p> <blockquote> <p>re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...</p> </blockquote> <p>So what's going on when I get the following unexpected result?</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = """// The quick brown fox. ... // Jumped over the lazy dog.""" &gt;&gt;&gt; re.sub('^//', '', s, re.MULTILINE) ' The quick brown fox.\n// Jumped over the lazy dog.' </code></pre>
<p>Look at the definition of <a href="http://docs.python.org/library/re.html#re.sub"><code>re.sub</code></a>:</p> <pre><code>sub(pattern, repl, string[, count]) </code></pre> <p>The 4th argument is the count, you are using <code>re.MULTILINE</code> (which is 8) as the count, not as a flag.</p> <p>You have to compile your regex if you wish to use flags.</p> <pre><code>re.sub(re.compile('^//', re.MULTILINE), '', s) </code></pre> <p>A <code>flags</code> argument was added in Python 2.7, so the full definition is now:</p> <pre><code>re.sub(pattern, repl, string[, count, flags]) </code></pre> <p>Which means that:</p> <pre><code>re.sub('^//', '', s, flags=re.MULTILINE) </code></pre> <p>works.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "string" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Get Last Day of the Month in Python
<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p> <p>If the standard library doesn't support that, does the dateutil package support this?</p>
<p>I didn't notice this earlier when I was looking at the <a href="https://docs.python.org/2/library/calendar.html">documentation for the calendar module</a>, but a method called <a href="http://docs.python.org/library/calendar.html#calendar.monthrange">monthrange</a> provides this information:</p> <blockquote> <p><b>monthrange(year, month)</b><br> &nbsp;&nbsp;&nbsp;&nbsp;Returns weekday of first day of the month and number of days in month, for the specified year and month. </p> </blockquote> <pre><code>&gt;&gt;&gt; import calendar &gt;&gt;&gt; calendar.monthrange(2002,1) (1, 31) &gt;&gt;&gt; calendar.monthrange(2008,2) (4, 29) &gt;&gt;&gt; calendar.monthrange(2100,2) (0, 28) </code></pre> <p>so:</p> <pre><code>calendar.monthrange(year, month)[1] </code></pre> <p>seems like the simplest way to go.</p> <p>Just to be clear, <code>monthrange</code> supports leap years as well:</p> <pre><code>&gt;&gt;&gt; from calendar import monthrange &gt;&gt;&gt; monthrange(2012, 2) (2, 29) </code></pre> <p><a href="http://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python#43088">My previous answer</a> still works, but is clearly suboptimal.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python-3.x", "pandas" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How can I get a commit message from a bzr post-commit hook?
<p>I'm trying to write a bzr post-commit hook for my private bugtracker, but I'm stuck at the function signature of post_commit(local, master, old_revno, old_revid, new_revno, mew_revid). How can I extract the commit message for the branch from this with bzrlib in Python?</p>
<p>And the answer is like so:</p> <pre><code>def check_commit_msg(local, master, old_revno, old_revid, new_revno, new_revid): branch = local or master revision = branch.repository.get_revision(new_revid) print revision.message </code></pre> <p>local and master are Branch objects, so once you have a revision, it's easy to extract the message.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "list" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How to generate urls in django
<p>In Django's template language, you can use <code>{% url [viewname] [args] %}</code> to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?</p> <p>What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.</p>
<p>If you need to use something similar to the <code>{% url %}</code> template tag in your code, Django provides the <code>django.core.urlresolvers.reverse()</code>. The <code>reverse</code> function has the following signature:</p> <pre><code>reverse(viewname, urlconf=None, args=None, kwargs=None) </code></pre> <p><a href="https://docs.djangoproject.com/en/dev/ref/urlresolvers/">https://docs.djangoproject.com/en/dev/ref/urlresolvers/</a></p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "string" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Can I write native iPhone apps using Python
<p>Using <a href="http://pyobjc.sourceforge.net/">PyObjC</a>, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?</p>
<p>You can use PyObjC on the iPhone as well, due to the excellent work by Jay Freeman (saurik). See <a href="http://www.saurik.com/id/5">iPhone Applications in Python</a>.</p> <p>Note that this requires a jailbroken iPhone at the moment.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "csv" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
A python web application framework for tight DB/GUI coupling?
<p>I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field.</p> <p>And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM.</p> <p>I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality.</p> <p>Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc.</p> <p>E.g., it should ideally be able to:</p> <ul> <li><strong>automatically select a suitable form widget</strong> for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown</li> <li><strong>auto-generate javascript form validation code</strong> which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc</li> <li>auto-generate a <strong>calendar widget</strong> for data which will end up in a DATE column</li> <li><strong>hint NOT NULL constraints</strong> as javascript which complains about empty or whitespace-only data in a related input field</li> <li>generate javascript validation code which matches relevant (simple) <strong>CHECK-constraints</strong></li> <li>make it easy to <strong>avoid SQL injection</strong>, by using prepared statements and/or validation of externally derived data</li> <li>make it easy to <strong>avoid cross site scripting</strong> by automatically escape outgoing strings when appropriate</li> <li><strong>make use of constraint names</strong> to generate somewhat user friendly error messages in case a constrataint is violated</li> </ul> <p>All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database.</p> <p>Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?</p>
<p>web2py does most of what you ask:</p> <p>Based on a field type and its validators it will render the field with the appropriate widget. You can override with</p> <pre><code>db.table.field.widget=... </code></pre> <p>and use a third party widget.</p> <p>web2py has js to blocks the user from entering a non-integer in a integer field or a non-double in a double field. time, date and datetime fields have their own pickers. These js validation work with (not instead) of server side validation.</p> <p>There is <code>IS_EMPTY_OR(...)</code> validator.</p> <p>The DAL prevents SQL injections since everthing is escaped when goes in the DB.</p> <p>web2py prevents XSS because in {{=variable}}, 'variable' is escaped unless specified otherwise {{=XML(variable)}} or {{=XML(variable,sanitize=True)}}</p> <p>Error messages are arguments of validators for example</p> <pre><code>db.table.field.requires=IS_NOT_EMPTY(error_message=T('hey! write something in here')) </code></pre> <p>T is for internationalization.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "google-app-engine" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How to find the mime type of a file in python?
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p> <p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p> <p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p> <p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p> <p>Does the browser add this information when posting the file to the web page?</p> <p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
<p>The python-magic method suggested by toivotuo is outdated. <a href="http://github.com/ahupp/python-magic">Python-magic's</a> current trunk is at Github and based on the readme there, finding the MIME-type, is done like this.</p> <pre><code># For MIME types &gt;&gt;&gt; import magic &gt;&gt;&gt; mime = magic.Magic(mime=True) &gt;&gt;&gt; mime.from_file("testdata/test.pdf") 'application/pdf' &gt;&gt;&gt; </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "arrays" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Pros and Cons of different approaches to web programming in Python
<p>I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that.</p> <p>It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like <a href="http://webpy.org/">web.py</a>, <a href="http://pyroxide.org/">Pyroxide</a> and <a href="http://wiki.python.org/moin/Django">Django</a>.</p> <ul> <li>What are the <strong>pros</strong> and <strong>cons</strong> of the frameworks or approaches that <em>you've worked on</em>?</li> <li>What <strong>trade-offs</strong> are there?</li> <li>For <strong>what kind of projects</strong> they do well and for what they don't?</li> </ul> <p>Edit: I haven't got much experience with web programing yet.<br /> I would like to avoid the basic and tedious things like parsing the URL for parameters, etc.<br /> On the other hand, while the video of <a href="http://www.rubyonrails.org/screencasts">blog created in 15 minutes</a> with <a href="http://www.rubyonrails.org/">Ruby on Rails</a> left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now.</p>
<p>CGI is great for low-traffic websites, but it has some performance problems for anything else. This is because every time a request comes in, the server starts the CGI application in its own process. This is bad for two reasons: 1) Starting and stopping a process can take time and 2) you can't cache anything in memory. You can go with FastCGI, but I would argue that you'd be better off just writing a straight <a href="http://www.python.org/dev/peps/pep-0333/">WSGI</a> app if you're going to go that route (the way WSGI works really isn't a whole heck of a lot different from CGI).</p> <p>Other than that, your choices are for the most part how much you want the framework to do. You can go with an all singing, all dancing framework like Django or Pylons. Or you can go with a mix-and-match approach (use something like CherryPy for the HTTP stuff, SQLAlchemy for the database stuff, paste for deployment, etc). I should also point out that most frameworks will also let you switch different components out for others, so these two approaches aren't necessarily mutually exclusive.</p> <p>Personally, I dislike frameworks that do too much magic for me and prefer the mix-and-match technique, but I've been told that I'm also completely insane. :)</p> <p>How much web programming experience do you have? If you're a beginner, I say go with Django. If you're more experienced, I say to play around with the different approaches and techniques until you find the right one.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "flask" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Modulus operation with negatives values - weird thing?
<p>Can you please tell me how much is <code>(-2) % 5</code>? According to my Python interpreter is 3, but do you have a wise explanation for this?</p> <p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
<p>By the way: most programming languages would disagree with Python and give the result <code>-2</code>. Depending on the interpretation of modulus this is correct. However, the most agreed-upon mathematical definition states that the modulus of <em>a</em> and <em>b</em> is the (strictly positive) rest <em>r</em> of the division of <em>a</em> / <em>b</em>. More precisely, 0 &lt;= <em>r</em> &lt; <em>b</em> by definition.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "list" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How do I document a module in Python?
<p>That's it. If you want to document a function or a class, you put a string just after the definition. For instance:</p> <pre><code>def foo(): """This function does nothing.""" pass </code></pre> <p>But what about a module? How can I document what a <em>file.py</em> does?</p>
<p>For the packages, you can document it in <code>__init__.py</code>. For the modules, you can add a docstring simply in the module file.</p> <p>All the information is here: <a href="http://www.python.org/dev/peps/pep-0257/">http://www.python.org/dev/peps/pep-0257/</a></p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "arrays" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Iterate over subclasses of a given class in a given module
<p>In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?</p>
<p>Although Quamrana's suggestion works fine, there are a couple of possible improvements I'd like to suggest to make it more pythonic. They rely on using the inspect module from the standard library.</p> <ol> <li>You can avoid the getattr call by using <code>inspect.getmembers()</code></li> <li>The try/catch can be avoided by using <code>inspect.isclass()</code></li> </ol> <p>With those, you can reduce the whole thing to a single list comprehension if you like:</p> <pre><code>def find_subclasses(module, clazz): return [ cls for name, cls in inspect.getmembers(module) if inspect.isclass(cls) and issubclass(cls, clazz) ] </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "json" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How would you make a comma-separated string from a list?
<p>What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, <code>[ 'a', 'b', 'c' ]</code> to <code>'a,b,c'</code>? (The cases <code>[ s ]</code> and <code>[]</code> should be mapped to <code>s</code> and <code>''</code>, respectively.)</p> <p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p> <p>Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed "simple" concatenation in the past and somehow memorised <code>s.join([e1,e2,...])</code> as a shorthand for <code>s+e1+e2+...</code>.)</p>
<pre><code>myList = ['a','b','c','d'] myString = ",".join(myList ) </code></pre> <p>This won't work if the list contains numbers.</p> <hr> <p>As <a href="http://stackoverflow.com/users/3399/ricardo-reyes">Ricardo Reyes</a> suggested, if it contains non-string types (such as integers, floats, bools, None) then do:</p> <pre><code>myList = ','.join(map(str, myList)) </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "csv" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Can someone explain __all__ in Python?
<p>I have been using Python more and more, and I keep seeing the variable <code>__all__</code> set in different <code>__init__.py</code> files. Can someone explain what this does?</p>
<p>Linked to, but not explicitly mentioned here, is exactly when <code>__all__</code> is used. It is a list of strings defining what symbols in a module will be exported when <code>from &lt;module&gt; import *</code> is used on the module.</p> <p>For example, the following code in a <code>foo.py</code> explicitly exports the symbols <code>bar</code> and <code>baz</code>:</p> <pre><code>__all__ = ['bar', 'baz'] waz = 5 bar = 10 def baz(): return 'baz' </code></pre> <p>These symbols can then be imported like so:</p> <pre><code>from foo import * print bar print baz # The following will trigger an exception, as "waz" is not exported by the module print waz </code></pre> <p>If the <code>__all__</code> above is commented out, this code will then execute to completion, as the default behaviour of <code>import *</code> is to import all symbols that do not begin with an underscore, from the given namespace.</p> <p>Reference: <a href="https://docs.python.org/3.5/tutorial/modules.html#importing-from-a-package">https://docs.python.org/3.5/tutorial/modules.html#importing-from-a-package</a></p> <p><strong>NOTE:</strong> <code>__all__</code> affects the <code>from &lt;module&gt; import *</code> behavior only. Members that are not mentioned in <code>__all__</code> are still accessible from outside the module and can be imported with <code>from &lt;module&gt; import &lt;member&gt;</code>.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "list" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Can the HTTP version or headers affect the visual appearance of a web page?
<p>I know, I would have thought the answer was obviously "no" as well, but I am experiencing a strange situation where when I view my site from our staging server it appears slightly larger than when I view it from my local dev server. I have used Charles to confirm that all of the content -- the HTML, the images, the CSS, the javascript, <strong>everything</strong> is the same.</p> <p>The ONLY difference in the traffic is that (because the local site is served from the Django development mode server) the response headers look like this:</p> <pre><code>HTTP/1.0 200 OK Server WSGIServer/0.1 Python/2.5.2 Date Thu, 04 Sep 2008 23:56:10 GMT Vary Cookie Content-Length 2301 Content-Type text/html; charset=utf-8 </code></pre> <p>Whereas on the staging server (where Django is running inside Apache) the headers look like this:</p> <pre><code>HTTP/1.1 200 OK Date Thu, 04 Sep 2008 23:56:06 GMT Server Apache/2.2.8 (Ubuntu) mod_python/3.3.1 Python/2.5.2 PHP/5.2.4-2ubuntu5 with Suhosin-Patch Vary Cookie Content-Length 2301 Content-Type text/html; charset=utf-8 </code></pre> <p>So, as far as I can tell the only differences are HTTP/1.1 vs HTTP/1.0, the server identifer (Apache vs WSGIServer) and the order of the Date/Server headers.</p> <p>To elaborate a bit further on the differences in appearance, basically it appears as if the version of the site on the staging server is "zoomed in" by about 10%. For example, the primary logo which dominates our home page is 220 pixels wide but when server from our staging server shows up as 245 pixels wide. Everything else on the page, (other images, text, spacing, etc) is also proportionately larger.</p> <p>This is all in Firefox 3. I don't have any other browsers available to test with at the moment.</p> <p>Has anyone else encountered any bizarre behavior anything like this before? I am at a loss.</p>
<p>Have you tried View -> Zoom -> Reset on both sites?</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "html" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Python packages - import by class, not file
<p>Say I have the following file structure:</p> <pre><code>app/ app.py controllers/ __init__.py project.py plugin.py </code></pre> <p>If app/controllers/project.py defines a class Project, app.py would import it like this:</p> <pre><code>from app.controllers.project import Project </code></pre> <p>I'd like to just be able to do:</p> <pre><code>from app.controllers import Project </code></pre> <p>How would this be done?</p>
<p>You need to put</p> <pre><code>from project import Project </code></pre> <p>in <code>controllers/__init__.py</code>.</p> <p>Note that when <a href="http://www.python.org/dev/peps/pep-0328/" rel="nofollow">Absolute imports</a> become the default (Python 2.7?), you will want to add a dot before the module name (to avoid collisions with a top-level model named <code>project</code>), i.e.,</p> <pre><code>from .project import Project </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python-2.7" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Where can I find the time and space complexity of the built-in sequence types in Python
<p>I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?</p>
<p>Checkout the <a href="http://wiki.python.org/moin/TimeComplexity">TimeComplexity</a> page on the py dot org wiki. It covers set/dicts/lists/etc at least as far as time complexity goes.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "dictionary" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Wacom tablet Python interface
<p>If possible I want to catch pressure sensitive input from a Wacom tablet in Python. Are there any Python libraries available that can do this?</p>
<p>You could perhaps take a look at the <a href="http://www.alexmac.cc/tablet-apps/tablet-apps-0.3.1.tar.bz2" rel="nofollow">software</a> described <a href="http://www.alexmac.cc/tablet-apps/" rel="nofollow">here</a>. It is a gnome applet, written in Python.</p> <p>From the web site:</p> <p>"The gnome wacom applet is a small gnome panel applet that shows how much pressure is being applied to your wacom tablet by the current device. Clicking on the panel icon brings up a dialog allowing you to select a different device and check what pressure and tilt information is being recieved from it. This dialog also contains a small drawing test area to give your pen a quick test."</p> <p><a href="http://www.google.com/search?q=wacom+tablet+python" rel="nofollow">Google is your friend</a></p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "flask" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Is there a Python library for generating .ico files?
<p>I'm looking to create <code>favicon.ico</code> files programatically from Python, but PIL only has support for reading <code>ico</code> files.</p>
<p>Perhaps the following would work:</p> <ul> <li>Generate your icon image using PIL</li> <li>Convert the image to .ico format using the python interface to ImageMagick, <a href="http://www.imagemagick.org/download/python/">PythonMagick</a></li> </ul> <p>I have not tried this approach. The ImageMagick convert command line program was able to convert a .png file to .ico format, so at least ImageMagick supports the .ico format.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "flask" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How to know whether a window with a given title is already open in Tk?
<p>I’ve writen a little python script that just pops up a message box containing the text passed on the command line. I want to pop it up only when the window —resulting from a previous call— is not open.</p> <pre><code>from Tkinter import * import tkMessageBox root = Tk() root.withdraw() # TODO not if a window with this title exists tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:])) </code></pre> <p>Any idea how to check that?</p>
<p>I believe you want:</p> <pre><code>if 'normal' != root.state(): tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:])) </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "html" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Analizing MIPS binaries: is there a Python library for parsing binary data?
<p>I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debugging information.</p> <p>I'm currently planning to fork objdump, passing in a list of hex addresses and parsing the output to get function names and source line numbers. I have compiled an objdump with support for MIPS binaries, and it is working.</p> <p>I'd prefer to have a package allowing me to look things up natively from the Python code without forking another process. I can find no mention of libdwarf, libelf, or libbfd on python.org, nor any mention of python on dwarfstd.org.</p> <p>Is there a suitable module available somewhere?</p>
<p>You might be interested in the DWARF library from <a href="http://code.google.com/p/pydevtools/" rel="nofollow">pydevtools</a>:</p> <pre><code>&gt;&gt;&gt; from bintools.dwarf import DWARF &gt;&gt;&gt; dwarf = DWARF('test/test') &gt;&gt;&gt; dwarf.get_loc_by_addr(0x8048475) ('/home/emilmont/Workspace/dbg/test/main.c', 36, 0) </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "arrays" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Which Version of Python to Use for Maximum Compatibility
<p>If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system?</p> <p>I'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current version seems to be working fine. What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?</p>
<p>As python is in kind of an transition phase towards python 3 with breaking backward compatibility I don't think it is a good idea to go python 3 only. Based on the <a href="http://www.python.org/dev/peps/pep-3000/#timeline" rel="nofollow">time line</a> there will be at least one or two following releases of the 2.x series after 2.6/3.0 in october.</p> <p>Beside not having python 3 available on your target platforms, it will take some time until important external python libraries will be ported and usable on python 3.</p> <p>So as Matthew suggests staying at 2.4/2.5 and keeping the <a href="http://www.python.org/dev/peps/pep-3000/#compatibility-and-transition" rel="nofollow">transition</a> plan to python 3 in mind is a solid choice.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "regex" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Django: Print url of view without hardcoding the url
<p>Can i print out a url <code>/admin/manage/products/add</code> of a certain view in a template?</p> <p>Here is the rule i want to create a link for</p> <pre><code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), </code></pre> <p>I would like to have /manage/products/add in a template without hardcoding it. How can i do this?</p> <p><strong>Edit:</strong> I am not using the default admin (well, i am but it is at another url), this is my own</p>
<p>You can use <code>get_absolute_url</code>, but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case.</p> <p>You want to use <a href="https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns" rel="nofollow">named URL patterns</a>. Here's a quick intro:</p> <p>Change the line in your urls.py to:</p> <pre><code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, "create-product"), </code></pre> <p>Then, in your template you use this to display the URL:</p> <pre><code>{% url create-product %} </code></pre> <p>If you're using Django 1.5 or higher you need this:</p> <pre><code>{% url 'create-product' %} </code></pre> <p>You can do some more powerful things with named URL patterns, they're very handy. Note that they are only in the development version (and also 1.0).</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "csv" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How do you set up a python wsgi server under IIS?
<p>I work in a windows environment and would prefer to deploy code to IIS. At the same time I would like to code in python.</p> <p>Having read that IIS can run fastCGI application, I went to the IIS site where it describes in detail how to get PHP up and running but not much about anything else.</p> <p>Does anyone have experience getting a <strong>Python</strong> framework <strong>running under IIS</strong> using something other that plain old CGI?</p> <p>If so can you explain to direct me to some instructions on setting this up?</p>
<p>There shouldn't be any need to use FastCGI. There exists a <a href="https://github.com/hexdump42/isapi-wsgi">ISAPI extension for WSGI</a>.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "google-app-engine" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Is there a way to attach a debugger to a multi-threaded Python process?
<p>I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? </p> <p>Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)</p>
<p>Use <a href="http://winpdb.org/">Winpdb</a>. It is a <strong>platform independent</strong> graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.</p> <p>Features:</p> <ul> <li>GPL license. Winpdb is Free Software.</li> <li>Compatible with CPython 2.3 through 2.6 and Python 3000</li> <li>Compatible with wxPython 2.6 through 2.8</li> <li>Platform independent, and tested on Ubuntu Gutsy and Windows XP.</li> <li>User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.</li> </ul> <p><img src="http://winpdb.org/images/screenshot%5Fwinpdb%5Fsmall.jpg" alt="Screenshot"></p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "html" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Generator Expressions vs. List Comprehension
<p>When should you use generator expressions and when should you use list comprehensions in Python?</p> <pre><code># Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] </code></pre>
<p>John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work:</p> <pre><code>def gen(): return (something for something in get_some_stuff()) print gen()[:2] # generators don't support indexing or slicing print [5,6] + gen() # generators can't be added to lists </code></pre> <p>Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension.</p> <p>Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "google-app-engine" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
User Authentication in Pylons + AuthKit
<p>I am trying to create a web application using Pylons and the resources on the web point to the <a href="http://pylonsbook.com/alpha1/authentication_and_authorization">PylonsBook</a> page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?</p> <p>I tried downloading the <a href="http://pypi.python.org/pypi/SimpleSiteTemplate/">SimpleSiteTemplate</a> from the cheeseshop but wasn't able to run the setup-app command. It throws up an error:</p> <pre><code> File "/home/cnu/env/lib/python2.5/site-packages/SQLAlchemy-0.4.7-py2.5.egg/sqlalchemy/schema.py", line 96, in __call__ table = metadata.tables[key] AttributeError: 'module' object has no attribute 'tables' </code></pre> <p>I use Pylons 0.9.7rc1, SQLAlchemy 0.4.7, Authkit 0.4.</p>
<p>I gave up on authkit and rolled my own: <a href="http://tonylandis.com/openid-db-authentication-in-pylons-is-easy-with-rpx/" rel="nofollow">http://tonylandis.com/openid-db-authentication-in-pylons-is-easy-with-rpx/</a></p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "linux" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
What are the advantages of packaging your python library/application as an .egg file?
<p>I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?</p>
<p>From the <a href="http://peak.telecommunity.com/DevCenter/PythonEggs">Python Enterprise Application Kit community</a>:</p> <blockquote> <p><em>"Eggs are to Pythons as Jars are to Java..."</em></p> <p>Python eggs are a way of bundling additional information with a Python project, that allows the project's dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several binary formats that embody eggs, but the most common is '.egg' zipfile format, because it's a convenient one for distributing projects. All of the formats support including package-specific data, project-wide metadata, C extensions, and Python code.</p> <p>The primary benefits of Python Eggs are:</p> <ul> <li><p>They enable tools like the "Easy Install" Python package manager</p></li> <li><p>.egg files are a "zero installation" format for a Python package; no build or install step is required, just put them on PYTHONPATH or sys.path and use them (may require the runtime installed if C extensions or data files are used)</p></li> <li><p>They can include package metadata, such as the other eggs they depend on</p></li> <li><p>They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e.g. zope.<em>, twisted.</em>, peak.* packages can be distributed as separate eggs, unlike normal packages which must always be placed under the same parent directory. This allows what are now huge monolithic packages to be distributed as separate components.)</p></li> <li><p>They allow applications or libraries to specify the needed version of a library, so that you can e.g. require("Twisted-Internet>=2.0") before doing an import twisted.internet.</p></li> <li><p>They're a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac, which uses eggs for plugins as of 0.9b1), because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept).</p></li> <li><p>There are also other benefits that may come from having a standardized format, similar to the benefits of Java's "jar" format.</p></li> </ul> </blockquote>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Glade or no glade: What is the best way to use PyGtk?
<p>I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade.</p> <p>The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade.</p> <p>I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).</p>
<p>I would say that it depends: if you find that using Glade you can build the apps you want or need to make than that's absolutely fine. If however you actually want to learn how GTK works or you have some non-standard UI requirements you will <strong>have</strong> to dig into GTK internals (which are not that complicated).</p> <p>Personally I'm usually about 5 minutes into a rich client when I need some feature or customization that is simply impossible through a designer such as Glade or <a href="http://www.mono-project.com/Stetic">Stetic</a>. Perhaps it's just me. Nevertheless it is still useful for me to bootstrap window design using a graphical tool.</p> <p>My recommendation: if making rich clients using GTK is going to be a significant part of your job/hobby then learn GTK as well since you <strong>will</strong> need to write that code someday.</p> <p>P.S. I personally find <a href="http://www.mono-project.com/Stetic">Stetic</a> to be superior to Glade for design work, if a little bit more unstable.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "regex" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Embedding a remote Python shell in an application
<p>You can embed the <a href="http://ipython.scipy.org/">IPython</a> shell inside of your application so that it launches the shell in the foreground. Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a remote IPython shell? </p> <p>Any tips for redirecting the input/output streams for IPython or how to hook it up to a telnet server library or recommendations for other libraries that could be used to implement this are much appreciated. </p>
<p>Python includes a <a href="http://www.python.org/doc/lib/module-telnetlib.html" rel="nofollow">telnet client</a>, but not a telnet server. You can implement a telnet server using <a href="http://twistedmatrix.com" rel="nofollow">Twisted</a>. <a href="http://twistedmatrix.com/pipermail/twisted-python/2004-August/008335.html" rel="nofollow">Here's an example</a>. As for hooking these things together, that's up to you.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "html" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Project structure for Google App Engine
<p>I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is <a href="http://www.bowlsk.com" rel="nofollow">BowlSK</a>. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working.</p> <p>What I have:</p> <ul> <li>Main Level contains: <ul> <li>all .py files (didn't know how to make packages work)</li> <li>all .html templates for main level pages</li> </ul></li> <li>Subdirectories: <ul> <li>separate folders for css, images, js, etc.</li> <li>folders that hold .html templates for subdirecty-type urls</li> </ul></li> </ul> <p>Example:<br/> <a href="http://www.bowlsk.com/" rel="nofollow">http://www.bowlsk.com/</a> maps to HomePage (default package), template at "index.html"<br/> <a href="http://www.bowlsk.com/games/view-series.html?series=7130" rel="nofollow">http://www.bowlsk.com/games/view-series.html?series=7130</a> maps to ViewSeriesPage (again, default package), template at "games/view-series.html"</p> <p>It's nasty. How do I restructure? I had 2 ideas:</p> <ul> <li><p>Main Folder containing: appdef, indexes, main.py?</p> <ul> <li>Subfolder for code. Does this have to be my first package?</li> <li>Subfolder for templates. Folder heirarchy would match package heirarchy</li> <li>Individual subfolders for css, images, js, etc.</li> </ul></li> <li><p>Main Folder containing appdef, indexes, main.py?</p> <ul> <li>Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage"</li> </ul></li> </ul> <p>Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again.</p>
<p>First, I would suggest you have a look at "<a href="http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine">Rapid Development with Python, Django, and Google App Engine</a>"</p> <p>GvR describes a general/standard project layout on page 10 of his <a href="http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine/rapid_development_with_django_gae.pdf?attredirects=0">slide presentation</a>. </p> <p>Here I'll post a slightly modified version of the layout/structure from that page. I pretty much follow this pattern myself. You also mentioned you had trouble with packages. Just make sure each of your sub folders has an __init__.py file. It's ok if its empty.</p> <h2>Boilerplate files</h2> <ul> <li>These hardly vary between projects</li> <li>app.yaml: direct all non-static requests to main.py </li> <li>main.py: initialize app and send it all requests </li> </ul> <h2>Project lay-out</h2> <ul> <li>static/*: static files; served directly by App Engine</li> <li>myapp/*.py: app-specific python code <ul> <li>views.py, models.py, tests.py, __init__.py, and more</li> </ul></li> <li>templates/*.html: templates (or myapp/templates/*.html)</li> </ul> <p>Here are some code examples that may help as well:</p> <h2>main.py</h2> <pre><code>import wsgiref.handlers from google.appengine.ext import webapp from myapp.views import * application = webapp.WSGIApplication([ ('/', IndexHandler), ('/foo', FooHandler) ], debug=True) def main(): wsgiref.handlers.CGIHandler().run(application) </code></pre> <h2>myapp/views.py</h2> <pre><code>import os import datetime import logging import time from google.appengine.api import urlfetch from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from models import * class IndexHandler(webapp.RequestHandler): def get(self): date = "foo" # Do some processing template_values = {'data': data } path = os.path.join(os.path.dirname(__file__) + '/../templates/', 'main.html') self.response.out.write(template.render(path, template_values)) class FooHandler(webapp.RequestHandler): def get(self): #logging.debug("start of handler") </code></pre> <h2>myapp/models.py</h2> <pre><code>from google.appengine.ext import db class SampleModel(db.Model): </code></pre> <p>I think this layout works great for new and relatively small to medium projects. For larger projects I would suggest breaking up the views and models to have their own sub-folders with something like:</p> <h2>Project lay-out</h2> <ul> <li>static/: static files; served directly by App Engine <ul> <li>js/*.js</li> <li>images/*.gif|png|jpg</li> <li>css/*.css</li> </ul></li> <li>myapp/: app structure <ul> <li>models/*.py</li> <li>views/*.py</li> <li>tests/*.py</li> <li>templates/*.html: templates</li> </ul></li> </ul>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "list" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How do I implement a pre-commit hook script in SVN that calls dos2unix to validate checked-in file
<p>I was wondering if anyone here had some experience writing this type of script and if they could give me some pointers.</p> <p>I would like to modify this <a href="http://wordaligned.org/articles/a-subversion-pre-commit-hook" rel="nofollow">script</a> to validate that the check-in file does not have a Carriage Return in the EOL formatting. The EOL format is CR LF in Windows and LF in Unix. When a User checks-in code with the Windows format. It does not compile in Unix anymore. I know this can be done on the client side but I need to have this validation done on the server side. To achieve this, I need to do the following:</p> <p>1) Make sure the file I check is not a binary, I dont know how to do this with svnlook, should I check the mime:type of the file? The <a href="http://svnbook.red-bean.com/nightly/en/svn.reposadmin.create.html" rel="nofollow">Red Book</a> does not indicate this clearly or I must have not seen it.</p> <p>2) I would like to run the <a href="http://linux.about.com/od/commands/l/blcmdl1_dos2uni.htm" rel="nofollow">dos2unix</a> command to validate that the file has the correct EOL format. I would compare the output of the dos2unix command against the original file. If there is a diff between both, I give an error message to the client and cancel the check-in.</p> <p>I would like your comments/feedback on this approach.</p>
<p>I think you can avoid a commit hook script in this case by using the <code>svn:eol-style</code> property as described in the SVNBook:</p> <ul> <li><p><a href="http://svnbook.red-bean.com/en/1.7/svn.advanced.props.file-portability.html#svn.advanced.props.special.eol-style" rel="nofollow">End-of-Line Character Sequences</a></p></li> <li><p><a href="http://svnbook.red-bean.com/en/1.7/svn.ref.properties.html" rel="nofollow">Subversion Properties</a></p></li> </ul> <p>This way SVN can worry about your line endings for you.</p> <p>Good luck!</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "linux" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Python: No module named core.exceptions
<p>I'm trying to get Google AppEngine to work on my Debian box and am getting the following error when I try to access my page:</p> <pre><code>&lt;type 'exceptions.ImportError'&gt;: No module named core.exceptions </code></pre> <p>The same app works fine for me when I run it on my other Ubuntu box, so I know it's not a problem with the app itself. However, I need to get it working on this Debian box. It originally had python 2.4 but after AppEngine complained about it I installed the python2.5 and python2.5-dev packages (to no avail). </p> <p>I saw on this <a href="http://groups.google.com/group/google-appengine/browse_thread/thread/8f2459d2df9d735a/df2b1e9bb76f87c0?show_docid=df2b1e9bb76f87c0&amp;fwc=1" rel="nofollow">Google Group post</a> that it may be due to the version of AppEngine and just to reinstall it, but that didn't work. Any ideas?</p> <p>Edit 1: Also tried uninstalling python2.4 and 2.5 then reinstalling 2.5, which also didn't work.</p> <p>Edit 2: Turns out when I made AppEngine into a CVS project it didn't add the core directory into my project, so when I checked it out there literally was no module named core.exceptions. Re-downloading that folder resolved the problem.</p>
<p><code>core.exceptions</code> is part of django; what version of django do you have installed? The AppEngine comes with the appropriate version for whatever release you've downloaded (in the lib/django directory). It can be installed by going to that directory and running <strong><code>python setup.py install</code></strong></p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "regex" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Calling python from a c++ program for distribution
<p>I would like to call python script files from my c++ program. </p> <p>I am not sure that the people I will distribute to will have python installed.</p> <p>Basically I'm looking for a .lib file that I can use that has an Apache like distribution license.</p>
<blockquote> <p>I would like to call python script files from my c++ program.</p> </blockquote> <p>This means that you want to embed Python in your C++ application. As mentioned in <a href="http://docs.python.org/extending/embedding.html">Embedding Python in Another Application</a>:</p> <blockquote> <p>Embedding Python is similar to extending it, but not quite. The difference is that when you extend Python, the main program of the application is still the Python interpreter, while if you embed Python, the main program may have nothing to do with Python — instead, some parts of the application occasionally call the Python interpreter to run some Python code.</p> </blockquote> <p>I suggest that you first go through <a href="http://docs.python.org/extending/embedding.html">Embedding Python in Another Application</a>. Then refer the following examples</p> <ol> <li><p><a href="http://www.codeproject.com/KB/cpp/embedpython_1.aspx">Embedding Python in C/C++: Part I</a></p></li> <li><p><a href="http://www.codeproject.com/KB/cpp/embedpython_2.aspx">Embedding Python in C/C++: Part II</a></p></li> <li><p><a href="http://www.linuxjournal.com/article/3641">Embedding Python in Multi-Threaded C/C++ Applications</a></p></li> </ol> <p>If you like <a href="http://www.boost.org/doc/libs/release/libs/python/doc/tutorial/doc/html/python/embedding.html">Boost.Python</a>, you may visit the following links:</p> <ol> <li><a href="http://members.gamedev.net/sicrane/articles/EmbeddingPythonPart1.html">Embedding Python with Boost.Python Part 1</a></li> </ol>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "csv" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How do I turn a python program into an .egg file?
<p>How do I turn a python program into an .egg file?</p>
<p><a href="http://peak.telecommunity.com/DevCenter/setuptools">Setuptools</a> is the software that creates <a href="http://peak.telecommunity.com/DevCenter/PythonEggs">.egg files</a>. It's an extension of the <a href="http://docs.python.org/lib/module-distutils.html"><code>distutils</code></a> package in the standard library.</p> <p>The process involves creating a <code>setup.py</code> file, then <code>python setup.py bdist_egg</code> creates an .egg package.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "html" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Can parallel traversals be done in MATLAB just as in Python?
<p>Using the <code>zip</code> function, Python allows for loops to traverse multiple sequences in parallel. </p> <p><code>for (x,y) in zip(List1, List2):</code></p> <p>Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?</p>
<p>If x and y are column vectors, you can do:</p> <pre><code>for i=[x';y'] # do stuff with i(1) and i(2) end </code></pre> <p>(with row vectors, just use <code>x</code> and <code>y</code>).</p> <p>Here is an example run:</p> <pre class="lang-matlab prettyprint-override"><code>&gt;&gt; x=[1 ; 2; 3;] x = 1 2 3 &gt;&gt; y=[10 ; 20; 30;] y = 10 20 30 &gt;&gt; for i=[x';y'] disp(['size of i = ' num2str(size(i)) ', i(1) = ' num2str(i(1)) ', i(2) = ' num2str(i(2))]) end size of i = 2 1, i(1) = 1, i(2) = 10 size of i = 2 1, i(1) = 2, i(2) = 20 size of i = 2 1, i(1) = 3, i(2) = 30 &gt;&gt; </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How does one decrypt a PDF with an owner password, but no user password?
<p>Although the <a href="http://www.adobe.com/devnet/pdf/pdf_reference.html" rel="nofollow">PDF specification</a> is available from Adobe, it's not exactly the simplest document to read through. PDF allows documents to be encrypted so that either a user password and/or an owner password is required to do various things with the document (display, print, etc). A common use is to lock a PDF so that end users can read it without entering any password, but a password is required to do anything else.</p> <p>I'm trying to parse PDFs that are locked in this way (to get the same privileges as you would get opening them in any reader). Using an empty string as the user password doesn't work, but it seems (section 3.5.2 of the spec) that there has to be a user password to create the hash for the admin password.</p> <p>What I would like is either an explanation of how to do this, or any code that I can read (ideally Python, C, or C++, but anything readable will do) that does this so that I can understand what I'm meant to be doing. Standalone code, rather than reading through (e.g.) the gsview source, would be best.</p>
<p>A plugin for GSview for viewing encrypted PDFs is <a href="http://www.cs.cmu.edu/~dst/Adobe/Gallery/Keating/" rel="nofollow">here</a>.</p> <p>If this works for you, you may be able to look at the source.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Java -> Python?
<p>Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?</p>
<ol> <li><p>List comprehensions. I often find myself filtering/mapping lists, and being able to say <code>[line.replace("spam","eggs") for line in open("somefile.txt") if line.startswith("nee")]</code> is really nice.</p></li> <li><p>Functions are first class objects. They can be passed as parameters to other functions, defined inside other function, and have lexical scope. This makes it really easy to say things like <code>people.sort(key=lambda p: p.age)</code> and thus sort a bunch of people on their age without having to define a custom comparator class or something equally verbose.</p></li> <li><p>Everything is an object. Java has basic types which aren't objects, which is why many classes in the standard library define 9 different versions of functions (for boolean, byte, char, double, float, int, long, Object, short). <code>Array.sort</code> is a good example. Autoboxing helps, although it makes things awkward when something turns out to be null.</p></li> <li><p>Properties. Python lets you create classes with read-only fields, lazily-generated fields, as well as fields which are checked upon assignment to make sure they're never 0 or null or whatever you want to guard against, etc.'</p></li> <li><p>Default and keyword arguments. In Java if you want a constructor that can take up to 5 optional arguments, you must define 6 different versions of that constructor. And there's no way at all to say <code>Student(name="Eli", age=25)</code></p></li> <li><p>Functions can only return 1 thing. In Python you have tuple assignment, so you can say <code>spam, eggs = nee()</code> but in Java you'd need to either resort to mutable out parameters or have a custom class with 2 fields and then have two additional lines of code to extract those fields.</p></li> <li><p>Built-in syntax for lists and dictionaries.</p></li> <li><p>Operator Overloading.</p></li> <li><p>Generally better designed libraries. For example, to parse an XML document in Java, you say<br /> <code>Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("test.xml");</code><br /> and in Python you say<br /> <code>doc = parse("test.xml")</code></p></li> </ol> <p>Anyway, I could go on and on with further examples, but Python is just overall a much more flexible and expressive language. It's also dynamically typed, which I really like, but which comes with some disadvantages.</p> <p>Java has much better performance than Python and has way better tool support. Sometimes those things matter a lot and Java is the better language than Python for a task; I continue to use Java for some new projects despite liking Python a lot more. But as a language I think Python is superior for most things I find myself needing to accomplish.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "matplotlib" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Open source alternative to MATLAB's fmincon function?
<p>Is there an open-source alternative to MATLAB's <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/optim/index.html?/access/helpdesk/help/toolbox/optim/ug/fmincon.html"><code>fmincon</code></a> function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / <a href="http://numpy.scipy.org/">NumPy</a> / <a href="http://www.scipy.org/">SciPy</a> and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.</p>
<p>Is your problem convex? Linear? Non-linear? I agree that SciPy.optimize will probably do the job, but fmincon is a sort of bazooka for solving optimization problems, and you'll be better off if you can confine it to one of the categories below (in increasing level of difficulty to solve efficiently)</p> <p>Linear Program (LP) Quadratic Program (QP) Convex Quadratically-Constrained Quadratic Program (QCQP) Second Order Cone Program (SOCP) Semidefinite Program (SDP) Non-Linear Convex Problem Non-Convex Problem</p> <p>There are also combinatoric problems such as Mixed-Integer Linear Programs (MILP), but you didn't mention any sort of integrality constraints, suffice to say that they fall into a different class of problems.</p> <p>The CVXOpt package will be of great use to you if your problem is convex. </p> <p>If your problem is not convex, you need to choose between finding a local solution or the global solution. Many convex solvers 'sort of' work in a non-convex domain. Finding a good approximation to the global solution would require some form Simulated Annealing or Genetic Algorithm. Finding the global solution will require an enumeration of all local solutions or a combinatorial strategy such as Branch and Bound.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "tkinter" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
What Python way would you suggest to check whois database records?
<p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p> <p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p> <p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
<p>Look at this: <a href="http://code.google.com/p/pywhois/">http://code.google.com/p/pywhois/</a></p> <p>pywhois - Python module for retrieving WHOIS information of domains</p> <p>Goal: - Create a simple importable Python module which will produce parsed WHOIS data for a given domain. - Able to extract data for all the popular TLDs (com, org, net, ...) - Query a WHOIS server directly instead of going through an intermediate web service like many others do. - Works with Python 2.4+ and no external dependencies</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; import pywhois &gt;&gt;&gt; w = pywhois.whois('google.com') &gt;&gt;&gt; w.expiration_date ['14-sep-2011'] &gt;&gt;&gt; w.emails ['contact-admin@google.com', 'dns-admin@google.com', 'dns-admin@google.com', 'dns-admin@google.com'] &gt;&gt;&gt; print w ... </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "matplotlib" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How do I get the path and name of the file that is currently executing?
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p> <p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile">execfile</a>:</p> <ul> <li><code>script_1.py</code> calls <code>script_2.py</code>. </li> <li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li> </ul> <p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p> <p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
<pre><code>__file__ </code></pre> <p>as others have said. You may want to use: </p> <pre><code>os.path.realpath(__file__) </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python-2.7" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Django Sessions
<p>I'm looking at sessions in Django, and by default they are stored in the database. What are the benefits of filesystem and cache sessions and when should I use them?</p>
<p>The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it.</p> <p>The memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost.</p> <p>If you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "html" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How do you create a weak reference to an object in Python?
<p>How do you create a weak reference to an object in Python? </p>
<pre><code>&gt;&gt;&gt; import weakref &gt;&gt;&gt; class Object: ... pass ... &gt;&gt;&gt; o = Object() &gt;&gt;&gt; r = weakref.ref(o) &gt;&gt;&gt; # if the reference is still active, r() will be o, otherwise None &gt;&gt;&gt; do_something_with_o(r()) </code></pre> <p>See the <a href="http://docs.python.org/lib/module-weakref.html">wearkref module docs</a> for more details. You can also use <code>weakref.proxy</code> to create an object that proxies o. Will throw <code>ReferenceError</code> if used when the referent is no longer referenced.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "string" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
What is the simplest way to find the difference between 2 times in python?
<p>I have 2 time values which have the type <code>datetime.time</code>. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type <code>datetime.datetime</code> but not for <code>datetime.time</code>. So what is the best way to do this?</p>
<p>Also a little silly, but you could try picking an arbitrary day and embedding each time in it, using <code>datetime.datetime.combine</code>, then subtracting:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; t1 = datetime.time(2,3,4) &gt;&gt;&gt; t2 = datetime.time(18,20,59) &gt;&gt;&gt; dummydate = datetime.date(2000,1,1) &gt;&gt;&gt; datetime.datetime.combine(dummydate,t2) - datetime.datetime.combine(dummydate,t1) datetime.timedelta(0, 58675) </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "linux" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How to write a download progress indicator in Python?
<p>I am writing a little application to download files over http (as, for example, described <a href="http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776" rel="nofollow">here</a>).</p> <p>I also want to include a little download progress indicator showing the percentage of the download progress.</p> <p>Here is what I came up with:</p> <pre> sys.stdout.write(rem_file + "...") urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress) def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("%2d%%" % percent) sys.stdout.write("\b\b\b") sys.stdout.flush() </pre> <p>Output: MyFileName... 9%</p> <p>Any other ideas or recommendations to do this? </p> <p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p> <p><strong>EDIT:</strong></p> <p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p> <pre> global rem_file # global variable to be used in dlProgress urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress) def dlProgress(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) sys.stdout.write("\r" + rem_file + "...%d%%" % percent) sys.stdout.flush() </pre> <p>Output: MyFileName...9% </p> <p>And the cursor shows up at the END of the line. Much better.</p>
<p>There's a text progress bar library for python at <a href="http://pypi.python.org/pypi/progressbar/2.2">http://pypi.python.org/pypi/progressbar/2.2</a> that you might find useful: </p> <blockquote> <p>This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway.</p> <p>The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line.</p> <p>The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when available.</p> </blockquote>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "regex" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How can I retrieve the page title of a webpage using Python?
<p>How can I retrieve the page title of a webpage (title html tag) using Python?</p>
<p>Here's a simplified version of <a href="http://stackoverflow.com/a/51242/4279">@Vinko Vrsalovic's answer</a>:</p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(urllib2.urlopen("https://www.google.com")) print soup.title.string </code></pre> <p>NOTE:</p> <ul> <li><p><em>soup.title</em> finds the first <em>title</em> element <strong>anywhere</strong> in the html document</p></li> <li><p><em>title.string</em> assumes it has only <strong>one</strong> child node, and that child node is a <strong>string</strong></p></li> </ul> <p>For <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/">beautifulsoup 4.x</a>, use different import:</p> <pre><code>from bs4 import BeautifulSoup </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "arrays" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Passing on named variable arguments in python
<p>Say I have the following methods:</p> <pre><code>def methodA(arg, **kwargs): pass def methodB(arg, *args, **kwargs): pass </code></pre> <p>In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define <code>methodA</code> as follows, the second argument will be passed on as positional rather than named variable arguments.</p> <pre><code>def methodA(arg, **kwargs): methodB("argvalue", kwargs) </code></pre> <p>How do I make sure that the **kwargs in methodA gets passed as **kwargs to methodB?</p>
<p>Put the asterisks before the kwargs variable. This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments.</p> <pre><code>methodB("argvalue", **kwargs) </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "pandas" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Improving Python readability?
<p>I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.</p> <p>However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.</p> <p>For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):</p> <pre><code>if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() did_i_not_warn_you_biz() my_father_is_avenged() </code></pre> <p>The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:</p> <pre><code>if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() #-- while -- #-- if -- did_i_not_warn_you_biz() my_father_is_avenged() </code></pre> <p>And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.</p>
<p>Part of learning a new programming language is learning to read code in that language. A crutch like this may make it easier to read your own code, but it's going to impede the process of learning how to read anyone else's Python code. I really think you'd be better off getting rid of the end of block comments and getting used to normal Python.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "google-app-engine" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How to get an absolute file path in Python
<p>Given a path such as <code>"mydir/myfile.txt"</code>, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:</p> <pre><code>"C:/example/cwd/mydir/myfile.txt" </code></pre>
<pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.path.abspath("mydir/myfile.txt") </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "list" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP)
<p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p> <pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples; </code></pre> <p>Is this normal behaviour when using a SQL database?</p> <p>The schema (the table holds responses to a survey):</p> <pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer); \copy tuples from '350,000 responses.csv' delimiter as ',' </code></pre> <p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p> <pre><code>java 1.5 threads ~ 7 ms java 1.5 ~ 10 ms python 2.5 numpy ~ 18 ms python 2.5 ~ 370 ms </code></pre> <p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p> <p>Tunings i've tried without success include (blindly following some web advice):</p> <pre><code>increased the shared memory available to Postgres to 256MB increased the working memory to 2MB disabled connection and statement logging used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL </code></pre> <p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p> <p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p> <hr> <p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p> <p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p> <p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p> <p>The Postgres query doesn't change timing on subsequent runs.</p> <p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
<p>I would say your test scheme is not really useful. To fulfill the db query, the db server goes through several steps:</p> <ol> <li>parse the SQL</li> <li>work up a query plan, i. e. decide on which indices to use (if any), optimize etc.</li> <li>if an index is used, search it for the pointers to the actual data, then go to the appropriate location in the data or</li> <li>if no index is used, scan <i>the whole table</i> to determine which rows are needed</li> <li>load the data from disk into a temporary location (hopefully, but not necessarily, memory)</li> <li>perform the count() and avg() calculations</li> </ol> <p>So, creating an array in Python and getting the average basically skips all these steps save the last one. As disk I/O is among the most expensive operations a program has to perform, this is a major flaw in the test (see also the answers to <a href="http://stackoverflow.com/questions/26021/how-is-data-compression-more-effective-than-indexing-for-search-performance">this question</a> I asked here before). Even if you read the data from disk in your other test, the process is completely different and it's hard to tell how relevant the results are.</p> <p>To obtain more information about where Postgres spends its time, I would suggest the following tests:</p> <ul> <li>Compare the execution time of your query to a SELECT without the aggregating functions (i. e. cut step 5)</li> <li>If you find that the aggregation leads to a significant slowdown, try if Python does it faster, obtaining the raw data through the plain SELECT from the comparison.</li> </ul> <p>To speed up your query, reduce disk access first. I doubt very much that it's the aggregation that takes the time.</p> <p>There's several ways to do that:</p> <ul> <li>Cache data (in memory!) for subsequent access, either via the db engine's own capabilities or with tools like memcached</li> <li>Reduce the size of your stored data</li> <li>Optimize the use of indices. Sometimes this can mean to skip index use altogether (after all, it's disk access, too). For MySQL, I seem to remember that it's recommended to skip indices if you assume that the query fetches more than 10% of all the data in the table.</li> <li>If your query makes good use of indices, I know that for MySQL databases it helps to put indices and data on separate physical disks. However, I don't know whether that's applicable for Postgres.</li> <li>There also might be more sophisticated problems such as swapping rows to disk if for some reason the result set can't be completely processed in memory. But I would leave that kind of research until I run into serious performance problems that I can't find another way to fix, as it requires knowledge about a lot of little under-the-hood details in your process.</li> </ul> <p><b>Update:</b></p> <p><i>I just realized that you seem to have no use for indices for the above query and most likely aren't using any, too, so my advice on indices probably wasn't helpful. Sorry. Still, I'd say that the aggregation is not the problem but disk access is. I'll leave the index stuff in, anyway, it might still have some use.</i></p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "csv" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Cross-platform space remaining on volume using python
<p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
<pre><code>import ctypes import os import platform import sys def get_free_space_mb(dirname): """Return folder/drive free space (in megabytes).""" if platform.system() == 'Windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes)) return free_bytes.value / 1024 / 1024 else: st = os.statvfs(dirname) return st.f_bavail * st.f_frsize / 1024 / 1024 </code></pre> <p>Note that you <em>must</em> pass a directory name for <code>GetDiskFreeSpaceEx()</code> to work (<code>statvfs()</code> works on both files and directories). You can get a directory name from a file with <code>os.path.dirname()</code>.</p> <p>Also see the documentation for <a href="https://docs.python.org/3/library/os.html#os.fstatvfs"><code>os.statvfs()</code></a> and <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx"><code>GetDiskFreeSpaceEx</code></a>.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "json" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Large Python Includes
<p>I have a file that I want to include in Python but the included file is fairly long and it'd be much neater to be able to split them into several files but then I have to use several include statements.</p> <p>Is there some way to group together several files and include them all at once?</p>
<ol> <li>Put files in one folder. </li> <li>Add &#95;&#95;init&#95;&#95;.py file to the folder. Do necessary imports in &#95;&#95;init&#95;&#95;.py</li> <li><p>Replace multiple imports by one:</p> <p>import folder_name </p></li> </ol> <p>See <a href="http://docs.python.org/tut/node8.html#SECTION008400000000000000000" rel="nofollow">Python Package Management</a></p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "list" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How can I do a line break (line continuation) in Python?
<p>I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?</p> <p>For example, adding a bunch of strings,</p> <pre><code>e = 'a' + 'b' + 'c' + 'd' </code></pre> <p>and have it like this:</p> <pre><code>e = 'a' + 'b' + 'c' + 'd' </code></pre>
<p>What is the line? You can just have arguments on the next line without any problems:</p> <pre><code>a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, blahblah6, blahblah7) </code></pre> <p>Otherwise you can do something like this:</p> <pre><code>if a == True and \ b == False </code></pre> <p>Check the <a href="http://www.python.org/dev/peps/pep-0008/">style guide</a> for more information.</p> <p>From your example line:</p> <pre><code>a = '1' + '2' + '3' + \ '4' + '5' </code></pre> <p>Or:</p> <pre><code>a = ('1' + '2' + '3' + '4' + '5') </code></pre> <p>Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How do you check whether a python method is bound or not?
<p>Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?</p>
<pre><code>def isbound(method): return method.im_self is not None def instance(bounded_method): return bounded_method.im_self </code></pre> <p><a href="http://docs.python.org/ref/types.html">User-defined methods:</a></p> <blockquote> <p>When a user-defined method object is created by retrieving a user-defined function object from a class, its <code>im_self</code> attribute is <code>None</code> and the method object is said to be unbound. When one is created by retrieving a user-defined function object from a class via one of its instances, its <code>im_self</code> attribute is the instance, and the method object is said to be bound. In either case, the new method's <code>im_class</code> attribute is the class from which the retrieval takes place, and its <code>im_func</code> attribute is the original function object.</p> </blockquote> <p>In Python <a href="http://docs.python.org/dev/whatsnew/2.6.html">2.6 and 3.0</a>:</p> <blockquote> <p>Instance method objects have new attributes for the object and function comprising the method; the new synonym for <code>im_self</code> is <code>__self__</code>, and <code>im_func</code> is also available as <code>__func__</code>. The old names are still supported in Python 2.6, but are gone in 3.0.</p> </blockquote>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "tkinter" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Best way to check if a list is empty
<p>For example, if passed the following:</p> <pre><code>a = [] </code></pre> <p>How do I check to see if <code>a</code> is empty?</p>
<pre><code>if not a: print("List is empty") </code></pre> <p>Using the implicit booleanness of the empty list <code>a</code> is quite pythonic.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python-2.7" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
What are some strategies to write python code that works in CPython, Jython and IronPython
<p>Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?</p>
<p>If you <em>do</em> find you need to write unique code for an environment, use pythons </p> <pre><code>import mymodule_jython as mymodule import mymodule_cpython as mymodule </code></pre> <p>have this stuff in a simple module (''module_importer''?) and write your code like this:</p> <pre><code>from module_importer import mymodule </code></pre> <p>This way, all you need to do is alter <code>module_importer.py</code> per platform.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "linux" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How do i generate a histogram for a given probability distribution (for functional testing a server)?
<p>I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation)</p> <p>I've chosen the <a href="http://en.wikipedia.org/wiki/Weibull_distribution" rel="nofollow">Weibull</a> distribution as it "sort of" matches the distribution I've observed (ramps up quickly, drops off quickly but not instantly)</p> <p>I use this distribution to generate the number of requests that should be sent each day between a given start and end date</p> <p>I've hacked together an algorithm in Python that sort of works but it feels kludgy:</p> <pre><code>how_many_days = (end_date - start_date).days freqs = defaultdict(int) for x in xrange(how_many_responses): freqs[int(how_many_days * weibullvariate(0.5, 2))] += 1 timeline = [] day = start_date for i,freq in sorted(freqs.iteritems()): timeline.append((day, freq)) day += timedelta(days=1) return timeline </code></pre> <p>What better ways are there to do this? </p>
<p>Why don't you try <a href="http://grinder.sourceforge.net" rel="nofollow">The Grinder 3</a> to load test your server, it comes with all this and more prebuilt, and it supports python as a scripting language</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "json" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Any good AJAX framework for Google App Engine apps?
<p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p> <p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
<p>As Google Web Toolkit is a <a href="http://code.google.com/support/bin/answer.py?answer=54830&amp;topic=10208" rel="nofollow">subset of Java</a> it works best when you Java at the backend too. Since Google App Engine is currently <a href="http://code.google.com/appengine/kb/general.html#language" rel="nofollow">Python only</a> I think you'd have to do a lot of messing about to get your server and client to talk nicely to each other.</p> <p>jQuery seems to be the most popular JavaScript library option in the <a href="http://www.djangosnippets.org/tags/ajax/?page=1" rel="nofollow">AJAX Tag at DjangoSnippets.com</a>.</p> <p><strong>Edit:</strong> The above is only true of Google App Engine applications written in Python. As Google App Engine now supports Java, GWT could now be a good choice for writing an AJAX front end. <a href="http://code.google.com/webtoolkit/doc/latest/tutorial/appengine.html" rel="nofollow">Google even have a tutorial showing you how to do it.</a></p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "html" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
What is the difference between old style and new style classes in Python?
<p>What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?</p>
<p>From <a href="http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes">http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes</a> :</p> <blockquote> <p>Up to Python 2.1, old-style classes were the only flavour available to the user. The concept of (old-style) class is unrelated to the concept of type: if <code>x</code> is an instance of an old-style class, then <code>x.__class__</code> designates the class of <code>x</code>, but <code>type(x)</code> is always <code>&lt;type 'instance'&gt;</code>. This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance. </p> <p><strong>New-style classes were introduced in Python 2.2 to unify the concepts of class and type</strong>. A new-style class is simply a user-defined type, no more, no less. If x is an instance of a new-style class, then <code>type(x)</code> is typically the same as <code>x.__class__</code> (although this is not guaranteed – a new-style class instance is permitted to override the value returned for <code>x.__class__</code>).</p> <p><strong>The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model</strong>. It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of "descriptors", which enable computed properties. </p> <p><strong>For compatibility reasons, classes are still old-style by default</strong>. New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the "top-level type" object if no other parent is needed. The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns. Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are "fixes" that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance. </p> <p><strong>Python 3 only has new-style classes</strong>. No matter if you subclass from <code>object</code> or not, classes are new-style in Python 3. It is however recommended that you still subclass from <code>object</code>.</p> </blockquote>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "csv" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
In Python, how can you easily retrieve sorted items from a dictionary?
<p>Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. </p> <p>What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?</p> <p>For example, you had this:</p> <pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'} </code></pre> <p>I want to print the associated values in the following sequence sorted by key:</p> <pre><code>this is a this is b this is c </code></pre>
<p>Do you mean that you need the values sorted by the value of the key? In that case, this should do it:</p> <pre><code>for key in sorted(d): print d[key] </code></pre> <p><strong>EDIT:</strong> changed to use sorted(d) instead of sorted(d.keys()), thanks <a href="http://stackoverflow.com/users/1694/eli-courtwright" rel="nofollow">Eli</a>!</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "csv" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 1, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How can I get Emacs' key bindings in Python's IDLE?
<p>I use Emacs primarily for coding Python but sometimes I use IDLE. Is there a way to change the key bindings easily in IDLE to match Emacs?</p>
<p>IDLE provides Emacs keybindings without having to install other software. </p> <ol> <li>Open up the menu item Options -> Configure IDLE...</li> <li>Go to Keys tab</li> <li>In the drop down menu on the right side of the dialog change the select to "IDLE Classic Unix"</li> </ol> <p>It's not the true emacs key bindings but you get the basics like movement, saving/opening, ...</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "numpy" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Python regular expression for HTML parsing (BeautifulSoup)
<p>I want to grab the value of a hidden input field in HTML.</p> <pre><code>&lt;input type="hidden" name="fooId" value="12-3456789-1111111111" /&gt; </code></pre> <p>I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format</p> <pre><code>&lt;input type="hidden" name="fooId" value="**[id is here]**" /&gt; </code></pre> <p>Can someone provide an example in Python to parse the HTML for the value?</p>
<p>For this particular case, BeautifulSoup is harder to write than a regex, but it is much more robust... I'm just contributing with the BeautifulSoup example, given that you already know which regexp to use :-)</p> <pre><code>from BeautifulSoup import BeautifulSoup #Or retrieve it from the web, etc. html_data = open('/yourwebsite/page.html','r').read() #Create the soup object from the HTML data soup = BeautifulSoup(html_data) fooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag value = fooId.attrs[2][1] #The value of the third attribute of the desired tag #or index it directly via fooId['value'] </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python-2.7" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
XML writing tools for Python
<p>I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?</p> <p>This is similar to what I'm actually doing:</p> <pre><code>import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElement(head,'script') script.set('type','text/javascript') script.text = "var a = 'I love &amp;aacute; letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 &gt; 1" tree = ET.ElementTree(root) tree.write('foo.xhtml') # more foo.xhtml &lt;html&gt;&lt;head&gt;&lt;script type="text/javascript"&gt;var a = 'I love &amp;amp;aacute; letters'&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;And I like the fact that 3 &amp;gt; 1&lt;/h1&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
<p>Another way is using the <a href="http://codespeak.net/lxml/tutorial.html#the-e-factory" rel="nofollow">E Factory</a> builder from lxml (available in <a href="http://effbot.org/zone/element-builder.htm" rel="nofollow">Elementtree</a> too)</p> <pre><code>&gt;&gt;&gt; from lxml import etree &gt;&gt;&gt; from lxml.builder import E &gt;&gt;&gt; def CLASS(*args): # class is a reserved word in Python ... return {"class":' '.join(args)} &gt;&gt;&gt; html = page = ( ... E.html( # create an Element called "html" ... E.head( ... E.title("This is a sample document") ... ), ... E.body( ... E.h1("Hello!", CLASS("title")), ... E.p("This is a paragraph with ", E.b("bold"), " text in it!"), ... E.p("This is another paragraph, with a", "\n ", ... E.a("link", href="http://www.python.org"), "."), ... E.p("Here are some reserved characters: &lt;spam&amp;egg&gt;."), ... etree.XML("&lt;p&gt;And finally an embedded XHTML fragment.&lt;/p&gt;"), ... ) ... ) ... ) &gt;&gt;&gt; print(etree.tostring(page, pretty_print=True)) &lt;html&gt; &lt;head&gt; &lt;title&gt;This is a sample document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1 class="title"&gt;Hello!&lt;/h1&gt; &lt;p&gt;This is a paragraph with &lt;b&gt;bold&lt;/b&gt; text in it!&lt;/p&gt; &lt;p&gt;This is another paragraph, with a &lt;a href="http://www.python.org"&gt;link&lt;/a&gt;.&lt;/p&gt; &lt;p&gt;Here are some reservered characters: &amp;lt;spam&amp;amp;egg&amp;gt;.&lt;/p&gt; &lt;p&gt;And finally an embedded XHTML fragment.&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "arrays" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Anyone used Dabo for a medium-big project?
<p>We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client. We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects?<br /> Thanks for your time!</p>
<p>I'm one of the authors of the Dabo framework. One of our users pointed out to me the extremely negative answer you received, and so I thought I had better chime in and clear up some of the incorrect assumptions in the first reply.</p> <p>Dabo is indeed well-known in the Python community. I have presented it at 3 of the last 4 US PyCons, and we have several hundred users who subscribe to our email lists. Our website (<a href="http://dabodev.com">http://dabodev.com</a>) has not had any service interruptions; I don't know why the first responder claimed to have trouble. Support is through our email lists, and we pride ourselves on helping people quickly and efficiently. Many of the newbie questions help us to identify places where our docs are lacking, so we strongly encourage newcomers to ask questions!</p> <p>Dabo has been around for 4 years. The fact that it is still a few days away from a 0.9 release is more of a reflection of the rather conservative version numbering of my partner, Paul McNett, than any instabilities in the framework. I know of Dabo apps that have been in production since 2006; I have used it for my own projects since 2004. Whatever importance you attach to release numbers, we are at revision 4522, with consistent work being done to add more and more stuff to the framework; refactor and streamline some of the older code, and yes, clean up some bugs.</p> <p>Please sign up for our free email support list:</p> <p><a href="http://leafe.com/mailman/listinfo/dabo-users">http://leafe.com/mailman/listinfo/dabo-users</a></p> <p>...and ask any questions you may have about Dabo there. Not many people have discovered Stack Overflow yet, so I wouldn't expect very informed answers here yet. There are several regular contributors there who use Dabo on a daily basis, and are usually more than happy to offer their opinions and their help.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "csv" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
round() in Python doesn't seem to be rounding properly
<p>The documentation for the <a href="http://docs.python.org/lib/built-in-funcs.html">round()</a> function states that you pass it a number, and the positions past the decimal to round. Thus it <em>should</em> do this:</p> <pre><code>n = 5.59 round(n, 1) # 5.6 </code></pre> <p>But, in actuality, good old floating point weirdness creeps in and you get:</p> <pre><code>5.5999999999999996 </code></pre> <p>For the purposes of UI, I need to display <code>5.6</code>. I poked around the Internet and found some <a href="http://mail.python.org/pipermail/python-list/2005-September/340383.html">documentation</a> that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. <a href="http://www.python.org/doc/2.5.1/tut/node16.html">See here also</a>.</p> <p>Short of creating my own round library, is there any way around this?</p>
<p>Formatting works correctly even without having to round:</p> <pre><code>"%.1f" % n </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "pandas" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 4, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Convert XML/HTML Entities into Unicode String in Python
<p>I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?</p> <p>For example:</p> <p>I get back:</p> <pre><code>&amp;#x01ce; </code></pre> <p>which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value <code>u'\u01ce'</code></p>
<p>Python has the <a href="https://docs.python.org/2/library/htmllib.html#module-htmlentitydefs">htmlentitydefs</a> module, but this doesn't include a function to unescape HTML entities.</p> <p>Python developer Fredrik Lundh (author of elementtree, among other things) has such a function <a href="http://effbot.org/zone/re-sub.htm#unescape-html">on his website</a>, which works with decimal, hex and named entities:</p> <pre><code>import re, htmlentitydefs ## # Removes HTML or XML character references and entities from a text string. # # @param text The HTML (or XML) source text. # @return The plain text, as a Unicode string, if necessary. def unescape(text): def fixup(m): text = m.group(0) if text[:2] == "&amp;#": # character reference try: if text[:3] == "&amp;#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass else: # named entity try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return re.sub("&amp;#?\w+;", fixup, text) </code></pre>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "regex" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 5, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Does re.compile() or any given Python library call throw an exception?
<p>I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are? </p>
<p>Well, <code>re.compile</code> certainly may:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.compile('he(lo') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python25\lib\re.py", line 180, in compile return _compile(pattern, flags) File "C:\Python25\lib\re.py", line 233, in _compile raise error, v # invalid expression sre_constants.error: unbalanced parenthesis </code></pre> <p><a href="http://docs.python.org/lib/node46.html#l2h-408">The documentation</a> does support this, in a roundabout way - check the bottom of the "Module Contents" page for (brief) description of the <code>error</code> exception.</p> <p>Unfortunately, I don't have any answer to the general question. I suppose the documentation for the various modules varies in quality and thoroughness. If there were particular modules you were interested in, you might be able to <a href="http://www.depython.net/">decompile</a> them (if written in Python) or even <a href="http://www.python.org/download/">look at the source</a>, if they're in the standard library.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How do I get the external IP of a socket in Python?
<p>When I call <code>socket.getsockname()</code> on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?</p>
<p>This isn't possible without cooperation from an external server, because there could be any number of NATs between you and the other computer. If it's a custom protocol, you could ask the other system to report what address it's connected to.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "arrays" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 2, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
Can I document Python code with doxygen (and does it make sense)?
<p>I like doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /* .. */ comments and also has its own self-documentation facility which seems to be the pythonic way to document.</p> <p>Can I just use doxygen? Anything particular to be aware of?</p> <p>I have done some coding in Python but so far only on small projects where I was to lazy to document at all (yeah, I know ... but let's just pretend that's OK for now).</p>
<p>The <a href="https://pypi.python.org/pypi/doxypy/">doxypy</a> input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "no", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "flask" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}
How would you design a very "Pythonic" UI framework?
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
<p>You could actually pull this off, but it would require using metaclasses, which are <em>deep</em> magic (there be dragons). If you want an intro to metaclasses, there's a series of <a href="http://www.ibm.com/developerworks/linux/library/l-pymeta.html" rel="nofollow">articles from IBM</a> which manage to introduce the ideas without melting your brain.</p> <p>The source code from an ORM like SQLObject might help, too, since it uses this same kind of declarative syntax.</p>
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "yes", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": [ "python-2.7" ], "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": 3, "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
[ { "user_id": "5a053951-24cd-4c9d-9e0c-8a054b95b812", "value": "Sample answer", "status": "submitted" } ]
null
{ "type": null, "score": null, "agent": null }
null
{}