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 |
|---|---|---|---|---|---|---|---|---|---|
Add new data to a text file without overwriting it in python | 38,959,849 | <p>Right, I'm running a while loop that does some calculations, and, at the end, exports the data to a .txt file. The problem is, rather than appending the data to the end of the file, it seems to overwrite it and create a brand new file instead. How would I make it append to the old file?</p>
<p>Here's my code:</p>
... | 0 | 2016-08-15T17:24:53Z | 38,959,890 | <p>Open the file before the loop starts. Every time you open the file for writing, it creates a new file (it deletes whatever is in it).</p>
<pre><code>with open("Monarchs Output.txt", "w") as text_file:
turn = 1
while turn < times:
dip1 = randint(1,4)
dip2 = randint(1,4)
dip = (dip1... | 2 | 2016-08-15T17:27:28Z | [
"python",
"python-3.x"
] |
Using power results in ValueError: a <= 0 | 38,959,864 | <p>I have written the following code but it fails with a <code>ValueError</code>.</p>
<pre><code>from numpy import *
from pylab import *
t = arange(-10, 10, 20/(1001-1))
x = 1./sqrt(2*pi)*exp(power(-(t*t), 2))
</code></pre>
<p>Specifically, the error message I'm receiving is:</p>
<pre><code>ValueError: a <= 0
... | -1 | 2016-08-15T17:25:42Z | 38,962,309 | <p>Both <code>numpy</code> and <code>pylab</code> define a function called <code>power</code>, but they are completely different. Because you imported <code>pylab</code> after <code>numpy</code> using <code>import *</code>, the <code>pylab</code> version is the one you end up with. What is <code>pylab.power</code>? Fro... | 2 | 2016-08-15T20:09:49Z | [
"python",
"python-3.x",
"numpy"
] |
python Selenium PermissionError: [WinError 5] Access is denied | 38,959,885 | <p>I'm trying to open up a Internet Explorer with python Selenium but keep getting an error "<strong>PermissionError: [WinError 5] Access is denied</strong>".</p>
<p>I have downloaded Internet Explorer Driver Server ran the script as administrator is there anything else I could do???</p>
<p><strong>Code</strong></p>
... | 0 | 2016-08-15T17:27:01Z | 38,960,070 | <p>The driver wasn't pointing at the exe file! so it should of been. </p>
<pre><code>driver = webdriver.Ie(r"C:\\Users\\N\\Downloads\\IEwebdriver\\IEDriverServer_x64_2.53.1\\IEDriverServer.exe")
</code></pre>
| 0 | 2016-08-15T17:40:30Z | [
"python",
"python-3.x",
"selenium"
] |
Fast advanced indexing in numpy | 38,960,001 | <p>I'm trying to take a slice from a large numpy array as quickly as possible using fancy indexing. I would be happy returning a view, but <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow">advanced indexing returns a copy</a>. </p>
<p>I've tried solutions from <a... | 1 | 2016-08-15T17:35:39Z | 38,960,059 | <p>There's no way to do this with a view. A view needs consistent strides, while your data is randomly scattered throughout the original array.</p>
| 4 | 2016-08-15T17:39:32Z | [
"python",
"arrays",
"numpy",
"optimization",
"indexing"
] |
How to send data to the TemplateView used in openpyxl to generate xlsx files in DJango | 38,960,008 | <p>I have downloaded <code>xlsx</code> files before by using this library, and it's amazing, but now I want to send data to use it in a queryset to fill the <code>xlsx</code> sheet.</p>
<p>I have a submit button that uses jquery to prevent default and according to a checkbox it either sends the data through Ajax to a ... | -2 | 2016-08-15T17:36:26Z | 38,963,430 | <p>The people that gave me -2 probably was thinking this was a simple excel problem.</p>
<p>I found a solution, in my jquery function I added this:</p>
<pre><code>$(location).attr('href', '/the_url?number=5');
</code></pre>
<p>Without using Ajax, just send the parameter in the URL that is linked to the TemplateView.... | 0 | 2016-08-15T21:35:39Z | [
"python",
"django",
"excel"
] |
np.savetxt - using variable for file name | 38,960,124 | <p>How can I use variable for a file name when using <code>np.savetxt</code></p>
<p>Here is my MWE:</p>
<pre><code>import numpy as np
k=0
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
np.savetxt('koo'+str(k)'.txt', zipped, fmt='%f\t%f')
</code></pre>
<p>However this throws me 'invalid syntax' error</p>
| 0 | 2016-08-15T17:43:10Z | 38,960,150 | <pre><code>np.savetxt('koo'+ str(k) + '.txt', zipped, fmt='%f\t%f')
</code></pre>
<p>You forgot a <code>+</code> sign.</p>
| 2 | 2016-08-15T17:44:51Z | [
"python"
] |
np.savetxt - using variable for file name | 38,960,124 | <p>How can I use variable for a file name when using <code>np.savetxt</code></p>
<p>Here is my MWE:</p>
<pre><code>import numpy as np
k=0
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
np.savetxt('koo'+str(k)'.txt', zipped, fmt='%f\t%f')
</code></pre>
<p>However this throws me 'invalid syntax' error</p>
| 0 | 2016-08-15T17:43:10Z | 38,960,158 | <p>You forgot a <code>+</code> sign, try replacing with this:</p>
<p>np.savetxt('koo'+str(k)+'.txt', zipped, fmt='%f\t%f')</p>
| 1 | 2016-08-15T17:45:10Z | [
"python"
] |
np.savetxt - using variable for file name | 38,960,124 | <p>How can I use variable for a file name when using <code>np.savetxt</code></p>
<p>Here is my MWE:</p>
<pre><code>import numpy as np
k=0
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
np.savetxt('koo'+str(k)'.txt', zipped, fmt='%f\t%f')
</code></pre>
<p>However this throws me 'invalid syntax' error</p>
| 0 | 2016-08-15T17:43:10Z | 38,960,208 | <p>You forgot the '+' sign between str(k) and '.txt'</p>
<pre><code>np.savetxt('koo'+ str(k) + '.txt', zipped, fmt='%f\t%f')
</code></pre>
| 1 | 2016-08-15T17:48:22Z | [
"python"
] |
Pythonic way of modifiying a string with a temporary list | 38,960,196 | <p>I have a string that is several thousand chars long and contains about 100 <code>\n</code>, separating it out when printed. I am deleting any lines that contain certain substrings, and certain individual chars.</p>
<p>This part is already completed, but I'm curious as to what the most <em>pythonic</em> way of doing... | 0 | 2016-08-15T17:47:56Z | 38,960,371 | <p>Here's a pythonic solution for this type of problem using <a href="https://docs.python.org/2/library/functions.html#filter" rel="nofollow">filter</a>:</p>
<pre><code>active_config = """this is an
example which contains
words like
cmdStatus=
cmdStatus2
or other
weird <?lxml
tags
"""
lines = active_config.splitli... | 1 | 2016-08-15T18:00:02Z | [
"python",
"naming-conventions"
] |
Pythonic way of modifiying a string with a temporary list | 38,960,196 | <p>I have a string that is several thousand chars long and contains about 100 <code>\n</code>, separating it out when printed. I am deleting any lines that contain certain substrings, and certain individual chars.</p>
<p>This part is already completed, but I'm curious as to what the most <em>pythonic</em> way of doing... | 0 | 2016-08-15T17:47:56Z | 38,960,555 | <p>A couple of list comprehensions will do it too:</p>
<pre><code>active_config = active_config.split('\n')
temp_list = [z for z in active_config if "cmdStatus=" in z or "<?xml" in z]
if temp_list[-1] == "*":
temp_list = "\n".join([x.replace("\r", "") for x in temp_list[:-1]])
#Do whatever you need to do wit... | 1 | 2016-08-15T18:12:14Z | [
"python",
"naming-conventions"
] |
Mutable indexed heterogeneous data structure? | 38,960,221 | <p>Is there a data class or type in Python that matches these criteria?</p>
<p>I am trying to build an object that looks something like this:</p>
<ul>
<li><p>ExperimentData</p>
<ul>
<li><p>ID 1</p>
<ul>
<li>sample_info_1: <code>character string</code></li>
<li>sample_info_2: <code>character string</code></li>
<li... | 1 | 2016-08-15T17:49:29Z | 38,966,174 | <p>You could use a dict of dicts instead of a dict of namedtuples. Dicts are mutable, so you'll be able to modify the inner dicts.</p>
<p>Given what you said in the comments about the structures of each DataFrame-1 and -2 being comparable, you could also group all of each into one big DataFrame, by adding a column to... | 1 | 2016-08-16T03:24:44Z | [
"python",
"pandas",
"tuples"
] |
Is there a better method for getting the CBV instance from Django's "as_view" mechanism | 38,960,398 | <p>I have a simple test using Django's RequestFactory for a view. My view, sets some state within itself that I want to test (this is not a great example, but the point is I want to test some state in the view after the request is processed rather than parsing it out of HTML for no good reason):</p>
<pre><code>def som... | 0 | 2016-08-15T18:01:20Z | 38,962,597 | <p><code>View.as_view()</code> does not create an instance. All it does is return a closure function that will create an instance when the view is called. </p>
<p>The best you can do is manually create an instance and prepare it the same way the closure function does. </p>
<pre><code>def some_test(self):
rf = Req... | 0 | 2016-08-15T20:32:13Z | [
"python",
"django"
] |
Stack cv2 Frame of RGB channel and Single Channel together | 38,960,411 | <p>What I am looking to do is make it so that I can stack the 4 Video feeds together, RGB, B, G, R Channels in a quad frame feed. Here is my code I get the error "All the input arrays must have same number of dimensions. I wanted to know if there is a way to work through or around this? If you insert GRAY where RGB ... | 1 | 2016-08-15T18:01:47Z | 38,961,299 | <p>Here's my solution:</p>
<pre><code>import numpy as np
import cv2
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
red = np.zeros(frame.shape, 'uint8')
green = np.zeros(frame.shape, 'uint8')
blue = np.zeros(frame.shape, 'uint8')
while(True):
ret, frame = cap.read()
b, g, r = cv2.split(frame)
red[...... | 0 | 2016-08-15T19:00:26Z | [
"python",
"opencv",
"numpy"
] |
Using scipy.io.savemat to Save Nested Lists | 38,960,464 | <p>This is relating to my last question, which can be found <a href="http://stackoverflow.com/questions/38924256/creating-a-nested-list-in-python">here</a>. I'm dealing with lists similar to the list I describe in that link as markerList - so a list with three levels. I need to save this information as a .mat file, but... | 1 | 2016-08-15T18:05:25Z | 38,961,045 | <p>Without looking again at your previous question I suspect the issue is with now <code>numpy.array</code> creates arrays from lists of sublists or arrays.</p>
<p>You note that <code>markerList</code> is saved as expected, and that the cells vary in size.</p>
<p>Try</p>
<pre><code>np.array(markerList)
</code></pre>... | 0 | 2016-08-15T18:45:25Z | [
"python",
"python-2.7",
"scipy"
] |
Using scipy.io.savemat to Save Nested Lists | 38,960,464 | <p>This is relating to my last question, which can be found <a href="http://stackoverflow.com/questions/38924256/creating-a-nested-list-in-python">here</a>. I'm dealing with lists similar to the list I describe in that link as markerList - so a list with three levels. I need to save this information as a .mat file, but... | 1 | 2016-08-15T18:05:25Z | 38,961,751 | <p>As per <a href="https://docs.scipy.org/doc/scipy-0.9.0/reference/tutorial/io.html#matlab-cell-arrays" rel="nofollow">savemat documentation</a>, convert into a numpy array of 'objects':</p>
<pre><code>from scipy.io import savemat
import numpy
a = numpy.array([[1,2,3],[1,2,3]])
b = numpy.array([[2,3,4],[2,3,4]])
c =... | 1 | 2016-08-15T19:31:18Z | [
"python",
"python-2.7",
"scipy"
] |
Curl command works but not pycurl command for smartsheet | 38,960,468 | <p>I am able to successfully update the smartsheet using Curl Commands: </p>
<pre><code>curl https://api.smartsheet.com/2.0/sheets/sheetID/rows \
> -H "Authorization: Bearer token" \
> -H "Content-Type: application/json" \
> -X PUT \
> -d '[{"id": rid, "locked" : false}]'
</code></pre>
<p>But when I try t... | 1 | 2016-08-15T18:05:34Z | 38,960,593 | <p>I think the issue is caused by your calling <code>c.setopt(pycurl.HTTPHEADER, ...)</code> twice, and the second invocation overwrites the auth token set in the first.</p>
<p>Try replacing the two <code>c.setopt</code> calls with the following:</p>
<p><code>c.setopt(pycurl.HTTPHEADER, ['Authorization: Bearer ' + to... | 0 | 2016-08-15T18:14:45Z | [
"python",
"curl",
"pycurl",
"smartsheet-api-1.1",
"smartsheet-api-2.0"
] |
Leap Year Boolean Logic: Include Parentheses? | 38,960,503 | <p>Which is "more correct (logically)"? <em>Specific to Leap Year, not in general</em>.</p>
<ol>
<li><p>With Parentheses</p>
<pre><code>return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
</code></pre></li>
<li><p>Without</p>
<pre><code>return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
</code></p... | 4 | 2016-08-15T18:07:36Z | 38,960,562 | <p>The parens affect what order your booleans take. <code>and</code>s are grouped together and resolved before <code>or</code>s are, so:</p>
<pre><code>a and b or c
</code></pre>
<p>becomes:</p>
<pre><code>(a and b) or c
</code></pre>
<p>if either BOTH <code>a</code> and <code>b</code> are truthy, OR if <code>c</co... | 5 | 2016-08-15T18:12:36Z | [
"python",
"boolean-logic",
"parentheses",
"leap-year"
] |
Leap Year Boolean Logic: Include Parentheses? | 38,960,503 | <p>Which is "more correct (logically)"? <em>Specific to Leap Year, not in general</em>.</p>
<ol>
<li><p>With Parentheses</p>
<pre><code>return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
</code></pre></li>
<li><p>Without</p>
<pre><code>return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
</code></p... | 4 | 2016-08-15T18:07:36Z | 38,960,673 | <blockquote>
<p>Which answer is "more correct" and why?</p>
</blockquote>
<p>It's not a matter of what is '<em>more correct</em>', rather; what logic do you wish to implement? Parenthesis' in <strong>boolean</strong> expressions change <a href="https://docs.python.org/3/reference/expressions.html#evaluation-order" r... | 3 | 2016-08-15T18:20:07Z | [
"python",
"boolean-logic",
"parentheses",
"leap-year"
] |
Leap Year Boolean Logic: Include Parentheses? | 38,960,503 | <p>Which is "more correct (logically)"? <em>Specific to Leap Year, not in general</em>.</p>
<ol>
<li><p>With Parentheses</p>
<pre><code>return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
</code></pre></li>
<li><p>Without</p>
<pre><code>return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
</code></p... | 4 | 2016-08-15T18:07:36Z | 38,960,751 | <p>Include the parentheses. In English, the rule is:</p>
<ol>
<li>Year must be divisible by 4.</li>
<li>Year must not be visible by 100, unless it's divisible by 400.</li>
</ol>
<p>The version with parentheses matches this two-pronged rule best.</p>
<pre><code>return year % 4 == 0 and (year % 100 != 0 or year % 400 ... | 3 | 2016-08-15T18:25:08Z | [
"python",
"boolean-logic",
"parentheses",
"leap-year"
] |
Leap Year Boolean Logic: Include Parentheses? | 38,960,503 | <p>Which is "more correct (logically)"? <em>Specific to Leap Year, not in general</em>.</p>
<ol>
<li><p>With Parentheses</p>
<pre><code>return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
</code></pre></li>
<li><p>Without</p>
<pre><code>return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
</code></p... | 4 | 2016-08-15T18:07:36Z | 38,960,804 | <blockquote>
<p>Which answer is "more correct" and why? (Specific to Leap Year Logic, not in general)</p>
<p>With Parentheses</p>
<p>return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)</p>
<p>Without</p>
<p>return year % 4 == 0 and year % 100 != 0 or year % 400 == 0</p>
</blockquote>
<p... | 1 | 2016-08-15T18:29:12Z | [
"python",
"boolean-logic",
"parentheses",
"leap-year"
] |
Leap Year Boolean Logic: Include Parentheses? | 38,960,503 | <p>Which is "more correct (logically)"? <em>Specific to Leap Year, not in general</em>.</p>
<ol>
<li><p>With Parentheses</p>
<pre><code>return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
</code></pre></li>
<li><p>Without</p>
<pre><code>return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
</code></p... | 4 | 2016-08-15T18:07:36Z | 38,960,865 | <p>As you noted, in operation, there is no difference, since the number being divisible by 400 implies that it is also divisible by 100, which implies that it is also divisible by 4. Operationally, whether the parentheses have any effect depends on the lexical order (order of evaluation) of the language. Most languag... | 1 | 2016-08-15T18:32:48Z | [
"python",
"boolean-logic",
"parentheses",
"leap-year"
] |
Leap Year Boolean Logic: Include Parentheses? | 38,960,503 | <p>Which is "more correct (logically)"? <em>Specific to Leap Year, not in general</em>.</p>
<ol>
<li><p>With Parentheses</p>
<pre><code>return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
</code></pre></li>
<li><p>Without</p>
<pre><code>return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
</code></p... | 4 | 2016-08-15T18:07:36Z | 38,986,193 | <p>Answer: <strong>Include Parentheses</strong></p>
<hr>
<p><a href="http://stackoverflow.com/users/68587/john-kugelman">John Kugelman</a> explains why they are 2 separate logical tests as opposed to 3, last 2 should be grouped together:</p>
<ol>
<li>Year must be divisible by 4.</li>
<li>Year must not be visible by ... | 0 | 2016-08-16T23:57:05Z | [
"python",
"boolean-logic",
"parentheses",
"leap-year"
] |
pd.Timedelta conversion on a dataframe column | 38,960,514 | <p>I am trying to convert a dataframe column to a timedelta but am having issues. The format that the column comes in looks like '+XX:XX:XX' or '-XX:XX:XX'</p>
<p>My dataframe:</p>
<pre><code> df = pd.DataFrame({'time':['+06:00:00', '-04:00:00'],})
</code></pre>
<p>My approach:</p>
<pre><code> df['time'] = p... | 1 | 2016-08-15T18:08:48Z | 38,960,586 | <p>The error is pretty clear: </p>
<blockquote>
<p>ValueError: Value must be Timedelta, string, integer, float, timedelta
or convertible</p>
</blockquote>
<p>What you are passing to <code>pd.Timedelta()</code> is none of the above data types:</p>
<pre><code>>>> type(df['time'])
<class 'pandas.core.se... | 2 | 2016-08-15T18:14:21Z | [
"python",
"pandas"
] |
pd.Timedelta conversion on a dataframe column | 38,960,514 | <p>I am trying to convert a dataframe column to a timedelta but am having issues. The format that the column comes in looks like '+XX:XX:XX' or '-XX:XX:XX'</p>
<p>My dataframe:</p>
<pre><code> df = pd.DataFrame({'time':['+06:00:00', '-04:00:00'],})
</code></pre>
<p>My approach:</p>
<pre><code> df['time'] = p... | 1 | 2016-08-15T18:08:48Z | 38,961,561 | <p>I would strongly recommend to use specifically designed and vectorized (i.e. very fast) method: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow">to_timedelta()</a>:</p>
<pre><code>In [40]: pd.to_timedelta(df['time'])
Out[40]:
0 06:00:00
1 -1 days +... | 1 | 2016-08-15T19:17:42Z | [
"python",
"pandas"
] |
Using gdal in python to produce tiff files from csv files | 38,960,568 | <p>I have many csv files with this format:</p>
<pre><code>Latitude,Longitude,Concentration
53.833399,-122.825257,0.021957
53.837893,-122.825238,0.022642
....
</code></pre>
<p>My goal is to produce GeoTiff files based on the information within these files (one tiff file per csv file), preferably using python. This was... | 0 | 2016-08-15T18:13:06Z | 38,978,123 | <p>Here is a little code I adapted for your case. You need to have the GDAL directory with all the *.exe in added to your path for it to work (in most cases it's <code>C:\Program Files (x86)\GDAL</code>). </p>
<p>It uses the <code>gdal_grid.exe</code> util (see doc here: <a href="http://www.gdal.org/gdal_grid.html" re... | 1 | 2016-08-16T14:52:50Z | [
"python",
"csv",
"tiff",
"gdal",
"geotiff"
] |
Find indexes of two lists | 38,960,631 | <p>I have two numpy lists:</p>
<pre><code>x = ['A', 'A', 'C', 'A', 'V', 'A', 'B', 'A', 'A', 'A']
y = ['1', '2', '1', '1', '3', '2', '1', '1', '1', '1']
</code></pre>
<p>How can I find indexes when simulataneously <code>x</code> equals <code>'A'</code> and <code>y</code> equals <code>'2'</code>?</p>
<p>I expect to ge... | 1 | 2016-08-15T18:17:15Z | 38,960,694 | <p>You need to convert the list to numpy array in order to use vectorized operation such as <code>==</code> and <code>&</code>:</p>
<pre><code>import numpy as np
np.where((np.array(x) == "A") & (np.array(y) == "2"))
# (array([1, 5]),)
</code></pre>
<p>Shorter version (if you are sure that x and y are numpy ar... | 2 | 2016-08-15T18:21:18Z | [
"python",
"numpy",
"where"
] |
Find indexes of two lists | 38,960,631 | <p>I have two numpy lists:</p>
<pre><code>x = ['A', 'A', 'C', 'A', 'V', 'A', 'B', 'A', 'A', 'A']
y = ['1', '2', '1', '1', '3', '2', '1', '1', '1', '1']
</code></pre>
<p>How can I find indexes when simulataneously <code>x</code> equals <code>'A'</code> and <code>y</code> equals <code>'2'</code>?</p>
<p>I expect to ge... | 1 | 2016-08-15T18:17:15Z | 38,960,750 | <p>pure python solution:</p>
<pre><code>>>> [i for i,j in enumerate(zip(x,y)) if j==('A','2')]
[1, 5]
</code></pre>
| 2 | 2016-08-15T18:25:08Z | [
"python",
"numpy",
"where"
] |
Find indexes of two lists | 38,960,631 | <p>I have two numpy lists:</p>
<pre><code>x = ['A', 'A', 'C', 'A', 'V', 'A', 'B', 'A', 'A', 'A']
y = ['1', '2', '1', '1', '3', '2', '1', '1', '1', '1']
</code></pre>
<p>How can I find indexes when simulataneously <code>x</code> equals <code>'A'</code> and <code>y</code> equals <code>'2'</code>?</p>
<p>I expect to ge... | 1 | 2016-08-15T18:17:15Z | 38,960,855 | <p>If you want to work with lists:</p>
<pre><code>idx1 = [i for i, x in enumerate(x) if x == 'A']
idx2 = [i for i, x in enumerate(y) if x == '2']
list(set(idx1).intersection(idx2))
</code></pre>
| 1 | 2016-08-15T18:32:09Z | [
"python",
"numpy",
"where"
] |
TypeError: int() argument must be a string or a number, not 'Model Instance' - Heroku | 38,960,708 | <p>Trying to deploy my project on the server, and i'm stuck in migrations becouse there is some error:</p>
<pre><code> File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 382, in add_field
definition, params = self.column_sql(model, field, include_default=True)
File "/app/... | 0 | 2016-08-15T18:22:13Z | 38,961,132 | <p>Here's the culprit:</p>
<pre><code>profile = models.ForeignKey(Profile, default=Profile)
# ^^^^^^^^^^^^^^^
</code></pre>
<p>You can't set a Model class as a <code>Foreignkey</code> default. If you're thinking of setting an <em>hardcoded</em> default then you should use an <code>i... | 1 | 2016-08-15T18:50:58Z | [
"python",
"django",
"heroku"
] |
Python: Strategically go through ten digit numbers with 0-9 | 38,960,714 | <p>Recently, I read a math problem inspiring me to write a program. It asked to <strong>arrange the digits 0-9 once each so that <em>xx xxx / xx xxx = 9</em>.</strong> I wrote a python program to find the solutions and had a bit of trouble making sure the digits were different. I found a way using nested <em>whiles</em... | 3 | 2016-08-15T18:22:39Z | 38,960,864 | <p>Here's one way to use <code>itertools</code> for this problem.</p>
<pre><code>import itertools
def makenum(digits):
return int(''.join(map(str, digits)))
for p in itertools.permutations(range(10)):
a = makenum(p[:5])
b = makenum(p[5:])
if a == 9 * b:
print(a, b)
</code></pre>
| 2 | 2016-08-15T18:32:46Z | [
"python",
"algorithm",
"python-3.x",
"digits"
] |
Python: Strategically go through ten digit numbers with 0-9 | 38,960,714 | <p>Recently, I read a math problem inspiring me to write a program. It asked to <strong>arrange the digits 0-9 once each so that <em>xx xxx / xx xxx = 9</em>.</strong> I wrote a python program to find the solutions and had a bit of trouble making sure the digits were different. I found a way using nested <em>whiles</em... | 3 | 2016-08-15T18:22:39Z | 38,961,088 | <p>Take advantage of algebra:</p>
<pre><code>a / b = 9 == a = 9 * b
</code></pre>
<p>Knowing that, you only have to bother generating the values:</p>
<pre><code>[(9*num, num) for num in range(10000, 100000)]
</code></pre>
<p>If you need to filter things out by some criteria, you can easily write a filter function:<... | 2 | 2016-08-15T18:48:11Z | [
"python",
"algorithm",
"python-3.x",
"digits"
] |
Python: Strategically go through ten digit numbers with 0-9 | 38,960,714 | <p>Recently, I read a math problem inspiring me to write a program. It asked to <strong>arrange the digits 0-9 once each so that <em>xx xxx / xx xxx = 9</em>.</strong> I wrote a python program to find the solutions and had a bit of trouble making sure the digits were different. I found a way using nested <em>whiles</em... | 3 | 2016-08-15T18:22:39Z | 38,961,197 | <p>Runs in <strong>0.7 secs</strong>. Faster than most solutions mentioned, though bit clumsy.</p>
<pre><code>def sol(a,b,zero):
for i in range(a,b):
fl = 0
marked = 10*[0]
marked[0] = zero
tmp = i
while tmp > 0:
marked[tmp%10] = marked[tmp%10] + 1
tmp = tmp/10
numerato... | 1 | 2016-08-15T18:54:58Z | [
"python",
"algorithm",
"python-3.x",
"digits"
] |
Python: Strategically go through ten digit numbers with 0-9 | 38,960,714 | <p>Recently, I read a math problem inspiring me to write a program. It asked to <strong>arrange the digits 0-9 once each so that <em>xx xxx / xx xxx = 9</em>.</strong> I wrote a python program to find the solutions and had a bit of trouble making sure the digits were different. I found a way using nested <em>whiles</em... | 3 | 2016-08-15T18:22:39Z | 38,961,307 | <p>This is a minor variation on @David's answer.</p>
<p>If we look at <code>itertools.permutations([1,2,3,4])</code></p>
<pre><code>>>> for p in itertools.permutations([1,2,3,4]):
... print(p)
...
(1, 2, 3, 4)
(1, 2, 4, 3)
(1, 3, 2, 4)
(1, 3, 4, 2)
(1, 4, 2, 3)
(1, 4, 3, 2)
(2, 1, 3, 4)
(2, 1, 4, 3)
(2, ... | 0 | 2016-08-15T19:01:03Z | [
"python",
"algorithm",
"python-3.x",
"digits"
] |
Python: Strategically go through ten digit numbers with 0-9 | 38,960,714 | <p>Recently, I read a math problem inspiring me to write a program. It asked to <strong>arrange the digits 0-9 once each so that <em>xx xxx / xx xxx = 9</em>.</strong> I wrote a python program to find the solutions and had a bit of trouble making sure the digits were different. I found a way using nested <em>whiles</em... | 3 | 2016-08-15T18:22:39Z | 38,961,548 | <p>Adapting Wayne Werner's solution you can do this to add the digit uniqueness constraint (assuming Python 3):</p>
<pre><code>[(9*num, num)
for num in range(10000, 100000 // 9)
if len(set(str(num) + str(num * 9))) == 10]
</code></pre>
<p>This runs in 1.5 ms on my machine.</p>
<p>Note, that you can only check nu... | 2 | 2016-08-15T19:16:56Z | [
"python",
"algorithm",
"python-3.x",
"digits"
] |
Does ending a python 2.7 print statement with a comma not work in tmux? | 38,960,887 | <p>Pretty much just what's in the question. I have a slow process running in tmux and wanted to document progress through the for loop by printing the loop variable.</p>
<pre><code>print 'Progress...',
for i in range(15):
...
print i,
print
</code></pre>
<p>This works in my terminal. In tmux, however, it d... | 3 | 2016-08-15T18:34:13Z | 38,960,910 | <p>This is almost surely due to output buffering. You can check that's the cause by calling flush:</p>
<pre><code>import sys
print 'Progress...',
for i in range(15):
...
print i,
sys.stdout.flush()
print
</code></pre>
<p>If this fixes your problem, you might consider to run <a href="https://docs.python... | 5 | 2016-08-15T18:36:01Z | [
"python",
"bash",
"tmux"
] |
Why don't these tkinter programs behave identically? | 38,960,936 | <p>I have 2 codes I made. The 2nd one is based off of the first one. Unfortunately for some reason the 2nd one doesn't work even though the first one does.</p>
<p>First code:</p>
<pre><code>import time
from Tkinter import *
root = Tk()
t=StringVar()
num=1
t.set(str(num)
thelabel = Label(root, textvariable=t).pack()
... | -2 | 2016-08-15T18:38:18Z | 38,960,987 | <p>You're overwriting the previous value of t with the temperature from read_retry on this line:</p>
<pre><code>h,t = dht.read_retry(dht.DHT22, 4)
</code></pre>
<p>Then, when you try to call <code>set</code>, <code>t</code> is now a float, so doesn't have a set method. Use a different variable name instead of <code>t... | 3 | 2016-08-15T18:41:46Z | [
"python",
"tkinter",
"raspberry-pi"
] |
Why don't these tkinter programs behave identically? | 38,960,936 | <p>I have 2 codes I made. The 2nd one is based off of the first one. Unfortunately for some reason the 2nd one doesn't work even though the first one does.</p>
<p>First code:</p>
<pre><code>import time
from Tkinter import *
root = Tk()
t=StringVar()
num=1
t.set(str(num)
thelabel = Label(root, textvariable=t).pack()
... | -2 | 2016-08-15T18:38:18Z | 38,961,932 | <p><code>root.update</code> doesn't do anything. You need to add <code>()</code>:</p>
<pre><code>root.update()
</code></pre>
<p>That being said, your algorithm is the wrong way to run periodic tasks in tkinter. See <a href="http://stackoverflow.com/a/37681471/7432">http://stackoverflow.com/a/37681471/7432</a></p>
| 1 | 2016-08-15T19:44:31Z | [
"python",
"tkinter",
"raspberry-pi"
] |
A value is trying to be set on a copy of a slice from a DataFrame Warning | 38,961,014 | <p>Not sure why I still get the warning after I updated to .loc method suggested by the message? Is it a false alarm?</p>
<pre><code>eG.loc[:,'wt']=eG.groupby(['date','BB'])['m'].transform(weightFunction)
</code></pre>
<blockquote>
<p>A value is trying to be set on a copy of a slice from a DataFrame</p>
</blockquot... | -2 | 2016-08-15T18:43:25Z | 38,961,755 | <p>I guess your <code>eG</code> DF is a copy of another DF...</p>
<p>Here is a small demo:</p>
<pre><code>In [69]: df = pd.DataFrame(np.random.randint(0, 5, (10, 3)), columns=list('abc'))
In [70]: cp = df[df.a > 0]
In [71]: cp.loc[:, 'c'] = cp.groupby('a').b.transform('sum')
c:\envs\py35\lib\site-packages\panda... | 1 | 2016-08-15T19:31:28Z | [
"python",
"pandas"
] |
How can I schedule a script to run every 46 minutes, between 6:00 am and 23:40pm, daily with python? | 38,961,111 | <p>I need a script to run every 46 minutes, between 6:00 am and 23:40pm, daily. Im currently using apscheduler, but I'm failing to set up the 24 runs per day on interval schedule, and programming each one of the run with a cron mode seems highly inefficient. Is there a simple way of telling python to "run this code eve... | -1 | 2016-08-15T18:49:30Z | 38,961,376 | <p>Assuming you're not using asyncio, gevent, tornado, etc.</p>
<pre><code>from apscheduler.schedulers.background import BackgroundScheduler
sched = BackgroundScheduler()
sched.start()
sched.add_job(function, 'cron', minute='46' hour='6-23')
</code></pre>
<p>See the <a href="https://apscheduler.readthedocs.io/en/lat... | 1 | 2016-08-15T19:06:16Z | [
"python",
"python-3.x",
"apscheduler"
] |
Django Form, User input fields not rendering in template | 38,961,126 | <p>Django newb here, but I'm learning.</p>
<p><strong>Problem Statement</strong></p>
<p>Input fields not rendering in html template.</p>
<p><strong>Output in Browser</strong></p>
<p>True</p>
<p>| Submit Button |</p>
<p><strong>Relevant Code</strong></p>
<pre><code>forms.py
from django import forms
from django.db... | 0 | 2016-08-15T18:50:39Z | 38,964,281 | <p>I modified the forms.py to use the model I already had for the DB.</p>
<pre><code>forms.py
from django.forms import ModelForm
from clientadmin.models import notes
class PostNotes(ModelForm):
class Meta:
model = notes
fields = ['notedate', 'notetext']
</code></pre>
<p>I also modified the views.... | 0 | 2016-08-15T23:03:01Z | [
"python",
"django",
"forms"
] |
Pandas Add Values of Column to Different Dataframe | 38,961,170 | <p>So I have a dataframe, df1, that has 3 rows, A, B, and C as such:</p>
<pre><code> A B C
Arizona 0 2.800000 5.600000
California 0 18.300000 36.600000
Colorado 0 2.666667 5.333333
Connecticut ... | 1 | 2016-08-15T18:53:30Z | 38,961,227 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add.html" rel="nofollow">add()</a> method:</p>
<pre><code>In [22]: df1.add(df2.D, axis='index')
Out[22]:
A B C
Arizona 13.0 15.800000 18.600000
California 18.0 36.300000 54.600000... | 2 | 2016-08-15T18:56:19Z | [
"python",
"pandas"
] |
Pandas Add Values of Column to Different Dataframe | 38,961,170 | <p>So I have a dataframe, df1, that has 3 rows, A, B, and C as such:</p>
<pre><code> A B C
Arizona 0 2.800000 5.600000
California 0 18.300000 36.600000
Colorado 0 2.666667 5.333333
Connecticut ... | 1 | 2016-08-15T18:53:30Z | 38,961,352 | <p>are you trying to do something like this?</p>
<pre><code>df1 = DataFrame({'A':{'a':1, 'b':2}, 'B':{'a':10, 'b':20}})
df2 = DataFrame({'C':{'a':2, 'b':2}})
df1['A+C'] = df1['A'] + df2['C']
df1['B+C'] = df1['B'] + df2['C']
print (df1)
A B A+C B+C
a 1 10 3 12
b 2 20 4 22
</code></pre>
| 0 | 2016-08-15T19:04:44Z | [
"python",
"pandas"
] |
Unable to login with python selenium error:NoSuchElementException error | 38,961,190 | <p>I have tried locating the submit button by id and xpath but none of them worked and checked in the page source ,the id is same.I have no idea why this is happening even though I am giving the correct Id or xpath
<br><br>
<strong>URL :</strong> <a href="https://moodle.niituniversity.in/moodle/login/index.php" rel="n... | 0 | 2016-08-15T18:54:45Z | 38,962,073 | <p>Might be possible this is timing issue, you should implement <code>WebDriverWait</code> to wait until button present on page as below :-</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support i... | 0 | 2016-08-15T19:53:11Z | [
"python",
"selenium",
"xpath",
"python-3.4"
] |
Reference many columns of pandas DataFrame at once | 38,961,217 | <p>Say I have a <em>n</em> ⨠<em>p</em> matrix of <em>n</em> samples of a single feature of <em>p</em> dimension (for example a word2vec element, so that <em>p</em> is of the order of ~300). I can create each column programatically, eg. with <code>features = ['f'+str(i) for i in range(p)]</code> and then appending to... | 0 | 2016-08-15T18:55:50Z | 38,965,123 | <p>I wouldn't use <code>df.f = df[fs]</code>. It may lead to undesired and surprising behaviour if you try to modify the data frame. Instead, I'd consider creating hierarchical columns as in the below example.</p>
<p>Say, we already have a preexisting data frame <code>df0</code> and another one with features:</p>
<p... | 1 | 2016-08-16T00:57:00Z | [
"python",
"pandas"
] |
python programming socket stream to functions | 38,961,224 | <p>I have many doubts about design a simply python program..
I have opened a socket from a server that stream data via simply telnet server.
I have 3 type of strings that begins with RED,BLUE,YELLOW and after that string the data, example: </p>
<p>RED 21763;22;321321 </p>
<p>BLUE 1;32132;3432</p>
<p>BLUE 1222;332;3<... | 0 | 2016-08-15T18:56:13Z | 38,961,642 | <p><a href="http://stackoverflow.com/questions/2483041/what-is-the-difference-between-fork-and-thread">This</a> should give you a brief idea of threads vs fork.</p>
<p>Creation of threads require lot less overhead. I would go with the thread architecture. Each of the three thread functions will be supplied with the re... | 0 | 2016-08-15T19:23:57Z | [
"python",
"multithreading",
"sockets",
"queue",
"ipc"
] |
Fill NaN based on MultiIndex Pandas | 38,961,234 | <p>I have a pandas Data Frame that I would like to fill in some NaN values of.</p>
<pre><code>import pandas as pd
tuples = [('a', 1990),('a', 1994),('a',1996),('b',1992),('b',1997),('c',2001)]
index = pd.MultiIndex.from_tuples(tuples, names = ['Type', 'Year'])
vals = ['NaN','NaN','SomeName','NaN','SomeOtherName','Som... | 0 | 2016-08-15T18:56:36Z | 38,961,374 | <p>You can sort your data frame by index in descending order and then <code>ffill</code> it:</p>
<pre><code>import pandas as pd
df.sort_index(level = [0,1], ascending = False).ffill()
# 0
# Type Year
# c 2001 SomeThirdName
# b 1997 SomeOtherName
# 1992 SomeOtherNa... | 1 | 2016-08-15T19:06:09Z | [
"python",
"pandas"
] |
java.lang.OutOfMemoryError: Unable to acquire 100 bytes of memory, got 0 | 38,961,251 | <p>I'm invoking Pyspark with Spark 2.0 in local mode with the following command:</p>
<pre><code>pyspark --executor-memory 4g --driver-memory 4g
</code></pre>
<p>The input dataframe is being read from a tsv file and has 580 K x 28 columns. I'm doing a few operation on the dataframe and then i am trying to export it to... | 1 | 2016-08-15T18:57:36Z | 38,961,806 | <p>I believe that the cause of this problem is <a href="https://spark.apache.org/docs/1.2.0/api/python/pyspark.html?highlight=coalesce#pyspark.RDD.coalesce" rel="nofollow">coalesce()</a>, which despite the fact that it avoids a full shuffle (like <a href="http://stackoverflow.com/questions/31610971/spark-repartition-vs... | 1 | 2016-08-15T19:34:50Z | [
"python",
"hadoop",
"memory",
"apache-spark",
"pyspark"
] |
java.lang.OutOfMemoryError: Unable to acquire 100 bytes of memory, got 0 | 38,961,251 | <p>I'm invoking Pyspark with Spark 2.0 in local mode with the following command:</p>
<pre><code>pyspark --executor-memory 4g --driver-memory 4g
</code></pre>
<p>The input dataframe is being read from a tsv file and has 580 K x 28 columns. I'm doing a few operation on the dataframe and then i am trying to export it to... | 1 | 2016-08-15T18:57:36Z | 39,106,641 | <p>The problem for me was indeed <code>coalesce()</code>.
What I did was exporting the file not using <code>coalesce()</code> but parquet instead using <code>df.write.parquet("testP")</code>. Then read back the file and export that with <code>coalesce(1)</code>.</p>
<p>Hopefully it works for you as well.</p>
| 1 | 2016-08-23T16:43:24Z | [
"python",
"hadoop",
"memory",
"apache-spark",
"pyspark"
] |
Heat maps of large data with pyplot slow | 38,961,252 | <p>I am working with a big set of data (240, 131000) and bigger. I am currently using the code below to plot this.</p>
<pre><code>fig,ax = pyplot.subplots()
spectrum = ax.pcolor(waterfallplot, cmap='viridis')
pyplot.colorbar()
pyplot.show()
</code></pre>
<p>However, it's taking a very long time (30 min+) and the plot... | 1 | 2016-08-15T18:57:41Z | 38,975,543 | <p><code>pcolorfast</code> works best for large arrays and updates quickly.</p>
| 0 | 2016-08-16T12:54:24Z | [
"python",
"performance",
"matplotlib",
"heatmap"
] |
Python variables not defined after if __name__ == '__main__' | 38,961,284 | <p>I'm trying to divvy up the task of looking up historical stock price data for a list of symbols by using <code>Pool</code> from the <code>multiprocessing</code> library. </p>
<p>This works great until I try to use the data I get back. I have my <code>hist_price</code> function defined and it outputs to a list-of-... | 1 | 2016-08-15T18:59:46Z | 38,961,389 | <p>I think there are two parts to your issue. The first is "what's wrong with <code>pcl</code> in the current code?", and the second is "why do I need the <code>if __name__ == "__main__"</code> guard block at all?".</p>
<p>Lets address them in order. The problem with the <code>pcl</code> variable is that it is only de... | 2 | 2016-08-15T19:06:42Z | [
"python",
"variables",
"multiprocessing",
"global",
"main"
] |
Python Requests module - proxy not working | 38,961,293 | <p>I'm trying to connect to website with python requests, but not with my real IP. So, I found some proxy on the internet and wrote this code:</p>
<pre><code>import requests
proksi = {
'http': 'http://5.45.64.97:3128'
}
x = requests.get('http://www.whatsmybrowser.org/', proxies = proksi)
print(x.text)
</code></p... | 0 | 2016-08-15T19:00:07Z | 38,961,568 | <p>The answer is quite simple. Although it is a proxy service, it doesn't guarantee 100% anonymity. When you send the HTTP GET request via the proxy server, the request sent by your program to the proxy server is:</p>
<pre><code>GET http://www.whatsmybrowser.org/ HTTP/1.1
Host: www.whatsmybrowser.org
Connection: keep-... | 0 | 2016-08-15T19:18:09Z | [
"python",
"proxy",
"python-requests"
] |
How do I create a string containing the filepath of my python program? | 38,961,327 | <p>We are creating a python program that executes specific macros within Polyworks based on user input into the program. Right now the code is:</p>
<pre><code>roto.command.CommandExecute('MACRO EXEC("C:\\RotoWorks\\Macros\\CentrifugalCompressor")')
</code></pre>
<p>However this assumes that our program is always inst... | 0 | 2016-08-15T19:02:44Z | 38,961,378 | <p>You can retrieve the path from the <code>__file__</code> attribute of the file. Use <code>os.path.abspath</code> on that attribute to retrieve the absolute path of the file and then <code>os.path.dirname</code> to retrieve the containing directory:</p>
<pre><code>import os
file_directory = os.path.dirname(os.path.... | 2 | 2016-08-15T19:06:19Z | [
"python",
"python-2.7"
] |
Use openpyxl to verify the structure of a spreadsheet | 38,961,360 | <p>I am working on a project that requires me to read a spreadsheet provided by the user and I need to build a system to check that the contents of the spreadsheet are valid. Specifically I want to validate that each column contains a specific datatype.</p>
<p>I know that this could be done by iterating over every cel... | 1 | 2016-08-15T19:05:20Z | 39,077,066 | <p>In openpyxl you'll have to go cell by cell.</p>
<p>You could use Excel's builtin Data Validation or Conditional Formatting, which openpyxl supports, for this. Let Excel do the work and talk to it using xlwings.</p>
| 2 | 2016-08-22T10:23:59Z | [
"python",
"excel",
"openpyxl"
] |
Use openpyxl to verify the structure of a spreadsheet | 38,961,360 | <p>I am working on a project that requires me to read a spreadsheet provided by the user and I need to build a system to check that the contents of the spreadsheet are valid. Specifically I want to validate that each column contains a specific datatype.</p>
<p>I know that this could be done by iterating over every cel... | 1 | 2016-08-15T19:05:20Z | 39,088,757 | <p>I ended up just manually looking at each cell. I have to read them all into my data structures before I can process anything anyways so it actually made sense to check then.</p>
| 1 | 2016-08-22T21:07:09Z | [
"python",
"excel",
"openpyxl"
] |
SQLAlchemy set default value for postgres JSON column | 38,961,396 | <p>I want to set the default value of my SQLAlchemy postgres JSON column to an empty dictionary. </p>
<pre><code>from sqlalchemy.dialects.postgresql import JSON
info = Column(JSON, default='{}')
info = Column(JSON, default={})
</code></pre>
<p>Neither of these work.</p>
| 0 | 2016-08-15T19:07:12Z | 38,999,937 | <p>Using default=lambda: {} works. Credit goes to univerio in the comments.</p>
| 0 | 2016-08-17T14:51:30Z | [
"python",
"json",
"postgresql",
"sqlalchemy"
] |
Python Script in Azure to Detect Vulnerable Ports | 38,961,402 | <p>I'm essentially trying to translate a Powershell script into a Python script. The script is used to scan all virtual machines within an Azure subscription. It checks to see if their ports are open to the world, and if they are, changes them to be open to only my machines. </p>
<p>The Powershell script is as follows... | 0 | 2016-08-15T19:07:21Z | 38,963,581 | <p>The Python package will allow you to do this is azure 2.0.0rc5:
<a href="https://pypi.python.org/pypi/azure/2.0.0rc5" rel="nofollow">https://pypi.python.org/pypi/azure/2.0.0rc5</a></p>
<p>Please note that this is a release candidate, but should be stable soon.</p>
<p>Even if not directly network oriented, this sam... | 0 | 2016-08-15T21:48:55Z | [
"python",
"powershell",
"azure"
] |
LogisticRegressionwithLBFGS throwing error about not supporting Mulitinomial Classification | 38,961,429 | <p>I am trying to implement Logistic Regression using pySpark
Here is my code</p>
<pre><code>from pyspark.mllib.classification import LogisticRegressionWithLBFGS
from time import time
from pyspark.mllib.regression import LabeledPoint
from numpy import array
RES_DIR="/home/shaahmed115/Pet_Projects/DA/TwitterStream_US... | 1 | 2016-08-15T19:09:16Z | 38,962,358 | <p>The error you see </p>
<blockquote>
<p>LogisticRegression with ElasticNet in ML package only supports binary
classification.</p>
</blockquote>
<p>is clear. You can use the <code>mllib</code> version to support multinomial:<br>
<code>org.apache.spark.mllib.classification.LogisticRegression</code></p>
<pre><co... | 1 | 2016-08-15T20:12:59Z | [
"python",
"machine-learning",
"pyspark",
"logistic-regression"
] |
how to write tests for a function using py3.5 os.scandir()? | 38,961,433 | <p>How to write tests to a function using the newly added to build-ins of python 3.5 <code>os.scandir()</code>?
Is there a helper to mock a <code>DirEntry</code> objects?</p>
<p>Any suggestions on how to mock <code>os.scandir()</code> of an empty folder and a folder with few 2 files for example?</p>
| 0 | 2016-08-15T19:09:32Z | 39,022,660 | <p>As suggested, my solution involves <code>@mock.patch()</code> decorator.
My test became something like:</p>
<pre><code>from django.test import TestCase, mock
from my_app.scan_files import my_method_that_return_count_of_files
mock_one_file = mock.MagicMock(return_value = ['one_file', ])
class MyMethodThatReturnCou... | 0 | 2016-08-18T15:54:18Z | [
"python",
"python-3.x",
"python-3.5",
"python-mock",
"python-os"
] |
Unicode in the standard TensorFlow format | 38,961,547 | <p>Following the documentation <a href="https://www.tensorflow.org/versions/r0.10/how_tos/reading_data/index.html#standard-tensorflow-format" rel="nofollow">here</a>, I am trying to create features from unicode strings. Here is what the feature creation method looks like,</p>
<pre><code>def _bytes_feature(value):
... | 0 | 2016-08-15T19:16:54Z | 38,961,670 | <p>BytesList <a href="https://github.com/tensorflow/tensorflow/blob/89e1cc59681b78e8193f899dca16474c19a7fc5b/tensorflow/core/example/feature.proto#L65" rel="nofollow">definition</a> is in feature.proto and it is of type <code>repeated bytes</code>, this means that you need to pass it something that's convertible to a l... | 0 | 2016-08-15T19:26:14Z | [
"python",
"unicode",
"tensorflow",
"protocol-buffers"
] |
Multiprocesses become zombie processes when increasing iterations. What is the advantage of mp.Queue() to Manager.list()? | 38,961,584 | <p>I'm trying to use multiprocessing to spawn 4 processes that brute force some calculations and each has a very small chance of manipulating a single list object on each iteration that I want to share between them. Not <a href="https://docs.python.org/2/library/multiprocessing.html#programming-guidelines" rel="nofollo... | 1 | 2016-08-15T19:19:23Z | 38,986,160 | <p><strong>Queue versus list</strong></p>
<p>Underneath the hood, a <code>multiprocessing.Queue</code> and a <code>manager.list()</code> are both writing to and reading from a buffer.</p>
<p><strong>Queue</strong></p>
<pre><code>shared_queue = multiprocessing.Queue()
</code></pre>
<p>When you call <code>put</code> ... | 1 | 2016-08-16T23:51:53Z | [
"python",
"python-2.7",
"multiprocessing"
] |
Pandas left join leads to column full of 'NaT' | 38,961,609 | <p>I'm just trying to merge two data frames, where the first one (the left in the left join) is <code>data</code>:</p>
<pre><code> userid date event
0 S3gFFFZtYF 2016-04-01 18:04:44.646000+00:00 goReview
1 9iYv7VWA3l 2016-04-01 18:07:43.461000+00:00 goReview
2 9iYv7... | 0 | 2016-08-15T19:21:31Z | 38,961,699 | <p>first things first. check your datatypes:</p>
<pre><code>last_use_date.userid.dtype
data.userid.dtype
</code></pre>
<p>are they equal? Then, replace <code>join</code> for <code>merge</code> instead, as your key is not in the index but in the columns of your dataframe. </p>
<pre><code>data.merge(last_use_date, on ... | 1 | 2016-08-15T19:27:53Z | [
"python",
"pandas"
] |
Pandas left join leads to column full of 'NaT' | 38,961,609 | <p>I'm just trying to merge two data frames, where the first one (the left in the left join) is <code>data</code>:</p>
<pre><code> userid date event
0 S3gFFFZtYF 2016-04-01 18:04:44.646000+00:00 goReview
1 9iYv7VWA3l 2016-04-01 18:07:43.461000+00:00 goReview
2 9iYv7... | 0 | 2016-08-15T19:21:31Z | 38,961,725 | <p><code>.join</code> joins by <em>index</em> by default, not by common columns. Use <code>.merge</code> instead:</p>
<pre><code>data.merge(last_use_date, left_on='userid', right_on='userid', sort=False, suffixes=('', '_right'))
</code></pre>
| 1 | 2016-08-15T19:29:53Z | [
"python",
"pandas"
] |
Python Code Error random script | 38,961,702 | <pre><code>import random, string
max_str_length = 20
while True:
random = ''.join(random.choice(string.lowercase) for _ in range(random.choice(range(1, max_str_length))))
print random
if random=="hugh":
print "Done"
</code></pre>
<p>What's the error here? It says "Attribute Error: 'str' object ... | -3 | 2016-08-15T19:28:40Z | 38,986,483 | <p>You define <code>random</code> as a string on the first line of your while loop, and then try to call a method on it that doesn't belong to <code>str</code>. Changing the name will fix your problem.</p>
| 1 | 2016-08-17T00:39:34Z | [
"python"
] |
How to release matplolib execution without closing window | 38,961,709 | <p>I want to show a series of images using <code>imshow()</code> and a <code>for</code> loop, but I want to wait for user input on the image (not on terminal) before continuing. The following does work but it requires closing the window, which is not optimal as my for loop has over a thousand iterations. How can I pu... | 0 | 2016-08-15T19:29:04Z | 38,961,781 | <p>Use:</p>
<pre><code>plt.ion()
plt.show()
</code></pre>
<p>before the loop, and remove <code>plt.close()</code> & <code>plt.show()</code> inside the loop.</p>
<p>To block the loop until a press event occurred add:</p>
<pre><code>f.canvas.start_event_loop(timeout=-1)
</code></pre>
<p>inside the loop</p>
| 0 | 2016-08-15T19:33:45Z | [
"python",
"user-interface",
"matplotlib"
] |
How to release matplolib execution without closing window | 38,961,709 | <p>I want to show a series of images using <code>imshow()</code> and a <code>for</code> loop, but I want to wait for user input on the image (not on terminal) before continuing. The following does work but it requires closing the window, which is not optimal as my for loop has over a thousand iterations. How can I pu... | 0 | 2016-08-15T19:29:04Z | 38,965,330 | <p>Actually, this turned out to be a repeated question:</p>
<p><a href="http://stackoverflow.com/questions/14325844/matplotlib-deliberately-block-code-execution-pending-a-gui-event">matplotlib: deliberately block code execution pending a GUI event</a></p>
<p>It is the mix of <code>f.canvas.start_event_loop(timeout=-1... | 1 | 2016-08-16T01:26:00Z | [
"python",
"user-interface",
"matplotlib"
] |
Python BST not working | 38,961,795 | <p>I'm new to Python thus the question,this is the implementation of my my BST</p>
<pre><code>class BST(object):
def __init__(self):
self.root = None
self.size = 0
def add(self, item):
return self.addHelper(item, self.root)
def addHelper(self, item, root):
if root is None:... | 0 | 2016-08-15T19:34:25Z | 38,961,882 | <p>Your add method probably shouldn't return a value. And you most certainly shouldn't assign the root of the tree to what the add method returns.</p>
<p>Try changing your main code to something like this:</p>
<pre><code>def main():
bst = BST()
bst.add(12)
bst.add(15)
bst.add(9)
bst.levelByLevel(... | -1 | 2016-08-15T19:41:05Z | [
"python",
"binary-search-tree"
] |
Python BST not working | 38,961,795 | <p>I'm new to Python thus the question,this is the implementation of my my BST</p>
<pre><code>class BST(object):
def __init__(self):
self.root = None
self.size = 0
def add(self, item):
return self.addHelper(item, self.root)
def addHelper(self, item, root):
if root is None:... | 0 | 2016-08-15T19:34:25Z | 38,962,262 | <p>Based on the following, you can see that <code>bst.root</code> in <code>None</code> after the second call to <code>add()</code>:</p>
<pre><code>>>> bst.root = bst.add(12)
>>> bst.root
<__main__.Node object at 0x7f9aaa29cfd0>
>>> bst.root = bst.add(15)
>>> type(bst.root)
<... | 1 | 2016-08-15T20:06:24Z | [
"python",
"binary-search-tree"
] |
Python BST not working | 38,961,795 | <p>I'm new to Python thus the question,this is the implementation of my my BST</p>
<pre><code>class BST(object):
def __init__(self):
self.root = None
self.size = 0
def add(self, item):
return self.addHelper(item, self.root)
def addHelper(self, item, root):
if root is None:... | 0 | 2016-08-15T19:34:25Z | 38,962,602 | <p>You're using the <code>BST</code> object basically only to hold a root <code>Node</code> and the <code>add</code> function doesn't really operate on the <code>BST</code> object so it's better to have only one class (<code>BtsNode</code>) and implement the <code>add</code> there. Try that and you'll see that the <cod... | 0 | 2016-08-15T20:32:50Z | [
"python",
"binary-search-tree"
] |
Python BST not working | 38,961,795 | <p>I'm new to Python thus the question,this is the implementation of my my BST</p>
<pre><code>class BST(object):
def __init__(self):
self.root = None
self.size = 0
def add(self, item):
return self.addHelper(item, self.root)
def addHelper(self, item, root):
if root is None:... | 0 | 2016-08-15T19:34:25Z | 38,962,685 | <p>If the <code>root</code> argument of your <code>addHelper</code> is <code>None</code>, you set it to a newly-created <code>Node</code> object and return it. If it is not, then you modify the argument but return nothing, so you end up setting <code>bst.root</code> to <code>None</code> again. Try the following with yo... | 2 | 2016-08-15T20:39:29Z | [
"python",
"binary-search-tree"
] |
cv2.phase gives the angle in radian | 38,961,957 | <p>I'm trying to get the orientation of the gradient through the Sobel function in opencv python. The problem is when I provide the gradient in the x and y direction to the phase function, it always gives me the same result, no matter phase in degree is true or False. Here is the sample code:</p>
<pre><code>img = cv2.... | 0 | 2016-08-15T19:46:04Z | 38,963,685 | <p>As you can see from the documentation <a href="http://docs.opencv.org/2.4/modules/core/doc/operations_on_arrays.html#phase" rel="nofollow">here</a> for cv2.phase:</p>
<pre><code>cv2.phase(x, y[, angle[, angleInDegrees]])
</code></pre>
<p>the third positional argument is not in fact for specifying degrees/radians, ... | 1 | 2016-08-15T21:57:35Z | [
"python",
"opencv"
] |
Why do I get null values from conditional statement? | 38,961,979 | <p>Thanks again for your patience, I am not the best communicator. Please let me know if there is any additional information that I should add.</p>
<p>My current data looks like:</p>
<pre><code>"Identifier","Status","OPENED","Resolv","closed_on","duplicate_on","junked_on","unproducible_on","verified_on"
"xx1","D","2... | 0 | 2016-08-15T19:47:20Z | 38,990,364 | <p>I made a quick code that basically gets the age using the status where if the status is not in the terminal, it will default to date today.</p>
<pre><code>def toDateTime(s): return dtt.strptime(s, '%Y-%m-%d')
def defect_age(row):
status_dict = {'R': 'Resolv', 'V': 'verified_on',
'D': 'duplicate_on',... | 1 | 2016-08-17T07:17:46Z | [
"python",
"pandas",
"conditional"
] |
10,000+ Point 3D Scatter Plots in Python (with Quick Rendering) | 38,962,015 | <p>Performance-wise, the following code snippet works perfectly fine for me when plotting in <code>mayavi</code>.</p>
<pre><code>import numpy as np
from mayavi import mlab
n = 5000
x = np.random.rand(n)
y = np.random.rand(n)
z = np.random.rand(n)
s = np.sin(x)**2 + np.cos(y)
mlab.points3d(x, y, z, s, colormap="RdYlB... | 2 | 2016-08-15T19:49:22Z | 39,205,127 | <p><a href="http://www.pyqtgraph.org/" rel="nofollow">PyQtGraph</a> is a much more performant plotting package, although not as "beautiful" as matplotlib or mayavi. It is made for number crunching and should therefore easily render points in the order of ten thousands.</p>
<p>As for <code>mayavi</code> and <code>matpl... | 1 | 2016-08-29T11:25:36Z | [
"python",
"matplotlib",
"mayavi",
"paraview"
] |
rendering matplotlib mathematical equations | 38,962,062 | <p>I am working to create a regression plot using a combination of Seaborn (to plot) and Statsmodels (to collect coefficients). The plotting function works fine, but I am attempting to add the linear regression equation to my plot using the <code>ax.text()</code> feature. However, I am having trouble getting the equa... | 0 | 2016-08-15T19:52:13Z | 38,962,188 | <p>You need to use <code>$...$</code> around your equation. As this</p>
<pre><code>import matplotlib.pyplot as plt
f, ax = plt.subplots(1,1)
# v v <-------- These two $-signs
label = 'y = %.2ex + %.2e\nr$^2$ = %.3f' % (10, 100, 0.01)
ax.text(0.5, 0.5, label, horizontalalignment = 'right... | 0 | 2016-08-15T20:01:40Z | [
"python",
"matplotlib"
] |
rendering matplotlib mathematical equations | 38,962,062 | <p>I am working to create a regression plot using a combination of Seaborn (to plot) and Statsmodels (to collect coefficients). The plotting function works fine, but I am attempting to add the linear regression equation to my plot using the <code>ax.text()</code> feature. However, I am having trouble getting the equa... | 0 | 2016-08-15T19:52:13Z | 39,154,546 | <p>I was able to get the desired end result by defining a function to convert a float into a latex readable format, which I adapted from <a href="http://stackoverflow.com/a/13490601/4995611" title="here">here</a>.</p>
<pre><code>def latex_float(f):
float_str = "{0:.3g}".format(f)
if "e" in float_str:
b... | 0 | 2016-08-25T20:52:22Z | [
"python",
"matplotlib"
] |
Automagically propagating deletion when using a bidirectional association_proxy | 38,962,124 | <p>I'm using a bidirectional <code>association_proxy</code> to associate properties <code>Group.members</code> and <code>User.groups</code>. I'm having issues with removing a member from <code>Group.members</code>. In particular, <code>Group.members.remove</code> will successfully remove an entry from <code>Group.membe... | 9 | 2016-08-15T19:56:51Z | 38,962,755 | <p>I discovered <a href="http://stackoverflow.com/a/4202016/344286">your problem</a> almost entirely by accident, as I was trying to figure out what's going on.</p>
<p>Because there wasn't any data in the db, I added a <code>session.commit()</code>. It turns out that (from the linked answer):</p>
<blockquote>
<p>Th... | 2 | 2016-08-15T20:43:49Z | [
"python",
"sqlalchemy"
] |
RDFLib Blank Node Printing | 38,962,190 | <p>I have an RDF dataset where triples are stored in N-Triples format like follows:</p>
<pre><code><http://ebola.ndssl.bi.vt.edu/country/1> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://ebola.ndssl.bi.vt.edu/vocab/country> .
_:AmapX3aXcountryX5fXcountryX5fXnameX5fXclassMapX40XX40X1 <ht... | 0 | 2016-08-15T20:01:46Z | 38,962,982 | <p>You (probably) can't. Blank node ids are local to the specific file they are in, they're not guaranteed preserved between different serializations. RDFLib simply replaces the id with its own new internal id. </p>
<p>Some tools have a parser setting to optionally preserve node ids. I don't know if RDFLib supports th... | 4 | 2016-08-15T20:59:59Z | [
"python",
"rdf",
"rdflib"
] |
python django: error using inline formset | 38,962,391 | <p>I have the following models:</p>
<pre><code>class Equipment(models.Model):
asset_number = models.CharField(max_length = 200)
serial_number = models.CharField(max_length = 200)
class Calibration(models.Model):
cal_asset = models.ForeignKey(Equipment, on_delete = models.CASCADE)
cal_by = models.CharF... | 0 | 2016-08-15T20:15:32Z | 38,963,499 | <p>Isn't it a missing closing parenthesis on this line?</p>
<pre><code> EquipmentInlineFormSet = inlineformset_factory(Equipment, Calibration, fields = ('cal_by', 'cal_dates', 'notes')
</code></pre>
| 0 | 2016-08-15T21:42:08Z | [
"python",
"django",
"django-forms"
] |
Splitting DataFrames in Apache Spark | 38,962,409 | <p>Using Apache Spark 2.0 with pyspark, I have a DataFrame containing 1000 rows of data and would like to split/slice that DataFrame into 2 separate DataFrames;</p>
<ul>
<li>The first DataFrame should contain the first 750 rows</li>
<li>The second DataFrame should contain the remaining 250 rows</li>
</ul>
<p>Note: a ... | 1 | 2016-08-15T20:16:51Z | 38,964,391 | <p>You are right to question using take because it draws the data to the driver and then createDataFrame redistributes it across the cluster. This is inefficient and may fail if your driver doesn't have enough memory to store the data.</p>
<p>Here's a solution that creates a row index column and slices on that:</p>
<... | 2 | 2016-08-15T23:18:11Z | [
"python",
"apache-spark",
"pyspark"
] |
VOLTTRON : Device communication aborted: segmentationNotSupported | 38,962,468 | <p>When running the <code>BACnet Proxy</code> and <code>MasterDriver</code> agents, I receive the following error message:</p>
<blockquote>
<p>master_driver.driver ERROR: Failed to scrape Device Name:
RuntimeError('Device communication aborted: segmentationNotSupported')</p>
</blockquote>
<p>Could anyone help me ... | 1 | 2016-08-15T20:22:15Z | 38,963,891 | <p>BACnet has a size limit for the size of a message. The message size has several different valid values based on the BACnet specification. If a device wants to send a message that exceeds the supported size of either device it may segment the message into smaller pieces. Both devices must support segmentation for thi... | 1 | 2016-08-15T22:19:09Z | [
"python",
"volttron"
] |
Seeing if an element from a 1D array is in another MD array | 38,962,479 | <pre><code>array1D = ['book', 'aa', 'Ab', 'AB']
arrayMD = ['ss', 'book', 'fd', '2'], ['sw', 'd'], ['we', 'wr']
</code></pre>
<p>How could I check to see if any element in array1D exists in arrayMD?</p>
<p>So far I just know of the find() method and that seems to only work for one element search.</p>
<p>Edit: I'd lik... | 0 | 2016-08-15T20:23:16Z | 38,962,515 | <p>Use <a href="https://docs.python.org/3/reference/expressions.html#membership-test-operations" rel="nofollow"><code>in</code></a>.</p>
<pre><code>for sublist in arrayMD:
for index, element in enumerate(sublist):
if element in array1D:
# Do something
</code></pre>
| 2 | 2016-08-15T20:26:15Z | [
"python",
"arrays",
"find"
] |
Seeing if an element from a 1D array is in another MD array | 38,962,479 | <pre><code>array1D = ['book', 'aa', 'Ab', 'AB']
arrayMD = ['ss', 'book', 'fd', '2'], ['sw', 'd'], ['we', 'wr']
</code></pre>
<p>How could I check to see if any element in array1D exists in arrayMD?</p>
<p>So far I just know of the find() method and that seems to only work for one element search.</p>
<p>Edit: I'd lik... | 0 | 2016-08-15T20:23:16Z | 38,962,687 | <pre><code>array1D = ['book', 'aa', 'Ab', 'AB']
arrayMD = [['ss', 'book', 'fd', '2'], ['sw', 'd'], ['we', 'wr']]
for word in array1D:
for arrindex, subarr in enumerate(arrayMD):
for wordindex, subword in enumerate(subarr):
if word == subword:
print(word, arrindex, wordindex)
... | 0 | 2016-08-15T20:39:35Z | [
"python",
"arrays",
"find"
] |
Seeing if an element from a 1D array is in another MD array | 38,962,479 | <pre><code>array1D = ['book', 'aa', 'Ab', 'AB']
arrayMD = ['ss', 'book', 'fd', '2'], ['sw', 'd'], ['we', 'wr']
</code></pre>
<p>How could I check to see if any element in array1D exists in arrayMD?</p>
<p>So far I just know of the find() method and that seems to only work for one element search.</p>
<p>Edit: I'd lik... | 0 | 2016-08-15T20:23:16Z | 38,962,730 | <p>If you are just wondering if the element is anywhere within the second 'array', then it is probably best to flatten it first which also has the advantage of being able to deal with arrays of any depth. This is most easily done with <code>numpy</code> if you aren't sure how deep the lists will be.</p>
<pre><code>im... | 1 | 2016-08-15T20:42:16Z | [
"python",
"arrays",
"find"
] |
Seeing if an element from a 1D array is in another MD array | 38,962,479 | <pre><code>array1D = ['book', 'aa', 'Ab', 'AB']
arrayMD = ['ss', 'book', 'fd', '2'], ['sw', 'd'], ['we', 'wr']
</code></pre>
<p>How could I check to see if any element in array1D exists in arrayMD?</p>
<p>So far I just know of the find() method and that seems to only work for one element search.</p>
<p>Edit: I'd lik... | 0 | 2016-08-15T20:23:16Z | 38,963,745 |
<pre><code>def check(list_md, list_1d):
def flatten(l, index=None):
"""
this function will flatten list_md recursively
getting only elements which where found
and return list of tuples
"""
for i, el in enumerate(l): # using enumerate to get index
_i... | 0 | 2016-08-15T22:03:36Z | [
"python",
"arrays",
"find"
] |
if else in a face detector with opencv | 38,962,582 | <p>Note I am a beginner. I made a script that analyzes a picture and places a box around any faces found in the image, that part works, What i need it to do is change the "faces" in "if faces = True" to something to the effect of If faces found = true, though I don't know what that would be, faces does nothing.</p>
<p... | -1 | 2016-08-15T20:30:40Z | 38,962,642 | <p>Use <code>faces</code> as the condition:</p>
<pre><code>if faces: # python types can be coerced to boolean
cv2.imshow("(1) Pamela Found" ,image)
else:
cv2.imshow("(0) Pamela's Found" ,image)
</code></pre>
<p>An empty list (or container) has a <em>falsy</em> value, while if a face was detected (i.e. <code>f... | 0 | 2016-08-15T20:35:57Z | [
"python",
"python-3.x",
"opencv"
] |
if else in a face detector with opencv | 38,962,582 | <p>Note I am a beginner. I made a script that analyzes a picture and places a box around any faces found in the image, that part works, What i need it to do is change the "faces" in "if faces = True" to something to the effect of If faces found = true, though I don't know what that would be, faces does nothing.</p>
<p... | -1 | 2016-08-15T20:30:40Z | 38,962,659 | <p>According to the documentation I found <a href="http://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html" rel="nofollow">in OpenCV</a> the faceCascade.detectMultiScale return a collection of <em>objects</em>.</p>
<p>To test is a collection (<code>list</code>, <code>set</code>, <code>tuple</code>... | 0 | 2016-08-15T20:37:04Z | [
"python",
"python-3.x",
"opencv"
] |
Python, pandas: how to extract values from a symmetric, multi-index dataframe | 38,962,618 | <p>I have a symmetric, multi-index dataframe from which I want to systematically extract data:</p>
<pre><code>import pandas as pd
df_index = pd.MultiIndex.from_arrays(
[["A", "A", "B", "B"], [1, 2, 3, 4]], names = ["group", "id"])
df = pd.DataFrame(
[[1.0, 0.5, 0.3, -0.4],
[0.5, 1.0, 0.9, -0.8],
[0.... | -3 | 2016-08-15T20:34:25Z | 38,962,711 | <p>is that what you want?</p>
<p>all elements above the diagonal:</p>
<pre><code>In [139]: df.values[np.triu_indices(len(df), 1)]
Out[139]: array([ 0.5, 0.3, -0.4, 0.9, -0.8, 0.1])
</code></pre>
<p>A_vals:</p>
<pre><code>In [140]: df.values[np.triu_indices(len(df), 1)][:-1]
Out[140]: array([ 0.5, 0.3, -0.4, 0.... | 0 | 2016-08-15T20:41:11Z | [
"python",
"pandas",
"numpy",
"dataframe",
"multi-index"
] |
Python, pandas: how to extract values from a symmetric, multi-index dataframe | 38,962,618 | <p>I have a symmetric, multi-index dataframe from which I want to systematically extract data:</p>
<pre><code>import pandas as pd
df_index = pd.MultiIndex.from_arrays(
[["A", "A", "B", "B"], [1, 2, 3, 4]], names = ["group", "id"])
df = pd.DataFrame(
[[1.0, 0.5, 0.3, -0.4],
[0.5, 1.0, 0.9, -0.8],
[0.... | -3 | 2016-08-15T20:34:25Z | 38,965,809 | <p>I don't assume <code>df</code> has the same columns and index. (Of course they can be the same). </p>
<pre><code>def extract_vals(group_label, df):
coord = [[i, j] for i in range(len(df)) for j in range(len(df)) if i<j and (df.index.get_level_values('group')[i] == group_label or df.columns.get_level_valu... | 1 | 2016-08-16T02:35:26Z | [
"python",
"pandas",
"numpy",
"dataframe",
"multi-index"
] |
Split pandas dataframe by column variable | 38,962,634 | <p>I've got a dataframe that I'd like to split by a column variable like the example below:</p>
<pre><code>gender height weight
male 42.8 157.5
male 41.3 165.6
female 48.4 144.2
</code></pre>
<p>My desired outcome is:</p>
<p><code>df_male</code></p>
<pre><code>gender height weight
male 42.8 157.5
... | 1 | 2016-08-15T20:35:23Z | 38,962,795 | <p>The following will produce a list containing one dataframe for each value of the <code>gender</code> column:</p>
<pre><code>import io
import pandas as pd
data = io.StringIO('''\
gender height weight
male 42.8 157.5
male 41.3 165.6
female 48.4 144.2
''')
df = pd.read_csv(data, delim_whitespace=True)
d... | 4 | 2016-08-15T20:46:26Z | [
"python",
"pandas",
"filtering"
] |
Serialize list of objects to JSON | 38,962,637 | <p>I am trying to serialize a list of objects.
I am making an HTTP API call. The call returns a list of objects (e.g. class A). I do not have access to the definition of class A.
I tried using dumps</p>
<pre><code>print ("Result is: %s", json.dumps(result_list.__dict__))
</code></pre>
<p>This prints an empty resu... | -1 | 2016-08-15T20:35:36Z | 38,963,137 | <p>Please specify more how the class of which <code>result_list</code> is an instance looks like (e.g. post the class code).
<code>json.dumps(result_list)</code> probably works not since <code>result_list</code> is not a plain dictionary, but an object of a class. You need to dump the variable that holds the data struc... | 0 | 2016-08-15T21:11:12Z | [
"python",
"json",
"serialization"
] |
Python - Django add username to QuerySet fields | 38,962,649 | <p>I have a problem since four days and I hope that anyone can help me.</p>
<p>I have a model class A, which has User as Foreign Key and other attributes:</p>
<p>class A(models.Model):</p>
<pre><code>user = models.ForeignKey(User)
....
</code></pre>
<p>In views.py:</p>
<pre><code>objects_as_json = serializers.seri... | 0 | 2016-08-15T20:36:25Z | 38,969,516 | <p>You can set the keyword argument <code>use_natural_foreign_keys</code> to <code>True</code>:</p>
<pre><code>objects_as_json = serializers.serialize(
'json',
classA.objects.filter(user_id=2).order_by("-date"),
use_natural_foreign_keys=True
)
</code></pre>
<p>Also <a href="https://docs.djangoproject.com/... | 1 | 2016-08-16T08:00:35Z | [
"python",
"django",
"python-2.7",
"django-queryset",
"username"
] |
Why do I need to keep a variable pointing to my QWidget? | 38,962,683 | <p>Why does the example below only work if the useless <code>_</code> variable is created?</p>
<p>The <code>_</code> variable is assigned and never used. I would assume a good compiler would optimize and not even create it, instead it does make a difference.</p>
<p>If I remove <code>_ =</code> and leave just <code>Te... | 5 | 2016-08-15T20:39:24Z | 38,962,809 | <p>That's a very good question and I've faced a lot of weird problems in the past because of this fact with my PyQt widgets and plugins, basically that happens thanks to the <a href="http://stackoverflow.com/questions/4484167/python-garbage-collector-documentation/4484312#4484312">python garbage collector</a>.</p>
<p>... | 3 | 2016-08-15T20:47:43Z | [
"python",
"pyqt4"
] |
Why do I need to keep a variable pointing to my QWidget? | 38,962,683 | <p>Why does the example below only work if the useless <code>_</code> variable is created?</p>
<p>The <code>_</code> variable is assigned and never used. I would assume a good compiler would optimize and not even create it, instead it does make a difference.</p>
<p>If I remove <code>_ =</code> and leave just <code>Te... | 5 | 2016-08-15T20:39:24Z | 38,962,903 | <p>@BPL is correct, but I wanted to add that you don't have to assign it to _. You can assign it to whatever variable you like. You just need a variable referencing to the object you created, otherwise it's collected by the garbage collector after being created.</p>
| 0 | 2016-08-15T20:54:06Z | [
"python",
"pyqt4"
] |
Functional Infix Implementation in Python | 38,962,846 | <p>I have a current implementation like this:</p>
<pre><code>class Infix(object):
def __init__(self, func):
self.func = func
def __or__(self, other):
return self.func(other)
def __ror__(self, other):
return Infix(partial(self.func, other))
def __call__(self, v1, v2):
return self.func(v1, v2)
@... | 2 | 2016-08-15T20:50:15Z | 38,963,030 | <p>If you don't mind dropping the final <code>|</code>, you could do </p>
<pre><code>class InfixR(object):
def __init__(self, func):
self.func = func
def __ror__(self, other):
return self.func(other)
def __call__(self, v1):
return self.func(v1)
@InfixR
def Unique(data):
return set(data)
</code></p... | 2 | 2016-08-15T21:03:59Z | [
"python",
"functional-programming"
] |
JSON from streamed data in Python | 38,962,888 | <p>I am simply trying to keep the following input and resulting JSON string in order.</p>
<p>Here is the input string and code:</p>
<pre><code>import json
testlist=[]
# we create a list as a tuple so the dictionary order stays correct
testlist=[({"header":{"stream":2,"function":3,"reply":True},"body": [({"format": "... | -1 | 2016-08-15T20:53:01Z | 38,964,022 | <p>As Laurent wrote your question is not very clear, but I give it a try:</p>
<p><code>OrderedDict.update</code> adds in the above case the entries of <code>databody</code> to the dictionary.
What you seem to want to do is something like <code>data['body'] = databody</code> where <code>databody</code> is this list
<c... | 0 | 2016-08-15T22:33:25Z | [
"python",
"jython-2.5"
] |
Is there a way to install all python modules at once using pip? | 38,962,947 | <p>I would like to install all available modules for Python 2.7.12 using a single pip command. Is there a way to do this without having to specify every single package name?</p>
| 0 | 2016-08-15T20:57:36Z | 38,963,343 | <p>I highly recommend against doing this - the overwhelmingly supported best practice is to use a requirements.txt file, listing the packages you want to install specifically.</p>
<p>You then install it with <code>pip install -r requirements.txt</code> and it installs all the packages for your project.</p>
<p>This ha... | 6 | 2016-08-15T21:28:50Z | [
"python",
"windows",
"ubuntu",
"pip"
] |
Is there a way to install all python modules at once using pip? | 38,962,947 | <p>I would like to install all available modules for Python 2.7.12 using a single pip command. Is there a way to do this without having to specify every single package name?</p>
| 0 | 2016-08-15T20:57:36Z | 39,045,649 | <p>This is a terrible idea, but you could always use <a href="https://github.com/mdipierro/autoinstaller" rel="nofollow">autoinstaller</a>, which will automatically download packages via <code>pip</code> if you don't have them installed.</p>
| 2 | 2016-08-19T18:30:49Z | [
"python",
"windows",
"ubuntu",
"pip"
] |
AWS Boto3 SQS MessageBody vs MessageAttributes | 38,963,001 | <p>I am setting up a SQS queue to ingest a block of config data to be processed by a backend container. My first idea was to <code>json.dumps</code> the dictionary with the config info and pass it through the <code>MessageBody</code> parameter of <code>sqsclient.send_message()</code>. However, after reading through the... | 0 | 2016-08-15T21:01:26Z | 38,964,763 | <blockquote>
<p>So if I understand correctly, the benefit is data type validation?</p>
</blockquote>
<p>No. </p>
<p>The benefit is that the metadata is essentially out-of-band: you can attach metadata -- information about the payload -- to the "outside" of an SQS message, without modifying (or even necessarily und... | 1 | 2016-08-16T00:06:18Z | [
"python",
"amazon-web-services",
"boto3"
] |
TypeError: super() takes at least 1 argument (0 given) error is specific to any python version? | 38,963,018 | <p>I'm getting this error</p>
<blockquote>
<p>TypeError: super() takes at least 1 argument (0 given)</p>
</blockquote>
<p>using this code on python2.7.11: </p>
<pre><code>class Foo(object):
def __init__(self):
pass
class Bar(Foo):
def __init__(self):
super().__init__()
Bar()
</code></pre>... | 1 | 2016-08-15T21:03:06Z | 38,963,433 | <p>You can use the <a href="https://pypi.python.org/pypi/future" rel="nofollow">future</a> library to have a Python2/Python3 compatibility.</p>
<p>The <a href="http://python-future.org/reference.html?highlight=super" rel="nofollow">super</a> function is back-ported.</p>
| 1 | 2016-08-15T21:35:46Z | [
"python",
"python-2.7",
"python-2.x"
] |
TypeError: super() takes at least 1 argument (0 given) error is specific to any python version? | 38,963,018 | <p>I'm getting this error</p>
<blockquote>
<p>TypeError: super() takes at least 1 argument (0 given)</p>
</blockquote>
<p>using this code on python2.7.11: </p>
<pre><code>class Foo(object):
def __init__(self):
pass
class Bar(Foo):
def __init__(self):
super().__init__()
Bar()
</code></pre>... | 1 | 2016-08-15T21:03:06Z | 38,964,291 | <p>Yes, the 0-argument syntax is specific to Python 3, see <a href="https://docs.python.org/3/whatsnew/3.0.html#builtins" rel="nofollow"><em>What's New in Python 3.0</em></a> and <a href="https://www.python.org/dev/peps/pep-3135/" rel="nofollow">PEP 3135 -- <em>New Super</em></a>.</p>
<p>In Python 2 and code that must... | 1 | 2016-08-15T23:03:56Z | [
"python",
"python-2.7",
"python-2.x"
] |
Python syntax error on mad libs | 38,963,038 | <p>So I'm trying to make a simple Mad Libs program and I'm getting multiple errors and I cannot figure out why. One of them is with the "Noah's First Program" part, and the other is with the printing of the story variable. How do I fix it?</p>
<pre><code>print "Noah's First Program!"
name=raw_input("Enter a name:")
a... | -2 | 2016-08-15T21:04:36Z | 38,963,125 | <p>It seems to be a Python 2.7 program.</p>
<p>But, if you use Python 2.7, you'll get syntax errors because <code>print</code> is not a statement but a function in Python 3: you need parenthesis.</p>
<p>Wrong:</p>
<pre><code>print "Noah's First Program!"
</code></pre>
<p>Good:</p>
<pre><code>print("Noah's First Pr... | -1 | 2016-08-15T21:10:30Z | [
"python",
"syntax"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.