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: Making a dict from tuple keys with multiple values from a nested list | 19,675,998 | 2 | 2013-10-30T07:13:29Z | 19,676,091 | 7 | 2013-10-30T07:18:23Z | [
"python",
"dictionary",
"tuples",
"nested-lists",
"dictionary-comprehension"
] | I am new to python and I am trying to make a dictionary using tuples as keys and a nested list as multiple values.
The list is nested in triplets; `[[[Isolation source],[host],[country]]...etc]`
example below:
```
value_list = [[['NaN'], ['sponge'], ['Palau']], [['skin'], ['fish'], ['Cuba']], [['claw'], ['crab'], ['... | You can use `itertools.chain.from_iterable`, `itertools.izip` (or `zip`) and a dict comprehension:
```
>>> from itertools import chain, izip
>>> value_list = [[['NaN'], ['sponge'], ['Palau']], [['skin'], ['fish'], ['Cuba']], [['claw'], ['crab'], ['Japan: Aomori, Natsudomari peninsula']]]
>>> key_tuple = ('AB479448', '... |
Numpy array assignment with copy | 19,676,538 | 22 | 2013-10-30T07:44:25Z | 19,676,652 | 8 | 2013-10-30T07:52:53Z | [
"python",
"arrays",
"numpy"
] | For example, if we have a numpy array `A`, and we want a numpy array `B` with the same elements.
What is difference between these methods? When is additional memory allocated, and when is it not?
1. `B = A`
2. `B[:] = A` (same as `B[:]=A[:]`?)
3. `numpy.copy(B, A)` | 1. `B=A` creates a reference
2. `B[:]=A` makes a deep copy
3. `numpy.copy(B,A)` makes a copy
the last two need additional memory.
EDIT: Take a look at this [Question](http://stackoverflow.com/questions/6431973/how-to-copy-data-from-a-numpy-array-to-another?rq=1) |
Numpy array assignment with copy | 19,676,538 | 22 | 2013-10-30T07:44:25Z | 19,676,762 | 27 | 2013-10-30T07:59:38Z | [
"python",
"arrays",
"numpy"
] | For example, if we have a numpy array `A`, and we want a numpy array `B` with the same elements.
What is difference between these methods? When is additional memory allocated, and when is it not?
1. `B = A`
2. `B[:] = A` (same as `B[:]=A[:]`?)
3. `numpy.copy(B, A)` | All three versions do different things.
1. This binds a new name `B` to the existing object already named `A`. Afterwards they refer to the same object, so if you modify one in place, you'll see the change through the other one too.
2. This copies the values from `A` into an existing array `B`. The two arrays must hav... |
How to run WindowCommand plugin from `sublime console` | 19,677,478 | 3 | 2013-10-30T08:41:51Z | 19,678,290 | 8 | 2013-10-30T09:23:01Z | [
"python",
"plugins",
"sublimetext2",
"sublimetext",
"sublimetext3"
] | I created plugin for `sublime text 3` with 3 commands:
2 of them are of type `TextCommand`, one of them is `WindowCommand`
```
import sublime, sublime_plugin
class simple_text_pluginCommand(sublime_plugin.TextCommand):
def run(self, edit):
print("Hello World simple_text_plugin")
class simple_text_pl... | * `ApplicationCommand`: `sublime.run_command('application_command_name')`. Check `run_command` function for `sublime` module in the [API reference](http://www.sublimetext.com/docs/2/api_reference.html).
* `WindowCommand`: `window.run_command('window_command_name')`. Check `run_command` method of [`sublime.Window`](http... |
How to catch write aborts in python-tornado? | 19,677,777 | 2 | 2013-10-30T08:58:54Z | 19,703,846 | 7 | 2013-10-31T10:22:17Z | [
"python",
"tornado"
] | I want to stream a long database result set through Tornado.
I obviously need a server cursor since its not feasible to load the whole query in memory.
So I have the following code:
```
class QueryStreamer(RequestHandler):
def get(self):
cursor.execute("Select * from ...")
chunk = cursor.fetch(1000)
... | You need to make the handler asynchronous and use `ioloop.add_timeout` instead of `time.sleep`, because that blocks the loop:
```
import tornado.ioloop
import tornado.web
import tornado.gen
class PingHandler(tornado.web.RequestHandler):
connection_closed = False
def on_connection_close(self):
print... |
Count the number of lists using recursion? | 19,680,118 | 4 | 2013-10-30T10:46:31Z | 19,680,163 | 9 | 2013-10-30T10:48:49Z | [
"python",
"recursion"
] | This is what I've tried:
```
def recursive_list_counter(l):
sum = 0
for e in l:
if type(e) == type([]):
#print e
sum += 1
recursive_list_counter(e)
return sum
# should be 6 if I count the first also
recursive_list_counter([[[13, 7], 90], 2, [1, 100, [5, [2]]], ... | Your recursive call *ignores* what is returned. Add the return value:
```
def recursive_list_counter(l):
sum = 0
for e in l:
if isinstance(e, list):
sum += 1
sum += recursive_list_counter(e)
return sum
```
Note that the *outer list* is ignored in the count, so the call retu... |
Count the number of lists using recursion? | 19,680,118 | 4 | 2013-10-30T10:46:31Z | 19,680,184 | 8 | 2013-10-30T10:49:58Z | [
"python",
"recursion"
] | This is what I've tried:
```
def recursive_list_counter(l):
sum = 0
for e in l:
if type(e) == type([]):
#print e
sum += 1
recursive_list_counter(e)
return sum
# should be 6 if I count the first also
recursive_list_counter([[[13, 7], 90], 2, [1, 100, [5, [2]]], ... | For your given example, if all you have are numbers within lists, you can try converting to string and counting the number of `[`
```
>>> li = [[[13, 7], 90], 2, [1, 100, [5, [2]]], 8, 6]
>>> str(li).count('[')
6
``` |
Compile latex from python | 19,683,123 | 5 | 2013-10-30T13:07:51Z | 19,683,545 | 7 | 2013-10-30T13:26:12Z | [
"python",
"compiler-construction",
"latex"
] | I have made some python function for compiling passed string as *pdf* file using latex. The function works as expected and has been quite useful, therefore I look for ways to improve it.
The code which I have:
```
def generate_pdf(pdfname,table):
"""
Generates the pdf from string
"""
import subprocess... | Use a temporary directory. Temporary directories are always writable and can be cleared by the operating system after a restart. `tempfile` library lets you create temporary files and directories in a secure way.
```
path_to_temporary_directory = tempfile.mkdtemp()
# work on the temporary directory
# ...
# move the ne... |
subprocess.Popen : how to pass a list as argument | 19,683,779 | 4 | 2013-10-30T13:35:48Z | 19,683,794 | 13 | 2013-10-30T13:36:24Z | [
"python",
"subprocess",
"popen"
] | I just need a hint on how to do things properly.
Say I have a script called script.py which uses a list of names as argument ["name1", "name2", etc. ].
I want to call this script from another script using the subprocess module. So what I would like to do is the following :
```
myList = ["name1", "name2", "name3"]
su... | Concatenate them using `+` operator.
```
myList = ["name1", "name2", "name3"]
subprocess.Popen(["python", "script.py"] + myList)
```
BTW, if you want use same python program, replace `"python"` with `sys.executable`. |
Why do python programs run very slow the first time? | 19,684,408 | 5 | 2013-10-30T14:02:39Z | 19,684,463 | 8 | 2013-10-30T14:04:45Z | [
"python",
"performance"
] | I have made a simple program, that searches for a particular file in a particular directory.
The problem with the program is that it runs very slow the first time , but very fast as compared to the first time when you run it subsequently. I am pasting a screenshot of the same.I would like to know, why is it so? I hav... | It's nothing to do with Python. The files scanned will still be in the OS's file system cache, so don't require as much disk access as the first run...
You could reproduce with something like:
```
with open('a 100mb or so file') as fin:
filedata = fin.read()
```
On the second run, it's likely the file is still i... |
Best way to check function arguments in Python | 19,684,434 | 19 | 2013-10-30T14:03:34Z | 19,684,493 | 8 | 2013-10-30T14:06:11Z | [
"python",
"function",
"arguments"
] | I'm looking for an efficient way to check variables of a python function. For example, I'd like to check arguments type and value. Is there a module for this? Or should I use something like decorators, or any specific idiom?
```
def my_function(a, b, c):
"""an example function I'd like to check the arguments of.""... | One way is to use `assert`:
```
def myFunction(a,b,c):
"This is an example function I'd like to check arguments of"
assert isinstance(a, int), 'a should be an int'
# or if you want to allow whole number floats: assert int(a) == a
assert b > 0 and b < 10, 'b should be betwen 0 and 10'
assert isinsta... |
Best way to check function arguments in Python | 19,684,434 | 19 | 2013-10-30T14:03:34Z | 19,684,782 | 21 | 2013-10-30T14:16:03Z | [
"python",
"function",
"arguments"
] | I'm looking for an efficient way to check variables of a python function. For example, I'd like to check arguments type and value. Is there a module for this? Or should I use something like decorators, or any specific idiom?
```
def my_function(a, b, c):
"""an example function I'd like to check the arguments of.""... | The most Pythonic idiom is to clearly *document* what the function expects and then just try to use whatever gets passed to your function and either let exceptions propagate or just catch attribute errors and raise a `TypeError` instead. Type-checking should be avoided as much as possible as it goes against duck-typing... |
Best way to check function arguments in Python | 19,684,434 | 19 | 2013-10-30T14:03:34Z | 19,684,962 | 8 | 2013-10-30T14:24:28Z | [
"python",
"function",
"arguments"
] | I'm looking for an efficient way to check variables of a python function. For example, I'd like to check arguments type and value. Is there a module for this? Or should I use something like decorators, or any specific idiom?
```
def my_function(a, b, c):
"""an example function I'd like to check the arguments of.""... | Type checking is generally not Pythonic. In Python, it is more usual to use [duck typing](http://en.wikipedia.org/wiki/Duck_typing). Example:
In you code, assume that the argument (in your example `a`) walks like an `int` and quacks like an `int`. For instance:
```
def my_function(a):
return a + 7
```
This means... |
Best way to check function arguments in Python | 19,684,434 | 19 | 2013-10-30T14:03:34Z | 37,961,120 | 13 | 2016-06-22T07:21:23Z | [
"python",
"function",
"arguments"
] | I'm looking for an efficient way to check variables of a python function. For example, I'd like to check arguments type and value. Is there a module for this? Or should I use something like decorators, or any specific idiom?
```
def my_function(a, b, c):
"""an example function I'd like to check the arguments of.""... | In this elongated answer, we implement a Python 3.x-specific type checking decorator based on [PEP 484](https://www.python.org/dev/peps/pep-0484)-style type hints in less than 275 lines of pure-Python (most of which is explanatory docstrings and comments) â heavily optimized for industrial-strength real-world use com... |
How to zip two different size list in python | 19,686,533 | 10 | 2013-10-30T15:09:43Z | 19,686,624 | 31 | 2013-10-30T15:13:36Z | [
"python",
"list",
"python-3.x"
] | I want to zip two list with different length
for example
```
A = [1,2,3,4,5,6,7,8,9]
B = ["A","B","C"]
```
and I expect this
```
[(1, 'A'), (2, 'B'), (3, 'C'), (4, 'A'), (5, 'B'), (6, 'C'), (7, 'A'), (8, 'B'), (9, 'C')]
```
But the build-in `zip` won't repeat to pair with the list with larger size .
Does there exi... | You can use [`itertools.cycle`](http://docs.python.org/2/library/itertools.html#itertools.cycle):
> Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely.
**Example:**
```
A = [1,2,3,4,5,6,7,8,9]
B = ... |
Difference between BeautifulSoup and Scrapy crawler? | 19,687,421 | 47 | 2013-10-30T15:43:23Z | 19,734,213 | 96 | 2013-11-01T19:41:41Z | [
"python",
"beautifulsoup",
"scrapy",
"web-crawler"
] | I want to make a website that shows the comparison between amazon and e-bay product price.
Which of these will work better and why? I am somewhat familiar with **BeautifulSoup** but not so much with **Scrapy crawler**. | **Scrapy** is a Web-spider or **web scraper framework**, You give Scrapy a root URL to start crawling, then you can specify constraints on how many (number of) URLs you want to crawl and fetch,etc. It is a complete framework for web-scraping or **crawling**.
While
**BeautifulSoup** is a **parsing library** which also... |
Why is apt-get function not working in terminal on mac osx 10.9? | 19,688,424 | 79 | 2013-10-30T16:25:49Z | 19,688,479 | 135 | 2013-10-30T16:27:58Z | [
"python",
"osx",
"terminal"
] | I was watching [this](https://www.youtube.com/watch?v=oT1A1KKf0SI) and as you can see the first command I am told to put in is:
```
sudo apt-get install python-setuptools
```
When I do this, it outputs:
```
sudo: apt-get: command not found
```
I have no idea why this is the case.
How can I resolve this so I am fol... | Mac OS X doesn't have `apt-get`. There is a package manager called [Homebrew](http://brew.sh/) that is used instead.
This command would be:
> brew install python
Use Homebrew to install packages that you would otherwise use `apt-get` for.
The page I linked to has an up-to-date way of installing homebrew, but at pre... |
Error starting iPython on Mac OSX: No module named jinja2 | 19,689,883 | 3 | 2013-10-30T17:29:40Z | 19,690,649 | 9 | 2013-10-30T18:09:12Z | [
"python",
"osx",
"python-2.7",
"pip",
"ipython"
] | `iPython` was installed on a Mac OS X Mountain Lion using `pip`. When running `ipython notebook` in the Terminal, I get the error
```
...
File "/Users/god/.virtualenvs/datasci/lib/python2.7/site-packages/IPython/html/notebookapp.py", line 38, in <module>
from jinja2 import Environment, FileSystemLoader
ImportError: No... | Jinja 2 is listed as an *optional* dependency, see the [iPython quickstart](http://ipython.org/ipython-doc/stable/install/install.html).
You must install optional dependencies separately:
```
pip install Jinja2
```
You can install such dependencies as optional functionality groups for `ipython`. Using these let you ... |
how to import __future__ for keyword-only argument of python 3.0? | 19,690,483 | 5 | 2013-10-30T18:01:06Z | 19,690,513 | 14 | 2013-10-30T18:02:34Z | [
"python",
"python-3.x",
"python-import",
"varargs"
] | The following code in python2.6 throws syntax error
```
>>> def f(a,*args,c):
File "<stdin>", line 1
def f(a,*args,c):
^
SyntaxError: invalid syntax
```
but this syntax is valid in python3.0. I would like to know what should I import in my interpreter to make it work.
ie. `from import __future... | This feature of the Python 3 compiler has *not* been backported to Python 2.x.
There is no magic `from __future__ import` switch to enable it, your only option is to upgrade to Python 3.x.
Your second function could instead be defined as:
```
def (a, *b, **kwargs):
c = 5
if 'c' in kwargs:
c = kwargs.pop... |
How can I get the stanford NLTK python module? | 19,694,106 | 3 | 2013-10-30T21:25:58Z | 19,702,651 | 7 | 2013-10-31T09:27:12Z | [
"python",
"ubuntu",
"nltk"
] | I have the `python` (2.7.5) and `python-nltk` packages installed in Ubuntu 13.10. Running `apt-cache policy python-nltk` returns:
```
python-nltk:
Installed: 2.0~b9-0ubuntu4
```
And according to the [Stanford site](http://nlp.stanford.edu/software/CRF-NER.shtml), 2.0+ should have the `stanford` module. Yet when I t... | You need to use NLTK downloader:
```
import nltk
nltk.download()
``` |
Slice indices limited to 0x7FFFFFFF | 19,697,329 | 8 | 2013-10-31T02:18:27Z | 19,697,420 | 7 | 2013-10-31T02:28:09Z | [
"python",
"python-2.7",
"python-internals"
] | I'm playing with slices in Python (2.7.4):
```
class Foo():
def __getitem__(self, key):
# Single value
if isinstance(key, (int,long)):
return key
# Slice
if isinstance(key, slice):
print 'key.start = 0x{0:X} key.stop = 0x{1:X}'.format(key.start, key.stop)
... | I've realized that this appears to be a limitation of old-style classes. [New-style classes](http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes) (ones that derive from `object`) behave as expected:
```
class Foo(object):
#...
```
Results:
```
>>> f = Foo()
>>>
>>> f[0x80000000:0x90000... |
Slice indices limited to 0x7FFFFFFF | 19,697,329 | 8 | 2013-10-31T02:18:27Z | 19,698,247 | 7 | 2013-10-31T04:05:18Z | [
"python",
"python-2.7",
"python-internals"
] | I'm playing with slices in Python (2.7.4):
```
class Foo():
def __getitem__(self, key):
# Single value
if isinstance(key, (int,long)):
return key
# Slice
if isinstance(key, slice):
print 'key.start = 0x{0:X} key.stop = 0x{1:X}'.format(key.start, key.stop)
... | After a lot of searching I found this
In python 3.3, the slice start and end are found like [this](http://hg.python.org/cpython/file/d0bb3460b91b/Objects/sliceobject.c#l134)
```
start = PyLong_FromSsize_t(istart);
...
end = PyLong_FromSsize_t(istop);
```
but in 2.7 they are found like [this](http://hg.python.org/cpy... |
Python CSV to JSON | 19,697,846 | 21 | 2013-10-31T03:15:15Z | 19,706,994 | 36 | 2013-10-31T12:49:43Z | [
"python",
"json",
"csv"
] | Here's my code, really simple stuff...
```
import csv
import json
csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')
fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
out = json.dumps( [ row for row in reader ] )
jsonfile.write(out)
```
Declare s... | The problem with your desired output is that it is not valid json document,; it's a *stream of json documents*!
That's okay, if its what you need, but that means that for each document you want in your output, you'll have to call `json.dumps`.
Since the newline you want separating your documents is not contained in t... |
Fast Fibonacci slows to a crawl over 1,000,000 | 19,697,914 | 4 | 2013-10-31T03:23:37Z | 19,697,999 | 9 | 2013-10-31T03:33:12Z | [
"python",
"performance",
"algorithm",
"recursion",
"fibonacci"
] | I've written a pretty standard fibonacci function through fast doubling using an algorithm derived from the matrix exponentiation algorithm which should run in O(log(n)) time and calls, but stalls out at around over 1,000,000 - even when that should be just around 25 calls.
Code:
```
"""
O(log(n)) time fibonacci algo... | Try running you code like this
```
print "calculating fib(1000000)"
res = fib(1000000)
print "displaying the result..."
print res
```
The problem is that `fib(1000000)` is a quite large number (>10200000). Your computer can operate on these numbers quite quicky because everything is done in binary.
When you try to d... |
Detecting 'unusual behavior' using machine learning with CouchDB and Python? | 19,698,469 | 15 | 2013-10-31T04:30:06Z | 19,766,617 | 20 | 2013-11-04T11:17:40Z | [
"python",
"machine-learning",
"couchdb",
"bayesian",
"cloudant"
] | I am collecting a lot of really interesting data points as users come to my Python web service. For example, I have their current city, state, country, user-agent, etc. What I'd like to be able to do is run these through some type of machine learning system / algorithm (maybe a Bayesian classifier?), with the eventual ... | You're correct in assuming that this is a problem ideally suited to Machine Learning, and [scikit-learn.org](http://scikit-learn.org/stable/) is my preferred library for these types of problems. Don't worry about specifics - (`couchdb` `cloudant`) for now, lets get your problem into a state where it can be solved.
If ... |
how does the callback function work in python multiprocessing map_async | 19,699,165 | 4 | 2013-10-31T05:39:29Z | 19,699,363 | 13 | 2013-10-31T05:55:17Z | [
"python",
"multiprocessing",
"pool"
] | It cost me a whole night to debug my code, and I finally found this tricky problem. Please take a look at the code below.
```
from multiprocessing import Pool
def myfunc(x):
return [i for i in range(x)]
pool=Pool()
A=[]
r = pool.map_async(myfunc, (1,2), callback=A.extend)
r.wait()
```
I thought I would get A=[... | Callback is called once with the result (`[[0], [0, 1]]`) if you use map\_async.
```
>>> from multiprocessing import Pool
>>> def myfunc(x):
... return [i for i in range(x)]
...
>>> A = []
>>> def mycallback(x):
... print('mycallback is called with {}'.format(x))
... A.extend(x)
...
>>> pool=Pool()
>>> r... |
UnicodeDecodeError: 'utf-8' codec can't decode byte | 19,699,367 | 24 | 2013-10-31T05:55:32Z | 19,699,399 | 10 | 2013-10-31T05:58:23Z | [
"python",
"python-3.x"
] | Here is my code,
```
for line in open('u.item'):
#read each line
```
whenever I run this code it gives the following error:
```
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 2892: invalid continuation byte
```
I tried to solve this and add an extra parameter in open(), the code looks like;
`... | Your file doesn't actually contain utf-8 encoded data, it contains some other encoding. Figure out what that encoding is and use it in the `open` call.
In Windows-1252 encoding for example the `0xe9` would be the character `é`. |
UnicodeDecodeError: 'utf-8' codec can't decode byte | 19,699,367 | 24 | 2013-10-31T05:55:32Z | 19,706,723 | 59 | 2013-10-31T12:35:45Z | [
"python",
"python-3.x"
] | Here is my code,
```
for line in open('u.item'):
#read each line
```
whenever I run this code it gives the following error:
```
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 2892: invalid continuation byte
```
I tried to solve this and add an extra parameter in open(), the code looks like;
`... | As suggested by Mark Ransom, I found the right encoding for that problem. The encoding was "ISO-8859-1", so replacing `open("u.item", encoding="utf-8")` with `open('u.item', encoding = "ISO-8859-1")` will solve the problem. |
python define a state object | 19,702,168 | 2 | 2013-10-31T08:59:56Z | 19,702,223 | 7 | 2013-10-31T09:03:35Z | [
"python",
"state"
] | I wrote the following code:
```
class Game(object):
class States(object):
STARTED = 1 << 0
LOADING = 1 << 1
ACTIVE = 1 << 2
ENDED = 1 << 3
state = States.LOADING
```
It there any better way to define a state object? | I have seen this pattern:
```
class Demo:
STARTED, LOADING, ACTIVE, ENDED = range(4)
```
or if you really need distinct bits:
```
class Demo:
STARTED, LOADING, ACTIVE, ENDED = (2**x for x in range(4))
```
That said, why do you want to burden yourself with doing bit manipulations? Just use boolean properti... |
How to store python dictionary in to mysql DB through python | 19,703,091 | 7 | 2013-10-31T09:48:43Z | 19,705,754 | 7 | 2013-10-31T11:50:49Z | [
"python",
"mysql",
"dictionary"
] | I am trying to store the the following dictionary in to mysql DB by converting the dictionary in to string and then trying to insert but I am getting following error.How to solve this or is any other way to store dictinary into mysql DB.
```
dic = {'office': {'component_office': ['Word2010SP0', 'PowerPoint2010SP0']}}
... | First of all, don't ever construct raw SQL queries like that. Never ever. This is what parametrized queries are for. You've asking for an [SQL injection](http://en.wikipedia.org/wiki/SQL_injection) attack.
If you want to store arbitrary data, as for example Python dictionaries, you should serialize that data. [JSON](h... |
Django sort by distance | 19,703,975 | 4 | 2013-10-31T10:27:43Z | 19,709,298 | 18 | 2013-10-31T14:32:00Z | [
"python",
"django",
"geodjango"
] | i have model:
```
class Vacancy(models.Model):
lat = models.FloatField('Latitude', blank = True)
lng = models.FloatField('Longitude', blank = True)
```
Hi should i make query to sort by distance (distance is infinity) ? Working on PosgreSQL, GeoDjango if it required.
Thank, you. | First of all, it is better to make a point field instead of making lat and lnt separated:
```
from django.contrib.gis.db import models
location = models.PointField(null=False, blank=False, srid=4326, verbose_name="Location")
```
Then, you can filter it like that:
```
from django.contrib.gis.geos import ... |
Django sort by distance | 19,703,975 | 4 | 2013-10-31T10:27:43Z | 26,219,292 | 9 | 2014-10-06T15:11:54Z | [
"python",
"django",
"geodjango"
] | i have model:
```
class Vacancy(models.Model):
lat = models.FloatField('Latitude', blank = True)
lng = models.FloatField('Longitude', blank = True)
```
Hi should i make query to sort by distance (distance is infinity) ? Working on PosgreSQL, GeoDjango if it required.
Thank, you. | Here is a solution that doesnt require GeoDjango using a custom manager.
```
class LocationManager(models.Manager):
def nearby(self, latitude, longitude, proximity):
"""
Return all object which distance to specified coordinates
is less than proximity given in kilometers
"""
... |
Django sort by distance | 19,703,975 | 4 | 2013-10-31T10:27:43Z | 35,896,358 | 7 | 2016-03-09T15:53:09Z | [
"python",
"django",
"geodjango"
] | i have model:
```
class Vacancy(models.Model):
lat = models.FloatField('Latitude', blank = True)
lng = models.FloatField('Longitude', blank = True)
```
Hi should i make query to sort by distance (distance is infinity) ? Working on PosgreSQL, GeoDjango if it required.
Thank, you. | the `.distance(ref_location)` is removed in django >=1.9 you should use an annotation instead.
```
from django.contrib.gis.db.models.functions import Distance
from django.contrib.gis.measure import D
ref_location = Point(1.232433, 1.2323232)
yourmodel.objects.filter(location__distance_lte=(ref_location, D(m=2000))).a... |
How can I apply a namedtuple onto a function? | 19,707,267 | 5 | 2013-10-31T13:02:58Z | 19,707,361 | 10 | 2013-10-31T13:07:39Z | [
"python",
"function",
"call",
"namedtuple"
] | In Python, if you have a dictionary
```
d = {'foo': 1, 'bar': False}
```
You can apply this onto a function that accept `foo` and `bar` keyword arguments by
```
def func(foo, bar):
# Do something complicated here
pass
func(**d)
```
But if instead, I wanted to call `func` with the namedtuple defined below:
... | A namedtuple instance has a [`._asdict()` method](http://docs.python.org/2/library/collections.html#collections.somenamedtuple._asdict):
```
func(**r._asdict())
```
but if the namedtuple attributes are in the same order as the arguments of the function, you could just apply it as a sequence instead:
```
func(*r)
```... |
How to make a SOAP request by using SOAPpy? | 19,708,597 | 6 | 2013-10-31T14:00:18Z | 19,751,606 | 11 | 2013-11-03T09:44:39Z | [
"python",
"web-services",
"soap",
"soap-client",
"soappy"
] | I'm trying to call a method using a SOAP request by using SOAPpy on Python 2.7. The method is called `GetCursOnDate` and returns exchange rates. It takes a date parameter.
I'm using the following code:
```
from SOAPpy import SOAPProxy
import datetime
date=datetime.datetime.now()
namespace ="http://web.cbr.ru/"
url =... | By default, SOAPpy uses the method name as the value of the HTTP `SOAPAction` header. If you run the following code you will see the value in the debug output:
```
from SOAPpy import SOAPProxy
from datetime import datetime
input = datetime.now()
namespace = "http://web.cbr.ru/"
url = "http://www.cbr.ru/DailyInfoWebSe... |
How can I list all available windows locales in python console? | 19,709,026 | 12 | 2013-10-31T14:21:46Z | 19,709,166 | 17 | 2013-10-31T14:26:44Z | [
"python",
"locale"
] | On linux we can use `locale -a` to see the list of locales available.
```
$ locale -a
C
C.UTF-8
en_US.utf8
POSIX
```
Is it possible to do the same from python console on **windows**?
This can be handy when you try to do `locale.setlocale(locale.LC_ALL, '???')` and simply don't know the name of the locale value. | ```
>>> import locale
>>> locale.locale_alias
``` |
Django - Rest Framework Multiple models | 19,709,101 | 6 | 2013-10-31T14:24:46Z | 23,481,901 | 13 | 2014-05-05T21:07:22Z | [
"python",
"django",
"json",
"rest",
"frameworks"
] | I'm starting to use Django Rest Framework, it's a great tool!
I'm actually stuck in something easy, but no way to figure out how to do... I have two models, CustomUser and Order. Here, a CustomUser has 0 to many Orders.
I would like to generate a JSON HTTPResponse with the following format:
```
{
"user": {
"city... | The question is old, so it may have been answered, but something like this should work:
```
class OrderSerializer(serializers.ModelSerializer)
class Meta:
model = Order
class UserSerializer(serializers.ModelSerializer)
orders = OrderSerializer(many = True)
class Meta:
model = user
... |
Concatenate sparse matrices in Python using SciPy/Numpy | 19,710,602 | 10 | 2013-10-31T15:28:43Z | 19,710,648 | 19 | 2013-10-31T15:30:41Z | [
"python",
"numpy",
"scipy",
"sparse-matrix"
] | What would be the most efficient way to concatenate sparse matrices in Python using SciPy/Numpy?
Here I used the following:
```
>>> np.hstack((X, X2))
array([ <49998x70000 sparse matrix of type '<class 'numpy.float64'>'
with 1135520 stored elements in Compressed Sparse Row format>,
<49998x70000 sparse... | You can use the `scipy.sparse.hstack`:
```
from scipy.sparse import hstack
hstack((X, X2))
```
Using the `numpy.hstack` will create an array with two sparse matrix objects. |
Find max since condition in pandas timeseries dataframe | 19,715,162 | 5 | 2013-10-31T19:36:09Z | 19,715,351 | 8 | 2013-10-31T19:47:13Z | [
"python",
"numpy",
"pandas"
] | I'm trying to find the max since condition was true in a pandas dataframe. I've searched for similar questions and read the documentation but haven't been able to find this problem discussed. To illustrate, I want a function that will return the maxsince column below.
```
In [84]: df
Out[84]:
a ... | How about:
```
>>> df.groupby(df["b"].cumsum())["a"].cummax()
2007-04-27 11:00:00 1
11:30:00 5
12:00:00 5
12:30:00 2
13:00:00 2
13:30:00 7
14:00:00 7
14:30:00 7
dtype: int64
```
This works because
```
>>> df[... |
Pycharm environment different than command line | 19,715,724 | 5 | 2013-10-31T20:09:44Z | 19,717,016 | 10 | 2013-10-31T21:35:43Z | [
"python",
"python-2.7",
"sqlite3",
"osx-mavericks",
"pycharm"
] | I am having an issue getting my Pycharm environment to match up with the environment that I have on the command line. I recently removed python and reinstalled it via home brew. The python in my path is pointing to `/usr/local/bin/python` I added `PATH=/usr/local/bin:$PATH` to the beginning of my .bash\_profile file an... | `.bash_profile` is being red by bash (your command line interpreter) only.
However if you want to preserve bash environment for PyCharm there is one
true Linux way.
Run PyCharm from your command line (from bash).
Thus environment variables will be inherited from bash to pycharm.
Read `$man` environ for information on ... |
Tornado non-blocking request | 19,716,831 | 3 | 2013-10-31T21:21:27Z | 19,716,936 | 7 | 2013-10-31T21:29:57Z | [
"python",
"asynchronous",
"tornado"
] | I have a function that takes a while to run, and need to run it in a request. What is the best way to deal with this so that this request does not block the main thread while it is being processed? I looked at the `@tornado.web.asynchronous` decorator, but that isn't much use here when the function isn't an async torna... | When you have some blocking task that doesn't play nice with the async event loop, you have to put it in a separate thread.
If you're going to have an unbounded number of blocking tasks, you want to use a thread pool.
Either way, you want to have a wrapper async task that blocks on notification from the threaded task... |
How to define an unsigned integer in SQLAlchemy | 19,717,738 | 4 | 2013-10-31T22:33:44Z | 19,718,413 | 14 | 2013-10-31T23:31:55Z | [
"python",
"mysql",
"flask",
"flask-sqlalchemy"
] | I am migrating a portal to Flask with Flask-SQLAlchemy (MySQL). Below is the code I used to create my DB for my existing portal:
```
Users = """CREATE TABLE Users(
id INT UNSIGNED AUTO_INCREMENT NOT NULL,
UserName VARCHAR(40) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
LastNa... | SQLAlchemy types (such as [Integer](http://docs.sqlalchemy.org/en/rel_0_9/core/types.html#sqlalchemy.types.Integer)) seem to try to abide by the [standard SQL data types](http://en.wikipedia.org/wiki/SQL#Data_types). Since an "unsigned integer" is not a standard data type, you won't see something like an `UnsignedInteg... |
Round timestamp to nearest day in Python | 19,718,390 | 5 | 2013-10-31T23:28:57Z | 19,718,517 | 7 | 2013-10-31T23:41:32Z | [
"python",
"datetime"
] | In Python 2.7.2 I am getting the seconds since epoch using:
`sec_since_epoch = (date_obj - datetime(1970, 1, 1, 0, 0)).total_seconds()`
Now I want to round these seconds to the nearest day e.g. if:
`datetime.fromtimestamp(sec_since_epoch)`
corresponds to `datetime(2013, 12, 14, 5, 0, 0)`
I want the new timestamp t... | You can use `datetime.timetuple()` to manipulate with the date. E.g. in this way:
```
from datetime import datetime
dt = datetime(2013, 12, 14, 5, 0, 0)
dt = datetime(*dt.timetuple()[:3]) # 2013-12-14 00:00:00
print dt.strftime('%s') # 1386997200
```
[**DEMO**](http://codepad.org/7vpTqE1O) |
Selecting unique observations in a pandas data frame | 19,718,531 | 4 | 2013-10-31T23:43:12Z | 19,720,669 | 7 | 2013-11-01T04:13:27Z | [
"python",
"pandas"
] | I have a `pandas` data frame with a column `uniqueid`. I would like to remove all duplicates from the data frame based on this column, such that all remaining observations are unique. | There is also the `drop_duplicates()` method for any data frame ([docs here](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html?highlight=drop_duplicates#pandas.DataFrame.drop_duplicates)). You can pass specific columns to drop from as an argument.
```
df.drop_duplicates(cols =... |
for n in a list: del n | 19,718,929 | 2 | 2013-11-01T00:25:05Z | 19,718,951 | 7 | 2013-11-01T00:27:20Z | [
"python",
"loops",
"scope"
] | When I loop over a list, the name that I give within the loop to the elements of the list apparently refers directly to each element in turn, as evidenced by:
```
>>> a = [1, 2, 3]
>>> for n in a:
... print n is a[a.index(n)]
True
True
True
```
So, **purely out of curiosity**, why doesn't this seem to do anything... | Inside the block of any `for n in X` statement, `n` refers to the variable named `n` itself, not to any notion of "the place in the list of the last value you iterated over". Therefore, what your loop is doing is repeatedly binding a variable `n` to a value fetched from the list and then immediately unbinding that same... |
Python: Where To Find Import For Exception | 19,719,143 | 3 | 2013-11-01T00:49:28Z | 19,719,186 | 9 | 2013-11-01T00:55:09Z | [
"python"
] | How do you find where a custom Exception is defined so that you can import it. In my stacktrace of an error that is thrown in my code I am getting a NoSuchElementException. I would like to catch this specific exception but I can't find where to import it from. Is there a way to determine what to import from the stacktr... | Catch the exception with `Exception` so that you have access to the exception object:
```
try:
call_your_function()
except Exception as e:
print e.__module__
```
Then replace `Exception` with the more specific one you find out. |
Cannot filter a non-Node argument - datastore - google app engine - python | 19,720,113 | 5 | 2013-11-01T03:01:44Z | 19,737,288 | 8 | 2013-11-01T23:51:29Z | [
"python",
"google-app-engine",
"gae-datastore"
] | ```
Class user(ndb.Model):
def post(self):
name = db.StringProperty()
age = db.StringProperty()
Class search(webapp2.RequestHandler):
def post(self):
x = userData.query().filter("age >=",1) #error points to this line
```
I get an error: *Cannot filter a non-Node argument; received 'age >='*
I am foll... | I finally found answer for this at
[Google App Engine (python): filter users based on custom fields](http://stackoverflow.com/questions/10913720/google-app-engine-python-filter-users-based-on-custom-fields).
The docs for this are mentioned at <https://developers.google.com/appengine/docs/python/ndb/queries#prope... |
Make legend correspond to colors of scatter points in matplotlib | 19,720,412 | 5 | 2013-11-01T03:40:44Z | 19,988,339 | 7 | 2013-11-14T21:04:20Z | [
"python",
"matplotlib",
"plot",
"legend"
] | I have a plot that I am generating through KMeans algorithm in scikit-learn. The clusters correspond to different colors. Here is the plot,

I need a legend for this plot which corresponds to the cluster number in the plot. Ideally, the legend should d... | I was able to make the legend correspond to the color. The key was using multiple scatterplots for each category in the data as mentioned by Rutger Kassies.
Here is the code:
```
import numpy as np
import matplotlib.pyplot as plt
# Setting various plot properties
plt.clf()
fig = plt.figure()
ax = fig.add_subplot(111... |
Invert negative values in a list | 19,720,445 | 3 | 2013-11-01T03:44:34Z | 19,720,452 | 7 | 2013-11-01T03:45:26Z | [
"python"
] | I am trying to convert a list that contains negative values, to a list of non-negative values; inverting the negative ones. I have tried `abs` but it didn't work.
My input is
```
x = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
```
How can I make it into this format as I am trying calculate the area
```
... | Try a list comprehension:
```
x2 = [abs(k) for k in x]
``` |
python: make pandas dataframe column headers all lowercase | 19,726,029 | 12 | 2013-11-01T11:39:26Z | 19,726,078 | 30 | 2013-11-01T11:42:38Z | [
"python",
"pandas",
"dataframe"
] | I want to make all column headers in my pandas data frame lower case
for example, if I have:
```
data =
country country isocode year XRAT tcgdp
0 Canada CAN 2001 1.54876 924909.44207
1 Canada CAN 2002 1.56932 957299.91586
2 Canada CAN 2003 1.40105 101... | You can do it like this:
```
data.columns = map(str.lower, data.columns)
```
or
```
data.columns = [x.lower() for x in data.columns]
```
example:
```
>>> data = pd.DataFrame({'A':range(3), 'B':range(3,0,-1), 'C':list('abc')})
>>> data
A B C
0 0 3 a
1 1 2 b
2 2 1 c
>>> data.columns = map(str.lower, da... |
multiplication of two arguments in python | 19,726,108 | 3 | 2013-11-01T11:44:23Z | 19,726,122 | 10 | 2013-11-01T11:45:20Z | [
"python",
"casting"
] | I was trying to use Python and I have created a short method:
```
def mul(x,y):
print(x*y)
```
by running `mul(2,"23")`, I'm getting this outstanding output : `2323`
Can someone explain this? | Because you're multiplying a string and an integer together:
```
>>> print '23' * 2
2323
```
Which is equivalent to `'23' + '23'`.
Do `mul(2, int('23'))` to turn `'23'` into an integer, or just get rid of the quotation marks surrounding the `23`.
By the way, such function already exists in the [`operator`](http://d... |
How to save the Pandas dataframe/series data as a figure? | 19,726,663 | 21 | 2013-11-01T12:22:13Z | 25,588,487 | 17 | 2014-08-31T02:31:58Z | [
"python",
"matplotlib",
"pandas"
] | It sounds somewhat weirdï¼ but I need to save the Pandas console output string to png pics. For example:
```
>>> df
sales net_pft ROE ROIC
STK_ID RPT_Date
600809 20120331 22.1401 4.9253 0.1651 0.6656
20120630 38.1565 7.8684 0.2567 1.0385
... | You have to use the figure returned by the `DataFrame.plot()` command:
```
ax = df.plot()
fig = ax.get_figure()
fig.savefig('asdf.png')
``` |
Is python's "in" language construct thread-safe for lists? | 19,727,759 | 7 | 2013-11-01T13:31:45Z | 19,727,862 | 13 | 2013-11-01T13:37:21Z | [
"python",
"list",
"thread-safety",
"in-operator"
] | Is `obj in a_list` thread-safe while `a_list` might be modified in a different thread?
[Here's a comprehensive yet non-exhaustive list of examples](http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm) of `list` operations and whether or not they are thread safe, however I couldn't find any ... | I am assuming you are using CPython here.
Provided there is no custom `__contains__` or `__iter__` hook dropping back into Python *or* the values you test against contained *in* the list use custom `__eq__` hooks implemented in Python code, the `in` operator can be handled entirely in C, and is just *one* opcode.
Thi... |
Serial import python | 19,728,535 | 4 | 2013-11-01T14:15:17Z | 19,730,344 | 11 | 2013-11-01T15:53:03Z | [
"python",
"module",
"serial-port",
"pyserial"
] | I"m trying to use pyserial. When I do the following script.
```
import serial
ser= serial.serial("COM5", 9600)
ser.write("Hello worldn")
x = ser.readline()
print(x)
```
Error code:
```
c:\Python27>python com.py
Traceback (most recent call last):
File "com.py", line 2, in <module>
ser= serial.serial("COM5", 960... | It should be:
```
import serial
ser = serial.Serial("COM5", 9600)
```
Note the capital 'S' in serial.Serial |
urllib module error! AttributeError: 'module' object has no attribute 'request' | 19,729,927 | 5 | 2013-11-01T15:30:47Z | 19,729,996 | 8 | 2013-11-01T15:35:03Z | [
"python",
"python-2.7"
] | I was currently playing with the 'urllib' module in python, and tried this to extract source code of a website:
```
import urllib
temp = urllib.request.urlopen('https://www.quora.com/#')
```
However, I get the following error:
> Traceback (most recent call last): File "", line 1, in
> temp = urllib.request.urlopen('... | It seems like you are reading [Python 3.x documentation](http://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen).
It's [`urllib.urlopen`](http://docs.python.org/2/library/urllib.html#urllib.urlopen) in Python 2.x. |
Python sort a List by length of value in tuple | 19,729,928 | 9 | 2013-11-01T15:30:48Z | 19,729,956 | 11 | 2013-11-01T15:32:16Z | [
"python",
"sorting",
"tuples"
] | I am having difficulty sorting a list of tuples. I would like to sort by the length of a string in the list.
For example:
```
l = [(99,'bbc', 121),(33,'abcd', 231),(44,'zb', 148), (23,'abcde',221)]
```
if I sort by element 1:
```
l.sort(key=itemgetter(1), reverse=True)
```
This will sort on the alphabetical rankin... | Well you can make the lambda simpler:
```
l.sort(key=lambda t: len(t[1]), reverse=True)
```
Also, don't use `list` as a variable name; it's already taken by a built-in function. |
'lxml.etree._ElementTree' object has no attribute 'cssselect' | 19,730,476 | 6 | 2013-11-01T15:59:31Z | 19,730,555 | 9 | 2013-11-01T16:03:21Z | [
"python",
"lxml"
] | I am running python 2.7.2
I have lxml and cssselect installed
My code is
```
from lxml import etree, html
r = html.parse(start_url)
all_titles = r.cssselect('span.titles') #should return a list of results
all_urls = r.cssselect('span.links') #and this as well
```
I am scraping a webpage that has titles and their ass... | [`ElementTree`](http://lxml.de/api/lxml.etree._ElementTree-class.html) does not have `cssselect` method, while [`HtmlElement`](http://lxml.de/api/lxml.html.HtmlElement-class.html) object have it.
Use [`ElementTree.getroot`](http://lxml.de/api/lxml.etree._ElementTree-class.html#getroot) to get `HtmlElement` object:
``... |
Python file.tell gives wrong value location | 19,730,875 | 4 | 2013-11-01T16:19:25Z | 19,731,163 | 7 | 2013-11-01T16:37:20Z | [
"python",
"seek",
"tell"
] | I am trying to extract a number of locations from an existing file using Python. This is my current code for extracting the locations:
```
self.fh = open( fileName , "r+")
p = re.compile('regGen regPorSnip begin')
for line in self.fh :
if ( p.search(line) ):
self.porSnipStartFPtr = self... | The cause is (rather obscurely) explained in the docs for a file object's `next()` method:
> When a file is used as an iterator, typically in a for loop (for example,
> for line in f: print line), the next() method is called repeatedly.
> This method returns the next input line, or raises StopIteration when
> EOF is h... |
iPython: Manipulate-like command | 19,731,900 | 15 | 2013-11-01T17:21:36Z | 19,732,436 | 16 | 2013-11-01T17:53:25Z | [
"python",
"wolfram-mathematica",
"ipython",
"ipython-notebook",
"sage"
] | In Wolfram Mathematica, I can interactively modify the value of a parameter by using the `Manipulate[]` command.
[For example](http://reference.wolfram.com/mathematica/tutorial/IntroductionToManipulate.html), `Manipulate[n, {n, 1, 20}]`
shows a slider through which is possible to vary the value of `n`.
Is there any s... | **Update**
This was added in IPython 2.0 (released Apr 1, 2014), it's called [Interactive Widgets](http://nbviewer.ipython.org/github/ipython/ipython/blob/2.x/examples/Interactive%20Widgets/Index.ipynb) and works in web notebooks.
**Original answer**
This is ongoing work for 2.0 (release December something-ish) Ha... |
How to Run Python Code on SublimeREPL | 19,732,006 | 22 | 2013-11-01T17:28:01Z | 19,732,557 | 20 | 2013-11-01T18:00:34Z | [
"python",
"ubuntu",
"python-2.7",
"sublimerepl"
] | I really like using sublime text 2 to write Python codes, however any time I try to run a script which has an input, the sublime text console reports an error. So, I decided to try `SublimeREPL`, however I've been searching for hours and I didn't find out how to run Python code...
could you guys help me?
I want to run... | First "`Install Package Control`" from <https://sublime.wbond.net/installation#st2>
**Optional**(*To check the above package is successfully installed:
Click the `Preferences > Browse Packages`⦠at this folder
Click `Back Button` one time and then into the Installed Packages/ folder, check there will be `Package Con... |
How to Run Python Code on SublimeREPL | 19,732,006 | 22 | 2013-11-01T17:28:01Z | 23,722,631 | 42 | 2014-05-18T13:50:03Z | [
"python",
"ubuntu",
"python-2.7",
"sublimerepl"
] | I really like using sublime text 2 to write Python codes, however any time I try to run a script which has an input, the sublime text console reports an error. So, I decided to try `SublimeREPL`, however I've been searching for hours and I didn't find out how to run Python code...
could you guys help me?
I want to run... | As [described here](http://www.sublimetext.com/forum/viewtopic.php?f=5&t=2964&start=60#p25231), create a new Build System file and save it as `..\Packages\User\SublimeREPL-python.sublime-build`. The file should contain:
```
{
"target": "run_existing_window_command",
"id": "repl_python_run",
"file": "confi... |
How to Run Python Code on SublimeREPL | 19,732,006 | 22 | 2013-11-01T17:28:01Z | 26,594,217 | 12 | 2014-10-27T18:21:00Z | [
"python",
"ubuntu",
"python-2.7",
"sublimerepl"
] | I really like using sublime text 2 to write Python codes, however any time I try to run a script which has an input, the sublime text console reports an error. So, I decided to try `SublimeREPL`, however I've been searching for hours and I didn't find out how to run Python code...
could you guys help me?
I want to run... | I want to expand on @sblair's response. @alexpmil asked in a comment how to prevent the REPL from closing.
1. In your packages, open `SublimeREPL\config\Python\Main.sublime-menu`.
2. Find the part that contains `id`: `repl_python_run`.
3. Under `args/cmd`, add `-i`. That's it.
For reference, mine looks like the follo... |
Python while statement error | 19,732,791 | 2 | 2013-11-01T18:14:03Z | 19,732,809 | 9 | 2013-11-01T18:15:02Z | [
"python",
"python-2.7",
"while-loop"
] | I am a beginner in python. My program is to set a number (I am not using random.randint for the moment) and I try to guess it. So here is the code:
```
def game():
print "I am thinking of a number between 1 and 10!"
global x
x = 7
y = raw_input("Guess!")
while x > y:
y = raw_input("Too low... | You need to convert `y` to an integer before comparing it to `x`:
```
y = int(raw_input("Guess!"))
```
Otherwise, you are comparing variables of different types, and the result is not always intuitive (such as `x` always being less than `y`). You can apply the same approach for the other times you ask the user to inp... |
What is "homogenous" in Python list documentation? | 19,733,666 | 9 | 2013-11-01T19:06:38Z | 19,733,702 | 10 | 2013-11-01T19:08:55Z | [
"python",
"list"
] | In python documentation list is defined as:
> mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application).
Why it's used to store collections of **homogeneous** items?
Are a string and an int item also homogeneous then?
```
a = [12,"h... | Homogeneous means ["of the same or a similar kind or nature"](http://www.merriam-webster.com/dictionary/homogeneous).
While *any* value can be stored in a list along with any other value, in doing so the definition of "kind or nature" must be *widened* when dealing with the sequence. During this widening (or "unificat... |
django, "is not JSON serializable" when using ugettext_lazy? | 19,734,724 | 3 | 2013-11-01T20:17:35Z | 19,734,757 | 13 | 2013-11-01T20:20:47Z | [
"python",
"django",
"json"
] | I have this in my `views.py`
```
response_dict = {
'status': status,
'message': message
}
return HttpResponse(simplejson.dumps(response_dict),
mimetype='application/javascript')
```
Since I start using this import:
`from django.utils.translation import ugettext_lazy as _`
at this line:
... | It's not a string yet, and Python's JSON encoder doesn't know about ugettext\_lazy, so you'll have to force it to become a string with something like
```
response_dict = {
'status': status,
'message': unicode(message)
}
``` |
django, "is not JSON serializable" when using ugettext_lazy? | 19,734,724 | 3 | 2013-11-01T20:17:35Z | 31,746,279 | 14 | 2015-07-31T12:30:43Z | [
"python",
"django",
"json"
] | I have this in my `views.py`
```
response_dict = {
'status': status,
'message': message
}
return HttpResponse(simplejson.dumps(response_dict),
mimetype='application/javascript')
```
Since I start using this import:
`from django.utils.translation import ugettext_lazy as _`
at this line:
... | You can also create you own JSON encoder that will force `__proxy__` to unicode.
From <https://docs.djangoproject.com/en/1.8/topics/serialization/>
```
from django.utils.functional import Promise
from django.utils.encoding import force_text
from django.core.serializers.json import DjangoJSONEncoder
class LazyEncoder... |
Running a Python script from PHP | 19,735,250 | 31 | 2013-11-01T20:54:21Z | 19,736,494 | 53 | 2013-11-01T22:34:58Z | [
"php",
"python",
"linux",
"exec",
"archlinux"
] | I'm trying to run a Python script from PHP using the following command:
`exec('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');`
However, PHP simply doesn't produce any output. Error reporting is set to E\_ALL and display\_errors is on.
Here's what I've tried:
* I used `python2`, `/usr/bin/python2` and... | Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.
In PHP:
```
<?php
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>
```
In Python file 'test.py' verify this text in first line: [(see shebang explain)](http://www.stackoverflow.com/questions/24... |
Running a Python script from PHP | 19,735,250 | 31 | 2013-11-01T20:54:21Z | 19,736,525 | 9 | 2013-11-01T22:38:27Z | [
"php",
"python",
"linux",
"exec",
"archlinux"
] | I'm trying to run a Python script from PHP using the following command:
`exec('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');`
However, PHP simply doesn't produce any output. Error reporting is set to E\_ALL and display\_errors is on.
Here's what I've tried:
* I used `python2`, `/usr/bin/python2` and... | I recommend using `passthru` and handling the output buffer directly:
```
ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean();
``` |
Kivy to Apk in Windows | 19,735,768 | 6 | 2013-11-01T21:36:27Z | 19,736,391 | 14 | 2013-11-01T22:25:23Z | [
"android",
"python",
"python-3.x",
"kivy"
] | I'm using windows right now and I want to ask is there any good tools to package a kivy app for android in windows or I have t use Linux distributions? And also is there anyway to use kivy for python 3.3.2? | > I'm using windows right now and I want to ask is there any good tools to package a kivy app for android in windows or I have t use Linux distributions?
Unfortunately the build tools don't work on windows right now. I think there are technical barriers to do with cross compilation.
Have you seen the kivy virtual mac... |
Can I extend list in Python with prepend elements instead append? | 19,736,058 | 12 | 2013-11-01T21:57:43Z | 19,736,074 | 49 | 2013-11-01T21:58:33Z | [
"python",
"list"
] | I can perform
```
a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]
```
Is there way to perform some action for extend list and add new items to begin of the list?
Like this
```
a = [1,2,3]
b = [4,5,6]
a.someaction(b)
# a is now [4,5,6,1,2,3]
```
I use version 2.7.5, if it is important. | You can assign to a slice:
```
a[:0] = b
```
Demo:
```
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a[:0] = b
>>> a
[4, 5, 6, 1, 2, 3]
```
Essentially, `list.extend()` is an assignment to the `list[len(list):]` slice.
You can 'insert' another list at any position, just address the empty slice at that location:
```
>>> a =... |
Can I extend list in Python with prepend elements instead append? | 19,736,058 | 12 | 2013-11-01T21:57:43Z | 19,736,094 | 9 | 2013-11-01T22:00:39Z | [
"python",
"list"
] | I can perform
```
a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]
```
Is there way to perform some action for extend list and add new items to begin of the list?
Like this
```
a = [1,2,3]
b = [4,5,6]
a.someaction(b)
# a is now [4,5,6,1,2,3]
```
I use version 2.7.5, if it is important. | This is what you need ;-)
```
a = b + a
``` |
Creating dataframe from a dictionary where entries have different lengths | 19,736,080 | 14 | 2013-11-01T21:59:09Z | 19,736,406 | 19 | 2013-11-01T22:27:02Z | [
"python",
"pandas"
] | Say I have a dictionary with 10 key-value pairs. Each entry holds a numpy array. However, the length of the array is not the same for all of them.
How can I create a dataframe where each column holds a different entry?
When I try:
```
pd.DataFrame(my_dict)
```
I get:
```
ValueError: arrays must all be the same len... | ```
In [6]: d = dict( A = np.array([1,2]), B = np.array([1,2,3,4]) )
In [7]: DataFrame(dict([ (k,Series(v)) for k,v in d.iteritems() ]))
Out[7]:
A B
0 1 1
1 2 2
2 NaN 3
3 NaN 4
``` |
Creating dataframe from a dictionary where entries have different lengths | 19,736,080 | 14 | 2013-11-01T21:59:09Z | 25,217,425 | 11 | 2014-08-09T10:06:16Z | [
"python",
"pandas"
] | Say I have a dictionary with 10 key-value pairs. Each entry holds a numpy array. However, the length of the array is not the same for all of them.
How can I create a dataframe where each column holds a different entry?
When I try:
```
pd.DataFrame(my_dict)
```
I get:
```
ValueError: arrays must all be the same len... | Here's a simple way to do that:
```
In[20]: my_dict = dict( A = np.array([1,2]), B = np.array([1,2,3,4]) )
In[21]: df = pd.DataFrame.from_dict(my_dict, orient='index')
In[22]: df
Out[22]:
0 1 2 3
A 1 2 NaN NaN
B 1 2 3 4
In[23]: df.transpose()
Out[23]:
A B
0 1 1
1 2 2
2 NaN 3
3 NaN 4
``` |
Reorder Python List | 19,736,234 | 3 | 2013-11-01T22:12:01Z | 19,736,293 | 8 | 2013-11-01T22:17:31Z | [
"python"
] | I have a list of 4 items like this:
```
a, b, c, d = [1, 2, 3, 4]
```
I'm reordering the list, flipping each pair:
```
[b, a, d, c]
```
Is there a way to do this in one expression? I've tried using list comprehension and unpacking, but can't seem to get it right.
I have [1, 2, 3, 4]. I'm trying to get [2, 1, 4, 3]... | More generically, if you're looking to flip pairs of numbers in a list:
```
>>> L = [1, 2, 3, 4, 5, 6]
>>> from itertools import chain
>>> list(chain.from_iterable(zip(L[1::2], L[::2])))
[2, 1, 4, 3, 6, 5]
``` |
Can't Use Tab in Python Shell | 19,737,454 | 9 | 2013-11-02T00:13:02Z | 19,737,514 | 10 | 2013-11-02T00:19:36Z | [
"python",
"python-3.4"
] | Using tab in Python 3.4, I get the following message:
```
Display all 184 possibilites? (y or n)
```
Is there a way to allow tabbing in Python 3.4? | This is a change introduced in the development versions of Python 3.4. It has been somewhat controversial. You might want to voice your opinions [on the issue](http://bugs.python.org/issue5845). |
Can't Use Tab in Python Shell | 19,737,454 | 9 | 2013-11-02T00:13:02Z | 26,718,771 | 9 | 2014-11-03T16:41:29Z | [
"python",
"python-3.4"
] | Using tab in Python 3.4, I get the following message:
```
Display all 184 possibilites? (y or n)
```
Is there a way to allow tabbing in Python 3.4? | Instead of tabbing you can use spaces. And in the interactive interpreter, you don't have to type out 4 spaces. Here I'm using two spaces to minimize the number of keystrokes.
```
if 1 == 1:
print('Hello Kitty')
print('Oh no, only two spaces for a new block')
```
To disable `tab: complete`, you can do the followi... |
Why isn't setup.py dependency_links doing anything? | 19,738,085 | 7 | 2013-11-02T01:44:20Z | 19,738,086 | 9 | 2013-11-02T01:44:20Z | [
"python",
"python-3.x",
"setup.py"
] | I have an entry in my `setup.py` to install a package not hosted on PyPi, that must be compiled using setup.py as it is a C extension. It's not installing when I run `python setup.py install`, I've checked the logs and I have no idea why.
```
dependency_links = ['git+https://github.com/liamzebedee/scandir.git#egg=scan... | Turns out that as well as a `dependency_links` line, I also needed to add the name of the package in an `install_requires` line, like so:
```
dependency_links = ['git+https://github.com/liamzebedee/scandir.git#egg=scandir-0.1'],
install_requires = ['scandir'],
``` |
Convert column of date objects in Pandas DataFrame to strings | 19,738,169 | 6 | 2013-11-02T01:58:40Z | 19,738,382 | 11 | 2013-11-02T02:33:53Z | [
"python",
"datetime",
"pandas"
] | How to convert a column consisting of datetime64 objects to a strings that would read
01-11-2013 for today's date of November 1.
I have tried
```
df['DateStr'] = df['DateObj'].strftime('%d%m%Y')
```
but I get this error
**AttributeError: 'Series' object has no attribute 'strftime'** | ```
In [6]: df = DataFrame(dict(A = date_range('20130101',periods=10)))
In [7]: df
Out[7]:
A
0 2013-01-01 00:00:00
1 2013-01-02 00:00:00
2 2013-01-03 00:00:00
3 2013-01-04 00:00:00
4 2013-01-05 00:00:00
5 2013-01-06 00:00:00
6 2013-01-07 00:00:00
7 2013-01-08 00:00:00
8 2013-01-09 00:00:00
9 2013-... |
Convert column of date objects in Pandas DataFrame to strings | 19,738,169 | 6 | 2013-11-02T01:58:40Z | 33,967,346 | 9 | 2015-11-28T03:31:25Z | [
"python",
"datetime",
"pandas"
] | How to convert a column consisting of datetime64 objects to a strings that would read
01-11-2013 for today's date of November 1.
I have tried
```
df['DateStr'] = df['DateObj'].strftime('%d%m%Y')
```
but I get this error
**AttributeError: 'Series' object has no attribute 'strftime'** | As of [version 17.0](http://pandas.pydata.org/pandas-docs/version/0.17.0/whatsnew.html#whatsnew-0170-strftime), you can format with the `dt` accessor:
```
df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y')
``` |
DFT matrix in python | 19,739,503 | 9 | 2013-11-02T06:19:49Z | 19,739,589 | 8 | 2013-11-02T06:38:13Z | [
"python",
"numpy",
"scipy",
"fft",
"dft"
] | What's the easiest way to get the [DFT matrix](http://en.wikipedia.org/wiki/DFT_matrix) for 2-d DFT in python? I could not find such function in [numpy.fft](http://docs.scipy.org/doc/numpy/reference/routines.fft.html). Thanks! | I don't think this is built in. However, direct calculation is straightforward:
```
import numpy as np
def DFT_matrix(N):
i, j = np.meshgrid(np.arange(N), np.arange(N))
omega = np.exp( - 2 * pi * 1J / N )
W = np.power( omega, i * j ) / sqrt(N)
return W
```
*EDIT* For a 2D FFT matrix, you can use the f... |
Cannot import settings; not on system path | 19,741,013 | 4 | 2013-11-02T10:34:45Z | 19,741,994 | 7 | 2013-11-02T12:41:05Z | [
"python",
"django"
] | I'm trying to get Django working using virtualenv. I already got the hello world page online. However, there seems to be something wrong now because most of my commands give me the same error about myProject.settings
```
(myenv)user@mint /opt/myenv/myProject $ python manage.py startapp polls
Traceback (most recent cal... | Your `settings.py` must be importable by python. This can be achieved several ways:
* You have folder containing `myProject` in your `PYTHONPATH` environment, i.e. in `sys.path` , as stated by @amyangfei
Note that [`PYTHONPATH`](http://docs.python.org/2/using/cmdline.html#envvar-PYTHONHOME) is a system environment va... |
MultiValueDictKeyError in Django admin | 19,741,314 | 8 | 2013-11-02T11:16:10Z | 20,246,225 | 17 | 2013-11-27T15:18:09Z | [
"python",
"django",
"django-models"
] | UPDATE
**model:**
```
class PicturesManager(models.Manager):
def create_pictures(self, flat, img):
pictures = self.create(car=car, image=img)
return pictures
def get_file_path(instance, filename):
filename = "%s.%s" % (uuid.uuid4(), filename.split('.')[-1])
return os.path.join('car_img/',... | I think it is related to a Django 1.6 ticket
[#ticket 13696 -- ensured inline pk field is rendered](https://github.com/kmtracey/django/commit/9e5519f50536288db2ae0c6fa4b95193788dfb7a)
You have to update the following admin templates:
* stacked.html
* tabular.html
Remove the single line:
```
{% if inline_admin_form... |
DataFrame.drop not dropping expected rows in Pandas | 19,741,997 | 3 | 2013-11-02T12:41:42Z | 19,742,325 | 7 | 2013-11-02T13:22:34Z | [
"python",
"pandas"
] | I have a Pandas DataFrame that includes rows that I want to drop based on values in a column "population":
```
data['population'].value_counts()
general population 21
developmental delay 20
sibling 2
general population + development... | [`dataFrame.drop`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.drop.html) accepts an index (list of labels) as a parameter, not a mask.
To use `drop` you should do:
```
data = data.drop(data.index[data.population == 'sibling'])
```
however it is much simpler to do
```
data = data[data.popul... |
Could not find library geos_c or load any of its variants | 19,742,406 | 14 | 2013-11-02T13:31:56Z | 23,057,508 | 23 | 2014-04-14T10:15:03Z | [
"python",
"shapely"
] | I use python in fedora 19. I wanted to run the following line Python: **import shapely.geometry**
the following error appears:
> OSError: Could not find or load any library geos\_c icts of variants ['libgeos\_c.so.1', 'libgeos\_c.so']
I installed the package Shapely, and the following two libraries:
**glibc-2.17-4.f... | Installed shapely using pip, and had the same problem. So I went ahead and installed it like so:
```
sudo apt-get install libgeos-dev
```
And it worked. I'm running Ubuntu, so if you're on Fedora, you should probably run:
```
sudo yum install libgeos-dev
``` |
Why can't Javascript give accurate results for scientific calculations compared to python | 19,742,689 | 3 | 2013-11-02T14:02:22Z | 19,742,813 | 10 | 2013-11-02T14:15:24Z | [
"javascript",
"python"
] | I tried performing Modular Exponentiation in Javascript to verify an algorithm and was shocked to find that **Javascript was not giving accurate results compared to Python**, Why is it so. I think it has something to do with the way Javascript handles datatypes(as Text), But I would like to know more about it and I kno... | It gets a bit clearer, when you look at the intermediary results before the modulo operation first:
```
> Math.pow(17, 22)
1.1745628765211486e+27
```
```
>>> pow(17, 22)
1174562876521148458974062689
```
As you can see, the Python result has a lot more digits than the JavaScript result. This is due to how each langua... |
Why can't Javascript give accurate results for scientific calculations compared to python | 19,742,689 | 3 | 2013-11-02T14:02:22Z | 19,742,818 | 7 | 2013-11-02T14:15:52Z | [
"javascript",
"python"
] | I tried performing Modular Exponentiation in Javascript to verify an algorithm and was shocked to find that **Javascript was not giving accurate results compared to Python**, Why is it so. I think it has something to do with the way Javascript handles datatypes(as Text), But I would like to know more about it and I kno... | The `pow()` function *in Python* returns an integer result for integer inputs:
```
>>> pow(17, 22)
1174562876521148458974062689L
```
This is *not the same function* as what `Math.pow()` gives you, which uses floating point results:
```
> Math.pow(17, 22)
1.1745628765211486e+27
```
The equivalent function in Pytho... |
Accessing dictionary by key in Django template | 19,745,091 | 16 | 2013-11-02T18:08:56Z | 19,745,156 | 35 | 2013-11-02T18:15:51Z | [
"python",
"django",
"json"
] | I'm passing a dictionary from my view to a template. So `{"key1":"value1","key2":"value2"}` is passed in and looping through key,value pairs is fine, however I've not found an elegant solution from access directly in the view from a specific key, say `"key1"` for example bu json.items["key1"]. I could use some if/then ... | The Django template language supports looking up dictionary keys as follows:
```
{{ json.key1 }}
```
See the template docs on [variables and lookups](https://docs.djangoproject.com/en/stable/ref/templates/api/#variables-and-lookups).
The template language does not provide a way to display `json[key]`, where `key` is... |
Run Python localhost through Grunt | 19,746,279 | 4 | 2013-11-02T20:05:46Z | 19,749,139 | 12 | 2013-11-03T02:10:06Z | [
"python",
"gruntjs"
] | I am relatively new to Gruntjs, but I've managed to get everything running automatically, except my localhost.
How can I make Grunt run `python manage.py runserver 0.0.0.0:8000 --insecure` ? | You can use grunt-shell <https://github.com/sindresorhus/grunt-shell>
Try something like this:
```
grunt.initConfig({
shell: {
pythonServer: {
options: {
stdout: true
},
command: 'python manage.py runserver 0.0.0.0:8000 --insecure'
}
}
});
g... |
Trouble with Django sending email though smtp.gmail.com | 19,746,783 | 4 | 2013-11-02T20:57:56Z | 20,874,184 | 11 | 2014-01-01T23:01:02Z | [
"python",
"django",
"smtp"
] | I am trying to configure Django's send\_email so I can send password reset emails to users. So far I've had no luck on getting it to work. I've set up a basic Gmail account (no Google App etc) and in my Django **settings.py** i have:
```
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_PASSWORD = 'my_password'
EMAIL_HOST... | You have made a typo in your settings. TLS should be set with EMAIL\_USE\_TLS not MAIL\_USE\_TLS. Not using TLS while connecting to 587 generates this error. |
Python exit commands - why so many and when should each be used? | 19,747,371 | 141 | 2013-11-02T22:00:32Z | 19,747,557 | 20 | 2013-11-02T22:22:20Z | [
"python"
] | It seems that python supports many different commands to stop script execution.
The choices I've found are: `quit()`, `exit()`, `sys.exit()`, `os._exit()`
Have I missed any?
What's the difference between them? When would you use each? | The functions\* `quit()`, `exit()`, and `sys.exit()` function in the same way: they raise the `SystemExit` exception. So there is no real difference, except that `sys.exit()` is always available but `exit()` and `quit()` are only available if the `site` module is imported.
The `os._exit()` function is special, it exit... |
Python exit commands - why so many and when should each be used? | 19,747,371 | 141 | 2013-11-02T22:00:32Z | 19,747,562 | 245 | 2013-11-02T22:22:32Z | [
"python"
] | It seems that python supports many different commands to stop script execution.
The choices I've found are: `quit()`, `exit()`, `sys.exit()`, `os._exit()`
Have I missed any?
What's the difference between them? When would you use each? | Let me give some information on them:
1. [`quit`](http://docs.python.org/2/library/constants.html#quit) raises the [`SystemExit`](http://docs.python.org/2/library/exceptions.html#exceptions.SystemExit) exception behind the scenes.
Furthermore, if you print it, it will give a message:
```
>>> print (quit)
... |
Python exit commands - why so many and when should each be used? | 19,747,371 | 141 | 2013-11-02T22:00:32Z | 19,751,330 | 8 | 2013-11-03T09:02:08Z | [
"python"
] | It seems that python supports many different commands to stop script execution.
The choices I've found are: `quit()`, `exit()`, `sys.exit()`, `os._exit()`
Have I missed any?
What's the difference between them? When would you use each? | `sys.exit` is the canonical way to exit.
Internally `sys.exit` just raises `SystemExit`. However, calling `sys.exit`is more idiomatic than raising `SystemExit`directly.
`os.exit` is a low-level system call that exits directly whiteout calling any cleanup handlers.
`quit`and `exit` exist only to provide an easy way o... |
Understanding this Pandas script | 19,748,000 | 2 | 2013-11-02T23:15:32Z | 19,787,433 | 8 | 2013-11-05T11:01:17Z | [
"python",
"python-2.7",
"numpy",
"pandas",
"comments"
] | I received this code to group data into a histogram type data. I have been Attempting to understand the code in this pandas script in order to edit, manipulate and duplicate it. I have comments for the sections I understand.
### Code
```
import numpy as np
import pandas as pd
column_names = ['col1', 'col2', 'col3',... | I'll try and explain my code. As it uses a few tricks.
* I've called it `df` to give a shorthand name for a pandas DataFrame
* I've called it `dfg` to mean group my `df`.
* Let me build up the expression `dfg = df[['bin','col7','col11']].groupby('bin').agg({'col11': [np.mean], 'col7': [count_ones, len]})`
+ the cod... |
Print is blocking forever when printing unicode subclass instance from IDLE | 19,749,757 | 3 | 2013-11-03T04:15:20Z | 19,749,827 | 7 | 2013-11-03T04:30:17Z | [
"python",
"unicode",
"python-idle"
] | When executing the following lines with an IDLE prompt, the execution is blocking forever at the last line.
```
>>> class Foo(unicode):
pass
>>> foo = Foo('bar')
>>> print str(foo) # prints bar
>>> print repr(foo) # prints u'bar'
>>> print foo # blocks forever!!
```
This is weird because it i... | FYI, after reproducing, I opened a bug report for you, here:
<http://bugs.python.org/issue19481> |
Is there any way to access denominator of a fraction in Python 2 | 19,750,416 | 8 | 2013-11-03T06:27:48Z | 19,750,433 | 10 | 2013-11-03T06:30:46Z | [
"python",
"python-2.7",
"fractions"
] | Is there any way to access the denominator in a fraction in Python 2?
For example, I have a variable:
> x = fractions.Fraction(4,1)
And I want to access its denominator. How do I do that? | ```
>>> from fractions import Fraction
>>> a = Fraction(1,2)
>>> a.denominator
2
```
Additionally Python's `help()` method can be very useful to determine exactly what methods and properties exist for an object. In the example above you could get a help description for the `Fraction` object by `help(Fraction)` or `hel... |
Python's in (__contains__) operator returns a bool whose value is neither True nor False | 19,751,556 | 32 | 2013-11-03T09:38:26Z | 19,751,586 | 45 | 2013-11-03T09:41:08Z | [
"python",
"boolean",
"membership",
"comparison-operators"
] | As expected, 1 is not contained by the empty tuple
```
>>> 1 in ()
False
```
but the `False` value returned is not equal to `False`
```
>>> 1 in () == False
False
```
Looking at it another way, the `in` operator returns a `bool` which is neither `True` nor `False`:
```
>>> type(1 in ())
<type 'bool'>
>>> 1 in () =... | You are running into comparison operator chaining; `1 in () == False` does **not** mean `(1 in ()) == False`.
Rather, comparisons are chained and the expression really means:
```
(1 in ()) and (() == False)
```
Because `(1 in ())` is already false, the second half of the chained expression is ignored altogether (sin... |
django paginator - how to show all page numbers available | 19,751,806 | 4 | 2013-11-03T10:10:43Z | 19,751,837 | 8 | 2013-11-03T10:14:16Z | [
"python",
"django",
"pagination"
] | I have simple issue:
I have this `{{ objects.paginator.num_pages }}` in template, which gives me the total number of pages that contain items.
now i want to show those page numbers like this
```
1 | 2 | 3 | 4 | 5
```
to achieve this, i need to make forloop till `the num_pages`. like `for i to num_pages`.
how is it... | You can use [`page_range`](https://docs.djangoproject.com/en/dev/topics/pagination/#django.core.paginator.Paginator.page_range)
```
{% for page in objects.paginator.page_range %}
{% if forloop.counter != 1 %} | {% endif %}
{{ page }}
{% endfor %}
``` |
django paginator - how to show all page numbers available | 19,751,806 | 4 | 2013-11-03T10:10:43Z | 25,822,994 | 14 | 2014-09-13T11:59:21Z | [
"python",
"django",
"pagination"
] | I have simple issue:
I have this `{{ objects.paginator.num_pages }}` in template, which gives me the total number of pages that contain items.
now i want to show those page numbers like this
```
1 | 2 | 3 | 4 | 5
```
to achieve this, i need to make forloop till `the num_pages`. like `for i to num_pages`.
how is it... | Formatted with twitter bootstrap and with links:
```
<ul class="pagination nav navbar-nav">
{% if objects.has_previous %}
<li><a href="?page={{ objects.previous_page_number }}">Prev</a></li>
{% endif %}
{% for page in objects.paginator.page_range %}
<li class="{% if objects.number == p... |
Repeat a tuple inside a tuple | 19,753,279 | 7 | 2013-11-03T13:07:35Z | 19,753,291 | 11 | 2013-11-03T13:08:50Z | [
"python",
"tuples"
] | Is there a way to repeat a tuple inside a tuple ?
If I do something like
```
a = ((0, 1) * n)
```
I still get
```
a = (0, 1, 0, 1 ..... n times)
```
what if I want something like
```
a = ((0, 1), (0, 1) ... n times)
``` | Multiply a tuple with a tuple as its item. Don't forget a trailing `,`.
```
>>> ((0, 1),) * 5
((0, 1), (0, 1), (0, 1), (0, 1), (0, 1))
``` |
Difference between Class variables and Instance variables | 19,753,897 | 2 | 2013-11-03T14:14:10Z | 19,753,997 | 7 | 2013-11-03T14:25:17Z | [
"python",
"class",
"oop"
] | I have already read many answers here on Stack Exchange like [Python - why use "self" in a class?](http://stackoverflow.com/questions/475871/python-why-use-self-in-a-class)
After reading these I understand that instance variables are unique to each instance of the class while the class variable is shared across all ins... | Class variables are *shadowed* by instance attribute. This means that when looking up an attribute, Python first looks in the instance, then in the class. Furthermore, setting a variable on an object (e.g. `self`) always creates an instance variable - it never changes the class variable.
This means that when, in your ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.