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 test if an object is a pandas datetime index? | 21,030,174 | 4 | 2014-01-09T20:11:44Z | 21,031,788 | 9 | 2014-01-09T21:41:34Z | [
"python",
"datetime",
"indexing",
"pandas"
] | If I use `type` on a `DataFrame` which I know has a datetime index, I get:
```
In [17]: type(df.index)
Out[17]: pandas.tseries.index.DatetimeIndex
```
but when I test it, I get:
```
In [18]: type(df.index) == 'pandas.tseries.index.DatetimeIndex'
Out[18]: False
```
I know I assumed the type of type is a string, but ... | You can use [isinstance](http://docs.python.org/2/library/functions.html#isinstance) of the DatetimeIndex class:
```
In [11]: dates = pd.date_range('20130101', periods=6)
In [12]: dates
Out[12]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01 00:00:00, ..., 2013-01-06 00:00:00]
Length: 6, Freq: D, Timezone:... |
how to normalize array numpy? | 21,030,391 | 41 | 2014-01-09T20:25:03Z | 21,031,303 | 27 | 2014-01-09T21:15:33Z | [
"python",
"numpy",
"scikit-learn"
] | I would like to have a norm 1 numpy array.
I am looking for an equivalent version of this function
```
def normalize(v):
norm=np.linalg.norm(v)
if norm==0:
return v
return v/norm
```
Is there something like that in skearn or numpy?
This function works in situation where v is the 0 vector. | If you're using scikit-learn you can use [`sklearn.preprocessing.normalize`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.normalize.html#sklearn.preprocessing.normalize):
```
import numpy as np
from sklearn.preprocessing import normalize
x = np.random.rand(1000)*10
norm1 = x / np.linalg.norm... |
how to normalize array numpy? | 21,030,391 | 41 | 2014-01-09T20:25:03Z | 21,032,099 | 14 | 2014-01-09T21:59:18Z | [
"python",
"numpy",
"scikit-learn"
] | I would like to have a norm 1 numpy array.
I am looking for an equivalent version of this function
```
def normalize(v):
norm=np.linalg.norm(v)
if norm==0:
return v
return v/norm
```
Is there something like that in skearn or numpy?
This function works in situation where v is the 0 vector. | I would agree that it were nice if such a function was part of the included batteries. But it isn't, as far as I know. Here is a version for arbitrary axes, and giving optimal performance.
```
import numpy as np
def normalized(a, axis=-1, order=2):
l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
l2[l2==0] ... |
Python and "arbitrary precision integers" | 21,031,093 | 8 | 2014-01-09T21:04:49Z | 21,031,196 | 14 | 2014-01-09T21:10:12Z | [
"python",
"arbitrary-precision"
] | Python is supposed to have "arbitrary precision integers," according to the answer in [Python integer ranges](http://stackoverflow.com/a/4581847/3113536). But this result is plainly *not* arbitrary precision:
```
$ python -c 'print("%d" % (999999999999999999999999/3))'
333333333333333327740928
```
According to [PEP 2... | Actually in python3 whenever you divide ints you get float as a result. There is a `//` operator that does integer division:
```
>>> 999999999999999999999999/3
3.333333333333333e+23
>>> 999999999999999999999999//3
333333333333333333333333
>>> type(999999999999999999999999/3)
<class 'float'>
>>> type(9999999999... |
Format number number with specific mask regex python | 21,031,668 | 5 | 2014-01-09T21:35:19Z | 21,031,811 | 8 | 2014-01-09T21:42:49Z | [
"python",
"regex",
"format",
"string-formatting",
"mask"
] | I need to format a number with a specifc mask: **9.9.9.9.99.999**, depending on the length of number string.
For example:
```
- 123456789 => 1.2.3.4.56.789
- 123456 => 1.2.3.4.56
- 1234 => 1.2.3.4
- 123 => 1.2.3
- 12 => 1.2
```
It will not occur a number string with 7 or 8 digits in the input.
... | You can use this pattern:
```
(?:(?<=^\d)|(?<=^\d{2})|(?<=^\d{3})|(?<=^\d{4})|(?<=^\d{6}))(?=\d)
```
with `.` as replacement.
example:
```
re.sub(r'(?:(?<=^\d)|(?<=^\d{2})|(?<=^\d{3})|(?<=^\d{4})|(?<=^\d{6}))(?=\d)', '.', yourstr)
``` |
Deleting multiple indexes from a list at once - python | 21,032,034 | 3 | 2014-01-09T21:55:38Z | 21,032,057 | 9 | 2014-01-09T21:57:12Z | [
"python",
"list",
"python-3.x",
"pop"
] | My problem is I have a list
eg.
```
lst = [2, 5, 7, 12, 13]
lst.pop(3) #12
lst.pop(4) #13
```
Because lst[3] has been removed lst[4] is no longer there (out of range). This gives me an error. Now I know you could say change your code to this:...
```
lst.pop(4) #13
lst.pop(3) #12
```
...and it ill fix the error, b... | You can use a list comprehension to rebuild the list:
```
indices = {3, 4}
newlist = [v for i, v in enumerate(oldlist) if i not in indices]
```
I used a set for the indices here, as set membership testing is faster than with a list.
Note that a delete (best done with `del lst[index]`) partially rebuilds the list as ... |
Python Pandas Histogram Log Scale | 21,033,720 | 13 | 2014-01-09T23:58:04Z | 21,033,789 | 20 | 2014-01-10T00:05:26Z | [
"python",
"pandas"
] | I'm making a fairly simple histogram in with pandas using
`results.val1.hist(bins=120)`
which works fine, but I really want to have a log scale on the y axis, which I normally (probably incorrectly) do like this:
```
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
plt.plot(np.random.rand(100))
ax.set_ysca... | Hard to diagnose without any data. The following works for me:
```
import numpy as np
import matplotlib.pyplot as plt
import pandas
series = pandas.Series(np.random.normal(size=2000))
fig, ax = plt.subplots()
series.hist(ax=ax, bins=100, bottom=0.1)
ax.set_yscale('log')
```
`
which works fine, but I really want to have a log scale on the y axis, which I normally (probably incorrectly) do like this:
```
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
plt.plot(np.random.rand(100))
ax.set_ysca... | I'd recommend using the `log=True` parameter in the pyplot hist function:
```
import matplotlib.pyplot as plt
plt.hist(df['column_name'], log=True)
``` |
Can I just stop using datetime.date entirely? | 21,034,204 | 7 | 2014-01-10T00:42:36Z | 21,034,313 | 12 | 2014-01-10T00:52:39Z | [
"python",
"date",
"datetime"
] | In Python, it's my impression that `datetime.date` is basically just a subset of `datetime.datetime`, with fewer features and slightly less overhead. I'd like to never use `datetime.date` again for the following reasons:
* No more conversions between the two types!
* `datetime.date` objects are always timezone-unaware... | They represent different things.
A `datetime` is a specific point in time.
A `date` is an *interval* in time. It's not 00:00:00 on that day, it's the *entire day*.
That's why you can't directly convert between them. And that's why you cannot use `datetime` as a substitute for `date`.
(The fact that the same `timede... |
Can I just stop using datetime.date entirely? | 21,034,204 | 7 | 2014-01-10T00:42:36Z | 21,034,728 | 9 | 2014-01-10T01:39:57Z | [
"python",
"date",
"datetime"
] | In Python, it's my impression that `datetime.date` is basically just a subset of `datetime.datetime`, with fewer features and slightly less overhead. I'd like to never use `datetime.date` again for the following reasons:
* No more conversions between the two types!
* `datetime.date` objects are always timezone-unaware... | This is the precise relationship:
```
>>> import datetime
>>> issubclass(datetime.datetime, datetime.date)
True
```
If you don't want to use `date`, simply don't. There are many applications in which the "small amount of extra memory and storage involved" for a `datetime` is a significant burden, especially when a ma... |
How to load/edit/run/save text files (.py) into an IPython notebook cell? | 21,034,373 | 80 | 2014-01-10T01:00:01Z | 21,034,906 | 108 | 2014-01-10T02:00:51Z | [
"python",
"ipython",
"ipython-notebook",
"jupyter"
] | I've recently moved over to using IPython notebooks as part of my workflow. However, I've not been successful in finding a way to import .py files into the individual cells of an open IPython notebook so that they can edited, run and then saved. Can this be done?
I've found [this](http://ipython.org/ipython-doc/stable... | A text file can be loaded in a notebook cell with the magic command `%load`.
If you execute a cell containing:
```
%load filename.py
```
the content of `filename.py` will be loaded in the next cell. You can edit and execute it as usual.
To save the cell content back into a file add the cell-magic `%%writefile filen... |
How to load/edit/run/save text files (.py) into an IPython notebook cell? | 21,034,373 | 80 | 2014-01-10T01:00:01Z | 30,250,285 | 23 | 2015-05-15T01:52:41Z | [
"python",
"ipython",
"ipython-notebook",
"jupyter"
] | I've recently moved over to using IPython notebooks as part of my workflow. However, I've not been successful in finding a way to import .py files into the individual cells of an open IPython notebook so that they can edited, run and then saved. Can this be done?
I've found [this](http://ipython.org/ipython-doc/stable... | ## write/save
`%%writefile myfile.py`
* write/save cell contents into myfile.py (use `-a` to append). Another alias: `%%file myfile.py`
## run
`%run myfile.py`
* run myfile.py and output results in the current cell
## load/import
`%load myfile.py`
* load "import" myfile.py into the current cell
### for more ma... |
How can I generate more colors on pie chart matplotlib | 21,034,830 | 3 | 2014-01-10T01:52:34Z | 21,034,988 | 12 | 2014-01-10T02:07:29Z | [
"python",
"matplotlib",
"pie-chart"
] | I am having more then 40 items to show in my chart.
I have only 10 colours that repeatedly are shown on the chart. How can I generate more colors.
```
plt.pie(f,labels=labels,autopct='%1.1f%%', startangle=90,shadow=True)
```
I should add "color=colors" where colors is generated infinitely ? | You need `colors` argument, beside that you can use some color maps from `cm`.
```
>>> import matplotlib.pyplot as plt
>>> from matplotlib import cm
>>> a=np.random.random(40)
>>> cs=cm.Set1(np.arange(40)/40.)
>>> f=plt.figure()
>>> ax=f.add_subplot(111, aspect='equal')
>>> p=plt.pie(a, colors=cs)
>>> plt.show()
```
... |
Python read JSON file and modify | 21,035,762 | 13 | 2014-01-10T03:34:57Z | 21,035,861 | 20 | 2014-01-10T03:44:30Z | [
"python",
"json",
"file-io"
] | Hi I am trying to take the data from a json file and insert and id then perform POST REST.
my file data.json has:
```
{
'name':'myname'
}
```
and I would like to add an id so that the json data looks like:
```
{
'id': 134,
'name': 'myname'
}
```
So I tried:
```
import json
f = open("data.json","r")... | Set item using `data['id'] = ...`.
```
import json
with open('data.json', 'r+') as f:
data = json.load(f)
data['id'] = 134 # <--- add `id` value.
f.seek(0) # <--- should reset file position to the beginning.
json.dump(data, f, indent=4)
``` |
DateTimeField received a naive datetime | 21,038,881 | 11 | 2014-01-10T07:57:02Z | 21,038,922 | 16 | 2014-01-10T08:00:07Z | [
"python",
"mysql",
"django",
"datetime",
"django-timezone"
] | I have model with **DateTimeField** column.
I'm try to insert row with database **current\_time** value directly into table by sql query.
My sql query for MySQL database like:
```
INSERT INTO MyTable (..., my_datetime, ...) VALUES (..., current_time, ...)
```
And get:
> RuntimeWarning: DateTimeField ModelName.fiel... | Use [`django.utils.timezone.now`](https://docs.djangoproject.com/en/1.6/ref/utils/#django.utils.timezone.now) instead of [`datetime.datetime.now`](http://docs.python.org/2/library/datetime.html#datetime.datetime.now).
```
from django.utils import timezone
current_time = timezone.now()
``` |
DateTimeField received a naive datetime | 21,038,881 | 11 | 2014-01-10T07:57:02Z | 21,043,638 | 25 | 2014-01-10T11:50:58Z | [
"python",
"mysql",
"django",
"datetime",
"django-timezone"
] | I have model with **DateTimeField** column.
I'm try to insert row with database **current\_time** value directly into table by sql query.
My sql query for MySQL database like:
```
INSERT INTO MyTable (..., my_datetime, ...) VALUES (..., current_time, ...)
```
And get:
> RuntimeWarning: DateTimeField ModelName.fiel... | Further to falsetru's answer, if the datetime has already been created you can convert it to timezone aware:
```
from django.utils import timezone
my_datetime = timezone.make_aware(my_datetime, timezone.get_current_timezone())
``` |
What does "table" in the string.translate function mean? | 21,038,891 | 12 | 2014-01-10T07:57:44Z | 21,038,977 | 11 | 2014-01-10T08:04:19Z | [
"python",
"string",
"python-2.7"
] | Going through the [`string.translate`](http://docs.python.org/2/library/string.html#string.translate) function which says:
> Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character v... | It depends on Python version you are using.
In Python 2.x. The table is 256-characters string. It can be created using [`string.maketrans`](http://docs.python.org/2/library/string.html#string.maketrans):
```
>>> import string
>>> tbl = string.maketrans('ac', 'dx')
>>> "abcabc".translate(tbl)
'dbxdbx'
```
In Python 3... |
Model has either not been installed or is abstract | 21,044,885 | 4 | 2014-01-10T12:52:40Z | 21,045,255 | 27 | 2014-01-10T13:12:01Z | [
"python",
"django-models",
"foreign-keys"
] | When I try to migrate my code I get this error.
Here are my code and classes:
```
from django.db import models
from core.models import Event
class TicketType(models.Model):
name = models.CharField(max_length=45)
price = models.DecimalField(max_length=2, decimal_places=2, max_digits=2)
type = models.CharFi... | You're unnecessarily confusing yourself by having these in separate files within the same app.
But your issue is caused by the way you're referenced the target model. You don't use the full module path to the model: you just use `'app_name.ModelName'`. So in your case it should be:
```
ticket_type=models.ForeignKey('... |
Model has either not been installed or is abstract | 21,044,885 | 4 | 2014-01-10T12:52:40Z | 22,536,134 | 7 | 2014-03-20T14:32:42Z | [
"python",
"django-models",
"foreign-keys"
] | When I try to migrate my code I get this error.
Here are my code and classes:
```
from django.db import models
from core.models import Event
class TicketType(models.Model):
name = models.CharField(max_length=45)
price = models.DecimalField(max_length=2, decimal_places=2, max_digits=2)
type = models.CharFi... | Another issue can be when using multiple models in separate files missing statement like:
```
class Meta:
app_label = 'core_backend'
``` |
Why is Python's weekday() different from tm_wday in C? | 21,045,569 | 8 | 2014-01-10T13:27:56Z | 21,045,622 | 8 | 2014-01-10T13:30:13Z | [
"python",
"c",
"datetime"
] | Python documentation defines `datetime.weekday()` as [an integer, where Monday is 0 and Sunday is 6](http://docs.python.org/2/library/datetime.html#datetime.date.weekday), while C's `tm.tm_wday` is defined as [days since Sunday](http://www.cplusplus.com/reference/ctime/tm/). Therefore `tm_wday` is `(datetime.weekday() ... | This was an explicit decision by Guido van Rossum, when he first created the `time` module for Python version 0.9.9; the [original commit](http://hg.python.org/cpython/diff/6ee380349c84/Modules/timemodule.c) doesn't explain *why* he made this choice, but using 0 meaning Monday has been part of Python from the very mome... |
python mocking raw input in unittests | 21,046,717 | 7 | 2014-01-10T14:23:46Z | 21,047,132 | 10 | 2014-01-10T14:42:07Z | [
"python",
"unit-testing",
"mocking"
] | Suppose I have this python code:
```
def answer():
ans = raw_input('enter yes or no')
if ans == 'yes':
print 'you entered yes'
if ans == 'no':
print 'you entered no'
```
How do I write a unittest for this ? I know i have to use 'Mock' but I don't understand how. Can anyone make some simple... | You can't patch input but you can wrap it to use mock.patch(). Here is a solution:
```
from unittest.mock import patch
from unittest import TestCase
def get_input(text):
return input(text)
def answer():
ans = get_input('enter yes or no')
if ans == 'yes':
return 'you entered yes'
if ans == '... |
python mocking raw input in unittests | 21,046,717 | 7 | 2014-01-10T14:23:46Z | 25,275,926 | 8 | 2014-08-12T23:51:10Z | [
"python",
"unit-testing",
"mocking"
] | Suppose I have this python code:
```
def answer():
ans = raw_input('enter yes or no')
if ans == 'yes':
print 'you entered yes'
if ans == 'no':
print 'you entered no'
```
How do I write a unittest for this ? I know i have to use 'Mock' but I don't understand how. Can anyone make some simple... | Okay, first off, I feel it's necessary to point out that in the original code in question, there are actually two things that need to be tackled:
1. `raw_input` (an input side effect) needs to be mocked.
2. `print` (an output side effect) needs to be checked.
In an ideal function for unit testing, there would be no s... |
Turn if-elseif statements into dictionary | 21,047,024 | 2 | 2014-01-10T14:37:33Z | 21,047,128 | 8 | 2014-01-10T14:42:02Z | [
"python",
"design-patterns",
"dictionary",
"switch-statement"
] | I have the following code for making a RESTful call to a server:
```
def request(self, request, account_id, user):
if request is 'get_id':
#Get user from id
result = requests.get(api_root + "/accounts/" + account_id + "/users/" + user, headers=self.headers)
elif request is 'get_username':
... | Using a `dict` to replace `if: elif:` loops is certainly Pythonic, but note that in your example you are *calling* `requests.get` etc for every case you store in the dictionary, i.e. the dictionary values are the results of those calls.
An alternative would be to store function and arguments separately in the dictiona... |
How does swapping of members in the python tuples (a,b)=(b,a) work internally? | 21,047,524 | 10 | 2014-01-10T15:01:36Z | 21,047,622 | 40 | 2014-01-10T15:05:47Z | [
"python",
"tuples",
"python-internals",
"iterable-unpacking"
] | ```
In [55]: a = 5
In [56]: b = 6
In [57]: (a, b) = (b, a)
In [58]: a
Out[58]: 6
In [59]: b
Out[59]: 5
```
How does this swapping of values of a and b work internally? Its definitely not using a temp variable. | Python separates the right-hand side expression from the left-hand side assignment. First the right-hand side is evaluated, and the result is stored on the stack, and then the left-hand side names are assigned using opcodes that take values *from* the stack again.
For tuple assignments with 2 or 3 items, Python just u... |
Python Map() reverse | 21,047,921 | 3 | 2014-01-10T15:19:20Z | 21,047,949 | 12 | 2014-01-10T15:20:58Z | [
"python"
] | Is there a function that takes a list of functions and an input and outputs a list of the functions operation on the input?
So like `map`, but backwards:
```
>>>map(lambda x: 2*x,[1,2,3,4,5,6,7,8,9])
[2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>reverseMap([lambda x: x**2,lambda x: x**3],3)
[9,27]
``` | You can in fact use a `map` to do this:
```
>>> map(lambda f: f(3), [lambda x: x**2,lambda x: x**3])
[9, 27]
```
Use the list of functions you want to apply as the iterable, and then apply each of them to your input (in this case 3). |
Django 1.6 - templates for password change/reset | 21,048,268 | 5 | 2014-01-10T15:35:17Z | 21,050,827 | 7 | 2014-01-10T17:39:01Z | [
"python",
"django"
] | I want to use django's password change/reset views so for example for the view
```
django.contrib.auth.views.password_change
```
I need create a template named
```
registration/password_change_form.html
```
the problem is that even though I have this template implemented in my project, django still shows the passwo... | I think because your app is under `django.contribute.admin` in the `INSTALLED_APP`. |
python: Convert a for loop into a recursion function | 21,049,724 | 2 | 2014-01-10T16:40:29Z | 21,049,837 | 7 | 2014-01-10T16:46:48Z | [
"python",
"for-loop",
"recursion"
] | First of all, I'm still a newb to python so please take it easy on me.
I've done my research and I have a basic understanding of how to write a recursive function, but I'm totally confused at the task ahead of me.
I would really like some tips and pointers so I can do this myself to really understand.
Here's the tas... | I would approach this as follows:
```
def recursive(input, output=None):
if output is None:
output = {} # container to store results
if 'children' in input:
# do whatever, add things to output
recursive(input['children'], output)
return output
```
This way, the `output` dictionary ... |
sklearn GridSearchCV with Pipeline | 21,050,110 | 8 | 2014-01-10T16:59:30Z | 21,061,500 | 15 | 2014-01-11T11:07:16Z | [
"python",
"scikit-learn"
] | I'm new to `sklearn`'s `Pipeline` and `GridSearchCV` features. I am trying to build a pipeline which first does RandomizedPCA on my training data and then fits a ridge regression model. Here is my code:
```
pca = RandomizedPCA(1000, whiten=True)
rgn = Ridge()
pca_ridge = Pipeline([('pca', pca),
... | Those scores are negative MSE scores, i.e. negate them and you get the MSE. The thing is that `GridSearchCV`, by convention, always tries to *maximize* its score so loss functions like MSE have to be negated. |
Flask 301 Response | 21,050,320 | 13 | 2014-01-10T17:12:05Z | 21,050,582 | 26 | 2014-01-10T17:25:54Z | [
"python",
"nginx",
"flask",
"varnish",
"uwsgi"
] | My flask app is doing a `301` redirect for one of the urls.
The traceback in New Relic is:
```
Traceback (most recent call last):
File "/var/www/app/env/local/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/var/www/app/env/local/lib/python2.7/... | The traceback shows that it was the route matching that raised a redirect; *usually* (e.g. unless you added explicit redirect routes), that means the client tried to access a *branch* URL (one that ends with a *trailing slash*), but the requested URL did not include the last slash. The client is simply being redirected... |
Pandas: Impute NaN's | 21,050,426 | 2 | 2014-01-10T17:17:22Z | 21,050,654 | 11 | 2014-01-10T17:29:34Z | [
"python",
"pandas",
null,
"dataframe",
"mean"
] | I have an incomplete dataframe, `incomplete_df`, as below. I want to impute the missing `amount`s with the average `amount` of the corresponding `id`. If the average for that specific `id` is itself NaN (see `id=4`), I want to use the overall average.
Below are the example data and my highly inefficient solution:
```... | Disclaimer: I'm not really interested in the fastest solution but the most pandorable.
Here, I think that would be something like:
```
>>> df["amount"].fillna(df.groupby("id")["amount"].transform("mean"), inplace=True)
>>> df["amount"].fillna(df["amount"].mean(), inplace=True)
```
which produces
```
>>> df
id ... |
Scikit-learn: Parallelize stochastic gradient descent | 21,052,050 | 3 | 2014-01-10T18:47:31Z | 21,055,202 | 8 | 2014-01-10T21:59:31Z | [
"python",
"parallel-processing",
"machine-learning",
"mpi",
"scikit-learn"
] | I have a fairly large training matrix (over 1 billion rows, two features per row). There are two classes (0 and 1).
This is too large for a single machine, but fortunately I have about 200 MPI hosts at my disposal. Each is a modest dual-core workstation.
Feature generation is already successfully distributed.
The ans... | Training a linear model on a dataset with 1e9 samples and 2 features is very likely to underfit or waste CPU / IO time in case the data is actually linearly separable. Don't waste time thinking about parallelizing such a problem with a linear model:
* either switch to a more complex class of models (e.g. train random ... |
Sklearn kNN usage with a user defined metric | 21,052,509 | 7 | 2014-01-10T19:12:53Z | 21,053,112 | 11 | 2014-01-10T19:45:19Z | [
"python",
"knn"
] | Currently I'm doing a project which may require using a kNN algorithm to find the top k nearest neighbors for a given point, say P. im using python, sklearn package to do the job, but our predefined metric is not one of those default metrics. so I have to use the user defined metric, from the documents of sklearn, whic... | You pass a metric as `metric` param, and additional metric arguments as keyword paramethers to NN constructor:
```
>>> def mydist(x, y):
... return np.sum((x-y)**2)
...
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> nbrs = NearestNeighbors(n_neighbors=4, algorithm='ball_tree',
... ... |
What does "del" do exactly? | 21,053,380 | 14 | 2014-01-10T20:00:33Z | 21,053,433 | 20 | 2014-01-10T20:03:43Z | [
"python",
"memory",
"python-internals"
] | Here is my code:
```
from memory_profiler import profile
@profile
def mess_with_memory():
huge_list = range(20000000)
del huge_list
print "why this kolaveri di?"
```
This is what the output is, when I ran it from interpreter:
# Line # Mem usage Increment Line Contents
```
3 7.0 MiB 0.0 MiB ... | Python is a garbage-collected language. If a value isn't "reachable" from your code anymore, it will eventually get deleted.
The `del` statement, as you saw, removes the binding of your variable. Variables aren't values, they're just names for values.
If that variable was the only reference to the value anywhere, the... |
Python pip unable to locate pyodbc | 21,054,656 | 24 | 2014-01-10T21:23:14Z | 21,055,195 | 40 | 2014-01-10T21:59:01Z | [
"python",
"pip",
"pyodbc"
] | Using virtualenv and just trying to install pyodbc. All resources I can find claim this should be extremely straightforward. After all the basic installs of MySQL, etc., just do:
```
pip install pyodbc
```
However, I am seeing a very strange error. It has nothing (as far as I can tell) to do with missing libraries, a... | Running `pip install --allow-external pyodbc --allow-unverified pyodbc pyodbc` will work if the PyPI directory structure is correct.
Based on the pip.log output when I originally posted this answer, I think that package's website directory structure was broken. You can always work around this type of problem by specif... |
Python pip unable to locate pyodbc | 21,054,656 | 24 | 2014-01-10T21:23:14Z | 24,377,180 | 9 | 2014-06-24T01:50:41Z | [
"python",
"pip",
"pyodbc"
] | Using virtualenv and just trying to install pyodbc. All resources I can find claim this should be extremely straightforward. After all the basic installs of MySQL, etc., just do:
```
pip install pyodbc
```
However, I am seeing a very strange error. It has nothing (as far as I can tell) to do with missing libraries, a... | I just tried installing pyodbc as well and hit the same wall. I think the problem you and I both hit is that --allow-external consumes the next argument as well. So you actually need to write:
```
sudo pip install --allow-external pyodbc pyodbc
```
I then hit another error about unverified sources so that command tha... |
Reversal of string.contains In python, pandas | 21,055,068 | 15 | 2014-01-10T21:51:10Z | 21,055,176 | 17 | 2014-01-10T21:57:30Z | [
"python",
"string",
"python-2.7",
"csv",
"pandas"
] | I have something like this in my code:
`df2 = df[df['A'].str.contains("Hello|World")]`
However, I want all the rows that *don't* contain either of Hello or World. How do I most efficiently reverse this? | You can use the tilde `~` to flip the bool values:
```
>>> df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]})
>>> df.A.str.contains("Hello|World")
0 True
1 False
2 True
3 False
Name: A, dtype: bool
>>> ~df.A.str.contains("Hello|World")
0 False
1 True
2 False
3 True
Name: A, dtype... |
What are the risks of running 'sudo pip'? | 21,055,859 | 26 | 2014-01-10T22:45:27Z | 21,056,000 | 34 | 2014-01-10T22:56:47Z | [
"python",
"security",
"pip",
"sudo"
] | Occasionally I run into [comments or responses](http://stackoverflow.com/a/21047830/656912) that state emphatically that running `pip` under `sudo` is "wrong" or "bad", but there are cases (including the way I have a bunch of tools set up) where it is either much simpler, or even necessary to run it that way.
What are... | When you run `pip` with `sudo`, you run `setup.py` with `sudo`. In other words, you run arbitrary Python code from the Internet as root. If someone puts up a malicious project on PyPI and you install it, you give an attacker root access to your machine. Prior to some recent fixes to `pip` and PyPI, an attacker could al... |
Pip install not functioning on windows 7 Cygwin install | 21,057,931 | 20 | 2014-01-11T02:44:06Z | 21,966,446 | 24 | 2014-02-23T09:27:33Z | [
"python",
"cygwin",
"install",
"pip"
] | I'm having a terrible time of getting pip up and running on Cygwin which I just recently installed on my Windows 7 Computer. I am writing in the hope that anyone out there can tell me what I am doing incorrectly in terms of getting these packages installed correctly.
To start, I followed the instructions on this site:... | There's a bug(?) in 64-bit Cygwin which causes `ctypes.util` to segfault when trying to find *libuuid* (`/usr/bin/cyguuid-1.dll`). The fix is to install *libuuid-devel* from Cygwin setup. I found this from [an issue filed against requests.py](https://github.com/kennethreitz/requests/issues/1547), but it's noted (and wo... |
Iterate over a webelement obtained using selenium | 21,058,099 | 5 | 2014-01-11T03:11:25Z | 21,058,235 | 13 | 2014-01-11T03:34:14Z | [
"python",
"selenium"
] | ```
rows = driver.find_element_by_xpath("//div[@style='display: block;']//table[@style='display: table;']//tr")
```
When I try to iterate over rows It throws an error `TypeError: 'WebElement' object is not iterable`
```
def get_size(e):
for entry in e:
count = count + 1
return count
get_size(rows)
``` | Try this . This should work. use `find_elements_by_xpath`
```
Listlinker = []
Listlinker = driver.find_elements_by_xpath(""//div[@style='display: block;']//table[@style='display: table;']//tr")
for link in Listlinker:
// more code
``` |
How to assert a dict contains another dict without assertDictContainsSubset in python? | 21,058,230 | 11 | 2014-01-11T03:33:40Z | 21,058,312 | 9 | 2014-01-11T03:48:11Z | [
"python",
"python-2.7",
"python-3.x",
"python-unittest"
] | I know `assertDictContainsSubset` can do this in python 2.7, but for some reason it's deprecated in python 3.2. So is there any way to assert a dict contains another one without `assertDictContainsSubset`?
This seems not good:
```
for item in dic2:
self.assertIn(item, dic)
```
any other good way? Thanks | ```
>>> d1 = dict(a=1, b=2, c=3, d=4)
>>> d2 = dict(a=1, b=2)
>>> set(d2.items()).issubset( set(d1.items()) )
True
```
And the other way around:
```
>>> set(d1.items()).issubset( set(d2.items()) )
False
```
*Limitation:* the dictionary values have to be hashable. |
Compute *rolling* maximum drawdown of pandas Series | 21,058,333 | 12 | 2014-01-11T03:52:30Z | 21,059,308 | 12 | 2014-01-11T06:26:15Z | [
"python",
"algorithm",
"numpy",
"pandas"
] | It's pretty easy to write a function that computes the maximum drawdown of a time series. It takes a small bit of thinking to write it in `O(n)` time instead of `O(n^2)` time. But it's not that bad. This will work:
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def max_dd(ser):
max2her... | Here's a numpy version of the rolling maximum drawdown function. `windowed_view` is a wrapper of a one-line function that uses `numpy.lib.stride_tricks.as_strided` to make a memory efficient 2d windowed view of the 1d array (full code below). Once we have this windowed view, the calculation is basically the same as you... |
Python json.loads shows ValueError: Extra data | 21,058,935 | 29 | 2014-01-11T05:36:42Z | 21,058,946 | 38 | 2014-01-11T05:39:19Z | [
"python",
"json"
] | I am getting some data from a JSON file "new.json", and I want to filter some data and store it into a new JSON file. Here is my code:
```
import json
with open('new.json') as infile:
data = json.load(infile)
for item in data:
iden = item.get["id"]
a = item.get["a"]
b = item.get["b"]
c = item.get["... | As you can see in the following example, `json.loads` (and `json.load`) does not decode multiple json object.
```
>>> json.loads('{}')
{}
>>> json.loads('{}{}') # == json.loads(json.dumps({}) + json.dumps({}))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\json\__init_... |
Python json.loads shows ValueError: Extra data | 21,058,935 | 29 | 2014-01-11T05:36:42Z | 29,312,618 | 11 | 2015-03-28T01:27:37Z | [
"python",
"json"
] | I am getting some data from a JSON file "new.json", and I want to filter some data and store it into a new JSON file. Here is my code:
```
import json
with open('new.json') as infile:
data = json.load(infile)
for item in data:
iden = item.get["id"]
a = item.get["a"]
b = item.get["b"]
c = item.get["... | Can I just suggest that you don't have to package all of the tweets into a list and then do `json.dumps`. You can just write to a file as you go, and then load them in with:
```
tweets = []
for line in open('test.txt', 'r'):
tweets.append(json.loads(line))
```
As long as your write one full tweet per write call, ... |
Dynamic inheritance in Python | 21,060,073 | 7 | 2014-01-11T08:08:18Z | 21,060,094 | 20 | 2014-01-11T08:11:27Z | [
"python",
"inheritance"
] | Say I have 2 different implementations of a class
```
class ParentA:
def initialize(self):
pass
def some_event(self):
pass
def order(self, value):
# handle order in some way for Parent A
class ParentB:
def initialize(self):
pass
def some_event(self):
pas... | Simply store the class-object in a variable (in the example below, it is named `base`), and use the variable in the base-class-spec of your `class` statement.
```
def get_my_code(base):
class MyCode(base):
def initialize(self):
...
return MyCode
my_code = get_my_code(ParentA)
``` |
Manipulating browser (window) size using Splinter | 21,061,770 | 3 | 2014-01-11T11:40:37Z | 21,062,539 | 12 | 2014-01-11T13:02:06Z | [
"python",
"selenium",
"browser-automation",
"splinter"
] | I am trying to use the Firefox driver for [Splinter](https://github.com/cobrateam/splinter) to test some responsive design.
Naturally, this requires me to resize the browser window. I can't find anything at all about browser resizing in [the documentation](https://splinter.readthedocs.org/en/latest/).
How can I do th... | Just do this:
```
browser.driver.set_window_size(640, 480)
```
The Splinter API doesn't seem to directly support this - or at least not yet. The generic [API docs](https://splinter.readthedocs.org/en/latest/api/driver-and-element-api.html), as well as the docs for each specific browser's driver, currently make no men... |
How can i read an image from an internet url in python cv2 , scikit image and mahotas? | 21,061,814 | 8 | 2014-01-11T11:45:06Z | 21,062,034 | 11 | 2014-01-11T12:07:59Z | [
"python",
"opencv",
"image-processing",
"scikit-image",
"mahotas"
] | How can i read an image from an internet url in python cv2?
this [stackoverflow answer](http://stackoverflow.com/questions/11253820/python-urllib2-and-opencv)
```
import cv2.cv as cv
import urllib2
from cStringIO import StringIO
import PIL.Image as pil
url="some_url"
img_file = urllib2.urlopen(url)
im = StringIO(img... | since a cv2 image is not a string (save a unicode one, yucc), but a numpy array, - use cv2 and numpy to achieve it:
```
import cv2
import urllib
import numpy as np
req = urllib.urlopen('http://answers.opencv.org/upfiles/logo_2.png')
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr,-1) # ... |
How can i read an image from an internet url in python cv2 , scikit image and mahotas? | 21,061,814 | 8 | 2014-01-11T11:45:06Z | 21,064,193 | 8 | 2014-01-11T15:36:55Z | [
"python",
"opencv",
"image-processing",
"scikit-image",
"mahotas"
] | How can i read an image from an internet url in python cv2?
this [stackoverflow answer](http://stackoverflow.com/questions/11253820/python-urllib2-and-opencv)
```
import cv2.cv as cv
import urllib2
from cStringIO import StringIO
import PIL.Image as pil
url="some_url"
img_file = urllib2.urlopen(url)
im = StringIO(img... | The following reads the image directly into a numpy array:
```
from skimage import io
image = io.imread('https://raw2.github.com/scikit-image/scikit-image.github.com/master/_static/img/logo.png')
``` |
How to reverse string with stride via Python String slicing | 21,061,959 | 4 | 2014-01-11T11:58:57Z | 21,061,987 | 7 | 2014-01-11T12:02:53Z | [
"python",
"string",
"slice"
] | I need to reverse an interleaved string, means i have 2-pairs which shouldt get messed up like this:
```
>>> interleaved = "123456"
```
reversing
```
>>> print interleaved[::-1]
654321
```
but what i actually want is
```
563412
```
is there a string slice operation for this? | For even length strings this should do it:
```
>>> s = "123456"
>>> it = reversed(s)
>>> ''.join(next(it) + x for x in it)
'563412'
```
For odd length strings, you need to prepend the first character separately:
```
>>> s = "7123456"
>>> it = reversed(s)
>>> (s[0] if len(s)%2 else '') + ''.join(next(it) + x for x in... |
Shortest way to get first item of `OrderedDict` in Python 3 | 21,062,781 | 12 | 2014-01-11T13:25:08Z | 21,067,850 | 10 | 2014-01-11T21:04:28Z | [
"python",
"python-3.x"
] | What's the shortest way to get first item of `OrderedDict` in Python 3?
My best:
```
list(ordered_dict.items())[0]
```
Quite long and ugly.
I can think of:
```
next(iter(ordered_dict.items())) # Fixed, thanks Ashwini
```
But it's not very self-describing.
Any better suggestions? | The usual ways to get an element from a *set*, *dict*, *OrderedDict*, consumeable iterator, or any other non-indexable collection are:
```
for value in some_collection:
break
```
and:
```
value = next(iter(some_collection))
```
The latter is nice because the *next()* function lets you specify a default value if... |
TypeError in Python single inheritance with "super" attribute | 21,063,228 | 10 | 2014-01-11T14:06:56Z | 21,063,283 | 11 | 2014-01-11T14:12:14Z | [
"python"
] | I never expected the inheritance of Python **2.7** is so anti-human. Why the following code give me a TypeError?
```
>>> class P:
... def __init__(self, argp):
... self.pstr=argp
...
>>> class C(P):
... def __init__(self, argp, argc):
... super.__init__(self,argp)
... self.cstr=argc
..... | There are two responses possible for your question, according to the version of Python you're using.
## Python 2.x
`super` has to be called like this [(example for the doc)](http://docs.python.org/2/library/functions.html#super):
```
class C(B):
def method(self, arg):
super(C, self).method(arg)
```
In y... |
What do I have to install to resolve Could not find any typelib for GtkSource, Cannot import: GtkSourceView, cannot import name GtkSource | 21,064,163 | 6 | 2014-01-11T15:34:26Z | 21,070,057 | 9 | 2014-01-12T01:05:40Z | [
"python",
"pygtk",
"pygobject",
"meld"
] | I'm trying to apply a patch for meld from <https://bugzilla.gnome.org/show_bug.cgi?id=680569> myself, and am having trouble with this:
```
$ git clone git://git.gnome.org/meld
$ cd meld
$ python setup.py build
$ bin/meld
2014-01-11 16:30:44,736 ERROR root: Could not find any typelib for GtkSource
Cannot import: GtkSo... | To install the library you need, on a Debian/Ubuntu machine:
```
sudo apt-get install gir1.2-gtksource-3.0
```
GtkSourceView is a C library that allows applications to display a text buffer with syntax highlight for code, and a bunch of other goodies.
<https://wiki.gnome.org/Projects/GtkSourceView>
The above packag... |
Aptana Error-pydev: Port not bound (found port -1)? | 21,065,690 | 31 | 2014-01-11T17:46:57Z | 25,971,061 | 20 | 2014-09-22T09:44:38Z | [
"python",
"aptana",
"pydev"
] | I just updated my Aptana Studio3. When I open my python file it says that it can not find `map`, `range` and `filter` and some other methods. but when I run my code, it'll run without any problem. my code completion doesn't work any more. The error for code completion when I use CTRL+SPACE is
```
Port not bound (fo... | It seems that this is solved on PyDev and the problem is you can't upgrade PyDev on Aptana 3.6.0. Version 3.6.1 takes out the integration with PyDev and lets you upgrade PyDev.
So I installed Aptana 3.6.1 through Beta repository and then installed the latest PyDev.
Aptana Beta link to add to "Available Software Sites"... |
Python sort() first element of list | 21,068,315 | 3 | 2014-01-11T21:48:51Z | 21,068,856 | 7 | 2014-01-11T22:44:56Z | [
"python",
"list",
"sorting",
"python-3.3"
] | I have a list that contains non specific amount of elements but every first element of the nested list is an identifier, I would like to use that identifier to sort the list in order
```
list = [['D', 'F', 'E', 'D', 'F', 'D'],['A', 'F', 'E', 'C', 'F', 'E'],['C', 'E', 'E', 'F', 'E', 'E'],['B', 'F', 'E', 'D', 'F', 'F']]... | Python automatically sorts lists of lists by the first element. For example:
```
lol=[[1,2,3],[5,6,7],[0,9,9]]
sorted(lol)
[[0, 9, 9], [1, 2, 3], [5, 6, 7]]
``` |
Parse the JavaScript returned from BeautifulSoup | 21,069,294 | 9 | 2014-01-11T23:35:48Z | 21,069,526 | 7 | 2014-01-12T00:02:15Z | [
"javascript",
"python",
"beautifulsoup",
"html-parsing"
] | I would like to parse the webpage <http://dcsd.nutrislice.com/menu/meadow-view/lunch/> to grab today's lunch menu. (I've built an Adafruit #IoT Thermal Printer and I'd like to automatically print the menu each day.)
I initially approached this using BeautifulSoup but it turns out that most of the data is loaded in Jav... | Something like PhantomJS may be more robust, but here's some basic Python code to extract it the full menu:
```
import json
import re
import urllib2
text = urllib2.urlopen('http://dcsd.nutrislice.com/menu/meadow-view/lunch/').read()
menu = json.loads(re.search(r"bootstrapData\['menuMonthWeeks'\]\s*=\s*(.*);", text).g... |
Alternative to dict comprehension prior to Python 2.7 | 21,069,668 | 21 | 2014-01-12T00:19:30Z | 21,069,676 | 45 | 2014-01-12T00:20:45Z | [
"python",
"dictionary",
"dictionary-comprehension"
] | How can I make the following functionality compatible with versions of Python earlier than Python 2.7?
```
gwfuncs = [reboot, flush_macs, flush_cache, new_gw, revert_gw, send_log]
gw_func_dict = {chr(2**i): func for i, func in enumerate(gwfuncs[:8])}
``` | Use:
```
gw_func_dict = dict((chr(2**i), func) for i, func in enumerate(gwfuncs[:8]))
```
That's the `dict()` function with a generator expression producing `(key, value)` pairs.
Or, to put it generically, a dict comprehension of the form:
```
{key_expr: value_expr for targets in iterable <additional loops or if ex... |
Running django tutorial tests fail - No module named polls.tests | 21,069,880 | 23 | 2014-01-12T00:44:01Z | 22,096,628 | 80 | 2014-02-28T13:33:54Z | [
"python",
"django",
"django-unittest"
] | I'm playing with django 1.6 tutorial but i can't run tests.
My project (name mydjango) and app structure (name is polls) are as shown below in a virtualenv. (.nja files are just created by ninja-ide the ide i'm using)
```
.
âââ __init__.py
âââ manage.py
âââ mydjango
â  âââ __init__.py
âÂ... | I had exactly the same issue with my Django project:
```
$ python manage test polls.tests
```
worked fine whereas the following failed with an import error:
```
$ python manage test polls
$ python manage test
(...)
ImportError: Failed to import test module: mydjango.polls.tests
Traceback (most recent call last):
(..... |
ImportError: No module named virtualenv | 21,070,369 | 8 | 2014-01-12T01:56:00Z | 21,071,358 | 13 | 2014-01-12T04:34:13Z | [
"python",
"django",
"windows-7"
] | I am using Django 1.3.7 and python 2.7.6 on windows7
I got an error when I executing my manage.py in this line of code
```
import shutil, sys, virtualenv, subprocess
```
amd running it, I got this error
```
C:\Django-Proj\>python manage.py update_ve
Traceback (most recent call last):
File "manage.py", line 4, in <... | Install virtualenv using `pip install virtualenv`.
If you have it already installed, try reinstalling it by removing it with `pip uninstall virtualenv` and then reinstalling it.
Good Luck. |
why \b doesn't work in python re module? | 21,071,264 | 8 | 2014-01-12T04:18:40Z | 21,071,269 | 18 | 2014-01-12T04:19:22Z | [
"python",
"regex"
] | It is known that `\b` means word boundary in regular expression. However the following code of `re` module in python doesn't work:
```
>>> p=re.compile('\baaa\b')
>>> p.findall("aaa vvv")
[]
```
I think the returned results of `findall` should be `["aaa"]`, however it didn't find anything. What's the matter? | You need to use a raw string, or else the `\b` is interpreted as a string escape. Use `r'\baaa\b'`. (Alternatively, you can write `'\\b'`, but that is much more awkward for longer regexes.) |
Redirecting stdout and stderr to a PyQt4 QTextEdit from a secondary thread | 21,071,448 | 14 | 2014-01-12T04:52:11Z | 21,071,865 | 13 | 2014-01-12T06:11:27Z | [
"python",
"multithreading",
"thread-safety",
"pyqt",
"stdout"
] | Stack overflow. Once again, I come to you in a time of dire need, teetering precariously on the brink of *insanity*. This question - as may be evident from the title - is an amalgamation of several other questions I have seen answered here.
**I have a PyQt application, and I want to re-route the stdout and stderr stre... | Firstly, +1 for realising how thread-**unsafe** many of the examples on stack overflow are!
The solution is to use a thread-safe object (like a Python `Queue.Queue`) to mediate the transfer of information. I've attached some sample code below which redirects `stdout` to a Python `Queue`. This `Queue` is read by a `QTh... |
Why does from scipy import spatial work, while scipy.spatial doesn't work after import scipy? | 21,071,715 | 7 | 2014-01-12T05:40:57Z | 21,071,752 | 8 | 2014-01-12T05:48:06Z | [
"python",
"scipy"
] | I would like to use `scipy.spatial.distance.cosine` in my code. I can import the `spatial` submodule if I do something like `import scipy.spatial` or `from scipy import spatial`, but if I simply `import scipy` calling `scipy.spatial.distance.cosine(...)` results in the following error: `AttributeError: 'module' object ... | Importing a package does not import submodule automatically. You need to import submodule explicitly.
For example, `import xml` does not import the submodule `xml.dom`
```
>>> import xml
>>> xml.dom
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribu... |
Converting non English words to % separated string in Python | 21,072,881 | 3 | 2014-01-12T08:48:26Z | 21,072,894 | 7 | 2014-01-12T08:50:34Z | [
"python",
"string",
"python-3.x",
"replace"
] | I have a Persian word like this: `word = Ù
ÛâØ¨Ø§Ø´Ø¯`.
If I run this:
```
word.encode(encoding='utf-8')
```
I see this in Python IDLE:
```
b'\xd9\x85\xdb\x8c\xe2\x80\x8c\xd8\xa8\xd8\xa7\xd8\xb4\xd8\xaf'
```
I want to convert the above line to a string that removes `b'` and replaces all `\x` with `%`.
So I want ... | Use [`urllib.parse.quote`](http://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote):
```
>>> import urllib.parse
>>> word = 'Ù
ÛâØ¨Ø§Ø´Ø¯'
>>> urllib.parse.quote(word, encoding='utf-8')
'%D9%85%DB%8C%E2%80%8C%D8%A8%D8%A7%D8%B4%D8%AF'
```
You can omit `encoding='utf-8'` because `utf-8` encoding is use... |
Wait on Arduino auto-reset using pySerial | 21,073,086 | 8 | 2014-01-12T09:21:19Z | 21,082,531 | 8 | 2014-01-13T01:19:40Z | [
"python",
"arduino",
"pyserial"
] | I'm trying to read lines from an Arduino board with a very simple code (for the sake of showcasing the problem) on Linux.
Python code:
```
# arduino.py
import serial
arduino = serial.Serial('/dev/ttyACM0')
with arduino:
while True:
print(arduino.readline())
```
Arduino code:
```
// simpleWrite.ino
long... | The Arduino IDE's monitor toggle's the assigned DTR pin of the port when connected. Where this toggling causes a reset on the Arduino. Noting that the DTR is toggled after the Monitor has opened the Serial port and is ready to receive data. In your case the below example should do the same.
```
Import serial
arduino ... |
How to use while loop inside a function ? | 21,074,086 | 2 | 2014-01-12T11:30:31Z | 21,074,135 | 8 | 2014-01-12T11:35:21Z | [
"python",
"while-loop",
"raw-input"
] | I decide to modify the following while loop and use it inside a function so that the loop can take any value instead of 6.
```
i = 0
numbers = []
while i < 6:
numbers.append(i)
i += 1
```
I created the following script so that I can use the variable(or more specifically argument ) instead of 6 .
```
def numb... | You need to convert `user_limit` to `Int`:
`raw_input()` return value is `str` and the statement is using i which is `int`
```
def numbers(limit):
i = 0
numbers = []
while i < limit:
numbers.append(i)
i = i + 1
print numbers
user_limit = int(raw_input("Give me a limit "))
numbers(use... |
error: Unable to find vcvarsall.bat in installing psycopg2 in windows7 | 21,074,191 | 8 | 2014-01-12T11:40:59Z | 21,074,232 | 16 | 2014-01-12T11:46:53Z | [
"python",
"django",
"postgresql",
"windows-7",
"psycopg2"
] | Im using Windows 7 for developing Django 1.3.7 using PostgreSQL 9.3 as database. on my `settings.py` I set `DATABASE_ENGINE = 'django.db.backends.postgresql_psycopg2'` but when I try to execute `python manage.py syncdb` I got this error:
```
C:\Django-Proj\myproj\myproj>python manage.py syncdb
Traceback (most recent c... | There is the huge list of Unofficial Windows Binaries for Python Extension Packages which are extremely useful for Windows users.
<http://www.lfd.uci.edu/~gohlke/pythonlibs/#psycopg>
Go to the link, download and install it and you are good to go.
Cheers ! |
Django model latest() method | 21,077,865 | 3 | 2014-01-12T17:28:16Z | 21,078,018 | 7 | 2014-01-12T17:42:39Z | [
"python",
"django",
"django-models",
"django-queryset"
] | I am having the following issue (BTW I think I had not had this problem the day before):
```
>>> rule = Rule.objects.get(user=user)
>>> rule.id
1
>>> rule = Rule.objects.get(user=user).latest('id')
AttributeError: 'Rule' object has no attribute 'latest'
```
Why am I getting the error? | The get() function of a model Manager returns an instance of the object itself.
The latest() function you mention belongs to the QuerySet class. Calling .filter(), .all(), .exclude() etc, all return a query set.
What you're likely looking for is to first filter for the specific user, then get the latest result by 'id... |
How do I make HTTP POST requests with grequests | 21,078,888 | 5 | 2014-01-12T18:56:38Z | 21,078,997 | 11 | 2014-01-12T19:08:44Z | [
"python",
"grequests"
] | I tried the following:
```
import grequests
urls = ['http://localhost/test', 'http://localhost/test']
params = {'a':'b', 'c':'d'}
rs = (grequests.post(u, params) for u in urls)
grequests.map(rs)
```
But it says the following:
```
File "search.py", line 6, in <genexpr>
rs = (grequests.post(u, params) for u in urls)... | grequests.post() function takes only one positional argument i.e URL to which you have send that POST request. The rest of the parameters are taken as key word arguments.
So you need to call grequests.post() as:
```
import grequests
urls = ['http://localhost/test', 'http://localhost/test']
params = {'a':'b', 'c':'d... |
Django Mezzanine framework - won't let me embed videos to blog post | 21,079,434 | 8 | 2014-01-12T19:47:08Z | 21,081,842 | 14 | 2014-01-12T23:50:11Z | [
"python",
"django",
"mezzanine"
] | I can't get Mezzanine Framework for Django to accept embedding videos into my blog posts. I tried using the `video` tag of the `rich text editor`, tried editing the `html` code and inserting the `iframe` YouTube provides me, but with no success. Once I hit save, Mezzanine strips the code right out, like it's never been... | It actually needs to be changed in the admin. Log in to your admin, then in the top left hover over 'Site', then click on 'Settings'. Scroll down and you should see a setting called 'Rich text filter level'. Change this setting to low and then save. You should be able to embed your video now. |
How to find pg_config path | 21,079,820 | 33 | 2014-01-12T20:20:43Z | 21,080,707 | 57 | 2014-01-12T21:48:55Z | [
"python",
"django",
"osx",
"postgresql"
] | Complete newbie here, trying to set up Django to work with ProstgreSQL.
I'm using mac osx 10.6.8. I have also installed PostgreSQL 9.3
When I run `pip install psycopg2` in terminal I get the following error
```
Downloading/unpacking psycopg2
Downloading psycopg2-2.5.2.tar.gz (685kB): 685kB downloaded
Running set... | I recommend that you try to use Postgres.app. (<http://postgresapp.com>)
This way you can easily turn Postgres on and off on your Mac.
Once you do, add the path to Postgres to your `.profile` file by appending the following:
```
PATH="/Applications/Postgres.app/Contents/Versions/latest/bin:$PATH"
```
Only after you a... |
How to find pg_config path | 21,079,820 | 33 | 2014-01-12T20:20:43Z | 22,761,898 | 13 | 2014-03-31T12:45:27Z | [
"python",
"django",
"osx",
"postgresql"
] | Complete newbie here, trying to set up Django to work with ProstgreSQL.
I'm using mac osx 10.6.8. I have also installed PostgreSQL 9.3
When I run `pip install psycopg2` in terminal I get the following error
```
Downloading/unpacking psycopg2
Downloading psycopg2-2.5.2.tar.gz (685kB): 685kB downloaded
Running set... | sudo find / -name "pg\_config" -print
The answer is /Library/PostgreSQL/9.1/bin/pg\_config in my configuration (MAC Maverick) |
How to find pg_config path | 21,079,820 | 33 | 2014-01-12T20:20:43Z | 25,357,902 | 20 | 2014-08-18T07:06:22Z | [
"python",
"django",
"osx",
"postgresql"
] | Complete newbie here, trying to set up Django to work with ProstgreSQL.
I'm using mac osx 10.6.8. I have also installed PostgreSQL 9.3
When I run `pip install psycopg2` in terminal I get the following error
```
Downloading/unpacking psycopg2
Downloading psycopg2-2.5.2.tar.gz (685kB): 685kB downloaded
Running set... | Postgres.app was updated recently. Now it stores all the binaries in "Versions" folder
```
PATH="/Applications/Postgres.app/Contents/Versions/9.4/bin:$PATH"
```
Where 9.4 â version of PostgreSQL. |
How to find pg_config path | 21,079,820 | 33 | 2014-01-12T20:20:43Z | 26,764,497 | 10 | 2014-11-05T18:32:22Z | [
"python",
"django",
"osx",
"postgresql"
] | Complete newbie here, trying to set up Django to work with ProstgreSQL.
I'm using mac osx 10.6.8. I have also installed PostgreSQL 9.3
When I run `pip install psycopg2` in terminal I get the following error
```
Downloading/unpacking psycopg2
Downloading psycopg2-2.5.2.tar.gz (685kB): 685kB downloaded
Running set... | Installing homebrew
```
/usr/bin/ruby -e "$(curl -fsSL https://raw.github.com/gist/323731)"
```
And then installing postgresql
```
brew install postgresql
```
gave me this lovely bit of output:
```
checking for pg_config... yes
```
ahhh yeahhhhh |
How to find pg_config path | 21,079,820 | 33 | 2014-01-12T20:20:43Z | 28,228,155 | 7 | 2015-01-30T02:10:49Z | [
"python",
"django",
"osx",
"postgresql"
] | Complete newbie here, trying to set up Django to work with ProstgreSQL.
I'm using mac osx 10.6.8. I have also installed PostgreSQL 9.3
When I run `pip install psycopg2` in terminal I get the following error
```
Downloading/unpacking psycopg2
Downloading psycopg2-2.5.2.tar.gz (685kB): 685kB downloaded
Running set... | To summarize -- PostgreSQL installs its files (including its binary or executable files) in different locations, depending on the version number and the installation method.
Some of the possibilities:
```
/usr/local/bin/
/Library/PostgreSQL/9.2/bin/
/Applications/Postgres93.app/Contents/MacOS/bin/
/Applications/Postg... |
How to find pg_config path | 21,079,820 | 33 | 2014-01-12T20:20:43Z | 35,228,663 | 8 | 2016-02-05T16:13:27Z | [
"python",
"django",
"osx",
"postgresql"
] | Complete newbie here, trying to set up Django to work with ProstgreSQL.
I'm using mac osx 10.6.8. I have also installed PostgreSQL 9.3
When I run `pip install psycopg2` in terminal I get the following error
```
Downloading/unpacking psycopg2
Downloading psycopg2-2.5.2.tar.gz (685kB): 685kB downloaded
Running set... | Once you install the current PostgreSQL app on the MacOS X 10.11, this is where the pg\_config file is `/Library/PostgreSQL/9.5/bin/pg_config`.
Then on the Terminal:
```
$ export PG_HOME=/Library/PostgreSQL/9.5
$ export PATH=$PATH:$PG_HOME/bin
```
This will put the path in the .profile of whatever terminal y... |
How can I kill a single shot QtCore.QTimer in PyQt4? | 21,079,941 | 2 | 2014-01-12T20:30:37Z | 21,081,371 | 7 | 2014-01-12T22:55:34Z | [
"python",
"python-2.7",
"timer",
"pyqt",
"pyqt4"
] | So, in my application, I create a single `QtCore.QTimer` object and then call the `singleShot` method on it to evoke a function after say 60 secs. Now, at any given point in time, if I would need to call the `singleShot` method on it again and prevent the previous `singleShot` method from taking effect (that is prevent... | The problem is that `QTimer.singleShot()` does not return a reference to the `QTimer`. I don't know of anyway to get the Timer ID so you can kill it using that method. However, you can instantiate a normal `QTimer` and make it a single-shot timer (this is not what you have done in your code provided, calling `singleSho... |
install_requires based on python version | 21,082,091 | 8 | 2014-01-13T00:19:23Z | 21,082,173 | 9 | 2014-01-13T00:28:22Z | [
"python",
"setuptools",
"distutils",
"distribute",
"install-requires"
] | I have a module that works both on python 2 and python 3. In Python<3.2 I would like to install a specific package as a dependency. For Python>=3.2.
Something like:
```
install_requires=[
"threadpool >= 1.2.7 if python_version < 3.2.0",
],
```
How can one make that? | This has been discussed [here](https://mail.python.org/pipermail/distutils-sig/2009-July/012826.html), it would appear the recommend way is to test for the Python version inside your `setup.py` using `sys.version_info`;
```
import sys
if sys.version_info >= (3,2):
install_requires = ["threadpool >= 1.2.7"]
else:
... |
install_requires based on python version | 21,082,091 | 8 | 2014-01-13T00:19:23Z | 32,643,122 | 11 | 2015-09-18T02:59:19Z | [
"python",
"setuptools",
"distutils",
"distribute",
"install-requires"
] | I have a module that works both on python 2 and python 3. In Python<3.2 I would like to install a specific package as a dependency. For Python>=3.2.
Something like:
```
install_requires=[
"threadpool >= 1.2.7 if python_version < 3.2.0",
],
```
How can one make that? | `setuptools` has support for this within the `extras_require` argument.
The format is the following:
```
extras_require={
':python_version=="2.7"': ["mock"],
},
```
It will support the other comparison operators.
---
Sadly, it is not mentioned in the [documentation](https://pythonhosted.org/setuptools/setuptoo... |
Paramiko: how to ensure data is received between commands | 21,083,195 | 5 | 2014-01-13T03:01:50Z | 21,105,626 | 7 | 2014-01-14T03:31:55Z | [
"python",
"paramiko"
] | I'm using Paramiko to issue a number of commands and collect results for further analysis. Every once in a while the results from the first command are note fully returned in time and end up in the output for the second command.
I'm attempting to use recv\_ready to account for this but it is not working so I assume I ... | I would use `transport` directly and create a new channel for each command. Then you can use something like:
```
def issue_command(transport, pause, command):
chan = transport.open_session()
chan.exec_command(command)
buff_size = 1024
stdout = ""
stderr = ""
while not chan.exit_status_ready()... |
Django Tutorial - ImproperlyConfigured exception (pytz isn't installed) | 21,084,332 | 10 | 2014-01-13T05:16:40Z | 21,084,433 | 12 | 2014-01-13T05:27:50Z | [
"python",
"django",
"pytz"
] | I'm currently working through the official Django tutorial using version 1.6.1 and version 2.7.5 of python on OSX. I'm working on part 2, which is the admin interface. When I attempt to go to /admin/polls/poll/, I get the following error report:
```
ImproperlyConfigured at /admin/polls/poll/
This query requires pytz, ... | After continuing to search for django and pytz, I found the 1.6 Django release notes, which mention that you must now install pytz to work with Sqlite3 if USE\_TZ=True in your settings.py.
I don't know what effect USE\_TZ has on your application, but setting that value to False allows me to proceed in the tutorial. I ... |
Django Tutorial - ImproperlyConfigured exception (pytz isn't installed) | 21,084,332 | 10 | 2014-01-13T05:16:40Z | 26,460,703 | 15 | 2014-10-20T07:45:04Z | [
"python",
"django",
"pytz"
] | I'm currently working through the official Django tutorial using version 1.6.1 and version 2.7.5 of python on OSX. I'm working on part 2, which is the admin interface. When I attempt to go to /admin/polls/poll/, I get the following error report:
```
ImproperlyConfigured at /admin/polls/poll/
This query requires pytz, ... | I was also getting the same error.
I installed pytz
```
$ pip install pytz
```
and then i restarted the server. The exception is no more now. |
Flask hello world using apache and mod_wsgi shows files in webroot only | 21,084,791 | 8 | 2014-01-13T05:58:23Z | 21,085,340 | 15 | 2014-01-13T06:43:09Z | [
"python",
"apache",
"apache2",
"flask",
"wsgi"
] | I'm attempting to run the basic hello.py from the flask site over apache2 using wsgi. Here is what my code looks like:
/var/www/flask\_dev/hello.py
```
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
```
/var/www/fl... | in /var/www/flask\_dev/hello.wsgi you should be importing app not ass.
Second you should not be using DocumentRoot to store your scripts. DocumentRoot is for storing static files and so it will certainly list them as files and never run them as script.
Try using
```
WSGIScriptAlias / /var/www/flask_dev/hello.wsgi... |
sys.stdin.readline() reads without prompt, returning 'nothing in between' | 21,086,736 | 7 | 2014-01-13T08:27:43Z | 21,087,010 | 14 | 2014-01-13T08:46:19Z | [
"python",
"python-3.x",
"stdin"
] | I have a function that executes the following (among other things):
```
userinput = stdin.readline()
betAmount = int(userinput)
```
Is supposed to take input integer from stdin as a string and convert it to an integer.
When I call the function, however, it returns a single newline character (it doesn't even wait for... | `stdin.read(1)` reads one character from `stdin`. If there was more than one character to be read at that point (e.g. the newline that followed the one character that was read in) then that character or characters will still be in the buffer waiting for the next `read()` or `readline()`.
As an example, given `rd.py`:
... |
sys.stdin.readline() reads without prompt, returning 'nothing in between' | 21,086,736 | 7 | 2014-01-13T08:27:43Z | 21,087,303 | 10 | 2014-01-13T09:06:54Z | [
"python",
"python-3.x",
"stdin"
] | I have a function that executes the following (among other things):
```
userinput = stdin.readline()
betAmount = int(userinput)
```
Is supposed to take input integer from stdin as a string and convert it to an integer.
When I call the function, however, it returns a single newline character (it doesn't even wait for... | Simon's answer and Volcano's together explain what you're doing wrong, and Simon explains how you can fix it by redesigning your interface.
But if you really *need* to read 1 character, and then later read 1 line, you can do that. It's not trivial, and it's different on Windows vs. everything else.
There are actually... |
Python service discovery: Advertise a service across a local network | 21,089,268 | 12 | 2014-01-13T10:43:04Z | 21,090,815 | 14 | 2014-01-13T12:02:06Z | [
"python",
"sockets",
"networking",
"client-server",
"service-discovery"
] | I have a "server" python script running on one of the local network machines, which waits for clients to connect, and passes them some work to do. The server and client code have both been written, and are working as expected...
The problem is, this server might be running from any machine in the local network, so I c... | An easy way to do service announcement/discovery *on the local network* is by broadcasting UDP packets.
**Constants:**
```
PORT = 50000
MAGIC = "fna349fn" #to make sure we don't confuse or get confused by other programs
```
**Announcement:**
```
from time import sleep
from socket import socket, AF_INET, SOCK_DGRAM,... |
hashlib vs crypt.crypt() in Python. Why different results? | 21,090,312 | 7 | 2014-01-11T07:21:32Z | 21,090,314 | 7 | 2014-01-12T02:18:56Z | [
"python",
"passwords",
"encryption",
"cryptography"
] | I'm learning Python. I can't figure out why `hashlib.sha512(salt + password).hexdigest()` doesn't give the expected results.
I'm looking for a pure Python implementation of the equivalent of Ulrich Drepper's [sha512crypt.c algorithm](http://www.akkadia.org/drepper/SHA-crypt.txt). (It took me a while to figure out what... | The manual of `crypt` is imprecise (even misleading). The algorithms used by `crypt` with the âMD5â, âSHA-256â or âSHA-512â monikers are in fact algorithms *built* on these primitives. They are [password-based key derivation functions](https://en.wikipedia.org/wiki/Key_derivation_function#Key_stretching), u... |
hashlib vs crypt.crypt() in Python. Why different results? | 21,090,312 | 7 | 2014-01-11T07:21:32Z | 21,090,315 | 8 | 2014-01-12T17:51:23Z | [
"python",
"passwords",
"encryption",
"cryptography"
] | I'm learning Python. I can't figure out why `hashlib.sha512(salt + password).hexdigest()` doesn't give the expected results.
I'm looking for a pure Python implementation of the equivalent of Ulrich Drepper's [sha512crypt.c algorithm](http://www.akkadia.org/drepper/SHA-crypt.txt). (It took me a while to figure out what... | Here's the solution. There is also more detail at this other question: [Python implementation of sha512\_crypt.c](http://stackoverflow.com/q/21082483/463994) where it shows that the backend of passlib contains a pure Python implementation of sha512\_crypt (and the Python implementation is called if crypt.crypt() isn't ... |
How print statement create a local variables | 21,090,930 | 22 | 2014-01-13T12:08:48Z | 21,091,119 | 23 | 2014-01-13T12:18:39Z | [
"python",
"python-internals"
] | Question are at the end of this post.
**First snippet:** empty local variable dictionary.
```
def outer():
x = 1
def inner():
print "Local variables: %s" % locals()
return inner()
print outer()
```
Output:
Local variables: {}
**Second snippet:** print inside inner() function and creating local v... | In Python, unless you specify otherwise (with a `global` statement, or a `nonlocal` statement in 3.0+), a variable is in `locals` if you modify it (assign to it, `del` it, etc.) anywhere in the function.\*
In the first snippet, you never modify `x`, or even access it, so it's not local. In fact, it doesn't even exist.... |
How print statement create a local variables | 21,090,930 | 22 | 2014-01-13T12:08:48Z | 21,091,138 | 8 | 2014-01-13T12:19:23Z | [
"python",
"python-internals"
] | Question are at the end of this post.
**First snippet:** empty local variable dictionary.
```
def outer():
x = 1
def inner():
print "Local variables: %s" % locals()
return inner()
print outer()
```
Output:
Local variables: {}
**Second snippet:** print inside inner() function and creating local v... | Python supports nested scopes, by looking at how variables are used at compile time. Variables that you assign to in a function (or bind to with an `import` in a function) are considered local, everything else is non-local. Trying to delete a variable also marks it as a local.
Non-local names are searched for in paren... |
Reference vs Assigment in Python mutable objects | 21,092,937 | 2 | 2014-01-13T13:52:32Z | 21,092,972 | 9 | 2014-01-13T13:54:22Z | [
"python",
"reference",
"variable-assignment"
] | **Assignment:**
```
>>> a = ['spam']
>>> b = ['spam']
>>> a is b
False
```
**Reference:**
```
>>> c = ['spam']
>>> d = c
>>> c is d
True
```
1. What is the difference between above both?
2. Why assignment results `False`?
3. Why reference results `True`? | Your first snippet creates *two* unique list objects, which are not the same. Hence `a is b` returns false because `a` and `b` are pointing to distinct objects:
```
+------+
a ------> | list |
+------+
+------+
b ------> | list |
+------+
```
Your second snippet creates a sing... |
error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied | 21,093,002 | 24 | 2014-01-13T13:55:49Z | 22,773,505 | 18 | 2014-03-31T22:34:25Z | [
"python",
"ubuntu-12.04",
"virtualenv",
"pip"
] | I am using ubuntu 12.04 and I am trying to pip install virtualenv but suddenly I got this error.
```
samuel@sampc:~$ pip install virtualenv
Downloading/unpacking virtualenv
Running setup.py egg_info for package virtualenv
warning: no previously-included files matching '*' found under directory 'docs/_templates'... | Use
```
sudo pip install virtualenv
```
Apparently you will have powers of administrator when adding "sudo" before the line... just don't forget your password. |
error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied | 21,093,002 | 24 | 2014-01-13T13:55:49Z | 38,088,879 | 8 | 2016-06-29T01:32:46Z | [
"python",
"ubuntu-12.04",
"virtualenv",
"pip"
] | I am using ubuntu 12.04 and I am trying to pip install virtualenv but suddenly I got this error.
```
samuel@sampc:~$ pip install virtualenv
Downloading/unpacking virtualenv
Running setup.py egg_info for package virtualenv
warning: no previously-included files matching '*' found under directory 'docs/_templates'... | I've heard that using `sudo` with `pip` is unsafe.
Try adding `--user` to the end of your command, as mentioned [here](http://stackoverflow.com/a/7143496).
```
pip install packageName --user
```
I suspect that installing with this method means the packages are not available to other users. |
Convert list of rgb codes to matplotlib colormap | 21,094,288 | 6 | 2014-01-13T14:55:46Z | 21,094,452 | 10 | 2014-01-13T15:02:28Z | [
"python",
"matplotlib"
] | I have a list of rgb values and would like to create a costum colormap from the list.
These are the example values:
```
my_rgbs =['#ece804','#ece804','#e8e804','#e4e804','#e4e804','#e0e804','#dce804','#dce804','#d8e804','#d4e404','#d4e404','#d0e404','#cce404','#cce404','#c8e404','#c4e404','#c4e404','#c0e404','#bce404... | You want to use [`ListedColormap`](http://matplotlib.org/api/colors_api.html#matplotlib.colors.ListedColormap) which exists for exactly this purpose:
```
my_cmap = matplotlib.colors.ListedColormap(my_rgb, name='my_name')
``` |
What is a 'NoneType' object? | 21,095,654 | 21 | 2014-01-13T15:58:06Z | 21,095,702 | 7 | 2014-01-13T16:00:14Z | [
"python",
"pexpect",
"optparse"
] | I'm getting this error when I run my python script:
```
TypeError: cannot concatenate 'str' and 'NoneType' objects
```
I'm pretty sure the 'str' means string, but I dont know what a 'NoneType' object is. My script craps out on the second line, I know the first one works because the commands from that line are in my a... | [`NoneType`](http://docs.python.org/2/library/types.html#types.NoneType) is simply the type of the [`None`](http://docs.python.org/3/library/constants.html#None) singleton:
```
>>> type(None)
<type 'NoneType'>
```
From the latter link above:
> **`None`**
>
> The sole value of the type `NoneType`. `None` is frequentl... |
What is a 'NoneType' object? | 21,095,654 | 21 | 2014-01-13T15:58:06Z | 21,095,731 | 21 | 2014-01-13T16:01:15Z | [
"python",
"pexpect",
"optparse"
] | I'm getting this error when I run my python script:
```
TypeError: cannot concatenate 'str' and 'NoneType' objects
```
I'm pretty sure the 'str' means string, but I dont know what a 'NoneType' object is. My script craps out on the second line, I know the first one works because the commands from that line are in my a... | `NoneType` is the type for the `None` object, which is an object that indicates *no value*. You cannot add it to strings or other objects.
What is most likely happening is that one of your names (the proper term for a *variable* in Python) is not set, hence it has the value of `None` and when you try to + it to a stri... |
Why doesn't `sys.modules.keys()` include name from `import...as`? | 21,095,931 | 3 | 2014-01-13T16:10:43Z | 21,095,984 | 9 | 2014-01-13T16:13:18Z | [
"python"
] | Say I import a module as follows:
```
import os as OSMOD
```
and then wanted to find the working directory
```
OSMOD.getcwd()
```
`OSMOD` is now a stand in for `os`, and using `os` won't work. This is all dandy, and works for me. However, I noticed something a little odd. If I import `os` as I do above, and then ge... | Because the name of the module is `os`. You did `import os`. `as OSMOD` just tells Python to assign that module to the name `OSMOD` *in your module's namespace.*
`sys.modules` is a cache of imported modules to prevent modules from being imported more than once. If it stored the imported module under `OSMOD`, another m... |
SSL backend error when using OpenSSL | 21,096,436 | 39 | 2014-01-13T16:33:45Z | 21,099,222 | 44 | 2014-01-13T19:01:13Z | [
"python",
"curl",
"virtualenv",
"pip",
"pycurl"
] | I was trying to install pycurl in a virtualenv using pip and I got this error
```
ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other)
```
I read some documentation saying that *"To fix this, you need to tell setup.py what SSL backend is used"* [(source)... | After reading their INSTALLATION file, I was able to solve my problem by setting an environment variable and did a reinstall
* remove existing pycurl installation
pip uninstall pycurl
* export variable with your link-time ssl backend (which is openssl above)
export PYCURL\_SSL\_LIBRARY=openssl
* install pycurl
... |
SSL backend error when using OpenSSL | 21,096,436 | 39 | 2014-01-13T16:33:45Z | 22,003,192 | 8 | 2014-02-25T02:04:05Z | [
"python",
"curl",
"virtualenv",
"pip",
"pycurl"
] | I was trying to install pycurl in a virtualenv using pip and I got this error
```
ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other)
```
I read some documentation saying that *"To fix this, you need to tell setup.py what SSL backend is used"* [(source)... | This worked for me:
```
pip uninstall pycurl
export PYCURL_SSL_LIBRARY=nss
easy_install pycurl
```
None of this worked for me (note the difference is simply easy\_install vs pip):
```
pip uninstall pycurl
export PYCURL_SSL_LIBRARY=[nss|openssl|ssl|gnutls]
pip install pycurl
#xor
curl -O https://pypi.python.org/packa... |
SSL backend error when using OpenSSL | 21,096,436 | 39 | 2014-01-13T16:33:45Z | 23,118,721 | 37 | 2014-04-16T19:42:27Z | [
"python",
"curl",
"virtualenv",
"pip",
"pycurl"
] | I was trying to install pycurl in a virtualenv using pip and I got this error
```
ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other)
```
I read some documentation saying that *"To fix this, you need to tell setup.py what SSL backend is used"* [(source)... | helloworld2013's answer is correct, but the key is matching the SSL library that pycurl is expecting. The error will be something like:
pycurl: libcurl link-time ssl backend (*<library>*) is different from compile-time ssl backend (*<library>* or "*none/other*")
To fix it, you have to use the library pycurl is expect... |
SSL backend error when using OpenSSL | 21,096,436 | 39 | 2014-01-13T16:33:45Z | 31,329,250 | 9 | 2015-07-09T22:19:44Z | [
"python",
"curl",
"virtualenv",
"pip",
"pycurl"
] | I was trying to install pycurl in a virtualenv using pip and I got this error
```
ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other)
```
I read some documentation saying that *"To fix this, you need to tell setup.py what SSL backend is used"* [(source)... | With pip 7.1 you can put the following in your requirements file:
```
pycurl==7.19.5.1 --global-option="--with-nss"
```
Simply replace nss with the relevant ssl backend library. |
What is the Matlab equivalent of the yield keyword in Python? | 21,099,040 | 5 | 2014-01-13T18:51:52Z | 21,100,611 | 8 | 2014-01-13T20:20:59Z | [
"python",
"matlab",
"generator",
"yield",
"yield-keyword"
] | I need to generate multiple results but one at a time, as opposed to everything at once in an array.
How do I do that in Matlab with a generator like syntax as in Python? | When executing functions that use the `yield` keyword, they actually return a generator. Generators are a type of iterators. While MATLAB does not provide the syntax for either, you can implement the ["iterator interface"](http://www.python.org/dev/peps/pep-0234/) yourself. Here is an example similar to `xrange` functi... |
Control the pip version in virtualenv | 21,099,057 | 7 | 2014-01-13T18:53:20Z | 21,102,447 | 9 | 2014-01-13T22:15:20Z | [
"python",
"pip",
"virtualenv",
"virtualenvwrapper",
"python-wheel"
] | How do I control the version of `pip` which is used in a freshly created virtualenv? I believe I've eradicated all other versions of pip from the OS, but still mkvirtualenv gets a pip-1.5 from somewhere! I want it to use pip 1.4.1 in the virtualenv.
```
wim@wim-zenbook:/tmp$ which pip
/usr/local/bin/pip
wim@wim-zenboo... | From reading the source of virtualenv, it looks like pip is installed from a source tarfile included with virtualenv. In virtualenv 1.10.1, it is `pip-1.4.1.tar.gz` in the `site-packages/virtualenv_support` directory (it gets `setuptools` from the same place). You could feasibly replace that archive to control the vers... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.