title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python Matlab Engine Install | 27,772,334 | 3 | 2015-01-05T01:36:09Z | 27,772,362 | 7 | 2015-01-05T01:40:42Z | [
"python",
"matlab"
] | Ive been trying to install matlab engine for python so I can call matlab functions from within my python scripts.
The guide Im using is this one: <http://uk.mathworks.com/help/matlab/matlab_external/install-the-matlab-engine-for-python.html>
It says the setup.py file is located in matlabroot\extern\engines\python, ho... | Looking at the release notes for Matlab 2014, the Python engine didn't exist until R2014b, so I don't think you'll be able to use it in 2012.
<http://uk.mathworks.com/help/matlab/release-notes.html> |
Python interpreters on OS X Yosemite - which one to use? | 27,776,494 | 4 | 2015-01-05T09:22:31Z | 27,776,823 | 12 | 2015-01-05T09:42:47Z | [
"python",
"osx-yosemite"
] | I recently switched from Windows to Mac, and after installing PyCharm I had to specify an interpreter. In the drop down I could choose between 3 interpreters:
1. Macintosh HD ⸠usr ⸠local ⸠Cellar ⸠python ⸠2.7.9 ⸠Frameworks ⸠Python.framework ⸠Versions ⸠2.7 ⸠bin
2. Macintosh HD ⸠System â... | You really only have *two* Python 2.7 installations, as well as a 2.6 Python version you can mostly ignore:
* `/usr/local/Cellar/` is user-installed (through [Homebrew](http://brew.sh/)). It'll be linked into the `/usr/local/opt` directory structure:
```
$ /usr/local/bin/python -c "import sys; print sys.prefix"
... |
Replace zeros in a numpy array with nan | 27,778,299 | 3 | 2015-01-05T11:10:56Z | 27,778,369 | 7 | 2015-01-05T11:15:19Z | [
"python",
"arrays",
"numpy",
null
] | I wrote a python script below:
```
import numpy as np
arr = np.arange(6).reshape(2, 3)
arr[arr==0]=['nan']
print arr
```
But I got this error:
```
Traceback (most recent call last):
File "C:\Users\Desktop\test.py", line 4, in <module>
arr[arr==0]=['nan']
ValueError: invalid literal for long() with base 10: 'n... | `np.nan` has type `float`: arrays containing it must also have this datatype (or the `object` datatype) so you may need to recast `arr` before you try to assign the value. The error arises because the string value `'nan'` can't be converted to an integer type to match `arr`'s type.
The string `'nan'` is interpreted as... |
Python - keeping counter inside list comprehension | 27,778,604 | 3 | 2015-01-05T11:29:03Z | 27,778,672 | 8 | 2015-01-05T11:32:37Z | [
"python",
"counter",
"list-comprehension"
] | Is it possible to write a list comprehension for the following loop?
```
m = []
counter = 0
for i, x in enumerate(l):
if x.field == 'something':
counter += 1
m.append(counter / i)
```
I do not know how to increment the counter inside the list comprehension. | You could use an [`itertools.count`](https://docs.python.org/2/library/itertools.html#itertools.count):
```
import itertools as IT
counter = IT.count(1)
[next(counter)/i for i, x in enumerate(l) if x.field == 'something']
```
To avoid the possible ZeroDivisionError pointed out by tobias\_k, you could make `enumerate`... |
Get better parse error message from ElementTree | 27,779,375 | 2 | 2015-01-05T12:17:01Z | 27,779,811 | 8 | 2015-01-05T12:44:47Z | [
"python",
"xml",
"xml-parsing"
] | If I try to parse a broken XML the exception shows the line number. Is there a way to show the XML context?
I want to see the xml tags before and after the broken part.
Example:
```
import xml.etree.ElementTree as ET
tree = ET.fromstring('<a><b></a>')
```
Exception:
```
Traceback (most recent call last):
File "t... | You could make a helper function to do this:
```
import io
import itertools as IT
import xml.etree.ElementTree as ET
def myfromstring(content):
try:
tree = ET.fromstring(content)
except ET.ParseError as err:
lineno, column = err.position
line = next(IT.islice(io.BytesIO(content), linen... |
python: format time elapsed from seconds to hour, mins and sceconds | 27,779,677 | 4 | 2015-01-05T12:36:30Z | 27,780,763 | 10 | 2015-01-05T13:40:40Z | [
"python",
"time",
"format",
"elapsed"
] | How can I format the time elapsed from seconds to hours, mins, seconds?
My code:
```
start = time.time()
... do something
elapsed = (time.time() - start)
```
Actual Output:
```
0.232999801636
```
Desired/Expected output:
```
00:00:00.23
``` | If you want to include times like `0.232999801636` as in your input:
```
import time
start = time.time()
end = time.time()
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
print("{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
In [12]: def timer(start,end):
....: ho... |
python: format time elapsed from seconds to hour, mins and sceconds | 27,779,677 | 4 | 2015-01-05T12:36:30Z | 27,793,118 | 22 | 2015-01-06T06:16:46Z | [
"python",
"time",
"format",
"elapsed"
] | How can I format the time elapsed from seconds to hours, mins, seconds?
My code:
```
start = time.time()
... do something
elapsed = (time.time() - start)
```
Actual Output:
```
0.232999801636
```
Desired/Expected output:
```
00:00:00.23
``` | You could exploit `timedelta`:
```
>>> from datetime import timedelta
>>> str(timedelta(seconds=elapsed))
'0:00:00.233000'
``` |
Ask user and print a list | 27,780,705 | 4 | 2015-01-05T13:37:03Z | 27,780,720 | 11 | 2015-01-05T13:38:17Z | [
"python",
"list",
"python-3.x"
] | I have a problem with printing a list.
For example I have two lists:
```
a = [1,2,3,4,5]
b = [6,7,8,9,10]
```
Now I want to ask user to input a list name and then print that list.
```
name = input("Write a list name")
```
User entered `"a"`
```
for x in name:
print(x)
```
But it does not work (not printing li... | You need to map the lists to strings, which are what the user can enter.
So use a dictionary:
```
lists_dict = {
'a': [1,2,3,4,5]
'b': [6,7,8,9,10]
}
key = input("Write a list name")
print lists_dict[key]
```
## Edit:
Your dictionary should look as follows:
```
poland = {
"poznan": {"name": 86470, "l... |
Ask user and print a list | 27,780,705 | 4 | 2015-01-05T13:37:03Z | 27,780,733 | 7 | 2015-01-05T13:38:50Z | [
"python",
"list",
"python-3.x"
] | I have a problem with printing a list.
For example I have two lists:
```
a = [1,2,3,4,5]
b = [6,7,8,9,10]
```
Now I want to ask user to input a list name and then print that list.
```
name = input("Write a list name")
```
User entered `"a"`
```
for x in name:
print(x)
```
But it does not work (not printing li... | You can use `globals()` dictionary like this `print(globals()[name])`. `input()` returns a single name, so there is no need to use loop either.
```
>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> name = input("Write a list name ")
Write a list name a
>>> globals()[name]
[1, 2, 3, 4, 5]
```
After OP's edit:
```
>>> pola... |
Python: confusion between types and dtypes | 27,780,878 | 6 | 2015-01-05T13:46:34Z | 27,781,185 | 8 | 2015-01-05T14:04:41Z | [
"python",
"numpy",
"types",
"unsigned-integer"
] | Suppose I enter:
```
a = uint8(200)
a*2
```
Then the result is 400, and it is recast to be of type uint16.
However:
```
a = array([200],dtype=uint8)
a*2
```
and the result is
```
array([144], dtype=uint8)
```
The multiplication has been performed modulo 256, to ensure that the result stays in one byte.
I'm conf... | The `type` of a NumPy array is `numpy.ndarray`; this is just the type of Python object it is (similar to how `type("hello")` is `str` for example).
`dtype` just defines how bytes in memory will be interpreted by a scalar (i.e. a single number) or an array and the way in which the bytes will be treated (e.g. `int`/`flo... |
Django UnicodeEncodeError in rendering form ('utf-8') | 27,781,019 | 5 | 2015-01-05T13:55:06Z | 27,781,442 | 20 | 2015-01-05T14:19:45Z | [
"python",
"django",
"forms",
"unicode",
"utf-8"
] | I got an UnicodeEncodeError while rendering page using forms.
```
UnicodeEncodeError at /individual/acc/
'ascii' codec can't encode character u'\u0142' in position 2: ordinal not in range(128)
```
Here's fragment of HTML (standard use of forms):
```
<table>
{{user_form.as_table}}
{{individual_form.as_table}... | Your model `__str__` is not handling Unicode correctly. You'll need to use explicit encoding:
```
def __str__(self):
return self.name.encode('utf8')
```
or use the [`force_bytes()` utility function](https://docs.djangoproject.com/en/1.7/ref/utils/#django.utils.encoding.force_bytes):
```
from django.utils.encodin... |
Eigenvectors computed with numpy's eigh and svd do not match | 27,781,872 | 13 | 2015-01-05T14:46:01Z | 27,782,269 | 14 | 2015-01-05T15:08:13Z | [
"python",
"numpy",
"svd",
"eigenvector"
] | Consider singular value decomposition M=USV\*. Then the eigenvalue decomposition of M\* M gives M\* M= V (S\* S) V\*=VS\* U\* USV\*. I wish to verify this equality with numpy by showing that the eigenvectors returned by `eigh` function are the same as those returned by `svd` function:
```
import numpy as np
np.random.... | Just play with small numbers to debug your problem.
Start with `A=np.random.randn(3,2)` instead of your much larger matrix with size `(50,20)`
In my random case, I find that
```
v1 = array([[-0.33872745, 0.94088454],
[-0.94088454, -0.33872745]])
```
and for `v2`:
```
v2 = array([[ 0.33872745, -0.94088454],
... |
numpy division with RuntimeWarning: invalid value encountered in double_scalars | 27,784,528 | 11 | 2015-01-05T17:15:04Z | 27,784,588 | 18 | 2015-01-05T17:19:19Z | [
"python",
"numpy",
"warnings"
] | I wrote the following script:
```
import numpy
d = numpy.array([[1089, 1093]])
e = numpy.array([[1000, 4443]])
answer = numpy.exp(-3 * d)
answer1 = numpy.exp(-3 * e)
res = answer.sum()/answer1.sum()
print res
```
But I got this result and with the error occurred:
```
nan
C:\Users\Desktop\test.py:16: RuntimeWarning:... | you can't solve it. Simply `answer1.sum()==0`, and you can't perform a division by zero.
This happens because `answer1` is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.
`nan` is returned in this case because of the division by zero.
Now to solve your problem you could:
* ... |
Why does print int (100*(11.20 - 11)) prints 19 instead of 20 in python? | 27,787,124 | 2 | 2015-01-05T20:11:53Z | 27,787,172 | 7 | 2015-01-05T20:14:51Z | [
"python",
"floating-point",
"int"
] | I have just started python tutorials. Why does
```
print int (100*(11.20 - 11))
```
print `19` instead of `20` in python ?? There is some sort of rounding off done by integer but i am unable to catch that. Help is appreciated. | This happens because `11.20` is not exactly 1120/100 but slightly less than that. So `11.20 - 11` ends up slightly less than 20/100 (\*). Multiplied by `100`, `11.20 - 11` produces a floating-point number slightly below 20, and since `int(...)` truncates (rounds towards zero), the result is 19.
For efficiency reasons,... |
How to get number of groups in a groupby object in pandas? | 27,787,930 | 5 | 2015-01-05T21:08:28Z | 27,787,977 | 12 | 2015-01-05T21:12:03Z | [
"python",
"pandas",
"grouping"
] | This would be useful so I know how many unique groups I have to perform calculations on. Thank you.
Suppose groupby object is called `dfgroup`. | As [documented](http://pandas.pydata.org/pandas-docs/stable/groupby.html#groupby-object-attributes), you can get the number of groups with `len(dfgroup)`. |
Count the number of elements found in selenium python | 27,788,397 | 3 | 2015-01-05T21:42:14Z | 27,788,426 | 10 | 2015-01-05T21:44:46Z | [
"python",
"selenium"
] | I have the following html page where I am trying to locate the word `silver` and keep count on how many were found.
This is just two showing here but it can generate more so I don't know the exact count.
```
<tr id="au_4" class="odd">
<td>Silver</td>
</tr>
<tr id="au_4" class="even">
<td>Silver</td>
</tr>
```
This i... | `count` is a *list* of all elements that were found. In order to find its length, you should:
```
len(count)
```
I highly recommend you to go through the [docs](http://selenium-python.readthedocs.org/en/latest/locating-elements.html) to better understand how Selenium works. |
IntegrityError: column slug is not unique | 27,788,456 | 4 | 2015-01-05T21:47:47Z | 27,788,566 | 7 | 2015-01-05T21:55:11Z | [
"python",
"django"
] | i'm studying django by tangowithdjango tutorials, and there on 7-th chapter I've stacked.
i'm trying to include a slug field in my model and override save method to make it all working. After migrate I have an integrity error.
models.py:
```
class Category(models.Model):
name = models.CharField(max_length=128, ... | Listen to the error. You have the slug attribute specified as unique, but you must have the same slug value for multiple instances of your `Category` class.
This can easily happen if you add a unique attribute column to a table that already has data, because any constant default you use will automatically break the un... |
Rearrange a Python List | 27,788,918 | 2 | 2015-01-05T22:22:21Z | 27,788,964 | 8 | 2015-01-05T22:26:01Z | [
"python",
"list"
] | I'm trying to rearrange a python list in this form:
```
[(title1,x1,y1),(title1,x2,y2),(title2,x3,y3),(title2,x4,y4),...]
```
And I need to rearrange it to this:
```
{title1:{
x1:y1,
x2:y2
},
title2:{
x3:y3,
x4:y4
}}
```
The output just needs to look the same and does not have to be an actual python... | You can do:
```
from collections import defaultdict
res = defaultdict(dict)
for title, x, y in my_list:
res[title][x] = y
``` |
Set lxml as default BeautifulSoup parser | 27,790,415 | 8 | 2015-01-06T00:49:30Z | 27,791,286 | 7 | 2015-01-06T02:38:11Z | [
"python",
"html",
"beautifulsoup",
"html-parsing",
"lxml"
] | I'm working on a web scraping project and have ran into problems with speed. To try to fix it, I want to use lxml instead of html.parser as BeautifulSoup's parser. I've been able to do this:
```
soup = bs4.BeautifulSoup(html, 'lxml')
```
but I don't want to have to repeatedly type `'lxml'` every time I call Beautiful... | According to the [Specifying the parser to use](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#specifying-the-parser-to-use) documentation page:
> The first argument to the BeautifulSoup constructor is a string or an
> open filehandleâthe markup you want parsed. The second argument is how
> youâd like the m... |
Eliminating series of .replace() calls in Python | 27,794,780 | 2 | 2015-01-06T08:29:20Z | 27,794,851 | 8 | 2015-01-06T08:33:59Z | [
"python",
"string",
"syntax",
"code-cleanup"
] | I'm working on a project that involves parsing pages of text. I've written the following function to remove certain punctuation from a word and convert it to lowercase:
```
def format_word(word):
return word.replace('.', '').replace(',', '').replace('\"', '').lower()
```
Is there any way to combine all of the cal... | You can use [`str.translate`](https://docs.python.org/3/library/stdtypes.html#str.translate) if you want to remove characters:
In python 2.x:
```
>>> 'Hello, "world".'.translate(None, ',."')
'Hello world'
```
In python 3.x:
```
>>> 'Hello, "world".'.translate(dict.fromkeys(map(ord, ',."')))
'Hello world'
``` |
When using asyncio, how do you allow all running tasks to finish before shutting down the event loop | 27,796,294 | 24 | 2015-01-06T10:06:31Z | 27,910,822 | 21 | 2015-01-12T21:12:54Z | [
"python",
"python-3.4",
"python-asyncio"
] | I have the following code:
```
@asyncio.coroutine
def do_something_periodically():
while True:
asyncio.async(my_expensive_operation())
yield from asyncio.sleep(my_interval)
if shutdown_flag_is_set:
print("Shutting down")
break
```
I run this function until complete.... | You can retrieve unfinished tasks and run the loop again until they finished, then close the loop or exit your program.
```
pending = asyncio.Task.all_tasks()
loop.run_until_complete(asyncio.gather(*pending))
```
* pending is a list of pending tasks.
* asyncio.gather() allows to wait on several tasks at once.
If you... |
What is an open tuple in python? | 27,797,283 | 2 | 2015-01-06T11:03:12Z | 27,797,409 | 7 | 2015-01-06T11:12:07Z | [
"python",
"tuples",
"variable-assignment"
] | I know the syntax `tup = ("x",)` allows Python to recognise that `tup` is a tuple rather than a string, but is there any difference between `a = (2,3,)` and `b = (2,3)`?
Such assignment yields:
```
>>> a == b
True
``` | We can assign value `tuple` in following ways
```
>>> a = (2,3)
>>> b = (2,3,)
>>> c = 2,3
>>> a==b
True
>>> a==c
True
>>> b==c
True
>>> d = 2,3,
>>> a==d
True
``` |
Python dateutil.parser.parse parses month first, not day | 27,800,775 | 8 | 2015-01-06T14:29:02Z | 27,800,808 | 14 | 2015-01-06T14:30:59Z | [
"python",
"parsing",
"format",
"python-dateutil"
] | I'm using `dateutil.parser.parse` to format a date from a string. But now it mixes up the month and the day.
I have a string that contains `05.01.2015`. After
```
dateutil.parser.parse("05.01.2015")
```
it returns:
```
datetime.datetime(2015, 5, 1, 0, 0)
```
I hoped the it would return `(2015, 1, 5, 0, 0)`
How ca... | Specify `dayfirst=True`:
```
>>> dateutil.parser.parse("05.01.2015", dayfirst=True)
datetime.datetime(2015, 1, 5, 0, 0)
```
This gives precedence to the DD-MM-YYYY format instead of MM-DD-YYYY in cases where the date format is ambiguous (e.g. when the day is 12 or lower). The function is documented [here](https://lab... |
Surprising results with Python timeit: Counter() vs defaultdict() vs dict() | 27,801,945 | 6 | 2015-01-06T15:35:36Z | 27,802,189 | 8 | 2015-01-06T15:49:13Z | [
"python",
"python-2.7",
"counter",
"timeit",
"defaultdict"
] | I obtained very surprising results with timeit, can someone tell me if I am doing something wrong ? I am using Python 2.7.
This is the contents of file speedtest\_init.py:
```
import random
to_count = [random.randint(0, 100) for r in range(60)]
```
These are the contents of speedtest.py:
```
__author__ = 'BlueTrin... | Yes, this is expected; the `Counter()` *constructor* uses `Counter.update()` which uses `self.get()` to load initial values rather than rely on `__missing__`.
Moreover, the `defaultdict` `__missing__` factory is handled entirely in C code, especially when using another type like `int()` that is itself implemented in C... |
Conditional with statement in Python | 27,803,059 | 10 | 2015-01-06T16:36:41Z | 27,806,978 | 13 | 2015-01-06T20:52:20Z | [
"python",
"conditional",
"indentation",
"conditional-statements",
"with-statement"
] | Is there a way to begin a block of code with a with statement, but conditionally?
Something like:
```
if needs_with():
with get_stuff() as gs:
# do nearly the same large block of stuff,
# involving gs or not, depending on needs_with()
```
To clarify, one scenario would have a block encased in the with statement... | If you want to avoid duplicating code, you could do something like:
```
class dummy_context_mgr():
def __enter__(self):
return None
def __exit__(self, exc_type, exc_value, traceback):
return False
with get_stuff() if needs_with() else dummy_context_mgr() as gs:
# do stuff involving gs or no... |
Get html using Python requests? | 27,803,503 | 4 | 2015-01-06T17:01:01Z | 27,803,961 | 8 | 2015-01-06T17:29:05Z | [
"python",
"html",
"python-requests"
] | I am trying to teach myself some basic web scraping. Using Python's requests module, I was able to grab html for various websites until I tried this:
```
>>> r = requests.get('http://www.wrcc.dri.edu/WRCCWrappers.py?sodxtrmts+028815+por+por+pcpn+none+mave+5+01+F')
```
Instead of the basic html that is the source for ... | The server in question is giving you a *gzipped response*. The server is also *very broken*; it sends the following headers:
```
$ curl -D - -o /dev/null -s -H 'Accept-Encoding: gzip, deflate' http://www.wrcc.dri.edu/WRCCWrappers.py?sodxtrmts+028815+por+por+pcpn+none+mave+5+01+F
HTTP/1.1 200 OK
Date: Tue, 06 Jan 2015 ... |
Python Urllib2 SSL error | 27,804,710 | 11 | 2015-01-06T18:21:04Z | 27,826,829 | 21 | 2015-01-07T19:09:43Z | [
"python",
"ssl",
"urllib2"
] | Python 2.7.9 is now much more strict about SSL certificate verification. Awesome!
I'm not surprised that programs that were working before are now getting CERTIFICATE\_VERIFY\_FAILED errors. But I can't seem to get them working (without disabling certificate verification entirely).
One program was using urllib2 to co... | To summarize the comments about the cause of the problem and explain the real problem in more detail:
If you check the trust chain for the OpenSSL client you get the following:
```
[0] 54:7D:B3:AC:BF:... /CN=*.s3.amazonaws.com
[1] 5D:EB:8F:33:9E:... /CN=VeriSign Class 3 Secure Server CA - G3
[2] F4:A8:0A:0C:D1:..... |
Performance of inline Python function definitions | 27,805,200 | 9 | 2015-01-06T18:52:35Z | 27,805,367 | 7 | 2015-01-06T19:02:51Z | [
"python"
] | A general question for someone that knows function definition internals better than I do.
In general, is there a performance trade off to doing something like this:
```
def my_function():
def other_function():
pass
# do some stuff
other_function()
```
Versus:
```
def other_function():
pass
... | Splitting larger functions into more readable, smaller functions is part of writing Pythonic code -- it should be obvious what you're trying to accomplish and smaller functions are easier to read, check for errors, maintain, and reuse.
As always, "which has better performance" questions should always be solved by [pro... |
How to only read lines in a text file after a certain string using python? | 27,805,919 | 6 | 2015-01-06T19:37:27Z | 27,805,988 | 8 | 2015-01-06T19:42:03Z | [
"python",
"python-2.7",
"text-mining"
] | Using python, I'd like to read to a dictionary all of the lines in a text file that come after a particular string. I'd like to do this over thousands of text files.
I'm able to identify and print out the particular string ('Abstract') using the following code (gotten from [this stack overflow answer](http://stackover... | just start another loop when you reach the line you want to start from :
```
for files in filepath:
with open(files, 'r') as f:
for line in f:
if 'Abstract' in line:
for line in f: # now you are at the lines you want
# do work
```
A file obje... |
Efficient outer product in python | 27,809,511 | 6 | 2015-01-07T00:16:39Z | 27,809,902 | 14 | 2015-01-07T01:02:45Z | [
"python",
"numpy",
"multiplication"
] | Outer product in python seems quite slow when we have to deal with vectors of dimension of order 10k. Could someone please give me some idea how could I speed up this operation in python?
Code is as follows:
```
In [8]: a.shape
Out[8]: (128,)
In [9]: b.shape
Out[9]: (32000,)
In [10]: %timeit np.outer(b,a)
100... | It doesn't really get any faster than that, these are your options:
**numpy.outer**
```
>>> %timeit np.outer(a,b)
100 loops, best of 3: 9.79 ms per loop
```
**numpy.einsum**
```
>>> %timeit np.einsum('i,j->ij', a, b)
100 loops, best of 3: 16.6 ms per loop
```
**numba**
```
from numba.decorators import autojit
@a... |
Why is my Python app stalled with 'system' / kernel CPU time | 27,810,561 | 5 | 2015-01-07T02:28:03Z | 29,693,756 | 7 | 2015-04-17T08:12:00Z | [
"python",
"linux",
"performance",
"python-multithreading",
"python-multiprocessing"
] | First off I wasn't sure if I should post this as a Ubuntu question or here.
But I'm guessing it's more of an Python question than a OS one.
My Python application is running on top of Ubuntu on a 64 core AMD server.
It pulls images from 5 GigE cameras over the network by calling out to a .so through `ctypes` and then p... | OK. I have the answer to my own question. Yes, it's taken me over 3 months to get this far.
It appears to be GIL thrashing in Python that is the reason for the massive 'system' CPU spikes and associated pauses. Here is a [good explanation of where the thrashing comes from](http://www.dabeaz.com/python/UnderstandingGIL... |
Django Rest: The view does not want to import | 27,817,313 | 4 | 2015-01-07T10:27:10Z | 27,817,627 | 10 | 2015-01-07T10:44:08Z | [
"python",
"django",
"import",
"django-rest-framework"
] | I'm doing the exercise with the Django tutorial Rest Framework (<http://www.django-rest-framework.org/tutorial/1-serialization>)
I'm at the stage of creating URLs and I have a problem with getting to the views.
I execute the code:
```
import snippets from views
```
I can not import views, will receive:
```
'module... | It is just an indentation problem, you should change your snippets/views.py to:
```
from .models import Snippet
from serializers import SnippetSerializer
from rest_framework.renderers import JSONPRenderer
from rest_framework.parsers import JSONParser
from django.http import HttpResponse
from django.views.decorators.cs... |
Why use getattr() instead of __dict__ when accessing Python object attributes? | 27,819,819 | 2 | 2015-01-07T12:44:23Z | 27,819,833 | 9 | 2015-01-07T12:45:55Z | [
"python",
"introspection"
] | In source examples and SO answers that have some degree of Python object introspection, a common pattern is:
```
getattr(some_object, attribute_name_string)
```
Is there a reason why this pattern is preferred to:
```
some_object.__dict__[attribute_name_string]
```
which seems to be more directly showing what's goin... | `some_object.__getattr__` is **not** a common pattern. `getattr(some_object, attribute_name_string)` is the proper way of accessing attributes dynamically.
Not all instances *have* a `__dict__` attribute; a class that uses `__slots__` for example won't have that attribute. Next, attributes are not necessarily found *o... |
how to solve diff. eq. using scipy.integrate.odeint? | 27,820,725 | 4 | 2015-01-07T13:36:37Z | 27,822,347 | 8 | 2015-01-07T15:07:43Z | [
"python",
"numpy",
"scipy",
"differential-equations",
"odeint"
] | I want to solve this differential equations with the given initial conditions:
```
(3x-1)y''-(3x+2)y'+(6x-8)y=0, y(0)=2, y'(0)=3
```
the ans should be
`y=2*exp(2*x)-x*exp(-x)`
here is my code:
```
def g(y,x):
y0 = y[0]
y1 = y[1]
y2 = (6*x-8)*y0/(3*x-1)+(3*x+2)*y1/(3*x-1)
return [y1,y2]
init =... | There are several things wrong here. Firstly, your equation is apparently
(3x-1)y''-(3x+2)y'-(6x-8)y=0; y(0)=2, y'(0)=3
(note the sign of the term in y). For this equation, your analytical solution and definition of `y2` are correct.
Secondly, as the @Warren Weckesser says, you must pass 2 parameters as `y` to `g`: ... |
Sort list B by the sort of list A? | 27,827,812 | 3 | 2015-01-07T20:10:43Z | 27,827,864 | 10 | 2015-01-07T20:13:59Z | [
"python",
"list"
] | Let's say I have some list A with k elements, and list B with k elements as well. I want to sort list A, but I also want to permute list B in the same way.
For example
```
A = [2,3,1,4]
B = [5,6,7,8]
```
after sorting A:
```
A = [1,2,3,4]
B = [7,5,6,8]
``` | Here is one way:
```
>>> A = [2,3,1,4]
>>> B = [5,6,7,8]
>>> A, B = zip(*sorted(zip(A, B)))
>>> list(A)
[1, 2, 3, 4]
>>> list(B)
[7, 5, 6, 8]
```
In a nutshell:
* zip `A` and `B` into a list of pairs;
* sort the pairs;
* [unzip](http://stackoverflow.com/questions/13635032/what-is-the-inverse-function-of-zip-in-pytho... |
Where should WSGIPythonPath point in my virtualenv? | 27,832,777 | 6 | 2015-01-08T04:08:48Z | 27,881,007 | 8 | 2015-01-10T20:41:33Z | [
"python",
"django",
"mod-wsgi",
"wsgi"
] | I have a folder called `python2.7` inside of `lib` in the virtual environment.
After reading half a dozen tutorials, I can't figure out exactly what I'm suppose to point the WSGIPythonPath to. I've seen some pointing to `site-packages` but some have been a colon `:` separated list.
```
Syntax error on line 1019 of /e... | You are getting the error because **WSGIPythonPath** Directive cannot be used inside the **VirtualHost** context. You have to declare it inside your main Apache configuration file. If you still want to point to the directories in your virtualenv inside the VirtualHost context, Use **WSGIDaemonProcess** Directive instea... |
Why doesn't 1 + 1 use BINARY_ADD? | 27,833,485 | 4 | 2015-01-08T05:27:37Z | 27,834,756 | 8 | 2015-01-08T07:11:47Z | [
"python",
"python-2.7",
"python-internals"
] | I do this:
```
>>> dis.dis(lambda: 1 + 1)
0 LOAD_CONST 2 (2)
3 RETURN_VALUE
```
I was expecting a BINARY\_ADD opcode to perform the addition. How was the sum computed? | This is the work of Python's peephole optimizer. It evaluates simple operations with only constants during the compile time itself and stores the result as a constant in the generated bytecode.
Quoting from the [Python 2.7.9 Source code](https://hg.python.org/cpython/file/648dcafa7e5f/Python/peephole.c#l472),
```
... |
"SSL: CERTIFICATE_VERIFY_FAILED" Error | 27,835,619 | 54 | 2015-01-08T08:14:34Z | 28,052,583 | 95 | 2015-01-20T18:26:12Z | [
"python",
"ssl",
"ssl-certificate",
"osx-yosemite"
] | I am getting this error
```
Exception in thread Thread-3:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 76... | If you **just** want to bypass verification, you can create a new [SSLContext](https://docs.python.org/2/library/ssl.html#ssl.SSLContext). By default newly created contexts use [CERT\_NONE](https://docs.python.org/2/library/ssl.html#ssl.CERT_NONE).
Be carefull with this as stated in section [17.3.7.2.1](https://docs.p... |
How to mock a tornado coroutine function using mock framework for unit testing? | 27,836,577 | 10 | 2015-01-08T09:17:39Z | 27,880,772 | 15 | 2015-01-10T20:15:07Z | [
"python",
"unit-testing",
"mocking",
"tornado"
] | The title simply described my problem. I would like to mock "\_func\_inner\_1" with specific return value. Thanks for any advises :)
code under test:
```
from tornado.gen import coroutine, Return
from tornado.testing import gen_test
from tornado.testing import AsyncTestCase
import mock
@coroutine
def _func_inner_1(... | There are two issues here:
First is the interaction between `@mock.patch` and `@gen_test`. gen\_test works by converting a generator into a "normal" function; mock.patch only works on normal functions (as far as the decorator can tell, the generator returns as soon as it reaches the first `yield`, so mock.patch undoes... |
How to effectively read large (30GB+) TAR file with BZ2 JSON twitter files into PostgreSQL | 27,838,842 | 4 | 2015-01-08T11:17:06Z | 27,840,223 | 7 | 2015-01-08T12:32:19Z | [
"python",
"json"
] | I'm trying to obtain twitter data from the [archive.org archive](https://archive.org/search.php?query=collection%3Atwitterstream&sort=-publicdate) and load it into a database. I am attempting to first load *all* tweets for a specific month, to then make a selection for tweets and only stage those I'm interested in (e.g... | A tar file does not contain an index of where files are located. Moreover, a tar file can contain [more than one copy of the same file](http://www.gnu.org/software/tar/manual/html_node/multiple.html). Therefore, when you extract one file, *the entire tar file must be read*. Even after it finds the file, the rest of the... |
Adding extra statements in a python list comprehension | 27,841,729 | 2 | 2015-01-08T13:52:23Z | 27,841,854 | 7 | 2015-01-08T13:58:26Z | [
"python",
"list-comprehension"
] | I have a requirement to find a line in a text file which contains a specific string and then append that line and all lines that follow it to a list. This is the way I accomplished it..
```
file1 = open("input.txt", "r")
always_print = False
lines = file1.readlines()
output = []
for line in lines:
if always_print ... | Use [`itertools.dropwhile()`](https://docs.python.org/2/library/itertools.html#itertools.dropwhile) to find the first line that contains your `def set`:
```
from itertools import dropwhile
output = list(dropwhile(lambda l: 'def set' not in l, lines))
```
`dropwhile()` will skip any entry in `lines` that doesn't matc... |
pandas groupby sort within groups | 27,842,613 | 12 | 2015-01-08T14:37:19Z | 27,844,045 | 19 | 2015-01-08T15:46:41Z | [
"python",
"sorting",
"pandas",
"group-by"
] | I want to group my dataframe by two columns and then sort the aggregated results within the groups.
```
In [167]:
df
Out[167]:
count job source
0 2 sales A
1 4 sales B
2 6 sales C
3 3 sales D
4 7 sales E
5 5 market A
6 3 market B
7 2 market C
8 4 market D
9 1 ma... | What you want to do is actually again a groupby (on the result of the first groupby): sort and take the first three elements per group.
Starting from the result of the first groupby:
```
In [60]: df_agg = df.groupby(['job','source']).agg({'count':sum})
```
We group by the first level of the index:
```
In [63]: g = ... |
python: get directory two levels up | 27,844,088 | 8 | 2015-01-08T15:49:25Z | 27,844,237 | 7 | 2015-01-08T15:56:06Z | [
"python",
"path",
"operating-system",
"directory"
] | Ok...I dont know where module `x` is, but I know that I need to get the path to the directory two levels up.
So, is there a more elegant way to do:
```
import os
two_up = os.path.dirname(os.path.dirname(__file__))
``` | You can use [`pathlib`](https://docs.python.org/3/library/pathlib.html). Unfortunately this is only available in the stdlib for Python 3.4. If you have an older version you'll have to install a copy from PyPI [here](https://pypi.python.org/pypi/pathlib/). This should be easy to do using `pip`.
```
from pathlib import ... |
What is the meaning of .xxxxxxx in Python Tkinter | 27,846,699 | 3 | 2015-01-08T18:05:17Z | 27,847,053 | 7 | 2015-01-08T18:27:39Z | [
"python",
"python-3.x",
"tkinter"
] | I wonder what is the meaning of `.xxxxxx` (e.g. `.50109912`) in Python Tkinter. I was trying to check what is returned by `Widget_name(container, **configuration options).pack()`
Of course it will return `None` But when I check what is returned by the widget before packing, it gives something as this `.50109912`. This ... | The number `50109912` is the unique Python object id of the button widget:
```
>>> from tkinter import *
>>> root = Tk()
>>> mybutton = Button(root, text="Click Me", command=root.destroy)
>>> print(mybutton)
.38321104
>>> id(mybutton)
38321104
>>>
```
Moreover, the string `.50109912` is the button widget's window pat... |
How to solve the ImportError: cannot import name simplejson in Django | 27,855,731 | 9 | 2015-01-09T07:25:24Z | 27,855,791 | 13 | 2015-01-09T07:29:32Z | [
"python",
"json",
"django",
"django-1.7",
"simplejson"
] | I'm trying to build a realtime chat app in Django(1.7.1). It seems that I needed to install Redis and ishout.js. So I installed them by following the instructions.
After making the project in Django, I put 'drealtime' under the INSTALLED\_APPS, and put:
```
'drealtime.middleware.iShoutCookieMiddleware'
```
right abo... | You are using an outdated version of `django-realtime`.
Upgrade it to the latest version, they [fixed the 1.7 compatibility](https://github.com/anishmenon/django-realtime/commit/e7223aeb60c27a5a571e6c7f9d7703d280826b70):
```
pip install django-realtime --upgrade
```
If the error persists, install directly from githu... |
Heroku TypeError: parse_requirements() missing 1 required keyword argument: 'session' | 27,869,152 | 14 | 2015-01-09T21:01:51Z | 29,506,380 | 8 | 2015-04-08T05:07:56Z | [
"python",
"heroku",
"pip"
] | I am trying to migeate an app to the cedar-14 stack from cedar on Heroku. In my requirements.txt file I have:
```
....
robobrowser==0.5.1
....
```
When I try to deploy by pushing the project to heroku I get:
```
Collecting robobrowser==0.5.1 (from -r requirements.txt (line 17))
Downloading robobrowser-0.5.1.tar... | I ran into this problem installing wabbit\_wappa for Python. I 'fixed' it by changing a line in setup.py from:
```
install_reqs = parse_requirements('requirements.txt')
```
to
```
install_reqs = parse_requirements('requirements.txt', session=False)
```
and it installed just fine. |
SQLAlchemy decimal precision | 27,869,239 | 5 | 2015-01-09T21:07:58Z | 27,869,390 | 7 | 2015-01-09T21:17:20Z | [
"python",
"sqlalchemy"
] | The documentation at sqlalchemy gives an example:
```
class sqlalchemy.types.DECIMAL(precision=None, scale=None, asdecimal=True)
```
What values other than None can you use for precision? I don't really understand how to set up the decimal precision. | From [documentation](http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.Numeric)
**precision** â the numeric precision for use in DDL CREATE TABLE
If you want to know which values are possible, check W3C for SQL data types: <http://www.w3schools.com/sql/sql_datatypes_general.asp>
In this c... |
How to post/put json data to ListSerializer | 27,869,841 | 15 | 2015-01-09T21:51:10Z | 27,871,396 | 24 | 2015-01-10T00:19:14Z | [
"python",
"django",
"django-rest-framework"
] | I'm reading about customizing multiple update [here](http://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-update) and I haven't figured out in what case the custom `ListSerializer` update method is called. I would like to update multiple objects at once, I'm not worried about multiple creat... | Django REST framework by default assumes that you are not dealing with bulk data creation, updates, or deletion. This is because 99% of people are not dealing with bulk data creation, and [DRF leaves the other 1% to third-party libraries](http://www.django-rest-framework.org/topics/third-party-resources/).
In Django R... |
pip install: Please check the permissions and owner of that directory | 27,870,003 | 66 | 2015-01-09T22:05:23Z | 27,871,374 | 17 | 2015-01-10T00:15:53Z | [
"python",
"pip",
"sudo",
"osx-yosemite"
] | When installing pip and python I have ran into a snag that says:
The directory `'/Users/Parthenon/Library/Logs/pi' or its parent directory is not owned by the current user and the debug log has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want the -H flag... | What is the problem here is that you somehow installed into virtualenv using `sudo`. Probably by accident. This means `root` user will rewrite Python package data, making all file owned by root and your normal user cannot write those files anymore. Usually virtualenv should be used and owned by your normal UNIX user on... |
pip install: Please check the permissions and owner of that directory | 27,870,003 | 66 | 2015-01-09T22:05:23Z | 27,880,573 | 64 | 2015-01-10T19:56:15Z | [
"python",
"pip",
"sudo",
"osx-yosemite"
] | When installing pip and python I have ran into a snag that says:
The directory `'/Users/Parthenon/Library/Logs/pi' or its parent directory is not owned by the current user and the debug log has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want the -H flag... | I also saw this change on my Mac when I went from running 'pip' to 'sudo pip'
Adding '-H' to sudo causes the message to go away for me. E.g.
> sudo -H pip install foo
'man sudo' tells me that '-H' causes sudo to set $HOME to the target users (root in this case).
So it appears pip is looking into $HOME/Library/Log a... |
python regular expression pattern * is not working as expected | 27,876,826 | 5 | 2015-01-10T13:40:45Z | 27,876,846 | 10 | 2015-01-10T13:43:05Z | [
"python",
"regex"
] | As per online python google class, I found the following documentation.
`'*'` -- 0 or more occurrences of the pattern to its left
But, When I tried the following, it is not giving expected result.
I am expecting `'iiiiiiiiiiiiii'` as output. But it is giving `''` as output.
May I know the reason please?
```
re.sea... | `*` means 0 or more but `re.search` would return only the first match. Here the first match is an empty string. So you get an empty string as output.
Change `*` to `+` to get the desired output.
```
>>> re.search(r'i*','biiiiiiiiiiiiiig').group()
''
>>> re.search(r'i+','biiiiiiiiiiiiiig').group()
'iiiiiiiiiiiiii'
```... |
Pythonic way of single list with all variations of sublists | 27,881,337 | 7 | 2015-01-10T21:21:57Z | 27,881,364 | 10 | 2015-01-10T21:25:43Z | [
"python",
"combinatorics"
] | I'm sure there are answers to this simple question but I don't really know how to formulate it in English (ashamed), so decided to ask human beings.
Suppose I have a list of lists:
```
[['Sometimes'], [' '], ['I'], [' '], ['love', 'hate'], [' '], ['pizza', 'coke']]
```
What would be the most pythonic way to obtain t... | ```
from itertools import product
options = [['Sometimes'],[' '],['I'],[' '],['love','hate'],[' '],['pizza','coke']]
for combo in product(*options):
print("".join(combo))
```
gives
```
Sometimes I love pizza
Sometimes I love coke
Sometimes I hate pizza
Sometimes I hate coke
``` |
MkDocs and MathJax | 27,882,261 | 11 | 2015-01-10T23:24:44Z | 31,926,644 | 11 | 2015-08-10T18:30:38Z | [
"python",
"markdown",
"mathjax"
] | I'm new to MkDocs and am writing some technical documentation that requires latex. I've successfully built a small website with one of the MkDocs themes, however it won't properly display the latex equations. I followed the instructions at:
<http://www.vlfeat.org/matconvnet/developers/>
as well as the instructions fo... | This is actually easier than I expected. First I installed the [Python-Markdown-Math Extension](https://github.com/mitya57/python-markdown-math):
```
pip install https://github.com/mitya57/python-markdown-math/archive/master.zip
```
Then I created a new MkDocs project:
```
mkdocs new test_math
```
Next I edited the... |
Flask projects on heroku returns 500 internal server error | 27,882,479 | 2 | 2015-01-10T23:57:45Z | 27,883,666 | 14 | 2015-01-11T03:23:32Z | [
"python",
"heroku",
"flask"
] | I have a basic flask project and i deploy it to heroku.
And page returns 500 internal server error. I m not using database.
Here is my logs :
```
2015-01-10T23:40:03.161880+00:00 heroku[web.1]: Starting process with command `gunicorn print:app --log-file=-`
2015-01-10T23:40:03.827603+00:00 app[web.1]: [2015-01-10 23:4... | I tried this locally and found out you have you can see what is wrong by setting a logger in your application and making it print to stdout
```
from flask import Flask, render_template
import sys
import logging
app = Flask(__name__)
app.logger.addHandler(logging.StreamHandler(sys.stdout))
app.logger.setLevel(logging.... |
Return Pandas dataframe from PostgreSQL query with sqlalchemy | 27,884,268 | 12 | 2015-01-11T05:27:49Z | 27,889,674 | 13 | 2015-01-11T17:00:53Z | [
"python",
"postgresql",
"pandas",
"sqlalchemy"
] | I want to query a PostgreSQL database and return the output as a Pandas dataframe.
I use `sqlalchemy` to create a connection the the database:
```
from sqlalchemy import create_engine
engine = create_engine('postgresql://user@localhost:5432/mydb')
```
I write a Pandas dataframe to a database table:
```
i=pd.read_cs... | You are bitten by the case (in)sensitivity issues with PostgreSQL. If you quote the table name in the query, it will work:
```
df = pd.read_sql_query('select * from "Stat_Table"',con=engine)
```
But personally, I would advise to just always use lower case table names (and column names), also when writing the table to... |
Printing test execution times and pinning down slow tests with py.test | 27,884,404 | 6 | 2015-01-11T05:54:22Z | 27,899,853 | 9 | 2015-01-12T10:28:41Z | [
"python",
"py.test"
] | I am running unit tests on a CI server using py.test. Tests use external resources fetched over network. Sometimes test runner takes too long, causing test runner to be aborted. I cannot repeat the issues locally.
Is there a way to make py.test print out execution times of (slow) test, so pinning down problematic test... | I'm not sure this will solve your problem, but you can pass `--durations=N` to print the slowest `N` tests after the test suite finishes. |
How do I install a Python package with a .whl file? | 27,885,397 | 311 | 2015-01-11T08:48:34Z | 27,885,547 | 30 | 2015-01-11T09:14:44Z | [
"python",
"windows",
"pip",
"python-wheel",
"jpype"
] | I'm having trouble installing a Python package (specifically, JPype1 0.5.7) on my Windows machine, and would like to install it with Christoph Gohlke's Window binaries. (Which, to my experience, alleviated much of the fuss for many other package installations.)
However, while Christoph used to provide .exe files in th... | To install from wheel, give it the directory where the wheel is downloaded. For example, to install `package_name.whl`:
```
pip install --use-wheel --no-index --find-links=/where/its/downloaded package_name
```
Make sure you have updated pip first to enable wheel support:
```
pip install --upgrade pip
``` |
How do I install a Python package with a .whl file? | 27,885,397 | 311 | 2015-01-11T08:48:34Z | 27,909,082 | 379 | 2015-01-12T19:12:41Z | [
"python",
"windows",
"pip",
"python-wheel",
"jpype"
] | I'm having trouble installing a Python package (specifically, JPype1 0.5.7) on my Windows machine, and would like to install it with Christoph Gohlke's Window binaries. (Which, to my experience, alleviated much of the fuss for many other package installations.)
However, while Christoph used to provide .exe files in th... | I just used the following which was quite simple. First open a console then cd to where you've downloaded your file like some-package.whl and use
```
pip install some-package.whl
```
Note: if pip.exe is not recognized, you may find it in the "Scripts" directory from where python has been installed. If pip is not inst... |
How do I install a Python package with a .whl file? | 27,885,397 | 311 | 2015-01-11T08:48:34Z | 28,157,796 | 14 | 2015-01-26T20:02:10Z | [
"python",
"windows",
"pip",
"python-wheel",
"jpype"
] | I'm having trouble installing a Python package (specifically, JPype1 0.5.7) on my Windows machine, and would like to install it with Christoph Gohlke's Window binaries. (Which, to my experience, alleviated much of the fuss for many other package installations.)
However, while Christoph used to provide .exe files in th... | in same boat as OP.
using windows command prompt, from directory:
```
C:\Python34\Scripts>
pip install wheel
```
seemed to work.
changing directory to where the whl was located it just tells me 'pip is not recognized'. going back to `C:\Python34\Scripts>`, then using the full command above to provide the 'where/its... |
How do I install a Python package with a .whl file? | 27,885,397 | 311 | 2015-01-11T08:48:34Z | 28,676,490 | 9 | 2015-02-23T14:53:20Z | [
"python",
"windows",
"pip",
"python-wheel",
"jpype"
] | I'm having trouble installing a Python package (specifically, JPype1 0.5.7) on my Windows machine, and would like to install it with Christoph Gohlke's Window binaries. (Which, to my experience, alleviated much of the fuss for many other package installations.)
However, while Christoph used to provide .exe files in th... | You have to run pip.exe from the command prompt...on my computer
I type C:/Python27/Scripts/pip2.exe install numpy |
Python check the whole loop before going to the else statement | 27,887,173 | 4 | 2015-01-11T12:41:55Z | 27,887,193 | 7 | 2015-01-11T12:43:55Z | [
"python",
"loops",
"if-statement"
] | How do I run through the whole loop and then after go to `else` statement, if the `if` condition is false?
The output is:
> No
>
> No
>
> Yes
But I only want it to jump to the else statement if all of the values does not equal!
```
test_1 = (255, 200, 100)
test_2 = (200, 200, 100)
test_3 = (500, 50, 200)
dict = {"... | You need to run the loop until you find a matche. You can use [`any`](https://docs.python.org/3/library/functions.html#any) function for this purpose, like this
```
if any(dict_object[key] == (500, 50, 200) for key in dict_object):
print('Yes')
else:
print('No')
```
We pass a generator expression to `any` fun... |
AttributeError using pyBrain _splitWithPortion - object type changed? | 27,887,936 | 14 | 2015-01-11T14:03:17Z | 28,138,852 | 15 | 2015-01-25T16:48:39Z | [
"python",
"pybrain"
] | I'm testing out pybrain following the basic classification tutorial [here](http://pybrain.org/docs/tutorial/datasets.html#classificationdataset) and a different take on it with some more realistic data [here](http://corpocrat.com/2014/10/10/tutorial-pybrain-neural-network-for-classifying-olivetti-faces/). However I rec... | I had the same problem. I added the following code to make it work on my machine.
```
tstdata_temp, trndata_temp = alldata.splitWithProportion(0.25)
tstdata = ClassificationDataSet(2, 1, nb_classes=3)
for n in xrange(0, tstdata_temp.getLength()):
tstdata.addSample( tstdata_temp.getSample(n)[0], tstdata_temp.getSa... |
Clustering text documents using scikit-learn kmeans in Python | 27,889,873 | 9 | 2015-01-11T17:20:15Z | 27,890,107 | 19 | 2015-01-11T17:41:28Z | [
"python",
"python-2.7",
"scikit-learn",
"cluster-analysis",
"k-means"
] | I need to implement [scikit-learn's kMeans](http://scikit-learn.org/stable/auto_examples/document_clustering.html#example-document-clustering-py) for clustering text documents. The [example code](http://scikit-learn.org/stable/auto_examples/document_clustering.html#example-document-clustering-py) works fine as it is bu... | This is a simpler example:
```
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score
documents = ["Human machine interface for lab abc computer applications",
"A survey of user opinion of computer system response tim... |
Is it possible to save datetime to DynamoDB? | 27,894,393 | 11 | 2015-01-12T02:06:48Z | 27,894,543 | 14 | 2015-01-12T02:31:47Z | [
"python",
"datetime",
"amazon-web-services",
"amazon-dynamodb",
"boto"
] | I have the next code:
```
users_table = Table(users_table_name, connection=Core.aws_dynamodb_connection)
users_table.put_item(data={
"login": login,
"password": hashlib.sha256(password.encode("utf-8")).hexdigest(),
"profile": profile,
"registration_date": datetime.now() # PROBLEM IS HERE
})
```
But when I run... | Okay, I see that DynamoDB does not support any date types. So the only solution is to use unix-like time as integer, or save date as string.
 |
No module named flask.ext.restful | 27,899,911 | 5 | 2015-01-12T10:31:59Z | 27,899,960 | 16 | 2015-01-12T10:34:51Z | [
"python",
"flask"
] | trying to run a server
```
(dal)â Server (master) python mainDAL.py â â±
Traceback (most recent call last):
File "mainDAL.py", line 4, in <module>
from flask.ext import restful
File "/Users/partuck/.virtualenvs/dal/lib/python2.7/s... | You have installed Flask, but you haven't installed `Flask-RESTful`, it's not in your `pip freeze` list.
You can [install](https://flask-restful.readthedocs.org/en/0.3.1/installation.html) it with `pip install flask-restful`. |
Convert Tweepy Status object into JSON | 27,900,451 | 9 | 2015-01-12T10:59:29Z | 27,901,076 | 29 | 2015-01-12T11:36:49Z | [
"python",
"tweepy"
] | I'm using [Tweepy](http://www.tweepy.org) to download tweets. I have a program that then writes the actual `Status` object to a file in text form. How do I translate this into JSON, or import this object back into Python? I've tried using the JSON library to encode, but Status is not JSON serializable. | The `Status` object of tweepy itself is not JSON serializable, but it has a `_json` property which contains JSON serializable response data. For example:
```
>>> status_list = api.user_timeline(user_handler)
>>> status = status_list[0]
>>> json_str = json.dumps(status._json)
``` |
How to replace NaNs by preceding values in pandas DataFrame? | 27,905,295 | 7 | 2015-01-12T15:22:48Z | 27,905,350 | 9 | 2015-01-12T15:25:42Z | [
"python",
"python-3.x",
"pandas"
] | Suppose I have a DataFrame with some `NaN`s:
```
>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
>>> df
0 1 2
0 1 2 3
1 4 NaN NaN
2 NaN NaN 9
```
What I need to do is replace every `NaN` with the first non-`NaN` value in the same column above it. It is as... | You could use the [`fillna`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html) method on the DataFrame and specify the method as `ffill` (forward fill):
```
>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
>>> df.fillna(method='ffill')
0 1 2
0 1 2 3
1 4 2... |
Python: Why is list comprehension slower than for loop | 27,905,965 | 2 | 2015-01-12T15:58:15Z | 27,906,182 | 8 | 2015-01-12T16:09:29Z | [
"python",
"performance",
"list-comprehension"
] | Essentially these are the same functions - except list comprehension uses `sum` instead of `x=0; x+=` since the later is not supported. Why is list comprehension compiled to something 40% slower?
```
#list comprehension
def movingAverage(samples, n=3):
return [float(sum(samples[i-j] for j in range(n)))/n for i in... | You are using a generator expression in your list comprehension:
```
sum(samples[i-j] for j in range(n))
```
Generator expressions require a new frame to be created each time you run one, just like a function call. This is relatively expensive.
You don't need to use a generator expression at all; you only need to *s... |
Dynamically change __slots__ in Python 3 | 27,907,373 | 2 | 2015-01-12T17:18:40Z | 27,907,938 | 10 | 2015-01-12T17:52:22Z | [
"python",
"python-3.x",
"slots"
] | Suppose I have a class with `__slots__`
```
class A:
__slots__ = ['x']
a = A()
a.x = 1 # works fine
a.y = 1 # AttributeError (as expected)
```
Now I am going to change `__slots__` of `A`.
```
A.__slots__.append('y')
print(A.__slots__) # ['x', 'y']
b = A()
b.x = 1 # OK
b.y = 1 # AttributeError (why?)
`... | You cannot dynamically alter the `__slots__` attribute after creating the class, no. That's because the value is used to create special [*descriptors*](https://docs.python.org/3/reference/datamodel.html#descriptors) for each slot. From the [`__slots__` documentation](https://docs.python.org/3/reference/datamodel.html#n... |
Change an attribute of a function inside its own body? | 27,909,592 | 7 | 2015-01-12T19:45:53Z | 27,909,683 | 9 | 2015-01-12T19:51:52Z | [
"python",
"function",
"python-3.x",
"decorator"
] | I'm attempting to create a function that keeps count of the times it has been called, and I want the information to stay inside the function itself.
I tried creating a wrapper like so:
```
def keep_count(f):
f.count = 0
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
f(*args, **kwargs)
... | Just set the attribute on `wrapped_f` instead of `f`. This requires you to set the initial `count` after defining the function, but that's no big deal:
```
def keep_count(f):
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
f(*args, **kwargs)
wrapped_f.count += 1
wrapped_f.count = 0
... |
How can you slice with string keys instead of integers on a python OrderedDict? | 27,912,308 | 20 | 2015-01-12T23:07:37Z | 27,912,525 | 22 | 2015-01-12T23:25:46Z | [
"python",
"python-2.7",
"dictionary",
"python-internals",
"ordereddictionary"
] | Since an `OrderedDict` has the features of both a list (with ordered elements), and a dictionary (with keys instead of indexes), it would seem natural that you could slice using keys.
```
>>> from collections import OrderedDict
>>> cities = OrderedDict((('san francisco', 650), ('new york', 212), ('shanghai', 8621), ('... | `__getslice__` is deprecated way of implementing slicing. Instead you should handle `slice` objects with `__getitem__`:
```
from collections import OrderedDict
class SlicableDict(OrderedDict):
def __getitem__(self, key):
if isinstance(key, slice):
return 'potato({},{},{})'.format(key.start, ke... |
How can you slice with string keys instead of integers on a python OrderedDict? | 27,912,308 | 20 | 2015-01-12T23:07:37Z | 27,912,838 | 12 | 2015-01-12T23:57:07Z | [
"python",
"python-2.7",
"dictionary",
"python-internals",
"ordereddictionary"
] | Since an `OrderedDict` has the features of both a list (with ordered elements), and a dictionary (with keys instead of indexes), it would seem natural that you could slice using keys.
```
>>> from collections import OrderedDict
>>> cities = OrderedDict((('san francisco', 650), ('new york', 212), ('shanghai', 8621), ('... | This is the actual implementation of the slicing feature you are expecting.
`OrderedDict` internally maintains the order of the keys in the form of a doubly linked list. [Quoting the actual comment from Python 2.7.9](https://hg.python.org/cpython/file/648dcafa7e5f/Lib/collections.py#l33),
```
# The internal self.__ma... |
Geopy: catch timeout error | 27,914,648 | 7 | 2015-01-13T03:58:25Z | 27,914,845 | 8 | 2015-01-13T04:22:54Z | [
"python",
"scrapy",
"geopy"
] | I am using geopy to geocode some addresses and I want to catch the timeout errors and print them out so I can do some quality control on the input. I am putting the geocode request in a try/catch but it's not working. Any ideas on what I need to do?
Here is my code:
```
try:
location = geolocator.geocode(my_address... | Try this:
```
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut
my_address = '1600 Pennsylvania Avenue NW Washington, DC 20500'
geolocator = Nominatim()
try:
location = geolocator.geocode(my_address)
print location.latitude, location.longitude
except GeocoderTimedOut as e:
prin... |
How to setup different subdomains in Flask (using blueprints)? | 27,914,926 | 8 | 2015-01-13T04:31:50Z | 27,988,898 | 7 | 2015-01-16T16:54:49Z | [
"python",
"flask-restful",
"flask"
] | I have a Flask application running at <https://app.mydomain.com>.
The blueprints look like this:
```
app.register_blueprint(main)
app.register_blueprint(account, url_prefix='/account')
app.register_blueprint(users, url_prefix='/users')
app.register_blueprint(boxes, url_prefix='/boxes')
app.register_blueprint(api_1_0,... | Since you want your Flask application to handle multiple subdomains, you should set `app.config['SERVER_NAME']` to the root domain. Then apply `app` as the default subdomain and overriding it in `api` blueprint registration.
The way to do this would be something like that I suppose:
```
app.config['SERVER_NAME'] = 'm... |
Randomly select 0 or 1 equal number of times? | 27,922,948 | 3 | 2015-01-13T13:08:43Z | 27,922,989 | 9 | 2015-01-13T13:11:04Z | [
"python",
"random"
] | I want to iterate over 100 values and select randomly 0 or 1, but end up with equal numbers of 0's and 1's,
The code below prints the counts:
```
import random
c_true = 0
c_false = 0
for i in range(100):
a = random.getrandbits(1)
if a == 1:
c_true += 1
else:
c_false += 1
print "true_coun... | 1. Create `numbers` with 50 0's and 50 1's,
```
>>> numbers = [0, 1] * 50
```
2. Import [`shuffle` from `random`](https://docs.python.org/2/library/random.html#random.shuffle)
```
>>> from random import shuffle
```
3. `shuffle` them
```
>>> shuffle(numbers)
```
**Note:** `shuffle` shuffle... |
Selenium Element not visible exception | 27,927,964 | 15 | 2015-01-13T17:28:16Z | 27,931,726 | 16 | 2015-01-13T21:21:12Z | [
"python",
"selenium"
] | I have been tasked with writing a parser to click a button on a website and I am having issues to click only one of the buttons. The following code works on every button except one.
Here's the html:
<http://pastebin.com/6dLF5ru8>
here's the source html:
<http://pastebin.com/XhsedGLb>
python code:
```
driver = webd... | If you look at the page source, you'll understand that almost all of the`SELECT`, `DIV` elements are `faked` and created from JavaScript, that is why webdriver cannot **SEE** them.
There's a workaround though, by using `ActionChains` to open your developer console, and inject an **artificial** CLICK on the desired ele... |
Selenium Element not visible exception | 27,927,964 | 15 | 2015-01-13T17:28:16Z | 28,443,965 | 8 | 2015-02-10T23:37:08Z | [
"python",
"selenium"
] | I have been tasked with writing a parser to click a button on a website and I am having issues to click only one of the buttons. The following code works on every button except one.
Here's the html:
<http://pastebin.com/6dLF5ru8>
here's the source html:
<http://pastebin.com/XhsedGLb>
python code:
```
driver = webd... | What worked for me was to find the element just before the problematic one (that is, just before it in terms of tab order), then call Tab on that element.
```
from selenium.webdriver.common.keys import Keys
elem = br.find_element_by_name("username")
elem.send_keys(Keys.TAB) # tab over to not-visible element
```
After... |
Find p-value (significance) in scikit-learn LinearRegression | 27,928,275 | 13 | 2015-01-13T17:46:13Z | 27,928,411 | 9 | 2015-01-13T17:54:43Z | [
"python",
"numpy",
"statistics",
"scikit-learn",
"regression"
] | How can I find the p-value (significance) of each coefficient?
```
lm = sklearn.linear_model.LinearRegression()
lm.fit(x,y)
``` | scikit-learn's LinearRegression doesn't calculate this information but you can easily extend the class to do it:
```
from sklearn import linear_model
from scipy import stats
import numpy as np
class LinearRegression(linear_model.LinearRegression):
"""
LinearRegression class after sklearn's, but calculate t-s... |
dir inside function | 27,931,539 | 2 | 2015-01-13T21:08:54Z | 27,931,578 | 7 | 2015-01-13T21:11:19Z | [
"python",
"scope"
] | Python has a nice feature that gives the contents of an object, like all of it's methods and existing variables, called `dir()`. However when dir is called in a function it only looks at the scope of the function. So then calling `dir()` in a function has a different value than calling it outside of one. For example:
... | `dir()` *without an argument* defaults to the current scope (the keys of `locals()`, but sorted). If you wanted a different scope, you'd have to pass in an object. From the [documentation](https://docs.python.org/2/library/functions.html#dir):
> Without arguments, return the list of names in the current local scope. W... |
Encoding Problems when running an app in docker (Python, Java, Ruby, ...) with Ubuntu Containers (ascii, utf-8) | 27,931,668 | 5 | 2015-01-13T21:16:48Z | 27,931,669 | 10 | 2015-01-13T21:16:48Z | [
"java",
"python",
"ruby",
"docker",
"locale"
] | On my own PC the application runs nice, but when it gets deployed into docker, it fails because of invalid characters.
I am using the `ubuntu:lastest` container and `python3`, `java` and `ruby`. | You need to set the **locale** correct.
This is the minimal correct Dockerfile:
```
FROM ubuntu:lastest
RUN locale-gen en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
```
The usual docker images don't specify a locales. You see it if you bash into it and execute `locale`:
```
su... |
Saml2 Service Provider in Python | 27,932,899 | 7 | 2015-01-13T22:46:31Z | 27,955,657 | 13 | 2015-01-15T01:55:45Z | [
"python",
"flask",
"saml",
"saml-2.0"
] | I am looking to implement a Saml2 based service provider in python.
My web apps are currently all Flask applications. I plan to make a Flask blueprint/decorator that allows me to drop single sign-on capabilities into pre existing applications.
I have looked into [python-saml](https://github.com/onelogin/python-saml) ... | *Update: A detailed explanation on [using PySAML2 with Okta](http://developer.okta.com/docs/examples/pysaml2.html) is now on developer.okta.com.*
Below is some sample code for implementing a SAML SP in Python/Flask. This sample code demonstrates several things:
1. Supporting multiple IdPs.
2. Using [Flask-Login](http... |
Get current user in Model Serializer | 27,934,822 | 8 | 2015-01-14T02:16:42Z | 27,934,823 | 13 | 2015-01-14T02:16:42Z | [
"python",
"django",
"serialization",
"django-rest-framework"
] | Is it possible to get the current user in a model serializer? I'd like to do so without having to branch away from generics, as it's an otherwise simple task that must be done.
My model:
```
class Activity(models.Model):
number = models.PositiveIntegerField(
blank=True, null=True, help_text="Activity numb... | I found the answer through the Djangorestframework source code.
```
class ActivitySerializer(serializers.ModelSerializer):
# Create a custom method field
current_user = serializers.SerializerMethodField('_user')
# Use this method for the custom field
def _user(self, obj):
user = self.context[... |
Get current user in Model Serializer | 27,934,822 | 8 | 2015-01-14T02:16:42Z | 31,745,371 | 7 | 2015-07-31T11:44:09Z | [
"python",
"django",
"serialization",
"django-rest-framework"
] | Is it possible to get the current user in a model serializer? I'd like to do so without having to branch away from generics, as it's an otherwise simple task that must be done.
My model:
```
class Activity(models.Model):
number = models.PositiveIntegerField(
blank=True, null=True, help_text="Activity numb... | A context is passed to the serializer in REST framework, which contains the request by default. So you can just use `self.context['request'].user` inside your serializer. |
Dynamically exclude or include a field in Django REST framework serializer | 27,935,558 | 12 | 2015-01-14T03:47:17Z | 27,936,077 | 22 | 2015-01-14T04:50:54Z | [
"python",
"django",
"serialization",
"django-rest-framework",
"django-serializer"
] | I have a serializer in Django REST framework defined as follows:
```
class QuestionSerializer(serializers.Serializer):
id = serializers.CharField()
question_text = QuestionTextSerializer()
topic = TopicSerializer()
```
Now I have two API views that use the above serializer:
```
class QuestionWithTopicVie... | Have you tried this technique
```
class QuestionSerializer(serializers.Serializer):
def __init__(self, *args, **kwargs):
remove_fields = kwargs.pop('remove_fields', None)
super(QuestionSerializer, self).__init__(*args, **kwargs)
if remove_fields:
# for multiple fields in a list... |
Flask - access the request in after_request or teardown_request | 27,938,818 | 5 | 2015-01-14T08:45:23Z | 27,939,619 | 7 | 2015-01-14T09:30:53Z | [
"python",
"flask",
"flask-restful"
] | I want to be able to access the request object before I return the response of the HTTP call.
I want access to the request via "teardown\_request" and "after\_request":
```
from flask import Flask
...
app = Flask(__name__, instance_relative_config=True)
...
@app.before_request
def before_request():
# do something... | The solution is simple -
```
from flask import request
@app.after_request
def after_request(response):
do_something_based_on_the_request_endpoint(request)
``` |
Reproduce uuid from java code in python | 27,939,281 | 3 | 2015-01-14T09:14:37Z | 27,939,485 | 7 | 2015-01-14T09:25:25Z | [
"java",
"python",
"uuid"
] | In a Java application files are created where the filename is a UUID generated from a protein sequence (e.g. TTCCPSIVARSNFNVCRLPGTPEAICATYTGCIIIPGATCPGDYAN) created using the function `UUID.nameUUIDFromBytes`. This results in the UUID `c6a0deb5-0c4f-3961-9d19-3f0fde0517c2`.
`UUID.namedUUIDFromBytes` doesn't take a nam... | [`nameUUIDFromBytes`](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/UUID.java#UUID.nameUUIDFromBytes%28byte%5B%5D%29) only takes one parameter, which is supposed to be the concatenation of the namespace and name just like you say. The namespace parameter is supposed to be a `UUI... |
Using WN-Affect to detect emotion/mood of a string | 27,943,396 | 6 | 2015-01-14T12:51:31Z | 27,945,838 | 9 | 2015-01-14T14:57:12Z | [
"python",
"nlp",
"nltk",
"wordnet"
] | I downloaded [WN-Affect](http://wndomains.fbk.eu/wnaffect.html). I am however not sure how to use it to detect the mood of a sentence. For example if I have a string "I hate football." I want to be able to detect whether the mood is bad and the emotion is fear. WN-Affect has no tutorial on how to do it, and I am kind o... | **In short**: Use SentiWordNet instead and look at <https://github.com/kevincobain2000/sentiment_classifier>
---
**In Long**:
**Affectedness vs Sentiment**
The line between affect and sentiment is very fine. One should looking into `Affectedness` in linguistics studies, e.g. <http://compling.hss.ntu.edu.sg/events/2... |
How to limit scrapy request objects? | 27,943,970 | 2 | 2015-01-14T13:21:55Z | 27,960,127 | 8 | 2015-01-15T09:19:16Z | [
"python",
"web-scraping",
"scrapy",
"web-crawler",
"bots"
] | So I have a spider that I thought was leaking memory, turns out it is just grabbing too many links from link rich pages (sometimes it puts upwards of 100,000) when I check the telnet console >>> prefs()
Now I have been over the docs and google again and again and I can't find a way to limit the requests that the spide... | I solved my problem, the answer was really hard to track down so I posted it here in case anyone else comes across the same problem.
After sifting through scrapy code and referring back to the docs, I could see that scrapy kept all requests in memory, I already deduced that, but in the code there is also some checks t... |
more pythonic version of list iteration function | 27,945,192 | 4 | 2015-01-14T14:25:41Z | 27,945,219 | 28 | 2015-01-14T14:26:55Z | [
"python",
"list",
"list-comprehension"
] | Is there a more Pythonic way of defining this function?
```
def idsToElements(ids):
elements = []
for i in ids:
elements.append(doc.GetElement(i))
return elements
```
Maybe its possible with list comprehension. I am basically looking to take a list of ids and change them to a list of elements in s... | If a list comprehension is all that you wanted
```
def idsToElements(ids):
return [doc.GetElement(i) for i in ids ]
``` |
more pythonic version of list iteration function | 27,945,192 | 4 | 2015-01-14T14:25:41Z | 27,945,226 | 14 | 2015-01-14T14:27:05Z | [
"python",
"list",
"list-comprehension"
] | Is there a more Pythonic way of defining this function?
```
def idsToElements(ids):
elements = []
for i in ids:
elements.append(doc.GetElement(i))
return elements
```
Maybe its possible with list comprehension. I am basically looking to take a list of ids and change them to a list of elements in s... | [`map()`](https://docs.python.org/2/library/functions.html#map) is a Python built-in which does exactly what you want.
```
def idsToElements(ids):
return map(doc.GetElement, ids)
```
The use of `map()` vs the use of list-comprehensions is discussed [here](http://stackoverflow.com/questions/1247486/python-list-com... |
How to manage division of huge numbers in Python? | 27,946,595 | 2 | 2015-01-14T15:32:29Z | 27,946,741 | 16 | 2015-01-14T15:38:54Z | [
"python",
"division"
] | I have a 100 digit number and I am trying to put all the digits of the number into a list, so that I can perform operations on them. To do this, I am using the following code:
```
for x in range (0, 1000):
list[x] = number % 10
number = number / 10
```
But the problem I am facing is that I am getting an overflo... | In Python 3, `number / 10` will return try to return a `float`. However, floating point values can't be of arbitrarily large size in Python and if `number` is large an `OverflowError` will be raised.
You can find the maximum that Python floating point values can take on your system using the `sys` module:
```
>>> imp... |
How to properly create a pyinstaller hook, or maybe hidden import? | 27,947,639 | 8 | 2015-01-14T16:20:58Z | 28,023,347 | 11 | 2015-01-19T11:15:07Z | [
"python",
"pyinstaller"
] | I have to packages (say, `dataread` and `datainspector`) that somehow not get detected by PyInstaller. Because of this, the application will terminated when the running application reach the point where it needs to import modules from those packages.
The easiest solution would be to copy `dataread` and `datainspector`... | Hooks are files that specify additional actions when pyinstaller finds import statement. So if you add "hook-data.py" file with `hiddenimports = ['_proxy', 'utils', 'defs']` inside if pyinstaller will find `import data` it will check for additional commands inside `hook-data.py` file. You have to specify path to hooks ... |
How can I write unit tests against code that uses matplotlib? | 27,948,126 | 12 | 2015-01-14T16:44:50Z | 27,950,953 | 11 | 2015-01-14T19:32:29Z | [
"python",
"matplotlib",
"python-unittest"
] | I'm working on a python (2.7) program that produce a lot of different matplotlib figure (the data are not random). I'm willing to implement some test (using unittest) to be sure that the generated figures are correct. For instance, I store the expected figure (data or image) in some place, I run my function and compare... | In my [experience](http://stanford.edu/~mwaskom/software/seaborn/), image comparison tests end up bring more trouble than they are worth. This is especially the case if you want to run continuous integration across multiple systems (like TravisCI) that may have slightly different fonts or available drawing backends. It... |
How to write __getitem__ cleanly? | 27,954,297 | 15 | 2015-01-12T03:30:36Z | 27,954,298 | 12 | 2015-01-14T21:36:32Z | [
"python",
"python-3.x"
] | In Python, when implementing a sequence type, I often (relatively speaking) find myself writing code like this:
```
class FooSequence(collections.abc.Sequence):
# Snip other methods
def __getitem__(self, key):
if isinstance(key, int):
# Get a single item
elif isinstance(key, slice)... | As much as it seems odd, I suspect that the way you have it is the best way to go about things. Patterns generally exist to encompass common use cases, but that doesn't mean that they should be taken as gospel when following them makes life more difficult. The main reason that PEP 443 gives for balking at explicit type... |
"Never invent such names; only use them as documented." Who? | 27,965,088 | 7 | 2015-01-15T14:00:10Z | 27,965,109 | 10 | 2015-01-15T14:01:19Z | [
"python",
"naming-conventions",
"terminology",
"pep8"
] | I read [PEP 8](https://www.python.org/dev/peps/pep-0008/#naming-conventions) for to know whether (an imaginary) me creating an object with a name such as `__foo__` is a good idea or not. PEP 8 says this about `__double_leading_and_trailing_underscore__`:
> Never invent such names; only use them as documented.
My ques... | You are discouraged from using such names in your APIs, yes, because if and when the *Python core developers* pick the same name for Python itself, you'll lose out, your API can break.
So, if you are not a Python core developer or writing a PEP that may be one day become part of the Python standard library or core lan... |
Communication between OCaml and Python | 27,965,967 | 4 | 2015-01-15T14:44:48Z | 27,966,451 | 8 | 2015-01-15T15:07:25Z | [
"python",
"ocaml"
] | I would like to know the best way to send data from OCaml to Python and get response from Python back to OCaml.
One naive method I can think is as follows.
1) In OCaml, write data into a file (input.txt) on file system.
2) In OCaml, run python, which opens input.txt and reads the data and write the execution result ... | This is a general question on how to talk between two programs, written in different languages. Actually, the problem should be further subdivided into two separate subproblems:
1. What transport to use? (file, socket, etc)
2. How to serialize and deserialize data.
The first question is very general. You can use sock... |
how to clear/delete the Textbox in tkinter python on Ubuntu | 27,966,626 | 3 | 2015-01-15T15:15:27Z | 27,967,664 | 12 | 2015-01-15T16:01:53Z | [
"python",
"ubuntu",
"tkinter",
"textbox"
] | I am writing a program in TKinter Python on Ubuntu, to import and print the name of files from particular folder in TEXTBOX.
It is just adding filenames to the previous filnames in the TEXTBOX, I want to clear it first then add only fresh list of filenames.
But I am struggling in clearing the TEXTBOX (Previous list of ... | I checked on my side by just adding '1.0' and it start working
```
tex.delete('1.0', END)
```
you can also try this |
Find min value in array > 0 | 27,966,757 | 4 | 2015-01-15T15:21:53Z | 27,966,830 | 10 | 2015-01-15T15:24:41Z | [
"python",
"list",
"search",
"min"
] | I am looking to find the lowest positive value in an array and its position in the list. If a value within the list is duplicated, only the FIRST instance is of interest. This is what I have which does what I want but includes 0.
```
print "Position:", myArray.index(min(myArray))
print "Value:", min(myArray)
```
for ... | You can use a [generator expression](https://wiki.python.org/moin/Generators) with `min`. This will set `m` as the minimum value in `a` that is greater than 0. It then uses `list.index` to find the index of the first time this value appears.
```
a = [4, 8, 0, 1, 5]
m = min(i for i in a if i > 0)
print("Position:", a... |
Pythonic sort a list of dictionaries in a tricky order | 27,967,496 | 3 | 2015-01-15T15:54:46Z | 27,967,639 | 9 | 2015-01-15T16:00:43Z | [
"python",
"list",
"sorting",
"dictionary"
] | I have a list of id's sorted in a proper oder:
```
ids = [1, 2, 4, 6, 5, 0, 3]
```
I also have a list of dictionaries, sorted in some random way:
```
rez = [{'val': 7, 'id': 1}, {'val': 8, 'id': 2}, {'val': 2, 'id': 3}, {'val': 0, 'id': 4}, {'val': -1, 'id': 5}, {'val': -4, 'id': 6}, {'val': 9, 'id': 0}]
```
My int... | You don't need to `sort` because `ids` specifies the entire ordering of the result. You just need to pick the correct elements by their ids:
```
rez_dict = {d['id']:d for d in rez}
rez_ordered = [rez_dict[id] for id in ids]
```
Which gives:
```
>>> rez_ordered
[{'id': 1, 'val': 7}, {'id': 2, 'val': 8}, {'id': 4, 'va... |
How do I resolve Django AllAuth - 'Connection aborted.', error(13, 'Permission denied') Error? | 27,974,128 | 7 | 2015-01-15T22:24:25Z | 27,986,163 | 15 | 2015-01-16T14:29:42Z | [
"python",
"django",
"google-app-engine",
"permission-denied",
"django-allauth"
] | I'm trying to resolve a connection error thrown by AllAuth/Django 1.7 running on Google App Engine:
I believe the error may be in the Sessions configuration but I've not been able to identify the problem.
Local signup is functioning correctly, but social logins throw an error.
**edit:** LinkedIn works fine.
**edit:**... | After doing some research, it seems AppEngine's problems were related to my installed version of *requests*.
I resolved this by `pip uninstall requests` (2.5.1), then `pip install requests==2.3`.
[Source](https://github.com/shazow/urllib3/issues/446) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.