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 |
|---|---|---|---|---|---|---|---|---|---|
How do I create test and train samples from one dataframe with pandas? | 24,147,278 | 49 | 2014-06-10T17:24:57Z | 24,151,789 | 111 | 2014-06-10T22:19:31Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] | I have a fairly large dataset in the form of a dataframe and I was wondering how I would be able to split the dataframe into two random samples (80% and 20%) for training and testing.
Thanks! | SciKit Learn's `train_test_split` is a good one.
```
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
train, test = train_test_split(df, test_size = 0.2)
``` |
How do I create test and train samples from one dataframe with pandas? | 24,147,278 | 49 | 2014-06-10T17:24:57Z | 30,454,743 | 12 | 2015-05-26T09:33:30Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] | I have a fairly large dataset in the form of a dataframe and I was wondering how I would be able to split the dataframe into two random samples (80% and 20%) for training and testing.
Thanks! | I would use scikit-learn's own training\_test\_split, and generate it from the index
```
from sklearn.cross_validation import train_test_split
y = df.pop('output')
X = df
X_train,X_test,y_train,y_test = train_test_split(X.index,y,test_size=0.2)
X.iloc[X_train] # return dataframe train
``` |
How do I create test and train samples from one dataframe with pandas? | 24,147,278 | 49 | 2014-06-10T17:24:57Z | 35,531,218 | 31 | 2016-02-21T01:28:55Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] | I have a fairly large dataset in the form of a dataframe and I was wondering how I would be able to split the dataframe into two random samples (80% and 20%) for training and testing.
Thanks! | Pandas random sample will also work
```
train=df.sample(frac=0.8,random_state=200)
test=df.drop(train.index)
``` |
cx_Oracle doesn't connect when using SID instead of service name on connection string | 24,149,138 | 13 | 2014-06-10T19:14:33Z | 25,971,630 | 14 | 2014-09-22T10:14:57Z | [
"python",
"oracle",
"python-2.7",
"cx-oracle"
] | I have a connection string that looks like this
```
con_str = "myuser/[email protected]:1521/ora1"
```
Where `ora1` is the SID of my database. Using this information in SQL Developer works fine, meaning that I can connect and query without problems.
However, if I attempt to connect to Oracle using this s... | I a similar scenario, I was able to connect to the database by using [`cx_Oracle.makedsn()`](http://cx-oracle.readthedocs.org/en/latest/module.html) to create a **dsn** string with a given `SID` (instead of the service name):
```
dsnStr = cx_Oracle.makedsn("oracle.sub.example.com", "1521", "ora1")
```
This returns so... |
How to benchmark unit tests in Python without adding any code | 24,150,016 | 3 | 2014-06-10T20:10:00Z | 24,216,133 | 9 | 2014-06-14T02:40:39Z | [
"python",
"unit-testing",
"testing",
"benchmarking"
] | I have a Python project with a bunch of tests that have already been implemented, and I'd like to begin benchmarking them so I can compare performance of the code, servers, etc over time. Locating the files in a manner similar to Nose was no problem because I have "test" in the names of all my test files anyway. Howeve... | Using [`nose`](https://nose.readthedocs.org/en/latest/) test runner would help to [discover the tests](http://nose.readthedocs.org/en/latest/finding_tests.html), setup/teardown functions and methods.
[`nose-timer`](https://github.com/mahmoudimus/nose-timer) plugin would help with benchmarking:
> A timer plugin for no... |
Django allauth does not log user in on email confirm | 24,152,139 | 5 | 2014-06-10T22:53:16Z | 24,219,288 | 8 | 2014-06-14T11:06:25Z | [
"python",
"django",
"django-allauth"
] | I'm using django-allauth in my django project and I understand that `ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION` is set to `True` by default. Unfortunately the user was not being logged in automatically on confirm so I explicitly set this setting to `True`. Unfortunately the user still does not get logged on when they confirm... | The `ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True` settings works only when the user performs a sign-up action and verifies the email in the same browser session.
[See this code fragment](https://github.com/pennersr/django-allauth/blob/e832a44e3ae082562c165b74a4b8c0fd1b6c49d7/allauth/account/utils.py#L295)
```
def send... |
Converting an RPy2 ListVector to a Python dictionary | 24,152,160 | 7 | 2014-06-10T22:55:14Z | 24,153,569 | 12 | 2014-06-11T02:02:47Z | [
"python",
"rpy2"
] | The natural Python equivalent to a named list in R is a dict, but [RPy2](http://rpy.sourceforge.net/) gives you a [ListVector](http://rpy.sourceforge.net/rpy2/doc-2.3/html/vector.html?highlight=listvector#rpy2.robjects.vectors.ListVector) object.
```
import rpy2.robjects as robjects
a = robjects.r('list(foo="barbat",... | I think to get a r vector into a `dictionary` does not have to be so involving, how about this:
```
In [290]:
dict(zip(a.names, list(a)))
Out[290]:
{'fizz': <FloatVector - Python:0x08AD50A8 / R:0x10A67DE8>
[123.000000],
'foo': <StrVector - Python:0x08AD5030 / R:0x10B72458>
['barbat']}
In [291]:
dict(zip(a.names, ma... |
Pass Dynamic Javascript Variable to Django/Python | 24,152,420 | 6 | 2014-06-10T23:24:49Z | 24,153,431 | 13 | 2014-06-11T01:43:41Z | [
"javascript",
"jquery",
"python",
"ajax",
"django"
] | I have looked at a number of answers and other websites, but none answer my specific question. I have a webpage with "+" and "-" buttons, which should increment a variable called "pieFact". This variable must be updated dynamically without having to refresh the page. It should then be passed to my Django view each time... | In order to keep from refreshing the page, yes, you will need AJAX. I usually don't like to suggest libraries too much in answers, however, in the interest of being easily cross-browser compatible, I would suggest the use of [jQuery](https://jquery.com/).
## With jQuery it would be as simple as
### Inside of your dja... |
NumPy: Evaulate index array during vectorized assignment | 24,154,437 | 5 | 2014-06-11T04:03:03Z | 24,154,672 | 7 | 2014-06-11T04:28:58Z | [
"python",
"arrays",
"numpy",
"vectorization"
] | I would like to vectorize this NumPy operation:
```
for j in range(yt):
for i in range(xt):
y[j, i] = x[idx[j, i], j, i]
```
where `idx` contains axis-0 index to an `x` slice. Is there some simple way to do this? | You can use:
```
J, I = np.ogrid[:yt, :xt]
x[idx, J, I]
```
Here is the test:
```
import numpy as np
yt, xt = 3, 5
x = np.random.rand(10, 6, 7)
y = np.zeros((yt, xt))
idx = np.random.randint(0, 10, (yt, xt))
for j in range(yt):
for i in range(xt):
y[j, i] = x[idx[j, i], j, i]
J, I = np.ogrid[:yt, :xt]... |
Dictionary of lists to Dictionary | 24,156,033 | 6 | 2014-06-11T06:31:11Z | 24,156,179 | 12 | 2014-06-11T06:39:46Z | [
"python",
"dictionary",
"cartesian-product"
] | I have a dictionary of lists:
```
In [72]: params
Out[72]: {'a': [1, 2, 3], 'b': [5, 6, 7, 8]}
```
I may have more than two key/value pairs. I want to create a list of dictionaries which gives me all the possible combinations of the the lists corresponding to `a` and `b`:
e.g.
```
[{'a':1, 'b'=5},
{'a':1, 'b'=6},
... | You're close:
```
from itertools import product, izip
for i in product(*p.itervalues()):
print dict(izip(p, i))
{'a': 1, 'b': 5}
{'a': 1, 'b': 6}
...
{'a': 3, 'b': 8}
``` |
When cassandra-driver was executing the query, cassandra-driver returned error OperationTimedOut | 24,157,534 | 4 | 2014-06-11T07:57:19Z | 24,218,862 | 9 | 2014-06-14T10:14:57Z | [
"python",
"cassandra",
"cql3"
] | I use python script, that passes to cassandra batch query, like this:
```
query = 'BEGIN BATCH ' + 'insert into ... ; insert into ... ; insert into ...; ' + ' APPLY BATCH;'
session.execute(query)
```
It is work some time, but in about 2 minutes after start scripts fails and print:
```
Traceback (most recent call las... | 1. This is a client side timeout (see the link in @Syrial's reply: <http://datastax.github.io/python-driver/api/cassandra.html#cassandra.OperationTimedOut>)
2. You can change the `Session` [default timeout](http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Session.default_timeout):
... |
J's x-type variables: how are they stored internally? | 24,159,654 | 6 | 2014-06-11T09:44:33Z | 24,175,658 | 11 | 2014-06-12T02:40:23Z | [
"python",
"data-structures",
"j"
] | I'm coding some J bindings in Python (<https://gist.github.com/Synthetica9/73def2ec09d6ac491c98>). However, I've run across a problem in handling arbitrary-precicion integers: the output doesn't make any sense. It's something different everytime (but in the same general magnitude). The relevant piece of code:
```
def ... | Short answer: **J's extended precision integers are stored in [base 10,000](https://github.com/sblom/openj-core/blob/master/vx.h#L12)**.
More specifically: A single extended integer is stored as an array of machine integers, each in the range [0,1e4). Thus, an array of extended integers is stored as a [recursive data ... |
Length of string in Jinja/Flask | 24,163,579 | 16 | 2014-06-11T12:58:27Z | 24,163,620 | 34 | 2014-06-11T13:00:08Z | [
"python",
"flask",
"jinja2",
"jinja"
] | Jinja unfortunately does not support executing arbitrary Python code, such as
```
{% if len(some_var)>1 %} ... {% endif %}
```
My current workaround is to use the deprecated, ugly, double-underscore method:
```
{% if some_var.__len__()>1 %} ... {% endif %}
```
Although this works, I'm afraid that some future implem... | You can use the [`length` filter](http://jinja.pocoo.org/docs/templates/#length):
```
{% if some_var|length > 1 %}
``` |
Adding extra data to Django Rest Framework results for entire result set | 24,164,160 | 6 | 2014-06-11T13:26:42Z | 24,212,269 | 10 | 2014-06-13T19:02:40Z | [
"python",
"django",
"django-rest-framework"
] | I'm using Django Rest Framework and need to add extra data to a result set. Specifically, where you would usually have:
```
{
"count": 45,
"next": "http://localhost:8000/foo/bar?page=2",
"previous": null,
"results": [
{...}
]
}
```
I would like to add extra counts like so:
```
{
"c... | Since you seem to be using one of the ListViews from the Rest Framework, you could override the list() method in your class and set new values on the resulting data, like this:
```
def list(self, request, *args, **kwargs):
response = super(YourClass, self).list(request, args, kwargs)
# Add data to ... |
Printing a function's local variable names and values | 24,165,374 | 5 | 2014-06-11T14:21:11Z | 24,166,179 | 7 | 2014-06-11T14:56:12Z | [
"python",
"namespaces",
"python-decorators"
] | To help me debug some of the code I write, I want to make a function decorator that prints off the name of a variable and its value as each variable is created or modified, essentially giving me a "play-by-play" view of what happens when I call the function.
The approach I had been using up until this point is simply ... | You cannot do this without enabling tracing; this will hurt performance. Function locals are constructed when the function is called, and cleaned up when it returns, so there is no other way to access those locals from a decorator.
You can insert a trace function using [`sys.settrace()`](https://docs.python.org/2/libr... |
PYTHON IndexError: tuple index out of range | 24,167,373 | 4 | 2014-06-11T15:51:39Z | 24,167,429 | 8 | 2014-06-11T15:55:28Z | [
"python",
"git"
] | Would really appreciate feedback on this issue
```
import subprocess
def main():
'''
Here's where the whole thing starts.
'''
#Edit this constant to change the file name in the git log command.
FILE_NAME = 'file1.xml'
#Do the git describe command to get the tag names.
gitDescribe = 'git describe --tags `git rev-list... | `tag2` is only a single value, like `tag1`, so you can't reference item[1]. No doubt you mean
```
print('Second revision: {0}'.format(tag2))
``` |
Unsupported command-line flag: --ignore-certificate-errors | 24,168,407 | 13 | 2014-06-11T16:52:02Z | 24,169,131 | 13 | 2014-06-11T17:32:54Z | [
"python",
"selenium",
"selenium-chromedriver"
] | Using Python 2.7.5, python module selenium (2.41.0) and chromedriver (2.9).
When Chrome starts it displays a message in a yellow popup bar: "You are using an unsupported command-line flag: --ignore-certificate-errors. Stability and security will suffer." This simple example reproduces the problem.
```
from selenium i... | This extra code removes the --ignore-certificate-errors command-line flag for me. In my opinion the arguments that can be added to webdriver.Chrome() could (and should) be better documented somewhere, I found this solution in a comment on the [chromedriver issues page](https://code.google.com/p/chromedriver/issues/deta... |
Why does the interpreter hang when evaluating the expression? | 24,169,108 | 4 | 2014-06-11T17:32:14Z | 24,169,172 | 7 | 2014-06-11T17:36:04Z | [
"python"
] | Here's my experiment:
```
$ python
Python 2.7.5 (default, Feb 19 2014, 13:47:28)
[GCC 4.8.2 20131212 (Red Hat 4.8.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 3
>>> while True:
... a = a * a
...
^CTraceback (most recent call last):
File "<stdin>", line 2, in <mod... | `a` is now a really large number and it takes a while to print. Print `a` in the loop and you'll see it gets really big, this is just a fraction of how large it is if you omit the print, because print takes time to execute. Also, note `a=1` always quickly returns `1`. |
Python TypeError: non-empty format string passed to object.__format__ | 24,170,519 | 27 | 2014-06-11T18:56:59Z | 24,170,567 | 26 | 2014-06-11T18:59:55Z | [
"python",
"python-3.x",
"string-formatting"
] | I hit this TypeError exception recently, which I found very difficult to debug. I eventually reduced it to this small test case:
```
>>> "{:20}".format(b"hi")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__
```
This is very non-ob... | `bytes` objects do not have a `__format__` method of their own, so the default from `object` is used:
```
>>> bytes.__format__ is object.__format__
True
>>> '{:20}'.format(object())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: non-empty format string passed to object.__format__
`... |
Cmake is not able to find Python-libraries | 24,174,394 | 17 | 2014-06-11T23:48:33Z | 29,657,288 | 7 | 2015-04-15T17:50:31Z | [
"python",
"python-2.7",
"cmake"
] | Getting this error:
```
sudo: unable to resolve host coderw@ll
-- Could NOT find PythonLibs (missing: PYTHON_LIBRARIES PYTHON_INCLUDE_DIRS)
CMake Error at /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:108
(message):
Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)
Call Stack (most rec... | I hit the same issue,and discovered the error message gives the wrong variable names. Try setting the following (singular instead of plural):
```
PYTHON_INCLUDE_DIR=/usr/include/python2.7
PYTHON_LIBRARY=/usr/lib/python2.7/config/libpython2.7.so
``` |
Cmake is not able to find Python-libraries | 24,174,394 | 17 | 2014-06-11T23:48:33Z | 30,847,814 | 11 | 2015-06-15T14:31:03Z | [
"python",
"python-2.7",
"cmake"
] | Getting this error:
```
sudo: unable to resolve host coderw@ll
-- Could NOT find PythonLibs (missing: PYTHON_LIBRARIES PYTHON_INCLUDE_DIRS)
CMake Error at /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:108
(message):
Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)
Call Stack (most rec... | I was facing this problem while trying to compile OpenCV 3 on a Xubuntu 14.04 Thrusty Tahr system.
With all the dev packages of Python installed, the configuration process was always returning the message:
```
Could NOT found PythonInterp: /usr/bin/python2.7 (found suitable version "2.7.6", minimum required is "2.7")
... |
How to change default install location for pip | 24,174,821 | 11 | 2014-06-12T00:38:05Z | 24,175,174 | 10 | 2014-06-12T01:30:45Z | [
"python",
"pip"
] | I'm trying to install Pandas using pip, but I'm having a bit of trouble. I just ran `sudo pip install pandas` which successfully downloaded pandas. However, it did not get downloaded to the location that I wanted. Here's what I see when I use `pip show pandas`:
```
---
Name: pandas
Version: 0.14.0
Location: /Library/P... | According to pip documentation at
<http://pip.readthedocs.org/en/stable/user_guide/#configuration>
You will need to specify the default install location within a **pip.ini** file, which, also according to the website above is usually located as follows
> On Unix and Mac OS X the configuration file is: $HOME/.pip/pip... |
How to use proxy with Robobrowser | 24,177,246 | 3 | 2014-06-12T05:46:20Z | 25,005,981 | 7 | 2014-07-28T23:34:11Z | [
"python",
"django"
] | I'm working with <http://robobrowser.readthedocs.org/en/latest/readme.html>, (a new python library based on the beautiful soup and request libraries) within django. My django app contains :
```
def index(request):
p=str(request.POST.get('p', False)) # p='https://www.yahoo.com/'
pr="http://10.10.1.10:3128... | After some recent API cleanup in RoboBrowser, there are now two relatively straightforward ways to control proxies. First, you can configure proxies in your requests session, and then pass that session to your browser. This will apply your proxies to all requests made through the browser.
```
from requests import Sess... |
Argparse: Required arguments listed under "optional arguments"? | 24,180,527 | 26 | 2014-06-12T09:09:13Z | 24,181,138 | 43 | 2014-06-12T09:39:00Z | [
"python",
"argparse"
] | I use the following simple code to parse some arguments; note that one of them is required. Unfortunately, when the user runs the script without providing the argument, the displayed usage/help text does not indicate that there is a non-optional argument, which I find very confusing. How can I get python to indicate th... | Parameters starting with `-` or `--` are usually considered optional. All other parameters are positional parameters and as such required by design (like positional function arguments). It is possible to require optional arguments, but this is a bit against their design. Since they are still part of the non-positional ... |
Python check if a list is nested or not | 24,180,879 | 5 | 2014-06-12T09:26:36Z | 24,180,923 | 16 | 2014-06-12T09:28:30Z | [
"python",
"list"
] | I have a list, sometimes it is nested, sometimes it is not. Based whether it is nested, the continuation is different. How do I check if this list is nested? `True` or `False` should be output.
example:
`[1,2,3]` --> `False`
`[[1],[2],[3]]` --> `True` | You can use [`isinstance`](https://docs.python.org/2/library/functions.html#isinstance) and a [generator expression](https://wiki.python.org/moin/Generators) combined with [`any`](https://docs.python.org/2/library/functions.html#any). This will check for instances of a `list` object within your original, outer list.
`... |
Pandas: Bar-Plot with two bars and two y-axis | 24,183,101 | 10 | 2014-06-12T11:22:07Z | 24,183,505 | 19 | 2014-06-12T11:44:31Z | [
"python",
"matplotlib",
"plot",
"pandas"
] | I have a DataFrame looking like this:
```
amount price
age
A 40929 4066443
B 93904 9611272
C 188349 19360005
D 248438 24335536
E 205622 18888604
F 140173 12580900
G 76243 6751731
H 36859 3418329
I 29304 2758928
J 39768 3201269
K 30350 2867059
```
Now ... | Using the new pandas release (0.14.0 or later) the below code will work. To create the two axis I have manually created two matplotlib axes objects (`ax` and `ax2`) which will serve for both bar plots.
When plotting a Dataframe you can choose the axes object using `ax=...`. Also in order to prevent the two plots from ... |
Python groupby doesn't work as expected | 24,185,591 | 2 | 2014-06-12T13:24:33Z | 24,185,741 | 7 | 2014-06-12T13:31:10Z | [
"python",
"itertools"
] | I am trying to read an excel spreadsheet that contains some columns in following format:
```
column1__
column1__AccountName
column1__SomeOtherFeature
column2__blabla
column2_SecondFeat
```
I've already saved values of one row as list of tuples, where is tuple is (column\_name, column\_value) in variable `x`.
Now I w... | As [the docs say](https://docs.python.org/library/itertools.html#itertools.groupby), you are supposed to apply `groupby` to a list which is already sorted using the same `key` as `groupby` itself:
```
key = lambda fv: fv[0].split('__')[0]
groups = groupby(sorted(x, key=key), key=key)
```
Then `grouped_fields` is:
``... |
Combining Flask-restless, Flask-security and regular Python requests | 24,186,694 | 6 | 2014-06-12T14:16:02Z | 24,258,886 | 13 | 2014-06-17T08:16:30Z | [
"python",
"flask",
"restful-authentication",
"flask-security",
"flask-restless"
] | My goal is to provide a REST API to my web application. Using:
* Python 2.7.5
* Flask==0.10.1
* Flask-Restless==0.13.1
* Flask-Security==1.7.3
I need to secure access to my data for both web and REST access. However, I am unable to get any regular python `request` succeeding when trying to connect to secured API.
Th... | I finally went to Flask-JWT (<https://pypi.python.org/pypi/Flask-JWT/0.1.0>)
Here is my modified minimal example:
```
from flask import Flask, render_template, request, url_for, redirect
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import Security, SQLAlchemyUserDatastore, \
UserMixin, Role... |
Matplotlib: Move ticklabels between ticks | 24,190,858 | 14 | 2014-06-12T17:52:29Z | 24,193,138 | 12 | 2014-06-12T20:10:41Z | [
"python",
"matplotlib"
] | I want to create a visualization of a confusion matrix using matplotlib.
Parameters to the methods shown below are the class labels (alphabet),
the classification results as a list of lists (conf\_arr) and an output filename.
I am pretty happy with the result so far, with one last problem:
I am not able to center the ... | As you've noticed, they're centered by default and you're overriding the default behavior by specifying `extent=[0, width, height, 0]`.
There are a number of ways to handle this. One is to use `pcolor` and set the edgecolors and linestyles to look like the gridlines (you actually need `pcolor` and not `pcolormesh` for... |
skewing or shearing an image in python | 24,191,545 | 2 | 2014-06-12T18:33:12Z | 24,195,454 | 7 | 2014-06-12T23:25:19Z | [
"python",
"image-processing",
"numpy",
"transformation",
"scikit-image"
] | I need to shear and skew some images using python.
I've come across [this skimage module](http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.AffineTransform) but I don't seem able to understand exactly how I'm supposed to use this.
I've tried a few things, which obviously gave me errors, bec... | If you wan to use the skimage module the order of operations are:
* Load image or define data to work with
* Create the transformation you want
* Apply the transformatioin
A work flow might look like the following:
```
from skimage import io
from skimage import transform as tf
# Load the image as a matrix
image = i... |
Reset color cycle in Matplotlib | 24,193,174 | 23 | 2014-06-12T20:13:44Z | 24,283,087 | 33 | 2014-06-18T10:21:52Z | [
"python",
"matplotlib",
"pandas"
] | Say I have data about 3 trading strategies, each with and without transaction costs. I want to plot, on the same axes, the time series of each of the 6 variants (3 strategies \* 2 trading costs). I would like the "with transaction cost" lines to be plotted with `alpha=1` and `linewidth=1` while I want the "no transacti... | You can reset the colorcycle to the original with [Axes.set\_color\_cycle](http://matplotlib.org/api/axes_api.html?#matplotlib.axes.Axes.set_color_cycle). Looking at the code for this, there is a function to do the actual work:
```
def set_color_cycle(self, clist=None):
if clist is None:
clist = rcParams['... |
Why does an import not always import nested packages? | 24,193,884 | 6 | 2014-06-12T21:05:37Z | 24,193,952 | 12 | 2014-06-12T21:09:47Z | [
"python",
"python-2.7",
"python-2.x"
] | Why the first code doesn't work while the second does?
First code:
```
import selenium
driver = selenium.webdriver.Firefox()
```
> AttributeError: 'module' object has no attribute 'webdriver'
Second code:
```
from selenium import webdriver
driver = webdriver.Firefox()
``` | Nested packages are not automatically loaded; not until you import `selenium.webdriver` is it available as an attribute. Importing *just* `selenium` is not enough.
Do this:
```
import selenium.webdriver
driver = selenium.webdriver.Firefox()
```
*Sometimes* the package itself will import a nested package in the `__i... |
installing pandas on python - where did numpy go? | 24,194,919 | 7 | 2014-06-12T22:32:08Z | 24,209,210 | 18 | 2014-06-13T15:41:08Z | [
"python",
"excel",
"url"
] | So I'm trying to open a website/url extract an excel file on the site, edit it, and then put it on a different website. I found another comment on this site that has excellent advice for how to do this using `import pandas`.
I downloaded pandas (and some other modules) from the python website, and wrote the code. But w... | Update:
Pandas 0.15.2 has been released, and it works pretty well with the most current version of openpyxl (2.0 or later). This answer is outdated.
---
OK, it appears that you have obtained the most recent version of pandas (==0.14.0), and this one requires some specific version of the Openpyxl. If you don't care ab... |
Fixed effect in Pandas or Statsmodels | 24,195,432 | 7 | 2014-06-12T23:23:38Z | 24,196,288 | 8 | 2014-06-13T01:12:37Z | [
"python",
"pandas",
"regression",
"statsmodels"
] | Is there an existing function to estimate fixed effect (one-way or two-way) from Pandas or Statsmodels.
There used to be a function in Statsmodels but it seems discontinued. And in Pandas, there is something called `plm`, but I can't import it or run it using `pd.plm()`. | An example with time fixed effects using pandas' `PanelOLS` (which is in the plm module). Notice, the import of `PanelOLS`:
```
>>> from pandas.stats.plm import PanelOLS
>>> df
y x
date id
2012-01-01 1 0.1 0.2
2 0.3 0.5
3 0.4 0.8
4 0.0 0.2
2012-02-... |
How to check if object is list of type str - python | 24,196,050 | 2 | 2014-06-13T00:37:39Z | 24,196,064 | 10 | 2014-06-13T00:39:43Z | [
"python",
"list",
"types"
] | Say I have the following objects.
```
d = ["foo1", "foo2", "foo3", "foo4"]
c = 1
a = ["foo1", 6]
```
I want to check to see if the object is a list of a certain type. If i want to check to see if d is a list and that list contains strings, how would i do that?
d should pass, but c and a should fail the... | ```
d = ["foo1", "foo2", "foo3", "foo4"]
print isinstance(d,list) and all(isinstance(x,str) for x in d)
True
d = ["foo1", "foo2", 4, "foo4"]
print isinstance(d,list) and all(isinstance(x,str) for x in d)
False
```
If `d` is a `list` and every element in `d` is a string it will return True.
You can check `int, di... |
How can I get the IP address of eth0 in Python? | 24,196,932 | 20 | 2014-06-13T02:46:10Z | 24,196,955 | 71 | 2014-06-13T02:49:36Z | [
"python",
"unix"
] | When an error occurs in a Python script on Unix , an email is sent.
I have been asked to add {Testing Environment} to the subject line of the email if the IP address is 192.168.100.37 which is the testing server. This way we can have one version of a script and a way to tell if the email is coming from messed up data ... | Two methods:
## Method #1 (use external package)
You need to ask for the IP address that is bound to your `eth0` interface. This is available from the [netifaces package](https://pypi.python.org/pypi/netifaces/)
```
import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[2][0]['addr']
print ip # s... |
How can I get the IP address of eth0 in Python? | 24,196,932 | 20 | 2014-06-13T02:46:10Z | 30,990,617 | 22 | 2015-06-22T22:04:25Z | [
"python",
"unix"
] | When an error occurs in a Python script on Unix , an email is sent.
I have been asked to add {Testing Environment} to the subject line of the email if the IP address is 192.168.100.37 which is the testing server. This way we can have one version of a script and a way to tell if the email is coming from messed up data ... | Alternatively, if you want to get the IP address of whichever interface is used to connect to the network without having to know its name, you can use this:
```
import socket
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
```
... |
How can I get the IP address of eth0 in Python? | 24,196,932 | 20 | 2014-06-13T02:46:10Z | 33,245,570 | 7 | 2015-10-20T19:47:32Z | [
"python",
"unix"
] | When an error occurs in a Python script on Unix , an email is sent.
I have been asked to add {Testing Environment} to the subject line of the email if the IP address is 192.168.100.37 which is the testing server. This way we can have one version of a script and a way to tell if the email is coming from messed up data ... | If you only need to work on Unix, you can use a system call (ref. Stack Overflow question *[Parse ifconfig to get only my IP address using Bash](http://stackoverflow.com/questions/23934425/bash-parse-ifconfig-to-get-only-my-ip-address)*):
```
import os
f = os.popen('ifconfig eth0 | grep "inet\ addr" | cut -d: -f2 | cu... |
PyCharm import external library | 24,197,970 | 9 | 2014-06-13T04:54:33Z | 24,206,781 | 29 | 2014-06-13T13:41:37Z | [
"python",
"import",
"pycharm"
] | I am using PyCharm as an editor for python code in Houdini. Whenever I try to import the main Houdini library (hou) I get an error flagged in PyCharm. If I include the code snippet:-
```
try:
import hou
except ImportError:
# Add $HFS/houdini/python2.6libs to sys.path so Python can find the
# hou mod... | Okay. I have found the answer to this myself.
It seems that since PyCharm 3.4 the path tab in the 'Project Interpreter' settings has been replaced. In order to add paths to a project you need to select the cogwheel, click on 'More...' and then select the "Show path for the selected interpreter" icon. This allows you t... |
How to speed up communication with subprocesses | 24,199,026 | 9 | 2014-06-13T06:29:40Z | 24,236,117 | 10 | 2014-06-16T02:59:10Z | [
"python",
"multithreading",
"subprocess",
"python-multithreading"
] | I am using Python 2 `subprocess` with `threading` threads to take standard input, process it with binaries `A`, `B`, and `C` and write modified data to standard output.
This script (let's call it: `A_to_C.py`) is very slow and I'd like to learn how to fix it.
The general flow is as follows:
```
A_process = subproces... | I think you are just being mislead by the way cProfile works. For example, here's a simple script that uses two threads:
```
#!/usr/bin/python
import threading
import time
def f():
time.sleep(10)
def main():
t = threading.Thread(target=f)
t.start()
t.join()
```
If I test this using cProfile, here'... |
Django cannot find static files. Need a second pair of eyes, I'm going crazy | 24,199,029 | 2 | 2014-06-13T06:30:14Z | 24,200,094 | 9 | 2014-06-13T07:40:14Z | [
"python",
"django",
"twitter-bootstrap",
"web",
"static"
] | Django will not serve my static files. Here's the **error** returned:
```
[13/Jun/2014 06:12:09] "GET /refund/ HTTP/1.1" 200 2927
[13/Jun/2014 06:12:09] "GET /static/css/bootstrap.min.css HTTP/1.1" 404 1667
[13/Jun/2014 06:12:09] "GET /static/css/cover.css HTTP/1.1" 404 1643
[13/Jun/2014 06:12:09] "GET /static/js/boot... | do the following:
1. If you are in DEBUG, set STATICFILES\_DIRS = ("path/to/static") variable in your settings.py. It should then work **only** in DEBUG mode.
2. If you want it to also work in deploy mode, set STATIC\_ROOT = ("path/to/static\_root") variable in the settings.py. Then, execute `python manage.py collects... |
pymongo.errors.CursorNotFound: cursor id '...' not valid at server | 24,199,729 | 13 | 2014-06-13T07:18:20Z | 24,200,795 | 26 | 2014-06-13T08:22:30Z | [
"python",
"mongodb",
"pymongo"
] | I am trying to fetch some ids that exist in a mongo database with the following code:
```
client = MongoClient('xx.xx.xx.xx', xxx)
db = client.test_database
db = client['...']
collection = db.test_collection
collection = db["..."]
for cursor in collection.find({ "$and" : [{ "followers" : { "$gt" : 2000 } }, { "follo... | You're getting this error because the cursor is timing out on the server (after 10 minutes of inactivity).
From the pymongo documentation:
> Cursors in MongoDB can timeout on the server if theyâve been open for
> a long time without any operations being performed on them. This can
> lead to an CursorNotFound except... |
pandas apply function to multiple columns and multiple rows | 24,202,110 | 5 | 2014-06-13T09:32:09Z | 24,202,646 | 7 | 2014-06-13T09:59:00Z | [
"python",
"pandas"
] | I have a dataframe with consecutive pixel coordinates in rows and columns 'xpos', 'ypos', and I want to calculate the angle in degrees of each path between consecutive pixels. Currently I have the solution presented below, which works fine and for teh size of my file is speedy enough, but iterating through all the rows... | You can do this via the following method and I compared the pandas way to your way and it is over 1000 times faster, and that is without adding the list back as a new column! This was done on a 10000 row dataframe
```
In [108]:
%%timeit
import numpy as np
df['angle'] = np.abs(180/math.pi * np.arctan(df['xpos'].shift(... |
Python dictionary get multiple values | 24,204,087 | 2 | 2014-06-13T11:18:52Z | 24,204,498 | 9 | 2014-06-13T11:42:30Z | [
"python",
"dictionary"
] | Sry if this question already exists, but I've been searching for quite some time now.
I have a dictionary in python, and what I want to do is get some values from it as a list, but I don't know if this is supported by the implementation.
```
myDictionary.get('firstKey') # works fine
myDictionary.get('firstKey','se... | There already exists a function for this:
```
from operator import itemgetter
my_dict = {x: x**2 for x in range(10)}
itemgetter(1, 3, 2, 5)(my_dict)
#>>> (1, 9, 4, 25)
```
`itemgetter` will return a tuple if more than one argument is passed. To pass a list to `itemgetter`, use
```
itemgetter(*wanted_keys)(my_dict)... |
Selenium Webdriver Exception: u'f.QueryInterface is not a function | 24,211,001 | 10 | 2014-06-13T17:39:21Z | 24,555,155 | 7 | 2014-07-03T13:35:17Z | [
"python",
"exception",
"selenium",
"webdriver",
"amazon-dynamodb"
] | I've run into an interesting exception but I haven no Idea what caused it.
This is my exception:
```
File "/Users/tai/Documents/workspace/testSelenium/testS/__init__.py", line 86, in runFlashY
openWebsites() File "/Users/tai/Documents/workspace/testSelenium/testS/__init__.py", line 50, in openWebsites
new... | In my case that's was just wrong parsing from config.
I got same error
`selenium.common.exceptions.WebDriverException: Message: u'f.QueryInterface is not a function'`
Url which I wrote was placed in quotes, but it's wrong.
Url should stay as it is without any quotes.
Your error here `self.execute(Command.GET, {'url... |
Exporting a Scikit Learn Random Forest for use on Hadoop Platform | 24,212,612 | 6 | 2014-06-13T19:28:11Z | 24,214,815 | 8 | 2014-06-13T22:54:05Z | [
"python",
"hadoop",
"machine-learning",
"scikit-learn",
"pmml"
] | I've developed a spam classifier using pandas and scikit learn to the point where it's ready for integration into our hadoop-based system. To this end, I need to export my classifier to a more common format than pickling.
The Predictive Model Markup Language (PMML) is my preferred export format. It plays exceedingly w... | You could use [Py2PMML](https://support.zementis.com/entries/37092748-Introducing-Py2PMML) to export the model to PMML and then evaluate it on Hadoop using [JPMML-Cascading](https://github.com/jpmml/jpmml-cascading). JPMML is open source but Py2PMML from Zementis seems to be a commercial product. Besides this alternati... |
How can I get tweets older than a week (using tweepy or other python libraries) | 24,214,189 | 13 | 2014-06-13T21:43:17Z | 24,246,840 | 13 | 2014-06-16T15:10:49Z | [
"python",
"twitter",
"tweepy"
] | I have been trying to figure this out but this is a really frustrating. I'm trying to get tweets with a certain hashtag (a great amount of tweets) using Tweepy. But this doesn't go back more than one week. I need to go back at least two years for a period of a couple of months. Is this even possible, if so how?
Just f... | You cannot use the twitter search API to collect tweets from two years ago. Per the docs:
> Also note that the search results at twitter.com may return historical results while the Search API usually only serves tweets from the past week. - [Twitter documentation](https://dev.twitter.com/docs/using-search).
If you ne... |
How can I get tweets older than a week (using tweepy or other python libraries) | 24,214,189 | 13 | 2014-06-13T21:43:17Z | 35,077,920 | 8 | 2016-01-29T06:05:27Z | [
"python",
"twitter",
"tweepy"
] | I have been trying to figure this out but this is a really frustrating. I'm trying to get tweets with a certain hashtag (a great amount of tweets) using Tweepy. But this doesn't go back more than one week. I need to go back at least two years for a period of a couple of months. Is this even possible, if so how?
Just f... | As you have noticed Twitter API has some limitations, I have implemented a code that do this using the same strategy as Twitter running over a browser. Take a look, you can get the oldest tweets: <https://github.com/Jefferson-Henrique/GetOldTweets-python> |
Django @override_settings does not allow dictionary? | 24,214,636 | 3 | 2014-06-13T22:33:00Z | 24,214,672 | 7 | 2014-06-13T22:37:47Z | [
"python",
"django",
"unit-testing",
"testing",
"django-settings"
] | I am new to Python decorators so perhaps I am missing something simple, here is my situation:
This works for me:
```
def test_something(self):
settings.SETTING_DICT['key'] = True #no error
...
```
But this throws a "SyntaxError: keyword can't be an expression":
```
@override_settings(SETTING_DICT['key'] = T... | You should override the whole dict:
```
@override_settings(SETTING_DICT={'key': True})
def test_something(self):
...
```
Or, you can use `override_settings` as a context manager:
```
def test_something(self):
value = settings.SETTING_DICT
value['key'] = True
with override_settings(SETTING_DICT=valu... |
Django CommandError: App 'polls' has migrations | 24,215,005 | 15 | 2014-06-13T23:18:49Z | 24,215,290 | 17 | 2014-06-13T23:58:56Z | [
"python",
"django",
"migration",
"database-migration",
"manage.py"
] | Trying to follow the tutorial at [Django project](https://docs.djangoproject.com/en/1.6/intro/tutorial01/).
The problem I've come across is that when performing the command:
`python manage.py sql polls` I'm given the error:
> CommandError: App 'polls' has migrations. only the sqlmigrate and sqlflush commands can be u... | The problem is that you are using `Django 1.8` while going through 1.6 tutorial. Pay attention to the first words at the beginning of the [tutorial](https://docs.djangoproject.com/en/1.6/intro/tutorial01/):
> This tutorial is written for Django 1.6 and Python 2.x. If the Django
> version doesnât match, you can refer... |
Django CommandError: App 'polls' has migrations | 24,215,005 | 15 | 2014-06-13T23:18:49Z | 25,794,327 | 30 | 2014-09-11T18:08:42Z | [
"python",
"django",
"migration",
"database-migration",
"manage.py"
] | Trying to follow the tutorial at [Django project](https://docs.djangoproject.com/en/1.6/intro/tutorial01/).
The problem I've come across is that when performing the command:
`python manage.py sql polls` I'm given the error:
> CommandError: App 'polls' has migrations. only the sqlmigrate and sqlflush commands can be u... | You can either run `python manage.py makemigration` followed by `python manage.py migrate` or just delete migrations folder |
"pip install line_profiler" fails | 24,215,492 | 9 | 2014-06-14T00:33:08Z | 24,215,582 | 12 | 2014-06-14T00:47:28Z | [
"python",
"pip"
] | I type
```
sudo pip install "line_profiler"
```
and I get
```
Downloading/unpacking line-profiler
Could not find a version that satisfies the requirement line-profiler (from versions: 1.0b1, 1.0b2, 1.0b3)
Cleaning up...
No distributions matching the version for line-profiler
Storing debug log for failure in /home/... | The problem is not in the fact that `pip` converts `_` into the `-` to meet the package naming requirements, but the thing is: the package is in `beta` state, there is no stable package versions. In other words, there are only `beta` package version links available on the [package PyPI page](https://pypi.python.org/pyp... |
Adding a new pandas column with mapped value from a dictionary | 24,216,425 | 12 | 2014-06-14T03:53:49Z | 24,216,489 | 19 | 2014-06-14T04:07:18Z | [
"python",
"pandas"
] | I'm trying do something that should be really simple in pandas, but it seems anything but. I'm trying to add a column to an existing pandas dataframe that is a mapped value based on another (existing) column. Here is a small test case:
```
import pandas as pd
equiv = {7001:1, 8001:2, 9001:3}
df = pd.DataFrame( {"A": [... | The right way of doing it will be `df["B"] = df["A"].map(equiv)`.
```
In [55]:
import pandas as pd
equiv = {7001:1, 8001:2, 9001:3}
df = pd.DataFrame( {"A": [7001, 8001, 9001]} )
df["B"] = df["A"].map(equiv)
print(df)
A B
0 7001 1
1 8001 2
2 9001 3
[3 rows x 2 columns]
```
And it will handle the situat... |
How to install PL/Python on PostgreSQL 9.3 x64 Windows 7? | 24,216,627 | 5 | 2014-06-14T04:39:19Z | 24,218,449 | 7 | 2014-06-14T09:18:48Z | [
"python",
"postgresql",
"windows-7-x64",
"postgresql-9.3",
"plpython"
] | I have tried to install the PL/Python v2.x language inside PostgreSQL on my database running the query:
```
CREATE EXTENSION plpythonu;
```
(I got this from <http://www.postgresql.org/docs/9.3/static/plpython.html>)
But I'm getting this error:
```
ERRO: não pôde acessar arquivo "$libdir/plpython2": No such file ... | Typically this error message is a misleading one emitted by the Windows API `LoadLibrary` call. What it actually means is closer to:
> Error when loading `plpython2.dll`: Cannot find dependency DLL `python27.dll` on `PATH`
but instead Windows just acts like it is `plpython2.dll` its self that could not be loaded.
Yo... |
adb pull file in a specific folder of Pc | 24,219,287 | 3 | 2014-06-14T11:06:11Z | 24,219,661 | 7 | 2014-06-14T11:55:45Z | [
"android",
"python",
"shell",
"adb",
"pull"
] | i want save the screenshot created, in a specific folder on my PC.
```
cmd = 'adb shell screencap -p /sdcard/screen.png'
subprocess.Popen(cmd.split())
time.sleep(5)
cmd ='adb pull /sdcard/screen.png screen.png'
subprocess.Popen(cmd.split())
```
This work if i want the image in my workspace. But if i want pull the s... | Always use double quotes("") for local paths. use it like this:
```
cmd = "adb pull /sdcard/screen.png \"C:\\Users\\xxx\\Desktop\\prova\\screen.png\"";
``` |
Starting phantomJS from a script in a cronjob | 24,219,473 | 2 | 2014-06-14T11:31:14Z | 24,219,836 | 8 | 2014-06-14T12:16:49Z | [
"python",
"cron",
"phantomjs",
"crontab"
] | I'm running a python script through a cronjob. I have a virtual environment and in the cronjob I'm running it through this virtual environment. When I run the script normally phantomJS starts as it should, but running it through a script in a cronjob I get this error. What is missing in the cronjob to be able to start ... | As phantom is probably installed in `/usr/local/bin`, you should add that dir to `PATH` in your crontab. The following should do the trick:
```
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
``` |
Content-length error in google cloud endpoints testing | 24,219,654 | 6 | 2014-06-14T11:55:05Z | 25,829,000 | 9 | 2014-09-14T00:25:02Z | [
"python",
"unit-testing",
"google-cloud-endpoints"
] | I get the following error whenever I want to test a 404 HTTP error path in my code:
> AssertionError: Content-Length is different from actual app\_iter length (512!=60)
I have created a minimal sample that triggers this behavior:
```
import unittest
import endpoints
from protorpc import remote
from protorpc.message_... | This is a known error with App Engine.
Endpoints does not set the correct Content-Length header when you raise an exception:
<https://code.google.com/p/googleappengine/issues/detail?id=10544>
To fix it there is a `diff` file included in the link above, or follow my instructions to temporarily patch it by yourself.
... |
Get access token from Python Social Auth | 24,221,117 | 4 | 2014-06-14T14:51:31Z | 24,231,525 | 15 | 2014-06-15T16:08:02Z | [
"python",
"django",
"python-social-auth"
] | I have Python Social Auth implemented on my site, and I'm trying to access (after the login process) into the access token that the user got. I can see on the Django admin that there's a field called extra\_data containing the access token, but I don't know how to access it from my code.
Any idea?
I want to do someth... | Given a user instance, you can get the token by doing this:
```
social = user.social_auth.get(provider='provider name')
social.extra_data['access_token']
```
Assuming Facebook provider:
```
social = user.social_auth.get(provider='facebook')
social.extra_data['access_token']
``` |
How do I use flask.url_for() with flask-restful? | 24,223,628 | 8 | 2014-06-14T19:41:24Z | 24,225,454 | 8 | 2014-06-15T00:15:53Z | [
"python",
"flask",
"flask-restful"
] | I have setup Flask restful like this:
```
api = Api(app, decorators=[csrf_protect.exempt])
api.add_resource(FTRecordsAPI,
'/api/v1.0/ftrecords/<string:ios_sync_timestamp>',
endpoint="api.ftrecord")
```
I would like to redirect internally to the endpoint `api.ftrecord`.
But the momen... | You'll need to specify a value for the `ios_sync_timestamp` part of your URL:
```
flask.url_for('api.ftrecord', ios_sync_timestamp='some value')
```
or you could use [`Api.url_for()`](http://flask-restful.readthedocs.org/en/latest/api.html#flask.ext.restful.Api.url_for), which takes a resource:
```
api.url_for(FTRec... |
ImportError: dynamic module does not define init function (initfizzbuzz) | 24,226,001 | 8 | 2014-06-15T02:17:52Z | 24,226,039 | 11 | 2014-06-15T02:27:33Z | [
"python",
"c",
"python-c-extension"
] | I tried to compile `fizzbuzz.c` to import from python. For building `fizzbuzz.c`,I used `python setup.py build_ext -i`.
After building it, I tried to import `fizzbuzz.c` but the error below occurred.
How can I solve this problem ?
### Error
```
>>> import fizzbuzz
Traceback (most recent call last):
File "<stdin>",... | Python doesn't and cannot support arbitrary C files as modules. You'll have to follow certain conventions to let Python know what functions your module supports.
To do so, Python will look for a `init<name>` function, where `<name>` is the module name. Python was looking for `initfizzbuzz` but failed to find it, so lo... |
ImportError: dynamic module does not define init function (initfizzbuzz) | 24,226,001 | 8 | 2014-06-15T02:17:52Z | 32,114,733 | 9 | 2015-08-20T09:37:25Z | [
"python",
"c",
"python-c-extension"
] | I tried to compile `fizzbuzz.c` to import from python. For building `fizzbuzz.c`,I used `python setup.py build_ext -i`.
After building it, I tried to import `fizzbuzz.c` but the error below occurred.
How can I solve this problem ?
### Error
```
>>> import fizzbuzz
Traceback (most recent call last):
File "<stdin>",... | The error also occurs, when using [boost::python](http://www.boost.org/doc/libs/1_59_0/libs/python/doc/), if the module name is different to the compiled .so file name. For example:
**hello.cpp**
```
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
using namespace std;
using namespace boost::python;... |
ValueError: The channel sent is invalid on a Raspberry Pi - Controlling GPIO Pin 2 (BOARD) using Python causes Error | 24,226,310 | 4 | 2014-06-15T03:32:43Z | 25,630,756 | 8 | 2014-09-02T19:20:19Z | [
"python",
"raspberry-pi",
"raspbian",
"gpio"
] | So I have a tiny little fan connected to pin 6(Ground) and pin 2. I am trying to manually start and stop the fan when needed but I am getting this error when trying:
ValueError: The channel sent is invalid on a Raspberry Pi
Here is my code that I am executing as root. It seems to be working on other pins but not Pin ... | It could be something stupid, i was looking exacty the same. It seems there are two "modes" in the GPIO. *Change GPIO.setmode(GPIO.BOARD)* to
```
GPIO.setmode(GPIO.BCM)
```
It worked for me on a clean installation of Raspbian |
Changing User Agent in Python 3 for urrlib.request.urlopen | 24,226,781 | 17 | 2014-06-15T05:18:14Z | 24,226,797 | 14 | 2014-06-15T05:21:37Z | [
"python",
"python-3.x",
"urllib",
"user-agent"
] | I want to open a url using `urllib.request.urlopen('someurl')`:
```
with urllib.request.urlopen('someurl') as url:
b = url.read()
```
I keep getting the following error:
```
urllib.error.HTTPError: HTTP Error 403: Forbidden
```
I understand the error to be due to the site not letting python access it, to stop bots ... | From the [Python docs](https://docs.python.org/3.4/library/urllib.request.html#urllib.request.Request):
```
import urllib.request
req = urllib.request.Request(
url,
data=None,
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.... |
Changing User Agent in Python 3 for urrlib.request.urlopen | 24,226,781 | 17 | 2014-06-15T05:18:14Z | 29,546,832 | 8 | 2015-04-09T19:03:35Z | [
"python",
"python-3.x",
"urllib",
"user-agent"
] | I want to open a url using `urllib.request.urlopen('someurl')`:
```
with urllib.request.urlopen('someurl') as url:
b = url.read()
```
I keep getting the following error:
```
urllib.error.HTTPError: HTTP Error 403: Forbidden
```
I understand the error to be due to the site not letting python access it, to stop bots ... | ```
from urllib.request import urlopen, Request
urlopen(Request(url, headers={'User-Agent': 'Mozilla'}))
``` |
Does Google App Engine support Python 3? | 24,229,203 | 32 | 2014-06-15T11:37:15Z | 24,229,338 | 31 | 2014-06-15T11:54:31Z | [
"python",
"google-app-engine"
] | I started learning **Python 3.4** and would like to start using libraries as well as **Google App Engine**, but the majority of **Python** libraries only support **Python 2.7** and the same with **Google App Engine**.
Should I learn **2.7** instead or is there an easier way? (Is it possible to have 2 Python versions o... | **No, It doesn't.**
`Google App Engine` `(GAE)` uses sandboxed `Python 2.7` runtime for `Python` applications. That is the normal **App Engine Hosting**. However, in `GAE` you can use [**Managed VM Hosting**](https://cloud.google.com/appengine/docs/managed-vms/).
The **Managed VM Hosting** lets you run `GAE` applicat... |
django object is not JSON serializable error after upgrading django to 1.6.5 | 24,229,397 | 9 | 2014-06-15T12:02:55Z | 24,233,767 | 36 | 2014-06-15T20:21:30Z | [
"python",
"json",
"django",
"jsonserializer",
"django-jsonfield"
] | I have a django app which was running on `1.4.2` version and working completely fine, but recently i updated it to django `1.6.5` and facing some wierd errors like below
Actually i am getting this during user/client registration process in my site functionality
```
Request URL: http://example.com/client/registrati... | Django 1.6 changed the serializer from pickle to json. pickle can serialize things that json can't.
You can change the value of [SESSION\_SERIALIZER](https://docs.djangoproject.com/en/1.5/ref/settings/#std:setting-SESSION_SERIALIZER) in your `settings.py` to get back the behaviour from Django before version 1.6.
```
... |
Python: can't catch an IndexError | 24,230,324 | 4 | 2014-06-15T13:58:40Z | 24,230,325 | 11 | 2014-06-15T13:58:40Z | [
"python",
"python-2.7",
"exception-handling"
] | Disclaimer: this looks like a duplicate, but finding an answer to this particular problem was more than trivial - I hope others will find this question/answer with more ease!
When I run the following code, it fails to catch the second IndexError, raising it instead:
```
try:
raise ValueError
except ValueError,Index... | The problem was bad use of `except ...` syntax. The line:
```
except ValueError,IndexError:
```
should be
```
except (ValueError,IndexError):
```
*Explanation*: If you want to inspect the exception that was thrown, the syntax is `except <exception-class>,e` where variable `e` is assigned an instance of `<exception-... |
Are tuples in Python immutable? | 24,232,305 | 2 | 2014-06-15T17:36:25Z | 24,232,331 | 7 | 2014-06-15T17:38:15Z | [
"python",
"tuples",
"immutability"
] | It says
> A tuple can not be changed in any way once it is created.
But when I do the following:
```
t1=(4,5,8,2,3)
t1=t1+(7,1)
print(t1)
```
the tuple is changing to `(4, 5, 8, 2, 3, 7, 1)`; why is that? What is really meant by "tuples are immutable"? | Yes, tuples are immutable; once created, they cannot be changed. `t1=t1+(7,1)` creates a *new tuple* and assigns it to the name `t1`. It **does not** change the tuple object originally referenced by that name.
Demo:
```
>>> t = (1, 2, 3)
>>> id(t)
4365928632
>>> t = t + (4, 5)
>>> id(t)
4354884624 # different id, dif... |
Django Serializer Method Field | 24,233,988 | 7 | 2014-06-15T20:49:28Z | 24,273,265 | 18 | 2014-06-17T21:05:22Z | [
"python",
"django",
"django-rest-framework"
] | Can't seem to find the right google search for this so here it goes:
I have a field in my serializer tat goes like this:
```
likescount = serializers.IntegerField(source='post.count', read_only=True)
```
which counts all the related field "post".
Now I want to use that field as part of my method:
```
def popularit... | assuming `post.count` is being used to measure the number of likes on a post and you don't actually intend to divide an integer by a timestamp in your popularity method, then try this:
use a [SerializerMethodField](http://www.django-rest-framework.org/api-guide/fields#serializermethodfield)
```
likescount = serialize... |
No module named machinery | 24,237,385 | 3 | 2014-06-16T05:59:32Z | 24,745,079 | 7 | 2014-07-14T20:11:21Z | [
"python",
"py2exe"
] | I am trying to make exe using `py2exe` in Python. When I import `py2exe` I am getting error like this:
```
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import py2exe
Traceback (most recent call last):
Fil... | I just ran into this myself. I had installed 0.9 from pypi as well. If you look at the pypi page here [py2exe on pypi](https://pypi.python.org/pypi/py2exe/0.9.2.0), you'll see that the download only supports Python 3.3 and later and you should use [the 0.6 download from here](http://sourceforge.net/project/showfiles.ph... |
How to split a python string on new line characters | 24,237,524 | 3 | 2014-06-16T06:09:23Z | 24,237,675 | 8 | 2014-06-16T06:22:40Z | [
"python",
"string",
"split"
] | In python3 in Win7 I read a web page into a string.
I then want to split the string into a list at newline characters.
I can't enter the newline into my code as the argument in split(), because I get a syntax error 'EOL while scanning string literal'
If I type in the characters \ and n, I get a Unicode error.
Is th... | Have you tried using [String splitlines() method](https://docs.python.org/2/library/stdtypes.html#str.splitlines)?
From the docs:
> str.splitlines([keepends])
>
> Return a list of the lines in the string, breaking at line boundaries.
> This method uses the universal newlines approach to splitting lines.
> Line breaks... |
Flask: Decorator to verify JSON and JSON Schema | 24,238,743 | 6 | 2014-06-16T07:40:48Z | 24,238,851 | 19 | 2014-06-16T07:48:52Z | [
"python",
"json",
"flask",
"jsonschema",
"python-decorators"
] | I have a flask application with calls expecting JSON payload. Before each call is processed, I have a 2-step error checking process:
* Assert that the payload is a valid JSON
* Assert that the JSON payload complies with a specific schema
Which is implemented in the following fashion:
```
@app.route('/activate', meth... | Just use the `request` context global in your decorator. It is available *during any request*.
```
from functools import wraps
from flask import (
current_app,
jsonify,
request,
)
def validate_json(f):
@wraps(f)
def wrapper(*args, **kw):
try:
request.json
except BadReq... |
Python - how to convert a "raw" string into a normal string | 24,242,433 | 4 | 2014-06-16T11:16:21Z | 24,242,596 | 12 | 2014-06-16T11:24:41Z | [
"python",
"string",
"python-3.x",
"rawstring"
] | In Python, I have a string like this:
```
'\\x89\\n'
```
How can I decode it into a normal string like:
```
'\x89\n'
``` | Python 2 byte strings can be decoded with the `'string_escape'` codec:
```
raw_string.decode('string_escape')
```
Demo:
```
>>> '\\x89\\n'.decode('string_escape')
'\x89\n'
```
For *unicode* literals, use `'unicode_escape'`. In Python 3, where strings are unicode strings by default, only byte strings have a `.decode... |
pymc3 : Multiple observed values | 24,242,660 | 4 | 2014-06-16T11:28:33Z | 24,271,760 | 12 | 2014-06-17T19:21:30Z | [
"python",
"pymc",
"poisson",
"pymc3"
] | I have some observational data for which I would like to estimate parameters, and I thought it would be a good opportunity to try out PYMC3.
My data is structured as a series of records. Each record contains a pair of observations that relate to a fixed one hour period. One observation is the total number of events th... | There is nothing fundamentally wrong with your approach, except for the pitfalls of any Bayesian MCMC analysis: (1) non-convergence, (2) the priors, (3) the model.
*Non-convergence*: I find a traceplot that looks like this:

This is not a good thin... |
python 3.4: random.choice on Enum | 24,243,500 | 6 | 2014-06-16T12:15:15Z | 24,243,545 | 12 | 2014-06-16T12:17:28Z | [
"python",
"random",
"enums",
"python-3.4"
] | I would like to use random.choice on an Enum.
I tried :
```
class Foo(Enum):
a = 0
b = 1
c = 2
bar = random.choice(Foo)
```
But this code is not working, how can I do that ? | An `Enum` is not a *sequence*, so you cannot pass it to `random.choice()`, which tries to pick an index between 0 and `len(Foo)`. Like a dictionary, index access to an `Enum` instead expects enumeration *names* to be passed in, so `Foo[<integer>]` fails here with a `KeyError`.
You can cast it to a list first:
```
bar... |
About the changing id of a Python immutable string | 24,245,324 | 16 | 2014-06-16T13:50:08Z | 24,245,514 | 30 | 2014-06-16T14:00:32Z | [
"python",
"string",
"python-2.7",
"immutability",
"python-internals"
] | Something about the `id` of objects of type `str` (in python 2.7) puzzles me. The `str` type is immutable, so I would expect that once it is created, it will always have the same `id`. I believe I don't phrase myself so well, so instead I'll post an example of input and output sequence.
```
>>> id('so')
14061415512388... | CPython does **not** intern strings by default, but in practice, a lot of places in the Python codebase do reuse already-created string objects. A lot of Python internals use (the C-equivalent of) the [`intern()` function call](https://docs.python.org/2/library/functions.html#intern) to explicitly intern Python strings... |
Long Int literal - Invalid Syntax? | 24,249,519 | 2 | 2014-06-16T17:59:45Z | 24,249,555 | 9 | 2014-06-16T18:02:25Z | [
"python",
"python-3.x",
"int",
"syntax-error",
"long-integer"
] | The Python tutorial book I'm using is slightly outdated, but I've decided to continue using it with the latest version of Python to practice debugging. Sometimes there are a few things in the book's code that I learn have changed in the updated Python, and I'm not sure if this is one of them.
While fixing a program so... | Just drop the `L`; **all** integers in Python 3 are long. What was `long` in Python 2 is now the standard `int` type in Python 3.
The original code doesn't have to use a long integer either; Python 2 switches to the `long` type transparently as needed *anyway*.
You could just install a Python 2.7 interpreter instead,... |
How can i vectorize list using sklearn DictVectorizer | 24,250,469 | 6 | 2014-06-16T19:07:35Z | 24,283,394 | 11 | 2014-06-18T10:37:24Z | [
"python",
"scikit-learn"
] | I found next example on sklearn docs site:
```
>>> measurements = [
... {'city': 'Dubai', 'temperature': 33.},
... {'city': 'London', 'temperature': 12.},
... {'city': 'San Fransisco', 'temperature': 18.},
... ]
>>> from sklearn.feature_extraction import DictVectorizer
>>> vec = DictVectorizer()
>>> vec.... | Change the representation to
```
>>> measurements = [
... {'city=Dubai': True, 'city=London': True, 'temperature': 33.},
... {'city=London': True, 'city=San Fransisco': True, 'temperature': 12.},
... {'city': 'San Fransisco', 'temperature': 18.},
... ]
```
Then the result is exactly as you expect:
```
>>... |
Pandas read_csv low_memory and dtype options | 24,251,219 | 48 | 2014-06-16T19:56:47Z | 24,251,426 | 14 | 2014-06-16T20:11:56Z | [
"python",
"parsing",
"numpy",
"pandas",
"dataframe"
] | When calling
```
df = pd.read_csv('somefile.csv')
```
I get:
> /Users/josh/anaconda/envs/py27/lib/python2.7/site-packages/pandas/io/parsers.py:1130:
> DtypeWarning: Columns (4,5,7,16) have mixed types. Specify dtype
> option on import or set low\_memory=False.
Why is the `dtype` option related to `low_memory`, and ... | Try:
```
dashboard_df = pd.read_csv(p_file, sep=',', error_bad_lines=False, index_col=False, dtype='unicode')
```
According to the pandas documentation:
> dtype : Type name or dict of column -> type
As for low\_memory, it's True [by default](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.parsers.read_... |
Pandas read_csv low_memory and dtype options | 24,251,219 | 48 | 2014-06-16T19:56:47Z | 27,232,309 | 62 | 2014-12-01T16:04:11Z | [
"python",
"parsing",
"numpy",
"pandas",
"dataframe"
] | When calling
```
df = pd.read_csv('somefile.csv')
```
I get:
> /Users/josh/anaconda/envs/py27/lib/python2.7/site-packages/pandas/io/parsers.py:1130:
> DtypeWarning: Columns (4,5,7,16) have mixed types. Specify dtype
> option on import or set low\_memory=False.
Why is the `dtype` option related to `low_memory`, and ... | # The deprecated low\_memory option
The `low_memory` option is not properly deprecated, but it should be, since it does not actually do anything differently[[source](https://github.com/pydata/pandas/issues/5888)]
The reason you get this `low_memory` warning is because guessing dtypes for each column is very memory de... |
TypeError: not enough arguments for format string when using %s | 24,252,358 | 6 | 2014-06-16T21:16:38Z | 24,252,405 | 11 | 2014-06-16T21:19:58Z | [
"python",
"string",
"string-formatting",
"typeerror"
] | this is my code
```
import sys
name = input("Enter your name:")
last_name = input("Enter your last name:")
gender = input("Enter your gender:")
age = input("Enter your age:")
print ("So your name is %s, your last name is %s, you are %s and you are %s years old" % name, last_name, gender, age)
```
I've searched the to... | You need to put your arguments for string formatting in parenthesis:
```
print (... % (name, last_name, gender, age))
```
Otherwise, Python will only see `name` as an argument for string formatting and the rest as arguments for the `print` function.
---
Note however that using `%` for string formatting operations i... |
numpy: multiplying a 2D array by a 1D array | 24,253,021 | 3 | 2014-06-16T22:10:21Z | 24,253,052 | 7 | 2014-06-16T22:12:53Z | [
"python",
"arrays",
"numpy"
] | Let us say one has an array of 2D vectors:
```
v = np.array([ [1, 1], [1, 1], [1, 1], [1, 1]])
v.shape = (4, 2)
```
And an array of scalars:
```
s = np.array( [2, 2, 2, 2] )
s.shape = (4,)
```
I would like the result:
```
f(v, s) = np.array([ [2, 2], [2, 2], [2, 2], [2, 2]])
```
Now, executing `v*s` is an error. ... | Add a new singular dimension to the vector:
```
v*s[:,None]
```
This is equivalent to reshaping the vector as (len(s), 1). Then, the shapes of the multiplied objects will be (4,2) and (4,1), which are compatible due to NumPy broadcasting rules (corresponding dimensions are either equal to each other or equal to 1).
... |
numpy logical_and: unexpected behaviour | 24,253,243 | 3 | 2014-06-16T22:35:38Z | 24,253,308 | 11 | 2014-06-16T22:42:26Z | [
"python",
"numpy"
] | Let us say I give you the following boolean arrays:
```
b1 = np.array([ True, True, False, True ])
b2 = np.array([ True, False, False, True ])
b3 = np.array([ True, True, True, False ])
```
If you `AND` them together, you would expect the following result:
```
b4 = np.array([ True, False, False, False ])
```
R... | Look at the [documentation of `np.logical_and`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_and.html). Like most of the NumPy operator functions, the third parameter is an `out` parameter, specifying a destination array. It is *not* an operand! Putting `b3` there will simply overwrite the contents... |
How do you call an instance of a class in Python? | 24,253,761 | 11 | 2014-06-16T23:40:55Z | 24,253,762 | 17 | 2014-06-16T23:40:55Z | [
"python",
"class",
"call"
] | This is inspired by a question I just saw, "Change what is returned by calling class instance", but was quickly answered with `__repr__` (and accepted, so the questioner did not actually intend to call the instance).
Now calling an instance of a class can be done like this:
```
instance_of_object = object()
instance... | You call an instance of a class as in the following:
```
o = object() # create our instance
o() # call the instance
```
But this will typically give us an error.
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'object' object is not callable
```
How can we call the instance a... |
Permanently set Python path for Anaconda within Cygwin | 24,255,407 | 19 | 2014-06-17T03:47:12Z | 27,258,333 | 13 | 2014-12-02T20:28:34Z | [
"python",
"windows",
"cygwin",
"anaconda"
] | I'm trying to install Anaconda on my Windows 7 machine. I often use cygwin to for my command-line work, and I would like to manage Anaconda from there. I've worked through the graphic installer without any issues, and checked necessary boxes to reset my default path to this install of python. I go ahead to check where ... | To work with the interactive Python shell in Cygwin I use the -i option.
To get it from the Anaconda install, I used the steps suggested above:
```
$ export PATH=/cygdrive/c/anaconda:$PATH
$ which python
/cygdrive/c/anaconda/python
```
Then I launch python within Cygwin with the -i option:
```
$ python -i
Python 2.... |
Print on the same line, step after step | 24,257,303 | 2 | 2014-06-17T06:46:20Z | 24,257,329 | 8 | 2014-06-17T06:47:46Z | [
"python",
"python-3.x"
] | I've developed a Python script that performs several tasks in a row (mainly connecting to servers and retrieving information).
There are many steps, and for each of them I would like to display a dot, so that the user knows there is something going on.
At the end of each step, I do:
```
print('.', end='')
```
And i... | By default, `stdout` is line buffered, meaning the buffer won't be flushed until you write a newline.
Flush the buffer explicitly each time you print a `'.'`:
```
print('.', end='', flush=True)
```
The `flush` keyword was added in Python 3.3; for older versions, use `sys.stdout.flush()`.
From the [`print()` functio... |
DistutilsOptionError: must supply either home or prefix/exec-prefix -- not both | 24,257,803 | 43 | 2014-06-17T07:16:07Z | 24,357,384 | 96 | 2014-06-23T01:35:53Z | [
"python",
"google-app-engine",
"install",
"pip",
"distutils"
] | I've been usually installed python packages through pip.
For Google App Engine, I need to install packages to another target directory.
So, I've tried
> pip install -I flask-restful --target ./lib
but, always fail with
> must supply either home or prefix/exec-prefix -- not both
any good suggestions? | Are you using OS X and Homebrew? The Homebrew python page <https://github.com/Homebrew/brew/blob/master/docs/Homebrew-and-Python.md> calls out a known issue with pip and a work around.
Worked for me.
> You can make this "empty prefix" the default by adding a
> ~/.pydistutils.cfg file with the following contents:
>
> ... |
Logging module does not print in IPython | 24,259,952 | 6 | 2014-06-17T09:17:10Z | 24,261,901 | 8 | 2014-06-17T10:50:22Z | [
"python",
"logging",
"ipython",
"qtconsole"
] | The following code does print 'I want this to print' in 'ipython qtconsole', however it does not print in plain IPython.
```
import logging
import logging.handlers
log = logging.getLogger()
f = logging.Formatter("%(asctime)s - %(module)s. %(funcName)s - %(levelname)s - %(message)s")
fh = logging.handlers.TimedRotat... | It seems like `qtconsole` adds an handler to the `root` logger:
```
In [1]: import logging
...: root = logging.getLogger()
...: root.handlers
...:
Out[1]: [<logging.StreamHandler at 0x7fd8e00e1f98>]
```
While using the normal python interpreter or just `ipython`:
```
In [1]: import logging
In [2]: root = ... |
python map object at | 24,260,582 | 2 | 2014-06-17T09:46:18Z | 24,260,781 | 7 | 2014-06-17T09:55:11Z | [
"python",
"map",
"filter"
] | im new to Python (version 3.41) and I have a problem with printing the result of using map and filter function. How can I find these results?
```
>>> def double(n):
return n*2
>>> li = [1,2,3]
>>> map(double, li)
<map object at 0x000000000333DCF8>
>>> print(map(double,li))
<map object at 0x000000000333DC50>
``` | Try either :
```
print(list(map(double,li))
```
Or :
```
for item in map(double,li):
print(item)
```
In Python 3.4 map will return an iterator instead of a list (as it did in 2.7+). This is great as far as memory footprint is concerned but it doesn't map well to printing (pun intended) |
Excluding directory, module in python nosetest | 24,263,365 | 6 | 2014-06-17T12:06:04Z | 24,263,587 | 13 | 2014-06-17T12:17:00Z | [
"python",
"unit-testing",
"testing",
"nose"
] | We use nose to discover tests and run them. All the tests are written in `TestCase` compatible way so any test runner can run the. Problem is we have some directories which doesn't have any test. But test runner continue to discover test from there. If one of those directory has lot of files its stuck. So how can I exc... | There is a [`nose-exclude`](https://pypi.python.org/pypi/nose-exclude) plugin specifically for the task:
> nose-exclude is a Nose plugin that allows you to easily specify
> directories to be excluded from testing.
Among other features, it introduces a new command-line argument called `exclude-dir`:
```
nosetests --p... |
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 34: ordinal not in range(128) | 24,264,892 | 8 | 2014-06-17T13:17:08Z | 24,265,848 | 23 | 2014-06-17T14:00:53Z | [
"python",
"python-2.7",
"pyscripter",
"stackexchange-api"
] | I have been working on a program to retrieve questions from stack overflow. Till yesterday the program was working fine, but since today I'm getting the error
```
"Message File Name Line Position
Traceback
<module> C:\Users\DPT\Desktop\questions.py 13
UnicodeEncodeError: 'ascii' c... | `q.title` is a Unicode string. When writing that to a file, you need to encode it first, preferably a fully Unicode-capable encoding such as `UTF-8` (if you don't, Python will default to using the `ASCII` codec which doesn't support any character codepoint above `127`).
```
question.write(q.title.encode("utf-8"))
```
... |
Dividing a string into a list of smaller strings of certain length | 24,267,747 | 4 | 2014-06-17T15:27:02Z | 24,267,838 | 8 | 2014-06-17T15:31:44Z | [
"python",
"string",
"python-2.7"
] | If
i have this string:
```
"0110100001100101011011000110110001101111"
```
How can I divide it at every eighth character into smaller strings, and put it into a list, so that it looks like this?:
```
['01101000','01100101','01101100','01101100','01101111']
```
So far, I can't figure out how this would be possible.
... | ```
>>> mystr = "0110100001100101011011000110110001101111"
>>> [mystr[i:i+8] for i in range(0, len(mystr), 8)]
['01101000', '01100101', '01101100', '01101100', '01101111']
```
The solution uses a so called list comprehension ([this](http://www.pythonforbeginners.com/basics/list-comprehensions-in-python) seems to be a ... |
Python delimited line split problems | 24,267,912 | 9 | 2014-06-17T15:35:48Z | 24,268,146 | 7 | 2014-06-17T15:47:55Z | [
"python",
"regex",
"csv",
"split",
"pyparsing"
] | I'm struggling to split text rows, based on variable delimiter, and preserve empty fields and quoted data.
Examples:
```
1,"2",three,'four, 4',,"6\tsix"
```
or as tab-delimited vesion
```
1\t"2"\tthree\t'four, 4'\t\t"6\tsix"
```
Should both result in:
```
['1', '"2"', 'three', 'four, 4', '', "6\tsix"]
```
So far... | This works for me:
```
import pyparsing as pyp
pyp.delimitedList(pyp.quotedString | pyp.SkipTo(',' | pyp.LineEnd()), ',') \
.parseWithTabs().parseString(s)
```
Gives
```
['1', '"2"', 'three', "'four, 4'", '', '"6\tsix"']
```
Avoid creating Words with whitespace characters, or all printable characters. Pyparsin... |
What are the differences between slices and partitions of RDDs? | 24,269,495 | 11 | 2014-06-17T17:01:05Z | 24,311,863 | 22 | 2014-06-19T16:35:50Z | [
"python",
"apache-spark"
] | I am using Spark's Python API and running Spark 0.8.
I am storing a large RDD of floating point vectors and I need to perform calculations of one vector against the entire set.
Is there any difference between slices and partitions in an RDD?
When I create the RDD, I pass it 100 as a parameter which causes it to stor... | I believe `slices` and `partitions` are the same thing in Apache Spark.
However, there is a subtle but potentially significant difference between the two pieces of code you posted.
This code will *attempt* to load `demo.txt` directly into 100 partitions using 100 concurrent tasks:
```
rdd = sc.textFile('demo.txt', 1... |
Is PythonQt deprecated? | 24,271,647 | 6 | 2014-06-17T19:14:29Z | 28,339,588 | 7 | 2015-02-05T08:45:21Z | [
"python",
"c++",
"qt"
] | I have a C++ application that I'm compiling with Visual Studio 2010 that needs to be able to call a couple python scripts and read their output, but I can't count on Python being installed on the computer. [PythonQt](http://pythonqt.sourceforge.net/) seems to be the favored simple option, but [every](http://stackoverfl... | PythonQt is under active development, PythonQt 3.0 with Qt 5 and Python 3 support has just been released. Have a look at the [PythonQt project page at Sourceforge](http://sourceforge.net/projects/pythonqt/). |
Get first element of Series without have information on index | 24,273,130 | 6 | 2014-06-17T20:55:43Z | 24,273,597 | 7 | 2014-06-17T21:27:45Z | [
"python",
"pandas"
] | Is that any way that I can get first element of Seires without have information on index.
For example,We have a Series
```
import pandas as pd
key='MCS096'
SUBJECTS=pd.DataFrame({'ID':Series([146],index=[145]),\
'study':Series(['MCS'],index=[145]),\
'center':Series(['... | Use iloc to access by position (rather than label):
```
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series ... |
Placeholder text not showing (pyside/pyqt) | 24,274,318 | 3 | 2014-06-17T22:27:29Z | 24,274,841 | 7 | 2014-06-17T23:22:05Z | [
"python",
"qt",
"user-interface",
"pyqt",
"pyside"
] | Learning PySide, I'm tweaking a text edit widget (QLineEdit) and trying to set the placeholder text using setPlaceHolderText as in the code snippet below (which I invoke from `main`). Unfortunately, it is not working as I expected. The code runs, but the text box is blank, does not show the placeholder text. I am in Wi... | As your widget only contains only one component (the `QLineEdit`), that component will always grab the focus initially. The placeholder text is [only shown](http://qt-project.org/doc/qt-4.8/qlineedit.html#placeholderText-prop) if the edit is empty and *does not* have the focus\*.
A simple solution would be to focus a ... |
Python String Format Explanation | 24,281,927 | 4 | 2014-06-18T09:29:38Z | 24,281,967 | 9 | 2014-06-18T09:31:32Z | [
"python",
"string-formatting"
] | I saw this in a code,
```
print('Job: {!r}, {!s}'.format(5,3))
```
and the answer is
```
Job: 5, 3
```
how does `{!r}` evaluate? Does it have any special meaning there? | `!r` calls [`repr()`](https://docs.python.org/3/library/functions.html#repr) on the value before interpolating.
For integers, the `str()`, default `format()` and `repr()` output doesn't differ. For other types, such as strings, the difference is more visible:
```
>>> print('Repr of a string: {!r}'.format("She said: '... |
Delimiting contiguous regions with values above a certain threshold in Pandas DataFrame | 24,281,936 | 2 | 2014-06-18T09:30:01Z | 24,283,319 | 8 | 2014-06-18T10:33:59Z | [
"python",
"numpy",
"pandas"
] | I have a Pandas Dataframe of indices and values between 0 and 1, something like this:
```
6 0.047033
7 0.047650
8 0.054067
9 0.064767
10 0.073183
11 0.077950
```
I would like to retrieve tuples of **the start and end points of regions of more than 5 consecutive values that are all over a certain threshold (... | You can find the first and last element of each consecutive region by looking at the series and 1-row shifted values, and then filter the pairs which are adequately apart from each other:
```
# tag rows based on the threshold
df['tag'] = df['values'] > .5
# first row is a True preceded by a False
fst = df.index[df['t... |
Python: Why isn't "next()" called "__next__()" | 24,282,368 | 3 | 2014-06-18T09:49:43Z | 24,282,464 | 8 | 2014-06-18T09:53:45Z | [
"python",
"naming-conventions"
] | I'm using Python 2.7.
By convention, builtin methods like `__iter__`, `__init__`, `__str__`, etc. have the double underscore to identify them as such. Why doesn't the `next()` function have this?
It features alongside the other built-in functions here: <https://docs.python.org/2/library/functions.html> and this doesn... | The built-in function doesn't have `__` because none of the built-ins do. You're confusing built-ins (like `str`) with special methods (like `__str__`).
Now the special method called by the built-in `next` is also called `next` in Python 2.7, but that naming was recognized as an accident and changed to `__next__` in P... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.