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 |
|---|---|---|---|---|---|---|---|---|---|
Python global logging | 11,131,734 | 4 | 2012-06-21T04:59:40Z | 11,131,858 | 14 | 2012-06-21T05:14:18Z | [
"python",
"logging"
] | How do I make a Logger global so that I can use it in every module I make?
Something like this in moduleA:
```
import logging
import moduleB
log = logging.getLogger('')
result = moduleB.goFigure(5)
log.info('Answer was', result)
```
With this in moduleB:
```
def goFigure(integer):
if not isinstance(integer, i... | You could make your own logging "module" which instantiates the logger, than have all of your code import that instead. Think:
logger.py:
```
import logging
log = logging.getLogger('')
```
codeA.py:
```
from logger import log
log.info('whatever')
```
codeB.py:
```
from logger import log
log.warn('some other thing... |
Python: Two-way Alphanumeric Encryption | 11,132,714 | 11 | 2012-06-21T06:31:17Z | 11,132,916 | 27 | 2012-06-21T06:47:27Z | [
"python",
"encryption"
] | I am using **Python 2.7**. I have an alphanumeric string, on which I want to perform a encryption/decryption. Whatever I do should remain 2-way and the result should be alphanumeric too.
For example:
```
str = 'ma6546fbd'
encrypted_data = encrypt_function(str)
decrypted_data = decrypt_function(encrypted_data)
print d... | If you want serious encryption (read unbreakable) then I'd use [AES](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard) from [pycrypto](https://www.dlitz.net/software/pycrypto/api/current/) something like this.
```
>>> from Crypto.Cipher import AES
>>> from Crypto import Random
>>> key = b'Sixteen byte key'
>>... |
parsing a complex logical expression in pyparsing in a binary tree fashion | 11,133,339 | 14 | 2012-06-21T07:19:09Z | 11,134,772 | 10 | 2012-06-21T08:59:44Z | [
"python",
"pyparsing"
] | I am trying to parse complex logical expression like the one below;
```
x > 7 AND x < 8 OR x = 4
```
and get the parsed string as a binary tree. For the above expression the expected parsed expression should look like
```
[['x', '>', 7], 'AND', [['x', '<', 8], 'OR', ['x', '=', 4]]]
```
'OR' logical operator has hig... | Try changing:
```
expr = pp.operatorPrecedence(clause,[
("OR", 2, pp.opAssoc.LEFT, ),
("AND", 2, pp.opAssoc.LEFT, ),])
```
to:
```
expr = pp.operatorPrecedence(condition,[
("OR", 2, pp.opAssoc.LEFT, ),
... |
Object Tracking: MATLAB vs. Python Numpy | 11,133,724 | 10 | 2012-06-21T07:47:42Z | 11,138,037 | 7 | 2012-06-21T12:21:42Z | [
"python",
"matlab",
"numpy",
"tracking",
"video-processing"
] | I will soon be starting a final year Engineering project, consisting of the real-time tracking of objects moving on a 2D-surface. The objects will be registered by my algorithm using [feature extraction](http://en.wikipedia.org/wiki/Feature_extraction).
I am trying to do some research to decide whether I should use MA... | I would recommend python.
I switched from MATLAB -> python about 1/2 way through my phd, and do not regret it. At the most simplistic, python is a much nicer language, has real objects, etc.
If you expect to be doing any parts of your code in c/c++ I would definitely recommend python. The mex interface works, but if ... |
Object Tracking: MATLAB vs. Python Numpy | 11,133,724 | 10 | 2012-06-21T07:47:42Z | 11,144,102 | 7 | 2012-06-21T18:04:58Z | [
"python",
"matlab",
"numpy",
"tracking",
"video-processing"
] | I will soon be starting a final year Engineering project, consisting of the real-time tracking of objects moving on a 2D-surface. The objects will be registered by my algorithm using [feature extraction](http://en.wikipedia.org/wiki/Feature_extraction).
I am trying to do some research to decide whether I should use MA... | Python (with NumPy, SciPy and MatPlotLib) is the new Matlab. So I strongly recommend Python over Matlab.
I made the change over a year ago and I am very happy with the results.
Here it is a short pro/con list for Python and Matlab
Python pros:
* Object Oriented
* Easy to write large and "real" programs
* Open Sourc... |
onupdate based on another field with sqlalchemy declarative base | 11,134,539 | 2 | 2012-06-21T08:46:12Z | 11,136,305 | 7 | 2012-06-21T10:36:45Z | [
"python",
"sqlalchemy",
"pyramid"
] | I use sqlalchemy with the pyramid framework, and i want to link a person to his geographical department using his postcode.
So i try to use the onupdate argument when defining the department\_id column define the department\_id.
see fallowing code:
```
from datetime import date
from emailing.models import Base, DBSess... | Move the function definition before its usage:
```
class Person(Base):
# ...
def dep_id_from_postcode(self):
return int(self.postcode[:2])
# ...
department_id = Column(Integer(), ForeignKey('department.id'), onupdate=dep_id_from_postcode)
# ...
```
Is the `postcode` really a field directly... |
Fast python front list extending | 11,134,843 | 5 | 2012-06-21T09:03:24Z | 11,134,901 | 10 | 2012-06-21T09:06:55Z | [
"python",
"performance",
"list",
"profiling",
"concatenation"
] | What is the fastest way to extend the front of an array in python? Lets say I've got 2 arrays:
a and b. I want to make the fastest way of a = b+a (b should not change).
My small benchamarks:
test 1:
```
a,b = [],[]
for i in range(0,100000):
a.append(i)
b.append(i)
def f(a,b):
for i in range(0,100):
... | The absolute fastest way would be to use a [`collections.deque`](http://docs.python.org/library/collections.html#collections.deque) which is optimised for exactly this use, and has methods called `.appendleft` and `.extendleft` to make the code nice and readable - `appendleft` does exactly what it says on the tin (ie, ... |
Pyramid: Routing schemas and restraints | 11,136,437 | 3 | 2012-06-21T10:43:51Z | 11,141,232 | 8 | 2012-06-21T15:12:57Z | [
"python",
"python-2.7",
"pyramid"
] | I have done my research and did some pattern matching trials but I still can not figure out how to:
1. Make part of the route optional. e.g.:
/required **(/optional/{str})**
Here the part in parentheses is optional.
2. Apply restraints to routing so instead of a wildcard string, it has to match an item from a t... | Pyramid does not support optional patterns in a route. The other answer suggests `*optional` but this will match much more than what you asked for which was one optional placeholder, and leaves you with no options at the end of the route for more patterns.
```
config.add_route('name_with_optional', '/required/{optiona... |
Python list reference in a function. | 11,136,746 | 3 | 2012-06-21T11:02:08Z | 11,136,775 | 9 | 2012-06-21T11:03:34Z | [
"python"
] | I'm having trouble understanding the odd behaviour in python functions if i pass in a list.
I made the following functions:
```
def func(x):
y = [4, 5, 6]
x = y
def funcsecond(x):
y = [4, 5, 6]
x[1] = y[1]
x = [1, 2, 3]
```
When i call func(x) and then print out x , it prints out [1, 2, 3], just the... | The former **rebinds** the **name**, the latter **mutates** the **object**. Changes to the name only exist in local scope, whereas a mutated object remains mutated after the scope is exited. |
Fabric : Unable to switch virtualenv with virtualenvwrapper? | 11,136,962 | 3 | 2012-06-21T11:15:21Z | 11,150,734 | 7 | 2012-06-22T05:41:40Z | [
"python",
"django",
"virtualenv",
"fabric",
"virtualenvwrapper"
] | I am using `virtualenvwrapper` to use `virtualenv` for my `django deployement`.
Following is my `fabric` task:
```
proj_path = '/path/to/proj'
def setup_code():
sudo('pip install virtualenvwrapper')
run('export WORKON_HOME=$HOME/.virtualenvs')
run('source /usr/local/bin/virtualenvwrapper.sh && mkvirtualen... | Figured out the problem :
For Fabric :
```
cd('dir') # doesn't works.
```
Following works:
```
with cd('dir'):
print('pwd') # Directory change reflects here.
```
Similarly, other environmental things like :
```
run('export WORKON_HOME=$HOME/.virtualenvs')
run('source /usr/local/bin/virtualenvwrapper.sh && mkv... |
Python: is this a passing parameter convention? | 11,138,717 | 3 | 2012-06-21T12:59:29Z | 11,138,766 | 10 | 2012-06-21T13:02:08Z | [
"python"
] | While I'm going through Python code and seeing functions called, I notice things like
```
functionCall(argument='something')
```
or
```
someclass.functionCall(argument='something')
```
I've played around with it and noticed you have to name that variable with the same name as the one in the scope of the function or... | Those are just standard [**keyword arguments**](http://docs.python.org/tutorial/controlflow.html#keyword-arguments).
They are mainly useful when calling functions that usually assume default values, but the user is interested in passing a custom value without affecting the other defaults.
For example:
```
def foo(a='... |
how to sort a dictionary using values and also be able to access keys | 11,139,038 | 2 | 2012-06-21T13:16:24Z | 11,139,068 | 7 | 2012-06-21T13:18:13Z | [
"python",
"python-3.x",
"dictionary"
] | ```
dic = {'Tea': 35, 'Coffee': 35, 'Chocolate': 10}
```
I want to sort this dictionary by values in descending order, but how can I access keys too?
Sample Code:
```
for x in sorted(dic.values()):
print(key, dic[key])
```
I'd also like the output to be sorted alphabetically by key when the values are equal.
E... | One option:
```
for key in sorted(dic, key=dic.get, reverse=True):
print(key,dic[key])
```
This sorts the keys of the dictionary, but uses `dic.get` as key function, thereby effectively sorting by value. Your example output indicates you want to sort in descending order, so I included `reverse=True`.
**Edit**: I... |
how to sort a dictionary using values and also be able to access keys | 11,139,038 | 2 | 2012-06-21T13:16:24Z | 11,139,075 | 9 | 2012-06-21T13:18:40Z | [
"python",
"python-3.x",
"dictionary"
] | ```
dic = {'Tea': 35, 'Coffee': 35, 'Chocolate': 10}
```
I want to sort this dictionary by values in descending order, but how can I access keys too?
Sample Code:
```
for x in sorted(dic.values()):
print(key, dic[key])
```
I'd also like the output to be sorted alphabetically by key when the values are equal.
E... | What you want is [the `dict.items()` method](http://docs.python.org/py3k/library/stdtypes.html?highlight=dict#dict.items), which provides `(key, value)` tuples.
To sort by the value, you then use a `key` method, in this case, an [`operator.itemgetter()`](http://docs.python.org/library/operator.html#operator.itemgetter... |
Python Join a list of integers | 11,139,330 | 11 | 2012-06-21T13:32:17Z | 11,139,365 | 8 | 2012-06-21T13:34:32Z | [
"python"
] | I am trying to get list of numbers from:
```
numbers= 1,2
```
to:
```
'1','2'
```
I tried `",".join(str(n) for n in numbers)` but it wont give the targeted format. | Use this:
```
>>> numbers = [1, 2]
>>> ",".join(repr(str(n)) for n in numbers)
'1','2'
``` |
Python Join a list of integers | 11,139,330 | 11 | 2012-06-21T13:32:17Z | 11,139,368 | 24 | 2012-06-21T13:34:34Z | [
"python"
] | I am trying to get list of numbers from:
```
numbers= 1,2
```
to:
```
'1','2'
```
I tried `",".join(str(n) for n in numbers)` but it wont give the targeted format. | How about that?
```
>>> numbers=1,2
>>> numbers
(1, 2)
>>> map(str, numbers)
['1', '2']
>>> ",".join(map(str, numbers))
'1,2'
``` |
Python Join a list of integers | 11,139,330 | 11 | 2012-06-21T13:32:17Z | 11,139,371 | 19 | 2012-06-21T13:34:40Z | [
"python"
] | I am trying to get list of numbers from:
```
numbers= 1,2
```
to:
```
'1','2'
```
I tried `",".join(str(n) for n in numbers)` but it wont give the targeted format. | ```
>>> numbers = 1,2
>>> print ",".join("'{0}'".format(n) for n in numbers)
'1','2'
``` |
How to convert unicoded dict into a string | 11,139,751 | 2 | 2012-06-21T13:54:18Z | 11,139,781 | 7 | 2012-06-21T13:56:06Z | [
"python",
"type-conversion"
] | My issue is as follows. We have dict that has all keys and values as unicode, example:
```
ab = {
u'a': u'A',
u'b': u'B',
u'c': u'C',
}
```
I want to convert it into a string. Obviously when I do:
```
str(ab)
```
I will receive:
```
"{u'a': u'A', u'c': u'C', u'b': u'B'}"
```
If I do:
```
unicode(ab)
... | No, you will need to convert each item to a string manually, then string the dict, and note that unless the Unicode data happens to all be ASCII, you could run into problems. Making that assumption, you can use a dict comprehension to make it quicker and more concise:
```
print({str(key): str(value) for key, value in ... |
Python/matplotlib : plotting a 3d cube, a sphere and a vector? | 11,140,163 | 40 | 2012-06-21T14:15:43Z | 11,156,353 | 100 | 2012-06-22T12:39:26Z | [
"python",
"matplotlib",
"3d",
"geometry"
] | I search how to plot something with less instruction as possible with matplotlib but I don't find any help for this in the documentation.
I want to plot the following things :
- a wireframe cube centered in 0 with a side length of 2
- a "wireframe" sphere centered in 0 with a radius of 1
- a point at coordinates [0, 0... | It is a little complicated, but you can draw all the objects by the following code:
```
# -*- coding: utf-8 -*-
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
... |
matplotlib - Legend in separate subplot | 11,140,311 | 8 | 2012-06-21T14:22:46Z | 11,153,040 | 14 | 2012-06-22T08:54:26Z | [
"python",
"matplotlib",
"legend"
] | I am plotting an array of pie charts, each using the same two colors for the same two types of data.
```
plt.figure(num=None, figsize=(6, 8))
for i in range(len(data_1)):
plt.subplot(sp_rows, sp_cols, i+1)
fracs = [data_1[i], data_2[i]]
plt.pie(fracs, autopct='%1.1f%%')
pp.savefig()
```
Obviously it does... | You can call legend() only once:
```
import numpy as np
import pylab as pl
for i in xrange(1, 5):
pl.subplot(220+i)
pl.pie([i,2], labels=["a","b"], autopct='%1.1f%%')
l = pl.legend(title="sample")
pl.show()
```

or if you want the legend in... |
Closing pyplot windows | 11,140,787 | 16 | 2012-06-21T14:51:02Z | 11,141,305 | 28 | 2012-06-21T15:16:37Z | [
"python",
"tkinter",
"matplotlib"
] | Final Edit:
What I found on the subject of closing pyplot windows is that it really probably shouldn't be done using pyplot. SRK gives a great example on how to handle plots that will be updated in his answer below. Also I have stumbled across how to put pyplot plots into a Tkinter window, and Tkinter is much more ade... | `plt.close()` will close current instance.
`plt.close(2)` will close figure 2
`plt.close(plot1)` will close figure with instance plot1
`plt.close('all')` will close all fiures
Found [here](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.close).
Remember that `plt.show()` is a *blocking* fun... |
Unique elements in each file | 11,140,947 | 2 | 2012-06-21T14:58:54Z | 11,140,982 | 10 | 2012-06-21T15:00:28Z | [
"python",
"perl",
"bash",
"shell"
] | I have 4 files and would like to know elements which are non overlapping (per file) compared to the elements in other files.
File A
```
Vincy
ruby
rome
```
File B
```
Vincy
rome
Peter
```
File C
```
Vincy
Paul
alex
```
File D
```
Vincy
rocky
Willy
```
Any suggestion for one liner in perl, python, shell, bash. ... | Edit after question clarified: Unique elements across all files, and the file in which it occurs:
```
cat File_A File_B File_C File_D |sort | uniq -u | while read line ; do file=`grep -l $line File*` ; echo "$file $line" ; done
```
Edit:
perly way of doing it, will be faster if the files are large:
```
#!/usr/bin/p... |
FileStorage for OpenCV Python API | 11,141,336 | 15 | 2012-06-21T15:18:00Z | 15,942,429 | 20 | 2013-04-11T06:52:34Z | [
"c++",
"python",
"image-processing",
"opencv"
] | I'm currently using **FileStorage** class for storing matrices **XML/YAML** using OpenCV **C++** API.
However, I have to write a Python Script that reads those **XML/YAML** files.
I'm looking for existing OpenCV **Python API** that can read the **XML/YAML** files generated by **OpenCV C++ API** | You can use [PyYAML](http://pyyaml.org/) to parse the YAML file.
Since PyYAML doesn't understand OpenCV data types, you need to specify a constructor for each OpenCV data type that you are trying to load. For example:
```
import yaml
def opencv_matrix(loader, node):
mapping = loader.construct_mapping(node, deep=T... |
Is there a way to preserve duplicate keys in python dictionary | 11,141,383 | 3 | 2012-06-21T15:20:12Z | 11,141,463 | 7 | 2012-06-21T15:24:14Z | [
"python"
] | is there any way to store duplicate keys in a dictionary?
I have a specific requirement to form pairs of requests and responses.
Requests from a particular node to another particular node form same keys. I need to store both those.
But if I tried to add them to dictionary, first one is being replaced by second. Is t... | While I'm not 100% sure, I'm pretty sure the answer is no. That sort of violates the purpose of a dictionary in python. How about you change the value to lists so instead of
```
{Key:value}
```
you have
```
{Key:[Value1,value2]}
``` |
Is there a way to preserve duplicate keys in python dictionary | 11,141,383 | 3 | 2012-06-21T15:20:12Z | 11,141,570 | 7 | 2012-06-21T15:29:55Z | [
"python"
] | is there any way to store duplicate keys in a dictionary?
I have a specific requirement to form pairs of requests and responses.
Requests from a particular node to another particular node form same keys. I need to store both those.
But if I tried to add them to dictionary, first one is being replaced by second. Is t... | I can think of two simple options, assuming you want to keep using a dictionary.
1. You could map keys to lists of items. A `defaultdict` from the `collections` module makes this easy.
```
>>> import collections
>>> data = collections.defaultdict(list)
>>> for k, v in (('a', 'b'), ('a', 'c'), ('b', 'c')):... |
Does Python have an immutable list? | 11,142,397 | 34 | 2012-06-21T16:15:54Z | 11,142,398 | 44 | 2012-06-21T16:15:55Z | [
"python"
] | Does python have immutable lists?
Suppose I wish to have the functionality of an ordered collection of elements, but which I want to guarantee will not change, how can this be implemented? Lists are ordered but they can be mutated. | Yes. It's called a `tuple`.
So, instead of `[1,2]` which is a `list` and which can be mutated, `(1,2)` is a `tuple` and cannot.
---
*Further Information:*
A one-element `tuple` cannot be instantiated by writing `(1)`, instead, you need to write `(1,)`. This is because the interpreter has various other uses for pare... |
Adding borders to an image using python | 11,142,851 | 9 | 2012-06-21T16:43:09Z | 11,142,952 | 15 | 2012-06-21T16:50:19Z | [
"python",
"image",
"image-processing"
] | I have a large number of images of a fixed size (say 500\*500). I want to write a python script which will resize them to a fixed size (say 800\*800) but will keep the original image at the center and fill the excess area with a fixed color (say black).
I am using PIL. I can resize the image using the `resize` functio... | Yes, there is.
Make something like this:
```
import Image, ImageOps
ImageOps.expand(Image.open('original-image.png'),border=300,fill='black').save('imaged-with-border.png')
```
You can write the same at several lines:
```
import Image, ImageOps
img = Image.open('original-image.png')
img_with_border = ImageOps.expan... |
Adding borders to an image using python | 11,142,851 | 9 | 2012-06-21T16:43:09Z | 11,143,078 | 18 | 2012-06-21T16:58:05Z | [
"python",
"image",
"image-processing"
] | I have a large number of images of a fixed size (say 500\*500). I want to write a python script which will resize them to a fixed size (say 800\*800) but will keep the original image at the center and fill the excess area with a fixed color (say black).
I am using PIL. I can resize the image using the `resize` functio... | You can create a new image with the desired new size, and paste the old image in the center, then saving it. If you want, you can overwrite the original image (are you sure? ;o)
```
import Image
old_im = Image.open('someimage.jpg')
old_size = old_im.size
new_size = (800, 800)
new_im = Image.new("RGB", new_size) ##... |
parsing C code using python | 11,143,095 | 12 | 2012-06-21T16:59:14Z | 11,143,209 | 16 | 2012-06-21T17:07:19Z | [
"python",
"c",
"parsing",
"structure"
] | I have a huge C file (~100k lines) which I need to be able to parse. Mainly I need to be able to get details about individual fields of every structure (like field name and type for every field in the structure) from its definition. Is there a good(open source, which i can use in my code) way to do this already? Or sho... | Take a look at [this link](http://wiki.python.org/moin/LanguageParsing) for an extensive list of parsing tools available for Python. Specifically, for parsing c code, try the [pycparser](https://github.com/eliben/pycparser) |
Find all upper, lower and mixed case combinations of a string | 11,144,389 | 11 | 2012-06-21T18:22:30Z | 11,144,539 | 17 | 2012-06-21T18:32:20Z | [
"python",
"string"
] | I want to write a program that would take a string, let's say `"Fox"`, then it would display:
```
fox, Fox, fOx, foX, FOx, FoX, fOX, FOX
```
My code so far:
```
string = raw_input("Enter String: ")
length = len(string)
for i in range(0, length):
for j in range(0, length):
if i == j:
x = strin... | ```
>>> import itertools
>>> map(''.join, itertools.product(*((c.upper(), c.lower()) for c in 'Fox')))
['FOX', 'FOx', 'FoX', 'Fox', 'fOX', 'fOx', 'foX', 'fox']
```
Or
```
>>> s = 'Fox'
>>> map(''.join, itertools.product(*zip(s.upper(), s.lower())))
``` |
Numpy: cartesian product of x and y array points into single array of 2D points | 11,144,513 | 28 | 2012-06-21T18:30:19Z | 11,144,716 | 21 | 2012-06-21T18:43:01Z | [
"python",
"numpy",
"cartesian-product"
] | I have two numpy arrays that define the x and y axes of a grid. For example:
```
x = numpy.array([1,2,3])
y = numpy.array([4,5])
```
I'd like to generate the Cartesian product of these arrays to generate:
```
array([[1,4],[2,4],[3,4],[1,5],[2,5],[3,5]])
```
In a way that's not terribly inefficient since I need to d... | ```
>>> numpy.transpose([numpy.tile(x, len(y)), numpy.repeat(y, len(x))])
array([[1, 4],
[2, 4],
[3, 4],
[1, 5],
[2, 5],
[3, 5]])
```
See [Using numpy to build an array of all combinations of two arrays](http://stackoverflow.com/questions/1208118/using-numpy-to-build-an-array-of-all-... |
Numpy: cartesian product of x and y array points into single array of 2D points | 11,144,513 | 28 | 2012-06-21T18:30:19Z | 11,146,645 | 39 | 2012-06-21T20:58:40Z | [
"python",
"numpy",
"cartesian-product"
] | I have two numpy arrays that define the x and y axes of a grid. For example:
```
x = numpy.array([1,2,3])
y = numpy.array([4,5])
```
I'd like to generate the Cartesian product of these arrays to generate:
```
array([[1,4],[2,4],[3,4],[1,5],[2,5],[3,5]])
```
In a way that's not terribly inefficient since I need to d... | Another approach that tests a bit faster for me is to use `meshgrid` + `dstack`:
```
>>> numpy.dstack(numpy.meshgrid(x, y)).reshape(-1, 2)
array([[1, 4],
[2, 4],
[3, 4],
[1, 5],
[2, 5],
[3, 5]])
```
I did a few tests; see the end of this post for a very simple, general solution that... |
Numpy: cartesian product of x and y array points into single array of 2D points | 11,144,513 | 28 | 2012-06-21T18:30:19Z | 19,459,709 | 9 | 2013-10-18T22:00:34Z | [
"python",
"numpy",
"cartesian-product"
] | I have two numpy arrays that define the x and y axes of a grid. For example:
```
x = numpy.array([1,2,3])
y = numpy.array([4,5])
```
I'd like to generate the Cartesian product of these arrays to generate:
```
array([[1,4],[2,4],[3,4],[1,5],[2,5],[3,5]])
```
In a way that's not terribly inefficient since I need to d... | You can just do normal list comprehension in python
```
x = numpy.array([1,2,3])
y = numpy.array([4,5])
[[x0, y0] for x0 in x for y0 in y]
```
which should give you
```
[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
``` |
Unit and functional testing a PySide-based application? | 11,145,583 | 15 | 2012-06-21T19:41:54Z | 12,026,440 | 28 | 2012-08-19T12:22:39Z | [
"python",
"unit-testing",
"qt4",
"pyside"
] | I'm building a PySide 1.1.0-based application, and have been looking for good examples to look at for unit and functional testing my application. I want to be able to do functional testing of the UI (simulating clicks, key presses, etc), unit testing of UI slots that alter the layout of the UI (presumably using a parti... | I've been playing around a bit now with unit-testing pyside code and came to the conclusion that combining python's `unittest` module with qt's `QTest` module works pretty good.
You will have to have a `QApplication` object instantiated, but you do not need to run its `exec_` method, because you don't need the event l... |
Python TypeError: not enough arguments for format string | 11,146,190 | 60 | 2012-06-21T20:25:24Z | 11,146,220 | 127 | 2012-06-21T20:27:31Z | [
"python",
"string",
"format",
"typeerror"
] | Here's the output. These are utf-8 strings I believe... some of these can be NoneType but it fails immediately, before ones like that...
```
instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname, procversion, int(percent), exe, description, company, procurl
```
TypeError: not enough arguments for format strin... | You need to put the format arguments into a tuple (add parentheses):
```
instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)
```
What you currently have is equivalent to the following:
```
intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" ... |
Python TypeError: not enough arguments for format string | 11,146,190 | 60 | 2012-06-21T20:25:24Z | 11,146,329 | 78 | 2012-06-21T20:36:18Z | [
"python",
"string",
"format",
"typeerror"
] | Here's the output. These are utf-8 strings I believe... some of these can be NoneType but it fails immediately, before ones like that...
```
instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname, procversion, int(percent), exe, description, company, procurl
```
TypeError: not enough arguments for format strin... | Note that the `%` syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:
```
instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)
```
This also fixes the error that you happened t... |
Handling extra newlines (carriage returns) in csv files parsed with Python? | 11,146,564 | 9 | 2012-06-21T20:53:15Z | 11,149,410 | 15 | 2012-06-22T02:18:31Z | [
"python",
"csv",
"newline"
] | I have a CSV file that has fields that contain newlines e.g.:
```
A, B, C, D, E, F
123, 456, tree
, very, bla, indigo
```
(In this case third field in the second row is "tree\n"
I tried the following:
```
import csv
catalog = csv.reader(open('test.csv', 'rU'), delimiter=",", dialect=csv.excel_tab)
for row in catalo... | Suppose you have this Excel spreadsheet:

Note:
1. the multi-line cell in C2;
2. embedded comma in C1 and D3;
3. blank cells, and cell with a space in D4.
Saving that as CSV in Excel, you will get this csv file:
```
A1,B1,"C1,+comma",D1
,B2,"... |
Suppress "None" output as string in Jinja2 | 11,146,619 | 34 | 2012-06-21T20:57:08Z | 11,146,693 | 29 | 2012-06-21T21:01:48Z | [
"python",
"jinja2"
] | How do I persuade Jinja2 to not print `"None"` when the value is `None`?
I have a number of entries in a dictionary and I would like to output everything in a single loop instead of having special cases for different keywords. If I have a value of `None` (the `NoneType` not the string) then the string `"None"` is inse... | `{{ value if value is not None }}` works great.
if this raises an error about not having an else try using an else ..
`{{ value if value is not None else '' }}` |
Suppress "None" output as string in Jinja2 | 11,146,619 | 34 | 2012-06-21T20:57:08Z | 11,147,125 | 13 | 2012-06-21T21:35:38Z | [
"python",
"jinja2"
] | How do I persuade Jinja2 to not print `"None"` when the value is `None`?
I have a number of entries in a dictionary and I would like to output everything in a single loop instead of having special cases for different keywords. If I have a value of `None` (the `NoneType` not the string) then the string `"None"` is inse... | [Default filter](http://jinja.pocoo.org/docs/templates/#default):
```
{{ value|default("", True) }}
``` |
Suppress "None" output as string in Jinja2 | 11,146,619 | 34 | 2012-06-21T20:57:08Z | 17,661,969 | 19 | 2013-07-15T19:10:07Z | [
"python",
"jinja2"
] | How do I persuade Jinja2 to not print `"None"` when the value is `None`?
I have a number of entries in a dictionary and I would like to output everything in a single loop instead of having special cases for different keywords. If I have a value of `None` (the `NoneType` not the string) then the string `"None"` is inse... | Another option is to use the `finalize` hook on the environment:
```
>>> import jinja2
>>> e = jinja2.Environment()
>>> e.from_string("{{ this }} / {{ that }}").render(this=0, that=None)
u'0 / None'
```
but:
```
>>> def my_finalize(thing):
... return thing if thing is not None else ''
...
>>> e = jinja2.Environm... |
Suppress "None" output as string in Jinja2 | 11,146,619 | 34 | 2012-06-21T20:57:08Z | 22,729,383 | 9 | 2014-03-29T09:39:29Z | [
"python",
"jinja2"
] | How do I persuade Jinja2 to not print `"None"` when the value is `None`?
I have a number of entries in a dictionary and I would like to output everything in a single loop instead of having special cases for different keywords. If I have a value of `None` (the `NoneType` not the string) then the string `"None"` is inse... | A custom filter can solve the problem. Declare it like this:
```
def filter_supress_none(val):
if not val is None:
return val
else:
return ''
```
Install it like this:
```
templating_environment.filters['sn'] = filter_supress_none
```
Use it like this:
```
{{value|sn}}
``` |
Suppress "None" output as string in Jinja2 | 11,146,619 | 34 | 2012-06-21T20:57:08Z | 26,536,945 | 7 | 2014-10-23T20:35:02Z | [
"python",
"jinja2"
] | How do I persuade Jinja2 to not print `"None"` when the value is `None`?
I have a number of entries in a dictionary and I would like to output everything in a single loop instead of having special cases for different keywords. If I have a value of `None` (the `NoneType` not the string) then the string `"None"` is inse... | According to this post from the Pocco Mailing List: <https://groups.google.com/d/msg/pocoo-libs/SQ9ubo_Kamw/TadIdab9eN8J>
Armin Ronacher (creater of Jinja2/Flask, etc...) recommends the following "pythonic" snippet:
`{{ variable or 0 }}` `{{ variable or '' }}`
The notion here being that once again, explicit is prefe... |
isinstance and Mocking | 11,146,725 | 9 | 2012-06-21T21:03:42Z | 26,567,750 | 14 | 2014-10-25T22:08:20Z | [
"python",
"unit-testing",
"mocking"
] | ```
class HelloWorld(object):
def say_it(self):
return 'Hello I am Hello World'
def i_call_hello_world(hw_obj):
print 'here... check type: %s' %type(HelloWorld)
if isinstance(hw_obj, HelloWorld):
print hw_obj.say_it()
from mock import patch, MagicMock
import unittest
class TestInstance(un... | IMHO that is a good question and say *don't use `isinstance`, use duck typing instead* is a bad answer. Duck typing is great but not a silver bullet and sometime `isinstance` is necessary even if it is not pythonic. For instance if you work with some library or legacy code that isn't pythonic you must play with `isinst... |
Is there a way to list pip dependencies/requirements? | 11,147,667 | 28 | 2012-06-21T22:23:09Z | 11,148,336 | 17 | 2012-06-21T23:36:53Z | [
"python",
"pip"
] | Without going through with the installation, I want to quickly see all the packages that `pip install` would install. | The closest you can get with pip directly is by using the `--no-install` argument:
```
pip install --no-install <package>
```
For example, this is the output when installing celery:
```
Downloading/unpacking celery
Downloading celer... |
Two assignments in single python list comprehension | 11,147,890 | 7 | 2012-06-21T22:42:59Z | 11,147,898 | 12 | 2012-06-21T22:43:53Z | [
"python",
"list-comprehension"
] | For example:
```
a = [1,2,3]
x = [2*i for i in a]
y = [3*i for i in a]
```
Would it be more efficient to combine the list comprehensions into one (if possible) if the size of a is large? If so, how do you do this?
Something like,
```
x,y = [2*i, 3*i for i in a]
```
which doesn't work. If using list comprehension i... | You want to use [the `zip()` builtin](http://docs.python.org/library/functions.html#zip) with the star operator to do this. `zip()` normally turns to lists into a list of pairs, when used like this, it unzips - taking a list of pairs and splitting into two lists.
```
>>> a = [1, 2, 3]
>>> x, y = zip(*[(2*i, 3*i) for i... |
Two assignments in single python list comprehension | 11,147,890 | 7 | 2012-06-21T22:42:59Z | 11,148,190 | 7 | 2012-06-21T23:18:47Z | [
"python",
"list-comprehension"
] | For example:
```
a = [1,2,3]
x = [2*i for i in a]
y = [3*i for i in a]
```
Would it be more efficient to combine the list comprehensions into one (if possible) if the size of a is large? If so, how do you do this?
Something like,
```
x,y = [2*i, 3*i for i in a]
```
which doesn't work. If using list comprehension i... | When in doubt about efficiency use the timeit module, it's always easy to use:
```
import timeit
def f1(aRange):
x = [2*i for i in aRange]
y = [3*i for i in aRange]
return x,y
def f2(aRange):
x, y = zip(*[(2*i, 3*i) for i in aRange])
return x,y
def f3(aRange):
x, y = zip(*((2*i, 3*i) for i i... |
homebrew macvim with python2.7.3 support not working | 11,148,403 | 4 | 2012-06-21T23:45:24Z | 12,697,440 | 23 | 2012-10-02T20:04:23Z | [
"python",
"vim",
"macvim",
"homebrew"
] | I installed macvim with homebrew, with python support. My incantation was as follow:
```
brew install macvim --override-system-vim
```
Now when I open a python file, I get a series of errors if I try to import anything. e.g. if I `import re` I see `ImportError: no module name re`.
The first time I open macvim after ... | I got this working with a quick hack where you temporarily point the system python to your preferred python:
```
cd /System/Library/Frameworks/Python.framework/Versions
sudo mv Current Current-sys
sudo mv 2.7 2.7-sys
sudo ln -s /usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7 Current
sudo ln -s ... |
Is there a way to automatically get general info of many stocks like P/E ratio, Yield, and so on? | 11,148,641 | 6 | 2012-06-22T00:16:20Z | 11,148,696 | 9 | 2012-06-22T00:23:00Z | [
"python",
"stocks"
] | I know some ways to get daily stock prices and volumes in R or python, but just wondering whether these is a way (using either R or python) to get more info about stocks such as P/E ratio, company website, Yield and so on, preferably not just current value, but also historical values.
Thanks. | Historical is going to be difficult. The [quantmod](http://cran.r-project.org/web/packages/quantmod/index.html) package for R has `getQuote` which together with `yahooQF` will be all you need to get current values.
```
require("quantmod")
getQuote("GS", what = yahooQF(c("Market Capitalization", "Earnings/Share",
... |
Django Build URLs from template with integer param, the primary key | 11,149,288 | 2 | 2012-06-22T01:52:45Z | 11,149,295 | 11 | 2012-06-22T01:54:42Z | [
"python",
"django"
] | I have this link in a template:
```
<a href="{% url show_item item.id %}">Item 1</a>
```
and this url in the urls.py
```
url(r'item/(?P<id>)/$', show_item, name="page_item")
```
however, this error occurs:
```
Reverse for 'show_item' with arguments '(63L,)' and keyword arguments '{}' not found.
```
I looked at th... | The URL name doesn't match. Change the template to be:
```
<a href="{% url page_item item.id %}">Item 1</a>
``` |
Why can't I repeat the 'for' loop for csv.Reader? (Python) | 11,150,155 | 9 | 2012-06-22T04:24:23Z | 11,150,187 | 22 | 2012-06-22T04:27:51Z | [
"python",
"csv"
] | I am a beginner of Python. I am trying now figuring out why the second 'for' loop doesn't work in the following script. I mean that I could only get the result of the first 'for' loop, but nothing from the second one. I copied and pasted my script and the data csv in the below.
It will be helpful if you tell me why it... | The csv reader is an iterator over the file. Once you go through it once, you read to the end of the file, so there is no more to read. If you need to go through it again, you can seek to the beginning of the file:
```
fh.seek(0)
```
This will reset the file to the beginning so you can read it again.
If the file isn... |
Slow Requests on Local Flask Server | 11,150,343 | 42 | 2012-06-22T04:48:28Z | 11,150,849 | 51 | 2012-06-22T05:56:06Z | [
"python",
"flask"
] | Just starting to play around with Flask on a local server and I'm noticing the request/response times are way slower than I feel they should be.
Just a simple server like the following takes close to 5 seconds to respond.
```
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "ind... | Ok I figured it out. It appears to be an issue with Werkzeug and os's that support ipv6.
From the Werkzeug site <http://werkzeug.pocoo.org/docs/serving/>:
> On operating systems that support ipv6 and have it configured such as modern Linux systems, OS X 10.4 or higher as well as Windows Vista some browsers can be pai... |
Slow Requests on Local Flask Server | 11,150,343 | 42 | 2012-06-22T04:48:28Z | 28,776,624 | 26 | 2015-02-28T00:30:14Z | [
"python",
"flask"
] | Just starting to play around with Flask on a local server and I'm noticing the request/response times are way slower than I feel they should be.
Just a simple server like the following takes close to 5 seconds to respond.
```
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "ind... | Add "threaded=True" as an argument to app.run(), as suggested here:
<http://arusahni.net/blog/2013/10/flask-multithreading.html>
For example: `app.run(host="0.0.0.0", port=8080, threaded=True)`
The ipv6-disabling solution did not work for me, but this did. |
python string concatenation confusion | 11,152,333 | 8 | 2012-06-22T08:02:27Z | 11,152,368 | 9 | 2012-06-22T08:05:19Z | [
"python"
] | I recently came across the following piece of code. It doesn't look valid because of the single instance of triple quotes but seems to work fine. Can anyone explain what's going on here?
```
return ("Validation failed(%s): cannot calculate length "
"of %s.""" % (self.name, value))`
``` | All of the strings are concatenated first.
`""` is an empty string.
The substitutions are then made. |
What are the rules regarding chaining of "==" and "!=" in Python | 11,153,817 | 15 | 2012-06-22T09:43:28Z | 11,153,879 | 12 | 2012-06-22T09:47:18Z | [
"python"
] | This morning, I find myself writing something like:
```
if (a == b == c):
# do something
```
And was surprised that it gave me the expected result.
I thought it would behave as:
```
if ((a == b) == c):
# do something
```
But it obviously didn't. It seems Python is treating the first statement differently from ... | As far as I know the example you point out isn't chaining.
`2 == 2 == 2` is like `(2 == 2) and ( 2 == 2)` which turns out to be `True and True`
while
`(2 == 2) == 2` is like `(True) == 2` |
What are the rules regarding chaining of "==" and "!=" in Python | 11,153,817 | 15 | 2012-06-22T09:43:28Z | 11,153,891 | 24 | 2012-06-22T09:48:03Z | [
"python"
] | This morning, I find myself writing something like:
```
if (a == b == c):
# do something
```
And was surprised that it gave me the expected result.
I thought it would behave as:
```
if ((a == b) == c):
# do something
```
But it obviously didn't. It seems Python is treating the first statement differently from ... | This works with all comparison operators - eg, you can also do:
```
>>> 4 < 5 < 6
True
>>> 4 < 5 !=2
True
```
In general, [according to the documentation](http://docs.python.org/reference/expressions.html#not-in), `a op1 b op2 c` where `op1` and `op2` are any of: `<`, `>`, `!=`, `==`, `<=`, `>=`, `is` , `is not`, `in... |
Call Nested Function in Python | 11,154,634 | 8 | 2012-06-22T10:41:00Z | 11,154,682 | 18 | 2012-06-22T10:44:23Z | [
"python",
"nested"
] | I have a method that i have broken into smaller nested functions to break up the code base:
```
def foo(x,y):
def do_this(x,y):
pass
def do_that(x,y):
pass
do_this(x,y)
do_that(x,y)
return
```
Is there a way to run one of the nested functions by itself. eg:
```
foo.do_this(x,y)
``... | I assume `do_this` and `do_that` are actually dependent on some argument of `foo`, since otherwise you could just move them out of `foo` and call them directly.
I suggest reworking the whole thing as a class. Something like this:
```
class Foo(object):
def __init__(self, x, y):
self.x = x
self.y =... |
argparse: require either of two arguments | 11,154,946 | 66 | 2012-06-22T11:02:04Z | 11,155,124 | 94 | 2012-06-22T11:14:52Z | [
"python",
"argparse"
] | Given:
```
import argparse
pa = argparse.ArgumentParser()
pa.add_argument('--foo')
pa.add_argument('--bar')
print pa.parse_args('--foo 1'.split())
```
how do I
* make at least one of "foo, bar" mandatory: `--foo x`, `--bar y` and `--foo x --bar y` are fine
* make at most one of "foo, bar" mandatory: `--foo x` or `... | I think you are searching for something like [mutual exclusion](http://docs.python.org/library/argparse.html#mutual-exclusion) (at least for the second part of your question).
This way, only foo or bar will be accepted, not both.
```
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument... |
argparse: require either of two arguments | 11,154,946 | 66 | 2012-06-22T11:02:04Z | 11,155,237 | 9 | 2012-06-22T11:22:16Z | [
"python",
"argparse"
] | Given:
```
import argparse
pa = argparse.ArgumentParser()
pa.add_argument('--foo')
pa.add_argument('--bar')
print pa.parse_args('--foo 1'.split())
```
how do I
* make at least one of "foo, bar" mandatory: `--foo x`, `--bar y` and `--foo x --bar y` are fine
* make at most one of "foo, bar" mandatory: `--foo x` or `... | If you need some check that is not provided by the module you can always do it manually:
```
pa = argparse.ArgumentParser()
...
args = pa.parse_args()
if args.foo is None and args.bar is None:
pa.error("at least one of --foo and --bar required")
``` |
finding the derivative of a polynomial | 11,155,367 | 7 | 2012-06-22T11:31:39Z | 11,155,973 | 13 | 2012-06-22T12:16:04Z | [
"python",
"math"
] | I wondering symbolically how you would parse a polynomial into a function and return the derivative. What data structure would I use or method to parse the polynomial? Preferably without using any libraries, as this question could pop up in a technical interview.
```
polynomial-> of nth degree
def derivative(polynomi... | A polynomial in a single variable can be represented simply as an array containing the coefficients. So for example 1 + 5x3 - 29x5 can be expressed as `[1, 0, 0, 5, 0, -29]`. Expressed in this form the derivative is easy to compute.
suppose `poly` is a python list as above. Then
```
deriv_poly = [poly[i] * i for i in... |
Chameleon templates for javascript files? | 11,155,947 | 5 | 2012-06-22T12:14:24Z | 11,156,400 | 9 | 2012-06-22T12:42:46Z | [
"javascript",
"python",
"pyramid",
"chameleon"
] | I am developing a simple pyramid application where I am using JQuery to do AJAX requests. I have until now had my javascript code within my chameleon templates. Now I want to extract my javascript into another location (e.g. as static resources).
My problem is that I find my javascript code relies on dynamically gener... | Yes; you generally put context-specific information like expanded routes into the templates and access this information from your (static) JavaScript libraries.
Including the context info can be done in various ways, depending on taste:
1. You could use a data attribute on a tag in your generated HTML:
```
<bo... |
Divide a dictionary into variables | 11,156,739 | 8 | 2012-06-22T13:04:45Z | 11,157,531 | 8 | 2012-06-22T13:51:37Z | [
"python",
"python-2.7"
] | I am studying Python and currently going through some more learning with dictionaries.
I was wondering;
If I have a dictionary like: `d = {'key_1': 'value_a', 'key_2': 'value_b'}` and I want separate/divide this dictionary into variables where each variable is a key from the dictionary and each variables value is the... | A solution which has not been mentionned before would be
```
dictget = lambda d, *k: [d[i] for i in k]
```
and then use it:
```
key_1, key_2 = dictget(d, 'key_1', 'key_2')
```
whose advantage is that it is quite readable even with more variables to be retrieved.
Even more readable, however, would be a "real" funct... |
Does Python have a built-in function for unindenting a multiline string? | 11,157,043 | 21 | 2012-06-22T13:23:13Z | 11,157,061 | 45 | 2012-06-22T13:24:35Z | [
"python",
"string",
"indentation"
] | Say I have the string
```
s = """
Controller = require 'controller'
class foo
view: 'baz'
class: 'bar'
constructor: ->
Controller.mix @
"""
```
Every line in the string now has a global 4 space indentation. If this string was declared inside a function, it would have a 8 ... | Not a built-in function, but a function in the standard library: [`textwrap.dedent()`](http://docs.python.org/library/textwrap.html#textwrap.dedent)
```
>>> print(textwrap.dedent(s))
Controller = require 'controller'
class foo
view: 'baz'
class: 'bar'
constructor: ->
Controller.mix @
``` |
Looping over Iterator | 11,157,261 | 2 | 2012-06-22T13:36:26Z | 11,157,342 | 7 | 2012-06-22T13:41:37Z | [
"python",
"python-3.x",
"iterator"
] | Sorry if this is a silly question, but I could not make my mind up how it could work.
I defined an iterator which has a structure like that (it is a bit more complicated, but the model will do the job):
```
class MyIterator ():
def __init__(self):
print ('nothing happening here')
def __iter__ (self)... | One of the problems is that you are mixing two concepts: And
*iterable* defines an `__iter__()` method that returns an *iterator*,
but no `__next__()` method. An *iterator* in turn defines a
`__next__()` method, and a trivial `__iter__()` implementation that
returns `self`. Something like this:
```
class Iterable(obje... |
Python - intersection between a list and keys of a dictionary | 11,157,704 | 11 | 2012-06-22T14:01:10Z | 11,157,736 | 20 | 2012-06-22T14:02:46Z | [
"python"
] | I have a list that looks like this:
```
l1 = ['200:200', '90:728']
```
I have a dictionary that looks like this:
```
d1 = {'200:200':{'foo':'bar'},'300:300':{'foo':'bar'}}
```
I need to get filter out the dictioary where only the keys are in l1. The dict should look like this:
```
result = {'200:200':{'foo':'bar'}... | You can use the following code:
```
keys = set(l1).intersection(set(d1.keys()))
result = {k:d1[k] for k in keys}
```
**EDIT:** As commenters suggest you can replace the first line with, in Python 2.x:
```
keys = set(l1).intersection(d1)
```
And in Python 3.x:
```
keys = d1.keys() & l1
``` |
Less painful way to parse a RSS-Feed with lxml? | 11,157,894 | 3 | 2012-06-22T14:11:19Z | 11,158,374 | 8 | 2012-06-22T14:37:30Z | [
"python",
"django",
"lxml",
"atom",
"feedparser"
] | I need to display RSS-feeds with Python, Atom for the most part. Coming from PHP, where I could get values pretty fast with $entry->link i find lxml to be much more precise, faster, albeit complicated. After hours of probing I got this working with the arstechnica-feed:
```
def GetRSSFeed(url):
out = []
feed =... | Look at the feedparser library. It gives you a nicely formatted RSS object.
```
> import feedparser
> feed = feedparser.parse('http://feeds.marketwatch.com/marketwatch/marketpulse/')
> print feed.keys()
['feed',
'status',
'updated',
'updated_parsed',
'encoding',
'bozo',
'headers',
'etag',
'href',
'version',
... |
Non-Message Queue / Simple Long-Polling in Python (and Flask) | 11,158,121 | 23 | 2012-06-22T14:25:11Z | 11,161,888 | 36 | 2012-06-22T18:13:30Z | [
"python",
"flask",
"long-polling"
] | I am looking for a simple (i.e., not one that requires me to setup a separate server to handle a messaging queue) way to do long-polling for a small web-interface that runs calculations and produces a graph. This is what my web-interface needs to do:
1. User requests a graph/data in a web-interface
2. Server runs some... | I've built several apps like this using just Flask and jQuery. Based on that experience, I'd say your plan is good.
1. **Do not use the filesystem.** You will run into JavaScript security issues/protections. In the unlikely event you find reasonable workarounds, you still wouldn't have anything portable or scalable. I... |
Non-Message Queue / Simple Long-Polling in Python (and Flask) | 11,158,121 | 23 | 2012-06-22T14:25:11Z | 18,093,238 | 9 | 2013-08-07T01:36:27Z | [
"python",
"flask",
"long-polling"
] | I am looking for a simple (i.e., not one that requires me to setup a separate server to handle a messaging queue) way to do long-polling for a small web-interface that runs calculations and produces a graph. This is what my web-interface needs to do:
1. User requests a graph/data in a web-interface
2. Server runs some... | Long-polling was a reasonable work-around before simple, natural support for Web Sockets came to most browsers, and before it was easily integrated alongside Flask apps. But here in mid-2013, Web Socket support has come a long way.
[Here is an example](https://bitbucket.org/jeunice/flask-ws-example), similar to the on... |
Python load 2GB of text file to memory | 11,159,077 | 4 | 2012-06-22T15:14:48Z | 11,159,418 | 9 | 2012-06-22T15:34:40Z | [
"python",
"memory",
"text-files"
] | In Python 2.7, when I load all data from a text file of 2.5GB into memory for quicker processing like this:
```
>>> f = open('dump.xml','r')
>>> dump = f.read()
```
I got the following error:
```
Python(62813) malloc: *** mmap(size=140521659486208) failed (error code=12)
*** error: can't allocate region
*** set a br... | If you use [mmap](http://docs.python.org/library/mmap.html), you'll be able to load the entire file into memory immediately.
```
import mmap
with open('dump.xml', 'rb') as f:
# Size 0 will read the ENTIRE file into memory!
m = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) #File is open read-only
# Proceed with... |
How to recognize histograms with a specific shape in opencv / python | 11,159,493 | 6 | 2012-06-22T15:38:46Z | 11,163,952 | 9 | 2012-06-22T20:52:16Z | [
"python",
"opencv",
"histogram"
] | I want to segment images (from magazines) in text and image parts. I have several histograms for several ROIs in my picture. I use opencv with python (cv2).
I want to recognize histograms that look like this
<http://matplotlib.sourceforge.net/users/image_tutorial-6.png>
as it is a typical shape for a text region. Ho... | (See the EDIT at the end in case i misunderstood the question) :
If you are looking to draw the histograms, I had submitted one python sample to OpenCV, and you can get it from here :
<http://code.opencv.org/projects/opencv/repository/entry/trunk/opencv/samples/python2/hist.py>
It is used to draw two kinds of histog... |
Measure website load time with Python requests | 11,159,687 | 18 | 2012-06-22T15:48:07Z | 11,159,798 | 12 | 2012-06-22T15:54:54Z | [
"python",
"networking",
"delay",
"python-requests",
"timeit"
] | I'm trying to build a tool for testing the delay of my internet connection, more specifically web site load times. I thought of using the python [requests](http://docs.python-requests.org) module for the loading part.
Problem is, it's got no built-in functionality to measure the time it took to get the full response. ... | If you are not performing a single load time test for the Web, you can use
* <http://testutils.org/multi-mechanize/>
This is a very good way to perform web application load / stress test and get a picture of load / response times.
As for your question, it should be the total time for
1. time to create the request o... |
Measure website load time with Python requests | 11,159,687 | 18 | 2012-06-22T15:48:07Z | 21,017,825 | 42 | 2014-01-09T10:37:02Z | [
"python",
"networking",
"delay",
"python-requests",
"timeit"
] | I'm trying to build a tool for testing the delay of my internet connection, more specifically web site load times. I thought of using the python [requests](http://docs.python-requests.org) module for the loading part.
Problem is, it's got no built-in functionality to measure the time it took to get the full response. ... | There is such functionality in latest version of requests:
<http://docs.python-requests.org/en/latest/api/?highlight=elapsed#requests.Response.elapsed>
For example:
```
requests.get("http://127.0.0.1").elapsed.total_seconds()
``` |
Simplest way to run expect script from python | 11,160,504 | 3 | 2012-06-22T16:38:36Z | 11,160,553 | 11 | 2012-06-22T16:41:54Z | [
"python",
"ssh",
"subprocess",
"expect"
] | I'm trying to instruct my python to execute expect script "myexpect.sh":
```
#!/usr/bin/expect
spawn ssh usr@myip
expect "password:"
send "mypassword\n";
send "./mycommand1\r"
send "./mycommand2\r"
interact
```
I'm on windows so re-writing the lines in the expect script into python are not an option. Any suggestions?... | Use [pexpect library](http://pexpect.readthedocs.org/en/stable/index.html). This is python version for expect functionality.
Example:
```
child = pexpect.spawn('some command that requires password')
child.expect('Enter password:')
child.sendline('password')
child.expect(pexpect.EOF, timeout=None)
cmd_show_data = chi... |
writing integer values to a file using out.write() | 11,160,939 | 4 | 2012-06-22T17:08:18Z | 11,160,976 | 9 | 2012-06-22T17:10:41Z | [
"python"
] | I am generating some numbers(lets say, num) and writing the numbers to output file using `outf.write(num).`
But compiler is throwing an error:
```
"outf.write(num)
TypeError: argument 1 must be string or read-only character buffer, not int".
```
How can i solve this problem? | [write()](http://docs.python.org/library/stdtypes.html?highlight=write#file.write) only takes a *single string* argument, so you could do this:
```
outf.write(str(num))
```
or
```
outf.write('{}'.format(num)) # more "modern"
outf.write('%d' % num) # deprecated mostly
```
Also note that `write` will not appe... |
pip: inconsistent permissions issues | 11,161,776 | 8 | 2012-06-22T18:05:13Z | 11,169,137 | 9 | 2012-06-23T11:27:36Z | [
"python",
"centos",
"pip",
"python-module"
] | When installing a package via `sudo pip-python` (CentOS 6 package: `python-pip-0.8-1.el6.noarch`), I sometimes get permission issues with the installed packages being readable only by root.
Re-installing again one or two times usually fixes the problem. Has anyone experienced this? Or can anyone suggest any troublesho... | When you run a command using `sudo`, it will preserve the users `umask`. `pip` just installs files, it doesn't change access rights, so you'll end up with the files having the access rights set conforming to the current user's umask, which may be owner-readable only (0077) and therefore readable by root only.
That mea... |
Is it always faster to use string as key in a dict? | 11,162,201 | 16 | 2012-06-22T18:38:19Z | 11,162,265 | 7 | 2012-06-22T18:43:58Z | [
"python"
] | On this [page](http://wiki.python.org/moin/TimeComplexity), I see something interesting:
*Note that there is a fast-path for dicts that (in practice) only deal with str keys; this doesn't affect the algorithmic complexity, but it can significantly affect the constant factors: how quickly a typical program finishes.*
... | As this only affects the constant time, it's likely not to matter at all. The only time you really need to optimise is when you are working with very large data sets - which this does nothing to affect.
What this does mean is that in the cases where you have small dictionaries with strings as keys, Python will be quic... |
Is it always faster to use string as key in a dict? | 11,162,201 | 16 | 2012-06-22T18:38:19Z | 11,162,322 | 14 | 2012-06-22T18:47:58Z | [
"python"
] | On this [page](http://wiki.python.org/moin/TimeComplexity), I see something interesting:
*Note that there is a fast-path for dicts that (in practice) only deal with str keys; this doesn't affect the algorithmic complexity, but it can significantly affect the constant factors: how quickly a typical program finishes.*
... | The C code that underlies the Python dict is optimisted for String keys. [You can read about this here](http://lewk.org/blog/python-dictionary-optimizations) (and in the book the blog refers to).
If the Python runtime knows your dict only contains string keys it can do things such as not cater for errors that won't ha... |
how to issue a "show dbs" from pymongo | 11,162,551 | 26 | 2012-06-22T19:02:43Z | 11,162,624 | 40 | 2012-06-22T19:09:09Z | [
"python",
"mongodb",
"pymongo"
] | I'm using pymongo and I can't figure out how to execute the mongodb interactive shell equivalent of "show dbs". | ```
from pymongo import MongoClient
# Assuming youre running mongod on 'localhost' with port 27017
c = MongoClient('localhost',27017)
c.database_names()
``` |
Are there any real alternatives to reStructuredText for Python documentation? | 11,163,436 | 43 | 2012-06-22T20:12:27Z | 11,168,405 | 10 | 2012-06-23T09:32:56Z | [
"python",
"documentation",
"python-sphinx",
"restructuredtext",
"docstring"
] | I'm starting an open source Python project shortly and I'm trying to decide in advance how to write my docstrings. The obvious answer would be using reStructuredText and Sphinx with autodoc, because I *really* like the idea of simply properly documenting my code in my docstrings then have Sphinx automatically construct... | I use [epydoc](http://epydoc.sourceforge.net/) and not sphinx, so this answer may not apply.
The reStructuredText syntax you describe for documenting methods and functions is not the only possible one. By far, I prefer describing parameters using a [consolidated definition list](http://epydoc.sourceforge.net/manual-ot... |
Are there any real alternatives to reStructuredText for Python documentation? | 11,163,436 | 43 | 2012-06-22T20:12:27Z | 11,176,267 | 30 | 2012-06-24T09:14:25Z | [
"python",
"documentation",
"python-sphinx",
"restructuredtext",
"docstring"
] | I'm starting an open source Python project shortly and I'm trying to decide in advance how to write my docstrings. The obvious answer would be using reStructuredText and Sphinx with autodoc, because I *really* like the idea of simply properly documenting my code in my docstrings then have Sphinx automatically construct... | I don't think that there is something better than `sphinx` for documenting python projects at the moment.
To have a clearer docstring my favorite choice is using `sphinx` together with [`numpydoc`](http://pypi.python.org/pypi/numpydoc). Based on your example this would look like:
```
def foo(path, field_storage, temp... |
Are there any real alternatives to reStructuredText for Python documentation? | 11,163,436 | 43 | 2012-06-22T20:12:27Z | 17,731,693 | 61 | 2013-07-18T18:55:14Z | [
"python",
"documentation",
"python-sphinx",
"restructuredtext",
"docstring"
] | I'm starting an open source Python project shortly and I'm trying to decide in advance how to write my docstrings. The obvious answer would be using reStructuredText and Sphinx with autodoc, because I *really* like the idea of simply properly documenting my code in my docstrings then have Sphinx automatically construct... | I have created a [Sphinx extension](https://pypi.python.org/pypi/sphinxcontrib-napoleon/) that parses both Google style and NumPy style docstrings, and converts them to standard reStructuredText.
To use it, simply install it:
```
$ pip install sphinxcontrib-napoleon
```
And enable it in conf.py:
```
# conf.py
# Ad... |
Weird Try-Except-Else-Finally behavior with Return statements | 11,164,144 | 44 | 2012-06-22T21:07:35Z | 11,164,157 | 62 | 2012-06-22T21:09:04Z | [
"python",
"try-except"
] | This is some code that is behaving peculiarly. This is a simplified version of the behavior that I've written. This will still demonstrate the weird behavior and I had some specific questions on why this is occurring.
I'm using Python 2.6.6 on Windows 7.
```
def demo1():
try:
raise RuntimeError,"To Force ... | Because `finally` statements are **guaranteed** to be executed (well, presuming no power outage or anything outside of Python's control). This means that before the function can return, it must run the finally block, which returns a different value.
The [Python docs](http://docs.python.org/reference/compound_stmts.htm... |
Python closure + global strangeness | 11,164,149 | 9 | 2012-06-22T21:07:55Z | 11,164,869 | 8 | 2012-06-22T22:19:20Z | [
"python"
] | I expected this little snippet to print *"Why doesn't this work?"* Can someone help me understand why this doesn't work as I expect? I'm using Python 2.6, if this matters.
```
class WhyDoesntThisWork(object):
def outer(self):
acc = ''
def inner(msg):
global acc
acc = acc + msg
inner("Why does... | I don't know why so many comments above contain the correct answer and no one dared to write an actual answer, so I'll do it hereby.
```
class ThisWorksNow(object):
def outer(self):
acc = []
def inner(msg):
acc.append(msg)
inner("Why doesn't")
inner(" this work?")
print "".join(acc)
ThisWor... |
Pythonic, elegant way of dynamically defining a list of statically defined functions? | 11,164,286 | 4 | 2012-06-22T21:19:47Z | 11,164,327 | 8 | 2012-06-22T21:23:55Z | [
"python",
"dynamic",
"scripting",
"static"
] | I have only started learning Python recently. Let me explain what I am trying to accomplish. I have this .py script that basically has several functions (hard-coded into the script) that all need to be added to a single list, so that I can get the function I require by simply using the index operator as follows:
neede... | You are mistaken about decorators. They are invoked once when the function is defined, and the function they return is then the value assigned to the function name, and it is that function that is invoked each time. You can do what you want in a decorator without incurring runtime overhead.
```
my_functions = []
def ... |
Django Help: AttributeError: 'module' object has no attribute 'Charfield' | 11,164,420 | 4 | 2012-06-22T21:32:07Z | 11,164,431 | 24 | 2012-06-22T21:33:02Z | [
"python",
"django"
] | I have seen several similar posts of other attributes found but not this. New to Python and Django- I've done the first part of the several tutorials including Django's "Polls" tutorial and when it gets to the point where I syncdb for my app I invariably get 'AttributeError: 'module' object has no attribute CharField.
... | That is `CharField`, with uppercase 'f', and not `Charfield` as in your code. |
generating a CSV file online on Google App Engine | 11,164,686 | 4 | 2012-06-22T21:59:03Z | 11,164,791 | 12 | 2012-06-22T22:11:44Z | [
"python",
"google-app-engine",
"csv"
] | I am using Google App Engine (python), I want my users to be able to download a CSV file generated using some data from the datastore (but I don't want them to download the whole thing, as I re-order the columns and stuff).
I have to use the csv module, because there can be cells containing commas. But the problem tha... | I found a way to use the CSV module on GAE! Here it is:
```
self.response.headers['Content-Type'] = 'application/csv'
writer = csv.writer(self.response.out)
writer.writerow(["foo", "foo,bar", "bar"])
```
This way you don't need to write any files |
Why is my python function not defined, when it exists in the same file? | 11,165,423 | 2 | 2012-06-22T23:30:28Z | 11,165,524 | 9 | 2012-06-22T23:45:05Z | [
"python",
"function",
"nameerror",
"defined"
] | I have a simple function, which I shall call `myFunction`. It takes two parameters, performs some calculations on them, and returns the result.
I also have a class, `MyClass`, which has a constructor that has a header like this:
```
__init__(self, bar, fun=myFunction):
```
When I try to run anything in this class, I... | You haven't shown the actual code so it's hard to be sure, but I bet `myFunction` is defined after `MyClass`. The default value expression is evaluated when the `__init__` method is defined, so `myFunction` must be defined at that point. Defining it later is too late. |
Using subprocess with select and pty hangs when capturing output | 11,165,521 | 5 | 2012-06-22T23:44:36Z | 12,207,447 | 7 | 2012-08-31T00:32:35Z | [
"python",
"select",
"subprocess",
"pty"
] | I'm trying to write a python program that is able to interact with other programs. That means sending stdin and receiving stdout data. I cannot use pexpect (although it definitely inspired some of the design). The process I'm using right now is this:
1. Attach a pty to the subprocess's stdout
2. Loop until the subproc... | There are a number of things you can change to make your code correct. The simplest thing I can think of is just to close your parent process's copy of the slave fd after forking, so that when the child exits and closes its own slave fd, the parent's `select.select()` will mark the master as available for read, and the... |
Using subprocess with select and pty hangs when capturing output | 11,165,521 | 5 | 2012-06-22T23:44:36Z | 12,225,379 | 10 | 2012-09-01T06:10:54Z | [
"python",
"select",
"subprocess",
"pty"
] | I'm trying to write a python program that is able to interact with other programs. That means sending stdin and receiving stdout data. I cannot use pexpect (although it definitely inspired some of the design). The process I'm using right now is this:
1. Attach a pty to the subprocess's stdout
2. Loop until the subproc... | First of all, `os.read` does block, contrary to what you state. However, it does not block after `select`. Also `os.read` on a closed file descriptor always returns an empty string, that you might want to check for.
The real problem however is that the master device descriptor is never closed, thus the final `select` ... |
Build list using only list comprehensions, no function | 11,165,742 | 3 | 2012-06-23T00:28:09Z | 11,165,776 | 8 | 2012-06-23T00:33:40Z | [
"python",
"list-comprehension"
] | Given
```
userplays = { "Alice" : { "AC/DC" : 2,
"The Raconteurs" : 3,
"Mogwai" : 1
},
"Bob" : { "The XX" : 4,
"Lady Gaga" : 3,
"Mogwai" : 1,
... | This will do it:
```
set(b for v in userplays.values() for b in v.keys())
```
produces:
```
set(['Lady Gaga', 'Mogwai', 'AC/DC', 'The Raconteurs', 'The XX'])
``` |
How to tell if you have multiple Django's installed | 11,166,014 | 7 | 2012-06-23T01:15:42Z | 11,166,539 | 9 | 2012-06-23T03:18:18Z | [
"python",
"django",
"installation",
"duplicates"
] | In the process of trying to install django, I had a series of failures. I followed many different tutorials online and ended up trying to install it several times. I think I may have installed it twice (which the website said was not a good thing), so how do I tell if I actually have multiple versions installed? I have... | open terminal and type `python` then type `import django` then type `django` and it will tell you the path to the django you are importing. Goto that folder [it should look something like this: `/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/`] and look for more than one instance of djang... |
How to create a Django image gallery | 11,166,156 | 9 | 2012-06-23T01:50:04Z | 11,167,647 | 8 | 2012-06-23T07:10:51Z | [
"python",
"django",
"image",
"gallery",
"portfolio"
] | I am looking to create a portfolio using Django. I have tried using ImageField but it only allows me to upload and replace 1 photo.
I am new to Python and Django programming. How would I create a model to upload multiple images and show them in a gallery? Thanks. | You can also use apps like [photologue](http://code.google.com/p/django-photologue/), [imagekit](https://github.com/jdriscoll/django-imagekit), etc to simplify some of the tasks.
You may also upload multiple images using [Model Formsets](https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets) |
App engine NDB: how to access verbose_name of a property | 11,166,242 | 5 | 2012-06-23T02:13:17Z | 11,170,781 | 7 | 2012-06-23T15:39:31Z | [
"python",
"google-app-engine",
"gae-datastore",
"app-engine-ndb"
] | suppose I have this code:
```
class A(ndb.Model):
prop = ndb.StringProperty(verbose_name="Something")
m = A()
m.prop = "a string value"
```
Now of course if I print m.prop, it will output "a string value" while in fact it's a StringProperty instance. So verbose\_name can't be accessed the "normal" way, i.e `m.pr... | Use a class attribute: `A.prop._verbose_name`. Or `m.__class__.prop._verbose_name`. |
Generating random words | 11,166,547 | 2 | 2012-06-23T03:19:39Z | 11,166,556 | 7 | 2012-06-23T03:20:56Z | [
"python",
"random"
] | I'm trying to create a string that has a set amount of different words I include in a list, however the code I use only uses one word at random, not a different word for every word printed.
This is my code:
```
import random
words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
print random.choice(words)... | `random.choice(words) * 5` executes `random.choice` only once and then multiplies the result by five, causing the same string to be repeated.
```
>>> import random
>>> words = ['hello', 'apple', 'something', 'yeah', 'nope', 'lalala']
>>> print ''.join(random.choice(words) for _ in range(5))
applesomethinghellohellolal... |
What is best way to remove items from layout in pyqt | 11,166,712 | 4 | 2012-06-23T03:55:24Z | 11,167,610 | 8 | 2012-06-23T07:04:48Z | [
"python",
"layout",
"pyqt",
"qwidget"
] | I am having some issue with layout in pyqt. After closing the items from the layout still if layout.count() returns the old item count. So I think .close() not really removing items from the layout. Here is a full working example.
```
import sys
from PyQt4 import QtGui,QtCore
class LayoutTest(QtGui.QWidget):
def _... | Your comment is indeed a solution but rather than `close` use `deleteLater`. It is safer. With a bit of modification, I'd rewrite your method as:
```
def removeButtons(self):
for cnt in reversed(range(self.dvbox.count())):
# takeAt does both the jobs of itemAt and removeWidget
# namely it removes a... |
identity versus equality for None in Python | 11,166,748 | 13 | 2012-06-23T04:02:45Z | 11,166,757 | 14 | 2012-06-23T04:05:11Z | [
"python",
"coding-style"
] | Various Python guides say to use `x is None` instead of `x == None`. Why is that? Equality is used for comparing values, so it seems natural to ask if `x` has the value `None`, denoted with `==` and not `is`. Can someone explain why `is` is the preferred form and show an example where the two do not give the same answe... | The reason people use `is` is because there is no advantage to using `==`. It is possible to write objects that compare equal to `None`, but it is uncommon.
```
class A(object):
def __eq__(self, other):
return True
print A() == None
```
Output:
```
True
```
The `is` operator is also faster, but I don't... |
identity versus equality for None in Python | 11,166,748 | 13 | 2012-06-23T04:02:45Z | 11,167,217 | 9 | 2012-06-23T05:43:53Z | [
"python",
"coding-style"
] | Various Python guides say to use `x is None` instead of `x == None`. Why is that? Equality is used for comparing values, so it seems natural to ask if `x` has the value `None`, denoted with `==` and not `is`. Can someone explain why `is` is the preferred form and show an example where the two do not give the same answe... | The `is` keyword tests identity. It is not a comparison operator like `==`. Using `is` does more than test whether two arguments have the same value and/or the same internal structure: namely, it tests whether the two actually refer to the same object in memory. There are numerous implications to this, one of them bein... |
Python Bottle template issue: AttributeError("'dict' object has no attribute 'city'",) | 11,166,763 | 2 | 2012-06-23T04:06:48Z | 11,166,798 | 14 | 2012-06-23T04:14:26Z | [
"python",
"mongodb",
"bottle"
] | As a learning project, I'm using MongoDB with Bottle for a web service. What I want to do is fetch results from MongoDB and display them in a template. Here's the output I want from my template:
```
output.tpl
<html><body>
%for record in records:
<li>{{record.city}} {{record.date}}
%end
</body></html>
```
I can pu... | You need to use the dictionary syntax to lookup the properties:
```
{{record['city']}} {{record['date']}}
``` |
How do I reference a documented Python function parameter using Sphinx markup? | 11,168,178 | 22 | 2012-06-23T08:58:10Z | 11,178,709 | 21 | 2012-06-24T15:33:27Z | [
"python",
"documentation",
"python-sphinx",
"docstring"
] | I'd like to reference a previously-documented function parameter elsewhere in a Python docstring. Consider the following (admittedly completely artificial) example:
```
def foo(bar):
"""Perform foo action
:param bar: The bar parameter
"""
def nested():
"""Some nested function that depends on e... | There is no simple way to get a direct reference to a parameter of a function with `sphinx` and I don't know an extension for this problem.
The [documentation of the python domain](http://sphinx.pocoo.org/domains.html#cross-referencing-python-objects) explains which objects can be cross referenced.
A possible way to ... |
How do I reference a documented Python function parameter using Sphinx markup? | 11,168,178 | 22 | 2012-06-23T08:58:10Z | 20,845,306 | 13 | 2013-12-30T18:30:39Z | [
"python",
"documentation",
"python-sphinx",
"docstring"
] | I'd like to reference a previously-documented function parameter elsewhere in a Python docstring. Consider the following (admittedly completely artificial) example:
```
def foo(bar):
"""Perform foo action
:param bar: The bar parameter
"""
def nested():
"""Some nested function that depends on e... | I've just built an extension to accomplish this task. So far it seems to be working with standalone HTML build and additionally with readthedocs (after some more tweaks).
the extension is available at: <https://pypi.python.org/pypi/sphinx-paramlinks/>.
I'm rolling it out right now for the Alembic and SQLAlchemy proje... |
Composite Keys in Sqlalchemy | 11,168,492 | 8 | 2012-06-23T09:45:57Z | 11,169,106 | 17 | 2012-06-23T11:22:45Z | [
"python",
"sqlalchemy",
"primary-key"
] | I'm using `flask-sqlalchemy` to build a webapp and I have the following model(s):
```
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
candidates = db.relationship('Candidate', backref='post', lazy='dynamic')
def __init__(self, name):
... | > Is the id column necessary? Most of the tutorials I've seen have that as a column(primary key specifically). Can I do without it? Especially in cases where I have another primary key?
For the post table, yes. For the other one, no. Some might argue that since name is unique, make it a primary key, but that would mea... |
Objects With No Behavior | 11,170,120 | 7 | 2012-06-23T14:07:59Z | 11,170,163 | 8 | 2012-06-23T14:13:01Z | [
"python",
"object-oriented-analysis"
] | I'm thinking about a situation where I have an object "Transaction", that has quite a few properties to it like account, amount, date, currency, type, etc.
I never plan to mutate these data points, and calculation logic will live in other classes. My question is, is it poor Python design to instantiate thousands of ob... | No, this is perfectly fine. In fact, Python has support for it in the standard `collections` module:
```
from collections import namedtuple
Transaction = namedtuple("Transaction", ["account", "amount"])
```
instead of `class Transaction(object):` etc. Note that `namedtuple` is a kind of "class factory" and you need ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.