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 - Split a row into columns - csv data | 38,855,648 | <p>Am trying to read data from csv file, split each row into respective columns. </p>
<p>But my regex is failing when a particular column has <strong>commas with in itself</strong>. </p>
<p>eg: a,b,c,"d,e, g,",f </p>
<p>I want result like: </p>
<pre><code>a b c "d,e, g," f
</code></pre>
<p>which... | 2 | 2016-08-09T16:06:55Z | 38,855,765 | <p>You can't easily parse CSV files with regex.</p>
<p>My go-to toolkit for handling CSV from the Unix command line is <code>csvkit</code>, which you can get from <a href="https://csvkit.readthedocs.io" rel="nofollow">https://csvkit.readthedocs.io</a> . It has a Python library as well.</p>
<p>The Python docs for the ... | 2 | 2016-08-09T16:13:31Z | [
"python",
"regex",
"csv",
"pyspark",
"rdd"
] |
Retrieve Default ACL in Python Using Posix 1e | 38,855,666 | <p>Using the <a href="http://pylibacl.k1024.org/module.html" rel="nofollow">posix 1e Python module</a> I am able to get/set the ACL for a file without having to spawn a subprocess and call <code>getfacl</code>/<code>setfacl</code>:</p>
<pre><code>>>> import posix1e
>>> acl1 = posix1e.ACL(file="file.t... | 0 | 2016-08-09T16:08:27Z | 38,856,272 | <p>Turns out there is a way to do this:</p>
<pre><code>default_acl1 = posix1e.ACL(filedef="/some/other/path/")
</code></pre>
| 0 | 2016-08-09T16:42:08Z | [
"python",
"acl"
] |
assertRaises for method with optional parameters | 38,855,717 | <p>I'm using <code>assertRaises</code> for <a href="https://docs.djangoproject.com/en/dev/topics/testing/" rel="nofollow">unit test in Django</a>.</p>
<p>Example method I want to test:</p>
<pre><code>def example_method(var, optional_var=None):
if optional_var is not None:
raise ExampleException()
</code><... | 0 | 2016-08-09T16:10:43Z | 38,855,718 | <p>Two ways to do it:</p>
<ol>
<li><p><strong>Just like in the question but putting the args</strong>:</p>
<pre><code>def test_method(self):
self.assertRaises(ExampleException, example_method, "some_var",
optional_var="not_none")
</code></pre></li>
<li><p><strong>With <code>with</co... | 1 | 2016-08-09T16:10:43Z | [
"python",
"django",
"unit-testing"
] |
Append float to list with for loop in python | 38,855,729 | <p>I am trying to add a list of monthly temperatures into a big list that will contain 24 months of temperatures. The problem is that they are given in floats, but to append items, they must be integers. </p>
<pre><code>temperatures = []
np.array(temperatures, dtype = np.float32)
</code></pre>
<p>(after my first mont... | -3 | 2016-08-09T16:11:19Z | 38,855,789 | <p>You have to save your nparray in a variable and then you can add your TEMP1 monthly temperatures all at once with the method append() like this :</p>
<pre><code>import numpy as np
TEMP1 = [22.4, 14.4, 12.3]
temperatures = []
floatTemperatures = np.array(temperatures, dtype = np.float32)
floatTemperatures = np.app... | 0 | 2016-08-09T16:14:35Z | [
"python",
"list",
"append"
] |
matplotlib generating strange y-axis on certain data sets? | 38,855,748 | <p>I am writing a python 2.7 script that generates multiple matplotlib graphs in a loop.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
</code></pre>
<p>Here I scale the data so the first point is 100</p>
<pre><code>scalefac = 100/float(sdata[0])
for dat in range(len(sdata)):
sdata[dat] = floa... | 0 | 2016-08-09T16:12:32Z | 38,859,468 | <p>If I understand you correctly the problem is the offset, e.g. <code>0.0002 + 9.9998e1</code>, which you want to be plotted as <code>100</code>, right? If so <a href="https://stackoverflow.com/questions/14711655/how-to-prevent-numbers-being-changed-to-exponential-form-in-python-matplotlib-fi">this answer</a> might h... | 0 | 2016-08-09T20:02:31Z | [
"python",
"python-2.7",
"numpy",
"matplotlib"
] |
Send data from Python to node a server with socket (NodeJS,Socket.io) | 38,855,818 | <p>I trying to send sensor data (in python) from my raspberry pi3 to my local node server.</p>
<p>I found a module for python called <a href="http://www.python-requests.org/en/latest/user/quickstart/#passing-parameters-in-urls" rel="nofollow">requests</a> to send data to a server.</p>
<p>Here I'm trying send the valu... | 2 | 2016-08-09T16:16:39Z | 38,856,592 | <p>you are using HTTP PUT from Python, but you are listening with a websocket server on nodejs side.</p>
<p><strong>Either</strong> have node listening for HTTP POST (I'd use POST rather than PUT):</p>
<pre><code>app.post('/data', function (req, res) {
//do stuff with the data here
});
</code></pre>
<p><stro... | 1 | 2016-08-09T17:00:45Z | [
"python",
"node.js",
"websocket",
"socket.io"
] |
Making functions to print first and last 10 elements of array | 38,855,944 | <p>I couldn't find anything related to printing the first 10 and last 10 elements of an array that's imported from a text file. Here's what I need to do:</p>
<ul>
<li>Add in a function will print the first ten elements of the array.</li>
<li>Add in a function that will print the last ten elements of the array.</li>
<l... | -2 | 2016-08-09T16:22:54Z | 38,856,058 | <p>You need to define <code>myList</code>, or simply pass <code>arr_intValues</code> into the function call for <code>ten</code>, i.e.</p>
<pre><code> ten(arr_intValues)
</code></pre>
<p>Print the first ten (as you do above)</p>
<pre><code>for item in myList[:10]:
print (item)
</code></pre>
<p>Print the last te... | 2 | 2016-08-09T16:29:12Z | [
"python",
"arrays",
"list",
"elements"
] |
Making functions to print first and last 10 elements of array | 38,855,944 | <p>I couldn't find anything related to printing the first 10 and last 10 elements of an array that's imported from a text file. Here's what I need to do:</p>
<ul>
<li>Add in a function will print the first ten elements of the array.</li>
<li>Add in a function that will print the last ten elements of the array.</li>
<l... | -2 | 2016-08-09T16:22:54Z | 38,856,232 | <p>Read a file into a list, one element per line:</p>
<pre><code>with open("filename.txt") as f:
lines = f.read().splitlines()
</code></pre>
<p>Print the first 10 elements of the list:</p>
<pre><code>print("\n".join(lines[:10]))
</code></pre>
<p>Print the last 10 elements of the list:</p>
<pre><code>print("\n"... | 0 | 2016-08-09T16:39:47Z | [
"python",
"arrays",
"list",
"elements"
] |
Prevent Django from parsing incorrect TIMESTAMP field | 38,856,034 | <p>I have a sqlite database (from an iOS application) similar to:</p>
<pre><code>CREATE TABLE ZSPL ( Z_PK INTEGER PRIMARY KEY, ZWHEN TIMESTAMP, ZWHEN2 real)
1, 492445270.121238, 492445270.121238
2, 492445270.871551, 492445270.871551
</code></pre>
<p>I was hoping to build a Django (v1.10) model to work with it <a hre... | 0 | 2016-08-09T16:27:49Z | 38,856,629 | <p>This isn't the answer I'm looking for as it involves changes to the Django library but at least it doesn't involve editing the source code itself.</p>
<p>In the same file as the model I've added the following lines:</p>
<pre><code>from django.db.backends.sqlite3.base import Database, decoder
Database.register_con... | 0 | 2016-08-09T17:03:18Z | [
"python",
"django",
"sqlite3"
] |
Matplotlib; adding circle to subplot - Issue/Confused | 38,856,061 | <p>Bit of an odd one, and I'm clearly missing something, but I'm getting some really weird behaviour, and I can't work out what I'm doing wrong.</p>
<p>I have a plot with subplots in a grid format (for the sake of this post, I'll say just a 2 by 2 grid). I want to plot some stuff on each and also add a circle. Should ... | 0 | 2016-08-09T16:29:19Z | 38,856,487 | <p>you are using same 'circle' plot for two different patches i think that is creating problem,it throws an error </p>
<blockquote>
<p>Can not reset the axes. You are probably trying to re-use an artist in more than one Axes which is not supported</p>
</blockquote>
<p>you need to create different circles for each ... | 1 | 2016-08-09T16:53:54Z | [
"python",
"matplotlib",
"geometry",
"subplot"
] |
Get the absolute value of a sum in an Excel sheet using openpyxl | 38,856,115 | <p>I am starting to use openpyxl and I want to copy the sum of a row.
In Excel the value is 150, but when I try to print it, the output I get is the formula, not the actual value: </p>
<pre><code>=SUM(B1:B19)
</code></pre>
<p>The script I use is: </p>
<pre><code>print(ws["B20"].value)
</code></pre>
<p>Using "data_o... | 0 | 2016-08-09T16:32:22Z | 38,858,349 | <p>Okay, here's a simple example</p>
<p>I have created a spreadsheet with first spreadsheet "Feuil1" (french version) which contains <code>A1,...,A7</code> as <code>1,2,3,4,5,6,7</code> and <code>A8=SUM(A1:A7)</code></p>
<p>Here's the code, that could be adapted maybe to other operators. maybe not so simply. It also ... | 1 | 2016-08-09T18:52:14Z | [
"python",
"openpyxl"
] |
Get the absolute value of a sum in an Excel sheet using openpyxl | 38,856,115 | <p>I am starting to use openpyxl and I want to copy the sum of a row.
In Excel the value is 150, but when I try to print it, the output I get is the formula, not the actual value: </p>
<pre><code>=SUM(B1:B19)
</code></pre>
<p>The script I use is: </p>
<pre><code>print(ws["B20"].value)
</code></pre>
<p>Using "data_o... | 0 | 2016-08-09T16:32:22Z | 38,919,882 | <p>I have solved the matter using a combination of openpyxl and pandas:</p>
<pre><code>import pandas as pd
import openpyxl
from openpyxl import Workbook , load_workbook
source_file = "Test.xlsx"
# write to file
wb = load_workbook (source_file)
ws = wb.active
ws.title = "hello world"
ws.append ([10,10])
wb.save(source... | 0 | 2016-08-12T13:59:48Z | [
"python",
"openpyxl"
] |
Unable to Load an Image from an URL at TKinter | 38,856,128 | <p>My goal is to display an JPG image from an URL using tkinter python.</p>
<p>This is the <a href="http://stackoverflow.com/questions/6086262/python-3-how-to-retrieve-an-image-from-the-web-and-display-in-a-gui-using-tkint">stackoverflow link</a> that I used as a reference. But when I try to run the code, I have recei... | 0 | 2016-08-09T16:33:08Z | 38,857,099 | <p>The first error is not specifying the <code>data</code> parameter within <code>ImageTk.PhotoImage(data=b64_data)</code>. However, I'm unsure why <code>PhotoImage</code> is unable to read base64 data.</p>
<p>A workaround would be to use <code>BytesIO</code> from the <code>io</code> module. You can pass in the raw da... | 1 | 2016-08-09T17:31:30Z | [
"python",
"tkinter",
"base64",
"python-imaging-library",
"urllib"
] |
Simple multithread for loop in Python | 38,856,172 | <p>I searched everywhere and I don't find any simple example of iterating a loop with multithreading.</p>
<p>For example, how can I do to multithread this loop?</p>
<pre><code>for item in range(0, 1000):
print item
</code></pre>
<p>Is there any way to cut it in like 4 threads, so one thread has 250 iterations?</... | 0 | 2016-08-09T16:35:51Z | 38,856,378 | <p>Easiest way is with <a href="https://docs.python.org/2.7/library/multiprocessing.html#module-multiprocessing.dummy" rel="nofollow">multiprocessing.dummy</a> (which uses threads instead of processes) and a <a href="https://docs.python.org/2.7/library/multiprocessing.html#module-multiprocessing.pool" rel="nofollow">Po... | 1 | 2016-08-09T16:47:27Z | [
"python",
"multithreading",
"iteration"
] |
Simple multithread for loop in Python | 38,856,172 | <p>I searched everywhere and I don't find any simple example of iterating a loop with multithreading.</p>
<p>For example, how can I do to multithread this loop?</p>
<pre><code>for item in range(0, 1000):
print item
</code></pre>
<p>Is there any way to cut it in like 4 threads, so one thread has 250 iterations?</... | 0 | 2016-08-09T16:35:51Z | 38,856,443 | <p>You'll have to do the splitting manually:</p>
<pre><code>import threading
def ThFun(start, stop):
for item in range(start, stop):
print item
for n in range(0, 1000, 100):
stop = n + 100 if n + 100 <= 1000 else 1000
threading.Thread(target = ThFun, args = (n, stop)).start()
</code></pre>
<p... | 0 | 2016-08-09T16:51:42Z | [
"python",
"multithreading",
"iteration"
] |
Cannot Import easygui module | 38,856,178 | <p>This is my first question on Stack Oveflow, so forgive me if I do something wrong.
I've been using Python for a few months. I'm trying to make a simple GUI. I came across EasyGUI. </p>
<p>When i try to import the module, i get an error:</p>
<pre><code> Traceback (most recent call last):
File "C:/Users/matthew... | 0 | 2016-08-09T16:36:21Z | 38,858,770 | <p>Try easygui 0.96.0 </p>
<p>I've been using easygui for some time but I had exactly the same problem today on a new machine with a fresh install of 3.5.2 with easygui 0.98.0. However, easygui 0.96.0 works for me.</p>
<ol>
<li>reverted to Py 3.5.1, same problem. </li>
<li>easygui 0.97 same issue on both Py 3.... | 3 | 2016-08-09T19:18:23Z | [
"python",
"import",
"importerror",
"easygui"
] |
Python: String replace index | 38,856,180 | <p>I mean, i want to replace <code>str[9:11]</code> for another string.
If I do <code>str.replace(str[9:11], "###")</code> It doesn't work, because the sequence [9:11] can be more than one time.
If str is <code>"cdabcjkewabcef"</code> i would get <code>"cd###jkew###ef"</code> but I only want to replace the second. </p>... | 0 | 2016-08-09T16:36:22Z | 38,856,340 | <p>Given txt and s - the string you want to replace:</p>
<pre><code>txt.replace(s, "***", 1).replace(s, "###").replace("***", s)
</code></pre>
<p>Another way:</p>
<pre><code>txt[::-1].replace(s[::-1], "###", 1)[::-1]
</code></pre>
| 0 | 2016-08-09T16:45:58Z | [
"python",
"string",
"python-3.x"
] |
Python: String replace index | 38,856,180 | <p>I mean, i want to replace <code>str[9:11]</code> for another string.
If I do <code>str.replace(str[9:11], "###")</code> It doesn't work, because the sequence [9:11] can be more than one time.
If str is <code>"cdabcjkewabcef"</code> i would get <code>"cd###jkew###ef"</code> but I only want to replace the second. </p>... | 0 | 2016-08-09T16:36:22Z | 38,856,436 | <p>Here is a sample code:</p>
<pre><code>word = "astalavista"
index = 0
newword = ""
addon = "xyz"
while index < 8:
newword = newword + word[index]
index += 1
ind = index
i = 0
while i < len(addon):
newword = newword + addon[i]
i += 1
while ind < len(word):
newword = newword + word[i... | 0 | 2016-08-09T16:51:22Z | [
"python",
"string",
"python-3.x"
] |
Python: String replace index | 38,856,180 | <p>I mean, i want to replace <code>str[9:11]</code> for another string.
If I do <code>str.replace(str[9:11], "###")</code> It doesn't work, because the sequence [9:11] can be more than one time.
If str is <code>"cdabcjkewabcef"</code> i would get <code>"cd###jkew###ef"</code> but I only want to replace the second. </p>... | 0 | 2016-08-09T16:36:22Z | 38,856,460 | <p>You can use <code>join()</code> with sub-strings.</p>
<pre><code>s = 'cdabcjkewabcef'
sequence = '###'
indicies = (9,11)
print sequence.join([s[:indicies[0]-1], s[indicies[1]:]])
>>> 'cdabcjke###cef'
</code></pre>
| 1 | 2016-08-09T16:52:34Z | [
"python",
"string",
"python-3.x"
] |
Python: String replace index | 38,856,180 | <p>I mean, i want to replace <code>str[9:11]</code> for another string.
If I do <code>str.replace(str[9:11], "###")</code> It doesn't work, because the sequence [9:11] can be more than one time.
If str is <code>"cdabcjkewabcef"</code> i would get <code>"cd###jkew###ef"</code> but I only want to replace the second. </p>... | 0 | 2016-08-09T16:36:22Z | 38,856,535 | <p>you can do</p>
<pre><code>s="cdabcjkewabcef"
snew="".join((s[:9],"###",s[12:]))
</code></pre>
<p>which should be faster than joining like <code>snew=s[:9]+"###"+s[12:]</code> on large strings</p>
| 1 | 2016-08-09T16:57:12Z | [
"python",
"string",
"python-3.x"
] |
Running an R script from command line (to execute from python) | 38,856,271 | <p>I'm currently trying to run an R script from the command line (my end goal is to execute it as the last line of a python script). I'm not sure what a batch file is, or how to make my R script 'executable'. Currently it is saved as a .R file. It works when I run it from R.<br>
How do I execute this from the windows... | 2 | 2016-08-09T16:42:05Z | 38,856,331 | <p>You probably already have R, since you can already run your script.</p>
<p>All you have to do is find its binaries (the Rscript.exe file).</p>
<p>Then open windows command line ([cmd] + [R] > type in : "cmd" > [enter])</p>
<p>Enter the full path to R.exe, followed by the full path to your script.</p>
| 1 | 2016-08-09T16:45:39Z | [
"python",
"shell",
"command-line"
] |
Running an R script from command line (to execute from python) | 38,856,271 | <p>I'm currently trying to run an R script from the command line (my end goal is to execute it as the last line of a python script). I'm not sure what a batch file is, or how to make my R script 'executable'. Currently it is saved as a .R file. It works when I run it from R.<br>
How do I execute this from the windows... | 2 | 2016-08-09T16:42:05Z | 38,856,393 | <p>You already have <code>Rscript</code>, it came with your version of R. If <code>R.exe</code>, <code>Rgui.exe</code>, ... are in your path, then so is <code>Rscript.exe</code>.</p>
<p>Your call from Python could just be <code>Rscript myFile.R</code>. Rscript is much better than <code>R BATCH CMD ...</code> and othe... | 1 | 2016-08-09T16:48:22Z | [
"python",
"shell",
"command-line"
] |
Running an R script from command line (to execute from python) | 38,856,271 | <p>I'm currently trying to run an R script from the command line (my end goal is to execute it as the last line of a python script). I'm not sure what a batch file is, or how to make my R script 'executable'. Currently it is saved as a .R file. It works when I run it from R.<br>
How do I execute this from the windows... | 2 | 2016-08-09T16:42:05Z | 38,856,920 | <p>As mentioned, Rscript.exe the automated executable to run R scripts ships with any R installation (usually located in bin folder) and as <a href="http://stackoverflow.com/questions/3412911/r-exe-rcmd-exe-rscript-exe-and-rterm-exe-whats-the-difference">@Dirk Eddelbuettel mentions</a> is the recommended automated vers... | 1 | 2016-08-09T17:20:56Z | [
"python",
"shell",
"command-line"
] |
python: read data from stdin and raw_input | 38,856,286 | <p>I want to pass some data to a python script using echo and after that promote the user to input options. I am running through an <code>EOFError</code> which I think is happening since I read all data in <code>sys.stdin</code>. How do I fix this issue? Thanks!</p>
<p>code.py:</p>
<pre><code>x = ''
for line in sys.s... | 0 | 2016-08-09T16:42:43Z | 38,856,351 | <p>You just cannot send data through stdin (that's redirecting) and then get back the interactive mode.</p>
<p>When you perform <code>a | b</code>, b cannot read from standard input anymore. If it wants to do that, it will stop as soon as <code>a</code> finishes and breaks the pipe. </p>
<p>But when <code>a</code> fi... | 1 | 2016-08-09T16:46:17Z | [
"python",
"stdin",
"eoferror"
] |
python: read data from stdin and raw_input | 38,856,286 | <p>I want to pass some data to a python script using echo and after that promote the user to input options. I am running through an <code>EOFError</code> which I think is happening since I read all data in <code>sys.stdin</code>. How do I fix this issue? Thanks!</p>
<p>code.py:</p>
<pre><code>x = ''
for line in sys.s... | 0 | 2016-08-09T16:42:43Z | 38,856,370 | <p>Use:</p>
<pre><code>{ echo -e -n '1324'; cat; } | ./code.py
</code></pre>
<p>First <code>echo</code> will write the literal string to the pipe, then <code>cat</code> will read from standard input and copy that to the pipe. The python script will see this all as its standard input.</p>
| 2 | 2016-08-09T16:46:51Z | [
"python",
"stdin",
"eoferror"
] |
TensorFlow queue feed order | 38,856,292 | <p>I'm wondering in what order TensorFlow queues feed data (specifically when you have a list of tensors that they're feeding from).</p>
<p>For example, in a queue like this:</p>
<pre><code>fifo_q = tf.FIFOQueue(
capacity=10,
dtypes=[tf.string, tf.string]
shapes=[[], []])
</... | 2 | 2016-08-09T16:43:17Z | 38,856,513 | <p>TensorFlow queues allow you to enqueue and dequeue lists (more precisely fixed-length tuples) of tensors atomically, in a single operation. The tensors <code>dq1</code> and <code>dq2</code> are the outputs of the same dequeue operation, which in this case will remove a tuple of two tensors from the queue. Each invoc... | 1 | 2016-08-09T16:55:59Z | [
"python",
"tensorflow"
] |
Selecting multiple partitioned regions in ABAQUS with findAt for setting mesh controls | 38,856,474 | <p>With reference to my previous question, </p>
<p><a href="http://stackoverflow.com/questions/38625874/faster-way-to-partition-a-face-with-sketch-in-abaqus-with-scripting">Faster way to partition a Face with Sketch in ABAQUS with scripting</a>,</p>
<p>I have to select the multiple regions created by the partitioning... | 0 | 2016-08-09T16:53:14Z | 38,859,808 | <p>try this, use <code>findAt</code> on each individual point and add the results:</p>
<pre><code> for i in range(range_arg):
# Put x,y,z coords in one value
incremental_picked_regions = (x_left + (i * (x_right -
x_left)/2), y_bottom + (i * (y_top - y_bottom)/2), 0.0)
if i==0 :
... | 0 | 2016-08-09T20:26:03Z | [
"python",
"scripting",
"abaqus"
] |
Selecting multiple partitioned regions in ABAQUS with findAt for setting mesh controls | 38,856,474 | <p>With reference to my previous question, </p>
<p><a href="http://stackoverflow.com/questions/38625874/faster-way-to-partition-a-face-with-sketch-in-abaqus-with-scripting">Faster way to partition a Face with Sketch in ABAQUS with scripting</a>,</p>
<p>I have to select the multiple regions created by the partitioning... | 0 | 2016-08-09T16:53:14Z | 38,883,235 | <p>Anyone looking for a better understanding of this question, I'd first of all, advise to look up on my other linked question.</p>
<p>I solved this problem of mine by using <code>getByBoundingBox</code>which has the following syntax:
<code>getByBoundingBox(xmin, ymin, zmin, xmax, ymax, zmax)</code></p>
<p>So, this ... | 0 | 2016-08-10T20:46:57Z | [
"python",
"scripting",
"abaqus"
] |
optimising way of exporting a dataframe in pandas | 38,856,482 | <p>I want to export dataframes efficiently by avoiding the use of loops.My format is specific so I can not use any prebuilt function like pandas.to_csv...
This is what i have at the moment</p>
<pre><code>def export(datafr,fout):
fo=open(fout,'w')
fo.write('#channel d '+'\" "date" - date\n')
fo.write('#chan... | 0 | 2016-08-09T16:53:33Z | 38,922,724 | <p>IIUC you want to write some header to an output file first, and afterwards, the data frame with formatted floats.</p>
<p>I believe you can still do it with pandas <code>to_csv</code> using the arguments: <code>mode</code> (set to "append" instead of default "write") and <code>float_format</code>.</p>
<p>So first g... | 1 | 2016-08-12T16:34:45Z | [
"python",
"pandas",
"file-io"
] |
Execute SQL file with multiple statements separated by ";" using pyodbc | 38,856,534 | <p>I am currently writing a script to run multiple SQL files using Python, a little background before you mention alternative methods; this is to automate the scripts and Python is the only tools I have on our windows 2008 server. I have a script that works for one set but the issue is when the other set has two statem... | 0 | 2016-08-09T16:57:06Z | 38,857,840 | <p>The API in the pyodbc connector (or pymysql) doesn't allow multiple statements in a SQL call. This is an issue of engine parsing; an API would need to completely understand the SQL that it's passing in order for multiple statements to be passed, and then multiple results handled upon return.</p>
<p>A slight modific... | 3 | 2016-08-09T18:19:46Z | [
"python",
"pyodbc",
"netezza"
] |
NameError: name not defined | 38,856,538 | <p>I'm trying to analyze some data, my code is as follows:</p>
<pre><code>for line in h:
if line_cnt in start_x:
recording_scores = True
temp_i = start_x.index(line_cnt)
score_acc = [0, 0, 0]
codon_id = remainder_x[temp_i]
temp_z = line.split()
temp_score = float(te... | -3 | 2016-08-09T16:57:21Z | 38,856,854 | <p>As Morgan pointed out, you don't define <code>temp_i</code> or <code>line_cnt</code> if you don't go into the first loop. I don't know what you want to do exactly, but you probably meant to do this if you only meant to test the second condition if the first was true.</p>
<pre><code>for line in h:
if line_cnt i... | 0 | 2016-08-09T17:16:25Z | [
"python"
] |
Panda rolling window percentile rank | 38,856,551 | <p>I am trying to calculate the percentile rank of data by column within a rolling window.</p>
<pre><code>test=pd.DataFrame(np.random.randn(20,3),pd.date_range('1/1/2000',periods=20),['A','B','C'])
test
Out[111]:
A B C
2000-01-01 -0.566992 -1.494799 0.462330
2000-01-02 -0.550769 -... | 2 | 2016-08-09T16:57:56Z | 38,856,907 | <p>Your lambda receives a numpy array, which does not have a <code>.rank</code> method — it is pandas's <code>Series</code> and <code>DataFrame</code> that have it. You can thus change it to</p>
<pre><code>pctrank = lambda x: pd.Series(x).rank(pct=True).iloc[-1]
</code></pre>
<p>Or you could use pure numpy alon... | 1 | 2016-08-09T17:20:20Z | [
"python",
"pandas",
"apply",
"rank",
"percentile"
] |
**line 110, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str' | 38,856,565 | <p>So, someone at the company left and I was handed this script (which we really need to work). I've never programmed a day in my life.</p>
<p>After some googling and YouTube, I understand the issue to be that somewhere in the code it is trying to string together using + an integer and a string (and this is not allowe... | 1 | 2016-08-09T16:58:53Z | 38,856,672 | <p>In Python, you cannot "add" a number and a string of characters. Hence, you must first convert the number to its character representation.
Try replacing the code with this:</p>
<pre><code> account_str = str(account) # Save the converted account string
if stage == 'CAC':
if fund == 'ELP':
logNotes(acc... | 0 | 2016-08-09T17:06:29Z | [
"python",
"python-3.x"
] |
What does the group_keys argument to pandas.groupby actually do? | 38,856,583 | <p>In <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>pandas.DataFrame.groupby</code></a>, there is an argument <code>group_keys</code>, which I gather is supposed to do something relating to how group keys are included in the dataframe subsets. Accordi... | 5 | 2016-08-09T17:00:09Z | 38,857,246 | <p>If you are passing a function that preserves an index, pandas tries to keep that information. But if you pass a function that removes all semblance of index information, <code>group_keys=True</code> allows you to keep that information.</p>
<p>Use this instead</p>
<pre><code>f = lambda df: df.reset_index(drop=True... | 2 | 2016-08-09T17:41:51Z | [
"python",
"pandas"
] |
What does the group_keys argument to pandas.groupby actually do? | 38,856,583 | <p>In <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>pandas.DataFrame.groupby</code></a>, there is an argument <code>group_keys</code>, which I gather is supposed to do something relating to how group keys are included in the dataframe subsets. Accordi... | 5 | 2016-08-09T17:00:09Z | 38,857,733 | <p><code>group_keys</code> parameter in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> comes handy during <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></... | 1 | 2016-08-09T18:12:23Z | [
"python",
"pandas"
] |
Given three coordinate points, how do you detect when the angle between them crosses 180 degrees? | 38,856,588 | <p>This seems like it should be really simple but I'm having trouble with it. Basically, I have three points that keep changing (lets call them p1, p2, and p3). Also, let's define p2 as the vertex point.</p>
<p>Essentially, what I need to do is calculate the angle between the three points. A good example would be i... | 2 | 2016-08-09T17:00:25Z | 38,856,685 | <p>What you are trying to decide is whether (p3-p2) is a left or right turn comparing to (p2-p1). This is actually a core part of Graham Scan which is used for computing convex hulls (<a href="https://en.wikipedia.org/wiki/Graham_scan" rel="nofollow">https://en.wikipedia.org/wiki/Graham_scan</a>). Quoting Wikipedia wit... | 5 | 2016-08-09T17:07:05Z | [
"python",
"math",
"geometry",
"trigonometry",
"angle"
] |
Given three coordinate points, how do you detect when the angle between them crosses 180 degrees? | 38,856,588 | <p>This seems like it should be really simple but I'm having trouble with it. Basically, I have three points that keep changing (lets call them p1, p2, and p3). Also, let's define p2 as the vertex point.</p>
<p>Essentially, what I need to do is calculate the angle between the three points. A good example would be i... | 2 | 2016-08-09T17:00:25Z | 38,856,694 | <p>To get signed angle in the full range, use atan2 function with dot and cross product of vectors <code>p2p1</code> and <code>p2p3</code></p>
<pre><code>Angle(in radians) = atan2(cross(p2p1,p2p3), dot(p2p1,p2p3))
</code></pre>
| 0 | 2016-08-09T17:07:43Z | [
"python",
"math",
"geometry",
"trigonometry",
"angle"
] |
Tensorflow: No module named contrib.learn.python.learn.datasets.mnist | 38,856,636 | <pre><code>import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
</code></pre>
<p>I tried executing the above and I am getting the below error:</p>
<pre><code>ImportError: No module named contrib.learn.python.learn.datasets.mnist
</code></pre>
<p>I did <code>sudo pip... | 0 | 2016-08-09T17:03:57Z | 38,858,627 | <p>The <a href="https://www.tensorflow.org/versions/r0.7/tutorials/mnist/beginners/index.html" rel="nofollow">TF 0.7 MNIST tutorial</a> suggests this snippet for loading data</p>
<pre><code>from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
</code>... | 0 | 2016-08-09T19:08:22Z | [
"python",
"module",
"tensorflow"
] |
median of multiple files in pandas | 38,856,754 | <p>I have several csv files that I'm loading into pandas. The contain all the same columns, and <strong>almost</strong> but not exactly the same indexes. The rows are indexed by a pair (segVar, val). </p>
<p>What I want is a new DataFrame in with the same columns, and the union of the indexes, and each row is the medi... | -1 | 2016-08-09T17:10:44Z | 38,857,211 | <p>The answer, as Ayhan says is concat and groupby. I'll post my next question (how to sort the rows) in a different question, because it is easier to phrase.</p>
| 0 | 2016-08-09T17:39:07Z | [
"python",
"pandas",
"dataframe"
] |
median of multiple files in pandas | 38,856,754 | <p>I have several csv files that I'm loading into pandas. The contain all the same columns, and <strong>almost</strong> but not exactly the same indexes. The rows are indexed by a pair (segVar, val). </p>
<p>What I want is a new DataFrame in with the same columns, and the union of the indexes, and each row is the medi... | -1 | 2016-08-09T17:10:44Z | 38,956,742 | <p>You can use pd.concat to combine the DataFrames and use groupby on the index:</p>
<pre><code>df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [2, 3, 5]}, index = [1, 2, 3])
df1
Out:
A B
1 1 2
2 2 3
3 3 5
df2 = pd.DataFrame({'A': [4, 5, 2], 'B': [1, 6, 3]}, index = [2, 3, 5])
df2
Out:
A B
2 4 1
3 5 6
... | 1 | 2016-08-15T14:11:15Z | [
"python",
"pandas",
"dataframe"
] |
What is the point of calling super in custom error classes in python? | 38,856,819 | <p>So I have a simple custom error class in Python that I created based on the Python 2.7 documentation:</p>
<pre><code>class InvalidTeamError(Exception):
def __init__(self, message='This user belongs to a different team'):
self.message = message
</code></pre>
<p>This gives me warning <code>W0231: __init_... | 7 | 2016-08-09T17:14:36Z | 38,857,670 | <p>Lookinv at the cpython2.7 source code there should be no problem avoiding that call to super <strong>init</strong> and Yes it's done just because its generally a good practice to call base class init in your init.</p>
<p><a href="https://github.com/python/cpython/blob/master/Objects/exceptions.c" rel="nofollow">htt... | -1 | 2016-08-09T18:08:58Z | [
"python",
"python-2.7",
"exception",
"pylint"
] |
What is the point of calling super in custom error classes in python? | 38,856,819 | <p>So I have a simple custom error class in Python that I created based on the Python 2.7 documentation:</p>
<pre><code>class InvalidTeamError(Exception):
def __init__(self, message='This user belongs to a different team'):
self.message = message
</code></pre>
<p>This gives me warning <code>W0231: __init_... | 7 | 2016-08-09T17:14:36Z | 38,857,736 | <p>This was a valid pylint warning: by not using the superclass <code>__init__</code> you can miss out on implementation changes in the parent class. And, indeed, you have - because <code>BaseException.message</code> has been deprecated as of Python 2.6.</p>
<p>Here would be an implementation which will avoid your wa... | 8 | 2016-08-09T18:12:37Z | [
"python",
"python-2.7",
"exception",
"pylint"
] |
Iterating through two pandas dataframes and appending data from one dataframe to the other | 38,856,904 | <p>I have two pandas data-frames that look like this: </p>
<p>data_frame_1:</p>
<pre><code>index un_id city
1 abc new york
2 def atlanta
3 gei toronto
4 lmn tampa
</code></pre>
<p>data_frame_2:</p>
<pre><code>index name un_id
1 frank gei
2 ... | 1 | 2016-08-09T17:20:04Z | 38,857,189 | <p>use pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow">merge</a>:</p>
<pre><code>In[14]:df2.merge(df1,on='un_id')
Out[14]:
name un_id city
0 frank gei toronto
1 john lmn tampa
2 lisa abc new york
3 jessica def at... | 2 | 2016-08-09T17:37:21Z | [
"python",
"pandas",
"dataframe",
"iteration"
] |
neural net sigmoid function "takes exactly 1 argument (2 given)" | 38,856,948 | <p>trying to forward propagate some data through a neural net</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
class Neural_Network(object):
def __init__(self):
#Define Hyperparameters
self.inputLayerSize = 2
self.outputLayerSize = 1
self.hiddenLayerSize = 3
#Weights (par... | 0 | 2016-08-09T17:22:16Z | 38,856,964 | <p>You are missing a <code>self</code> argument for the <code>sigmoid</code> function. <code>def sigmoid(z):</code> -> <code>def sigmoid(self, z):</code>. This <code>self.sigmoid(self.z3)</code> is effectively calling <code>sigmoid</code> with <code>self</code> as the first parameter and <code>self.z3</code> as the sec... | 1 | 2016-08-09T17:23:07Z | [
"python",
"neural-network",
"matrix-multiplication",
"sigmoid"
] |
Make a list of every column in a file in Python | 38,856,990 | <p>I would like to create a list for every column in a txt file.
The file looks like this:</p>
<p><code>NAME S1 S2 S3 S4
A 1 4 3 1
B 2 1 2 6
C 2 1 3 5</code></p>
<p>PROBLEM 1 . How do I dynamically make the number of lists that fit the number of columns, such that I can f... | 0 | 2016-08-09T17:24:40Z | 38,857,072 | <h2>Problem 1:</h2>
<p>You can use <code>len(head_list)</code> instead of having to specify <code>HOW_MANY_SAMPLES</code>.</p>
<p>You can also try using <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">Python's CSV module</a> and setting the delimiter to a space or a tab instead of a comma.</p>
<p... | 2 | 2016-08-09T17:29:38Z | [
"python",
"list",
"multiple-columns"
] |
Make a list of every column in a file in Python | 38,856,990 | <p>I would like to create a list for every column in a txt file.
The file looks like this:</p>
<p><code>NAME S1 S2 S3 S4
A 1 4 3 1
B 2 1 2 6
C 2 1 3 5</code></p>
<p>PROBLEM 1 . How do I dynamically make the number of lists that fit the number of columns, such that I can f... | 0 | 2016-08-09T17:24:40Z | 38,857,834 | <p>By using <code>pandas</code> you can create a list of list or a dic to get what you are looking for.</p>
<p>Create a <code>dataframe</code> from your file, then iterate through each column and add it to a list or dic.</p>
<pre><code>from StringIO import StringIO
import pandas as pd
TESTDATA = StringIO("""NAME S... | 2 | 2016-08-09T18:19:15Z | [
"python",
"list",
"multiple-columns"
] |
Pandas: df.mul vs df.rmul | 38,857,004 | <p>Can anybody help me understand the difference (if any) between the two methods: <code>df.mul</code> and <code>df.rmul</code>? The documentation looks identical:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html#pandas.DataFrame.mul">http://pandas.pydata.org/pandas-docs/... | 5 | 2016-08-09T17:25:43Z | 38,857,643 | <p>From the code:</p>
<pre><code># not entirely sure why this is necessary, but previously was included
# so it's here to maintain compatibility
rmul=arith_method(operator.mul, names('rmul'), op('*'),
default_axis=default_axis, reversed=True),
</code></pre>
<p>Analogous lines for <code>mul</code></p... | 2 | 2016-08-09T18:06:59Z | [
"python",
"pandas"
] |
Pandas: df.mul vs df.rmul | 38,857,004 | <p>Can anybody help me understand the difference (if any) between the two methods: <code>df.mul</code> and <code>df.rmul</code>? The documentation looks identical:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html#pandas.DataFrame.mul">http://pandas.pydata.org/pandas-docs/... | 5 | 2016-08-09T17:25:43Z | 38,857,747 | <p>The documentation is not identical. As stated in the documentation, <code>df.mul(other)</code> is equivalent to <code>df * other</code>, while <code>df.rmul(other)</code> is equivalent to <code>other * df</code>.</p>
<p>This probably doesn't matter for most cases, but it will matter if, e.g., you have a dataframe o... | 3 | 2016-08-09T18:13:35Z | [
"python",
"pandas"
] |
Pythonic way to replace every second comma of string with space | 38,857,048 | <p>I have a string which looks like this:</p>
<pre><code>coords = "86.2646484375,23.039297747769726,87.34130859375,22.59372606392931,88.13232421875,24.066528197726857"
</code></pre>
<p>What I want is to bring it to this format:</p>
<pre><code>coords = "86.2646484375,23.039297747769726 87.34130859375,22.5937260639293... | 3 | 2016-08-09T17:28:08Z | 38,857,104 | <p>This sort of works:</p>
<pre><code>>>> s = coords.split(',')
>>> s
['86.2646484375', '23.039297747769726', '87.34130859375', '22.59372606392931', '88.13232421875', '24.066528197726857']
>>> [','.join(i) for i in zip(s[::2], s[1::2])]
['86.2646484375,23.039297747769726', '87.34130859375,22... | 2 | 2016-08-09T17:31:56Z | [
"python"
] |
Pythonic way to replace every second comma of string with space | 38,857,048 | <p>I have a string which looks like this:</p>
<pre><code>coords = "86.2646484375,23.039297747769726,87.34130859375,22.59372606392931,88.13232421875,24.066528197726857"
</code></pre>
<p>What I want is to bring it to this format:</p>
<pre><code>coords = "86.2646484375,23.039297747769726 87.34130859375,22.5937260639293... | 3 | 2016-08-09T17:28:08Z | 38,857,120 | <p>First let's import the regular expression module and define your <code>coords</code> variable:</p>
<pre><code>>>> import re
>>> coords = "86.2646484375,23.039297747769726,87.34130859375,22.59372606392931,88.13232421875,24.066528197726857"
</code></pre>
<p>Now, let's replace every second comma wit... | 12 | 2016-08-09T17:32:37Z | [
"python"
] |
Pythonic way to replace every second comma of string with space | 38,857,048 | <p>I have a string which looks like this:</p>
<pre><code>coords = "86.2646484375,23.039297747769726,87.34130859375,22.59372606392931,88.13232421875,24.066528197726857"
</code></pre>
<p>What I want is to bring it to this format:</p>
<pre><code>coords = "86.2646484375,23.039297747769726 87.34130859375,22.5937260639293... | 3 | 2016-08-09T17:28:08Z | 38,857,321 | <p>The pythonic way is to split the string and join it again, with the alternating delimiters:</p>
<pre><code>from itertools import chain, cycle, izip
coords = ''.join(chain.from_iterable(izip(coords.split(','), cycle(', '))))
</code></pre>
| 1 | 2016-08-09T17:47:23Z | [
"python"
] |
Identify Django User table based on content_type and field name links | 38,857,096 | <p>I've writing an app for managing subscriptions, for example annual club membership. There are different catergories of membership and these categories can have admin specified criteria which could relate to any table in the database. The only requirement is there must be a link back to the Django User table.</p>
<p... | 1 | 2016-08-09T17:30:57Z | 38,866,989 | <p>For validation purposes I've got the solution below, which replaces the main <code>else</code> clause in <code>def clean</code>.</p>
<pre><code> else:
s = apps.get_model(self.content_type.app_label, self.content_type.model)
if not hasattr(s, self.user_link):
raise ValidationError(
... | 1 | 2016-08-10T07:35:18Z | [
"python",
"django",
"django-contenttypes"
] |
How can I evaluate a value in a Python generator at the time I create the generator, not at the time I iterate it? | 38,857,108 | <p>The following is my code:</p>
<pre><code>import itertools
i = itertools.chain()
for a in [1, 2, 3]:
i = itertools.chain(i, (a for _ in range(2)))
print(list(i))
[3, 3, 3, 3, 3, 3]
</code></pre>
<p>Is there a way I can access the value of <code>a</code> when creating the generator, rather than when I iterate ... | 1 | 2016-08-09T17:32:15Z | 38,857,573 | <p>One way would be to restructure your code to use a two-<code>for</code> genexp, so that <code>id</code> has the right value when it's needed:</p>
<pre><code>InnerModel.objects.bulk_create(
InnerModel(fk=id) for id in ParentModel.objects.all().value_list('id', flat=True)
for i in range(10000))
</code... | 2 | 2016-08-09T18:03:23Z | [
"python",
"django",
"generator"
] |
How can I evaluate a value in a Python generator at the time I create the generator, not at the time I iterate it? | 38,857,108 | <p>The following is my code:</p>
<pre><code>import itertools
i = itertools.chain()
for a in [1, 2, 3]:
i = itertools.chain(i, (a for _ in range(2)))
print(list(i))
[3, 3, 3, 3, 3, 3]
</code></pre>
<p>Is there a way I can access the value of <code>a</code> when creating the generator, rather than when I iterate ... | 1 | 2016-08-09T17:32:15Z | 38,857,662 | <p>If you don't mind wrapping the tuple into a lambda:</p>
<pre><code>>>> import itertools
>>> i = itertools.chain()
>>> for a in [1, 2, 3]:
>>> i = itertools.chain(i, (lambda x: (x for _ in range(2)))(a))
>>> print(list(i))
[1, 1, 2, 2, 3, 3]
</code></pre>
<p>The idea... | 1 | 2016-08-09T18:08:00Z | [
"python",
"django",
"generator"
] |
Capture the numbers in this regex | 38,857,270 | <p>I have a string like this:</p>
<pre><code>{{1090872, "A"}, {4281, "AA"}, {1332552, "AAACU"}, {1287145, "AABB"}}
</code></pre>
<p>How can I write a regex to capture the numbers. I know that I can capture the letters with: "(.*?)"</p>
| 3 | 2016-08-09T17:43:32Z | 38,857,346 | <p>If you don't have number in quotes, then answer is</p>
<pre class="lang-py prettyprint-override"><code>import re
str = '{{1090872, "A"}, {4281, "AA"}, {1332552, "AAACU"}, {1287145, "AABB"}}'
re.findall(r'\d+', str)
['1090872', '4281', '1332552', '1287145']
</code></pre>
<p>otherwise you can try</p>
<pre class="la... | 2 | 2016-08-09T17:49:10Z | [
"python",
"regex"
] |
How to sort rows in pandas with a non-standard order | 38,857,311 | <p>I have a pandas dataframe, say:</p>
<pre><code>df = pd.DataFrame ([['a', 3, 3], ['b', 2, 5], ['c', 4, 9], ['d', 1, 43]], columns = ['col 1' , 'col2', 'col 3'])
</code></pre>
<p>or:</p>
<pre><code> col 1 col2 col 3
0 a 3 3
1 b 2 5
2 c 4 9
3 d 1 43
</code></pre>... | 3 | 2016-08-09T17:46:50Z | 38,857,529 | <p>One way is to convert that column to a <code>Categorical</code> type, which can have an arbitrary ordering.</p>
<pre><code>In [51]: df['col2'] = df['col2'].astype('category', categories=[4, 1, 2, 3], ordered=True)
In [52]: df.sort_values('col2')
Out[52]:
col 1 col2 col 3
2 c 4 9
3 d 1 43... | 3 | 2016-08-09T18:00:23Z | [
"python",
"sorting",
"pandas"
] |
How to sort rows in pandas with a non-standard order | 38,857,311 | <p>I have a pandas dataframe, say:</p>
<pre><code>df = pd.DataFrame ([['a', 3, 3], ['b', 2, 5], ['c', 4, 9], ['d', 1, 43]], columns = ['col 1' , 'col2', 'col 3'])
</code></pre>
<p>or:</p>
<pre><code> col 1 col2 col 3
0 a 3 3
1 b 2 5
2 c 4 9
3 d 1 43
</code></pre>... | 3 | 2016-08-09T17:46:50Z | 38,857,613 | <p>Try this:</p>
<pre><code>sortMap = {4:1, 2:2, 1:3,3:4 }
df["new"] = df2['col2'].map(sortMap)
df.sort_values('new', inplace=True)
df
col1 col2 col3 new
2 c 4 9 1
1 b 2 5 2
3 d 1 43 3
0 a 3 3 4
</code></pre>
<p>alt method to create dict: </p>
<pre><code>... | 3 | 2016-08-09T18:05:21Z | [
"python",
"sorting",
"pandas"
] |
How to sort rows in pandas with a non-standard order | 38,857,311 | <p>I have a pandas dataframe, say:</p>
<pre><code>df = pd.DataFrame ([['a', 3, 3], ['b', 2, 5], ['c', 4, 9], ['d', 1, 43]], columns = ['col 1' , 'col2', 'col 3'])
</code></pre>
<p>or:</p>
<pre><code> col 1 col2 col 3
0 a 3 3
1 b 2 5
2 c 4 9
3 d 1 43
</code></pre>... | 3 | 2016-08-09T17:46:50Z | 38,857,621 | <p>alternative solution:</p>
<pre><code>In [409]: lst = [4, 2, 1, 3]
In [410]: srt = pd.Series(np.arange(len(lst)), index=lst)
In [411]: srt
Out[411]:
4 0
2 1
1 2
3 3
dtype: int32
In [412]: df.assign(x=df.col2.map(srt))
Out[412]:
col 1 col2 col 3 x
0 a 3 3 3
1 b 2 5 1
2 ... | 1 | 2016-08-09T18:05:43Z | [
"python",
"sorting",
"pandas"
] |
Stopping processes in ThreadPool in Python | 38,857,379 | <p>I've been trying to write an interactive wrapper (for use in ipython) for a library that controls some hardware. Some calls are heavy on the IO so it makes sense to carry out the tasks in parallel. Using a ThreadPool (almost) works nicely:</p>
<pre><code>from multiprocessing.pool import ThreadPool
class hardware(... | 5 | 2016-08-09T17:51:03Z | 38,861,184 | <p>This is a very interesting use of parallelism. </p>
<p>However, if you are using <code>multiprocessing</code>, the goal is to have many processes running in parallel, as opposed to one process running many threads. </p>
<p>Consider these few changes to implement it using <code>multiprocessing</code>:</p>
<p>You h... | 1 | 2016-08-09T22:06:14Z | [
"python",
"threadpool"
] |
Stopping processes in ThreadPool in Python | 38,857,379 | <p>I've been trying to write an interactive wrapper (for use in ipython) for a library that controls some hardware. Some calls are heavy on the IO so it makes sense to carry out the tasks in parallel. Using a ThreadPool (almost) works nicely:</p>
<pre><code>from multiprocessing.pool import ThreadPool
class hardware(... | 5 | 2016-08-09T17:51:03Z | 38,921,883 | <p>In answer to the question of why pool did not work then this is due to (as quoted in the <a href="https://docs.python.org/3.1/library/multiprocessing.html" rel="nofollow">Documentation</a>) then <strong>main</strong> needs to be importable by the child processes and due to the nature of this project interactive pyth... | 0 | 2016-08-12T15:46:35Z | [
"python",
"threadpool"
] |
How to get only one list in python? | 38,857,433 | <p>i need little help about some lists, so i have this part of code:</p>
<pre class="lang-py prettyprint-override"><code>get_attributeName = \
soup.find(True, {"class": ["product-attributes", "product-attribute-value"]}).find_all('li')
allDataList = []
for attData, attValues in get_attributeName:
data... | 0 | 2016-08-09T17:55:09Z | 38,857,474 | <p>Your code is <em>printing</em> the list each iteration, as you build it. Simply don't print each iteration; print only <em>after</em> the <code>for</code> loop has completed (if at all).</p>
<pre><code>get_attributeName = soup.find(True,{"class": ["product-attributes", "product-attribute-value"]}).find_all('li')
a... | 2 | 2016-08-09T17:56:59Z | [
"python",
"list"
] |
AttributeError: 'module' object has no attribute 'Screen' and indentation error | 38,857,435 | <p>I'm learning Turtle class for Python. While running <code>shp.py</code> file in terminal I got multiple errors:</p>
<p><a href="http://i.stack.imgur.com/GuYq8.png" rel="nofollow"><img src="http://i.stack.imgur.com/GuYq8.png" alt="enter image description here"></a></p>
<p>What is going wrong?</p>
<pre><code>import... | -1 | 2016-08-09T17:55:14Z | 38,857,575 | <p>Currently, your script is importing itself. A simple change to the file name can fix this. </p>
<pre><code>Go to My Documents -> Locate your file -> Right click on it -> Click Rename -> Enter a new name like myTurtle.py
</code></pre>
| 0 | 2016-08-09T18:03:25Z | [
"python",
"terminal",
"turtle-graphics"
] |
NameError: name '[string]' is not defined | 38,857,541 | <p>When testing my program, I keep getting this error:</p>
<pre><code>1. Encrypt a file
2. Decrypt a file
----> 1
Enter the filename you'd like to encrypt: test
Traceback (most recent call last):
File "./encrypt.py", line 71, in <module>
Main()
File "./encrypt.py", line 58, in Main
filename = inpu... | 0 | 2016-08-09T18:01:03Z | 38,857,602 | <blockquote>
<p>it keeps telling me whatever information I enter in at runtime, the name of what I just entered is not defined. I don't see any formatting errors, syntax errors, etc.</p>
</blockquote>
<p>You are probably using Python 2.x. You should use: <code>raw_input(..)</code> instead of <code>input(..)</code></... | 0 | 2016-08-09T18:05:03Z | [
"python"
] |
NameError: name '[string]' is not defined | 38,857,541 | <p>When testing my program, I keep getting this error:</p>
<pre><code>1. Encrypt a file
2. Decrypt a file
----> 1
Enter the filename you'd like to encrypt: test
Traceback (most recent call last):
File "./encrypt.py", line 71, in <module>
Main()
File "./encrypt.py", line 58, in Main
filename = inpu... | 0 | 2016-08-09T18:01:03Z | 38,857,609 | <p>You're going to want to use <code>raw_input()</code> instead of <code>input()</code>. <code>input</code> tries to run the expression it gets as a Python expression, whereas <code>raw_input</code> returns a string. This is in Python 2.x; in 3.x <code>raw_input</code> doesn't exist.</p>
<p>When you get the <code>Name... | 1 | 2016-08-09T18:05:15Z | [
"python"
] |
NameError: name '[string]' is not defined | 38,857,541 | <p>When testing my program, I keep getting this error:</p>
<pre><code>1. Encrypt a file
2. Decrypt a file
----> 1
Enter the filename you'd like to encrypt: test
Traceback (most recent call last):
File "./encrypt.py", line 71, in <module>
Main()
File "./encrypt.py", line 58, in Main
filename = inpu... | 0 | 2016-08-09T18:01:03Z | 38,857,632 | <p>The <code>input</code> function treats whatever you input as a python expression. What you're looking for is the <code>raw_input</code> function which treats your input as a string.
Switch all your <code>input</code>s for <code>raw_input</code>s and you should be fine.</p>
| 0 | 2016-08-09T18:06:24Z | [
"python"
] |
NameError: name '[string]' is not defined | 38,857,541 | <p>When testing my program, I keep getting this error:</p>
<pre><code>1. Encrypt a file
2. Decrypt a file
----> 1
Enter the filename you'd like to encrypt: test
Traceback (most recent call last):
File "./encrypt.py", line 71, in <module>
Main()
File "./encrypt.py", line 58, in Main
filename = inpu... | 0 | 2016-08-09T18:01:03Z | 38,857,906 | <p>It turns out my linux distro has both python 2.7.12 and python 3.5.2. Apparently the system defaults to python 2.7.12 instead of the newer version, so I fixed it by changing:</p>
<pre><code>#!/usr/bin/python
</code></pre>
<p>to:</p>
<pre><code>#!/usr/bin/python3
</code></pre>
| 0 | 2016-08-09T18:25:03Z | [
"python"
] |
assigning hashtags to django models | 38,857,778 | <p>I have defined Job model in my django website as shown here:</p>
<pre><code>class Job(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.title
</code></pre>
<p>Skills required by a job:</p>
<pre><code>class SkillsGroup(model... | 0 | 2016-08-09T18:15:34Z | 38,857,860 | <p>It sounds like you want <code>Skill</code> to be a <code>ForiegnKey</code> to <code>Job</code>.</p>
| -1 | 2016-08-09T18:21:23Z | [
"python",
"django"
] |
assigning hashtags to django models | 38,857,778 | <p>I have defined Job model in my django website as shown here:</p>
<pre><code>class Job(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.title
</code></pre>
<p>Skills required by a job:</p>
<pre><code>class SkillsGroup(model... | 0 | 2016-08-09T18:15:34Z | 38,858,079 | <p>perhaps you will want to take a look for this django app:
<a href="http://django-tagging.readthedocs.io/" rel="nofollow">django-tagging</a></p>
| -1 | 2016-08-09T18:36:00Z | [
"python",
"django"
] |
assigning hashtags to django models | 38,857,778 | <p>I have defined Job model in my django website as shown here:</p>
<pre><code>class Job(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.title
</code></pre>
<p>Skills required by a job:</p>
<pre><code>class SkillsGroup(model... | 0 | 2016-08-09T18:15:34Z | 38,863,648 | <p>You need ManyToManyField. I will simplify a bit your example.</p>
<pre><code>class Job(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
skills = models.ManyToManyField(Skill)
def __str__(self):
return self.title
class Skill(models.Model):
nam... | 0 | 2016-08-10T03:12:52Z | [
"python",
"django"
] |
Getting a Tic Tac Toe move from a button click (in Python with Tkinter) | 38,857,811 | <p>I'm trying to write a Tic Tac Toe program with a simple GUI using Tkinter. Here is the result so far:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import Tkinter as tk
class Game:
def __init__(self, player1, player2, with_GUI=False):
self.player1 = player1
self.player2 = pl... | 0 | 2016-08-09T18:17:59Z | 38,868,972 | <p>To get the Button itself, do not use a lambda binding.</p>
<p>Use the default bindings and use the event object.</p>
<p>Using this approach you do not need to pass row, col at creation time.</p>
<pre><code>import Tkinter as tk
class someclass(tk.Frame):
def __init__(self, *args, **kwargs):
# the ini... | -1 | 2016-08-10T09:12:35Z | [
"python",
"tkinter"
] |
Remove the last empty line in CSV file | 38,857,870 | <pre><code>nf=open(Output_File,'w+')
with open(Input_File,'read') as f:
for row in f:
Current_line = str(row)
Reformated_line=str(','.join(Current_line.split('|')[1:-1]))
nf.write(Reformated_line+ "\n")
</code></pre>
<p>I'm trying to read <code>Input file</code> which is in Table Format and... | 1 | 2016-08-09T18:22:20Z | 38,857,965 | <p>Just a question of reordering things a little:</p>
<pre><code>first = True
with open(Input_File,'read') as f, open(Output_File,'w+') as nf:
for row in f:
Current_line = str(row)
Reformated_line=str(','.join(Current_line.split('|')[1:-1]))
if not first:
nf.write('\n')
... | 0 | 2016-08-09T18:29:04Z | [
"python",
"csv"
] |
Remove the last empty line in CSV file | 38,857,870 | <pre><code>nf=open(Output_File,'w+')
with open(Input_File,'read') as f:
for row in f:
Current_line = str(row)
Reformated_line=str(','.join(Current_line.split('|')[1:-1]))
nf.write(Reformated_line+ "\n")
</code></pre>
<p>I'm trying to read <code>Input file</code> which is in Table Format and... | 1 | 2016-08-09T18:22:20Z | 38,858,214 | <p>It sounds like you have an empty line in your input file. From your comments, you actually have a non-empty line that has no <code>|</code> characters in it. In either case, it is easy enough to check for an empty result line.</p>
<p>Try this:</p>
<pre><code>#UNTESTED
nf=open(Output_File,'w+')
with open(Input_File... | 1 | 2016-08-09T18:44:23Z | [
"python",
"csv"
] |
How to catch requests.get() exceptions | 38,857,883 | <p>I'm working on a web scraper for yellowpages.com, which seems to be working well overall. However, while iterating through the pagination of a long query, requests.get(url) will randomly return <code><Response [503]></code> or <code><Response [404]></code>. Occassionally, I will receive worse exceptions... | 0 | 2016-08-09T18:22:54Z | 38,857,939 | <p>What about something like this</p>
<pre><code>try:
req = ..
if req.status_code == 503:
pass
elif ..:
pass
else:
do something when request succeeds
except ConnectionError:
pass
</code></pre>
| 0 | 2016-08-09T18:27:19Z | [
"python",
"exception-handling",
"web-scraping",
"python-requests",
"yellow-pages"
] |
Python - parsing configuration file - flow control | 38,857,898 | <p>I am trying to write a python 2.7 script to parse through a configuration file. The configuration file has standard settings but not all settings are populated. I've been able to extract the values for a single section, but when I added additional entries my script logic fails. I am thinking I could use the attri... | 0 | 2016-08-09T18:24:46Z | 38,858,480 | <p>This looks like a dictionary to me.</p>
<pre><code>optionsdict = dict()
curkey = None
for line in optionsfile:
if line.strip().startswith("RuleName"):
curkey = line.split("=")[1].strip() # whatever's after the =
elif line.strip() == "Next":
pass # not sure what you're doing with the Next ... | 0 | 2016-08-09T18:59:52Z | [
"python",
"python-2.7"
] |
pandas to_json - return timestamp with units of days rather than seconds | 38,857,941 | <p>I have a pandas series containing datetime objects which have been created from day-month-year strings</p>
<pre><code>series = pd.Series(['3/11/2000', '3/12/2000', '3/13/2000'])
series = pd.to_datetime(series)
print series
0 2000-03-11
1 2000-03-12
2 2000-03-13
dtype: datetime64[ns]
</code></pre>
<p>Later, ... | 4 | 2016-08-09T18:27:41Z | 38,858,104 | <p>This is not elegant but you can try convert to string before to json:</p>
<pre><code>>>> series.apply(lambda x : x.strftime('%Y-%m-%d')).to_json()
'{"0":"2000-03-11","1":"2000-03-12","2":"2000-03-13"}'
</code></pre>
| 3 | 2016-08-09T18:37:30Z | [
"python",
"date",
"datetime",
"pandas"
] |
pandas to_json - return timestamp with units of days rather than seconds | 38,857,941 | <p>I have a pandas series containing datetime objects which have been created from day-month-year strings</p>
<pre><code>series = pd.Series(['3/11/2000', '3/12/2000', '3/13/2000'])
series = pd.to_datetime(series)
print series
0 2000-03-11
1 2000-03-12
2 2000-03-13
dtype: datetime64[ns]
</code></pre>
<p>Later, ... | 4 | 2016-08-09T18:27:41Z | 38,858,132 | <p>Something like this?</p>
<pre><code>In [64]: series.dt.date.astype(str).to_json()
Out[64]: '{"0":"2000-03-11","1":"2000-03-12","2":"2000-03-13"}'
</code></pre>
| 5 | 2016-08-09T18:38:55Z | [
"python",
"date",
"datetime",
"pandas"
] |
Add values to array in one line | 38,857,966 | <p>How can I write this code in one-line?</p>
<pre><code>aa = []
for s in complete:
aa.append(s)
</code></pre>
<p>I know there are several solutions. I would really appreciate if you could write them down.
Thanks! </p>
| 2 | 2016-08-09T18:29:05Z | 38,857,997 | <p>List comprehensions are awesome:</p>
<pre><code>aa = [s for s in complete]
</code></pre>
| 1 | 2016-08-09T18:30:55Z | [
"python"
] |
Add values to array in one line | 38,857,966 | <p>How can I write this code in one-line?</p>
<pre><code>aa = []
for s in complete:
aa.append(s)
</code></pre>
<p>I know there are several solutions. I would really appreciate if you could write them down.
Thanks! </p>
| 2 | 2016-08-09T18:29:05Z | 38,858,003 | <p>like this (be care with strings):</p>
<pre><code>aa.extend(complete)
</code></pre>
<p>or with list comprehension:</p>
<pre><code>aa = list(s for s in complete)
</code></pre>
<p>or if u want to copy list u can do follow:</p>
<pre><code>aa = complete[:]
aa = complete.copy() # same
aa = list(complete) # same
</cod... | 2 | 2016-08-09T18:31:18Z | [
"python"
] |
Add values to array in one line | 38,857,966 | <p>How can I write this code in one-line?</p>
<pre><code>aa = []
for s in complete:
aa.append(s)
</code></pre>
<p>I know there are several solutions. I would really appreciate if you could write them down.
Thanks! </p>
| 2 | 2016-08-09T18:29:05Z | 38,858,043 | <p>As long as you just need to set <code>aa</code> equal to <code>complete</code>, just use</p>
<p><code>aa = complete</code></p>
| 2 | 2016-08-09T18:33:27Z | [
"python"
] |
Add values to array in one line | 38,857,966 | <p>How can I write this code in one-line?</p>
<pre><code>aa = []
for s in complete:
aa.append(s)
</code></pre>
<p>I know there are several solutions. I would really appreciate if you could write them down.
Thanks! </p>
| 2 | 2016-08-09T18:29:05Z | 38,858,050 | <p>If you want to add values to array in one line, it depends how the values are given. If you have another <code>list</code>, you can also use extend:</p>
<pre><code>my_list = []
my_list.extend([1,2,3,4])
</code></pre>
| 0 | 2016-08-09T18:33:39Z | [
"python"
] |
Add values to array in one line | 38,857,966 | <p>How can I write this code in one-line?</p>
<pre><code>aa = []
for s in complete:
aa.append(s)
</code></pre>
<p>I know there are several solutions. I would really appreciate if you could write them down.
Thanks! </p>
| 2 | 2016-08-09T18:29:05Z | 38,858,080 | <p>To extend <code>aa</code>, use the <code>extend()</code> function:</p>
<pre><code>aa.extend(s for s in complete)
</code></pre>
<p>or </p>
<pre><code>aa.extend(complete)
</code></pre>
<p>If you simply wanted to equate the two, a simple <code>=</code> is fine:</p>
<pre><code>aa = complete
</code></pre>
| 0 | 2016-08-09T18:36:00Z | [
"python"
] |
Add values to array in one line | 38,857,966 | <p>How can I write this code in one-line?</p>
<pre><code>aa = []
for s in complete:
aa.append(s)
</code></pre>
<p>I know there are several solutions. I would really appreciate if you could write them down.
Thanks! </p>
| 2 | 2016-08-09T18:29:05Z | 38,858,099 | <p>I like to do such things with a list comprehension:</p>
<pre><code>aa = [s for s in complete]
</code></pre>
<p>Though, depending on the type of <code>complete</code>, and whether or not you want to use package like numpy there may be a faster way, such as</p>
<pre><code>import numpy as np
aa = np.array(complete)
... | 0 | 2016-08-09T18:36:58Z | [
"python"
] |
How to Bind and Send from Google Cloud Forwarding Rule IP Address? | 38,858,086 | <p>I've followed the instructions for <a href="https://cloud.google.com/compute/docs/protocol-forwarding/">Using Protocol Forwarding</a> on the Google Cloud Platform. So I now have something like this:</p>
<pre><code>$ gcloud compute forwarding-rules list
NAME REGION IP_ADDRESS IP_PROTOCOL TARGET
x-fr-1 u... | 11 | 2016-08-09T18:36:20Z | 38,973,628 | <ol>
<li>it's not in the local routing table ('ip route show table local')
[ you could of course add it (e.g. 'ip address add x.x.x.x/32 dev ens4'),
but doing so wouldn't do you much good, since no packets will be
delivered to your VM using that as the destination address - see
below... ]</li>
<li>because the forwarded... | 4 | 2016-08-16T11:23:43Z | [
"python",
"networking",
"google-compute-engine",
"google-cloud-platform"
] |
Python asyncio performance on OS X vs Ubuntu | 38,858,144 | <p>I have some issues with Python asyncio performance on OS X. I have Macbook pro 2015 with 16gb RAM. But can't get the same performance on OS X (El Capitan) as on Ubuntu. Even given the fact that I am running Ubuntu inside VM (vagrant, 4gb RAM) with OS X host.</p>
<p>OS X benchmark with wrk:
<code>
wrk -t8 -d 10s -c ... | 1 | 2016-08-09T18:39:49Z | 38,866,429 | <p>MacOSX has slower network stack implementation that linux, it's well known fact.</p>
<p>I don't know why Arch Linux is slower than Ubuntu on your machine. Network stack is implemented by linux kernel itself, linux distros with the same kernel version should display almost the same performance. </p>
| 0 | 2016-08-10T07:06:36Z | [
"python",
"osx",
"ubuntu",
"tcp",
"python-asyncio"
] |
Pandas - Sort by group membership numbers | 38,858,177 | <p>When faced with large numbers of groups, any graph you might make is apt to be useless due to having too many lines and an unreadable legend. In these cases, being able to find the groups that have the most and least information in them is very useful. However, while <code>x.size()</code> tells you the group members... | 3 | 2016-08-09T18:42:13Z | 38,858,324 | <p>You can use <code>transform</code> to get the counts and sort on that column:</p>
<pre><code>df = pd.DataFrame({'A': list('aabababc'), 'B': np.arange(8)})
df
Out:
A B
0 a 0
1 a 1
2 b 2
3 a 3
4 b 4
5 a 5
6 b 6
7 c 7
</code></pre>
<hr>
<pre><code>df['counts'] = df.groupby('A').transform('count'... | 3 | 2016-08-09T18:51:16Z | [
"python",
"pandas"
] |
Is there a way to use python 2.x and 3.x in same virtualenv? | 38,858,195 | <p>I want to use jupyter with both the versioned kernel of python in a virtualenv. How can I do that?</p>
| 0 | 2016-08-09T18:43:01Z | 38,859,614 | <p>you can use <code>tox</code> to setup multiple virtualenvs instead ... that would generally be the standard solution</p>
| -2 | 2016-08-09T20:12:48Z | [
"python",
"virtualenv",
"jupyter"
] |
Regular expression (Python) - match MAC address | 38,858,244 | <p>I have this text (from ipconfig /all)</p>
<pre><code>Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Atheros AR8151 PCI-E Gigabit Ethernet Controller (NDIS 6.20)
Physical Address. . . . . . . . . : 50-E5-49-CE-FC-EF
DHCP Enabl... | 1 | 2016-08-09T18:45:55Z | 38,858,490 | <p>You get the non-<code>-</code> symbols on both sides because the negated character class <code>[^-]</code> matches and consumes the characters. To avoid getting these characters in the match value, you can use lookarounds:</p>
<pre><code>p = re.compile(r'(?<!-)(?:[0-9a-f]{2}[:-]){5}[0-9a-f]{2}(?!-)', re.IGNOREC... | 1 | 2016-08-09T19:00:25Z | [
"python",
"regex",
"mac-address",
"regular-language"
] |
Remote shell using python | 38,858,259 | <p>I want to do a simple remote shell. I have used sockets to comunicate and it works, in LAN. Now my friend is trying to connect to my server script from his client but he cannot do it.
I have opened port 4333 public and associated it to 10001 private in my router.</p>
<p>By the way I've replaced the IP with XX.</p>
... | 0 | 2016-08-09T18:47:21Z | 38,858,563 | <p>What is the value of <code>direc</code>? It should be a connectable IP address for your server to work, i.e. <code>127.0.0.1</code> doesn't work for your friends, even they are under same LAN with your machine.</p>
<p><code>sock.bind()</code> means that the socket will only listen connections to <code>direc</code>:... | 0 | 2016-08-09T19:05:10Z | [
"python",
"linux",
"shell",
"sockets",
"remote-access"
] |
JSON to DataFrames in Python3.X | 38,858,261 | <p>I have a JSON data as below in list. Each line is a independent dictionary</p>
<pre class="lang-py prettyprint-override"><code>["{'asin': '0001048791', 'salesRank': {'Books': 6334800}, 'imUrl': 'http://ecx.images-amazon.com/images/I/51MKP0T4DBL.jpg', 'categories': [['Books']], 'title': 'The Crucible: Performed by S... | 0 | 2016-08-09T18:47:33Z | 38,868,751 | <h2>Your Data is not JSON </h2>
<p>OK - There are several issues with what you are attempting to do. First, just copying and pasting your list into an interactive interpreter session:</p>
<pre><code>>>> data = ["{'asin': '0001048791', 'salesRank': {'Books': 6334800}, 'imUrl': 'http://ecx.images-amazon.com/im... | 0 | 2016-08-10T09:03:19Z | [
"python",
"python-3.x",
"pandas",
"dataframe"
] |
How can I search for a specific string that varies by a single character in beautiful soup python? | 38,858,276 | <p>I want to search for all variations of a string that is completely the same other than a single character. Here is an example of the string:</p>
<p>AccordionPanelTab cond1_left
AccordionPanelTab cond2_left
AccordionPanelTab cond3_left</p>
<p>I would normally just iterate through a for loop however this string is t... | 1 | 2016-08-09T18:49:06Z | 38,859,179 | <p>As per my understanding, you needed a list of all the strings that needs to match your conditions.You can use regular expression for that. </p>
<p><a href="https://docs.python.org/3/library/re.html#re.findall" rel="nofollow">re.findall(pattern, string)</a> returns a list of matching strings.</p>
<p>You can do that... | -1 | 2016-08-09T19:43:09Z | [
"python",
"beautifulsoup"
] |
Reference instance method outside class definition | 38,858,279 | <p>I'm trying to pass a method as an argument outside of the definition of a class. However, since it's not defined in that scope, it doesn't work. Here's what I'd like to do:</p>
<pre><code>def applyMethod(obj, method):
obj.method()
class MyClass():
def myMethod(self):
print 1
a = MyClass()
#wo... | 2 | 2016-08-09T18:49:13Z | 38,858,367 | <p>myMethod is only defined in the namespace of MyClass. Your code could look like this:</p>
<pre><code>def applyMethod(obj, method):
method(obj)
class MyClass():
def myMethod(self):
print 1
a = MyClass()
a.myMethod()
applyMethod(a, MyClass.myMethod)
</code></pre>
<p>Now you're referencing <co... | 2 | 2016-08-09T18:53:27Z | [
"python",
"function",
"methods",
"parameter-passing"
] |
Reading the files from a log file list | 38,858,317 | <p>I have the following log file called <code>log.txt</code>, with all the file names to be considered from a folder:</p>
<pre><code>log.txt
C:\data\01.log
C:\data\02.log
C:\data\03.log
C:\data\04.log
</code></pre>
<p>My task is to read these files one after another from log.txt using a for loop.</p>
<pre><code>... | -1 | 2016-08-09T18:50:57Z | 38,860,543 | <p>What is the error you are getting? </p>
<p>Is it "IOError: [Errno 2] No such file or directory:"? </p>
<p>This error means that the directory C:\data\ does not exist. Are you sure this folder exists? Also if it does exist, is the logs.txt file in that directory? </p>
<p>I personally do not have a C:\data director... | 0 | 2016-08-09T21:14:42Z | [
"python",
"file-io"
] |
Python Client to nodeJS Server with Socket.IO | 38,858,352 | <p>I'm trying to send values from my raspberry pi (in python 2.7.9) to my nodeJS server with socket.io.</p>
<p>My goal ist send many values continuously from my pi over a websocket connection to my node Server (local), which should take the values and show it on the index.html (for other clients, like a Web-Chat where... | 0 | 2016-08-09T18:52:24Z | 38,858,405 | <p>Socket.io communications aren't plain websockets. You probably need an implementation of the socket.io client on python, to make sure that the messages you are sending are compatible with the socket.io protocol. Something like <a href="https://pypi.python.org/pypi/socketIO-client" rel="nofollow">socketIO-client</a>,... | 0 | 2016-08-09T18:55:35Z | [
"python",
"node.js",
"websocket",
"socket.io"
] |
How to count values in a certain range in a Numpy array? (Does not work) | 38,858,363 | <p>I have already checked this thread <a href="http://stackoverflow.com/questions/9560207/how-to-count-values-in-a-certain-range-in-a-numpy-array">How to count values in a certain range in a Numpy array?</a> but their answer does not seem to work.</p>
<p>I have a numpy array of 2000 floats called data:</p>
<pre><cod... | -1 | 2016-08-09T18:53:10Z | 38,858,460 | <p>It seems that <code>data</code> is not an array. Please check it. The suggested solution does work with arrays. Perhaps at some point <code>data</code> became a number or something.</p>
| 0 | 2016-08-09T18:59:09Z | [
"python",
"arrays",
"numpy"
] |
How to count values in a certain range in a Numpy array? (Does not work) | 38,858,363 | <p>I have already checked this thread <a href="http://stackoverflow.com/questions/9560207/how-to-count-values-in-a-certain-range-in-a-numpy-array">How to count values in a certain range in a Numpy array?</a> but their answer does not seem to work.</p>
<p>I have a numpy array of 2000 floats called data:</p>
<pre><cod... | -1 | 2016-08-09T18:53:10Z | 38,858,610 | <p>I suspect you are using python 2 because comparing a list and a number doesn't raise a <code>TypeError</code> in your case. </p>
<p>But in order to use element-wise comparison (<code><</code>, <code>></code>, <code>&</code>) you need to convert your list to a numpy array:</p>
<pre><code>import numpy as n... | 1 | 2016-08-09T19:07:49Z | [
"python",
"arrays",
"numpy"
] |
AttributeError: 'Cycler' object has no attribute 'change_key' | 38,858,407 | <p>I'm trying to <code>import matplotlib</code> on Ubuntu. I reinstalled matplotlib from source because i couldn't use the <code>TkAgg</code> backend. Now I'm facing a new problem which I cannot solve and also can't find the solution anywhere. I'm using Python 3.5.
I have this error showing me when i run a simple impor... | -1 | 2016-08-09T18:55:37Z | 38,858,585 | <p>Just checked the version of cycler and it was outdated. Just update cycler with</p>
<p><code>sudo python3 pip install --upgrade cycler</code>.</p>
| 0 | 2016-08-09T19:06:28Z | [
"python",
"python-3.x",
"matplotlib"
] |
Scraping a website with BeautifulSoup | 38,858,466 | <p>I'm trying to scrape a website with BeautifulSoup. More specifically I'm trying to get the string from a following tag:</p>
<pre><code><td class="Fz(s) Fw(500) Ta(end)" data-reactid=".17c0h26fqwq.1.$0.0.0.3.1.$main-0-Quote-Proxy.$main 0-Quote.2.0.0.0.1.0.0:$VALUATION_MEASURES.0.1.0.$MARKET_CAP_INTRADAY.1">4.3... | 1 | 2016-08-09T18:59:33Z | 38,859,825 | <p>So this is additional code that I wrote, now I can nicely save dynamically generated content and get the tag that I want with BeautifulSoup:</p>
<pre><code>from contextlib import closing
from selenium.webdriver import Firefox
from selenium.webdriver.support.ui import WebDriverWait
with closing(Firefox()) as browse... | 0 | 2016-08-09T20:27:05Z | [
"python",
"beautifulsoup",
"screen-scraping"
] |
Scraping a website with BeautifulSoup | 38,858,466 | <p>I'm trying to scrape a website with BeautifulSoup. More specifically I'm trying to get the string from a following tag:</p>
<pre><code><td class="Fz(s) Fw(500) Ta(end)" data-reactid=".17c0h26fqwq.1.$0.0.0.3.1.$main-0-Quote-Proxy.$main 0-Quote.2.0.0.0.1.0.0:$VALUATION_MEASURES.0.1.0.$MARKET_CAP_INTRADAY.1">4.3... | 1 | 2016-08-09T18:59:33Z | 38,859,891 | <p>You can get the data just using requests, the content is generated from an ajax get to <em><a href="https://query1.finance.yahoo.com/v10/finance/quoteSummary/IONS" rel="nofollow">https://query1.finance.yahoo.com/v10/finance/quoteSummary/IONS</a></em>:</p>
<pre><code>from pprint import pprint as pp
import requests
... | 2 | 2016-08-09T20:31:47Z | [
"python",
"beautifulsoup",
"screen-scraping"
] |
Parsing keyword next to special character (pyparsing) | 38,858,479 | <p>Using pyparsing, how can I match a keyword immediately before or after a special character (like "{" or "}")? The code below shows that my keyword "msg" is not matched unless it is preceded by whitespace (or at start):</p>
<pre><code>import pyparsing as pp
openBrace = pp.Suppress(pp.Keyword("{"))
closeBrace = pp.S... | 1 | 2016-08-09T18:59:52Z | 38,858,834 | <pre><code>openBrace = pp.Suppress(pp.Keyword("{"))
closeBrace = pp.Suppress(pp.Keyword("}"))
</code></pre>
<p>should be:</p>
<pre><code>openBrace = pp.Suppress(pp.Literal("{"))
closeBrace = pp.Suppress(pp.Literal("}"))
</code></pre>
<p>or even just:</p>
<pre><code>openBrace = pp.Suppress("{")
closeBrace = pp.Suppr... | 1 | 2016-08-09T19:22:08Z | [
"python",
"python-2.7",
"parsing",
"text-parsing",
"pyparsing"
] |
Python version of h=area() in Matlab | 38,858,506 | <p>I asked a related question yesterday and fortunately got my answer from jlarsch quickly. But now I am stuck with the next part, which starts with the <code>h=area()</code> line. I'd like to know the python version of the <code>area()</code> function, via which I will be able to set the colors. Could someone shed ... | -1 | 2016-08-09T19:01:18Z | 38,858,631 | <p>You might be looking for <a href="http://www.pygame.org/docs/ref/draw.html" rel="nofollow">pygame.draw.polygon()</a>, which can fill a polygon defined by an arbitrary array of points.</p>
| 0 | 2016-08-09T19:08:34Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.