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 passing in various ways but always get errors.</p> <p><strong>mainscript.py</strong></p> <pre><code>import helperfunctions.py as helper spi = spidev.SpiDev() spi.open(0, 0) response = spi.xfer([ ... some data ...]) #this works when #called from mainscript.py helper.sendOtherStuff() #this doesn't work (see helper script below) </code></pre> <p><strong>helperfunctions.py</strong></p> <pre><code>def sendOtherStuff(): #need to somehow reference 'spi.' object from mainscript.py file otherData = ([... some different data ...]) resp = spi.xfer([otherData]) #this fails because helperfunctions #apparently doesn't know spi. object return resp </code></pre> <p>I have the same general question often regarding global variable values as well. I'm sure there is a "better" way to do it, but out of convenience for now, I often wish to define some global variables in mainscript.py then reference those globals inside functions of helperfunctions.py. I can't figure a way to do this. Going the other way is easy - declare the globals inside helperfunctions.py then reference them from mainscript.py as helper.variableName, but I don't know how to go the other direction.</p> <p>Any direction is much appreciated. Thank you.</p>
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 function. I removed your variable assignment because it seemed redundant.</p>
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(shape=(2,3))</code></p>
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="nofollow"><code>empty</code></a> variant, since it seems to be more popular:</p> <pre><code>numpy.empty(shape=(1,) * 6) </code></pre>
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><code>np.concatenate((np.array([[[]]]),np.array([1,2,3])), axis=0) </code></pre> <p>will give you dimensions error.</p> <p>The only thing you can concatenate to such an array is an array with size 0 dimenions</p> <pre><code>In [348]: np.concatenate((np.array([[]]),np.array([[]])),axis=0) Out[348]: array([], shape=(2, 0), dtype=float64) In [349]: np.concatenate((np.array([[]]),np.array([[1,2]])),axis=0) ------ ValueError: all the input array dimensions except for the concatenation axis must match exactly In [354]: np.array([[]]) Out[354]: array([], shape=(1, 0), dtype=float64) In [355]: np.concatenate((np.zeros((1,0)),np.zeros((3,0))),axis=0) Out[355]: array([], shape=(4, 0), dtype=float64) </code></pre> <p>To work iteratively, start with a empty list, and <code>append</code> to it; then make the array at the end.</p> <p><code>a = np.zeros((1,1,1,1,1,0))</code> could be concatenated on the last axis with another <code>np.ones((1,1,1,1,1,n))</code> array.</p> <pre><code>In [363]: np.concatenate((a,np.array([[[[[[1,2,3]]]]]])),axis=-1) Out[363]: array([[[[[[ 1., 2., 3.]]]]]]) </code></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>&gt;&gt;&gt; a = np.array([[[[[[]]]]]]) &gt;&gt;&gt; b = np.empty(shape = [1] * 5 + [0]) &gt;&gt;&gt; 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>df['a'] = df.a.str.split().str[1] # Optional `.astype(int)` </code></pre> <p>b) Use regex to extract any digits (<code>\d*</code>) from the end of the string.</p> <pre><code>df['a'] = df.a.str.extract(r'(\d*)$') # Optional `.astype(int)` </code></pre>
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.</p> <p>My code:</p> <pre><code>from Tkinter import * root = Tk() class PokemonClass(object): def __init__(self, master): frame = Frame(master) frame.pack() self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!", bg="Black", fg="White") self.WelcomeLabel.pack(fill=X) self.CharButton = Button(root, text="Charmander", bg="RED", fg="White", command=self.CharClick) self.CharButton.pack(side=LEFT, fill=X) self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White") self.SquirtButton.pack(side=LEFT, fill=X) self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green", fg="White") self.BulbButton.pack(side=LEFT, fill=X) def CharClick(self): print "You like Charmander!" global CharSwitch CharSwitch = 'Yes' CharSwitch = 'No' if CharSwitch == 'Yes': CharPhoto = PhotoImage(file="Charmander.gif") ChLabel = Label(root, image=CharPhoto) ChLabel.pack() k = PokemonClass(root) root.mainloop() </code></pre>
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) frame.pack() self.WelcomeLabel = Label(root, text = "Welcome! Pick your Pokemon!", bg = "Black", fg = "White") self.WelcomeLabel.pack(fill = X) self.CharButton = Button(root, text = "Charmander", bg = "RED", fg = "White", command = CharClick) self.CharButton.pack(side = LEFT, fill = X) self.SquirtButton = Button(root, text = "Squirtle", bg = "Blue", fg = "White") self.SquirtButton.pack(side = LEFT, fill = X) self.BulbButton = Button(root, text = "Bulbasaur", bg = "Dark Green", fg = "White") self.BulbButton.pack(side = LEFT, fill = X) def CharClick(): print "You like Charmander!" CharPhoto = PhotoImage(file = "Charmander.gif") ChLabel = Label(root, image = CharPhoto) ChLabel.pack() k = PokemonClass(root) root.mainloop() </code></pre>
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.</p> <p>My code:</p> <pre><code>from Tkinter import * root = Tk() class PokemonClass(object): def __init__(self, master): frame = Frame(master) frame.pack() self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!", bg="Black", fg="White") self.WelcomeLabel.pack(fill=X) self.CharButton = Button(root, text="Charmander", bg="RED", fg="White", command=self.CharClick) self.CharButton.pack(side=LEFT, fill=X) self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White") self.SquirtButton.pack(side=LEFT, fill=X) self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green", fg="White") self.BulbButton.pack(side=LEFT, fill=X) def CharClick(self): print "You like Charmander!" global CharSwitch CharSwitch = 'Yes' CharSwitch = 'No' if CharSwitch == 'Yes': CharPhoto = PhotoImage(file="Charmander.gif") ChLabel = Label(root, image=CharPhoto) ChLabel.pack() k = PokemonClass(root) root.mainloop() </code></pre>
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 the <code>CharPhoto</code> variable goes out of scope at the end of the function <code>CharClick</code>, the number of reference to the <code>PhotoImage</code> falls to zero and the object is made available for garbage collection.</p> <p>If you keep a reference to the image somewhere, it will appear. When you kept it globally it remained in scope for the entire script and hence appeared.</p> <p>You can keep a reference to it in the <code>PokemonClass</code> object or in the <code>Label</code> widget.</p> <p>Below is the later of those options</p> <pre><code>from Tkinter import * root = Tk() class PokemonClass(object): def __init__(self, master): frame = Frame(master) frame.pack() self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!", bg="Black", fg="White") self.WelcomeLabel.pack(fill=X) self.CharButton = Button(root, text="Charmander", bg="RED", fg="White", command=self.CharClick) self.CharButton.pack(side=LEFT, fill=X) self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White") self.SquirtButton.pack(side=LEFT, fill=X) self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green", fg="White") self.BulbButton.pack(side=LEFT, fill=X) def CharClick(self): print "You like Charmander!" global CharSwitch CharSwitch = 'Yes' CharPhoto = PhotoImage(file="Charmander.gif") ChLabel = Label(root, image=CharPhoto) ChLabel.img = CharPhoto ChLabel.pack() CharSwitch = 'No' k = PokemonClass(root) root.mainloop() </code></pre>
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 NaN 2016-08-10 14:01:00 2.6 A 0 4.6 NaN 2016-08-10 14:02:00 4.8 A 0 NaN 4.3 2016-08-10 14:03:00 5.7 A 1 NaN NaN 2016-08-10 14:04:00 5.5 A 1 5.7 NaN 2016-08-10 14:05:00 5.6 A 1 NaN NaN 2016-08-10 14:06:00 7.8 A 1 NaN 5.2 2016-08-10 14:07:00 8.9 A 0 NaN NaN 2016-08-10 14:08:00 3.6 A 0 NaN NaN print (df.dtypes) A float64 B object C int64 D float64 E float64 dtype: object </code></pre> <p>Thanks to a lot of input from the community I have this code now which allows me to upsample my df to second intervals, applying different methods to different <code>dtypes</code> </p> <pre><code>int_cols = df.select_dtypes(['int64']).columns index = pd.date_range(df.index[0], df.index[-1], freq="s") df2 = df.reindex(index) for col in df2: if col == int_cols.all(): df2[col].ffill(inplace=True) df2[col] = df2[col].astype(int) elif df2[col].dtype == float: df2[col].interpolate(inplace=True) else: df2[col].ffill(inplace=True) </code></pre> <p>I am looking for a way now, to only interpolate between my actual measurements. The interpolate function extends my last measurement until the end of the <code>df</code>: </p> <pre><code> df2.tail() Out[75]: A B C D E 2016-08-10 14:07:56 3.953333 A 0 5.7 5.2 2016-08-10 14:07:57 3.865000 A 0 5.7 5.2 2016-08-10 14:07:58 3.776667 A 0 5.7 5.2 2016-08-10 14:07:59 3.688333 A 0 5.7 5.2 2016-08-10 14:08:00 3.600000 A 0 5.7 5.2 </code></pre> <p>But I would like to stop this when the last measurement took place (for example at 14:04:00 <code>col['D']</code> and 14:06:00 <code>col['D']</code>) and leave the NaNs. </p> <p>It tried adding a zero value for 'limit' and 'limit_direction' to 'both':</p> <pre><code> for col in df2: if col == int_cols.all(): df2[col].ffill(inplace=True) df2[col] = df2[col].astype(int) elif df2[col].dtype == float: df2[col].interpolate(inplace=True,limit=0, limit_direction='both') else: df2[col].ffill(inplace=True) </code></pre> <p>but this didn't change anything to the output. I than tried to incorporate the solution I found to this question: <a href="http://stackoverflow.com/questions/33691591/pandas-interpolation-where-first-and-last-data-point-in-column-is-nan">Pandas: interpolation where first and last data point in column is NaN</a> into my code:</p> <pre><code>for col in df2: if col == int_cols.all(): df2[col].ffill(inplace=True) df2[col] = df2[col].astype(int) elif df2[col].dtype == float: df2[col].loc[df2[col].first_valid_index(): df2[col].last_valid_index()]=df2[col].loc[df2[col].first_valid_index(): df2[col].last_valid_index()].astype(float).interpolate(inplace=True) else: df2[col].ffill(inplace=True) </code></pre> <p>...but that did not work and my <code>float64</code> columns are purely NaNs now...Also, the way I tried to insert the code, I know it would only have affected the <code>float</code> columns. In an ideal solution I would hope to do the set this <code>first_valid_index():.last_valid_index()</code> selection also to the <code>object</code> and <code>int64</code> columns. Can somebody help me? ..thank you </p>
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 NaN 2016-08-10 14:01:00 2.6 A 0 4.6 NaN 2016-08-10 14:02:00 4.8 A 0 NaN 4.3 2016-08-10 14:03:00 5.7 A 1 NaN NaN 2016-08-10 14:04:00 5.5 A 1 5.7 NaN 2016-08-10 14:05:00 5.6 A 1 NaN NaN 2016-08-10 14:06:00 7.8 A 1 NaN 5.2 2016-08-10 14:07:00 8.9 A 0 NaN NaN 2016-08-10 14:08:00 3.6 A 0 NaN NaN print (df.dtypes) A float64 B object C int64 D float64 E float64 dtype: object </code></pre> <p>Thanks to a lot of input from the community I have this code now which allows me to upsample my df to second intervals, applying different methods to different <code>dtypes</code> </p> <pre><code>int_cols = df.select_dtypes(['int64']).columns index = pd.date_range(df.index[0], df.index[-1], freq="s") df2 = df.reindex(index) for col in df2: if col == int_cols.all(): df2[col].ffill(inplace=True) df2[col] = df2[col].astype(int) elif df2[col].dtype == float: df2[col].interpolate(inplace=True) else: df2[col].ffill(inplace=True) </code></pre> <p>I am looking for a way now, to only interpolate between my actual measurements. The interpolate function extends my last measurement until the end of the <code>df</code>: </p> <pre><code> df2.tail() Out[75]: A B C D E 2016-08-10 14:07:56 3.953333 A 0 5.7 5.2 2016-08-10 14:07:57 3.865000 A 0 5.7 5.2 2016-08-10 14:07:58 3.776667 A 0 5.7 5.2 2016-08-10 14:07:59 3.688333 A 0 5.7 5.2 2016-08-10 14:08:00 3.600000 A 0 5.7 5.2 </code></pre> <p>But I would like to stop this when the last measurement took place (for example at 14:04:00 <code>col['D']</code> and 14:06:00 <code>col['D']</code>) and leave the NaNs. </p> <p>It tried adding a zero value for 'limit' and 'limit_direction' to 'both':</p> <pre><code> for col in df2: if col == int_cols.all(): df2[col].ffill(inplace=True) df2[col] = df2[col].astype(int) elif df2[col].dtype == float: df2[col].interpolate(inplace=True,limit=0, limit_direction='both') else: df2[col].ffill(inplace=True) </code></pre> <p>but this didn't change anything to the output. I than tried to incorporate the solution I found to this question: <a href="http://stackoverflow.com/questions/33691591/pandas-interpolation-where-first-and-last-data-point-in-column-is-nan">Pandas: interpolation where first and last data point in column is NaN</a> into my code:</p> <pre><code>for col in df2: if col == int_cols.all(): df2[col].ffill(inplace=True) df2[col] = df2[col].astype(int) elif df2[col].dtype == float: df2[col].loc[df2[col].first_valid_index(): df2[col].last_valid_index()]=df2[col].loc[df2[col].first_valid_index(): df2[col].last_valid_index()].astype(float).interpolate(inplace=True) else: df2[col].ffill(inplace=True) </code></pre> <p>...but that did not work and my <code>float64</code> columns are purely NaNs now...Also, the way I tried to insert the code, I know it would only have affected the <code>float</code> columns. In an ideal solution I would hope to do the set this <code>first_valid_index():.last_valid_index()</code> selection also to the <code>object</code> and <code>int64</code> columns. Can somebody help me? ..thank you </p>
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.nan, np.nan, 2.0, np.nan]}, columns=['A', 'B'], index=pd.date_range(start='2016-08-10 13:50:00', periods=7, freq='S')) print df A_first = df['A'].first_valid_index() A_last = df['A'].last_valid_index() df.loc[A_first:A_last, 'A'] = df.loc[A_first:A_last, 'A'].interpolate() B_first = df['B'].first_valid_index() B_last = df['B'].last_valid_index() df.loc[B_first:B_last, 'B'] = df.loc[B_first:B_last, 'B'].interpolate() print df </code></pre> <p>result:</p> <pre><code> A B 2016-08-10 13:50:00 NaN NaN 2016-08-10 13:50:01 1.0 NaN 2016-08-10 13:50:02 NaN 0.0 2016-08-10 13:50:03 NaN NaN 2016-08-10 13:50:04 4.0 NaN 2016-08-10 13:50:05 NaN 2.0 2016-08-10 13:50:06 NaN NaN A B 2016-08-10 13:50:00 NaN NaN 2016-08-10 13:50:01 1.0 NaN 2016-08-10 13:50:02 2.0 0.000000 2016-08-10 13:50:03 3.0 0.666667 2016-08-10 13:50:04 4.0 1.333333 2016-08-10 13:50:05 NaN 2.000000 2016-08-10 13:50:06 NaN NaN </code></pre> <p>The two problems in your code were:</p> <ol> <li>If you are going to do <code>df[...] = df[...].interpolate()</code>, you need to remove <code>inplace=True</code> since that will make it return <code>None</code>. That is your main problem and why you were getting all <code>NaNs</code>. </li> <li>Though it seems to work here, in general, chained indexing is bad:</li> </ol> <p>You want:</p> <pre><code>df.loc[A_first:A_last, 'A'] = df.loc[A_first:A_last, 'A'].interpolate() </code></pre> <p>Not: </p> <pre><code>df['A'].loc[A_first:A_last] = df['A'].loc[A_first:A_last].interpolate() </code></pre> <p>See here for more detail: <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy</a></p>
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.com/rxi4kfej" rel="nofollow">code</a> currently </p> <p>If anyone can help that would be much appreciated. And the csv file is called " data.csv "</p>
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><code> A B C a 11 13 15 b 20 22 24 c 20 22 24 </code></pre> <p>each elements shows conditional sum of df.for instance,(I am inconfident about expression) </p> <pre><code>result.loc[0,0]=df.loc[df.A=="a"].sum() </code></pre> <p>how can I get this dataframe ?</p>
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.jpg </code></pre> <p>Here's my code</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) dir_src = 'C:\\Users\\Willie\\Desktop\\Suppliers Dropship\\hunting\\' dir_dst = 'C:\\image\\' for file in os.listdir(dir_src): src_file = os.path.join(dir_src, file) dst_file = os.path.join(dir_dst, file) if file in rowDict[1]: shutil.move(src_file, dst_file) </code></pre>
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 = set(keys.values()) # file names found in csv dir_src = 'C:\\Users\\Willie\\Desktop\\Suppliers Dropship\\hunting\\' dir_dst = 'C:\\image\\' for file in os.listdir(dir_src): if file in valid_files: src_file = os.path.join(dir_src, file) dst_file = os.path.join(dir_dst, file) shutil.move(src_file, dst_file) </code></pre> <p>As an optimization, unless you need the <code>keys</code> dictionary for other processing, you could change the first part so it just creates the <code>valid_files</code> set variable used in the second <code>for</code> loop:</p> <pre><code>valid_files = set() # empty set with open('shuttle_image.csv', 'r') as f: for rowDict in csv.reader(f, delimiter=','): valid_files |= {rowDict[1]} # add file name to set print(rowDict) # if desired </code></pre>
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.jpg </code></pre> <p>Here's my code</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) dir_src = 'C:\\Users\\Willie\\Desktop\\Suppliers Dropship\\hunting\\' dir_dst = 'C:\\image\\' for file in os.listdir(dir_src): src_file = os.path.join(dir_src, file) dst_file = os.path.join(dir_dst, file) if file in rowDict[1]: shutil.move(src_file, dst_file) </code></pre>
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 understand correctly what you are trying to do you could try something like this (untested code):</p> <pre><code>import os import shutil import csv dir_src = 'C:\\Users\\Willie\\Desktop\\Suppliers Dropship\\hunting\\' dir_dst = 'C:\\image\\' with open('shuttle_image.csv', 'r') as f: reader = csv.reader(f, delimiter = ',') for rowDict in reader: id, filename = rowDict src_file = os.path.join(dir_src, filename) if os.path.exists(src_file): shutil.move(src_file, dir_dst) </code></pre> <p>So instead of:</p> <ol> <li><p>Constructing a dictionary with all the values in your CSV file </p></li> <li><p>Somehow check for every file in your source directory that it is included in your dictionary (which is what I interpreted you were trying to do) </p> <ul> <li>And move it if it does.</li> </ul></li> </ol> <p>You could:</p> <ol> <li>For every file extracted from your CSV, check that it exists in your source directory. <ul> <li>If it does, you move it to the destination directory.</li> </ul></li> </ol> <p>Is that what you were trying to do ?</p> <p>[And if the filename stays the same, you only need to specify the destination directory for the second argument of shutil.move()]</p>
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, and liba.so has some undefined function which can be solved in libb.so.</p> <p>But how to do that in ctypes? ctypes.cdll.LoadLibrary('liba.so') said that there are some undefined symbols, how to tell ctypes to find libb.so? Because ldd liba.so not show a link to libb.so.</p> <p>Example: I want to use some functions in gsl. In g++: </p> <pre><code>g++ main.cpp -lgsl -lgslcblas </code></pre> <p>and ldd libgsl.so does not show a link to libgslcblas</p> <p>In python:</p> <pre><code>ctypes.cdll.LoadLibrary('libgsl.so') </code></pre> <p>how to tell ctypes to find libgslcblas? </p> <p>The same problem also happen if I use scalapack. I use ubuntu 16.04</p>
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(data_list)) rects1 = ax.bar(y_pos, count_list, 0.28, color='r') # plt.bar(y_pos, count_list, 0.28, color='b', align='center', alpha=0.5) ax.set_xticks(y_pos, data_list) ax.set_xticklabels(data_list, rotation='vertical') ax.set_ylabel('Counts') ax.set_title('Some stats ') plt.plot() plt.ylim([0, 50]) autolabel(rects1) def autolabel(rects): # attach some text labels for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height, '%d' % int(height), ha='center', va='bottom') </code></pre> <p>which as you can see is standard boiler plate code. In my main I do:</p> <pre><code>if __name__ == "__main__": my_graph() plt.ion() while True: time.sleep(3) get_updated_data() my_graph() plt.pause(0.01) </code></pre> <p>get_updated_data will just pull new data and call the code to generate the graph. This is correctly updating the bars. However, the labels added above each bar aren't overwritten. They get "stacked" above each other each time the graph is refreshed. Whats the appropriate way to fix this ? I have tried fig.canvas.draw() but it is not working. Maybe I am adding it in the wrong place. Whats the right approach ?</p> <p>Thanks</p>
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.canvas.draw() </code></pre>
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 so on. i.e. the shape at the bottom is the original shape.</p> <p>So I tried to do this in a recursive manner using some ideas from mathematical induction.</p> <pre><code>def tree(n, shape): a = n if n == 1: return scale(1/a, shape) else: return overlay_frac((n-1)/n, tree(n-1, shape) , scale(n/a, shape)) </code></pre> <p>My question is how would you fix the initial value of <code>n</code> because this recursion keeps altering the value? I can't set <code>a = n</code> outside of the recursion as <code>n</code> is defined in the function.</p> <p>Is there a way for me to set the initial value of <code>n</code> to another letter so it wouldn't change?</p> <p>Right now I'm not even sure if this code works. But without being able to fix it, I can't test it.</p> <p>FYI: I am aware that you guys might not know what <code>overlay_frac</code> and <code>scale</code> does but the codes for those are given to me.</p> <p>My question really revolves around a way to set the initial input of a recursion so that it will not be affected as the process loops.</p>
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 = initial_size if n == 1: return scale(1/a, shape) else: return overlay_frac((n-1)/a, tree(n-1, initial_size, shape), \ scale(n/a, shape)) </code></pre>
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 so on. i.e. the shape at the bottom is the original shape.</p> <p>So I tried to do this in a recursive manner using some ideas from mathematical induction.</p> <pre><code>def tree(n, shape): a = n if n == 1: return scale(1/a, shape) else: return overlay_frac((n-1)/n, tree(n-1, shape) , scale(n/a, shape)) </code></pre> <p>My question is how would you fix the initial value of <code>n</code> because this recursion keeps altering the value? I can't set <code>a = n</code> outside of the recursion as <code>n</code> is defined in the function.</p> <p>Is there a way for me to set the initial value of <code>n</code> to another letter so it wouldn't change?</p> <p>Right now I'm not even sure if this code works. But without being able to fix it, I can't test it.</p> <p>FYI: I am aware that you guys might not know what <code>overlay_frac</code> and <code>scale</code> does but the codes for those are given to me.</p> <p>My question really revolves around a way to set the initial input of a recursion so that it will not be affected as the process loops.</p>
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) { return rune; } else { return overlay_frac(1 / k, scale((1 + n - i)/ n, rune), drawTree(i - 1)); } } return drawTree(n); } </code></pre>
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 what is the difference between these two in terms of internal functions and which is better to use?</p>
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 check it , you may need to locate the folder contains python.exe to run <strong><em>.py</em></strong> file .</p> <p>In addition , python.exe can be run under other user privilege using 'start-process' with parameter '-credential' . If you run python.exe in PS console it will inherits user privilege of PS console .</p>
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 image.ndim == 2 </code></pre>
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; float *data; }; int read_image(struct myimage_t *output); // fill in '*output' void free_image(struct myimage_t *img); // free output-&gt;data """) myimage = ffi.new("struct myimage_t *") if lib.read_image(myimage) &lt; 0: raise IOError ... lib.free_image(myimage) </code></pre> <p>Then you need to manually convert the <code>myimage</code> to a numpy array, somewhere in the "..." code above.</p> <p>One better alternative is to use a Python callback: a callback that makes the numpy array according to spec and returns a C-standard <code>float *</code> pointer. The numpy array itself is saved somewhere in the callback. You could save it as a Python global, or more cleanly use a "handle" you pass via C. Requires the API version, not the ABI. In _example_build.py:</p> <pre><code>ffi.cdef(""" extern "Python" float *alloc_2d_numpy_array(void *handle, int w, int h); void read_image(void *handle); """) ffi.set_source("_example_cffi", """ void read_image(void *handle) { // the C code that eventually invokes float *p = alloc_2d_numpy_array(handle, w, h); // and then fill the data at 'p' } """) ffi.compile(verbose=True) </code></pre> <p>In file example.py:</p> <pre><code>from _example_cffi import ffi, lib class Context: pass @ffi.def_extern() def alloc_2d_numpy_array(handle, w, h): context = ffi.from_handle(handle) context.image = np.ndarray([w, h], dtype=np.float32) return ffi.cast("float *", ffi.from_buffer(context.image)) context = Context() lib.read_image(ffi.new_handle(context)) image = context.image </code></pre>
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> <p>Word 3/5: Name How many vowels does the word contain</p> <p>5</p> <p>Incorrect! Correct answer 4</p> <p>Word 4/5: YES How many letters does the word contain? 3 Correct!</p> <p>Word 5/5: Day</p> <p>What is letter 3 of the word?</p> <p>Y</p> <p>Correct!</p> <p>Game Over. Your Score is 4/5</p> </blockquote> <p>@Niemmi Like this this? import random import string</p> <pre><code>def consonant_count(word): word = word.lower() return len([x for x in word if x in consonants]) def vowel_count(word): word = word.lower() return len([x for x in word if x in vowels]) def prompt_letter_count(word): correct = word_map[word]['letters'] ans = input('How many letters does "{}" contain?'.format(word)) return check(int(ans), correct) def prompt_vowel_count(word): correct = word_map[word]['vowels'] ans = input('How many vowels does "{}" contain?'.format(word)) return check(int(ans), correct) def prompt_consonant_count(word): correct = word_map[word]['consonants'] ans = input('How many consonants does "{}" contain?'.format(word)) return check(int(ans), correct) def prompt_random_letter(word): n = random.randint(0, len(word)) correct = word[n-1] ans = input('What is letter {} of "{}"?'.format(n, word)) return check(int(ans).lower(), correct.lower()) def check(ans, correct): if ans == correct: return prompt_correct() return prompt_incorrect() def prompt_correct(): print('That is correct! :)') return 1 def prompt_incorrect(): print('That is incorrect :(') return 0 def next_question(word): q_type = input_map[random.randint(1, 4)] return q_type(word) vowels = ['a', 'e', 'i', 'o', 'u'] consonants = [x for x in string.ascii_lowercase if x not in vowels] quizWords = ['WOMBAT', 'COMPUTER', 'BOOKS', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'HUGE', 'TINY', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'KOOKARBURRA', 'POSTER', 'TELEVISION', 'PRINCE', 'RHYTHM', 'SUDDENLY', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY'] word_map = {x:{'consonants':consonant_count(x), 'vowels':vowel_count(x), 'letters':len(x)} for x in quizWords} input_map = {1:prompt_letter_count, 2:prompt_vowel_count, 3:prompt_consonant_count, 4:prompt_random_letter} def start_quiz(number_questions): current_question = 0 correct_questions = 0 if number_questions &gt; len(quizWords): number_questions = len(quizWords) sample_questions = random.sample(quizWords, number_questions) print('WELCOME TO YOUR QUIZ') print ('---------------------') for x in sample_questions: print ("Question {}/{}:".format(current_question+1, number_questions)) correct_questions += next_question(x) print ('---------------------') current_question += 1 print ('Congragulations on completing your quiz!') print (" Score {}/{}:".format(correct_questions , number_questions)) try_again = input('Would you like to try again? (y/n)').lower() if try_again == 'y' or try_again == 'yes': start_quiz(number_questions) start_quiz(4) </code></pre>
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#raw_input" rel="nofollow"><code>raw_input</code></a> on Python 2 returning a string that you need to convert to other type yourself. You should be able to fix your code by doing the conversions at the required places and switching all <code>raw_input</code> calls to <code>input</code> since there's no <code>raw_input</code> on Python 3.</p> <p>Example:</p> <pre><code>def prompt_letter_count(word): correct = word_map[word]['letters'] ans = input('How many letters does "{}" contain?'.format(word)) return check(int(ans), correct) # instead of check(ans, correct) </code></pre>
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) category_list = Category.objects.all() context_dict = {'categories': category_list} for category in category_list: category.url = encode_url(category.name) page_list = Page.objects.order_by('-views')[:5] context_dict['pages'] = page_list #### 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) if (datetime.now() - datetime.strptime(last_visit_time[:-7], "%Y-%m-%d %H:%M:%S")).days &gt; 0: request.session['visits'] = visits + 1 request.session['last_visit'] = str(datetime.now()) else: # The get returns None, and the session does not have a value for the last visit. request.session['last_visit'] = str(datetime.now()) request.session['visits'] = 1 #### END NEW CODE #### # Render and return the rendered response back to the user. return render_to_response('rango/index.html', context_dict, context) </code></pre> <p>When i tried to understand what request.session.get('last_visit') does, i get None all the time. What i don't understand is the key 'last_visit'. Is it default object inside session? If it is default in the session object then why it shows None every time in my terminal.</p> <p>Please someone make me understand the object passed inside get().</p>
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) if (datetime.now() - datetime.strptime(last_visit_time[:-7], "%Y-%m-%d %H:%M:%S")).days &gt; 0: request.session['visits'] = visits + 1 request.session['last_visit'] = str(datetime.now()) else: # The get returns None, and the session does not have a value for the last visit. request.session['last_visit'] = str(datetime.now()) request.session['visits'] = 1 #### END NEW CODE #### context = RequestContext(request) category_list = Category.objects.all() context_dict = {'categories': category_list} for category in category_list: category.url = encode_url(category.name) page_list = Page.objects.order_by('-views')[:5] context_dict['pages'] = page_list # Render and return the rendered response back to the user. return render_to_response('rango/index.html', context_dict, context) </code></pre>
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</code> added in the past (even if said object was removed). When I export the object as .obj the names are no longer the same as before.</p> <p>How do I reset that "name-counter"? </p>
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. Objects that have been deleted are not considered in this process, while other items like materials and mesh data remain in the lists until the file is closed.</p> <p>The obj importer first creates the mesh datablock and then creates an object using the same name as the mesh data - this leads to the new objects always having a numeric suffix larger than previous objects.</p> <p>If you are importing multiple objects using a python script you can rename the object after you import it.</p> <pre><code>bpy.ops.import_scene.obj(filepath='Object1.obj') bpy.context.selected_objects[0].name = 'Object' bpy.context.selected_objects[0].data.name = 'Object' </code></pre> <p>In this scenario any existing object with the name "Object" will get renamed to have a suffix.</p>
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 itertools.combinations(l, 2): if some_function(a,b): remove_any_tup_with_a_or_b(a, b) </code></pre> <p>My list <code>l</code> is pretty big so I don't want to keep the combinations in memory.</p>
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 like <code>isdisjoint</code> will be faster than Python level <code>if</code> checks with <code>continue</code> statements typically, by pushing the <code>filter</code> work to the C layer):</p> <pre><code>from future_builtins import filter # Only on Py2, for generator based filter import itertools blacklist = set() for a, b in filter(blacklist.isdisjoint, itertools.combinations(l, 2)): if some_function(a,b): blacklist.update((a, b)) </code></pre>
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 itertools.combinations(l, 2): if some_function(a,b): remove_any_tup_with_a_or_b(a, b) </code></pre> <p>My list <code>l</code> is pretty big so I don't want to keep the combinations in memory.</p>
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>itertools.combinations(l, 2)</code> that <strong>don't</strong> contain the number <code>x</code>.</p> <p><strong>Example:</strong></p> <p>The set of all of combinations from <code>itertools.combinations([1,2,3,4], 2)</code> that don't contain the number 1 is given by <code>[(2, 3), (2, 4), (3, 4)]</code>. Notice that the number of elements in this list is equal to the number of elements of combinations in the list <code>itertools.combinations([1,2,3], 2)=[(1, 2), (1, 3), (2, 3)]</code>. </p> <p>Since order doesn't matter in combinations, you can map 1 to 4 in <code>[(1, 2), (1, 3), (2, 3)]</code> to get <code>[(1, 2), (1, 3), (2, 3)]=[(4, 2), (4, 3), (2, 3)]=[(2, 4), (3, 4), (2, 3)]=[(2, 3), (2, 4), (3, 4)]</code>.</p>
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 COEFFICIENT 0 A 0.5 1 B 0.4 2 C 0.3 </code></pre> <p>From the above dataframe, I need to create a final dataframe as below which has a matrix structure with the product of the coefficients:</p> <pre><code> A B C A 0.25 0.2 0.15 B 0.2 0.16 0.12 C 0.15 0.12 0.09 </code></pre> <p>I am using <code>np.multiply</code> but I am not successful in producing the result.</p>
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 A B C CODE A 0.25 0.20 0.15 B 0.20 0.16 0.12 C 0.15 0.12 0.09 </code></pre>
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 COEFFICIENT 0 A 0.5 1 B 0.4 2 C 0.3 </code></pre> <p>From the above dataframe, I need to create a final dataframe as below which has a matrix structure with the product of the coefficients:</p> <pre><code> A B C A 0.25 0.2 0.15 B 0.2 0.16 0.12 C 0.15 0.12 0.09 </code></pre> <p>I am using <code>np.multiply</code> but I am not successful in producing the result.</p>
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</em></strong></p> <p><a href="http://i.stack.imgur.com/d8W0P.png" rel="nofollow"><img src="http://i.stack.imgur.com/d8W0P.png" alt="enter image description here"></a></p> <p><strong><em>30,000 rows</em></strong></p> <pre><code>df = pd.concat([df for _ in range(10000)], ignore_index=True) </code></pre> <p><a href="http://i.stack.imgur.com/Q5nee.png" rel="nofollow"><img src="http://i.stack.imgur.com/Q5nee.png" alt="enter image description here"></a></p>
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, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.</p> <p>To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in <strong>calculator mode</strong>).</p> </blockquote> <p>(Emphasis mine)</p> <p>Here's the <a href="https://docs.python.org/3/tutorial/modules.html" rel="nofollow">original document</a>.</p>
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> or <code>python[version-number]</code> in your command prompt/terminal window:</p> <p>Assuming that you have python in your <code>PATH</code> variable, you can access the Python Shell by simply typing <code>python</code> or <code>python[version-number]</code> in your command prompt/terminal window.</p></li> <li><p>Running the Python Shell in the Python IDLE(Integrated Development Environment) GUI:</p> <p>To run the Python Shell in the Python IDLE GUI, you can type(again i'm assuming that the path to your python installation folder, is in your PATH variable), just type <code>idle</code> into your command prompt\terminal window and this should start the Python Shell in the Python IDLE GUI.</p></li> </ul> <p>Of course the exact text for the Python Shell heading will vary between OS's, but all of them look very similar. Here is an example of what the heading appears like on my mac:</p> <pre><code>Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; </code></pre> <p>As you might can tell from the text above, a newline in the Python Shell is denoted by three caret symbols: <code>&gt;&gt;&gt;</code>. Each newline, a new three carets are printed. When using Python Shell, there are a few differences, then just typing a script up, but the main one is that it execute your code line by line.</p> <p>In the Python Shell you can only type one line of code at a time. Here is an example to illustrate my point further:</p> <pre><code> &gt;&gt;&gt; xyz = 100 &gt;&gt;&gt; for i in range(1, 20): ... xyz += i ... print(xyz) ... 101 103 106 110 115 121 128 136 145 155 166 178 191 205 220 236 253 271 290 &gt;&gt;&gt; </code></pre> <p>As you can tell from the above program, indention is noted by three dots: <code>...</code>, and the only time the Python Shell shows more then one line at a time, is when it is 'echoing' back what you typed in.</p> <h2>Why is it called interactive?</h2> <p>One of the main reason its called interactive is that to display variable values or run the module in general, you don't have to explicitly invoke the python interpreter. Take the example below:</p> <pre><code>&gt;&gt;&gt; name = "Christian" &gt;&gt;&gt; name 'Christian' &gt;&gt;&gt; def func(): ... print(name) ... &gt;&gt;&gt; func() Christian &gt;&gt;&gt; </code></pre> <p>As displayed above, I was able to print the value of <code>name</code> and run the function <code>func()</code> without having to use a print command or explicitly calling the python interpreter.</p> <p>The Python Shell is not really a practical way to write long/complex programs, as writing code <code>__init__</code>(see what i did there) would prove to be cumbersome and awkward. A better choice would be to use the <a href="https://docs.python.org/3/library/idle.html" rel="nofollow">Python IDLE</a>. It is a script editor for python that comes builtin into the python installation package.</p> <p><sub>Disclaimer: i could be completely wrong about this. I am simply going off of the python docs and my own experience ;).</sub></p>
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> <li><p>I have defined the MEDIA_ROOT and MEDIA_URL in <em>settings.py</em></p> <pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" </code></pre></li> <li><p>This is my upload model in <em>models.py</em>:</p> <pre><code>from django.utils.html import mark_safe class ImageDetails(models.Model): image = models.ImageField(null=True) def image_img(self): if self.image: return mark_safe('&lt;img src="%s" height="125px" width="125px"/&gt;' % (self.image.url)) else: return '(No image found)' image_img.short_description = 'Thumbnail' </code></pre></li> <li><p>In my Application <em>urls.py</em>:</p> <pre><code>urlpatterns = [ url(r'^inputImage', views.inputImage, name='inputImage'), url(r'', views.index), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) </code></pre></li> <li><p>In my admin.py:</p> <pre><code>class ImageDetailsAdmin(admin.ModelAdmin): fields = ["image"] #for file upload list_display = ("image_img",) admin.site.register(ImageDetails, ImageDetailsAdmin) </code></pre></li> </ol> <p>The image was successfully stored at <em>ProjectDIR/media</em>. The HTML returns the url: <a href="http://127.0.0.1:8000/media/imagename.jpg" rel="nofollow">http://127.0.0.1:8000/media/imagename.jpg</a> at img tag. But the page fails to load the image (I will be redirected to index page whenever when using the url <a href="http://127.0.0.1:8000/media/imagename.jpg" rel="nofollow">http://127.0.0.1:8000/media/imagename.jpg</a>). I am using Django version 1.10</p>
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'), </code></pre> <p>And adding the following code at the project's main urls.py:</p> <pre><code> if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) </code></pre>
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 file</strong></p> <pre><code>server { listen 80; listen 443 ssl; server_name example.com; rewrite /test redirectexample.com/test permanent; rewrite / http://redirectedexample.com permanent; } server { listen 80; listen 443 ssl; server_name test.com; rewrite /example testing.com/example permanent; rewrite / http://www.testing.com permanent; } </code></pre> <p><strong>Script</strong></p> <pre><code>import.os InputFile= open('/tmp/redirect.conf', 'r') dict = {} file =InputFile.readlines() parsing = False for line in file: if line.startswith("}"): parsing = False if parsing: # Run some command here if line.startswith("server {"): parsing = True </code></pre> <p>I am not sure where to start calling the dictionary as I want to somehow call everything between the first <code>server {</code> and <code>}</code>. The final goal is to be able to run a curl to test the example.com/test redirection and test.com/example redirect get the output from this and diff that to what is currently in our configuration files. The purpose of this is to audit these prior to moving them to avoid keeping configurations that are no longer needed. I had trouble finding info on this, if there is a document somewhere I need to RTFM then please feel free to drop a link.</p> <p><strong>Edit</strong></p> <p>Things looking for script to do:</p> <ol> <li><p>Take nginx server block's and grab value(s) of "server_name"</p></li> <li><p>Grab value of rewrite /test /example &lt;-- actual string is random</p></li> <li><p>Test both of these value's with <code>curl -w "%{url_effective}\n" -I -L -s -S $m -o /dev/null</code></p></li> <li><p>Then diff the curl output to whats rewritten.</p></li> </ol> <p>Take note that I don't need to parse example.com/example as the /example redirection is in a different server block.</p> <p>Hope this makes more since. There are thousands of server blocks hence the reason for this.</p>
-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><code>import itertools def isplit(iterable, splitters): # thank you http://stackoverflow.com/a/4322780/6085135 return [list(g) for k,g in itertools.groupby(iterable,lambda x:x in splitters) if not k] with open('example.txt', 'r') as f: data = f.read() # split the data into lists data = data.replace('{', '').replace('}', '').replace(';', ' ;') data = data.split() data = isplit(data, ('server',)) # construct dict from sublists servers = {} for block in data: block = isplit(block, (';',)) server = {} for item in block: key, value = item[0], ' '.join(item[1:]) if key not in server.keys(): server[key] = value else: if isinstance(server[key], list): server[key] = server[key].append(value) else: server[key] = [server[key], value] server_name = server.pop('server_name') servers.update({server_name: server}) print(servers) </code></pre> <p>Output:</p> <pre><code>{ 'test.com': { 'listen': ['80', '443 ssl'], 'rewrite': ['/example testing.com/example permanent', '/ http://www.testing.com permanent'] }, 'example.com': { 'listen': ['80', '443 ssl'], 'rewrite': ['/test redirectexample.com/test permanent', '/ http://redirectedexample.com permanent'] } } </code></pre>
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).</p> <p>Here is an example:</p> <pre><code>my_module - __init__.py - a.py - b.py - setup.py </code></pre> <p>where <code>a.py</code> contains <code>import b</code>.</p> <p>I want to write <code>b.py</code> in Cython. The idea would be to add a folder containing the <code>.pyx</code> file, for example:</p> <pre><code>my_module - __init_.py - a.py - b.py - setup.py cython -b.pyx </code></pre> <p><code>setup.py</code> would contain the direction to compile <code>b.pyx</code> and to install the module. However, I would like that if someone runs <code>python setup.py install</code> then the pure Python code is installed, whereas if an option is added then the Cython code is compiled and installed. </p> <p>Any idea how to do that?</p> <p>Also, how should the file <code>a.py</code> be modified in order to import the correct module?</p>
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 MAKE_NOISE = False def external(f): """ Decorator that looks for an external version of the decorated function -- if one is found and imported, it replaces the decorated function in-place (and thus transparently, to would-be users of the code). """ f.__external__ = 0 # Mark func as non-native function_name = hasattr(f, 'func_name') and f.func_name or f.__name__ module_name = inspect.getmodule(f).__name__ # Always return the straight decoratee func, # whenever something goes awry. if not function_name or not module_name: MAKE_NOISE and print("Bad function or module name (respectively, %s and %s)" % ( function_name, module_name), file=sys.stderr) return f # This function is `pylire.process.external()`. # It is used to decorate functions in `pylire.process.*`, # each of which possibly has a native (Cython) accelerated # version waiting to be imported in `pylire.process.ext.*` # … for example: if in `pylire/process/my_module.py` you did this: # # @external # def my_function(*args, **kwargs): # """ The slow, pure-Python implementation """ # pass # # … and you had a Cython version of `my_function()` set up # in `pylire/process/ext/my_module.pyx` – you would get the fast # function version, automatically at runtime, without changing code. # # TL,DR: you'll want to change the `pylire.process.ext` string (below) # to match whatever your packages' structure looks like. module_file_name = module_name.split('.')[-1] module_name = "pylire.process.ext.%s" % module_file_name # Import the 'ext' version of process try: module = import_module(module_name) except ImportError: MAKE_NOISE and print("Error importing module (%s)" % ( module_name,), file=sys.stderr) return f MAKE_NOISE and print("Using ext module: %s" % ( module_name,), file=sys.stderr) # Get the external function with a name that # matches that of the decoratee. try: ext_function = getattr(module, function_name) except AttributeError: # no matching function in the ext module MAKE_NOISE and print("Ext function not found with name (%s)" % ( function_name,), file=sys.stderr) return f except TypeError: # function_name was probably shit MAKE_NOISE and print("Bad name given for ext_function lookup (%s)" % ( function_name,), file=sys.stderr) return f # Try to set telltale/convenience attributes # on the new external function -- this doesn't # always work, for more heavily encythoned # and cdef'd function examples. try: setattr(ext_function, '__external__', 1) setattr(ext_function, 'orig', f) except AttributeError: MAKE_NOISE and print("Bailing, failed setting ext_function attributes (%s)" % ( function_name,), file=sys.stderr) return ext_function return wraps(f)(ext_function) </code></pre> <p>… this lets you decorate functions as <code>@external</code> – and they are replaced at runtime automatically with the Cython-optimized versions you’ve provided.</p> <p>If you wanted to extend this idea to replacing entire Cythonized classes, it’d be straightforward to use the same logic in the <code>__new__</code> method of a metaclass (e.g. opportunistic find-and-replace in the optimized module).</p>
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).</p> <p>Here is an example:</p> <pre><code>my_module - __init__.py - a.py - b.py - setup.py </code></pre> <p>where <code>a.py</code> contains <code>import b</code>.</p> <p>I want to write <code>b.py</code> in Cython. The idea would be to add a folder containing the <code>.pyx</code> file, for example:</p> <pre><code>my_module - __init_.py - a.py - b.py - setup.py cython -b.pyx </code></pre> <p><code>setup.py</code> would contain the direction to compile <code>b.pyx</code> and to install the module. However, I would like that if someone runs <code>python setup.py install</code> then the pure Python code is installed, whereas if an option is added then the Cython code is compiled and installed. </p> <p>Any idea how to do that?</p> <p>Also, how should the file <code>a.py</code> be modified in order to import the correct module?</p>
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 setup from Cython.Build import cythonize import numpy setup( name='My_module', ext_modules=cythonize(["cython_my_module/b.pyx",]), include_dirs=[numpy.get_include()], ) </code></pre> <p>and the file <code>a.py</code> would contain the following lines in the header:</p> <pre><code>try: import cython_my_module.b except ImportError: import b </code></pre> <p>The way it works is very simple: if you don't do anything (i.e. if you don't compile the cython files) then module <code>a.py</code> imports module <code>b.py</code>; however, if you run <code>python setup.py build_ext --inplace</code> then the compiled cython files will appear inside <code>cython_my_module</code> and the next time you run <code>a.py</code> it will automatically import the cython module <code>b.pyx</code> (actually it will import the compiled library <code>b.so</code>).</p> <p>So far it seems to work and requires almost no effort. Hope it helps.</p> <p>fish2000 solution seems more generic but I haven't tried it yet. </p>
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 to go with, but you have to query the database multiple times. Is there a better way to do this?</p>
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 since at work I spend all my time with programing languages that require it, and only play with python in my spare time, putting semicolons on the end of every statement is a rather ingrained habit. And it's just going to be me looking at my codes anyway so if it's just a style convention I'm not going to worry about it. But if there's an actual reason to avoid it I'd like to know.</p> <p>So my question is: Does it actually hurt to use them or is it just bad style? I mean does it cause any performance or other issues or is it just a readability thing?</p> <p>Why I think this question is different then the one where the guy was asking if they need to put them in, is that I wanted to know if it slowed down the running of the program, or caused it to use more memory or anything other then simply "making it harder for a person to read the code" that wasn't addressed in that topic.</p>
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_length=30, null=False) uploadDate = models.DateTimeField(null=False) message = models.CharField(max_length=200, null=False) original_video = models.FileField(upload_to='video', null=True) converted = models.BooleanField(default=False) </code></pre> <p>And the code of converted.</p> <pre><code>video = Video.objects.filter(id=param_id).get() pathConverted = 'C:\\Users\\diego\\Documents\\GitHub\\convertido.mp4' cmd = ['ffmpeg', '-i ', video.original_video.path, ' -b 1500k -vcodec ibx264 -g 30', pathConverted] print('Ejecutando... ', ' '.join(cmd)) try: proc = subprocess.run(cmd, shell=True, check=True) proc.subprocess.wait() except subprocess.CalledProcessError as e: raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)) </code></pre> <p>The error is this.</p> <pre><code> raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)) RuntimeError: command '['ffmpeg', '-i ', 'C:\\Users\\diego\\Documents\\GitHub\\video1.avi', ' -b 1500k -vcodec libx264 -g 30', 'C:\\Users\\diego\\Documents\\GitHub\\convertido.mp4']' return with error (code 1): None </code></pre> <p>And also I have tried this:</p> <pre><code>video = Video.objects.filter(id=1).get() pathConverted = 'C:\\Users\\diego\\Documents\\GitHub\\convertido.mp4' cmd = ['ffmpeg', '-i ', video.original_video.path, ' -b 1500k -vcodec libx264 -g 30', pathConverted] print('Ejecutando... ', ' '.join(cmd)) proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) proc.subprocess.wait() </code></pre> <p>In this case the error is:</p> <pre><code>FileNotFoundError: [WinError 2] No such file or directory </code></pre> <p>But when I copy the path and paste this in CMD on windows for try this converted the video. It works fine.</p> <p>Then, I am confused, I don't understand what is the error.</p> <p>Somebody can help me please?</p>
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() self.window.set_border_width(10) self.window.set_title("GPS") self.window.connect("destroy", Gtk.main_quit) vbox = Gtk.VBox(False, 10) embed = GtkChamplain.Embed() self.view = embed.get_view() self.view.set_reactive(True) self.view.connect('button-release-event', self.mouse_click_cb, self.view) projector = Champlain.MapProjection.MAP_PROJECTION_MERCATOR renderer = Champlain.ImageRenderer() map_new = Champlain.FileTileSource.new_full('1','Colombia','OSM','Champlain',10,15,256, projector, renderer) map_source = Champlain.FileTileSource.load_map_data(map_new,'Utilidades/map.osm') self.view.set_property('kinetic-mode', True) self.view.set_property('map-source', map_source) #... self.window.add(vbox) self.window.show_all() </code></pre> <p>When I'm trying to run the code, the next error appears:</p> <blockquote> <blockquote> <p>Traceback (most recent call last): File "GUI.py", line 125, in LauncherGTK() File "GUI.py", line 33, in <strong>init</strong> projector = Champlain.MapProjection.MAP_PROJECTION_MERCATOR AttributeError: type object 'ChamplainMapProjection' has no attribute 'MAP_PROJECTION_MERCATOR' Press any key to continue . . .</p> </blockquote> </blockquote> <p>Someone has any idea of what I'm doing wrong?</p>
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>.</p>
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','no','no']}) </code></pre> <p><a href="http://i.stack.imgur.com/Mq1F2.png" rel="nofollow"><img src="http://i.stack.imgur.com/Mq1F2.png" alt="enter image description here"></a></p> <p>I would like to create a filtered DataFrame that lists only those cars that have all three features presented: the DVD player, the sunroof and a warranty (we know it is BMW here that has all features set to 'yes').</p> <p>I can do one column at time with:</p> <pre><code>cars_with_warranty = df['car'][df['warranty']=='yes'] print(cars_with_warranty) </code></pre> <p><a href="http://i.stack.imgur.com/hz3mn.png" rel="nofollow"><img src="http://i.stack.imgur.com/hz3mn.png" alt="enter image description here"></a></p> <p>Then I need to do a similar column calculation for dvd and sunroof columns:</p> <pre><code>cars_with_dvd = df['car'][df['dvd']=='yes'] cars_with_sunroof = df['car'][df['sunroof']=='yes'] </code></pre> <p>I wonder if there is a clever way of creating the filtered <code>DataFrame</code>?</p> <h3>EDITED LATER:</h3> <p>The posted solution works well. But the resulting <code>cars_with_all_three</code> is a simple list variable. We need the DataFrame object with a single 'bmw' car as its the only row and all three columns in place: dvd, sunroof and warranty (with all three values set to 'yes').</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>
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_all_three)</code> you will get <code>['bmw']</code>.</p> <p>Or, if you want to get really clever and use one-liner, you can do this:</p> <pre><code>[car for ind, car in enumerate(df['car']) if df['dvd'][ind] == df['warranty'][ind] == df['sunroof'][ind] == 'yes'] </code></pre> <p>Hope it helps</p>
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','no','no']}) </code></pre> <p><a href="http://i.stack.imgur.com/Mq1F2.png" rel="nofollow"><img src="http://i.stack.imgur.com/Mq1F2.png" alt="enter image description here"></a></p> <p>I would like to create a filtered DataFrame that lists only those cars that have all three features presented: the DVD player, the sunroof and a warranty (we know it is BMW here that has all features set to 'yes').</p> <p>I can do one column at time with:</p> <pre><code>cars_with_warranty = df['car'][df['warranty']=='yes'] print(cars_with_warranty) </code></pre> <p><a href="http://i.stack.imgur.com/hz3mn.png" rel="nofollow"><img src="http://i.stack.imgur.com/hz3mn.png" alt="enter image description here"></a></p> <p>Then I need to do a similar column calculation for dvd and sunroof columns:</p> <pre><code>cars_with_dvd = df['car'][df['dvd']=='yes'] cars_with_sunroof = df['car'][df['sunroof']=='yes'] </code></pre> <p>I wonder if there is a clever way of creating the filtered <code>DataFrame</code>?</p> <h3>EDITED LATER:</h3> <p>The posted solution works well. But the resulting <code>cars_with_all_three</code> is a simple list variable. We need the DataFrame object with a single 'bmw' car as its the only row and all three columns in place: dvd, sunroof and warranty (with all three values set to 'yes').</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>
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') &amp; (df.sunroof == 'yes') &amp; (df.warranty == 'yes')) 0 True 1 False 2 False 3 False dtype: bool print (df[(df.dvd == 'yes') &amp; (df.sunroof == 'yes') &amp; (df.warranty == 'yes')]) car dvd sunroof warranty 0 bmw yes yes yes #if need filter only column 'car' print (df.ix[(df.dvd == 'yes')&amp;(df.sunroof == 'yes')&amp;(df.warranty == 'yes'), 'car']) 0 bmw Name: car, dtype: object </code></pre> <p>Another solution with checking if all values in columns are <code>yes</code> and then check if all values are <code>True</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html" rel="nofollow"><code>all</code></a>:</p> <pre><code>print ((df[[ u'dvd', u'sunroof', u'warranty']] == "yes").all(axis=1)) 0 True 1 False 2 False 3 False dtype: bool print (df[(df[[ u'dvd', u'sunroof', u'warranty']] == "yes").all(axis=1)]) car dvd sunroof warranty 0 bmw yes yes yes print (df.ix[(df[[ u'dvd', u'sunroof', u'warranty']] == "yes").all(axis=1), 'car']) 0 bmw Name: car, dtype: object </code></pre> <p>Solution with minimal code, if <code>DataFrame</code> has only <code>4</code> columns like sample:</p> <pre><code>print (df[(df.set_index('car') == 'yes').all(1).values]) car dvd sunroof warranty 0 bmw yes yes yes </code></pre> <p><strong>Timings</strong>:</p> <pre><code>In [44]: %timeit ([car for ind, car in enumerate(df['car']) if df['dvd'][ind] == df['warranty'][ind] == df['sunroof'][ind] == 'yes']) 10 loops, best of 3: 120 ms per loop In [45]: %timeit (df[(df.dvd == 'yes')&amp;(df.sunroof == 'yes')&amp;(df.warranty == 'yes')]) The slowest run took 4.39 times longer than the fastest. This could mean that an intermediate result is being cached. 100 loops, best of 3: 2.09 ms per loop In [46]: %timeit (df[(df[[ u'dvd', u'sunroof', u'warranty']] == "yes").all(axis=1)]) 1000 loops, best of 3: 1.53 ms per loop In [47]: %timeit (df[(df.ix[:, [u'dvd', u'sunroof', u'warranty']] == "yes").all(axis=1)]) The slowest run took 4.46 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 1.51 ms per loop In [48]: %timeit (df[(df.set_index('car') == 'yes').all(1).values]) 1000 loops, best of 3: 1.64 ms per loop In [49]: %timeit (mer(df)) The slowest run took 4.17 times longer than the fastest. This could mean that an intermediate result is being cached. 100 loops, best of 3: 3.85 ms per loop </code></pre> <p><strong>Code for timings</strong>:</p> <pre><code>df = pd.DataFrame({ 'car': ['bmw','geo','vw','porsche'], 'warranty': ['yes','yes','yes','no'], 'dvd': ['yes','yes','no','yes'], 'sunroof': ['yes','no','no','no']}) print (df) df = pd.concat([df]*1000).reset_index(drop=True) def mer(df): df = df.set_index('car') return df[df[[ u'dvd', u'sunroof', u'warranty']] == "yes"].dropna().reset_index() </code></pre>
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','no','no']}) </code></pre> <p><a href="http://i.stack.imgur.com/Mq1F2.png" rel="nofollow"><img src="http://i.stack.imgur.com/Mq1F2.png" alt="enter image description here"></a></p> <p>I would like to create a filtered DataFrame that lists only those cars that have all three features presented: the DVD player, the sunroof and a warranty (we know it is BMW here that has all features set to 'yes').</p> <p>I can do one column at time with:</p> <pre><code>cars_with_warranty = df['car'][df['warranty']=='yes'] print(cars_with_warranty) </code></pre> <p><a href="http://i.stack.imgur.com/hz3mn.png" rel="nofollow"><img src="http://i.stack.imgur.com/hz3mn.png" alt="enter image description here"></a></p> <p>Then I need to do a similar column calculation for dvd and sunroof columns:</p> <pre><code>cars_with_dvd = df['car'][df['dvd']=='yes'] cars_with_sunroof = df['car'][df['sunroof']=='yes'] </code></pre> <p>I wonder if there is a clever way of creating the filtered <code>DataFrame</code>?</p> <h3>EDITED LATER:</h3> <p>The posted solution works well. But the resulting <code>cars_with_all_three</code> is a simple list variable. We need the DataFrame object with a single 'bmw' car as its the only row and all three columns in place: dvd, sunroof and warranty (with all three values set to 'yes').</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>
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>Yearly Income: 0 - 1000</p> <p>Tax Rate: 0%</p> <p>Yearly Income: 1,001 - 10,000</p> <p>Tax Rate: 10%</p> <p>Yearly Income: 10,001 - 20,200</p> <p>Tax Rate: 15%</p> <p>Yearly Income: 20,201 - 30,750</p> <p>Tax Rate: 20%</p> <p>Yearly Income: 30,751 - 50,000</p> <p>Tax Rate: 25%</p> <p>Yearly Income: Over 50,000</p> <p>Tax Rate: 30%</p> <p>Write a Python function named calculate_tax that will take as an argument, a dictionary containing key-value pairs of people's names as the keys and their yearly incomes as the values.</p> <p>The function should return a dictionary containing key-value pairs of the same people’s names as keys and their yearly tax bill as the values. For example, given the sample input below:</p> <pre><code> { ‘Alex’: 500, ‘James’: 20500, ‘Kinuthia’: 70000 } The output would be as follows: { ‘Alex’: 0, ‘James’: 2490, ‘Kinuthia’: 15352.5 } </code></pre> <p>The tax for James would be calculated as follows:</p> <p>The first 1000 (1000 - 0)</p> <p>Calculation: 1,000 * 0%</p> <p>Tax: 0</p> <p>The next 9000 (10,000 - 1,000)</p> <p>Calculation: 9,000 * 10%</p> <p>Tax: 900</p> <p>The next 10,200 (20,200 -10,000)</p> <p>Calculation: 10,200 * 15%</p> <p>Tax: 1530</p> <p>The remaining 300 (20,500 - 20,200)</p> <p>Calculation: 300 * 20%</p> <p>Tax: 60</p> <p>Total Income: 20,500</p> <p>Total Tax: 0 + 900 + 1530 + 60 = 2490</p> </blockquote> <p><strong>My Code</strong></p> <pre class="lang-py prettyprint-override"><code>income_input = {} for key in income_input.keys(): income_input[key] = income def calculate_tax(income_input): if (income &gt;= 0) and (income &lt;= 1000): tax = (0*income) elif (income &gt; 1000) and (income &lt;= 10000): tax = (0.1 * (income-1000)) elif (income &gt; 10000) and (income &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) elif (income &gt; 20200) and (income &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) elif (income &gt; 30750) and (income &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) elif (income &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) else: pass for key in income_input.keys(): income_input[key] = tax return tax </code></pre> <p><strong>Test</strong></p> <pre class="lang-py prettyprint-override"><code>from unittest import TestCase class CalculateTaxTests(TestCase): def test_it_calculates_tax_for_one_person(self): result = calculate_tax({"James": 20500}) self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}") def test_it_calculates_tax_for_several_people(self): income_input = {"James": 20500, "Mary": 500, "Evan": 70000} result = calculate_tax(income_input) self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result, msg="Should return {} for the input {}".format( {"James": 2490.0, "Mary": 0, "Evan": 15352.5}, {"James": 20500, "Mary": 500, "Evan": 70000} ) ) def test_it_does_not_accept_integers(self): with self.assertRaises(ValueError) as context: calculate_tax(1) self.assertEqual( "The provided input is not a dictionary.", context.exception.message, "Invalid input of type int not allowed" ) def test_calculated_tax_is_a_float(self): result = calculate_tax({"Jane": 20500}) self.assertIsInstance( calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict") self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.") def test_it_returns_zero_tax_for_income_less_than_1000(self): result = calculate_tax({"Jake": 100}) self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000") def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self): with self.assertRaises(ValueError, msg='Allow only numeric input'): calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5}) def test_it_return_an_empty_dict_for_an_empty_dict_input(self): result = calculate_tax({}) self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict') </code></pre> <p><strong>Output after running code</strong></p> <pre><code>THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, NameError("global name 'income' is not defined",), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p><strong>Updated Code</strong></p> <pre><code> income_input = {} def calculate_tax(income_input): for key in income_input.items(): tax = 0 if (income_input[key]&gt;= 0) and (income_input[key]&lt;= 1000): tax = (0*income_input[key]) elif (income_input[key]&gt; 1000) and (income_input[key]&lt;= 10000): tax = (0.1 * (income_input[key]-1000)) elif (income_input[key]&gt; 10000) and (income_input[key]&lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income_input[key]-10000))) elif (income_input[key]&gt; 20200) and (income_input[key]&lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income_input[key]-20200))) elif (income_input[key]&gt; 30750) and (income_input[key]&lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income_input[key]-30750))) elif (income_input[key]&gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income_input[key]-50000))) else: pass income_input[key] = tax return income_input </code></pre> <p><strong>New Error Message</strong></p> <pre><code> THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, KeyError(('Jane', 20500),), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p>Don't know how to eliminate the <code>KeyError</code> error.</p>
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>Yearly Income: 0 - 1000</p> <p>Tax Rate: 0%</p> <p>Yearly Income: 1,001 - 10,000</p> <p>Tax Rate: 10%</p> <p>Yearly Income: 10,001 - 20,200</p> <p>Tax Rate: 15%</p> <p>Yearly Income: 20,201 - 30,750</p> <p>Tax Rate: 20%</p> <p>Yearly Income: 30,751 - 50,000</p> <p>Tax Rate: 25%</p> <p>Yearly Income: Over 50,000</p> <p>Tax Rate: 30%</p> <p>Write a Python function named calculate_tax that will take as an argument, a dictionary containing key-value pairs of people's names as the keys and their yearly incomes as the values.</p> <p>The function should return a dictionary containing key-value pairs of the same people’s names as keys and their yearly tax bill as the values. For example, given the sample input below:</p> <pre><code> { ‘Alex’: 500, ‘James’: 20500, ‘Kinuthia’: 70000 } The output would be as follows: { ‘Alex’: 0, ‘James’: 2490, ‘Kinuthia’: 15352.5 } </code></pre> <p>The tax for James would be calculated as follows:</p> <p>The first 1000 (1000 - 0)</p> <p>Calculation: 1,000 * 0%</p> <p>Tax: 0</p> <p>The next 9000 (10,000 - 1,000)</p> <p>Calculation: 9,000 * 10%</p> <p>Tax: 900</p> <p>The next 10,200 (20,200 -10,000)</p> <p>Calculation: 10,200 * 15%</p> <p>Tax: 1530</p> <p>The remaining 300 (20,500 - 20,200)</p> <p>Calculation: 300 * 20%</p> <p>Tax: 60</p> <p>Total Income: 20,500</p> <p>Total Tax: 0 + 900 + 1530 + 60 = 2490</p> </blockquote> <p><strong>My Code</strong></p> <pre class="lang-py prettyprint-override"><code>income_input = {} for key in income_input.keys(): income_input[key] = income def calculate_tax(income_input): if (income &gt;= 0) and (income &lt;= 1000): tax = (0*income) elif (income &gt; 1000) and (income &lt;= 10000): tax = (0.1 * (income-1000)) elif (income &gt; 10000) and (income &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) elif (income &gt; 20200) and (income &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) elif (income &gt; 30750) and (income &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) elif (income &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) else: pass for key in income_input.keys(): income_input[key] = tax return tax </code></pre> <p><strong>Test</strong></p> <pre class="lang-py prettyprint-override"><code>from unittest import TestCase class CalculateTaxTests(TestCase): def test_it_calculates_tax_for_one_person(self): result = calculate_tax({"James": 20500}) self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}") def test_it_calculates_tax_for_several_people(self): income_input = {"James": 20500, "Mary": 500, "Evan": 70000} result = calculate_tax(income_input) self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result, msg="Should return {} for the input {}".format( {"James": 2490.0, "Mary": 0, "Evan": 15352.5}, {"James": 20500, "Mary": 500, "Evan": 70000} ) ) def test_it_does_not_accept_integers(self): with self.assertRaises(ValueError) as context: calculate_tax(1) self.assertEqual( "The provided input is not a dictionary.", context.exception.message, "Invalid input of type int not allowed" ) def test_calculated_tax_is_a_float(self): result = calculate_tax({"Jane": 20500}) self.assertIsInstance( calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict") self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.") def test_it_returns_zero_tax_for_income_less_than_1000(self): result = calculate_tax({"Jake": 100}) self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000") def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self): with self.assertRaises(ValueError, msg='Allow only numeric input'): calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5}) def test_it_return_an_empty_dict_for_an_empty_dict_input(self): result = calculate_tax({}) self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict') </code></pre> <p><strong>Output after running code</strong></p> <pre><code>THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, NameError("global name 'income' is not defined",), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p><strong>Updated Code</strong></p> <pre><code> income_input = {} def calculate_tax(income_input): for key in income_input.items(): tax = 0 if (income_input[key]&gt;= 0) and (income_input[key]&lt;= 1000): tax = (0*income_input[key]) elif (income_input[key]&gt; 1000) and (income_input[key]&lt;= 10000): tax = (0.1 * (income_input[key]-1000)) elif (income_input[key]&gt; 10000) and (income_input[key]&lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income_input[key]-10000))) elif (income_input[key]&gt; 20200) and (income_input[key]&lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income_input[key]-20200))) elif (income_input[key]&gt; 30750) and (income_input[key]&lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income_input[key]-30750))) elif (income_input[key]&gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income_input[key]-50000))) else: pass income_input[key] = tax return income_input </code></pre> <p><strong>New Error Message</strong></p> <pre><code> THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, KeyError(('Jane', 20500),), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p>Don't know how to eliminate the <code>KeyError</code> error.</p>
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_dict): tax_dict = {} #This will solve the error you were getting #Get income dictionary as input #Get income of individuals and calculate tax for it for key in income_dict.keys(): income = income_dict[key] tax = 0 if (income &gt;= 0) and (income &lt;= 1000): tax = (0*income) elif (income &gt; 1000) and (income &lt;= 10000): tax = (0.1 * (income-1000)) elif (income &gt; 10000) and (income &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) elif (income &gt; 20200) and (income &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) elif (income &gt; 30750) and (income &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) elif (income &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) else: pass #Save calculated tax in tax dictionary tax_dict[key]=tax #Last return tax dictionary return tax_dict </code></pre> <p>You need to modify certain things in unit tests you have written. Check the comments inline.</p> <pre><code>from unittest import TestCase class CalculateTaxTests(TestCase): def test_it_calculates_tax_for_one_person(self): result = calculate_tax({"James": 20500}) self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}") def test_it_calculates_tax_for_several_people(self): income_input = {"James": 20500, "Mary": 500, "Evan": 70000} result = calculate_tax(income_input) self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result, msg="Should return {} for the input {}".format( {"James": 2490.0, "Mary": 0, "Evan": 15352.5}, {"James": 20500, "Mary": 500, "Evan": 70000} ) ) def test_it_does_not_accept_integers(self): #Should be AttributeError instead of ValueError with self.assertRaises(AttributeError) as context: calculate_tax(1) self.assertEqual( "The provided input is not a dictionary.", context.exception.message, "Invalid input of type int not allowed" ) def test_calculated_tax_is_a_float(self): result = calculate_tax({"Jane": 20500}) self.assertIsInstance( calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict") self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.") def test_it_returns_zero_tax_for_income_less_than_1000(self): result = calculate_tax({"Jake": 100}) self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000") def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self): #Should be TypeError instead of ValueError with self.assertRaises(TypeError, msg='Allow only numeric input'): calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5}) def test_it_return_an_empty_dict_for_an_empty_dict_input(self): result = calculate_tax({}) self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict') </code></pre> <p>Output:</p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;nosetests -v b.py test_calculated_tax_is_a_float (b.CalculateTaxTests) ... ok test_it_calculates_tax_for_one_person (b.CalculateTaxTests) ... ok test_it_calculates_tax_for_several_people (b.CalculateTaxTests) ... ok test_it_does_not_accept_integers (b.CalculateTaxTests) ... ok test_it_return_an_empty_dict_for_an_empty_dict_input (b.CalculateTaxTests) ... ok test_it_returns_zero_tax_for_income_less_than_1000 (b.CalculateTaxTests) ... ok test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric (b.CalculateTaxTests ) ... ok ---------------------------------------------------------------------- Ran 7 tests in 0.000s OK C:\Users\dinesh_pundkar\Desktop&gt; </code></pre>
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>Yearly Income: 0 - 1000</p> <p>Tax Rate: 0%</p> <p>Yearly Income: 1,001 - 10,000</p> <p>Tax Rate: 10%</p> <p>Yearly Income: 10,001 - 20,200</p> <p>Tax Rate: 15%</p> <p>Yearly Income: 20,201 - 30,750</p> <p>Tax Rate: 20%</p> <p>Yearly Income: 30,751 - 50,000</p> <p>Tax Rate: 25%</p> <p>Yearly Income: Over 50,000</p> <p>Tax Rate: 30%</p> <p>Write a Python function named calculate_tax that will take as an argument, a dictionary containing key-value pairs of people's names as the keys and their yearly incomes as the values.</p> <p>The function should return a dictionary containing key-value pairs of the same people’s names as keys and their yearly tax bill as the values. For example, given the sample input below:</p> <pre><code> { ‘Alex’: 500, ‘James’: 20500, ‘Kinuthia’: 70000 } The output would be as follows: { ‘Alex’: 0, ‘James’: 2490, ‘Kinuthia’: 15352.5 } </code></pre> <p>The tax for James would be calculated as follows:</p> <p>The first 1000 (1000 - 0)</p> <p>Calculation: 1,000 * 0%</p> <p>Tax: 0</p> <p>The next 9000 (10,000 - 1,000)</p> <p>Calculation: 9,000 * 10%</p> <p>Tax: 900</p> <p>The next 10,200 (20,200 -10,000)</p> <p>Calculation: 10,200 * 15%</p> <p>Tax: 1530</p> <p>The remaining 300 (20,500 - 20,200)</p> <p>Calculation: 300 * 20%</p> <p>Tax: 60</p> <p>Total Income: 20,500</p> <p>Total Tax: 0 + 900 + 1530 + 60 = 2490</p> </blockquote> <p><strong>My Code</strong></p> <pre class="lang-py prettyprint-override"><code>income_input = {} for key in income_input.keys(): income_input[key] = income def calculate_tax(income_input): if (income &gt;= 0) and (income &lt;= 1000): tax = (0*income) elif (income &gt; 1000) and (income &lt;= 10000): tax = (0.1 * (income-1000)) elif (income &gt; 10000) and (income &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) elif (income &gt; 20200) and (income &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) elif (income &gt; 30750) and (income &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) elif (income &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) else: pass for key in income_input.keys(): income_input[key] = tax return tax </code></pre> <p><strong>Test</strong></p> <pre class="lang-py prettyprint-override"><code>from unittest import TestCase class CalculateTaxTests(TestCase): def test_it_calculates_tax_for_one_person(self): result = calculate_tax({"James": 20500}) self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}") def test_it_calculates_tax_for_several_people(self): income_input = {"James": 20500, "Mary": 500, "Evan": 70000} result = calculate_tax(income_input) self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result, msg="Should return {} for the input {}".format( {"James": 2490.0, "Mary": 0, "Evan": 15352.5}, {"James": 20500, "Mary": 500, "Evan": 70000} ) ) def test_it_does_not_accept_integers(self): with self.assertRaises(ValueError) as context: calculate_tax(1) self.assertEqual( "The provided input is not a dictionary.", context.exception.message, "Invalid input of type int not allowed" ) def test_calculated_tax_is_a_float(self): result = calculate_tax({"Jane": 20500}) self.assertIsInstance( calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict") self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.") def test_it_returns_zero_tax_for_income_less_than_1000(self): result = calculate_tax({"Jake": 100}) self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000") def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self): with self.assertRaises(ValueError, msg='Allow only numeric input'): calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5}) def test_it_return_an_empty_dict_for_an_empty_dict_input(self): result = calculate_tax({}) self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict') </code></pre> <p><strong>Output after running code</strong></p> <pre><code>THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, NameError("global name 'income' is not defined",), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p><strong>Updated Code</strong></p> <pre><code> income_input = {} def calculate_tax(income_input): for key in income_input.items(): tax = 0 if (income_input[key]&gt;= 0) and (income_input[key]&lt;= 1000): tax = (0*income_input[key]) elif (income_input[key]&gt; 1000) and (income_input[key]&lt;= 10000): tax = (0.1 * (income_input[key]-1000)) elif (income_input[key]&gt; 10000) and (income_input[key]&lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income_input[key]-10000))) elif (income_input[key]&gt; 20200) and (income_input[key]&lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income_input[key]-20200))) elif (income_input[key]&gt; 30750) and (income_input[key]&lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income_input[key]-30750))) elif (income_input[key]&gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income_input[key]-50000))) else: pass income_input[key] = tax return income_input </code></pre> <p><strong>New Error Message</strong></p> <pre><code> THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, KeyError(('Jane', 20500),), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p>Don't know how to eliminate the <code>KeyError</code> error.</p>
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) without having to change the code. No matter how many tax ranges and rates you have, the function <code>calctax(income)</code> will do its job if you defined the ranges and the top- rate: </p> <pre class="lang-py prettyprint-override"><code># define maximum tax rate and when it applies (income/max rate) maxinc = 50000; maxtax = 30 # define tax ranges; bottom, top and the according tax percentage ranges = [ [0, 1000, 0], [1000, 10000, 10], [10000, 20200, 15], [20200, 30750, 20], [30750, 50000, 25], ] def calctax(income): pay = [] for r in ranges: if all([income &gt; r[0], income &gt; r[1]]): pay.append((r[1]-r[0]) * r[2]/100) elif all([income &gt; r[0], income &lt;= r[1]]): pay.append((income-r[0]) * r[2]/100) if income &gt; maxinc: pay.append((income-maxinc) * maxtax/100) return int(sum(pay)) # The test: taxes = {"Alex": 500, "James": 20500, "Kinuthia": 70000} for key in taxes: taxes[key] = calctax(taxes[key]) print(taxes) &gt; {'Kinuthia': 15352, 'James': 2490, 'Alex': 0} </code></pre> <h3>if the assignment is it <em>must</em> be in one function:</h3> <pre class="lang-py prettyprint-override"><code>def calctax(tax_dict): # define maximum tax rate and when it applies (income/max rate) maxinc = 50000; maxtax = 30 # define tax ranges; bottom, top and the according tax percentage ranges = [ [0, 1000, 0], [1000, 10000, 10], [10000, 20200, 15], [20200, 30750, 20], [30750, 50000, 25], ] for key in tax_dict: pay = [] income = tax_dict[key] for r in ranges: if all([income &gt; r[0], income &gt; r[1]]): pay.append((r[1]-r[0]) * r[2]/100) elif all([income &gt; r[0], income &lt;= r[1]]): pay.append((income-r[0]) * r[2]/100) if income &gt; maxinc: pay.append((income-maxinc) * maxtax/100) taxes[key] = int(sum(pay)) return tax_dict </code></pre> <p>The test:</p> <pre><code>taxes = {"Alex": 500, "James": 20500, "Kinuthia": 70000} print(calctax(taxes)) &gt; &gt; {'Kinuthia': 15352, 'James': 2490, 'Alex': 0} </code></pre> <h3>Making your code work</h3> <p>Your code is not entirely correct; you need to grab the dictionary and calculate taxes for each item in a loop, edit the corresponding item of the dictionary and output the edited one:</p> <pre><code>income_input = {"Alex": 500, "James": 20500, "Kinuthia": 70000} def calculate_tax(income_input): for item in income_input: income = income_input[item] # print(income) if (income &gt;= 0) and (income &lt;= 1000): tax = (0*income) elif (income &gt; 1000) and (income &lt;= 10000): tax = (0.1 * (income-1000)) elif (income &gt; 10000) and (income &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) elif (income &gt; 20200) and (income &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) elif (income &gt; 30750) and (income &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) elif (income &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) else: pass income_input[item] = int(tax) return income_input </code></pre> <p>The test:</p> <pre class="lang-py prettyprint-override"><code>print(calculate_tax(income_input)) &gt; {'Kinuthia': 15352, 'James': 2490, 'Alex': 0} </code></pre>
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>Yearly Income: 0 - 1000</p> <p>Tax Rate: 0%</p> <p>Yearly Income: 1,001 - 10,000</p> <p>Tax Rate: 10%</p> <p>Yearly Income: 10,001 - 20,200</p> <p>Tax Rate: 15%</p> <p>Yearly Income: 20,201 - 30,750</p> <p>Tax Rate: 20%</p> <p>Yearly Income: 30,751 - 50,000</p> <p>Tax Rate: 25%</p> <p>Yearly Income: Over 50,000</p> <p>Tax Rate: 30%</p> <p>Write a Python function named calculate_tax that will take as an argument, a dictionary containing key-value pairs of people's names as the keys and their yearly incomes as the values.</p> <p>The function should return a dictionary containing key-value pairs of the same people’s names as keys and their yearly tax bill as the values. For example, given the sample input below:</p> <pre><code> { ‘Alex’: 500, ‘James’: 20500, ‘Kinuthia’: 70000 } The output would be as follows: { ‘Alex’: 0, ‘James’: 2490, ‘Kinuthia’: 15352.5 } </code></pre> <p>The tax for James would be calculated as follows:</p> <p>The first 1000 (1000 - 0)</p> <p>Calculation: 1,000 * 0%</p> <p>Tax: 0</p> <p>The next 9000 (10,000 - 1,000)</p> <p>Calculation: 9,000 * 10%</p> <p>Tax: 900</p> <p>The next 10,200 (20,200 -10,000)</p> <p>Calculation: 10,200 * 15%</p> <p>Tax: 1530</p> <p>The remaining 300 (20,500 - 20,200)</p> <p>Calculation: 300 * 20%</p> <p>Tax: 60</p> <p>Total Income: 20,500</p> <p>Total Tax: 0 + 900 + 1530 + 60 = 2490</p> </blockquote> <p><strong>My Code</strong></p> <pre class="lang-py prettyprint-override"><code>income_input = {} for key in income_input.keys(): income_input[key] = income def calculate_tax(income_input): if (income &gt;= 0) and (income &lt;= 1000): tax = (0*income) elif (income &gt; 1000) and (income &lt;= 10000): tax = (0.1 * (income-1000)) elif (income &gt; 10000) and (income &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) elif (income &gt; 20200) and (income &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) elif (income &gt; 30750) and (income &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) elif (income &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) else: pass for key in income_input.keys(): income_input[key] = tax return tax </code></pre> <p><strong>Test</strong></p> <pre class="lang-py prettyprint-override"><code>from unittest import TestCase class CalculateTaxTests(TestCase): def test_it_calculates_tax_for_one_person(self): result = calculate_tax({"James": 20500}) self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}") def test_it_calculates_tax_for_several_people(self): income_input = {"James": 20500, "Mary": 500, "Evan": 70000} result = calculate_tax(income_input) self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result, msg="Should return {} for the input {}".format( {"James": 2490.0, "Mary": 0, "Evan": 15352.5}, {"James": 20500, "Mary": 500, "Evan": 70000} ) ) def test_it_does_not_accept_integers(self): with self.assertRaises(ValueError) as context: calculate_tax(1) self.assertEqual( "The provided input is not a dictionary.", context.exception.message, "Invalid input of type int not allowed" ) def test_calculated_tax_is_a_float(self): result = calculate_tax({"Jane": 20500}) self.assertIsInstance( calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict") self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.") def test_it_returns_zero_tax_for_income_less_than_1000(self): result = calculate_tax({"Jake": 100}) self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000") def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self): with self.assertRaises(ValueError, msg='Allow only numeric input'): calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5}) def test_it_return_an_empty_dict_for_an_empty_dict_input(self): result = calculate_tax({}) self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict') </code></pre> <p><strong>Output after running code</strong></p> <pre><code>THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, NameError("global name 'income' is not defined",), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p><strong>Updated Code</strong></p> <pre><code> income_input = {} def calculate_tax(income_input): for key in income_input.items(): tax = 0 if (income_input[key]&gt;= 0) and (income_input[key]&lt;= 1000): tax = (0*income_input[key]) elif (income_input[key]&gt; 1000) and (income_input[key]&lt;= 10000): tax = (0.1 * (income_input[key]-1000)) elif (income_input[key]&gt; 10000) and (income_input[key]&lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income_input[key]-10000))) elif (income_input[key]&gt; 20200) and (income_input[key]&lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income_input[key]-20200))) elif (income_input[key]&gt; 30750) and (income_input[key]&lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income_input[key]-30750))) elif (income_input[key]&gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income_input[key]-50000))) else: pass income_input[key] = tax return income_input </code></pre> <p><strong>New Error Message</strong></p> <pre><code> THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, KeyError(('Jane', 20500),), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p>Don't know how to eliminate the <code>KeyError</code> error.</p>
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 wrong according to the tests of the solution. </p>
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>Yearly Income: 0 - 1000</p> <p>Tax Rate: 0%</p> <p>Yearly Income: 1,001 - 10,000</p> <p>Tax Rate: 10%</p> <p>Yearly Income: 10,001 - 20,200</p> <p>Tax Rate: 15%</p> <p>Yearly Income: 20,201 - 30,750</p> <p>Tax Rate: 20%</p> <p>Yearly Income: 30,751 - 50,000</p> <p>Tax Rate: 25%</p> <p>Yearly Income: Over 50,000</p> <p>Tax Rate: 30%</p> <p>Write a Python function named calculate_tax that will take as an argument, a dictionary containing key-value pairs of people's names as the keys and their yearly incomes as the values.</p> <p>The function should return a dictionary containing key-value pairs of the same people’s names as keys and their yearly tax bill as the values. For example, given the sample input below:</p> <pre><code> { ‘Alex’: 500, ‘James’: 20500, ‘Kinuthia’: 70000 } The output would be as follows: { ‘Alex’: 0, ‘James’: 2490, ‘Kinuthia’: 15352.5 } </code></pre> <p>The tax for James would be calculated as follows:</p> <p>The first 1000 (1000 - 0)</p> <p>Calculation: 1,000 * 0%</p> <p>Tax: 0</p> <p>The next 9000 (10,000 - 1,000)</p> <p>Calculation: 9,000 * 10%</p> <p>Tax: 900</p> <p>The next 10,200 (20,200 -10,000)</p> <p>Calculation: 10,200 * 15%</p> <p>Tax: 1530</p> <p>The remaining 300 (20,500 - 20,200)</p> <p>Calculation: 300 * 20%</p> <p>Tax: 60</p> <p>Total Income: 20,500</p> <p>Total Tax: 0 + 900 + 1530 + 60 = 2490</p> </blockquote> <p><strong>My Code</strong></p> <pre class="lang-py prettyprint-override"><code>income_input = {} for key in income_input.keys(): income_input[key] = income def calculate_tax(income_input): if (income &gt;= 0) and (income &lt;= 1000): tax = (0*income) elif (income &gt; 1000) and (income &lt;= 10000): tax = (0.1 * (income-1000)) elif (income &gt; 10000) and (income &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) elif (income &gt; 20200) and (income &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) elif (income &gt; 30750) and (income &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) elif (income &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) else: pass for key in income_input.keys(): income_input[key] = tax return tax </code></pre> <p><strong>Test</strong></p> <pre class="lang-py prettyprint-override"><code>from unittest import TestCase class CalculateTaxTests(TestCase): def test_it_calculates_tax_for_one_person(self): result = calculate_tax({"James": 20500}) self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}") def test_it_calculates_tax_for_several_people(self): income_input = {"James": 20500, "Mary": 500, "Evan": 70000} result = calculate_tax(income_input) self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result, msg="Should return {} for the input {}".format( {"James": 2490.0, "Mary": 0, "Evan": 15352.5}, {"James": 20500, "Mary": 500, "Evan": 70000} ) ) def test_it_does_not_accept_integers(self): with self.assertRaises(ValueError) as context: calculate_tax(1) self.assertEqual( "The provided input is not a dictionary.", context.exception.message, "Invalid input of type int not allowed" ) def test_calculated_tax_is_a_float(self): result = calculate_tax({"Jane": 20500}) self.assertIsInstance( calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict") self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.") def test_it_returns_zero_tax_for_income_less_than_1000(self): result = calculate_tax({"Jake": 100}) self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000") def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self): with self.assertRaises(ValueError, msg='Allow only numeric input'): calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5}) def test_it_return_an_empty_dict_for_an_empty_dict_input(self): result = calculate_tax({}) self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict') </code></pre> <p><strong>Output after running code</strong></p> <pre><code>THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, NameError("global name 'income' is not defined",), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p><strong>Updated Code</strong></p> <pre><code> income_input = {} def calculate_tax(income_input): for key in income_input.items(): tax = 0 if (income_input[key]&gt;= 0) and (income_input[key]&lt;= 1000): tax = (0*income_input[key]) elif (income_input[key]&gt; 1000) and (income_input[key]&lt;= 10000): tax = (0.1 * (income_input[key]-1000)) elif (income_input[key]&gt; 10000) and (income_input[key]&lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income_input[key]-10000))) elif (income_input[key]&gt; 20200) and (income_input[key]&lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income_input[key]-20200))) elif (income_input[key]&gt; 30750) and (income_input[key]&lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income_input[key]-30750))) elif (income_input[key]&gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income_input[key]-50000))) else: pass income_input[key] = tax return income_input </code></pre> <p><strong>New Error Message</strong></p> <pre><code> THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, KeyError(('Jane', 20500),), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p>Don't know how to eliminate the <code>KeyError</code> error.</p>
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 &gt;= 0) and (income_input &lt;= 1000): tax = (0*income_input) elif (income_input &gt; 1000) and (income_input &lt;= 10000): tax = (0.1 * (income_input-1000)) elif (income_input &gt; 10000) and (income_input &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income_input-10000))) elif (income_input &gt; 20200) and (income_input &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income_input-20200))) elif (income_input &gt; 30750) and (income_input &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income_input-30750))) elif (income_input &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income_input-50000))) else: pass keys = set(data) return income_input, keys </code></pre>
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>Yearly Income: 0 - 1000</p> <p>Tax Rate: 0%</p> <p>Yearly Income: 1,001 - 10,000</p> <p>Tax Rate: 10%</p> <p>Yearly Income: 10,001 - 20,200</p> <p>Tax Rate: 15%</p> <p>Yearly Income: 20,201 - 30,750</p> <p>Tax Rate: 20%</p> <p>Yearly Income: 30,751 - 50,000</p> <p>Tax Rate: 25%</p> <p>Yearly Income: Over 50,000</p> <p>Tax Rate: 30%</p> <p>Write a Python function named calculate_tax that will take as an argument, a dictionary containing key-value pairs of people's names as the keys and their yearly incomes as the values.</p> <p>The function should return a dictionary containing key-value pairs of the same people’s names as keys and their yearly tax bill as the values. For example, given the sample input below:</p> <pre><code> { ‘Alex’: 500, ‘James’: 20500, ‘Kinuthia’: 70000 } The output would be as follows: { ‘Alex’: 0, ‘James’: 2490, ‘Kinuthia’: 15352.5 } </code></pre> <p>The tax for James would be calculated as follows:</p> <p>The first 1000 (1000 - 0)</p> <p>Calculation: 1,000 * 0%</p> <p>Tax: 0</p> <p>The next 9000 (10,000 - 1,000)</p> <p>Calculation: 9,000 * 10%</p> <p>Tax: 900</p> <p>The next 10,200 (20,200 -10,000)</p> <p>Calculation: 10,200 * 15%</p> <p>Tax: 1530</p> <p>The remaining 300 (20,500 - 20,200)</p> <p>Calculation: 300 * 20%</p> <p>Tax: 60</p> <p>Total Income: 20,500</p> <p>Total Tax: 0 + 900 + 1530 + 60 = 2490</p> </blockquote> <p><strong>My Code</strong></p> <pre class="lang-py prettyprint-override"><code>income_input = {} for key in income_input.keys(): income_input[key] = income def calculate_tax(income_input): if (income &gt;= 0) and (income &lt;= 1000): tax = (0*income) elif (income &gt; 1000) and (income &lt;= 10000): tax = (0.1 * (income-1000)) elif (income &gt; 10000) and (income &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) elif (income &gt; 20200) and (income &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) elif (income &gt; 30750) and (income &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) elif (income &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) else: pass for key in income_input.keys(): income_input[key] = tax return tax </code></pre> <p><strong>Test</strong></p> <pre class="lang-py prettyprint-override"><code>from unittest import TestCase class CalculateTaxTests(TestCase): def test_it_calculates_tax_for_one_person(self): result = calculate_tax({"James": 20500}) self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}") def test_it_calculates_tax_for_several_people(self): income_input = {"James": 20500, "Mary": 500, "Evan": 70000} result = calculate_tax(income_input) self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result, msg="Should return {} for the input {}".format( {"James": 2490.0, "Mary": 0, "Evan": 15352.5}, {"James": 20500, "Mary": 500, "Evan": 70000} ) ) def test_it_does_not_accept_integers(self): with self.assertRaises(ValueError) as context: calculate_tax(1) self.assertEqual( "The provided input is not a dictionary.", context.exception.message, "Invalid input of type int not allowed" ) def test_calculated_tax_is_a_float(self): result = calculate_tax({"Jane": 20500}) self.assertIsInstance( calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict") self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.") def test_it_returns_zero_tax_for_income_less_than_1000(self): result = calculate_tax({"Jake": 100}) self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000") def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self): with self.assertRaises(ValueError, msg='Allow only numeric input'): calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5}) def test_it_return_an_empty_dict_for_an_empty_dict_input(self): result = calculate_tax({}) self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict') </code></pre> <p><strong>Output after running code</strong></p> <pre><code>THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, NameError("global name 'income' is not defined",), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p><strong>Updated Code</strong></p> <pre><code> income_input = {} def calculate_tax(income_input): for key in income_input.items(): tax = 0 if (income_input[key]&gt;= 0) and (income_input[key]&lt;= 1000): tax = (0*income_input[key]) elif (income_input[key]&gt; 1000) and (income_input[key]&lt;= 10000): tax = (0.1 * (income_input[key]-1000)) elif (income_input[key]&gt; 10000) and (income_input[key]&lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income_input[key]-10000))) elif (income_input[key]&gt; 20200) and (income_input[key]&lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income_input[key]-20200))) elif (income_input[key]&gt; 30750) and (income_input[key]&lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income_input[key]-30750))) elif (income_input[key]&gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income_input[key]-50000))) else: pass income_input[key] = tax return income_input </code></pre> <p><strong>New Error Message</strong></p> <pre><code> THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, KeyError(('Jane', 20500),), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p>Don't know how to eliminate the <code>KeyError</code> error.</p>
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 iterating_people: earning = people[key] if earning &lt;= 1000: people[key] = 0 elif earning in range(1001,10001): tax1 = 0 * 1000 tax2 = 0.1 * (earning - 1000) total_tax = tax1 + tax2 people[key] = total_tax elif earning in range(10001,20201): tax1 = 0 * 1000 tax2 = 0.1 *9000 tax3 = 0.15 * (earning - 10000) total_tax = tax1+tax2+tax3 people[key] = total_tax elif earning in range(20201,30751): tax1 = 0 * 1000 tax2 = 0.1 * 9000 tax3 = 0.15 * 10200 tax4 = 0.20 * (earning - 20200) total_tax = tax1+tax2+tax3+tax4 people[key] = total_tax elif earning in range(30751,50001): tax1 = 0 * 1000 tax2 = 0.1 * 9000 tax3 = 0.15 * 10200 tax4 = 0.20 * 10550 tax5 = 0.25 * (earning - 30750) total_tax = tax1+tax2+tax3+tax4+tax5 people[key] = total_tax elif earning &gt; 50000: tax1 = 0 * 1000 tax2 = 0.1 * 9000 tax3 = 0.15 * 10200 tax4 = 0.20 * 10550 tax5 = 0.25 * 19250 tax6 = 0.3 * (earning - 50000) total_tax = tax1+tax2+tax3+tax4+tax5+tax6 people[key] = total_tax return people break except (AttributeError,TypeError): raise ValueError('The provided input is not a dictionary') </code></pre> <p>Cheers!</p>
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>Yearly Income: 0 - 1000</p> <p>Tax Rate: 0%</p> <p>Yearly Income: 1,001 - 10,000</p> <p>Tax Rate: 10%</p> <p>Yearly Income: 10,001 - 20,200</p> <p>Tax Rate: 15%</p> <p>Yearly Income: 20,201 - 30,750</p> <p>Tax Rate: 20%</p> <p>Yearly Income: 30,751 - 50,000</p> <p>Tax Rate: 25%</p> <p>Yearly Income: Over 50,000</p> <p>Tax Rate: 30%</p> <p>Write a Python function named calculate_tax that will take as an argument, a dictionary containing key-value pairs of people's names as the keys and their yearly incomes as the values.</p> <p>The function should return a dictionary containing key-value pairs of the same people’s names as keys and their yearly tax bill as the values. For example, given the sample input below:</p> <pre><code> { ‘Alex’: 500, ‘James’: 20500, ‘Kinuthia’: 70000 } The output would be as follows: { ‘Alex’: 0, ‘James’: 2490, ‘Kinuthia’: 15352.5 } </code></pre> <p>The tax for James would be calculated as follows:</p> <p>The first 1000 (1000 - 0)</p> <p>Calculation: 1,000 * 0%</p> <p>Tax: 0</p> <p>The next 9000 (10,000 - 1,000)</p> <p>Calculation: 9,000 * 10%</p> <p>Tax: 900</p> <p>The next 10,200 (20,200 -10,000)</p> <p>Calculation: 10,200 * 15%</p> <p>Tax: 1530</p> <p>The remaining 300 (20,500 - 20,200)</p> <p>Calculation: 300 * 20%</p> <p>Tax: 60</p> <p>Total Income: 20,500</p> <p>Total Tax: 0 + 900 + 1530 + 60 = 2490</p> </blockquote> <p><strong>My Code</strong></p> <pre class="lang-py prettyprint-override"><code>income_input = {} for key in income_input.keys(): income_input[key] = income def calculate_tax(income_input): if (income &gt;= 0) and (income &lt;= 1000): tax = (0*income) elif (income &gt; 1000) and (income &lt;= 10000): tax = (0.1 * (income-1000)) elif (income &gt; 10000) and (income &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) elif (income &gt; 20200) and (income &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) elif (income &gt; 30750) and (income &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) elif (income &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) else: pass for key in income_input.keys(): income_input[key] = tax return tax </code></pre> <p><strong>Test</strong></p> <pre class="lang-py prettyprint-override"><code>from unittest import TestCase class CalculateTaxTests(TestCase): def test_it_calculates_tax_for_one_person(self): result = calculate_tax({"James": 20500}) self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}") def test_it_calculates_tax_for_several_people(self): income_input = {"James": 20500, "Mary": 500, "Evan": 70000} result = calculate_tax(income_input) self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result, msg="Should return {} for the input {}".format( {"James": 2490.0, "Mary": 0, "Evan": 15352.5}, {"James": 20500, "Mary": 500, "Evan": 70000} ) ) def test_it_does_not_accept_integers(self): with self.assertRaises(ValueError) as context: calculate_tax(1) self.assertEqual( "The provided input is not a dictionary.", context.exception.message, "Invalid input of type int not allowed" ) def test_calculated_tax_is_a_float(self): result = calculate_tax({"Jane": 20500}) self.assertIsInstance( calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict") self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.") def test_it_returns_zero_tax_for_income_less_than_1000(self): result = calculate_tax({"Jake": 100}) self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000") def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self): with self.assertRaises(ValueError, msg='Allow only numeric input'): calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5}) def test_it_return_an_empty_dict_for_an_empty_dict_input(self): result = calculate_tax({}) self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict') </code></pre> <p><strong>Output after running code</strong></p> <pre><code>THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, NameError("global name 'income' is not defined",), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p><strong>Updated Code</strong></p> <pre><code> income_input = {} def calculate_tax(income_input): for key in income_input.items(): tax = 0 if (income_input[key]&gt;= 0) and (income_input[key]&lt;= 1000): tax = (0*income_input[key]) elif (income_input[key]&gt; 1000) and (income_input[key]&lt;= 10000): tax = (0.1 * (income_input[key]-1000)) elif (income_input[key]&gt; 10000) and (income_input[key]&lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income_input[key]-10000))) elif (income_input[key]&gt; 20200) and (income_input[key]&lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income_input[key]-20200))) elif (income_input[key]&gt; 30750) and (income_input[key]&lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income_input[key]-30750))) elif (income_input[key]&gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income_input[key]-50000))) else: pass income_input[key] = tax return income_input </code></pre> <p><strong>New Error Message</strong></p> <pre><code> THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, KeyError(('Jane', 20500),), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p>Don't know how to eliminate the <code>KeyError</code> error.</p>
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[key] if income &lt;= 1000 or income &lt; 0: payroll[key] = 0 elif income in range(1001, 10001): payroll[key] = 0.1 * (payroll[key]-1000) elif income in range(10001, 20201): payroll[key] = ((0.1*(10000-1000)) + (0.15*(payroll[key]-10000))) elif income in range(20201, 30751): payroll[key] = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(payroll[key]-20200))) elif income in range(30751 , 50001): payroll[key] = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(payroll[key]-30750))) elif income &gt; 50000: payroll[key] = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(payroll[key]-50000))) else: pass return payroll break except (AttributeError,TypeError): raise ValueError('The provided input is not a dictionary') </code></pre> <p>Cheers! </p>
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>Yearly Income: 0 - 1000</p> <p>Tax Rate: 0%</p> <p>Yearly Income: 1,001 - 10,000</p> <p>Tax Rate: 10%</p> <p>Yearly Income: 10,001 - 20,200</p> <p>Tax Rate: 15%</p> <p>Yearly Income: 20,201 - 30,750</p> <p>Tax Rate: 20%</p> <p>Yearly Income: 30,751 - 50,000</p> <p>Tax Rate: 25%</p> <p>Yearly Income: Over 50,000</p> <p>Tax Rate: 30%</p> <p>Write a Python function named calculate_tax that will take as an argument, a dictionary containing key-value pairs of people's names as the keys and their yearly incomes as the values.</p> <p>The function should return a dictionary containing key-value pairs of the same people’s names as keys and their yearly tax bill as the values. For example, given the sample input below:</p> <pre><code> { ‘Alex’: 500, ‘James’: 20500, ‘Kinuthia’: 70000 } The output would be as follows: { ‘Alex’: 0, ‘James’: 2490, ‘Kinuthia’: 15352.5 } </code></pre> <p>The tax for James would be calculated as follows:</p> <p>The first 1000 (1000 - 0)</p> <p>Calculation: 1,000 * 0%</p> <p>Tax: 0</p> <p>The next 9000 (10,000 - 1,000)</p> <p>Calculation: 9,000 * 10%</p> <p>Tax: 900</p> <p>The next 10,200 (20,200 -10,000)</p> <p>Calculation: 10,200 * 15%</p> <p>Tax: 1530</p> <p>The remaining 300 (20,500 - 20,200)</p> <p>Calculation: 300 * 20%</p> <p>Tax: 60</p> <p>Total Income: 20,500</p> <p>Total Tax: 0 + 900 + 1530 + 60 = 2490</p> </blockquote> <p><strong>My Code</strong></p> <pre class="lang-py prettyprint-override"><code>income_input = {} for key in income_input.keys(): income_input[key] = income def calculate_tax(income_input): if (income &gt;= 0) and (income &lt;= 1000): tax = (0*income) elif (income &gt; 1000) and (income &lt;= 10000): tax = (0.1 * (income-1000)) elif (income &gt; 10000) and (income &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) elif (income &gt; 20200) and (income &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) elif (income &gt; 30750) and (income &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) elif (income &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) else: pass for key in income_input.keys(): income_input[key] = tax return tax </code></pre> <p><strong>Test</strong></p> <pre class="lang-py prettyprint-override"><code>from unittest import TestCase class CalculateTaxTests(TestCase): def test_it_calculates_tax_for_one_person(self): result = calculate_tax({"James": 20500}) self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}") def test_it_calculates_tax_for_several_people(self): income_input = {"James": 20500, "Mary": 500, "Evan": 70000} result = calculate_tax(income_input) self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result, msg="Should return {} for the input {}".format( {"James": 2490.0, "Mary": 0, "Evan": 15352.5}, {"James": 20500, "Mary": 500, "Evan": 70000} ) ) def test_it_does_not_accept_integers(self): with self.assertRaises(ValueError) as context: calculate_tax(1) self.assertEqual( "The provided input is not a dictionary.", context.exception.message, "Invalid input of type int not allowed" ) def test_calculated_tax_is_a_float(self): result = calculate_tax({"Jane": 20500}) self.assertIsInstance( calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict") self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.") def test_it_returns_zero_tax_for_income_less_than_1000(self): result = calculate_tax({"Jake": 100}) self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000") def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self): with self.assertRaises(ValueError, msg='Allow only numeric input'): calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5}) def test_it_return_an_empty_dict_for_an_empty_dict_input(self): result = calculate_tax({}) self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict') </code></pre> <p><strong>Output after running code</strong></p> <pre><code>THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, NameError("global name 'income' is not defined",), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p><strong>Updated Code</strong></p> <pre><code> income_input = {} def calculate_tax(income_input): for key in income_input.items(): tax = 0 if (income_input[key]&gt;= 0) and (income_input[key]&lt;= 1000): tax = (0*income_input[key]) elif (income_input[key]&gt; 1000) and (income_input[key]&lt;= 10000): tax = (0.1 * (income_input[key]-1000)) elif (income_input[key]&gt; 10000) and (income_input[key]&lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income_input[key]-10000))) elif (income_input[key]&gt; 20200) and (income_input[key]&lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income_input[key]-20200))) elif (income_input[key]&gt; 30750) and (income_input[key]&lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income_input[key]-30750))) elif (income_input[key]&gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income_input[key]-50000))) else: pass income_input[key] = tax return income_input </code></pre> <p><strong>New Error Message</strong></p> <pre><code> THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, KeyError(('Jane', 20500),), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p>Don't know how to eliminate the <code>KeyError</code> error.</p>
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 has no attribute 'exception'",), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable</p> <p>then it clicked i went to the tests and raised value error for test values that fail and voila it clicked</p>
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>Yearly Income: 0 - 1000</p> <p>Tax Rate: 0%</p> <p>Yearly Income: 1,001 - 10,000</p> <p>Tax Rate: 10%</p> <p>Yearly Income: 10,001 - 20,200</p> <p>Tax Rate: 15%</p> <p>Yearly Income: 20,201 - 30,750</p> <p>Tax Rate: 20%</p> <p>Yearly Income: 30,751 - 50,000</p> <p>Tax Rate: 25%</p> <p>Yearly Income: Over 50,000</p> <p>Tax Rate: 30%</p> <p>Write a Python function named calculate_tax that will take as an argument, a dictionary containing key-value pairs of people's names as the keys and their yearly incomes as the values.</p> <p>The function should return a dictionary containing key-value pairs of the same people’s names as keys and their yearly tax bill as the values. For example, given the sample input below:</p> <pre><code> { ‘Alex’: 500, ‘James’: 20500, ‘Kinuthia’: 70000 } The output would be as follows: { ‘Alex’: 0, ‘James’: 2490, ‘Kinuthia’: 15352.5 } </code></pre> <p>The tax for James would be calculated as follows:</p> <p>The first 1000 (1000 - 0)</p> <p>Calculation: 1,000 * 0%</p> <p>Tax: 0</p> <p>The next 9000 (10,000 - 1,000)</p> <p>Calculation: 9,000 * 10%</p> <p>Tax: 900</p> <p>The next 10,200 (20,200 -10,000)</p> <p>Calculation: 10,200 * 15%</p> <p>Tax: 1530</p> <p>The remaining 300 (20,500 - 20,200)</p> <p>Calculation: 300 * 20%</p> <p>Tax: 60</p> <p>Total Income: 20,500</p> <p>Total Tax: 0 + 900 + 1530 + 60 = 2490</p> </blockquote> <p><strong>My Code</strong></p> <pre class="lang-py prettyprint-override"><code>income_input = {} for key in income_input.keys(): income_input[key] = income def calculate_tax(income_input): if (income &gt;= 0) and (income &lt;= 1000): tax = (0*income) elif (income &gt; 1000) and (income &lt;= 10000): tax = (0.1 * (income-1000)) elif (income &gt; 10000) and (income &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) elif (income &gt; 20200) and (income &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) elif (income &gt; 30750) and (income &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) elif (income &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) else: pass for key in income_input.keys(): income_input[key] = tax return tax </code></pre> <p><strong>Test</strong></p> <pre class="lang-py prettyprint-override"><code>from unittest import TestCase class CalculateTaxTests(TestCase): def test_it_calculates_tax_for_one_person(self): result = calculate_tax({"James": 20500}) self.assertEqual(result, {"James": 2490.0}, msg="Should return {'James': 2490.0} for the input {'James': 20500}") def test_it_calculates_tax_for_several_people(self): income_input = {"James": 20500, "Mary": 500, "Evan": 70000} result = calculate_tax(income_input) self.assertEqual({"James": 2490.0, "Mary": 0, "Evan": 15352.5}, result, msg="Should return {} for the input {}".format( {"James": 2490.0, "Mary": 0, "Evan": 15352.5}, {"James": 20500, "Mary": 500, "Evan": 70000} ) ) def test_it_does_not_accept_integers(self): with self.assertRaises(ValueError) as context: calculate_tax(1) self.assertEqual( "The provided input is not a dictionary.", context.exception.message, "Invalid input of type int not allowed" ) def test_calculated_tax_is_a_float(self): result = calculate_tax({"Jane": 20500}) self.assertIsInstance( calculate_tax({"Jane": 20500}), dict, msg="Should return a result of data type dict") self.assertIsInstance(result["Jane"], float, msg="Tax returned should be an float.") def test_it_returns_zero_tax_for_income_less_than_1000(self): result = calculate_tax({"Jake": 100}) self.assertEqual(result, {"Jake": 0}, msg="Should return zero tax for incomes less than 1000") def test_it_throws_an_error_if_any_of_the_inputs_is_non_numeric(self): with self.assertRaises(ValueError, msg='Allow only numeric input'): calculate_tax({"James": 2490.0, "Kiura": '200', "Kinuthia": 15352.5}) def test_it_return_an_empty_dict_for_an_empty_dict_input(self): result = calculate_tax({}) self.assertEqual(result, {}, msg='Should return an empty dict if the input was an empty dict') </code></pre> <p><strong>Output after running code</strong></p> <pre><code>THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, NameError("global name 'income' is not defined",), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p><strong>Updated Code</strong></p> <pre><code> income_input = {} def calculate_tax(income_input): for key in income_input.items(): tax = 0 if (income_input[key]&gt;= 0) and (income_input[key]&lt;= 1000): tax = (0*income_input[key]) elif (income_input[key]&gt; 1000) and (income_input[key]&lt;= 10000): tax = (0.1 * (income_input[key]-1000)) elif (income_input[key]&gt; 10000) and (income_input[key]&lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income_input[key]-10000))) elif (income_input[key]&gt; 20200) and (income_input[key]&lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income_input[key]-20200))) elif (income_input[key]&gt; 30750) and (income_input[key]&lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income_input[key]-30750))) elif (income_input[key]&gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income_input[key]-50000))) else: pass income_input[key] = tax return income_input </code></pre> <p><strong>New Error Message</strong></p> <pre><code> THERE IS AN ERROR/BUG IN YOUR CODE Results: Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, result=, outcome='error', exc_info=(, KeyError(('Jane', 20500),), ), reason=None, expected=False, shortLabel=None, longLabel=None) is not JSON serializable </code></pre> <p>Don't know how to eliminate the <code>KeyError</code> error.</p>
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() for keys in d.keys(): income=d[keys] if (income &gt;=0) and (income&lt;=1000): tax=(0*income) d[keys]=tax#Updtae the key after taxation elif (income &gt; 1000) and (income &lt;= 10000): tax = (0.1 * (income-1000)) d[keys]=tax#Updtae the key after taxation elif (income &gt; 10000) and (income &lt;= 20200): tax = ((0.1*(10000-1000)) + (0.15*(income-10000))) d[keys]=tax#Updtae the key after taxation elif (income &gt; 20200) and (income &lt;= 30750): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(income-20200))) d[keys]=tax#Updtae the key after taxation elif (income &gt; 30750) and (income &lt;= 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(income-30750))) d[keys]=tax#Updtae the key after taxation elif (income &gt; 50000): tax = ((0.1*(10000-1000)) + (0.15*(20200-10000)) + (0.2*(30750-20200)) + (0.25*(50000-30750)) + (0.3*(income-50000))) d[keys]=tax#Updtae the key after taxation """updating d1 dictionary""" d[keys]=tax return d1 break except(AttributeError,TypeError): raise ValueError('The input provided is not A dictionary') d2={'Alex': 700,'Njuguna': 20500,'Kinuthia': 70000,'Anex': 700,'Ngori': 20500,'jumaa': 70000} calculate_tax(d2) </code></pre> <p><strong>Note: This is to help you understand the logics in algorithm</strong></p>
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\virtualenv.exe\__main__.py", line 9, in &lt;module&gt; File "c:\python27\lib\site-packages\virtualenv.py", line 711, in main symlink=options.symlink) File "c:\python27\lib\site-packages\virtualenv.py", line 924, in create_environment site_packages=site_packages, clear=clear, symlink=symlink)) File "c:\python27\lib\site-packages\virtualenv.py", line 1131, in install_python copy_required_modules(home_dir, symlink) File "c:\python27\lib\site-packages\virtualenv.py", line 1061, in copy_required_modules dst_filename = change_prefix(filename, dst_prefix) File "c:\python27\lib\site-packages\virtualenv.py", line 1035, in change_prefix (filename, prefixes) **AssertionError: Filename C:\Python27\Lib\os.py does not start with any of theseprefixes: ['C:\\python27']** </code></pre> <p>my system enviroment variable : PYTHONPATH </p> <pre><code>C:\Python27;C:\Python27\Lib;C:\Python27\DLLs </code></pre> <p>how can i solve this problem?</p>
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 &amp; /etc/apache2/sites-available/default-ssl.conf</code> files Then tried to restart the server. And I got following Errors. Uninstalling &amp; reinstalling the apache2 too is not fixing this error. Any suggestions to fix this issue ?</p> <p>Command: </p> <pre><code>sudo service apache2 restart </code></pre> <p>Error:</p> <pre><code>Job for apache2.service failed. See 'systemctl status apache2.service' and 'journalctl -xn' for details. </code></pre> <p>Command: </p> <pre><code>sudo systemctl status apache2.service -l </code></pre> <p>Error:</p> <pre><code>apache2.service - LSB: Apache2 web server Loaded: loaded (/etc/init.d/apache2) Active: active (exited) since Wed 2016-08-31 05:08:43 UTC; 3min 37s ago Process: 3539 ExecStop=/etc/init.d/apache2 stop (code=exited, status=0/SUCCESS) Process: 3521 ExecReload=/etc/init.d/apache2 reload (code=exited, status=1/FAILURE) Process: 3546 ExecStart=/etc/init.d/apache2 start (code=exited, status=0/SUCCESS) Unit apache2.service entered failed state. Starting LSB: Apache2 web server... Starting web server: apache2(98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down AH00015: Unable to open logs Action 'start' failed. The Apache error log may have more information. . Started LSB: Apache2 web server. </code></pre> <p>Thanks,</p>
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</code> or <code>libapache2-mod-wsgi-python3</code> installed? if you have access to shell you can install it with</p> <pre><code>sudo apt-get install libapache2-mod-wsgi # or for python 3 sudo apt-get install libapache2-mod-wsgi-python3 </code></pre>
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 &amp; /etc/apache2/sites-available/default-ssl.conf</code> files Then tried to restart the server. And I got following Errors. Uninstalling &amp; reinstalling the apache2 too is not fixing this error. Any suggestions to fix this issue ?</p> <p>Command: </p> <pre><code>sudo service apache2 restart </code></pre> <p>Error:</p> <pre><code>Job for apache2.service failed. See 'systemctl status apache2.service' and 'journalctl -xn' for details. </code></pre> <p>Command: </p> <pre><code>sudo systemctl status apache2.service -l </code></pre> <p>Error:</p> <pre><code>apache2.service - LSB: Apache2 web server Loaded: loaded (/etc/init.d/apache2) Active: active (exited) since Wed 2016-08-31 05:08:43 UTC; 3min 37s ago Process: 3539 ExecStop=/etc/init.d/apache2 stop (code=exited, status=0/SUCCESS) Process: 3521 ExecReload=/etc/init.d/apache2 reload (code=exited, status=1/FAILURE) Process: 3546 ExecStart=/etc/init.d/apache2 start (code=exited, status=0/SUCCESS) Unit apache2.service entered failed state. Starting LSB: Apache2 web server... Starting web server: apache2(98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down AH00015: Unable to open logs Action 'start' failed. The Apache error log may have more information. . Started LSB: Apache2 web server. </code></pre> <p>Thanks,</p>
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 :::* LISTEN 24482/nginx -g daem </code></pre> <p>Running the next two commands then fixed the issue:</p> <pre><code>sudo kill -9 24482 sudo service apache2 restart </code></pre> <p>Hope it can be helpful.</p> <p>Thanks,</p>
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 displaying the document on the terminal using python? Also, the json has to be pretty printed.</p> <p>Expected</p> <pre><code>{ "text" : " `hello` world" } </code></pre> <p>Text that is qoutes should be displayed in red color.</p>
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 "hello" with colored("hello", "red")</p> <pre><code>from termcolor import colored sample_text = "colored hello there !" print(sample_text) print(sample_text.replace("hello", colored("hello", "red"))) </code></pre>
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 directory, however, python fails to find it even though the file exists. I am having a hard time figuring it out why this is happening. My python file looks as follow:</p> <pre><code>#!/usr/bin/env python #SBATCH --job-name=Python print('hi') import main_nn </code></pre> <p>however the output of my slurm dump file is:</p> <pre><code>hi Traceback (most recent call last): File "/home/slurm/slurmd/job3223398/slurm_script", line6, in &lt;module&gt; import main_nn ImportError: No module named main_nn </code></pre> <p>I tried checking if the module <code>main_nn</code> was in the current directory and it was there indeed. Thus, the first thing that seemed suspicious to me was that the error in the slurm file said the location of my script was at <code>"/home/slurm/slurmd/job3223398/slurm_script"</code> rather than at <code>path_to_project</code>. Thus I went ahead an added the line </p> <p>os.system('pwd')</p> <p>to see where my script was executing from and to my surprise it was executing at <code>path_to_project</code> rather than at <code>"/home/slurm/slurmd/job3223398/slurm_script"</code> which must mean that sbatch is doing something funky to executed a script at one location but make it think its at another. If this is the case how am I suppose to do an import in python where the module is in the same location as in my submission script? Am I forced to put it in a package and trick python to think its in a package/library?</p>
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><code>sys.path.append(os.getcwd()) </code></pre> <p>near the beginning of your script.</p>
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 organized. When I try to import these modules, which exist as files within the Django app folder, it says there is no module with that name. How do I fix this?</p> <pre><code>Error: File "/Users/andrewho/Desktop/website/charts/views.py", line 48, in &lt;module&gt; import graphing ImportError: No module named 'graphing' </code></pre> <p>I clearly have a file in the app folder called graphing.py, so why does it give me this error?</p>
-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 in my django site as well. </p> <p>I have been reading about some SSO options, but I am unclear on how to appraoch the problem down the road. here is the process that I have roughly in my head... Let me know if it sounds coherent...</p> <ol> <li><p>Use Discourse auth (since it already has social auth and profiles and a lot of user tables.</p></li> <li><p>Make some SSO hook for django so that it will accept the Discourse login</p></li> <li><p>Upon account creation of the Discourse User, I will send (from the discourse instance) an API request that will create a user in my django instance with the proper user tables for my django site.</p></li> </ol> <p>Does this sound like a good idea? </p>
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 JWT. It has been gainining ground to marry different services and the only thing you need is to be able to decode the JWT token, which a lot of languages have nowadays in the form of libraries. </p>
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 same question on Python dictionary and deque, about whether we need lock to protect it in a multi-threaded environment. Thanks.</p> <pre><code>import threading import time import random class checkStatus: def __init__(self): self.message = [] self.lock = threading.Lock() def checkInStatus(self, msg): self.lock.acquire() self.message.append(msg) self.lock.release() def checkOutStatus(self): self.lock.acquire() if len(self.message) &gt; 0: msg = self.message.pop(0) else: msg = 'Queue empty' self.lock.release() return msg def checkMessageStatus(self): self.lock.acquire() size = len(self.message) self.lock.release() return size messageQueue = checkStatus() class myThread (threading.Thread): def __init__(self, threadID, name): threading.Thread.__init__(self) self.threadID = threadID self.name = name def run(self): global messageQueue while True: time.sleep(1+5*random.random()) print "%s: %s : %s" % (self.name, time.ctime(time.time()), messageQueue.checkMessageStatus()) time.sleep(1 + 5 * random.random()) msg = time.ctime(time.time()) + ' ' + self.name print "%s: %s : check in message, %s" % (self.name, time.ctime(time.time()), msg) messageQueue.checkInStatus(msg) time.sleep(1 + 5 * random.random()) print "%s: %s : check out message, %s" % (self.name, time.ctime(time.time()), messageQueue.checkOutStatus()) if __name__ == "__main__": threads = [] # Create new threads thread1 = myThread(1, "Thread-1") thread2 = myThread(2, "Thread-2") # Start new Threads thread1.start() thread2.start() # Add threads to thread list threads.append(thread1) threads.append(thread2) # Wait for all threads to complete for t in threads: t.join() print "Exiting Main Thread" </code></pre> <p>Output,</p> <pre><code>Thread-2: Tue Aug 30 22:08:04 2016 : 0 Thread-1: Tue Aug 30 22:08:05 2016 : 0 Thread-1: Tue Aug 30 22:08:07 2016 : check in message, Tue Aug 30 22:08:07 2016 Thread-1 Thread-2: Tue Aug 30 22:08:07 2016 : check in message, Tue Aug 30 22:08:07 2016 Thread-2 Thread-2: Tue Aug 30 22:08:09 2016 : check out message, Tue Aug 30 22:08:07 2016 Thread-1 Thread-1: Tue Aug 30 22:08:11 2016 : check out message, Tue Aug 30 22:08:07 2016 Thread-2 Thread-2: Tue Aug 30 22:08:11 2016 : 0 Thread-1: Tue Aug 30 22:08:13 2016 : 0 Thread-2: Tue Aug 30 22:08:15 2016 : check in message, Tue Aug 30 22:08:15 2016 Thread-2 Thread-1: Tue Aug 30 22:08:17 2016 : check in message, Tue Aug 30 22:08:17 2016 Thread-1 Thread-2: Tue Aug 30 22:08:18 2016 : check out message, Tue Aug 30 22:08:15 2016 Thread-2 Thread-1: Tue Aug 30 22:08:19 2016 : check out message, Tue Aug 30 22:08:17 2016 Thread-1 </code></pre>
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, there can be a case where the if statement evaluates to True but a thread switch occurs immediately, before retrieving the message with <code>self.message.pop(0)</code>. If the second thread then removes the message, when the first thread continues it will attempt to pop from an empty list. If you rewrite the function as follows:</p> <pre><code>def checkOutStatus(self): try: msg = self.message.pop(0) except IndexError: msg = 'Queue empty' return msg </code></pre> <p>it too will be threadsafe, since the only operation is atomic. In that case you could drop all the locking code.</p>
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> <p>But this doesn't work, because <code>c</code> not in database and can't be fetched from db. How to get minimum value <code>c</code> of <code>Foo</code>?</p>
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>mat_c, C = 0.1</code> </p> <p>Here, we find the array with the least value, in this case it is C </p> <ol> <li><p>We compute the amount of <code>C</code> that should be allocated to <code>B</code> as <code>0.1 * (0.2/ (0.2 + 0.3))</code> i.e. Value of cell in <code>C</code> multiplied by the fraction of <code>B</code> with <code>total</code> being <code>A + B</code>. The newly computed value is stored in a <code>2D</code> array called <code>C_B</code> </p></li> <li><p>Similarly, the amount of <code>C</code> that should be allocated to <code>A</code> is <code>0.1 * (0.3/(0.2 + 0.3))</code>. The newly computed value is stored in a <code>2D</code> array called <code>C_A</code>.</p></li> <li><p>We repeat this process for cells where least value is in array <code>B</code>, storing the newly computed results in <code>2D</code> arrays <code>B_C</code> and <code>B_A</code> respectively.</p></li> <li><p>We repeat this process for cells where least value is in array <code>A</code>, storing the newly computed results in <code>2D</code> arrays <code>A_C</code> and <code>A_B</code> respectively.</p></li> </ol> <p>The only way I can think of doing this is using nested for loops, but that would be prohibitive for larger arrays and not very pythonic. Is there a fast and pythonic solution?</p> <p>-- edit</p> <p><code>C_B</code> should contain 0 where <code>mat_c</code> does not contain smallest value </p>
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 0,1,2 for a,b,c respectively c_a = mat_c * mat_a / (mat_b + mat_c) c_a[minima != 2] = 0 </code></pre> <p>You can repeat this for the other 5 answer arrays. Or, you could also do:</p> <pre><code>c_a = np.zeros((5,5)) c_a[minima == 2] = (mat_c * mat_a / (mat_b + mat_c))[minima == 2] </code></pre>
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 this pandas error:</p> <pre><code> A value is trying to be set on a copy of a slice from a DataFrame </code></pre> <p>Is there another way where can I dropna on ['Killed'] when ['Type'] == 'Dog'?</p> <p>(This is my first post), sorry if I can't explain properly Cheers</p>
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") &amp; 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 this pandas error:</p> <pre><code> A value is trying to be set on a copy of a slice from a DataFrame </code></pre> <p>Is there another way where can I dropna on ['Killed'] when ['Type'] == 'Dog'?</p> <p>(This is my first post), sorry if I can't explain properly Cheers</p>
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') &amp; (cd.Killed.isnull())].index, inplace=True) </code></pre> <h3>Setup</h3> <pre><code>cd = pd.DataFrame([ ['Dog', 'Yorkie'], ['Cat', 'Rag Doll'], ['Cat', None], ['Bird', 'Caique'], ['Dog', None], ], columns=['Type', 'Killed']) </code></pre> <h3>Solution</h3> <pre><code>cd.drop(cd[(cd.Type == 'Dog') &amp; (cd.Killed.isnull())].index, inplace=True) cd </code></pre> <p><a href="http://i.stack.imgur.com/2pPHv.png" rel="nofollow"><img src="http://i.stack.imgur.com/2pPHv.png" alt="enter image description here"></a></p> <hr> <p>Equivalently with DeMorgan's law</p> <pre><code>cond1 = cd.Type == 'Dog' cond2 = cd.Killed.isnull() cd[~cond1 | ~cond2] </code></pre> <hr> <p>A silly one, because I felt like it!</p> <pre><code>cd.groupby('Type', group_keys=False) \ .apply(lambda df: df.dropna(subset=['Killed']) if df.name == 'Dog' else df) </code></pre>
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) def create(self, validated_data): Personnels.objects.create(**self.validated_data) def update(self, instance, validated_data): # for k,v in self.validated_data.iteritems(): # instance['k'] = self.validated_data.get(k, instance[k]) # instance.name = self.validated_data.get('name', instance.name) instance['name'] = self.validated_data.get('name', instance.name) instance.save() return instance </code></pre> <p><strong>views.py</strong></p> <pre><code>@api_view(['PUT']) def artist_serialization_specific(request, artist_id): if request.method == "PUT": # Example of updating an object via manual serialization # return HttpResponse(artist_id) personnel = Personnels.objects.get(id=artist_id) x = ArtistSerializer(personnel, data={"name":"John Doe"}) if x.is_valid(): x.update(personnel, x.validated_data) else: print x.errors return Response(x.data, status=status.HTTP_200_OK) </code></pre> <p>However I get this error:</p> <pre><code>Internal Server Error: /forms/artists/serialization/3/ Traceback (most recent call last): File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/rest_framework/views.py", line 474, in dispatch response = self.handle_exception(exc) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/rest_framework/views.py", line 434, in handle_exception self.raise_uncaught_exception(exc) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/rest_framework/views.py", line 471, in dispatch response = handler(request, *args, **kwargs) File "/Users/deanarmada/.virtualenvs/django-cassandra/lib/python2.7/site-packages/rest_framework/decorators.py", line 52, in handler return func(*args, **kwargs) File "/Users/deanarmada/Desktop/projects/python-projects/django/django-cassandra/tutorial/example/views.py", line 85, in artist_serialization_specific x.update(personnel, x.validated_data) File "/Users/deanarmada/Desktop/projects/python-projects/django/django-cassandra/tutorial/example/serializers.py", line 21, in update instance['name'] = self.validated_data.get('name', instance.name) TypeError: 'Personnels' object does not support item assignment </code></pre>
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/httpcache.py#L18" rel="nofollow">Here's the source for the DummyPolicy</a> And these are the lines that actually matter:</p> <pre><code>class DummyPolicy(object): def __init__(self, settings): self.ignore_http_codes = [int(x) for x in settings.getlist('HTTPCACHE_IGNORE_HTTP_CODES')] def should_cache_response(self, response, request): return response.status not in self.ignore_http_codes </code></pre> <p>So in reality you can also extend this and override <code>should_cache_response()</code> to something that would check for <code>200</code> explicitly, i.e. <code>return response.status == 200</code> and then set it as your cache policy via <a href="http://doc.scrapy.org/en/latest/topics/downloader-middleware.html?highlight=ignore_http_codes#httpcache-policy" rel="nofollow"><code>HTTPCACHE_POLICY</code> setting</a>.</p>
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 to do this? </p>
4
2016-08-31T05:36:54Z
39,241,555
<pre><code>l = [] a = 0 for i in xrnage (N) : a += 2 if i&amp;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 to do this? </p>
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>&gt;&gt;&gt; [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 to do this? </p>
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 &lt; stop: yield val val += next(steps) </code></pre> <p>You'd call it like so:</p> <pre><code>&gt;&gt;&gt; list(fancy_range(0, 20, (4, 2))) [0, 4, 6, 10, 12, 16, 18] </code></pre> <p>The advantage here is that is scales to an arbitrary number of steps quite nicely (though I can't really think of a good use for that at the moment -- But perhaps you can).</p>
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 to do this? </p>
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_longest(a,b) for j in i if j!=None] custom_range(4,2,(0,19)) custom_range(6,5,(0,34)) </code></pre> <p>Output:</p> <pre><code>[0, 4, 6, 10, 12, 16, 18] [0, 6, 11, 17, 22, 28, 33] </code></pre>
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 to do this? </p>
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>&gt;&gt;&gt; a = range(0,20,4) &gt;&gt;&gt; a [0, 4, 8, 12, 16] &gt;&gt;&gt; b = range(0,20,6) &gt;&gt;&gt; c = sorted(a + b) &gt;&gt;&gt; b [0, 6, 12, 18] &gt;&gt;&gt; c [0, 0, 4, 6, 8, 12, 12, 16, 18] &gt;&gt;&gt; c = list(set(c)) &gt;&gt;&gt; c [0, 4, 6, 8, 12, 16, 18] </code></pre>
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 retrieve <code>df['A']</code> as a list of <code>dicts</code> as <code>dicts</code>? Any help highly appreciated. </p>
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': u'con'}, {u'z': 47, u'at': ... 5 [{u'c': 47, u'at': u'con'}, {u'z': 47, u'at': ... Name: A, dtype: object </code></pre> <h3>Setup</h3> <pre><code>df = pd.DataFrame([ '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]', '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]', '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]', '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]', '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]', '[{"at": "con", "c": 47}, {"at": "cli", "z": 47}, {"at": "cks", "d": 5}]', ], columns=['A']) </code></pre>
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, chicken curry, thai curry </code></pre> <p>Basically, I am looking to parse the sentence tree and try to generate bi-grams by pairing an adjective with the noun.</p> <p>And I would like to achieve this with spacy or nltk</p>
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 match the pattern <em>JJ NN</em>.</p></li> </ol> <p>Example:</p> <pre><code>def jjnn_pairs(phrase): ''' Iterate over pairs of JJ-NN. ''' tagged = nltk.pos_tag(nltk.word_tokenize(phrase)) for ngram in ngramise(tagged): tokens, tags = zip(*ngram) if tags == ('JJ', 'NN'): yield tokens def ngramise(sequence): ''' Iterate over bigrams and 1,2-skip-grams. ''' for bigram in nltk.ngrams(sequence, 2): yield bigram for trigram in nltk.ngrams(sequence, 3): yield trigram[0], trigram[2] </code></pre> <p>Extend the pattern <code>('JJ', 'NN')</code> and the desired n-grams to your needs.</p> <p>I think there is no need for parsing. The major problem of this approach, however, is that most PoS taggers will probably not tag everything exactly the way you want. For example, the default PoS tagger of my NLTK installation tagged "chili" as <em>NN</em>, not <em>JJ</em>, and "fried" got <em>VBD</em>. Parsing won't help you with that, though!</p>
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, chicken curry, thai curry </code></pre> <p>Basically, I am looking to parse the sentence tree and try to generate bi-grams by pairing an adjective with the noun.</p> <p>And I would like to achieve this with spacy or nltk</p>
0
2016-08-31T05:53:14Z
39,244,988
<p>Something like this:</p> <pre><code>&gt;&gt;&gt; from nltk import bigrams &gt;&gt;&gt; text = """thai iced tea ... spicy fried chicken ... sweet chili pork ... thai chicken curry""" &gt;&gt;&gt; lines = map(str.split, text.split('\n')) &gt;&gt;&gt; for line in lines: ... ", ".join([" ".join(bi) for bi in bigrams(line)]) ... 'thai iced, iced tea' 'spicy fried, fried chicken' 'sweet chili, chili pork' 'thai chicken, chicken curry' </code></pre> <hr> <p>Alternatively using <code>colibricore</code> <a href="https://proycon.github.io/colibri-core/doc/#installation" rel="nofollow">https://proycon.github.io/colibri-core/doc/#installation</a> ;P</p>
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 what the error is called or why I am getting it.</p>
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#what-are-wheels-pip-and-wheel" rel="nofollow">https://kivy.org/docs/installation/installation-windows.html#what-are-wheels-pip-and-wheel</a></p> <p>extract from that Kivy docs,</p> <blockquote> <p>In Python, packages such as Kivy can be installed with the python package manager, pip. Some packages such as Kivy require additional steps, such as compilation, when installing using the Kivy source code with pip. Wheels (with a .whl extension) are pre-built distributions of a package that has already been compiled and do not require additional steps to install.</p> <p>When hosted on pypi one installs a wheel using pip, e.g. python -m pip install kivy. When downloading and installing a wheel directly, python -m pip install wheel_file_name is used, such as:</p> <p>python -m pip install C:\Kivy-1.9.1.dev-cp27-none-win_amd64.whl</p> </blockquote>
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.com/s4wTn.png" rel="nofollow">By investigating the problem, I found that the server returns a <strong>text/html</strong> instead of <strong>text/css</strong></a></p> <p><strong>Apache 2.4.23 / mod_wsgi 4.5.5 / Python 3.4.2 / Django 1.8 on Linux Debian (64-bit)</strong></p> <p>Additional informations:</p> <p>This is my <strong>settings.py</strong> file</p> <pre><code>""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '##################################################' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT = '/var/www/django-projects/mysite/static' STATIC_URL = '/static/' </code></pre> <p>The lines wich are appended to the httpd.conf (Apache HTTP Server)</p> <pre><code># Enable access for Django website mysite WSGIScriptAlias /mysite /var/www/django-projects/mysite/mysite/wsgi.py process-group=mysite WSGIScriptAlias /static /var/www/django-projects/mysite/static process-group=mysite WSGIPythonPath /var/www/django-projects/mysite:/home/ibrahim/.virtualenvs/django-1.8/lib/python3.4/site-packages WSGIDaemonProcess mysite python-path=/var/www/django-projects/mysite:/home/ibrahim/.virtualenvs/django-1.8/lib/python3.4/site-packages WSGIProcessGroup mysite &lt;Directory /var/www/django-projects/mysite&gt; Require all granted Options FollowSymLinks ServerSignature On &lt;/Directory&gt; </code></pre> <p>Project structure:</p> <pre><code>- mysite - mysite + __pycache__ __init__.py settings.py urls.py wsgi.py - polls + __pycache__ + migrations __init__.py admin.py models.py tests.py views.py - static - admin - css base.css ........ + img + js + templates .schema db.sqlite3 manage.py </code></pre> <p>Note that the file <code>/usr/local/apache2/conf/mime.types</code> include the following line: <code>text/css css</code></p>
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 blocks the script.</p> <p>I need the page to wait for the page to load first and then continue, but i failed in doing that. </p> <p>The following things are what i have tried till now.</p> <p>The code goes as follows : </p> <pre><code>while int(number_of_news) != int(len(news)) : driver.execute_script("window.scrollTo(document.body.scrollHeight/2, document.body.scrollHeight);") news = driver.find_elements_by_class_name("news-text") print(len(news)) </code></pre> <p>The output is something like</p> <p><a href="http://i.stack.imgur.com/uTRaL.png" rel="nofollow"><img src="http://i.stack.imgur.com/uTRaL.png" alt="enter image description here"></a></p> <p>Which i interpreted as the loop being executed multiple times when the value is <code>43, 63... and so on</code>.</p> <p>I also tried making it recursive, but the result is still the same. The recursive code is as follows :</p> <pre><code>def call_news(_driver, _news, _number_of_news): _driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") _news = driver.find_elements_by_class_name("news-text") print(len(_news)) if int(len(_news)) != int(number_of_news) : call_news(_driver, _news, _number_of_news) else : return _news </code></pre> <p>Any kind of tip is appreciated.</p>
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)) : driver.execute_script("window.scrollTo(document.body.scrollHeight/2, document.body.scrollHeight);") while (current_number_of_news == len(news)) : news = driver.find_elements_by_class_name("news-text") current_number_of_news = len(news) print(len(news)) </code></pre>
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>Well, it is self explanatory</p>
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/3/library/stdtypes.html#range" rel="nofollow"><code>range</code></a> is equivalent to <a href="https://docs.python.org/2/library/stdtypes.html#typesseq-xrange" rel="nofollow"><code>xrange</code></a> in Python 2 and it returns an instance of a new class named <code>range</code>. For more changes/differences between Python 2/3 see <a href="https://www.python.org/dev/peps/pep-3100/#built-in-namespace" rel="nofollow"><code>PEP 3100</code></a>.</p>
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>Well, it is self explanatory</p>
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></a>). Python 2 does not have such a range class, so the <code>range</code> function just returns a list.</p>
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> <p>Here is an excerpt from the book: MIT Introduciton to algorithms:</p> <p>"Similarly, the <strong>RIGHT</strong> procedure can quickly compute 2i + 1 by shifting the binary representation of i left by one bit position and then adding in a 1 as the low-order bit". </p> <p><a href="http://i.stack.imgur.com/NSIYI.png" rel="nofollow"><img src="http://i.stack.imgur.com/NSIYI.png" alt="MIT Introduction to Algorithms - Heap"></a></p> <p><strong>Access Operations:</strong></p> <p>LEFT: 2*i</p> <pre><code>i&lt;&lt;1 </code></pre> <p>RIGHT: 2*i+1</p> <pre><code>(i&lt;&lt;1)+1 </code></pre> <p>PARENT: i/2</p> <pre><code>i&gt;&gt;1 </code></pre>
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> <p>It is easy to prove, that two distinct nodes cannot have same child. </p> <p>Suppose, <code>N1</code>, <code>N2</code> and <code>C</code> are heap nodes. <code>N1 != N2</code> and <code>C.is_child_of(N1)</code> and <code>C.is_child_of(N2)</code>, where <code>C.is_child_of(N)</code> returns <code>true</code> when <code>C</code> is either right or left child of <code>N</code>. Then:</p> <ol> <li>If <code>C</code> is the left child of both <code>N1</code> and <code>N2</code>, then <code>N1 * 2 = N2 * 2 &lt;=&gt; N1 = N2</code></li> <li>Similarly, if <code>C</code> is the right child of both <code>N1</code> and <code>N2</code>, then <code>N1 * 2 + 1 = N2 * 2 + 1 &lt;=&gt; N1 = N2</code></li> <li>If <code>C</code> is the left child of <code>N1</code> and <code>C</code> is the right child of <code>N2</code>, then <code>N1 * 2 = N2 * 2 + 1</code> which is incorrect, because <code>N1 * 2</code> is even and <code>N2 * 2 + 1</code> is odd.</li> </ol> <hr> <p>Note, that your bitwise access operations are incorrect - you should shift indices by one, not by two, because <code>N &lt;&lt; M</code> is <code>N * 2^M</code>. I'd also suggest you to use plain division / multiplication instead of bit shifting - the compiler knows how to optimize your code.</p>
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>&lt;tag1&gt; &lt;tag2&gt; .... &lt;div id=article&gt; &lt;p&gt; stuff1 &lt;/p&gt; &lt;p&gt; stuff2 &lt;/p&gt; &lt;p&gt; ...... &lt;/p&gt; &lt;p&gt; stuff30 &lt;/p&gt; </code></pre> <p>I want to extract <code>stuff1</code> through <code>stuff30</code> as string. Here is my Python code snippet.</p> <pre><code>import lxml.html import urllib.request html = urllib.request.urlopen('http://www.something.com/news/blah/').read() root = lxml.html.fromstring(html) content = root.xpath('string(//div[@id="article"]/p[position()=&gt;1 and position()&lt;=last()]/.)') </code></pre> <p>This code did not return anything.</p> <p>If I rewrite from <code>position()</code> statement to individual element index, it works.</p> <pre><code>content = root.xpath('string(//div[@id="article"]/p[25]/.)') </code></pre> <p>This code returns <code>stuff25</code> correctly.</p> <p>I don't want to run for loop just for this. I believe there is a way to get my code work with <code>position()</code>, but not sure what's wrong in my code.</p>
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()&gt;=1 and position()&lt;=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 given time x, runners on the course would have a start time &lt;= x and a endtime > x. However in Pandas one of these is giving me an error. </p> <p>I've imported the dataframe from Excel using the <code>read_exel</code> which automatically converts the start times and end times as <code>Datetime.time</code> objects. Here's some sample data</p> <pre><code>df = pd.DataFrame( {'name':['Bob','Sue','Joe'], 'start_time':[datetime.time(6,50,0),datetime.t‌​ime(6,55,0),dateti‌​me.time(7,0,0)], 'start_time':[datetime.time(7,15,04),datetime.time(7,21,41)‌​,datetime.time(7,23,24)],}) </code></pre> <p>Runners start at <code>6:50</code> and I would like to make a list of the amount of runners on the course every <code>4</code> minutes. So I've set up some variables to handle that:</p> <pre><code>race_start = datetime.datetime(100,1,1,6,50) intervaul = datetime.timedelta(minutes = 4) capture_time = race_start </code></pre> <p>Then I try to select the correct rows using Pandas built in selection</p> <pre><code>df[df.start_time &lt;= capture_time.time() &amp; df.end_time &gt; capture_time.time()] </code></pre> <p>However I get the error: </p> <blockquote> <p>TypeError: Cannot compare datetime.time and unicode</p> </blockquote> <p>In fact, <code>df.start_time &lt;= capture_time.time()</code> is perfectly fine and runs, but <code>df.end_time &lt;= capture_time.time()</code> returns this error.</p> <p>I have no idea what is going on here and any help would be appreciated.</p>
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 &lt;= capture_time.time()) &amp; (pd.end_time &lt;= capture_time.time())] </code></pre> <p>Or maybe <code>dtype</code> of column <code>end_time</code> is not <code>datetime</code>, so you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>:</p> <pre><code>pd.end_time = pandas.to_datetime(pd.end_time) </code></pre> <p>I think name for <code>DataFrame</code> is better <code>df</code>, then you can use:</p> <pre><code>import pandas as pd df.end_time = pd.to_datetime(df.end_time) </code></pre>
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 Lucas Perez, Granit Xhaka, and the young trio of Rob Holding, Takuma Asano and Kelechi Nwakali, alongside the German international. The news comes hours after the north London club announced the transfer of Perez to the Emirates, which is likely to see an end to their transfer business this summer.</p> </blockquote> <p>I want likely to categorize this content in category <strong>Sports</strong>. Is there any well written library in any programming languages like python,php,ruby?</p> <p>Question inspiration : <a href="http://www.newsnow.co.uk/" rel="nofollow">http://www.newsnow.co.uk/</a></p> <p>I saw one another question related to this but the answer not satisfying my requirement.</p> <p><a href="http://stackoverflow.com/questions/820296/auto-categorization-of-content">Auto Categorization of Content</a></p>
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) dict_writer.writeheader() dict_writer.writerows(final) </code></pre> <p>where <code>final</code> is a list of dictionaries of the form</p> <pre><code>final = [{'Name':'A','Hour':0,'Time':120},{'Name':'A','Hour':1,'Time':219},...,{'Name':'B','Hour':0,'Time':10},...] </code></pre> <p>How can I output final to .tsv format?</p>
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></pre>
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 Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name') </code></pre> <p><strong>views.py:</strong></p> <pre><code>class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer </code></pre> <p><strong>urls.py:</strong></p> <pre><code>router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) router.register(r'rooms', views.RoomViewSet) router.register(r'devices', views.DeviceViewSet) router.register(r'deviceTypes', views.DeviceTypeViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] </code></pre> <p>Now this all works fine, but I cant find out how to DELETE or UPDATE a user or a group, seems I can only add users and groups and view them. So my question is: How can I modify this code to make it possible to delete/update users and groups?</p>
-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-routers/#refactoring-to-use-viewsets" rel="nofollow">docs</a></p> <pre><code>class SnippetViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. </code></pre> <p>and the docs for <a href="http://www.django-rest-framework.org/api-guide/viewsets/#modelviewset" rel="nofollow"><code>ModelViewSet</code></a></p> <blockquote> <p>The actions provided by the ModelViewSet class are <code>.list()</code>, <code>.retrieve()</code>, <code>.create()</code>, <code>.update()</code>, <code>.partial_update()</code>, and <code>.destroy()</code>.</p> </blockquote>
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. 𝑑𝑒𝑠𝑡𝑖𝑛𝑎𝑡𝑖𝑜𝑛(𝑖) and 𝑠𝑜𝑢𝑟𝑐𝑒(𝑖) are the numbers of two tables with real data. If 𝑑𝑒𝑠𝑡𝑖𝑛𝑎𝑡𝑖𝑜𝑛(𝑖) ̸=𝑠𝑜𝑢𝑟𝑐𝑒(𝑖), copy all the rows from table 𝑠𝑜𝑢𝑟𝑐𝑒(𝑖) to table 𝑑𝑒𝑠𝑡𝑖𝑛𝑎𝑡𝑖𝑜𝑛(𝑖), then clear the table 𝑠𝑜𝑢𝑟𝑐𝑒(𝑖) and instead of real data put a symbolic link to 𝑑𝑒𝑠𝑡𝑖𝑛𝑎𝑡𝑖𝑜𝑛(𝑖) into it. And the answer is the maximum table size of the list lines. An example of order of operations:</p> <pre><code>5 5 1 1 1 1 1 3 5 2 4 1 4 5 4 5 3 </code></pre> <p>The input shows there are 5 tables, and we want to do 5 operations. Each of the tables has size 1. The following five lines show that we want to merge source5 to destination3, source4 to destination2... The output should be:</p> <pre><code>2 2 3 5 5 </code></pre> <p>Explanation: In this sample, all the tables initially have exactly 1 row of data. Consider the merging operations:</p> <ol> <li><p>All the data from the table 5 is copied to table number 3. Table 5 now contains only a symbolic link to table 3, while table 3 has 2 rows. 2 becomes the new maximum size.</p></li> <li><p>2 and 4 are merged in the same way as 3 and 5.</p></li> <li><p>We are trying to merge 1 and 4, but 4 has a symbolic link pointing to 2, so we actually copy all the data from the table number 2 to the table number 1, clear the table number 2 and put a symbolic link to the table number 1 in it. Table 1 now has 3 rows of data, and 3 becomes the new maximum size.</p></li> <li><p>Traversing the path of symbolic links from 4 we have 4 → 2 → 1, and the path from 5 is 5 → 3. So we are actually merging tables 3 and 1. We copy all the rows from the table number 1 into the table number 3, and now the table number 3 has 5 rows of data, which is the new maximum.</p></li> <li><p>All tables now directly or indirectly point to table 3, so all other merges won’t change anything.</p></li> </ol> <p>Instruction: Think how to use disjoint set union with path compression and union by rank heuristics to solve this problem. In particular, you should separate in your thinking the data structure that performs union/find operations from the merges of tables. If you’re asked to merge the first table into second, but the rank of the second table is smaller than the rank of the first table, you can ignore the requested order while merging in the Disjoint Set Union data structure and join the node corresponding to the second table to the node corresponding to the first table instead in you Disjoint Set Union. However, you will need to store the number of the actual second table to which you were requested to merge the first table in the parent node of the corresponding Disjoint Set, and you will need an additional field in the nodes of Disjoint Set Union to store it.</p> <p>Here is my code to implement it using rank heuristic and path compression:</p> <pre><code># python2 import sys n, m = map(int, sys.stdin.readline().split()) lines = list(map(int, sys.stdin.readline().split())) rank = [1] * n rank_original=[1]*n parent = list(range(0, n)) ans = max(lines) rank=lines for i in range(len(lines)): rank[i]=lines[i] rank_original[i]=lines[i] def getParent(i): # find parent and compress path if i!=parent[i]: parent[i]=getParent(parent[i]) return parent[i] def merge(destination, source): realDestination, realSource = getParent(destination), getParent(source) if realDestination == realSource: return False if rank[realDestination]&gt;=rank[realSource]: parent[realSource]=realDestination rank[realDestination] += rank[realSource] rank_original[realDestination]=rank[realDestination] else: parent[realDestination]=realSource rank[realSource]+=rank[realDestination] rank_original[realDestination]=rank[realSource] rank_original[source]=0 return True for i in range(m): destination, source = map(int, sys.stdin.readline().split()) merge(destination - 1, source - 1) ans=max(rank) print(ans) </code></pre>
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 this will result to <code>O(m + n)</code> time complexity.</p> <pre><code>n, m = map(int, raw_input().split()) rank = [0] + map(int, raw_input().split()) parent = range(n + 1) current_max = max(rank) def find_parent(x): if parent[x] != x: parent[x] = find_parent(parent[x]) return parent[x] for source, dest in (map(int, raw_input().split()) for _ in xrange(m)): source, dest = find_parent(source), find_parent(dest) if source != dest: if rank[source] &gt; rank[dest]: source, dest = dest, source parent[source] = dest rank[dest] += rank[source] current_max = max(current_max, rank[dest]) print current_max </code></pre>
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 # Create an ADS1115 ADC (16-bit) instance. adc = Adafruit_ADS1x15.ADS1115() # Or create an ADS1015 ADC (12-bit) instance. #adc = Adafruit_ADS1x15.ADS1015() # Note you can change the I2C address from its default (0x48), and/or the I2C # bus by passing in these optional parameters: #adc = Adafruit_ADS1x15.ADS1015(address=0x49, busnum=1) # Choose a gain of 1 for reading voltages from 0 to 4.09V. # Or pick a different gain to change the range of voltages that are read: # - 2/3 = +/-6.144V # - 1 = +/-4.096V # - 2 = +/-2.048V # - 4 = +/-1.024V # - 8 = +/-0.512V # - 16 = +/-0.256V # See table 3 in the ADS1015/ADS1115 datasheet for more info on gain. GAIN = 1 time_sensor = time.time() # Main loop. x = [1]*4 y = [2]*4 z = [3]*4 for i in range(4): x[i] = adc.start_adc(i, gain=GAIN) y[i] = adc.start_adc(i, gain=GAIN) z[i] = adc.start_adc(i, gain=GAIN) # Read the specified ADC channel using the previously set gain value. # Once continuous ADC conversions are started you can call get_last_result() to db = MySQLdb.connect("localhost", "root", "raspberry", "sensor_log") curs=db.cursor() while True: try: 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() except: print "Error" db.rollback() time.sleep(1) db.close() </code></pre> <p>The problem is when I run that script, the received data was duplicated, that script only getting data from the first data of accelerometer sensor and then insert it repeatedly.</p> <p>This is what i get.</p> <pre><code>+-------+------------+------------+------------+------------+ | id | time | koordinatX | koordinatY | koordinatZ | +-------+------------+------------+------------+------------+ | 24743 | 1472624612 | 15443 | 20351 | 20454 | | 24744 | 1472624612 | 15443 | 20351 | 20454 | | 24745 | 1472624612 | 15443 | 20351 | 20454 | | 24746 | 1472624612 | 15443 | 20351 | 20454 | | 24747 | 1472624612 | 15443 | 20351 | 20454 | | 24748 | 1472624612 | 15443 | 20351 | 20454 | +-------+------------+------------+------------+------------+ </code></pre> <p>I need the real data from the sensor, if i use print, the data will correctly displaying, but when i inserting it to mysql, the data will be like that.</p>
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: print "Error" db.rollback() time.sleep(1) </code></pre>
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>[Killed]</code> for <code>[Type] = Dog</code>.</p> <p>My code is as follow:</p> <ol> <li>Search for the mean</li> </ol> <p><code>df[df['Type'] == 'Dog'].mean().round()</code></p> <p>This will give me the mean (around 2.25)</p> <ol start="2"> <li>Impute the mean (This is where the problem begins)</li> </ol> <p><code>df.loc[(df['Type'] == 'Dog') &amp; (df['Killed'])].fillna(2.25, inplace = True)</code></p> <p>The code runs, but the value is not impute, the NaN value is still there.</p> <p>My Question is, how do I impute the mean in <code>[Killed]</code> based on <code>[Type] = Dog</code>.</p>
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="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a> by <code>Series</code> - because 2 columns <code>Killed</code> and <code>Survived</code>:</p> <pre><code>m = df[df['Type'] == 'Dog'].mean().round() print (m) Killed 4.0 Survived 3.0 dtype: float64 df.ix[df['Type'] == 'Dog'] = df.ix[df['Type'] == 'Dog'].fillna(m) print (df) Type Killed Survived 0 Dog 5.0 2 1 Dog 3.0 4 2 Cat 1.0 7 3 Dog 4.0 3 4 cow NaN 2 </code></pre> <p>If need fillna only in column <code>Killed</code>:</p> <pre><code>#if dont need rounding, omit it m = round(df.ix[df['Type'] == 'Dog', 'Killed'].mean()) print (m) 4 df.ix[df['Type'] == 'Dog', 'Killed'] = df.ix[df['Type'] == 'Dog', 'Killed'].fillna(m) print (df) Type Killed Survived 0 Dog 5.0 2 1 Dog 3.0 8 2 Cat 1.0 7 3 Dog 4.0 3 4 cow NaN 2 </code></pre> <p>You can reuse code like:</p> <pre><code>filtered = df.ix[df['Type'] == 'Dog', 'Killed'] print (filtered) 0 5.0 1 3.0 3 NaN Name: Killed, dtype: float64 df.ix[df['Type'] == 'Dog', 'Killed'] = filtered.fillna(filtered.mean()) print (df) Type Killed Survived 0 Dog 5.0 2 1 Dog 3.0 8 2 Cat 1.0 7 3 Dog 4.0 3 4 cow NaN 2 </code></pre>
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>[Killed]</code> for <code>[Type] = Dog</code>.</p> <p>My code is as follow:</p> <ol> <li>Search for the mean</li> </ol> <p><code>df[df['Type'] == 'Dog'].mean().round()</code></p> <p>This will give me the mean (around 2.25)</p> <ol start="2"> <li>Impute the mean (This is where the problem begins)</li> </ol> <p><code>df.loc[(df['Type'] == 'Dog') &amp; (df['Killed'])].fillna(2.25, inplace = True)</code></p> <p>The code runs, but the value is not impute, the NaN value is still there.</p> <p>My Question is, how do I impute the mean in <code>[Killed]</code> based on <code>[Type] = Dog</code>.</p>
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] ], columns=['Type', 'Killed', 'Survived']) df.Killed = df.groupby('Type').Killed.transform(lambda x: x.fillna(x.mean())) df </code></pre> <p><a href="http://i.stack.imgur.com/FkEYl.png" rel="nofollow"><img src="http://i.stack.imgur.com/FkEYl.png" alt="enter image description here"></a></p> <p>If you meant to consider the <code>np.nan</code> when calculating the mean</p> <pre><code>df.Killed = df.groupby('Type').Killed.transform(lambda x: x.fillna(x.fillna(0).mean())) df </code></pre> <p><a href="http://i.stack.imgur.com/SfAwg.png" rel="nofollow"><img src="http://i.stack.imgur.com/SfAwg.png" alt="enter image description here"></a></p>
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>[Killed]</code> for <code>[Type] = Dog</code>.</p> <p>My code is as follow:</p> <ol> <li>Search for the mean</li> </ol> <p><code>df[df['Type'] == 'Dog'].mean().round()</code></p> <p>This will give me the mean (around 2.25)</p> <ol start="2"> <li>Impute the mean (This is where the problem begins)</li> </ol> <p><code>df.loc[(df['Type'] == 'Dog') &amp; (df['Killed'])].fillna(2.25, inplace = True)</code></p> <p>The code runs, but the value is not impute, the NaN value is still there.</p> <p>My Question is, how do I impute the mean in <code>[Killed]</code> based on <code>[Type] = Dog</code>.</p>
3
2016-08-31T06:50:38Z
39,242,855
<p>Two problems: Note that <code>df.loc[(df['Type'] == 'Dog') &amp; (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 you garbage - <code>False</code> precisely where the columns 'Killed' is <code>nan</code>!</p> <p>See:</p> <pre><code>In [6]: df.loc[(df['Type'] == 'Dog') &amp; (df['Killed'])] Out[6]: Type Killed Survived 0 Dog 5.0 2 1 Dog 3.0 4 </code></pre> <p>What you want is the following:</p> <pre><code>In [5]: df.loc[(df['Type'] == 'Dog'), ['Killed']] Out[5]: Killed 0 5.0 1 3.0 3 NaN </code></pre> <p>One more problem is that you need to use assignment in combination with <code>.loc</code>. and <code>.fillna</code>, so like the following:</p> <pre><code>In [6]: df.loc[(df['Type'] == 'Dog'), ['Killed']] = df.loc[(df['Type'] == 'Dog'), ['Killed']].fillna(2.25) In [7]: df Out[7]: 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><h2> NOTE </h2> The value you gave for your mean is wrong or does not correspond to the data you gave in the answer. The mean should be 4.</p>
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. </p> <pre><code> def unnest (alist): List_ = list() for elements in alist: if type(elements) == list: unnest(elements) else: List_.append(elements) return List_ if __name__=='__main__': unnest([1,2,[3,4,5,[6,7,[8,9,[10,11,[12,[13,[14]]]]]]]]) </code></pre>
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: List_.append(elements) # just add "leaf" element return List_ if __name__=='__main__': z=recursion([1,2,[3,4,5,[6,7,[8,9,[10,11,[12,[13,[14]]]]]]]]) print(z) </code></pre> <p>output:</p> <pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] </code></pre>
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. </p> <pre><code> def unnest (alist): List_ = list() for elements in alist: if type(elements) == list: unnest(elements) else: List_.append(elements) return List_ if __name__=='__main__': unnest([1,2,[3,4,5,[6,7,[8,9,[10,11,[12,[13,[14]]]]]]]]) </code></pre>
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> <p>then use <code>flatten</code> instead of <code>rec</code>:</p> <pre><code>flatten([1,2,[3,4,[5,6,7]]]) </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. </p> <pre><code> def unnest (alist): List_ = list() for elements in alist: if type(elements) == list: unnest(elements) else: List_.append(elements) return List_ if __name__=='__main__': unnest([1,2,[3,4,5,[6,7,[8,9,[10,11,[12,[13,[14]]]]]]]]) </code></pre>
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: List_.append(elements) return List_ unnest([1,2,[3,4,5,[6,7,[8,9,[10,11,[12,[13,[14]]]]]]]]) </code></pre> <p>returns </p> <pre><code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] </code></pre>
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. </p> <pre><code> def unnest (alist): List_ = list() for elements in alist: if type(elements) == list: unnest(elements) else: List_.append(elements) return List_ if __name__=='__main__': unnest([1,2,[3,4,5,[6,7,[8,9,[10,11,[12,[13,[14]]]]]]]]) </code></pre>
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>def flatern(l,ml): for i in l: if isinstance(i,list): flatern(i,ml) else: ml.append(i) return ml </code></pre> <p><strong>Result</strong></p> <pre><code>In [52]: flatern(lst,[]) Out[52]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] </code></pre>
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. </p> <pre><code> def unnest (alist): List_ = list() for elements in alist: if type(elements) == list: unnest(elements) else: List_.append(elements) return List_ if __name__=='__main__': unnest([1,2,[3,4,5,[6,7,[8,9,[10,11,[12,[13,[14]]]]]]]]) </code></pre>
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 flattenA(old_list,new_list): for item in old_list: if isinstance(item,list): flattenA(item , new_list) else: new_list.append(item) return new_list return flattenA(old_list,[]) if __name__=='__main__': print( flatten([1,2,[3,4,5,[6,7,[8,9,[10,11,[12,[13,[14]]]]]]]]) ) # prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] </code></pre>
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. </p> <pre><code> def unnest (alist): List_ = list() for elements in alist: if type(elements) == list: unnest(elements) else: List_.append(elements) return List_ if __name__=='__main__': unnest([1,2,[3,4,5,[6,7,[8,9,[10,11,[12,[13,[14]]]]]]]]) </code></pre>
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, 10, 11, 12, 13, 14] </code></pre>
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: queryset = Model.objects.filter(a=1) if queryset.count(): with transaction.atomic(): queryset.update(a=2) # queryset will [] after this. for item in queryset: item.emit_event('Updated') except: logger.info('Exception') </code></pre> <p>My question is do I really need to have <code>transaction.atomic():</code> here? </p> <p>Secondly, after <code>.update</code> my queryset gets empty because its a filtered queryset. how to retain the values in my case as I want to emit an event on the individual objects.</p>
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 atomicity on the database is guaranteed. If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.</p> </blockquote> <p>In your example you would need <code>atomic</code> if <code>emit_event</code> is doing something and you want this update to be done only if all <code>emit_event</code> function calls and <code>queryset.update</code> are successfull. But if states of <code>emit_event</code> does not affect your business logic of update, <code>atomic</code> here would be redundant because as you said yourself <code>update</code> has internal <code>atomic</code>.</p> <p><strong>Second</strong></p> <p>Querysets are lazy. Which means evaluation of queryset will be done when you are iterating over it. So you need to do something like this. Answering latest comment</p> <pre><code>try: queryset = Model.objects.filter(a=1) item_ids = list(queryset.values_list('id', flat=True)) # store ids for later if item_ids: # optimzing here instead of queryset.count() so there won't be hit to DB with transaction.atomic(): queryset.update(a=2) # queryset will [] after this. for item in Model.objects.filter(id__in=item_ids): # &lt;- new queryset which gets only updated objects item.emit_event('Updated') except: logger.info('Exception') </code></pre> <p>See there we make new queryset when iterating over it to get updated items</p>
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', processors=[ResizeToCover(640, 640)], format='JPEG', options={'quality': 90}) image_thumbnail = ProcessedImageField(upload_to='thumbnails', processors=[SmartResize(128, 128)], format='JPEG', options={'quality': 70}) user = models.ForeignKey(User) def upload_image(self, image, user): if len(image.name) &gt; 30: image.name = image.name[:20] i = Images.objects.create(image=image, image_thumbnail=image, user=user) return i </code></pre> <p>The traceback is:</p> <pre><code>File "C:\Python35\lib\site-packages\imagekit\specs\__init__.py" in generate 149. img = open_image(self.source) File "C:\Python35\lib\site-packages\pilkit\utils.py" in open_image 21. target.seek(0) During handling of the above exception (I/O operation on closed file.), another exception occurred: File "C:\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python35\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "C:\Users\sp\industryo\nodes\views.py" in set_logo 173. i = Images.objects.create(image=image, user=user, image_thumbnail=image) File "C:\Python35\lib\site-packages\django\db\models\manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python35\lib\site-packages\django\db\models\query.py" in create 399. obj.save(force_insert=True, using=self.db) File "C:\Python35\lib\site-packages\django\db\models\base.py" in save 796. force_update=force_update, update_fields=update_fields) File "C:\Python35\lib\site-packages\django\db\models\base.py" in save_base 824. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Python35\lib\site-packages\django\db\models\base.py" in _save_table 908. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Python35\lib\site-packages\django\db\models\base.py" in _do_insert 947. using=using, raw=raw) File "C:\Python35\lib\site-packages\django\db\models\manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python35\lib\site-packages\django\db\models\query.py" in _insert 1043. return query.get_compiler(using=using).execute_sql(return_id) File "C:\Python35\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql 1053. for sql, params in self.as_sql(): File "C:\Python35\lib\site-packages\django\db\models\sql\compiler.py" in as_sql 1006. for obj in self.query.objs File "C:\Python35\lib\site-packages\django\db\models\sql\compiler.py" in &lt;listcomp&gt; 1006. for obj in self.query.objs File "C:\Python35\lib\site-packages\django\db\models\sql\compiler.py" in &lt;listcomp&gt; 1005. [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "C:\Python35\lib\site-packages\django\db\models\sql\compiler.py" in pre_save_val 955. return field.pre_save(obj, add=True) File "C:\Python35\lib\site-packages\django\db\models\fields\files.py" in pre_save 292. file.save(file.name, file, save=False) File "C:\Python35\lib\site-packages\imagekit\models\fields\files.py" in save 12. content = generate(spec) File "C:\Python35\lib\site-packages\imagekit\utils.py" in generate 134. content = generator.generate() File "C:\Python35\lib\site-packages\imagekit\specs\__init__.py" in generate 153. self.source.open() File "C:\Python35\lib\site-packages\django\db\models\fields\files.py" in open 81. self.file.open(mode) File "C:\Python35\lib\site-packages\django\core\files\uploadedfile.py" in open 96. self.file.seek(0) Exception Type: ValueError at /nodes/set_logo/ Exception Value: I/O operation on closed file. </code></pre> <p>What can be done here. Do i need to make changes in the packages? Help!</p>
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_image1(self, image, user, name, image1): if len(image1.name) &gt; 30: image1.name = image1.name[:20] i = Images.objects.create(image=image1, user=user) new_image_io = BytesIO() image.save(new_image_io, format='JPEG') i.image_thumbnail.save(name, content=ContentFile(new_image_io.getvalue())) return i </code></pre> <p>To Create the thumbnail, we had to open the image and save it as here:</p> <pre><code>new_image_io = BytesIO() image.save(new_image_io, format='JPEG') i.image_thumbnail.save(name, content=ContentFile(new_image_io.getvalue())) </code></pre> <p>Hope it helps!</p>
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="nofollow">http://doc.scrapy.org/en/latest/intro/tutorial.html#defining-our-item</a>, and even download an exact project from the github repo but the output I get is not of that described in the tutorial. </p> <pre><code>from scrapy.spiders import Spider from scrapy.selector import Selector from dirbot.items import Website class DmozSpider(Spider): name = "dmoz" allowed_domains = ["dmoz.org"] start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/", ] def parse(self, response): """ The lines below is a spider contract. For more info see: http://doc.scrapy.org/en/latest/topics/contracts.html @url http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/ @scrapes name """ sel = Selector(response) sites = sel.xpath('//ul[@class="directory-url"]/li') items = [] for site in sites: item = Website() item['name'] = site.xpath('a/text()').extract() item['url'] = site.xpath('a/@href').extract() item['description'] = site.xpath('text()').re('-\s[^\n]*\\r') items.append(item) return items </code></pre> <p>After I downloaded the project from github, I run "scrapy crawl dmoz" at the top level directory. I get the following output:</p> <pre><code>2016-08-31 00:08:19 [scrapy] INFO: Scrapy 1.1.1 started (bot: scrapybot) 2016-08-31 00:08:19 [scrapy] INFO: Overridden settings: {'DEFAULT_ITEM_CLASS': 'dirbot.items.Website', 'NEWSPIDER_MODULE': 'dirbot.spiders', 'SPIDER_MODULES': ['dirbot.spiders']} 2016-08-31 00:08:19 [scrapy] INFO: Enabled extensions: ['scrapy.extensions.logstats.LogStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.corestats.CoreStats'] 2016-08-31 00:08:19 [scrapy] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2016-08-31 00:08:19 [scrapy] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] 2016-08-31 00:08:19 [scrapy] INFO: Enabled item pipelines: ['dirbot.pipelines.FilterWordsPipeline'] 2016-08-31 00:08:19 [scrapy] INFO: Spider opened 2016-08-31 00:08:19 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2016-08-31 00:08:19 [scrapy] DEBUG: Telnet console listening on 128.1.2.1:2700 2016-08-31 00:08:20 [scrapy] DEBUG: Crawled (200) &lt;GET http://www.dmoz.org/Computers/Programming/Languages/Python/Books/&gt; (referer: None) 2016-08-31 00:08:20 [scrapy] DEBUG: Crawled (200) &lt;GET http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/&gt; (referer: None) 2016-08-31 00:08:20 [scrapy] INFO: Closing spider (finished) 2016-08-31 00:08:20 [scrapy] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 514, 'downloader/request_count': 2, 'downloader/request_method_count/GET': 2, 'downloader/response_bytes': 16179, 'downloader/response_count': 2, 'downloader/response_status_count/200': 2, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2016, 8, 31, 7, 8, 20, 314625), 'log_count/DEBUG': 3, 'log_count/INFO': 7, 'response_received_count': 2, 'scheduler/dequeued': 2, 'scheduler/dequeued/memory': 2, 'scheduler/enqueued': 2, 'scheduler/enqueued/memory': 2, 'start_time': datetime.datetime(2016, 8, 31, 7, 8, 19, 882944)} 2016-08-31 00:08:20 [scrapy] INFO: Spider closed (finished) </code></pre> <p>Was expecting this per the tutorial:</p> <pre><code>[scrapy] DEBUG: Scraped from &lt;200 http://www.dmoz.org/Computers/Programming/Languages/Python/Books/&gt; {'desc': [u' - By David Mertz; Addison Wesley. Book in progress, full text, ASCII format. Asks for feedback. [author website, Gnosis Software, Inc.\n], 'link': [u'http://gnosis.cx/TPiP/'], 'title': [u'Text Processing in Python']} [scrapy] DEBUG: Scraped from &lt;200 http://www.dmoz.org/Computers/Programming/Languages/Python/Books/&gt; {'desc': [u' - By Sean McGrath; Prentice Hall PTR, 2000, ISBN 0130211192, has CD-ROM. Methods to build XML applications fast, Python tutorial, DOM and SAX, new Pyxie open source XML processing library. [Prentice Hall PTR]\n'], 'link': [u'http://www.informit.com/store/product.aspx?isbn=0130211192'], 'title': [u'XML Processing with Python']} </code></pre>
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'] = site.xpath("text()").extract_first() item['url'] = site.xpath("@href").extract_first() item['description'] = site.xpath("following-sibling::div/text()").extract_first('').strip() yield item </code></pre> <p>For future reference you can always test whether a specific xpath works with <code>scrapy shell</code> command.<br> e.g. what I did to test this:</p> <pre><code>$ scrapy shell "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/" # test sites xpath response.xpath('//ul[@class="directory-url"]/li') [] # ok it doesn't work, check out page in web browser view(response) # find correct xpath and test that: response.xpath('//div[@class="title-and-desc"]/a') # 21 result nodes printed # it works! </code></pre>
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__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] </code></pre> <p>Cython class:</p> <pre><code>cdef class MyClass: def test(self, arg: int): pass print(dir(MyClass.test)) ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__objclass__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__'] </code></pre> <p>Are there any ways to get argumnets with annotations from Cython method?</p> <p>P.S. type of Cython's class method is not a method: <code>&lt;class 'method_descriptor'&gt;</code>, not a <code>&lt;class 'cython_function_or_method'&gt;</code></p>
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__' in dir(i) for i in [test2, test1, test]]) [False, False, True] </code></pre> <p>Apart from that, getting <code>__annotations__</code> simply returns an empty dictionary. It seems annotations are only used when generating the <code>C</code> code (haven't verified) and not meant to be available for the user.</p>
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 function iterates through the <code>df</code> and checks the content of <code>'text'</code> to make sure it is empty first. If <code>'text'</code> already has content it will <code>pass</code>. If <code>'text'</code> is empty it checks <code>'pub'</code> to see if I've got an appropriate BeautifulSoup template for that publication and if so returns clean text. If there is not yet a template the function will <code>pass</code>.</p> <pre><code>def pull_text(row): try: if(pd.isnull(row['text'])): if row['publication' ] == 'PubA': print('Now serving row',row.name,'of',len(df),'Template:',row['publication']) sys.stdout.flush() #Do Template A time.sleep(rand) return article.strip() elif row['publication' ] == 'PubB': #Do Template B time.sleep(rand) return article.strip() elif row['publication' ] == 'PubC': # Do Template C rand = randint(2,10) print('Waiting', rand, 'seconds') sys.stdout.flush() time.sleep(rand) return result.strip() else: pass print('No template set for', row['publication'],':row', row.name) else: pass except AttributeError: print('error at',row.name) sys.stdout.flush() return 'error' df['text'] = df.apply (lambda row: pull_text (row),axis=1) </code></pre> <p>Each template works fine and has pulled text from each publication. However whenever I run the function (such as after adding a new template) it seems to erase all pre-existing text data and fills in the pre-existing blanks (where it can).</p> <pre><code>In [3] df['text'] = df.apply (lambda row: pull_text (row),axis=1) In [4] df Out [4] pub link text 0 pubA linkA textA 1 pubB linkB None 2 pubC linkC None </code></pre> <p>Whilst what I desire is</p> <pre><code>Out [4] pub link text 0 pubA linkA textA 1 pubB linkB textB 2 pubC linkC textC </code></pre> <p>All I can think of is that I am somehow setting the value of <code>'text'</code> as a null value if it is not already, but I'm not sure how I'm doing it.</p>
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(required=True) </code></pre> <p>And</p> <pre><code>class Category(ndb.Model): name=StringProperty(required=True) </code></pre> <p>So how can i get all the datas from Product Class that belong to a certain Category?</p> <p>In Relational SQL i used:</p> <pre><code>SELECT * FROM Product WHERE category = 'CertainName'; </code></pre> <p>Thank you!</p>
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 category_entity and then apply the filter like this:</p> <pre><code>query = Product.query(Product.category == category_entity.key) </code></pre> <p>where, for example, you could fetch a category_entity like shown below:</p> <pre><code>category_entity = Category.query(Category.name == "SomeCat").fetch() </code></pre> <p>Refer to <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/appengine/standard/ndb/queries/snippets.py" rel="nofollow">https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/appengine/standard/ndb/queries/snippets.py</a> for more info (look at query_purchases_for_customer_via_key)</p>
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(required=True) </code></pre> <p>And</p> <pre><code>class Category(ndb.Model): name=StringProperty(required=True) </code></pre> <p>So how can i get all the datas from Product Class that belong to a certain Category?</p> <p>In Relational SQL i used:</p> <pre><code>SELECT * FROM Product WHERE category = 'CertainName'; </code></pre> <p>Thank you!</p>
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>category_key = Category.create_key(name='CertainName')</p> <p>query = Product.query(Product.category == category_key)</p>
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, or is it even possible?</p>
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" ]