title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How do I make two different lists with the corresponding elements of the first list?
38,150,512
<p>Suppose I have a list like this:</p> <pre><code>[[1, 2], [2, 3], [5, 4]] </code></pre> <p>What I want is two different lists from the above list with first element in one list and <br>the second element in the other. </p> <p>The result will look like this:</p> <pre><code>[1,2,5] and [2,3,4] </code></pre> <p>Is ...
1
2016-07-01T16:56:22Z
38,150,584
<p>Use <code>zip()</code> to pair up the elements of the input lists:</p> <pre><code>lista, listb = zip(*inputlist) </code></pre> <p>The <code>*</code> applies the <em>elements</em> in <code>inputlist</code> as separate arguments, as if you called <code>zip()</code> as <code>zip([1, 2], [2, 3], [5, 4])</code>. <code>...
2
2016-07-01T17:00:45Z
[ "python", "python-2.7" ]
How do I make two different lists with the corresponding elements of the first list?
38,150,512
<p>Suppose I have a list like this:</p> <pre><code>[[1, 2], [2, 3], [5, 4]] </code></pre> <p>What I want is two different lists from the above list with first element in one list and <br>the second element in the other. </p> <p>The result will look like this:</p> <pre><code>[1,2,5] and [2,3,4] </code></pre> <p>Is ...
1
2016-07-01T16:56:22Z
38,150,770
<p>How about use <code>numpy</code> array?</p> <pre><code>import numpy as np np.array(myList).transpose() # array([[1, 2, 5], # [2, 3, 4]]) </code></pre> <p>Or </p> <pre><code>np.array(myList)[:, 0] # array([1, 2, 5]) np.array(myList)[:, 1] # array([2, 3, 4]) </code></pre>
1
2016-07-01T17:13:20Z
[ "python", "python-2.7" ]
call function over list
38,150,543
<p>I'm trying to learn python and have gotten way over my head on this problem. </p> <p>I have a a nested list like so, with a mixture of fractions and integers in the numbers:</p> <pre><code>results = [ { "date": "2016-06-30", "item1": [ "9/2", "4", ], "item2": [ "13/10", ...
0
2016-07-01T16:58:09Z
38,150,650
<p>First of all, there are two '}' , you wrongly placed them. It's actually not a list.By the way, what is rsplit? I think you should use just split.</p>
0
2016-07-01T17:05:17Z
[ "python", "python-2.7", "nested-lists" ]
call function over list
38,150,543
<p>I'm trying to learn python and have gotten way over my head on this problem. </p> <p>I have a a nested list like so, with a mixture of fractions and integers in the numbers:</p> <pre><code>results = [ { "date": "2016-06-30", "item1": [ "9/2", "4", ], "item2": [ "13/10", ...
0
2016-07-01T16:58:09Z
38,150,653
<p>Assuming that only <code>item1</code> and <code>item2</code> keys have list of floats or ints, you can try this:</p> <pre><code>list_ = [] for dicts in results: item_1 = dicts["item1"] // pass item_1 in the method, append to list_ item_2 = dicts["item2"] // pass item_2 in the method, list_ is updated ...
0
2016-07-01T17:05:31Z
[ "python", "python-2.7", "nested-lists" ]
call function over list
38,150,543
<p>I'm trying to learn python and have gotten way over my head on this problem. </p> <p>I have a a nested list like so, with a mixture of fractions and integers in the numbers:</p> <pre><code>results = [ { "date": "2016-06-30", "item1": [ "9/2", "4", ], "item2": [ "13/10", ...
0
2016-07-01T16:58:09Z
38,151,054
<p>The last part is the key to the solution. You'll need to have access to both the key and the value in the dict key:value pair in order to test the key for 'item' and perform something on the value if it matches. Hopefully this solves the problem, or at least points you in the right direction.</p> <pre><code>resul...
0
2016-07-01T17:31:28Z
[ "python", "python-2.7", "nested-lists" ]
call function over list
38,150,543
<p>I'm trying to learn python and have gotten way over my head on this problem. </p> <p>I have a a nested list like so, with a mixture of fractions and integers in the numbers:</p> <pre><code>results = [ { "date": "2016-06-30", "item1": [ "9/2", "4", ], "item2": [ "13/10", ...
0
2016-07-01T16:58:09Z
38,151,745
<p>Given these revision to the op:</p> <pre><code>results = [ { "date": "2016-06-30", "item1": [ "9/2", "4", ], "item2": [ "13/10", "6/5" ] }, { "date": "2016-06-29", "item1": "5/4", "item2": [ "9/10", "1" ] } ] # cleaned up or...
0
2016-07-01T18:20:23Z
[ "python", "python-2.7", "nested-lists" ]
python script run failed in crontab while meeting local()
38,150,545
<p>I'm trying to run a python script in crontab.</p> <pre><code>5 0 * * * python /home/hadoop/import_openapp.py &gt;&gt; /home/hadoop/openapp.out 2&gt;&amp;1 </code></pre> <p>The python script is something like below:</p> <pre><code>import sys import datetime from fabric.api import local ystd = datetime.date.today...
0
2016-07-01T16:58:19Z
38,152,679
<p>It is likely that the PYTHONPATH it not set up correctly for whatever the user that CRON is using to run the script. Print out the path to a debug file to check:</p> <pre><code>with open('/path/to/debug_file.txt', 'wt') as f: f.write(str(sys.path)) </code></pre> <p>Try adding the line:</p> <pre><code>sys.path...
0
2016-07-01T19:23:15Z
[ "python", "crontab", "local", "fabric" ]
PYTHON - After first tab, remove portions of lines within a text file
38,150,654
<p>I am new to python and I'm trying to remove portions of lines within a text file. Need to know the best way to remove all characters remaining on lines within a text file after and including the first tab.</p> <p>Before :</p> <p>10</p> <pre><code>.10.10.0 10.10.10.255 24 123 ABC GOOD be (XXXX-XXX-X-BLK1) ...
-1
2016-07-01T17:05:31Z
38,150,960
<pre><code>f=open("filename.txt","r") for line in f: print(line.split("\t")[0]) </code></pre> <p>So first you open the file you want to read. You start reading it line by line. For each line, split the line with the <strong>\t</strong> character which stands for tab and than print the first item on the list.(split...
0
2016-07-01T17:25:47Z
[ "python", "python-3.x" ]
For, html, and beautiful soup
38,150,678
<p>I'm trying to do something like:</p> <pre><code>from BeautifulSoup import BeautifulSoup import urllib2,unicodedata import re for x in range(1,105): html_page = urllib2.urlopen('http://xxxxxx/BUSCAR/H=1;OR=5;ST=;LIST_ART_PAGENUMBER='+str(x)+';/Dxxxxx.aspx') soup = BeautifulSoup(html_page) for link in soup.findAll(...
-2
2016-07-01T17:07:22Z
38,150,762
<p>You need to indent when you start the for loop. Try this:</p> <pre><code>from BeautifulSoup import BeautifulSoup import urllib2,unicodedata import re for x in range(1,105): html_page = urllib2.urlopen('http://xxxxxx/BUSCAR/H=1;OR=5;ST=;LIST_ART_PAGENUMBER='+str(x)+';/Dxxxxx.aspx') soup = BeautifulSoup(htm...
1
2016-07-01T17:12:46Z
[ "python", "html", "hyperlink", "beautifulsoup" ]
Python BrowserMob Proxy with IE captures incorrect HAR?
38,150,738
<p>I am currently trying to use BrowserMob Proxy (v2.1.1) + Selenium (v2.5.3) for Python (v2.6) to test page load times and output them to HAR files. I need to test both Chrome and IE. I currently have it working perfectly for Chrome and it runs without errors on IE but it doesn't capture the correct data to the HAR fi...
0
2016-07-01T17:11:02Z
38,151,542
<p>You need to ensure that the cache of IE is clean before launching the browser:</p> <pre><code>desired_capabilities = webdriver.DesiredCapabilities.INTERNETEXPLORER desired_capabilities ["ie.ensureCleanSession"] = True driver = webdriver.Ie(capabilities=desired_capabilities ) </code></pre> <p>Note that you are rea...
1
2016-07-01T18:06:02Z
[ "python", "internet-explorer", "selenium", "browsermob-proxy" ]
Python interpreter and pip give different versions of module
38,150,783
<p>I have encountered some issues a long time ago with python and pip and I don't remember what exactly. Now this bothers me: <code>python3 -m pip show scipy</code> returns <code>Version: 0.17.1</code> but when I launch a Python interpreter with <code>python3</code> and <code>import scipy</code>, <code>scipy.__version_...
0
2016-07-01T17:14:13Z
38,150,984
<p>It sounds like have two versions of <code>scipy</code> installed, and <code>sys.path</code> is finding the older version first. In a Python3 interpreter type:</p> <pre><code>&gt;&gt;&gt; import scipy &gt;&gt;&gt; scipy.__version__ '0.18.0.dev0+4a89f2d' &gt;&gt;&gt; scipy.__file__ '/home/unutbu/.virtualenvs/muffy/li...
0
2016-07-01T17:27:21Z
[ "python", "scipy", "pip" ]
Comparing datetime object to 8601 strings gives wrong result, why is it allowed?
38,150,803
<p>Maybe I am missing something obvious, but it looks like date comparing is off here:</p> <pre><code>from pyspark import SparkContext from pyspark.sql import SQLContext import pandas as pd import datetime sc = SparkContext() sqlContext = SQLContext(sc) action_pandas_df = pd.DataFrame({"customerId": ["Cat", "Hat", ...
4
2016-07-01T17:15:31Z
38,175,079
<p>Because you don't compare dates. Since types don't match and column is a string query is casted to string as well. String representation of <code>cut_off</code> in SQL is <code>2016-06-29 15:00:00</code>:</p> <pre><code>from pyspark.sql.functions import lit cut_off = datetime.datetime(2016, 6, 29, 15) action_df.s...
3
2016-07-03T23:01:59Z
[ "python", "datetime", "apache-spark", "pyspark", "apache-spark-sql" ]
in IntelliJ, showing "No module named xxx", but "xxx" is actually installed in my system
38,150,837
<p>My IntelliJ version is <strong>15.0.3</strong>, and have python plugin installed.</p> <p>And when I open a python file in IntelliJ it's like below <a href="http://i.stack.imgur.com/qrmPE.png" rel="nofollow"><img src="http://i.stack.imgur.com/qrmPE.png" alt="enter image description here"></a></p> <p>Situation here ...
0
2016-07-01T17:18:08Z
39,202,419
<p>You have to add the site-packages path of your interpreter.</p> <p>For that you have to:</p> <ol> <li>go to Project Structure</li> <li>choose Global Libraries</li> <li>choose your Python interpreter</li> <li>press + at the upper left corner</li> <li>choose the site-package path of your interpreter</li> <li>choose ...
0
2016-08-29T09:09:49Z
[ "python", "intellij-idea", "ide", "python-import", "python-module" ]
Add shared row headers in matplotlib
38,150,914
<p>I haven't been able to find a way to add a shared row header across multiple subplots, as in the figure below. I don't want to use the xlabel of any plot, both because I need the label and because they don't align in the center of the row. I'd appreciate any suggestions.</p> <p><img src="http://i.stack.imgur.com/GG...
0
2016-07-01T17:22:52Z
38,152,613
<p>Is this six different subplots? Maybe see Text in matplotlib helps you. <a href="http://matplotlib.org/users/text_intro.html" rel="nofollow">http://matplotlib.org/users/text_intro.html</a> Consider this is not title but a text at an arbitrary place.</p>
0
2016-07-01T19:18:33Z
[ "python", "matplotlib", "rowheader" ]
IndexError: list index out of range - Can't get my txt file to save the output in Python
38,150,920
<p>I'm writing a program that is referring to two text files. One stores the list of currencies in a sentence and one stores the current value. I want it to only store the value of the currency in the sentence once, but then stores each order so it can be replaced on screen. E.g. Sterling, Euro (in one file). 1,1,2 (in...
0
2016-07-01T17:23:26Z
38,151,276
<p>You are getting error because you are mainly indexing the currency first. Since in you case there is only 2 currency that's why trying to get the third index eg. arr[2] giving this error. </p>
0
2016-07-01T17:48:27Z
[ "python", "list", "indexing", "range" ]
IndexError: list index out of range - Can't get my txt file to save the output in Python
38,150,920
<p>I'm writing a program that is referring to two text files. One stores the list of currencies in a sentence and one stores the current value. I want it to only store the value of the currency in the sentence once, but then stores each order so it can be replaced on screen. E.g. Sterling, Euro (in one file). 1,1,2 (in...
0
2016-07-01T17:23:26Z
38,155,225
<pre><code>def read_words(words_file): return [word for line in open(words_file, 'r') for word in line.strip().split(',')] all_currency = read_words("a.txt") print(all_currency) value_of_currency = read_words("b.txt") print(value_of_currency ) positions = "" for mynumbers in value_of_currency: positions += al...
0
2016-07-02T00:05:22Z
[ "python", "list", "indexing", "range" ]
Forbidden (CSRF token missing or incorrect.)
38,150,929
<p>I've searched through similar questions, but nothing seems relevant to my situation.</p> <p>Why does this code work fine:</p> <pre><code>&lt;form action="/signup/" method="post"&gt; {% csrf_token %} [FORM] &lt;/form&gt; </code></pre> <p>but</p> <pre><code>&lt;form id="signup-form"&gt; {% csrf_token %} [FORM] ...
0
2016-07-01T17:23:42Z
38,151,601
<p>you are doing an ajax post call for which you need to give csrf token also: </p> <pre><code>$.post("/signup/", { user: user, csrfmiddlewaretoken: '{{ csrf_token }}' }, function() { // success todo }, function(){ // fail todo }); </code></pre>
1
2016-07-01T18:10:14Z
[ "python", "django" ]
Python sqlite3 select min values from group with exceptions
38,150,937
<p>I'm using <code>sqlite3</code> in python to retrieve data from an sqlite table called <code>"Documents"</code> with fields <code>"Title,Date,Author"</code>. For each unique title (group), I want to select the minimum <code>Date</code> and the <code>Author</code> for that date, unless the author's name is <code>'foo'...
0
2016-07-01T17:24:03Z
38,151,308
<p>If you don't mind using two queries and Python to do the job, this would work as expected:</p> <pre><code># first query to get the min date of each "Title" query = "SELECT Title, MIN(Date) FROM Documents GROUP BY Title" min_date_by_title = cursor.fetchall(query) # then get the author for each "Title", except if it...
2
2016-07-01T17:50:53Z
[ "python", "sqlite", "sqlite3" ]
Can I bulk upload a CSV to Django with many to one relationship mapping?
38,150,971
<p>I am trying to find/create a module that allows for bulk upload of data into Django. I am trying to associate many artists with a given festival, but all of the modules I have found so far only support 1:1 uploading. <a href="https://github.com/edcrewe/django-csvimport" rel="nofollow">https://github.com/edcrewe/djan...
1
2016-07-01T17:26:28Z
38,163,052
<p>Here's an example of what you want to do. I have stripped down the original code as it was too large. But this would still give you a good starting point.</p> <p>In reality, the CSV files uploaded by the client weren't as simple as I've shown in the example. Some lines were blank, some lines contained some other un...
1
2016-07-02T18:02:52Z
[ "python", "django", "csv", "mapping" ]
Pythonic way to "merge" strings, handling all possible lengths
38,151,000
<p>I'm trying to solve a fairly common problem in bioinformatics without resorting to a bunch of if statements.</p> <p><strong>The problem at hand:</strong></p> <p>I'm given two overlapping strings and a length of the expected output, and I want to produce a merged string. Here all the ways the strings might overlap:...
0
2016-07-01T17:28:17Z
38,151,956
<p>I would start with a generator that yields each character:</p> <pre><code>def merge_gen(x, y, overhang): buffer = ' ' * overhang for s in map(set, zip(buffer + x, y + buffer)): yield max(s) </code></pre> <p>Where <code>overhang</code> is <code>len(x) - size</code> (see below)</p> <p>That works as ...
0
2016-07-01T18:34:00Z
[ "python", "string", "bioinformatics" ]
Pythonic way to "merge" strings, handling all possible lengths
38,151,000
<p>I'm trying to solve a fairly common problem in bioinformatics without resorting to a bunch of if statements.</p> <p><strong>The problem at hand:</strong></p> <p>I'm given two overlapping strings and a length of the expected output, and I want to produce a merged string. Here all the ways the strings might overlap:...
0
2016-07-01T17:28:17Z
38,151,985
<p>Is this the functionality you were looking for?</p> <pre><code>def consensus(left, right, ignore_blank_padding=True): if ignore_blank_padding: left = left.strip() right = right.strip() slide = len(left) + len(right) - 1 #slides the strings over each other one spot at a time solutio...
0
2016-07-01T18:36:09Z
[ "python", "string", "bioinformatics" ]
Pythonic way to "merge" strings, handling all possible lengths
38,151,000
<p>I'm trying to solve a fairly common problem in bioinformatics without resorting to a bunch of if statements.</p> <p><strong>The problem at hand:</strong></p> <p>I'm given two overlapping strings and a length of the expected output, and I want to produce a merged string. Here all the ways the strings might overlap:...
0
2016-07-01T17:28:17Z
38,153,931
<p>Here is a working example, but uses the "way too many if statements" approach which is hard to read, hard to reason about, and extremely inelegant:</p> <pre><code>def extra_left(x, y, size): if size - len(y) &gt; 0: return x[:size - len(y)] else: return "" def extra_right(x, y, size): ...
0
2016-07-01T21:12:22Z
[ "python", "string", "bioinformatics" ]
Pandas GroupBy date range depending on each row
38,151,013
<p>I would like to do the following:</p> <p>for a data frame that looks like this:</p> <pre><code>df = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"], "date":["06/24/2014","06/25/2014","06/23/2014","07/02/1999","07/02/1999"], "value": ["3","5","1","7","8"] }) </code></pre> <p>I would like to group by date all those ob...
1
2016-07-01T17:29:15Z
38,151,207
<p>You could sort the rows by <code>date</code>, then take the difference between consecutive dates. Test when the difference is greater than 2 days. Taking the cumulative sum assigns the desired group numbers:</p> <pre><code>import pandas as pd df = pd.DataFrame({"ID":["A", "A", "C" ,"B", "B"], "date":["06/24/2014","...
2
2016-07-01T17:42:47Z
[ "python", "pandas" ]
Using multiple NOT IN statements with Python
38,151,203
<p>I need to URLs with three specific specific substrings out of a loop. The following code worked, but I am sure there's a more elegant way to do it:</p> <pre><code>for node in soup.findAll('loc'): url = node.text.encode("utf-8") if "/store/" not in url and "/cell-phones/" not in url and "/accessories/" not i...
2
2016-07-01T17:42:28Z
38,151,232
<pre><code>url = node.text.encode("utf-8") sub_strings = ['/store','/cell-phones/','accessories'] if not any(x in url for x in sub_strings): objlist.loc.append(url) else: continute </code></pre> <p>From the <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow">docs</a>:</p> <p><co...
3
2016-07-01T17:44:23Z
[ "python", "if-statement", "condition" ]
Error while parsing out few fields from dictionary to CSV
38,151,225
<pre><code>b {u'message': {u'method': u'XXXX', u'params': {u'documentURL': u'xxxx', u'A': u'yyyy', u'initialPriority': u'Medium', u'method': u'GET', u'mixedContentType': u'none', u'url': u'xxxx'}, u'date': u'qqqq', u'time': u'wwww', u'type': u'Other', u'wallTime': u'uuuu'}, u'webvi...
1
2016-07-01T17:43:55Z
38,152,461
<p>You can use <code>get()</code> instead of <code>[]</code>, since it returns <code>None</code> if key is not present in the dictionary.</p>
1
2016-07-01T19:07:54Z
[ "python", "csv", "parsing", "pandas", "dictionary" ]
Error while parsing out few fields from dictionary to CSV
38,151,225
<pre><code>b {u'message': {u'method': u'XXXX', u'params': {u'documentURL': u'xxxx', u'A': u'yyyy', u'initialPriority': u'Medium', u'method': u'GET', u'mixedContentType': u'none', u'url': u'xxxx'}, u'date': u'qqqq', u'time': u'wwww', u'type': u'Other', u'wallTime': u'uuuu'}, u'webvi...
1
2016-07-01T17:43:55Z
38,152,754
<p>This is assuming that 'message' is always present, but others may or may not:</p> <pre><code>result = [] for k in b: msg=b[k]['message'] # if b is a dictionary of dictionaries msg=k['message'] # if b is a list of dictionaries if 'params' in msg: if 'A' in msg['params']: output['a']=m...
3
2016-07-01T19:29:33Z
[ "python", "csv", "parsing", "pandas", "dictionary" ]
Counting by letters in Python
38,151,233
<p><strong>Objective:</strong> count by letters instead of integers.</p> <p>Is there a clean way to count-by-letters in Python-2.7? I have a program where I am enumerating some data by letter, and my solution would not be very clear to someone reading my code.</p> <p>I've been checking through the standard documentat...
1
2016-07-01T17:44:30Z
38,151,272
<pre><code>import string alphabet = string.ascii_uppercase &gt;&gt;&gt; for char in alphabet[2:6]: ... print char ... C D E F &gt;&gt;&gt; </code></pre>
2
2016-07-01T17:48:05Z
[ "python", "python-2.7", "count", "letter" ]
Counting by letters in Python
38,151,233
<p><strong>Objective:</strong> count by letters instead of integers.</p> <p>Is there a clean way to count-by-letters in Python-2.7? I have a program where I am enumerating some data by letter, and my solution would not be very clear to someone reading my code.</p> <p>I've been checking through the standard documentat...
1
2016-07-01T17:44:30Z
38,151,441
<p>Here is a function that would do what you wish:</p> <pre><code>import string def enumerate(first, last): alphabet = string.ascii_uppercase start = alphabet.index(first) while alphabet[start] != last: print alphabet[start] start += 1 print last </code></pre>
0
2016-07-01T18:00:06Z
[ "python", "python-2.7", "count", "letter" ]
Counting by letters in Python
38,151,233
<p><strong>Objective:</strong> count by letters instead of integers.</p> <p>Is there a clean way to count-by-letters in Python-2.7? I have a program where I am enumerating some data by letter, and my solution would not be very clear to someone reading my code.</p> <p>I've been checking through the standard documentat...
1
2016-07-01T17:44:30Z
38,151,611
<p>Another solution I have become fond of for my particular application is:</p> <pre><code>alphabet = iter('ABCDEFGHIJKLMNOPQRSTUVWXYZ') print next(alphabet) </code></pre>
0
2016-07-01T18:11:10Z
[ "python", "python-2.7", "count", "letter" ]
Counting by letters in Python
38,151,233
<p><strong>Objective:</strong> count by letters instead of integers.</p> <p>Is there a clean way to count-by-letters in Python-2.7? I have a program where I am enumerating some data by letter, and my solution would not be very clear to someone reading my code.</p> <p>I've been checking through the standard documentat...
1
2016-07-01T17:44:30Z
38,151,640
<p>Your <em>Solution B</em> could be expressed:</p> <pre><code>for charcode in range(ord('B'), ord('G')): print chr(charcode) </code></pre> <p>But to attack your larger issue, how about:</p> <pre><code>from string import ascii_lowercase, ascii_uppercase def letter_code(string): indexes = [ascii_lowercase.in...
1
2016-07-01T18:13:41Z
[ "python", "python-2.7", "count", "letter" ]
Find a python transformation function or numpy matrix to transform skewed normal distribution to normal distribution
38,151,261
<p>I have an input dataset (DataFrame / numpy matrix) that has a skewed normal distribution. I am trying to find the python transformation function (or numpy matrix) which will transform the input dataset to a normal distribution with no skew.</p> <p>I have looked at curve_fit (in scipy.optimize) and am not sure how ...
2
2016-07-01T17:47:01Z
38,151,652
<p>I've done one of 2 things:</p> <ul> <li>Use <a href="https://www.isixsigma.com/tools-templates/normality/making-data-normal-using-box-cox-power-transformation/" rel="nofollow">box-cox transformations</a>. This requires you find the appropriate power or lambda that transforms you data to having zero skew.</li> <li>...
2
2016-07-01T18:14:16Z
[ "python", "numpy", "pandas", "scipy" ]
boto3 Route53 complains Could not connect to the endpoint URL:
38,151,294
<p>I was trying to get some Route53 automation working with boto, and noticed that this tiny boto3 (version 1.3.1) example:</p> <pre><code>import boto3 client = boto3.client('route53') print client.list_hosted_zones() </code></pre> <p>blows up with a complaint about:</p> <pre> File "... venv/lib/python2.7/site-pac...
0
2016-07-01T17:49:45Z
38,172,933
<p>Thanks to this answer <a href="http://stackoverflow.com/questions/34685446/exception-in-boto3-botocore-exceptions-endpointconnectionerror">Exception in Boto3 - botocore.exceptions.EndpointConnectionError</a> all you need to do is to configure your <code>~/.aws/config</code> file. That's seems like you didn't config...
1
2016-07-03T18:13:35Z
[ "python", "boto", "amazon-route53", "boto3" ]
Change the character image for a while in Python Pygame
38,151,300
<p>I am struggling with a problem I can't solve.</p> <p>I want to <strong>change the image of my character when the enemy hurts it</strong>.</p> <p>In <strong>pseudocode</strong>, it would be like this:</p> <pre><code> *If enemy collides -&gt; player close eyes and get red;* *After 0.50 seg -&gt; player gets norm...
0
2016-07-01T17:50:11Z
38,174,642
<p>I would assume it's as easy as this. <code>pygame.time.set_timer(x, y)</code> basically creates an x event on the event stack every y milliseconds.</p> <pre><code># Main game loop while True: # display stuff and other parts of your game # replace this with whatever detection you have for collision if e...
1
2016-07-03T21:50:12Z
[ "python", "timer", "pygame" ]
Where is target specified in tensorflow's load_csv function
38,151,301
<p>I'm trying to follow along this tensorflow tutorial which uses a <code>load_csv</code> function. <a href="https://www.tensorflow.org/versions/r0.9/tutorials/tflearn/index.html">TUTORIAL_LINK</a></p> <p>One of two lines in question is:</p> <blockquote> <pre><code>IRIS_TEST = "iris_test.csv" test_set = tf.contrib.l...
5
2016-07-01T17:50:30Z
38,152,067
<p>From the <a href="https://github.com/tensorflow/tensorflow/blob/r0.9/tensorflow/contrib/learn/python/learn/datasets/base.py">code</a>:</p> <pre><code>def load_csv(filename, target_dtype, target_column=-1, has_header=True): """Load dataset from CSV file.""" </code></pre> <p>default for <code>target_column</code> ...
5
2016-07-01T18:41:04Z
[ "python", "tensorflow" ]
Github API return encoded characters
38,151,331
<p>Using Ansible I query github API to retrieve comments from a Github Pull Request. It returns something like:</p> <p>\\u3053\\u306e\\u30aa</p> <p>Because the content is in Japanese.</p> <p>Is there a way to ask Github to return non-encoded characters? If not, is there a way in Ansible/Jinja2 or in Python to easily...
0
2016-07-01T17:52:51Z
38,151,617
<p>You can use the <code>unidecode</code> module to convert it to ascii:</p> <pre><code>&gt;&gt;&gt; from unidecode import unidecode &gt;&gt;&gt; unidecode(u'\u3053\u306e\u30aa') 'konoo' </code></pre>
0
2016-07-01T18:11:35Z
[ "python", "github", "ansible", "jinja2", "github-api" ]
How to sort groupby and filter using pandas
38,151,373
<p>I have a code like this:</p> <pre><code>grouped=L2014.groupby(['state','NAME']) grouped.mask.value_counts(normalize=True,).sort_index() </code></pre> <p>results like this:</p> <pre><code>state NAME mask CO Adams False 0.407195 True 0.592805 Alamosa ...
-1
2016-07-01T17:55:09Z
38,154,497
<p>Try this: </p> <pre><code>grouped.mask.value_counts(normalize=1).sort_index(level=2,ascending=False).filter(like='True', axis=0).nlargest(5) </code></pre> <p>or </p> <pre><code>grouped.mask.value_counts(normalize=1).filter(like='True', axis=0).nlargest(5) </code></pre>
1
2016-07-01T22:17:08Z
[ "python", "pandas", "group-by" ]
Celsius to Fahrenheit conversion in CSV file
38,151,382
<p>I want to take a CSV file with Temperatures in celsius and convert it to fahrenheit. </p> <p>Current attempt:</p> <pre><code>import pandas as pd df = pd.read_csv('/temperature_data.csv', ) def f(x): x = x * 1.8 + 32 return float(x) df['AirTemperature'] = df.apply(f, axis=1) </code></pre> <p>I am able to...
0
2016-07-01T17:55:38Z
38,152,169
<p>I've not used Pandas before but reviewing the documentation, this looks like it should work:</p> <pre><code>df['Air Temperature'] = df['Air Temperature'].apply(f) </code></pre> <p><code>'Air Temperature'</code> is a series in the DataFrame, and the <a href="http://pandas.pydata.org/pandas-docs/stable/api.html#seri...
0
2016-07-01T18:48:02Z
[ "python", "csv", "temperature" ]
Twilio environment variable error
38,151,401
<p><a href="https://www.twilio.com/docs/libraries/python" rel="nofollow">Twilio-Python</a> works fine if I place my account_sid and auth_token directly into the code but will not work when I set them to environment variables. I'm using PyCharm and set them by going to edit configurations > Environment variables, just a...
1
2016-07-01T17:56:36Z
38,151,555
<p>For OS X El Capitan, add environment variables:</p> <ul> <li><p>open terminal, then</p> <p><code>cd ~/</code></p> <p><code>vi .bash_profile</code></p></li> </ul> <p>once in vi editor editing the file, get into insert mode (press i) then add these two lines:</p> <pre><code>export TWILIO_ACCOUNT_SID="AC0123456789...
2
2016-07-01T18:06:37Z
[ "python", "python-3.x", "environment-variables", "pycharm", "twilio" ]
Can anyone tell my why I'm getting the error [AttributeError: 'list' object has no attribute 'encode']
38,151,440
<p>I keep trying to run this code in order to send an excel sheet as an attachment on an email. I can send normal emails using smtplib but can't get the MIMEMultipart to work. I keep getting the [AttributeError: 'list' object has no attribute 'encode'] error </p> <pre><code>import smtplib, ssl from email.mime.multipar...
1
2016-07-01T18:00:00Z
38,151,472
<pre><code>fromaddr = ['Email'] sendto = ['Email'] </code></pre> <p>This looks a little odd to me. Shouldn't they be strings, not lists?</p> <pre><code>fromaddr = 'Email' sendto = 'Email' </code></pre>
2
2016-07-01T18:02:03Z
[ "python", "excel", "smtp", "attachment" ]
What Am I Missing When Parsing this JSON Output
38,151,466
<p>What am I missing when trying to parse this JSON output with Python? The JSON looks like this:</p> <pre><code> { "start": 0, "terms": [ "process_name:egagent.exe" ], "highlights": [], "total_results": 448, "filtered": {}, "facets": {}, "results": [ { "username": "SYSTEM", "al...
2
2016-07-01T18:01:52Z
38,151,534
<p>If <code>readable</code> is your JSON object (<code>dict</code>), you can access elements like you'd in every map, using their keys.</p> <pre><code>readable["results"][0]["username"] </code></pre> <p>Should give you <code>"SYSTEM"</code> string as result.</p> <p>To print every username, do:</p> <pre><code>for re...
0
2016-07-01T18:05:42Z
[ "python", "json" ]
What Am I Missing When Parsing this JSON Output
38,151,466
<p>What am I missing when trying to parse this JSON output with Python? The JSON looks like this:</p> <pre><code> { "start": 0, "terms": [ "process_name:egagent.exe" ], "highlights": [], "total_results": 448, "filtered": {}, "facets": {}, "results": [ { "username": "SYSTEM", "al...
2
2016-07-01T18:01:52Z
38,151,538
<p>Try this:</p> <pre><code>for i in readable["results"]: print i["username"] </code></pre>
2
2016-07-01T18:05:58Z
[ "python", "json" ]
What Am I Missing When Parsing this JSON Output
38,151,466
<p>What am I missing when trying to parse this JSON output with Python? The JSON looks like this:</p> <pre><code> { "start": 0, "terms": [ "process_name:egagent.exe" ], "highlights": [], "total_results": 448, "filtered": {}, "facets": {}, "results": [ { "username": "SYSTEM", "al...
2
2016-07-01T18:01:52Z
38,151,568
<p>Load your json string:</p> <pre><code>import json s = """ { "start": 0, "terms": [ "process_name:egagent.exe" ], "highlights": [], "total_results": 448, "filtered": {}, "facets": {}, "results": [ { "username": "SYSTEM", "alert_type": "test" }, { "username": "SYSTEM...
2
2016-07-01T18:08:02Z
[ "python", "json" ]
What Am I Missing When Parsing this JSON Output
38,151,466
<p>What am I missing when trying to parse this JSON output with Python? The JSON looks like this:</p> <pre><code> { "start": 0, "terms": [ "process_name:egagent.exe" ], "highlights": [], "total_results": 448, "filtered": {}, "facets": {}, "results": [ { "username": "SYSTEM", "al...
2
2016-07-01T18:01:52Z
38,151,595
<p><code>for i in readable</code> will iterate <code>i</code> through each key in the <code>readable</code> dictionary. If you then print <code>i[0]</code>, you are printing the first character of each key.</p> <p>Given that you want the values associated with the <code>"username"</code> key in the entries of the list...
1
2016-07-01T18:09:35Z
[ "python", "json" ]
Trying to fix my equation program
38,151,708
<p>I'm trying to make a simple equation solver by my own that will solve problems like (3*x-4=7+2*x). The user will enter a equation and the program will split the equation to two parts, and in a loop, it will replace the x on both sides with the same numbers. The program will check if both sides of the equation are eq...
0
2016-07-01T18:17:52Z
38,151,792
<p>In your loop, each time you call:</p> <pre><code>side1=side1.replace("x", str(i+1)) side2=side2.replace("x", str(i+1)) </code></pre> <p>you are overwriting the original side variables. So the next time the loop runs, when it goes to replace 'x' in the string, there's no longer any 'x' character. The replacement wi...
2
2016-07-01T18:23:08Z
[ "python" ]
django db_index for foreign key reverse lookup
38,151,773
<p>I've read that django creates db_index automatically for all foreign keys. However, does that db_index improve the performance of the reverse lookup as well? </p> <p>For example, if B has a foreign key to A and I use a.b_set.all(), do I enjoy the performance boost from the db index or not?</p> <p>And if not, is th...
1
2016-07-01T18:22:10Z
38,153,632
<p>Let's say the you have a simple model structure:</p> <pre><code>class Author(models.Model): name = models.CharField(max_length=70) email = models.EmailField() class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author) </code></pre> <p>As you mention <code...
1
2016-07-01T20:43:28Z
[ "python", "django", "django-models", "django-filter" ]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 7601: ordinal not in range(128)
38,151,790
<p>I am currently running: Python 3.5.1 :: Anaconda 4.0.0 (x86_64).</p> <p>ERROR: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 7601: ordinal not in range(128)</p> <p>When running the below code I get the above error. When I save and try to open the txt file from a local directy I experience th...
0
2016-07-01T18:23:02Z
38,152,253
<p>Unfortunately, the <a href="http://www1.ncdc.noaa.gov/pub/data/ghcn/daily/readme.txt" rel="nofollow">documentation for that directory</a> does not specify what codec is used for the files, so I opened the file in binary mode instead and found the bytes that caused 'offense'.</p> <p>The data is encoded as UTF-8; the...
2
2016-07-01T18:54:43Z
[ "python", "python-3.5", "python-unicode", "urldecode" ]
Sqlalchemy: Print contents of table
38,151,817
<p>I want to print all the contents of a table using sqalchemy. I can't seem to figure out how inspect works.</p> <p>I want to achieve something like that:</p> <pre><code>column1: value1, column2: value4 column1: value2, column2: value5 column1: value3, column2: value6 </code></pre> <p>In a table that looks like thi...
1
2016-07-01T18:24:55Z
38,152,378
<p>Maybe you have a look here: </p> <p><a href="http://docs.sqlalchemy.org/en/rel_1_0/core/reflection.html" rel="nofollow">http://docs.sqlalchemy.org/en/rel_1_0/core/reflection.html</a></p> <p>The inspector object could help you solving your problem.</p>
0
2016-07-01T19:03:01Z
[ "python", "sqlite", "sqlalchemy" ]
Developer Inactive error when calling UnderArmour api
38,151,820
<p>A 403 "Developer Inactive" error is received when trying to post to the <a href="https://developer.underarmour.com/docs/v71_OAuth_2" rel="nofollow">access_token endpoint</a> in the UnderArmour Connected Fitness api. The <strong>client_id</strong> being used is active. The url used in the call is: <a href="https://ap...
4
2016-07-01T18:25:06Z
38,151,887
<p>All calls made to api.ua.com must include an 'api-key' header value, otherwise, you'll get the 403 Developer Inactive error.</p> <p>This snippet shows how to do it, in python:</p> <pre><code>import requests access_token_url = 'https://api.ua.com/v7.1/oauth2/access_token/' access_token_data = {'grant_type': 'auth...
3
2016-07-01T18:29:25Z
[ "python", "api", "oauth2", "mapmyfitness", "underarmour" ]
Partitioning a List of Dictionaries in Python According to a Value
38,151,826
<p>I have a coding challenge requires me to create a logic that partitions a list of dictionaries into three new lists of dicts. The new lists need to have the same number of experienced and inexperienced personnel. The original list has an even number of experienced and inexperienced personnel. I have no idea how to f...
1
2016-07-01T18:25:23Z
38,151,946
<p>Try slicing the list of dictionaries into three seperate list</p> <pre><code>list1 = mylist[0:2] list2 = mylist[2:4] list3 = mylist[4:6] </code></pre>
0
2016-07-01T18:33:19Z
[ "python", "list", "dictionary", "iteration" ]
Partitioning a List of Dictionaries in Python According to a Value
38,151,826
<p>I have a coding challenge requires me to create a logic that partitions a list of dictionaries into three new lists of dicts. The new lists need to have the same number of experienced and inexperienced personnel. The original list has an even number of experienced and inexperienced personnel. I have no idea how to f...
1
2016-07-01T18:25:23Z
38,152,147
<p>You can have 2 lists - one with experienced and one with inexperienced and build whatever lists you need from that, something like:</p> <pre><code>experienced = [worker for worker in mylist if 'y' == worker['experience']] inexperienced = [worker for worker in mylist if 'n' == worker['experience']] list1, list2, lis...
1
2016-07-01T18:46:08Z
[ "python", "list", "dictionary", "iteration" ]
Partitioning a List of Dictionaries in Python According to a Value
38,151,826
<p>I have a coding challenge requires me to create a logic that partitions a list of dictionaries into three new lists of dicts. The new lists need to have the same number of experienced and inexperienced personnel. The original list has an even number of experienced and inexperienced personnel. I have no idea how to f...
1
2016-07-01T18:25:23Z
38,152,304
<pre><code>def make_teams(my_list): # divide the member list in two experienced = list() novice = list() for record in my_list: if record.get('experience') in ['Y','y']: experienced.append(record) else: novice.append(record) # stitch the two lists together as a list of tuples teams = z...
0
2016-07-01T18:58:28Z
[ "python", "list", "dictionary", "iteration" ]
Python: Input and output filename matching
38,151,866
<p>I'm trying to come up with a way for the filenames that I'm reading to have the same filename as what I'm writing. The code is currently reading the images and doing some processing. My output will be extracting the data from that process into a csv file. I want both the filenames to be the same. I've come across fn...
-2
2016-07-01T18:27:44Z
38,152,059
<p>So if your input file name is in_file = myfile.jpg do this:</p> <pre><code>my_outfile = "".join(infile.split('.')[:-1]) + 'csv' </code></pre> <p>This splits infile into a list of parts that are separated by '.'. It then puts them back together minus the last part, and adds csv</p> <p>your my_outfile will be <cod...
1
2016-07-01T18:40:38Z
[ "python", "filenames", "matching" ]
Python: Input and output filename matching
38,151,866
<p>I'm trying to come up with a way for the filenames that I'm reading to have the same filename as what I'm writing. The code is currently reading the images and doing some processing. My output will be extracting the data from that process into a csv file. I want both the filenames to be the same. I've come across fn...
-2
2016-07-01T18:27:44Z
38,152,119
<p>Well in python it's possible to do that but, the original file might be corrupted if we were to have the same exact file name i.e <code>BibleKJV.pdf</code> to path <code>BibleKJV.pdf</code> will corrupt the first file. Take a look at this script to verify that I'm on the right track (if I'm totally of disregard my a...
1
2016-07-01T18:44:37Z
[ "python", "filenames", "matching" ]
Pandas - Line Graph Subplots with Multiple Indexes
38,151,940
<p>I want to create line graph subplots with each Code per Customer having it's own subplot in a separate file for each customer. </p> <pre><code> Date Code Customer Purchases 1 6/22/2016 6-BZt Piggy 8 2 6/22/2016 7rTPn Piggy 1 3 6/22/2016 Hb4vZ Piggy...
0
2016-07-01T18:32:42Z
38,154,803
<p>So I think the order of operations you'll want to go with is to first split your dataframe into separate dataframes for each Customer, set the index, and then unstack and plot. Given an arbitrary number of customers you can do something like this</p> <pre><code>lineSess.sort_values(by='Customer', inplace=True) line...
0
2016-07-01T22:54:35Z
[ "python", "python-3.x", "pandas", "matplotlib" ]
Converting File Number to Date--Python/matplotlib
38,151,987
<p>I'm currently working with files of data that are chronologically sorted by number, starting with 0000000120 and moving upwards in increments of 120 (so the next is 0000000240, etc). Each file moves forward 5 days, so if 0000000120 is 1/1/02, then 0000000240 would be 1/5/02 and so on. I'm trying to convert these num...
0
2016-07-01T18:36:11Z
38,152,721
<pre><code>date_1 = datetime.datetime.strptime(start_date, "%m/%d/%y") for i, num in enumerate(filenums): num /= 120 endDates+=[date_1 + datetime.timedelta(days=i*5)] </code></pre>
0
2016-07-01T19:26:28Z
[ "python", "matplotlib" ]
Strip everything until any number (0-9) is reached?
38,152,024
<p>How can I strip everything leading up to a number? Of course this would have to work for any number, not just 1.</p> <p>I would like <code>blahblahblah 1 main street</code> as input. And <code>1 main street</code> as output.</p>
3
2016-07-01T18:38:25Z
38,152,093
<p>You can use <a href="https://docs.python.org/2.7/library/itertools.html#itertools.dropwhile" rel="nofollow"><code>itertools.dropwhile</code></a>. Drops everthing before a <code>'1'</code> (or any other number) is reached:</p> <pre><code>from itertools import dropwhile s = 'blahblahblah 1 main street' r = ''.join(d...
5
2016-07-01T18:42:52Z
[ "python", "string", "replace" ]
Strip everything until any number (0-9) is reached?
38,152,024
<p>How can I strip everything leading up to a number? Of course this would have to work for any number, not just 1.</p> <p>I would like <code>blahblahblah 1 main street</code> as input. And <code>1 main street</code> as output.</p>
3
2016-07-01T18:38:25Z
38,152,118
<p>You can use the <code>re</code> module's <code>sub</code> function to replace all non-numerical characters from the left side.</p> <pre><code>import re s = 'blahblahblah 1 main street' re.sub(re.compile(r'^[^0-9]*'), '', s) #Outputs '1 main street' </code></pre>
3
2016-07-01T18:44:32Z
[ "python", "string", "replace" ]
Strip everything until any number (0-9) is reached?
38,152,024
<p>How can I strip everything leading up to a number? Of course this would have to work for any number, not just 1.</p> <p>I would like <code>blahblahblah 1 main street</code> as input. And <code>1 main street</code> as output.</p>
3
2016-07-01T18:38:25Z
38,152,200
<p>Here's an even simpler solution:</p> <pre><code>s = "blahblahblah 1 main street" i = 0 for char in s: if char.isdigit(): s = s[i:] break i += 1 print(s) </code></pre> <p>Just slice the original string starting from the point that you encounter a digit up till the end of the string.</p>
1
2016-07-01T18:50:29Z
[ "python", "string", "replace" ]
Strip everything until any number (0-9) is reached?
38,152,024
<p>How can I strip everything leading up to a number? Of course this would have to work for any number, not just 1.</p> <p>I would like <code>blahblahblah 1 main street</code> as input. And <code>1 main street</code> as output.</p>
3
2016-07-01T18:38:25Z
38,152,359
<p>You could go about doing this by a simple use of ASCII code. ASCII of 0 is 48 and 9 is 57. So you can do something like this:</p> <pre><code>str = raw_input("Enter a string:") print(str) stripstr = "" flag = 0 for i in range(0, len(str)): if flag == 1: stripstr += str[i] elif ord(str[i]) &gt;= 48 an...
0
2016-07-01T19:01:30Z
[ "python", "string", "replace" ]
Issue with passing string from Python to C shared lib using ctypes
38,152,036
<p>I'm having difficulty passing string from Python to C by ctypes:</p> <p>My C code(compiled into a hello.so)</p> <pre><code>... typedef struct test{ unsigned int a; unsigned char* b; } my_struct; int hello(my_struct *in) { FILE *fp; ... fprintf(fp, "%d\t%s\n", in-&gt;a, in-&gt;b); fclos...
5
2016-07-01T18:39:06Z
38,154,181
<p>The solution depends on whether you need the data type to be mutable (from Python's perspective).</p> <p>If don't need the data to be mutable, then don't bother with the buffer constructor. Just pass the <code>bytes</code> object direct to the <code>TEST_STRUCT</code> constructor. eg.</p> <pre><code>from ctypes im...
1
2016-07-01T21:40:04Z
[ "python", "c", "ctypes" ]
List only unique values in column
38,152,052
<p>I want to filter out repeated values and list only unique values in my DataFrame.</p> <p>Lets say I have a df like this:</p> <pre><code> A B 0 1 3 1 2 4 2 3 3 3 1 1 4 3 0 </code></pre> <p>And I want to list only the unique values in column 'A'</p> <p>My desired df</p> <pre><code> ['2'] ...
0
2016-07-01T18:40:08Z
38,152,107
<pre><code>df[~df['A'].duplicated(keep=False)] Out[100]: A B 1 2 4 </code></pre> <p>Or, if you want only the column A:</p> <pre><code>df.loc[~df['A'].duplicated(keep=False), 'A'] Out[102]: 1 2 Name: A, dtype: int64 </code></pre> <p>drop_duplicates would also work like this:</p> <pre><code>df.drop_duplica...
3
2016-07-01T18:43:48Z
[ "python", "list", "pandas" ]
How do you quantize a simple input using python
38,152,081
<p>I am using the below codes to quantise the input signal for quantisation interval of 0.5 and this should give me staircase signal.The algorithm used here is same as used in Simulink.Could any one help me plot the quantised signal.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt for i in range(0,1...
1
2016-07-01T18:41:54Z
38,152,278
<p>Do you mean something like this?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt q = 0.5 x = np.linspace(0, 10, 1000) y = q * np.round(x/q) plt.plot(x,y) </code></pre> <p><a href="http://i.stack.imgur.com/qq0o3.png" rel="nofollow"><img src="http://i.stack.imgur.com/qq0o3.png" alt="Quantized sign...
1
2016-07-01T18:57:00Z
[ "python", "numpy", "matplotlib" ]
django-tastypie : Related data not saving
38,152,123
<p>My <code>models.py</code></p> <pre><code>class Orders(models.Model): order_id = models.CharField(max_length=7, primary_key=True) users = models.ForeignKey(ProductUsers, on_delete=models.DO_NOTHING) address = models.ForeignKey(ProductUsersAddress, on_delete=models.DO_NOTHING) payment_method = models....
2
2016-07-01T18:45:05Z
38,170,243
<p>Try this:</p> <pre><code>def hydrate_m2m(self, bundle): for ordered_product in bundle.data['ordered_products']: if isinstance(ordered_product, dict): ordered_product.update({'orders': bundle.obj}) return super(OrdersResource, self).hydrate_m2m(bundle) </code></pre> <p>and remove <code>...
1
2016-07-03T13:08:44Z
[ "python", "django", "api", "rest", "tastypie" ]
How to unit test if function output list of dictionaries?
38,152,173
<p>I'm writing a unit test for a function that returns a list of dictionaries. What is the best way to check if the output is as expected? Here, "as expected" means the dictionaries in the lists have the same keys and values, irrespective of the order of keys within the dictionary, or of the dictionary's order within ...
3
2016-07-01T18:48:17Z
38,152,222
<p>If you are using <code>unittest</code>, there is <a href="https://docs.python.org/2.7/library/unittest.html#unittest.TestCase.assertItemsEqual" rel="nofollow">a method for this</a>:</p> <pre><code>self.assertItemsEqual(actual_output, expected_output) </code></pre> <p>In Python-3, this method is renamed to <code>as...
4
2016-07-01T18:52:14Z
[ "python", "python-3.x", "testing" ]
In kivy python how to get data from a url request
38,152,228
<p>I am requesting JSON from a url in kivy. In the main App:</p> <pre><code>data = UrlRequest('http://myhost.ninja/request', gotArticles, onFailure) </code></pre> <p>and the callback:</p> <pre><code>def gotArticles(req, results): for key in results: return key </code></pre> <p>when I then <code>print(data)</c...
0
2016-07-01T18:52:41Z
38,153,252
<p>I think it's pretty obvious that you are not attempting to print a function's return(like <code>print(int('1'))</code>), but rather object i.e. the whole <code>UrlRequest</code> class that you assigned to <code>data</code> variable. Same as <code>print(TextInput())</code></p> <p>Try to print a variable from that ob...
0
2016-07-01T20:09:24Z
[ "python", "request", "kivy" ]
TypeError: as_view() takes 1 positional argument but 2 were given
38,152,266
<p>I got an error and I'm not sure what it means: </p> <p><code>TypeError at / as_view() takes 1 positional argument but 2 were given</code></p> <pre><code>from django.db import models from django.contrib.auth.models import User from django.contrib import admin class Employee(models.Model): user = models.OneToOn...
3
2016-07-01T18:56:19Z
38,152,312
<p><code>as_view</code> doesn't take positional arguments, it takes keyword arguments.</p> <pre><code>EmployeeTemplateView.as_view(emp='employees') </code></pre>
5
2016-07-01T18:59:11Z
[ "python", "django", "django-views" ]
TypeError: as_view() takes 1 positional argument but 2 were given
38,152,266
<p>I got an error and I'm not sure what it means: </p> <p><code>TypeError at / as_view() takes 1 positional argument but 2 were given</code></p> <pre><code>from django.db import models from django.contrib.auth.models import User from django.contrib import admin class Employee(models.Model): user = models.OneToOn...
3
2016-07-01T18:56:19Z
38,152,573
<p>Since it looks like you are just trying to pass the <code>employees</code> variable from the view to the template, you can just send it this way:</p> <p><strong>views.py</strong></p> <pre><code>from django.views.generic import ListView from web_app.models import Employee class EmployeeListView(ListView): mode...
1
2016-07-01T19:15:14Z
[ "python", "django", "django-views" ]
Why am I getting incorrect results from scipy.optimize.fmin?
38,152,316
<pre><code>import pandas as pd from scipy.optimize import fmin data = pd.DataFrame({'DIV': [1,2,3]*3, 'MONTH': ['May','May','May','June','June','Jun','Jul','Jul','Jul'], 'C':[8]*9, 'U':[3,2,1]*3, 'S':[9]*9}) data.to_csv(r'C:\Users\mba...
3
2016-07-01T18:59:15Z
38,152,773
<p><code>scipy.optimize.fmin</code> will pass the value it is trying to minimize as the first argument to the function. If you rewrite your function as </p> <pre><code>def e(r,c,u,s): #calculates average of the MAPEs return np.mean(mape(c,u,s,r)) </code></pre> <p>You get the correct results</p> <pre><code>for d ...
3
2016-07-01T19:30:59Z
[ "python", "python-2.7", "pandas", "optimization", "scipy" ]
Python: Pass arguments to function which are stored in a file file
38,152,320
<p>We have a databse from which we run queries. Some of these queries take a (too) long time and and since there seems to be no easy optimization (this has to do with h5py not supporting fast fancy indexing), we decided to make a cache, so that once run queries are fast. This works fine so far.</p> <p>What I would lik...
0
2016-07-01T18:59:23Z
38,275,060
<p>I don't know Python very well, but I think that you simply want to serialize a list of arguments and deserialize it later. If this is the case, something like <a href="https://docs.python.org/2/library/pickle.html" rel="nofollow">pickle</a> should help.</p>
0
2016-07-08T20:39:39Z
[ "python", "file", "caching" ]
How to add None to the list where there is no corresponding value?
38,152,345
<p>For every element from 'b' I need to find its value from 'a' and put it to the resulting list. If there is no corresponding value stored at 'a' I need to put None</p> <p>Example: </p> <pre><code>getValues([("key1", "value1"), ("key2", "value2"), ("key3", "value3")], ["key2","key3","key3","key4","key1","key5"]) </...
1
2016-07-01T19:00:21Z
38,152,411
<pre><code>&gt;&gt;&gt; [dict(a).get(el) for el in b] ['value2', 'value3', 'value3', None, 'value1', None] </code></pre>
2
2016-07-01T19:04:44Z
[ "python", "list", "tuples", "nonetype" ]
How to add None to the list where there is no corresponding value?
38,152,345
<p>For every element from 'b' I need to find its value from 'a' and put it to the resulting list. If there is no corresponding value stored at 'a' I need to put None</p> <p>Example: </p> <pre><code>getValues([("key1", "value1"), ("key2", "value2"), ("key3", "value3")], ["key2","key3","key3","key4","key1","key5"]) </...
1
2016-07-01T19:00:21Z
38,152,605
<p>Starting from your code, what you need to do is figure out whether you found something in <code>a</code> or not. You could <code>break</code> from the inner for loop once you find a match. That way, you can use the <code>for..else</code> syntax to figure out that you need to use <code>None</code> instead:</p> <pre>...
2
2016-07-01T19:17:57Z
[ "python", "list", "tuples", "nonetype" ]
How to remove elements of lists in a dictionary of lists?
38,152,350
<p>I am attempting to filter out pesky <strong><em>None</em></strong> values from a dictionary of lists. Here is an example dictionary:</p> <pre><code>parsed_data = {'DATA1': [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, '0.17998362', '0.0638807...
0
2016-07-01T19:00:57Z
38,152,387
<p>You need to iterate over the elements in the list filtering the Nones and keeping everything else, if you want to change the original just update each list:</p> <pre><code>for v in parsed_data.values(): v[:] = (ele for ele in v if ele is not None) </code></pre> <p>Or if you want a new dict:</p> <pre><code...
2
2016-07-01T19:03:27Z
[ "python", "list", "dictionary" ]
How to remove elements of lists in a dictionary of lists?
38,152,350
<p>I am attempting to filter out pesky <strong><em>None</em></strong> values from a dictionary of lists. Here is an example dictionary:</p> <pre><code>parsed_data = {'DATA1': [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, '0.17998362', '0.0638807...
0
2016-07-01T19:00:57Z
38,152,409
<p>You can use the following <code>dict</code> comprehension then assign it back to <code>parsed_data</code></p> <pre><code>parsed_data = {key: [i for i in value if i] for key, value in parsed_data.items()} </code></pre> <p>Output</p> <pre><code>{'DATA2': [], 'DATA3': [], 'DATA1': ['0.17998362', '0.06388072', '0.0...
2
2016-07-01T19:04:34Z
[ "python", "list", "dictionary" ]
How to remove elements of lists in a dictionary of lists?
38,152,350
<p>I am attempting to filter out pesky <strong><em>None</em></strong> values from a dictionary of lists. Here is an example dictionary:</p> <pre><code>parsed_data = {'DATA1': [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, '0.17998362', '0.0638807...
0
2016-07-01T19:00:57Z
38,153,361
<p>You can create a new dic, set the value of each key to be an empty list, and then append to each list the values that are !=None</p> <pre><code>new_arsed_data={} for key,value in arsed_data.items(): new_arsed_data.setdefault(key,[]) for item in value: if item!=None: new_arsed_data[key].a...
0
2016-07-01T20:19:00Z
[ "python", "list", "dictionary" ]
Validating correct spelling of user input in Python
38,152,372
<p>How would a computer program deal with user misspelling of words in such a way that forces them to reenter until it is correct? e.g. Entering Male and Female for a gender argument. I'm using this Python code:</p> <pre><code>def mean(values): length = len(values) total_sum = 0 for i in range(length): ...
0
2016-07-01T19:02:29Z
38,152,516
<p>Just keep looping until they give a valid input. Do the same for the gender. </p> <pre><code>Age = "" while True: Age = int(input('How old are they?')) if int(Age) &gt;= 18 and int(Age) &lt;= 25: break </code></pre>
0
2016-07-01T19:10:56Z
[ "python" ]
Validating correct spelling of user input in Python
38,152,372
<p>How would a computer program deal with user misspelling of words in such a way that forces them to reenter until it is correct? e.g. Entering Male and Female for a gender argument. I'm using this Python code:</p> <pre><code>def mean(values): length = len(values) total_sum = 0 for i in range(length): ...
0
2016-07-01T19:02:29Z
38,152,575
<p>Simply use a while operator that continues until you have satisfied the condition you wish be satisfied.</p> <pre><code> Gender = "" while Gender != "Male" or Gender != "Female": Gender = raw_input("What is your gender, Male or Female?") </code></pre>
0
2016-07-01T19:15:28Z
[ "python" ]
Validating correct spelling of user input in Python
38,152,372
<p>How would a computer program deal with user misspelling of words in such a way that forces them to reenter until it is correct? e.g. Entering Male and Female for a gender argument. I'm using this Python code:</p> <pre><code>def mean(values): length = len(values) total_sum = 0 for i in range(length): ...
0
2016-07-01T19:02:29Z
38,158,387
<blockquote> <p>"... that forces them to <strong>reenter</strong> until it is correct?... "</p> </blockquote> <p>Since you also asked for a way to re-enter, the following snippet uses an escape sequence of the form <code>\033[&lt;N&gt;A</code> which <a href="http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html" rel...
1
2016-07-02T09:02:17Z
[ "python" ]
Coalesce values from 2 columns into a single column in a pandas dataframe
38,152,389
<p>I'm looking for a method that behaves similarly to coalesce in T-SQL. I have 2 columns (column A and B) that are sparsely populated in a pandas dataframe. I'd like to create a new column using the following rules:</p> <ol> <li>If the value in column A <strong><em>is not null</em></strong>, use that value for the ne...
2
2016-07-01T19:03:34Z
38,152,458
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.combine_first.html" rel="nofollow">combine_first()</a>:</p> <pre><code>In [16]: df = pd.DataFrame(np.random.randint(0, 10, size=(10, 2)), columns=list('ab')) In [17]: df.ix[::2, 'a'] = np.nan In [18]: df Out[18]: a b 0 NaN 0 ...
3
2016-07-01T19:07:37Z
[ "python", "pandas", "dataframe" ]
Coalesce values from 2 columns into a single column in a pandas dataframe
38,152,389
<p>I'm looking for a method that behaves similarly to coalesce in T-SQL. I have 2 columns (column A and B) that are sparsely populated in a pandas dataframe. I'd like to create a new column using the following rules:</p> <ol> <li>If the value in column A <strong><em>is not null</em></strong>, use that value for the ne...
2
2016-07-01T19:03:34Z
38,153,693
<p>Try this also.. easier to remember: </p> <pre><code>df['c'] = np.where(df["a"].isnull, df["b"], df["a"] ) </code></pre> <p>This is slighty faster: <code>df['c'] = np.where(df["a"].isnull == True, df["b"], df["a"] )</code></p> <pre><code>%timeit df['d'] = df.a.combine_first(df.b) 1000 loops, best of 3: 472 µs pe...
2
2016-07-01T20:48:58Z
[ "python", "pandas", "dataframe" ]
How to execute UPDATE query with SQLAlchemy SQL-builder in python?
38,152,416
<p>If have a sqlalchemy database and want to run an update query. I thought I could just use the same method that I also use for SELECT commands.</p> <p>Here's my code:</p> <pre><code>disk_engine = create_engine('sqlite:///test.db') chunksize = 20000 j = 0 index_start = 1 for df in pd.read_csv('test.csv', chunksize=...
0
2016-07-01T19:05:02Z
38,152,805
<p>If the exact string <code>UPDATE data SET score = ROUND(score,1)</code> is what you want to be executed, you should be able to execute that from a connection to <code>disk_engine</code>. For example:</p> <pre><code>conn = disk_engine.connect() result = conn.execute('UPDATE data SET score = ROUND(score,1)') </code><...
0
2016-07-01T19:33:15Z
[ "python", "pandas", "dataframe", "sqlalchemy" ]
My function is confused about whether or not it wants a second argument (python, matplotlib)
38,152,419
<p>I'm writing a (should be) simple program in Python using Tkinter and Matplotlib to control a machine. It's my first Python program, so apologies for any egregious non-conventions, and I welcome all feedback. Also, sorry for the large code block.</p> <p>I'm trying to have a main page for controls, and a secondary ...
1
2016-07-01T19:05:14Z
38,152,697
<p>That i must be defined, you can check how 'frames' work in FuncAnimation. I will suggest you to read the documentation about matplotlib.animation.FuncAnimation. </p>
1
2016-07-01T19:24:39Z
[ "python", "matplotlib", "tkinter" ]
How to adjust x limits in subplot without shrinking colorbar
38,152,473
<p>I have a set of subplots that each require a colorbar. If I plot each subplot without setting the x limits, the x-axis extends past the domain of my data and shows a lot of white space. I'm using this code:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.mlab import griddata from numpy import ma from...
0
2016-07-01T19:08:29Z
38,157,205
<p>Instead of</p> <pre><code>make_subplot(axarr[0], x, y, z1, "Plot 1") plt.xlim(0,14) make_subplot(axarr[1], x, y, z2, 'Plot 2') plt.xlim(0,14) make_subplot(axarr[2], x, y, z3, 'Plot 3') plt.xlim(0,14) </code></pre> <p>try</p> <pre><code>make_subplot(axarr[0], x, y, z1, "Plot 1") axarr[0].set_xlim(0,14) make_s...
0
2016-07-02T06:27:46Z
[ "python", "matplotlib" ]
Why is my program printing to only one line instead of a seperate line?
38,152,526
<p>so i'm using this snippet of code:</p> <pre><code>def print_slow(str): for letter in str: print letter, time.sleep(.1) </code></pre> <p>from this link on SO: <a href="http://stackoverflow.com/questions/4099422/print-slowly-in-python-simulate-typing?newreg=117d11c5570c472ebfce62191fb8d55f">print slowly ...
0
2016-07-01T19:11:59Z
38,152,539
<p>You are missing a newline; normally <code>print</code> outputs that, but not if you add a <code>,</code> comma at the end.</p> <p>You could insert an extra blank <code>print</code> between calls to <code>print_slow()</code> to write one:</p> <pre><code>print_slow("MEME QUEST!") print time.sleep(.5) print_slow("BY ...
2
2016-07-01T19:13:00Z
[ "python" ]
Why is my program printing to only one line instead of a seperate line?
38,152,526
<p>so i'm using this snippet of code:</p> <pre><code>def print_slow(str): for letter in str: print letter, time.sleep(.1) </code></pre> <p>from this link on SO: <a href="http://stackoverflow.com/questions/4099422/print-slowly-in-python-simulate-typing?newreg=117d11c5570c472ebfce62191fb8d55f">print slowly ...
0
2016-07-01T19:11:59Z
38,152,567
<p>You could just simply add a newline character</p> <pre><code>print_slow("MEME QUEST!\n") </code></pre>
0
2016-07-01T19:14:38Z
[ "python" ]
Why is my program printing to only one line instead of a seperate line?
38,152,526
<p>so i'm using this snippet of code:</p> <pre><code>def print_slow(str): for letter in str: print letter, time.sleep(.1) </code></pre> <p>from this link on SO: <a href="http://stackoverflow.com/questions/4099422/print-slowly-in-python-simulate-typing?newreg=117d11c5570c472ebfce62191fb8d55f">print slowly ...
0
2016-07-01T19:11:59Z
38,152,674
<p>The comma after your </p> <pre><code>print letter, </code></pre> <p>statement is suppressing it from printing a new line. </p> <p>Try </p> <pre><code>import time def print_slow(string): for letter in string: print letter, time.sleep(.1) print '\n' print_slow("hello") pri...
0
2016-07-01T19:22:53Z
[ "python" ]
Passing list to string formatter in Python
38,152,564
<p>I am making a Python script to turn a CSV into a GeoJSON file, however, I want to use it over again with different datasets, and don't want to hard code anything. I am trying to pass a list of items to a string formatter within a loop. I keep getting errors and saw that Python can take a list as an argument in a fun...
-1
2016-07-01T19:14:27Z
38,152,649
<p>That's not how positional expansion works. But it's the wrong tool anyways.</p> <pre><code>output += template % tuple(property_arr) </code></pre>
0
2016-07-01T19:21:31Z
[ "python", "loops", "parameter-passing", "string-formatting" ]
Optimizing djangos count() method
38,152,602
<p>So I have this queryset:</p> <pre><code>from django.contrib.gis.db.models.query import GeoQuerySet from django.db import models as base_models class RestaurantsQuerySet(GeoQuerySet): def get_list(self, lng, lat): reference_point = Point(lng, lat, srid=SRID) return self.annotate(rating=models.A...
2
2016-07-01T19:17:44Z
38,157,787
<p>After browsing through django-rest-framework code I came up with this idea:</p> <ol> <li><p>Override default <code>Paginator</code> class for a given view:</p> <p><code>class RestaurantList(generics.ListAPIView): pagination_class = custom.LimitOffsetPagination</code></p></li> <li><p>Create custom pagination cl...
0
2016-07-02T07:41:59Z
[ "python", "sql", "django", "django-rest-framework" ]
accessing router via telnet lib python
38,152,644
<p>I'm working on a code that uses telnetlib of python to connect to a router and execute commands and stores the output in a file.</p> <p>I'm using read_until('#') function and expecting a Router prompt, then execute the next command but my code freezes when I receive a '--More--' data from the remote telnet side. I ...
0
2016-07-01T19:21:08Z
38,157,763
<blockquote> <p>sometime the --More-- keyword doesn't come at once</p> </blockquote> <p>Try passing in a timeout.</p> <p>Example: set timeout to 5 seconds for <a href="https://docs.python.org/2/library/telnetlib.html#telnetlib.Telnet.read_until" rel="nofollow">read_until()</a>:</p> <pre><code>read_until('--More--...
0
2016-07-02T07:37:58Z
[ "python", "telnetlib" ]
Iterating over columns with for loops in pandas dataframe
38,152,686
<p>I am trying to take a dataframe read in from CSV file, and generate scatter plots for each column within the dataframe. For example, I have read in the following with <code>df=pandas.readcsv()</code></p> <pre><code>Sample AMP ADP ATP 1A 239847 239084 987374 1B 245098 241210 988950 2A 2...
1
2016-07-01T19:23:58Z
38,152,771
<p><code>iteritems</code> iterates over columns, not rows. But your real problem is when you are trying to <code>df[row]</code> instead of <code>df[index]</code>. I'd switch wording to columns and do this:</p> <pre><code>for colname, col in df.iteritems(): p = figure() p.scatter(df['Sample'], df[colname]) show(p) </...
1
2016-07-01T19:30:47Z
[ "python", "pandas", "dataframe", "bokeh" ]
Tweepy user_id and trailing L
38,152,778
<p>I have a list of followers, I'd like to follow. The one problem that I'm having is that it appears the user_id has to be an int, not a string, and can't have the trailing L. I have some large numbers as id. For example</p> <pre><code>user_id = 900000000000000L </code></pre> <p>I tried changing using a few suggest...
-1
2016-07-01T19:31:18Z
38,152,840
<p><code>900000000000000L</code> is of type <code>long</code> which is an int-like class. When integers get too big to represent, the automatically convert to long... e.g.:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.maxint 9223372036854775807 &gt;&gt;&gt; sys.maxint + 1 9223372036854775808L </code></pre>...
3
2016-07-01T19:35:23Z
[ "python", "int", "long-integer", "tweepy" ]
Python: getting file names using regular expression?
38,152,799
<p>I have thousands of these lines in a list:</p> <blockquote> <p>[/usr/local/sa/ftp/collectorftp/AVideoP05D20160608000020E310.txt.gz, /usr/local/sa/ftp/collectorftp/AHTTPP05D20160608000008E307.txt.gz, /usr/local/sa/ftp/collectorftp/AVideoP05D20160608000122E322.txt.gz]</p> </blockquote> <p>I need to get just fi...
-5
2016-07-01T19:32:52Z
38,152,833
<p>Just use <code>split</code>:</p> <pre><code>name.split('/')[-1] </code></pre>
0
2016-07-01T19:35:12Z
[ "python", "regex" ]
Python: getting file names using regular expression?
38,152,799
<p>I have thousands of these lines in a list:</p> <blockquote> <p>[/usr/local/sa/ftp/collectorftp/AVideoP05D20160608000020E310.txt.gz, /usr/local/sa/ftp/collectorftp/AHTTPP05D20160608000008E307.txt.gz, /usr/local/sa/ftp/collectorftp/AVideoP05D20160608000122E322.txt.gz]</p> </blockquote> <p>I need to get just fi...
-5
2016-07-01T19:32:52Z
38,152,844
<p>You wouldn't need a regex for this. A <em>rightward</em> split on <code>'/'</code> should do:</p> <pre><code>[i.rsplit('/')[-1] for i in lst] </code></pre>
0
2016-07-01T19:35:43Z
[ "python", "regex" ]
Python: getting file names using regular expression?
38,152,799
<p>I have thousands of these lines in a list:</p> <blockquote> <p>[/usr/local/sa/ftp/collectorftp/AVideoP05D20160608000020E310.txt.gz, /usr/local/sa/ftp/collectorftp/AHTTPP05D20160608000008E307.txt.gz, /usr/local/sa/ftp/collectorftp/AVideoP05D20160608000122E322.txt.gz]</p> </blockquote> <p>I need to get just fi...
-5
2016-07-01T19:32:52Z
38,152,846
<h1>Use the right tool for the job.</h1> <p><strong>Much safer option</strong> is to use <code>os.path.basename(..)</code> than <code>string.split(..)</code></p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; paths = "/usr/local/sa/ftp/collectorftp/AVideoP05D20160608000020E310.txt.gz, /usr/local/sa/ftp/collectorftp/A...
1
2016-07-01T19:35:55Z
[ "python", "regex" ]
Python: getting file names using regular expression?
38,152,799
<p>I have thousands of these lines in a list:</p> <blockquote> <p>[/usr/local/sa/ftp/collectorftp/AVideoP05D20160608000020E310.txt.gz, /usr/local/sa/ftp/collectorftp/AHTTPP05D20160608000008E307.txt.gz, /usr/local/sa/ftp/collectorftp/AVideoP05D20160608000122E322.txt.gz]</p> </blockquote> <p>I need to get just fi...
-5
2016-07-01T19:32:52Z
38,152,848
<p>This is a simple task to do using the split operator. All you need to do is the following:</p> <pre><code>[item.split('/')[-1] for item in you_list] </code></pre> <p>This will take each item in the list an splits the item using <code>/</code>, -1 will be the last item of the list which is the result of split.</p>
0
2016-07-01T19:36:13Z
[ "python", "regex" ]
Using list items as keys in a python dictionary
38,152,834
<p>I'm working with a large CSV file in python and I'm trying to create a dictionary based on lists of text tied to a unique identifier. In the CSV, the values in each cell of the Items column were originally free text and are now comma separated lists. The data looks like this:</p> <pre><code>ID Items 123 'A...
-2
2016-07-01T19:35:13Z
38,165,403
<p>Based on the file format you gave, this will work. But depending on what edge cases you have you may have to modify the regexs. I didn't use the csv reader because for this case a regex seemed easy enough not to.</p> <pre><code># import regular expressions import re itemLookup = dict() file = 'data.csv' with open(...
0
2016-07-02T23:40:11Z
[ "python", "csv", "dictionary", "key" ]
Python startswith error in OpenCV
38,152,898
<p>I have just installed OpenCV 3 (using <a href="http://www.pyimagesearch.com/2015/10/26/how-to-install-opencv-3-on-raspbian-jessie/" rel="nofollow">this</a> tutorial) on my raspberry pi 2 model b and i found this code that should work with my version of openCV and python(3):</p> <pre><code>from picamera.array impor...
0
2016-07-01T19:40:43Z
38,173,756
<p>I was having the same issue. Based on <a href="http://stackoverflow.com/questions/19827615/startswith-typeerror-in-function">this answer</a>, it appears to be an error in picamera/encoders.py. After editing the end of line 534 of picamera/encoders.py to: ... <code>.startswith(b'vc.ril.video_splitter')</code> I was a...
0
2016-07-03T19:47:19Z
[ "python", "python-3.x", "opencv", "image-processing", "raspberry-pi" ]
replacing black background with another image
38,152,940
<p>I am trying to replace all black pixels in an image with pixels of another image...</p> <p>this is the code I have so far-</p> <pre><code>imgFront = cv2.imread('withoutbackground.jpg') imgBack = cv2.imread('background.jpg') height, width = img.shape[:2] resizeBack = cv2.resize(imgBack, (width, height), interpola...
0
2016-07-01T19:43:37Z
38,153,278
<p>I don't believe it is possible to make a .jpg background transparent (see post: <a href="http://stackoverflow.com/questions/16906144/transparent-background-in-jpeg-image">Transparent background in JPEG image</a>. </p> <p>You can try PNG or GIF instead.</p>
-2
2016-07-01T20:12:01Z
[ "python", "opencv" ]
replacing black background with another image
38,152,940
<p>I am trying to replace all black pixels in an image with pixels of another image...</p> <p>this is the code I have so far-</p> <pre><code>imgFront = cv2.imread('withoutbackground.jpg') imgBack = cv2.imread('background.jpg') height, width = img.shape[:2] resizeBack = cv2.resize(imgBack, (width, height), interpola...
0
2016-07-01T19:43:37Z
38,179,385
<p>Your idea is correct, but there are some minor mistakes.</p> <p>First, in line 3, it should be the shape of <code>imgFront</code> right?:</p> <pre><code>height, width = imgFront.shape[:2] </code></pre> <p>Second, in line <code>if pixel == [255, 255, 255]:</code> you should change it to :</p> <pre><code>np.all(pi...
0
2016-07-04T07:47:36Z
[ "python", "opencv" ]
How to iterate when you don't know if your object will be iterable
38,153,008
<p>Sometimes I have multiple axes in <code>axes[0]</code>, and sometimes just one. So to iterate over it/them, I use the following:</p> <p><code>for ax,_x in [(axes[0], X[0])] if len(X)==1 else zip(axes[0],X):</code></p> <p>What is the idiomatic way to do this?</p>
3
2016-07-01T19:49:28Z
38,154,282
<p>In general, the best way is to just iterate. <a href="https://docs.python.org/3/glossary.html#term-eafp" rel="nofollow">Don't ask for permission</a> (with <code>if</code> checks, rather wrap it in a <code>try-except</code> block for handling the "forgiveness" cases.</p> <p>As others have commented though, you shoul...
0
2016-07-01T21:49:41Z
[ "python", "python-3.x" ]
How can I scrape data from a <span> locked tag?
38,153,046
<p>I'm using <code>bs4</code> and <code>urllib2</code> to fetch some info from a website.</p> <p>Here's the <a href="http://www.ribeiraosaude.com.br/detalhe/937" rel="nofollow">webpage</a>.</p> <p>I must fetch the rest of the telephone <code>3610...</code>... but first I must press this button to show the rest of the...
3
2016-07-01T19:52:37Z
38,153,171
<p>The phone number is loaded from the response to the <code>http://www.ribeiraosaude.com.br/home/GetTelefone/&lt;id&gt;</code> url, make this request with <code>requests</code> and extract the phone number from the JSON response:</p> <pre><code>import requests from bs4 import BeautifulSoup page_id = 937 with request...
3
2016-07-01T20:03:21Z
[ "python", "html", "web-scraping", "beautifulsoup" ]