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 |
|---|---|---|---|---|---|---|---|---|---|
Reference python object in an imported function | 39,239,398 | <p>I have two .py script files. The "main" script will import the second script containing misc "helper" functions.</p>
<p>In the main script, I have set up an object for a SPI interface. I would like to write functions in the imported file that use the SPI interface directly. I'm a noob at this and tried writing and ... | 3 | 2016-08-31T01:30:43Z | 39,239,431 | <p>By my lights the easiest thing to do would be to pass the spi object to the helper function as a parameter:</p>
<pre><code>def sendOtherStuff(spi):
otherData = ([... some different data ...])
return spi.xfer([otherData])
</code></pre>
<p>Once it's passed in, you can call methods on it in the body of the... | 3 | 2016-08-31T01:36:11Z | [
"python",
"object",
"import"
] |
How can I initialize an empty Numpy array with a given number of dimensions? | 39,239,425 | <p>I basically want to initialize an empty 6-tensor, like this:</p>
<pre><code>a = np.array([[[[[[]]]]]])
</code></pre>
<p>Is there a better way than writing the brackets explicitly?</p>
| 2 | 2016-08-31T01:35:08Z | 39,239,567 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html" rel="nofollow">empty</a> or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html" rel="nofollow">zeros</a>.</p>
<p>For example, to create a new array of 2x3, filled with zeros, use: <code>numpy.zeros(... | 3 | 2016-08-31T01:55:04Z | [
"python",
"arrays",
"numpy"
] |
How can I initialize an empty Numpy array with a given number of dimensions? | 39,239,425 | <p>I basically want to initialize an empty 6-tensor, like this:</p>
<pre><code>a = np.array([[[[[[]]]]]])
</code></pre>
<p>Is there a better way than writing the brackets explicitly?</p>
| 2 | 2016-08-31T01:35:08Z | 39,239,584 | <p>You could directly use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html" rel="nofollow"><code>ndarray</code></a> constructor:</p>
<pre><code>numpy.ndarray(shape=(1,) * 6)
</code></pre>
<p>Or the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html" rel="n... | 1 | 2016-08-31T01:57:59Z | [
"python",
"arrays",
"numpy"
] |
How can I initialize an empty Numpy array with a given number of dimensions? | 39,239,425 | <p>I basically want to initialize an empty 6-tensor, like this:</p>
<pre><code>a = np.array([[[[[[]]]]]])
</code></pre>
<p>Is there a better way than writing the brackets explicitly?</p>
| 2 | 2016-08-31T01:35:08Z | 39,239,597 | <blockquote>
<p>Iteratively adding rows of that rank-1 using np.concatenate(a,b,axis=0)</p>
</blockquote>
<p>Don't. Creating an array iteratively is slow, since it has to create a new array at each step. Plus <code>a</code> and <code>b</code> have to match in all dimensions except the concatenation one.</p>
<pre>... | 1 | 2016-08-31T01:59:20Z | [
"python",
"arrays",
"numpy"
] |
How can I initialize an empty Numpy array with a given number of dimensions? | 39,239,425 | <p>I basically want to initialize an empty 6-tensor, like this:</p>
<pre><code>a = np.array([[[[[[]]]]]])
</code></pre>
<p>Is there a better way than writing the brackets explicitly?</p>
| 2 | 2016-08-31T01:35:08Z | 39,239,615 | <p>You can do something like <code>np.empty(shape = [1] * (dimensions - 1) + [0])</code>.
Example:</p>
<pre class="lang-py prettyprint-override"><code>>>> a = np.array([[[[[[]]]]]])
>>> b = np.empty(shape = [1] * 5 + [0])
>>> a.shape == b.shape
True
</code></pre>
| 2 | 2016-08-31T02:00:58Z | [
"python",
"arrays",
"numpy"
] |
pandas string to numeric | 39,239,506 | <p>I have a set of data like</p>
<pre><code> a b
0 type 1 True
1 type 2 False
</code></pre>
<p>How can I keep the numerical part of column <code>a</code> and transfer ture to 1, false to zero at the same time. Below is what I want.</p>
<pre><code> a b
0 1 1
1 2 0
</code></pre>
| 0 | 2016-08-31T01:46:06Z | 39,239,518 | <p>You can convert Booleans to integers as follows:</p>
<pre><code>df['b'] = df.b.astype(int)
</code></pre>
<p>Depending on the nature of your text in Column <code>A</code>, you can do a few things:</p>
<p>a) Split on the space and take the second part (either string or int depending on your needs).</p>
<pre><code>... | 1 | 2016-08-31T01:47:34Z | [
"python",
"pandas",
"numeric"
] |
Tkinter - How to display image when clicking a button? | 39,239,620 | <p>First time here so forgive me as this is my FIRST attempt at making a silly GUI game (if you want to call it that). I'm trying to get the user to click a button and the image of their selection pops up. I can't seem to figure out how to get the image to pop up though.</p>
<p>Image does show if I run it separately.<... | 0 | 2016-08-31T02:01:12Z | 39,240,150 | <p>This works, but the actual image no longer shows, if I keep the PhotoImage OUT of the class it will print but I want to have it print IF they click the specific button: </p>
<pre><code>from Tkinter import *
root = Tk()
class PokemonClass(object):
def __init__(self, master):
frame = Frame(master)
... | 0 | 2016-08-31T03:11:48Z | [
"python",
"tkinter"
] |
Tkinter - How to display image when clicking a button? | 39,239,620 | <p>First time here so forgive me as this is my FIRST attempt at making a silly GUI game (if you want to call it that). I'm trying to get the user to click a button and the image of their selection pops up. I can't seem to figure out how to get the image to pop up though.</p>
<p>Image does show if I run it separately.<... | 0 | 2016-08-31T02:01:12Z | 39,260,672 | <p>You need to maintain a reference to your <code>PhotoImage</code> object. Unfortunately there is an inconsistency in tkinter in that attaching a <code>Button</code> to a parent widget increments the reference count, but adding an image to a widget does not increment the reference count. As a consequence at the moment... | 0 | 2016-08-31T23:46:53Z | [
"python",
"tkinter"
] |
How to interpolate only between values (stopping before and after last NaN in a column) with pandas? | 39,239,627 | <p>If I have a <code>df</code> similar to this one: </p>
<pre><code>print(df)
A B C D E
DATE_TIME
2016-08-10 13:57:00 3.6 A 1 NaN NaN
2016-08-10 13:58:00 4.7 A 1 4.5 NaN
2016-08-10 13:59:00 3.4 A 0 NaN 5.7
2016-08-10 14:00:00 3.5 A 0 NaN... | 1 | 2016-08-31T02:02:08Z | 39,239,708 | <p>You can backfill null values and then use boolean indexing to take the null values of each column (which must be the tail nulls).</p>
<pre><code>for col in ['D', 'E']:
idx = df[df[col].bfill().isnull()].index
df[col].ffill(inplace=True)
df.loc[idx, col] = None
</code></pre>
| 1 | 2016-08-31T02:14:41Z | [
"python",
"pandas",
"interpolation"
] |
How to interpolate only between values (stopping before and after last NaN in a column) with pandas? | 39,239,627 | <p>If I have a <code>df</code> similar to this one: </p>
<pre><code>print(df)
A B C D E
DATE_TIME
2016-08-10 13:57:00 3.6 A 1 NaN NaN
2016-08-10 13:58:00 4.7 A 1 4.5 NaN
2016-08-10 13:59:00 3.4 A 0 NaN 5.7
2016-08-10 14:00:00 3.5 A 0 NaN... | 1 | 2016-08-31T02:02:08Z | 39,240,280 | <p>You were very close! Here's an example to get the point across that's very similar to the code you posted toward the end of your post:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'A': [np.nan, 1.0, np.nan, np.nan, 4.0, np.nan, np.nan],
'B': [np.nan, np.nan, 0.0, np.n... | 1 | 2016-08-31T03:30:34Z | [
"python",
"pandas",
"interpolation"
] |
'admin' object has no attribute 'fileName' | 39,239,665 | <p>I'm trying to load my csv in QTableView and when I click on the button it gives this errorFile </p>
<blockquote>
<p>Zap Lunchies.py, line 61, in on_show_clicked
self.loadCsv(self.fileName)
AttributeError: 'admin' object has no attribute 'fileName'</p>
</blockquote>
<p>This is my <a href="http://pastebin.... | 0 | 2016-08-31T02:08:32Z | 39,240,674 | <p>Your <code>__init__</code> function for your <code>admin</code> class needs a line</p>
<pre><code>self.fileName = fileName
</code></pre>
| 0 | 2016-08-31T04:20:51Z | [
"python",
"csv",
"pyqt",
"qtableview"
] |
how to sum complicated condition in pandas dataframe | 39,239,667 | <p>I have dataframe below;</p>
<pre><code>df=pd.DataFrame(np.arange(1,19).reshape(6,3),columns=list('ABC'),index=list('acbabc'))
A B C
a 1 2 3
c 4 5 6
b 7 8 9
a 10 11 12
b 13 14 15
c 16 17 18
</code></pre>
<p>I would like to conditional summing dataframe shown as below;</p>
<pre><... | 2 | 2016-08-31T02:08:51Z | 39,239,680 | <p>Groupby <code>index</code> and <code>sum</code> the columns should give you what you need:</p>
<pre><code>df.groupby(df.index).sum()
# A B C
#a 11 13 15
#b 20 22 24
#c 20 22 24
</code></pre>
| 4 | 2016-08-31T02:11:06Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Move files listed in csv file? | 39,239,748 | <p>I have been trying to use the following code to move files that are listed in a csv list. But at most it will copy the last file in the list but not the rest.
I keep hitting this wall with every example I have seen listed what am I doing wrong?</p>
<p>My CVS list will have a list like: </p>
<pre><code>12355,12355.... | 1 | 2016-08-31T02:20:17Z | 39,239,863 | <p>I think doing something like this will work (untested):</p>
<pre><code>import os
import shutil
import csv
keys={}
with open('shuttle_image.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
for rowDict in reader:
keys[rowDict[0]] = rowDict[1]
print(rowDict) # if desired
valid_files = se... | 0 | 2016-08-31T02:32:55Z | [
"python",
"csv"
] |
Move files listed in csv file? | 39,239,748 | <p>I have been trying to use the following code to move files that are listed in a csv list. But at most it will copy the last file in the list but not the rest.
I keep hitting this wall with every example I have seen listed what am I doing wrong?</p>
<p>My CVS list will have a list like: </p>
<pre><code>12355,12355.... | 1 | 2016-08-31T02:20:17Z | 39,240,993 | <p>The reason why it's only the last file that could be copied (if it was) is because in this line:</p>
<pre><code> if file in rowDict[1]:
</code></pre>
<p>you are referencing <code>rowDict</code> outside of the first for-loop. So at that execution moment, it contains the last value of this loop.</p>
<p>If I und... | 0 | 2016-08-31T04:52:48Z | [
"python",
"csv"
] |
python ctypes link multiple shared library with example gsl gslcblas | 39,239,775 | <p>I want to use some functions from a shared library in python. From the python doc, I know ctypes is a good choice. However such library have some undefined symbols and I should link it to another shared library to get the symbols.</p>
<p>In g++, it is simple: g++ main.cpp -la -lb. The function I need is in liba.so,... | 0 | 2016-08-31T02:23:26Z | 39,445,587 | <p>This <a href="http://stackoverflow.com/a/30845750/5781248">old answer</a> tells to apply <code>mode=ctypes.RTLD_GLOBAL</code>, i.e. in this case</p>
<pre><code>import ctypes
dll1 = ctypes.CDLL('libgslcblas.so', mode=ctypes.RTLD_GLOBAL)
dll2 = ctypes.CDLL('libgsl.so')
</code></pre>
| 0 | 2016-09-12T07:48:33Z | [
"python",
"linker",
"ctypes",
"gsl",
"scalapack"
] |
updating labels using pylab / matplotlib when refreshing a graph | 39,239,823 | <p>I have some standard boiler plate code to draw a simple bar graph with a "count" label on top of each bar. I am live updating this bar graph as the data changes. I am able to successfully live update the graph. Here is the code : </p>
<pre><code>fig, ax = plt.subplots()
def my_graph():
y_pos = np.arange(len(dat... | 0 | 2016-08-31T02:29:10Z | 39,279,940 | <p>One option is to clear the axes each iteration with <a href="http://matplotlib.org/api/pyplot_api.html?highlight=clf#matplotlib.pyplot.cla" rel="nofollow">cla()</a>. Alternately you could store each text object and remove them when needed. </p>
<pre><code>t = ax.text(0.5,0.5,"label")
plt.pause(3)
t.remove()
fig.can... | 0 | 2016-09-01T19:58:31Z | [
"python",
"matplotlib"
] |
Using recursion, is it possible to set the initial input as a fixed letter so that it will not be affected as the process loops? | 39,240,051 | <p>Implement the function tree that takes a number of slices n and a rune as arguments, and generates a stack of runes (shape) scaled and overlayed on top of each other.</p>
<p>the shape at the top must be 1/n the size of the original shape. the shape at the second level must be 2/n the size of the original shape and ... | 1 | 2016-08-31T02:57:45Z | 39,240,285 | <p>What you can do is add a third parameter that will keep track of the original size, and have your arguments in your <code>overlay_frac()</code> function be based off of that variable, so that the values don't alter in recursion. Here's how I've done it:</p>
<pre><code>def tree(n, initial_size, shape):
a = initi... | 1 | 2016-08-31T03:31:29Z | [
"python"
] |
Using recursion, is it possible to set the initial input as a fixed letter so that it will not be affected as the process loops? | 39,240,051 | <p>Implement the function tree that takes a number of slices n and a rune as arguments, and generates a stack of runes (shape) scaled and overlayed on top of each other.</p>
<p>the shape at the top must be 1/n the size of the original shape. the shape at the second level must be 2/n the size of the original shape and ... | 1 | 2016-08-31T02:57:45Z | 39,241,362 | <p>Adding another parameter is certainly a feasible option. In the event that you under certain constraints and unable to change the formal parameters defined for the outer function, you may consider using a helper function as well.</p>
<pre><code>function tree(n, rune){
function drawTree(i) {
if (i === 1)... | 1 | 2016-08-31T05:23:59Z | [
"python"
] |
What is the difference between "Start-Process python ex.py" and "python ex.py" in powershell? | 39,240,080 | <p>I am learning powershell and trying to start a python service using the powershell IDE. I came to know I can start the python services either by one of these commands.</p>
<pre><code>Start-Process python example.py
python example.py
</code></pre>
<p>Though both of these gives the same result, I am curious to know... | 0 | 2016-08-31T03:01:16Z | 39,267,152 | <p>Both of them are calling python.exe .
As for the python.exe there is no difference to run .</p>
<p>During python installation , if you selected <strong><em>'add python to PATH'</em></strong> to add path of python.exe into environment variables ,then, you can run python.exe directly in PS .</p>
<p>If you didn't ch... | 0 | 2016-09-01T09:02:33Z | [
"python",
"powershell",
"powershell-v3.0"
] |
How to pass Numpy PyArray* via FFI | 39,240,146 | <p>Idea is to be able to modify array from library, like an "output" from a function.
Example:</p>
<pre><code>ffi.cdef("""
//Reads data from a file, and store in the numpy array
void read_image(PyArray* arr);
""")
C = ffi.dlopen('libimage.so')
image = np.array([], dtype=np.float32)
C.read_image(image)
assert ... | 1 | 2016-08-31T03:10:36Z | 39,243,270 | <p>You can't pass CPython-specific <code>PyXxx</code> structures via CFFI: you need to pass standard C data. Normally I'd answer that you need to design your cdef()'ed function with a standard C interface, for example something like:</p>
<pre><code>ffi.cdef("""
struct myimage_t {
int width, height;
... | 0 | 2016-08-31T07:25:55Z | [
"python",
"numpy",
"python-cffi"
] |
3.5 Python Interactive Quiz App Answer Check Not Working | 39,240,178 | <p>I'm trying to have only one defined function for this </p>
<blockquote>
<p>WELCOME TO Your Test</p>
<p>Word 1/5: Potato How many consanants does the word contain?</p>
<p>3</p>
<p>Correct!</p>
<p>Word 2/5: Potato How many vowels does the word contain?</p>
<p>1</p>
<p>Correct!</p>
... | 0 | 2016-08-31T03:15:27Z | 39,240,255 | <p>The problem is that you're expecting <a href="https://docs.python.org/3/library/functions.html#input" rel="nofollow"><code>input</code></a> to return you a <code>int</code> which it doesn't do on Python 3. Python 3 <code>input</code> works the same way as <a href="https://docs.python.org/2.7/library/functions.html#r... | 2 | 2016-08-31T03:26:54Z | [
"python",
"python-3.x",
"for-loop"
] |
request.session.get('last_visit') yields None all the time | 39,240,211 | <p>I am recently into session and cookies. I comprehend session and cookies well in theory but i have one issue in understanding the code of session. It is about getting the last_visit by the user. The code is
from the tangowithdjango.com </p>
<pre><code>def index(request):
context = RequestContext(request)
c... | 0 | 2016-08-31T03:19:50Z | 39,240,630 | <p>Move your <code>RequestContext</code> stuff to bottom </p>
<pre><code>def index(request):
#### NEW CODE ####
if request.session.get('last_visit'):
# The session has a value for the last visit
last_visit_time = request.session.get('last_visit')
visits = request.session.get('visits',... | 0 | 2016-08-31T04:15:05Z | [
"python",
"django",
"session",
"django-sessions"
] |
Preventing blender name indexing | 39,240,238 | <p>I'm using a python script to import and export wavefront obj files in Blender. The problem is that Blender adds an index to an object's name if an object with the same name was already added. For example <code>myObject</code> becomes <code>myObject.001</code> if there was already an object called <code>myObject</cod... | 0 | 2016-08-31T03:24:32Z | 39,244,433 | <p>Each item in blender must have a unique name within the list of items it belongs to (each name is a dictionary key) and will make a name unique by appending a numeric suffix based on the other items within the file, note that it is based on the file - not the scene, as a blend file can contain multiple scenes. Objec... | 1 | 2016-08-31T08:26:14Z | [
"python",
"blender"
] |
Remove element from itertools.combinations while iterating? | 39,240,242 | <p>Given a list <code>l</code> and all combinations of the list elements is it possible to remove any combination containing <code>x</code> while iterating over all combinations, so that you never consider a combination containing <code>x</code> during the iteration after it is removed?</p>
<pre><code>for a, b in iter... | 0 | 2016-08-31T03:25:11Z | 39,240,343 | <p>A cheap trick to accomplish this would be to filter by disjoint testing using a dynamically updated <code>set</code> of exclusion values, but it wouldn't actually avoid generating the combinations you wish to exclude, so it's not a major performance benefit (though <code>filter</code>ing using a C built-in function ... | 2 | 2016-08-31T03:38:33Z | [
"python",
"iterator",
"combinations"
] |
Remove element from itertools.combinations while iterating? | 39,240,242 | <p>Given a list <code>l</code> and all combinations of the list elements is it possible to remove any combination containing <code>x</code> while iterating over all combinations, so that you never consider a combination containing <code>x</code> during the iteration after it is removed?</p>
<pre><code>for a, b in iter... | 0 | 2016-08-31T03:25:11Z | 39,240,655 | <p>If you want to remove all tuples containing the number <code>x</code> from the list of combinations <code>itertools.combinations(l, 2)</code>, consider that you there is a one-to-one mapping (mathematically speaking) from the set <code>itertools.combinations([i for i in range(1,len(l)], 2)</code> to the <code>iterto... | 0 | 2016-08-31T04:18:51Z | [
"python",
"iterator",
"combinations"
] |
create matrix structure using pandas | 39,240,286 | <p>I have loaded the below CSV file containing code and coefficient data into the below dataframe df: </p>
<pre><code>CODE|COEFFICIENT
A|0.5
B|0.4
C|0.3
import pandas as pd
import numpy as np
df= pd.read_csv('cod_coeff.csv', delimiter='|', encoding="utf-8-sig")
</code></pre>
<p>giving</p>
<pre><code> ITEM ... | 3 | 2016-08-31T03:31:32Z | 39,240,436 | <p>You want to do the math between a vector and its tranposition. Transpose with <code>.T</code> and apply the matrix <code>dot</code> function between the two dataframes.</p>
<pre><code>df = df.set_index('CODE')
df.T
Out[10]:
CODE A B C
COEFFICIENT 0.5 0.4 0.3
df.dot(df.T)
Out[11]:
CODE ... | 4 | 2016-08-31T03:51:56Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
create matrix structure using pandas | 39,240,286 | <p>I have loaded the below CSV file containing code and coefficient data into the below dataframe df: </p>
<pre><code>CODE|COEFFICIENT
A|0.5
B|0.4
C|0.3
import pandas as pd
import numpy as np
df= pd.read_csv('cod_coeff.csv', delimiter='|', encoding="utf-8-sig")
</code></pre>
<p>giving</p>
<pre><code> ITEM ... | 3 | 2016-08-31T03:31:32Z | 39,242,054 | <p>numpy as a faster alternative</p>
<pre><code>pd.DataFrame(np.outer(df, df), df.index, df.index)
</code></pre>
<p><a href="http://i.stack.imgur.com/hHaPR.png" rel="nofollow"><img src="http://i.stack.imgur.com/hHaPR.png" alt="enter image description here"></a></p>
<hr>
<h3>Timing</h3>
<p><strong><em>Given sample<... | 5 | 2016-08-31T06:17:28Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
What is calculator mode? | 39,240,325 | <p>I don't know about the meaning of calculator mode in Python, and I've put the portion of documentation below.</p>
<blockquote>
<p>If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program,... | 4 | 2016-08-31T03:36:51Z | 39,241,144 | <p>Interactive mode or <strong>Calculator mode</strong>, is an interactive mode that comes with python. If you have installed python, then you have also, installed something called the <strong>Python Shell</strong>. </p>
<p>There are two ways you can access the Python Shell:</p>
<ul>
<li><p>Typing <code>python</code>... | 2 | 2016-08-31T05:06:07Z | [
"python"
] |
Django Admin: Determine correct image upload path | 39,240,329 | <p>I am new to Django and I am currently having problems in showing uploaded images in Django Admin. I have followed many posted Q and A here in stackoverflow but of those worked in my problem. I hope any active of the coding ninja here could help me with this problem. Here is the detailed view of the problem:</p>
<ol... | 0 | 2016-08-31T03:37:12Z | 39,253,944 | <p>As suspected, this problem is about URLs in Django. The problem occurred because I declared the following urlpattern in an app urls.py:</p>
<pre><code> url(r'', views.index, name='index'),
</code></pre>
<p>I solved the problem by changing the code to:</p>
<pre><code> url(r'^$', views.index, name='index'),... | 0 | 2016-08-31T15:46:46Z | [
"python",
"django",
"django-admin",
"django-urls",
"django-1.10"
] |
Dictionary Assigning multiple lists from input file from character | 39,240,340 | <p>I am trying to parse and then edit the text that lives between <code>{</code> and a <code>}</code>. The information is different(in between the curly braces) so I would need to be able to have these results separated in some type of buffer to test the /test and /example for each one.</p>
<p><strong>Information in f... | -1 | 2016-08-31T03:38:09Z | 39,242,785 | <p>Here's one method that splits the data into nested lists and then constructs a dict. I'm largely guessing at the desired data structure. Disclaimer: there is likely a more efficient way of doing this with regex, and this method isn't ideal if reading the entire file into memory is going to be an issue.</p>
<pre><co... | 0 | 2016-08-31T07:00:19Z | [
"python",
"dictionary"
] |
How to distribute a module with both a pure Python and Cython version | 39,240,463 | <p>I have a pure Python module and I want to rewrite some of submodules using Cython. Then I would like to add the new Cython submodules to the original Python module and make them available only as an option, meaning that cythoning the module is not compulsory (in which case the 'old' pure Python module should be used... | 2 | 2016-08-31T03:54:18Z | 39,641,724 | <p>I am not sure about your <code>setup.py</code> requirement (I donât know why you would need that) but as for the runtime import issue, I wrote a decorator to do just that:</p>
<pre><code>from __future__ import print_function
from importlib import import_module
from functools import wraps
import inspect
import sys... | 1 | 2016-09-22T14:23:20Z | [
"python",
"module",
"cython"
] |
How to distribute a module with both a pure Python and Cython version | 39,240,463 | <p>I have a pure Python module and I want to rewrite some of submodules using Cython. Then I would like to add the new Cython submodules to the original Python module and make them available only as an option, meaning that cythoning the module is not compulsory (in which case the 'old' pure Python module should be used... | 2 | 2016-08-31T03:54:18Z | 39,829,434 | <p>My solution was to set up the module like this:</p>
<pre><code>my_module
- __init_.py
- a.py
- b.py
- setup.py
cython_my_module
- __init_.py
- b.pyx
</code></pre>
<p>The <code>setup.py</code> would contain something similar to this:</p>
<pre><code>from distutils.core import set... | 1 | 2016-10-03T10:25:43Z | [
"python",
"module",
"cython"
] |
Matching substrings of a list from peewee(SQL) | 39,240,578 | <p>Say I have a list <code>str_list</code>, and now I want to get all entries from a table which matches any substring in the list. What's the correct way to do this? So I checked the operators provided by peewee, and there doesn't seem to be a easy way to do this. Looks like <code>.contains(substr)</code> is the way ... | 0 | 2016-08-31T04:08:46Z | 39,300,327 | <p>You can:</p>
<pre><code>import operator
class MyModel(Model):
field_to_check = TextField()
big_expression = reduce(operator.or_, [MyModel.field_to_check.contains(s) for s in str_list])
query = MyModel.select().where(big_expression)
</code></pre>
| 0 | 2016-09-02T20:34:07Z | [
"python",
"sql",
"database",
"peewee"
] |
Python syntax trailing semicolon | 39,240,672 | <p>So I know in python it's considered bad form to end statements with a ;
when not doing compound statements. and the use of such statements are considered bad form as well. I also understand the reasons to stick with the k.i.s.s. mentality an that since they aren't required it doesn't make sense to keep them. But si... | 1 | 2016-08-31T04:20:50Z | 39,240,725 | <p>It's purely a style thing. It's not going to hurt performance, and the worst weird edge case you'll run into is that this:</p>
<pre><code>do_whatever();;
# two of these^
</code></pre>
<p>is a syntax error.</p>
| 2 | 2016-08-31T04:25:58Z | [
"python",
"python-2.7"
] |
How run subprocess in Python 3 on windows for convert video? | 39,240,735 | <p>I have a little problem, I have trying for a lot time converted a video with FFMPEG in python 3 like this:</p>
<p>The model,</p>
<pre><code>class Video(models.Model):
name = models.CharField(max_length=200, null=False)
state = models.CharField(max_length=30, null=False)
user_email = models.CharField(max_l... | 2 | 2016-08-31T04:27:20Z | 39,241,860 | <p>The file not found is file "ffmpeg".
Try to enter file with path and extension : c:\Program Files\ffmpeg\ffmpeg.exe</p>
<p>Best Regard
Emmanuel</p>
| 1 | 2016-08-31T06:04:25Z | [
"python",
"django",
"python-3.x",
"cmd",
"ffmpeg"
] |
How to use GTK Champlain with local .osm tiles in my computer? | 39,240,757 | <p>I'm trying to make a GPS application in python, and I'm using GTK-Champlain as a widget using also Clutter. But right now I'm having problems trying to use a local tiles file I downloaded from OpenStreetMaps. Watch this:</p>
<pre><code> class LauncherGTK:
def __init__(self):
self.window = Gtk.Window... | 0 | 2016-08-31T04:29:13Z | 39,241,367 | <p>PyGObject-based bindings <a href="https://lazka.github.io/pgi-docs/Champlain-0.12/enums.html" rel="nofollow">drop the enum name from the enum values themselves</a>. In your case, your code should be using <code>Champlain.MapProjection.MERCATOR</code>, not <code>Champlain.MapProjection.MAP_PROJECTION_MERCATOR</code>.... | 0 | 2016-08-31T05:24:09Z | [
"python",
"widget",
"gtk",
"openstreetmap"
] |
How to create filtered DataFrame with minimum code | 39,240,820 | <p>There are four cars: <code>bmw</code>, <code>geo</code>, <code>vw</code> and <code>porsche</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'car': ['bmw','geo','vw','porsche'],
'warranty': ['yes','yes','yes','no'],
'dvd': ['yes','yes','no','yes'],
'sunroof': ['yes','no','n... | 4 | 2016-08-31T04:35:50Z | 39,240,928 | <p>You can use simple for <code>loop</code> with <code>enumerate</code>:</p>
<pre><code>cars_with_all_three = []
for ind, car in enumerate(df['car']):
if df['dvd'][ind] == df['warranty'][ind] == df['sunroof'][ind] == 'yes':
cars_with_all_three.append(car)
</code></pre>
<p>If you do <code>print(cars_with_a... | 3 | 2016-08-31T04:46:57Z | [
"python",
"pandas",
"indexing",
"dataframe",
"condition"
] |
How to create filtered DataFrame with minimum code | 39,240,820 | <p>There are four cars: <code>bmw</code>, <code>geo</code>, <code>vw</code> and <code>porsche</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'car': ['bmw','geo','vw','porsche'],
'warranty': ['yes','yes','yes','no'],
'dvd': ['yes','yes','no','yes'],
'sunroof': ['yes','no','n... | 4 | 2016-08-31T04:35:50Z | 39,241,195 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>print ((df.dvd == 'yes') & (df.sunroof == 'yes') & (df.warranty == 'yes'))
0 True
1 False
2 False
3 False
dtype: bool
print (df[(df.... | 4 | 2016-08-31T05:09:50Z | [
"python",
"pandas",
"indexing",
"dataframe",
"condition"
] |
How to create filtered DataFrame with minimum code | 39,240,820 | <p>There are four cars: <code>bmw</code>, <code>geo</code>, <code>vw</code> and <code>porsche</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'car': ['bmw','geo','vw','porsche'],
'warranty': ['yes','yes','yes','no'],
'dvd': ['yes','yes','no','yes'],
'sunroof': ['yes','no','n... | 4 | 2016-08-31T04:35:50Z | 39,241,235 | <p>Try this: </p>
<pre><code>df = df.set_index('car')
df[df[[ u'dvd', u'sunroof', u'warranty']] == "yes"].dropna().reset_index()
df
car dvd sunroof warranty
0 bmw yes yes yes
df = df.set_index('car')
df[df[[ u'dvd', u'sunroof', u'warranty']]== "yes"].dropna().index.values
['bmw']
</code></pre>
| 3 | 2016-08-31T05:12:51Z | [
"python",
"pandas",
"indexing",
"dataframe",
"condition"
] |
An Income Tax program in Python | 39,240,884 | <p>I have been trying to solve a coding lab exercise but I keep getting errors in my program. Kindly help look at this code and tell me what's wrong with it.</p>
<p><strong>Question:</strong></p>
<blockquote>
<p>Country X calculates tax for its citizens using a graduated scale rate as shown below:</p>
<p>Yearl... | 1 | 2016-08-31T04:42:42Z | 39,240,941 | <p>You have not defined or assigned a value to the variable <code>income</code> anywhere in the code.</p>
<p>In your code,</p>
<pre><code>def calculate_tax(income_input):
for key in income_input.keys():
income=income_input[key]
....
</code></pre>
| 1 | 2016-08-31T04:48:08Z | [
"python"
] |
An Income Tax program in Python | 39,240,884 | <p>I have been trying to solve a coding lab exercise but I keep getting errors in my program. Kindly help look at this code and tell me what's wrong with it.</p>
<p><strong>Question:</strong></p>
<blockquote>
<p>Country X calculates tax for its citizens using a graduated scale rate as shown below:</p>
<p>Yearl... | 1 | 2016-08-31T04:42:42Z | 39,241,056 | <p>Please check the code below :</p>
<ul>
<li>You are trying to access income outside function. So you are getting error </li>
<li>According to question, you need to create new dictionary for calculated tax with same keys as income dictionary and return it.</li>
</ul>
<p></p>
<pre><code>def calculate_tax(income_dic... | 0 | 2016-08-31T04:58:37Z | [
"python"
] |
An Income Tax program in Python | 39,240,884 | <p>I have been trying to solve a coding lab exercise but I keep getting errors in my program. Kindly help look at this code and tell me what's wrong with it.</p>
<p><strong>Question:</strong></p>
<blockquote>
<p>Country X calculates tax for its citizens using a graduated scale rate as shown below:</p>
<p>Yearl... | 1 | 2016-08-31T04:42:42Z | 39,241,704 | <h3>Separating data and code</h3>
<p>You can do this in a more flexibel way, and a bit shorter than the verbose <code>if -elif</code> -series.</p>
<p>This will split the <em>data</em> and the <em>code</em> making it possible to easily change the tax ranges and rates (defined in ranges and the top- rate/income) withou... | 0 | 2016-08-31T05:52:33Z | [
"python"
] |
An Income Tax program in Python | 39,240,884 | <p>I have been trying to solve a coding lab exercise but I keep getting errors in my program. Kindly help look at this code and tell me what's wrong with it.</p>
<p><strong>Question:</strong></p>
<blockquote>
<p>Country X calculates tax for its citizens using a graduated scale rate as shown below:</p>
<p>Yearl... | 1 | 2016-08-31T04:42:42Z | 39,279,984 | <p>am having the same problem with my code. the solution has to pass all the tests including the hidden ones. with hidden i mean your code might pass all the tests and it might still not submitt due to failure of hidden tests. the syntax of the program could be right but the intended outcome of the program could be wro... | 0 | 2016-09-01T20:01:40Z | [
"python"
] |
An Income Tax program in Python | 39,240,884 | <p>I have been trying to solve a coding lab exercise but I keep getting errors in my program. Kindly help look at this code and tell me what's wrong with it.</p>
<p><strong>Question:</strong></p>
<blockquote>
<p>Country X calculates tax for its citizens using a graduated scale rate as shown below:</p>
<p>Yearl... | 1 | 2016-08-31T04:42:42Z | 39,297,741 | <pre><code>def calculate_tax(income_input="dictionary", data= {"Alex": 500, "James": 20500, "Kinuthia": 70000}):
for item in income_input():
if (income_input >= 0) and (income_input <= 1000):
tax = (0*income_input)
elif (income_input > 1000) and (income_input <= 10000):
... | 0 | 2016-09-02T17:19:24Z | [
"python"
] |
An Income Tax program in Python | 39,240,884 | <p>I have been trying to solve a coding lab exercise but I keep getting errors in my program. Kindly help look at this code and tell me what's wrong with it.</p>
<p><strong>Question:</strong></p>
<blockquote>
<p>Country X calculates tax for its citizens using a graduated scale rate as shown below:</p>
<p>Yearl... | 1 | 2016-08-31T04:42:42Z | 39,307,567 | <p>@KaiserPhemi
Its not a lab platform issue. Your code is not catching the errors it is supposed to catch. I've passed that test. Here's an algorithm that works:</p>
<pre><code>def calculate_tax(people):
while True:
try:
iterating_people = people.keys()
for key in i... | 3 | 2016-09-03T13:41:09Z | [
"python"
] |
An Income Tax program in Python | 39,240,884 | <p>I have been trying to solve a coding lab exercise but I keep getting errors in my program. Kindly help look at this code and tell me what's wrong with it.</p>
<p><strong>Question:</strong></p>
<blockquote>
<p>Country X calculates tax for its citizens using a graduated scale rate as shown below:</p>
<p>Yearl... | 1 | 2016-08-31T04:42:42Z | 39,313,120 | <p>Thanks everyone. I've been able to solve this. As rightly pointed out by @Eke Enyinnaya Nelson, I need to catch the errors.</p>
<p><strong>Final Code</strong></p>
<pre><code> def calculate_tax(payroll):
while True:
try:
for key in payroll.keys():
income = payroll... | 0 | 2016-09-04T02:50:19Z | [
"python"
] |
An Income Tax program in Python | 39,240,884 | <p>I have been trying to solve a coding lab exercise but I keep getting errors in my program. Kindly help look at this code and tell me what's wrong with it.</p>
<p><strong>Question:</strong></p>
<blockquote>
<p>Country X calculates tax for its citizens using a graduated scale rate as shown below:</p>
<p>Yearl... | 1 | 2016-08-31T04:42:42Z | 39,548,620 | <p>my own code which is very much correct and the fastest way to write this function is by recursively calculating total tax per person
here is what i get below
Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, AttributeError("'_AssertRaisesContext' object ha... | 0 | 2016-09-17T15:37:05Z | [
"python"
] |
An Income Tax program in Python | 39,240,884 | <p>I have been trying to solve a coding lab exercise but I keep getting errors in my program. Kindly help look at this code and tell me what's wrong with it.</p>
<p><strong>Question:</strong></p>
<blockquote>
<p>Country X calculates tax for its citizens using a graduated scale rate as shown below:</p>
<p>Yearl... | 1 | 2016-08-31T04:42:42Z | 39,889,225 | <p><strong>If you were to run just the Script alone, This Could Work</strong></p>
<pre><code>def calculate_tax(d):
d1={}#Dictionary for calculated tax
income=0#Value to deduct tax from(Value in income dictionary)
"""cheking for Key pairs"""
while True:
try:
d1=d.keys()
... | 0 | 2016-10-06T06:43:31Z | [
"python"
] |
MINGW64 run 'virtualenv venv' AssertionError | 39,240,916 | <p>here.
$ virtualenv just_test</p>
<pre><code> Traceback (most recent call last):
File "C:\Python27\Lib\runpy.py", line 174, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "C:\Python27\Lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "C:\Python27\Scripts\virtua... | 0 | 2016-08-31T04:45:52Z | 39,260,785 | <p>Finally I found an ugly solution as follow:</p>
<p>Win + X -> Click Command Prompt(admin)
run</p>
<pre><code> c:\Python27\python.exe C:\Python27\Lib\site-packages\virtualenv.py venv
</code></pre>
<p>venv is your virtual enviroment name.</p>
| 0 | 2016-09-01T00:00:54Z | [
"python",
"mingw",
"virtualenv"
] |
Apache & mod_wsgi settings for Django Python Project | 39,240,964 | <p>I am trying to setup my django-python project on Google Compute Engine Debian8 VM. I made few config changes in <code>/etc/apache2/sites-available/000-default.conf & /etc/apache2/sites-available/default-ssl.conf</code> files
Then tried to restart the server. And I got following Errors. Uninstalling & reinsta... | 0 | 2016-08-31T04:50:02Z | 39,241,028 | <p>Have you read the error ? It's clearly stated why it fails:</p>
<blockquote>
<p>Cannot load /usr/lib/apache2/modules/mod_wsgi.so into server: /usr/lib/apache2/modules/mod_wsgi.so: cannot open shared object file: <strong>No such file or directory</strong></p>
</blockquote>
<p>do you have <code>libapache2-mod-wsgi... | 0 | 2016-08-31T04:56:06Z | [
"python",
"django",
"apache",
"google-compute-engine"
] |
Apache & mod_wsgi settings for Django Python Project | 39,240,964 | <p>I am trying to setup my django-python project on Google Compute Engine Debian8 VM. I made few config changes in <code>/etc/apache2/sites-available/000-default.conf & /etc/apache2/sites-available/default-ssl.conf</code> files
Then tried to restart the server. And I got following Errors. Uninstalling & reinsta... | 0 | 2016-08-31T04:50:02Z | 39,241,438 | <p>Ran the Command to see the process running on port 80:</p>
<pre><code>sudo netstat -ltnp | grep ':80'
</code></pre>
<p>Output:</p>
<pre><code>tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 24482/nginx -g daem
tcp6 0 0 :::80 :::* LIST... | 0 | 2016-08-31T05:30:17Z | [
"python",
"django",
"apache",
"google-compute-engine"
] |
Python Highlight specific text in json document on terminal | 39,240,990 | <p>I am interested in highlighting a specific portion of the json document based on some arbitrary matching algorithm. For example</p>
<pre><code>{
"text" : "hello world"
}
</code></pre>
<p>I searched for "hello" and above json document has hello in it. How to highlight that particular portion "hello" while display... | 0 | 2016-08-31T04:52:25Z | 39,241,134 | <p>I can't comment :(</p>
<p>The answer here might be able to help you: <a href="http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python">Print in terminal with colors using Python?</a></p>
<p>For example, you could use termcolor (if you are using a linux style terminal) and replace "hell... | 2 | 2016-08-31T05:04:49Z | [
"python",
"json",
"pprint"
] |
How to import a local python module when using the sbatch command in SLURM | 39,241,032 | <p>I was using the cluster manager <a href="http://slurm.schedmd.com/" rel="nofollow">slurm</a> and I was running a submission script with sbatch (with a python interpeter). The sbatch submission imported one of my modules called <code>main_nn.py</code>. The module is located in the same place as my submission director... | 0 | 2016-08-31T04:56:20Z | 39,574,373 | <p>As Slurm copies the submission script to a specific location on the compute node to run it, your Python script will not find the modules that are in the submission directory.</p>
<p>But Slurm correctly sets the current working directory so you can explicitly add it to the python path with something like:</p>
<pre>... | 0 | 2016-09-19T13:26:04Z | [
"python",
"slurm"
] |
How do I use modules in Django? | 39,241,133 | <p>I'm trying to display a graph on a web page. I can get the graph to show up with a simple example that only uses functions defined within the function. However, I want to be able to expand it further. In my original code, I have one main 'graphing' function that uses the functions of other modules so that it stays o... | -3 | 2016-08-31T05:04:42Z | 39,241,892 | <p>use " from 'where' import 'what'"</p>
<p>so may be like "from . import graphing" if its in the same directory</p>
| 0 | 2016-08-31T06:06:39Z | [
"python",
"django",
"matplotlib"
] |
How would Auth work between Django and Discourse (working together) | 39,241,151 | <p>I need a modern looking forum solution that is self hosted (to go with a django project)</p>
<p>The only reasonable thing I can see using is discourse, but that gives me a problem... How can I take care of auth between the two? It will need to be slightly deeper than just auth because I will need a few User tables ... | 1 | 2016-08-31T05:06:32Z | 39,243,456 | <p>That sounds plausible. To make sure a user is logged in to both, you may put one of the auths in front of the other. For example, if discourse is in front of Django, you can use something like the builtin RemoteUserMiddleware. </p>
<p>In general, if they are going to be hosted on different domains, take a look at J... | 0 | 2016-08-31T07:36:41Z | [
"python",
"django",
"discourse"
] |
do I need lock to protect python 2.7 list in multi-threaded environment? | 39,241,226 | <p>Wondering if we need lock on a Python list if multiple threads needs to access (read/write/get size)? Using Python 2.7 on Mac.</p>
<p>I have written a prototype to add a lock to protect the list. Not sure if necessary or any issues (for both performance and functional) in my code? Thanks.</p>
<p>BTW, I have the sa... | 1 | 2016-08-31T05:12:04Z | 39,241,681 | <p>Your <code>checkOutStatus</code> method requires a lock to work properly; the other methods do not since they are performing atomic operations (simple Python statement are atomic, see this <a href="http://effbot.org/zone/thread-synchronization.htm" rel="nofollow">reference</a>). Without a lock in checkOutStatus, th... | 1 | 2016-08-31T05:50:27Z | [
"python",
"multithreading",
"python-2.7"
] |
How to aggregate QuerySet based on property of model? | 39,241,267 | <p>For example some model:</p>
<pre><code>class Foo(models.Model):
a = models.FloatField()
b = models.FloatField()
@property
def c(self):
return self.a / self.b
</code></pre>
<p>And we want to find minimal value in QuerySet:</p>
<pre><code>bar = Foo.objects.aggregate(Min('c'))
</code></pre>
... | 0 | 2016-08-31T05:16:27Z | 39,241,355 | <p>You have to do the logic inside the query itself instead of as a property that is evaluated in Python. Something like this should work:</p>
<pre><code>from django.db.models import F, Min
bar = Foo.objects.annotate(c=F('a') / F('b')).aggregate(Min('c'))
</code></pre>
| 2 | 2016-08-31T05:23:20Z | [
"python",
"django",
"django-queryset"
] |
Performing complex conditional operation on numpy arrays | 39,241,282 | <pre><code>import numpy as np
mat_a = np.random.random((5, 5))
mat_b = np.random.random((5, 5))
mat_c = np.random.random((5, 5))
</code></pre>
<p>Lets say for a specific grid cell, the values in the same position in the 3 arrays are as follows:<br>
<code>mat_a, A = 0.3</code><br>
<code>mat_b, B = 0.2</code><br>
<code... | 2 | 2016-08-31T05:17:30Z | 39,241,557 | <p>One solution is to calculate all values, replace unwanted ones with zeros.</p>
<pre><code>mat_a = np.random.random((5, 5))
mat_b = np.random.random((5, 5))
mat_c = np.random.random((5, 5))
bigmat = np.stack((mat_a, mat_b, mat_c)) # this is a 3, 5, 5 array
minima = np.argmin(bigmat, axis=0) # contains a 5x5 array of... | 2 | 2016-08-31T05:42:22Z | [
"python",
"numpy"
] |
Pandas .dropna() on specify attribute | 39,241,346 | <p>I have this code to drop null values from column Type, specifically looking at Dog.</p>
<pre><code>cd.loc[cd['Type'] == 'Dog'].dropna(subset = ['Killed'], inplace = True)
</code></pre>
<p>I would like to dropna when the ['Killed'] column associating with Type = Dog has NaN value.</p>
<p>The code above generate th... | 3 | 2016-08-31T05:22:31Z | 39,241,397 | <p>It sounds like what you are saying is you want to remove rows where Type is "Dog" and Killed is <code>NaN</code>. So just select the negation of that condition:</p>
<pre><code>cd = cd.loc[~((cd.Type=="Dog") & cd.Killed.isnull())]
</code></pre>
| 3 | 2016-08-31T05:27:02Z | [
"python",
"pandas"
] |
Pandas .dropna() on specify attribute | 39,241,346 | <p>I have this code to drop null values from column Type, specifically looking at Dog.</p>
<pre><code>cd.loc[cd['Type'] == 'Dog'].dropna(subset = ['Killed'], inplace = True)
</code></pre>
<p>I would like to dropna when the ['Killed'] column associating with Type = Dog has NaN value.</p>
<p>The code above generate th... | 3 | 2016-08-31T05:22:31Z | 39,241,708 | <p>Very similar to @BrenBarn's answer but using <code>drop</code> and <code>inplace</code></p>
<pre><code>cd.drop(cd[(cd.Type == 'Dog') & (cd.Killed.isnull())].index, inplace=True)
</code></pre>
<h3>Setup</h3>
<pre><code>cd = pd.DataFrame([
['Dog', 'Yorkie'],
['Cat', 'Rag Doll'],
['Cat', ... | 3 | 2016-08-31T05:53:12Z | [
"python",
"pandas"
] |
Dynamic update instance on Django REST Framework | 39,241,385 | <p>Hi I'm trying to update dynamically using custom method update Django REST Framework like this:</p>
<p><strong>serializers.py</strong></p>
<pre><code>class ArtistSerializer(serializers.Serializer):
id = serializers.IntegerField(required=False)
name = serializers.CharField(max_length=100, required=True)
... | 0 | 2016-08-31T05:25:48Z | 39,241,456 | <p>Use <code>setattr(instance, "name", value)</code> instead:</p>
<pre><code>setattr(instance, "name", self.validated_data.get('name', instance.name))
</code></pre>
<p>It's not possible to change django object attributes by "item assignments" indeed.</p>
| 1 | 2016-08-31T05:31:58Z | [
"python",
"django",
"django-rest-framework"
] |
Only cache 200 with scrapy | 39,241,476 | <p>I am using <code>scrapy.downloadermiddlewares.httpcache.HttpCacheMiddleware</code> to cache scrapy requests. I'd like it to only cache if status is 200. Is that the default behavior? Or do I need to specify <code>HTTPCACHE_IGNORE_HTTP_CODES</code> to be everything <em>except</em> 200?</p>
| 2 | 2016-08-31T05:34:05Z | 39,242,636 | <p>Yes, by default <code>HttpCacheMiddleware</code> run a <code>DummyPolicy</code> for the requests. It pretty much does nothing special on it's own so you need to set <code>HTTPCACHE_IGNORE_HTTP_CODES</code> to everything except 200.</p>
<p><a href="https://github.com/scrapy/scrapy/blob/master/scrapy/extensions/httpc... | 0 | 2016-08-31T06:51:46Z | [
"python",
"scrapy"
] |
Python: simple way to increment by alternating values? | 39,241,505 | <p>I am building a list of integers that should increment by 2 alternating values. </p>
<p>For example, starting at 0 and alternating between 4 and 2 up to 20 would make:</p>
<pre><code>[0,4,6,10,12,16,18]
</code></pre>
<p>range and xrange only accept a single integer for the increment value. What's the simplest way... | 4 | 2016-08-31T05:36:54Z | 39,241,555 | <pre><code>l = []
a = 0
for i in xrnage (N) :
a += 2
if i&1 == 0 :
a+=2
l.append (a)
</code></pre>
<p>Looks simple enough to me.</p>
| 1 | 2016-08-31T05:42:12Z | [
"python",
"increment"
] |
Python: simple way to increment by alternating values? | 39,241,505 | <p>I am building a list of integers that should increment by 2 alternating values. </p>
<p>For example, starting at 0 and alternating between 4 and 2 up to 20 would make:</p>
<pre><code>[0,4,6,10,12,16,18]
</code></pre>
<p>range and xrange only accept a single integer for the increment value. What's the simplest way... | 4 | 2016-08-31T05:36:54Z | 39,241,566 | <p>You can use a list comprehension and the modulus operator to do clever things like that. For example:</p>
<pre><code>>>> [3*i + i%2 for i in range(10)]
[0, 4, 6, 10, 12, 16, 18, 22, 24, 28]
</code></pre>
| 6 | 2016-08-31T05:42:47Z | [
"python",
"increment"
] |
Python: simple way to increment by alternating values? | 39,241,505 | <p>I am building a list of integers that should increment by 2 alternating values. </p>
<p>For example, starting at 0 and alternating between 4 and 2 up to 20 would make:</p>
<pre><code>[0,4,6,10,12,16,18]
</code></pre>
<p>range and xrange only accept a single integer for the increment value. What's the simplest way... | 4 | 2016-08-31T05:36:54Z | 39,241,588 | <p>I might use a simple <code>itertools.cycle</code> to cycle through the steps:</p>
<pre><code>from itertools import cycle
def fancy_range(start, stop, steps=(1,)):
steps = cycle(steps)
val = start
while val < stop:
yield val
val += next(steps)
</code></pre>
<p>You'd call it like so:</... | 12 | 2016-08-31T05:44:10Z | [
"python",
"increment"
] |
Python: simple way to increment by alternating values? | 39,241,505 | <p>I am building a list of integers that should increment by 2 alternating values. </p>
<p>For example, starting at 0 and alternating between 4 and 2 up to 20 would make:</p>
<pre><code>[0,4,6,10,12,16,18]
</code></pre>
<p>range and xrange only accept a single integer for the increment value. What's the simplest way... | 4 | 2016-08-31T05:36:54Z | 39,241,783 | <p>This could be solution that is flexible and work for any range. </p>
<pre><code>def custom_range(first, second, range_limit):
start , end = range_limit
step = first + second
a = range(start, end, step)
b = range(first, end, step)
from itertools import izip_longest
print [j for i in izip_long... | 0 | 2016-08-31T05:58:52Z | [
"python",
"increment"
] |
Python: simple way to increment by alternating values? | 39,241,505 | <p>I am building a list of integers that should increment by 2 alternating values. </p>
<p>For example, starting at 0 and alternating between 4 and 2 up to 20 would make:</p>
<pre><code>[0,4,6,10,12,16,18]
</code></pre>
<p>range and xrange only accept a single integer for the increment value. What's the simplest way... | 4 | 2016-08-31T05:36:54Z | 39,242,065 | <p>1 Generate a range of numbers from 0 to n with step size 4
2 generate another range of numbers from 0 to n with step size 6
3 Combine both the list and sorted. Remove duplicates</p>
<pre><code>>>> a = range(0,20,4)
>>> a
[0, 4, 8, 12, 16]
>>> b = range(0,20,6)
>>> c = sorted(a + ... | 0 | 2016-08-31T06:18:06Z | [
"python",
"increment"
] |
convert dataframe column of type 'object' into type list | 39,241,590 | <p>Trying to convert the <code>object</code> type column of a <code>dataframe</code> into a list of <code>dicts</code> as it actually needs to be.</p>
<pre><code>print df['A'].dtype
object
print df['A'][:1]
[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]
</code></pre>
<p>Is it possible to ret... | 3 | 2016-08-31T05:44:22Z | 39,242,349 | <p>use <code>json</code></p>
<pre><code>import json
df.A.apply(json.loads)
0 [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
1 [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
2 [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
3 [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ...
4 [{u'c': 47, u'at'... | 3 | 2016-08-31T06:36:29Z | [
"python",
"pandas",
"dataframe"
] |
How to generate bi/tri-grams using spacy/nltk | 39,241,709 | <p>The input text are always list of dish names where there are 1~3 adjectives and a noun</p>
<p>Inputs</p>
<pre><code>thai iced tea
spicy fried chicken
sweet chili pork
thai chicken curry
</code></pre>
<p>outputs:</p>
<pre><code>thai tea, iced tea
spicy chicken, fried chicken
sweet pork, chili pork
thai chicken, ... | 0 | 2016-08-31T05:53:14Z | 39,242,299 | <p>You can achieve this in a few steps with NLTK:</p>
<ol>
<li><p>PoS tag the sequences</p></li>
<li><p>generate the desired n-grams (in your examples there are no trigrams, but skip-grams which can be generated through trigrams and then punching out the middle token)</p></li>
<li><p>discard all n-grams that don't mat... | 0 | 2016-08-31T06:33:30Z | [
"python",
"nlp",
"nltk",
"n-gram",
"spacy"
] |
How to generate bi/tri-grams using spacy/nltk | 39,241,709 | <p>The input text are always list of dish names where there are 1~3 adjectives and a noun</p>
<p>Inputs</p>
<pre><code>thai iced tea
spicy fried chicken
sweet chili pork
thai chicken curry
</code></pre>
<p>outputs:</p>
<pre><code>thai tea, iced tea
spicy chicken, fried chicken
sweet pork, chili pork
thai chicken, ... | 0 | 2016-08-31T05:53:14Z | 39,244,988 | <p>Something like this:</p>
<pre><code>>>> from nltk import bigrams
>>> text = """thai iced tea
... spicy fried chicken
... sweet chili pork
... thai chicken curry"""
>>> lines = map(str.split, text.split('\n'))
>>> for line in lines:
... ", ".join([" ".join(bi) for bi in bigram... | 0 | 2016-08-31T08:52:55Z | [
"python",
"nlp",
"nltk",
"n-gram",
"spacy"
] |
I cant install kivy through pip | 39,241,741 | <p>Im getting this error when installing kivy through pip, any help on this issue?</p>
<p><a href="http://i.stack.imgur.com/OzJ0o.png" rel="nofollow"><img src="http://i.stack.imgur.com/OzJ0o.png" alt="enter image description here"></a></p>
<p>I would provide more info on the error if I could, but I don't even know wh... | 0 | 2016-08-31T05:56:20Z | 39,241,979 | <p>Download the respective wheel file for your architecture, os and Python version from <a href="https://pypi.python.org/pypi/Kivy" rel="nofollow">https://pypi.python.org/pypi/Kivy</a> and install the downloaded wheel through pip, as documented in <a href="https://kivy.org/docs/installation/installation-windows.html#wh... | 1 | 2016-08-31T06:11:57Z | [
"python",
"pip",
"kivy"
] |
Server responds by "text/html" to a "text/css" request | 39,241,820 | <p><strong>PROBLEM:</strong> When I try to access the web page (localhost/mysite/admin), all goes well, except the CSS files which my server can't deliver !!</p>
<p><a href="http://i.stack.imgur.com/0VNcT.png" rel="nofollow">I got a <strong>500 Internal Server Error</strong></a></p>
<p><a href="http://i.stack.imgur.c... | 0 | 2016-08-31T06:02:10Z | 39,250,567 | <p>@Ankush Raghuvanshi:
Yes, it serves all kind of files except CSS !
Also, when I us the built-in development server (which I run by using the command <code>python manage.py runserver</code> ): these CSS files works fine on my website.</p>
| 0 | 2016-08-31T13:09:36Z | [
"python",
"css",
"django",
"apache"
] |
Running loop synchronously in python | 39,241,837 | <p>I have a block of code, that crawls an infinite height website <code>(Like FACEBOOK)</code>. </p>
<p>The Python selenium script asks the page javascript to go to the bottom of the page in order to load page further down. But eventually it happens that the loop runs asynchronously and the website's rate-limiter bloc... | 3 | 2016-08-31T06:03:09Z | 39,242,113 | <p>You can set the <code>page_load_timeout</code> to make the driver wait for the page to load</p>
<pre><code>driver.set_page_load_timeout(10)
</code></pre>
<p>Another option is to wait for the number of elements to change</p>
<pre><code>current_number_of_news = 0
news = []
while int(number_of_news) != int(len(news)... | 3 | 2016-08-31T06:21:23Z | [
"python",
"selenium",
"asynchronous",
"selenium-webdriver",
"synchronous"
] |
What is a <class 'range'> | 39,241,877 | <p>Python3:</p>
<pre><code>string = range(10)
print("{}".format(type(string)))
</code></pre>
<p>The output: </p>
<pre><code>class 'range'
</code></pre>
<p>I am just curious about this class 'range'.
Could anyone explain?</p>
<p>But in Python2:</p>
<p>The output: </p>
<pre><code>class 'list'
</code></pre>
<p>Wel... | 2 | 2016-08-31T06:05:40Z | 39,241,939 | <p>In Python 2 <code>range(val)</code> produces an instance of a list, it <a href="https://docs.python.org/2/library/functions.html#range" rel="nofollow">simply a function</a>. Thereby <code>type(range(10))</code> will return <code>class 'list'</code>.</p>
<p>In Python <code>3</code>, <a href="https://docs.python.org/... | 2 | 2016-08-31T06:09:28Z | [
"python",
"python-2.7",
"python-3.x",
"range"
] |
What is a <class 'range'> | 39,241,877 | <p>Python3:</p>
<pre><code>string = range(10)
print("{}".format(type(string)))
</code></pre>
<p>The output: </p>
<pre><code>class 'range'
</code></pre>
<p>I am just curious about this class 'range'.
Could anyone explain?</p>
<p>But in Python2:</p>
<p>The output: </p>
<pre><code>class 'list'
</code></pre>
<p>Wel... | 2 | 2016-08-31T06:05:40Z | 39,241,940 | <p>Python 3 added a new <a href="https://docs.python.org/3/library/stdtypes.html#range" rel="nofollow"><code>range</code></a> class to efficiently handle "an immutable sequence of numbers" (similar to Python 2's <a href="https://docs.python.org/2/library/stdtypes.html#typesseq-xrange" rel="nofollow"><code>xrange</code>... | 1 | 2016-08-31T06:09:35Z | [
"python",
"python-2.7",
"python-3.x",
"range"
] |
Heap Bit-Shift Macros for Left, Right and Parent | 39,241,977 | <p>I am reading about Heaps, which describes that you can do the operations of accessing the left child, the <strong>RIGHT</strong>/<strong>LEFT</strong> child and the <strong>PARENT</strong> with bit shift operations. While Left and Parent seems trivial i am not sure with the right one. Do i just have to add one?</p>
... | 0 | 2016-08-31T06:11:53Z | 39,242,571 | <p>This is how heap works - for every node you could easily get:</p>
<ol>
<li>Parent - just divide the node index by two (<code>N / 2</code>)</li>
<li>Left child - multiply index by two (<code>N * 2</code>)</li>
<li>Right child - multiply index by two and increase new index by one (<code>N * 2 + 1</code>)</li>
</ol>
... | 0 | 2016-08-31T06:47:58Z | [
"python",
"c++",
"algorithm",
"heap"
] |
lxml XPath position() does not work | 39,242,154 | <p>I tried to scrape a page via XPath but I could not get it work as expected.</p>
<p>The page is like,</p>
<pre><code><tag1>
<tag2>
....
<div id=article>
<p> stuff1 </p>
<p> stuff2 </p>
<p&g... | 1 | 2016-08-31T06:24:27Z | 39,242,701 | <p>Thats because you have position()=>1, should be position()>=1</p>
<pre><code>content = root.xpath('string(//div[@id="article"]/p[position()>=1 and position()<=last()]/.)')
</code></pre>
<p>will set content to stuff1.</p>
| 2 | 2016-08-31T06:54:58Z | [
"python",
"python-3.x",
"xpath"
] |
Datetime comparison within Pandas messing with datetime.time() | 39,242,158 | <p>I have a large excel file with start and finish times for marathon runners. In order to determine the number of runners still on the course after delayed start times, I've tried to import the data into Pandas and use the built in pandas comparison in order to return a list of runners running at a certain time. At a ... | 3 | 2016-08-31T06:24:40Z | 39,242,184 | <p>You need add <code>()</code> twice only, first can be omit, but by best practices are used too:</p>
<pre><code>pd[(pd.start_time <= capture_time.time()) & (pd.end_time <= capture_time.time())]
</code></pre>
<p>Or maybe <code>dtype</code> of column <code>end_time</code> is not <code>datetime</code>, so yo... | 2 | 2016-08-31T06:25:48Z | [
"python",
"datetime",
"pandas",
"indexing",
"time"
] |
Categorizing natural content | 39,242,269 | <p>My question is how to extract a relevant category from a natural content.</p>
<p>For example, below is a news article from a newspaper.</p>
<blockquote>
<p>Arsenal have completed the signing of Shkodran Mustafi from Valencia as the Gunners enter deadline day having made six signings this summer, in the form of L... | 1 | 2016-08-31T06:31:53Z | 39,243,858 | <p>Ther is a rubygem which can help you out in this. check <a href="https://github.com/alexandru/stuff-classifier" rel="nofollow">this</a></p>
| 0 | 2016-08-31T07:57:41Z | [
"php",
"python",
"ruby",
"content-management-system",
"lexical-analysis"
] |
Save list of dictionaries to .tsv file | 39,242,335 | <p>I have the following piece of code to output to csv. </p>
<pre><code>import csv
keys = ['Name','Hour','Time']
dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'CSVFile.csv')
with open(csvfilename, 'wb') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
... | 0 | 2016-08-31T06:35:53Z | 39,242,484 | <p>You can specify that in your <code>DictWriter</code> with the <code>delimiter</code> option:</p>
<pre><code>dict_writer = csv.DictWriter(output_file, keys, delimiter='\t')
</code></pre>
<p>Or using the <code>dialect</code>:</p>
<pre><code>dict_writer = csv.DictWriter(output_file, keys, dialect='excel-tab')
</code... | 2 | 2016-08-31T06:43:47Z | [
"python",
"python-2.7"
] |
DjangoREST using DELETE and UPDATE with serializers | 39,242,346 | <p>So I followed the <a href="http://www.django-rest-framework.org/tutorial/quickstart/" rel="nofollow">Quickstart Guide</a> on the DjangoREST framewok site and ended up with the following code:</p>
<p><strong>serializers.py:</strong></p>
<pre><code>class UserSerializer(serializers.HyperlinkedModelSerializer):
class ... | -1 | 2016-08-31T06:36:28Z | 39,242,694 | <p>The code is fine, you just need to use <code>PUT</code> and <code>DELETE</code> data methods for update and delete respectively (instead of <code>GET/POST</code>)</p>
<p>You can see from the code example for a <code>ModelViewSet</code> in the <a href="http://www.django-rest-framework.org/tutorial/6-viewsets-and-rou... | 1 | 2016-08-31T06:54:34Z | [
"python",
"django",
"django-rest-framework"
] |
Disjoint Sets path compression running time error | 39,242,472 | <p>I am taking an online data structure course now. Here is my Python implementation of a merge and find algorithm. I followed the instructions, but the running time far exceeds the limits. Can anyone take a look? It should be a simple one. Thanks.</p>
<p>We must do 'm' merges or union operations. í µí±í µí±í µí± í ... | 0 | 2016-08-31T06:43:07Z | 39,242,896 | <p>The problem is that you're calling <code>max</code> on the whole data on each round thus having <code>O(nm)</code> time complexity. Instead of doing that call <code>max</code> on initial data, store the result and after each merge update it in case destination table is larger than current max. With path compression ... | 0 | 2016-08-31T07:06:40Z | [
"python",
"data-structures",
"disjoint-sets"
] |
Insert Data to MySQL From ADS1115 Python | 39,242,563 | <p>i have a problem extracting data from accelerometer sensor in raspberry pi using ADC ADS1115.</p>
<p>I'm using this code for inserting the data to mysql</p>
<pre><code># Author: Tony DiCola
# License: Public Domain
# Import the ADS1x15 module.
import Adafruit_ADS1x15
import MySQLdb
import time
import datetime
# Cr... | 2 | 2016-08-31T06:47:35Z | 39,320,173 | <p>Move cursor initialization inside loop</p>
<pre><code>while True:
try:
curs=db.cursor()
curs.execute("""INSERT INTO table_sensor_log(time, koordinatx, koordinaty, koordinatz)
values(%s,%s,%s,%s)""",(time_sensor,x[i],y[i],z[i]))
db.commit()
curs.close()
except:
... | 0 | 2016-09-04T18:27:00Z | [
"php",
"python",
"mysql",
"raspberry-pi2",
"adc"
] |
Pandas fillna() based on specific column attribute | 39,242,615 | <p>Let's say I have this table</p>
<pre><code>Type | Killed | Survived
Dog 5 2
Dog 3 4
Cat 1 7
Dog nan 3
cow nan 2
</code></pre>
<p>One of the value on <code>Killed</code> is missing for <code>[Type] = Dog</code>.</p>
<p>I want to impute the mean in <code>... | 3 | 2016-08-31T06:50:38Z | 39,242,802 | <p>For me working:</p>
<pre><code>df.ix[df['Type'] == 'Dog', 'Killed'] = df.ix[df['Type'] == 'Dog', 'Killed'].fillna(2.25)
print (df)
Type Killed Survived
0 Dog 5.00 2
1 Dog 3.00 4
2 Cat 1.00 7
3 Dog 2.25 3
4 cow NaN 2
</code></pre>
<p>If need <a href="... | 2 | 2016-08-31T07:01:29Z | [
"python",
"pandas",
"indexing",
null,
"mean"
] |
Pandas fillna() based on specific column attribute | 39,242,615 | <p>Let's say I have this table</p>
<pre><code>Type | Killed | Survived
Dog 5 2
Dog 3 4
Cat 1 7
Dog nan 3
cow nan 2
</code></pre>
<p>One of the value on <code>Killed</code> is missing for <code>[Type] = Dog</code>.</p>
<p>I want to impute the mean in <code>... | 3 | 2016-08-31T06:50:38Z | 39,242,805 | <p><code>groupby</code> with <code>transform</code></p>
<pre><code>df.groupby('Type').Killed.transform(lambda x: x.fillna(x.mean()))
</code></pre>
<h3>Setup</h3>
<pre><code>df = pd.DataFrame([
['Dog', 5, 2],
['Dog', 3, 4],
['Cat', 1, 7],
['Dog', np.nan, 3],
['Cow', np.nan, 2]
... | 3 | 2016-08-31T07:01:42Z | [
"python",
"pandas",
"indexing",
null,
"mean"
] |
Pandas fillna() based on specific column attribute | 39,242,615 | <p>Let's say I have this table</p>
<pre><code>Type | Killed | Survived
Dog 5 2
Dog 3 4
Cat 1 7
Dog nan 3
cow nan 2
</code></pre>
<p>One of the value on <code>Killed</code> is missing for <code>[Type] = Dog</code>.</p>
<p>I want to impute the mean in <code>... | 3 | 2016-08-31T06:50:38Z | 39,242,855 | <p>Two problems: Note that <code>df.loc[(df['Type'] == 'Dog') & (df['Killed'])]</code> isn't doing what (I presume) you think it is doing. Instead of selecting rows where type is dog and the column 'Killed', you are selecting rows of type dog, then doing elementwise "and" with the column 'Killed', which will give y... | 1 | 2016-08-31T07:04:28Z | [
"python",
"pandas",
"indexing",
null,
"mean"
] |
how to get the declaration of a list done during the unnesting recursively? | 39,242,718 | <p>I have been getting my head around to do the recursion <strong>without using any global variable</strong>. If am passing the lists the lists of lists ... and resultantly, i should have all the elements from the input in a single list. The problem is every time i call the function the list is declared from the start.... | 0 | 2016-08-31T06:55:42Z | 39,242,776 | <p>You have to use the returned <code>List_</code>, in subsequent calls, and extend the current list:</p>
<pre><code>def recursion (alist):
List_ = list()
for elements in alist:
if type(elements) == list:
List_.extend(recursion(elements)) # extend list with recursive call
else:
... | 4 | 2016-08-31T06:59:26Z | [
"python",
"python-3.x",
"recursion"
] |
how to get the declaration of a list done during the unnesting recursively? | 39,242,718 | <p>I have been getting my head around to do the recursion <strong>without using any global variable</strong>. If am passing the lists the lists of lists ... and resultantly, i should have all the elements from the input in a single list. The problem is every time i call the function the list is declared from the start.... | 0 | 2016-08-31T06:55:42Z | 39,242,817 | <p>you need to pass an accumulator list to the recursive bit of your computation:</p>
<pre><code>def flatten(xs):
accum = []
def rec(xs):
for x in xs:
if isinstanceof(x, list):
rec(x)
else:
accum.append(x)
rec(xs)
return accum
</code></pre... | 1 | 2016-08-31T07:02:22Z | [
"python",
"python-3.x",
"recursion"
] |
how to get the declaration of a list done during the unnesting recursively? | 39,242,718 | <p>I have been getting my head around to do the recursion <strong>without using any global variable</strong>. If am passing the lists the lists of lists ... and resultantly, i should have all the elements from the input in a single list. The problem is every time i call the function the list is declared from the start.... | 0 | 2016-08-31T06:55:42Z | 39,242,863 | <p>Your code fixed:
You have to append the next recursion level, so the return of a deeper recursion is appended all the way to the top level</p>
<pre><code>def unnest (alist):
List_ = list()
for elements in alist:
if type(elements) == list:
List_.extend(unnest(elements))
else:... | 1 | 2016-08-31T07:04:51Z | [
"python",
"python-3.x",
"recursion"
] |
how to get the declaration of a list done during the unnesting recursively? | 39,242,718 | <p>I have been getting my head around to do the recursion <strong>without using any global variable</strong>. If am passing the lists the lists of lists ... and resultantly, i should have all the elements from the input in a single list. The problem is every time i call the function the list is declared from the start.... | 0 | 2016-08-31T06:55:42Z | 39,242,984 | <p>Try this, There are inbuilt module support for making flattern.</p>
<pre><code>In [47]: from compiler.ast import flatten
In [48]: lst = [1,2,[3,4,5,[6,7,[8,9,[10,11,[12,[13,[14]]]]]]]]
In [49]: flatten(lst)
Out[49]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
</code></pre>
<p>Recursion method,</p>
<pre><code>... | 2 | 2016-08-31T07:11:22Z | [
"python",
"python-3.x",
"recursion"
] |
how to get the declaration of a list done during the unnesting recursively? | 39,242,718 | <p>I have been getting my head around to do the recursion <strong>without using any global variable</strong>. If am passing the lists the lists of lists ... and resultantly, i should have all the elements from the input in a single list. The problem is every time i call the function the list is declared from the start.... | 0 | 2016-08-31T06:55:42Z | 39,243,119 | <p>You can use inner function which will do the recursion. This has several adventages:</p>
<ul>
<li>The function signature will not change </li>
<li>No use of global variables</li>
<li>You will not create a new list each recursion call (memory friendly)</li>
</ul>
<hr>
<pre><code>def flatten(old_list):
def ... | 1 | 2016-08-31T07:18:16Z | [
"python",
"python-3.x",
"recursion"
] |
how to get the declaration of a list done during the unnesting recursively? | 39,242,718 | <p>I have been getting my head around to do the recursion <strong>without using any global variable</strong>. If am passing the lists the lists of lists ... and resultantly, i should have all the elements from the input in a single list. The problem is every time i call the function the list is declared from the start.... | 0 | 2016-08-31T06:55:42Z | 39,243,142 | <pre><code>list1=[1,2,[3,4,5,[6,7,[8,9,[10,11,[12,[13,[14]]]]]]]]
l=[]
def recursion(list1,l):
for i in list1:
if type(i) is list:
recursion(i,l)
else:
l.append(i)
recursion(list1,l)
print(l)
</code></pre>
<p>output </p>
<pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 1... | 1 | 2016-08-31T07:19:44Z | [
"python",
"python-3.x",
"recursion"
] |
Atomic transaction on django queryset.update(**kwargs) | 39,242,799 | <p>It seems <code>Django</code>'s <code>queryset.update</code> method execute under <code>transaction.atomic</code> context manager. When would I need to do that explicitly in my code during <code>update</code>? Or what will be the benefits doing it, or problems not doing it?</p>
<h2>Code</h2>
<pre><code>try:
que... | 0 | 2016-08-31T07:01:14Z | 39,243,269 | <p><strong>First</strong></p>
<p>As <a href="https://docs.djangoproject.com/en/1.10/topics/db/transactions/#django.db.transaction.atomic" rel="nofollow">docs</a> state</p>
<blockquote>
<p>Atomicity is the defining property of database transactions. atomic allows us to create a block of code within which the atomici... | 1 | 2016-08-31T07:25:48Z | [
"python",
"django",
"django-queryset"
] |
I/O operation on closed file: Django Imagekit & Pillow | 39,242,871 | <p>I am using django imagekit and pillow to upload images which was working fine in django 1.7. Recently we shifted to django 1.10 and now the image upload is not working. Code snippet is:</p>
<pre><code>class Images(models.Model):
image = ProcessedImageField(upload_to='main',
proce... | 2 | 2016-08-31T07:05:03Z | 39,343,498 | <p>It seems that Imagekit and Pillow are not interacting very well in latest release. The Problem as it can be seen was happening because the file sent by imagekit could not be processed directly by PIL.</p>
<p>So for cropping and changing size and quality, we shifted entirely to PIL.</p>
<pre><code>def upload_image... | 0 | 2016-09-06T07:54:25Z | [
"python",
"django",
"python-imaging-library",
"django-imagekit"
] |
Scrapy Tutorial Example | 39,243,009 | <p>Looking to see if someone can point me in the right direction in regards to using Scrapy in python.</p>
<p>I've been trying to follow the example for several days and still can't get the output expected. Used the Scrapy tutorial, <a href="http://doc.scrapy.org/en/latest/intro/tutorial.html#defining-our-item" rel="n... | 1 | 2016-08-31T07:12:44Z | 39,243,432 | <p>Seems like this spider is outdated in the tutorial. The website has changed a bit so all of the xpaths now capture nothing. This is easily fixable:</p>
<pre><code>def parse(self, response):
sites = response.xpath('//div[@class="title-and-desc"]/a')
for site in sites:
item = dict()
item['name... | 0 | 2016-08-31T07:34:58Z | [
"python",
"web-scraping",
"scrapy",
"web-crawler"
] |
How to get argument names and __annotations__ from Cython method descriptor? | 39,243,290 | <p>If I define method in <code>cdef class</code>, method has no any info about arguments and annotations:</p>
<p>Python class:</p>
<pre><code>class MyClass:
def test(self, arg: int):
pass
print(dir(MyClass.test))
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__dela... | 2 | 2016-08-31T07:26:57Z | 39,244,615 | <p>According to <a href="https://github.com/cython/cython/issues/1053" rel="nofollow">this issue</a> on the Cython github repo, annotations were added but only for <code>cdef</code> functions:</p>
<pre><code>%%cython
def test2(arg: int): pass
cpdef test1(arg: int): pass
cdef test(arg: int): pass
print(['__annotations... | 2 | 2016-08-31T08:35:32Z | [
"python",
"methods",
"annotations",
"cython",
"inspect"
] |
Pandas applied function erasing data | 39,243,305 | <pre><code>In [1]: df = pd.DataFrame([[pubA, linkA,None], [pubB, linkB,textB], [pubC, linkC,textC]], columns=['pub', 'link','text])
In [2]: df
Out [2]:
pub link text
0 pubA linkA None
1 pubB linkB textB
2 pubC linkC textC
</code></pre>
<p>I have code I'm using to pull text from the web. My func... | 1 | 2016-08-31T07:27:59Z | 39,243,596 | <p>What is going on is that <code>pass</code> makes your function return <code>None</code>. </p>
| 4 | 2016-08-31T07:43:55Z | [
"python",
"pandas"
] |
How to retrieve entities from Google Cloud Datastore | 39,243,414 | <p>I have some problems with Cloud Datastore in Google App Engine.</p>
<p>I have 2 Models in the database which are:</p>
<pre><code>class Product(ndb.Model):
name = StringProperty(required=True)
category = KeyProperty(kind=Category)
description = TextProperty(required=True)
price = IntegerProperty(req... | 1 | 2016-08-31T07:34:06Z | 39,243,616 | <p>The following should perform what your sql query is doing:</p>
<pre><code>query = Product.query(Product.category == "CertainName") # Note the "=="
</code></pre>
<p>Edit:</p>
<p>I just realized you need to filter by key(thank you @mgilson). The query changes a little. Basically you just need to first get your cate... | 1 | 2016-08-31T07:45:00Z | [
"python",
"google-app-engine",
"nosql",
"google-cloud-datastore"
] |
How to retrieve entities from Google Cloud Datastore | 39,243,414 | <p>I have some problems with Cloud Datastore in Google App Engine.</p>
<p>I have 2 Models in the database which are:</p>
<pre><code>class Product(ndb.Model):
name = StringProperty(required=True)
category = KeyProperty(kind=Category)
description = TextProperty(required=True)
price = IntegerProperty(req... | 1 | 2016-08-31T07:34:06Z | 39,244,512 | <p>You could generate your own key in class Category based on the 'name' field and use it: </p>
<p>1) when you generate a new Category entity</p>
<p>2) when you need to query Product against a specific category. </p>
<p>So after Category entities have a key you can generate at any time, you could say: </p>
<p>categ... | 0 | 2016-08-31T08:30:41Z | [
"python",
"google-app-engine",
"nosql",
"google-cloud-datastore"
] |
Executing script when SQL query is executed | 39,243,626 | <p>I want to execute script(probably written in python), when update query is executed on MySQL database. The query is going to be executed from external system written in PHP to which I don't have access, so I can't edit the source code. The MySQL server is installed on our machine. Any ideas how I can accomplish this... | 1 | 2016-08-31T07:45:50Z | 39,244,221 | <p>No, it is not possible to call external scripts from MySQL.</p>
<p>The only thing you can do is adding an ON UPDATE trigger that will write into some queue. Then you will have the python script POLLING the queue and doing whatever it's supposed to do with the rows it finds.</p>
| 0 | 2016-08-31T08:16:51Z | [
"php",
"python",
"mysql",
"database"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.