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 |
|---|---|---|---|---|---|---|---|---|---|
Selenium and Python to find elements and text? | 12,019,780 | 10 | 2012-08-18T15:27:19Z | 12,019,997 | 22 | 2012-08-18T15:56:54Z | [
"python",
"selenium",
"webdriver"
] | When I go to a certain webpage I am trying to find a certain element and piece of text:
```
<span class="Bold Orange Large">0</span>
```
This didn't work: *(It gave an error of compound class names...)*
```
elem = browser.find_elements_by_class_name("Bold Orange Large")
```
So I tried this: *(but I'm not sure it wo... | you want: **`elem.text`** to get "the number that is inside".
explanation:
in your example, `elem` is an instance of webdriver's `WebElement` class (from [selenium.webdriver.remote.webelement](http://selenium.googlecode.com/svn/trunk/docs/api/py/webdriver_remote/selenium.webdriver.remote.webelement.html))
a WebEleme... |
Python Nested lists and iteration | 12,019,825 | 7 | 2012-08-18T15:32:54Z | 12,019,855 | 11 | 2012-08-18T15:37:35Z | [
"python",
"python-2.7"
] | *I am new to Python and I did my search but I could not find what I am looking for. I apologise in advance if this question has been asked and if I could not find it due to my lack of not knowing the name of what I am trying to achieve. I will gladly read any document you might suggest.*
I have a list of lists. e.g. =... | ```
[n for n, (i, s) in enumerate(t) if s == 'str_3']
```
Explanation:
```
>>> t = [[100, 'str_1'], [200, 'str_2'], [300, 'str_3']]
# Use enumerate to get each list item along with its index.
>>> list(enumerate(t))
[(0, [100, 'str_1']), (1, [200, 'str_2']), (2, [300, 'str_3'])]
# Use list comprehension syntax to it... |
Python Nested lists and iteration | 12,019,825 | 7 | 2012-08-18T15:32:54Z | 12,019,891 | 7 | 2012-08-18T15:41:13Z | [
"python",
"python-2.7"
] | *I am new to Python and I did my search but I could not find what I am looking for. I apologise in advance if this question has been asked and if I could not find it due to my lack of not knowing the name of what I am trying to achieve. I will gladly read any document you might suggest.*
I have a list of lists. e.g. =... | Use the [`any` function](http://docs.python.org/library/functions.html#any) with a generator expression:
```
any(el[1] == 'str_1' for el in t)
```
What this does is loop over `t`, and for each `el` in `t` we test if the second value in it is equal to `str_1`, just like your loop.
But it'll only do this until it find... |
Python: pickling nested functions | 12,019,961 | 4 | 2012-08-18T15:51:03Z | 12,022,055 | 7 | 2012-08-18T20:35:23Z | [
"python",
"function",
"nested",
"pickle"
] | Using the example
```
def foo(a):
def bar(b):
return a+b
return bar
d = {1:foo(1), 2:foo(2)}
```
It appears that pickle module will not work with a function not defined at the module scope, so pickling 'd' will not work. Is there another pickling mechanism available that I should consider? | I'm afraid that you can't pickle nested functions.
The `pickle` module serializes functions by name. That is, if you have a function `myfunc` in a module `mymodule` it simply saves the name `mymodule.myfunc` and looks it up again when unserializing. (This is an important security and compatibility issue, as it guarant... |
How to list specific node/edge in networkx? | 12,020,020 | 7 | 2012-08-18T16:00:16Z | 12,042,333 | 8 | 2012-08-20T17:39:04Z | [
"python",
"graph",
"traversal",
"networkx"
] | Suppose one below tree-like structure in `networkx` graph:
```
n-----n1----n11
| |----n12
| |----n13
| |----n131
|----n2 |
| |-----n21 X
| |-----n22 |
| |----n221
|----n3
n4------n41
n5
```
1. How to list all nodes with "subnode" and it... | Graph construction:
```
>>> import networkx as nx
>>> G = nx.DiGraph()
>>> G.add_edges_from([('n', 'n1'), ('n', 'n2'), ('n', 'n3')])
>>> G.add_edges_from([('n4', 'n41'), ('n1', 'n11'), ('n1', 'n12'), ('n1', 'n13')])
>>> G.add_edges_from([('n2', 'n21'), ('n2', 'n22')])
>>> G.add_edges_from([('n13', 'n131'), ('n22', 'n2... |
Python 'if' within assignment acceptable? | 12,020,454 | 4 | 2012-08-18T16:53:42Z | 12,020,486 | 8 | 2012-08-18T16:57:08Z | [
"python"
] | Friday I had a discussion with someone about the following contruction:
```
class C(....
c = C()
d = C()
...
(c if some_boolean else d).some_function_of_class_C()
```
Is this kind of if statement acceptable/encouraged?
The problem is that a lot of people I work with have C experience but not that much Python exper... | There's nothing technically wrong with your code, but it is a little odd and surprising to see code like that.
Splitting your statement into two separate statements improves the readability:
```
c = c1 if some_boolean else c2
c.some_function_of_class_C()
```
The terrible variable names you have chosen still make it ... |
How do I open an image from the internet in PIL? | 12,020,657 | 13 | 2012-08-18T17:21:45Z | 12,020,860 | 21 | 2012-08-18T17:46:37Z | [
"python",
"python-imaging-library",
"urllib2"
] | I would like to find the dimensions of an image on the internet. I tried using
```
from PIL import Image
import urllib2 as urllib
fd = urllib.urlopen("http://a/b/c")
im = Image.open(fd)
im.size
```
as suggested in [this answer](http://stackoverflow.com/a/6014074/159388), but I get the error message
```
addinfourl in... | You might consider using [`io.BytesIO`](http://docs.python.org/library/io.html#buffered-streams) for [forward compatibility](http://dictionary.reference.com/browse/forward+compatibility).
The StringIO and cStringIO modules do not exist in Python 3.
```
from PIL import Image
import urllib2 as urllib
import io
fd = u... |
How do I open an image from the internet in PIL? | 12,020,657 | 13 | 2012-08-18T17:21:45Z | 12,020,866 | 7 | 2012-08-18T17:47:35Z | [
"python",
"python-imaging-library",
"urllib2"
] | I would like to find the dimensions of an image on the internet. I tried using
```
from PIL import Image
import urllib2 as urllib
fd = urllib.urlopen("http://a/b/c")
im = Image.open(fd)
im.size
```
as suggested in [this answer](http://stackoverflow.com/a/6014074/159388), but I get the error message
```
addinfourl in... | Using your same example, just use StringIO to wrap the buffer into a proper file-like object:
```
from PIL import Image
import urllib2 as urllib
from StringIO import StringIO
fd = urllib.urlopen("http://a/b/c")
im = Image.open(StringIO(fd.read()))
im.size
``` |
python int( ) function | 12,020,821 | 6 | 2012-08-18T17:41:14Z | 12,020,935 | 8 | 2012-08-18T17:57:35Z | [
"python",
"int"
] | The code below shows error if a decimal *(eg. 49.9)* is sent to `next` variable. Can you please tell me why? Why does `int()` converts it into an integer?
```
next=raw_input("> ")
how_much = int(next)
if how_much < 50:
print"Nice, you're not greedy, you win"
exit(0)
else:
dead("You greedy bastard!")
```
I... | As the other answers have mentioned, the `int` operation will crash if the string input is not convertible to an int (such as a float or characters). What you can do is use a little helper method to try and interpret the string for you:
```
def interpret_string(s):
if not isinstance(s, basestring):
return ... |
Python: Converting file to base64 encoding | 12,020,885 | 11 | 2012-08-18T17:49:58Z | 12,020,890 | 33 | 2012-08-18T17:50:47Z | [
"python"
] | This is my code:
```
import base64
with open('/Users/Bob/test.txt') as f:
encoded = base64.b64encode(f.readlines())
print(encoded)
```
I've based it on the [base64 documentation](http://docs.python.org/library/base64.html). However, when I try running it with Python 2.7.1 and Python 3.2.2 I get the error:
`... | You have a script named `base64.py` which is shadowing the stdlib module. Rename it. |
What does << represent in python? | 12,021,467 | 6 | 2012-08-18T19:08:51Z | 12,021,504 | 9 | 2012-08-18T19:12:28Z | [
"python",
"syntax"
] | Python says
```
1 << 16 = 65536
```
What operation does `<<` performs in Python? | This is `left shift operator`
`1<<16` implies 1 to be shifted left by 16 bits. |
What does << represent in python? | 12,021,467 | 6 | 2012-08-18T19:08:51Z | 12,021,618 | 12 | 2012-08-18T19:26:33Z | [
"python",
"syntax"
] | Python says
```
1 << 16 = 65536
```
What operation does `<<` performs in Python? | It is the left shift operator for Python.
A left shift operation, as the name says, move bits to the left.
Suppose you have 2 whose binary representation is 0010.
So `2<<2` means to shift the bits twice to the left:
0010 -> 0100 -> 1000
1000 is the binary representation for 8. Mathematically, left shifting is the ... |
can pandas handle variable-length whitespace as column delimeters | 12,021,730 | 12 | 2012-08-18T19:45:34Z | 12,022,047 | 14 | 2012-08-18T20:35:00Z | [
"python",
"table",
"pandas"
] | I have a textfile where columns are separated by variable amounts of whitespace. Is it possible to load this file directly as a pandas dataframe without pre-processing the file? In the [pandas documentation the delimiter section](http://pandas-docs.github.io/pandas-docs-travis/io.html#csv-text-files) says that I can us... | I think there's just a missing `\` in the docs (maybe because it was interpreted as an escape marker at some point?) It's a regexp, after all:
```
In [68]: data = read_table('sample.txt', skiprows=3, header=None, sep=r"\s*")
In [69]: data
Out[69]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 7 entries, 0 to 6
D... |
can pandas handle variable-length whitespace as column delimeters | 12,021,730 | 12 | 2012-08-18T19:45:34Z | 30,201,213 | 15 | 2015-05-12T20:53:51Z | [
"python",
"table",
"pandas"
] | I have a textfile where columns are separated by variable amounts of whitespace. Is it possible to load this file directly as a pandas dataframe without pre-processing the file? In the [pandas documentation the delimiter section](http://pandas-docs.github.io/pandas-docs-travis/io.html#csv-text-files) says that I can us... | You should be able to just do this, which @DSM just taught me in another thread:
```
data = read_table('sample.txt', skiprows=3, header=None, delim_whitespace=True)
```
[Documentation](http://pandas-docs.github.io/pandas-docs-travis/io.html#csv-text-files) |
Pull random keys from dictionary in Python that are not equal to one another | 12,022,229 | 6 | 2012-08-18T21:02:15Z | 12,022,251 | 12 | 2012-08-18T21:05:34Z | [
"python",
"function",
"dictionary",
"python-2.7"
] | So I'm trying to setup a multiple choice quiz via Python. I'm fairly new to Python, so my apologies up front if there is a simpler way to do this. However, I'm trying to really understand some basics before moving forward to newer techniques.
I have a dictionary. In this dictionary, I want to grab 3 random keys. I als... | You can use `random.sample`:
```
>>> random.sample(word_drills, 3)
['has-a', 'attribute', 'instance']
```
and you don't need `.keys()`, iteration over a dictionary is over the keys.
Note that `random.sample` will return three unique values from the list you supply (i.e. it will never return `'has-a'` twice):
```
>>... |
What is the complexity of bisect algorithim? | 12,022,249 | 4 | 2012-08-18T21:05:31Z | 12,022,278 | 13 | 2012-08-18T21:08:44Z | [
"python",
"list",
"search",
"complexity-theory",
"bisect"
] | I wrote code to understand which of them is faster when it comes to search an element in a list. It turns out to be bisect. What I do not understand is what is complexity of bisect algorithm and does it use Van Emde Boas tree?
```
#python inbuilt list search using 'in' took 0.0702499200317 secs
def mul3():
a = [1... | It uses binary search, which makes it O(log n). |
Execute some code when an SQLAlchemy object's deletion is actually committed | 12,023,526 | 12 | 2012-08-19T01:26:14Z | 12,026,787 | 12 | 2012-08-19T13:19:52Z | [
"python",
"postgresql",
"sqlalchemy",
"commit",
"flask-sqlalchemy"
] | I have a SQLAlchemy model that represents a file and thus contains the path to an actual file. Since deletion of the database row and file should go along (so no orphaned files are left and no rows point to deleted files) I added a `delete()` method to my model class:
```
def delete(self):
if os.path.exists(self.p... | When using SQLAlchemy in a Flask app with [Flask-SQLAlchemy](http://packages.python.org/Flask-SQLAlchemy/) it provides a [models\_committed](http://packages.python.org/Flask-SQLAlchemy/signals.html#models_committed) signal which receives a list of `(model, operation)` tuples. Using this signal doing what I'm looking fo... |
Python 3.3 source code setup: modules were not found: _lzma _sqlite3 _tkinter | 12,023,773 | 5 | 2012-08-19T02:34:22Z | 15,492,986 | 12 | 2013-03-19T06:35:51Z | [
"python",
"python-3.3"
] | I am trying to set up the compiled version of CPython, on Ubuntu 12.04, by following the python developer guide.
Even after installing the dependent packages lzma and sqlite3, build fails indicating that the dependent modules were not found.
*Exact Error:*
\*Python build finished, but the necessary bits to build these... | I was able to build `Python 3.3` without modifying `setup.py` after installing the following packages on my Ubuntu Precise box.
```
build-essential
zlib1g-dev
libbz2-dev
libncurses5-dev
libreadline6-dev
libsqlite3-dev
libssl-dev
libgdbm-dev
liblzma-dev
tk8.5-dev
``` |
Bad Request Error with flask, python, HTML, unusual initialization behavior with flask.request.form | 12,023,864 | 10 | 2012-08-19T02:55:10Z | 12,023,885 | 27 | 2012-08-19T03:01:08Z | [
"python",
"html",
"flask",
"bad-request"
] | I'm writing a web-app using flask, python and HTML. My issue is that the first time I load the a webpage, I get the following error
> Bad Request The browser (or proxy) sent a request that this server
> could not understand.
I'm able to get the page to load eventually by "tricking" first running it without any `flask... | The issue here is that you are attempting to access `POST`ed variables in a method that will only handle `GET` requests. When you attempt to access a query string or POST parameter that is not set [Flask will, by default, raise a `BadRequest` error](http://flask.pocoo.org/docs/quickstart/#the-request-object) (because y... |
No module named Image | 12,024,397 | 3 | 2012-08-19T05:17:49Z | 12,024,519 | 12 | 2012-08-19T05:48:59Z | [
"python",
"image",
"django-grappelli"
] | Sorry for my grammar, I don't speak English.
After I set filebrowser, tinymce, and grappelli, I get this error: `No module named Image`
```
try:
from PIL import Image
except ImportError:
import Image
```
I set it to `PIL` but it didn't solve the problem.
my platform windows
If i want: pip install PIL
```
`c... | Did you setup PIL module? [Link](http://www.pythonware.com/products/pil/)
You can try to reinstall it on your computer. |
No module named Image | 12,024,397 | 3 | 2012-08-19T05:17:49Z | 32,166,371 | 7 | 2015-08-23T11:54:14Z | [
"python",
"image",
"django-grappelli"
] | Sorry for my grammar, I don't speak English.
After I set filebrowser, tinymce, and grappelli, I get this error: `No module named Image`
```
try:
from PIL import Image
except ImportError:
import Image
```
I set it to `PIL` but it didn't solve the problem.
my platform windows
If i want: pip install PIL
```
`c... | You are missing PIL (Python Image Library and Imaging package). To install PIL I used
```
pip install pillow
```
For my machine running Mac OSX 10.6.8, I downloaded Imaging package and installed it from source.
<http://effbot.org/downloads/Imaging-1.1.6.tar.gz> and cd into Download directory. Then run these:
```
... |
Danger of mixing numpy matrix and array | 12,024,820 | 12 | 2012-08-19T07:00:41Z | 12,024,981 | 18 | 2012-08-19T07:34:08Z | [
"python",
"arrays",
"matrix",
"numpy"
] | The science/engineering application I'm working on has lots of linear algebra matrix multiplications, therefore I use Numpy matrices. However, there are many functions in python that interchangeably accept matrix or array types. Nice, no? Well, not really. Let me demonstrate the problem with an example:
```
from scipy... | I tend to use `array` instead of `matrix` in `numpy` for a few reasons:
1. `matrix` is strictly 2D whereas you can have a `numpy` `array` of any dimension.
2. Aside from a few differences, `array` and `matrix` operations are pretty much [interchangeable](http://www.scipy.org/NumPy_for_Matlab_Users) for a Matlab user.
... |
Automatic screenshots when test fail by Selenium Webdriver in Python | 12,024,848 | 11 | 2012-08-19T07:05:50Z | 12,026,744 | 13 | 2012-08-19T13:12:01Z | [
"python",
"selenium",
"webdriver",
"screenshot"
] | I want to automatic capturing screenshots if my webdriver tests failed (any exception or assertion error). I am using Python unittest and Selenium Webdriver. Does anyone have any solution to this problem? | do some webdriver stuff in Firefox... save screenshot on any exception to a dated image file:
```
from datetime import datetime
from selenium import webdriver
browser = webdriver.Firefox()
try:
# do some webdriver stuff here
except Exception as e:
print e
now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S'... |
How to read from a zip file within zip file in Python? | 12,025,469 | 15 | 2012-08-19T09:19:35Z | 12,025,492 | 22 | 2012-08-19T09:25:03Z | [
"python",
"file",
"zip",
"unzip"
] | I have a file that I want to read that is itself zipped within a zip archive. For example, parent.zip contains child.zip, which contains child.txt. I am having trouble reading child.zip. Can anyone correct my code?
I assume that I need to create child.zip as a file-like object and then open it with a second instance o... | When you use the `.open()` call on a `ZipFile` instance you indeed get an open file handle. However, to *read* a zip file, the `ZipFile` class needs a little more. It needs to be able to *seek* on that file, and the object returned by `.open()` is not seekable.
The workaround is to read the whole zip entry into memory... |
GAE Webapp2 - destroying session doesn't work | 12,025,612 | 3 | 2012-08-19T09:51:15Z | 12,026,815 | 9 | 2012-08-19T13:26:06Z | [
"python",
"google-app-engine",
"session",
"webapp2"
] | Or do I misunderstand how destroying work? Here's an example code:
```
class TestHandler(BaseHandler):
def get(self):
counter = self.session.get('counter')
if not counter:
counter = 0
counter += 1
if counter > 5:
self.auth.unset_session()
else:
... | unset\_session removes the *user* from the session not the other session variables. The unset\_session method is on the auth module.
If you dig a little deeper in the code you can have a look at what the code is doing.
<http://code.google.com/p/webapp-improved/source/browse/webapp2_extras/auth.py>
```
def unset_sess... |
Combine lists row-wise (Python) | 12,025,750 | 4 | 2012-08-19T10:18:08Z | 12,025,763 | 12 | 2012-08-19T10:20:15Z | [
"python",
"list"
] | Let's say I have 3 different lists
```
col1 = ['2006-03-28','2006-04-05','2006-04-06']
col2 = ['IBM', 'MSFT', 'IBM']
col3 = [1000, 1000, 500]
```
What is the most efficient way to combine those lists in another list like this:
```
col = [('2006-03-28', 'IBM', 1000),
('2006-04-05', 'MSFT', 1000),
('2006... | ```
>>> col1 = ['2006-03-28','2006-04-05','2006-04-06']
>>> col2 = ['IBM', 'MSFT', 'IBM']
>>> col3 = [1000, 1000, 500]
>>> zip(col1, col2, col3)
[('2006-03-28', 'IBM', 1000), ('2006-04-05', 'MSFT', 1000), ('2006-04-06', 'IBM', 500)]
```
If your columns are already in one list you can just use `zip(*cols)` |
Trying to serve django static files on development server - not found | 12,026,010 | 10 | 2012-08-19T11:08:27Z | 12,029,220 | 12 | 2012-08-19T19:14:12Z | [
"python",
"django"
] | I've followed the instructions in [this question](http://stackoverflow.com/q/9197599/344286), [the documentation](https://docs.djangoproject.com/en/dev/howto/static-files/), and I've even looked at [this one](http://stackoverflow.com/q/10644649/344286), but so far I'm unable to get at my static files using `python mana... | Django's handling of static files continue to be slightly confusing, particularly in terms of the naming of relevant settings.
The short answer is to move your static files; instead of
```
/home/wayne/programming/somesite/static
```
put them in
```
/home/wayne/programming/somesite/yourapp/static
```
(where "yourap... |
Selecting specific columns from df -h output in python | 12,027,237 | 7 | 2012-08-19T14:24:06Z | 12,027,521 | 8 | 2012-08-19T15:06:17Z | [
"python",
"parsing",
"unix"
] | I'm trying to create a simple script that will select specific columns from the unix `df - h` command. I can use awk to do this but how can we do this in python?
Here is `df -h` output:
```
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/vg_base-lv_root 28G 4.8G 22G 19% /
tmpfs... | You can use [`op.popen`](http://docs.python.org/library/os.html#os.popen) to run the command and retrieve its output, then [`splitlines`](http://docs.python.org/library/stdtypes.html#str.splitlines) and [`split`](http://docs.python.org/library/stdtypes.html#str.split) to split the lines and fields. Run [`df -Ph`](http:... |
Determine if Django is running under the development server | 12,027,545 | 7 | 2012-08-19T15:09:18Z | 12,028,260 | 7 | 2012-08-19T16:54:46Z | [
"python",
"django"
] | Is there a way to determine if Django is running on localhost and setting the `DEBUG` variable in `settings.py` accordingly.
So that if I run the server locally it will set `DEBUG` to `True` and otherwise set it to `False`.
Localhost: `python manage.py runserver`
Not localhost: `python manage.py runserver 0.0.0.0:8... | As suggested by Bernhard Vallant, you can just check for `runserver` in `sys.argv`.
You can just replace your `DEBUG` assignment in `settings.py` with this:
```
DEBUG = (sys.argv[1] == 'runserver')
```
You should also `import sys` somewhere in `settings.py`. |
Python - can't import Set from sets ("no module named sets") | 12,028,204 | 2 | 2012-08-19T16:46:11Z | 12,028,229 | 8 | 2012-08-19T16:49:58Z | [
"python",
"import",
"module"
] | I'm trying to learn python and I was trying to write something simple. I am developing under Pydev (Eclipse) using OS X 10.8. I installed python 3.2 using the 64bits .dmg installer.
I configured the Python interpreter successfully (or I think so, as I actually can create a "hello world" project and run it). But for so... | You don't need the `sets` module anymore. [`set`](http://docs.python.org/py3k/tutorial/datastructures.html#sets) is a built-in class in Python 3 and can be used without import.
```
mySet = set()
``` |
Python - can't import Set from sets ("no module named sets") | 12,028,204 | 2 | 2012-08-19T16:46:11Z | 12,028,231 | 11 | 2012-08-19T16:50:10Z | [
"python",
"import",
"module"
] | I'm trying to learn python and I was trying to write something simple. I am developing under Pydev (Eclipse) using OS X 10.8. I installed python 3.2 using the 64bits .dmg installer.
I configured the Python interpreter successfully (or I think so, as I actually can create a "hello world" project and run it). But for so... | In every recent python version sets are builtin as `set` and Python 3 got rid of the deprecated `sets` module altogether.
If you wanted to ensure that the code also works with ancient versions you could do something like this though:
```
try:
set
except NameError:
from sets import Set as set
```
If you need ... |
Python's StringIO doesn't do well with `with` statements | 12,028,637 | 14 | 2012-08-19T17:50:14Z | 12,028,682 | 28 | 2012-08-19T17:58:17Z | [
"python",
"unit-testing",
"stringio",
"stubs"
] | I need to stub `tempfile` and `StringIO` seemed perfect. Only that all this fails in an omission:
```
In [1]: from StringIO import StringIO
In [2]: with StringIO("foo") as f: f.read()
--> AttributeError: StringIO instance has no attribute '__exit__'
```
What's the usual way to provide canned info instead of reading ... | The StringIO module predates the `with` statement. Since StringIO [has been removed in Python 3](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit) anyways, you can just use its replacement, [`io.BytesIO`](http://docs.python.org/library/io.html#io.BytesIO):
```
>>> import ... |
What version of Visual Studio and/or MinGW do I need to build extension modules for a given version of Python? | 12,028,762 | 8 | 2012-08-19T18:07:09Z | 12,029,585 | 9 | 2012-08-19T20:04:02Z | [
"python",
"c",
"windows",
"visual-studio",
"build"
] | To put this question a different way, what version of Visual C++ was each official build of Python from [python.org](http://python.org) of Python built with, and what versions of MinGW are compatible with those versions of Visual C++?
Is this information readily available on some web site? | Python 2.6, 2.7, 3.1, and 3.2 were all compiled with VS 2008. Python 3.3 and 3.4 are compiled with VS 2010.
I'm not sure about MinGW compatibility.
If you are looking for command line compilers, Microsoft has released two different SDKs for Windows 7 that include the command line compilers. The first SDK (for .NET 3.... |
Generate list of numbers in specific format | 12,030,074 | 3 | 2012-08-19T21:15:41Z | 12,030,095 | 11 | 2012-08-19T21:18:14Z | [
"python",
"list",
"python-2.7"
] | I need to generate a list of numbers in a specific format. The format is
```
mylist = [00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15]
#Numbers between 0-9 are preceded by a zero.
```
I know how to generate a normal list of numbers using `range`
```
>>> for i in range(0,16):
... print i
```
So, is there any bu... | Python [string formatting](http://docs.python.org/library/stdtypes.html#string-formatting) allows you to specify a precision:
> Precision (optional), given as a '.' (dot) followed by the precision.
In this case, you can use it with a value of 2 to get what you want:
```
>>> ["%.2d" % i for i in range(16)]
['00', '01... |
Getting current date and current time only respectively | 12,030,187 | 17 | 2012-08-19T21:33:51Z | 12,030,230 | 44 | 2012-08-19T21:40:18Z | [
"python",
"django"
] | I came across an interesting situation.
```
class Company(models.Model):
date = models.DateField()
time = models.TimeField()
```
When using this class:
```
c = Company(date=datetime.datetime.now(), time=datetime.datetime.now())
```
Django decides to use `DATETIME_INPUT_FORMATS`... | For the date, you can use `datetime.date.today()` or `datetime.datetime.now().date()`.
For the time, you can use `datetime.datetime.now().time()`.
---
However, why have separate fields for these in the first place? Why not use a single `DateTimeField`?
You can always define helper functions on the model that return... |
Getting current date and current time only respectively | 12,030,187 | 17 | 2012-08-19T21:33:51Z | 33,142,852 | 7 | 2015-10-15T07:51:32Z | [
"python",
"django"
] | I came across an interesting situation.
```
class Company(models.Model):
date = models.DateField()
time = models.TimeField()
```
When using this class:
```
c = Company(date=datetime.datetime.now(), time=datetime.datetime.now())
```
Django decides to use `DATETIME_INPUT_FORMATS`... | ```
import datetime
datetime.datetime.now().strftime ("%Y%m%d")
20151015
```
For the time
```
from time import gmtime, strftime
showtime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
print showtime
2015-10-15 07:49:18
``` |
CherryPy redirect to root | 12,030,195 | 6 | 2012-08-19T21:34:41Z | 12,030,705 | 18 | 2012-08-19T23:08:34Z | [
"python",
"redirect",
"cherrypy"
] | quick question: I have created a web server using CherryPy. It requires authentication for all pages, so my default handler returns the login page object. Due to the way that CherryPy handles the dispatches, somebody who requests:
```
localhost:80/a/b/c
```
would be redirected to:
```
localhost:80/a/b/login
```
how... | You can specify the login page with a redirect: `raise cherrypy.HTTPRedirect("/auth/login")`
But, take a look here, there is a sample of how to write an authentication routine:
<http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions>
There is also an example of how to redirect the user back at the reques... |
Mongo conditional for "key doesn't exist"? | 12,030,487 | 11 | 2012-08-19T22:26:06Z | 12,030,597 | 9 | 2012-08-19T22:49:08Z | [
"python",
"mongodb",
"pymongo",
"key-value"
] | I want to find a document using a conditional if the key == None or if the key doesn't exist. Something like this:
```
myDoc = self.request.root.db.myDocs.find_one({
'$or': [
{'myKey' : $doesNotExist } ,
{'myKey' : None }
... | You can test for a key not existing with:
```
db.myDocs.find_one({'myKey': { '$exists': False }})
```
Mongo documentation about the [$exists operator](http://docs.mongodb.org/manual/reference/operator/query/exists/#op._S_exists) |
Mongo conditional for "key doesn't exist"? | 12,030,487 | 11 | 2012-08-19T22:26:06Z | 15,487,336 | 12 | 2013-03-18T21:31:23Z | [
"python",
"mongodb",
"pymongo",
"key-value"
] | I want to find a document using a conditional if the key == None or if the key doesn't exist. Something like this:
```
myDoc = self.request.root.db.myDocs.find_one({
'$or': [
{'myKey' : $doesNotExist } ,
{'myKey' : None }
... | For "if key exists" checks, using a `.find()` is [significantly faster](http://blog.serverdensity.com/checking-if-a-document-exists-mongodb-slow-findone-vs-find/) than `find_one()`.
*Single document:* `cursor = db.myDocs.find({"mykey": {"$exists": True}}).limit(1)`
*Multiple documents:* `cursor = db.myDocs.find({"myk... |
Flask and uWSGI - unable to load app 0 (mountpoint='') (callable not found or import error) | 12,030,809 | 18 | 2012-08-19T23:30:49Z | 12,030,880 | 13 | 2012-08-19T23:46:04Z | [
"python",
"flask",
"uwsgi"
] | I get the below error when I try and start Flask using uWSGI.
Here is how I start:
```
> # cd ..
> root@localhost:# uwsgi --socket 127.0.0.1:6000 --file /path/to/folder/run.py --callable app - -processes 2
```
Here is my directory structure:
```
-/path/to/folder/run.py
-|app
-|__init__.py
... | uWSGI doesn't load your app as `__main__`, so it never will find the `app` (since that only gets loaded when the app is run as name `__main__`). Thus, you need to import it outside of the `if __name__ == "__main__":` block.
Really simple change:
```
from app import app
if __name__ == "__main__":
app.run()
```
N... |
Flask and uWSGI - unable to load app 0 (mountpoint='') (callable not found or import error) | 12,030,809 | 18 | 2012-08-19T23:30:49Z | 32,060,673 | 49 | 2015-08-17T22:23:07Z | [
"python",
"flask",
"uwsgi"
] | I get the below error when I try and start Flask using uWSGI.
Here is how I start:
```
> # cd ..
> root@localhost:# uwsgi --socket 127.0.0.1:6000 --file /path/to/folder/run.py --callable app - -processes 2
```
Here is my directory structure:
```
-/path/to/folder/run.py
-|app
-|__init__.py
... | I had problems with the accepted solution because my flask app was in a variable called `app`. You can solve that with putting just this in your wsgi:
```
from module_with_your_flask_app import app as application
```
So the problem was simply that uwsgi expects a variable called `application`. |
Disable static file caching in Tornado | 12,031,007 | 15 | 2012-08-20T00:16:49Z | 12,031,093 | 11 | 2012-08-20T00:40:01Z | [
"python",
"caching",
"tornado",
"static-files"
] | By default, Tornado puts a `Cache-Control: public` header on any file served by a `StaticFileHandler`. How can this be changed to `Cache-Control: no-cache`? | Looking into the tornado/web.py it seems that the easiest way is to subclass the StaticFileHandler and override the set\_extra\_headers method.
```
def set_extra_headers(self, path):
self.set_header("Cache-control", "no-cache")
``` |
Disable static file caching in Tornado | 12,031,007 | 15 | 2012-08-20T00:16:49Z | 18,879,658 | 28 | 2013-09-18T18:27:42Z | [
"python",
"caching",
"tornado",
"static-files"
] | By default, Tornado puts a `Cache-Control: public` header on any file served by a `StaticFileHandler`. How can this be changed to `Cache-Control: no-cache`? | The accepted answer does not work for Chrome. Subclass `StaticFileHandler` using the following:
```
class MyStaticFileHandler(tornado.web.StaticFileHandler):
def set_extra_headers(self, path):
# Disable cache
self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
``` |
Custom Sorting Python Dictionary | 12,031,482 | 2 | 2012-08-20T01:55:13Z | 12,031,752 | 9 | 2012-08-20T02:45:31Z | [
"python"
] | So I have a dictionary that looks like this when I print it:
```
{'10': -10, 'ZT21': 14, 'WX21': 12, '2': 15, '5': -3, 'UM': -25}
```
I want to sort these in a custom manner, which I define. Let's say the way I want it to be sorted (by key) is `ZT21`, `10`, `WX21`, `UM`, `5`, `2`.
Anyone know how to go about sorting... | Dictionaries in Python are unordered. You can get the results you need as a `list`
```
>>> d = {'10': -10, 'ZT21': 14, 'WX21': 12, '2': 15, '5': -3, 'UM': -25}
>>> keyorder = ['ZT21', '10', 'WX21', 'UM', '5', '2']
>>> sorted(d.items(), key=lambda i:keyorder.index(i[0]))
[('ZT21', 14), ('10', -10), ('WX21', 12), ('UM',... |
Cross platform interface for virtualenv | 12,033,861 | 10 | 2012-08-20T07:38:30Z | 12,034,416 | 12 | 2012-08-20T08:27:40Z | [
"python",
"django",
"virtualenv",
"cloud-hosting",
"paas"
] | I have developed my entire project (Django, Python) on Windows and all the PaaS out there use Linux.
```
VirtualEnv on Linux:
VirtualEnv_dir /
bin/ activate, activate_this.py
include /
lib /
local /
VirtualEnv of Windows:
VitualEnv_dir /
... | Unless you use some Windows specific libraries; or an alternate Python implementation (like IronPython), there is nothing to worry about.
Many people (including myself) use Windows for development and deploy on Linux for production and use virtualenv for this purpose. It is designed to make your environment portable.
... |
python - TypeError: 'dict' object is not callable | 12,034,296 | 2 | 2012-08-20T08:17:10Z | 12,034,330 | 8 | 2012-08-20T08:20:48Z | [
"python",
"docx",
"typeerror"
] | I am using the python library docx: <http://github.com/mikemaccana/python-docx>
My goal is to open a file, replace certain words, then write the file with replacement.
My current code:
```
#! /usr/bin/python
from docx import *
openDoc = "test.docx"
writeDoc = "test2.docx"
replace = {"Test":"TEST"}
document = open... | You assigned `replace` to a dictionary at the very top:
`replace = {"Test":"TEST"}`
So you cannot use the `replace()` method, because the word `replace` is now pointing to a dictionary - instead of what I suspect is some method from your library.
Rename your dictionary and it should work. |
Get python unit test duration in seconds | 12,034,755 | 6 | 2012-08-20T08:55:00Z | 12,034,838 | 9 | 2012-08-20T09:01:50Z | [
"python",
"unit-testing",
"time"
] | Is there any way to get the total amount of time that "unittest.TextTestRunner().run()" has taken to run a specific unit test.
I'm using a for loop to test modules against certain scenarios (some having to be used and some not, so they run a few times), and I would like to print the total time it has taken to run all ... | **UPDATED**, thanks to @Centralniak's comment.
How about simple
```
from datetime import datetime
tick = datetime.now()
# run the tests here
tock = datetime.now()
diff = tock - tick # the result is a datetime.timedelta object
print(diff.total_seconds())
``` |
How to set rpc timeout in thrift python client? | 12,034,768 | 4 | 2012-08-20T08:55:57Z | 12,739,744 | 9 | 2012-10-05T04:59:08Z | [
"python",
"rpc",
"thrift"
] | I'm writing python client using thrift, but I can't find any available option to set rpc time out.
My client code goes below:
```
socket = TSocket.TSocket(address, port)
transport = TTransport.TBufferedTransport(socket)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
server = Client.Client(protocol)
transport.o... | You can use socket.setTimeout() function.
```
from thrift.transport.THttpClient import THttpClient
socket = THttpClient(server_url)
socket.setTimeout(SERVICE_TIMEOUT_IN_mS)
transport = TTransport.TBufferedTransport(socket)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
``` |
Python:How to prohibit opening of an application if it is already running | 12,036,146 | 6 | 2012-08-20T10:37:08Z | 12,036,216 | 9 | 2012-08-20T10:41:56Z | [
"python",
"wxpython"
] | I am designing a windows utility software for **Windows 7** coded in **Python** with **Wxpython** for *GUI* works.I dont want to open my software if it is already opened.
I want a function like this if user opens that software a message box is to be displayed on windows screen showing that "Your application is already ... | There's already existing wxPython facility that implements wanted logic, called `wx.SingleInstanceChecker`. Here's and example of code (shamelessly borrowed from [wxPython wiki](http://wiki.wxpython.org/OneInstanceRunning)):
```
import wx
class SingleAppFrame(wx.Frame):
def __init__(self, parent, title):
... |
Tab/Enter (and other keystrokes) handling in Kivy's TextInput widgets | 12,037,379 | 7 | 2012-08-20T12:09:36Z | 28,652,466 | 8 | 2015-02-21T23:07:59Z | [
"python",
"kivy"
] | I'm writing an app using Kivy framework and I stumbled upon a minor but annoying problem: I don't know how to handle *Tab/Enter/Arrow* keys in text fields so that pressing either of them would dispatch an event, eg. switch the focus (jump) to another *TextInput* or launch something like `send_form()`
Could anyone plea... | Kivy 1.9 provides the ability to set `write_tab: False` on text inputs ([see docs](http://kivy.org/docs/api-kivy.uix.textinput.html#kivy.uix.textinput.TextInput.write_tab)), causing the tab key to focus on the next focusable widget.
Kivy allows the Enter key to dispatch events by setting `multiline: False` and `on_tex... |
How to check if a zip file is encrypted using python's standard library zipfile? | 12,038,446 | 7 | 2012-08-20T13:18:47Z | 12,038,744 | 7 | 2012-08-20T13:36:18Z | [
"python",
"zip",
"python-2.7",
"zipfile",
"encryption"
] | I am using python's standard library, zipfile, to test an archive:
```
zf = zipfile.ZipFile(archive_name)
if zf.testzip()==None: checksum_OK=True
```
And I am getting this Runtime exception:
```
File "./packaging.py", line 36, in test_wgt
if zf.testzip()==None: checksum_OK=True
File "/usr/lib/python2.7/zipfile... | A quick glance at [the zipfile.py library code](http://hg.python.org/cpython/file/2.7/Lib/zipfile.py) shows that you can check the ZipInfo class's flag\_bits property to see if the file is encrypted, like so:
```
zf = zipfile.ZipFile(archive_name)
for zinfo in zf.infolist():
is_encrypted = zinfo.flag_bits & 0x1
... |
Loading Large File in Python | 12,039,235 | 11 | 2012-08-20T14:08:54Z | 12,039,261 | 12 | 2012-08-20T14:10:22Z | [
"python"
] | I'm using Python 2.6.2 [GCC 4.3.3] running on Ubuntu 9.04. I need to read a big datafile (~1GB, >3 million lines) , line by line using a Python script.
I tried the methods below, I find it uses a very large space of memory (~3GB)
```
for line in open('datafile','r').readlines():
process(line)
```
or,
```
for lin... | ```
with open('datafile') as f:
for line in f:
process(line)
```
This works because files are iterators yielding 1 line at a time until there are no more lines to yield. |
Python: sort list of nested lists according to two criteria | 12,039,459 | 2 | 2012-08-20T14:23:40Z | 12,039,764 | 7 | 2012-08-20T14:39:49Z | [
"python",
"list",
"sorting"
] | In Python, I have a nested list like the following:
```
[ [[x1,y1,z1], [['0.9', 4], [0.8, 3], [0.5, 10], [0.1, 11]],
[[x2,y2,z2], [['1.0', 8], [0.8, 3], [0.2, 1], [0.1, 8]]
...]
```
So each element is in the form:
```
[[3-tuple], [[val1, occurrences_of_val1], [val2, occurrences_of_val2],...]]
```
The second nes... | `yourList.sort(key=lambda x: x[1], reverse=True)` |
Finding the corresponding item in two tuples with Python | 12,040,199 | 2 | 2012-08-20T15:06:12Z | 12,040,225 | 12 | 2012-08-20T15:07:50Z | [
"python",
"python-3.x",
"tuples"
] | I have a list of tuples containing data, and another corresponding tuple containing some header information. Based on the header, I would like to extract a specific value from a given element in the list. Example:
```
>>> hdr = ("a", "b", "c", "d", "e")
>>> elt = (1, 2, 3, 4, 5)
>>> my_func(elt, "c")
3
```
The key he... | Easiest?
```
dict(zip(hdr, elt))["c"]
```
An alternative would be:
```
elt[hdr.index("c")]
```
However building a `dict` (as per the first suggestion) would be more efficient if you're making repeated searches. |
How to avoid blocking code in python with gevent? | 12,040,880 | 8 | 2012-08-20T15:45:36Z | 12,041,101 | 12 | 2012-08-20T16:00:37Z | [
"python",
"nonblocking",
"gevent"
] | I am playing around with gevent, and I am trying to understand why my code is blocking and how I can fix it.
I have a pool of greenlets, and each of them talk to a thrift client which gathers data from a remote thrift server. For the purpose of the exercise, the thrift server always take > 1s to return any data.
When ... | Greenlets never run in parallel, they all share the same process and the same thread, so, there is at most one of them running at a time.
Greenlets are green because they are co-routines ("co" from cooperation), thus, it can not even be said that they run concurrently, because you need to coordinate their running. Gev... |
Printing all the values from multiple lists at the same time | 12,040,989 | 2 | 2012-08-20T15:52:18Z | 12,041,023 | 7 | 2012-08-20T15:54:50Z | [
"python",
"list"
] | Suppose I have 3 lists such as these
```
l1 = [1,2,3]
l2 = [4,5,6]
l3 = [7,8,9]
```
how do I get to print out everything from these lists at the same time ?
What's the pythonic way to do something like that ?
```
for f in l1,l2 and l3:
print f
```
This only seems to be taking 2 lists into account.
Desired outp... | I think you might want `zip`:
```
for x,y,z in zip(l1,l2,l3):
print x,y,z #1 4 7
#2 5 8
#3 6 9
```
What you're doing:
```
for f in l1,l2 and l3:
```
is a little strange. It is basically equivalent to `for f in (l1,l3):` since `l2 and l3` returns `l3` (assuming that `l2` and `l... |
A system independent way using python to get the root directory/drive on which python is installed | 12,041,525 | 23 | 2012-08-20T16:32:44Z | 12,041,606 | 14 | 2012-08-20T16:38:36Z | [
"python",
"path",
"operating-system",
"cross-platform"
] | For Linux this would give me `/`, for Windows on the C drive that would give me `C:\\`. Note that python is not necessarily installed on the C drive on windows. | You can get the path to the Python executable using `sys.executable`:
```
>>> import sys
>>> import os
>>> sys.executable
'/usr/bin/python'
```
Then, for Windows, the drive letter will be the first part of splitdrive:
```
>>> os.path.splitdrive(sys.executable)
('', '/usr/bin/python')
``` |
A system independent way using python to get the root directory/drive on which python is installed | 12,041,525 | 23 | 2012-08-20T16:32:44Z | 22,255,432 | 41 | 2014-03-07T16:26:24Z | [
"python",
"path",
"operating-system",
"cross-platform"
] | For Linux this would give me `/`, for Windows on the C drive that would give me `C:\\`. Note that python is not necessarily installed on the C drive on windows. | Try this:
```
import os
def root_path():
return os.path.abspath(os.sep)
```
On Linux this returns '/'
On Windows this returns 'C:\' or whatever the current drive is |
"after" looping indefinitely: never entering mainloop | 12,043,693 | 7 | 2012-08-20T19:15:51Z | 12,043,756 | 17 | 2012-08-20T19:20:00Z | [
"python",
"event-handling",
"tkinter",
"tetris"
] | This is my first post. I started coding when considering a career swap two months ago and am working on a Tetris clone. I've implemented most of the core features, but cannot get the game to refresh continually with an after loop.
I'm using Tkinter to produce my Gui and am trying out event oriented programming.
My un... | You want to do `self.frame.after(500, self.updateBoard)`.
The difference here is subtle, (`self.updateBoard` instead of `self.updateBoard()`). In your version, you're passing the *result of your function* to the `after` method instead of passing the *function*. This results in the infinite recursion that you described... |
Python and Powers Math | 12,043,913 | 13 | 2012-08-20T19:31:45Z | 12,043,929 | 10 | 2012-08-20T19:33:14Z | [
"python",
"math",
"multiplication",
"exponents"
] | I've been learning Python but I'm a little confused. Online instructors tell me to use the operator \*\* as opposed to ^ when I'm trying to raise to a certain number. Example:
```
print 8^3
```
Gives an output of 11. But what I'm look for (I'm told) is more akin to: print 8\*\*3 which gives the correct answer of 512.... | The symbols represent different operators.
[The `^` represents the bitwise exclusive or (`XOR`)](http://wiki.python.org/moin/BitwiseOperators).
> Each bit of the output is the same as the corresponding bit in x if
> that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.
`**` represents th... |
Python and Powers Math | 12,043,913 | 13 | 2012-08-20T19:31:45Z | 12,043,968 | 28 | 2012-08-20T19:35:35Z | [
"python",
"math",
"multiplication",
"exponents"
] | I've been learning Python but I'm a little confused. Online instructors tell me to use the operator \*\* as opposed to ^ when I'm trying to raise to a certain number. Example:
```
print 8^3
```
Gives an output of 11. But what I'm look for (I'm told) is more akin to: print 8\*\*3 which gives the correct answer of 512.... | Operator `^` is a *bitwise operator*, which does **"bitwise exclusive or"**.
More: <http://wiki.python.org/moin/BitwiseOperators>
The power operator is `**`, like **`8**3`** which equals to `512`.
Ref: <http://docs.python.org/reference/expressions.html#the-power-operator> |
ImportError: No module named pysqlite2 | 12,044,548 | 8 | 2012-08-20T20:21:10Z | 12,044,582 | 16 | 2012-08-20T20:23:18Z | [
"python",
"sqlite",
"pysqlite"
] | Why does
```
from pysqlite2 import dbapi2 as sqlite
```
cause
> ImportError: No module named pysqlite2
Isn't pysqlite2 already installed in Python 2.6.5? | The module is called `sqlite3`. `pysqlite2` was the module's name before it became part of the Python standard library.
You probably want to use this in your code:
```
import sqlite3
```
And the standard documentation is here: <http://docs.python.org/library/sqlite3.html>
edit: And just to cover all the bases:
The... |
How to use Flask-SQLAlchemy in a Celery task | 12,044,776 | 17 | 2012-08-20T20:38:53Z | 14,146,403 | 40 | 2013-01-03T20:07:57Z | [
"python",
"flask",
"celery",
"flask-sqlalchemy"
] | I recently switch to Celery 3.0. Before that I was using [Flask-Celery](https://github.com/ask/flask-celery/) in order to integrate Celery with Flask. Although it had many issues like hiding some powerful Celery functionalities but it allowed me to use the full context of Flask app and especially Flask-SQLAlchemy.
In ... | ### Update: We've since started using a better way to handle application teardown and set up on a per-task basis, based on the pattern described [in the more recent flask documentation](http://flask.pocoo.org/docs/0.10/patterns/celery/).
extensions.py
```
import flask
from flask.ext.sqlalchemy import SQLAlchemy
from ... |
What happens if I attribute a second instance of a class with the same variable holding an existing instance? | 12,045,539 | 4 | 2012-08-20T21:35:07Z | 12,045,697 | 13 | 2012-08-20T21:48:38Z | [
"python",
"class",
"variables",
"instantiation"
] | I'm not sure how to ask the question other than by example.
Lets say I have a class:
```
class Foo():
pass
```
and I create an instance of it:
```
foo = Foo()
...
```
then, as part of my program, I recreate the same instance with the same name (to restart a game but keeping a score total in yet another, se... | Let me try to explain it graphically.
When you do
```
foo = Foo()
```
for the first time, you are creating an *object* of type `Foo` in memory (with `Foo()`) and, at the same time, creating a *variable* which will point to this object:

When you ex... |
SQLAlchemy boolean value is None | 12,045,698 | 11 | 2012-08-20T21:48:39Z | 12,045,897 | 22 | 2012-08-20T22:06:50Z | [
"python",
"sqlalchemy",
"pyramid"
] | I have this table in my Pyramid app
```
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
.....
is_active = Column(Boolean, unique=False)
def __init__(self, name, raw_password):
is_active = True
```
When I did my test, it said `is_active` is None.
```
def te... | You have to set a default value otherwise None/NULL is used:
```
is_active = Column(Boolean, unique=False, default=True)
```
You wanted to do this in `__init__` but you used `is_active = True` (a local variable) instead of `self.is_active = True`. |
Babel doesn't recognize jinja2 extraction method for language support | 12,046,998 | 2 | 2012-08-21T00:28:37Z | 13,471,618 | 8 | 2012-11-20T10:50:58Z | [
"python",
"translation",
"jinja2",
"babel"
] | I'm adding language translation support to my project. The code is on Python and has jinja2 in the html files, and Javascript.
I'm trying to use Babel to do the translation, but it doesn't recognize the extraction method of jinja2. Maybe I'm using an incorrect name for it.
This is my ini file:
```
# Extraction from ... | I saw that your question was still unanswered. Your problem looks similar to what I got after reinstalling my development environment:
```
$ pybabel extract -F babel.cfg -o messages.pot .
extracting messages from admin.py
:
extracting messages from templates/404.html (extensions="jinja2.ext.autoescape,jinja2.ext.with_... |
How to convert SQL Query result to PANDAS Data Structure? | 12,047,193 | 32 | 2012-08-21T01:02:02Z | 12,056,933 | 15 | 2012-08-21T14:20:22Z | [
"python",
"mysql",
"data-structures",
"pandas"
] | Any help on this problem will be greatly appreciated. So basically I want to run a query to my SQL database and store the returned data as Pandas data structure. I have attached code for query. I am reading the documentation on Pandas, but I have problem to identify the return type of my query. I tried to print the que... | ### Edit 2014-09-30:
pandas now has a `read_sql` function. You definitely want to use that instead.
### Original answer:
I can't help you with SQLAlchemy -- I always use pyodbc, MySQLdb, or psychopg2 as needed. But when doing so, a function as simple as the one below tends to suit my needs:
```
import decimal
impo... |
How to convert SQL Query result to PANDAS Data Structure? | 12,047,193 | 32 | 2012-08-21T01:02:02Z | 12,060,886 | 30 | 2012-08-21T18:28:30Z | [
"python",
"mysql",
"data-structures",
"pandas"
] | Any help on this problem will be greatly appreciated. So basically I want to run a query to my SQL database and store the returned data as Pandas data structure. I have attached code for query. I am reading the documentation on Pandas, but I have problem to identify the return type of my query. I tried to print the que... | Here's the shortest code that will do the job:
```
from pandas import DataFrame
df = DataFrame(resoverall.fetchall())
df.columns = resoverall.keys()
```
You can go fancier and parse the types as in Paul's answer. |
How to convert SQL Query result to PANDAS Data Structure? | 12,047,193 | 32 | 2012-08-21T01:02:02Z | 14,487,936 | 43 | 2013-01-23T19:38:02Z | [
"python",
"mysql",
"data-structures",
"pandas"
] | Any help on this problem will be greatly appreciated. So basically I want to run a query to my SQL database and store the returned data as Pandas data structure. I have attached code for query. I am reading the documentation on Pandas, but I have problem to identify the return type of my query. I tried to print the que... | **Edit: Mar. 2015**
As noted below, pandas now uses [SQLAlchemy](http://www.sqlalchemy.org/) to both read from ([read\_sql](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.read_sql.html)) and insert into ([to\_sql](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_sql.html)) a database. ... |
How to convert SQL Query result to PANDAS Data Structure? | 12,047,193 | 32 | 2012-08-21T01:02:02Z | 19,031,661 | 22 | 2013-09-26T14:56:11Z | [
"python",
"mysql",
"data-structures",
"pandas"
] | Any help on this problem will be greatly appreciated. So basically I want to run a query to my SQL database and store the returned data as Pandas data structure. I have attached code for query. I am reading the documentation on Pandas, but I have problem to identify the return type of my query. I tried to print the que... | If you are using SQLAlchemy's ORM rather than the expression language, you might find yourself wanting to convert an object of type `sqlalchemy.orm.query.Query` to a Pandas data frame.
Here is one way to do it, starting with a Query object called 'query':
```
data_records = [rec.__dict__ for rec in query.all()]
df = ... |
'super' object not calling __getattr__ | 12,047,847 | 13 | 2012-08-21T02:50:39Z | 12,048,087 | 10 | 2012-08-21T03:31:14Z | [
"python",
"getattr"
] | I have one object wrapped inside another.
The "Wrapper" accesses the attributes from the "Wrapped" object by overriding `__getattr__`.
This works well until I need to override an atribute on a sub class, and then access the attribute from the base class using `super()`.
I can still access the attribute directly from `... | [According to this,](http://www.gossamer-threads.com/lists/python/python/159397?do=post_view_threaded) super does not allow implicit calls of "hook" functions such as `__getattr__`. I'm not sure why it is implemented this way (there's probably a good reason and things are already confusing enough since the super object... |
How can I rename a column label in Django Admin for a field that is a method//property? | 12,048,176 | 4 | 2012-08-21T03:45:48Z | 12,048,244 | 23 | 2012-08-21T03:56:18Z | [
"python",
"django",
"unicode",
"admin"
] | I am trying to redefine my admin page for the `auth.User` model.
Everything is working properly, except for one thing. Check the code below:
```
from django.contrib import admin
from django.contrib.auth.models import User
from access.models import UserProfile
class UserProfileInline(admin.StackedInline):
model =... | Set an attribute in your function called `short_description` to your desired label in your model definition.
```
# note, this must be done in the class definition;
# not User.get_full_name.short_description
get_full_name.short_description = 'my label'
```
Alternatively, if you don't want to pollute your model with ad... |
python numpy vector math | 12,049,154 | 6 | 2012-08-21T06:01:49Z | 12,051,080 | 14 | 2012-08-21T08:39:55Z | [
"python",
"numpy"
] | What is the `numpy` equivalent to [`euclid`](https://pypi.python.org/pypi/euclid)'s 2d vector classes / operations ? ( like: `euclid.Vector2` )
So far I have this. Create two vectors
```
import numpy as np
loc = np.array([100., 100.])
vel = np.array([30., 10])
loc += vel
# reseting speed to a default value, mainta... | You can just use numpy arrays. Look at the [numpy for matlab users](http://www.scipy.org/NumPy_for_Matlab_Users#head-e9a492daa18afcd86e84e07cd2824a9b1b651935) page for a detailed overview of the pros and cons of arrays w.r.t. matrices.
As I mentioned in the comment, having to use the `dot()` function or method for mut... |
scrapy log issue | 12,049,770 | 3 | 2012-08-21T06:57:31Z | 12,124,473 | 7 | 2012-08-25T18:14:49Z | [
"python",
"python-2.7",
"scrapy",
"scrapyd"
] | i have multiple spiders in one project , problem is right now i am defining **LOG\_FILE** in SETTINGS like
```
LOG_FILE = "scrapy_%s.log" % datetime.now()
```
what i want is `scrapy_SPIDERNAME_DATETIME`
but i am unable to provide spidername in log\_file name ..
i found
```
scrapy.log.start(logfile=None, loglevel=N... | The spider's `__init__()` is not early enough to call `log.start()` by itself since the log observer is already started at this point; therefore, you need to reinitialize the logging state to trick Scrapy into (re)starting it.
In your spider class file:
```
from datetime import datetime
from scrapy import log
from sc... |
Force the Y axis to only use integers | 12,050,393 | 5 | 2012-08-21T07:48:30Z | 12,051,323 | 7 | 2012-08-21T08:53:38Z | [
"python",
"matplotlib",
"axis-labels"
] | I'm plotting a histogram using the matplotlib.pyplot module and I am wondering how I can force the y-axis labels to only show integers (e.g. 0, 1, 2, 3 etc.) and not decimals (e.g. 0., 0.5, 1., 1.5, 2. etc.).
I'm looking at the guidance notes and suspect the answer lies somewhere around [matplotlib.pyplot.ylim](http:/... | If you have the y-data
```
y = [0., 0.5, 1., 1.5, 2., 2.5]
```
You can use the maximum and minimum values of this data to create a list of natural numbers in this range. For example,
```
import math
print range(math.floor(min(y)), math.ceil(max(y))+1)
```
yields
```
[0, 1, 2, 3]
```
You can then set the y tick ma... |
Neural Network training with PyBrain won't converge | 12,050,460 | 29 | 2012-08-21T07:53:49Z | 12,050,816 | 33 | 2012-08-21T08:23:06Z | [
"python",
"neural-network",
"pybrain"
] | I have the following code, from the PyBrain tutorial:
```
from pybrain.datasets import SupervisedDataSet
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure.modules import TanhLayer
ds = SupervisedDataSet(2, 1)
ds.addSample((0,0), (0,))
ds.ad... | After some more digging I found that the example on the PyBrain's tutorial is completely out of place.
When we look at the method signature in the source code we find:
```
def trainUntilConvergence(self, dataset=None, maxEpochs=None, verbose=None, continueEpochs=10, validationProportion=0.25):
```
This means that 25... |
Neural Network training with PyBrain won't converge | 12,050,460 | 29 | 2012-08-21T07:53:49Z | 20,486,148 | 16 | 2013-12-10T04:30:43Z | [
"python",
"neural-network",
"pybrain"
] | I have the following code, from the PyBrain tutorial:
```
from pybrain.datasets import SupervisedDataSet
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure.modules import TanhLayer
ds = SupervisedDataSet(2, 1)
ds.addSample((0,0), (0,))
ds.ad... | I took the excellent [Machine Learning class on Coursera](https://www.coursera.org/course/ml), taught by Andrew Ng, and one part of the class covered training a small neural net to recognize xor. So I was a bit troubled by the pybrain example based on parts of the [quickstart](http://pybrain.org/docs/#quickstart) that ... |
Using Multiple Installations of Celery with a Redis Backend | 12,052,094 | 8 | 2012-08-21T09:39:29Z | 15,874,270 | 9 | 2013-04-08T08:12:43Z | [
"python",
"redis",
"celery"
] | Is it possible to use the same redis database for multiple projects using celery? Like using the same database for multiple projects as a cache using a key prefix. Or do i have to use a seperate database for every installation? | To summarise from this helpful blog post: <http://kfalck.net/2013/02/21/run-multiple-celeries-on-a-single-redis>
* Specify a different database number for each project, e.g. redis://localhost/0 and redis://localhost/1
* Define and use different queue names for the different projects. On the task side, define CELERY\_D... |
Matplotlib: draw a selection area in the shape of a rectangle with the mouse | 12,052,379 | 4 | 2012-08-21T09:54:59Z | 12,057,517 | 14 | 2012-08-21T14:49:12Z | [
"python",
"matplotlib",
"mouse",
"selection",
"matplotlib-basemap"
] | I want to be able to draw a selection area on a matplotlib plot with a mouse event. I didn't find information on how to do it with python.
In the end, I want to be able to draw a region of interest with my mouse on a map created with matplotlib basemap and retrieve the corner coordinates.
Anyone has an idea, example,... | Here's a small example that shows how to use the mouse to draw a rectangle on a matplotlib plot.
```
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
class Annotate(object):
def __init__(self):
self.ax = plt.gca()
self.rect = Rectangle((0,0), 1, 1)
self.x0 = None
... |
Test a string if it's Unicode, which UTF standard is and get its length in bytes? | 12,053,107 | 7 | 2012-08-21T10:37:10Z | 12,053,219 | 13 | 2012-08-21T10:44:57Z | [
"python",
"string",
"unicode",
"utf-8",
"python-2.5"
] | I need to test if a string is Unicode, and then if it whether it's UTF-8. After that, get the string's length in bytes including the [BOM](http://en.wikipedia.org/wiki/Byte_order_mark), if it ever uses that. How can this be done in Python?
Also for didactic purposes, what does a byte list representation of a UTF-8 str... | ```
try:
string.decode('utf-8')
print "string is UTF-8, length %d bytes" % len(string)
except UnicodeError:
print "string is not UTF-8"
```
In Python 2, `str` is a sequence of bytes and `unicode` is a sequence of characters. You use `str.decode` to decode a byte sequence to `unicode`, and `unicode.encode` ... |
Python equivalent for PHP's implode? | 12,053,236 | 34 | 2012-08-21T10:46:08Z | 12,053,276 | 88 | 2012-08-21T10:48:17Z | [
"php",
"python",
"implode"
] | Is there an equivalent for PHP's implode in Python? I've read in and split up a set of delimited words, and now I want to sort them out in random orders and print the words out with spaces in between.
> implode â Join array elements with a string
<http://php.net/manual/en/function.implode.php> | Use the strings [join-method](https://docs.python.org/2/library/stdtypes.html#str.join).
```
print ' '.join(['word1', 'word2', 'word3'])
```
You can join any iterable (not only the `list` used here) and of course you can use any string (not only `' '`) as the delimiter.
If you want a random order like you said in yo... |
Previous weekday in Python | 12,053,633 | 6 | 2012-08-21T11:14:07Z | 12,053,711 | 17 | 2012-08-21T11:20:03Z | [
"python",
"date",
"weekday"
] | In Python, given a date, how do I find the preceding weekday? (Weekdays are Mon to Fri. I don't care about holidays) | Simply subtract a day from the given date, then check if the date is a weekday. If not, subtract another, until you do have a weekday:
```
from datetime import date, timedelta
def prev_weekday(adate):
adate -= timedelta(days=1)
while adate.weekday() > 4: # Mon-Fri are 0-4
adate -= timedelta(days=1)
... |
where should I define functions that i use in __init__ | 12,053,998 | 4 | 2012-08-21T11:37:48Z | 12,054,066 | 9 | 2012-08-21T11:41:33Z | [
"python",
"function"
] | I'm writing a class that makes use of some functions inside its `__init__` function and I'm not sure about the best practice of where to define those functions. I usually like to define `__init__` first but if I need to use the a function/method within the `__init__` then it needs to be defined first. I dont want to de... | Just add the methods to your class like every other method
```
class Test(object):
def __init__(self):
self.hi()
def hi(self):
print "Hi!"
```
No problem at all.
While it is not mentioned in the [Python Style Guide](http://www.python.org/dev/peps/pep-0008/) IIRC, it's convention to let `__in... |
Django: How to change a field widget in a Inline Formset | 12,054,726 | 7 | 2012-08-21T12:21:41Z | 30,192,034 | 8 | 2015-05-12T13:14:46Z | [
"python",
"django",
"forms",
"inline-formset"
] | I am new to Django and I think I am missing this in the docs.
The problem is that in inline-formset I dont declare a form, just pass two models to construct it.
I want to know how can I change a widget of a single field using inline formset? | [As of Django 1.6](https://docs.djangoproject.com/en/1.6/topics/forms/modelforms/#specifying-widgets-to-use-in-the-form-with-widgets), you can use the `widgets` parameter of `modelformset_factory` in order to customize the widget of a particular field:
```
AuthorFormSet = modelformset_factory(Author, widgets={
'na... |
Scrapy:How to print request referrer | 12,054,958 | 7 | 2012-08-21T12:34:58Z | 12,055,059 | 18 | 2012-08-21T12:40:45Z | [
"python",
"scrapy"
] | Is it possible to get the request referrer from the response object in parse function?
10x | HTTP `Referer` field is set up by HTTP client in request headers, **not in response headers**, as this header tells server where did client come from to current page.
It would be rather wierd to receive http `Referer` header in response.
But when talking about scrapy, there's a reference to `Request` object on which ... |
How to generate a continuous string? | 12,055,601 | 5 | 2012-08-21T13:11:12Z | 12,055,669 | 27 | 2012-08-21T13:15:03Z | [
"python",
"string",
"generator",
"brute-force",
"alphanumeric"
] | I want to generate, in python (without a dictionary), a list of string from aaa-zzz and then output a txtfile such as this (note, the ... is short for the strings in between):
```
aaa
aab
aac
aad
...
aaz
aba
abb
abc
abd
...
aaz
...
zaa
...
zzy
zzz
```
The harder challenge is to genrate alternating (upper and lower) s... | ```
import itertools, string
map(''.join, itertools.product(string.ascii_lowercase, repeat=3))
map(''.join, itertools.product(string.ascii_letters, repeat=3))
map(''.join, itertools.product(string.ascii_letters + string.digits, repeat=3))
``` |
Python: Using popen poll on background process | 12,057,794 | 11 | 2012-08-21T15:02:32Z | 12,057,918 | 8 | 2012-08-21T15:08:35Z | [
"python",
"python-3.x",
"popen",
"subprocess"
] | I am running a long process (actually another python script) in the background. I need to know when it has finished. I have found that `Popen.poll()` always returns 0 for a background process. Is there another way to do this?
```
p = subprocess.Popen("sleep 30 &", shell=True,
stdout=subprocess.PIPE, stderr=subproc... | You shouldn't run your script with ampersand at the end. Because shell forks your process and returns 0 exit code. |
Python: Using popen poll on background process | 12,057,794 | 11 | 2012-08-21T15:02:32Z | 12,058,609 | 22 | 2012-08-21T15:49:03Z | [
"python",
"python-3.x",
"popen",
"subprocess"
] | I am running a long process (actually another python script) in the background. I need to know when it has finished. I have found that `Popen.poll()` always returns 0 for a background process. Is there another way to do this?
```
p = subprocess.Popen("sleep 30 &", shell=True,
stdout=subprocess.PIPE, stderr=subproc... | You don't need to use the shell backgrounding `&` syntax, as `subprocess` will run the process in the background by itself
Just run the command normally, then wait until `Popen.poll` returns `not None`
```
import time
import subprocess
p = subprocess.Popen("sleep 30", shell=True)
# Better: p = subprocess.Popen(["sle... |
How use libtorrent for python to get info_hash | 12,058,802 | 4 | 2012-08-21T16:00:40Z | 13,102,689 | 7 | 2012-10-27T17:57:57Z | [
"python",
"libtorrent"
] | ```
from libtorrent as lt
info = lt.torrent_info(open('example.torrent','rb').read())
info.info_hash()
```
This doesn't get the hash, instead I get the object `<libtorrent.big_number object at ...... >`
What should I do? | The existing answers give you everything you need ... but here's some code to make it explicit:
```
import libtorrent as lt
info = lt.torrent_info(open('example.torrent','rb').read())
info_hash = info.info_hash()
hexadecimal = str(info_hash)
integer = int(hexadecimal, 16)
```
**EDIT**: Actually, that's wrong - `torre... |
Create a single executable from a Python project | 12,059,509 | 26 | 2012-08-21T16:47:58Z | 12,059,635 | 7 | 2012-08-21T16:58:43Z | [
"python",
"compilation",
"exe",
"packaging",
"software-distribution"
] | I want to create a single executable from my Python project. A user should be able to download and run it without needing Python installed. If I were just distributing a package, I could use pip, wheel, and PyPI to build and distribute it, but this requires that the user has Python and knows how to install packages. Wh... | [pyinstaller](http://www.pyinstaller.org/) is still under active development. You can see [the latest changes](https://github.com/pyinstaller/pyinstaller/commits/develop) on GitHub.
It has support for all three major platforms:
* Windows (32-bit and 64-bit)
* Linux (32-bit and 64-bit)
* Mac OS X (32-bit and 64-bit)
... |
Create a single executable from a Python project | 12,059,509 | 26 | 2012-08-21T16:47:58Z | 12,059,644 | 32 | 2012-08-21T16:59:25Z | [
"python",
"compilation",
"exe",
"packaging",
"software-distribution"
] | I want to create a single executable from my Python project. A user should be able to download and run it without needing Python installed. If I were just distributing a package, I could use pip, wheel, and PyPI to build and distribute it, but this requires that the user has Python and knows how to install packages. Wh... | Here are some common ones. Unless explicitly noted, all projects listed below are being actively maintained as of my last edit (January 2016).
I've also included links to their respective repos, in case you want to check for yourself on how frequently they've been updated.
Also, unless otherwise noted, all programs l... |
Python subprocess.call a bash alias | 12,060,863 | 6 | 2012-08-21T18:26:41Z | 12,060,888 | 12 | 2012-08-21T18:28:36Z | [
"python",
"bash",
"subprocess"
] | At work there's a script that lists completed tasks. This was written by someone else and is hosted over the network. I have an alias in my .bashrc that calls this script, with its many flags and such, and I wanted to write a python script that would call this alias every few minutes so I can have a shell open with upd... | You need to set the `shell` keyword to True:
```
call("myAlias", shell=True)
```
From the [relevant documentation](http://docs.python.org/library/subprocess.html#frequently-used-arguments):
> If `shell` is `True`, the specified command will be executed through the shell. This can be useful if you are using Python pr... |
Python subprocess.call a bash alias | 12,060,863 | 6 | 2012-08-21T18:26:41Z | 25,099,813 | 19 | 2014-08-02T22:03:01Z | [
"python",
"bash",
"subprocess"
] | At work there's a script that lists completed tasks. This was written by someone else and is hosted over the network. I have an alias in my .bashrc that calls this script, with its many flags and such, and I wanted to write a python script that would call this alias every few minutes so I can have a shell open with upd... | If the alias you require is defined in ~/.bashrc, then it won't get run for a few reasons:
1) You must give the 'shell' keyword arg:
```
subprocess.call('command', shell=True)
```
Otherwise your given command is used to find an executable file, rather than passed to a shell, and it is the shell which expands things ... |
Best way to share code across several setup.py scripts? | 12,060,925 | 4 | 2012-08-21T18:31:16Z | 12,061,891 | 8 | 2012-08-21T19:40:32Z | [
"python",
"setuptools"
] | I've got several packages I'm working on, and I'd like to share code between their setup.py scripts. Is there any good way to do this or is code duplication my only option? | Normally `setup.py` is the entry point for distribution of distinct packages. As such, it's hard to then share code between those packages.
If you use [`setuptools`](http://pypi.python.org/pypi/setuptools) (or it's fork, [`distribute`](http://pypi.python.org/pypi/distribute/)) in your `setup.py`, you *can* specify pac... |
How do I specify the literal generator type in Python? | 12,061,966 | 3 | 2012-08-21T19:47:00Z | 12,061,992 | 7 | 2012-08-21T19:48:37Z | [
"python",
"generator",
"assert",
"literals"
] | I need to check if a certain variable is a generator object.
How would I specify the literal generator type in place of the ??? below?
```
def go():
for i in range(999):
yield i
la = go()
print repr(type(la))
<type 'generator'>
assert type(la) == ???
``` | Use `types.GeneratorType` (from the `types` module). You should think, though, about why you're doing this. It's usually better to avoid explicit type-checking and just try iterating over the object and see if it works. |
Breaking 1 String into 2 Strings based on special characters using python | 12,062,151 | 3 | 2012-08-21T20:00:15Z | 12,062,171 | 12 | 2012-08-21T20:01:38Z | [
"python",
"string",
"character",
"substring"
] | I am working with python and I am new to it. I am looking for a way to take a string and split it into two smaller strings. An example of the string is below
```
wholeString = '102..109'
```
And what I am trying to get is:
```
a = '102'
b = '109'
```
The information will always be separated by two periods like show... | Try this:
```
a, b = wholeString.split('..')
```
It'll put each value into the corresponding variables. |
How do I create an image in PIL using a list of RGB tuples? | 12,062,920 | 12 | 2012-08-21T20:55:30Z | 12,063,264 | 17 | 2012-08-21T21:23:53Z | [
"python",
"python-imaging-library"
] | Suppose I have a list of pixels (represented as tuples with 3 RGB values) in a list that looks like `list(im.getdata())`, like this:
```
[(0,0,0),(255,255,255),(38,29,58)...]
```
How do I create a new image using RGB values (each tuple corresponds to a pixel) in this format?
Thanks for your help. | You can do it like this:
```
list_of_pixels = list(im.getdata())
# Do something to the pixels...
im2 = Image.new(im.mode, im.size)
im2.putdata(list_of_pixels)
``` |
Where is the Gunicorn config file? | 12,063,463 | 8 | 2012-08-21T21:39:41Z | 13,340,800 | 8 | 2012-11-12T09:03:16Z | [
"python",
"flask",
"gunicorn"
] | The gunicorn documentation talks about editing the config files, but I have no idea where it is.
Probably a simple answer :) I'm on Amazon Linux AMI. | The answer is in the documentation of gunicorn.
<http://docs.gunicorn.org/en/latest/configure.html>
You can specify the config file with .ini or a python script.
For example, from the django-skel project
```
"""gunicorn WSGI server configuration."""
from multiprocessing import cpu_count
from os import environ
def ... |
Pymongo, query on list field, and/or | 12,064,764 | 5 | 2012-08-22T00:09:42Z | 12,064,888 | 20 | 2012-08-22T00:29:56Z | [
"python",
"mongodb",
"pymongo"
] | I have a collection with some documents like:
```
{
_id: 5,
vals: [100, 1100, 1500]
},
{
_id: 10,
vals: [1100, 1700]
}
```
How can I query for documents that have, in `vals` field:
* 1100
* 1700 OR 100
* 100 AND 1100
I can use some comprehension magic like:
```
g = lambda codes: (
d for d in co... | ```
yourmongocoll.find({"vals":1100})
yourmongocoll.find({"$or":[ {"vals":1700}, {"vals":100}]})
yourmongocoll.find({"$and":[ {"vals":100}, {"vals":1100}]})
```
i would recommend reading [Mongodb Advanced queries](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24in)
you will also find [$in](htt... |
itertools: Cartesian product of permutations | 12,064,780 | 3 | 2012-08-22T00:11:51Z | 12,064,810 | 10 | 2012-08-22T00:17:11Z | [
"python",
"permutation",
"itertools",
"cartesian-product"
] | Using pythons `itertools`, I'd like to create an iterator over the outer product of all permutations of a bunch of lists. An explicit example:
```
import itertools
A = [1,2,3]
B = [4,5]
C = [6,7]
for x in itertools.product(itertools.permutations(A),itertools.permutations(B),itertools.permutations(C)):
print x
```... | You missed the `*` to unpack the list into 3 arguments
```
itertools.product(*map(itertools.permutations,[A,B,C]))
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.