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 |
|---|---|---|---|---|---|---|---|---|---|
Python: Send multiple POST requests on the same page | 37,797,408 | <p>Is it possible to send multiple HTTP POST requests to a server using selenium webdriver?</p>
<p>If, for example the user IDs are auto-incremented and the first 1000 followers had followed me, would it be possible to run something like the following on a site where POST requests dont return a reload:</p>
<p>** The ... | 1 | 2016-06-13T19:10:28Z | 37,797,532 | <p>don't know how to make it using selenium web driver. but you can send multiple post request using AJAX. Its quite simple language you can learn it within 2 days if you know little bit javascript. you can learn it from w3schools Try it. </p>
| -1 | 2016-06-13T19:18:23Z | [
"python",
"selenium",
"selenium-webdriver",
"http-post"
] |
Python: Send multiple POST requests on the same page | 37,797,408 | <p>Is it possible to send multiple HTTP POST requests to a server using selenium webdriver?</p>
<p>If, for example the user IDs are auto-incremented and the first 1000 followers had followed me, would it be possible to run something like the following on a site where POST requests dont return a reload:</p>
<p>** The ... | 1 | 2016-06-13T19:10:28Z | 37,797,560 | <p>Why shouldn't it work?</p>
<p>"where POST requests don't return a reload" Please explain what you mean by this!</p>
<p>Anyway, <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a> seems to be more suitable for this task:</p>
<p>Here is a simple example:</p>
<pre><code>imp... | -1 | 2016-06-13T19:20:18Z | [
"python",
"selenium",
"selenium-webdriver",
"http-post"
] |
Extracting certain lines from a text file | 37,797,487 | <p>So I have a text file from which I am trying to extract certain lines which contain a specific word. The lines are want are lines which contain the word HEIGHT, however there is another category in my text file called AVERAGEHEIGHT. So when I run this code it extracts all lines that contain both HEIGHT and AVERAGEHE... | 1 | 2016-06-13T19:15:32Z | 37,797,513 | <p>The simplest way I can think of, without knowing the rest of your input, would be as follows:</p>
<pre><code>open('height.txt','w').writelines([ line for line in open("Test1.txt") if "HEIGHT" in line and "AVERAGEHEIGHT" not in line])
</code></pre>
<p>EDIT:</p>
<pre><code>open('height.txt','w').writelines([ line f... | 1 | 2016-06-13T19:17:24Z | [
"python"
] |
Extracting certain lines from a text file | 37,797,487 | <p>So I have a text file from which I am trying to extract certain lines which contain a specific word. The lines are want are lines which contain the word HEIGHT, however there is another category in my text file called AVERAGEHEIGHT. So when I run this code it extracts all lines that contain both HEIGHT and AVERAGEHE... | 1 | 2016-06-13T19:15:32Z | 37,797,698 | <p>You can do it like this:</p>
<pre><code>with open('linestoread.txt') as f:
our_lines = f.readlines()
for l in our_lines:
if 'HEIGHT' in l and not 'AVERAGEHEIGHT' in l:
with open('height.txt', 'a') as f:
f.writelines(l)
</code></pre>
| 0 | 2016-06-13T19:29:19Z | [
"python"
] |
Would a dns name not existing for an IP cause this python error message? | 37,797,489 | <p>I am attempting to run the following script using the suds library:</p>
<pre><code>from suds.client import Client
from suds.transport.http import HttpAuthenticated
import os
t = HttpAuthenticated(username='xxxxxxx', password='xxxxxxxx')
url = 'http://10.14.9.42/NodeBeanService/NodeBean?wsdl'
client = Client(url, t... | 2 | 2016-06-13T19:15:42Z | 37,820,035 | <p>I was able to get things working correctly by adding the server's IP to my hosts file and then associating it with the hostname that is hardcoded on the server</p>
| 0 | 2016-06-14T18:57:21Z | [
"python",
"python-2.7",
"soap",
"suds"
] |
I need to make it so the sentence and numbers that are outputted are stored into a file. Any help would be great | 37,797,511 | <p>The code I have made:</p>
<ul>
<li>asks the user for a sentence,</li>
<li>makes it lower case so it is not case sensitive</li>
<li>splits the sentence into separate words so each word can have a number assigned to it according to its position</li>
</ul>
<blockquote>
<p>How can I add a part to my code that saves ... | -4 | 2016-06-13T19:17:12Z | 37,797,838 | <p>Use <code>raw_input</code> if you want to treat everything as strings. You do not need to store the positions but, instead, get them from the wonderful <code>enumerate</code> function. Then write to the file like so</p>
<pre><code>sentence = raw_input("Please enter a sentence: ")
sentence = sentence.lower()
sen... | 0 | 2016-06-13T19:37:09Z | [
"python"
] |
I need to make it so the sentence and numbers that are outputted are stored into a file. Any help would be great | 37,797,511 | <p>The code I have made:</p>
<ul>
<li>asks the user for a sentence,</li>
<li>makes it lower case so it is not case sensitive</li>
<li>splits the sentence into separate words so each word can have a number assigned to it according to its position</li>
</ul>
<blockquote>
<p>How can I add a part to my code that saves ... | -4 | 2016-06-13T19:17:12Z | 37,797,856 | <pre><code>sentence = input("Please enter a sentence")
sentence = sentence.lower()
sentence = sentence.split()
wordPositionDict = {}
( wordPositionDict.get(x,[]).append(i+1) for i,x in enumerate(sentence))
print wordPositionDict[word]
</code></pre>
<p>append all the index for each word to dict. after iterate ... | 0 | 2016-06-13T19:37:51Z | [
"python"
] |
Write a string matrix on a .txt file on Python | 37,797,517 | <p>I'm doing a RogueLike game with Python and I use a DungeonGenerator.py.
In my game I read the dungeons from a .txt file. </p>
<p>The problem is I can't write the dungeon I make with the DungeonGenerator.py on a .txt file because is a matrix of strings.</p>
<p>This is an example of the result of DungeonGenerator.p... | -3 | 2016-06-13T19:17:35Z | 37,797,558 | <p>What you want to do is called object serialization.</p>
<p>The <a href="https://docs.python.org/2/library/pickle.html" rel="nofollow">pickle module</a> should work just fine for you.</p>
| 0 | 2016-06-13T19:20:13Z | [
"python",
"json",
"string",
"matrix",
"roguelike"
] |
Balanced Error Rate as metric function | 37,797,621 | <p>I am trying to solve a binary classification problem with the sequential model from Keras<br>
and have to meet a given <a href="http://www.damienfrancois.be/blog/files/modelperfcheatsheet.pdf?search=Balanced" rel="nofollow">Balanced Error Rate (BER)</a></p>
<p>So I thought it would be a good idea to use the BER ins... | 1 | 2016-06-13T19:24:19Z | 37,801,219 | <blockquote>
<p>A way to get the array dimensions / an explanation why shape acts like it does / the reason why <code>y_true</code> seems to have 0 dimensions</p>
</blockquote>
<p>The deal with <code>print</code> and abstraction libraries like Theano is that you usually do not get the values but a represenation of t... | 1 | 2016-06-14T00:36:20Z | [
"python",
"python-2.7",
"theano",
"keras"
] |
Update position of custom QGraphicsItem on connected item change | 37,797,775 | <p>I have two subclassed QGraphicsRectItems that are supposed to be connected with a line that adjusts based on the position of the textboxes.</p>
<p>In the <a href="http://doc.qt.io/qt-5/qtwidgets-graphicsview-diagramscene-example.html" rel="nofollow">diagramscene example</a> of the Qt docus the <code>itemChanged</co... | 1 | 2016-06-13T19:33:28Z | 37,800,212 | <p>The position of the item doesn't actually matter - it can remain at 0,0 - providing the bounding box is correct (which it will be according to your Arrow::boundingBox implementation). Hence, I think if you simply trigger a bounding box change, and a redraw in updatePosition, everything will work as you want.</p>
<p... | 2 | 2016-06-13T22:35:36Z | [
"python",
"c++",
"qt",
"pyqt",
"qgraphicsitem"
] |
Python: reading 12 bit packed binary image | 37,797,779 | <p>I have a 12 bit packed image from a GigE camera. It is a little-endian file and each 3 bytes hold 2 12-bit pixels.
I am trying to read this image using python and I tried something like this:</p>
<pre><code>import bitstring
import numpy
with open('12bitpacked1.bin', 'rb') as f:
data = f.read()
ii=numpy.zeros(... | 5 | 2016-06-13T19:33:51Z | 37,798,391 | <p>With this code</p>
<pre><code>for oo in range(0,len(data)/3):
aa = bitstring.Bits(bytes=data[oo:oo+3], length=24)
</code></pre>
<p>you are reading bytes <code>data[0:3]</code>, <code>data[1:4]</code>, ... What you actually want is probably this:</p>
<pre><code>for oo in range(0,len(data)/3):
aa = bitstring.Bi... | 3 | 2016-06-13T20:15:08Z | [
"python",
"binary",
"unpack"
] |
Reading Tab delimited file in Pandas with unintended line break | 37,797,869 | <p>I'm trying to read the uncompressed version of the file found here:
<a href="http://ftp.ncbi.nlm.nih.gov/pub/clinvar/tab_delimited/variant_summary.txt.gz" rel="nofollow">http://ftp.ncbi.nlm.nih.gov/pub/clinvar/tab_delimited/variant_summary.txt.gz</a></p>
<p>I'm using Pandas and the read_table function; however, som... | 1 | 2016-06-13T19:38:53Z | 37,799,428 | <p>Your CSV file contains NULL bytes (i.e. <code>b'\x00'</code>). Although the file is somewhat big (100+MB), it is (probably) small enough to be read entirely into memory. So a quick fix would be to remove the NULL bytes with:</p>
<pre><code>with open('variant_summary.txt', 'rb') as f, open('variant_summary-fixed.txt... | 1 | 2016-06-13T21:28:13Z | [
"python",
"pandas"
] |
Flask-Babel Multiple Language URL Routing | 37,797,925 | <p>I am creating a multi-language site (EN and FR) and I need it to toggle back and forth on click if the user so chooses. I am using Flask-Babel and the translations and toggle are working correctly on click, however, I need the URLs to be translated as well. I have currently wrapped my URL routes like so, with both t... | 1 | 2016-06-13T19:42:35Z | 38,078,260 | <p>I have found a solution! I had to add endpoints to the URL routes like so:</p>
<pre><code>@main.route('accueil', endpoint="index_fr")
@main.route('home', endpoint="index_en")
def index():
return render('index.html', {})
@main.route('a-propos-de-nous', endpoint="about_fr")
@main.route('about-us', endpoint="abou... | 0 | 2016-06-28T13:57:29Z | [
"python",
"url",
"flask",
"routing",
"babel"
] |
kivy to run python code with threads and matplotlib | 37,797,965 | <p>I have created this python code:</p>
<pre><code>import threading
from drawnow import drawnow
import matplotlib.pyplot as plt
import random
import time
stop = []
timer = []
times = []
plt.ion()
class MyThread(threading.Thread):
def run(self):
c = 30
print 'TIMER START'
while not stop:... | 1 | 2016-06-13T19:45:25Z | 37,798,800 | <p>For plotting there is <a href="https://github.com/kivy-garden/garden.graph" rel="nofollow">Graph</a> in the Garden, which will make your life easier if you don't want to play with graphic instructions alone - it's a nice practice though.</p>
<p>In Kivy you can easily access e.g. <code>.text</code> property in widge... | 1 | 2016-06-13T20:43:07Z | [
"python",
"multithreading",
"matplotlib",
"kivy"
] |
Regex - Python matching between string and first occurence | 37,797,979 | <p>I'm having a hard time grasping regex no matter how much documentation I read up on. I'm trying to match everything between a a string and the first occurrence of <code>&</code> this is what I have</p>
<pre><code>link = "group.do?sys_id=69adb887157e450051e85118b6ff533c&amp;&"
rex = re.compile("group\.d... | 2 | 2016-06-13T19:46:30Z | 37,798,006 | <p>You don't necessarily need regular expressions here. Use <a href="https://docs.python.org/2/library/urlparse.html"><code>urlparse</code></a> instead:</p>
<pre><code>>>> from urlparse import urlparse, parse_qs
>>> parse_qs(urlparse(link).query)['sys_id'][0]
'69adb887157e450051e85118b6ff533c'
</cod... | 7 | 2016-06-13T19:48:45Z | [
"python",
"regex"
] |
Regex - Python matching between string and first occurence | 37,797,979 | <p>I'm having a hard time grasping regex no matter how much documentation I read up on. I'm trying to match everything between a a string and the first occurrence of <code>&</code> this is what I have</p>
<pre><code>link = "group.do?sys_id=69adb887157e450051e85118b6ff533c&amp;&"
rex = re.compile("group\.d... | 2 | 2016-06-13T19:46:30Z | 37,798,012 | <p>You can simply regex out to the <code>&amp</code> instead of the final <code>&</code> like so:</p>
<pre><code>import re
link = "user_group.do?sys_id=69adb887157e450051e85118b6ff533c&amp;&"
rex = re.compile("user_group\.do\?sys_id=(.*)&amp;&")
sysid = rex.search(link).groups()[0]
print(sysi... | 2 | 2016-06-13T19:48:54Z | [
"python",
"regex"
] |
Regex - Python matching between string and first occurence | 37,797,979 | <p>I'm having a hard time grasping regex no matter how much documentation I read up on. I'm trying to match everything between a a string and the first occurrence of <code>&</code> this is what I have</p>
<pre><code>link = "group.do?sys_id=69adb887157e450051e85118b6ff533c&amp;&"
rex = re.compile("group\.d... | 2 | 2016-06-13T19:46:30Z | 37,798,085 | <pre><code>.*
</code></pre>
<p>is greedy but </p>
<pre><code>.*?
</code></pre>
<p>should not be in regex. </p>
<pre><code>.?
</code></pre>
<p>would only look for any character 0-1 times while </p>
<pre><code>.*?
</code></pre>
<p>will look for it up to the earliest matching occurrence. I hope that explains it... | 2 | 2016-06-13T19:53:45Z | [
"python",
"regex"
] |
Convert uploaded csv file into list in Django | 37,798,021 | <p>I'm having a problem when I'm trying to convert the the first column of the uploaded csv file in django into a list. Originally, my code was like this without using django:</p>
<pre><code>with open("export.csv") as f:
my_list = [row["BASE_NAME"] for row in DictReader(f)]
</code></pre>
<p>But when developing th... | 2 | 2016-06-13T19:49:27Z | 37,799,661 | <pre><code>paramFile =TextIOWrapper(request.FILES['pic'].file).read()
portfolio1 = csv.DictReader(paramFile)
</code></pre>
<p><code>DictReader</code> expects an iterable of strings (usually a file object), where each string represents a line. Because you called <code>.read()</code>, <code>paramFile</code>is a string,... | 1 | 2016-06-13T21:47:11Z | [
"python",
"django",
"csv",
"django-forms",
"django-views"
] |
Convert uploaded csv file into list in Django | 37,798,021 | <p>I'm having a problem when I'm trying to convert the the first column of the uploaded csv file in django into a list. Originally, my code was like this without using django:</p>
<pre><code>with open("export.csv") as f:
my_list = [row["BASE_NAME"] for row in DictReader(f)]
</code></pre>
<p>But when developing th... | 2 | 2016-06-13T19:49:27Z | 37,799,746 | <pre><code> paramFile =io.TextIOWrapper(request.FILES['pic'].file)
portfolio1 = csv.DictReader(paramFile)
print(type(paramFile))
users = []
users = [row["BASE_NAME"] for row in portfolio1]
print(len(users))
</code></pre>
<p>Somehow I was able to fix it with the above, by looking at the local variab... | 0 | 2016-06-13T21:53:10Z | [
"python",
"django",
"csv",
"django-forms",
"django-views"
] |
Multivariate Normal pdf in Scipy | 37,798,025 | <p>Trying to evaluate scipy's <code>multivariate_normal.pdf</code> function, but keep getting errors. MWE:</p>
<pre><code>import numpy as np
from scipy.stats import multivariate_normal as mvnorm
x = np.random.rand(5)
mvnorm.pdf(x)
</code></pre>
<p>gives</p>
<pre><code>TypeError: pdf() takes at least 4 arguments (2... | 3 | 2016-06-13T19:49:32Z | 37,798,262 | <p><strong><em>It looks like these parameters aren't optional.</em></strong></p>
<p>If I pass the default values for <code>mean</code> and <code>cov</code> like:</p>
<pre><code>import numpy as np
from scipy.stats import multivariate_normal as mvnorm
x = np.random.rand(5)
mvnorm.pdf(x, mean=0, cov=1)
</code></pre>
<... | 3 | 2016-06-13T20:06:32Z | [
"python",
"numpy",
"scipy"
] |
Getting deprecation warning in Sklearn over 1d array, despite not having a 1D array | 37,798,056 | <p>I am trying to use SKLearn to run an SVM model. I am just trying it out now with some sample data. Here is the data and the code:</p>
<pre><code>import numpy as np
from sklearn import svm
import random as random
A = np.array([[random.randint(0, 20) for i in range(2)] for i in range(10)])
lab = [0, 1, 0, 1, 0, 1, 0... | 3 | 2016-06-13T19:51:38Z | 37,798,323 | <p>The error is coming from the predict method. Numpy will interpret [1,1] as a 1d array. So this should avoid the warning:</p>
<p><code>clf.predict(np.array([[1,1]]))</code></p>
<p>Notice that:</p>
<pre><code>In [14]: p1 = np.array([1,1])
In [15]: p1.shape
Out[15]: (2,)
In [16]: p2 = np.array([[1,1]])
In [17]: p... | 6 | 2016-06-13T20:10:55Z | [
"python",
"scikit-learn",
"svm"
] |
Getting deprecation warning in Sklearn over 1d array, despite not having a 1D array | 37,798,056 | <p>I am trying to use SKLearn to run an SVM model. I am just trying it out now with some sample data. Here is the data and the code:</p>
<pre><code>import numpy as np
from sklearn import svm
import random as random
A = np.array([[random.randint(0, 20) for i in range(2)] for i in range(10)])
lab = [0, 1, 0, 1, 0, 1, 0... | 3 | 2016-06-13T19:51:38Z | 37,824,406 | <p>the sample for the prediction intuitively could be:</p>
<p>[1,9]</p>
<p>But you can reshape the vector as the previous answer. Or just do the following:</p>
<p>[[1,9]]</p>
<h1>EXAMPLE</h1>
<p>import numpy as np
from sklearn import svm
import random as random</p>
<p>A = np.array([[random.randint(0, 20) for i in... | 0 | 2016-06-15T00:47:41Z | [
"python",
"scikit-learn",
"svm"
] |
Django Rest Framework Custom Serializer Method | 37,798,208 | <p>I'm trying to create a custom serializer method that counts the number of passed and failed quizzes from my QuizResults model. A failed quiz is under .7 and a passed quiz is .7 or over.</p>
<p>I want to be able to look into the Users QuizResult and count the number of passed quizzes(.7 or over). I would then duplic... | 2 | 2016-06-13T20:02:48Z | 37,801,958 | <p>You can use a <a href="https://docs.djangoproject.com/es/1.9/topics/db/models/#model-methods" rel="nofollow">model method</a> on the user model to count that user's number of passed quizzes:</p>
<pre><code>class User(models.model):
# rest of your User attributes
def get_quizzes_passed_count(self):
r... | 2 | 2016-06-14T02:17:19Z | [
"python",
"django",
"serialization",
"django-rest-framework"
] |
Why does this python generator have no output according to keras? | 37,798,410 | <p>EDIT: updating all the code to organize this question, same issue and question though. </p>
<pre><code>def extract_hypercolumn(model, layer_indexes, instance):
layers = [model.layers[li].output for li in layer_indexes]
get_feature = K.function([model.layers[0].input],layers)
assert instance.shape == (1,... | 1 | 2016-06-13T20:16:50Z | 38,076,156 | <p>generator should be infinite (loops through data) in fit_generator. </p>
<p>c.f. <a href="http://keras.io/models/sequential/#fit_generator" rel="nofollow">keras documentation on fit_generator</a></p>
<blockquote>
<p>The generator is expected to loop over its data indefinitely. </p>
</blockquote>
<p>Try changing... | 1 | 2016-06-28T12:22:10Z | [
"python",
"keras"
] |
Python: how to start an invisible python console from a python script under windows? | 37,798,445 | <p>I need to start a python console from a python script under windows.
Output of this console must be written on a textbox.
I'm using subprocess 'cause python console can be python 2 or 3, depends on choice of user, so I can't use code.InteractiveConsole.
Now, i start python with subprocess.Popen, stdin=PIPE, stdout a... | -1 | 2016-06-13T20:18:24Z | 37,799,551 | <p>To hide the command prompt window, pass the appropriate flags:</p>
<pre><code>si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
#si.wShowWindow = subprocess.SW_HIDE
subprocess.call('whoami', startupinfo=si)
</code></pre>
| 0 | 2016-06-13T21:37:13Z | [
"python",
"windows",
"popen"
] |
cx_Oracle: DLL load failed | 37,798,490 | <p>I'm trying to <code>import cx_Oracle</code> in Python and getting an:</p>
<pre><code>ImportError: DLL load failed: The specified procedure could not be found.
</code></pre>
<p><a href="http://stackoverflow.com/questions/24124110/cx-oracle-dll-load-failed">This post</a> suggests that there's a mismatch between the ... | 1 | 2016-06-13T20:22:06Z | 37,812,896 | <p>I've had a few DLL Load failures myself when trying to use cx_Oracle (also using 11g).<br></p>
<ol>
<li>I've fixed it by downloading <b>instant_client-basic (12)</b>.
(I assume you're using windows.) <br>If you use Linux, there will be
some environemnt variables you are going to need to change (you can
find all abo... | 0 | 2016-06-14T13:04:10Z | [
"python",
"oracle",
"cx-oracle"
] |
Downloading xlwt to Python 3.5.1 | 37,798,552 | <p>I'm trying to download the package xlwt to my Python 3.5.1 but typing <code>'pip install xlwt'</code> isn't working and gives me an error at the word <code>install</code> that says invalid syntax, though all the websites I've checked told me to do exactly this.</p>
<p>I mostly have a theoretical knowledge of Python... | 0 | 2016-06-13T20:27:01Z | 37,798,884 | <p>Sounds like you are typing <code>pip install ...</code> into a Python prompt and not a shell command prompt. This is not a Python statement but a shell command that has to be executed at the command-line prompt.</p>
| 0 | 2016-06-13T20:50:20Z | [
"python",
"python-3.5",
"xlwt"
] |
Python function to return listed imports gives empty result, but works line by line | 37,798,580 | <p>Adapting code from</p>
<p><a href="http://stackoverflow.com/questions/4858100/how-to-list-imported-modules">How to list imported modules?</a></p>
<p>to look like</p>
<pre><code>def imports():
import types
Module = None
Modules = list()
for name, val in globals().items():
if isinstance(va... | 0 | 2016-06-13T20:28:39Z | 37,798,652 | <p>The <a href="https://docs.python.org/3/library/functions.html#globals" rel="nofollow"><code>globals()</code> function</a> returns the global namespace for the <em>module it is used in</em>. You are seeing the modules that are imported in your <code>imports</code> module, and there are 0 such imports. You can't use t... | 3 | 2016-06-13T20:32:47Z | [
"python",
"global",
"python-3.4",
"python-module"
] |
Easiest way to get a http.response object in Scrapy | 37,798,626 | <p>I'm new to Scrapy and I am trying to "get the content of a web page" into a response object (if I correctly understood).</p>
<p>I am following <a href="http://doc.scrapy.org/en/latest/topics/selectors.html" rel="nofollow">http://doc.scrapy.org/en/latest/topics/selectors.html</a>,
which however works in scrapy shell... | 0 | 2016-06-13T20:31:20Z | 37,807,488 | <p>Your statement</p>
<pre><code>response = HtmlResponse(url=URL)
</code></pre>
<p>only builds <a href="http://doc.scrapy.org/en/latest/topics/request-response.html#htmlresponse-objects" rel="nofollow">a "local scope" <code>HtmlResponse</code> object</a>, with an empty body. It does not download anything, and especia... | 1 | 2016-06-14T09:03:19Z | [
"python",
"scrapy"
] |
How add plot to subplot matplotlib | 37,798,645 | <p>I have plots like this </p>
<pre><code>fig = plt.figure()
desire_salary = (df[(df['inc'] <= int(salary_people))])
print desire_salary
# Create the pivot_table
result = desire_salary.pivot_table('city', 'cult', aggfunc='count')
# plot it in a separate step. this returns the matplotlib axes
ax = result.plot(kind=... | 0 | 2016-06-13T20:32:16Z | 37,798,754 | <p><code>result</code> is of pandas.Series type, which doesn't have <code>add_subplot()</code> method.</p>
<p>use <code>fig.add_subplot(...)</code> instead</p>
<p>Here is an <a href="http://stackoverflow.com/a/37687133/5741205">example</a> (using seaborn module):</p>
<pre><code>labels = df.columns.values
fig, axes =... | 0 | 2016-06-13T20:39:51Z | [
"python",
"pandas",
"matplotlib"
] |
How add plot to subplot matplotlib | 37,798,645 | <p>I have plots like this </p>
<pre><code>fig = plt.figure()
desire_salary = (df[(df['inc'] <= int(salary_people))])
print desire_salary
# Create the pivot_table
result = desire_salary.pivot_table('city', 'cult', aggfunc='count')
# plot it in a separate step. this returns the matplotlib axes
ax = result.plot(kind=... | 0 | 2016-06-13T20:32:16Z | 37,799,021 | <p><a href="http://matplotlib.org/api/pyplot_api.html#module-matplotlib.pyplot" rel="nofollow"><code>matplotlib.pyplot</code></a> has the concept of the current figure and the current axes. All plotting commands apply to the current axes.</p>
<pre><code>import matplotlib.pyplot as plt
fig, axarr = plt.subplots(2, 3) ... | 1 | 2016-06-13T20:59:12Z | [
"python",
"pandas",
"matplotlib"
] |
Python program not exiting in except block | 37,798,767 | <p>I have a python program that does some data collection. In the collection function, I have to first check that the network connection is still alive, and exit(1) if it has been disconnected like so:</p>
<pre><code>try:
collect_data()
except:
logging.error("Connection dropped. Exiting program.")
exit(1)
... | 0 | 2016-06-13T20:40:58Z | 37,801,202 | <p>Thank you to @user2357112 and all others who commented for figuring this out. Turns out I was using too many blanket except statements and two things were happening:</p>
<ol>
<li><p>Depending on when the exit() was called, it sometimes got caught by other except blocks and got ignored.</p></li>
<li><p>Sometimes whe... | 0 | 2016-06-14T00:33:31Z | [
"python",
"exception-handling"
] |
Python - Find and replace regex substring in a string variable | 37,798,808 | <p>I have a variable with a multiline string and I'm trying to replace the line <code>test v1.0</code> with <code>upside</code> but the problem is I'm trying to replace it only if the entire line matches the pattern so it shouldn't replace the first <code>test v1.0.1</code></p>
<pre><code>pkgLogExtract = dedent("""
... | 1 | 2016-06-13T20:43:39Z | 37,798,877 | <p><code>\^</code> matches a literal <code>^</code>. Same goes about <code>$</code>. You need to pass <code>flags=re.M</code> to the <code>re.sub</code> and remove the backslashes from <code>^</code> and <code>$</code> so that they could match the start and end of line respectively. And escape the <code>.</code>.</p>
... | 3 | 2016-06-13T20:49:32Z | [
"python",
"regex",
"string"
] |
Getting an out of list assignment index out of range | 37,798,876 | <p>Not sure why it is going out of range. I set the range from 0 to 5.
Here is my code </p>
<pre><code>class Car(object):
def __init__ (self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
self.price = price
... | 0 | 2016-06-13T20:49:22Z | 37,798,916 | <p>Auto is a matrix of one entry, that is the number 5, i.e. [5]. You want it to instead be a matrix with 5 entries.</p>
| 1 | 2016-06-13T20:52:11Z | [
"python",
"indexing"
] |
Getting an out of list assignment index out of range | 37,798,876 | <p>Not sure why it is going out of range. I set the range from 0 to 5.
Here is my code </p>
<pre><code>class Car(object):
def __init__ (self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
self.price = price
... | 0 | 2016-06-13T20:49:22Z | 37,798,917 | <p>You set auto to <code>auto=[5]</code> but it should be <code>auto=[None]*5</code> or <code>auto=range(5)</code> </p>
<p>otherwise you create a list of length 1 and will get an out of bounds error when calling <code>auto[car]</code></p>
| 0 | 2016-06-13T20:52:21Z | [
"python",
"indexing"
] |
Getting an out of list assignment index out of range | 37,798,876 | <p>Not sure why it is going out of range. I set the range from 0 to 5.
Here is my code </p>
<pre><code>class Car(object):
def __init__ (self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
self.price = price
... | 0 | 2016-06-13T20:49:22Z | 37,798,929 | <p>That's because you're just creating a list with one element <code>5</code> in it. A better way to write this code might be </p>
<pre><code>auto = []
for car in range(0,5):
price = input("How much does the car cost? ")
speed = input("Mile per hour? ")
mileage = input("Mile per gallon? ")
fuel = raw_i... | 2 | 2016-06-13T20:53:28Z | [
"python",
"indexing"
] |
scrape website using python returns [] | 37,798,906 | <p>I'm trying to build a simple scrape for the following URL:</p>
<p><a href="http://www.bizjournals.com/milwaukee/datacenter/project-watch-what-is-being-built-in-milwaukee.html" rel="nofollow">http://www.bizjournals.com/milwaukee/datacenter/project-watch-what-is-being-built-in-milwaukee.html</a></p>
<p>What I'm tryi... | 1 | 2016-06-13T20:51:28Z | 37,798,995 | <p>They think you are a bot and are not allowing you to pull the content</p>
<p>Key lesson here - when you don't get what you expect, inspect what you get.</p>
<p>To get the text below I just took the content and printed it.</p>
<pre><code>>>>import requests
>>>page = requests.get('http://www.bizjo... | 4 | 2016-06-13T20:57:44Z | [
"python",
"web-scraping",
"beautifulsoup",
"python-requests",
"lxml"
] |
scrape website using python returns [] | 37,798,906 | <p>I'm trying to build a simple scrape for the following URL:</p>
<p><a href="http://www.bizjournals.com/milwaukee/datacenter/project-watch-what-is-being-built-in-milwaukee.html" rel="nofollow">http://www.bizjournals.com/milwaukee/datacenter/project-watch-what-is-being-built-in-milwaukee.html</a></p>
<p>What I'm tryi... | 1 | 2016-06-13T20:51:28Z | 37,823,583 | <p>As aforementioned, they apparently forbid scraping in their TOS. But might be happy if you ask them about your use case etc. </p>
<p>For the academic interest - all the map data is coming from <a href="https://online.maps4news.com/ia/2.0/?id=351%2FBE9%2FB24870F6A499C237B88CB54F27" rel="nofollow">https://online.map... | 0 | 2016-06-14T23:10:09Z | [
"python",
"web-scraping",
"beautifulsoup",
"python-requests",
"lxml"
] |
Installing Python Libraries in Built-from-source Python 2.7.11 | 37,798,969 | <p>I have built python from scratch and it now sits in a folder in my home directory. I am unsure of how to install libraries for this particular version/location.</p>
<p>Ubuntu comes with 2.7.6 and I need something in particular from 2.7.11.</p>
<p>Thanks!</p>
| 0 | 2016-06-13T20:56:35Z | 37,799,075 | <p>First of all get setuptools</p>
<pre><code> apt-get update
apt-get install python-setuptools
apt-get install python-pip
</code></pre>
<p>If you plan to use git and other tools install</p>
<pre><code> apt-get install git
apt-get install python-dev
</code></pre>
<p>Once pip and setuptools are in place you can g... | 0 | 2016-06-13T21:04:05Z | [
"python",
"ubuntu",
"linux-from-scratch"
] |
Installing Python Libraries in Built-from-source Python 2.7.11 | 37,798,969 | <p>I have built python from scratch and it now sits in a folder in my home directory. I am unsure of how to install libraries for this particular version/location.</p>
<p>Ubuntu comes with 2.7.6 and I need something in particular from 2.7.11.</p>
<p>Thanks!</p>
| 0 | 2016-06-13T20:56:35Z | 37,799,356 | <p>Get setuptools from <a href="https://pypi.python.org/pypi/setuptools" rel="nofollow">https://pypi.python.org/pypi/setuptools</a></p>
<p>run </p>
<pre><code>wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python
</code></pre>
<p>now you got setuptools and ez_setup.py - locate this file and run</p>
<pre><c... | 0 | 2016-06-13T21:23:20Z | [
"python",
"ubuntu",
"linux-from-scratch"
] |
Disable invalid name arguments pylint | 37,799,062 | <p>I have code like this:</p>
<pre><code>def func(df):
return df.column[0]
</code></pre>
<p>I am running pylint and it gives me this message all the time because it flags df as an invalid name despite it's convention.</p>
<pre><code>C:210, 9: Invalid variable name "df" (invalid-name)
</code></pre>
<p>Where 210 ... | 0 | 2016-06-13T21:02:54Z | 37,799,332 | <p>In your <code>pylintrc</code> file you can define a <code>good-names</code> variable with a comma seperated list of acceptable names that would otherwise fail the regex.</p>
<pre><code># Good variable names which should always be accepted, separated by a comma
good-names=i,j,df
</code></pre>
<p>If you do not alrea... | 4 | 2016-06-13T21:20:59Z | [
"python",
"pylint"
] |
Dataflow Python SDK Avro Source/Sync | 37,799,065 | <p>I am looking to ingest and write Avro files in GCS with the Python SDK. Is this currently possible with Avro leveraging the Python SDK? If so how would I do this? I see TODO comments in the source regarding this so I am not too optimistic.</p>
| 0 | 2016-06-13T21:03:14Z | 37,866,731 | <p>You are correct: the Python SDK does not yet support this, but it will soon.</p>
| 0 | 2016-06-16T18:25:57Z | [
"python",
"avro",
"google-cloud-dataflow"
] |
Pandas: simple numeric subtract from one column | 37,799,069 | <p>I need to simply subtract 2 from one column in a DataFrame. There are more columns in the df that need to remain unchanged.</p>
<p>The following has not effect. What am I doing wrong?</p>
<pre><code>func = lambda x: x - 2
df["customer"].apply(func)
</code></pre>
| -1 | 2016-06-13T21:03:22Z | 37,799,164 | <p><code>apply()</code> function returns changed data frame, but it doesn't change your DF in place</p>
<pre><code>In [49]: df
Out[49]:
a b c
0 2 9 1
1 0 5 9
2 1 5 6
3 6 3 4
4 8 0 8
In [50]: df["a"].apply(func)
Out[50]:
0 0
1 -2
2 -1
3 4
4 6
Name: a, dtype: int64
In [51]: df
Out[51]:... | 1 | 2016-06-13T21:09:14Z | [
"python",
"pandas"
] |
How to append data to text file in python 2.7.11? | 37,799,078 | <p>Could any one show me how i can add hyperlinks to new line in text file? If there is already data in first line of text file i want the data get inserted in the next empty line. I am writing multiple hyperlinks to text file(append). Thanks in advance.</p>
<pre><code> print "<a href=\"http://somewebsite.com/te... | 0 | 2016-06-13T21:04:15Z | 37,799,232 | <p>Take a look at the python <a href="https://docs.python.org/2.7/tutorial/inputoutput.html" rel="nofollow">docs</a>.</p>
<p>You can use the <code>with open</code> statement to open the file.</p>
<pre><code>with open(filename, 'a') as f:
f.write(text)
</code></pre>
| 0 | 2016-06-13T21:13:36Z | [
"python",
"string",
"python-2.7",
"text",
"file-io"
] |
How to append data to text file in python 2.7.11? | 37,799,078 | <p>Could any one show me how i can add hyperlinks to new line in text file? If there is already data in first line of text file i want the data get inserted in the next empty line. I am writing multiple hyperlinks to text file(append). Thanks in advance.</p>
<pre><code> print "<a href=\"http://somewebsite.com/te... | 0 | 2016-06-13T21:04:15Z | 37,799,510 | <p>You can collect the strings you want to write to the file in a list (etc.) and then use python's built-in file operations, namely <code>open(<file>)</code> and <code><file>.write(<string>)</code>, as such:</p>
<pre><code>strings = ['hello', 'world', 'today']
# Open the file for (a)ppending, (+) c... | 0 | 2016-06-13T21:34:32Z | [
"python",
"string",
"python-2.7",
"text",
"file-io"
] |
Run Python Selenium webdriver in ssh | 37,799,134 | <p>I want to run selenium webdriver in a remote server. I just tried a really simple script:</p>
<pre><code>from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(800,600))
display.start()
driver = webdriver.Chrome()
driver.get("http://www.google.com")
print browser.titl... | 2 | 2016-06-13T21:07:12Z | 38,077,050 | <p>If you change Chrome for Firefox, it works just fine (as long as you have correct version of Firefox - selenium always catches up, but it has some delay - so older version might be needed (update selenium and check what version works with it).</p>
<p>As for Chrome, try giving it path in argument. For example: <code... | 0 | 2016-06-28T13:03:56Z | [
"python",
"selenium",
"ssh"
] |
Overriding default and not plotting combinations of data on boxplot | 37,799,140 | <p>I have a <code>dataframe</code> in the following format:</p>
<p><a href="http://i.stack.imgur.com/TNA5k.png" rel="nofollow"><img src="http://i.stack.imgur.com/TNA5k.png" alt="enter image description here"></a></p>
<p>and I'm trying to <code>boxplot</code> it using the following code:</p>
<pre><code>plot = toPlot.... | 0 | 2016-06-13T21:07:30Z | 37,799,449 | <pre><code>fig = plt.figure()
ax1 = plt.subplot(1,2,1)
df.boxplot(column='Score',by='Q1',ax=ax1)
ax2 = plt.subplot(1,2,2)
df.boxplot(column='Score',by='Q2',ax=ax2)
fig.suptitle('test title', fontsize=20)
plt.show()
</code></pre>
| 1 | 2016-06-13T21:30:01Z | [
"python",
"pandas",
"plot",
"boxplot"
] |
BeautifulSoup subpages of list with "load more" pagination | 37,799,149 | <p>Quite new here, so apologies in advance. I'm looking to get a list of all company descriptions from <a href="https://angel.co/companies" rel="nofollow">https://angel.co/companies</a> to play around with. The web-based parsing tools I've tried aren't cutting it, so I'm looking to write a simple python script. Should ... | 2 | 2016-06-13T21:08:03Z | 37,799,849 | <p>The data you want to scrape is dynamically loaded using ajax, you need to do a lot of work to get to the html you actually want: </p>
<pre><code>import requests
from bs4 import BeautifulSoup
header = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Sa... | 2 | 2016-06-13T22:01:50Z | [
"python",
"parsing",
"beautifulsoup",
"screen-scraping"
] |
How can I configure category, subcategory and posts with slug in Django urls.py? | 37,799,182 | <p>I need to configure Django urls like this:</p>
<pre><code>/<slug_category>/
/<slug_category>/<slug_sub_category>/
/<slug_category>/<slug_post>/
</code></pre>
<p>I've tried this. The problem is that the <code>/<slug_category>/<slug_sub_category>/</code> and <code>/<slug_... | 1 | 2016-06-13T21:10:31Z | 37,838,325 | <p>You cannot use two different URLs because they have the same pattern (as has been pointed out in the comments). The solution is to use the same URL and to fetch the content accordingly. For example </p>
<pre><code>urlpatterns = [
url(r'^(?P<category_slug>[\w-]+)$', views.category),
url(r'^(?P<cat... | 1 | 2016-06-15T14:29:19Z | [
"python",
"django"
] |
Django - how to use kwargs | 37,799,248 | <p>I'm overriding the <code>.save()</code> method of a django model and I'm trying to pass an extra argument when saving:</p>
<p>View:</p>
<pre><code>def form_valid(self, form):
response = super(DeliveryCreateView, self).form_valid(form)
self.object.save(owner=self.request.user)
return response
</... | 0 | 2016-06-13T21:14:44Z | 37,799,516 | <p>Assuming this is a standard create or update view, the superclass <code>form_valid</code> will already be calling the model save method, via the form. You'll either need to deal with that situation, or don't call super.</p>
| 0 | 2016-06-13T21:35:01Z | [
"python",
"django"
] |
Create dataframe from nested dictionary keeping nested dictionary as column | 37,799,267 | <p>I have the following nested dictionary and I would like to convert it to a dataframe. </p>
<p><img src="http://i.stack.imgur.com/uTaVi.png" alt="Nested Dictionary"></p>
<p>The first two columns will be the keys of the first dictionary and the third column will be the nested dictionary. </p>
<p><img src="http://i.... | 0 | 2016-06-13T21:15:42Z | 37,799,567 | <p>That's not the greatest input data, but if you're confident that the structure of the dictionary won't change, you could try something like the below:</p>
<pre><code>DataFrame([
[x[0] for x in nested_dict.keys()],
[x[1] for x in nested_dict.keys()],
[x for x in nested_dict.values()],
]).... | 0 | 2016-06-13T21:38:54Z | [
"python",
"dictionary",
"dataframe"
] |
How to set request.body in django Request factory post request? | 37,799,491 | <p>trying to set request.body in python unit test as</p>
<pre><code> self.factory = RequestFactory()
self.request = self.factory.get(reverse('get_associations'))
self.request.user = self.auth_user
self.request.body = json.dumps(self.post_data)
</code></pre>
<p>but it gives error:</p>
<... | 0 | 2016-06-13T21:33:00Z | 37,799,823 | <p>Based on <a href="http://stackoverflow.com/questions/11802299/django-testing-post-based-views-with-json-objects">this answer</a>, try this:</p>
<pre><code>self.request = self.factory.get(reverse('get_associations'),
data=json.dumps(self.post_data),
con... | 1 | 2016-06-13T21:58:47Z | [
"python",
"django",
"unit-testing"
] |
save the values from dictionary in django fields running a for loop | 37,799,568 | <p>I am sending a dictionary with key as model fields in django and want to save them running a <code>for</code> loop like this:</p>
<pre><code>for key in dictionary:
object.key = dictionary[key]
object.save()
</code></pre>
<p>Here, the keys are the exact names of model fields, but it is not getting saved.</p... | 0 | 2016-06-13T21:38:58Z | 37,799,622 | <p>You're not setting the values on your object properly. You can use <code>setattr</code>, to set the values in the dictionary to the corresponding object attribute</p>
<pre><code>for key in dictionary:
setattr(object, key, dictionary[key])
object.save()
</code></pre>
<p><code>save</code> should be called after ... | 1 | 2016-06-13T21:44:26Z | [
"python",
"django",
"python-3.x",
"dictionary"
] |
save the values from dictionary in django fields running a for loop | 37,799,568 | <p>I am sending a dictionary with key as model fields in django and want to save them running a <code>for</code> loop like this:</p>
<pre><code>for key in dictionary:
object.key = dictionary[key]
object.save()
</code></pre>
<p>Here, the keys are the exact names of model fields, but it is not getting saved.</p... | 0 | 2016-06-13T21:38:58Z | 37,799,638 | <p>You can instantiate a Django model by passing its attributes to the constructor as kwargs, e.g.:</p>
<pre><code>model = Model(attr1=value1, attr2=value2)
</code></pre>
<p>This means you can instantiate a model based on your dictionary like this:</p>
<pre><code>model = Model(**dictionary)
</code></pre>
| 4 | 2016-06-13T21:45:22Z | [
"python",
"django",
"python-3.x",
"dictionary"
] |
Using placeholders (%d,%s) in plt.text (matplotlib.pyplot.text) | 37,799,598 | <p>I am facing an issue in assigning a numerical value to the annotated text (mean and standard deviation in this case) using plt.text command.</p>
<p>Since I have six subplots, I want to automate this process instead of writing it one by one. The code snippet containing the problem is attached below:</p>
<pre><code>... | 0 | 2016-06-13T21:41:42Z | 37,799,763 | <p>Try the following:</p>
<pre><code>for i, _ in enumerate(var):
plt.text(X_cord,Y_cord, r'$\mu=%s$' % (Mean[i]), fontsize=14)
</code></pre>
<p>I prefer to use the string method<code>.format</code>:</p>
<pre><code>for i, _ in enumerate(var):
plt.text(X_cord,Y_cord, r'$\mu={}$'.format(Mean[i]), fontsize=14)... | 2 | 2016-06-13T21:54:35Z | [
"python",
"matplotlib",
"tex"
] |
Confusion about one example to check if an object is an iterator in Python | 37,799,761 | <p>I have read some posts on stackoverflow about how to check an object is an iterator in Python but it seems that they did not solve my question. I have this example from the book <em>Effective Python</em></p>
<pre><code>def normalize_defensive(numbers):
if iter(numbers) is iter(numbers): # An iterator â bad!
... | 0 | 2016-06-13T21:54:30Z | 37,799,804 | <p>When you call an <em>iterable</em>, calling <code>iter()</code> on such an object will always produce a <em>new</em> iterator object. But calling <code>iter()</code> on an <em>iterator</em> will always return the same object; it is a requirement of the <a href="https://docs.python.org/3/library/stdtypes.html#iterato... | 2 | 2016-06-13T21:57:08Z | [
"python",
"iterator",
"iterable"
] |
Confusion about one example to check if an object is an iterator in Python | 37,799,761 | <p>I have read some posts on stackoverflow about how to check an object is an iterator in Python but it seems that they did not solve my question. I have this example from the book <em>Effective Python</em></p>
<pre><code>def normalize_defensive(numbers):
if iter(numbers) is iter(numbers): # An iterator â bad!
... | 0 | 2016-06-13T21:54:30Z | 37,799,947 | <p>To help you understand Martijn's explanation, take a look at the following:</p>
<pre><code>>>> numbers = [15, 35, 80]
>>> it = iter(numbers)
>>> it2 = iter(numbers)
>>> it3 = iter(it)
>>> id(it1)
51123792
>>> id(it2)
51056464 # id of it2 is different from it... | 0 | 2016-06-13T22:09:38Z | [
"python",
"iterator",
"iterable"
] |
ValueError: num must be 1 <= num <= 2, not 3 | 37,799,865 | <p>I have the following <code>dataframe</code> that I generated using <code>pivot_table</code>:</p>
<p><a href="http://i.stack.imgur.com/5tEeL.png" rel="nofollow"><img src="http://i.stack.imgur.com/5tEeL.png" alt="enter image description here"></a></p>
<p>and I'm using the following code to <code>boxplot</code> the m... | 1 | 2016-06-13T22:03:11Z | 37,800,200 | <p>Note that you only generate two subplots:</p>
<pre><code>ax = plt.subplot(1,2,i+1)
</code></pre>
<p>The first argument is the number of plots in each row and the second the number of plots per column (see also <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot" rel="nofollow">the matplotl... | 2 | 2016-06-13T22:34:25Z | [
"python",
"pandas",
"boxplot"
] |
How to organize an array that is returned using Curl? | 37,799,866 | <p>I am using the following command to list all the images in a catalog:</p>
<pre><code>curl -s http://internal.private.registry.com/v2/_catalog | python -c 'import sys,json;data=json.loads(sys.stdin.read()); print data["repositories"]'
</code></pre>
<p>It is giving the following output: </p>
<pre><code>[u'centos',... | -1 | 2016-06-13T22:03:11Z | 37,800,150 | <p>You should consider taking a look at <a href="https://stedolan.github.io/jq/" rel="nofollow"><code>jq</code></a> it's really quite fun to play with:</p>
<pre><code>curl -s ... | jq -r '.repositories[0:2] | to_entries | map("Repo \(.key+1 | tostring): \"\(.value)\"")[]'
Repo1: "centos"
Repo2: "containersol/consul-se... | 2 | 2016-06-13T22:29:51Z | [
"python",
"linux",
"bash",
"curl",
"sh"
] |
Iteration & Casting index values to integer and float in nested lists | 37,799,911 | <p>I'm having difficulty with iterating through the nested list table below. I understand how to iterate through the table once, but to go a level deeper and iterate through each nested list, I am stuck on the correct syntax to use. In iterating through the sublists, I am trying to cast each 'age' and 'years experience... | 0 | 2016-06-13T22:06:56Z | 37,800,105 | <p>Pass the argument <code>start</code> to <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>, <code>enumerate(table, 1)</code> in your case,</p>
<pre><code>table = [['first_name', 'last_name', 'age', 'years experience', 'salary'],
['James', 'Butt',... | 0 | 2016-06-13T22:25:21Z | [
"python",
"iteration"
] |
Iteration & Casting index values to integer and float in nested lists | 37,799,911 | <p>I'm having difficulty with iterating through the nested list table below. I understand how to iterate through the table once, but to go a level deeper and iterate through each nested list, I am stuck on the correct syntax to use. In iterating through the sublists, I am trying to cast each 'age' and 'years experience... | 0 | 2016-06-13T22:06:56Z | 37,800,408 | <p>If you can convert the space to an underscore in <code>years experience</code> you can use <code>collections.namedtuple</code> to make your life simpler:</p>
<pre><code>from collections import namedtuple
table = [
['first_name', 'last_name', 'age', 'years_experience', 'salary'],
['James', 'Butt', '29', '8'... | 0 | 2016-06-13T22:55:54Z | [
"python",
"iteration"
] |
What happens when we edit(append, remove...) a list and can we execute actions each time a list is edited | 37,799,938 | <p>I would like to know if there is a way to create a <code>list</code> that will execute some actions each time I use the method <code>append</code>(or an other similar method).
I know that I could create a <code>class</code> that inherits from <code>list</code> and overwrite <code>append</code>, <code>remove</code> a... | 1 | 2016-06-13T22:08:48Z | 37,801,475 | <p>If I understand correctly, you would want something like <code>Notify_list</code> that would call some method (argument to the constructor in my implementation) every time a mutating method is called, so you could do something like this:</p>
<pre><code>class Test:
def __init__(self):
self.list = Notify... | 3 | 2016-06-14T01:14:05Z | [
"python",
"list"
] |
Which scipy wheel to install for Windows 7? | 37,799,956 | <p>I'm running 64 bit python 2.7 on Windows 7.</p>
<p>There are wheels for scipy at <a href="https://pypi.python.org/pypi/scipy" rel="nofollow">https://pypi.python.org/pypi/scipy</a></p>
<p>In the above link, which wheel is for scipy for 64-bit Windows?</p>
| 0 | 2016-06-13T22:10:26Z | 37,800,072 | <p>As it is mentioned here:</p>
<blockquote>
<p>Windows does not have any package manager analogous to that in Linux, so installing one of the scientific Python distributions mentioned above is preferred. However, if that is not an option, Christoph Gohlke provides pre-built Windows installers for many Python packag... | 1 | 2016-06-13T22:22:33Z | [
"python",
"windows",
"scipy",
"64bit",
"python-wheel"
] |
How to process [Ljava.lang.object in hashmap from XML-RPC in Matlab? | 37,799,970 | <p>I'm trying to use the Apache XML-RPC Java client into Matlab, in combination with a python SimpleXMLRPCserver.</p>
<p>From the python server, I try to return a dictionary that is linking strings with lists, juts like the following:</p>
<pre><code>return {'node15': [12,58748], 'node34': [28,45784]}
</code></pre>
<... | 1 | 2016-06-13T22:11:36Z | 37,800,602 | <p>You need to convert it to array first, then you can use <code>cell</code> to cast to Matlab native types:</p>
<pre><code>cell(myHashMap.values().toArray());
</code></pre>
| 0 | 2016-06-13T23:16:05Z | [
"java",
"python",
"matlab",
"hashmap",
"xml-rpc"
] |
How to launch a TKinter Progress Bar from main | 37,800,007 | <p>I have code in a method that creates a progress bar:</p>
<pre><code>def progress_bar(self, message = None, icon_path = None, icon_name = None, size = 0, file_location = None, interval = 100):
#size: in bytes of download
#file_location: location of the download
#interval: frequency, in ms, of how often t... | 0 | 2016-06-13T22:15:11Z | 37,806,974 | <p>Simply keep calling the function <code>check_for_completion</code> with <code>after()</code> until your process is complete.</p>
<pre><code>def check_for_completion(self, file_location):
... # your code
if (self.progress["value"] >= self.progress["maximum"]):
... # you code
else: ... | 1 | 2016-06-14T08:39:41Z | [
"python",
"multithreading",
"tkinter",
"multiprocessing"
] |
How to launch a TKinter Progress Bar from main | 37,800,007 | <p>I have code in a method that creates a progress bar:</p>
<pre><code>def progress_bar(self, message = None, icon_path = None, icon_name = None, size = 0, file_location = None, interval = 100):
#size: in bytes of download
#file_location: location of the download
#interval: frequency, in ms, of how often t... | 0 | 2016-06-13T22:15:11Z | 37,815,185 | <p>Stevo, thanks for the lambda tip. I think we are close, but not quite there.. Perhaps I should share the code I am using to test this with: </p>
<pre><code>tmp, location = tempfile.mkstemp()
print location
frame4 = InstallerUserMessage(text = "", title = "foo")
frame4.progress_bar(message = "bar", icon_name="l... | 0 | 2016-06-14T14:41:32Z | [
"python",
"multithreading",
"tkinter",
"multiprocessing"
] |
How to animate a BuiltinSurface in Mayavi mlab? | 37,800,054 | <p>I'm attempting to animate the Earth rotating using Mayavi mlab. I've succeeded in the past by just rotating the camera around a BuiltinSurface representation of the Earth, but this becomes inconvenient when I need to plot many other objects (spacecraft, stars, etc) in the frame as well. The code below seems to "almo... | 0 | 2016-06-13T22:20:39Z | 38,750,556 | <p>I haven't been able to figure out a way to use Mayavi to make this happen. However, Vpython appears to be much better suited to accomplish this task. I've posted an example section of code below to make a revolving Earth, along with a few other features.</p>
<pre><code>from visual import *
def destroy():
for o... | 0 | 2016-08-03T17:53:06Z | [
"python",
"python-2.7",
"animation",
"mayavi",
"mlab"
] |
How to add extra fields to a django model by extending it? | 37,800,087 | <p>I am developing a django application using Pinax Stripe(<a href="https://github.com/pinax/pinax-stripe" rel="nofollow">https://github.com/pinax/pinax-stripe</a>). Pinax stripe is a bundled application which has a model called 'Plans'. Now in my application, I want to add some extra fields to the model 'Plans' in my ... | 0 | 2016-06-13T22:23:56Z | 37,800,135 | <p>You can inherit the <code>Plan</code> models and add your own attributes:</p>
<pre><code>from pinax-stripe.models import Plan
class MyPlan(Plan):
# add your attributes
pass
</code></pre>
<p>This works like normal inheritance in python, plus your custom attributes are migrated when you run a migration beca... | 0 | 2016-06-13T22:28:21Z | [
"python",
"django"
] |
How to add extra fields to a django model by extending it? | 37,800,087 | <p>I am developing a django application using Pinax Stripe(<a href="https://github.com/pinax/pinax-stripe" rel="nofollow">https://github.com/pinax/pinax-stripe</a>). Pinax stripe is a bundled application which has a model called 'Plans'. Now in my application, I want to add some extra fields to the model 'Plans' in my ... | 0 | 2016-06-13T22:23:56Z | 37,800,137 | <p>You can simply subclass <code>Plan</code> and add whatever fields / methods you want:</p>
<pre><code>from pinax-stripe.models import Plan
class UserProfile(Plan):
#write the extra fields here
</code></pre>
| 0 | 2016-06-13T22:28:44Z | [
"python",
"django"
] |
How to add extra fields to a django model by extending it? | 37,800,087 | <p>I am developing a django application using Pinax Stripe(<a href="https://github.com/pinax/pinax-stripe" rel="nofollow">https://github.com/pinax/pinax-stripe</a>). Pinax stripe is a bundled application which has a model called 'Plans'. Now in my application, I want to add some extra fields to the model 'Plans' in my ... | 0 | 2016-06-13T22:23:56Z | 37,804,272 | <p>I'd recommend you, use the <code>OneToOne</code> relationship <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model" rel="nofollow">like Django docs recommend to use in the User model</a></p>
<pre><code>from pinax-stripe.models import Plan
class UserProfile(model... | 0 | 2016-06-14T06:17:27Z | [
"python",
"django"
] |
How to add extra fields to a django model by extending it? | 37,800,087 | <p>I am developing a django application using Pinax Stripe(<a href="https://github.com/pinax/pinax-stripe" rel="nofollow">https://github.com/pinax/pinax-stripe</a>). Pinax stripe is a bundled application which has a model called 'Plans'. Now in my application, I want to add some extra fields to the model 'Plans' in my ... | 0 | 2016-06-13T22:23:56Z | 37,933,992 | <p>You can download pinax folder from <a href="https://github.com/pinax/pinax-stripe" rel="nofollow">https://github.com/pinax/pinax-stripe</a> into your app and edit models.py and admin.py files as per your requirement.</p>
| 0 | 2016-06-21T00:51:14Z | [
"python",
"django"
] |
add nested attributes to python | 37,800,161 | <p>the following code</p>
<pre><code>def _say(x): return x
class newObject(object):
def __init__(self, **kw):
for x in kw:
self.x = kw[x]
for i in self.x:
a = self.x[i]
eval('self.x.{u}={t}'.format(u=i, t=a)) #on another note, why would setattr(self... | 1 | 2016-06-13T22:30:41Z | 37,800,581 | <p>Why not pass data as a parameter to the class when you initialize it? So have the class take a dictionary as an argument. Not sure if I am missing something here.</p>
| 0 | 2016-06-13T23:13:44Z | [
"python",
"object",
"attributes"
] |
add nested attributes to python | 37,800,161 | <p>the following code</p>
<pre><code>def _say(x): return x
class newObject(object):
def __init__(self, **kw):
for x in kw:
self.x = kw[x]
for i in self.x:
a = self.x[i]
eval('self.x.{u}={t}'.format(u=i, t=a)) #on another note, why would setattr(self... | 1 | 2016-06-13T22:30:41Z | 37,800,634 | <p>You mixed up a couple of things. Here is a working version that is close to your code:</p>
<pre><code>class Attributes:
pass
class NewObject(object):
def __init__(self, **kw):
for x in kw:
attrs = Attributes()
setattr(self, x, attrs)
for i in kw[x]:
... | 1 | 2016-06-13T23:19:17Z | [
"python",
"object",
"attributes"
] |
Python readline() returns string that wont convert to int or float | 37,800,225 | <p>I am using Arduino SoftwareSerial library to send serial data to a Raspberry Rx pin. I can get the Arduino serial data sent over to the Raspberry successfully, in as much that the integers I sent arrive as the equivalent in a string.</p>
<p>The problem:</p>
<p>I am trying to convert the string that the .readline(... | -1 | 2016-06-13T22:36:48Z | 37,800,278 | <p>You can try doing:</p>
<p>a, b, c = IsInput</p>
<p>And probably you will get the integer values extracted into separate variables</p>
| -2 | 2016-06-13T22:41:57Z | [
"python",
"arduino",
"raspberry-pi"
] |
Python readline() returns string that wont convert to int or float | 37,800,225 | <p>I am using Arduino SoftwareSerial library to send serial data to a Raspberry Rx pin. I can get the Arduino serial data sent over to the Raspberry successfully, in as much that the integers I sent arrive as the equivalent in a string.</p>
<p>The problem:</p>
<p>I am trying to convert the string that the .readline(... | -1 | 2016-06-13T22:36:48Z | 37,800,306 | <p>The error is caused by the <code>\r\n</code> at the end of the line. <code>int()</code> and <code>float()</code> don't like that.</p>
<p>You can either strip it off like so:</p>
<pre><code>sInput = oSer.readline().strip()
</code></pre>
<p>Or you can modify the loop to ignore non-numbers:</p>
<pre><code>liInput ... | 2 | 2016-06-13T22:44:21Z | [
"python",
"arduino",
"raspberry-pi"
] |
Python readline() returns string that wont convert to int or float | 37,800,225 | <p>I am using Arduino SoftwareSerial library to send serial data to a Raspberry Rx pin. I can get the Arduino serial data sent over to the Raspberry successfully, in as much that the integers I sent arrive as the equivalent in a string.</p>
<p>The problem:</p>
<p>I am trying to convert the string that the .readline(... | -1 | 2016-06-13T22:36:48Z | 37,800,361 | <p>You can <code>rstrip</code> the trailing white space:</p>
<pre><code>while True:
sInput = oSer.readline().rstrip().split(",")
</code></pre>
<p>Or a more robust approach is to see if an element can be cast to a float using a try/except:</p>
<pre><code>def cast(it):
for ele in it:
try:
y... | 1 | 2016-06-13T22:50:05Z | [
"python",
"arduino",
"raspberry-pi"
] |
Python Dict Key with Multiple Values | 37,800,255 | <p>I'm VERY new to python, so please bare with me, (using learn python the hard way and it does NOT explain this very well at all).</p>
<p>I'm learning about dictionaries, and I know I could do this by creating two more dictionaries, but for brevity's sake, I wanted to make the code a bit more concise than having to c... | 0 | 2016-06-13T22:39:19Z | 37,800,324 | <p>Ideally, you'd have a homgonous datastructure -- e.g. a <code>list</code> of <code>dict</code><sup>1</sup>. Each <code>dict</code> would hold the information about a particular state:</p>
<pre><code>states1 = [
{'name': 'Oregon', 'abbrev': 'OR', 'population': 1000},
{'name': 'Florida', 'abbrev': 'FL', 'populat... | 1 | 2016-06-13T22:45:45Z | [
"python",
"dictionary"
] |
Python Dict Key with Multiple Values | 37,800,255 | <p>I'm VERY new to python, so please bare with me, (using learn python the hard way and it does NOT explain this very well at all).</p>
<p>I'm learning about dictionaries, and I know I could do this by creating two more dictionaries, but for brevity's sake, I wanted to make the code a bit more concise than having to c... | 0 | 2016-06-13T22:39:19Z | 37,800,443 | <p>You could make each value be a list.</p>
<p>I do not understand what exactly you want to achieve, but the easy way would be:</p>
<pre><code>states1 = {
1: ["Oregon", "OR", 1000]
2: ["Florida", "FL", 1000]
3: ["Pythonville", "PY", 1000]
4: ["Dictville", "DI", 1000]
}
</code></pre>
<p>Another thing you could look u... | 0 | 2016-06-13T22:59:34Z | [
"python",
"dictionary"
] |
Python Dict Key with Multiple Values | 37,800,255 | <p>I'm VERY new to python, so please bare with me, (using learn python the hard way and it does NOT explain this very well at all).</p>
<p>I'm learning about dictionaries, and I know I could do this by creating two more dictionaries, but for brevity's sake, I wanted to make the code a bit more concise than having to c... | 0 | 2016-06-13T22:39:19Z | 37,800,484 | <p>When I run it as you recommended me to (below), it spits out </p>
<pre><code>Michigan has the abbreviation MI and a population of 1000
Michigan has the abbreviation MI and a population of 1000
Michigan has the abbreviation MI and a population of 1000
</code></pre>
<p>not sure why it's continually doing that, I wou... | 0 | 2016-06-13T23:03:44Z | [
"python",
"dictionary"
] |
Python Dict Key with Multiple Values | 37,800,255 | <p>I'm VERY new to python, so please bare with me, (using learn python the hard way and it does NOT explain this very well at all).</p>
<p>I'm learning about dictionaries, and I know I could do this by creating two more dictionaries, but for brevity's sake, I wanted to make the code a bit more concise than having to c... | 0 | 2016-06-13T22:39:19Z | 37,800,497 | <p>Another example of how you could structure your data depending on your needs.</p>
<pre><code>states1 = {
'Oregon': {'abrv': 'OR','population': '1000'},
'Florida':{ 'abrv': 'MI', 'population': '1000'},
'California':{'abrv': 'CA', 'population': '1000'},
'NewYork':{'abrv': 'NY', 'population': '1000'},
'Michigan':{'abr... | 0 | 2016-06-13T23:05:05Z | [
"python",
"dictionary"
] |
Python Dict Key with Multiple Values | 37,800,255 | <p>I'm VERY new to python, so please bare with me, (using learn python the hard way and it does NOT explain this very well at all).</p>
<p>I'm learning about dictionaries, and I know I could do this by creating two more dictionaries, but for brevity's sake, I wanted to make the code a bit more concise than having to c... | 0 | 2016-06-13T22:39:19Z | 37,800,516 | <p>Just saw the last post, that makes a lot of sense. As far as how this could be useful, I don't know, it was just something I wanted to do, have three values to one key. I'm sure in the future I could take the info from a website or database and have it create pairs, like actors to characters played, but maybe not. I... | 0 | 2016-06-13T23:06:46Z | [
"python",
"dictionary"
] |
Healpy query_polygon returns incorrect area | 37,800,258 | <p>I'm using healpy.query_polygon to find the pixel indices corresponding to a rectangular FOV. However, the indices which are returned do not match my input- creating a polygon in healpy space which is ~100x larger than the FOV (or returns ~14000 pixels instead of the expected ~30 pixels).</p>
<p>The query_disc funct... | -1 | 2016-06-13T22:39:31Z | 37,803,530 | <p>Your problem is easily solved by considering what <code>query_polygon</code> accepts as input: it wants an <code>(N, 3)</code> array of coordinates, not an <code>(3, N)</code>. The value you're passing it is a 3-tuple of 4 elements each, which is transformed into an array of shape <code>(3, 4)</code>. Not sure what ... | 0 | 2016-06-14T05:21:36Z | [
"python",
"healpy"
] |
Verlet Integration in Python resulting in particles running away | 37,800,349 | <p>My fallowing code (was supposed to) solve the equation of motion for two bodies but the result is the particles running way and I wasn't able to find where is the error</p>
<pre class="lang-python prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
DIM = 2
N = 2
... | 1 | 2016-06-13T22:48:11Z | 38,226,678 | <p>Acceleration doesn't accumulate over time, the way velocity and position do: it should be computed from scratch at each step of the process. So, </p>
<ol>
<li>Remove <code>a</code> from the argument list of both <code>acc</code> and <code>verlet</code></li>
<li>Initialize <code>a</code> by zeros at the beginning of... | 1 | 2016-07-06T14:32:51Z | [
"python",
"numerical-integration",
"verlet-integration"
] |
Can't randomly generate list with functions with random.shuffle | 37,800,364 | <p>I'm trying to make a simple command line game in python. The only problem is that when I want to make the question randomly display, they don't. I will show you the current method I'm using to pick the functions (questions) out. </p>
<pre><code>while 1:
questionList = [Question1(), Question2(), Question3(), Que... | -2 | 2016-06-13T22:50:20Z | 37,800,397 | <p>To expand on John Gordon's comment this is what you need:</p>
<pre><code>while 1:
questionList = [Question1(), Question2(), Question3(), Question4(), Question5()]
random.shuffle(questionList)
print(questionList.pop())
print("Checking question list\n")
</code></pre>
| 0 | 2016-06-13T22:54:53Z | [
"python",
"random"
] |
Can't randomly generate list with functions with random.shuffle | 37,800,364 | <p>I'm trying to make a simple command line game in python. The only problem is that when I want to make the question randomly display, they don't. I will show you the current method I'm using to pick the functions (questions) out. </p>
<pre><code>while 1:
questionList = [Question1(), Question2(), Question3(), Que... | -2 | 2016-06-13T22:50:20Z | 37,800,468 | <p>You can use the shuffle function from the random module:</p>
<pre><code>while 1:
questionList = [Question1(), Question2(), Question3(), Question4(), Question5()]
newList = questionList
random.shuffle(questionList)
print(newList.pop(newList.index(holder)))
print("Checking question list\n")
</cod... | 0 | 2016-06-13T23:01:53Z | [
"python",
"random"
] |
Can't randomly generate list with functions with random.shuffle | 37,800,364 | <p>I'm trying to make a simple command line game in python. The only problem is that when I want to make the question randomly display, they don't. I will show you the current method I'm using to pick the functions (questions) out. </p>
<pre><code>while 1:
questionList = [Question1(), Question2(), Question3(), Que... | -2 | 2016-06-13T22:50:20Z | 37,800,580 | <p>Please keep in mind that in this case the functions in the array, i.e. <code>Question1(), Question2(), Question3(), Question4(), Question5()</code> will get called first. It is the <em>results</em> of these evaluations that will be assigned as the elements of <code>questionList</code>.</p>
<p>If you want to have th... | 0 | 2016-06-13T23:13:38Z | [
"python",
"random"
] |
Python / Elaphe generates broken barcodes | 37,800,370 | <p>I am trying to generate code128 barcodes using Python/Elaphe, which is based on Barcode Writer In Pure Postscript (BWIPP). Strangely, the barcodes generated by Elaphe don't match the ones generated by BWIPP and do not conform to code 128 standard.</p>
<p>In particular, I tried a simple example, the generation of a ... | 0 | 2016-06-13T22:51:07Z | 37,848,003 | <p>See this bug report:
<a href="https://bitbucket.org/whosaysni/elaphe/issues/84/code-128-generation-produces-unreadable" rel="nofollow">https://bitbucket.org/whosaysni/elaphe/issues/84/code-128-generation-produces-unreadable</a></p>
<p>It seems that this bug is fixed in the current source version, also the bug is st... | 0 | 2016-06-16T00:34:12Z | [
"python",
"barcode",
"elaphe"
] |
pandas dataframe(DatetimeIndex column) to spark dataframe (datetime format) | 37,800,383 | <p>I have a python pandas dataframe (pd_df) as follows: </p>
<pre><code> time count
0 2015-01-31 835
1 2015-02-28 1693
2 2015-03-31 2439
</code></pre>
<p>which I want to convert to spark dataframe (sp_df). I am using the following command : </p>
<p>When I tried </p>
<p... | 0 | 2016-06-13T22:52:47Z | 39,901,499 | <p>What I ended up doing in the same situation was to use apply to convert the date column (which for me was an int of year month day, ie 20150129) to a date using apply. Reminder, that apply runs for each row of the table, and returns the result.</p>
<pre><code>import datetime
pos_data['TRANSACTION_DATE_converted'] =... | 0 | 2016-10-06T16:44:49Z | [
"python",
"pandas",
"apache-spark",
"pyspark"
] |
Passing a subclass of a class that inherits from ctypes.Structure | 37,800,403 | <p>For code-cleanliness, I want to have my auto-generated ctypes wrapper for my c-structure separate from my Python-only extension (which has additional helper functions, etc).</p>
<p>I having trouble passing my sub-classed structure to the bindings that I auto-generated. Is there a way to do this?</p>
<pre><code>// ... | 0 | 2016-06-13T22:55:10Z | 37,827,528 | <p>As requested in the comments, here's an example using <code>ctypes.cast</code>:</p>
<pre><code># Python Implementation
import ctypes
class PyStruct(ctypes.Structure):
_fields_ = [('value', ctypes.c_int32)]
# Declaring a type name for simplicity
LP_LP_PyStruct = ctypes.POINTER(ctypes.POINTER(PyStruct))
pyfunc ... | 1 | 2016-06-15T06:21:44Z | [
"python",
"ctypes"
] |
Merging two columns which don't overlap and create new columns | 37,800,486 | <pre><code>import pandas as pd
df1 = pd.DataFrame([["2014", "q2"]],
columns=('Year', 'Quarter'))
df2 = pd.DataFrame([["2016", "q1"],
["2015", "q1"]],
columns=('Year', 'Quarter'))
print(df1.merge(df2, on='Year', how='outer'))
</code></pre>
<p>Results in:</p... | 0 | 2016-06-13T23:03:54Z | 37,800,550 | <p>You can use:</p>
<pre><code>df1.merge(df2, on=['Year', 'Quarter'], how='outer').dropna()
</code></pre>
<p>to get:</p>
<pre><code> Year Quarter
0 2014 q2
1 2016 q1
2 2015 q1
</code></pre>
<p>You can also look into pd.concat().</p>
| 1 | 2016-06-13T23:10:28Z | [
"python",
"pandas",
"merge"
] |
How to give each Category a color? | 37,800,493 | <p>We have a code to draw circles on the Location on the map with the name of each category. Now the circles and text are one color. How do we get them in different color's by category? Example: Category Garden: Blue, Category Stone: Grey.</p>
<p>So far the code:</p>
<pre><code>size(1500,800)
background(1)
nofill()
s... | 0 | 2016-06-13T23:04:39Z | 37,800,685 | <p>Here is a sketch of what I intend to include in my pure python data utility.</p>
<pre><code>def hexidecimalDiget(n,deHex = false):
if(n<0):
print "negitive values not supported by call to hexidecimalDiget("+str(n)+")"
return None
elif(n < 10):
return str(n)
elif(n < 15):... | 0 | 2016-06-13T23:25:22Z | [
"python",
"json",
"if-statement",
"colors"
] |
iterating in dataframe using python | 37,800,541 | <p>I need to iterate from the Dataframe, where str like </p>
<pre><code>http://work4you.su/register
http://vk.com/anime_yes
http://vk.com/anime_yes?z=photo-33172903_414023351%2Fwall-33172903_34658
http://yandex.ru/search?
http://vk.com/anime_yes?z=photo-33172903_413008739%2Fwall-33172903_34522
</code></pre>
<p>And if... | 0 | 2016-06-13T23:09:18Z | 37,800,658 | <p>Looks like the krux of the problem is finding the next row in a Dataframe</p>
<pre><code>for index,row in enumerate(df[column_with_urls][:-1]):
if 'yandex.ru/search' in row: print df[column_with_urls][index+1] == 'yandex.ru'
</code></pre>
<p>enumerate allows you to iterate over the rows and indexes, and you ca... | 0 | 2016-06-13T23:22:08Z | [
"python",
"loops",
"pandas"
] |
How to store Tornado logs to a file? | 37,800,585 | <p>I've been facing issues where my server is throwing a 500 if the API isn't accessed for 30 mins at a stretch. To check the problem, I need to keep track of every single API request made. I'm using Tornado in front of Flask. This is my code so far:</p>
<pre><code>import tornado.httpserver
import tornado.ioloop
impor... | 0 | 2016-06-13T23:14:07Z | 37,800,781 | <p>You have used <a href="http://www.tornadoweb.org/en/stable/log.html#tornado.log.enable_pretty_logging" rel="nofollow"><code>enable_pretty_logging</code></a> which is good, and if you might note the documentation says you can pass in a logger. So what is a logger? Turns out Python has very extensive support for log... | 2 | 2016-06-13T23:37:46Z | [
"python",
"flask",
"tornado"
] |
Multiple conditional data adjustments | 37,800,594 | <p>I have a df like this:</p>
<pre><code> Species Status T1 T2 T3
0 Kentucky L 96.0 88.0 79.0
1 Eupesu L 0.0 2.0 3.0
2 Serrated L 1.0 4.0 ... | 1 | 2016-06-13T23:15:08Z | 37,800,788 | <p>Here's how you can adjust the values:</p>
<pre><code>df = df.drop('Total').set_index(['Species', 'Status']) # recreating 'Total' and leaving only numerical columns
difference = 100 - df.sum() # adjustment values
for col, index in df.idxmax().items(): # works also if max() occurs in different rows
df.loc[index, ... | 2 | 2016-06-13T23:39:00Z | [
"python",
"pandas",
"dataframe"
] |
Multiple conditional data adjustments | 37,800,594 | <p>I have a df like this:</p>
<pre><code> Species Status T1 T2 T3
0 Kentucky L 96.0 88.0 79.0
1 Eupesu L 0.0 2.0 3.0
2 Serrated L 1.0 4.0 ... | 1 | 2016-06-13T23:15:08Z | 37,800,869 | <p>You have to use the .loc method on your dataframe:</p>
<pre><code>if df.T1.sum() > 1:
df.loc[df.T1 == df.T1.max(),'T1'] = df.T1.max()+df.T1.sum()
...
</code></pre>
| 1 | 2016-06-13T23:49:19Z | [
"python",
"pandas",
"dataframe"
] |
Implementing Iter for doubly-linked list | 37,800,639 | <p>Problem: Being new to python I am currently trying to learn the ropes, getting a better handle on the difference between an array and a linked structure. I've attempted creating a linked list class to assist in getting a better understanding of the language and its structures.
What I have written so far:</p>
<pre>... | 0 | 2016-06-13T23:19:28Z | 37,800,722 | <p>Since you say <code>self.head</code> is the sentinel node, your <code>__iter__</code> is incorrect; it's testing as if it expects to find a "falsy" value (e.g. <code>None</code>), when being circularly linked, it will never reach such a point. Presumably, you want something like:</p>
<pre><code>def __iter__(self):
... | 3 | 2016-06-13T23:29:35Z | [
"python",
"doubly-linked-list"
] |
Implementing Iter for doubly-linked list | 37,800,639 | <p>Problem: Being new to python I am currently trying to learn the ropes, getting a better handle on the difference between an array and a linked structure. I've attempted creating a linked list class to assist in getting a better understanding of the language and its structures.
What I have written so far:</p>
<pre>... | 0 | 2016-06-13T23:19:28Z | 37,800,866 | <p>You have a circular list. I diagnosed this with the usual high-tech method: the print statement. :-)</p>
<p>I inserted a couple of prints into your <strong>str</strong> method:</p>
<pre><code>def __str__(self):
if len(self)==0:
return '[]'
else:
print "NODE VALUE:", self.head.val
... | 0 | 2016-06-13T23:49:07Z | [
"python",
"doubly-linked-list"
] |
Protect against null environment variables when using os.path.expandvars | 37,800,710 | <p>How can I protect against Python's <code>os.path.expandvars()</code> treatment of null/unset environment variables?</p>
<p>From <a href="https://docs.python.org/2/library/os.path.html#os.path.expandvars" rel="nofollow">os.path</a>:</p>
<blockquote>
<p>Malformed variable names and references to non-existing varia... | 0 | 2016-06-13T23:27:52Z | 37,800,939 | <p>You could use <code>string.Template</code>, which uses a similar dollar-sign syntax for interpolation of variables but will raise <code>KeyError</code> if something doesn't exist rather than leaving it in.</p>
<pre><code>import os
from string import Template
print(Template('$HOME/stuff').substitute(os.environ))
</c... | 2 | 2016-06-13T23:58:25Z | [
"python",
"path",
"environment-variables"
] |
Deleting rows of data for multiple variables | 37,800,718 | <p>I have over 500 files that I cleaned up using a pandas data frame, and read in later as a matrix. I now want to delete missing rows of data from multiple variables for the entirety of my files. Each variable is pretty lengthy for its shape, for example, tc and wspd have the shape (84479, 558) and pressure has the sh... | 0 | 2016-06-13T23:28:56Z | 37,801,101 | <p>I would load your 2 dimensional arrays as pandas DataFrames and then use the <code>dropna</code> function to drop any rows that contain a null value</p>
<pre><code>wspd = pd.read_pickle('/home/wspd').dropna()
tc = pd.read_pickle('/home/tc').dropna()
</code></pre>
<p>The documentation for pandas.DataFrame.dropna is... | 0 | 2016-06-14T00:20:18Z | [
"python",
"pandas",
"multidimensional-array",
"missing-data",
"rowdeleting"
] |
Connection being reset by client | 37,800,846 | <p>So I am trying to have my computer to communicate with a device and I am getting an error of the Ethernet connection reset. The output from the server side looks like this</p>
<p><code>Calling accept on socket
Accepted connection socket csock:10
Received Ethernet connection from ip: 186.142.1.23
Warning - ... | 0 | 2016-06-13T23:47:06Z | 37,803,728 | <p>"Connection reset by peer" means that you tried to send data when the receiver had already closed the connection (and isn't expecting more data to arrive).</p>
<p>It looks like your server sends some data when you connect to it. Your client should read what it sends before closing the socket.</p>
| 0 | 2016-06-14T05:37:37Z | [
"python",
"sockets",
"networking"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.