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 to cache reads? | 34,302,597 | 14 | 2015-12-16T01:37:03Z | 34,661,090 | 8 | 2016-01-07T17:06:10Z | [
"python",
"caching",
"samtools",
"pysam",
"bam"
] | I am using python/pysam to do analyze sequencing data. In its tutorial ([pysam - An interface for reading and writing SAM files](http://pysam.readthedocs.org/en/latest/api.html#pysam.AlignmentFile.mate)) for the command mate it says:
'This method is too slow for high-throughput processing. If a read needs to be proces... | [Caching](https://en.wikipedia.org/wiki/Memoization) is a typical approach to speed up long running operations. It sacrifices memory for the sake of computational speed.
Let's suppose you have a function which given a set of parameters always returns the same result. Unfortunately this function is very slow and you ne... |
Beautiful soup meta content tag | 34,302,774 | 2 | 2015-12-16T02:00:37Z | 34,302,789 | 8 | 2015-12-16T02:03:13Z | [
"python",
"html",
"beautifulsoup",
"html-parsing"
] | ```
<meta itemprop="streetAddress" content="4103 Beach Bluff Rd">
```
I have to get the content '4103 Beach Bluff Rd'. I'm trying to get this done with `BeautifulSoup` so, I'm trying this:
```
soup = BeautifulSoup('<meta itemprop="streetAddress" content="4103 Beach Bluff Rd"> ')
soup.find(itemprop="streetAddress").g... | > `soup.find(itemprop="streetAddress").get_text()`
You are getting the text of a matched element. Instead, *get the "content" attribute value*:
```
soup.find(itemprop="streetAddress").get("content")
```
---
This is possible since `BeautifulSoup` provides a [dictionary-like interface to tag attributes](http://www.cr... |
"Failed building wheel for psycopg2" - MacOSX using virtualenv and pip | 34,304,833 | 12 | 2015-12-16T05:52:31Z | 34,841,594 | 20 | 2016-01-17T17:52:17Z | [
"python",
"django",
"postgresql",
"virtualenv",
"psycopg2"
] | I'm attempting to make a website with a few others for the first time, and have run into a weird error when trying to use Django/Python/VirtualEnv. I've found solutions to this problem for other operating systems, such as Ubuntu, but can't find any good solutions for Mac.
This is the relevant code being run:
```
virt... | I had the same problem on Arch linux. I think that it's not an OS dependant problem. Anyway, I fixed this by finding the outdated packages and updating then.
```
pip uninstall psycopg2
pip list --outdated
pip install --upgrade wheel
pip install --upgrade setuptools
pip install psycopg2
```
hope this helps... |
Is the python "elif" compiled differently from else: if? | 34,304,936 | 5 | 2015-12-16T06:01:24Z | 34,305,041 | 11 | 2015-12-16T06:09:49Z | [
"java",
"python",
"c++",
"if-statement",
"micro-optimization"
] | I know in languages such as C, C++, Java and C#, ([C# example](http://stackoverflow.com/questions/3374909/do-else-if-statements-exist-in-c))the `else if` statement is syntactic sugar, in that it's really just a one `else` statement followed by an `if` statement.
```
else if (conition(s)) { ...
```
is equal to
```
el... | When you really want to know what is going on behind the scenes in the interpreter, you can use the `dis` module. In this case:
```
>>> def f1():
... if a:
... b = 1
... elif aa:
... b = 2
...
>>> def f2():
... if a:
... b = 1
... else:
... if aa:
... b = 2
...
>>> dis.dis(f1)
2 ... |
Unpack list to variables | 34,308,337 | 4 | 2015-12-16T09:32:26Z | 34,308,407 | 8 | 2015-12-16T09:35:26Z | [
"python",
"list"
] | I have a list:
```
row = ["Title", "url", 33, "title2", "keyword"]
```
Is there a more pythonic way to unpack this values like:
```
title, url, price, title2, keyword = row[0], row[1], row[2], row[3], row[4]
``` | Something like this ?
```
>>> row = ["Title", "url", 33, "title2", "keyword"]
>>> title, url, price, title2, keyword = row
```
Also and for the record, note that your example will fail with an IndexError (Python's lists are zero-based).
*EDIT : the above note was written before the OP example was fixed...* |
How can I train a simple, non-linear regression model with tensor flow? | 34,311,893 | 6 | 2015-12-16T12:20:20Z | 34,316,689 | 7 | 2015-12-16T16:04:16Z | [
"python",
"regression",
"tensorflow"
] | I've seen [this example for linear regression](https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/2%20-%20Basic%20Classifiers/linear_regression.ipynb) and I would like to train a model
[](http://i.stack.imgur.com/SsHgX.png)
whe... | The `InvalidArgumentError` is due to the values that you are feeding (`train_X` and `train_Y`) not having the necessary shape to be multiplied by `W1`.
There are a few issues here:
1. The statement `mul = X * W1` should be `mul = tf.matmul(X, W1)`, since `*` computes an elementwise multiplication, which is not what y... |
Why values of an OrderedDict are not equal? | 34,312,674 | 43 | 2015-12-16T12:55:32Z | 34,312,883 | 22 | 2015-12-16T13:05:41Z | [
"python",
"python-3.x"
] | With Python 3:
```
>>> from collections import OrderedDict
>>> d1 = OrderedDict([('foo', 'bar')])
>>> d2 = OrderedDict([('foo', 'bar')])
```
I want to check equality:
```
>>> d1 == d2
True
>>> d1.keys() == d2.keys()
True
```
But:
```
>>> d1.values() == d2.values()
False
```
Do you know why values are not equal?
... | In python3, `d1.values()` and `d2.values()` are `collections.abc.ValuesView` objects:
```
>>> d1.values()
ValuesView(OrderedDict([('foo', 'bar')]))
```
Don't compare them as an object, c
onvert them to lists and then compare them:
```
>>> list(d1.values()) == list(d2.values())
True
```
---
Investigating why it wor... |
Why values of an OrderedDict are not equal? | 34,312,674 | 43 | 2015-12-16T12:55:32Z | 34,312,962 | 34 | 2015-12-16T13:09:48Z | [
"python",
"python-3.x"
] | With Python 3:
```
>>> from collections import OrderedDict
>>> d1 = OrderedDict([('foo', 'bar')])
>>> d2 = OrderedDict([('foo', 'bar')])
```
I want to check equality:
```
>>> d1 == d2
True
>>> d1.keys() == d2.keys()
True
```
But:
```
>>> d1.values() == d2.values()
False
```
Do you know why values are not equal?
... | In Python 3, `dict.keys()` and `dict.values()` return special iterable classes - respectively a `collections.abc.KeysView` and a `collections.abc.ValuesView`. The first one inherit it's `__eq__` method from `set`, the second uses the default `object.__eq__` which tests on object identity. |
Indexing a list with an unique index | 34,313,761 | 24 | 2015-12-16T13:48:35Z | 34,313,968 | 33 | 2015-12-16T13:58:09Z | [
"python",
"list",
"indexing"
] | I have a list say `l = [10,10,20,15,10,20]`. I want to assign each unique value a certain "index" to get `[1,1,2,3,1,2]`.
This is my code:
```
a = list(set(l))
res = [a.index(x) for x in l]
```
Which turns out to be very slow.
`l` has 1M elements, and 100K unique elements. I have also tried map with lambda and sort... | You can do this in `O(N)` time using a [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) and a list comprehension:
```
>>> from itertools import count
>>> from collections import defaultdict
>>> lst = [10, 10, 20, 15, 10, 20]
>>> d = defaultdict(count(1).next)
>>> [d[k] for k ... |
Indexing a list with an unique index | 34,313,761 | 24 | 2015-12-16T13:48:35Z | 34,314,042 | 21 | 2015-12-16T14:01:48Z | [
"python",
"list",
"indexing"
] | I have a list say `l = [10,10,20,15,10,20]`. I want to assign each unique value a certain "index" to get `[1,1,2,3,1,2]`.
This is my code:
```
a = list(set(l))
res = [a.index(x) for x in l]
```
Which turns out to be very slow.
`l` has 1M elements, and 100K unique elements. I have also tried map with lambda and sort... | The slowness of your code arises because `a.index(x)` performs a linear search and you perform that linear search for each of the elements in `l`. So for each of the 1M items you perform (up to) 100K comparisons.
The fastest way to transform one value to another is looking it up in a map. You'll need to create the map... |
How to print flag descriptions in Tensorflow? | 34,314,455 | 2 | 2015-12-16T14:22:13Z | 34,316,117 | 7 | 2015-12-16T15:38:44Z | [
"python",
"tensorflow"
] | Google has many examples that use flags. They all have descriptions in the definition. Is there a way I can print these descriptions out to the terminal?
```
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_boolean('test_mode', False, 'This is the description I want A.')
flags.DEFINE_boolean('cool_mode', True, 'T... | The `flags` module used in TensorFlow is a wrapper around the [`python-gflags` module](https://github.com/google/python-gflags). To see a list of all flags used in a Python application using `python-gflags`, you can run it with the `-h` or `--help` flag. For example:
```
$ tensorboard -h
usage: tensorboard [-h] [--log... |
Python nested range function | 34,315,140 | 2 | 2015-12-16T14:52:22Z | 34,315,175 | 7 | 2015-12-16T14:53:56Z | [
"python",
"range"
] | What is the output of the following nested control structure in Python when executed?
```
for x in range(3):
for y in range(x):
print x,y
```
I know the answer is
```
1 0
2 0
2 1
```
But it is not clear for me why it is this output.
I know that the range(3) function would give you {0, 1, 2} so why is ... | Because range(0) returns an empty list `[]`, so the inner loop does nothing the first time it is run. |
Python nested range function | 34,315,140 | 2 | 2015-12-16T14:52:22Z | 34,315,231 | 7 | 2015-12-16T14:57:08Z | [
"python",
"range"
] | What is the output of the following nested control structure in Python when executed?
```
for x in range(3):
for y in range(x):
print x,y
```
I know the answer is
```
1 0
2 0
2 1
```
But it is not clear for me why it is this output.
I know that the range(3) function would give you {0, 1, 2} so why is ... | Lets go through this
**First run**
```
x = 0
range(0) is []
the print is never reached
```
**Second Run**
```
x = 1
range(1) is [0] <-- one element
print is called once with 1 0
```
**Third Run**
```
x = 2
range(2) is [0,1] <-- two elements
print is called twice with 2 0 and 2 1
``` |
Python re can't split zero-width anchors? | 34,317,442 | 6 | 2015-12-16T16:41:49Z | 34,317,471 | 7 | 2015-12-16T16:43:18Z | [
"python",
"regex"
] | ```
import re
s = 'PythonCookbookListOfContents'
# the first line does not work
print re.split('(?<=[a-z])(?=[A-Z])', s )
# second line works well
print re.sub('(?<=[a-z])(?=[A-Z])', ' ', s)
# it should be ['Python', 'Cookbook', 'List', 'Of', 'Contents']
```
How to split a string from the border of a lower case c... | According to [`re.split`](https://docs.python.org/2/library/re.html#re.split):
> Note that split will never split a string on an empty pattern match.
> For example:
>
> ```
> >>> re.split('x*', 'foo')
> ['foo']
> >>> re.split("(?m)^$", "foo\n\nbar\n")
> ['foo\n\nbar\n']
> ```
---
How about using [`re.findall`](https... |
Create dictionary from splitted strings from list of strings | 34,319,156 | 9 | 2015-12-16T18:09:33Z | 34,319,180 | 15 | 2015-12-16T18:11:05Z | [
"python",
"dictionary",
"split",
"list-comprehension",
"string-split"
] | I feel that this is very simple and I'm close to solution, but I got stacked, and can't find suggestion in the Internet.
I have list that looks like:
```
my_list = ['name1@1111', 'name2@2222', 'name3@3333']
```
In general, each element of the list has the form: `namex@some_number`.
I want to make dictionary in pr... | You actually don't need the extra step of creating the tuple
```
>>> my_list = ['name1@1111', 'name2@2222', 'name3@3333']
>>> dict(i.split('@') for i in my_list)
{'name3': '3333', 'name1': '1111', 'name2': '2222'}
``` |
Can you do sums with a datetime in Python? | 34,321,209 | 6 | 2015-12-16T20:12:55Z | 34,321,276 | 7 | 2015-12-16T20:17:01Z | [
"python",
"python-3.x"
] | I know how to get the date:
```
from datetime import datetime
time = datetime.now()
print(time)
```
But is there a way where you can work out the days/hours until a certain date, maybe storing the date as an integer or something? Thx for all answers | Just create another datetime object and subtract which will give you a [timedelta](https://docs.python.org/3.5/library/datetime.html#datetime.timedelta) object.
```
from datetime import datetime
now = datetime.now()
then = datetime(2016,1,1,0,0,0)
diff = then - now
print(diff)
print(diff.total_seconds())
15 days, 3:... |
SubfieldBase has been deprecated. Use Field.from_db_value instead | 34,321,332 | 3 | 2015-12-16T20:20:21Z | 34,537,893 | 9 | 2015-12-30T22:00:48Z | [
"python",
"django"
] | ```
/python3.4/site-packages/django/db/models/fields/subclassing.py:22: RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead.
RemovedInDjango110Warning)
```
Since I upgraded to Django 1.9 I started having this warning on `runserver` startup. The problem is that I have no idea ... | I experienced this error while using `python-social-auth 0.2.13`. If you are using `python-social-auth`, I submitted a fix for this on [GitHub](https://github.com/omab/python-social-auth/pull/813), just now. This extends another fix submitted [here](https://github.com/omab/python-social-auth/pull/806).
Subscribe to bo... |
SQLAlchemy: engine, connection and session difference | 34,322,471 | 6 | 2015-12-16T21:29:31Z | 34,364,247 | 10 | 2015-12-18T21:32:15Z | [
"python",
"session",
"orm",
"sqlalchemy",
"psycopg2"
] | I use SQLAlchemy and there are at least three entities: `engine`, `session` and `connection`, which have `execute` method, so if I e.g. want to select all records from `table` I can do this
```
engine.execute(select([table])).fetchall()
```
and this
```
connection.execute(select([table])).fetchall()
```
and even th... | **A one-line overview:**
The behavior of `execute()` is same in all the cases, but they are 3 different methods, in `Engine`, `Connection`, and `Session` classes.
**What exactly is `execute()`:**
To understand behavior of `execute()` we need to look into the `Executable` class. `Executable` is a superclass for all â... |
Programming language with multiple roots | 34,322,604 | 2 | 2015-12-16T21:39:29Z | 34,324,155 | 7 | 2015-12-16T23:32:16Z | [
"python",
"programming-languages",
"octave",
"julia-lang",
"complex-numbers"
] | The answer to 2^(-1/3) are three roots:
0.79370, -0.39685-0.68736i and 0.39685+0.68736i (approximately)
See the correct answer at [Wolfram Alpha](http://www.wolframalpha.com/input/?i=2%5E%28-1%2F3%29).
I know several languages that supports complex numbers, but they all only return the first of the three results:
P... | As many comments explained, wanting a general purpose language to give by default the result from every branch of the complex root function is probably a tall order. But **Julia** allows specializing/overloading operators very naturally (as even the out-of-the-box implementation is often written in Julia). Specifically... |
can't terminate a sudo process created with python, in Ubuntu 15.10 | 34,337,840 | 4 | 2015-12-17T15:08:36Z | 34,376,188 | 7 | 2015-12-19T22:47:04Z | [
"python",
"ubuntu",
"subprocess",
"sudo",
"ubuntu-15.10"
] | I just updated to Ubuntu 15.10 and suddenly in Python 2.7 I am not able to **terminate** a process I created when being **root**.
For example, this doesn't terminate tcpdump:
```
import subprocess, shlex, time
tcpdump_command = "sudo tcpdump -w example.pcap -i eth0 -n icmp"
tcpdump_process = subprocess.Popen(
... | **TL;DR**: `sudo` does not forward signals sent by a process in the command's process group [since 28 May 2014 commit](https://www.sudo.ws/repos/sudo/rev/7ffa2eefd3c0) released in `sudo 1.8.11` -- the python process (sudo's parent) and the tcpdump process (grandchild) are in the same process group by default and theref... |
Pickle python lasagne model | 34,338,838 | 7 | 2015-12-17T15:54:56Z | 34,345,432 | 9 | 2015-12-17T22:24:46Z | [
"python",
"lasagne"
] | I have trained a simple lstm model in lasagne following the recipie here:<https://github.com/Lasagne/Recipes/blob/master/examples/lstm_text_generation.py>
Here is the architecture:
l\_in = lasagne.layers.InputLayer(shape=(None, None, vocab\_size))
```
# We now build the LSTM layer which takes l_in as the input layer... | You can save the weights with numpy:
```
np.savez('model.npz', *lasagne.layers.get_all_param_values(network_output))
```
And load them again later on like this:
```
with np.load('model.npz') as f:
param_values = [f['arr_%d' % i] for i in range(len(f.files))]
lasagne.layers.set_all_param_values(network_output, p... |
Tensorflow read images with labels | 34,340,489 | 18 | 2015-12-17T17:14:59Z | 34,345,827 | 14 | 2015-12-17T22:54:53Z | [
"python",
"tensorflow"
] | I am building a standard image classification model with Tensorflow. For this I have input images, each assigned with a label (number in {0,1}). The Data can hence be stored in a list using the following format:
```
/path/to/image_0 label_0
/path/to/image_1 label_1
/path/to/image_2 label_2
...
```
I want to use Tenso... | There are three main steps to solving this problem:
1. Populate the [`tf.train.string_input_producer()`](https://www.tensorflow.org/versions/master/api_docs/python/io_ops.html#string_input_producer) with a list of strings containing the original, space-delimited string containing the filename and the label.
2. Use [`t... |
Tensorflow read images with labels | 34,340,489 | 18 | 2015-12-17T17:14:59Z | 36,947,632 | 11 | 2016-04-29T21:20:28Z | [
"python",
"tensorflow"
] | I am building a standard image classification model with Tensorflow. For this I have input images, each assigned with a label (number in {0,1}). The Data can hence be stored in a list using the following format:
```
/path/to/image_0 label_0
/path/to/image_1 label_1
/path/to/image_2 label_2
...
```
I want to use Tenso... | Using `slice_input_producer` provides a solution which is much cleaner. Slice Input Producer allows us to create an Input Queue containing arbitrarily many separable values. This snippet of the question would look like this:
```
def read_labeled_image_list(image_list_file):
"""Reads a .txt file containing pathes a... |
Convert elements in a list using a dictionary key | 34,341,833 | 3 | 2015-12-17T18:34:38Z | 34,341,876 | 8 | 2015-12-17T18:37:05Z | [
"python",
"list",
"dictionary"
] | I have a list of `values` that match with certain `keys` from a dictionary I created earlier.
```
myDict = {1:'A',2:'B',3:'C'}
myList = ['A','A','A','B','B','A','C','C']
```
How can I create/convert `myList` into something like:
```
myNewList = [1,1,1,2,2,1,3,3]
```
Could someone point me in the right direction?
N... | One easy way is to just invert `myDict` and then use that to map the new list:
```
myNewDict = {v: k for k, v in myDict.iteritems()}
myNewList = [myNewDict[x] for x in myList]
```
Also take a look at this for Python naming conventions: [What is the naming convention in Python for variable and function names?](http://... |
SQL BETWEEN command not working for large ranges | 34,348,390 | 5 | 2015-12-18T04:08:45Z | 34,348,426 | 8 | 2015-12-18T04:13:09Z | [
"python",
"sql",
"sql-azure",
"pyodbc"
] | The SQL command BETWEEN only works when I give it a small range for column.
Here is what I mean:
My code:
```
import AzureSQLHandler as sql
database_layer = sql.AzureSQLHandler()
RESULTS_TABLE_NAME = "aero2.ResultDataTable"
where_string = " smog BETWEEN '4' AND '9'"
print database_layer.select_data(RESULTS_TABLE_NA... | Strings in databases are compared alphabetically. A string `'4.0'` is greater than a string `'200.0'` because character `4` comes after character `2`. You should use numeric type in your database if you need to support this kind of queries. Make sure that `smog` column has a numeric type (such as DOUBLE) and use `BETWE... |
Error loading MySQLdb module: libmysqlclient.so.20: cannot open shared object file: No such file or directory | 34,348,752 | 8 | 2015-12-18T04:53:19Z | 34,348,823 | 7 | 2015-12-18T05:02:06Z | [
"python",
"mysql",
"django"
] | I had a running django project and for some reasons I had to remove the current mysql version and install a different MySQL version in my machine.
But now when I am trying to run this program am getting an error as follows:
```
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.... | reinstall the c shared library:
```
pip uninstall mysql-python
pip install mysql-python
``` |
Writing fits files with astropy.io.fits | 34,348,787 | 4 | 2015-12-18T04:57:34Z | 34,349,126 | 7 | 2015-12-18T05:37:26Z | [
"python",
"astropy",
"fits"
] | I'm trying to append data to a fits file using astropy.io.
Here is an example of my code:
```
import numpy as np
from astropy.io import fits
a1 = np.array([1,2,4,8])
a2 = np.array([0,1,2,3])
hdulist = fits.BinTableHDU.from_columns(
[fits.Column(name='FIRST', format='E', array=a1),
fits.Column(nam... | You'll have to upgrade astropy.
I can run your example fine; that's with the most recent astropy version.
Looking at the change log for 0.4, it's definitely looks like your astropy version is too old. The [log says](https://github.com/astropy/astropy/blob/v0.4.x/CHANGES.rst#api-changes-1):
> The astropy.io.fits.new... |
How to delete objects from two apps with the same model name? | 34,351,073 | 2 | 2015-12-18T08:10:05Z | 34,351,122 | 8 | 2015-12-18T08:13:39Z | [
"python",
"django",
"django-models"
] | I have two apps `news` and `article` which both have exactly the same model name `Comment`:
```
class Comment(models.Model):
author = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, default='', blank=True)
body = models.TextField()
... | You can use `import ... as ...` so that both model names do not conflict:
```
from news.models import Comment as NewsComment
from article.models import Comment as ArticleComment
...
NewsComment.objects.filter(author=someauthor).delete()
ArticleComment.objects.filter(author=someauthor).delete()
``` |
python .get() and None | 34,357,513 | 4 | 2015-12-18T14:08:58Z | 34,357,748 | 9 | 2015-12-18T14:24:06Z | [
"python"
] | I love python one liners:
```
u = payload.get("actor", {}).get("username", "")
```
Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine.
Problem of... | ### Using EAFP
As xnx suggested, you can take advantage of the following python paradigm:
> [Easier to ask for forgiveness than permission](https://docs.python.org/3/glossary.html#term-eafp)
you can use it on `KeyError`s as well:
```
try:
u = payload["actor"]["username"]
except (AttributeError, KeyError):
u... |
pycharm ssh interpter No such file or directory | 34,359,415 | 2 | 2015-12-18T15:56:58Z | 34,359,948 | 8 | 2015-12-18T16:28:36Z | [
"python",
"ssh",
"pycharm"
] | I am using a macbook pro 15 as local machine and I have a remote server running ubuntu 14.04
I want to use the remote intepreter to run all the computation but I want to write the code from my local machine.
When I try to run a simple file with pycharm I receive this error:
```
ssh://donbeo@149.157.140.205:22/usr/bi... | To execute your code on remote machine you'll have to perform few steps
# Define a remote interpreter for your project
1. Go to File -> Settings -> Project: {project\_name} -> Project Interpreter.
2. Click on cog icon and select Add Remote.
3. Add your SSH host credentials and interpreter path (on remote machine).
4.... |
nltk StanfordNERTagger : NoClassDefFoundError: org/slf4j/LoggerFactory (In Windows) | 34,361,725 | 9 | 2015-12-18T18:20:22Z | 34,364,699 | 11 | 2015-12-18T22:10:57Z | [
"python",
"windows",
"nlp",
"nltk",
"stanford-nlp"
] | NOTE: I am using Python 2.7 as part of Anaconda distribution. I hope this is not a problem for nltk 3.1.
I am trying to use nltk for NER as
```
import nltk
from nltk.tag.stanford import StanfordNERTagger
#st = StanfordNERTagger('stanford-ner/all.3class.distsim.crf.ser.gz', 'stanford-ner/stanford-ner.jar')
st = Stanf... | # EDITED
**Note:** The following answer will only work on:
* NLTK version 3.1
* Stanford Tools compiled since 2015-04-20
As both tools changes rather quickly and the API might look very different 3-6 months later. Please treat the following answer as temporal and not an eternal fix.
Always refer to <https://github.... |
Cannot press button | 34,372,953 | 12 | 2015-12-19T16:36:50Z | 34,521,990 | 10 | 2015-12-30T02:08:12Z | [
"python",
"automation",
"mechanize",
"mechanize-python"
] | I'm trying to code a bot for a game, and need some help to do it. Being a complete noob, I googled how to do it with python and started reading a bit about mechanize.
```
<div class="clearfix">
<a href="#" onclick="return Index.submit_login('server_br73');">
<span class="world_button_ac... | There is quite a lot of javascript involved when you perform different actions on a page, `mechanize` [is not a browser and cannot execute javascript](http://stackoverflow.com/questions/802225/how-do-i-use-mechanize-to-process-javascript). One option to make your life easier here would be to *automate a real browser*. ... |
Deploy to AWS EB failing because of YAML error in python.config | 34,373,107 | 2 | 2015-12-19T16:52:55Z | 34,424,225 | 8 | 2015-12-22T20:51:25Z | [
"python",
"django",
"amazon-web-services"
] | I am trying to deploy some Django code to an AWS Elastic Beanstalk Environment. I am getting a deployment error:
```
The configuration file __MACOSX/OriginalNewConfig-deploy/.ebextensions/._python.config in application version OriginalNewConfig2-deploy contains invalid YAML or JSON. YAML exception: unacceptable charac... | Seems like MAC creates this hidden folder automatically. I was also having this issue.
I've used the following command on terminal:
```
zip -d filename.zip __MACOSX/\*
```
found here:
[Mac zip compress without \_\_MACOSX folder?](http://stackoverflow.com/questions/10924236/mac-zip-compress-without-macosx-folder) |
Await Future from Executor: Future can't be used in 'await' expression | 34,376,814 | 5 | 2015-12-20T00:24:50Z | 34,376,938 | 9 | 2015-12-20T00:47:13Z | [
"python",
"python-3.x",
"async-await",
"future",
"python-asyncio"
] | I wanted to use a [ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html) from a [python coroutine](https://docs.python.org/3/library/asyncio-task.html), to delegate some blocking network calls to a separate thread. However, running the following code:
```
from concurrent.futures import ThreadP... | You should use [`loop.run_in_executor`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_in_executor):
```
from concurrent.futures import ThreadPoolExecutor
import asyncio
def work():
# do some blocking io
pass
async def main(loop):
executor = ThreadPoolExecutor()
await loop... |
Confused a bit about django INSTALLED_APPS naming convention | 34,377,237 | 7 | 2015-12-20T01:50:44Z | 34,377,341 | 9 | 2015-12-20T02:11:25Z | [
"python",
"django"
] | The tutorial on the site creates an app named polls. It's using django 1.9, so the in the INSTALLED\_APPS its
```
polls.apps.PollsConfig
```
I'm watching a tutorial he names the app newsletter and in INSTALLED\_APPS he has
```
newsletter
```
he's using 1.8, though. I am using 1.9. I've watched other tutorials and t... | That is the [*Application Configuration*](https://docs.djangoproject.com/en/1.9/ref/applications/) feature, new to Django 1.7.
Basically, now you can list in `INSTALLED_APPS` either the module that contains the application or a class that derives from `django.apps.AppConfig` and defines the behavior of the application... |
Passing arguments to process.crawl in Scrapy python | 34,382,356 | 3 | 2015-12-20T15:06:10Z | 34,383,962 | 7 | 2015-12-20T17:50:26Z | [
"python",
"web-crawler",
"scrapy",
"scrapy-spider",
"google-crawlers"
] | I would like to get the same result as this command line :
scrapy crawl linkedin\_anonymous -a first=James -a last=Bond -o output.json
My script is as follows :
```
import scrapy
from linkedin_anonymous_spider import LinkedInAnonymousSpider
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import ge... | pass the spider arguments on the `process.crawl` method:
```
process.crawl(spider, input='inputargument', first='James', last='Bond')
``` |
How can I easily machine translate something with python? | 34,382,722 | 7 | 2015-12-20T15:45:15Z | 34,382,738 | 9 | 2015-12-20T15:47:21Z | [
"python",
"nltk"
] | You used to be able to use `nltk.misc.babelfish` to translate things, but the Yahoo Babelfish API went down. Is there an easy way I can, say, do this?
```
>>> import translate
>>> translate('carpe diem', 'latin', 'english')
'seize the day'
``` | Goslate is a good library for this that uses Google Translate: <http://pythonhosted.org/goslate/>
Here's the example from the docs:
```
>>> import goslate
>>> gs = goslate.Goslate()
>>> print(gs.translate('hello world', 'de'))
hallo welt
```
In order to go from "carpe diem" to "seize the day":
```
>>> print(gs.tran... |
'if x % 2: return True' , wouldn't that return True if the number was divisible by 2? | 34,385,292 | 4 | 2015-12-20T20:07:15Z | 34,385,311 | 10 | 2015-12-20T20:09:29Z | [
"python",
"python-2.7"
] | I don't understand how `if not x % 2: return True` works. Wouldn't that mean this if x is not divisible by two, return True? That's what i see in this code.
I see it as `if not x % 2: return True` would return the opposite of if a number is divisible by 2, return True.
I just don't understand how that part of the syn... | > Wouldn't that mean this if x is not divisible by two, return True?
No, because when x is not divisible by 2 the result of `x%2` would be a nonzero value, which will be evaluated as `True` by Python, so its `not` would be `False`.
Read more about [Truth value testing](https://docs.python.org/3/library/stdtypes.html#... |
'if x % 2: return True' , wouldn't that return True if the number was divisible by 2? | 34,385,292 | 4 | 2015-12-20T20:07:15Z | 34,385,341 | 7 | 2015-12-20T20:13:15Z | [
"python",
"python-2.7"
] | I don't understand how `if not x % 2: return True` works. Wouldn't that mean this if x is not divisible by two, return True? That's what i see in this code.
I see it as `if not x % 2: return True` would return the opposite of if a number is divisible by 2, return True.
I just don't understand how that part of the syn... | The modulo operator `%` returns the remainder of a division. If `x` is divisible by 2 ('even'), then the remainder is zero and `x % 2` thus evaluates to zero (=False), which makes the whole expression True. |
How to Exit Linux terminal using Python script? | 34,389,322 | 4 | 2015-12-21T05:12:21Z | 34,389,409 | 7 | 2015-12-21T05:21:23Z | [
"python",
"linux",
"python-2.7",
"terminal",
"exit"
] | ```
import sys
def end():
foo=raw_input()
sys.exit()
print 'Press enter to Exit python and Terminal'
end()
```
When we run the program, we should able to exit the Python Interpreter and Terminal itself.
But it only exits python interpreter, not the terminal.
Thanks in advance. | `SIGHUP` (hang up) will tell the terminal to exit. The terminal should be your script's parent process, so
```
import os
import signal
os.kill(os.getppid(), signal.SIGHUP)
``` |
intersecting lists in a dict (more than two) | 34,395,826 | 3 | 2015-12-21T12:34:16Z | 34,395,882 | 11 | 2015-12-21T12:37:55Z | [
"python",
"dictionary",
"intersection"
] | I have a dict, of varying length. Each entry has a name and a list as so:
```
somedict = {'Name': [1, 2, 3], 'Name2': [], 'Name3': [2,3] }
```
How do I get the intersection for the following list? I need to do it dynamically, I don't know how long the dict will be.
For the above list, the intersection would be empty... | Normally, intersection is a set operation. So, you might want to convert the values of the dictionary to sets and then run intersection, like this
```
>>> set.intersection(*(set(values) for values in data.values()))
{2, 3}
```
If you want the result to be a list, just convert the resulting set to a list, like this
`... |
Docker how to run pip requirements.txt only if there was a change? | 34,398,632 | 7 | 2015-12-21T15:01:30Z | 34,399,661 | 10 | 2015-12-21T15:58:19Z | [
"python",
"docker",
"dockerfile"
] | In a Dockerfile I have a layer which installs `requirements.txt`:
```
FROM python:2.7
RUN pip install -r requirements.txt
```
When I build the docker image it runs the whole process **regardless** of any changes made to this file.
How do I make sure Docker only runs `pip install -r requirements.txt` if there has bee... | I'm assuming that at some point in your build process, you're copying your entire application into the Docker image with `ADD`:
```
ADD . /opt/app
WORKDIR /opt/app
RUN pip install -r requirements.txt
```
The problem is that you're invalidating the Docker build cache every time you're copying the entire application in... |
Does Conda replace the need for virtualenv? | 34,398,676 | 9 | 2015-12-21T15:03:54Z | 34,398,794 | 9 | 2015-12-21T15:10:02Z | [
"python",
"scipy",
"virtualenv",
"anaconda",
"conda"
] | I recently discovered [Conda](http://conda.pydata.org/docs/index.html) after I was having trouble installing SciPy, specifically on a Heroku app that I am developing.
With Conda you create environments, very similar to what [virtualenv](https://virtualenv.readthedocs.org/en/latest/) does. My questions are:
1. If I us... | 1. Conda replaces virtualenv. In my opinion it is better. It is not limited to Python but can be used for other languages too. In my experience it provides a much smoother experience, especially for scientific packages. The first time I got MayaVi properly installed on Mac was with `conda`.
2. You can still use `pip`. ... |
Install wxPython in osx 10.11 | 34,402,303 | 2 | 2015-12-21T18:42:24Z | 34,622,956 | 8 | 2016-01-05T23:13:04Z | [
"python",
"osx",
"wxpython"
] | when i try to install wxPython, it show a error:
> ```
> > The Installer could not install the software because there was no
> > software found to install.
> ```
How can i fix it?
thank you so much | wxPython is using a [legacy script](https://github.com/wxWidgets/wxPython/blob/14476d72d92c44624d5754c4f1fac2e8d7bc30da/distrib/mac/buildpkg.py), and according to this [technical note](https://developer.apple.com/library/mac/technotes/tn2206/_index.html#//apple_ref/doc/uid/DTS40007919-CH1-TNTAG405) *bundle installers* ... |
Can't reproduce distance value between sources obtained with astropy | 34,407,678 | 6 | 2015-12-22T02:42:55Z | 34,407,928 | 8 | 2015-12-22T03:16:27Z | [
"python",
"coordinates",
"astropy"
] | I have two sources with equatorial coordinates `(ra, dec)` and `(ra_0, dec_0)` located at distances `r` and `r_0`, and I need to calculate the 3D distance between them.
I use two approaches that *should* give the same result as far as I understand, but do not.
The first approach is to apply [astropy](http://www.astro... | This is a problem with coordinate systems, and the difference between **declination** (astral coordinates) and **polar angle θ** (spherical coordinates) :-)
Astral coordinates define **declination as north of the celestial equator**, while spherical coordinates define polar angle **θ as downward from from vertical.*... |
python 2.7 : remove a key from a dictionary by part of key | 34,415,897 | 3 | 2015-12-22T12:25:13Z | 34,415,949 | 8 | 2015-12-22T12:28:47Z | [
"python",
"python-2.7",
"dictionary"
] | I have a python dictionary , the dictionary key composed from tupples,
like this :
```
{
(u'A_String_0', u'A_String_1', u'B_String_3', u'Remove_Me'): 300,
(u'A_String_0', u'B_String_4'): 301,
(u'A_String_0', u'A_String_1', u'B_String_3', u'Remove_Key'): 301,
}
```
I'd like to remove all keys from dictionary whe... | One way:
```
>>> d = {
(u'A_String_0', u'A_String_1', u'B_String_3', u'Remove_Me'): 300,
(u'A_String_0', u'B_String_4'): 301,
(u'A_String_0', u'A_String_1', u'B_String_3', u'Remove_Key'): 301,
}
>>>
>>>
>>> d_out = {k:v for k,v in d.items() if not any(x.startswith('Remove_') for ... |
Unpacking tuple-like textfile | 34,416,365 | 9 | 2015-12-22T12:53:10Z | 34,416,814 | 7 | 2015-12-22T13:17:50Z | [
"python",
"regex",
"list",
"tuples"
] | Given a textfile of lines of 3-tuples:
```
(0, 12, Tokenization)
(13, 15, is)
(16, 22, widely)
(23, 31, regarded)
(32, 34, as)
(35, 36, a)
(37, 43, solved)
(44, 51, problem)
(52, 55, due)
(56, 58, to)
(59, 62, the)
(63, 67, high)
(68, 76, accuracy)
(77, 81, that)
(82, 91, rulebased)
(92, 102, tokenizers)
(103, 110, ac... | This is, in my opinion, a little more readable and clear, but it may be a little less performant and assumes the input file is correctly formatted (e.g. empty lines are really empty, while your code works even if there is some random whitespace in the "empty" lines). It leverages regex groups, they do all the work of p... |
Why is this Python code executing twice? | 34,419,062 | 3 | 2015-12-22T15:22:17Z | 34,419,159 | 8 | 2015-12-22T15:27:11Z | [
"python",
"functional-programming"
] | I'm very new to Python and trying to learn how classes, methods, scopes, etc works by building very silly programs with no real purpose.
The code I wrote below is suppose to just define a class `Functions` that is instantiated using an `x` and a `y` value and then one can execute various simple math functions like add... | Remove the following statement.
```
from MyMath import Functions
```
The first line of the program defines the name `Functions`, and you can use it without having to import it. You only use the import command if the class (or function, or variable, ...) is defined in a different file/module.
**Note in addition:** Wh... |
SQLAlchemy Model Circular Import | 34,421,205 | 10 | 2015-12-22T17:18:38Z | 34,503,626 | 7 | 2015-12-29T02:35:19Z | [
"python",
"sqlalchemy"
] | I have two models in the same module named `models`. They are a 1-1 relationship and have been configured per the [SQLAlchemy docs](http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#one-to-one).
**Vehicle.py**
```
from models.AssetSetting import AssetSetting
class Vehicle(Base):
__tablename__ = ... | To avoid circular import errors, you should use *string relationship building*, but **both of your models have to use the same `Base`** - the same `declarative_base` instance. Instantiate your `Base` once and use it when initializing both `Vehicle` and `AssetSetting`.
Or, you may [explicitly map the table names and cl... |
SQLAlchemy Model Circular Import | 34,421,205 | 10 | 2015-12-22T17:18:38Z | 34,503,823 | 7 | 2015-12-29T03:05:07Z | [
"python",
"sqlalchemy"
] | I have two models in the same module named `models`. They are a 1-1 relationship and have been configured per the [SQLAlchemy docs](http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#one-to-one).
**Vehicle.py**
```
from models.AssetSetting import AssetSetting
class Vehicle(Base):
__tablename__ = ... | I discovered my problem was two fold:
1. I was referencing `Vehicles` improperly in my relationship. It should be `relationship('Vehicle'` not `relationship('vehicles'`
2. Apparently it is improper to declare the FK inside the relationship as I did in **AssetSettings.py** (`foreign_keys=Column(ForeignKey('vehicles.veh... |
Increment the next element based on previous element | 34,422,238 | 2 | 2015-12-22T18:28:08Z | 34,422,279 | 7 | 2015-12-22T18:31:02Z | [
"python",
"list",
"for-loop",
"indexing"
] | When looping through a list, you can work with the current item of the list. For example, if you want to replace certain items with others, you can use:
```
a=['a','b','c','d','e']
b=[]
for i in a:
if i=='b':
b.append('replacement')
else:
b.append(i)
print b
['a', 'replacement', 'c', '... | Use a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) along with [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate)
```
>>> ['replacement' if a[i+1]=='b' else v for i,v in enumerate(a[:-1])]+[a[-1]]
['replacement', 'b', 'c', 'd', 'e']
```
The cod... |
Increment the next element based on previous element | 34,422,238 | 2 | 2015-12-22T18:28:08Z | 34,422,346 | 7 | 2015-12-22T18:35:38Z | [
"python",
"list",
"for-loop",
"indexing"
] | When looping through a list, you can work with the current item of the list. For example, if you want to replace certain items with others, you can use:
```
a=['a','b','c','d','e']
b=[]
for i in a:
if i=='b':
b.append('replacement')
else:
b.append(i)
print b
['a', 'replacement', 'c', '... | It's generally better style to not iterate over indices in Python. A common way to approach a problem like this is to use [`zip`](https://docs.python.org/3/library/functions.html#zip) (or the similar [`izip_longest`](https://docs.python.org/3/library/itertools.html#itertools.izip) in `itertools`) to see multiple values... |
Replacing characters in string by whitespace except digits | 34,429,202 | 3 | 2015-12-23T05:29:31Z | 34,429,225 | 10 | 2015-12-23T05:31:30Z | [
"python"
] | I am trying to remove all the characters and special symbols from a string in python except the numbers(digits 0-9). This is what I am doing-
```
s='das dad 67 8 - 11 2928 313'
s1=''
for i in range(0,len(s)):
if not(ord(s[i])>=48 and ord(s[i])<=57):
s1=s1+' '
else:
s1=s1+s[i]
#s1=s1.split() ... | ```
import re
s1=re.sub(r"[^0-9 ]"," ",s)
```
You can use `re` here.
To prevent `.` of floating numbers use
```
(?!(?<=\d)\.(?=\d))[^0-9 ]
``` |
Changing a variable inside a method with another method inside it | 34,431,264 | 21 | 2015-12-23T08:11:05Z | 34,431,308 | 30 | 2015-12-23T08:14:06Z | [
"python"
] | The following code raises an `UnboundLocalError`:
```
def foo():
i = 0
def incr():
i += 1
incr()
print(i)
foo()
```
Is there a way to accomplish this? | Use `nonlocal` statement
```
def foo():
i = 0
def incr():
nonlocal i
i += 1
incr()
print(i)
foo()
```
For more information on this new statement added in python 3.x, go to <https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement> |
Changing a variable inside a method with another method inside it | 34,431,264 | 21 | 2015-12-23T08:11:05Z | 34,431,314 | 9 | 2015-12-23T08:14:48Z | [
"python"
] | The following code raises an `UnboundLocalError`:
```
def foo():
i = 0
def incr():
i += 1
incr()
print(i)
foo()
```
Is there a way to accomplish this? | See [9.2. Python Scopes and Namespaces](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces):
> if no `global` statement is in effect â assignments to names always go into the innermost scope.
Also:
> The `global` statement can be used to indicate that particular variables live in the glob... |
Changing a variable inside a method with another method inside it | 34,431,264 | 21 | 2015-12-23T08:11:05Z | 34,431,331 | 20 | 2015-12-23T08:15:59Z | [
"python"
] | The following code raises an `UnboundLocalError`:
```
def foo():
i = 0
def incr():
i += 1
incr()
print(i)
foo()
```
Is there a way to accomplish this? | You can use `i` as an argument like this:
```
def foo():
i = 0
def incr(i):
return i + 1
i = incr(i)
print(i)
foo()
``` |
Sum of product of combinations in a list | 34,437,284 | 5 | 2015-12-23T13:58:22Z | 34,437,352 | 9 | 2015-12-23T14:02:19Z | [
"python",
"python-3.x",
"functional-programming"
] | What is the Pythonic way of summing the product of all combinations in a given list, such as:
```
[1, 2, 3, 4]
--> (1 * 2) + (1 * 3) + (1 * 4) + (2 * 3) + (2 * 4) + (3 * 4) = 35
```
(For this example I have taken all the two-element combinations, but it could have been different.) | Use `itertools.combinations`
```
>>> l = [1, 2, 3, 4]
>>> sum([i*j for i,j in list(itertools.combinations(l, 2))])
35
``` |
AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context | 34,438,290 | 5 | 2015-12-23T14:54:40Z | 34,444,082 | 8 | 2015-12-23T21:34:35Z | [
"python",
"django",
"django-views",
"django-rest-framework",
"django-serializer"
] | I want to create a `many-to-many` relationship where one person can be in many clubs and one club can have many persons. I added the `models.py` and `serializers.py` for the following logic but when I try to serialize it in the command prompt, I get the following error - What am I doing wrong here? I don't even have a ... | You're getting this error as the `HyperlinkedIdentityField` expects to receive `request` in `context` of the serializer so it can build absolute URLs. As you are initializing your serializer on the command line, you don't have access to request and so receive an error.
If you need to check your serializer on the comma... |
Can't run pip: UnicodeDecodeError | 34,440,958 | 6 | 2015-12-23T17:36:10Z | 34,613,967 | 20 | 2016-01-05T14:24:45Z | [
"python",
"numpy",
"encoding",
"pip",
"ubuntu-14.04"
] | I have trouble using pip. For example:
```
pip install numpy --upgrade
```
Gives me the following error:
```
Collecting numpy
Using cached numpy-1.10.2.tar.gz
Exception:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 211, in main
... | I had the same issue. In my case, it comes from a non-standard character in a module description.
I added a
> print f.path
in the script
> /usr/local/lib/python2.7/dist-packages/pkg\_resources/\_\_init\_\_.py
before line 2025, which allowed me to identify the file which was raising an error. It appeared to be the ... |
Count consecutive characters | 34,443,946 | 4 | 2015-12-23T21:24:21Z | 34,444,401 | 7 | 2015-12-23T22:02:38Z | [
"python"
] | **EDITED**
How would I count consecutive characters in Python to see the number of times each unique digit repeats before the next unique digit? I'm very new to this language so I am looking for something simple.
At first I thought I could do something like:
```
word = '1000'
counter=0
print range(len(word))
for i... | ## Consecutive counts:
Ooh nobody's posted [`itertools.groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby) yet!
```
s = "111000222334455555"
from itertools import groupby
groups = groupby(s)
result = [(label, sum(1 for _ in group)) for label, group in groups]
```
After which, `result` loo... |
Unpacking "the rest" of the elements in list comprehension - python3to2 | 34,449,869 | 2 | 2015-12-24T08:49:54Z | 34,449,889 | 9 | 2015-12-24T08:51:55Z | [
"python",
"list",
"python-3.x",
"tuples",
"python-2.x"
] | In Python 3, I could use `for i, *items in tuple` to isolate the first time from the tuple and the rest into items, e.g.:
```
>>> x = [(2, '_', 'loves', 'love', 'VBZ', 'VBZ', '_', '0', 'ROOT', '_', '_'), (1, '_', 'John', 'John', 'NNP', 'NNP', '_', '2', 'nsubj', '_', '_'), (3, '_', 'Mary', 'Mary', 'NNP', 'NNP', '_', '2... | Just use slicing to skip the first element:
```
[all_items[1:] for all_items in sorted(x)]
```
The syntax is referred to *extended tuple unpacking*, where the `*`-prefixed name is called the *catch-all name*. See [PEP 3132](https://www.python.org/dev/peps/pep-3132/). There is no backport of the syntax. |
ElementNotVisibleException: Message: Element is not currently visible... selenium (python) | 34,456,584 | 8 | 2015-12-24T18:23:45Z | 34,485,327 | 7 | 2015-12-27T22:06:41Z | [
"javascript",
"python",
"selenium",
"selenium-webdriver"
] | I am getting those annoying element is not visible exception using python's selenium, while the element is active, selected, and flashing.
The issue is on the page to make a jfiddle, so instead of making a fiddle of the fiddle itself here is a cut and paste way to log in and have a webdriver (named 'driver') in your i... | JSFiddle editors are powered by [`CodeMirror`](https://codemirror.net/index.html) which has a *programmatic way to set editor values.*
For every JSFiddle editor you need to put values into, locate the element with a `CodeMirror` class, get the `CodeMirror` object and call [`setValue()`](https://codemirror.net/doc/manu... |
Sphinx-apidoc on django build html failure on `django.core.exceptions.AppRegistryNotReady` | 34,461,088 | 5 | 2015-12-25T07:57:59Z | 34,462,027 | 8 | 2015-12-25T10:28:19Z | [
"python",
"django",
"documentation",
"python-sphinx"
] | ### Question background:
I want to write documents with sphinx on my django project and auto create docs with my django code comments.
Now I have a django(1.9) project, the file structure is as below:
```
myproject/
myproject/
__init__.py
settings.py
urls.py
wsgi.py
myapp/
migrations/
__i... | Long time to find the solution:
In the `conf.py`, add the following:
```
import django
sys.path.insert(0, os.path.abspath('..'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
django.setup()
``` |
Replace single instances of a character that is sometimes doubled | 34,464,490 | 15 | 2015-12-25T16:27:38Z | 34,464,504 | 20 | 2015-12-25T16:30:07Z | [
"python",
"regex",
"string",
"replace"
] | I have a string with each character being separated by a pipe character (including the `"|"`s themselves), for example:
```
"f|u|n|n|y||b|o|y||a||c|a|t"
```
I would like to replace all `"|"`s which are not next to another `"|"` with nothing, to get the result:
```
"funny|boy|a|cat"
```
I tried using `mytext.replace... | You could replace the double pipe by something else first to make sure that you can still recognize them after removing the single pipes. And then you replace those back to a pipe:
```
>>> t = "f|u|n|n|y||b|o|y||a||c|a|t"
>>> t.replace('||', '|-|').replace('|', '').replace('-', '|')
'funny|boy|a|cat'
```
You should t... |
Replace single instances of a character that is sometimes doubled | 34,464,490 | 15 | 2015-12-25T16:27:38Z | 34,464,508 | 12 | 2015-12-25T16:30:35Z | [
"python",
"regex",
"string",
"replace"
] | I have a string with each character being separated by a pipe character (including the `"|"`s themselves), for example:
```
"f|u|n|n|y||b|o|y||a||c|a|t"
```
I would like to replace all `"|"`s which are not next to another `"|"` with nothing, to get the result:
```
"funny|boy|a|cat"
```
I tried using `mytext.replace... | Use sentinel values
Replace the `||` by `~`. This will remember the `||`. Then remove the `|`s. Finally re-replace them with `|`.
```
>>> s = "f|u|n|n|y||b|o|y||a||c|a|t"
>>> s.replace('||','~').replace('|','').replace('~','|')
'funny|boy|a|cat'
```
---
Another better way is to use the fact that they are almost alt... |
Replace single instances of a character that is sometimes doubled | 34,464,490 | 15 | 2015-12-25T16:27:38Z | 34,464,509 | 9 | 2015-12-25T16:30:39Z | [
"python",
"regex",
"string",
"replace"
] | I have a string with each character being separated by a pipe character (including the `"|"`s themselves), for example:
```
"f|u|n|n|y||b|o|y||a||c|a|t"
```
I would like to replace all `"|"`s which are not next to another `"|"` with nothing, to get the result:
```
"funny|boy|a|cat"
```
I tried using `mytext.replace... | You can use a [*positive look ahead*](http://www.regular-expressions.info/lookaround.html) regex to replace the pips that are followed with an alphabetical character:
```
>>> import re
>>> st = "f|u|n|n|y||b|o|y||a||c|a|t"
>>> re.sub(r'\|(?=[a-z]|$)',r'',st)
'funny|boy|a|cat'
``` |
Replace single instances of a character that is sometimes doubled | 34,464,490 | 15 | 2015-12-25T16:27:38Z | 34,464,512 | 27 | 2015-12-25T16:30:49Z | [
"python",
"regex",
"string",
"replace"
] | I have a string with each character being separated by a pipe character (including the `"|"`s themselves), for example:
```
"f|u|n|n|y||b|o|y||a||c|a|t"
```
I would like to replace all `"|"`s which are not next to another `"|"` with nothing, to get the result:
```
"funny|boy|a|cat"
```
I tried using `mytext.replace... | This can be achieved with a relatively simple regex without having to chain `str.replace`:
```
>>> import re
>>> s = "f|u|n|n|y||b|o|y||a||c|a|t"
>>> re.sub('\|(?!\|)' , '', s)
'funny|boy|a|cat'
```
Explanation: \|(?!\|) will look for a `|` character which is not followed by another `|` character. (?!foo) means negat... |
In py.test, what is the use of conftest.py files? | 34,466,027 | 19 | 2015-12-25T20:08:20Z | 34,520,971 | 23 | 2015-12-29T23:53:08Z | [
"python",
"testing",
"py.test"
] | I recently discovered `py.test`. It seems great. However I feel the documentation could be better.
I'm trying to understand what `conftest.py` files are meant to be used for.
In my (currently small) test suite I have one `conftest.py` file at the project root. I use it to define the fixtures that I inject into my tes... | > Is this the correct use of conftest.py?
Yes it is, Fixtures are a potential and common use of `conftest.py`. The
fixtures that you will define will be shared among all tests in your test suite. However defining fixtures in the root `conftest.py` might be useless and it would slow down testing if such fixtures are no... |
Using Excel like solver in Python or SQL | 34,468,947 | 3 | 2015-12-26T06:03:20Z | 34,573,807 | 7 | 2016-01-03T05:57:12Z | [
"python",
"sql",
"numpy",
"pandas",
"solver"
] | Here is a simple calculation that I do in Excel. I will like to know if it can be done python or any other language.
```
Loan amount 7692
Period : 12 months
Rate of interest 18 Per Annum
The formula in the B2 cell is =A1*18/100/12
The formula in the A2 cells is =A1+B2-C2
```
The column C is tentative amount the borro... | Well, you can solve it using numerical method (as Excel does), you can solve it with brute force by checking every amount with some step within some range, or you can solve it analytically on a piece of paper.
Using the following notation
```
L - initial loan amount = 7692
R - monthly interest rate = 1 + 0.18/12
m - ... |
How to check if all elements in a tuple or list are in another? | 34,468,983 | 5 | 2015-12-26T06:09:27Z | 34,469,004 | 11 | 2015-12-26T06:14:26Z | [
"python",
"list",
"set",
"tuples"
] | For example, I want to check every elements in tuple `(1, 2)` are in tuple `(1, 2, 3, 4, 5)`.
I don't think use loop is a good way to do it, I think it could be done in one line. | You can use [`set.issubset`](https://docs.python.org/3.5/library/stdtypes.html?highlight=issubset#set.issubset) or [`set.issuperset`](https://docs.python.org/3.5/library/stdtypes.html?highlight=issubset#set.issuperset) to check if every element in one tuple or list is in other.
```
>>> tuple1 = (1, 2)
>>> tuple2 = (1,... |
Python native coroutines and send() | 34,469,060 | 5 | 2015-12-26T06:25:15Z | 34,469,122 | 7 | 2015-12-26T06:37:11Z | [
"python",
"async-await",
"coroutine"
] | Generator based coroutines have a `send()` method which allow bidirectional communication between the caller and the callee and resumes a yielded generator coroutine from the caller. This is the functionality that turns generators into coroutines.
While the new native `async/await` coroutines provide superior support ... | > Is there a way to resume a returned coroutine from where it left off and potentially send in a new value?
No.
`async` and `await` are *just* syntactic sugar for `yield from`. When a coroutine returns (with the `return` statement), that's it. The frame is gone. It is not resumable. This is exactly how generators hav... |
Linear Regression and Gradient Descent in Scikit learn/Pandas? | 34,469,237 | 4 | 2015-12-26T06:57:53Z | 34,470,001 | 8 | 2015-12-26T09:18:05Z | [
"python",
"pandas",
"machine-learning",
"scikit-learn"
] | in coursera course for machine learning <https://share.coursera.org/wiki/index.php/ML:Linear_Regression_with_Multiple_Variables#Gradient_Descent_for_Multiple_Variables>, it says gradient descent should converge.
I m using Linear regression from scikit learn. It doesn't provide gradient descent info. I have seen many q... | Scikit learn provides you two approaches to linear regression:
1) `LinearRegression` object uses Ordinary Least Squares solver from scipy, as LR is one of two classifiers which have **closed form solution**. Despite the ML course - you can actually learn this model by just inverting and multiplicating some matrices.
... |
Logging training and validation loss in tensorboard | 34,471,563 | 5 | 2015-12-26T13:02:27Z | 34,474,533 | 7 | 2015-12-26T19:31:54Z | [
"python",
"tensorflow",
"tensorboard"
] | I'm trying to learn how to use tensorflow and tensorboard. I have a test project based on the MNIST neural net tutorial (<https://www.tensorflow.org/versions/master/tutorials/mnist/tf/index.html>).
In my code, I construct a node that calculates the fraction of digits in a data set that are correctly classified, like t... | There are several different ways you could achieve this, but you're on the right track with creating different [`tf.scalar_summary()`](https://www.tensorflow.org/versions/master/api_docs/python/train.html#scalar_summary) nodes. Since you must explicitly call [`SummaryWriter.add_summary()`](https://www.tensorflow.org/ve... |
Use a.any() or a.all() | 34,472,814 | 6 | 2015-12-26T15:46:56Z | 34,473,104 | 11 | 2015-12-26T16:22:39Z | [
"python",
"numpy"
] | ```
x = np.arange(0,2,0.5)
valeur = 2*x
if valeur <= 0.6:
print ("this works")
else:
print ("valeur is too high")
```
here is the error I get:
```
if valeur <= 0.6:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
```
I have read several posts about ... | If you take a look at the result of `valeur <= 0.6`, you can see whatâs causing this ambiguity:
```
>>> valeur <= 0.6
array([ True, False, False, False], dtype=bool)
```
So the result is another array that has in this case 4 boolean values. Now what should the result be? Should the condition be true when one value ... |
using pandas and numpy to parametrize stack overflow's number of users and reputation | 34,473,089 | 8 | 2015-12-26T16:20:57Z | 34,474,542 | 8 | 2015-12-26T19:33:50Z | [
"python",
"numpy",
"pandas"
] | I noticed that Stack Overflow's number of users and their reputation follows an interesting distribution. I created a **pandas DF** to see if I could create a **parametric fit**:
```
import pandas as pd
import numpy as np
soDF = pd.read_excel('scores.xls')
print soDF
```
Which returns this:
```
total_rep user... | NumPy has a lot of functions to do fitting. For polynomial fits, we use **numpy.polyfit** ([documentation](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.polyfit.html)).
Initalize your dataset:
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = [k.split() for k in '''... |
using pandas and numpy to parametrize stack overflow's number of users and reputation | 34,473,089 | 8 | 2015-12-26T16:20:57Z | 34,475,210 | 9 | 2015-12-26T21:02:25Z | [
"python",
"numpy",
"pandas"
] | I noticed that Stack Overflow's number of users and their reputation follows an interesting distribution. I created a **pandas DF** to see if I could create a **parametric fit**:
```
import pandas as pd
import numpy as np
soDF = pd.read_excel('scores.xls')
print soDF
```
Which returns this:
```
total_rep user... | ## `python`, `pandas`, and `scipy`, oh my!
The scientific python ecosystem has several complimentary libraries. No one library does everything, by design. `pandas` provides tools to manipulate table-like data and timeseries. However, it deliberately doesn't include the type of functionality you're looking for.
For fi... |
Remove items from list by using python list comprehensions | 34,473,834 | 9 | 2015-12-26T18:01:25Z | 34,473,912 | 7 | 2015-12-26T18:11:01Z | [
"python",
"list"
] | I have a list of integers which goes like this:
```
unculledlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
```
I would like cull the values from this list, so that it looks like this:
```
culledlist = [0, 2, 4, 10, 12, 14, 20, 22, 24]
```
But I ... | I saw this and thought string manipulation would be the easier approach
```
culled_list = [item for item in unculledlist if str(item)[-1] in ['0','2','4']]
```
The result is still a list of integers
```
>>> culled_list
[0, 2, 4, 10, 12, 14, 20, 22, 24]
```
Thanks to eugene y for the less complicated approach
```
>... |
How comparator works for objects that are not comparable in python? | 34,474,538 | 7 | 2015-12-26T19:33:30Z | 34,474,650 | 10 | 2015-12-26T19:46:32Z | [
"python"
] | I have defined a list as below:
```
list = [1,3,2,[4,5,6]]
```
then defined a comparator method as below:
```
def reverseCom(x,y):
if(x>y):
return -1
elif(x<y):
return 1
else:
return 0
```
Now I have sorted the list using reverseCom:
```
list.sort(reverseCom)
print list
```
> Resu... | This is a Python 2 quirk. In Python 2, numeric and non numeric values are comparable, and numeric values are always considered to be less than the value of container objects:
```
>>> 1 < [1]
True
>>> 1 < [2]
True
>>> 1558 < [1]
True
>>> 1 < {}
True
```
when comparing two containers values of different types, on the o... |
Need to install urllib2 for Python 3.5.1 | 34,475,051 | 6 | 2015-12-26T20:40:15Z | 34,475,081 | 13 | 2015-12-26T20:44:04Z | [
"python",
"urllib2"
] | I'm running Python 3.5.1 for Mac. I want to use urllib2. I tried installing that but I'm told that it's been split into urllib.request and urllib.error for Python 3.
My command (running from the framework bin directory for now because it's not in my path):
```
sudo ./pip3 install urllib.request
```
Returns:
```
Cou... | You can't, and you don't need to.
`urllib2` is the name of the library included in Python 2. You can use the [`urllib.request` library](https://docs.python.org/3/library/urllib.request.html#module-urllib.request) included with Python 3, instead. The `urllib.request` library works the same way `urllib2` works in Python... |
import local function from a module housed in another directory with relative imports in jupyter notebook using python3 | 34,478,398 | 7 | 2015-12-27T07:14:20Z | 35,273,613 | 9 | 2016-02-08T15:48:01Z | [
"python",
"jupyter-notebook",
"relative-import"
] | I have a directory structure similar to the following
```
meta_project
project1
__init__.py
lib
module.py
__init__.py
notebook_folder
notebook.jpynb
```
When working in `notebook.jpynb` if I try to use a relative import to access a function `function()` in `modu... | I had almost the same example as you in [this notebook](https://github.com/qPRC/qPRC/blob/master/notebook/qPRC.ipynb) where I wanted to illustrate the usage of an adjacent module's function in a DRY manner.
My solution was to tell Python of that additional module import path by adding a snippet like this one to the no... |
Example program of Cython as Python to C Converter | 34,480,973 | 9 | 2015-12-27T13:40:08Z | 34,482,471 | 10 | 2015-12-27T16:38:02Z | [
"python",
"c",
"cython"
] | I found [here](http://stackoverflow.com/questions/7112812/use-cython-as-python-to-c-converter) and [here](http://stackoverflow.com/questions/4650243/convert-python-program-to-c-c-code) that one can use Cython to convert Python to C, but I cannot find any step-by-step example. Let's say I have a simple function:
**foo.... | Far from a c expert but for me using ubuntu, the following works:
main.c:
```
#include "foo_api.h"
#include <stdio.h>
int main(int argc, char *argv[]) {
Py_Initialize();
initfoo();
import_foo();
double arr[5] = {1,2,3,4,5};
int i = 0;
foo(arr);
for(i = 0; i < 5; i++)
{
p... |
Memory-efficient way to generate a large numpy array containing random boolean values | 34,485,591 | 16 | 2015-12-27T22:34:44Z | 34,485,956 | 12 | 2015-12-27T23:24:28Z | [
"python",
"performance",
"numpy",
"random",
"boolean"
] | I need to create a large numpy array containing random boolean values without hitting the swap.
My laptop has 8 GB of RAM. Creating a `(1200, 2e6)` array takes less than 2 s and use 2.29 GB of RAM:
```
>>> dd = np.ones((1200, int(2e6)), dtype=bool)
>>> dd.nbytes/1024./1024
2288.818359375
>>> dd.shape
(1200, 2000000)... | One problem with using `np.random.randint` is that it generates 64-bit integers, whereas numpy's `np.bool` dtype uses only 8 bits to represent each boolean value. You are therefore allocating an intermediate array 8x larger than necessary.
A workaround that avoids intermediate 64-bit dtypes is to generate a string of ... |
function of difference between value | 34,485,990 | 5 | 2015-12-27T23:29:38Z | 34,486,002 | 8 | 2015-12-27T23:31:49Z | [
"python",
"list",
"python-2.7",
"python-3.x"
] | Is there a function in Python to get the difference between two or more values in a list? So, in those two lists:
```
list1 = [1, 5, 3, 7]
list2 = [4, 2, 6, 4]
```
I need to calculate the difference between every value in list1 and list2.
```
for i in list1:
for ii in list2:
print i -ii
```
This gives ne... | Either `zip` the lists, or use `numpy`:
```
>>> list1 = [1, 5, 3, 7]
>>> list2 = [4, 2, 6, 4]
>>> [a-b for a,b in zip(list1, list2)]
[-3, 3, -3, 3]
>>> import numpy as np
>>> np.array(list1) - np.array(list2)
array([-3, 3, -3, 3])
```
Remember to cast the array back to a list as needed.
# **edit:**
In response to... |
function of difference between value | 34,485,990 | 5 | 2015-12-27T23:29:38Z | 34,486,121 | 10 | 2015-12-27T23:51:45Z | [
"python",
"list",
"python-2.7",
"python-3.x"
] | Is there a function in Python to get the difference between two or more values in a list? So, in those two lists:
```
list1 = [1, 5, 3, 7]
list2 = [4, 2, 6, 4]
```
I need to calculate the difference between every value in list1 and list2.
```
for i in list1:
for ii in list2:
print i -ii
```
This gives ne... | Assuming you expect `[3, 3, 3, 3]` as the answer in your question, you can use `abs` and `zip`:
```
[abs(i-j) for i,j in zip(list1, list2)]
``` |
What is the currently correct way to dynamically update plots in Jupyter/iPython? | 34,486,642 | 21 | 2015-12-28T01:21:11Z | 34,486,703 | 17 | 2015-12-28T01:33:30Z | [
"python",
"matplotlib",
"jupyter",
"jupyter-notebook"
] | In the answers to [how to dynamically update a plot in a loop in ipython notebook (within one cell)](http://stackoverflow.com/questions/21360361/how-to-dynamically-update-a-plot-in-a-loop-in-ipython-notebook-within-one-cell), an example is given of how to dynamically update a plot inside a Jupyter notebook within a Pyt... | Here is an example that updates a plot in a loop. It updates the data in the figure and does not redraw the whole figure every time. It does block execution, though if you're interested in running a finite set of simulations and saving the results somewhere, it may not be a problem for you.
```
%matplotlib notebook
i... |
How to unravel array? | 34,489,254 | 7 | 2015-12-28T07:20:07Z | 34,489,295 | 10 | 2015-12-28T07:23:34Z | [
"python",
"arrays",
"list"
] | I need to generate a `list` for `scipy.optimize.minimize`'s `boundry condition`, it should look like this:
```
bonds = [(0., 0.99),(-30, 30),(-30, 30),(0., 30),(0., 30),(-0.99, 0.99),
(0., 0.99),(-30, 30),(-30, 30),(0., 30),(0., 30),(-0.99, 0.99),
(0., 0.99),(-30, 30),(-30, 30),(0., 30),(0., 30),(-0.99... | you can do:
```
bonds = [(0., 0.99),(-30, 30),(-30, 30),(0., 30),(0., 30),(-0.99, 0.99)] * 3
``` |
Why `type(x).__enter__(x)` instead of `x.__enter__()` in Python standard contextlib? | 34,490,998 | 6 | 2015-12-28T09:37:10Z | 34,491,119 | 11 | 2015-12-28T09:45:46Z | [
"python"
] | In [contextlib.py](https://hg.python.org/cpython/file/003f1f60a09c/Lib/contextlib.py#l304), I see the ExitStack class is calling `__enter__()` method via the type object (`type(cm)`) instead of direct method calls to the given object (`cm`).
I wonder why or why not.
e.g.,
* does it give better exception traces when ... | First of all, this is what happens when you do `with something`, it's not just `contextlib` that looks up special method on the type. Also, it's worth noting that the same happens with other special methods too: e.g. `a + b` results in `type(a).__add__(a, b)`.
But why does it happen? This is a question that is often f... |
Reversing lists of numbers in python | 34,494,963 | 7 | 2015-12-28T14:01:45Z | 34,495,024 | 8 | 2015-12-28T14:05:31Z | [
"python",
"list"
] | So I have been trying to do this for a while now and am constantly coming up with differing failures. I need to take numerical input from the user and put it into a list and output it in decreasing value:
```
bids = []
bid = input('Bid: ')
while bid != '':
bids.append(bid)
bid = input('Bid: ')
print('The auction h... | In your
```
bids.append(bid)
```
you get a list of strings. You want to convert them to integers and sort in decreasing order:
```
numerical_bids = [int(bid) for bid in bids]
numerical_bids.sort(reverse=True)
```
and now `numerical_bids` is a list of integers sorted in decreasing order.
In your code:
```
for bid ... |
DataFrame object has no attribute 'sort_values' | 34,499,728 | 5 | 2015-12-28T19:44:49Z | 34,499,784 | 10 | 2015-12-28T19:49:55Z | [
"python",
"pandas",
"dataframe"
] | ```
dataset = pd.read_csv("dataset.csv").fillna(" ")[:100]
dataset['Id']=0
dataset['i']=0
dataset['j']=0
#...
entries=dataset[dataset['Id']==0]
print type(entries) # Prints <class 'pandas.core.frame.DataFrame'>
entries=entries.sort_values(['i','j','ColumnA','ColumnB'])
```
What might be the possible reason of the fol... | Hello `sort_values` is [new in version 0.17.0](http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.sort_values.html), so check your version of pandas.
In the previous versions you should use `sort`.
```
entries=entries.sort(['i','j','ColumnA','ColumnB'])
``` |
Dictionary order in python | 34,499,794 | 4 | 2015-12-28T19:50:40Z | 34,499,864 | 11 | 2015-12-28T19:56:03Z | [
"python",
"dictionary"
] | Everywhere I search, they say python dictionary's doesn't have any order.
When I run code 1 each time shows a different output (random order). But when I run code 2 it always shows the same sorted output. Why is the dictionary ordered in the second snippet?
```
#code 1
d = {'one': 1, 'two': 2, 'three': 3, 'fou... | It's related to how hash randomisation is applied. Quoting [docs](https://docs.python.org/3/reference/datamodel.html#object.__hash__) (emphasis mine):
> By default, the `__hash__()` values of **str**, **bytes** and **datetime**
> objects are âsaltedâ with an unpredictable random value. Although they
> remain const... |
tensorflow: saving and restoring session | 34,500,052 | 5 | 2015-12-28T20:11:24Z | 34,500,690 | 7 | 2015-12-28T20:59:34Z | [
"python",
"scikit-learn",
"tensorflow"
] | I am trying to implement a suggestion from answers:
[Tensorflow: How to restore a previously saved model (python)](http://stackoverflow.com/questions/33759623/tensorflow-how-to-restore-a-previously-saved-model-python)
I have an object which wraps a `tensorflow` model in a `sklearn` style.
```
import tensorflow as tf
... | **TL;DR:** You should try to rework this class so that `self.create_network()` is called (i) only once, and (ii) before the `tf.train.Saver()` is constructed.
There are two subtle issues here, which are due to the code structure, and the default behavior of the [`tf.train.Saver` constructor](https://www.tensorflow.org... |
Finding that which sums to the smallest value | 34,501,487 | 3 | 2015-12-28T22:06:49Z | 34,501,496 | 7 | 2015-12-28T22:07:52Z | [
"python",
"python-3.x"
] | Is there a better way of doing the following in python:
```
m = float("inf")
for i in ((1,2,3),(1,3,1),(2,2,3),(0,2,2)):
r = sum(i)
if r < m:
best = i
m = r
print(best)
```
Where I'm trying to find the item in ((1,2,3),(1,3,1),(2,2,3),(0,2,2)) which sums to the smallest value.
The following i... | Just use the built-in [**`min`**](https://docs.python.org/2/library/functions.html#min)
```
data = ((1,2,3),(1,3,1),(2,2,3),(0,2,2))
print(min(data, key=sum))
``` |
Download and save PDF file with Python requests module | 34,503,412 | 3 | 2015-12-29T02:00:58Z | 34,503,421 | 10 | 2015-12-29T02:02:31Z | [
"python",
"python-2.7"
] | I am trying to download a PDF file from a website and save it to disk. My attempts either fail with encoding errors or result in blank PDFs.
```
In [1]: import requests
In [2]: url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
In [3]: response = requests.get(url)
In [4]: with open('/tmp/metadat... | You should use `response.content` in this case:
```
with open('/tmp/metadata.pdf', 'wb') as f:
f.write(response.content)
```
From [the document](http://requests.readthedocs.org/en/latest/user/quickstart/#binary-response-content):
> You can also access the response body as bytes, for non-text requests:
>
> ```
> ... |
Best way to hash ordered permutation of [1,9] | 34,510,823 | 3 | 2015-12-29T12:12:19Z | 34,512,030 | 7 | 2015-12-29T13:23:35Z | [
"python",
"algorithm",
"hash",
"permutation",
"8-puzzle"
] | I'm trying to implement a method to keep the visited states of the 8 puzzle from generating again.
My initial approach was to save each visited pattern in a list and do a linear check each time the algorithm wants to generate a child.
Now I want to do this in `O(1)` time through list access. Each pattern in 8 puzzl... | You can map a permutation of N items to its index in the list of all permutations of N items (ordered lexicographically).
Here's some code that does this, and a demonstration that it produces indexes 0 to 23 once each for all permutations of a 4-letter sequence.
```
import itertools
def fact(n):
r = 1
for i ... |
Extracting comments from Python Source Code | 34,511,673 | 7 | 2015-12-29T13:03:14Z | 34,512,388 | 7 | 2015-12-29T13:46:21Z | [
"python",
"python-2.7"
] | I'm trying to write a program to extract comments in code that user enters. I tried to use regex, but found it difficult to write.
Then I found a post [here](http://stackoverflow.com/questions/7032031/python-regex-to-remove-comments). The answer suggests to use `tokenize.generate_tokens` to analyze the grammar, but [t... | ## Answer for more general cases (extracting from modules, functions):
### Modules:
The documentation specifies that one needs to provide a callable which exposes the same interface as the **[`readline()`](https://docs.python.org/2.7/library/io.html#io.IOBase.readline)** method of built-in **file** objects. This hint... |
Split string to various data types | 34,515,139 | 2 | 2015-12-29T16:33:50Z | 34,515,155 | 10 | 2015-12-29T16:35:01Z | [
"python",
"string",
"list"
] | I would like to convert the following string:
```
s = '1|2|a|b'
```
to
```
[1, 2, 'a', 'b']
```
Is it possible to do the conversion in one line? | > Is it possible to do the conversion in one line?
**YES**, It is possible. But how?
*Algorithm for the approach*
* Split the string into its constituent parts using [`str.split`](https://docs.python.org/3/library/stdtypes.html#str.split). The output of this is
```
>>> s = '1|2|a|b'
>>> s.split('|')
['1', '... |
Werkzeug raises BrokenFilesystemWarning | 34,515,331 | 2 | 2015-12-29T16:46:46Z | 34,517,230 | 7 | 2015-12-29T18:55:19Z | [
"python",
"unix",
"encoding",
"utf-8",
"flask"
] | I get the following error when I send form data to my Flask app. It says it will use the UTF-8 encoding, but the locale is already UTF-8. What does this error mean?
```
/home/.virtualenvs/project/local/lib/python2.7/site-packages/werkzeug/filesystem.py:63:
BrokenFilesystemWarning: Detected a misconfigured UNIX filesys... | This is not a critical error, just a warning that Werkzeug couldn't detect a good locale and so is using `UTF-8` instead. This guess is probably correct.
See [this Arch Linux wiki article](https://wiki.archlinux.org/index.php/Locale) for how to set up the locale correctly. It mentions that Python may see the `ANSI_X3.... |
sum over a list of tensors in tensorflow | 34,519,627 | 5 | 2015-12-29T21:50:33Z | 34,520,066 | 10 | 2015-12-29T22:25:05Z | [
"python",
"tensorflow",
"cost-based-optimizer"
] | I have a deep neural network where the weights between layers are stored in a list.
`layers[j].weights` I want to incluse the ridge penalty in my cost function. I need then to use something like
`tf.nn.l2_loss(layers[j].weights**2 for j in range(self.n_layers))` i.e. the squared sum of all the weights.
In particular ... | The standard way to sum a list of tensors is to use the [`tf.add_n()`](https://www.tensorflow.org/versions/master/api_docs/python/math_ops.html#add_n) operation, which takes a list of tensors (each having the same size and shape) and produces a single tensor containing the sum.
For the particular problem that you have... |
Python recursive function that retain variable values | 34,519,841 | 3 | 2015-12-29T22:07:23Z | 34,519,921 | 8 | 2015-12-29T22:13:28Z | [
"python",
"recursion"
] | I am brushing up a bit of good old algorithms, and doing it with python, since I use it more often nowadays.
I am facing an issue when running a recursive function; where the variable get reset every time that the recursive function call itself:
```
def recursive_me(mystring):
chars = len(mystring)
if chars i... | You can code as simply as this:
```
def recursive_me(mystring):
if mystring: # recursive case
return int(mystring[0]) + recursive_me(mystring[1:])
else: # base case
return 0
```
or
```
def recursive_me(mystring, total = 0):
if mystring: # recursive case
return recursive_me(... |
Check if a list has one or more strings that match a regex | 34,520,279 | 9 | 2015-12-29T22:44:43Z | 34,520,315 | 7 | 2015-12-29T22:47:55Z | [
"python",
"regex",
"list"
] | If need to say
```
if <this list has a string in it that matches this rexeg>:
do_stuff()
```
I [found](http://www.cademuir.eu/blog/2011/10/20/python-searching-for-a-string-within-a-list-list-comprehension/) this powerful construct to extract matching strings from a list:
```
[m.group(1) for l in my_list for m in... | You can simply use `any`. Demo:
```
>>> lst = ['hello', '123', 'SO']
>>> any(re.search('\d', s) for s in lst)
True
>>> any(re.search('\d{4}', s) for s in lst)
False
```
use `re.match` if you want to enforce matching from the start of the string.
*Explanation*:
`any` will check if there is any truthy value in an ite... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.