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 |
|---|---|---|---|---|---|---|---|---|---|
find_package() errors during installing package via pip | 29,477,456 | 7 | 2015-04-06T18:42:35Z | 29,477,720 | 10 | 2015-04-06T18:58:39Z | [
"python",
"pip"
] | I'm tring to install **django-dbsettings** with pip but it causes the following error:
```
Downloading django-dbsettings-0.7.4.tar.gz
Running setup.py egg_info for package django-dbsettings
Traceback (most recent call last):
File "<string>", line 16, in <module>
File "/path/virtualenv/build/django-dbsettings/setup... | There is no `include` keyword in `find_packages()` using older versions of setuptools, you need to upgrade:
```
pip install -U setuptools
```
I would also update pip. |
There is no South database module 'south.db.postgresql_psycopg2' for your database | 29,478,400 | 14 | 2015-04-06T19:41:10Z | 30,435,113 | 57 | 2015-05-25T09:28:33Z | [
"python",
"django",
"django-south"
] | i new to django and I'm getting this error from south but i don't know what i'm missing. I search for answers but i can't found anything.
```
There is no South database module 'south.db.postgresql_psycopg2' for your database. Please either choose a supported database, check for SOUTH_DATABASE_ADAPTER[S] settings, or r... | Try `pip uninstall South`, then you will see if your application is 1.8 ready. |
Docker Compose vs. Dockerfile - which is better? | 29,480,099 | 24 | 2015-04-06T21:36:43Z | 29,487,120 | 22 | 2015-04-07T08:28:57Z | [
"python",
"django",
"docker",
"boot2docker",
"docker-compose"
] | I have been reading up and learning about [Docker](https://docs.docker.com/), and am trying to correctly choose the Django setup to use. So far there is either:
[Docker Compose](https://docs.docker.com/compose/) or [Dockerfile](https://docs.docker.com/reference/builder/)
I understand that `Dockerfiles` are used in `D... | The answer is neither.
Docker Compose (herein referred to as compose) will use the Dockerfile if you add the build command to your project's `docker-compose.yml`.
Your Docker workflow should be to build a suitable `Dockerfile` for each image you wish to create, then use compose to assemble the images using the `build... |
How can I tell if a string repeats itself in Python? | 29,481,088 | 320 | 2015-04-06T23:02:09Z | 29,481,228 | 173 | 2015-04-06T23:18:16Z | [
"python",
"string",
"pattern-matching"
] | I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.
Examples:
```
[
'0045662100456621004566210045662100456621', # '00456621'
'0072992700729927007299270072992700729927', # '00729927'
'001443001443001443001443001443001443001443', ... | Here's a solution using regular expressions.
```
import re
REPEATER = re.compile(r"(.+?)\1+$")
def repeated(s):
match = REPEATER.match(s)
return match.group(1) if match else None
```
Iterating over the examples in the question:
```
examples = [
'0045662100456621004566210045662100456621',
'007299270... |
How can I tell if a string repeats itself in Python? | 29,481,088 | 320 | 2015-04-06T23:02:09Z | 29,481,244 | 37 | 2015-04-06T23:20:38Z | [
"python",
"string",
"pattern-matching"
] | I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.
Examples:
```
[
'0045662100456621004566210045662100456621', # '00456621'
'0072992700729927007299270072992700729927', # '00729927'
'001443001443001443001443001443001443001443', ... | Non-regex solution:
```
def repeat(string):
for i in range(1, len(string)//2+1):
if not len(string)%len(string[0:i]) and string[0:i]*(len(string)//len(string[0:i])) == string:
return string[0:i]
```
Faster non-regex solution, thanks to @ThatWeirdo (see comments):
```
def repeat(string):
l... |
How can I tell if a string repeats itself in Python? | 29,481,088 | 320 | 2015-04-06T23:02:09Z | 29,481,262 | 89 | 2015-04-06T23:22:51Z | [
"python",
"string",
"pattern-matching"
] | I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.
Examples:
```
[
'0045662100456621004566210045662100456621', # '00456621'
'0072992700729927007299270072992700729927', # '00729927'
'001443001443001443001443001443001443001443', ... | You can make the observation that for a string to be considered repeating, its length must be divisible by the length of its repeated sequence. Given that, here is a solution that generates divisors of the length from `1` to `n / 2` inclusive, divides the original string into substrings with the length of the divisors,... |
How can I tell if a string repeats itself in Python? | 29,481,088 | 320 | 2015-04-06T23:02:09Z | 29,482,465 | 16 | 2015-04-07T01:55:31Z | [
"python",
"string",
"pattern-matching"
] | I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.
Examples:
```
[
'0045662100456621004566210045662100456621', # '00456621'
'0072992700729927007299270072992700729927', # '00729927'
'001443001443001443001443001443001443001443', ... | Here's a straight forward solution, without regexes.
For substrings of `s` starting from zeroth index, of lengths 1 through `len(s)`, check if that substring, `substr` is the repeated pattern. This check can be performed by concatenating `substr` with itself `ratio` times, such that the length of the string thus forme... |
How can I tell if a string repeats itself in Python? | 29,481,088 | 320 | 2015-04-06T23:02:09Z | 29,482,830 | 23 | 2015-04-07T02:42:00Z | [
"python",
"string",
"pattern-matching"
] | I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.
Examples:
```
[
'0045662100456621004566210045662100456621', # '00456621'
'0072992700729927007299270072992700729927', # '00729927'
'001443001443001443001443001443001443001443', ... | First, halve the string as long as it's a "2 part" duplicate. This reduces the search space if there are an even number of repeats. Then, working forwards to find the smallest repeating string, check if splitting the full string by increasingly larger sub-string results in only empty values. Only sub-strings up to `len... |
How can I tell if a string repeats itself in Python? | 29,481,088 | 320 | 2015-04-06T23:02:09Z | 29,482,936 | 81 | 2015-04-07T02:55:24Z | [
"python",
"string",
"pattern-matching"
] | I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.
Examples:
```
[
'0045662100456621004566210045662100456621', # '00456621'
'0072992700729927007299270072992700729927', # '00729927'
'001443001443001443001443001443001443001443', ... | Here are some benchmarks for the various answers to this question. There were some surprising results, including wildly different performance depending on the string being tested.
Some functions were modified to work with Python 3 (mainly by replacing `/` with `//` to ensure integer division). If you see something wro... |
How can I tell if a string repeats itself in Python? | 29,481,088 | 320 | 2015-04-06T23:02:09Z | 29,484,962 | 16 | 2015-04-07T06:13:35Z | [
"python",
"string",
"pattern-matching"
] | I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.
Examples:
```
[
'0045662100456621004566210045662100456621', # '00456621'
'0072992700729927007299270072992700729927', # '00729927'
'001443001443001443001443001443001443001443', ... | This version tries only those candidate sequence lengths that are factors of the string length; and uses the `*` operator to build a full-length string from the candidate sequence:
```
def get_shortest_repeat(string):
length = len(string)
for i in range(1, length // 2 + 1):
if length % i: # skip non-f... |
How can I tell if a string repeats itself in Python? | 29,481,088 | 320 | 2015-04-06T23:02:09Z | 29,489,919 | 536 | 2015-04-07T10:58:10Z | [
"python",
"string",
"pattern-matching"
] | I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.
Examples:
```
[
'0045662100456621004566210045662100456621', # '00456621'
'0072992700729927007299270072992700729927', # '00729927'
'001443001443001443001443001443001443001443', ... | Here's a concise solution which avoids regular expressions and slow in-Python loops:
```
def principal_period(s):
i = (s+s).find(s, 1, -1)
return None if i == -1 else s[:i]
```
See the [Community Wiki answer](http://stackoverflow.com/a/29482936/2447250) started by @davidism for benchmark results. In summary,
... |
How can I tell if a string repeats itself in Python? | 29,481,088 | 320 | 2015-04-06T23:02:09Z | 29,519,746 | 16 | 2015-04-08T16:04:38Z | [
"python",
"string",
"pattern-matching"
] | I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.
Examples:
```
[
'0045662100456621004566210045662100456621', # '00456621'
'0072992700729927007299270072992700729927', # '00729927'
'001443001443001443001443001443001443001443', ... | The problem may also be solved in `O(n)` in worst case with prefix function.
Note, it may be slower in general case(UPD: and is much slower) than other solutions which depend on number of divisors of `n`, but usually find fails sooner, I think one of bad cases for them will be `aaa....aab`, where there are `n - 1 = 2 ... |
How can I tell if a string repeats itself in Python? | 29,481,088 | 320 | 2015-04-06T23:02:09Z | 29,543,743 | 9 | 2015-04-09T16:15:01Z | [
"python",
"string",
"pattern-matching"
] | I'm looking for a way to test whether or not a given string repeats itself for the entire string or not.
Examples:
```
[
'0045662100456621004566210045662100456621', # '00456621'
'0072992700729927007299270072992700729927', # '00729927'
'001443001443001443001443001443001443001443', ... | I started with more than eight solutions to this problem. Some were bases on regex (match, findall, split), some of string slicing and testing, and some with string methods (find, count, split). Each had benefits in code clarity, code size, speed and memory consumption. I was going to post my answer here when I noticed... |
Unable to upgrade python six package in mac osx 10.10.2 | 29,485,741 | 7 | 2015-04-07T07:04:42Z | 29,498,533 | 10 | 2015-04-07T18:24:28Z | [
"python",
"osx",
"pip",
"six"
] | I am trying to install latest version of six python package but I have following issues. Can't get rid of six 1.4.1 in mac OSX 10.10.2
```
sudo pip install six --upgrade
Requirement already up-to-date: six in /Library/Python/2.7/site-packages
Cleaning up...
pip search six
six - Python 2 and 3 compatibility utilities
... | Your `pip` binary belongs to `/usr/local/bin/python`, whereas `python` points to `/usr/bin/python`. As a consequence
```
pip install --upgrade six
```
will install to `/usr/local/bin/python`.
The command below will make sure that the right version of pip is used:
```
python -m pip install --upgrade six
``` |
Unable to upgrade python six package in mac osx 10.10.2 | 29,485,741 | 7 | 2015-04-07T07:04:42Z | 33,956,146 | 8 | 2015-11-27T11:13:58Z | [
"python",
"osx",
"pip",
"six"
] | I am trying to install latest version of six python package but I have following issues. Can't get rid of six 1.4.1 in mac OSX 10.10.2
```
sudo pip install six --upgrade
Requirement already up-to-date: six in /Library/Python/2.7/site-packages
Cleaning up...
pip search six
six - Python 2 and 3 compatibility utilities
... | For me, just using [homebrew](http://brew.sh/) fixed everything.
```
brew install python
``` |
Pypi: Not allowed to store or edit package information | 29,485,874 | 4 | 2015-04-07T07:13:11Z | 29,562,043 | 7 | 2015-04-10T12:54:50Z | [
"python",
"packages",
"setuptools",
"pypi"
] | Pypi problems: Not allowed to store or edit package information. I'm following [this tutorial](http://peterdowns.com/posts/first-time-with-pypi.html%20%22this%20tutorial%22.).
.pypirc
```
[distutils]
index-servers =
pypi
pypitest
[pypi]
respository: https://pypi.python.org/pypi
username: Redacted
password: R... | From this list one can see all the packages on PyPi:
<https://pypi.python.org/simple/>
*quick* is there. The question author says he/she cannot create quick package, so he/she is not the package author on PyPi and somebody else has created a package with the same name before. |
Bare words / new keywords in Python | 29,492,895 | 5 | 2015-04-07T13:31:10Z | 29,492,897 | 7 | 2015-04-07T13:31:10Z | [
"python",
"keyword",
"bareword"
] | I wanted to see if it was possible to define new keywords or, as they're called in [WAT's Destroy All Software talk](https://www.destroyallsoftware.com/talks/wat) when discussing Ruby, bare words, in Python.
I came up with an answer that I couldn't find elsewhere, so I decided to share it Q&A style on StackOverflow. | I've only tried this in the REPL, outside any block, so far. It may be possible to make it work elsewhere, too.
I put this in my python startup file:
```
def bareWordHandler(type_, value, traceback_):
if isinstance(value, SyntaxError):
import traceback
# You can probably modify this next line so ... |
How to compile OpenCV with OpenMP | 29,494,503 | 2 | 2015-04-07T14:49:05Z | 30,619,632 | 7 | 2015-06-03T12:05:21Z | [
"python",
"c++",
"opencv",
"raspberry-pi",
"raspberry-pi2"
] | A user in [this SOF post](http://stackoverflow.com/questions/28938644/opencv-multi-core-support) suggests building OpenCV with a `WITH_OPENMP` flag to enable (some) multi-core support. I have tried building OpenCV-2.4.10 with OpenMP but I am unable to then import cv2 in Python.
**Note:** I am able to build and use Ope... | I had a similiar question. cmake with -D WITH\_OPENMP=ON worked fine for me. |
Asyncio Making HTTP Requests Slower? | 29,495,598 | 5 | 2015-04-07T15:43:03Z | 29,498,115 | 7 | 2015-04-07T18:01:34Z | [
"python",
"performance",
"python-3.x",
"benchmarking",
"python-asyncio"
] | I'm using Asyncio and Requests to benchmark a series of HTTP requests.
For some reason, it's slightly slower to use Asyncio than just straight Requests. Any idea why? Am I using Asyncio incorrectly?
```
import asyncio
import functools
import requests
import time
ts = time.time()
for i in range(10):
@asyncio.corout... | You are waiting for each request to finish before you start the next one. So you have the overhead of the event loop with no benefits.
Try this:
```
import asyncio
import functools
import requests
import time
ts = time.time()
loop = asyncio.get_event_loop()
@asyncio.coroutine
def do_checks():
futures = []
f... |
Plot bar graph from Pandas DataFrame | 29,498,652 | 7 | 2015-04-07T18:30:59Z | 29,499,109 | 10 | 2015-04-07T18:56:00Z | [
"python",
"pandas",
"plot"
] | Assuming i have a `DataFrame` that looks like this:
```
Hour | V1 | V2 | A1 | A2
0 | 15 | 13 | 25 | 37
1 | 26 | 52 | 21 | 45
2 | 18 | 45 | 45 | 25
3 | 65 | 38 | 98 | 14
```
Im trying to create a bar plot to compare columns `V1` and `V2` by the `Hour`.
When I do:
```
import matplotlib.pyplot as plt
ax... | To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:
```
ax = df[['V1','V2']].plot(kind='bar', title ="V comp",figsize=(15,10),legend=True, fontsize=12)
```
What you tried was `df['V1','V2']` this will raise a `KeyError` as correctly no column ex... |
How to check if there is only consecutive ones and zeros in bytestream | 29,499,638 | 2 | 2015-04-07T19:25:23Z | 29,500,110 | 9 | 2015-04-07T19:52:44Z | [
"python",
"algorithm",
"bit-manipulation"
] | I want to check if an int/long consists only of one set of consecutive ones or zero. For example `111100000`, `1100000` but not `101000`.
I have a basic implementation as follows:
```
def is_consecutive(val):
count = 0
while val %2 == 0:
count += 1
val = val >> 1
... | For a number `n`, `n | (n - 1)` will be all ones *if and only if* it meets the pattern you describe.
A number `x` that is all ones is one less than a power of two. You can [check for a power of two by ANDing it with itself minus one](https://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2). Or in othe... |
How to install numpy on windows using pip install? | 29,499,815 | 10 | 2015-04-07T19:35:27Z | 29,503,549 | 7 | 2015-04-08T00:01:09Z | [
"python",
"python-2.7",
"visual-c++",
"numpy",
"pip"
] | I want to install numpy using `pip install numpy` command but i get follwing error:
```
RuntimeError: Broken toolchain: cannot link a simple C program
```
I'm using windows 7 32bit, python 2.7.9, pip 6.1.1 and some MSVC compiler. I think it uses compiler from Visual C++ 2010 Express, but actually I'm not sure which o... | Installing extension modules can be an issue with pip. This is why conda exists. conda is an open-source BSD-licensed cross-platform package manager. It can easily install NumPy.
Two options:
* Install Anaconda [here](http://www.continuum.io/downloads)
* Install Miniconda [here](http://repo.continuum.io/miniconda/ind... |
How to install numpy on windows using pip install? | 29,499,815 | 10 | 2015-04-07T19:35:27Z | 34,587,391 | 8 | 2016-01-04T08:45:38Z | [
"python",
"python-2.7",
"visual-c++",
"numpy",
"pip"
] | I want to install numpy using `pip install numpy` command but i get follwing error:
```
RuntimeError: Broken toolchain: cannot link a simple C program
```
I'm using windows 7 32bit, python 2.7.9, pip 6.1.1 and some MSVC compiler. I think it uses compiler from Visual C++ 2010 Express, but actually I'm not sure which o... | Frustratingly the Numpy package published to PyPI won't install on most Windows computers <https://github.com/numpy/numpy/issues/5479>
Instead:
1. Download the Numpy wheel for your Python version from <http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy>
2. Install it from the command line `pip install numpy-1.10.2+mkl-... |
Bradley adaptive thresholding algorithm | 29,502,241 | 7 | 2015-04-07T22:08:23Z | 29,503,184 | 7 | 2015-04-07T23:28:27Z | [
"python",
"python-imaging-library",
"adaptive-threshold"
] | I am currently working on implementing a thresholding algorithm called `Bradley Adaptive Thresholding`.
I have been following mainly two links in order to work out how to implement this algorithm. I have also successfully been able to implement two other thresholding algorithms, mainly, [Otsu's Method](http://en.wikip... | You cannot create the integral image with PIL the way that you are doing it because the image that you are packing data into cannot accept values over 255. The values in the integral image get very large because they are the sums of the pixels above and to the left (see page 3 of your white paper). They will grow much ... |
aiohttp - exception ignored message | 29,502,779 | 7 | 2015-04-07T22:52:09Z | 29,503,234 | 7 | 2015-04-07T23:33:30Z | [
"python",
"python-3.x",
"python-asyncio",
"aiohttp"
] | I'm running the following code which makes 5 requests via aiohttp:
```
import aiohttp
import asyncio
def fetch_page(url, idx):
try:
url = 'http://google.com'
response = yield from aiohttp.request('GET', url)
print(response.status)
except Exception as e:
print(e)
def main():
... | I'm not exactly sure why, but it seems that leaving the `aiohttp.ClientResponse` object open is causing an unraisable exception to be thrown when the interpreter exits. On my system, this results in warnings like this, rather than "Exception ignored in" messages:
```
sys:1: ResourceWarning: unclosed <socket object at ... |
using the * (splat) operator with print | 29,503,331 | 2 | 2015-04-07T23:40:29Z | 29,503,361 | 8 | 2015-04-07T23:43:08Z | [
"python",
"python-2.7"
] | I often use Python's `print` statement to display data. Yes, I know about the `'%s %d' % ('abc', 123)` method, and the `'{} {}'.format('abc', 123)` method, and the `' '.join(('abc', str(123)))` method. I also know that the splat operator (`*`) can be used to expand an iterable into function arguments. However, I can't ... | `print` is a statement in Python 2.x and does not support the `*` syntax. You can see this from the grammar for `print` listed in the [documentation](https://docs.python.org/2/reference/simple_stmts.html#grammar-token-print_stmt):
```
print_stmt ::= "print" ([expression ("," expression)* [","]]
| ">>"... |
How to get all values from python enum class? | 29,503,339 | 12 | 2015-04-07T23:41:10Z | 29,503,414 | 7 | 2015-04-07T23:47:55Z | [
"python",
"django",
"enums"
] | I'm using Enum4 library to create an enum class as follows:
```
class Color(Enum):
RED = 1
BLUE = 2
```
I want to print `[1, 2]` as a list somewhere. How can I achieve this? | You can use [IntEnum](https://docs.python.org/3/library/enum.html#intenum):
```
from enum import IntEnum
class Color(IntEnum):
RED = 1
BLUE = 2
print(int(Color.RED)) # prints 1
```
To get list of the ints:
```
enum_list = list(map(int, Color))
print(enum_list) # prints [1, 2]
``` |
How to get all values from python enum class? | 29,503,339 | 12 | 2015-04-07T23:41:10Z | 29,503,454 | 35 | 2015-04-07T23:51:35Z | [
"python",
"django",
"enums"
] | I'm using Enum4 library to create an enum class as follows:
```
class Color(Enum):
RED = 1
BLUE = 2
```
I want to print `[1, 2]` as a list somewhere. How can I achieve this? | You can do the following:
```
[e.value for e in Color]
``` |
Why do new style class and old style class have different behavior in this case? | 29,511,332 | 11 | 2015-04-08T09:50:53Z | 29,519,325 | 10 | 2015-04-08T15:45:23Z | [
"python",
"python-3.x",
"python-2.x",
"python-internals"
] | I found something interesting, here is a snippet of code:
```
class A(object):
def __init__(self):
print "A init"
def __del__(self):
print "A del"
class B(object):
a = A()
```
If I run this code, I will get:
```
A init
```
But if I change `class B(object)` to `class B()`, I will get:
... | TL;DR: this is an [old issue](http://bugs.python.org/issue1545463) in CPython, that was finally fixed in [CPython 3.4](https://docs.python.org/3/whatsnew/3.4.html#pep-442-safe-object-finalization). Objects kept live by reference cycles that are referred to by module globals are not properly finalized on interpreter exi... |
Is there a way to rerun an Upgrade Step in Plone? | 29,513,201 | 3 | 2015-04-08T11:21:14Z | 29,515,070 | 8 | 2015-04-08T12:48:09Z | [
"python",
"python-2.7",
"plone",
"plone-4.x"
] | I've got a Plone 4.2.4 application and from time to time I need to create an Upgrade Step.
So, I register it in the `configure.zcml`, create the function to invoke and increase the profile version number in the `metadata.xml` file.
However, it might happen that something goes not really as expected during the upgrade... | Go to `portal_setup` (from ZMI), then:
* go in the "Upgrades" tab
* select your profile (the one where you defined the metadata.xml)
From here you commonly can run upgrade step not yet ran. In your case click on the "Show" button of "Show old upgrades". |
Get request body as string in Django | 29,514,077 | 10 | 2015-04-08T12:02:53Z | 29,514,222 | 16 | 2015-04-08T12:10:00Z | [
"python",
"django"
] | I'm sending a POST request with JSON body to a Django server (fairly standard). On the server I need to decode this using `json.loads()`.
The problem is how do I get the body of the request in a string format?
I have the following code currently:
```
body_data = {}
if request.META.get('CONTENT_TYPE', '').lower() == ... | The request body, `request.body`, is a byte string. In Python 3, `json.loads()` will only accept a unicode string, so you must decode `request.body` before passing it to `json.loads()`.
```
body_unicode = request.body.decode('utf-8')
body_data = json.loads(body_unicode)
```
In Python 2, `json.loads` will accept a uni... |
"sudo pip install Django" => sudo: pip: command not found | 29,514,136 | 4 | 2015-04-08T12:06:02Z | 29,514,178 | 10 | 2015-04-08T12:08:00Z | [
"python",
"django",
"terminal",
"install"
] | This what my terminal is saying when trying to install Django.
```
MacBook-XXXX:~ Stephane$ sudo pip install Django
sudo: pip: command not found
```
I have tested in idle shell if pip is installed:
```
>>> import easy_install
>>> import pip
>>>
```
What am I doing wrong? | you need to install pip
```
sudo easy_install pip
``` |
Filling WTForms FormField FieldList with data results in HTML in fields | 29,514,798 | 5 | 2015-04-08T12:35:27Z | 29,517,799 | 8 | 2015-04-08T14:39:08Z | [
"python",
"flask",
"wtforms",
"flask-wtforms",
"fieldlist"
] | I have a Flask app in which I can populate form data by uploading a CSV file which is then read. I want to populate a FieldList with the data read from the CSV. However, when I try to populate the data, it enters raw HTML into the TextFields instead of just the value that I want. What am I doing wrong?
**app.py**
```... | OK, I spent hours on this and in the end it was such a trivial code change.
Most fields let you change their value by modifying the `data` attribute (as I was doing above). In fact, in my code, I had this comment as above:
```
### either of these ways have the same end result.
#
# studentform = StudentFor... |
Add column to dataframe with default value | 29,517,072 | 12 | 2015-04-08T14:09:22Z | 29,517,089 | 12 | 2015-04-08T14:09:52Z | [
"python",
"pandas"
] | I have an existing dataframe which I need to add an additional column to which will contain the same value for every row.
Existing df:
```
Date, Open, High, Low, Close
01-01-2015, 565, 600, 400, 450
```
New df:
```
Name, Date, Open, High, Low, Close
abc, 01-01-2015, 565, 600, 400, 450
```
I know how to append an e... | `df['Name']='abc'` will add the new column and set all rows to that value:
```
In [79]:
df
Out[79]:
Date, Open, High, Low, Close
0 01-01-2015, 565, 600, 400, 450
In [80]:
df['Name'] = 'abc'
df
Out[80]:
Date, Open, High, Low, Close Name
0 01-01-2015, 565, 600, 400, 450 abc
``` |
error while following Tumblelog Application with Flask and MongoEngine | 29,517,930 | 8 | 2015-04-08T14:44:49Z | 29,518,117 | 11 | 2015-04-08T14:51:23Z | [
"python",
"mongodb",
"flask",
"flask-mongoengine"
] | I am following tumbleblog application [here](http://docs.mongodb.org/ecosystem/tutorial/write-a-tumblelog-application-with-flask-mongoengine/)
my `__init__.py`:
```
from flask import Flask
from flask.ext.mongoengine import MongoEngine
app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {'DB': "sencha_web_service"... | In your MONGODB\_SETTINGS dictionary, the key for the database name should be 'db', not 'DB' (i.e. all lowercase).
The error you're getting is because the MongoEngine extension cannot find the 'db' entry in your configuration, and so uses 'default' as the database name.
**Edit**
Upon further inspection, it seems thi... |
numpy.asarray: how to check up that its result dtype is numeric? | 29,518,923 | 3 | 2015-04-08T15:27:28Z | 29,519,728 | 7 | 2015-04-08T16:04:03Z | [
"python",
"numpy"
] | I have to create a `numpy.ndarray` from array-like data with int, float or complex numbers.
I hope to do it with `numpy.asarray` function.
I don't want to give it a strict `dtype` argument, because I want to convert complex values to `complex64` or `complex128`, floats to `float32` or `float64`, etc.
But if I just s... | You could check if the dtype of the array is a sub-dtype of `np.number`. For example:
```
>>> np.issubdtype(np.complex128, np.number)
True
>>> np.issubdtype(np.int32, np.number)
True
>>> np.issubdtype(np.str_, np.number)
False
>>> np.issubdtype('O', np.number) # 'O' is object
False
```
Essentially, this just checks w... |
SQLAlchemy set default nullable=False | 29,522,557 | 4 | 2015-04-08T18:28:17Z | 29,522,697 | 11 | 2015-04-08T18:34:48Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] | I'm using SQLAlchemy for Flask to create some models. The problem is, nearly all my columns need `nullable=False`, so I'm looking for a way to set this option as default when creating a column. Surely I could add them manually (as a Vim exercise), but I just don't feel like it today. For a reference, this is how my set... | just create a wrapper that sets it
```
def NullColumn(*args,**kwargs):
kwargs["nullable"] = kwargs.get("nullable",True)
return db.Column(*args,**kwargs)
...
username = NullColumn(db.String(80))
```
using `functools.partial` as recommended in the comments
```
from functools import partial
NullColumn = partia... |
SQLAlchemy ORM conversion to pandas DataFrame | 29,525,808 | 24 | 2015-04-08T21:36:34Z | 29,528,804 | 43 | 2015-04-09T02:40:13Z | [
"python",
"pandas",
"sqlalchemy",
"flask-sqlalchemy"
] | This topic hasn't been addressed in a while, here or elsewhere. Is there a solution converting a SQLAlchemy `<Query object>` to a pandas DataFrame?
Pandas has the capability to use `pandas.read_sql` but this requires use of raw SQL. I have two reasons for wanting to avoid it: 1) I already have everything using the ORM... | Below should work in most cases:
```
df = pd.read_sql(query.statement, query.session.bind)
``` |
numpy.isnan(value) not the same as value == numpy.nan? | 29,528,092 | 4 | 2015-04-09T01:17:10Z | 29,528,160 | 7 | 2015-04-09T01:24:43Z | [
"python",
"numpy",
"types",
"boolean",
null
] | Why am I getting the following:
```
>>> v
nan
>>> type(v)
<type 'numpy.float64'>
>>> v == np.nan
False
>>> np.isnan(v)
True
```
I would have thought the two should be equivalent? | `nan != nan`. That's just how equality comparisons on `nan` are defined. It was decided that this result is more convenient for numerical algorithms than the alternative. This is specifically why `isnan` exists. |
Python pandas: check if any value is NaN in DataFrame | 29,530,232 | 50 | 2015-04-09T05:09:39Z | 29,530,559 | 26 | 2015-04-09T05:37:26Z | [
"python",
"pandas",
null
] | In python pandas, what's the best way to check whether a DataFrame has one (or more) NaN values?
I know about the function `pd.isnan`, but this returns a DataFrame of booleans for each element. [This post](http://stackoverflow.com/questions/27754891/python-nan-value-in-pandas) right here doesn't exactly answer my ques... | You have a couple options.
```
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10,6))
# Make a few areas have NaN values
df.iloc[1:3,1] = np.nan
df.iloc[5,3] = np.nan
df.iloc[7:9,5] = np.nan
```
Now the data frame looks something like this:
```
0 1 2 3 ... |
Python pandas: check if any value is NaN in DataFrame | 29,530,232 | 50 | 2015-04-09T05:09:39Z | 29,530,601 | 56 | 2015-04-09T05:39:54Z | [
"python",
"pandas",
null
] | In python pandas, what's the best way to check whether a DataFrame has one (or more) NaN values?
I know about the function `pd.isnan`, but this returns a DataFrame of booleans for each element. [This post](http://stackoverflow.com/questions/27754891/python-nan-value-in-pandas) right here doesn't exactly answer my ques... | [jwilner](http://stackoverflow.com/users/1567452/jwilner)'s response is spot on. I was exploring to see if there's a faster option, since in my experience, summing flat arrays is (strangely) faster than counting. This code seems faster:
```
df.isnull().values.any()
```
For example:
```
In [2]: df = pd.DataFrame(np.r... |
iPython/Jupyter Notebook and Pandas, how to plot multiple graphs in a for loop? | 29,532,894 | 5 | 2015-04-09T07:55:00Z | 29,533,687 | 7 | 2015-04-09T08:38:12Z | [
"python",
"pandas",
"matplotlib",
"plot",
"ipython-notebook"
] | Consider the following code running in iPython Notebook:
```
from pandas import *
%matplotlib inline
ys = [[0,1,2,3,4],[4,3,2,1,0]]
x_ax = [0,1,2,3,4]
for y_ax in ys:
ts = Series(y_ax,index=x_ax)
ts.plot(kind='bar', figsize=(15,5))
```
I would expect to have 2 separate plots as output, instead I got the two... | In the IPython notebook the best way to do this is often with subplots. You create multiple axes on the same figure and then render the figure in the notebook. For example:
```
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
ys = [[0,1,2,3,4],[4,3,2,1,0]]
x_ax = [0,1,2,3,4]
fig, axs = plt.sub... |
django admin error - Unknown column 'django_content_type.name' in 'field list' | 29,538,388 | 7 | 2015-04-09T12:23:07Z | 29,680,795 | 8 | 2015-04-16T16:29:45Z | [
"python",
"django"
] | My django project had a working admin page, but all of the sudden I started receiving:
`"Unknown column 'django_content_type.name' in 'field list'"` whenever I try to access the admin page. I can still access some portions of the admin, just not the main page.
I'm pretty new to django and python, so I have no idea whe... | I had this same issue just now and it was related to different versions of django. I updated all of the machines working on my project to django 1.8 using pip install -U Django and everything worked fine after that. |
Python 2 - How would you round up/down to the nearest 6 minutes? | 29,545,758 | 15 | 2015-04-09T18:02:27Z | 29,545,984 | 20 | 2015-04-09T18:16:06Z | [
"python",
"python-2.7",
"datetime"
] | There are numerous examples of people rounding to the nearest ten minutes but I can't figure out the logic behind rounding to the nearest six. I thought it would be a matter of switching a few numbers around but I can't get it to work.
The code I'm working with is located at [my Github](https://github.com/minorsecond/... | Here's a general function to round to nearest `x`:
```
def round_to_nearest(num, base):
n = num + (base//2)
return n - (n % base)
[round_to_nearest(i, 6) for i in range(20)]
# [0, 0, 0, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 12, 18, 18, 18, 18, 18]
```
Explanation:
* `n % base` is the remainder left over whe... |
Trouble installing pygame using pip install | 29,548,982 | 7 | 2015-04-09T21:04:29Z | 29,579,587 | 14 | 2015-04-11T15:28:32Z | [
"python",
"pygame",
"shared-libraries",
"pip"
] | I tried: `c:/python34/scripts/pip install http://bitbucket.org/pygame/pygame`
and got this error:
```
Cannot unpack file C:\Users\Marius\AppData\Local\Temp\pip-b60d5tho-unpack\pygame
(downloaded from C:\Users\Marius\AppData\Local\Temp\pip-rqmpq4tz-build, conte
nt-type: text/html; charset=utf-8); cannot detect archiv... | This is the only method that works for me.
```
pip install pygame==1.9.1release --allow-external pygame --allow-unverified pygame
```
--
These are the steps that lead me to this command (I put them so people finds it easily):
```
$ pip install pygame
Collecting pygame
Could not find any downloads that satisfy the... |
how to split column of tuples in pandas dataframe? | 29,550,414 | 7 | 2015-04-09T22:50:38Z | 29,550,458 | 12 | 2015-04-09T22:55:11Z | [
"python",
"numpy",
"pandas",
"dataframe",
"tuples"
] | I have a pandas dataframe (this is only a little piece)
```
>>> d1
y norm test y norm train len(y_train) len(y_test) \
0 64.904368 116.151232 1645 549
1 70.852681 112.639876 1645 549
SVR RBF \
0 (35.652207342877873, 22... | You can do this by `apply(pd.Series)` on that column:
```
In [13]: df = pd.DataFrame({'a':[1,2], 'b':[(1,2), (3,4)]})
In [14]: df
Out[14]:
a b
0 1 (1, 2)
1 2 (3, 4)
In [16]: df['b'].apply(pd.Series)
Out[16]:
0 1
0 1 2
1 3 4
In [17]: df[['b1', 'b2']] = df['b'].apply(pd.Series)
In [18]: df
Out[1... |
how to split column of tuples in pandas dataframe? | 29,550,414 | 7 | 2015-04-09T22:50:38Z | 33,763,855 | 7 | 2015-11-17T17:58:08Z | [
"python",
"numpy",
"pandas",
"dataframe",
"tuples"
] | I have a pandas dataframe (this is only a little piece)
```
>>> d1
y norm test y norm train len(y_train) len(y_test) \
0 64.904368 116.151232 1645 549
1 70.852681 112.639876 1645 549
SVR RBF \
0 (35.652207342877873, 22... | On much larger datasets, I found that `.apply()` is few orders slower than `pd.DataFrame(df['b'].values.tolist())` |
Algorithm to group sets of points together that follow a direction | 29,550,785 | 29 | 2015-04-09T23:26:46Z | 29,561,234 | 10 | 2015-04-10T12:17:33Z | [
"python",
"image",
"algorithm",
"matlab",
"image-processing"
] | **Note: I am placing this question in both the MATLAB and Python tags as I am the most proficient in these languages. However, I welcome solutions in any language.**
---
# Question Preamble
I have taken an image with a fisheye lens. This image consists of a pattern with a bunch of square objects. What I want to do w... | Note 1: It has a number of settings -> which for other images may need to altered to get the result you want *see % Settings - play around with these values*
Note 2: It doesn't find all of the lines you want -> but its a starting point....
To call this function, invoke this in the command prompt:
```
>> [h, v] = tes... |
Why is "if not (a and b)" faster than "if not a or not b"? | 29,551,438 | 21 | 2015-04-10T00:39:18Z | 29,551,787 | 24 | 2015-04-10T01:21:36Z | [
"python",
"python-2.7",
"if-statement",
"logical-operators",
"micro-optimization"
] | On a whim, I recently tested these two methods with `timeit`, to see which evaluation method was faster:
```
import timeit
"""Test method returns True if either argument is falsey, else False."""
def and_chk((a, b)):
if not (a and b):
return True
return False
def not_or_chk((a, b)):
if not a or ... | ## TL;DR
The `not_or_chk` function requires two unary operations in *addition* to two jumps (in the worst case), while the `and_chk` function only has the two jumps (again, in the worst case).
## Details
The [dis module](https://docs.python.org/2/library/dis.html) to the rescue! The `dis` module lets you take a look... |
Python program running in PyCharm but not from the command line | 29,553,668 | 5 | 2015-04-10T04:54:12Z | 29,553,778 | 8 | 2015-04-10T05:03:26Z | [
"python",
"startup",
"fedora"
] | When I try to run my program from the PyCharm IDE everything works fine but if I type in Fedora:
```
python myScript.py
```
in a shell prompt I get an import error from 1 of the module.
```
ImportError : No modue named myDependency.
```
What does PyCharm do that allows the interpreter to find my dependencies when l... | There are a few possible things that can be causing this:
1. The same python interpreter? Check with `import sys; print(sys.executable)`
2. Is it the same working directory? Check with `import os; print(os.getcwd())`
3. Discrepancies in `sys.path`, which is the list python searches sequentially for import locations, c... |
Django 1.8 HStore field throwing Progamming Error | 29,557,782 | 4 | 2015-04-10T09:22:19Z | 29,566,352 | 11 | 2015-04-10T16:28:39Z | [
"python",
"database",
"postgresql",
"psycopg2",
"django-1.8"
] | I'm following the code in the documentation
```
from django.contrib.postgres.fields import HStoreField
from django.db import models
class Dog(models.Model):
name = models.CharField(max_length=200)
data = HStoreField()
def __str__(self): # __unicode__ on Python 2
return self.name
```
Running thi... | Ensure you add `'django.contrib.postgres'` to `settings.INSTALLED_APPS`. |
How can I generate a list of consecutive numbers? | 29,558,007 | 6 | 2015-04-10T09:34:50Z | 29,558,077 | 9 | 2015-04-10T09:38:41Z | [
"python",
"list",
"python-3.x"
] | Say if you had a number input `8` in python and you wanted to generate a list of consecutive numbers up to `8` like
```
[0, 1, 2, 3, 4, 5, 6, 7, 8]
```
How could you do this? | In Python 3, you can use the builtin [`range`](https://docs.python.org/3/library/functions.html#func-range) function like this
```
>>> list(range(9))
[0, 1, 2, 3, 4, 5, 6, 7, 8]
```
**Note 1:** Python 3.x's `range` function, returns a `range` object. If you want a list you need to explicitly convert that to a list, w... |
How to suppress the deprecation warnings in Django? | 29,562,070 | 23 | 2015-04-10T12:56:43Z | 29,983,195 | 8 | 2015-05-01T07:32:52Z | [
"python",
"django",
"django-admin"
] | Every time I'm using the `django-admin` command â even on TABâcompletion â it throws a `RemovedInDjango19Warning` (and a lot more if I use the *test* command). How can I suppress those warnings?
I'm using Django 1.8 with Python 3.4 (in a virtual environment).
As far as I can tell, all those warnings come from l... | In manage.py, add this to the top line --
```
#!/usr/bin/env PYTHONWARNINGS=ignore python
```
This will suppress all warnings, which I agree can in some situations be undesirable if you're using a lot of third party libraries.
Disclaimer: Recommended only after you've already seen the warnings at least 1,000 too man... |
How to suppress the deprecation warnings in Django? | 29,562,070 | 23 | 2015-04-10T12:56:43Z | 31,103,483 | 27 | 2015-06-28T18:48:37Z | [
"python",
"django",
"django-admin"
] | Every time I'm using the `django-admin` command â even on TABâcompletion â it throws a `RemovedInDjango19Warning` (and a lot more if I use the *test* command). How can I suppress those warnings?
I'm using Django 1.8 with Python 3.4 (in a virtual environment).
As far as I can tell, all those warnings come from l... | Adding a logging filter to settings.py can suppress these console warnings (at least for manage.py commands in Django 1.7, Python 3.4).
A filter can selectively suppress warnings. The following code creates a new "suppress\_deprecated" filter for the console and appends it to the default logging filters. Add this bloc... |
How to suppress the deprecation warnings in Django? | 29,562,070 | 23 | 2015-04-10T12:56:43Z | 34,895,696 | 8 | 2016-01-20T09:07:53Z | [
"python",
"django",
"django-admin"
] | Every time I'm using the `django-admin` command â even on TABâcompletion â it throws a `RemovedInDjango19Warning` (and a lot more if I use the *test* command). How can I suppress those warnings?
I'm using Django 1.8 with Python 3.4 (in a virtual environment).
As far as I can tell, all those warnings come from l... | Nothing of the above have worked for me, django 1.9. I fixed this by adding the following lines to settings.py:
```
import logging
def filter_deprecation_warnings(record):
warnings_to_suppress = [
'RemovedInDjango110Warning'
]
# Return false to suppress message.
return not any([warn in recor... |
Conditional mocking: Call original function if condition does match | 29,562,460 | 7 | 2015-04-10T13:17:12Z | 29,563,665 | 7 | 2015-04-10T14:11:08Z | [
"python",
"mocking"
] | How can I conditionally call the orignal method in a mock?
In this example I only want to fake a return value if `bar=='x'`. Otherwise I want to call the original method.
```
def mocked_some_method(bar):
if bar=='x':
return 'fake'
return some_how_call_original_method(bar)
with mock.patch('mylib.foo.s... | If you need just replace behavior without care of mock's calls assert function you can use `new` argument; otherwise you can use [`side_effect`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect) that take a callable.
I guess that `some_method` is a object method (instead of a `static... |
How do I load session and cookies from Selenium browser to requests library in Python? | 29,563,335 | 6 | 2015-04-10T13:56:12Z | 29,563,698 | 9 | 2015-04-10T14:12:24Z | [
"python",
"selenium-webdriver",
"python-requests"
] | How can I load session and cookies from Selenium browser? The following code:
```
import requests
cookies = [{u'domain': u'academics.vit.ac.in',
u'name': u'ASPSESSIONIDAEQDTQRB',
u'value': u'ADGIJGJDDGLFIIOCEZJHJCGC',
u'expiry': None, u'path': u'/',
u'secure': True}]
re... | First you have to get the cookies from your driver instance:
```
cookies = driver.get_cookies()
```
This returns a [set of cookie dictionaries](http://selenium-python.readthedocs.io/api.html?highlight=get_cookies#selenium.webdriver.remote.webdriver.WebDriver.get_cookies) for your session.
Next, set those cookies in ... |
Why don't I get any syntax errors when I execute my Python script with Perl? | 29,563,832 | 80 | 2015-04-10T14:19:28Z | 29,563,961 | 110 | 2015-04-10T14:25:08Z | [
"python",
"perl"
] | I just wrote some testing python code into `test.py`, and I'm launching it as follows:
```
perl test.py
```
After a while I realized my mistake. I say "after a while", because the
Python code gets actually correctly executed, as if in Python interpreter!
Why is my Perl interpreting my Python? `test.py` looks like th... | From [perlrun](http://perldoc.perl.org/perlrun.html),
> If the `#!` line does not contain the word "perl" nor the word "indir" the program named after the `#!` is executed instead of the Perl interpreter. This is slightly bizarre, but it helps people on machines that don't do `#!` , because they can tell a program tha... |
Most pythonic way to remove tuples from a list if first element is a duplicate | 29,563,953 | 2 | 2015-04-10T14:24:48Z | 29,564,118 | 8 | 2015-04-10T14:32:40Z | [
"python",
"list",
"tuples"
] | The code I have so far is pretty ugly:
```
orig = [(1,2),(1,3),(2,3),(3,3)]
previous_elem = []
unique_tuples = []
for tuple in orig:
if tuple[0] not in previous_elem:
unique_tuples += [tuple]
previous_elem += [tuple[0]]
assert unique_tuples == [(1,2),(2,3),(3,3)]
```
There must be a more pythonic solu... | If you don't care which tuple round you return for duplicates, you could always convert your list to a dictionary and back:
```
>>> orig = [(1,2),(1,3),(2,3),(3,3)]
>>> list(dict(orig).items())
[(1, 3), (2, 3), (3, 3)]
```
If you want to return the ***first*** tuple round, you could reverse your list twice and use an... |
Avoiding code repetition in default arguments in Python | 29,566,400 | 14 | 2015-04-10T16:31:40Z | 29,566,493 | 7 | 2015-04-10T16:36:36Z | [
"python",
"default",
"argument-passing"
] | Consider a typical function with default arguments:
```
def f(accuracy=1e-3, nstep=10):
...
```
This is compact and easy to understand. But what if we have another function `g` that will call `f`, and we want to pass on some arguments of `g` to `f`? A natural way of doing this is:
```
def g(accuracy=1e-3, nstep=... | Define global constants:
```
ACCURACY = 1e-3
NSTEP = 10
def f(accuracy=ACCURACY, nstep=NSTEP):
...
def g(accuracy=ACCURACY, nstep=NSTEP):
f(accuracy, nstep)
```
---
If `f` and `g` are defined in different modules, then you could make a `constants.py` module too:
```
ACCURACY = 1e-3
NSTEP = 10
```
and the... |
Generators and for loops in Python | 29,570,348 | 21 | 2015-04-10T20:42:45Z | 29,570,364 | 45 | 2015-04-10T20:44:01Z | [
"python",
"generator"
] | So I have a generator function, that looks like this.
```
def generator():
while True:
for x in range(3):
for j in range(5):
yield x
```
After I load up this function and call "next" a bunch of times, I'd expect it to yield values
`0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 0 0 0 0 0 ...`
... | `generator()` initializes new generator object:
```
In [4]: generator() is generator() # Creating 2 separate objects
Out[4]: False
```
Then `generator().next()` gets the first value from the newly created generator object (*0* in your case).
You should call `generator` once:
```
In [5]: gen = generator() # Storing ... |
Generators and for loops in Python | 29,570,348 | 21 | 2015-04-10T20:42:45Z | 29,570,452 | 17 | 2015-04-10T20:49:30Z | [
"python",
"generator"
] | So I have a generator function, that looks like this.
```
def generator():
while True:
for x in range(3):
for j in range(5):
yield x
```
After I load up this function and call "next" a bunch of times, I'd expect it to yield values
`0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 0 0 0 0 0 ...`
... | With each call of `generator` you are creating a new generator object:
```
generator().next() # 1st item in 1st generator
generator().next() # 1st item in 2nd generator
```
Create one generator, and then call the `next` for subsequent items:
```
g = generator()
g.next() # 1st item in 1st generator
g.next() # 2nd i... |
Django not able to render context when in shell | 29,571,606 | 6 | 2015-04-10T22:26:01Z | 29,571,809 | 8 | 2015-04-10T22:46:44Z | [
"python",
"django",
"shell",
"django-templates",
"django-context"
] | This is what I am trying to run. When I run the server and run these lines within a view and then return an HttpResponse, then everything goes fine. However when I run `python manage.py shell` and then try to run through these lines then I get an error:
```
product = Product.objects.get(pk=4)
template = loader.get_tem... | This is a known issue and will be fixed in 1.8.1.
Meanwhile, you can manually activate a language in your shell to fix it:
```
from django.utils.translation import activate
activate('en') # or any language code
```
**UPDATE**: 1.8.1 has been released, so the best solution is to upgrade to the latest 1.8.x version. |
Remove multiple elements from a list of index with Python | 29,571,621 | 4 | 2015-04-10T22:27:54Z | 29,571,633 | 7 | 2015-04-10T22:29:14Z | [
"python",
"list",
"collections"
] | I have a list of values, and a list of indices, and I need to remove the elements that the indices point to.
This is my solution, but I don't like the implementation as it requires to import packages, doesn't work when the values contain maxint, and iterate over the values multiple times.
```
def remove_abnormalities... | This should work:
```
def remove_abnormalities(values, indices):
return [val for i, val in enumerate(values) if i not in indices]
```
Additionally you can turn `indices` into a set before filtering for more performance, if the number of indices is large. |
Test if python Counter is contained in another Counter | 29,575,660 | 3 | 2015-04-11T08:12:23Z | 29,576,074 | 8 | 2015-04-11T09:07:48Z | [
"python",
"algorithm",
"counter",
"inclusion"
] | How to test if a python [`Counter`](https://docs.python.org/2/library/collections.html#collections.Counter) is *contained* in another one using the following definition:
> *A Counter `a` is contained in a Counter `b` if, and only if, for every key `k` in `a`, the value `a[k]` is less or equal to the value `b[k]`. The ... | While `Counter` instances are not comparable with the `<` and `>` operators, you can find their difference with the `-` operator. The difference never returns negative counts, so if `A - B` is empty, you know that `B` contains all the items in `A`.
```
def contains(larger, smaller):
return not smaller - larger
``` |
Django migration file in an other app? | 29,575,802 | 4 | 2015-04-11T08:31:49Z | 29,587,968 | 7 | 2015-04-12T09:32:21Z | [
"python",
"django",
"django-models",
"django-admin"
] | Let's imagine a following simplified Django project:
```
<root>/lib/python2.7/site-packages/externalapp/shop
<root>/myapp
```
`myapp` also extends `externalapp.shop.models` models by adding a few fields. `manage.py makemigrations` did generated following schema migration file called *0004\_auto\_20150410\_2001.py*:
... | To move a migration file around a Django project, like in case of injecting models of other applications, you need to ensure in your `django.db.migrations.Migration` descendant:
* explicitly set application name, as migrations loader derives it automatically by app where migration file resides and would attempt to per... |
Shuffle DataFrame rows | 29,576,430 | 12 | 2015-04-11T09:47:57Z | 29,576,803 | 20 | 2015-04-11T10:26:59Z | [
"python",
"pandas",
"dataframe",
"permutation",
"shuffle"
] | I have the following DataFrame:
```
Col1 Col2 Col3 Type
0 1 2 3 1
1 4 5 6 1
...
20 7 8 9 2
21 10 11 12 2
...
45 13 14 15 3
46 16 17 18 3
...
```
The DataFrame is read from a csv file. All rows which have `Type` 1 are on to... | You can shuffle the rows of a dataframe by indexing with a shuffled index. For this, you can eg use `np.random.permutation` (but `np.random.choice` is also a possibility):
```
In [12]: df = pd.read_csv(StringIO(s), sep="\s+")
In [13]: df
Out[13]:
Col1 Col2 Col3 Type
0 1 2 3 1
1 4 5 ... |
Shuffle DataFrame rows | 29,576,430 | 12 | 2015-04-11T09:47:57Z | 34,879,805 | 31 | 2016-01-19T14:49:17Z | [
"python",
"pandas",
"dataframe",
"permutation",
"shuffle"
] | I have the following DataFrame:
```
Col1 Col2 Col3 Type
0 1 2 3 1
1 4 5 6 1
...
20 7 8 9 2
21 10 11 12 2
...
45 13 14 15 3
46 16 17 18 3
...
```
The DataFrame is read from a csv file. All rows which have `Type` 1 are on to... | The more idiomatic way to do this with pandas is to use the `.sample` method of your dataframe, i.e.
```
df.sample(frac=1)
```
The `frac` keyword argument specifies the fraction of rows to return in the random sample, so `frac=1` means return all rows (in random order).
**Note:**
*If you wish to shuffle your datafra... |
How to make an object both a Python2 and Python3 iterator? | 29,578,469 | 3 | 2015-04-11T13:34:53Z | 29,578,499 | 13 | 2015-04-11T13:38:09Z | [
"python",
"python-2.7",
"python-3.x",
"iterator"
] | [This Stack Overflow post](http://stackoverflow.com/questions/19151/build-a-basic-python-iterator) is about making an object an iterator in Python.
In Python 2, that means you need to implement an `__iter__()` method, and a `next()` method. But in Python 3, you need to implement a *different* method, instead of `next(... | Just give it both `__next__` and `next` method; one can be an alias of the other:
```
class Iterator(object):
def __iter__(self):
return self
def __next__(self):
# Python 3
return 'a value'
next = __next__ # Python 2
``` |
Still can't install scipy due to missing fortran compiler after brew install gcc on Mac OC X | 29,586,487 | 15 | 2015-04-12T06:00:41Z | 29,596,528 | 15 | 2015-04-13T01:10:47Z | [
"python",
"osx",
"numpy",
"fortran",
"homebrew"
] | I have read and followed [this answer](http://stackoverflow.com/questions/14821297/scipy-build-install-mac-osx) to install scipy/numpy/theano. However, it still failed on the same error of missing Fortran compiler after brew install gcc. While HomeBrew installed the gcc-4.8, it didn't install any gfortran or g95 comman... | Fixed by upgrading pip, even though I just installed my pip/virtualenv the first time anew on the same day.
```
(mypy)MAC0227: $ pip install --upgrade pip
...
(mypy)MAC0227: $ pip install theano
/Users/me/.virtualenvs/mypy/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:79: InsecurePlatf... |
Still can't install scipy due to missing fortran compiler after brew install gcc on Mac OC X | 29,586,487 | 15 | 2015-04-12T06:00:41Z | 34,038,311 | 11 | 2015-12-02T08:46:53Z | [
"python",
"osx",
"numpy",
"fortran",
"homebrew"
] | I have read and followed [this answer](http://stackoverflow.com/questions/14821297/scipy-build-install-mac-osx) to install scipy/numpy/theano. However, it still failed on the same error of missing Fortran compiler after brew install gcc. While HomeBrew installed the gcc-4.8, it didn't install any gfortran or g95 comman... | The following worked for me:
`sudo apt-get install gfortran`
on my system:
Ubuntu 15.10 (Linux 4.2.0-19-generic #23-Ubuntu x86\_64 x86\_64 x86\_64 GNU/Linux) |
How to find the length of a leading sequence in a string? | 29,586,698 | 3 | 2015-04-12T06:32:40Z | 29,586,719 | 7 | 2015-04-12T06:36:45Z | [
"python",
"string"
] | I'd like to count the number of leading spaces in a string.What's the most Pythonic way of doing this?
```
>>>F(' ' * 5 + 'a')
5
```
(update) Here are timings of several of the answers:
```
import timeit
>>> timeit.timeit("s.index(re.search(r'\S',s).group())", number=10000, setup="import re;s=' a'")
0.0273840427... | Using [`re` module](https://docs.python.org/2/howto/regex.html)
```
>>> s
' a'
>>> import re
>>> s.index(re.search(r'\S',s).group())
5
```
Using [`itertools`](https://docs.python.org/2/library/itertools.html#itertools.takewhile)
```
>>> import itertools
>>> len([i for i in itertools.takewhile(str.isspace,s)])
5
... |
How do I install Hadoop and Pydoop on a fresh Ubuntu instance | 29,588,595 | 4 | 2015-04-12T10:51:47Z | 30,322,610 | 9 | 2015-05-19T10:08:07Z | [
"python",
"ubuntu",
"hadoop",
"amazon-web-services"
] | Most of the setup instructions I see are verbose. Is there a near script-like set of commands that we can just execute to set up Hadoop and Pydoop on an Ubuntu instance on Amazon EC2? | Another solution would be to use Juju (Ubuntu's service orchestration framework).
First install the Juju client on your standard computer:
```
sudo add-apt-repository ppa:juju/stable
sudo apt-get update && sudo apt-get install juju-core
```
(instructions for MacOS and Windows are also available [here](https://jujuch... |
Django: how to check if username already exists | 29,588,808 | 4 | 2015-04-12T11:17:53Z | 29,588,913 | 8 | 2015-04-12T11:28:54Z | [
"python",
"django",
"validation",
"registration",
"username"
] | i am not very advanced user of Django. I have seen many different methods online, but they all are for modified models or too complicated for me to understand.
I am reusing the `UserCreationForm` in my `MyRegistrationForm`
```
class MyRegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
... | You can use [exists](https://docs.djangoproject.com/en/1.8/ref/models/querysets/#django.db.models.query.QuerySet.exists):
```
if User.objects.filter(username=self.cleaned_data['username']).exists():
# Username exists
...
``` |
Plot width settings in ipython notebook | 29,589,119 | 16 | 2015-04-12T11:48:45Z | 29,612,806 | 19 | 2015-04-13T18:48:02Z | [
"python",
"matplotlib",
"ipython",
"ipython-notebook"
] | I've got the following plots:

It would look nicer if they have the same width. Do you have any idea how to do it in ipython notebook when I am using `%matplotlib inline`?
**UPDATE:**
To generate both figures I am using the following functions:
```
import numpy a... | If you use `%pylab inline` you can (on a new line) insert the following command:
```
%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)
```
This will set all figures in your document (unless otherwise specified) to be of the size `(10, 6)`, where the first entry is the width and the second is the height.
See t... |
Plot width settings in ipython notebook | 29,589,119 | 16 | 2015-04-12T11:48:45Z | 34,787,587 | 16 | 2016-01-14T10:46:17Z | [
"python",
"matplotlib",
"ipython",
"ipython-notebook"
] | I've got the following plots:

It would look nicer if they have the same width. Do you have any idea how to do it in ipython notebook when I am using `%matplotlib inline`?
**UPDATE:**
To generate both figures I am using the following functions:
```
import numpy a... | If you're not in an ipython notebook (like the OP), you can also just declare the size when you declare the figure:
```
width = 12
height = 12
plt.figure(figsize=(width, height))
``` |
How should I handle inclusive ranges in Python? | 29,596,045 | 29 | 2015-04-12T23:55:32Z | 29,596,068 | 12 | 2015-04-12T23:59:12Z | [
"python",
"range",
"slice"
] | I am working in a domain in which ranges are conventionally described inclusively. I have human-readable descriptions such as `from A to B` , which represent ranges that include both end points - e.g. `from 2 to 4` means `2, 3, 4`.
What is the best way to work with these ranges in Python code? The following code works... | Write an additional function for inclusive slice, and use that instead of slicing. While it would be possible to e.g. subclass list and implement a `__getitem__` reacting to a slice object, I would advise against it, since your code will behave contrary to expectation for anyone but you â and probably to you, too, in... |
How should I handle inclusive ranges in Python? | 29,596,045 | 29 | 2015-04-12T23:55:32Z | 29,700,201 | 7 | 2015-04-17T13:11:56Z | [
"python",
"range",
"slice"
] | I am working in a domain in which ranges are conventionally described inclusively. I have human-readable descriptions such as `from A to B` , which represent ranges that include both end points - e.g. `from 2 to 4` means `2, 3, 4`.
What is the best way to work with these ranges in Python code? The following code works... | Since in Python, the ending index is always exclusive, it's worth considering to always use the "Python-convention" values internally. This way, you will save yourself from mixing up the two in your code.
Only ever deal with the "external representation" through dedicated conversion subroutines:
```
def text2range(te... |
import check_arrays from sklearn | 29,596,237 | 14 | 2015-04-13T00:26:17Z | 29,616,386 | 16 | 2015-04-13T22:51:45Z | [
"python",
"scikit-learn",
"svm"
] | I'm trying to use a svm function from the scikit learn package for python but I get the error message:
```
from sklearn.utils.validation import check_arrays
```
> ImportError: cannot import name 'check\_arrays'
I'm using python 3.4. Can anyone give me an advice? Thanks in advance. | This method was removed in 0.16, replaced by a (very different) `check_array` function.
You are likely getting this error because you didn't upgrade from 0.15 to 0.16 properly. [Or because you relied on a not-really-public function in sklearn]. See <http://scikit-learn.org/dev/install.html#canopy-and-anaconda-for-all-s... |
How to uninstall mini conda? python | 29,596,350 | 11 | 2015-04-13T00:43:47Z | 29,616,442 | 14 | 2015-04-13T22:58:15Z | [
"python",
"pip",
"uninstall",
"conda",
"miniconda"
] | I've install the conda package as such:
```
$ wget http://bit.ly/miniconda
$ bash miniconda
$ conda install numpy pandas scipy matplotlib scikit-learn nltk ipython-notebook seaborn
```
I want to uninstall it because it's messing up my pips and environment.
* **How do I uninstall conda totally?**
* **Will it uninstal... | In order to [uninstall miniconda](http://docs.continuum.io/anaconda/install.html#id6), simply remove the `miniconda` folder,
```
rm -r ~/miniconda/
```
this should not remove any of your pip installed packages (but you should check the contents of the `~/miniconda` folder to confirm).
As to avoid conflicts between d... |
How to pip install cairocffi? | 29,596,426 | 6 | 2015-04-13T00:54:39Z | 29,596,525 | 8 | 2015-04-13T01:10:25Z | [
"python",
"install",
"pip",
"cairo",
"python-cffi"
] | **How do I install `cairocffi` through `pip`?**
`cairocffi` is a CFFI-based drop-in replacement for `Pycairo` <https://github.com/SimonSapin/cairocffi>.
I'm trying to install it on Ubuntu 14.04:
```
alvas@ubi:~$ cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="U... | It's right in the error message:
```
No package 'libffi' found
```
You'll need to install **`libffi`** and **`libffi-dev`** through your distro's package manager (`yum`, `apt-get`, whatever) before the `pip` installation will work. Their names may very slightly from platform to platform. |
Python regex explanation needed - $ character usage | 29,599,122 | 5 | 2015-04-13T06:33:44Z | 29,599,140 | 8 | 2015-04-13T06:35:09Z | [
"python",
"regex"
] | My apologies for a completely newbie question. I did try searching stackoverflow first before posting this question.
I am trying to learn regex using python from diveintopython3.net. While fiddling with the examples, I failed to understand one particular output
for a regex search (shown below):
```
>>> pattern = 'M?M... | > Why does the above regex pattern match the input text?
Because you made the previous `M`'s as optional. `M?` refers an optional `M`. `M` may or maynot present. So the above regex `'M?M?M?$'` matches only the zero width end of the line boundary. Hence you got a match. |
regex.sub() gives different results to re.sub() | 29,602,177 | 14 | 2015-04-13T09:38:37Z | 29,602,793 | 13 | 2015-04-13T10:09:36Z | [
"python",
"regex",
"python-3.x"
] | I work with [Czech](http://en.wikipedia.org/wiki/Czechs) accented text in Python 3.4.
Calling [`re.sub()`](https://docs.python.org/3.4/library/re.html#re.sub) to perform substitution by regex on an accented sentence works well, but using a regex compiled with [`re.compile()`](https://docs.python.org/3.4/library/re.htm... | As [Padraic Cunningham figured out](http://stackoverflow.com/a/29602850/908494), this is not actually a bug.
However, it is *related* to a bug which you didn't run into, and to you using a flag you probably shouldn't be using, so I'll leave my earlier answer below, even though his is the right answer to your problem.
... |
regex.sub() gives different results to re.sub() | 29,602,177 | 14 | 2015-04-13T09:38:37Z | 29,602,850 | 9 | 2015-04-13T10:12:59Z | [
"python",
"regex",
"python-3.x"
] | I work with [Czech](http://en.wikipedia.org/wiki/Czechs) accented text in Python 3.4.
Calling [`re.sub()`](https://docs.python.org/3.4/library/re.html#re.sub) to perform substitution by regex on an accented sentence works well, but using a regex compiled with [`re.compile()`](https://docs.python.org/3.4/library/re.htm... | The last argument in the compile is `flags`, if you actually use `flags=flags` in the `re.sub` you will see the same behaviour:
```
compiled = re.compile(pattern, flags)
print(compiled)
text = 'PoplatnÃkem danÄ z pozemků je vlastnÃk pozemku'
mark = r'**\1**' # wrap 1st matching group in double stars
r = re.sub(pa... |
TemplateDoesNotExist in project folder django 1.8 | 29,610,085 | 2 | 2015-04-13T16:12:25Z | 29,610,501 | 16 | 2015-04-13T16:35:34Z | [
"python",
"django",
"django-templates",
"django-views",
"django-1.8"
] | I have structured my application Django (Django 1.8) as shown below.
When I try template in app1 or app2 extends base.html in base.html of my application, I get this error.
```
TemplateDoesNotExist at /
base.html
Error during template rendering
In template /myProject/project_folder/app1/templates/app1/base.html, erro... | You need to tell Django what is the additional location of your template folder (`projekt_folder/template`) which is not under installed apps, add following lines at top of your settings file:
```
import os
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
```
Then set `DIRS` in `TEMPLATES` setting var:
```... |
Why numpy/scipy is faster without OpenBLAS? | 29,616,487 | 4 | 2015-04-13T23:02:55Z | 29,638,143 | 8 | 2015-04-14T22:01:31Z | [
"python",
"performance",
"numpy",
"scipy",
"openblas"
] | I made two installations:
1. `brew install numpy` (and scipy) `--with-openblas`
2. Cloned GIT repositories (for numpy and scipy) and built it myself
After I cloned two handy scripts for verification of these libraries in multi-threaded environment:
```
git clone https://gist.github.com/3842524.git
```
Then for each... | There are two obvious differences that might account for the discrepancy:
1. You are comparing two different versions numpy. The OpenBLAS-linked version you installed using Homebrew is 1.9.1, whereas the one you built from source is 1.10.0.dev0+3c5409e.
2. Whilst the newer version is not linked against OpenBLAS, it is... |
Is there a way to start android emulator in Travis CI build? | 29,622,597 | 3 | 2015-04-14T08:31:03Z | 29,625,997 | 7 | 2015-04-14T11:19:25Z | [
"android",
"python",
"unit-testing",
"adb",
"travis-ci"
] | I have [python wrapper-library for adb](https://github.com/vmalyi/adb-lib) where I have unit-test which depend on emulator or real device (since they execute adb commands).
I want also to use Travis CI as build environment along with executing those unit tests for each build.
Is there a way to have android emulator a... | According to the [Travis CI documentation](http://docs.travis-ci.com/user/languages/android/#How-to-Create-and-Start-an-Emulator), you can start an emulator with the following script in your `.travis.yml`:
```
# Emulator Management: Create, Start and Wait
before_script:
- echo no | android create avd --force -n test... |
Pytest where to store expected data | 29,627,341 | 3 | 2015-04-14T12:28:02Z | 29,631,801 | 9 | 2015-04-14T15:46:16Z | [
"python",
"py.test"
] | Testing function I need to pass parameters and see the output matches the expected output.
It is easy when function's response is just a small array or a one-line string which can be defined inside the test function, but suppose function I test modifies a config file which can be huge. Or the resulting array is someth... | I had a similar problem once, where I have to test configuration file against an expected file. That's how I fixed it:
1. Create a folder with the same name of your test module and at the same location. Put all your expected files inside that folder.
```
test_foo/
expected_config_1.ini
expected_co... |
Pretty-printing physical quantities with automatic scaling of SI prefixes | 29,627,796 | 10 | 2015-04-14T12:50:06Z | 29,749,228 | 8 | 2015-04-20T13:26:09Z | [
"python",
"units-of-measurement"
] | I am looking for an elegant way to pretty-print physical quantities with the most appropriate prefix (as in `12300 grams` are `12.3 kilograms`). A simple approach looks like this:
```
def pprint_units(v, unit_str, num_fmt="{:.3f}"):
""" Pretty printer for physical quantities """
# prefixes and power:
u_pre... | I have solved the same problem once. And IMHO with more elegance. No degrees or temperatures though.
```
def sign(x, value=1):
"""Mathematical signum function.
:param x: Object of investigation
:param value: The size of the signum (defaults to 1)
:returns: Plus or minus value
"""
return -value... |
Python get the smallest words between two characters | 29,632,847 | 3 | 2015-04-14T16:40:22Z | 29,632,905 | 7 | 2015-04-14T16:42:40Z | [
"python",
"regex",
"string"
] | How do I find the smallest string between two characters in python.
I tried this to extract words between `[[` and `]]` and put them into a list:
```
clause_text ="Bien_id [[bien_id.name]] dossier [[dossier_id.name]] "
list_variables = re.findall(re.escape("[[")+"(.*)"+re.escape("]]"),clause_text)
print list_variable... | You are looking for a non-greedy regex. Use `(.*?)` instead of `(.*)` |
Python reverse / inverse a mapping (but with multiple values for each key) | 29,633,848 | 4 | 2015-04-14T17:33:34Z | 29,633,896 | 7 | 2015-04-14T17:36:00Z | [
"python",
"dictionary",
"mapping",
"inverse"
] | This is really a variation on this question, but not a duplicate:
[Python reverse / inverse a mapping](http://stackoverflow.com/q/483666/992834)
Given a dictionary like so:
`mydict= { 'a': ['b', 'c'], 'd': ['e', 'f'] }`
How can one invert this dict to get:
`inv_mydict = { 'b':'a', 'c':'a', 'e':'d', 'f':'d' }`
Not... | ### TL;DR
Use dictionary comprehension, like this
```
>>> my_map = { 'a': ['b', 'c'], 'd': ['e', 'f'] }
>>> {value: key for key in my_map for value in my_map[key]}
{'c': 'a', 'f': 'd', 'b': 'a', 'e': 'd'}
```
---
The above seen dictionary comprehension is functionally equivalent to the following looping structure w... |
Django 1.9 deprecation warnings app_label | 29,635,765 | 39 | 2015-04-14T19:24:01Z | 29,703,136 | 29 | 2015-04-17T15:14:57Z | [
"python",
"django",
"deprecation-warning"
] | I've just updated to Django v1.8, and testing my local setup before updating my project and I've had a deprecation warning that I've never seen before, nor does it make any sense to me. I may be just overlooking something or misunderstanding the documentation.
```
/Users/neilhickman/Sites/guild/ankylosguild/apps/raidi... | As stated in the warning, this happens either :
* When you're using a model which is not in an `INSTALLED_APPS`;
* Or when you're using a model before its application is loaded.
Since you did refer the app in the `INSTALLED_APPS` setting, this is most likely you're using a model before the app initialisation.
Typica... |
Django 1.9 deprecation warnings app_label | 29,635,765 | 39 | 2015-04-14T19:24:01Z | 31,370,311 | 40 | 2015-07-12T17:01:28Z | [
"python",
"django",
"deprecation-warning"
] | I've just updated to Django v1.8, and testing my local setup before updating my project and I've had a deprecation warning that I've never seen before, nor does it make any sense to me. I may be just overlooking something or misunderstanding the documentation.
```
/Users/neilhickman/Sites/guild/ankylosguild/apps/raidi... | Similar error. In my case the error was:
`RemovedInDjango19Warning: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. This will no longer be supported in Django 1.9.
class Site(... |
Scatterplot without linear fit in seaborn | 29,637,150 | 8 | 2015-04-14T20:50:05Z | 29,644,094 | 15 | 2015-04-15T07:29:19Z | [
"python",
"matplotlib",
"seaborn"
] | I am wondering if there is a way to turn of the linear fit in seaborn's `lmplot` or if there is an equivalent function that just produces the scatterplot.
Sure, I could also use matplotlib, however, I find the syntax and aesthetics in seaborn quite appealing. E.g,. I want to plot the following plot
```
import seaborn ... | set `fit_reg` argument to `False`:
```
sns.lmplot("x", "y", data=df, hue='dataset', fit_reg=False)
``` |
Django - present current date and time in template | 29,637,768 | 2 | 2015-04-14T21:31:38Z | 29,637,791 | 8 | 2015-04-14T21:33:38Z | [
"python",
"django"
] | The tittle is pretty self explanatory. How can one present current data and time in django's template? | Try using built-in django template tags and filters:
<https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#now>
Example: `It is {% now "jS F Y H:i" %}` |
How to set a ProtoBuf field which is an empty message in Python? | 29,643,295 | 5 | 2015-04-15T06:44:11Z | 29,651,069 | 7 | 2015-04-15T13:05:27Z | [
"python",
"protocol-buffers"
] | The following are the contents of the Google Protocol Buffer (.proto) file
```
message First
{
required uint32 field1 = 1;
optional MessageType1 request = 2;
}
message MessageType1
{
}
```
I want to set the MessageType1 field request. But I get this as an error:
```
AttributeError: Assignment not allowed t... | Got this in the source code of Message class in Proto Buffer.
```
def SetInParent(self):
"""Mark this as present in the parent.
This normally happens automatically when you assign a field of a
sub-message, but sometimes you want to make the sub-message
present while keeping it empty. If you find yo... |
Tornado framework. TypeError: 'Future' object is not callable | 29,645,115 | 8 | 2015-04-15T08:20:54Z | 29,645,882 | 14 | 2015-04-15T08:58:02Z | [
"python",
"asynchronous",
"frameworks",
"tornado",
"python-asyncio"
] | I've started to learn Tornado framework sometime ago. I've faced the lack of documentation for unexperienced users and checked also asyncio module docs.
So the problem is, that I have some simple code in asyncio:
```
import asyncio
@asyncio.coroutine
def compute(x, y):
print("Compute %s + %s ..." ... | `run_sync` takes a function as argument. You are calling the function in-place and then giving the result as argument. You can create an anonymous function simply by using `lambda`:
```
IOLoop.instance().run_sync(lambda: print_sum(1,2))
``` |
Python zip by key | 29,645,415 | 3 | 2015-04-15T08:35:33Z | 29,645,569 | 9 | 2015-04-15T08:43:13Z | [
"python",
"list"
] | I'd like to combine (zip?) two python lists of tuples, but matching on a key.
e.g. I'd like to create a function that takes two input lists and produces an output like this:
```
lst1 = [(0, 1.1), (1, 1.2), (2, 1.3), (5, 2.5)]
lst2 = [ (1, 4.5), (2, 3.4), (4, 2.3), (5, 3.2)]
desiredOutput = [(1, 1.... | ```
>>> [(i, a, b) for i, a in lst1 for j, b in lst2 if i==j]
[(1, 1.2, 4.5), (2, 1.3, 3.4), (5, 2.5, 3.2)]
``` |
igraph Graph from numpy or pandas adjacency matrix | 29,655,111 | 11 | 2015-04-15T15:57:19Z | 29,673,192 | 15 | 2015-04-16T11:21:46Z | [
"python",
"numpy",
"pandas",
"igraph"
] | I have an adjacency matrix stored as a `pandas.DataFrame`:
```
node_names = ['A', 'B', 'C']
a = pd.DataFrame([[1,2,3],[3,1,1],[4,0,2]],
index=node_names, columns=node_names)
a_numpy = a.as_matrix()
```
I'd like to create an `igraph.Graph` from either the `pandas` or the `numpy` adjacency matrices. In an ideal wor... | In igraph you can use [`igraph.Graph.Adjacency`](http://igraph.org/python/doc/igraph.GraphBase-class.html#Adjacency) to create a graph from an adjacency matrix without having to use `zip`. There are some things to be aware of when a weighted adjacency matrix is used and stored in a `np.array` or `pd.DataFrame`.
* `igr... |
What does extra parameter mean in this for-loop in Python? | 29,655,449 | 6 | 2015-04-15T16:13:47Z | 29,655,554 | 7 | 2015-04-15T16:18:07Z | [
"python",
"for-loop"
] | I have come across a for-loop that is unusual to me. What does `method` mean in this for-loop?
`for method, config in self.myList.items():` | `items()` is a method used on python `dictionaries` to return an `iterable` holding `tuples` for each of the dictionary's `keys` and their corresponding `value`.
In Python you can unpack `lists` and `tuples` into variables using the method you've shown.
e.g.:
```
item1, item2 = [1,2]
# now we have item1 = 1, item2 =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.