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
listlengths
1
5
Find First Non-zero Value in Each Row of Pandas DataFrame
38,467,749
<p>I have a Pandas DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame([[0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], [1.0, 0.0, 1.0, 3.0, 1.0, 1.0, 7.0, 0.0], [0.0, 0.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0] ] , columns=['A', 'B', 'C', '...
6
2016-07-19T20:18:26Z
38,467,981
<p>I'm not sure that I would call this "better". But it returns a series in a one liner.</p> <pre><code>df.apply(lambda x: x[np.where(x &gt; 0)[0][0]], axis=1) &gt;&gt;&gt; 0 2.0 1 1.0 2 13.0 dtype: float64 </code></pre>
2
2016-07-19T20:31:30Z
[ "python", "pandas" ]
Find First Non-zero Value in Each Row of Pandas DataFrame
38,467,749
<p>I have a Pandas DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame([[0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], [1.0, 0.0, 1.0, 3.0, 1.0, 1.0, 7.0, 0.0], [0.0, 0.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0] ] , columns=['A', 'B', 'C', '...
6
2016-07-19T20:18:26Z
38,468,180
<p>try this:</p> <pre><code>res = df[df != 0.0].bfill(axis=1)['A'] </code></pre> <p>all i'm doing is replacing all non-zeros with <code>nan</code>s and then filling them in from the right, which forces all resulting values in the first column to be the first non-zero value in the row.</p> <p>or, a quicker way, as su...
5
2016-07-19T20:44:39Z
[ "python", "pandas" ]
Find First Non-zero Value in Each Row of Pandas DataFrame
38,467,749
<p>I have a Pandas DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame([[0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], [1.0, 0.0, 1.0, 3.0, 1.0, 1.0, 7.0, 0.0], [0.0, 0.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0] ] , columns=['A', 'B', 'C', '...
6
2016-07-19T20:18:26Z
38,468,431
<p>@acushner's answer is better. Just putting this out there.</p> <p>use <code>idxmax</code> and <code>apply</code></p> <pre><code>m = (df != 0).idxmax(1) df.T.apply(lambda x: x[m[x.name]]) 0 2.0 1 1.0 2 13.0 dtype: float64 </code></pre> <p>This also works:</p> <pre><code>m = (df != 0).idxmax(1) t = zi...
3
2016-07-19T20:59:21Z
[ "python", "pandas" ]
Find First Non-zero Value in Each Row of Pandas DataFrame
38,467,749
<p>I have a Pandas DataFrame:</p> <pre><code>import pandas as pd df = pd.DataFrame([[0.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], [1.0, 0.0, 1.0, 3.0, 1.0, 1.0, 7.0, 0.0], [0.0, 0.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0] ] , columns=['A', 'B', 'C', '...
6
2016-07-19T20:18:26Z
38,468,641
<p>This seems to work:</p> <pre><code>df[df!=0].cumsum(axis=1).min(axis=1) Out[74]: 0 2.0 1 1.0 2 13.0 dtype: float64 </code></pre>
4
2016-07-19T21:14:05Z
[ "python", "pandas" ]
Convert a list with filenames in to a name and suffix list in Python
38,467,899
<p>i have a list with filenames. How do i use the <code>os.path.splitext()</code> function to split the suffix and a filename and wirte it again into a list without the suffix.</p> <pre><code>import os image_names = os.listdir('C:\Pictures\Sample Pictures') newimageList = [] for name in image_names: newimageList.ap...
1
2016-07-19T20:27:03Z
38,467,993
<p>According to the <a href="https://docs.python.org/2/library/os.path.html#os.path.splitext" rel="nofollow">docs</a>, you should try <code>os.path.splitext('/desired_path')</code>.</p> <p>You just have to adjust your code...</p> <p>So, instead of:</p> <pre><code>newimageList.append(name.os.path.splitext()) </code><...
1
2016-07-19T20:32:23Z
[ "python" ]
Convert a list with filenames in to a name and suffix list in Python
38,467,899
<p>i have a list with filenames. How do i use the <code>os.path.splitext()</code> function to split the suffix and a filename and wirte it again into a list without the suffix.</p> <pre><code>import os image_names = os.listdir('C:\Pictures\Sample Pictures') newimageList = [] for name in image_names: newimageList.ap...
1
2016-07-19T20:27:03Z
38,468,004
<p>You want <code>os.path.splitext(name)</code> instead of <code>name.os.path.splitext()</code>.</p>
1
2016-07-19T20:33:09Z
[ "python" ]
Python Imgur API JSON output to CSV
38,467,926
<p>I'm pretty new to Python and coding in general but I somehow figured out how to string together an the Imgur API to give me a JSON out put file. My end goal is to be able to put the file into an Excel with some other already collected data so I'd like to be able to convert the API output to a CSV. - so far my only ...
0
2016-07-19T20:28:28Z
38,469,356
<p>This shouldn't be too hard as both JSON and CSV file structures can be represented fairly easily in Python using dictionaries. First, however, I should point out that the JSON data is in fact nested, which can be seen if we format it nicely:</p> <pre><code>{ "status": 200, "data": { "in_gallery": false, ...
0
2016-07-19T22:10:18Z
[ "python", "json", "csv", "export", "imgur" ]
Flip second dimension of tensor
38,467,955
<p>I want to flip order of elements in the second dimension of a tensor:</p> <pre><code>x = T.tensor3('x') f = theano.function([x], ?) print(f(x_data)) </code></pre> <p>input:</p> <pre><code>x_data = [[[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]], [[5, 0, 0, 0], [0, 6, 0, 0], [0, 0, 7, 0], [0, 0...
0
2016-07-19T20:30:16Z
38,468,041
<pre><code>[line[::-1] for line in x_data ] </code></pre>
1
2016-07-19T20:35:28Z
[ "python", "theano" ]
Flip second dimension of tensor
38,467,955
<p>I want to flip order of elements in the second dimension of a tensor:</p> <pre><code>x = T.tensor3('x') f = theano.function([x], ?) print(f(x_data)) </code></pre> <p>input:</p> <pre><code>x_data = [[[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]], [[5, 0, 0, 0], [0, 6, 0, 0], [0, 0, 7, 0], [0, 0...
0
2016-07-19T20:30:16Z
38,483,010
<p>You simply flip the dimensions you want and use full slice on the dimension before that you don't want to be changed: x_data[::, ::-1]</p> <pre><code>import numpy as np x = T.tensor3('x') x_data = np.asarray([[[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]], [[5, 0, 0, 0], [0, 6, 0, 0], [0,...
1
2016-07-20T13:42:24Z
[ "python", "theano" ]
unable to install python from source
38,467,966
<p>Every time I try to install install python 2.7.12 from source I get error while running the command <code>sudo make install</code> and python installation fails. However there is no error while running <code>make</code>. What could be the probable error?</p> <pre><code>Compiling /usr/local/lib/python2.7/xml/parsers...
-1
2016-07-19T20:30:43Z
38,468,452
<p>It's hard to tell since the error is so vague. I would try running the configure file again with possible options about you system. Without much more information, I can only guess you Makefile isn't configured right.</p> <p>You can also try downloading it using apt-get with the deadsnake repository. Just try:</p...
1
2016-07-19T21:00:33Z
[ "python", "python-2.7" ]
Combinations of several dicts python
38,468,030
<p>I have 15 dicts like the following 3 (all 15 are of varying lengths). For example:</p> <pre><code> HQDict = {'HQ1':10, 'HQ2':3, 'HQ3':5} BADict = {'BA1':15, 'BA2':4, 'BA3':3} STDict = {'ST1':5, 'ST2':4, 'ST3':3} </code></pre> <p>I want to create all the possible combinations of the 15 dicts with only one element...
0
2016-07-19T20:34:53Z
38,468,109
<blockquote> <p>I have seen itertools.combinations but I'm not sure how to make it only select 1 element from each dict.</p> </blockquote> <p>Use <code>itertools.product(..)</code> instead. It takes a varying list of arguments each corresponding to a list of options to pick in one iteration:</p> <pre><code>&gt;&gt;...
2
2016-07-19T20:40:14Z
[ "python", "dictionary" ]
Reverse estimating 3 numbers from mean and n
38,468,052
<p>I am trying to work out the n for three categories from the mean average and total number. I basically have the below:</p> <pre> Price n A 160.17 ? B 162.06 ? C 140 ? Total n: 27 Avg price: 156.95</pre> <p>For this one it comes out as A - 3, B - 18, C - 6. I basically found this out by tria...
0
2016-07-19T20:36:23Z
38,468,131
<p>This is not possible to formulaicly solve in the general case. If you let the number of items of A, B, and C be a, b, and c, respectively, this situation gives you the equations:</p> <p>a + b + c = 27 </p> <p>160.17*a + 162.06 * b + 140* c = 27 * 156.95</p> <p>This is two equations, but you are trying to solve f...
1
2016-07-19T20:41:40Z
[ "python", "math", "statistics", "average", "mean" ]
How to follow links with PyQT4?
38,468,056
<p>I am trying to do a search on google and then load the first link.</p> <p>I modified some sample code I found online:</p> <pre><code>class Render(QWebPage): def __init__(self, url): self.app = QApplication(sys.argv) QWebPage.__init__(self) self.loadFinished.connect(self._loadFinished) s...
0
2016-07-19T20:36:30Z
38,491,122
<p>So, I want to get this straight in my head... you're loading the default google page, setting the search text box to your search term, and then trying to emulate a click on "search?"</p> <p>Wouldn't it be far easier to just access google's search directly? i.e.:</p> <pre><code>http://www.google.com/search?q=stack...
0
2016-07-20T21:25:11Z
[ "python", "python-2.7", "pyqt", "pyqt4" ]
How to follow links with PyQT4?
38,468,056
<p>I am trying to do a search on google and then load the first link.</p> <p>I modified some sample code I found online:</p> <pre><code>class Render(QWebPage): def __init__(self, url): self.app = QApplication(sys.argv) QWebPage.__init__(self) self.loadFinished.connect(self._loadFinished) s...
0
2016-07-19T20:36:30Z
38,597,745
<p>After a little poking around with the code, I found out that <code>button.isNull()</code> returns <code>True</code>. It basically means that there is no element called <code>input[name=btnK]</code>. So you might want to search for the right element. </p> <p>However, initiating an instance is QApplication inside a Q...
0
2016-07-26T18:51:55Z
[ "python", "python-2.7", "pyqt", "pyqt4" ]
converting timedeltas to days error
38,468,069
<p>I've had problems converting <code>timedeltas</code> to an <code>int (days)</code>. </p> <pre><code>df.FIN = pd.to_datetime(df.FIN, errors = 'coerce') df.START = pd.to_datetime(df.START, errors = 'coerce') df["FIN-START"] = df["FIN"] - df["START"] </code></pre> <p><strong>* input: *</strong></p> <pre><code>0 0...
0
2016-07-19T20:37:11Z
38,468,486
<p>for each of the elements in the <code>Series</code>, convert the <code>timedelta</code> to <code>timedelta[D]</code> in the form of, for example, <code>94 days</code>. Then, just take it <code>astype</code> int.</p> <pre><code>df["days"] = df["FIN-START"].apply(lambda td: td.astype('timedelta64[D]').astype(int)) </...
0
2016-07-19T21:03:06Z
[ "python", "pandas" ]
Store tuples in an dictionary - Python
38,468,113
<p>Let's say I have a namedtuple:</p> <pre><code>tempTuple = namedtuple('tempTuple', 'lyrics num1 num2 num3') </code></pre> <p>and I want to store the namedtuple into a dictionary.</p> <p>I create several objects such as:</p> <pre><code>temp1 = tempTuple("hello, goodbye", 1, 2, 3) temp2 = tempTuple("final goodbye"...
-1
2016-07-19T20:40:28Z
38,468,313
<p>You can just put the namedtuples into the dictionary:</p> <pre><code>In [6]: test[temp1] = 'foo' In [7]: test Out[7]: {tempTuple(lyrics='hello, goodbye', num1=1, num2=2, num3=3): 'foo'} </code></pre> <p>edit: You can also use <code>test.keys()</code>.</p>
0
2016-07-19T20:52:23Z
[ "python", "dictionary", "tuples" ]
Store tuples in an dictionary - Python
38,468,113
<p>Let's say I have a namedtuple:</p> <pre><code>tempTuple = namedtuple('tempTuple', 'lyrics num1 num2 num3') </code></pre> <p>and I want to store the namedtuple into a dictionary.</p> <p>I create several objects such as:</p> <pre><code>temp1 = tempTuple("hello, goodbye", 1, 2, 3) temp2 = tempTuple("final goodbye"...
-1
2016-07-19T20:40:28Z
38,468,392
<p>namedtuples are stored in a dictionary the same way as any other object: (using the sample tuples you created above):</p> <pre><code>mydict = {} mydict['tuple1'] = temp1 mydict['tuple2'] = temp2 </code></pre> <p>Print the "lyrics" attribute like this: (using the namedtuple directly)</p> <pre><code>print(temp2.lyr...
0
2016-07-19T20:56:59Z
[ "python", "dictionary", "tuples" ]
Store tuples in an dictionary - Python
38,468,113
<p>Let's say I have a namedtuple:</p> <pre><code>tempTuple = namedtuple('tempTuple', 'lyrics num1 num2 num3') </code></pre> <p>and I want to store the namedtuple into a dictionary.</p> <p>I create several objects such as:</p> <pre><code>temp1 = tempTuple("hello, goodbye", 1, 2, 3) temp2 = tempTuple("final goodbye"...
-1
2016-07-19T20:40:28Z
38,468,439
<p>If the tuples are values in your dictionary, you privide a key and store the tuples.</p> <pre><code>your_dict['some_key'] = temp1 </code></pre> <p>and you extract information either by position or name:</p> <pre><code>your_dict['some_key'].lyrics your_dict['some_key'][0] # equivalent </code></pre> <p>If your tup...
0
2016-07-19T20:59:56Z
[ "python", "dictionary", "tuples" ]
Finding the Symbols for Companies in a Body of Text
38,468,149
<p>I am currently working in Python and I am trying to do some language processing on finance articles. However, every way I know of for querying information about a stock is via its ticker. <strong>So, my question is, do you know of a way to look up stock tickers from a general company name (not just the official name...
0
2016-07-19T20:42:42Z
38,469,914
<p>Sounds like a cool application. You could probably try creating a tuple for each company and make the values be a ticker and all possible nicknames for the company. Then you could store the tuples in a list and iterate through them to perform a search for the desired ticker.</p> <p>For example,</p> <pre><code>goog...
0
2016-07-19T23:04:36Z
[ "python", "python-3.x", "nlp", "finance", "stocks" ]
Why does sorted()'s key parameter require a keyword argument
38,468,150
<p>If you inspect the signature of Python's built-in <code>sorted()</code> function like this:</p> <pre><code>import inspect print(inspect.signature(sorted)) </code></pre> <p>The signature is: <code>(iterable, key=None, reverse=False)</code>.</p> <p>Based on my understanding of positional and optional arguments acqu...
4
2016-07-19T20:42:43Z
38,468,584
<p>This is <a href="https://bugs.python.org/issue26729" rel="nofollow">Python issue 26729</a>, an error in <code>sorted.__text_signature__</code>, which is missing the <code>/</code> and <code>*</code> required to indicate that <code>iterable</code> is positional-only and <code>key</code> and <code>reverse</code> are k...
2
2016-07-19T21:10:01Z
[ "python", "python-3.x", "sorted", "keyword-argument" ]
Find the index of a value in an array
38,468,209
<p>I have a two dimensional array. If I have one of the values how do I find its corresponding value? For example:</p> <pre><code> my_array=[[1,2][3,4][5,6]] </code></pre> <p>If I have the value <code>4</code>, how do I get it to tell me <code>3</code>? I tried</p> <pre><code>my_array.index(4) </code></pre> <p...
0
2016-07-19T20:46:50Z
38,468,275
<p>This is kind of a strange solution, but:</p> <pre><code>for item in my_array: if 4 in item: print item[abs(item.index(4)-1)] </code></pre> <p>First, check if the item is there. Then, if it is, <code>abs(item.index(4)-1</code> will always return the opposite index of the tuple.</p>
0
2016-07-19T20:50:12Z
[ "python", "python-3.x", "numpy" ]
Find the index of a value in an array
38,468,209
<p>I have a two dimensional array. If I have one of the values how do I find its corresponding value? For example:</p> <pre><code> my_array=[[1,2][3,4][5,6]] </code></pre> <p>If I have the value <code>4</code>, how do I get it to tell me <code>3</code>? I tried</p> <pre><code>my_array.index(4) </code></pre> <p...
0
2016-07-19T20:46:50Z
38,468,425
<p>Try this out. </p> <pre><code>import numpy as np my_array = np.array([[1,2],[3,4],[4,6]]) print x goodvalues = [3, 4, 7] ix = np.in1d(x.ravel(), goodvalues).reshape(x.shape) print ix </code></pre> <p>My outputs are...</p> <pre><code>[[1 2] [3 4] [4 6]] [[False False] [ True True] [ True False]] </code></p...
0
2016-07-19T20:58:48Z
[ "python", "python-3.x", "numpy" ]
Find the index of a value in an array
38,468,209
<p>I have a two dimensional array. If I have one of the values how do I find its corresponding value? For example:</p> <pre><code> my_array=[[1,2][3,4][5,6]] </code></pre> <p>If I have the value <code>4</code>, how do I get it to tell me <code>3</code>? I tried</p> <pre><code>my_array.index(4) </code></pre> <p...
0
2016-07-19T20:46:50Z
38,482,661
<p>Try this code:</p> <pre><code>[y for x in my_array for y in x].index(4) </code></pre> <p>Output :</p> <pre><code>3 </code></pre>
0
2016-07-20T13:27:40Z
[ "python", "python-3.x", "numpy" ]
Can this code be turned to use generators instead of lists?
38,468,215
<p>I have a structure like this (pseudo code):</p> <pre><code>class Player { steamid: str hero: Hero } class Hero { class_id: str level: int xp: int skills: list[Skill] } class Skill { class_id: str level: int } </code></pre> <p>Now I'm trying to store it into a database, and I gave my...
3
2016-07-19T20:47:16Z
38,468,604
<p>There's no way to avoid storing <code>O(len(players))</code> worth of data if you want to save the sets of your player, hero and skill data in separate operations on the database (rather than doing one operation for each player with their associated hero and skill data, or saving it all somehow in parallel).</p> <p...
1
2016-07-19T21:11:44Z
[ "python", "python-3.x", "generator" ]
How do I add the --trusted-host in pycharm package install?
38,468,224
<p>I installed Pycharm community Edition 2016.1.4 on a Windows 7 machine and tried to update some packages used by the project I intend to work on. The update failed because the local repository "<em>is not trusted or a secure host</em>" (according to <em>pip</em>), so to update packages in the command-line I need to r...
0
2016-07-19T20:47:51Z
38,514,593
<p>After some digging I found the answer. Registering it here in case someone is interested.</p> <p>Go to <em>File</em> --> <em>Settings</em> --> Project: <em>name_of_the_project</em> --> <em>Project Interpreter</em>. Choose (double click) the package you want to update and the <em>Available Packages</em> will pop-up....
0
2016-07-21T21:23:02Z
[ "python", "pycharm", "packages" ]
configuring theano in windows ? ' where to put the .theanorc.txt
38,468,255
<p>I've followed this installation tutorial : <a href="http://deeplearning.net/software/theano/install_windows.html#install-windows" rel="nofollow">http://deeplearning.net/software/theano/install_windows.html#install-windows</a></p> <p>As described in the tutorial, I've put the <code>.theanorc.txt</code> file in : </...
0
2016-07-19T20:49:26Z
38,605,098
<p>I did this myself just recently... nearly the exact situation!</p> <p>If you running an external IDE (i.e., not WinPython/Spyder), you need to put .theanorc in your Windows Users folder.</p> <p>For example: C:\Users[Your Name]\</p> <p>Note, I also recommend using the filename .theanorc not .theanorc.txt. I read t...
1
2016-07-27T06:17:21Z
[ "python", "theano", "deep-learning", "keras" ]
pandas: drop indices in dataframe A which don't appear in dataframe B
38,468,274
<p>I have 2 dataframes:</p> <p><strong>dataframe A:</strong></p> <pre><code> value1 value2 0 -0.5 0.5 1 0.5 -0.5 2 -0.5 -1 3 0.5 1 4 0.5 1.5 </code></pre> <p><strong>dataframe B:</strong></p> <pre><code> value1 value2 1 15 -5 2 -7 -1 3 -3 ...
2
2016-07-19T20:50:12Z
38,468,541
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html" rel="nofollow"><code>Index.intersection</code></a> to get overlapping index values.</p> <pre><code>i = dfa.index.intersection(dfb.index) print(dfa.loc[i]) # value1 value2 # 1 0.5 -0.5 # 2 -0.5 -1.0 ...
2
2016-07-19T21:07:03Z
[ "python", "pandas" ]
How can I get specific rows of a tensor in TensorFlow?
38,468,367
<p>I have several tensors: </p> <p>logits: This tensor contains the final prediction scores.</p> <pre><code>tf.Tensor 'MemN2N_1/MatMul_3:0' shape=(?, 18230) dtype=float32 </code></pre> <p>The final prediction is computed as predicted_op = tf.argmax(logits, 1, name="predict_op")</p> <p>Now I want to restrict the pre...
1
2016-07-19T20:55:34Z
38,480,751
<p>Did you try out <code>tf.equal</code>? This compares two tensors and creates a new tensor containing True where equal, and False where not equal. </p> <p>With this bool-tensor you feed <code>tf.select</code>, which choses from one tensor or another, element-wise, depending on the bool-value you created in step one....
0
2016-07-20T12:01:18Z
[ "python", "numpy", "tensorflow" ]
How can I get specific rows of a tensor in TensorFlow?
38,468,367
<p>I have several tensors: </p> <p>logits: This tensor contains the final prediction scores.</p> <pre><code>tf.Tensor 'MemN2N_1/MatMul_3:0' shape=(?, 18230) dtype=float32 </code></pre> <p>The final prediction is computed as predicted_op = tf.argmax(logits, 1, name="predict_op")</p> <p>Now I want to restrict the pre...
1
2016-07-19T20:55:34Z
39,319,715
<p>Try <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/array_ops.html#gather" rel="nofollow">tf.gather</a>.</p> <pre class="lang-py prettyprint-override"><code>row_indices = [1] row = tf.gather(tf.constant([[1, 2],[3, 4]]), row_indices) tf.Session().run(row) # returns [[3, 4]] </code></pre> <p>You...
0
2016-09-04T17:39:07Z
[ "python", "numpy", "tensorflow" ]
multiple .doc to .docx file conversion using python
38,468,442
<p>I want to convert all the .doc files from a particular folder to .docx file.</p> <p>I tried using the following code,</p> <pre><code>import subprocess import os for filename in os.listdir(os.getcwd()): if filename.endswith('.doc'): print filename subprocess.call(['soffice', '--headless', '--con...
0
2016-07-19T21:00:00Z
38,468,509
<p>Use <code>os.path.join</code> to specify the correct directory. </p> <pre><code>import os, subprocess main_dir = os.path.join('/', 'Users', 'username', 'Desktop', 'foldername') for filename in os.listdir(main_dir): if filename.endswith('.doc'): print filename subprocess.call(['soffice', '--he...
0
2016-07-19T21:04:22Z
[ "python", ".doc" ]
multiple .doc to .docx file conversion using python
38,468,442
<p>I want to convert all the .doc files from a particular folder to .docx file.</p> <p>I tried using the following code,</p> <pre><code>import subprocess import os for filename in os.listdir(os.getcwd()): if filename.endswith('.doc'): print filename subprocess.call(['soffice', '--headless', '--con...
0
2016-07-19T21:00:00Z
38,472,691
<p>I prefer to use the <code>glob</code> module for tasks like that. Put this in a file <code>doc2docx.py</code>. To make it executable, set <code>chmod +x</code>. And optionally put that file in your <code>$PATH</code> as well, to make it available "everywhere".</p> <pre><code>#!/usr/bin/env python import glob impor...
0
2016-07-20T05:04:37Z
[ "python", ".doc" ]
How to program this puzzle recursively?
38,468,488
<p>So I solved a brainteaser in my head, but i'm having a difficult time translating it to a recursive definition. The brainteaser is the broken weight problem (<a href="https://mathlesstraveled.com/2010/05/01/the-broken-weight-problem/" rel="nofollow">https://mathlesstraveled.com/2010/05/01/the-broken-weight-problem/<...
0
2016-07-19T21:03:09Z
38,469,000
<p>I believe this is the code you are looking for:</p> <pre><code>def _x(n): if n &lt;= 1: return (1,1) else: oldsum, oldterm = _x(n-1) newterm = 2*oldsum + 1 newsum = oldsum+newterm return (newsum, newterm) def x(n): return _x(n)[1] </code></pre> <p>Example:</p> ...
0
2016-07-19T21:41:26Z
[ "python", "logic", "puzzle" ]
How can I incorporate Python scripts into my website? Do I need a framework?
38,468,540
<p>I'm wondering if there's a good way for me to incorporate Python scripts into my current website. </p> <p>I have a personal website &amp; my own server that I have been working with for a while. So far it's just been html / css / javascript. I have made a Python script in the past that uses another website's API to...
2
2016-07-19T21:07:01Z
38,468,623
<p>If you are using only javascript and don't feel like a framework is the solution, you'd better rewrite your python script using javascript. These two languages have a lot in common and most of the stuff are transferable. Calling python from javascript would most likely not going to work that great. Again, unless you...
4
2016-07-19T21:12:51Z
[ "javascript", "python" ]
How can I incorporate Python scripts into my website? Do I need a framework?
38,468,540
<p>I'm wondering if there's a good way for me to incorporate Python scripts into my current website. </p> <p>I have a personal website &amp; my own server that I have been working with for a while. So far it's just been html / css / javascript. I have made a Python script in the past that uses another website's API to...
2
2016-07-19T21:07:01Z
38,468,783
<p>I completly agree with you about Django, but I think you can give a chance to Flask, it is really light and I can be used for many porpouses. Anyway if you want to call a python scripts you need a way to call it. I think you need a "listener" for the script for example a service or a web service (for this reason I t...
2
2016-07-19T21:23:35Z
[ "javascript", "python" ]
How can I incorporate Python scripts into my website? Do I need a framework?
38,468,540
<p>I'm wondering if there's a good way for me to incorporate Python scripts into my current website. </p> <p>I have a personal website &amp; my own server that I have been working with for a while. So far it's just been html / css / javascript. I have made a Python script in the past that uses another website's API to...
2
2016-07-19T21:07:01Z
38,469,045
<p>Give a chance to Flask! It's designed for the micro service that you just described. </p> <p>Here is what you could do with less than 30 lines of code:</p> <p><strong>app.py (flask file)</strong></p> <pre><code>from flask import Flask, request from flask import jsonify, render_template app = Flask(__name__, templ...
2
2016-07-19T21:45:34Z
[ "javascript", "python" ]
how to convert pandas series to tuple of index and value
38,468,549
<p>I'm looking for an efficient way to convert a series to a tuple of its index with its values.</p> <pre><code>s = pd.Series([1, 2, 3], ['a', 'b', 'c']) </code></pre> <p>I want an array, list, series, some iterable:</p> <pre><code>[(1, 'a'), (2, 'b'), (3, 'c')] </code></pre>
2
2016-07-19T21:07:36Z
38,468,600
<p>One possibility is to swap the order of the index elements and the values from <code>iteritems</code>:</p> <pre><code>res = [(val, idx) for idx, val in s.iteritems()] </code></pre> <p>EDIT: @Divakar's answer is faster by about a factor of 2. Building a series of random strings for testing:</p> <pre><code>N = 100...
3
2016-07-19T21:11:23Z
[ "python", "pandas" ]
how to convert pandas series to tuple of index and value
38,468,549
<p>I'm looking for an efficient way to convert a series to a tuple of its index with its values.</p> <pre><code>s = pd.Series([1, 2, 3], ['a', 'b', 'c']) </code></pre> <p>I want an array, list, series, some iterable:</p> <pre><code>[(1, 'a'), (2, 'b'), (3, 'c')] </code></pre>
2
2016-07-19T21:07:36Z
38,468,711
<p>Well it seems simply <code>zip(s,s.index)</code> works too!</p>
3
2016-07-19T21:18:21Z
[ "python", "pandas" ]
Countdown thread RPi stop if GPIO input change
38,468,557
<p>I'm not sure the best way to do this, and is not working for my as it will lock the program on when its asleep not sure how to make it works right...</p> <p>Im trying to monitor when a door open and closes with a raspberry Pi if there door is open for more than x time send some sort of alert (like and email), I've ...
0
2016-07-19T21:08:05Z
38,486,421
<p>I think i got a working script</p> <pre><code>#!/usr/bin/python import threading import time import logging import RPi.GPIO as GPIO import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText logging.basicConfig(level=logging.DEBUG,format='(%(threadName)-9s) %(message)s',) # ...
0
2016-07-20T16:52:14Z
[ "python", "linux", "raspbian", "python-multithreading", "gpio" ]
Multiple consecutive join with pyspark
38,468,568
<p>I'm trying to join multiple DF together. Because how join work, I got the same column name duplicated all over. </p> <blockquote> <p>When called on datasets of type (K, V) and (K, W), returns a dataset of (K, (V, W)) pairs with all pairs of elements for each key.</p> </blockquote> <pre><code># Join Min and Max...
1
2016-07-19T21:08:51Z
38,469,777
<p>You can use equi-join:</p> <pre><code> minTime.join(maxTime, ["UserId"]).join(sumTime, ["UserId"]) </code></pre> <p>aliases:</p> <pre><code>minTime.alias("minTime").join( maxTime.alias("maxTime"), col("minTime.UserId") == col("maxTime.UserId") ) </code></pre> <p>or reference parent table:</p> <pre><cod...
2
2016-07-19T22:53:00Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
Python loop freezing with no error
38,468,670
<p>I am trying to make a code in Python that shows the number of steps needed to reach one from any number using a simple algorithm. This is my code:</p> <pre><code>print('Enter the lowest and highest numbers to test.') min = input('Minimum number: ') min = int(min) max = input('Maximum number: ') max = int(max) + 1 p...
1
2016-07-19T21:15:39Z
38,468,755
<p>1) You are invoking <code>range()</code> incorrectly.</p> <p>Your code: <code>for n in range(max - min):</code> produces the range of numbers starting at <code>0</code> and ending at the value <code>max-min</code>. Rather, you want the range of numbers starting at <code>min</code> and ending at <code>max</code>.</p...
1
2016-07-19T21:21:20Z
[ "python", "python-3.x" ]
Python loop freezing with no error
38,468,670
<p>I am trying to make a code in Python that shows the number of steps needed to reach one from any number using a simple algorithm. This is my code:</p> <pre><code>print('Enter the lowest and highest numbers to test.') min = input('Minimum number: ') min = int(min) max = input('Maximum number: ') max = int(max) + 1 p...
1
2016-07-19T21:15:39Z
38,468,780
<p>It looks like it's getting stuck in the <code>while not num == 1</code> loop. Remember that <code>range()</code> starts at 0, so num is first set to 0, which is divisible by 2, and so will be reset to 0/2... which is 0 again! It will never reach 1 to break the loop.</p> <p>EDIT: I earlier said that <code>count = ...
0
2016-07-19T21:23:15Z
[ "python", "python-3.x" ]
Total number of alphanum values in python
38,468,677
<p>I am making a code in which every character is associated with a number. To make my life easier I decided to use alphanumeric values (a=97, b=98, z=121). The first step in my code would be to get a number out of a character. For example: <code>char = input"Write a character:" print(ord(char.lower()))</code></p> <p...
-3
2016-07-19T21:16:03Z
38,468,905
<p>Your question is not very clear. Why would you need total number of alphanum characters?</p> <p>thing is, that number depends on the encoding in question. If ASCII is in question then:</p> <pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; len(string.letters+string.digits) </code></pre> <p>Which is something you ...
1
2016-07-19T21:34:04Z
[ "python", "python-3.x", "alphanumeric" ]
Split a dataframe column's list into two dataframe columns
38,468,679
<p>I'm effectively trying to do a text-to-columns (from MS Excel) action, but in Pandas.</p> <p>I have a dataframe that contains values like: 1_1, 2_1, 3_1, and I only want to take the values to the right of the underscore. I figured out how to split the string, which gives me a list of the broken up string, but I don...
2
2016-07-19T21:16:12Z
38,468,767
<p>Use <code>expand=True</code> when doing the <code>split</code> to get multiple columns:</p> <pre><code>test['values'].str.split('_', expand=True) </code></pre> <p>If there's only one underscore, and you only care about the value to the right, you could use:</p> <pre><code>test['values'].str.split('_').str[1] </co...
3
2016-07-19T21:22:15Z
[ "python", "pandas" ]
Split a dataframe column's list into two dataframe columns
38,468,679
<p>I'm effectively trying to do a text-to-columns (from MS Excel) action, but in Pandas.</p> <p>I have a dataframe that contains values like: 1_1, 2_1, 3_1, and I only want to take the values to the right of the underscore. I figured out how to split the string, which gives me a list of the broken up string, but I don...
2
2016-07-19T21:16:12Z
38,468,820
<p>You are close:</p> <p>Instead of just splitting try this:</p> <pre><code>test2 = pd.DataFrame(test['values'].str.split('_').tolist(), columns = ['c1','c2']) </code></pre>
2
2016-07-19T21:27:27Z
[ "python", "pandas" ]
Looking for a way to de-reference a bash var wrapped in a python command call
38,468,720
<p>I'm trying to find a way to de-reference goldenClusterID to use it in an AWS CLI command to terminate my cluster. This program is to compensate for dynamic Job-Flow Numbers generated each day so normal Data Pipeline shutdown via schedule is applicable. I can os.system("less goldenClusterID") all day and it gives m...
-2
2016-07-19T21:19:09Z
38,483,988
<p>Never mind, I figured it out. Too much coffee and not enough sleep. The answer is to use: goldkeyID=open('goldenClusterID', 'r').read() os.system("aws emr describe-cluster --cluster-id %s" % goldkeyID)</p>
0
2016-07-20T14:25:26Z
[ "python", "linux", "bash", "amazon-web-services", "emr" ]
python pandas reading csv file error in column name
38,468,750
<p>I have a csv file with the first 2 rows with data as:</p> <pre><code>NewDateTime ResourceName 9/18/12 1:00 ANACACHO_ANA 9/18/12 2:00 ANACACHO_ANA </code></pre> <p>When I read it using pandas data frame as:</p> <pre><code>df = pd.read_csv(r'MyFile.csv') </code></pre> <p>I get </p> <pre><code>df...
1
2016-07-19T21:21:07Z
38,472,046
<p>It looks like your CSV file has a <a href="http://stackoverflow.com/questions/17912307/u-ufeff-in-python-string">BOM (Byte Order Mark) signature</a>, so try to parse using <code>'utf-8-sig'</code>, <code>'utf-16'</code> or another encoding <strong>with BOM</strong>:</p> <pre><code>df = pd.read_csv(r'MyFile.csv', en...
1
2016-07-20T03:53:52Z
[ "python", "csv", "pandas", "dataframe" ]
Efficient way to compare elements in two lists?
38,468,757
<p>I know this is similar to <a href="http://stackoverflow.com/questions/16974839/efficient-way-to-compare-elements-in-2-lists">Efficient way to compare elements in 2 lists</a>, but I have an extension on the question basically. </p> <p>Say I have two lists:</p> <pre><code>a = [1,2,4,1,0,3,2] b = [0,1,2,3,4] </code><...
0
2016-07-19T21:21:30Z
38,468,813
<p>If b is sorted consecutive integers as you shown here, then bucket sort is most effective. Otherwise, you may construct a hash table, with value b as the key, and construction a list of a's as values.</p>
1
2016-07-19T21:27:08Z
[ "python" ]
Efficient way to compare elements in two lists?
38,468,757
<p>I know this is similar to <a href="http://stackoverflow.com/questions/16974839/efficient-way-to-compare-elements-in-2-lists">Efficient way to compare elements in 2 lists</a>, but I have an extension on the question basically. </p> <p>Say I have two lists:</p> <pre><code>a = [1,2,4,1,0,3,2] b = [0,1,2,3,4] </code><...
0
2016-07-19T21:21:30Z
38,468,908
<pre><code>import collections dd=collections.defaultdict(list) for i,x in enumerate(a): dd[x].append(i) &gt;&gt;&gt; sorted(dd.items()) [(0, [4]), (1, [0, 3]), (2, [1, 6]), (3, [5]), (4, [2])] </code></pre>
1
2016-07-19T21:34:11Z
[ "python" ]
Efficient way to compare elements in two lists?
38,468,757
<p>I know this is similar to <a href="http://stackoverflow.com/questions/16974839/efficient-way-to-compare-elements-in-2-lists">Efficient way to compare elements in 2 lists</a>, but I have an extension on the question basically. </p> <p>Say I have two lists:</p> <pre><code>a = [1,2,4,1,0,3,2] b = [0,1,2,3,4] </code><...
0
2016-07-19T21:21:30Z
38,468,914
<p>A very simple and efficient solution is to build a mapping from the values in the range <code>0..N-1</code> to indices of <code>a</code>. The mapping can be a simple list, so you end up with:</p> <pre><code>indices = [[] for _ in b] for i, x in enumerate(a): indices[x].append(i) </code></pre> <hr> <p>Example ...
2
2016-07-19T21:34:24Z
[ "python" ]
Efficient way to compare elements in two lists?
38,468,757
<p>I know this is similar to <a href="http://stackoverflow.com/questions/16974839/efficient-way-to-compare-elements-in-2-lists">Efficient way to compare elements in 2 lists</a>, but I have an extension on the question basically. </p> <p>Say I have two lists:</p> <pre><code>a = [1,2,4,1,0,3,2] b = [0,1,2,3,4] </code><...
0
2016-07-19T21:21:30Z
38,469,394
<p>I'm not sure if this is efficient enough for your needs, but this would work:</p> <pre><code>from collections import defaultdict indexes = defaultdict(set) a = [1,2,4,1,0,3,2] b = [0,1,2,3,4] for i, x in enumerate(a): indexes[x].add(i) for x in b: print b, indexes.get(x) </code></pre>
0
2016-07-19T22:14:32Z
[ "python" ]
IDL-Python bridge fails due to SIP on OSX El Capitan
38,468,764
<p>I'm attempting to utilize the new IDL-Python bridge in IDL 8.5.1 on OSX El Capitan 10.11.5. I have used this feature on Windows since it was launched, which works beautifully, but it simply doesn't work on OSX.</p> <p>I have installed Anaconda Python 3.4.1 64bit to test.</p> <p>After setting up the environment as...
0
2016-07-19T21:22:00Z
38,601,032
<p>Okay, we are currently working on ways to more easily get the IDL-Python bridge to work on El Capitan. In the meantime, here are the steps you can take to get it to work. First, make sure you have your paths set up correctly. For example, in your .login file (not .cshrc):</p> <pre><code>setenv PATH /Users/username/...
1
2016-07-26T22:43:50Z
[ "python", "osx", "idl-programming-language" ]
cannot import pygame on pycharm - linux
38,468,795
<p>I'm trying to import pygame on pycharm, i already have installed pygame and it runs when i execute programs by command line, but when i try to use it from pycharm it doesn't work. I tried to add it to the project interpreter but an error occurs: </p> <p><code>Non-zero exit code (1) Collecting Pygame</code> <code>No...
0
2016-07-19T21:24:54Z
38,509,023
<p>I solved the problem by uninstalling and reinstalling pygame making sure to correctly solve all dependencies as explained by the <a href="http://www.pygame.org/wiki/CompileUbuntu?parent=Compilation" rel="nofollow">wiki</a></p>
0
2016-07-21T16:00:43Z
[ "python", "python-3.x", "pygame", "pycharm" ]
Python: Functions of arrays that return arrays of the same shape
38,468,798
<p>Note: I'm using numpy</p> <pre><code>import numpy as np </code></pre> <p>Given 4 arrays of the same (but arbitrary) shape, I am trying to write a function that forms 2x2 matrices from each corresponding element of the arrays, finds the eigenvalues, and returns two arrays of the same shape as the original four, wit...
0
2016-07-19T21:25:18Z
38,469,137
<p>Construct a 2x2x... array:</p> <pre><code>temp = np.array([[m1, m2], [m3, m4]]) </code></pre> <p>Move the first two dimensions to the end for a ...x2x2 array:</p> <pre><code>for _ in range(2): temp = np.rollaxis(temp, 0, temp.ndim) </code></pre> <p>Call <code>np.linalg.eigvals</code> (which broadcasts) for a...
1
2016-07-19T21:52:26Z
[ "python", "arrays", "function", "numpy" ]
Efficient way to match coordinates in 2d array
38,468,828
<p>I have a 2d array of coordinates and I want to find the index of the entry that matches a given coordinate.</p> <p>For example, my array could be <code>A</code>:</p> <pre><code>A = [[[1.5, 2.0], [1.0, 2.3], [5.4, 2.3]], [[3.2, 4.4], [2.0, 3.1], [0.0, 2.3]], [[1.0, 2.0], [2.3, 3.4], [4.0, 1.1]]] </code></...
0
2016-07-19T21:27:53Z
38,469,078
<p>You can possibly try this:</p> <pre><code>import numpy as np arrA = np.array(A) x = [1.0, 2.0] np.where((arrA == x).sum(axis = 2) == 2) # (array([2]), array([0])) </code></pre>
1
2016-07-19T21:48:20Z
[ "python", "arrays", "python-2.7", "numpy" ]
Efficient way to match coordinates in 2d array
38,468,828
<p>I have a 2d array of coordinates and I want to find the index of the entry that matches a given coordinate.</p> <p>For example, my array could be <code>A</code>:</p> <pre><code>A = [[[1.5, 2.0], [1.0, 2.3], [5.4, 2.3]], [[3.2, 4.4], [2.0, 3.1], [0.0, 2.3]], [[1.0, 2.0], [2.3, 3.4], [4.0, 1.1]]] </code></...
0
2016-07-19T21:27:53Z
38,469,084
<p>You could use a slightly simpler version of your code:</p> <pre><code>In [115]: A = [[[1.5, 2.0], [1.0, 2.3], [5.4, 2.3]], ...: [[3.2, 4.4], [2.0, 3.1], [0.0, 2.3]], ...: [[1.0, 2.0], [2.3, 3.4], [4.0, 1.1]]] In [116]: x = [1., 2.] In [117]: [(i, j) for i, row in enumerate(A) for j, coor in en...
2
2016-07-19T21:48:32Z
[ "python", "arrays", "python-2.7", "numpy" ]
Efficient way to match coordinates in 2d array
38,468,828
<p>I have a 2d array of coordinates and I want to find the index of the entry that matches a given coordinate.</p> <p>For example, my array could be <code>A</code>:</p> <pre><code>A = [[[1.5, 2.0], [1.0, 2.3], [5.4, 2.3]], [[3.2, 4.4], [2.0, 3.1], [0.0, 2.3]], [[1.0, 2.0], [2.3, 3.4], [4.0, 1.1]]] </code></...
0
2016-07-19T21:27:53Z
38,469,689
<p>If you'll be doing a lot of lookups, you can build an index mapping the coordinates to positions in your matrix. E.g., <code>(1.5, 2.0)</code> maps to <code>(0,0)</code>, <code>(1.0, 2.3)</code> maps to <code>(0, 1)</code>, etc. Here's how to build an index of your array:</p> <pre><code>&gt;&gt;&gt; A = [[[1.5, 2....
1
2016-07-19T22:44:30Z
[ "python", "arrays", "python-2.7", "numpy" ]
first-in-first-out matplotlib plotting
38,468,857
<p>I am doing a FIFO queue with temperature and dT lists and I am trying to plot the data. I have checked and the length of x,y,y1 are all 10 after they reach that many index values, so I know the if len(x)>10: part is working. However, when I plot, the real time plot does not update as I would expect. It essentially s...
0
2016-07-19T21:30:21Z
38,469,402
<p>When you want to dynamically update a plot, it is not recommended to 1) do the complete plot configuration in each iteration and 2) draw the plots on top of each other, e.g. <code>plt.scatter(..)</code> multiple times for the same position.</p> <p><a href="http://stackoverflow.com/questions/10944621/dynamically-upd...
1
2016-07-19T22:15:29Z
[ "python", "matplotlib" ]
Use series to get at value in dataframe
38,468,859
<p>I have a series and dataframe</p> <pre><code>import pandas as pd import numpy as np s = pd.Series(['x', 'y', 'z'], ['a', 'b', 'c']) df = pd.DataFrame(np.arange(9).reshape(3, 3), s.index, s.values) </code></pre> <p>I want to use <code>s</code> to select elements of <code>df</code>. I want a series of:</p> <pre><...
1
2016-07-19T21:30:30Z
38,468,947
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html" rel="nofollow"><code>lookup</code></a>:</p> <pre><code>df.lookup(s.index, s.values) [0 4 8] </code></pre> <p>Or as a pandas.Series:</p> <pre><code>pd.Series(df.lookup(s.index, s.values), s.index) a 0 b ...
4
2016-07-19T21:36:50Z
[ "python", "pandas" ]
Use series to get at value in dataframe
38,468,859
<p>I have a series and dataframe</p> <pre><code>import pandas as pd import numpy as np s = pd.Series(['x', 'y', 'z'], ['a', 'b', 'c']) df = pd.DataFrame(np.arange(9).reshape(3, 3), s.index, s.values) </code></pre> <p>I want to use <code>s</code> to select elements of <code>df</code>. I want a series of:</p> <pre><...
1
2016-07-19T21:30:30Z
38,468,960
<p>Use <code>at</code> in a <code>list</code> comprehension.</p> <pre><code>pd.Series([df.at[i, s[i]] for i in s.index], s.index) a 0 b 4 c 8 dtype: int64 </code></pre> <hr> <h3>Timing</h3> <p><strong>I'm leaving this here, but this is insufficient as pointed out by @root</strong></p> <p><strong>Just lis...
3
2016-07-19T21:37:53Z
[ "python", "pandas" ]
Use series to get at value in dataframe
38,468,859
<p>I have a series and dataframe</p> <pre><code>import pandas as pd import numpy as np s = pd.Series(['x', 'y', 'z'], ['a', 'b', 'c']) df = pd.DataFrame(np.arange(9).reshape(3, 3), s.index, s.values) </code></pre> <p>I want to use <code>s</code> to select elements of <code>df</code>. I want a series of:</p> <pre><...
1
2016-07-19T21:30:30Z
38,469,097
<p>Just chiming in</p> <pre><code>In [295]: %timeit pd.Series([df.at[i, s[i]] for i in s.index], s.index) 10000 loops, best of 3: 96.5 µs per loop In [296]: %timeit pd.Series([ df.ix[ind,col] for ind, col in s.iteritems() ], s.index) 10000 loops, best of 3: 86.3 µs per loop </code></pre>
2
2016-07-19T21:49:34Z
[ "python", "pandas" ]
RPC crashes with AttributeError: 'NoneType' object has no attribute 'call'
38,468,962
<p>I am trying to develop an agent that queries platform.historian but got this error message when using RPC query method: AttributeError: 'NoneType' object has no attribute 'call'</p> <pre><code>class TCMAgent(Agent): def __init__(self, config_path, **kwargs): super(TCMAgent, self).__init__(**kwargs) ...
0
2016-07-19T21:37:55Z
38,469,278
<p>Your agent doesn't connect to the platform nor does it "start". That is the issue you are dealing with here. I don't see how you are specifying your vip address to connect to the running platform either.</p> <p>You need to run your agent before you are able to allow it to make rpc calls. Something like the follo...
1
2016-07-19T22:04:16Z
[ "python", "volttron" ]
Wait for complete deletion of a DynamoDB table using boto3
38,469,105
<p>I need to delete a dynamodb table, and wait until it is completely removed. How can I check this?<br> boto3 api expose a method <code>get_waiter</code> to wait for certain events, but it is not well documented. Can I used for this purpose? Which would be the event name, or maybe handle a ResourceNotFoundException</p...
0
2016-07-19T21:50:33Z
38,471,181
<p>After <code>delete_table</code> API, call <code>table_not_exists</code> waiter. This waits until the specified table returns 404.</p> <pre><code>import boto3 client = boto3.client('dynamodb') client.delete_table(TableName='foo') waiter = client.get_waiter('table_not_exists') waiter.wait(TableName='foo') print ("tab...
1
2016-07-20T02:05:50Z
[ "python", "amazon-dynamodb", "boto3" ]
Extremely oversized/large buttons inside Kivy Screen class
38,469,175
<p>For the sake of brevity I'll explain my problem before posing the code. Here it goes:</p> <p>I have a <code>Screen</code> class in Kivy that holds two widgets, a <code>GridLayout</code> and an <code>Image</code>. The latter is fine, but the buttons are extremely oversized:</p> <p><a href="http://i.stack.imgur.com/...
0
2016-07-19T21:56:02Z
38,469,352
<p>You can use size_hint for this.</p> <p>Here is an example The pyhton file:</p> <pre><code>from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.lang import Builder from kivy.uix.screenmanager import Screen,ScreenManager Builder.load_file("my.kv") class MainButtons(GridLayout): pass c...
1
2016-07-19T22:09:41Z
[ "python", "user-interface", "graphics", "kivy" ]
Comparing Python Strings
38,469,205
<p>I have the following code. The variable transaction_date (which is retrieved from a Pandas dataframe) has the value '03/04/2015'. However, when I compare it to the string '03/04/2015', they are not equal. </p> <pre><code>for index, rows in df_per_line.iterrows(): validations = rows['NB_VALID'] transaction_d...
-1
2016-07-19T21:57:54Z
38,469,246
<p>The <code>transaction_date</code> is <code>'03/04/15'</code>. You're comparing it to <code>'03/04/2015'</code>. Note the <code>20</code>.</p>
3
2016-07-19T22:00:35Z
[ "python", "string", "equality" ]
Compare two python lists and expand the shorter list to the length of the longer list
38,469,212
<p>The question header I have is a little confusing and I just wasn't sure how too explain it well with just the header.</p> <p>I have two lists.</p> <pre><code>list_1 = [10,20,30,40,50,60,70,80,90] list_2 = [10,40,70] </code></pre> <p>Expected output:</p> <pre><code>new_list = [10,0,0,40,0,0,70,0,0] </code></pre> ...
0
2016-07-19T21:58:17Z
38,469,296
<pre><code>list_1 = [10,20,30,40,50,60,70,80,90] list_2 = [10,40,70] new_list = list_1[:] for i, v in enumerate(list_1): if v not in list_2: new_list[i] = 0 print new_list </code></pre> <p>result: </p> <pre><code>[10, 0, 0, 40, 0, 0, 70, 0, 0] </code></pre> <p>This checks the positions in list_1 which...
2
2016-07-19T22:05:16Z
[ "python", "list" ]
Compare two python lists and expand the shorter list to the length of the longer list
38,469,212
<p>The question header I have is a little confusing and I just wasn't sure how too explain it well with just the header.</p> <p>I have two lists.</p> <pre><code>list_1 = [10,20,30,40,50,60,70,80,90] list_2 = [10,40,70] </code></pre> <p>Expected output:</p> <pre><code>new_list = [10,0,0,40,0,0,70,0,0] </code></pre> ...
0
2016-07-19T21:58:17Z
38,469,315
<p>You are going over all the <code>to_be_expand_list</code> for each item on the <code>complete_list</code> and in (almost) each iteration you append an item, so at the end you will have <code>len(list1)*len(list2)</code> items.</p> <p>You should change it to:</p> <pre><code>def expand_list(complete_list, to_be_expa...
2
2016-07-19T22:06:35Z
[ "python", "list" ]
Compare two python lists and expand the shorter list to the length of the longer list
38,469,212
<p>The question header I have is a little confusing and I just wasn't sure how too explain it well with just the header.</p> <p>I have two lists.</p> <pre><code>list_1 = [10,20,30,40,50,60,70,80,90] list_2 = [10,40,70] </code></pre> <p>Expected output:</p> <pre><code>new_list = [10,0,0,40,0,0,70,0,0] </code></pre> ...
0
2016-07-19T21:58:17Z
38,469,320
<p>Try something like this:</p> <pre><code>def expand_list(full_list, short_list): return [x if x in short_list else 0 for x in full_list] </code></pre> <p>This uses a list comprehension to generate a list which is the length of the complete list, but contains only those elements which were in the short list, repla...
6
2016-07-19T22:06:44Z
[ "python", "list" ]
Take 4 number's sums, then add those 4 numbers onto the sums of those 4 numbers, then repeat
38,469,226
<p>Every year during the Super Bowl my dad does a bet with his friends, guess the last number of the score, and whoever guesses correctly wins 20 dollars. My question is hard to explain in words so I drew a diagram: <a href="http://i.stack.imgur.com/1ECrH.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/1ECrH.jpg...
4
2016-07-19T21:58:58Z
38,469,592
<pre><code>nums = [2,3,6,7] x = [] for i in range(5): for p in itertools.product(nums, repeat=i): x.append(sum(p)) </code></pre>
2
2016-07-19T22:34:57Z
[ "python", "math" ]
Scrapy: extrat items within JSON response
38,469,273
<p>I'm trying to pull individual objects out of a JSON response. The following is the response I get from the website I'm trying to scrape:</p> <pre><code>[{"name":"AAA 404","id":"AAA404","sections":[{"id":"5393643","name":"40053","instructor":"Dellabough"}]},{"name":"AAA 604","id":"AAA604","sections":[{"id":"5393644"...
1
2016-07-19T22:03:35Z
38,469,333
<p>Just iterate over the <em>sections</em> dicts using an inner loop, the id and name from each i will be associated with each:</p> <pre><code>for dct in i["sections"]: print(i["id"], i["name"], dct["instructor"], dct["id"], dct["name"]) </code></pre>
0
2016-07-19T22:07:36Z
[ "python", "json", "scrapy" ]
Understanding references in Python
38,469,325
<p>Following example:</p> <pre><code>a = 1 b = a b = 3 print(a) # gives 1 </code></pre> <p>But, when I do:</p> <pre><code>a = [1,2] b = a b[0] = 3 print(a) # gives [3,2] </code></pre> <p>How do I know whether a variable is treated like a (C++ type) reference or a plain variable? Are elementary data types just an ex...
3
2016-07-19T22:07:00Z
38,469,412
<p>Every name is a plain reference.</p> <p>A variable name is a reference to an object, and what matters is the properties of the object. Rule: numbers (int, float, etc.), strings, tuples (and others) are <em>immutable</em> - read-only. Lists, dictionaries, sets (and others) are <em>mutable</em>.</p> <p>So the dif...
0
2016-07-19T22:16:24Z
[ "python", "reference" ]
Understanding references in Python
38,469,325
<p>Following example:</p> <pre><code>a = 1 b = a b = 3 print(a) # gives 1 </code></pre> <p>But, when I do:</p> <pre><code>a = [1,2] b = a b[0] = 3 print(a) # gives [3,2] </code></pre> <p>How do I know whether a variable is treated like a (C++ type) reference or a plain variable? Are elementary data types just an ex...
3
2016-07-19T22:07:00Z
38,469,590
<p>Everything is a reference. All python variables reference objects, all objects can have more than one reference.</p> <p>The difference you're seeing is between the assignment operator and the <code>__setitem__</code> operator. The syntax is similar, but they do different things.</p> <p>This is an assignment, it up...
0
2016-07-19T22:34:46Z
[ "python", "reference" ]
Understanding references in Python
38,469,325
<p>Following example:</p> <pre><code>a = 1 b = a b = 3 print(a) # gives 1 </code></pre> <p>But, when I do:</p> <pre><code>a = [1,2] b = a b[0] = 3 print(a) # gives [3,2] </code></pre> <p>How do I know whether a variable is treated like a (C++ type) reference or a plain variable? Are elementary data types just an ex...
3
2016-07-19T22:07:00Z
38,469,647
<p><em>All</em> variables in Python are references. Elementary data types aren't an exception.</p> <p>In the first example, you <em>reassign</em> <code>b</code>. It no longer references the same object as <code>a</code>.</p> <p>In the second example, you <em>modify</em> <code>b</code>. Since you've previously set <co...
3
2016-07-19T22:40:13Z
[ "python", "reference" ]
Understanding references in Python
38,469,325
<p>Following example:</p> <pre><code>a = 1 b = a b = 3 print(a) # gives 1 </code></pre> <p>But, when I do:</p> <pre><code>a = [1,2] b = a b[0] = 3 print(a) # gives [3,2] </code></pre> <p>How do I know whether a variable is treated like a (C++ type) reference or a plain variable? Are elementary data types just an ex...
3
2016-07-19T22:07:00Z
38,469,820
<p>For a better grasp of this kind of issues, I would encourage you to use the <strong>Online Python Tutor</strong>. This is an extremely handy tool that renders a graphical representation of the objects in memory while the code is executed step by step.</p> <p>To show the Online Python Tutor in action I have splitted...
1
2016-07-19T22:56:18Z
[ "python", "reference" ]
Selecting a string from python enumeration
38,469,326
<p>So, for example let's just say we have a list of strings, like months. We want to only print one of those, based on the input from a variable (or var-1, due to the enumerate function starting with 0 opposed to 1, so the variable is between 0 and 11). So how would I go about selecting one of those based on input and ...
0
2016-07-19T22:07:00Z
38,469,368
<p>Just <a href="http://www.tutorialspoint.com/python/list_index.htm" rel="nofollow">index</a> the list:</p> <pre><code>i = int(input("0-11: ")) months = ["January",.."December"] if 0 &lt;= i &lt; 12: print(months[i]) else: print("Must be a number from 0-11") </code></pre> <p>Or using 1-12:</p> <pre><code>...
0
2016-07-19T22:11:31Z
[ "python", "enumerate" ]
Selecting a string from python enumeration
38,469,326
<p>So, for example let's just say we have a list of strings, like months. We want to only print one of those, based on the input from a variable (or var-1, due to the enumerate function starting with 0 opposed to 1, so the variable is between 0 and 11). So how would I go about selecting one of those based on input and ...
0
2016-07-19T22:07:00Z
38,469,627
<p>I think that we can use a simple answer here, as long as your months are in order. Simply convert the input to int and index the list normally:</p> <pre><code>i = int(input("0-11: ")) months= ['january', 'february', 'etc'] print(months[i]) # input of 1 will yield the 2nd item in the list of months &gt;&gt;&gt;0-1...
0
2016-07-19T22:38:07Z
[ "python", "enumerate" ]
How do you draw a sector in matplotlib?
38,469,404
<p>I would like just a pure sector line, not a wedge. I am trying to use it to represent the uncertainty of a vector's direction, at the tip of the vector arrow. I am using plt.arrow to plot the arrow over a basemap in matplotlib. </p> <p>I haven't been able to find any way to express this uncertainty other than with ...
3
2016-07-19T22:15:31Z
38,469,858
<p>Assuming you have an arbitrary vector <code>v</code> relative to some origin <code>v_origin</code>, and it's angular uncertainty in degrees:</p> <pre><code>import pylab as plt import numpy as np #plt.style.use('ggplot') # because it's just better ;) v_origin = [.2, .3] v = [1., 1.] angular_uncert = 20. # angular ...
5
2016-07-19T22:59:46Z
[ "python", "matplotlib", "sector" ]
Django Rest Framework: Specifying a OneToOneField by ID when creating an object via ModelViewSet
38,469,411
<p>I'm having some trouble creating an object with a OneToOneField reference by ID. Example of my code:</p> <p>models.py</p> <pre><code>class Person(models.Model): name = models.CharField(length=50) class ExtraInfo(models.Model): person = models.OneToOneField( Person, related_name='+', ...
0
2016-07-19T22:16:18Z
38,470,138
<p>The serializer expect the <code>person</code> to be model instance, so you could do:</p> <pre><code>{ "person": Person.objects.get(pk=3), "info": "blah" } </code></pre> <p>In the view you get the firs-order representation of related model instance, which is its primary key. You could also get the complete ...
0
2016-07-19T23:31:03Z
[ "python", "django", "django-rest-framework" ]
How to insert into an existing mysql database table using flask and sqlalchemy
38,469,448
<p>Ok I am trying to insert a new row into an existing mysql database table using a restful API application based on Flask and sqlalchemy. I want it to take the values from the incoming http POST request and then create a new row in the "object" table of the given database with the values received from the POST request...
-1
2016-07-19T22:19:40Z
38,535,272
<p>The fix was to change the way the class was instantiated. </p> <p>I changed line 30 from this:</p> <pre><code>r_object_row = Object(r_object_id, r_object_name) </code></pre> <p>to this:</p> <pre><code>r_object_row = Object() r_object_row.id = r_object_id r_object_row.name = r_object_name </code></pre>
0
2016-07-22T21:09:34Z
[ "python", "rest", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Python Selenium - element is not attached to the page document
38,469,472
<p>I'm trying to parse Facebook fan page likers and get exception in line </p> <pre><code>driver.get("{}".format(url.get_attribute("href"))) </code></pre> <blockquote> <p>selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document</p> <...
0
2016-07-19T22:22:15Z
38,470,048
<p>You are no longer on the same page after you navigate to another page in the for loop. This should be resolved if you navigate back to the original page where you fetched the <code>all_likes_urls</code> from at the end of each iteartion of the for loop i.e. </p> <pre><code>def open_post_likes(): all_likers = []...
0
2016-07-19T23:20:24Z
[ "python", "parsing", "selenium", "selenium-webdriver" ]
tensorflow-syntaxnet: Where are sentence_pb2 and gen_parser_ops?
38,469,494
<p>I cannot import these two python files from syntaxnet and I cannot find them either. Does anyone know how to solve this issue? Thanks!</p> <p>from syntaxnet.ops import gen_parser_ops from syntaxnet import sentence_pb2</p>
0
2016-07-19T22:24:24Z
39,182,361
<p>Those two are imported in <code>syntaxnet/syntaxnet/conll2tree.py</code>. You can get their locations by adding lines like below in <code>conll2tree.py</code>:</p> <pre><code>import os print os.path.realpath(gen_parser_ops.__file__) </code></pre> <p>and then run the <code>demo.sh</code> as in the installation guid...
0
2016-08-27T14:43:44Z
[ "python", "tensorflow", "syntaxnet" ]
RabbitMQ on Docker: Pika hangs on connection when given port, connection refused without port
38,469,497
<p>I am trying to connect to a queue using pika, run on my local box, and rabbitmq run in a docker container. I am able to access rabbitmq on <a href="http://0.0.0.0:15677" rel="nofollow">http://0.0.0.0:15677</a> with both curl commands and by viewing it in a web browser, so I know that rabbitmq looks like it is runnin...
0
2016-07-19T22:24:40Z
38,509,825
<p>If you use the TCP port of the management web UI for your AMQP client, it cannot work: RabbitMQ expects HTTP requests on that port, not AMQP frames. That's why the client appears to hang.</p> <p>If you don't specify a TCP port, it will use 5672, the default AMQP port. According to the management UI port (15677), I ...
1
2016-07-21T16:39:36Z
[ "python", "docker", "rabbitmq", "pika", "connection-refused" ]
Python for loop only executes once
38,469,510
<p>I am currently working on some code that will look through multiple directories from an .ini file then print and copy them to a new directory. I ran into a problem where the for loop that prints the files only executes once when it is supposed to execute 5 times. How can i fix it so the for loop works every time it ...
0
2016-07-19T22:26:03Z
38,470,259
<p>The <code>pathName</code> you get when iterating over the file has a newline character at the end for each line but the last. This is why you get the blank lines in your output after each path is printed.</p> <p>You need to call <code>strip</code> on your paths to remove the newlines:</p> <pre><code>for pathName i...
0
2016-07-19T23:46:58Z
[ "python", "for-loop" ]
Python Tkinter Scrollbar within a Class
38,469,608
<p>My goal is to create a GUI TKinter class with vertical and horizontal scrolls.</p> <p>I have a chart whose dimension is bigger than the window dimension of the GUI. I put the chart within a canvas to enable the scrollbar function that allows vertical and horizontal scroll.</p> <p>However when I run my code, the gr...
1
2016-07-19T22:36:28Z
38,479,010
<p>First note I would like to point to is that you have many useless container widgets. So in my solution below, I will remove away all that useless code; I mean all what is related to <code>Frame_parent</code>, <code>Frame_child</code> and <code>Canvas_parent</code>. Note that in my solution below, I can let those wi...
1
2016-07-20T10:40:31Z
[ "python", "canvas", "tkinter", "scrollbar", "frame" ]
Iterate list while assigning new values to it
38,469,609
<p>I have a python code that changes the list while iterating. Why is it iterating 5 times? I expect it should iterate according to the new list. </p> <p>what is "<code>for i in l</code>" doing underneath? why it has nothing to do with l while iteration? </p> <p>if <code>l</code> is not changed, why after loop it is...
0
2016-07-19T22:36:32Z
38,469,664
<p>Inside the for loop, you are reassigning the variable of <code>l</code> to a new list – but <em>not</em> changing the original <code>l</code> over which you are still iterating.</p> <p>Here's a more concise example demonstrating this situation, where <code>l</code> is now called <code>my_object</code>, and where ...
1
2016-07-19T22:42:17Z
[ "python", "for-loop" ]
Iterate list while assigning new values to it
38,469,609
<p>I have a python code that changes the list while iterating. Why is it iterating 5 times? I expect it should iterate according to the new list. </p> <p>what is "<code>for i in l</code>" doing underneath? why it has nothing to do with l while iteration? </p> <p>if <code>l</code> is not changed, why after loop it is...
0
2016-07-19T22:36:32Z
38,469,851
<p>You are not actually changing the list by assigning</p> <pre><code>l = range(1, cnt) </code></pre> <p>If you studied C type languages before, this assignment behaves like another definition in another scope. Also the list is cached before the for loop starts running to avoid repetition. For example,</p> <pre><cod...
1
2016-07-19T22:59:13Z
[ "python", "for-loop" ]
Realtime plotting with PyQt PlotWidget - error message PlotWidget object is not callable
38,469,630
<p>I am trying to create a real time data plot using a PyQt plot widget. I read that PyQt is the best option for plotting real time graphs but so far I am not having any success. </p> <p>I have tried to plot random data using the method <a href="http://stackoverflow.com/questions/18080170/what-is-the-easiest-way-to-ac...
1
2016-07-19T22:38:23Z
38,486,131
<p>I have been confronted with similar issues. But in the end I got my realtime plot working!</p> <p>I have taken a look at my code, and thrown out all the things that are not relevant for you. So what you will find here is the basic code that you need to display a live graph:</p> <pre><code>#########################...
1
2016-07-20T16:37:22Z
[ "python", "plot", "pyqt", "real-time" ]
Realtime plotting with PyQt PlotWidget - error message PlotWidget object is not callable
38,469,630
<p>I am trying to create a real time data plot using a PyQt plot widget. I read that PyQt is the best option for plotting real time graphs but so far I am not having any success. </p> <p>I have tried to plot random data using the method <a href="http://stackoverflow.com/questions/18080170/what-is-the-easiest-way-to-ac...
1
2016-07-19T22:38:23Z
38,515,464
<p>Ok so I was able to solve the error I was getting and was able to update the plot widget in real time. The code below gives some basic examples. I hope to improve this answer overtime to show the functionality of real time plotting in PyQt. </p> <pre><code>from PyQt4.QtGui import * from PyQt4.QtCore import * impor...
0
2016-07-21T22:36:48Z
[ "python", "plot", "pyqt", "real-time" ]
TensorFlow: Non-repeatable results
38,469,632
<h1>The Problem</h1> <p>I have a Python script that uses TensorFlow to create a multilayer perceptron net (with dropout) in order to do binary classification. Even though I've been careful to set both the Python and TensorFlow seeds, I get non-repeatable results. If I run once and then run again, I get different resul...
0
2016-07-19T22:38:34Z
38,469,668
<p>You need to set operation level seed in addition to graph-level seed, ie</p> <pre><code>tf.reset_default_graph() a = tf.constant([1, 1, 1, 1, 1], dtype=tf.float32) graph_level_seed = 1 operation_level_seed = 1 tf.set_random_seed(graph_level_seed) b = tf.nn.dropout(a, 0.5, seed=operation_level_seed) </code></pre>
1
2016-07-19T22:42:37Z
[ "python", "random", "tensorflow" ]
Redirect output to HTML using flask
38,469,729
<p>I am trying to connect to DB and show some data on webpage, below is what i tried:</p> <pre><code>import jaydebeapi import jpype import sys from flask import Flask from flask import request, render_template app = Flask(__name__) @app.route('/') def my_form(): return render_template('Name.html') @app.route('/'...
0
2016-07-19T22:48:30Z
38,472,682
<pre><code>@app.route('/', methods = ['GET','POST']) def my_form(): if request.method='GET': return render_template('Name.html') if request.method='POST': classpath="/export/home/tdgssconfig.jar:/export/home/terajdbc4.jar" Name = request.form['Name'] query="select top 1 Col1, Col...
-1
2016-07-20T05:03:26Z
[ "python", "html", "flask" ]
Redirect output to HTML using flask
38,469,729
<p>I am trying to connect to DB and show some data on webpage, below is what i tried:</p> <pre><code>import jaydebeapi import jpype import sys from flask import Flask from flask import request, render_template app = Flask(__name__) @app.route('/') def my_form(): return render_template('Name.html') @app.route('/'...
0
2016-07-19T22:48:30Z
38,492,580
<p>Based on the output of <code>print request.form</code>, your trouble is not in Flask, but in your form submission. Flask is a receiving a form with key-value pairs: <code>text:someName</code> and <code>my-form:Send</code>.</p> <p>(Flask will return a <code>400 Bad Request</code> error if you attempt to access a pro...
0
2016-07-20T23:45:10Z
[ "python", "html", "flask" ]
How to read data of url response into string array in python?
38,469,779
<p>I have a url and when I open the url in python using below code, </p> <pre><code>data = urllib.request.urlopen(url).read() print(data) </code></pre> <p>i get a data like this </p> <p>b'{"status": "success", "data": {"candles": [["2016-03-01T09:15:00+0530",1199,1243.35,1195,1232.9,150747],["2016-03-02T09:15:00+05...
-1
2016-07-19T22:53:18Z
38,469,826
<p>You probably just want to use <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a>:</p> <pre><code>import requests data = requests.get(url).json()['candles'] </code></pre>
0
2016-07-19T22:57:00Z
[ "python", "arrays" ]
How to read data of url response into string array in python?
38,469,779
<p>I have a url and when I open the url in python using below code, </p> <pre><code>data = urllib.request.urlopen(url).read() print(data) </code></pre> <p>i get a data like this </p> <p>b'{"status": "success", "data": {"candles": [["2016-03-01T09:15:00+0530",1199,1243.35,1195,1232.9,150747],["2016-03-02T09:15:00+05...
-1
2016-07-19T22:53:18Z
38,469,886
<p>The response looks like json, so load it up and manipulate the dict data as you want:</p> <pre><code>import json import urllib2 def process_data(data): ''' Process in the most efficient manner ''' pass data = json.loads(urllib2. urlopen(url)) if data['status'] == 'success': process_data(data['data']) ...
0
2016-07-19T23:01:36Z
[ "python", "arrays" ]
Modify .update function for dictionary
38,469,901
<p>I would like to know how can I modify the already existing .update function from dict.</p> <p>For example:</p> <pre><code>import __builtin__ def test(a): print a __builtin__.update = test </code></pre> <p>So when I'll use X.update again it will show a print saying the values.</p> <p>What I mean:</p> <pre>...
0
2016-07-19T23:03:22Z
38,469,955
<pre><code>class dict2(dict): def update(*args,**kwargs): print "Update:",args,kwargs dict.update(*args,**kwargs) d = dict2(a=5,b=6,c=7) d.update({'x':10}) </code></pre> <p>as im sure you noticed you cannot simply do <code>dict.update=some_other_fn</code> ... however there are ways of doing it if ...
0
2016-07-19T23:09:41Z
[ "python", "dictionary", "hook" ]
Modify .update function for dictionary
38,469,901
<p>I would like to know how can I modify the already existing .update function from dict.</p> <p>For example:</p> <pre><code>import __builtin__ def test(a): print a __builtin__.update = test </code></pre> <p>So when I'll use X.update again it will show a print saying the values.</p> <p>What I mean:</p> <pre>...
0
2016-07-19T23:03:22Z
38,470,070
<p>you could override the update method by subclassing <code>dict</code>.</p> <pre><code>from collections import Mapping class MyDict(dict): def update(self, other=None, **kwargs): if isinstance(other, Mapping): for k, v in other.items(): print(k, v) super().update...
0
2016-07-19T23:22:42Z
[ "python", "dictionary", "hook" ]
Vectorizing a multiplication and dict mapping on a Pandas DataFrame without iterating?
38,469,902
<p>I have a Pandas DataFrame, <code>df</code>:</p> <pre><code>import pandas as pd import numpy as np import math df = pd.DataFrame({'A':[1,2,2,4,np.nan],'B':[1,2,3,4,5]}) </code></pre> <p>and a dict, <code>mask</code>:</p> <pre><code>mask = {1:32,2:64,3:100,4:200} </code></pre> <p>I want my end result to be a Data...
2
2016-07-19T23:03:23Z
38,470,060
<p>Here is an option using <code>apply</code>, and the <code>get</code> method for dictionary which returns <code>None</code> if the key is not in the dictionary:</p> <pre><code>df['C'] = df.apply(lambda r: mask.get(r.A) if r.A == 1 else mask.get(r.A - 1), axis = 1) * df.B df # A B C #0 1 1 32 #1 2 ...
3
2016-07-19T23:21:52Z
[ "python", "loops", "pandas", "dataframe", "vectorization" ]
Vectorizing a multiplication and dict mapping on a Pandas DataFrame without iterating?
38,469,902
<p>I have a Pandas DataFrame, <code>df</code>:</p> <pre><code>import pandas as pd import numpy as np import math df = pd.DataFrame({'A':[1,2,2,4,np.nan],'B':[1,2,3,4,5]}) </code></pre> <p>and a dict, <code>mask</code>:</p> <pre><code>mask = {1:32,2:64,3:100,4:200} </code></pre> <p>I want my end result to be a Data...
2
2016-07-19T23:03:23Z
38,470,104
<p>This should work:</p> <pre><code>df['C'] = df.B * (df.A - (df.A != 1)).map(mask) </code></pre> <p><a href="http://i.stack.imgur.com/8CnVw.png" rel="nofollow"><img src="http://i.stack.imgur.com/8CnVw.png" alt="enter image description here"></a></p> <hr> <h3>Timing</h3> <p><strong>10,000 rows</strong></p> <pre><...
4
2016-07-19T23:26:51Z
[ "python", "loops", "pandas", "dataframe", "vectorization" ]
Mapping User Input to Text File List
38,469,930
<p>I'm trying to make a function that, given input from the User, can map input to a list of strings in a text file, and return some integer corresponding to the string in the file. Essentially, I check if what the user input is in the file and return the index of the matching string in the file. I have a working funct...
0
2016-07-19T23:06:42Z
38,470,037
<p>I would say to combine the files. You can have your words, and their corresponding values as follows:</p> <p><strong>words.txt</strong></p> <pre><code>string1|something here string2|something here </code></pre> <p>Then you can store each line as an entry to a dictionary and recall the value based on your input:</...
0
2016-07-19T23:19:34Z
[ "python", "function", "pseudocode" ]
Mapping User Input to Text File List
38,469,930
<p>I'm trying to make a function that, given input from the User, can map input to a list of strings in a text file, and return some integer corresponding to the string in the file. Essentially, I check if what the user input is in the file and return the index of the matching string in the file. I have a working funct...
0
2016-07-19T23:06:42Z
38,470,323
<blockquote> <p>I'm trying to make a function that, given input from the User, can map input to a list of strings in a text file, and return some integer corresponding to the string in the file. Essentially, I check if what the user input is in the file and return the index of the matching string in the file</p> </bl...
0
2016-07-19T23:54:51Z
[ "python", "function", "pseudocode" ]
share variable between classes and methods
38,469,952
<p>Im pretty new to OOP languages and I have a scenario where I want to share a variable between two classes that both have methods. In class One I have a function with a variable var1. I would like to make that variable available to my class Two, func2 however I'm not sure how to make this happen ? </p> <pre><cod...
-4
2016-07-19T23:09:29Z
38,470,035
<p>If one of the classes can actually be a sub-class of another class, you can use inheritance.</p> <pre><code>class One(object): def func1(self): var1 = 'foo' class Two(One): # func1 already exists here. # So does var1 </code></pre> <p>You can make the function accept arguments</p> <pre><code...
0
2016-07-19T23:19:11Z
[ "python", "python-2.7" ]
Python Simulation
38,470,055
<p>I am using the graphics.py library to generate a simulation of multiple balls falling from the top of the screen. The balls should 'bounce' off the bottom and then resume falling back down. The rate at which the ball falls is determined by its size.</p> <p>Currently the program generates and drops the balls with ap...
1
2016-07-19T23:21:08Z
38,470,306
<p><strong>This is an answer to the follow-up question regarding avoiding bubble overlaps:</strong></p> <p>Here is a half pseudo-code method for checking if a generated center and radius pair overlaps another bubble in the bubble list. Note that it is indeed pseudocode because I don't know python syntax very well. Als...
0
2016-07-19T23:52:55Z
[ "python", "graphics" ]