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 |
|---|---|---|---|---|---|---|---|---|---|
Can I use more than 26 letters in `numpy.einsum`? | 37,794,245 | <p>I am using <code>np.einsum</code> to multiply probability tables like:</p>
<pre><code>np.einsum('ijk,jklm->ijklm', A, B)
</code></pre>
<p>The issue is that I am dealing with more than 26 random variables (axes) overall, so if I assign each random variable a letter I run out of letters. Is there another way I ca... | 4 | 2016-06-13T15:56:18Z | 37,796,451 | <p>The short answer is, you can use any of the 52 letters (upper and lower). That's all the letters in the English language. Any fancier axes names will have to be mapped on those 52, or an equivalent set of numbers. Practically speaking you will want to use a fraction of those 52 in any one <code>einsum</code> call... | 4 | 2016-06-13T18:08:42Z | [
"python",
"numpy",
"numpy-einsum"
] |
python how to split test files from code into separate directories | 37,794,249 | <p>Below is a fizzbuzz program done TDD using unittest in one file, I run it in the command line using <code>python fizzbuzz.py -v</code>.</p>
<pre><code>import unittest
class FizzBuzz():
def fizz_buzz(self, number):
if number % 3 == 0 and number % 5 == 0:
return 'fizzbuzz'
if number ... | 1 | 2016-06-13T15:56:28Z | 37,795,015 | <p>It has to do with how python finds and executes code.</p>
<p>Python looks for modules/scripts/packages using <code>sys.path</code>.
When you run a python script, it appends the directory of that script to <code>sys.path</code> which would be <code>/etc/fizzbuzz/tests</code>. This will not let python find the folder... | 0 | 2016-06-13T16:40:29Z | [
"python",
"unit-testing"
] |
newlines in double quotes in reading CSV in python | 37,794,283 | <p>I have a csv file in the following format:</p>
<pre><code>"4931286","Lotion","New York","Bright color, yellow with 5" long
20% nylon"
"931286","Shampoo","New York","Dark, yellow with 10" long
20% nylon"
"3931286","Conditioner","LA","Bright color, yellow with 5" long
50% nylon"
</code></pre>
<p>The above data shoul... | 2 | 2016-06-13T15:58:03Z | 37,794,621 | <p>How about iterating over every two lines, </p>
<pre><code>import csv
from StringIO import StringIO
from itertools import izip
def pairwise(iterable):
"s -> (s0, s1), (s2, s3), (s4, s5), ..."
a = iter(iterable)
return izip(a, a)
file = StringIO(""""4931286","Lotion","New York","Bright color, yellow... | 1 | 2016-06-13T16:17:45Z | [
"python",
"csv",
"pandas"
] |
newlines in double quotes in reading CSV in python | 37,794,283 | <p>I have a csv file in the following format:</p>
<pre><code>"4931286","Lotion","New York","Bright color, yellow with 5" long
20% nylon"
"931286","Shampoo","New York","Dark, yellow with 10" long
20% nylon"
"3931286","Conditioner","LA","Bright color, yellow with 5" long
50% nylon"
</code></pre>
<p>The above data shoul... | 2 | 2016-06-13T15:58:03Z | 37,794,694 | <p>The data is not in CSV format.</p>
<p><code>"</code> in CSV must be escaped with <code>\</code> like <code>"Bright color, yellow\n with 5\" long 20% nylon"</code>.</p>
<p>If <code>"</code> is only used for inches (prefixed with number) try this:</p>
<pre><code>import re
data = re.sub(r'([0-9])"(?![,\n])', r'\1... | 3 | 2016-06-13T16:22:06Z | [
"python",
"csv",
"pandas"
] |
Measure time a user stays in a webpage and display it for the admin (Python - Django) | 37,794,336 | <p>I have a website built in django. All pages are static. Now I'm trying to measure time each user spends in each page and display it in a table.
Currently I'm working on an idea I got in another similar topic as in the link:
<a href="http://stackoverflow.com/questions/4667068/how-to-measure-a-time-spent-on-a-page">Ho... | 0 | 2016-06-13T16:00:58Z | 37,805,289 | <p>Sending the data <code>onunload</code> may or may not work.</p>
<p>Another way would be to ping your server every x seconds, so you know that the use has the page still open.</p>
<pre><code>setInterval(function () {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://127.0.0.1:8000",false);
xm... | 0 | 2016-06-14T07:12:22Z | [
"javascript",
"python",
"html",
"django"
] |
How to get rows of a tsv file with common values in one of the columns using pandas? | 37,794,352 | <p>I have a tsv (tab separated) file with data like this:</p>
<pre><code>1 102 apple
2 102 orange
3 103 grapes
4 103 banana
5 103 carrot
</code></pre>
<p>I want to get the rows of the file which have common values in the second field. And, then I want to perform operations on individual elements of each group. So I a... | 0 | 2016-06-13T16:02:07Z | 37,794,497 | <p>Would be helpful to see the output of <code>df.info()</code> after <code>pd.read_csv()</code>. In any case, you should probably do </p>
<pre><code>pd.read_csv(file, sep='\t', header=None)
</code></pre>
<p>and then set the columns using </p>
<pre><code>df.columns = ['A', 'B', 'C']
</code></pre>
<p>or do the same ... | 1 | 2016-06-13T16:10:46Z | [
"python",
"python-2.7",
"csv",
"pandas"
] |
How do I implement this similarity measure in Python? | 37,794,520 | <p>I tried implementing the distance measure shown in the image, in Python as such:</p>
<pre><code>import numpy as np
A = [1, 2, 3, 4, 5, 6, 7, 8, 1]
B = [1, 2, 3, 2, 4, 6, 7, 8, 2]
A = np.asarray(A).flatten()
B = np.asarray(B).flatten()
x = np.sum(1 - np.divide((1 + np.minimum(A, B)), (1 + np.maximum(A, B))))
prin... | 2 | 2016-06-13T16:11:51Z | 37,794,671 | <p>This should work. First, we create a matrix <code>AB</code> by stacking the columns and calculate the minimum vector <code>AB_min</code> and maximum vector <code>AB_max</code> out of that. Then, we compute <code>D</code> as you defined it, making use of <code>numpy.where</code> to specify the two conditions. After t... | 1 | 2016-06-13T16:20:24Z | [
"python",
"numpy",
"math"
] |
Download modules in python 2.7 and not 3.4 | 37,794,585 | <p>I have python 3.4 and 2.7 installed in my ubuntu. I have most of my required modules installed in python 3.4 but I want to install them in python 2.7 also. Whenever I try the normal installation commands, I get <code>Requirement already satisfied</code> due to the module already being installed in python 3.4. How ca... | 0 | 2016-06-13T16:15:46Z | 37,794,684 | <p>With two versions of python installed, specify the specific version of pip on invocation. For example: <code>pip2.7 install numpy</code></p>
| 0 | 2016-06-13T16:21:31Z | [
"python",
"python-2.7"
] |
Download modules in python 2.7 and not 3.4 | 37,794,585 | <p>I have python 3.4 and 2.7 installed in my ubuntu. I have most of my required modules installed in python 3.4 but I want to install them in python 2.7 also. Whenever I try the normal installation commands, I get <code>Requirement already satisfied</code> due to the module already being installed in python 3.4. How ca... | 0 | 2016-06-13T16:15:46Z | 37,795,065 | <p>Have you tried:</p>
<pre><code>sudo apt-get install python-numpy
</code></pre>
| 0 | 2016-06-13T16:44:27Z | [
"python",
"python-2.7"
] |
Download modules in python 2.7 and not 3.4 | 37,794,585 | <p>I have python 3.4 and 2.7 installed in my ubuntu. I have most of my required modules installed in python 3.4 but I want to install them in python 2.7 also. Whenever I try the normal installation commands, I get <code>Requirement already satisfied</code> due to the module already being installed in python 3.4. How ca... | 0 | 2016-06-13T16:15:46Z | 37,795,259 | <p>My pip --version has this return:</p>
<pre><code>pip 8.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
</code></pre>
<p>verify what's return. The default is:</p>
<p>use pip3 to python 3.4: </p>
<pre><code>sudo apt-get install python3-pip
</code></pre>
<p>and pip to python 2.7.</p>
<p>Try uninstall... | 0 | 2016-06-13T16:55:45Z | [
"python",
"python-2.7"
] |
equivalent of Matlab's gaminv in python | 37,794,648 | <p>I would like to translate the following Matlab code in Python:</p>
<pre><code> tau=40 %scale parameter
a=3 %shape parameter
t = gaminv(0.90,a,tau);
</code></pre>
<p>The code returns t = 212.8928. I've tried:</p>
<pre><code> import scipy.stats.distributions as dist
tau=40
a=3
t = dist.invgamma.cdf(90, a, sca... | 0 | 2016-06-13T16:18:55Z | 37,795,020 | <p>You want the <code>ppf</code> ("percent point function", which is a somewhat less common name for the inverse of the CDF or quantile function) method of <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html" rel="nofollow"><code>scipy.stats.gamma</code></a>:</p>
<pre><code>In [27]: fro... | 4 | 2016-06-13T16:40:56Z | [
"python",
"matlab",
"scipy",
"gamma-distribution"
] |
Twython filters track and follow | 37,794,716 | <p>i need obtain tweets in real time with filters and certain accounts. I try with this:</p>
<pre><code>filtro="messi,copa100,copaamierica"
personas="488916863,3034605958" #twitters ids here
stream.statuses.filter(track=filtro, follow=[personas])
</code></pre>
<p>but only use the track filter, not the follow filter.<... | 0 | 2016-06-13T16:23:05Z | 37,796,632 | <p>I think you are using <a href="https://dev.twitter.com/streaming/reference/post/statuses/filter" rel="nofollow"><code>filter</code></a> method wrongly. It should be:</p>
<pre><code>filtro= ["messi", "copa100", "copaamierica"] # Exact matching of keywords
personas= ["488916863", "3034605958"] # Comma-separate... | 0 | 2016-06-13T18:20:06Z | [
"python",
"twitter-streaming-api",
"twython"
] |
Selenium: Dynamically loaded page causes automatic scrolling to fail | 37,794,784 | <p>I'm using <code>Selenium</code> for Python to navigate a dynamic webpage (<a href="http://en.boerse-frankfurt.de/etp/Deka-Oekom-Euro-Nachhaltigkeit-UCITS-ETF-DE000ETFL474" rel="nofollow">link</a>).</p>
<p>I would like to automatically scroll down to a y-point on the page. I have tried various ways to code this, whi... | 2 | 2016-06-13T16:26:45Z | 37,794,858 | <p><em>It is just quite a dynamic page</em>. I would <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow">wait for this specific element to be visible</a> and then <em>scroll into it's view</em>. This works for me:</p>
<pre><code>from selenium import webdriver
from selenium.webdrive... | 2 | 2016-06-13T16:31:06Z | [
"python",
"selenium"
] |
How to append global list variable in try/except exception in Python? | 37,794,813 | <p>I'm trying to append global list variable with new words in try/except exceptions, but after try/except I get empty list.</p>
<pre><code> list = [] # created empty list with global scope
def try_multiple_operations(j):
try:
jopen = urllib2.urlopen(j) #... | -1 | 2016-06-13T16:28:24Z | 37,794,877 | <p>In your code, the function <code>try_multiple_operations</code> is never called. Hence no elements are added to the list. After calling it the list will contain the expected elements:</p>
<pre><code>list = [] # created empty list with global scope
def try_multiple_operations(j):
... | -1 | 2016-06-13T16:31:56Z | [
"python"
] |
How to append global list variable in try/except exception in Python? | 37,794,813 | <p>I'm trying to append global list variable with new words in try/except exceptions, but after try/except I get empty list.</p>
<pre><code> list = [] # created empty list with global scope
def try_multiple_operations(j):
try:
jopen = urllib2.urlopen(j) #... | -1 | 2016-06-13T16:28:24Z | 37,795,287 | <p>You have several problems. First, <code>list</code> (which really should be renamed so that you don't shadow the built-in <code>list</code> function) is empty, so </p>
<pre><code>futures = [executor.submit(try_multiple_operations, j) for j in list]
</code></pre>
<p>runs your function zero times.</p>
<p>The second... | 2 | 2016-06-13T16:57:26Z | [
"python"
] |
Efficient and precise calculation of the euclidean distance | 37,794,849 | <p>Following some online research (<a href="http://stackoverflow.com/a/1401828/6182051">1</a>, <a href="http://www.codehamster.com/2015/03/09/different-ways-to-calculate-the-euclidean-distance-in-python/" rel="nofollow">2</a>, <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html" rel="nof... | 2 | 2016-06-13T16:30:39Z | 37,795,087 | <p>As a general rule of thumb, stick to the <code>scipy</code> and <code>numpy</code> implementations where possible, as they're vectorized and much faster than native Python code. (Main reasons are: implementations in C, vectorization eliminates type checking overhead that looping does.)</p>
<p>(Aside: My answer does... | 0 | 2016-06-13T16:46:01Z | [
"python",
"python-3.x",
"euclidean-distance"
] |
Efficient and precise calculation of the euclidean distance | 37,794,849 | <p>Following some online research (<a href="http://stackoverflow.com/a/1401828/6182051">1</a>, <a href="http://www.codehamster.com/2015/03/09/different-ways-to-calculate-the-euclidean-distance-in-python/" rel="nofollow">2</a>, <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html" rel="nof... | 2 | 2016-06-13T16:30:39Z | 37,795,190 | <h3>Conclusion first:</h3>
<p>From the test result by using <code>timeit</code> for efficiency test, we can conclude that <strong>regarding the efficiency</strong>:</p>
<p><strong><code>Method5 (zip, math.sqrt)</code> > <code>Method1 (numpy.linalg.norm)</code> > <code>Method2 (scipy.spatial.distance)</code> > <code>M... | 2 | 2016-06-13T16:51:37Z | [
"python",
"python-3.x",
"euclidean-distance"
] |
Efficient and precise calculation of the euclidean distance | 37,794,849 | <p>Following some online research (<a href="http://stackoverflow.com/a/1401828/6182051">1</a>, <a href="http://www.codehamster.com/2015/03/09/different-ways-to-calculate-the-euclidean-distance-in-python/" rel="nofollow">2</a>, <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html" rel="nof... | 2 | 2016-06-13T16:30:39Z | 37,800,568 | <p>I don't know how the precision and speed compares to the other libraries you mentioned, but you can do it for 2D vectors using the built-in <code>math.hypot()</code> function:</p>
<pre><code>from math import hypot
def pairwise(iterable):
"s -> (s0, s1), (s1, s2), (s2, s3), ..."
a, b = iter(iterable), it... | 1 | 2016-06-13T23:11:46Z | [
"python",
"python-3.x",
"euclidean-distance"
] |
Pause URL request Downloads | 37,794,874 | <pre><code>import urllib.request
import re
import csv
import pandas as pd
from bs4 import BeautifulSoup
columns = []
data = []
f = open('companylist.csv')
csv_f = csv.reader(f)
for row in csv_f:
stocklist = row
print(stocklist)
for s in stocklist:
print('http://finance.yahoo.com/q?s='+s)
... | 0 | 2016-06-13T16:31:48Z | 37,795,344 | <p>To pause after every 200 downloads, you could - also when you use <code>pandas_datareader</code>:</p>
<pre><code>import time
for i, s in enumerate(stocklist):
if i % 200 == 0:
time.sleep(5) # in seconds
</code></pre>
<p>To save all data into a single file (IIUC):</p>
<pre><code>stocks = pd.DataFrame()... | 0 | 2016-06-13T17:00:57Z | [
"python",
"python-3.x",
"pandas",
"finance",
"datareader"
] |
Pause URL request Downloads | 37,794,874 | <pre><code>import urllib.request
import re
import csv
import pandas as pd
from bs4 import BeautifulSoup
columns = []
data = []
f = open('companylist.csv')
csv_f = csv.reader(f)
for row in csv_f:
stocklist = row
print(stocklist)
for s in stocklist:
print('http://finance.yahoo.com/q?s='+s)
... | 0 | 2016-06-13T16:31:48Z | 37,796,218 | <p>Use <code>python_datareader</code> for this. </p>
<pre><code>In [1]: import pandas_datareader.data as web
In [2]: import datetime
In [3]: start = datetime.datetime(2010, 1, 1)
In [4]: end = datetime.datetime(2013, 1, 27)
In [5]: f = web.DataReader("F", 'yahoo', start, end)
In [6]: f.ix['2010-01-04']
Out[6]:
... | 1 | 2016-06-13T17:54:22Z | [
"python",
"python-3.x",
"pandas",
"finance",
"datareader"
] |
Pause URL request Downloads | 37,794,874 | <pre><code>import urllib.request
import re
import csv
import pandas as pd
from bs4 import BeautifulSoup
columns = []
data = []
f = open('companylist.csv')
csv_f = csv.reader(f)
for row in csv_f:
stocklist = row
print(stocklist)
for s in stocklist:
print('http://finance.yahoo.com/q?s='+s)
... | 0 | 2016-06-13T16:31:48Z | 37,797,875 | <p>As @Merlin has recommended you - take a closer look at <code>pandas_datareader</code> module - you can do a LOT using this tool. Here is a small example:</p>
<pre><code>import csv
import pandas_datareader.data as data
from pandas_datareader.yahoo.quotes import _yahoo_codes
stocklist = ['aapl','goog','fb','amzn','C... | 1 | 2016-06-13T19:39:10Z | [
"python",
"python-3.x",
"pandas",
"finance",
"datareader"
] |
Python: "__init__() takes 2 positional arguments but 3 were givenâ with Webdriver, when the element locator info is pulled from a separate file | 37,794,898 | <p>I am fairly new to Python and Selenium, and am trying to get some automated testing of our website off the ground. I am setting the tests up using the page object model so that changes to locators only need to be updated in one place. As part of this, I am setting up a function to wait for our subscribe button to be... | 1 | 2016-06-13T16:32:56Z | 37,794,908 | <p>Just <em>don't unpack the locator at all</em>, pass it as is, as a tuple:</p>
<pre><code>wait.until(EC.element_to_be_clickable(MainPageLocators.subscribe_button))
</code></pre>
| 1 | 2016-06-13T16:33:50Z | [
"python",
"selenium",
"selenium-webdriver",
"pageobjects"
] |
Encoding Issue when using Item in Scrapy in Python | 37,794,901 | <p>My Item class is as follows:</p>
<pre><code>class SkeletonItem(scrapy.Item):
name = scrapy.Field()
</code></pre>
<p>In the parse() function of spider class, the logic is as follows:</p>
<pre><code>soup = BeautifulSoup(response.body, 'html.parser')
si = SkeletonItem()
si['name'] = li.find("div", {"class": "inf... | 0 | 2016-06-13T16:33:20Z | 37,801,231 | <p>I think you will find your answer <a href="https://github.com/scrapy/scrapy/issues/1963#issuecomment-215943619" rel="nofollow">here</a>.</p>
| 1 | 2016-06-14T00:37:24Z | [
"python",
"unicode",
"encoding",
"scrapy"
] |
Regular expressions for password in Python 3 | 37,794,949 | <p>I want to verify if user's password is:</p>
<ol>
<li>Consists of 8 characters</li>
<li>Consists of numbers and letters</li>
<li>At least one big letter and one number</li>
<li>It should contain $ or ! or ?</li>
<li>The order doesn't matter</li>
</ol>
<p>My code is:</p>
<pre><code>r.match(r'([A-Z]+)([a-z])([0-9]+)... | -4 | 2016-06-13T16:36:18Z | 37,795,642 | <p>This seems to work tested in IDLE 2.7.9. Keep in mind this only matches with 8 characters</p>
<p><code>^(?=.*[!$?])(?=.*[a-z])(?=.*[A-Z]).{8}$</code></p>
<pre><code>import re
p = re.compile('^(?=.*[!$?])(?=.*[a-z])(?=.*[A-Z]).{8}$')
test_str = 'a2Cd$F!8'
if re.search(p, test_str):
print('string matched')
</cod... | 1 | 2016-06-13T17:20:23Z | [
"python",
"regex"
] |
Regular expressions for password in Python 3 | 37,794,949 | <p>I want to verify if user's password is:</p>
<ol>
<li>Consists of 8 characters</li>
<li>Consists of numbers and letters</li>
<li>At least one big letter and one number</li>
<li>It should contain $ or ! or ?</li>
<li>The order doesn't matter</li>
</ol>
<p>My code is:</p>
<pre><code>r.match(r'([A-Z]+)([a-z])([0-9]+)... | -4 | 2016-06-13T16:36:18Z | 37,795,937 | <p>I guess the obvious non-regex way would be:</p>
<pre><code>symbols = '$!?'
if (len(pwd) >= 8 and
any(c.isdigit() for c in pwd) and
any(c.isupper() for c in pwd) and
any(c in symbols for c in pwd) and
all(c.isalnum() or c in symbols for c in pwd)):
print('good password')
else:
... | 0 | 2016-06-13T17:37:36Z | [
"python",
"regex"
] |
Regular expressions for password in Python 3 | 37,794,949 | <p>I want to verify if user's password is:</p>
<ol>
<li>Consists of 8 characters</li>
<li>Consists of numbers and letters</li>
<li>At least one big letter and one number</li>
<li>It should contain $ or ! or ?</li>
<li>The order doesn't matter</li>
</ol>
<p>My code is:</p>
<pre><code>r.match(r'([A-Z]+)([a-z])([0-9]+)... | -4 | 2016-06-13T16:36:18Z | 37,796,124 | <p>At least on my system, doing the check without using <code>re</code> is a little faster. Also, the speed difference seems to get more pronounced as the password length increases. </p>
<pre><code>import re
import timeit
passwords_varied = ("kk", "999999999999999999999999", "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk... | 0 | 2016-06-13T17:49:12Z | [
"python",
"regex"
] |
How to build a list of tags from classes in a hierarchy | 37,794,966 | <p>There's a logger that uses "tags" and some other dotted-namespace-things to divvy up events. My program implements logic across various classes, most of which are inherited, but some are mixins.</p>
<p>How can I cleanly have the various levels of inheritance build up a list of items available to the final object, i... | 1 | 2016-06-13T16:37:41Z | 37,798,347 | <p>That is the "typical" use case for metaclasses. The normal class creation process in Python uses the "type" metaclass: it is responsible for creating the correct <code>__mro__</code> attribute which enables multiple inheritance. By extending the metaclass behavior we can make the <code>_tags</code> attribute to be ... | 0 | 2016-06-13T20:12:29Z | [
"python",
"multiple-inheritance"
] |
Find where a certain string of numbers occurs using Regex | 37,794,978 | <p>Out of a large text file I want to extract all the places where "RA"+6 numbers after it occur. How would I do this? </p>
<p>For instance, I want the new txt file to look like</p>
<pre><code>RA000000
RA111111
RA222222
RA333333
RA444444
</code></pre>
<p>Where other instances of RA do not show up either.</... | -2 | 2016-06-13T16:38:33Z | 37,795,139 | <p>This might work for you:</p>
<pre><code>import re
with open('input.txt') as input_file:
ra_list = re.findall(r'RA\d{6}', input_file.read())
with open('output.txt', 'w') as output_file:
output_file.write('\n'.join(ra_list) + '\n')
</code></pre>
<p>Tested input:</p>
<pre><code>hello
RA111111 goodbye
RA222... | 0 | 2016-06-13T16:48:54Z | [
"python",
"regex"
] |
Find where a certain string of numbers occurs using Regex | 37,794,978 | <p>Out of a large text file I want to extract all the places where "RA"+6 numbers after it occur. How would I do this? </p>
<p>For instance, I want the new txt file to look like</p>
<pre><code>RA000000
RA111111
RA222222
RA333333
RA444444
</code></pre>
<p>Where other instances of RA do not show up either.</... | -2 | 2016-06-13T16:38:33Z | 37,795,171 | <p>The regex is '^(RA\d{6})$'. Then print each time the capture group 1 was found. </p>
| 0 | 2016-06-13T16:50:29Z | [
"python",
"regex"
] |
Nearest value of a given value | 37,795,044 | <p>Given this pandas Series.</p>
<p><code>x = pd.Series([5, 10])</code></p>
<p>I use searchsorted and a loop to find the closest value of the looped number, X.</p>
<pre><code>for X in xrange(1, 11):
print X, x.searchsorted(X)
</code></pre>
<p>What is returned.</p>
<pre><code>1 [0]
2 [0]
3 [0]
4 [0]
5 [0]
6 [1]... | 3 | 2016-06-13T16:42:52Z | 37,795,256 | <p>Instead of <code>.searchsorted()</code> you could also check for the <code>index</code> of the <code>pd.Series</code> value that minimizes the <code>absolute</code> difference to the value in question:</p>
<pre><code>import numpy as np
for X in range(1, 11):
print(X, (np.abs(x - X)).argmin())
1 0
2 0
3 0
4 0
5... | 4 | 2016-06-13T16:55:30Z | [
"python",
"numpy",
"pandas"
] |
Removing elements corresponding to 'None' in lists | 37,795,060 | <p>I have two lists </p>
<pre><code>x = [ None , None , "foo" , "bar" ]
y = [ "bar" , "foo" , "foo" ,"bar"]
len(x) == len(y)
</code></pre>
<p>I want to check if there exists an element in list <code>x</code> that is <code>None</code> then remove that element and remove corresponding element in y too .
like remove <c... | 1 | 2016-06-13T16:44:00Z | 37,795,153 | <p>Using the <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow">zip</a> method you can do this very nicely:</p>
<pre><code>x, y = zip(*[(e_x, e_y) for e_x, e_y in zip(x, y) if e_x is not None])
</code></pre>
<p>Here you iterate over both lists at once, creating a new list with tuples contai... | 3 | 2016-06-13T16:49:35Z | [
"python"
] |
Removing elements corresponding to 'None' in lists | 37,795,060 | <p>I have two lists </p>
<pre><code>x = [ None , None , "foo" , "bar" ]
y = [ "bar" , "foo" , "foo" ,"bar"]
len(x) == len(y)
</code></pre>
<p>I want to check if there exists an element in list <code>x</code> that is <code>None</code> then remove that element and remove corresponding element in y too .
like remove <c... | 1 | 2016-06-13T16:44:00Z | 37,795,157 | <p>First go through and figure out what you need to remove:</p>
<pre><code>remove_ix = {ix for ix, val in enumerate(x) if val is None}
</code></pre>
<p>Now you can use it to filter <code>x</code> and <code>y</code>:</p>
<pre><code>x = [item for ix, item in enumerate(x) if ix not in remove_ix]
y = [item for ix, item ... | 0 | 2016-06-13T16:49:44Z | [
"python"
] |
Removing elements corresponding to 'None' in lists | 37,795,060 | <p>I have two lists </p>
<pre><code>x = [ None , None , "foo" , "bar" ]
y = [ "bar" , "foo" , "foo" ,"bar"]
len(x) == len(y)
</code></pre>
<p>I want to check if there exists an element in list <code>x</code> that is <code>None</code> then remove that element and remove corresponding element in y too .
like remove <c... | 1 | 2016-06-13T16:44:00Z | 37,795,193 | <p>Let's call your lists xs and ys.</p>
<pre><code>ys = [y for (x, y) in zip(xs, ys) if x]
xs = [x for x in xs if x]
</code></pre>
<p>should do the trick. </p>
| 3 | 2016-06-13T16:51:47Z | [
"python"
] |
Removing elements corresponding to 'None' in lists | 37,795,060 | <p>I have two lists </p>
<pre><code>x = [ None , None , "foo" , "bar" ]
y = [ "bar" , "foo" , "foo" ,"bar"]
len(x) == len(y)
</code></pre>
<p>I want to check if there exists an element in list <code>x</code> that is <code>None</code> then remove that element and remove corresponding element in y too .
like remove <c... | 1 | 2016-06-13T16:44:00Z | 37,795,282 | <p>I think the most performant way to achieve desired output would be dict comprehension. In that case you avoid avoid 2 list comprehension expressions:</p>
<pre><code>x_list = [ None , None , "foo" , "bar" ]
y_list = [ "bar" , "foo" , "foo" ,"bar"]
d = {val:y_list[i] for i,val in enumerate(x_list) if val is not None}... | 0 | 2016-06-13T16:57:13Z | [
"python"
] |
Removing elements corresponding to 'None' in lists | 37,795,060 | <p>I have two lists </p>
<pre><code>x = [ None , None , "foo" , "bar" ]
y = [ "bar" , "foo" , "foo" ,"bar"]
len(x) == len(y)
</code></pre>
<p>I want to check if there exists an element in list <code>x</code> that is <code>None</code> then remove that element and remove corresponding element in y too .
like remove <c... | 1 | 2016-06-13T16:44:00Z | 37,795,341 | <p>Use <code>zip</code> to remove items that are <code>None</code> (in x) from matching pairs of x and y, then use another <code>zip(*...)</code> to transpose the list of lists back to the references x and y:</p>
<pre><code>x, y = zip(*[[ix, iy] for ix, iy in zip(x, y) if ix is not None])
</code></pre>
| 0 | 2016-06-13T17:00:48Z | [
"python"
] |
Numbers not adding correctly | 37,795,212 | <p>So I am trying to make a list which contains the running total of a list of numbers, however I still want the first number to be displayed without anything being added to it, sort of like this:</p>
<p>Input<br>
0.1<br>
0.3<br>
0.2<br>
0.4<br>
0.2<br></p>
<p>Desired Output<br>
0.1<br>
0.4<br>
0.6<br>
1.0<br>
1.2<br... | 0 | 2016-06-13T16:53:05Z | 37,795,294 | <pre><code>widthtotal = float(width[0])
h = open("WidthValue1.txt", "w")
for line in width[1:19]:
widthtotal += float(line)
</code></pre>
<p><code>widthtotal</code> already contains 0.1 before the loop begins, and <code>0.3</code> gets added to it before you print anything. So it's not too surprising that <code>0.... | 1 | 2016-06-13T16:57:57Z | [
"python"
] |
Best way to trigger a function when DateField in model expires | 37,795,296 | <p>I have a "Contest" model that a user creates and one of the fields is</p>
<p><code>(endTime = models.DateField(default=datetime.now()+timedelta(days=7))</code>. </p>
<p>I need a method to run a function when their contest has expired. The function would be to notify users, update objects, etc.</p>
<p>What would b... | 1 | 2016-06-13T16:57:59Z | 37,795,618 | <p>To schedule a task you can look <a href="http://stackoverflow.com/questions/573618/django-set-up-a-scheduled-job">here</a></p>
<p>as for a this question,</p>
<blockquote>
<p>procedure to identify that the datetime field has passed</p>
</blockquote>
<p>This would work:</p>
<pre><code>Contest.objects.filter(endT... | 1 | 2016-06-13T17:18:12Z | [
"python",
"django",
"python-3.x"
] |
Control Atomic Transactions in Django | 37,795,302 | <p>I have a simple library application. In order to force 3 actions to commit as one action, and rollback if any of the actions fail, I made the following code changes:</p>
<p>In <code>settings.py</code>:</p>
<pre><code>AUTOCOMMIT=False
</code></pre>
<p>In <code>forms.py</code></p>
<pre><code>from django.db import ... | 0 | 2016-06-13T16:58:18Z | 37,818,860 | <p>You're using <code>transaction.atomic()</code> correctly (including putting the <code>try ... except</code> outside the transaction) but you should definitely not be setting <code>AUTOCOMMIT = False</code>.</p>
<p>As the <a href="https://docs.djangoproject.com/en/dev/ref/settings/#autocommit" rel="nofollow">documen... | 1 | 2016-06-14T17:48:25Z | [
"python",
"mysql",
"django",
"atomicity"
] |
How to put multi lines i? | 37,795,515 | <p>I am planning to put one line text</p>
<p>So, how can I get the text started from TOP-LEFT?</p>
<p>Hope you understand my english and my problem. </p>
<p>Thank you all.</p>
| 1 | 2016-06-13T17:12:59Z | 37,796,376 | <p>The label will only take as much room as it needs to contain the text, when the root window is resized the label itself will position itself top center even if the text inside it is <code>justified=LEFT</code></p>
<p>To position the label to the left side of the root window use <code>anchor=W</code> when <code>pack... | 3 | 2016-06-13T18:04:12Z | [
"python",
"tkinter"
] |
Python 3 - Limiting Memory Usage from a Script | 37,795,520 | <p>I am using the itertools module to create a list of possible permutations for the order of letters in a rather long sentence. However, every time I do so I run out of memory (I have 16GB RAM before anyone asks).</p>
<p>I don't have the code on this machine, however it is not inefficient code since it is a carbon co... | 1 | 2016-06-13T17:13:13Z | 37,796,802 | <p>You can just loop over the permutations and write each of them to the file, like this:</p>
<pre><code>import itertools
f = open('File.txt','w')
for key, value in dict.items():
for i in itertools.permutations((str(counter-value))):
print(i, file=f)
</code></pre>
<p>As it is a generator, the items are re... | 0 | 2016-06-13T18:30:34Z | [
"python",
"python-3.x",
"memory",
"memory-management",
"memory-leaks"
] |
Python Matplotlib histogram bin shift | 37,795,540 | <p>I have created a cumulative (CDF) histogram from a list which is what I wanted. Then I subtracted a fixed value (by using <code>x = [ fixed_value - i for i in myArray]</code>) from each element in the list to essential just shift the bins over a fixed amount. This however makes my CDF histogram inverted in the y-ax... | 1 | 2016-06-13T17:14:20Z | 37,798,264 | <p>I think that the problem might be in how you calculate the shifted values. This example works fine for me:</p>
<pre><code>import numpy as np
import matplotlib.pylab as pl
original_array = np.random.normal(size=100)
bins = np.linspace(-5,5,11)
pl.figure()
pl.subplot(121)
pl.hist(original_array, bins, normed=1, cum... | 1 | 2016-06-13T20:06:47Z | [
"python",
"python-2.7",
"matplotlib",
"histogram",
"cdf"
] |
Python Matplotlib histogram bin shift | 37,795,540 | <p>I have created a cumulative (CDF) histogram from a list which is what I wanted. Then I subtracted a fixed value (by using <code>x = [ fixed_value - i for i in myArray]</code>) from each element in the list to essential just shift the bins over a fixed amount. This however makes my CDF histogram inverted in the y-ax... | 1 | 2016-06-13T17:14:20Z | 37,798,328 | <p>Your problem has nothing to do with histograms, but purely with the fact that you write <code>x = [ fixed_value - i for i in myArray]</code>, rather than <code>x = [i - fixed_value for i in myArray]</code>. Check the following example:</p>
<pre><code>import numpy as np
import pylab as pl
x = np.linspace(0, 10., 10... | 1 | 2016-06-13T20:11:09Z | [
"python",
"python-2.7",
"matplotlib",
"histogram",
"cdf"
] |
Prune a list of combinations based on sets | 37,795,593 | <p>While this question is formulated using the Python programming language, I believe it is more of a programming logic problem. </p>
<p>I have a list of all possible combinations, i.e.: n choose k</p>
<p>I can prepare such a list using</p>
<pre><code>import itertools
bits_list = list(itertools.combinations(range(n)... | 4 | 2016-06-13T17:17:17Z | 37,796,819 | <p>A faster implementation would be to replace the if and all() statements in:</p>
<pre><code>bits_list = [x for x in list(itertools.combinations(range(n), k))
if all(y in x for y in [0, 1, 2]) or
all(y not in x for y in [0, 1, 2])]
</code></pre>
<p>with python's set operations <code>isdisj... | 0 | 2016-06-13T18:31:56Z | [
"python",
"algorithm"
] |
Prune a list of combinations based on sets | 37,795,593 | <p>While this question is formulated using the Python programming language, I believe it is more of a programming logic problem. </p>
<p>I have a list of all possible combinations, i.e.: n choose k</p>
<p>I can prepare such a list using</p>
<pre><code>import itertools
bits_list = list(itertools.combinations(range(n)... | 4 | 2016-06-13T17:17:17Z | 37,797,756 | <p>This still gets crushed by a memory error (<em>which I don't see how you're getting away from if you insist on a list</em>) at a certain point (around n=90, k=5), but it is much faster than your current implementation. For <code>n=80</code> and <code>k=5</code>, my rudimentary benchmarking had my solution at 2.6 sec... | 2 | 2016-06-13T19:32:30Z | [
"python",
"algorithm"
] |
Prune a list of combinations based on sets | 37,795,593 | <p>While this question is formulated using the Python programming language, I believe it is more of a programming logic problem. </p>
<p>I have a list of all possible combinations, i.e.: n choose k</p>
<p>I can prepare such a list using</p>
<pre><code>import itertools
bits_list = list(itertools.combinations(range(n)... | 4 | 2016-06-13T17:17:17Z | 37,797,977 | <p>If you actually represented your bits as bits, that is, 0/1 values in a binary representation of an integer n bits long with exactly k bits set, the amount of RAM you'd need to store the data would be drastically smaller. </p>
<p>Also, you'd be able to use bit operations to look check if all bits in a <code>mask</... | 1 | 2016-06-13T19:46:04Z | [
"python",
"algorithm"
] |
Prune a list of combinations based on sets | 37,795,593 | <p>While this question is formulated using the Python programming language, I believe it is more of a programming logic problem. </p>
<p>I have a list of all possible combinations, i.e.: n choose k</p>
<p>I can prepare such a list using</p>
<pre><code>import itertools
bits_list = list(itertools.combinations(range(n)... | 4 | 2016-06-13T17:17:17Z | 37,913,183 | <p>Based on the ideas from <a href="http://stackoverflow.com/a/37797756/3919475">@Mitch's answer</a>, I created a solution with a slightly different thinking than originally presented in the question. Instead of creating the list (<code>bits_list</code>) of all combinations and then pruning those combinations that do n... | 0 | 2016-06-20T00:19:15Z | [
"python",
"algorithm"
] |
File dialog in python sl4a | 37,795,626 | <p>I am looking for an simple file chooser dialog in <code>sl4a</code>. I have found a few native dialogs <a href="http://pythoncentral.io/python-android-androids-native-dialogs-sl4a/" rel="nofollow">here</a> but did not find the one I was looking for.</p>
<p>I wish I could save time by finding something readily avail... | 1 | 2016-06-13T17:18:49Z | 37,808,251 | <p>I decided to write my own (see below for reference). This could probably be made better, any suggestions welcome.</p>
<pre><code>import android, os, time
droid = android.Android()
# Specify root directory and make sure it exists.
base_dir = '/sdcard/sl4a/scripts/'
if not os.path.exists(base_dir): os.makedirs(base_... | 0 | 2016-06-14T09:35:50Z | [
"python",
"dialog",
"sl4a"
] |
'if i, j in zip(range...)' gives syntax error in python | 37,795,655 | <p>I am trying to move a sprite depending on a direction entered in a different section of code, but I am getting a syntax error. </p>
<pre><code>def move(self, direction):
if i, j in zip(range(4),[[0,-1],[0,1],[-1,0],[1,0]]):
if direction == i:
Character.x+= j[0]
Character.y += j[1... | -1 | 2016-06-13T17:21:01Z | 37,795,713 | <p>I think you meant to write <code>for</code> not <code>if</code>:</p>
<pre><code>for i, j in zip(range(4),[[0,-1],[0,1],[-1,0],[1,0]]):
</code></pre>
| 0 | 2016-06-13T17:24:00Z | [
"python",
"pygame"
] |
'if i, j in zip(range...)' gives syntax error in python | 37,795,655 | <p>I am trying to move a sprite depending on a direction entered in a different section of code, but I am getting a syntax error. </p>
<pre><code>def move(self, direction):
if i, j in zip(range(4),[[0,-1],[0,1],[-1,0],[1,0]]):
if direction == i:
Character.x+= j[0]
Character.y += j[1... | -1 | 2016-06-13T17:21:01Z | 37,795,986 | <p>You <em>could</em> use a <code>for</code> loop, as shown in Simon's answer, but there's a much simpler way that doesn't use loops or <code>zip</code>.</p>
<pre><code>def move(self, direction):
steps = [[0,-1], [0,1], [-1,0], [1,0]]
j = steps[direction]
Character.x += j[0]
Character.y += j[1]
</code>... | 1 | 2016-06-13T17:40:45Z | [
"python",
"pygame"
] |
how to converting sting into dateobject for date comparison? | 37,795,664 | <p>I am facing trouble while converting string into dateobject in python.
I want to convert string '10 JAN 2016" to dateobject so that i can compare it to the present date and get the time difference. </p>
<p>I tired but i am getting formatting error.What is the solution to this problem?</p>
| 0 | 2016-06-13T17:21:19Z | 37,795,734 | <p>Use the <a href="https://docs.python.org/2/library/datetime.html#" rel="nofollow"><code>datetime</code></a> module.</p>
<pre><code>import datetime
date = datetime.datetime.strptime('10 jan 2016`,'%d %b %Y').date()
difference_in_dates = date - datetime.date.today() #this returns a timedelta object
</code></pre>
<p>... | 1 | 2016-06-13T17:25:10Z | [
"python"
] |
how to converting sting into dateobject for date comparison? | 37,795,664 | <p>I am facing trouble while converting string into dateobject in python.
I want to convert string '10 JAN 2016" to dateobject so that i can compare it to the present date and get the time difference. </p>
<p>I tired but i am getting formatting error.What is the solution to this problem?</p>
| 0 | 2016-06-13T17:21:19Z | 37,795,806 | <p>You need to use a valid format.</p>
<p>Try looking here: <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior</a></p>
<pre><code>dt = '10 JAN 2016'
dtime = datetime.datetime.strptime(dt... | -1 | 2016-06-13T17:28:56Z | [
"python"
] |
Renaming file extension in Python 2.7 | 37,795,776 | <p>I am trying to rename the extension of a text file to zip as advised <a href="http://stackoverflow.com/questions/2900035/changing-file-extension-in-python">here</a>.
The file is being written based on a base64 encoded response from a server, which I am decoding before writing.</p>
<p>This is my code snippet:</p>
<... | 0 | 2016-06-13T17:27:25Z | 37,795,868 | <pre><code>file1 = "C:\Users\xyz\response.txt"
</code></pre>
<p>"\r" is a single character representing a carriage return. You probably don't have a file that has a carriage return in its name. If you intended that to be a backslash followed by an R, use raw strings.</p>
<pre><code>file1 = r"C:\Users\xyz\response.txt... | 2 | 2016-06-13T17:32:23Z | [
"python",
"rename"
] |
Renaming file extension in Python 2.7 | 37,795,776 | <p>I am trying to rename the extension of a text file to zip as advised <a href="http://stackoverflow.com/questions/2900035/changing-file-extension-in-python">here</a>.
The file is being written based on a base64 encoded response from a server, which I am decoding before writing.</p>
<p>This is my code snippet:</p>
<... | 0 | 2016-06-13T17:27:25Z | 37,795,888 | <p>Try changing this line:</p>
<pre><code>file1 = "C:\Users\xyz\response.txt"
</code></pre>
<p>to this:</p>
<pre><code>file1 = "C:\\Users\\xyz\\response.txt"
</code></pre>
<p>or this:</p>
<pre><code>file1 = r"C:\Users\xyz\response.txt"
</code></pre>
| 0 | 2016-06-13T17:33:26Z | [
"python",
"rename"
] |
Django - custom userprofile NoSuchTable error | 37,796,097 | <p>I'm writing an app in django. I wanted to add some custom fields to User model.</p>
<p>I've been following this guide:</p>
<p><a href="http://www.tangowithdjango.com/book/chapters/login.html" rel="nofollow">http://www.tangowithdjango.com/book/chapters/login.html</a></p>
<p>Login works fine, but while executing re... | 0 | 2016-06-13T17:47:35Z | 37,797,127 | <p>I fixed it. My mistake was that i assumed that </p>
<blockquote>
<p>python manage.py migrate</p>
</blockquote>
<p>and</p>
<blockquote>
<p>python manage.py makemigrations </p>
</blockquote>
<p>will do everything for me. As it turned out i had to use </p>
<blockquote>
<p>python manage.py makemigrations appn... | -1 | 2016-06-13T18:51:49Z | [
"python",
"django"
] |
having this error TypeError: cannot concatenate 'str' and 'int' objects when trying to do math with variables stored with pickle | 37,796,119 | <p>I'm having this error </p>
<pre><code>TypeError: cannot concatenate 'str' and 'int' objects
</code></pre>
<p>when I'm trying to do calculations with variables sent using pickle from my client file to my server when a second computer joins my server heres my code for my server </p>
<pre><code>import socket, select... | -2 | 2016-06-13T17:49:01Z | 37,796,332 | <p>You replaced the <code>pjoin</code> <em>integer</em> with a string:</p>
<pre><code># at the top
pjoin = 0
# inside the while True and for clientInList loops
pjoin = pickle.dumps(pjoin)
</code></pre>
<p><code>pickle.dumps()</code> returns a string object. Next time you get a response from a client, you'll now will... | 1 | 2016-06-13T18:01:38Z | [
"python",
"python-2.7",
"integer",
"pickle"
] |
de-duplication function that only keeps the minimum for every 5 sec of previous value | 37,796,154 | <p>I have a question: </p>
<p>Write a de-duplication function that only keeps the minimum for every 5 sec of previous value</p>
<pre><code>0.0 (keep)
2.3 (drop)
4.1 (drop)
5.3 (keep)
7.5 (drop)
8.3 (drop)
10.2 (drop)
11.4 (keep)
</code></pre>
<p>How do I this is sql and Python in as quick as possible?</p>
<p>Consid... | -4 | 2016-06-13T17:51:04Z | 37,796,265 | <p>I do know what kind of data you have.<br>
you can add data with time created to the list than compare the latest on with new item.</p>
<pre><code>keepLst = []
if not keepLst:
keepLst.append(item)
else:
if item.created_time() - keepLst[-1].created_time() > 5:
keepLst.append(item)
</code></pre>
<p>or <b... | 0 | 2016-06-13T17:57:54Z | [
"python",
"sql"
] |
python SQLite3 update row id when removing one row | 37,796,241 | <p>I've been building a python/flask website, and it works so far, but because I actually need/use the count(id) (where id is the auto-increment primary key), I can't just remove some rows randomly.</p>
<p>Do anyone know the best way to update every other higher IDs when removing one row, kinda like a list, so the cou... | -4 | 2016-06-13T17:55:44Z | 37,798,632 | <p>One way to recreate sequential numbering of your key is to drop the table and reconstruct it. Consider the <code>renumber()</code> function in the code below:</p>
<pre><code>import sqlite3
from pprint import pprint
schema = '''
create table S (
id integer primary key autoincrement not null,
con... | 0 | 2016-06-13T20:31:46Z | [
"python",
"sql",
"sqlite3"
] |
parsing xml content in python | 37,796,347 | <p>I want to write information from xml to dict in Python.
Below is xml file:</p>
<pre><code><data>
<files>
<links>
<item>
<file_name>file1</file_name>
<id>100</id>
</item>
<item>
<file_name>file2</file... | 1 | 2016-06-13T18:02:36Z | 37,797,124 | <p>Using <a href="https://github.com/martinblech/xmltodict" rel="nofollow"><code>xmltodict</code></a> this simple code can be used to extract your dictionary:</p>
<p>install <code>xmltodict</code> with <code>pip install xmltodict</code></p>
<pre><code>import xmltodict
doc = xmltodict.parse("""
<data>
<fil... | 1 | 2016-06-13T18:51:42Z | [
"python",
"xml"
] |
parsing xml content in python | 37,796,347 | <p>I want to write information from xml to dict in Python.
Below is xml file:</p>
<pre><code><data>
<files>
<links>
<item>
<file_name>file1</file_name>
<id>100</id>
</item>
<item>
<file_name>file2</file... | 1 | 2016-06-13T18:02:36Z | 37,825,724 | <p>Beautiful Soup should help you</p>
<p>Link - <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/</a></p>
<p>Something like this should work</p>
<pre><code>from bs4 import BeautifulSoup
soup = BeautifulSoup("""
<data>
<files>
<... | 0 | 2016-06-15T03:44:08Z | [
"python",
"xml"
] |
Query for MongoDB Associative Arrays | 37,796,351 | <p>I am writing a python script to query a MongoDB database. I am in need of assistance with querying, filtering, and parsing data that is stored in associative arrays.</p>
<p>Requirements:</p>
<ul>
<li><p>Query Hostname, Last seen date, Status, and IPV4 Address (other fields not needed)</p></li>
<li><p>Parse the dat... | 0 | 2016-06-13T18:02:59Z | 37,798,587 | <p>You need to <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/" rel="nofollow"><code>$unwind</code></a> the "hostnames" array or use the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt/" rel="nofollow"><code>$arrayElemAt</code></a> operator to access t... | 1 | 2016-06-13T20:29:17Z | [
"python",
"mongodb",
"pymongo",
"aggregation-framework"
] |
creating a request to replace curl -XDelete - Python | 37,796,395 | <p>I'm executing the following <code>cURL</code> command to clean an Elastic Search index:</p>
<pre><code>curl -s -XDELETE "http://<server>/<server_index>/<index>/_query" -d '{
"query":{"match_all":{}}}
}'
</code></pre>
<p>However, I don't to execute a shell script or a <code>subprocess</code> c... | 0 | 2016-06-13T18:05:09Z | 37,808,975 | <p>The equivalent requests code should be something like:</p>
<pre><code>data = {"query": {"match_all": {}}}
import requests
r = requests.delete("http://<server>/<server_index>/<index>/_query", data=data)
</code></pre>
| 0 | 2016-06-14T10:06:38Z | [
"python",
"http",
"post",
"curl",
"python-requests"
] |
How to complete this function then print it out, using Python? | 37,796,453 | <p>I'm having a hard time to understand how to work with functions - I can make then but after that I don't know how to use them. My question is how can I print this code with a function?</p>
<pre><code>string = "Hello"
reverse = string[::-1]
print(reverse)
</code></pre>
<p>I tried putting it in a function but I cann... | 0 | 2016-06-13T18:08:49Z | 37,796,666 | <p>I don't know whether you are asking how to define functions in python or something else</p>
<p>If you want to learn python functions, go to <a href="http://www.tutorialspoint.com/python/python_functions.htm" rel="nofollow">http://www.tutorialspoint.com/python/python_functions.htm</a> or just write python tutorial i... | 1 | 2016-06-13T18:22:24Z | [
"python",
"reverse"
] |
How to complete this function then print it out, using Python? | 37,796,453 | <p>I'm having a hard time to understand how to work with functions - I can make then but after that I don't know how to use them. My question is how can I print this code with a function?</p>
<pre><code>string = "Hello"
reverse = string[::-1]
print(reverse)
</code></pre>
<p>I tried putting it in a function but I cann... | 0 | 2016-06-13T18:08:49Z | 37,796,752 | <pre><code># defines the 'Reverse a String' function and its arguments
def reverse_a_string():
print(string)
reverse = string[::-1]
print(reverse)
print("Type a string") # asks the user for a string input
string = input() # assigns whatever the user input to the string variable
reverse_a_string() # simply... | 1 | 2016-06-13T18:27:36Z | [
"python",
"reverse"
] |
How to complete this function then print it out, using Python? | 37,796,453 | <p>I'm having a hard time to understand how to work with functions - I can make then but after that I don't know how to use them. My question is how can I print this code with a function?</p>
<pre><code>string = "Hello"
reverse = string[::-1]
print(reverse)
</code></pre>
<p>I tried putting it in a function but I cann... | 0 | 2016-06-13T18:08:49Z | 37,796,832 | <p>Once you create a function you must call it. You have created the function <code>reverse_a_string</code> but then you never actually call it. Think about a function as a button that does something everytime it is pushed (or in our case called). If you never push the button then although it has the potential to do so... | 2 | 2016-06-13T18:32:35Z | [
"python",
"reverse"
] |
How to complete this function then print it out, using Python? | 37,796,453 | <p>I'm having a hard time to understand how to work with functions - I can make then but after that I don't know how to use them. My question is how can I print this code with a function?</p>
<pre><code>string = "Hello"
reverse = string[::-1]
print(reverse)
</code></pre>
<p>I tried putting it in a function but I cann... | 0 | 2016-06-13T18:08:49Z | 37,796,834 | <h1>Functions without a return value</h1>
<p>Functions that just take action or do something without returning a value (for example, <code>print</code>).<br/>
Functions that don't return a value can be defined like that:</p>
<pre><code>def sayHello():
print "Hello!"
</code></pre>
<p>And can be used (called) like... | 2 | 2016-06-13T18:32:39Z | [
"python",
"reverse"
] |
Tweepy error: attribute error | 37,796,502 | <p>The code was working fine but all of a sudden this error started to raise, though I did not change my codebase.</p>
<pre><code>searched_tweets = ( status._json for status in tweepy.Cursor(api.search, q=query, count=300, since=from_date, until=to_date,
File "build/bdist.linux-x86_64/egg/tweepy/cursor.py", line 197... | 0 | 2016-06-13T18:11:38Z | 37,819,989 | <p>I was able to solve this issue by installing Anaconda3.4 and then,</p>
<blockquote>
<blockquote>
<p>pip3 install tweepy</p>
</blockquote>
</blockquote>
<p>I suppose that it was a dependency or an update issue.</p>
| 0 | 2016-06-14T18:54:35Z | [
"python",
"twitter",
"urllib",
"tweepy"
] |
How to call a function in view by clicking a button in django? | 37,796,566 | <p>I am trying to call the function ssl_verify from my html template . But it gives 404 error. Can anyone help me with this? Where i am wrong ?</p>
<pre><code>#views.py
def ssl_verify( request , dns, port ):
if request.is_ajax():
result = dns + port
return result
#urls.py
url(r'ssl_verify/(\d+)/(\d+)/$', ... | -2 | 2016-06-13T18:15:10Z | 37,797,200 | <p>Your urls.py must contain (replace the regexp line)</p>
<pre><code>url(r'^ssl_verify/(?P<dns>[^/]+)/(?P<port>[^/]+)/$','views.check_ssl'),
</code></pre>
<p>or if you import:</p>
<pre><code>from views import check_ssl
....
url(r'^ssl_verify/(?P<dns>[^/]+)/(?P<port>[^/]+)/$','check_ssl'),
... | 0 | 2016-06-13T18:57:52Z | [
"javascript",
"jquery",
"python",
"html",
"django"
] |
Tensorflow LSTM RNN output activation function | 37,796,595 | <p>I have an input image with grey scale values ranging from let's say <code>25000 - 35000</code>. I'm doing a binary pixel-wise classification, so the output ground truth is a matrix of either <code>0's</code> or <code>1's</code>. </p>
<p>Does anyone know what the default output activation function is? My question is... | 2 | 2016-06-13T18:17:16Z | 37,800,264 | <p>Looking at <a href="https://github.com/tensorflow/tensorflow/blob/b2a812b962f8088a8256d4e6271b9cd425936446/tensorflow/python/ops/rnn_cell.py#L351" rel="nofollow">the code</a>, the default activation function for <code>BasicLSTMCell</code> is <code>tf.tanh()</code>. You can customize the activation function by specif... | 3 | 2016-06-13T22:39:54Z | [
"python",
"machine-learning",
"neural-network",
"artificial-intelligence",
"tensorflow"
] |
How to sort file names in a particular order using python | 37,796,598 | <p>Is there a simple way to sort files in a directory in python? The files I have in mind come in an ordering as </p>
<pre><code>file_01_001
file_01_005
...
file_02_002
file_02_006
...
file_03_003
file_03_007
...
file_04_004
file_04_008
</code></pre>
<p>What I want is something like</p>
<pre><code>file_01_001
file_0... | 1 | 2016-06-13T18:17:35Z | 37,796,686 | <p>As mentioned, files in a directory are not inherently sorted in a particular way. Thus, we usually 1) grab the file names 2) sort the file names by desired property 3) process the files in the sorted order. </p>
<p>You can get the file names in the directory as follows. Suppose the directory is "~/home" then</p>
<... | 3 | 2016-06-13T18:23:50Z | [
"python",
"sorting",
"python-3.x",
"io"
] |
Map equivalent of nested list comprehension using zip | 37,796,601 | <p>Below, I have a list of ids and a list of number of urls to create for each id, using the <code>url_str</code> as the base of the created urls. So, for id <code>id2</code>, I'd expect three urls. I've accomplished this with a <code>list comprehension</code>, which seems to be the most pythonic way to solve the probl... | 0 | 2016-06-13T18:17:53Z | 37,796,878 | <p>I don't want to delete the question, because someone was able to answer my question in the comments above.</p>
<pre><code> map((lambda x: x[0] + x[1] + "page=" + str(x[2])), ((url_str, id_r, x) for id_r, page in zip(ids, revs) for x in xrange(1, page + 1)))
</code></pre>
| 0 | 2016-06-13T18:35:59Z | [
"python",
"list"
] |
Map equivalent of nested list comprehension using zip | 37,796,601 | <p>Below, I have a list of ids and a list of number of urls to create for each id, using the <code>url_str</code> as the base of the created urls. So, for id <code>id2</code>, I'd expect three urls. I've accomplished this with a <code>list comprehension</code>, which seems to be the most pythonic way to solve the probl... | 0 | 2016-06-13T18:17:53Z | 37,797,017 | <p>I don't think <code>map</code> is going to work out in a great way here but after I gave up on it I was at least able to simplify your list comp into something a little more readable and efficient:</p>
<pre><code>In [31]: ids = xrange(1, 5)
In [32]: pages = (1, 3, 1, 8)
In [33]: pages_per_id = zip(ids, pages)
In... | 1 | 2016-06-13T18:44:23Z | [
"python",
"list"
] |
Map equivalent of nested list comprehension using zip | 37,796,601 | <p>Below, I have a list of ids and a list of number of urls to create for each id, using the <code>url_str</code> as the base of the created urls. So, for id <code>id2</code>, I'd expect three urls. I've accomplished this with a <code>list comprehension</code>, which seems to be the most pythonic way to solve the probl... | 0 | 2016-06-13T18:17:53Z | 37,797,074 | <p>Keep in mind that <code>map</code> existed before list comprehension existed, if you want to map a function to every element of a sequence, for example:</p>
<pre><code>map(func, seq)
</code></pre>
<p>would be equivalent to:</p>
<pre><code>[func(x) for x in seq]
</code></pre>
<p>Although in python 3 <code>map</co... | 2 | 2016-06-13T18:49:11Z | [
"python",
"list"
] |
Requests using smtplib module denied | 37,796,611 | <p>I have been using the smtplib module in python to send text messages from a gmail account and my requests to connect to the server recently started being denied. My code isn't anything special:</p>
<pre><code>import smtplib
server = smtplib.SMTP( "smtp.gmail.com", 587 )
server.starttls()
server.login( '<gmail_ad... | 0 | 2016-06-13T18:18:38Z | 37,797,176 | <p>Google explain that you can <a href="https://support.google.com/accounts/answer/6010255" rel="nofollow">lower your security settings</a> but they don't rcommend it, and give precious little in the way of advice apart from that.</p>
| 1 | 2016-06-13T18:55:56Z | [
"python",
"smtp",
"smtplib"
] |
netifaces import error on android in kivy buildozer | 37,796,631 | <p>I Have import netifaces in buildozer requirments. But After buillding the app. At the runtime of app, I'm having a problem importing netifaces on android in kivy app. Output is below. Whats this error trying to say. Its gives some error like:</p>
<pre><code> [Errno 13] Permission denied: '/data/.python-eggs'
</code... | 1 | 2016-06-13T18:20:04Z | 37,805,076 | <p>The error is clear, it tries to extract egg to a folder that it doesn't have permission to write to.</p>
<p>Python <code>.egg</code> is <a href="http://stackoverflow.com/a/2051195/5994041">this</a>, however it seemed kind of weird that other packages work and this one somehow... doesn't.</p>
<p>I looked at its cod... | 1 | 2016-06-14T07:03:03Z | [
"android",
"python",
"kivy",
"buildozer",
"python-netifaces"
] |
Download OpenCV for Pycharm | 37,796,684 | <p>I have literally spent numerous hours trying to install OpenCV on Pycharm but have not succeeded. I have gone through numerous SO answers and blog posts but still without any luck. I followed <a href="http://rodrigoberriel.com/2014/10/installing-opencv-3-0-0-on-ubuntu-14-04/" rel="nofollow">this</a> which seemed to ... | 1 | 2016-06-13T18:23:48Z | 37,796,739 | <p>You dont install opencv in Pycharm but on your OS and at your python environment.</p>
<p>For some reason i cant comment but, </p>
<p>You need to tell us :</p>
<p><strong>A) Your OS</strong></p>
<p><strong>B) PYTHON environment 2.x 3.x , anaconda? canopy? winpython?</strong> </p>
<p><em>So we can properly reply.... | 2 | 2016-06-13T18:27:11Z | [
"python",
"opencv",
"pycharm"
] |
Python: How can I sort file line by line in lexicographic order and write result to file? | 37,796,689 | <p>I'm a beginner in Python and having trouble understanding this question. Can someone check to see if my code reflects the instructions / how to fix it? Thank you!</p>
<p>Question: Write a function sortFile(src, dst) that sorts file with name src line by line in lexicographic order and writes the result to file with... | -4 | 2016-06-13T18:24:03Z | 37,796,830 | <p>I would use file.write(string) to write to the ouput file:</p>
<pre><code>def sortFile(src, dst):
x, y = open(src, 'r'), open(dst, 'w')
b = x.readlines()
x.close()
b.sort()
for i in b:
y.write(i.strip() + "\n")
y.close()
</code></pre>
<p>I tested this and it should produce the corre... | 1 | 2016-06-13T18:32:29Z | [
"python",
"sorting"
] |
Pandas Comparing aggregates with original columns | 37,796,702 | <p>I'm having difficulty comparing a pandas dataframe with aggregate columns generated from that dataframe. Concretely if I have</p>
<pre><code>df = Col1 Col2
a p
a q
a r
b r
c s
</code></pre>
<p>I'd like a boolean dataframe that is true where each entry is equal to the modal v... | 1 | 2016-06-13T18:25:06Z | 37,796,798 | <p>You can compare <code>df</code> with <code>numpy array</code> created by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html" rel="nofollow"><code>values</code></a>:</p>
<pre><code>print (df.mode().values)
[['a' 'r']]
print (df == df.mode().values)
Col1 Col2
0 True ... | 2 | 2016-06-13T18:30:22Z | [
"python",
"pandas"
] |
Django Model Formset: only track changes to those items that have been updated/saved in the set? | 37,796,721 | <p>So, I'm using Django's Model Formset to produce sets of forms for different data. It is working great, but I want to add a feature where when a user displays the formset and, say, updates 2 out of the 10 items, I can track just the 2 updated, and output a message like "You have updated 2 items" kind-of-thing.</p>
<... | 0 | 2016-06-13T18:25:59Z | 37,796,987 | <p>Formsets have a <code>has_changed</code> method which will report whether or not any of its forms have been changed. That's not exactly what you're looking for, but if you look at its implementation it should show you how to do it. That method is:</p>
<pre><code>def has_changed(self):
"""
Returns true if da... | 2 | 2016-06-13T18:42:41Z | [
"python",
"django",
"django-forms",
"django-views",
"modelform"
] |
How to apply a matrix to an image | 37,796,768 | <p>i've made some search but didn't find the exact same questions - and the solutions I found were not adaptable.</p>
<p>I have an Image, represented by a numpy array of shape <code>(l1,l2,3)</code>
where l1,l2 are integers and three because RGB.</p>
<p>And for reasons, I want to change the basis, it means applying a... | 2 | 2016-06-13T18:28:27Z | 37,798,200 | <p>You are reducing the last axis on the two inputs <code>Image</code> and <code>P</code>. So, you can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.tensordot.html" rel="nofollow"><code>np.tensordot</code></a>, like so -</p>
<pre><code>np.tensordot(Image,P,axes=(-1,-1))
</code></pre>
<... | 0 | 2016-06-13T20:02:10Z | [
"python",
"image",
"numpy",
"matrix",
"basis"
] |
Theano force tensor elements to be value | 37,796,812 | <p>I have a theano tensor W. I want to force some elements of W to be 2. How do I do it? I know that theano TensorVariable does not support item assignment. Is it not possible to do this? I can not use a shared variable for it as W is derived from another theano variable.</p>
| 0 | 2016-06-13T18:31:21Z | 37,809,518 | <p>You can try <a href="http://deeplearning.net/software/theano/library/tensor/basic.html#theano.tensor.set_subtensor" rel="nofollow">set_subtensor</a> in theano.tensor. The example provided there should hopefully be sufficiently clear.</p>
| 1 | 2016-06-14T10:32:38Z | [
"python",
"theano"
] |
Python, threading.Timer stops updating after I change system time | 37,796,915 | <p>I have a simple GUI that shows your current time and updates it every 0.2 seconds. When I change time using the change() function, my system time changes but the time in my app freezes and stops updating. </p>
<pre><code>import sys
import time
from Tkinter import *
import threading
from datetime import date
import ... | 1 | 2016-06-13T18:38:15Z | 37,797,125 | <p>You can't change the clock while you have pending timers and expect them to trigger based on their previous relative time. The timers are associated with fixed (not relative) values in the kernel.</p>
<p>What I would do instead is change the time in <code>value2</code>. <code>change</code> could set a variable:</... | 0 | 2016-06-13T18:51:47Z | [
"python",
"datetime",
"time"
] |
Pandas read sql integer became float | 37,796,916 | <p>I met a problem that when I use pandas to read Mysql table, some columns (see 'to_nlc') used to be integer became a float number (automatically add .0 after that).
Can anyone figure it out? Or some guessings? Thanks very much!</p>
<p><a href="http://i.stack.imgur.com/1obo8.png" rel="nofollow"><img src="http://i.sta... | 1 | 2016-06-13T18:38:18Z | 37,797,008 | <p>Problem is your data contains <code>NaN</code> values, so <code>int</code> is automatically cast to <code>float</code>.</p>
<p>I think you can check <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#na-type-promotions" rel="nofollow">NA type promotions</a>:</p>
<blockquote>
<p>When introducing NA... | 3 | 2016-06-13T18:43:57Z | [
"python",
"mysql",
"table",
"pandas",
"int"
] |
Getting Co-ordinates of a particular location using Bing Map api in python/odoo | 37,796,933 | <p>I have been working on a task in Odoo9 for getting latitude longitude using bing map api.In Odoo 9 there is a model called base_geolocalize where they used this function for getting lat/long by the help of google api</p>
<pre><code>def find(addr):
url = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=fal... | 0 | 2016-06-13T18:39:11Z | 37,971,005 | <p>You can use the Bing Maps REST services: <a href="https://msdn.microsoft.com/en-us/library/ff701711.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/ff701711.aspx</a></p>
<p>The structure of the response will be different from Google of course, but it will have the information you are looking for. Here... | 0 | 2016-06-22T14:27:04Z | [
"python",
"bing-api",
"odoo-9"
] |
Calculating mean absolute percentage error between values in 2 dictionaries in python | 37,797,025 | <p>I have a dictionary of locations, and then property-value pairs, as so:</p>
<pre><code>{"Russia":
{"/location/statistical_region/size_of_armed_forces": 65700.0,
"/location/statistical_region/gni_per_capita_in_ppp_dollars": 42530.0,
"/location/statistical_region/gdp_nominal": 1736050505050.0,
"/... | 0 | 2016-06-13T18:45:11Z | 37,798,354 | <p>In the future <strong>please</strong> read how to formulate a good question: <a href="http://stackoverflow.com/help/mcve">http://stackoverflow.com/help/mcve</a></p>
<p><strong>Minimum, Complete, and Verifiable.</strong></p>
<hr>
<p>I think this is what you are looking for.</p>
<pre><code>countries = {'Canada': {... | 1 | 2016-06-13T20:13:01Z | [
"python",
"for-loop",
"dictionary"
] |
Creating new dataframe from existing - SettingWithCopyWarning | 37,797,093 | <p>I have a csv file that I import as a dataframe. This dataframe goes through multiple filtering steps. Data is also moved between columns based on conditionals.</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.read_csv('my_csv_file.csv', names=headers)
df2 = df.drop_duplicates(['Column_X'])
series1 = d... | 2 | 2016-06-13T18:50:17Z | 37,797,570 | <p>I believe the issue is that <code>df2</code> is a view of <code>df1</code>. Instead put a <code>.copy()</code> at the end of the <code>.drop_duplicates</code> call. </p>
<pre><code>df2 = df.drop_duplicates(['Column_X']).copy()
</code></pre>
| 1 | 2016-06-13T19:20:52Z | [
"python",
"pandas"
] |
Python: List or float or array to float | 37,797,143 | <p>I have a function which needs input as type <code>float</code> for further calculation.
Unfortunately the input type ranges from:</p>
<ol>
<li><code>list</code> </li>
<li><code>float</code> </li>
<li><code>numpy.array</code></li>
</ol>
<p>I am unhappy with my workaround and I wonder whether there is a better solu... | 2 | 2016-06-13T18:53:29Z | 37,797,349 | <p>Use <a href="https://docs.python.org/2/library/functions.html#isinstance" rel="nofollow"><code>isinstance</code></a>,</p>
<pre><code>>>> import numpy as np
>>> l = [[.5], .5, np.array([.5])]
>>> f = [x if isinstance(x, float) else x[0] for x in l]
>>> f
[0.5, 0.5, 0.5]
</code></... | 2 | 2016-06-13T19:06:05Z | [
"python",
"data-type-conversion"
] |
How to print progress when training a DNNClassifier in tensorflow r0.9 (skflow)? | 37,797,194 | <p>I couldn't get that a DNNClassifier prints the progress while training, ie, loss and validation score. As I understood the loss can be printed using the config parameter that inherits from BaseEstimator, but when I passed a RunConfig object, the classifier didn't printed anything.</p>
<pre><code>from tensorflow.con... | 4 | 2016-06-13T18:57:08Z | 38,084,584 | <p>Adding these before the fit function shows the progress:</p>
<pre><code>import logging
logging.getLogger().setLevel(logging.INFO)
</code></pre>
<p>Sample:</p>
<pre><code>INFO:tensorflow:global_step/sec: 0
INFO:tensorflow:Training steps [0,1000000)
INFO:tensorflow:Step 1: loss = 10.5043
INFO:tensorflow:training st... | 4 | 2016-06-28T19:18:40Z | [
"python",
"tensorflow",
"skflow"
] |
python imports - public or private convention | 37,797,227 | <p>In Python convention, should a module's imports be considered part of its public interface, or not? </p>
<p>I have some code that does this:</p>
<p><strong>foo.py</strong>:</p>
<pre><code>from a import b
</code></pre>
<p><strong>bar.py</strong>:</p>
<pre><code>from foo import b
</code></pre>
<p>I'm trying to d... | 3 | 2016-06-13T18:59:18Z | 37,797,382 | <blockquote>
<p>In Python convention, should a module's imports be considered part of it's public interface, or not?</p>
</blockquote>
<p>A module's public API is whatever the module documents its public API to be. If module <code>foo</code> documents that it provides <code>b</code>, then <code>b</code> is part of i... | 2 | 2016-06-13T19:08:05Z | [
"python",
"import",
"conventions"
] |
python imports - public or private convention | 37,797,227 | <p>In Python convention, should a module's imports be considered part of its public interface, or not? </p>
<p>I have some code that does this:</p>
<p><strong>foo.py</strong>:</p>
<pre><code>from a import b
</code></pre>
<p><strong>bar.py</strong>:</p>
<pre><code>from foo import b
</code></pre>
<p>I'm trying to d... | 3 | 2016-06-13T18:59:18Z | 37,797,842 | <p>Documentation point of view. The convention is that everything that does not start with underscore is public. If you want to mark an import symbol as private, alias it with underscore like <code>from a import b as _b</code>. There's an alternative. You can use <a href="http://stackoverflow.com/q/44834/2072035"><code... | 2 | 2016-06-13T19:37:13Z | [
"python",
"import",
"conventions"
] |
python imports - public or private convention | 37,797,227 | <p>In Python convention, should a module's imports be considered part of its public interface, or not? </p>
<p>I have some code that does this:</p>
<p><strong>foo.py</strong>:</p>
<pre><code>from a import b
</code></pre>
<p><strong>bar.py</strong>:</p>
<pre><code>from foo import b
</code></pre>
<p>I'm trying to d... | 3 | 2016-06-13T18:59:18Z | 37,799,143 | <p>ninja mode module definition</p>
<pre><code>def defmod():
global foo
import sys
def foo(): return sys.path
defmod()
del defmod
</code></pre>
| 0 | 2016-06-13T21:07:42Z | [
"python",
"import",
"conventions"
] |
Reading regular expressions from a XML file, store them into a list of list and afterwards use them | 37,797,279 | <p>I want to read many regular expressions from a XML file, store them into a list of list and use them. My solution does not work and I do not know why.</p>
<p>Suppose that I have a XML that contains the regex that I want to store in my list of list. The XML is like this:</p>
<pre><code><?xml version="1.0" encodi... | 0 | 2016-06-13T19:02:18Z | 37,797,947 | <p>The regex you are using</p>
<pre><code>str(listOfList[0])
</code></pre>
<p>will in your example be</p>
<pre><code>["r'\\d+\\.\\d+'"]
</code></pre>
<p>and that literally with the <code>["r'</code> before and <code>'"]</code> after.</p>
<p>The <a href="https://docs.python.org/2/library/functions.html#str" rel="no... | 0 | 2016-06-13T19:44:01Z | [
"python",
"regex",
"xml",
"list"
] |
Better way to overload constructor in python? | 37,797,290 | <p>So I am aware that class methods can be used to "overload" the init method in python, but I'm running into a bit of a problem. Say, for example, I have a constructor like this:</p>
<pre><code>def __init__(self, serviceName, endpoint, exportedInterface, exportedObject, remoteObjectInterface, remoteObjectProxy,
... | 0 | 2016-06-13T19:03:01Z | 37,797,385 | <p>You can use default values for the parameters. Then you can specify which one you want to replace.
</p>
<pre><code>def __init__(self, serviceName, endpoint = None, exportedInterface = None,
exportedObject = None, remoteObjectInterface = None, remoteObjectProxy = None,
interruptionHandler ... | 5 | 2016-06-13T19:08:44Z | [
"python"
] |
Better way to overload constructor in python? | 37,797,290 | <p>So I am aware that class methods can be used to "overload" the init method in python, but I'm running into a bit of a problem. Say, for example, I have a constructor like this:</p>
<pre><code>def __init__(self, serviceName, endpoint, exportedInterface, exportedObject, remoteObjectInterface, remoteObjectProxy,
... | 0 | 2016-06-13T19:03:01Z | 37,797,410 | <p>Two options are:</p>
<p>Use keyword arguments. e.g.</p>
<pre><code>def __init__(self, **kwargs):
for names in ("serviceName", ...):
setattr(self, "_" + name, kwargs.get(names, None))
</code></pre>
<p>Make <code>__init__</code> do the bare minimum and use factory functions to do the appropriate initial... | 0 | 2016-06-13T19:10:30Z | [
"python"
] |
Google Foobar: Attribute Error when submitting solution | 37,797,291 | <p>I've been a reading the site for many year and today is my first question.</p>
<p>I was invited to play in Google Foobar for searching Python, as I was testing my new found knowledge after finishing a tutorial.</p>
<p>When I submit my 'solution.py' I get the following error:
AttributeError on line 13</p>
<p>This ... | 1 | 2016-06-13T19:03:09Z | 37,797,981 | <p>It looks like <code>time</code> is an instance of <code>datetime.time</code>, which doesn't have a <code>strptime</code> method. Since you're constructing a date, you probably want it to be <code>datetime.datetime</code> instead.</p>
<pre><code>import datetime
if datetime.datetime.strptime(str(v), '(%m, %d, %y)'):
... | 1 | 2016-06-13T19:46:41Z | [
"python",
"google-search",
"attributeerror",
"python-datetime"
] |
Google Foobar: Attribute Error when submitting solution | 37,797,291 | <p>I've been a reading the site for many year and today is my first question.</p>
<p>I was invited to play in Google Foobar for searching Python, as I was testing my new found knowledge after finishing a tutorial.</p>
<p>When I submit my 'solution.py' I get the following error:
AttributeError on line 13</p>
<p>This ... | 1 | 2016-06-13T19:03:09Z | 37,800,263 | <p>So, it seems like the foo.bar project does not like the imported datetime module. I took it off and re-wrote some code to do what time.strptime() was doing and it started working.</p>
<p>Unfortunately, my code did not pass and I ran out of time to submit :'''(</p>
<p>I hope I get another invite.</p>
| 0 | 2016-06-13T22:39:44Z | [
"python",
"google-search",
"attributeerror",
"python-datetime"
] |
Using Pandas, How to replace the last word of the string with an empty strings without distorting rest of the string? | 37,797,325 | <p>I can't share the actual data. So I am taking an example.
Suppose I have a list of suffixes - </p>
<pre><code>Suffix_List = ["Ltd.", "Inc.", "Limited", "Corp.", "AG"]
</code></pre>
<p>I have a data frame with a column containing company names. I want to replace the suffixes of the company name with an empty strin... | 0 | 2016-06-13T19:04:55Z | 37,797,459 | <p>You can use regex to substitute out the suffix:</p>
<pre><code>In [11]: re.sub("\s?(" + "|".join(Suffix_List) + ")$", "", "CAGE AG")
Out[11]: 'CAGE'
</code></pre>
<p><em>This looks whether any (<code>|</code>) of the suffixes ends (<code>$</code>) the string.</em></p>
<p>On the Series/column you can use <a href="... | 2 | 2016-06-13T19:13:29Z | [
"python",
"pandas"
] |
PyQt5 mousetracking not working | 37,797,342 | <p>I've found an example that changing a QPushButton's icon when mouse is hover on it. I tried to convert it to my codes, but there are some problems. First check the example I found, it's really short. <a href="http://paste.ubuntu.com/17302717/" rel="nofollow">http://paste.ubuntu.com/17302717/</a></p>
<p>These codes ... | 0 | 2016-06-13T19:05:53Z | 37,798,210 | <p>Your code has a few problems, namely with imports. The main problem though is that you don't need this: <code>return QPushButton.mouseMoveEvent(self, event)</code></p>
<p>Try the following corrections to your code:</p>
<pre><code>from PyQt5.QtWidgets import QApplication,QPushButton,QWidget from
PyQt5.QtGui import ... | 2 | 2016-06-13T20:02:54Z | [
"python",
"mouseevent",
"python-3.4",
"pyqt5",
"qpushbutton"
] |
Why does Twitter Bootstrap input validation affect name arguments in Tornado? | 37,797,363 | <p>I am modifying the <a href="https://github.com/tornadoweb/tornado/blob/master/demos/chat/" rel="nofollow">Tornado <code>chatdemo</code> example</a>. I copy the example as-is and make two modifications:</p>
<ol>
<li><p>I add a new input element adjacent to the current input element:</p>
<pre><code><tr>
<t... | 0 | 2016-06-13T19:06:57Z | 37,798,361 | <p>This fixes it:</p>
<pre><code>str(self.get_argument("bnum"))
</code></pre>
<p>It makes sense that the value gets returned as a number rather than a string, I suppose, but the error that results is pretty cryptic.</p>
| 0 | 2016-06-13T20:13:26Z | [
"python",
"twitter-bootstrap",
"tornado"
] |
Google API client (Python): is it possibile to use BatchHttpRequest with ETag caching | 37,797,374 | <p>I'm using YouTube data API v3. </p>
<p>Is it possible to make a big <code>BatchHttpRequest</code> (e.g., see <a href="https://developers.google.com/api-client-library/python/guide/batch" rel="nofollow">here</a>) and also to use ETags for local caching at the <code>httplib2</code> level (e.g., see <a href="https://d... | 4 | 2016-06-13T19:07:40Z | 38,168,154 | <p><strong>First lets see the way to initialize <code>BatchHttpRequest</code>:</strong></p>
<pre><code>from apiclient.http import BatchHttpRequest
def list_animals(request_id, response, exception):
if exception is not None:
# Do something with the exception
pass
else:
# Do something with the response
... | 1 | 2016-07-03T08:32:42Z | [
"python",
"youtube-data-api",
"google-api-client",
"httplib2",
"youtube-data-api-v3"
] |
How to pick a random no from a list (contain 1 to n values) with certain thresold value? | 37,797,404 | <p>I have a list like below:</p>
<pre><code>l=[1,2,3,4,5]
thresold value = 0.5
</code></pre>
<p>From this list , I want to pick a random no which is > thresold value (0.5).</p>
<p>Thanking you in advance</p>
| 2 | 2016-06-13T19:10:12Z | 37,797,468 | <p>You can use a <code>list comprehension</code> to filter it and then <code>random.choice()</code> to get a random one. See below...</p>
<pre><code>import random
l = [1,2,3,4,5]
threshold_value = 4
r = random.choice([x for x in l if x>threshold_value])
print(r)
</code></pre>
| 4 | 2016-06-13T19:14:16Z | [
"python",
"python-2.7",
"random",
"random-sample",
"choice"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.