title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Bundling data files with PyInstaller (--onefile)
7,674,790
42
2011-10-06T13:20:34Z
7,675,014
45
2011-10-06T13:36:18Z
[ "python", "pyinstaller" ]
I'm trying to build a one-file EXE with PyInstaller which is to include an image and an icon. I cannot for the life of me get it to work with `--onefile`. If I do `--onedir` it works all works very well. When I use `--onefile`, it can't find the referenced additional files (when running the compiled EXE). It finds the...
pyinstaller unpacks your data into a temporary folder, and stores this directory path in the `_MEIPASS2` environment variable. To get the `_MEIPASS2` dir in packed-mode and use the local directory in unpacked (development) mode, I use this: ``` def resource_path(relative): return os.path.join( os.environ.g...
Bundling data files with PyInstaller (--onefile)
7,674,790
42
2011-10-06T13:20:34Z
13,790,741
57
2012-12-09T19:08:32Z
[ "python", "pyinstaller" ]
I'm trying to build a one-file EXE with PyInstaller which is to include an image and an icon. I cannot for the life of me get it to work with `--onefile`. If I do `--onedir` it works all works very well. When I use `--onefile`, it can't find the referenced additional files (when running the compiled EXE). It finds the...
I know this is old but to update newer pyinstaller's do not set `env` variable anymore, now the path gets set as `sys._MEIPASS` ``` def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEI...
Rounding in jinja2 brackets
7,675,653
8
2011-10-06T14:19:53Z
7,675,866
19
2011-10-06T14:34:18Z
[ "python", "templates", "jinja2" ]
I guess just generally I'm curious about what operations are allowable in jinja2 brackets, e.g. what I'm trying to do is perform an operation on embedded data like so: ``` {{ round(255*(mileage['chevy'] - mileage['ford']))/1000 }} ``` This throws the error on traceback: > UndefinedError: 'round' is undefined Simila...
The jinja2 templating language is different from the python language. In jinja2, operation on values are often done during filters : `{{ something | operation }}`. You can find a [list of filters](http://jinja.pocoo.org/docs/templates/#list-of-builtin-filters) in the jinja2 documentation. For example, to [round](http:...
Automating Review Requests with ReviewBoard and Mercurial using Python hooks
7,675,917
2
2011-10-06T14:37:19Z
8,615,156
7
2011-12-23T10:53:26Z
[ "python", "mercurial", "automation", "mercurial-hook", "review-board" ]
Here is my problem: I got a remote mercurial repository where the hook is gonna be setup either incoming or changegroup, and I got a ReviewBoard setup on a different server. The idea is to automate review request tickets generation upon push from devs into the remote repository. Of course, I would need a hook that inv...
Not sure if this is quite what you need, but this is something I use for executing a commit message check in pretty much the same circumstances, it has to check each change and verify information based on the user. In the same way I need to check the user the changelist is for, not the 'pushing' user. It should be fair...
Py_initialize / Py_Finalize not working twice with numpy
7,676,314
8
2011-10-06T15:02:44Z
7,676,916
9
2011-10-06T15:46:30Z
[ "python", "c", "numpy" ]
On the second call of the following code, my app segfault, so I guess I am missing something : ``` Py_Initialize(); pName = PyString_FromString("comp_macbeth"); pModule = PyImport_Import(pName); Py_DECREF(pName); if(pModule == NULL) { PyErr_Print(); Py_Finalize(); return; } pFunc = PyObject_GetAttrString...
From the [Py\_Finalize docs](http://docs.python.org/c-api/init.html#Py_Finalize): > Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py\_Initialize() and Py\_Finalize() more than once. Apparently Numpy is one of those. See also [th...
How do i pass parameters to a class based view in django?
7,676,815
4
2011-10-06T15:40:28Z
7,676,907
12
2011-10-06T15:45:50Z
[ "python", "django" ]
I have the following class based view; ``` class myClassView(): def get(self): # lots of code ... return response ``` My urlconf for this looks like ``` (r^'call_myClassView/', myClassView.as_view()) ``` I want to pass parameters to the urlconf the old functional way ``` (r'call_myClassView/(?P...
They *are* passed in the old way. You access them via `self.args` and `self.kwargs`, for positional and keyword arguments respectively. In your case, `self.kwargs['id']` would do the trick. **Edit** because you've overridden `get()` but not preserved the signature. If you're overriding a method, always do `def get(se...
What is the advantage in using `exec` over `type()` when creating classes at runtime?
7,676,947
10
2011-10-06T15:48:28Z
7,677,359
7
2011-10-06T16:18:59Z
[ "python", "namedtuple", "dynamic-class-creation" ]
I want to dynamically create classes at runtime in python. For example, I want to replicate the code below: ``` >>> class RefObj(object): ... def __init__(self, ParentClassName): ... print "Created RefObj with ties to %s" % ParentClassName ... class Foo1(object): ... ref_obj = RefObj("Foo1") ... class...
I would recommend `type` over `exec` here. In fact, the `class` statement is just syntactic sugar for a call to `type`: The class body is executed within its own namespace, which is then passed on to the metaclass, which defaults to `type` if no custom metaclass is specified. This approach is less errorprone since th...
List assignment with [:]
7,677,275
12
2011-10-06T16:12:38Z
7,677,417
27
2011-10-06T16:23:35Z
[ "python", "list" ]
What's the difference between ``` list = range(100) ``` and ``` list[:] = range(100) ``` in Python? **EDIT** I should have mentioned that before that assignment list variable was already assigned to a list: ``` list = [1, 2, 3] list = range(100) ``` or ``` list = [1, 2, 3] list[:] = range(100) ```
When you do ``` lst = anything ``` You're pointing the *name* `lst` at an object. It doesn't change the old object `lst` used to point to in *any way*, though if nothing else pointed to that object its reference count will drop to zero and it will get deleted. When you do ``` lst[:] = whatever ``` You're iterating...
python: run interactive python shell from program
7,677,312
21
2011-10-06T16:15:39Z
7,677,387
30
2011-10-06T16:21:09Z
[ "python", "debugging" ]
I often have the case that I'll be writing a script, and I'm up to a part of the script where I want to play around with some of the variables interactively. Getting to that part requires running a large part of the script I've already written. In this case it isn't trivial to run this program from inside the shell. I...
``` import code code.interact(local=locals()) ``` But using the Python debugger is probably more what you want: ``` import pdb pdb.set_trace() ```
What does the python re.template function do?
7,677,889
11
2011-10-06T17:03:24Z
7,678,131
10
2011-10-06T17:24:26Z
[ "python", "regex" ]
While using the re module in ipython I noticed an undocumented `template` function: ``` In [420]: re.template? Type: function Base Class: <type 'function'> String Form: <function template at 0xb7eb8e64> Namespace: Interactive File: /usr/tideway/lib/python2.7/re.py Definition: re.tem...
In CPython 2.7.1, [`re.template()` is defined](http://hg.python.org/cpython/file/e685b02ddcac/Lib/re.py#l213) as: ``` def template(pattern, flags=0): "Compile a template pattern, returning a pattern object" return _compile(pattern, flags|T) ``` `_compile` calls `_compile_typed` which calls `sre_compile.compil...
Is there a framework that can be used to test Python modules against several versions of Python?
7,677,897
3
2011-10-06T17:04:17Z
7,677,931
7
2011-10-06T17:07:27Z
[ "python", "unit-testing", "tox" ]
I there a framework that can be used to run Python unit tests on all installed versions of python? I have 3 versions of python installed on my system and I want to be able to run the unitests on all of them. The executables are using the "usual" naming convention: python2.5 python2.7 python3.2 My current environment ...
[tox](http://pypi.python.org/pypi/tox) does this and even more, like running the tests on multiple platforms too.
python - condensing comparisons
7,678,271
3
2011-10-06T17:37:25Z
7,678,301
8
2011-10-06T17:39:40Z
[ "python", "comparison", "comparison-operators" ]
I'm a new member here and also new to python. My question is as follows, is it valid to have a line like this? ``` if x or y is 'whatever': ``` I tested this in the interpreter and am getting inconsistent results. It would seem that this line yields more consistent and expected results ``` if (x or y) is 'whatever':...
`or` doesn't work like it does in English. `x or y` returns x if x is a true-ish value, otherwise it returns y. Strings are true-ish if they are not empty. Worse, "is" has a higher precedence that "or", so your expression is the same as `x or (y is 'whatever')`. So if x is not empty, it returns x (which will be true,...
How to override a column name in sqlalchemy using reflection and descriptive syntax
7,679,893
5
2011-10-06T20:09:23Z
7,680,509
9
2011-10-06T21:12:55Z
[ "python", "sqlalchemy" ]
Hello I'm trying to port a legacy application to python with sqlalchemy. The application's existing database has about 300 tables and in every table there is a colum named def such as : ``` create table accnt ( code varchar(20) , def varchar(50) --for accnt definition , ... ) ``` So when with declarative syn...
You can have your cake and eat it too. Define the columns you want to rename; sqlalchemy will automatically infer any columns you don't mention. ``` >>> from sqlalchemy import * >>> from sqlalchemy.ext.declarative import declarative_base >>> >>> engine = create_engine("sqlite:///:memory:") >>> >>> engine.execute("""...
run python source code line by line
7,681,431
6
2011-10-06T23:00:40Z
7,681,464
9
2011-10-06T23:05:32Z
[ "python" ]
Given a Python source code, is it possible to run the code line by line, as if you were debugging? And when it comes to a function call, I would like to 'step into' the function also. Thanks
`python -m pdb <script.py>` will run the script in the [Python debugger](http://docs.python.org/library/pdb.html).
Querying full name in Django
7,681,708
15
2011-10-06T23:42:46Z
17,361,729
7
2013-06-28T09:42:15Z
[ "python", "django" ]
How can I query on the full name in Django? To clarify, I essentially want to do create a temporary column, combining first\_name and last\_name to give a fullname, then do a LIKE on that, like so: ``` select [fields] from Users where CONCAT(first_name, ' ', last_name) LIKE '%John Smith%"; ``` The above query would ...
Easier: ``` from django.db.models import Q def find_user_by_name(query_name): qs = User.objects.all() for term in query_name.split(): qs = qs.filter( Q(first_name__icontains = term) | Q(last_name__icontains = term)) return qs ``` Where query\_name could be "John Smith" (but would also retrieve user Sm...
What's the difference between subprocess Popen and call (how can I use them)?
7,681,715
97
2011-10-06T23:44:34Z
7,681,815
136
2011-10-06T23:59:09Z
[ "python", "subprocess", "popen" ]
I want to call an external program from Python. I have used both `Popen()` and `call()` to do that. What's the difference between the two? My specific goal is to run the following command from Python. I am not sure how redirects work. ``` ./my_script.sh > output ``` I read [the documentation](http://docs.python.org...
There are two ways to do the redirect. Both apply to either `subprocess.Popen` or `subprocess.call`. 1. Set the keyword argument `shell = True` or `executable = /path/to/the/shell` and specify the command just as you have it there. 2. Since you're just redirecting the output to a file, set the keyword argument ```...
How is hash(None) calculated?
7,681,786
7
2011-10-06T23:55:43Z
7,681,889
9
2011-10-07T00:12:36Z
[ "python", "hash" ]
On my machine, `hash(None)` returns a value: ``` >>> hash(None) -2138947203 ``` Just out of curiosity, how is this hash value calculated? It doesn't seem as though this value is based on `None`'s `id` as it is the same if I restart the Python interpreter.
It *is* based on None's `id`, but None is one of a few Python objects that are defined as C global variables, so its address (typically) doesn't change between Python runs. Other such objects are `True` and `False` (but these are hashed as ints), or built-in classes like `object` and `tuple`. The address (and hash) is...
Python: Removing duplicate CSV entries
7,682,796
5
2011-10-07T03:35:38Z
7,682,814
8
2011-10-07T03:41:33Z
[ "python", "csv" ]
I have a CSV file with multiple entries. Example csv: ``` user, phone, email joe, 123, joe@x.com mary, 456, mary@x.com ed, 123, ed@x.com ``` I'm trying to remove the duplicates by a specific column in the CSV however with the code below I'm getting an "list index out of range". I thought by comparing `row[1]` with `n...
`row[1]` refers to the second column in the current row (phone). That's all well in good. However, you `newrows.append(row)` add the entire row to the list. When you check `row[1] in newrows` you are checking the individual phone number against a list of complete rows. But that's not what you want to do. You need to ...
Testing if Python string variable holds number (int,float) or non-numeric str?
7,682,798
5
2011-10-07T03:36:38Z
7,682,813
10
2011-10-07T03:41:26Z
[ "python" ]
If a Python string variable has had either an integer, floating point number or a non-numeric string placed in it, is there a way to easily test the "type" of that value? The code below is real (and correct of course): ``` >>> strVar = "145" >>> print type(strVar) <type 'str'> >>> ``` but is there a Python function ...
``` import ast def type_of_value(var): try: return type(ast.literal_eval(var)) except Exception: return str ``` Or, if you only want to check for int, change the third line to block inside `try` with: ``` int(var) return int ```
Converting xml to dictionary using ElementTree
7,684,333
14
2011-10-07T07:38:23Z
7,684,581
15
2011-10-07T08:07:52Z
[ "python", "xml", "dictionary", "elementtree" ]
I'm looking for an XML to dictionary parser using ElementTree, I already found some but they are excluding the attributes, and in my case I have a lot of attributes.
``` def etree_to_dict(t): d = {t.tag : map(etree_to_dict, t.iterchildren())} d.update(('@' + k, v) for k, v in t.attrib.iteritems()) d['text'] = t.text return d ``` Call as ``` tree = etree.parse("some_file.xml") etree_to_dict(tree.getroot()) ``` This works as long as you don't actually have an attri...
Converting xml to dictionary using ElementTree
7,684,333
14
2011-10-07T07:38:23Z
10,076,823
15
2012-04-09T17:03:35Z
[ "python", "xml", "dictionary", "elementtree" ]
I'm looking for an XML to dictionary parser using ElementTree, I already found some but they are excluding the attributes, and in my case I have a lot of attributes.
The following XML-to-Python-dict snippet parses entities as well as attributes following [this XML-to-JSON "specification"](http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html): ``` from collections import defaultdict def etree_to_dict(t): d = {t.tag: {} if t.attrib else None} children = ...
Django cannot import name x
7,684,408
25
2011-10-07T07:46:51Z
7,684,485
54
2011-10-07T07:55:48Z
[ "python", "django", "django-models" ]
I got an error I don't understand ! *cannot import name Item* In my model, I have items. These items are required for actions. But some of these items have an effect on actions : **items** ``` from django.db import models from effects.models import Effect class Type(models.Model): name = models.CharField(max_l...
There is a circular import in your code, that's why the Item can't be imported in action. You can solve the problem by removing the import of a class in one of your files, and replacing it with a string containing the name of the class, [as explained in the documentation](https://docs.djangoproject.com/en/dev/ref/mode...
Django cannot import name x
7,684,408
25
2011-10-07T07:46:51Z
16,353,007
21
2013-05-03T06:33:09Z
[ "python", "django", "django-models" ]
I got an error I don't understand ! *cannot import name Item* In my model, I have items. These items are required for actions. But some of these items have an effect on actions : **items** ``` from django.db import models from effects.models import Effect class Type(models.Model): name = models.CharField(max_l...
Like madjar suggested, there is likely a circular import in your code. If you're having trouble finding out where the circle is (which modules and imports are involved), you can use the traceback option to get an idea of where the problem lies: ``` python manage.py validate --traceback ```
sparse 3d matrix/array in Python?
7,685,128
38
2011-10-07T09:08:40Z
7,728,830
10
2011-10-11T15:47:18Z
[ "python", "numpy", "scipy", "sparse-matrix" ]
In scipy, we can construct a sparse matrix using scipy.sparse.lil\_matrix() etc. But the matrix is in 2d. I am wondering if there is an existing data structure for sparse 3d matrix / array (tensor) in Python? p.s. I have lots of sparse data in 3d and need a tensor to store / perform multiplication. Any suggestions to...
Happy to suggest a (possibly obvious) implementation of this, which could be made in pure Python or C/Cython if you've got time and space for new dependencies, and need it to be faster. A sparse matrix in N dimensions can assume most elements are empty, so we use a dictionary keyed on tuples: ``` class NDSparseMatrix...
Optimal file structure organization of Python module unittests?
7,685,483
18
2011-10-07T09:38:40Z
7,685,835
16
2011-10-07T10:11:27Z
[ "python", "unit-testing" ]
Sadly I observed that there are are too many ways to keep your unittest in Python and they are not usually well documented. I am looking for an "ultimate" structure, one would accomplish most of the below requirements: * be discoverable by test frameworks, including: + `pytest` + `nosetests` + `tox` * the tests...
Here's the approach I've been using: **Directory structure** ``` # All __init__.py files are empty in this example. app package_a __init__.py module_a.py package_b __init__.py module_b.py test __init__.py test_app.py __init__.py main.py ``` **main.py** ...
Removing delimiters
7,686,194
2
2011-10-07T10:46:03Z
7,687,139
8
2011-10-07T12:19:46Z
[ "python", "perl", "shell" ]
I have a file looking like this: ``` ('chr1', '1499102', '1500297') ('chr1', '1811177', '1812131') ('chr1', '2312420', '2313646') ('chr1', '6683999', '6684724') ``` N number of rows. I want to print it like this: ``` chr1 (tab) 1499102 (tab) 1500297 ``` Any one liner shell or python or perl.
``` perl -nE '$,="\t"; say eval' file.txt ``` Making use of perl's output record separator, `$,` to provide the tabs. `eval` should be safe to use on single quoted strings, and is probably the best option.
What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()?
7,686,275
27
2011-10-07T10:54:28Z
7,686,464
22
2011-10-07T11:13:40Z
[ "python", "subprocess", "posix", "file-descriptor", "ioerror" ]
I am using a scientific software including a Python script that is calling `os.system()` which is used to run another scientific program. While the subprocess is running, Python at some point prints the following: ``` close failed in file object destructor: IOError: [Errno 9] Bad file descriptor ``` I believe that th...
You get this error message if a Python file was closed from "the outside", i.e. not from the file object's `close()` method: ``` >>> f = open(".bashrc") >>> os.close(f.fileno()) >>> del f close failed in file object destructor: IOError: [Errno 9] Bad file descriptor ``` The line `del f` deletes the last reference to ...
Are docstrings for internal functions (python) necessary?
7,687,407
7
2011-10-07T12:42:05Z
7,687,430
10
2011-10-07T12:44:54Z
[ "python", "documentation", "standards", "pep8" ]
In python we designate internal function/ private methonds with an underscore at the beginning. Should these functions be documented with docstrings(is it required?)? (the formal documentation i mean, not the one helping the code-reader to understand the code) What is common practice for this?
Lo, I quote from [PEP 8](http://www.python.org/dev/peps/pep-0008/), the wise words of which should be considered law. Upon this very topic, PEP 8 saith: > * Write docstrings for all public modules, functions, classes, and > methods. Docstrings are not necessary for non-public methods, but you > should have a comme...
'tuple' object does not support item assignment
7,687,510
14
2011-10-07T12:52:02Z
7,687,615
21
2011-10-07T13:00:40Z
[ "python", "python-imaging-library" ]
I am using the PIL library. I am trying to make an image look red-er, this is what i've got. ``` from PIL import Image image = Image.open('balloon.jpg') pixels = list(image.getdata()) for pixel in pixels: pixel[0] = pixel[0] + 20 image.putdata(pixels) image.save('new.bmp') ``` However I get this error: `Typ...
PIL pixels are tuples, and tuples are immutable. You need to construct a new tuple. So, instead of the for loop, do: ``` pixels = [(pixel[0] + 20, pixel[1], pixel[2]) for pixel in pixels] image.putdata(pixels) ``` Also, if the pixel is already too red, adding 20 will overflow the value. You probably want something li...
How to generate 2D gaussian with Python?
7,687,679
11
2011-10-07T13:05:27Z
7,687,702
29
2011-10-07T13:07:29Z
[ "python", "gaussian" ]
I can generate Gaussian data with `random.gauss(mu, sigma)` function, but how can I generate 2D gaussian? Is there any function like that?
If you can use `numpy`, there is [`numpy.random.multivariate_normal(mean, cov[, size])`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.multivariate_normal.html#numpy.random.multivariate_normal). For example, to get 10,000 2D samples: ``` np.random.multivariate_normal(mean, cov, 10000) ``` where `m...
How to generate 2D gaussian with Python?
7,687,679
11
2011-10-07T13:05:27Z
7,687,768
10
2011-10-07T13:13:53Z
[ "python", "gaussian" ]
I can generate Gaussian data with `random.gauss(mu, sigma)` function, but how can I generate 2D gaussian? Is there any function like that?
Since the standard 2D Gaussian distribution is just the product of two 1D Gaussian distribution, *if there are no correlation between the two axes* (i.e. the covariant matrix is diagonal), just call `random.gauss` twice.
How to generate 2D gaussian with Python?
7,687,679
11
2011-10-07T13:05:27Z
14,525,830
8
2013-01-25T16:17:53Z
[ "python", "gaussian" ]
I can generate Gaussian data with `random.gauss(mu, sigma)` function, but how can I generate 2D gaussian? Is there any function like that?
I'd like to add an approximation using exponential functions. This directly generates a 2d matrix which contains a movable, symmetric 2d gaussian. I should note that I found this code on the scipy mailing list archives and modified it a little. ``` import numpy as np def makeGaussian(size, fwhm = 3, center=None): ...
Maximum flow - Ford-Fulkerson: Undirected graph
7,687,732
15
2011-10-07T13:10:05Z
7,688,088
9
2011-10-07T13:39:25Z
[ "python", "algorithm", "ford-fulkerson" ]
I am trying to solve the maxium flow problem for a graph using Ford–Fulkerson algorithm. The algorithm is only described with a directed graph. What about when the graph is undirected? What I have done to mimic an undirected graph is to use two directed edges between a pair of vertices. What confuses me is: Should e...
Your approach using two antiparallel edges works. If your edge is `a->b` (capacity 10, we send 7 over it), we introduce a new residual edge (from `b` to `a` that has residual capacity 17, the residual edge from `a` to `b` has the remaining capacity 3). The original back-edge (from `b` to `a`) can be left as it is or t...
convert dec number to 6 bit binary number
7,687,928
2
2011-10-07T13:26:51Z
7,687,962
8
2011-10-07T13:30:17Z
[ "python", "binary", "bin" ]
I am looking to convert a dec number to a 6 bit binary number.. `bin()` works fine but omits leading zeros which are important. for example: * 0 = 000000 * 1 = 000001 * 2 = 000010 etc... with the largest dec number allowed being 63.
Either what Matt said in the comment (`bin(63)[2:].zfill(6)`), or use [format strings](http://docs.python.org/library/string.html#formatstrings) in Python 2.6+: ``` '{0:06b}'.format(63) ``` You can omit the first zero in Python 2.7+ as you can implicitly number groups.
How to force numpy array order to fortran style?
7,688,304
9
2011-10-07T13:58:48Z
7,689,039
7
2011-10-07T14:58:03Z
[ "python", "arrays", "performance", "numpy", "fortran" ]
I am using quite a lot of fortran libraries to do some mathematical computation. So all the arrays in numpy need to be *Fortran-contiguous*. Currently I accomplish this with [numpy.asfortranarray()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.asfortranarray.html). My questions are: 1. Is this a fast w...
Use optional argument order='F' (default 'C'), when generating numpy.array objects. This is the way I do it, probably does the same thing that you are doing. About number 2, I am not aware of setting default order, but it's easy enough to just include order optional argument when generating arrays.
How to fix default values from a dictionary Pythonically?
7,688,453
5
2011-10-07T14:11:46Z
7,688,512
15
2011-10-07T14:15:25Z
[ "python" ]
I am parsing JSON requests using the JSON library which parses into python dictionary. As the requests are user-generated, I need to fix default values for parameters that have not been supplied. Other languages have stuff like ternary operators which make sense for repetitive applications. But the code below needs 4 l...
Use the [`dict.update`](http://docs.python.org/library/stdtypes.html#dict.update) method on a copy of the defaults: ``` defaults = dict(a=1, b=2, c=3) result = dict(defaults) # Copy the defaults result.update(request) # Update with your values ``` This allows you to keep `defaults` as a class attribute or module g...
How to fix default values from a dictionary Pythonically?
7,688,453
5
2011-10-07T14:11:46Z
7,688,516
12
2011-10-07T14:15:42Z
[ "python" ]
I am parsing JSON requests using the JSON library which parses into python dictionary. As the requests are user-generated, I need to fix default values for parameters that have not been supplied. Other languages have stuff like ternary operators which make sense for repetitive applications. But the code below needs 4 l...
You can use the dictionary method `get`, whose second argument is the default value to return if no value exists in the dictionary. ``` start = request.get('start', 0) ```
multiple actions in list comprehension python
7,688,725
7
2011-10-07T14:31:59Z
7,688,754
15
2011-10-07T14:35:00Z
[ "python", "list-comprehension" ]
I would like to know how to perform multiple commands in a list comprehension. Can you give me an exmple for something simple like: ``` [print ("bla1") and print ("bla2") for i in list] ``` so for a list of 4 length 4 I would have: ``` bla1 bla2 bla1 bla2 bla1 bla2 bla1 bla2 ``` strangely enough I didn't easily fi...
Don't use list comprehension for commands. List comprehensions are for *creating lists*, not for commands. Use a plain old loop: ``` for i in list: print('bla1') print('bla2') ``` List comprehensions are wonderful amazing things full of unicorns and chocolate, but they're not a solution for everything.
Passing variables between Python and Javascript
7,689,695
11
2011-10-07T15:49:38Z
7,689,782
9
2011-10-07T15:55:11Z
[ "javascript", "python", "variables", "sqlalchemy" ]
Imagine that you need to write some Javascript that simply changes a set of checkboxes when a drop down list is changed. Depending on which item is selected in the list, some of the checkboxes will become checked/unchecked. In the back, you have Python code along with some SQLAlchemy. The Javascript needs to identif...
Funny, I've got web pages with JavaScript that talk to Python CGI modules that use SQLAlchemy. What I do is send AJAX request but with JSON request in the body instead of XML. Python CGI modules use standard [`json`](http://docs.python.org/library/json.html) module to deserialize JSON into a dictionary. JavaScript si...
How can I retrieve the TLS/SSL peer certificate of a remote host using python?
7,689,941
18
2011-10-07T16:07:13Z
7,691,293
28
2011-10-07T18:19:39Z
[ "python", "ssl", "m2crypto" ]
I need to scan through a list of IPs and retrieve the common name from the certificate on that IP (for every IP that allows port 443 connections). I have been able to successfully do this using the sockets and ssl modules. It works for all IPs with valid, signed certificates but it isn't working for self-signed certifi...
The python ssl library seems like it only parses out the cert for you if it has a valid signature. ``` """Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not valida...
How to document python function parameter types?
7,690,220
11
2011-10-07T16:36:39Z
22,552,647
8
2014-03-21T07:22:06Z
[ "python", "doxygen" ]
I know that the parameters can be any object but for the documentation it is quite important to specify what you would expect. First is how to specify a parameter types like these below? * `str` (or use `String` or `string`?) * `int` * `list` * `dict` * function() * `tuple` * object instance of class `MyClass` Secon...
There is a better way. We use ``` def my_method(x, y): """ my_method description @type x: int @param x: An integer @type y: int|string @param y: An integer or string @rtype: string @return: Returns a sentence with your variables in it """ return "Hello World! %s, %s" % (x,y)...
Extracting text from XML using python
7,691,514
4
2011-10-07T18:40:53Z
7,691,612
9
2011-10-07T18:49:48Z
[ "python", "xml" ]
I have this example xml file ``` <page> <title>Chapter 1</title> <content>Welcome to Chapter 1</content> </page> <page> <title>Chapter 2</title> <content>Welcome to Chapter 2</content> </page> ``` I like to extract the contents of title tags and content tags. Which method is good to extract the data, using pat...
There is already a built-in XML library, notably [`ElementTree`](http://docs.python.org/library/xml.etree.elementtree.html). For example: ``` >>> from xml.etree import cElementTree as ET >>> xmlstr = """ ... <root> ... <page> ... <title>Chapter 1</title> ... <content>Welcome to Chapter 1</content> ... </page> ... ...
execute python script with function from command line, Linux
7,691,599
4
2011-10-07T18:48:36Z
7,691,690
12
2011-10-07T18:59:04Z
[ "python", "linux", "shell", "command-line" ]
I have my python file called convertImage.py and inside the file I have a script that converts an image to my liking, the entire converting script is set inside a function called convertFile(fileName) Now my problem is I need to execute this python script from the linux command line while passing the convertFile(fileN...
This ``` if __name__ == "__main__": command= " ".join( sys.argv[1:] ) eval( command ) ``` This will work. But it's insanely dangerous. You really need to think about what your command-line syntax is. And you need to think about why you're breaking the long-established Linux standards for specifying arguments...
Filtering Django Admin by Null/Is Not Null
7,691,890
6
2011-10-07T19:18:04Z
9,593,302
11
2012-03-06T22:59:21Z
[ "python", "django", "django-admin", "django-admin-filters" ]
I have a simple Django model like: ``` class Person(models.Model): referrer = models.ForeignKey('self', null=True) ... ``` In this model's ModelAdmin, how would I allow it to be filtered by whether or not referrer is null? By default, adding referrer to list\_filter causes a dropdown to be shown that lists **...
Since Django 1.4 brings some changes to filters, I thought I save someone the time I just spent modifying the code from Cerin's accepted answer to work with Django 1.4 rc1. I have a model that has TimeField(null=True) named "started" and I wanted to filter for null and non-null values, so it's prety much the same prob...
Python version of C#'s conditional operator (?)
7,692,121
5
2011-10-07T19:40:48Z
7,692,125
10
2011-10-07T19:41:59Z
[ "python", "conditional-operator" ]
I saw [this question](http://stackoverflow.com/questions/4978738/is-there-a-python-equivalent-of-the-c-null-coalescing-operator) but it uses the ?? operator as a null check, I want to use it as a bool true/false test. I have this code in Python: ``` if self.trait == self.spouse.trait: trait = self.trait else: ...
Yes, you can write: ``` trait = self.trait if self.trait == self.spouse.trait else defaultTrait ``` This is called a [Conditional Expression](http://docs.python.org/reference/expressions.html#conditional-expressions) in Python.
Individual point-sizing in Matplotlib?
7,692,174
6
2011-10-07T19:46:58Z
7,692,591
7
2011-10-07T20:32:17Z
[ "python", "matlab", "plot", "matplotlib" ]
I'd like to have non-uniform point sizes in matplotlib (set a size for each point). Is there a way to do this? I guess I could hack it by having a separate plot command (with markersize set) for each point, but that would be really annoying. Is there a more principled way?
I just found out that you can use `scatter` for this: ``` scatter(500:600,600:700,1:101); ``` where the format is: `scatter(x,y,sizes,markerType)` Produces: ![enter image description here](http://i.stack.imgur.com/LNBXk.png)
Why is '+' not understood by Python sets?
7,692,324
46
2011-10-07T20:02:23Z
7,692,347
59
2011-10-07T20:06:01Z
[ "python", "set" ]
I would like to know why this is valid: ``` set(range(10)) - set(range(5)) ``` but this is not valid: ``` set(range(10)) + set(range(5)) ``` Is it because '+' could mean both intersection and union?
Python sets don't have an implementation for the `+` operator. You can use `|` for set union and `&` for set intersection. Sets do implement `-` as set difference. You can also use `^` for symmetric set difference (i.e., it will return a new set with only the objects that appear in one set but do not appear in both s...
Why is '+' not understood by Python sets?
7,692,324
46
2011-10-07T20:02:23Z
7,692,368
9
2011-10-07T20:08:35Z
[ "python", "set" ]
I would like to know why this is valid: ``` set(range(10)) - set(range(5)) ``` but this is not valid: ``` set(range(10)) + set(range(5)) ``` Is it because '+' could mean both intersection and union?
Because `|` means union and `&` means intersection. There's clearly no reason to add multiple operators for the same function. The reasons for using `|` and `&` probably goes back to bitwise operations. If you represent a set as the bits in a number, those are the operators you'd use to do union and intersect. `+` si...
Why is '+' not understood by Python sets?
7,692,324
46
2011-10-07T20:02:23Z
7,692,369
21
2011-10-07T20:08:42Z
[ "python", "set" ]
I would like to know why this is valid: ``` set(range(10)) - set(range(5)) ``` but this is not valid: ``` set(range(10)) + set(range(5)) ``` Is it because '+' could mean both intersection and union?
Sure, they could have used `+` to do a union, but then would still need a symbol for intersection. `|` for union is symmetrical with `&` for intersection and thus makes a better choice.
Why is '+' not understood by Python sets?
7,692,324
46
2011-10-07T20:02:23Z
7,692,469
63
2011-10-07T20:19:09Z
[ "python", "set" ]
I would like to know why this is valid: ``` set(range(10)) - set(range(5)) ``` but this is not valid: ``` set(range(10)) + set(range(5)) ``` Is it because '+' could mean both intersection and union?
Python chose to use `|` instead of `+` because set union is a concept that is closely related to boolean disjunction; Bit vectors (which in python are just `int`/`long`) define this operation across a sequence of boolean values and call it "bitwise or". In fact this operation is so similar to the set union that binary ...
Why is '+' not understood by Python sets?
7,692,324
46
2011-10-07T20:02:23Z
7,695,491
15
2011-10-08T07:46:54Z
[ "python", "set" ]
I would like to know why this is valid: ``` set(range(10)) - set(range(5)) ``` but this is not valid: ``` set(range(10)) + set(range(5)) ``` Is it because '+' could mean both intersection and union?
In set theory the + symbol normally indicates the **disjoint union** of two sets. If A and B are sets, their disjoint union is defined to be the set ``` A + B = {(a, 1) | a in A} U {(b, 2) | b in B} ``` i.e., to construct the disjoint union, we mark all elements of A and all elements of B with different tags (in the ...
python closure + oop
7,692,423
3
2011-10-07T20:12:53Z
7,692,447
7
2011-10-07T20:16:18Z
[ "python", "oop", "closures" ]
I'm trying to do something a bit strange (at least to me) with python closure. Say I have 2 classes like this: ``` #!/usr/bin/python import types def method_a(self): print "ma %d" % self.val class A(object): def __init__(self): self.val = 5 pass def foo(self, a): def closure(self...
Give the inner self another name: ``` def foo(self, a): def closuer(b): print "closure %d, %d" % (self.val, a) return closuer ``` Also, rather then using types.MethodType, you might want to use functools.partial
Using Django Managers vs. staticmethod on Model class directly
7,692,487
16
2011-10-07T20:20:48Z
7,693,340
23
2011-10-07T22:09:10Z
[ "python", "django" ]
After reading up on Django Managers, I'm still unsure how much benefit I will get by using it. It seems that the best use is to add custom queries (read-only) methods like `XYZ.objects.findBy*()`. But I can easily do that with static methods off of the `Model` classes themselves. I prefer the latter always because: 1...
Adding custom queries to managers is the Django convention. From the Django docs on [custom managers](https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers): > Adding extra Manager methods is the preferred way to add "table-level" functionality to your models. If it's your own private app, the con...
How to make a log log histogram in python
7,694,298
13
2011-10-08T01:53:28Z
7,696,814
17
2011-10-08T12:31:45Z
[ "python", "matplotlib", "histogram" ]
Given an an array of values, I want to plot a log log histogram of these values by their counts. I only know how to log the x values, but not the y values because they are not explicitly created in my program.
Check out the pyplot [documentation](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.hist). * pyplot.hist can "log" y axis for you with keyword argument log=True * pyplot.hist accepts `bins` keyword argument, but you have to "log" x axis yourself For example: ``` #!/usr/bin/python import nump...
3D/4D graphics with Python and wxPython?
7,694,692
12
2011-10-08T03:51:13Z
7,695,647
13
2011-10-08T08:23:20Z
[ "python", "graphics", "wxpython", "3d", "vtk" ]
In my day job as a PhD student, I do geological modeling. In my spare time (mainly for fun), I am learning Python and trying to write a simple program to view 3D geocellular models. ![geological model](http://img710.imageshack.us/img710/6503/sgems.png) ![geo model2](http://img638.imageshack.us/img638/529/1sblockmodel....
What you are looking for is called *voxel* visualization, *voxel grid* or such. I would seriously consider [MayaVi](http://code.enthought.com/projects/mayavi/) (never used it, but I keep eye on it), it seems to have something very close [here](http://docs.enthought.com/mayavi/mayavi/mlab.html#visualizing-volumetric-sca...
3D/4D graphics with Python and wxPython?
7,694,692
12
2011-10-08T03:51:13Z
7,716,433
9
2011-10-10T17:29:03Z
[ "python", "graphics", "wxpython", "3d", "vtk" ]
In my day job as a PhD student, I do geological modeling. In my spare time (mainly for fun), I am learning Python and trying to write a simple program to view 3D geocellular models. ![geological model](http://img710.imageshack.us/img710/6503/sgems.png) ![geo model2](http://img638.imageshack.us/img638/529/1sblockmodel....
In my case, I chose to use directly the VTK bindings for Python. To be honest I found it simpler to get going with VTK than Mayavi, partly because the documentation is better (many many examples!). It felt like Mayavi was adding another layer of complexity on my way to get the job done. But `tom10` is right. After you'...
How to approach number guessing game(with a twist) algorithm?
7,694,978
46
2011-10-08T05:20:52Z
7,696,379
11
2011-10-08T11:06:58Z
[ "java", "python", "algorithm", "machine-learning", "data-mining" ]
I am learning programming (python and algo’s) and was trying to work on a project that I find interesting. I have created a few basic python scripts but I’m not sure how to approach a solution to a game I am trying to build. **Here’s how the game will work:** users will be given items with a value. For example ...
We'll combine graph-theory and probability: On the 1st day, build a set of all feasible solutions. Lets denote the solutions set as A1={a1(1), a1(2),...,a1(n)}. On the second day you can again build the solutions set A2. Now, for each element in A2, you'll need to check if it can be reached from each element of A1 (...
How to approach number guessing game(with a twist) algorithm?
7,694,978
46
2011-10-08T05:20:52Z
7,697,660
7
2011-10-08T15:02:56Z
[ "java", "python", "algorithm", "machine-learning", "data-mining" ]
I am learning programming (python and algo’s) and was trying to work on a project that I find interesting. I have created a few basic python scripts but I’m not sure how to approach a solution to a game I am trying to build. **Here’s how the game will work:** users will be given items with a value. For example ...
This problem is impossible to solve. Lets say that you know exactly for what ratio number of items was increased, not just what is maximum ratio for this. User has N fruits and you have D days of guessing. In each day you get N new variables and then you have in total D\*N variables. For each day you can generate on...
Way to create multiline comments?
7,696,924
491
2011-10-08T12:51:13Z
7,696,949
46
2011-10-08T12:54:52Z
[ "python", "comments" ]
I have recently started studying [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), but I couldn't find how to implement multi-line comments. Most languages have block comment symbols like ``` /* */ ``` I tried this in Python, but it throws an error, so this probably is not the correct way. D...
Python does have a [multiline string/comment syntax](http://stackoverflow.com/a/7696966/190597) in the sense that unless used as docstrings, [multiline strings *generate no bytecode*](https://twitter.com/gvanrossum/status/112670605505077248) -- just like `#`-prepended comments. In effect, it acts exactly like a comment...
Way to create multiline comments?
7,696,924
491
2011-10-08T12:51:13Z
7,696,951
7
2011-10-08T12:55:01Z
[ "python", "comments" ]
I have recently started studying [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), but I couldn't find how to implement multi-line comments. Most languages have block comment symbols like ``` /* */ ``` I tried this in Python, but it throws an error, so this probably is not the correct way. D...
AFAIK, Python doesn't have block comments. For commenting individual lines, you can use the `#` character. If you are using [Notepad++](https://en.wikipedia.org/wiki/Notepad++), [there is a shortcut for block commenting](http://stackoverflow.com/questions/1022261/commenting-code-in-notepad). I'm sure others like [gVim...
Way to create multiline comments?
7,696,924
491
2011-10-08T12:51:13Z
7,696,966
818
2011-10-08T12:58:47Z
[ "python", "comments" ]
I have recently started studying [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), but I couldn't find how to implement multi-line comments. Most languages have block comment symbols like ``` /* */ ``` I tried this in Python, but it throws an error, so this probably is not the correct way. D...
You can use triple-quoted strings. When they're not a docstring (first thing in a class/function/module), they are ignored. ``` ''' This is a multiline comment. ''' ``` Guido van Rossum (creator of Python) [tweeted this](https://twitter.com/gvanrossum/status/112670605505077248) as a "pro tip". However, Python's styl...
Way to create multiline comments?
7,696,924
491
2011-10-08T12:51:13Z
28,543,125
11
2015-02-16T14:00:30Z
[ "python", "comments" ]
I have recently started studying [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), but I couldn't find how to implement multi-line comments. Most languages have block comment symbols like ``` /* */ ``` I tried this in Python, but it throws an error, so this probably is not the correct way. D...
In python 2.7 the multile comment is: ``` """ this is a multilline comment """ ``` in case you are inside a class you should tab it properly. for example: ``` class weather2(): """ def getStatus_code(self, url): world.url = url result = requests.get(url) return result.status_code """ ...
how to show a message from a blender script?
7,697,532
7
2011-10-08T14:44:03Z
7,743,556
7
2011-10-12T16:45:53Z
[ "python", "scripting", "blender" ]
Is there a way to show a simple message box with a text from a blender script? For example if i'm having an error during execution.
Have a look at this [code snippet](http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Cookbook/Code_snippets/Interface#An_error_dialog) for an error dialog / message window. After selecting, a (text) file a message pops up when the word *return* is read. It works basically but I had to hit escape to make the box disa...
Python running out of memory parsing XML using cElementTree.iterparse
7,697,710
15
2011-10-08T15:12:26Z
7,699,801
11
2011-10-08T21:13:41Z
[ "python", "memory-management", "memory-leaks", "elementtree" ]
A simplified version of my XML parsing function is here: ``` import xml.etree.cElementTree as ET def analyze(xml): it = ET.iterparse(file(xml)) count = 0 for (ev, el) in it: count += 1 print('count: {0}'.format(count)) ``` This causes Python to run out of memory, which doesn't make a whole ...
[The documentation](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.iterparse) does tell you "Parses an XML section *into an element tree* [my emphasis] incrementally" but doesn't cover how to avoid retaining uninteresting elements (which may be all of them). That is covered by [this art...
How to debug urllib2 request that uses a basic authentication handler
7,697,963
16
2011-10-08T15:56:03Z
7,698,546
22
2011-10-08T17:29:50Z
[ "python", "debugging", "urllib2", "basic-authentication" ]
I'm making a request using `urllib2` and the `HTTPBasicAuthHandler` like so: ``` import urllib2 theurl = 'http://someurl.com' username = 'username' password = 'password' passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, theurl, username, password) authhandler = urllib2.HTTPBasicAuthHand...
Have you tried setting the debug level in your own HTTP handler? Change your code to something like this: ``` >>> import urllib2 >>> handler=urllib2.HTTPHandler(debuglevel=1) >>> opener = urllib2.build_opener(handler) >>> urllib2.install_opener(opener) >>> resp=urllib2.urlopen('http://www.google.com').read() send: 'GE...
python PIL draw multiline text on image
7,698,231
19
2011-10-08T16:34:17Z
7,698,300
27
2011-10-08T16:46:02Z
[ "python", "image", "text", "python-imaging-library" ]
I try to add text at the bottom of image and actually I've done it, but in case of my text is longer then image width it is cut from both sides, to simplify I would like text to be in multiple lines if it is longer than image width. Here is my code: ``` FOREGROUND = (255, 255, 255) WIDTH = 375 HEIGHT = 50 TEXT = 'Chyb...
You could use [`textwrap.wrap`](https://docs.python.org/2/library/textwrap.html#textwrap.wrap) to break `text` into a list of strings, each at most `width` characters long: ``` import textwrap lines = textwrap.wrap(text, width=40) y_text = h for line in lines: width, height = font.getsize(line) draw.text(((w -...
defining python function without the brackets
7,698,603
9
2011-10-08T17:41:39Z
7,698,683
7
2011-10-08T17:54:37Z
[ "python", "function", "definition" ]
I understand that my question might sound stupid, and that there might be something in the language definition that explicitly prohibits this notion, but since I don't know about this prohibition, I was wondering whether someone could shed some light on it. In short, I would like to define a python function that I coul...
You're going to get some syntax in there somewhere. You could try something like: ``` import os class Shell(object): @property def pwd(self): print os.getcwd() ``` And then in your interpreter, run: ``` >>> s = Shell() >>> s.pwd /tmp ```
defining python function without the brackets
7,698,603
9
2011-10-08T17:41:39Z
7,698,790
9
2011-10-08T18:16:37Z
[ "python", "function", "definition" ]
I understand that my question might sound stupid, and that there might be something in the language definition that explicitly prohibits this notion, but since I don't know about this prohibition, I was wondering whether someone could shed some light on it. In short, I would like to define a python function that I coul...
You can't do this without modifying the language or the shell. If you want to use Python as a shell, you should really try [IPython](http://ipython.org/), it allows you to define macros that you can use without typing as many keys. It also lets you do `!pwd`, you can assign this to a variable as well `x = !pwd`. It ev...
Clean and type-safe state machine implementation in a statically typed language?
7,699,912
25
2011-10-08T21:34:49Z
7,700,034
11
2011-10-08T21:57:34Z
[ "python", "c", "language-agnostic", "haskell", "typing" ]
I implemented a simple state machine in Python: ``` import time def a(): print "a()" return b def b(): print "b()" return c def c(): print "c()" return a if __name__ == "__main__": state = a while True: state = state() time.sleep(1) ``` I wanted to port it to C, be...
In the C-like type systems functions are not first order citizens. There are certain restrictions on handling them. That was a decision for simplicity and speed of implementation/execution that stuck. To have functions behave like objects, one generally requires support for closures. Those however are not naturally sup...
Clean and type-safe state machine implementation in a statically typed language?
7,699,912
25
2011-10-08T21:34:49Z
7,700,082
11
2011-10-08T22:07:05Z
[ "python", "c", "language-agnostic", "haskell", "typing" ]
I implemented a simple state machine in Python: ``` import time def a(): print "a()" return b def b(): print "b()" return c def c(): print "c()" return a if __name__ == "__main__": state = a while True: state = state() time.sleep(1) ``` I wanted to port it to C, be...
The problem with your Haskell code is, that `type` only introduces a synonym, which is quite similar to what `typedef` in C does. One important restriction is, that the expansion of the type must be finite, you can't give a finite expansion of your state machine. A solution is using a `newtype`: A `newtype` is a wrappe...
Clean and type-safe state machine implementation in a statically typed language?
7,699,912
25
2011-10-08T21:34:49Z
7,700,169
21
2011-10-08T22:26:43Z
[ "python", "c", "language-agnostic", "haskell", "typing" ]
I implemented a simple state machine in Python: ``` import time def a(): print "a()" return b def b(): print "b()" return c def c(): print "c()" return a if __name__ == "__main__": state = a while True: state = state() time.sleep(1) ``` I wanted to port it to C, be...
In Haskell, the idiom for this is just to go ahead and execute the next state: ``` type StateMachine = IO () a, b, c :: StateMachine a = print "a()" >> b b = print "b()" >> c c = print "c()" >> a ``` You need not worry that this will overflow a stack or anything like that. If you insist on having states, then you sho...
Clean and type-safe state machine implementation in a statically typed language?
7,699,912
25
2011-10-08T21:34:49Z
7,700,185
15
2011-10-08T22:30:48Z
[ "python", "c", "language-agnostic", "haskell", "typing" ]
I implemented a simple state machine in Python: ``` import time def a(): print "a()" return b def b(): print "b()" return c def c(): print "c()" return a if __name__ == "__main__": state = a while True: state = state() time.sleep(1) ``` I wanted to port it to C, be...
If you use `newtype` instead of `data`, you don't incur any overhead. Also, you can wrap each state's function at the point of definition, so the expressions that use them don't have to: ``` import Control.Monad newtype State = State { runState :: IO State } a :: State a = State $ print "a()" >> return b b :: State...
What's the idiomatic python equivalent of get() for lists?
7,699,937
3
2011-10-08T21:39:02Z
7,699,955
7
2011-10-08T21:42:08Z
[ "python", "idiomatic", "idioms" ]
Calling get(key) on a dictionary will return None by default if the key isn't present in a dictionary. What is the idiomatic equivalent for a list, such that if a list is of at least size of the passed in index the element is returned, otherwise None is returned? To rephrase, what's a more idiomatic/compact version of...
Your implementation is [Look Before You Leap](http://docs.python.org/glossary.html#term-lbyl)-style. It's pythonic to [execute the code and catch errors](http://docs.python.org/glossary.html#term-eafp) instead: ``` def get(l, i, d=None): try: return l[i] except IndexError: return d ```
DHT: BitTorrent vs kademlia vs clones (python)
7,700,562
5
2011-10-09T00:11:39Z
7,708,738
7
2011-10-10T05:05:30Z
[ "python", "bittorrent", "xor", "dht", "kademlia" ]
I'm in the middle of implementing my own dht for internal cluster. Since it will be used in file-sharing program like bittorrent, "Mainline DHT" was the first thing I was look at. After that I found "entangled" (python, dht using twisted matrix), congress (python, dht using pyev + libev) and of course original "kademli...
The kademlia paper actually calls out the optimization of dynamically splitting buckets as the routing table grows. There is no logic difference between these two approaches, it's just an optimization to save some space. When implementing a fixed full sized routing table, you have to find k nodes to send requests to. I...
Python: multiprocessing.map: If one process raises an exception, why aren't other processes' finally blocks called?
7,700,929
19
2011-10-09T01:52:05Z
7,703,607
22
2011-10-09T12:48:50Z
[ "python", "multithreading", "multiprocessing", "try-catch-finally" ]
My understanding is that finally clauses *must* \*always\* be executed if the try has been entered. ``` import random from multiprocessing import Pool from time import sleep def Process(x): try: print x sleep(random.random()) raise Exception('Exception: ' + x) finally: print 'Finally: ' + x Pool...
**Short answer: `SIGTERM` trumps `finally`.** Long answer: Turn on logging with `mp.log_to_stderr()`: ``` import random import multiprocessing as mp import time import logging logger=mp.log_to_stderr(logging.DEBUG) def Process(x): try: logger.info(x) time.sleep(random.random()) raise Exc...
Efficient evaluation of a function at every cell of a NumPy array
7,701,429
57
2011-10-09T04:21:10Z
7,701,560
78
2011-10-09T05:06:11Z
[ "python", "performance", "function", "numpy", "vectorization" ]
Given a [NumPy](http://en.wikipedia.org/wiki/NumPy) array *A*, what is the fastest/most efficient way to apply the **same** function, *f*, to **every** cell? 1. Suppose that we will assign to *A(i,j)* the *f(A(i,j))*. 2. The function, *f*, doesn't have a binary output, thus the mask(ing) operations won't help. Is the...
You could just [vectorize](http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html) the function and then apply it directly to a Numpy array each time you need it: ``` import numpy as np def f(x): return x * x + 3 * x - 2 if x > 0 else x * 5 + 8 f = np.vectorize(f) # or use a different name if ...
how to call a function from another file?
7,701,646
26
2011-10-09T05:32:30Z
7,701,650
30
2011-10-09T05:34:09Z
[ "python" ]
Sorry basic question I'm sure but I can't seem to figure this out. Say I have this program , the file is called `pythonFunction.py`: ``` def function(): return 'hello world' if __name__=='__main__': print function() ``` How can I call it in another program? I tried: ``` import pythonFunction as pythonFunctio...
You need to print the result of calling the function, rather than the function itself: ``` print pythonFunction.function() ``` Additionally, rather than `import pythonFunction as pythonFunction`, you can omit the `as` clause: ``` import pythonFunction ``` If it's more convenient, you can also use `from...import`: ...
Python - Trouble in building executable
7,701,855
7
2011-10-09T06:42:13Z
10,559,877
10
2012-05-11T23:45:22Z
[ "python", "selenium", "wxpython" ]
I'm a python programmer and I'm trying to build an executable binary to distribute my software to my clients, even if it's not fully executable I want to be able to distribute my software in a way so that it is convenient for the end user. I have already tried PyInstaller as well as Py2Exe and I'm facing the same prob...
I was at this all day and found a workaround, it's sneaky but it works. In the error message I was receiving I noticed that there was a space between in library .zip. I could not trace it down in the source code for py2exe or selenium. I too had tried putting the xpi file in the library zip and it did not work. The wor...
Python - Finding each occurrence of a value in a mixed array (integers, lists)
7,702,036
4
2011-10-09T07:25:33Z
7,702,063
8
2011-10-09T07:31:39Z
[ "python", "arrays", "for-loop" ]
I have an array: `x = [ [1, 2], 1, 1, [2, 1, [1, 2]] ]` in which I want to count every occurrence of the number `1`, and store that number in the variable `one_counter`. `x.count(1)` returns only 2 occurrences of `1`, which is insufficient. My code below serves my purpose and stores `5` in `one_counter`, however ...
You could use recursion: ``` def flatten_count(iterable, element): count = 0 for item in iterable: if item == element: count += 1 if isinstance(item, list): count += flatten_count(item, element) return count ``` Or more concisely: ``` def flatten_count(iterable, el...
Produce PDF files, draw polygons with rounded corners
7,702,773
5
2011-10-09T10:10:43Z
7,705,852
13
2011-10-09T19:10:47Z
[ "python", "pdf-generation", "vector-graphics", "bezier-curve", "polygons" ]
What's the right tool for the job if I want to write a Python script that produces **vector graphics in PDF format**? In particular, I need to draw filled **polygons with rounded corners** (i.e., plane figures that are composed of straight lines and **circular arcs**). It seems that [matplotlib](http://matplotlib.sour...
Here's a somewhat hacky matplotlib solution. The main complications are related to using matplotlib `Path` objects to build a composite `Path`. ``` #!/usr/bin/env python import numpy as np from matplotlib.path import Path from matplotlib.patches import PathPatch, Polygon from matplotlib.transforms import Bbox, BboxTr...
How to write namespaced element attributes with LXML?
7,703,018
10
2011-10-09T10:56:19Z
7,703,144
14
2011-10-09T11:21:42Z
[ "python", "lxml", "xml-namespaces", "cytoscape" ]
I'm using lxml (2.2.8) to create and write out some XML (specifically XGMML). The [app](http://www.cytoscape.org/) which will be reading it is apparently fairly [fussy](http://wiki.cytoscape.org/XGMML) and wants to see a top level element with: ``` <graph label="Test" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:...
Unlike ElementTree or other serializers that would allow this, `lxml` needs you to set up these namespaces beforehand: ``` NSMAP = {"dc" : 'http://purl.org/dc/elements/1.1', "xlink" : 'http://www.w3.org/1999/xlink'} root = Element("graph", nsmap = NSMAP) ``` (and so on and so forth for the rest of the decla...
Bad magic number error with ZipFile module in Python
7,703,639
5
2011-10-09T12:55:33Z
7,705,133
7
2011-10-09T17:14:56Z
[ "python", "unzip", "python-2.7", "zipfile" ]
I am using Python 2.7 on Windows 7 (64 bit). When I try to unzip a zip file with ZipFile module I get the following error:- ``` Traceback (most recent call last): File "unzip.py", line 8, in <module> z.extract(name) File "C:\Python27\lib\zipfile.py", line 950, in extract return self._extract_member(member,...
Correct ZIP files always have "\x50\x4B\x03\x04" in the beginning. You can test whether file is really ZIP file with this code: ``` with open('/path/to/file', 'rb') as MyZip: print(MyZip.read(4)) ``` It will print header of file so you can check. **UPDATE** Strange, testzip() and all other functions work good. Had...
Need to close python socket / Find the current running server on my dev environment
7,703,797
20
2011-10-09T13:23:57Z
7,706,873
71
2011-10-09T22:07:44Z
[ "python", "sockets", "flask" ]
I'm trying to learn python (using the Flask micro-framework) and I am confused because somewhere in my code i'm keeping the server open I believe. I spin up my server with 'python app.py' and then close it however.... it still lives! I'm not sure how this is possible but i must have done something wrong with a connec...
If you use linux you can use **lsof** to find out which process is using a given port, you might have to install it first though, usage is pretty simple: ``` lsof -i :5000 ```
Going from twitter date to Python datetime date
7,703,865
23
2011-10-09T13:37:09Z
7,704,266
9
2011-10-09T14:39:49Z
[ "python", "django", "date", "twitter" ]
I am receiving twitter messages that are sent at a certain date in the following format from twitter: ``` Tue Mar 29 08:11:25 +0000 2011 ``` I want to store these dates in 'timestamp with time zone' field in postgresql with djangos DateTimeField field. When I store that string however I get this error: ``` Validatio...
Give this a go. It assumes the date format from twitter is RFC822 compliant (see the question linked to by @Adrien). A naive datetime object is constructed (i.e. no timezone info). It is adjusted according to the timezone offset to UTC. Unless you have a need to keep the original timezone, I'd store the date time as U...
Going from twitter date to Python datetime date
7,703,865
23
2011-10-09T13:37:09Z
7,711,869
43
2011-10-10T11:04:57Z
[ "python", "django", "date", "twitter" ]
I am receiving twitter messages that are sent at a certain date in the following format from twitter: ``` Tue Mar 29 08:11:25 +0000 2011 ``` I want to store these dates in 'timestamp with time zone' field in postgresql with djangos DateTimeField field. When I store that string however I get this error: ``` Validatio...
Writing something like this should convert a twitter date to a timestamp. ``` ts = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y')) ```
How to install Qt documentation for PyQt demo and Qt tools
7,706,306
9
2011-10-09T20:18:58Z
7,707,340
16
2011-10-09T23:44:11Z
[ "python", "documentation", "qt4", "pyqt", "pyqt4" ]
I installed PyQt on windows 7 with python 2.6 and when trying to execute the demo I got the following warning: ![enter image description here](http://i.stack.imgur.com/uPzNP.png) After some research I could obtain a copy of the Qt4 documentation in .qch format that works with Qt Assistant. How documentation has to b...
The .qch files have to be in the pyqt documentation folder for the demos to work correctly. If you accepted the default paths when you installed python and pyqt, this will probably be `C:\Python27\Lib\site-packages\PyQt4\doc`. Before you move the .qch files, open up Qt Assistant and remove the documentation you added ...
where is the __enter__ and __exit__ defined for zipfile?
7,706,563
3
2011-10-09T21:08:58Z
7,706,586
9
2011-10-09T21:13:09Z
[ "python", "with-statement", "contextmanager" ]
Based on the [with statement](http://docs.python.org/reference/compound_stmts.html) * The context manager’s `__exit__()` is loaded for later use. * The context manager’s `__enter__()` method is invoked. I have seen one of the with usage with [zipfile](http://stackoverflow.com/questions/7533677/how-to-process-zip-...
`zipfile.ZipFile` is not a context manager in 2.6, this has been added in 2.7.
Running a python debug session from a program, not from the console
7,707,822
5
2011-10-10T01:48:03Z
7,708,221
7
2011-10-10T03:16:52Z
[ "python", "debugging" ]
I'm writing a little python IDE, and I want to add simple debugging. I don't need all the features of winpdb. How do I launch a python program (by file name) with a breakpoint set at a line number so that it runs until that line number and halts? Note that I don't want to do this from the command-line, and I don't want...
Pretty much the only viable way to do it (as far as I know) is to run Python as a subprocess from within your IDE. This avoids "pollution" from the current Python interpreter, which makes it fairly likely that the program will run in the same way as if you had started it independently. (If you have issues with this, ch...
Is it ever useful to use Python's input over raw_input?
7,709,022
27
2011-10-10T05:57:31Z
7,710,959
28
2011-10-10T09:42:25Z
[ "python", "user-input", "python-2.x" ]
I currently teach first year university students python, and I was surprised to learn that the seemingly innocuous `input` function, that some of my students had decided to use (and were confused by the odd behaviour), was hiding a call to `eval` behind it. So my question is, why does the `input` function call `eval`,...
Is it ever useful to use Python 2's input over raw\_input? **No.** --- `input()` evaluates the code the user gives it. It puts the full power of Python in the hands of the user. With generator expressions/list comprehensions, [`__import__`](http://docs.python.org/library/functions.html#__import__), and the `if/else`...
Why finally block is executing after calling sys.exit(0) in except block?
7,709,411
22
2011-10-10T06:56:35Z
7,709,453
49
2011-10-10T07:00:39Z
[ "python" ]
I'm new to Python. I just want to know why the `finally` block is executing after calling `sys.exit(0)` in the `except` block? Code: ``` import sys def sumbyzero(): try: 10/0 print "It will never print" except Exception: sys.exit(0) print "Printing after exit" finally: ...
All [`sys.exit()`](http://docs.python.org/library/sys.html#sys.exit) does is raise an exception of type [`SystemExit`](http://docs.python.org/library/exceptions.html#exceptions.SystemExit). From the [documentation](http://docs.python.org/library/sys.html#sys.exit): > Exit from Python. This is implemented by raising t...
Python Functions Confusion
7,711,382
6
2011-10-10T10:21:51Z
7,711,416
12
2011-10-10T10:24:03Z
[ "python" ]
I am learning Python. I have a function **readwrite(filename, list)**. filename is of type string. list is a list containing strings to be wtitten in the file. I have a simple function call like this: ``` fname = 'hello.txt' readwrite('xx'+fname, datalist) ``` I am facing problem that when i print the filename argum...
**Python is case-sensitive**. The two lines below are referring to two different variables (note the capital "N" in the first one): ``` def readwrite(fileName, list): print 'arg file=',filename ``` What's happening is that the second line picks up the global variable called `filename` instead of the function argu...
Copy-paste into Python interactive interpreter and indentation
7,712,389
12
2011-10-10T11:57:59Z
7,712,446
13
2011-10-10T12:02:47Z
[ "python", "indentation", "copy-paste" ]
This piece of code, test.py: ``` if 1: print "foo" print "bar" ``` can be succesfully executed with `execfile("test.py")` or `python test.py`, but when one tries to copy-paste it into python interpreter: ``` File "<stdin>", line 3 print "bar" ^ SyntaxError: invalid syntax ``` Why is it so? Can interprete...
Indentation is probably lost or broken. Have a look at [IPython](http://ipython.org/) -- it's enhanced python interpreter with many convenient features. One of them is a magic function `%paste` that allows you to paste multiple lines of code. It also has tab-completion, auto-indentation.. and many more. Have a look a...
Copy-paste into Python interactive interpreter and indentation
7,712,389
12
2011-10-10T11:57:59Z
7,712,477
15
2011-10-10T12:06:35Z
[ "python", "indentation", "copy-paste" ]
This piece of code, test.py: ``` if 1: print "foo" print "bar" ``` can be succesfully executed with `execfile("test.py")` or `python test.py`, but when one tries to copy-paste it into python interpreter: ``` File "<stdin>", line 3 print "bar" ^ SyntaxError: invalid syntax ``` Why is it so? Can interprete...
I don't know any trick for the standard command prompt, but I can suggest you a more advanced interpreter like [IPython](http://ipython.org/) that has a special syntax for multi-line paste: ``` In [1]: %cpaste Pasting code; enter '--' alone on the line to stop. :for c in range(3): : print c : :-- 0 1 2 ``` Another...
Python: how to avoid code duplication in exception catching?
7,712,651
9
2011-10-10T12:21:07Z
7,712,707
10
2011-10-10T12:25:23Z
[ "python", "exception", "exception-handling" ]
What is a good pattern to avoid code duplication when dealing with different exception types in Python, eg. I want to treat URLError and HTTPError simlar but not quite: ``` try: page = urlopen(request) except URLError, err: logger.error("An error ocurred %s", err) except HTTPError, err: logger.error("An er...
I think that your third example is the best solution. * It's the shortest version * It avoids duplication * It is clear to read and easy to follow, much unlike the second version. You might want to use the newer `except FooError as err` syntax, though, if you're on Python 2.6 or higher. Also, in your example, the fi...
python read binary from specific position
7,713,311
6
2011-10-10T13:15:18Z
7,713,338
7
2011-10-10T13:17:20Z
[ "python", "file", "binary" ]
I have a huge binary file from which I want to read some bytes from exact positions in the file. How can I access specific bytes from binary file not having to loop through all bytes from the beginning of the file? Thanx,
Make sure you open the file with the "b" attribute (for example: `file("myfile.bin", "rb")`). Then use the `seek()` method of the file object. Look here: <http://docs.python.org/release/2.4.4/lib/bltin-file-objects.html>
Check variable if it is in a list
7,713,700
2
2011-10-10T13:44:13Z
7,713,751
9
2011-10-10T13:48:16Z
[ "python" ]
I am fairly new to Python, and I was wondering if there was a succinct way of testing a value to see if it is one of the values in the list, similar to a SQL WHERE clause. Sorry if this is a basic question. ``` MsUpdate.UpdateClassificationTitle in ( 'Critical Updates', 'Feature Packs', 'Securi...
Seems succinct enough, but if you're using it more than once you should name the tuple: ``` titles = ('Critical Updates', 'Feature Packs', 'Security Updates', 'Tools', 'Update Rollups', 'Updates') if MsUpdate.UpdateClassificationTitle in titles: do_something_with_update(MsUpdate) ``` Tuples...
Check variable if it is in a list
7,713,700
2
2011-10-10T13:44:13Z
7,713,776
7
2011-10-10T13:50:05Z
[ "python" ]
I am fairly new to Python, and I was wondering if there was a succinct way of testing a value to see if it is one of the values in the list, similar to a SQL WHERE clause. Sorry if this is a basic question. ``` MsUpdate.UpdateClassificationTitle in ( 'Critical Updates', 'Feature Packs', 'Securi...
It's quite straightforward: ``` sample = ['one', 'two', 'three', 'four'] if 'four' in sample: print True ```
return actual tweets in tweepy?
7,714,282
11
2011-10-10T14:30:28Z
7,714,546
16
2011-10-10T14:47:49Z
[ "python", "twitter", "tweepy" ]
I was writing a twitter program using tweepy. When I run this code, it prints the Python ... values for them, like ``` <tweepy.models.Status object at 0x95ff8cc> ``` Which is not good. How do I get the actual tweet? ``` import tweepy, tweepy.api key = XXXXX sec = XXXXX tok  = XXXXX tsec = XXXXX auth = tweepy.OAut...
In general, you can use the `dir()` builtin in Python to inspect an object. It would seem the Tweepy documentation is very lacking here, but I would imagine the Status objects mirror the structure of Twitter's REST status format, see (for example) <https://dev.twitter.com/docs/api/1/get/statuses/home_timeline> So -- ...
Pad list in Python
7,714,287
5
2011-10-10T14:30:48Z
7,714,330
10
2011-10-10T14:33:57Z
[ "python", "list", "padding" ]
How can I pad a list when printed in python? For example, I have the following list: ``` mylist = ['foo', 'bar'] ``` I want to print this padded to four indices, with commas. I know I can do the following to get it as a comma and space separated list: ``` ', '.join(mylist) ``` But how can I pad it to four indices ...
``` In [1]: l = ['foo', 'bar'] In [2]: ', '.join(l + ['x'] * (4 - len(l))) Out[2]: 'foo, bar, x, x' ``` The `['x'] * (4 - len(l))` produces a list comprising the correct number of `'x'`entries needed for the padding. **edit** There's been a question about what happens if `len(l) > 4`. In this case `['x'] * (4 - len(...
Python multiprocessing: How can I RELIABLY redirect stdout from a child process?
7,714,868
22
2011-10-10T15:10:49Z
11,779,039
7
2012-08-02T14:00:20Z
[ "python", "windows", "stdout", "multiprocessing", "stderr" ]
NB. I have seen [Log output of multiprocessing.Process](http://stackoverflow.com/questions/1501651/log-output-of-multiprocessing-process) - unfortunately, it doesn't answer this question. I am creating a child process (on windows) via multiprocessing. I want *all* of the child process's stdout and stderr output to be ...
The solution you suggest is a good one: create your processes manually such that you have explicit access to their stdout/stderr file handles. You can then create a socket to communicate with the sub-process and use multiprocessing.connection over that socket (multiprocessing.Pipe creates the same type of connection ob...