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 |
|---|---|---|---|---|---|---|---|---|---|
Create range without certain numbers | 25,368,493 | 2 | 2014-08-18T17:06:28Z | 25,368,530 | 10 | 2014-08-18T17:08:40Z | [
"python"
] | I want to create a range `x` from `0 ... n`, without any of the numbers in the list `y`. How can I do this?
For example:
```
n = 10
y = [3, 7, 8]
x = # Do Something
```
Should give the output:
```
x = [0, 1, 2, 4, 5, 6, 9]
```
One naive way would be to concatonate several ranges, each spanning a set of numbers whi... | You can use a list comprehension to filter the range from `0` to `n`: `range(n)` generates a list (or, in Python 3, a generator object) from `0` to `n - 1` (including both ends):
```
x = [i for i in range(n) if i not in y]
```
This filters out all numbers in `y` from the range.
You can also turn it into a generator ... |
python `print` does not work in loop | 25,368,786 | 5 | 2014-08-18T17:25:19Z | 25,368,787 | 7 | 2014-08-18T17:25:19Z | [
"python",
"python-2.7"
] | I have multi loops in together and a sleep in the most inner loop. for example:
```
from time import sleep
for i in range(10):
print i,
for j in range(-5,5):
if j > 0:
print '.',
else:
print 'D',
sleep(1)
print ''
```
if you run the code, you may expected t... | Because of existence of comma, the output buffers until a `\n`.
You should flush the `stdout` after every print or use `sys.stdout.write` and flush buffer.
Define your print method:
```
import sys
def my_print(text):
sys.stdout.write(str(text))
sys.stdout.flush()
```
and at the end of line print a `\n` |
Caught exception is None | 25,371,732 | 13 | 2014-08-18T20:45:15Z | 25,371,794 | 17 | 2014-08-18T20:49:45Z | [
"python",
"python-2.7"
] | I have a script written in python2.7 where I, for debugging purposes, use a catch-all statement to catch and print all exceptions. For some reason, the exception caught is sometimes `None`. What could cause this to happen?
the code is something like this:
```
from __future__ import print_function
try:
run_arbitr... | Look at the type of the exception, I bet it's a KeyError:
```
try:
dict()[None]
except Exception as e:
print(type(e), e)
```
Output:
```
<class 'KeyError'> None
``` |
Python multiple inheritance constructor not called when using super() | 25,372,653 | 2 | 2014-08-18T21:55:15Z | 25,372,689 | 9 | 2014-08-18T21:57:40Z | [
"python",
"oop",
"inheritance",
"python-3.x",
"multiple-inheritance"
] | Consider the following code:
```
class A(object):
def __init__(self):
pass
class B(object):
def __init__(self):
self.something = 'blue'
def get_something(self):
return self.something
class C(A,B):
def __init__(self):
super().__init__()
print(self.get_something())... | Superclasses should use super if their subclasses do. If you add the `super().__init__()` line into A and B your example should work again.
Check the method resolution order of C:
```
>>> C.mro()
[__main__.C, __main__.A, __main__.B, builtins.object]
```
[This article](https://fuhm.net/super-harmful/) should clear th... |
python/pip error on osx | 25,372,911 | 13 | 2014-08-18T22:17:15Z | 25,373,020 | 44 | 2014-08-18T22:27:52Z | [
"python",
"osx"
] | I've recently purchased a new hard drive and installed a clean copy of OS X Mavericks. I installed python using homebrew and i need to create a python virtual environment. But when ever i try to run any command using pip, I get this error. I haven't been able to find a solution online for this problem. Any reference wo... | Ok I found out online that these errors are related to openssl. But i already had openssl installed. A little more research and I tried the following and it solved the issue for me. Here's my solution in case you get the same error.
```
brew install openssl
brew link openssl --force
brew uninstall python
brew install ... |
list of dictionary in jinja template | 25,373,154 | 9 | 2014-08-18T22:41:07Z | 25,375,815 | 15 | 2014-08-19T04:46:33Z | [
"python",
"flask",
"jinja"
] | How to iterate through the list of dictionaries in jinja template?
```
list1=[{"username": "abhi","pass": 2087}]
return render_template("file_output.html",lis=list1)
```
in the template
```
<table border=2>
<tr>
<td>
Key
</td>
<td>
Value
</td>
</tr>
{% for lis1 in lis %}
{% for key in lis1 %} ... | ### Data:
```
parent_dict = [{'A':'val1','B':'val2'},{'C':'val3','D':'val4'}]
```
### in Jinja2 iteration:
```
{% for dict_item in parent_dict %}
{% for key, value in dict_item.items() %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}
{% endfor %}
```
### Note:
make sure you have th... |
Delete unused packages from requirements file | 25,376,213 | 9 | 2014-08-19T05:28:39Z | 25,470,946 | 16 | 2014-08-24T10:53:29Z | [
"python",
"refactoring",
"pycharm",
"requirements"
] | Is there any easy way to delete no-more-using packages from **requirements** file?
I wrote a bash script for this task but, it doesn't work as I expected. Because, some packages are not used following their PyPI project names. For example;
```
dj-database-url
```
package is used as
```
dj_database_url
```
My proje... | You can use Code Inspection in [PyCharm](http://www.jetbrains.com/pycharm/).
Delete the contents of your `requirements.txt` but keep the empty file.
Load your project in, PyCharm go to `Code -> Inspect code...`. Choose `Whole project` option in dialog and click `OK`.
In inspection results panel locate `Package require... |
Python NotImplementedError: pool objects cannot be passed between processes | 25,382,455 | 6 | 2014-08-19T11:38:54Z | 25,385,582 | 7 | 2014-08-19T14:08:14Z | [
"python",
"multiprocessing",
"pool"
] | I'm trying to deliver work when a page is appended to the pages list, but my code output returns a NotImplementedError. Here is the code with what I'm trying to do:
**Code:**
```
from multiprocessing import Pool, current_process
import time
import random
import copy_reg
import types
import threading
class PageContr... | In order to pickle the instance method you're trying to pass to the `Pool`, Python needs to pickle the entire `PageControler` object, including its instance variables. One of those instance variables is the `Pool` object itself, and `Pool` objects can't be pickled, hence the error. You can work around this by implement... |
Flask tutorial - 404 Not Found | 25,383,187 | 3 | 2014-08-19T12:15:28Z | 25,383,455 | 7 | 2014-08-19T12:27:52Z | [
"python",
"python-2.7",
"flask",
"http-status-code-404"
] | I just finished the Flask basic tutorial ([here](http://flask.pocoo.org/docs/tutorial/)) and even though I've done completed every step, when I am trying
`python flaskr.py`
what I get is a `404 Not Found` error saying
`The requested URL was not found on the server. If you entered the URL manually please check your s... | You put your `app.run()` call **too early**:
```
if __name__== '__main__':
app.run()
```
This is executed before any of your routes are registered. Move these two lines to the *end* of your file.
Next, you have the first line in `show_entries()` is incorrect:
```
def show_entries():
db_get_db()
```
There i... |
How to refresh sys.path? | 25,384,922 | 5 | 2014-08-19T13:39:36Z | 25,384,923 | 8 | 2014-08-19T13:39:36Z | [
"python",
"python-2.7",
"packages",
"reload",
"sys.path"
] | I've installed some packages during the execution of my script as a user. Those packages were the first user packages, so python didn't add `~/.local/lib/python2.7/site-packages` to the `sys.path` before script run. I want to import those installed packages. But I cannot because they are not in `sys.path`.
How can I r... | As explained in [What sets up sys.path with Python, and when?](http://stackoverflow.com/questions/4271494/what-sets-up-sys-path-with-python-and-when) `sys.path` is populated with the help of builtin `site.py` module.
So you just need to reload it. You cannot it in one step because you don't have `site` in your namespa... |
Whats the difference between a OneToOne, ManyToMany, and a ForeignKey Field in Django? | 25,386,119 | 9 | 2014-08-19T14:32:30Z | 25,389,754 | 20 | 2014-08-19T17:45:10Z | [
"python",
"django",
"many-to-many",
"foreign-key-relationship",
"one-to-one"
] | I'm having a little difficulty getting my head around relationships in Django models.
Could someone explain what the difference is between a OneToOne, ManyToMany and ForeignKey? | Well, there's essentially two questions here:
1. What is the difference (in general) between one to one, many to many, and foreign key relations
2. What are their differences specific to Django.
Both of these questions are quite easily answered through a simple Google search, but as I cannot find an exact dupe of thi... |
Pandas Plotting with Multi-Index | 25,386,870 | 15 | 2014-08-19T15:05:48Z | 25,412,939 | 18 | 2014-08-20T19:28:55Z | [
"python",
"matplotlib",
"pandas",
"multi-index"
] | After performing a groupby.sum() on a dataframe I'm having some trouble trying to create my intended plot.

How can I create a subplot (kind='bar') for each 'Code', where the x-axis is the 'Month' and the bars are ColA and ColB? | I found the unstack(level) method to work perfectly, which has the added benefit of not needing a priori knowledge about how many Codes there are.
```
summed_group.unstack(level=0).plot(kind='bar', subplots=True)
``` |
matplotlib.pyplot.subplots() - how to set the name of the figure? | 25,387,365 | 4 | 2014-08-19T15:29:55Z | 25,387,458 | 8 | 2014-08-19T15:34:19Z | [
"python",
"matplotlib"
] | When I create a single plot using the figure()-function of PyPlot, I can set the name of the appearing window using a string as argument:
```
import matplotlib.pyplot as plt
figure = plt.figure('MyName')
```
The function plt.subplots() doesn´t accept strings as first argument. For example:
```
plt.subplots(2,2) # ... | Taken from [the docs](http://matplotlib.org/examples/pylab_examples/subplots_demo.html):
```
import matplotlib.pyplot as plt
#...
# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
```
And, to change the title of the Window:
```
import matplotlib.pyplot as plt
fig = p... |
sqlite3.OperationalError: near "?": syntax error | 25,387,537 | 8 | 2014-08-19T15:38:35Z | 25,387,570 | 14 | 2014-08-19T15:40:00Z | [
"python",
"sqlite",
"python-2.7",
"sqlite3"
] | I have a problem, i just keep getting error however i am trying to format this. Also tried %s.
Any suggestions?
```
group_food = (group, food)
group_food_new = (group, food, 1)
with con:
cur = con.cursor()
tmp = cur.execute("SELECT COUNT(Name) FROM (?) WHERE Name=?", group_food)
if tmp == 0:
c... | You cannot use SQL parameters to be placeholders in SQL objects; one of the *reasons* for using a SQL parameters is to escape the value such that the database can never mistake the contents for a database object.
You'll have to interpolate the database objects separately:
```
cur.execute("SELECT COUNT(Name) FROM {} W... |
Python - Get path of root project structure | 25,389,095 | 10 | 2014-08-19T17:02:46Z | 25,389,715 | 12 | 2014-08-19T17:42:27Z | [
"python"
] | I've got a python project with a configuration file in the project root.
The configuration file needs to be accessed in a few different files throughout the project.
So it looks something like: `<ROOT>/configuration.conf`
`<ROOT>/A/a.py`, `<ROOT>/A/B/b.py` (when b,a.py access the configuration file).
What's the best ... | You can do this how Django does it: **define a variable to the Project Root from a file that is in the top-level of the project.** For example, if this is what your project structure looks like:
```
project/
configuration.conf
definitions.py
main.py
utils.py
```
In `definitions.py` you can define:
``... |
What exactly is Python multiprocessing Module's .join() Method Doing? | 25,391,025 | 21 | 2014-08-19T18:59:28Z | 25,391,156 | 23 | 2014-08-19T19:07:53Z | [
"python",
"multiprocessing"
] | Learning about Python [Multiprocessing](https://docs.python.org/2/library/multiprocessing.html) (from a [PMOTW article](http://pymotw.com/2/multiprocessing/basics.html)) and would love some clarification on what exactly the `join()` method is doing.
In an [old tutorial from 2008](http://toastdriven.com/blog/2008/nov/1... | The `join()` method, when used with `threading` or `multiprocessing`, is not related to `str.join()` - it's not actually concatenating anything together. Rather, it just means "wait for this [thread/process] to complete". The name `join` is used because the `multiprocessing` module's API is meant to look as similar to ... |
Locust : How to make locust run for a specific amount of time | 25,392,451 | 6 | 2014-08-19T20:30:47Z | 25,715,975 | 12 | 2014-09-08T00:20:50Z | [
"python",
"load-testing",
"locust"
] | official [locustio documentation](http://docs.locust.io/en/latest/) tells about how to write simple locust tasks which run indefinitely.
Couldn't find out how to run load which lasts for a specific amount of time, so that the test will automatically stop after the specified interval.
I dont need it from the web inter... | I recently started using locust myself and unfortunately locust 0.7.1 does not provide a way to terminate a test based on a length of time.
It does however provide a way to terminate the test based on the number of requests that have been issued. If you run locust using the CLI interface you can specify that it stop e... |
How can I use seaborn without changing the matplotlib defaults? | 25,393,936 | 36 | 2014-08-19T22:22:05Z | 25,393,997 | 43 | 2014-08-19T22:27:36Z | [
"python",
"matplotlib",
"seaborn"
] | I am trying to use seaborn, because of its distplot function. But I prefer the default matplotlib settings. When I import seaborn, it changes automatically the appearance of my figure.
How can I use seaborn functions without changing the look of the plots? | Import seaborn like this:
```
import seaborn.apionly as sns
```
and then you should be able to use `sns.distplot` but maintain the default matplotlib styling + your personal rc configuration. |
py2app: modulegraph missing scan_code | 25,394,320 | 11 | 2014-08-19T23:03:11Z | 29,449,144 | 13 | 2015-04-04T17:04:10Z | [
"python",
"osx",
"python-3.x",
"py2app"
] | For some reason I can't explain or google, py2app crashes on me even with the simplest examples. Im using a python 3.4.1 virtual environment created as `Projects/Test/virtenv` which has py2app installed via pip.
Here is the output of `$pip list`:
```
altgraph (0.12)
macholib (1.7)
modulegraph (0.12)
pip (1.5.6)
py2ap... | I had the same problem as you and solved it now.
I referred to this [post](http://www.marinamele.com/from-a-python-script-to-a-portable-mac-application-with-py2app).
First, search for the path
```
$ /yourenv/lib/python2.7/site-packages/py2app/recipes/virtualenv.py
```
Next, open this file `virtualenv.py`, look for ... |
ImportError: No module named nose.tools | 25,398,915 | 2 | 2014-08-20T07:20:48Z | 25,398,981 | 8 | 2014-08-20T07:24:37Z | [
"python",
"scikit-learn"
] | I encounter some difficulties loading dataset onto my programme. I am unsure of the import error as stated below.
```
Traceback (most recent call last):
File "C:\Users\Khoo Family\Downloads\lsa_clustering (3).py", line 4, in <module>
from sklearn.datasets import fetch_20newsgroups
File "C:\Python27\lib\site-pa... | Check if nose in a list of installed python packages.
You can do it in *python console* (windows + R, type cmd then enter, type python then enter):
```
>>> help('modules')
```
If nose is there, then you either have a problem with PYTHONPATH when running your code or you using another interpreter to run console and yo... |
Using pandas Combining/merging 2 different Excel files/sheets | 25,400,240 | 6 | 2014-08-20T08:37:29Z | 25,403,088 | 8 | 2014-08-20T11:04:24Z | [
"python",
"excel",
"pandas"
] | I am trying to combine 2 different Excel files. (thanks to the post [Import multiple excel files into python pandas and concatenate them into one dataframe](http://stackoverflow.com/questions/20908018/import-multiple-excel-files-into-python-pandas-and-concatenate-them-into-one-dat))
The one I work out so far is:
```
... | For num. 1, you can specify `skip_footer` as explained [here](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html#pandas.read_excel); or, alternatively, do
```
data = data.iloc[:-2]
```
once your read the data.
For num. 2, you may do:
```
from os.path import basename
data.index = [basename(... |
How do I log from my Python Spark script | 25,407,550 | 4 | 2014-08-20T14:37:06Z | 25,408,277 | 9 | 2014-08-20T15:07:44Z | [
"python",
"logging",
"apache-spark"
] | I have a Python Spark program which I run with `spark-submit`. I want to put logging statements in it.
```
logging.info("This is an informative message.")
logging.debug("This is a debug message.")
```
I want to use the same logger that Spark is using so that the log messages come out in the same format and the level ... | You need to get the logger for spark itself, by default getLogger() will return the logger for you own module. Try something like:
```
logger = logging.getLogger('py4j')
logger.info("My test info statement")
```
It might also be 'pyspark' instead of 'py4j'.
In case the function that you use in your spark program (an... |
How do I log from my Python Spark script | 25,407,550 | 4 | 2014-08-20T14:37:06Z | 34,683,626 | 12 | 2016-01-08T18:23:50Z | [
"python",
"logging",
"apache-spark"
] | I have a Python Spark program which I run with `spark-submit`. I want to put logging statements in it.
```
logging.info("This is an informative message.")
logging.debug("This is a debug message.")
```
I want to use the same logger that Spark is using so that the log messages come out in the same format and the level ... | You can get the logger from the SparkContext object:
```
log4jLogger = sc._jvm.org.apache.log4j
LOGGER = log4jLogger.LogManager.getLogger(__name__)
LOGGER.info("pyspark script logger initialized")
``` |
Getting individual colors from a color map in matplotlib | 25,408,393 | 16 | 2014-08-20T15:12:26Z | 25,408,562 | 21 | 2014-08-20T15:20:55Z | [
"python",
"matplotlib",
"colors"
] | If you have a Colormap from
```
cmap = matplotlib.cm.get_cmap('Spectral')
```
how can you get a particular colour out of it between 0 and 1, where 0.0 is the first colour in the map and 1.0 is the last colour in the map?
Ideally I would be able to get the middle colour in the map by doing:
```
>>> do_some_magic(cma... | You can do this with the code below, and the code in your question was actually very close to what you needed, all you have to do is call the `cmap` object you have.
```
import matplotlib
cmap = matplotlib.cm.get_cmap('Spectral')
rgba = cmap(0.5)
print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.74602077638... |
Uploading an Image from an external link to google cloud storage using google app engine python | 25,412,119 | 2 | 2014-08-20T18:40:23Z | 25,417,071 | 7 | 2014-08-21T01:44:04Z | [
"python",
"google-app-engine",
"google-cloud-storage"
] | I'm looking for a solution on how to upload a picture from an external url like `http://example.com/image.jpg` to google cloud storage using appengine python,
I am now using
```
blobstore.create_upload_url('/uploadSuccess', gs_bucket_name=bucketPath)
```
for users that want to upload a picture from their computer, c... | To upload an external image you have to get it and save it.
To get the image you van use [this code](https://developers.google.com/appengine/docs/python/urlfetch/):
```
from google.appengine.api import urlfetch
file_name = 'image.jpg'
url = 'http://example.com/%s' % file_name
result = urlfetch.fetch(url)
if result.st... |
gmail login failure using python and imaplib | 25,413,301 | 9 | 2014-08-20T19:52:58Z | 25,447,206 | 11 | 2014-08-22T12:35:53Z | [
"python",
"email",
"gmail-imap"
] | I'm seeking some help logging into a gmail account and downloading some emails using a python script. I'm trying to adapt an approach found [here](http://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail), but I'm running into a problem with step 1, accessing the account via i... | You can try to turn on this: <https://www.google.com/settings/security/lesssecureapps>
This action solved the same problem for me. |
"Pythonic" for loop over integers 0 to k-1 except i | 25,415,016 | 5 | 2014-08-20T21:51:16Z | 25,415,079 | 11 | 2014-08-20T21:55:18Z | [
"python",
"loops",
"for-loop"
] | I want to create a for loop that will go through the integers 0 to k-1, except for integer i. (I'm comparing some lists of k items, and I don't need to compare item i in one list with item i in another list.)
I have a fairly easy way to do it, but I keep thinking there's a more "Pythonic", elegant way to do it.
What ... | Perhaps using `itertools.chain`
```
from itertools import chain
for j in chain(range(i), range(i+1, k)):
# ...
``` |
Kill Python Multiprocessing Pool | 25,415,104 | 8 | 2014-08-20T21:57:00Z | 25,415,676 | 8 | 2014-08-20T22:43:17Z | [
"python",
"linux",
"multiprocessing"
] | I am running a Python program which uses the multiprocessing module to spawn some worker threads. Using `Pool.map` these digest a list of files.
At some point, I would like to stop everything and have the script die.
Normally `Ctrl+C` from the command line accomplishes this. But, in this instance, I think that just i... | SIGQUIT (`Ctrl` + `\`) will kill all processes even under Python 2.x.
You can also update to Python 3.x, where this behavior (only child gets the signal) seems to have been fixed. |
django: raise BadRequest as exception? | 25,422,176 | 9 | 2014-08-21T08:59:39Z | 26,815,483 | 9 | 2014-11-08T09:07:33Z | [
"python",
"django",
"exception-handling",
"httpresponse"
] | Is it possible to raise `BadRequest` as exception in django?
I have seen that you can raise a 404 [1].
Use case: in a helper method I load a json from request.GET. If the json was cut since the browser (IE) cut the url, I would like to raise a matching exception.
A BadRequest exception looks appropriate, but up to n... | The other answers are explaining how to return an HTTP response with 400 status.
If you want to hook into Django's [400 error handling](https://docs.djangoproject.com/en/1.7/ref/urls/#django.conf.urls.handler400), you can raise a [`SuspiciousOperation`](https://docs.djangoproject.com/en/1.7/ref/exceptions/#suspiciouso... |
merging dictionaries in ansible | 25,422,771 | 14 | 2014-08-21T09:26:53Z | 25,426,516 | 7 | 2014-08-21T12:35:25Z | [
"python",
"dictionary",
"merge",
"ansible"
] | I'm currently building a role for installing PHP using ansible, and I'm having some difficulty merging dictionaries. I've tried several ways to do so, but I can't get it to work like I want it to:
```
# A vars file:
my_default_values:
key = value
my_values:
my_key = my_value
# In a playbook, I create a task to ... | If you want hash merging I would turn the hash merging feature on in ansible.
In your ansible config file [turn hash merging on](http://docs.ansible.com/intro_configuration.html#hash-behaviour).
With *hash\_behaviour=merge* you can have two var files with the same variable name:
defaults.yml:
```
values:
key: valu... |
merging dictionaries in ansible | 25,422,771 | 14 | 2014-08-21T09:26:53Z | 33,226,471 | 21 | 2015-10-20T01:14:57Z | [
"python",
"dictionary",
"merge",
"ansible"
] | I'm currently building a role for installing PHP using ansible, and I'm having some difficulty merging dictionaries. I've tried several ways to do so, but I can't get it to work like I want it to:
```
# A vars file:
my_default_values:
key = value
my_values:
my_key = my_value
# In a playbook, I create a task to ... | In Ansible 2.0, there is a Jinja filter, [`combine`](https://docs.ansible.com/ansible/playbooks_filters.html#combining-hashes-dictionaries), for this:
```
- debug: msg="{{ item.key }} = {{ item.value }}"
with_dict: "{{ my_default_values | combine(my_values) }}"
``` |
Scrapy Shell - How to change USER_AGENT | 25,429,671 | 3 | 2014-08-21T15:00:08Z | 25,438,234 | 10 | 2014-08-22T01:15:01Z | [
"python",
"shell",
"scrapy",
"agent"
] | I have a fully functioning scrapy script to extract data from a website. During setup, the target site banned me based on my USER\_AGENT information. I subsequently added a RotateUserAgentMiddleware to rotate the USER\_AGENT randomly. This works great.
However, now when I trying to use the scrapy shell to test xpath a... | `scrapy shell -s USER_AGENT='custom user agent' 'http://www.example.com'` |
Keeping NaN values and dropping nonmissing values | 25,430,995 | 5 | 2014-08-21T16:08:38Z | 25,431,104 | 7 | 2014-08-21T16:14:52Z | [
"python",
"pandas"
] | I have a DataFrame where I would like to keep the rows when a particular variable has a NaN value and drop the nonmissing values.
Example:
```
ticker opinion x1 x2
aapl GC 100 70
msft NaN 50 40
goog GC 40 60
wmt GC 45 15
... | Use [`pandas.isnull`](http://pandas.pydata.org/pandas-docs/stable/missing_data.html#values-considered-missing) on the column to find the missing values and index with the result.
```
import pandas as pd
data = pd.DataFrame({'ticker': ['aapl', 'msft', 'goog'],
'opinion': ['GC', nan, 'GC'],
... |
Use oauth2 service account to authenticate to Google API in python | 25,433,507 | 3 | 2014-08-21T18:29:36Z | 25,435,674 | 8 | 2014-08-21T20:48:23Z | [
"python",
"google-cloud-storage",
"google-compute-engine"
] | I've followed the directions in <https://developers.google.com/accounts/docs/OAuth2ServiceAccount> to use a service account to authenticate to the Google Cloud Storage API. I tried to send a JWT to google's authenticate servers in python, but got an error:
```
urllib2.HTTPError: HTTP Error 400: Bad Request
```
It loo... | Ok so there's a better way to do this! Google already has a python client API that handles some of the complexity. The following code works after installing google python client API: <https://developers.google.com/api-client-library/python/guide/aaa_oauth>
```
from oauth2client.client import SignedJwtAssertionCredenti... |
Running bpython inside a virtualenv | 25,434,576 | 7 | 2014-08-21T19:37:45Z | 25,434,577 | 11 | 2014-08-21T19:37:45Z | [
"python",
"pip",
"virtualenv",
"bpython"
] | I have created a virtualenv and installed [SQLAlchemy](http://www.sqlalchemy.org/) in it:
```
$ virtualenv alchemy
$ source alchemy/bin/activate
$ pip install sqlalchemy
```
`import` works in python:
```
$ python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on ... | `bpython` must be installed in the virtualenv, otherwise the external, system-wide bpython is called:
```
$ source alchemy/bin/activate
(alchemy)[ 10:34PM ] [ adamatan@rubidium:/tmp ]
$ pip install bpython
...
$ alchemy/bin/bpython
--------------
>>> import sqlalchemy
>>> print sqlalchemy.__version__
0.9.7
``` |
How to enable python repl autocomplete and still allow new line tabs | 25,434,997 | 6 | 2014-08-21T20:05:21Z | 25,489,318 | 13 | 2014-08-25T15:28:24Z | [
"python",
"shell",
"scripting",
"read-eval-print-loop"
] | I currently have the following in `~/.pythonrc` to enable auto completion in the python repl:
```
# Autocompletion
import rlcompleter, readline
readline.parse_and_bind('tab:complete')
```
However, when I `tab` from the start of a new line (for instance, on the inner part of a for loop), I get a list of suggestions in... | You should just use [IPython](http://ipython.org/). It has both tab completion and auto-indenting of for loops or function definitions. For example:
```
# Ipython prompt
In [1]: def stuff(x):
...: |
# ^ cursor automatically moves to this position
```
To install it, you can use `pip`:
```
pip install... |
Using sqlalchemy to query using multiple column where in clause | 25,436,838 | 3 | 2014-08-21T22:18:53Z | 25,437,619 | 7 | 2014-08-21T23:45:25Z | [
"python",
"mysql",
"sql",
"sqlalchemy"
] | I'm looking to execute this query using sqlalchemy.
```
SELECT name,
age,
favorite_color,
favorite_food
FROM kindergarten_classroom
WHERE (favorite_color,
favorite_food) IN (('lavender','lentil soup'),('black','carrot juice'));
```
I only want kids that like (lavender AND lentil soup) OR (... | You want the [`tuple_`](http://docs.sqlalchemy.org/en/rel_0_9/core/sqlelement.html#sqlalchemy.sql.expression.tuple_) construct:
```
session.query(...).filter(tuple_(favorite_color, favorite_food).in_([('lavender', 'lentil soup'), ('black', 'carrot juice')]))
``` |
Create a list of default objects of a class in Python? | 25,436,874 | 4 | 2014-08-21T22:21:49Z | 25,436,894 | 7 | 2014-08-21T22:23:27Z | [
"python"
] | I have define a class in Python
```
class node(object):
def __init__(self, children = []):
self.children = children
```
I would like to create a list or array of default objects of class `node`. For example, something like in C++
```
node * nodes = node[100];
```
then `nodes` will point to an array of 1... | Using a list comprehension:
```
nodes = [node() for _ in range(100)]
``` |
Indexes of elements in Numpy array that satisfy conditions on the value and the index | 25,438,420 | 5 | 2014-08-22T01:40:08Z | 25,438,720 | 7 | 2014-08-22T02:28:58Z | [
"python",
"numpy"
] | I have a numpy array A. I want to know the indexes of the elements in A equal to a value and which indexes satisfy some condition:
```
import numpy as np
A = np.array([1,2,3,4,1,2,3,4,1,2,3,4])
value = 2
ind = np.array([0,1,5,10]) #index belongs to ind
```
Here is what I did:
```
B = np.where(A==value)[0] #gives ... | If you flip the operation order around you can do it in one line:
```
B = ind[A[ind]==value]
print B
[1 5]
```
Breaking that down:
```
#subselect first
print A[ind]
[1 2 2 3]
#create a mask for the indices
print A[ind]==value
[False True True False]
print ind
[ 0 1 5 10]
print ind[A[ind]==value]
[1 5]
``` |
Python calculating time difference, to give âyears, months, days, hours, minutes and secondsâ in 1 | 25,439,279 | 6 | 2014-08-22T03:53:14Z | 25,439,989 | 9 | 2014-08-22T05:15:23Z | [
"python",
"datetime"
] | I want to know how many years, months, days, hours, minutes and seconds in between '2014-05-06 12:00:56' and '2012-03-06 16:08:22'. The result shall looked like: âthe difference is xxx year xxx month xxx days xxx hours xxx minutesâ
For example:
```
import datetime
a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:... | Use a `relativedelta` from the [dateutil package](https://pypi.python.org/pypi/python-dateutil/). This will take into account leap years and other quirks.
```
import datetime
from dateutil.relativedelta import relativedelta
a = '2014-05-06 12:00:56'
b = '2013-03-06 16:08:22'
start = datetime.datetime.strptime(a, '%Y... |
python pandas flatten a dataframe to a list | 25,440,008 | 6 | 2014-08-22T05:17:57Z | 25,440,505 | 18 | 2014-08-22T06:02:14Z | [
"python",
"list",
"numpy",
"pandas",
"dataframe"
] | I have a df like so:
```
import pandas
a=[['1/2/2014', 'a', '6', 'z1'],
['1/2/2014', 'a', '3', 'z1'],
['1/3/2014', 'c', '1', 'x3'],
]
df = pandas.DataFrame.from_records(a[1:],columns=a[0])
```
I want to flatten the df so it is one continuous list like so:
`['1/2/2014', 'a', '6', 'z1', '1/2/2014', 'a', '3'... | You can just do:
```
df.values.flatten()
```
and you can also add `.tolist()` if you want the result to be a Python `list`. |
Python string format: When to use !s conversion flag | 25,441,628 | 7 | 2014-08-22T07:21:25Z | 25,441,669 | 8 | 2014-08-22T07:24:22Z | [
"python",
"string",
"string-formatting"
] | What's the difference between these 2 string format statements in Python:
```
'{0}'.format(a)
'{0!s}'.format(a)
```
Both have the same output if `a` is an integer, list or dictionary. Is the first one `{0}` doing an implicit `str()` call?
[Source](https://docs.python.org/2/library/string.html#format-string-syntax)
... | It is mentioned in the documentation:
> The conversion field causes a type coercion before formatting.
> Normally, the job of formatting a value is done by the `__format__()`
> method of the value itself. However, in some cases it is desirable to
> force a type to be formatted as a string, overriding its own
> definit... |
Python string format: When to use !s conversion flag | 25,441,628 | 7 | 2014-08-22T07:21:25Z | 25,442,988 | 7 | 2014-08-22T08:45:39Z | [
"python",
"string",
"string-formatting"
] | What's the difference between these 2 string format statements in Python:
```
'{0}'.format(a)
'{0!s}'.format(a)
```
Both have the same output if `a` is an integer, list or dictionary. Is the first one `{0}` doing an implicit `str()` call?
[Source](https://docs.python.org/2/library/string.html#format-string-syntax)
... | Simply said:
* `'{0}'.format(a)` will use the result of `a.__format__()` to display the value
* `'{0!s}'.format(a)` will use the result of `a.__str__()` to display the value
* `'{0!r}'.format(a)` will use the result of `a.__repr__()` to display the value
---
```
>>> class C:
... def __str__(self): return "str"
.... |
Python repeat set generator | 25,442,019 | 5 | 2014-08-22T07:46:02Z | 25,442,087 | 7 | 2014-08-22T07:49:51Z | [
"python",
"iterator"
] | Is there a simpler way of doing the following?
```
(set() for _ in itertools.repeat(None))
```
Note that it is different to `itertools.repeat(set())`, since the latter only constructs the set object once. | You can do
```
iter(set, None)
```
which calls the given callable until it returns `None` (what it won't). |
What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python? | 25,445,439 | 157 | 2014-08-22T10:58:51Z | 25,445,440 | 265 | 2014-08-22T10:58:51Z | [
"python",
"python-3.x"
] | When I try to use a `print` statement in Python, it gives me this error:
```
>>> print "Hello world!"
File "<stdin>", line 1
print "Hello world!"
^
SyntaxError: Missing parentheses in call to 'print'
```
What does that mean? | This error message means that you are attempting to use Python 3 to follow an example or run a program that uses the Python 2 `print` statement:
```
print "Hello world"
```
The statement above does not work in Python 3. In Python 3 you need to add parentheses around the value to be printed:
```
print("Hello world")
... |
Annotate bars with values on Pandas bar plots | 25,447,700 | 9 | 2014-08-22T13:01:37Z | 25,449,186 | 24 | 2014-08-22T14:19:45Z | [
"python",
"matplotlib",
"plot",
"pandas",
"dataframe"
] | I looking for a way to annotate my bars in a Pandas bar plot with the values (rounded) in my DataFrame.
```
>>> df=pd.DataFrame({'A':np.random.rand(2),'B':np.random.rand(2)},index=['value1','value2'] )
>>> df
A B
value1 0.440922 0.911800
value2 0.588242 0.797366
```
I would l... | You get it directly from the axes' patches:
```
In [35]: for p in ax.patches:
ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))
```
You'll want to tweak the string formatting and the offsets to get things centered, maybe use the width from `p.get_width()`, but that should get you start... |
Python socket connection exception | 25,447,803 | 4 | 2014-08-22T13:07:21Z | 25,448,603 | 7 | 2014-08-22T13:48:39Z | [
"python",
"sockets",
"exception",
"exception-handling"
] | I have a socket-connection going on and I wanna improve the exception handling and Im stuck. Whenever I use the socket.connect(server\_address) function with an invalid argument the program stops, but doesnt seem to throw any exceptions. Heres my code
```
import socket
import sys
import struct
class ARToolkit():
... | If you have chosen a random, but valid, IP address and port, `socket.connect()` will attempt to make a connection to that endpoint. By default, if no explicit timeout is set for the socket, it will block while doing so and eventually timeout, raising exception `socket.error: [Errno 110] Connection timed out`.
The defa... |
"3" < "4" evaluates True but "3" < "10" evaluates False. why? | 25,449,289 | 2 | 2014-08-22T14:24:12Z | 25,449,348 | 10 | 2014-08-22T14:26:54Z | [
"python"
] | ```
print("3" < "10") #This prints False
print("3" < "4") #This prints True
```
How is it possible to compare numbers inside of a string, and why one is True and the other False when in the case of being poissible to compare numbers inside a string both should be True?
I came across this while doing an exercise of pr... | You are comparing **strings**; these are sorted [lexicographically](http://en.wikipedia.org/wiki/Lexicographical_order).
Since `'1'` comes earlier in the ASCII standard than `'3'`, the string `'10'` is sorted before `'3'` and considered lower, just like 'Martijn' would be sorted before 'Rodrigo' based on the letter 'M... |
QLayout: Attempting to add QLayout "" to QWidget "", which already has a layout | 25,450,598 | 2 | 2014-08-22T15:30:43Z | 25,451,334 | 7 | 2014-08-22T16:12:13Z | [
"python",
"tabs",
"pyside",
"qwidget",
"qlayout"
] | I want to create some tabs, and I read this answer: [How to add a tab in PySide](http://stackoverflow.com/questions/24965432/how-to-add-a-tab-in-pyside)
I use the code in the answer and made some changes. Cause my code has to read some files and get the name of my tabs from those file, so that I add a for loop in my c... | When you assign a widget as the parent of a `QLayout` by passing it into the constructor, the layout is automatically set as the layout for that widget. In your code you are not only doing this, but explicitly calling `setlayout()`. This is no problem when when the widget passed is the same. If they are different you w... |
Python: try/except call returning wrong value, calling except clause unneeded | 25,452,955 | 2 | 2014-08-22T17:55:50Z | 25,453,081 | 8 | 2014-08-22T18:05:32Z | [
"python",
"recursion",
"try-except"
] | In the attached code snippet the goal is to receive a user input and, depending if it is an integer or not, return the integer or call the function recursively until a valid integer is given.
```
def verify_input(msg, str_exp=True, req_str=None):
user_input = input(msg)
if str_exp:
pass # TODO: impleme... | You're missing a `return` when you call `verify_input` in the `except ValueError` block:
```
try:
return int(user_input)
except ValueError:
return verify_input("Enter a whole number please. ", str_exp=False)
``` |
numpy array concatenation error: 0-d arrays can't be concatenated | 25,453,173 | 5 | 2014-08-22T18:11:26Z | 25,453,219 | 7 | 2014-08-22T18:14:45Z | [
"python",
"arrays",
"numpy",
"concatenation"
] | I am trying to concatenate two numpy arrays, but I got this error. Could some one give me a bit clue about what this actually means?
```
Import numpy as np
allValues = np.arange(-1, 1, 0.5)
tmp = np.concatenate(allValues, np.array([30], float))
```
Then I got
```
ValueError: 0-d arrays can't be concatena... | You need to put the arrays you want to concatenate into a sequence (usually a tuple or list) in the argument.
```
tmp = np.concatenate((allValues, np.array([30], float)))
tmp = np.concatenate([allValues, np.array([30], float)])
```
Check the [documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.co... |
Unwanted extra dimensions in numpy array | 25,453,587 | 8 | 2014-08-22T18:39:58Z | 25,453,912 | 13 | 2014-08-22T19:02:33Z | [
"python",
"numpy",
"pyfits"
] | I've opened a .fits image:
```
scaled_flat1 = pyfits.open('scaled_flat1.fit')
scaled_flat1a = scaled_flat1[0].data
```
and when I print its shape:
```
print scaled_flat1a.shape
```
I get the following:
```
(1, 1, 510, 765)
```
I want it to read:
```
(510,765)
```
How do I get rid of the two ones before it? | There is the method called [`squeeze`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html) which does just what you want:
> Remove single-dimensional entries from the shape of an array.
>
> ## Parameters
>
> ```
> a : array_like
> Input data.
> axis : None or int or tuple of ints, optional
> ... |
Django auth model Error: name 'User' is not defined | 25,455,379 | 3 | 2014-08-22T20:52:48Z | 25,455,451 | 9 | 2014-08-22T20:58:09Z | [
"python",
"django",
"django-models",
"django-admin",
"django-authentication"
] | **1. The error codes:**
*NameError: name 'User' is not defined*
```
>>> myproject ME$ python manage.py shell
NameError: name 'User' is not defined
myproject ME$ python manage.py shell
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyrigh... | You are referencing `User` here: `author = models.ForeignKey(User)`, but forgot to import `User` in your models.py
Put this at the top of your `models.py` file
```
from django.contrib.auth.models import User
```
EDIT:
An alternate (newer) way of importing user model - for configurable user models would be:
```
fro... |
What is the python equivalent to a Java .jar file? | 25,455,978 | 9 | 2014-08-22T21:45:41Z | 25,456,235 | 7 | 2014-08-22T22:08:50Z | [
"python"
] | Java has the concept of packaging all of the code into a file called a Jar file. Does Python have an equivalent idea? If so, what is it? How do I package the files? | Python doesn't have any exact equivalent to a `.jar` file.
There are many differences, and without knowing exactly what you want to do, it's hard to explain how to do it. But the [Python Packaging User Guide](https://python-packaging-user-guide.readthedocs.org) does a pretty good job of explaining just about everythin... |
Reading emails with imaplib - "Got more than 10000 bytes" error | 25,457,441 | 9 | 2014-08-23T00:51:50Z | 25,457,500 | 18 | 2014-08-23T01:03:15Z | [
"python",
"gmail",
"imaplib"
] | I'm trying to connect to my gmail account with imaplib:
```
import imaplib
mail = imaplib.IMAP4_SSH('imap.gmail.com')
mail.login('[email protected]', 'mypassword')
mail.select("inbox")
# returns ('OK', [b'12009'])
```
This all seems to work nicely, however:
```
mail.search(None, "ALL")
# returns error: command: SEAR... | > Is the issue with the first email account related to the number of mails in it?
Not *directly*, but yeah, pretty much. The issue is with the fact that you're trying to download the whole list of 9000 messages at once.
Sending ridiculously long lines has been a useful DoS attack and, for programs implemented in C ra... |
Mac OS X - EnvironmentError: mysql_config not found | 25,459,386 | 42 | 2014-08-23T07:08:18Z | 25,491,082 | 144 | 2014-08-25T17:19:40Z | [
"python",
"mysql",
"django",
"osx"
] | First off, yeah, I've already seen this:
[pip install mysql-python fails with EnvironmentError: mysql\_config not found](http://stackoverflow.com/questions/5178292/pip-install-mysql-python-fails-with-environmenterror-mysql-config-not-found)
**The problem**
I am trying to use Django on a Google App Engine project. Ho... | Ok, well, first of all, let me check if I am on the same page as you:
* You installed python
* You did `brew install mysql`
* You did `export PATH=$PATH:/usr/local/mysql/bin`
* And finally, you did `pip install MySQL-Python`
If you did all those steps in the same order, and you still got an error, read on to the end,... |
list vs UserList and dict vs UserDict | 25,464,647 | 3 | 2014-08-23T17:40:35Z | 25,464,724 | 7 | 2014-08-23T17:49:37Z | [
"python",
"list",
"dictionary",
"subclass"
] | Coding this day, which of the above is preferred and recommended (both in Python 2 and 3) for subclassing?
I read that `UserList` and `UserDict` have been introduced because in the past `list` and `dict` couldn't be subclassed, but since this isn't an issue anymore, is it encouraged to use them? | Depending on your usecase, these days you'd either subclass `list` and `dict` directly, or you can subclass [`collections.MutableSequence` and `collections. MutableMapping`](https://docs.python.org/2/library/collections.html#collections-abstract-base-classes); these options are there *in addition* to using the `User*` ... |
Python: subprocess call with shell=False not working | 25,465,700 | 4 | 2014-08-23T19:35:22Z | 25,465,797 | 9 | 2014-08-23T19:51:10Z | [
"python",
"shell",
"subprocess"
] | I am using Python script to invoke a Java virtual machine. The following command works:
```
subprocess.call(["./rvm"], shell=False) # works
subprocess.call(["./rvm xyz"], shell=True) # works
```
But,
```
subprocess.call(["./rvm xyz"], shell=False) # not working
```
does not work. [Python documentation](https://doc... | You need to split the commands into separate strings:
```
subprocess.call(["./rvm", "xyz"], shell=False)
```
A string will work when `shell=True` but you need a list of args when `shell=False`
The [shlex](https://docs.python.org/2/library/shlex.html) module is useful more so for more complicated commands and dealing... |
Print raw HTTP request in Flask or WSGI | 25,466,904 | 12 | 2014-08-23T22:26:11Z | 25,467,101 | 13 | 2014-08-23T22:54:50Z | [
"python",
"flask",
"wsgi"
] | I am debugging a microcontroller I've built which is writing raw HTTP requests line by line. I am using Flask for my backend and I would like to see the entire request as it appears in this format:
```
GET / HTTP/1.1
Content-length: 123
User-agent: blah
...
```
I know Flask is based on WSGI. Is there anyway to get th... | With flask you have access to the request object which contains all the HTTP details:
```
from flask import request
@app.route('/')
def index():
print request.headers
``` |
Print raw HTTP request in Flask or WSGI | 25,466,904 | 12 | 2014-08-23T22:26:11Z | 25,467,602 | 15 | 2014-08-24T00:39:49Z | [
"python",
"flask",
"wsgi"
] | I am debugging a microcontroller I've built which is writing raw HTTP requests line by line. I am using Flask for my backend and I would like to see the entire request as it appears in this format:
```
GET / HTTP/1.1
Content-length: 123
User-agent: blah
...
```
I know Flask is based on WSGI. Is there anyway to get th... | Yes, Flask is a WSGI application, so it is trivial to wrap your app in an extra layer that logs the request:
```
import pprint
class LoggingMiddleware(object):
def __init__(self, app):
self._app = app
def __call__(self, environ, resp):
errorlog = environ['wsgi.errors']
pprint.pprint((... |
Using Anaconda Python with PyQt5 | 25,468,397 | 6 | 2014-08-24T03:57:37Z | 25,489,659 | 7 | 2014-08-25T15:47:54Z | [
"python",
"matplotlib",
"anaconda",
"pyqt5"
] | I have an existing PyQt5/Python3.4 application that works great, and would now like to add "real-time" data graphing to it. Since matplotlib installation specifically looks for Python 3.2, and NumPhy / ipython each have there own Python version requirements, I thought I'd use a python distribution to avoid confusion.
... | We are working on adding pyqt5, but for now, you can install it from <https://binstar.org/dsdale24/pyqt5>.
```
conda config --add channels dsdale24
conda install pyqt5
``` |
Using Anaconda Python with PyQt5 | 25,468,397 | 6 | 2014-08-24T03:57:37Z | 33,178,792 | 9 | 2015-10-16T20:10:58Z | [
"python",
"matplotlib",
"anaconda",
"pyqt5"
] | I have an existing PyQt5/Python3.4 application that works great, and would now like to add "real-time" data graphing to it. Since matplotlib installation specifically looks for Python 3.2, and NumPhy / ipython each have there own Python version requirements, I thought I'd use a python distribution to avoid confusion.
... | I was able to install it from dsdale24's and asmeurer's channels but then, when trying to run a qt script with a QApplication object, I got an error message regarding to cocoa library not being found.
Then, following asmeurer's comment, I could install PyQt5 on anaconda with python 3.4 using the [mmcauliffe package](h... |
Matplot: How to plot true/false or active/deactive data? | 25,469,950 | 2 | 2014-08-24T08:36:33Z | 25,470,112 | 7 | 2014-08-24T09:03:48Z | [
"python",
"matplotlib",
"plot",
"scipy"
] | I want to plot a `true/false` or `active/deactive` binary data similar to the following picture:

The horizontal axis is time and the vertical axis is some entities(Here some sensors) which is active(white) or deactive(black). How can I plot such a graphs using `py... | What you are looking for is `imshow`:
```
import matplotlib.pyplot as plt
import numpy as np
# get some data with true @ probability 80 %
data = np.random.random((20, 500)) > .2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data, aspect='auto', cmap=plt.cm.gray, interpolation='nearest')
```
Then you will j... |
Specify format for input arguments argparse python | 25,470,844 | 25 | 2014-08-24T10:41:29Z | 25,470,943 | 67 | 2014-08-24T10:53:22Z | [
"python",
"python-2.7",
"argparse"
] | I have a python script that requires some command line inputs and I am using argparse for parsing them. I found the documentation a bit confusing and couldn't find a way to check for a format in the input parameters. What I mean by checking format is explained with this example script:
```
parser.add_argument('-s', "-... | Per [the documentation](https://docs.python.org/2/library/argparse.html#type):
> The `type` keyword argument of `add_argument()` allows any necessary type-checking and type conversions to be performed ... `type=` can take any callable that takes a single string argument and returns the converted value
You could do so... |
repeating each element of numpy array 5 times | 25,471,878 | 3 | 2014-08-24T12:51:19Z | 25,471,966 | 8 | 2014-08-24T13:00:49Z | [
"python",
"numpy"
] | ```
import numpy as np
data = np.arange(-50,50,10)
print data
[-50 -40 -30 -20 -10 0 10 20 30 40]
```
I want to repeat each element of data 5 times and make new array as follows:
```
ans = [-50 -50 -50 -50 -50 -40 -40 ....40]
```
How can I do it?
What about repeating the whole array 5 times?
```
ans = [-5... | ```
In [1]: data = np.arange(-50,50,10)
```
To repeat each element 5 times use [np.repeat](http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html):
```
In [3]: np.repeat(data, 5)
Out[3]:
array([-50, -50, -50, -50, -50, -40, -40, -40, -40, -40, -30, -30, -30,
-30, -30, -20, -20, -20, -20, -20, -... |
anaconda launcher links don't work | 25,472,840 | 2 | 2014-08-24T14:42:10Z | 25,869,706 | 9 | 2014-09-16T13:10:31Z | [
"python",
"python-2.7",
"osx-mavericks",
"ipython-notebook",
"anaconda"
] | I've installed anaconda on mavericks osx. When I'm trying to install ipython notebook from launcher app - it shows message that app is installing, but nothing happens after. Also links in launcher don't work and I can easily start ipython notebook from terminal. So I guess something wrong with launcher itself.
How can... | ```
conda install -f launcher
conda install -f node-webkit
```
The Launcher application requires both of these on OSX.
It is also a good idea to make sure you Anaconda environment is up to date first with:
```
conda update conda
conda update anaconda
``` |
Finding mid-point date between two dates in Python? | 25,473,394 | 2 | 2014-08-24T15:42:17Z | 25,473,433 | 7 | 2014-08-24T15:47:03Z | [
"python",
"date"
] | Given:
```
my_guess = '2014-11-30'
their_guess = '2017-08-30'
```
How do I split the delta between the dates, returning the correct calendar date. | One way would be to use `datetime`. Find the difference between two dates, halve it, and add it on the earlier date:
```
>>> from datetime import datetime
>>> a = datetime(2014, 11, 30)
>>> b = datetime(2017, 8 ,30)
>>> a + (b - a)/2
2016-04-15 00:00:00
``` |
fastest list index searching | 25,476,179 | 4 | 2014-08-24T20:46:52Z | 25,476,827 | 15 | 2014-08-24T22:15:40Z | [
"python",
"performance",
"search"
] | What is the fastest way to find the index of an element in a list of integers?
Now I am doing
```
if value in mylist:
return mylist.index(value)
```
but it seems I am doing the same thing two times: to know if `value` is in `mylist` I also know the index position. I tried also other solutions:
```
try:
retu... | As you have only four items, you can also try this :
```
if value == mylist[0]:
return 0
elif value == mylist[1]:
return 1
elif value == mylist[2]:
return 2
elif value == mylist [3]:
return 3
```
Let me know how it works in your case. I am curious. :) |
Updating value in iterrow for pandas | 25,478,528 | 8 | 2014-08-25T03:10:55Z | 25,478,896 | 17 | 2014-08-25T04:04:16Z | [
"python",
"loops",
"pandas",
"explicit"
] | I am doing some geocoding work that I used `selenium` to screen scrape the x-y coordinate I need for address of a location, I imported an xls file to panda dataframe and want to use explicit loop to update the rows which do not have the x-y coordinate, like below:
```
for index, row in rche_df.iterrows():
if isins... | The rows you get back from `iterrows` are copies that are no longer connected to the original data frame, so edits don't change your dataframe. Thankfully, because each item you get back from `iterrows` contains the current index, you can use that to access and edit the relevant row of the dataframe:
```
for index, ro... |
Pandas min() of selected row and columns | 25,479,607 | 6 | 2014-08-25T05:40:04Z | 25,479,955 | 9 | 2014-08-25T06:14:26Z | [
"python",
"pandas",
"row",
"minimum",
"calculated-columns"
] | I am trying to create a column which contains only the minimum of the one row and a few columns, for example:
```
A0 A1 A2 B0 B1 B2 C0 C1
0 0.84 0.47 0.55 0.46 0.76 0.42 0.24 0.75
1 0.43 0.47 0.93 0.39 0.58 0.83 0.35 0.39
2 0.12 ... | This is a one-liner, you just need to use the `axis` argument for `min` to tell it to work across the columns rather than down:
```
df['Minimum'] = df.loc[:, ['B0', 'B1', 'B2']].min(axis=1)
```
If you need to use this solution for different numbers of columns, you can use a for loop or list comprehension to construct... |
Initializing an OrderedDict using its constructor | 25,480,089 | 20 | 2014-08-25T06:25:39Z | 25,480,206 | 20 | 2014-08-25T06:34:33Z | [
"python",
"dictionary",
"ordereddictionary"
] | What's the correct way to initialize an ordered dictionary (OD) so that it retains the order of initial data?
```
from collections import OrderedDict
# Obviously wrong because regular dict loses order
d = OrderedDict({'b':2, 'a':1})
# An OD is represented by a list of tuples, so would this work?
d = OrderedDict([('... | ```
# An OD is represented by a list of tuples, so would this work?
d = OrderedDict([('b', 2), ('a', 1)])
```
Yes, that will work. By definition, a list is always ordered the way it is represented. This goes for list-comprehension too, the list generated is in the same way the data was provided (i.e. source from a lis... |
Initializing an OrderedDict using its constructor | 25,480,089 | 20 | 2014-08-25T06:25:39Z | 25,480,214 | 19 | 2014-08-25T06:35:05Z | [
"python",
"dictionary",
"ordereddictionary"
] | What's the correct way to initialize an ordered dictionary (OD) so that it retains the order of initial data?
```
from collections import OrderedDict
# Obviously wrong because regular dict loses order
d = OrderedDict({'b':2, 'a':1})
# An OD is represented by a list of tuples, so would this work?
d = OrderedDict([('... | The OrderedDict will preserve any order that it has access to. The only way to pass ordered data to it to initialize is to pass a list (or, more generally, an iterable) of key-value pairs, as in your last two examples. As the documentation you linked to says, the OrderedDict does not have access to any order when you p... |
check how many elements are equal in two numpy arrays python | 25,490,641 | 6 | 2014-08-25T16:49:32Z | 25,490,688 | 17 | 2014-08-25T16:52:56Z | [
"python",
"arrays",
"numpy"
] | I have two numpy arrays with number (Same length), and I want to count how many elements are equal between those two array (equal = same value and position in array)
```
A = [1, 2, 3, 4]
B = [1, 2, 4, 3]
```
then I want the return value to be 2 (just 1&2 are equal in position and value) | Using [`numpy.sum`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html):
```
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4])
>>> b = np.array([1, 2, 4, 3])
>>> np.sum(a == b)
2
>>> (a == b).sum()
2
``` |
check how many elements are equal in two numpy arrays python | 25,490,641 | 6 | 2014-08-25T16:49:32Z | 25,490,691 | 8 | 2014-08-25T16:53:00Z | [
"python",
"arrays",
"numpy"
] | I have two numpy arrays with number (Same length), and I want to count how many elements are equal between those two array (equal = same value and position in array)
```
A = [1, 2, 3, 4]
B = [1, 2, 4, 3]
```
then I want the return value to be 2 (just 1&2 are equal in position and value) | As long as both arrays are guaranteed to have the same length, you can do it with:
```
np.count_nonzero(A==B)
``` |
how to use python to execute a curl command | 25,491,090 | 13 | 2014-08-25T17:20:21Z | 25,491,297 | 22 | 2014-08-25T17:33:30Z | [
"python",
"curl"
] | I'm new to python and I want to execute a curl command in python.
Usually, I just need enter the command in terminal and press return key. However, I don't know how it works in python.
The command shows below:
```
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v... | For sake of simplicity, maybe you should consider using the standard library
[Requests](http://docs.python-requests.org/).
An example with json response content would be something like:
```
import requests
r = requests.get('https://github.com/timeline.json')
r.json()
```
If you look for further information, in the [... |
Python3: JSON POST Request WITHOUT requests library | 25,491,541 | 3 | 2014-08-25T17:49:07Z | 25,491,579 | 8 | 2014-08-25T17:51:19Z | [
"php",
"python",
"json",
"urllib"
] | I want to send JSON encoded data to a server using only native Python libraries. I love requests but I simply can't use it because I can't use it on the machine which runs the script. I need to do it without.
```
newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"}
params = urllib.parse.url... | You are not posting JSON, you are posting a `application/x-www-form-urlencoded` request.
Encode to JSON and set the right headers:
```
import json
newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"}
params = json.dumps(newConditions).encode('utf8')
req = urllib.request.Request(conditions... |
Python: Loop: formatting string | 25,493,591 | 2 | 2014-08-25T20:09:41Z | 25,493,634 | 8 | 2014-08-25T20:12:32Z | [
"python"
] | I don't know how to express this. I want to print:
`_1__2__3__4_`
With `"_%s_"` as a substring of that. How to get the main string when I format the substring? (as a shortcut of:
```
for x in range(1,5):
print "_%s_" % (x)
```
(Even though this prints multiple lines))
Edit: just in one line | Did you mean something like this?
```
my_string = "".join(["_%d_" % i for i in xrange(1,5)])
```
That creates a list of the substrings as requested and then concatenates the items in the list using the empty string as separator (See [str.join()](https://docs.python.org/2/library/stdtypes.html#str.join) documentation... |
vlookup in Pandas using join | 25,493,625 | 11 | 2014-08-25T20:12:08Z | 25,493,765 | 29 | 2014-08-25T20:22:13Z | [
"python",
"join",
"pandas",
"vlookup"
] | I have the following 2 dataframes
```
Example1
sku loc flag
122 61 True
123 61 True
113 62 True
122 62 True
123 62 False
122 63 False
301 63 True
Example2
sku dept
113 a
122 b
123 b
301 c
```
I want to perform a merge, or join opertation using Pandas (or whichever Python operator is best) to produce t... | Perform a `left` merge, this will use `sku` column as the column to join on:
```
In [26]:
df.merge(df1, on='sku', how='left')
Out[26]:
sku loc flag dept
0 122 61 True b
1 122 62 True b
2 122 63 False b
3 123 61 True b
4 123 62 False b
5 113 62 True a
6 301 63 T... |
Print not showing in ipython notebook - python | 25,494,182 | 13 | 2014-08-25T20:51:51Z | 26,050,685 | 29 | 2014-09-26T01:30:49Z | [
"python",
"printing",
"ipython",
"ipython-notebook"
] | I am using ipython notebook (<http://ipython.org/notebook.html>) to do a demo and it seems like the print function is not working:

Sorry the print screen might not be that clear but in short it's showing:
```
In [1]: 'hello world'
Out [1]: 'hellow w... | I had a similar printing problem when my first code cell was:
```
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
```
Then I've commented the second and third lines like this:
```
import sys
#reload(sys)
#sys.setdefaultencoding("utf-8")
```
Reset the kernel and re-ran the program and now my print statements ... |
Celery 'Getting Started' not able to retrieve results; always pending | 25,495,613 | 4 | 2014-08-25T23:01:07Z | 25,506,186 | 9 | 2014-08-26T12:46:08Z | [
"python",
"windows",
"python-2.7",
"celery"
] | I've been trying to follow the Celery [First Steps With Celery](http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html) and [Next Steps](http://docs.celeryproject.org/en/latest/getting-started/next-steps.html) guides. My setup is Windows 7 64-bit, Anaconda Python 2.7 (32-bit), Installed Er... | * W8 x64
* Python 2.7.3 (ActivePython)
* Erlang 17.1 x64
* RabbitMQ server 3.3.5
* Celery 3.1.13
Randomly stopped working too. Exact same problem - forever pending.
Reinstalling Erlang or RabbitMQ didn't help.
I tested also on Debian Linux 7 x86 and here it's working fine without problems.
Also: <https://github.com/... |
Adding y=x to a matplotlib scatter plot if I haven't kept track of all the data points that went in | 25,497,402 | 7 | 2014-08-26T03:07:54Z | 25,497,638 | 10 | 2014-08-26T03:36:50Z | [
"python",
"matplotlib",
"plot",
"scatter-plot"
] | Here's some code that does scatter plot of a number of different series using matplotlib and then adds the line y=x:
```
import numpy as np, matplotlib.pyplot as plt, matplotlib.cm as cm, pylab
nseries = 10
colors = cm.rainbow(np.linspace(0, 1, nseries))
all_x = []
all_y = []
for i in range(nseries):
x = np.rand... | You don't need to know anything about your data *per se*. You can get away with what your matplotlib Axes object will tell you about the data.
See below:
```
import numpy as np
import matplotlib.pyplot as plt
# random data
N = 37
x = np.random.normal(loc=3.5, scale=1.25, size=N)
y = np.random.normal(loc=3.4, scale=... |
Batch posting on blogger using gdata python client | 25,498,773 | 7 | 2014-08-26T05:37:32Z | 25,639,768 | 14 | 2014-09-03T08:34:56Z | [
"python",
"batch-processing",
"blogger",
"gdata-python-client"
] | I'm trying to copy all my Livejournal posts to my new blog on blogger.com. I do so by using slightly modified [example](https://code.google.com/p/gdata-python-client/source/browse/samples/blogger/BloggerExampleV1.py) that ships with the [gdata python client](https://code.google.com/p/gdata-python-client/). I have a jso... | I would recommend using Google Blog converters instead ( <http://code.google.com/p/google-blog-converters-appengine/> )
To get started you will have to go through
<http://gdata-python-client.googlecode.com/svn/trunk/INSTALL.txt> - Steps for setting up Google GData API
<http://google-blog-converters-appengine.googleco... |
python list comprehensions invalid syntax while if statement | 25,500,630 | 3 | 2014-08-26T07:49:43Z | 25,500,663 | 9 | 2014-08-26T07:52:01Z | [
"python",
"string",
"list",
"list-comprehension"
] | I've got list like this `z = ['aaaaaa','bbbbbbbbbb','cccccccc']` i would like to cut off first 6 chars from all elements and if element is empty not to put in another list. So I made this code:
`[x[6:] if x[6:] is not '' else pass for x in z]`
I've tried with
`pass`
`continue`
and still syntax error. Maybe someone ... | Whenever you need to filter items from a list, the condition has to be at the end. So you need to filter the empty items, like this
```
[x[6:] for x in z if x[6:] != ""]
# ['bbbb', 'cc']
```
Since, an empty string is falsy, we can write the same condition succinctly as follows
```
[x[6:] for x in z if x[6:]]
```
As... |
Storing the secrets (passwords) in a separate file | 25,501,403 | 3 | 2014-08-26T08:36:53Z | 25,501,861 | 7 | 2014-08-26T09:01:05Z | [
"python",
"configuration",
"settings"
] | What's the simplest way to store the application secrets (passwords, access tokens) for a Python script? I thought it'd be a `*.yml` file like in Ruby but surprisingly I found that it wasn't the case. So what is it then? What are the most simplest solutions?
I want to put them in a **separate** file because that way I... | I think storing credentials inside another \*py file is your safest bet. Then just import it. Example would look like this
config.py
```
username = "xy"
password = "abcd"
```
main.py
```
import config
login(config.username, config.password)
``` |
Why is variable1 += variable2 much faster than variable1 = variable1 + variable2? | 25,503,703 | 46 | 2014-08-26T10:36:00Z | 25,503,738 | 76 | 2014-08-26T10:37:38Z | [
"python",
"html",
"string",
"performance",
"python-internals"
] | I have inherited some Python code which is used to create huge tables (of up to 19 columns wide by 5000 rows). It took **nine seconds** for the table to be drawn on the screen. I noticed that each row was added using this code:
```
sTable = sTable + '\n' + GetRow()
```
where `sTable` is a string.
I changed that to:
... | This isn't about using inplace `+=` versus `+` binary add. You didn't tell us the whole story. Your original version concatenated 3 strings, not just two:
```
sTable = sTable + '\n' + sRow # simplified, sRow is a function call
```
Python tries to help out and optimises string concatenation; both when using `strobj +... |
Why does running the Flask dev server run itself twice? | 25,504,149 | 36 | 2014-08-26T10:58:15Z | 25,504,196 | 61 | 2014-08-26T11:00:27Z | [
"python",
"flask"
] | I'm using [Flask](http://flask.pocoo.org/) for developing a website and while in development I run flask using the following file:
```
#!/usr/bin/env python
from datetime import datetime
from app import app
import config
if __name__ == '__main__':
print '################### Restarting @', datetime.utcnow(), '####... | The Werkzeug reloader spawns a child process so that it can restart that process each time your code changes. Werkzeug is the library that supplies Flask with the development server when you call `app.run()`.
See the [`restart_with_reloader()` function code](https://github.com/mitsuhiko/werkzeug/blob/49ee2786630a03076... |
OpenCV python: ValueError: too many values to unpack | 25,504,964 | 9 | 2014-08-26T11:39:33Z | 25,510,061 | 24 | 2014-08-26T15:50:20Z | [
"python",
"opencv",
"image-processing"
] | I'm writing an opencv program and I found a script on another stackoverflow question: [Computer Vision: Masking a human hand](http://stackoverflow.com/questions/14752006/computer-vision-masking-a-human-hand/14756351#14756351)
When I run the scripted answer, I get the following error:
```
Traceback (most recent call l... | I got the answer from the OpenCV Stack Exchange site. [Answer](http://answers.opencv.org/question/40329/python-valueerror-too-many-values-to-unpack/)
THE ANSWER:
> I bet you are using the current OpenCV's master branch: here the return statements have changed, see <http://docs.opencv.org/modules/imgproc/doc/structura... |
Python Matplotlib add Colorbar | 25,505,674 | 3 | 2014-08-26T12:19:10Z | 25,507,812 | 9 | 2014-08-26T14:04:38Z | [
"python",
"matplotlib",
"legend",
"shapes",
"cartopy"
] | i've got a problem using MatlobLib with "Custom" Shapes from a shapereader. Importing and viewing inserted faces works fine, but i'm not able to place a colorbar on my figure.
I already tried several ways from the tutorial, but im quite sure there is a smart solution for this problem.
maybe somebody can help me, my c... | As mentioned in the comments above, i would think twice about mixing `Basemap` and `Cartopy`, is there a specific reason to do so? Both are basically doing the same thing, extending Matplotlib with geographical plotting capabilities. Both are valid to use, they both have their pro's and con's.
In your example you have... |
Python: convert complicated date and time string to timestamp | 25,506,772 | 2 | 2014-08-26T13:14:24Z | 25,506,834 | 7 | 2014-08-26T13:17:09Z | [
"python",
"datetime",
"timestamp"
] | I want to know how to convert this date format
```
"Thu 21st Aug '14, 4:58am"
```
to a timestamp with Python?
Another format that I need to convert:
```
"Yesterday, 7:22am"
```
I tried parse util without success... | If you haven't done so already, have a look at the `parse` function in [`dateutils.parser`](https://pypi.python.org/pypi/python-dateutil) for parsing strings representing dates...
```
>>> from dateutil.parser import parse
>>> dt = parse("Thu 21st Aug '14, 4:58am")
>>> dt
datetime.datetime(2014, 8, 21, 4, 58)
```
...a... |
How do I "randomly" select numbers with a specified bias toward a particular number | 25,507,558 | 2 | 2014-08-26T13:52:39Z | 25,507,635 | 8 | 2014-08-26T13:56:05Z | [
"python",
"numpy",
"scipy"
] | How do I generate random numbers with a specified bias toward one number. For example, how would I pick between two numbers, 1 and 2, with a 90% bias toward 1. The best I can come up with is...
```
import random
print random.choice([1, 1, 1, 1, 1, 1, 1, 1, 1, 2])
```
Is there a better way to do this? The method I sh... | [`np.random.choice`](http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html) has a `p` parameter which you can use to specify the probability of the choices:
```
np.random.choice([1,2], p=[0.9, 0.1])
``` |
Fastest way to parse large CSV files in Pandas | 25,508,510 | 8 | 2014-08-26T14:34:35Z | 25,509,805 | 9 | 2014-08-26T15:36:57Z | [
"python",
"pandas"
] | I am using pandas to analyse the large data files here: <http://www.nielda.co.uk/betfair/data/> They are around 100 megs in size.
Each load from csv takes a few seconds, and then more time to convert the dates.
I have tried loading the files, converting the dates from strings to datetimes, and then re-saving them as ... | As @chrisb said, pandas' `read_csv` is probably faster than `csv.reader/numpy.genfromtxt/loadtxt`. I don't think you will find something better to parse the csv (as a note, `read_csv` is not a 'pure python' solution, as the CSV parser is implemented in C).
But, if you have to load/query the data often, a solution woul... |
Python argparse fails to parse hex formatting to int type | 25,513,043 | 7 | 2014-08-26T18:45:28Z | 25,513,044 | 14 | 2014-08-26T18:45:28Z | [
"python",
"argparse"
] | I have the following code which attempts to get the DUT VID from the invoked command line:
```
parser = argparse.ArgumentParser(description='A Test',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
group.add_argument("--vid",
... | `argparse` is looking to create a callable type conversion from the `'type'` value:
```
def _get_value(self, action, arg_string):
type_func = self._registry_get('type', action.type, action.type)
if not _callable(type_func):
msg = _('%r is not callable')
raise ArgumentError(action, msg % type_fu... |
How to provide Python syntax coloring inside Webstorm? | 25,513,340 | 15 | 2014-08-26T19:02:15Z | 25,545,919 | 25 | 2014-08-28T09:56:51Z | [
"python",
"webstorm"
] | I have a Python project, and I use WebStorm as my Editor. The problem is that Python's syntax doesn't get colored.
How can I display Python pages with a nice syntax? I am not searching more than than. I'm not going to develop pages in Python, but I do want them to get displayed nicely in Webstorm. | Your ONLY option is to use **TextMate bundles support plugin** with Python bundle.
This official article (with pictures) is for PhpStorm, but it should work the same for WebStorm as well: <http://confluence.jetbrains.com/display/PhpStorm/TextMate+Bundles+in+PhpStorm> |
how to call python script from javascript? | 25,517,662 | 2 | 2014-08-27T01:39:03Z | 25,517,740 | 7 | 2014-08-27T01:48:46Z | [
"javascript",
"python",
"sql",
"sqlalchemy"
] | I have a backend python script where it retrieves the data from the sqlalchemy engine. And I would like to show the data in a search box where you can scroll down the list of data and select it. I read some answers to the similar questions like mine, (use ajax to call python script). But I'm still not clear about this.... | Step 1: make your script available as a web service. You can use [CGI](https://docs.python.org/2/library/cgi.html), or you can use one of the cool server frameworks that will run standalone or WSGI like CherryPy, web.py or Flask.
Step 2: make an AJAX call to the URL served by step 1, either manually (look for `XmlHttp... |
PyCharm resolving - flask.ext.sqlalchemy vs flask_sqlalchemy | 25,518,093 | 16 | 2014-08-27T02:36:14Z | 25,558,257 | 27 | 2014-08-28T21:24:01Z | [
"python",
"python-2.7",
"flask",
"pycharm",
"flask-sqlalchemy"
] | If I use the following format in my application, everything works, except PyCharms resolving / autocomplete feature:
```
from flask.ext.sqlalchemy import SQLAlchemy
```
If I use the following format in my application, everything works. But, alas, it is not the correct way to import the libraries:
```
from flask_sqla... | The `flask.ext` namespace is a *transistion* namespace, see the [*Extension Import Transition* section](http://flask.pocoo.org/docs/0.10/extensiondev/#ext-import-transition) of the *Flask Extension Development* docs:
> For a while we recommended using namespace packages for Flask extensions. This turned out to be prob... |
py.test: Temporary folder for the session scope | 25,525,202 | 7 | 2014-08-27T10:49:11Z | 25,527,537 | 12 | 2014-08-27T12:42:12Z | [
"python",
"py.test"
] | The `tmpdir` fixture in py.test uses the `function` scope and thus isn't available in a fixture with a broader scope such as `session`. However, this would be useful for some cases such as setting up a temporary PostgreSQL server (which of course shouldn't be recreated for each test).
Is there any clean way to get a t... | Unfortunately there is currently no way of doing this nicely. In the future py.test will introduce a new "any" scope or something similar for this, but that's the future.
Right now you have to do this manually yourself. However as you note you loose quite a few nice features: symlinks in /tmp to the last test, auto cl... |
How does "enumerate" know when to unpack the values returned? | 25,526,480 | 2 | 2014-08-27T11:53:11Z | 25,526,530 | 11 | 2014-08-27T11:55:52Z | [
"python",
"iterator"
] | Example 1
```
for i, v in enumerate({'a', 'b'}):
print(i, v)
```
returns
```
0 a
1 b
```
Example 2
```
for x in enumerate({'a', 'b'}):
print(x)
```
Returns
```
(0, 'a')
(1, 'b')
```
But how does `enumerate` know when to unpack the values it returns? | `enumerate()` knows nothing about unpacking. It is the `for` statement that does this.
The `target` part of the `for` statement acts like a regular assignment does, you can name multiple targets and the right-hand-side value is expected to be a sequence with the same number of elements. `enumerate()` *always* produces... |
Round a value to nearest number divisible by 2, 4, 8 and 16? | 25,529,635 | 3 | 2014-08-27T14:18:21Z | 25,529,757 | 9 | 2014-08-27T14:23:10Z | [
"python"
] | How do i round a decimal number to the nearest number divisible by 2, 4, 8 and 16 in python?
Example:
```
1920/1.33 = 1443.609022556391
```
It should round off to 1440 as it is easily divisible by the 2, 4, 8 and 16 and vice versa ( 1440\*1.33 = 1920 ).
```
1920/1.33 = 1440
``` | What about `int( 16 * round( value / 16. ))` ? |
NLTK WordNet Lemmatizer: Shouldn't it lemmatize all inflections of a word? | 25,534,214 | 6 | 2014-08-27T18:10:12Z | 25,535,348 | 18 | 2014-08-27T19:20:59Z | [
"python",
"nlp",
"nltk"
] | I'm using the NLTK WordNet Lemmatizer for a Part-of-Speech tagging project by first modifying each word in the training corpus to its stem (in place modification), and then training only on the new corpus. However, I found that the lemmatizer is not functioning as I expected it to.
For example, the word `loves` is lem... | The WordNet lemmatizer *does* take the POS tag into account, but it doesn't magically determine it:
```
>>> nltk.stem.WordNetLemmatizer().lemmatize('loving')
'loving'
>>> nltk.stem.WordNetLemmatizer().lemmatize('loving', 'v')
u'love'
```
Without a POS tag, it assumes everything you feed it is a noun. So here it think... |
NLTK WordNet Lemmatizer: Shouldn't it lemmatize all inflections of a word? | 25,534,214 | 6 | 2014-08-27T18:10:12Z | 25,544,239 | 12 | 2014-08-28T08:30:18Z | [
"python",
"nlp",
"nltk"
] | I'm using the NLTK WordNet Lemmatizer for a Part-of-Speech tagging project by first modifying each word in the training corpus to its stem (in place modification), and then training only on the new corpus. However, I found that the lemmatizer is not functioning as I expected it to.
For example, the word `loves` is lem... | The best way to troubleshoot this is to actually look in Wordnet. Take a look here: [Loving in wordnet](http://wordnetweb.princeton.edu/perl/webwn?s=loving&sub=Search%20WordNet&o2=&o0=1&o8=1&o1=1&o7=&o5=&o9=&o6=&o3=&o4=&h=). As you can see, there is actually an adjective "loving" present in Wordnet. As a matter of fact... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.