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
Why is non-greedy Python Regex not non-greedy enough?
38,148,043
<p>I've implemented non-greedy regex on a group of string URLs, where I'm trying to clean them up so that they end after the .com (.co.uk etc). Some of them continued with <code>'</code> or <code>"</code> or <code>&lt;</code> after the desired cutoff, and so I used <code>x = re.findall('([A-Za-z0-9]+@\S+.co\S*?)[\'"&l...
0
2016-07-01T14:33:28Z
38,148,290
<p>The issue with your regex is that you currently are only looking for Non-spaces(period)co instead of looking for Non-spaces(period)Non-spaces.</p> <p>So in this case you could get away with the following regex based on the information above.</p> <pre><code>&gt;&gt;&gt; finalSoup2 = """ ... misc@misc.misc'misc''mis...
2
2016-07-01T14:46:08Z
[ "python", "regex", "non-greedy" ]
How to calculate shortest paths between all pairs of nouns in a group with NLTK, WordNet, and similarity?
38,148,124
<p>I am trying to calculate shortest paths between all pairs of nouns in a group. I have many such groups of nouns with different group sizes. The biggest group contains about 250 nouns. The input is a txt file with nouns, each on a new line. The output as a txt file should list of all pairs of nouns with corresponding...
0
2016-07-01T14:38:23Z
38,151,226
<p>The following should do for you, I only provide the relevant parts. </p> <pre><code>from itertools import product for word1 in myList1: for word2 in myList2: list1 = wn.synsets(word1) list2 = wn.synsets(word2) sList = [ss1.path_similarity(ss2) for ss1, ss2 in product(list1, list2)] ...
3
2016-07-01T17:43:56Z
[ "python", "nlp", "nltk", "similarity", "wordnet" ]
star wars api => IndexError: list index out of range error
38,148,186
<p>I am working with a star wars API from <a href="http://swapi.co/api/" rel="nofollow">http://swapi.co/api/</a>. I can connect to it just fine and my project is coming along fine. However, I am running into the following error message: IndexError: list index out of range error. Looking at other stack overflow question...
1
2016-07-01T14:40:54Z
38,148,372
<p>Iterate through results you have using <code>foreach</code> loop like this:</p> <pre><code>for item in repo_dicts: if view == 'films': repo_dict = item['title'] print(str(num) + " " + repo_dict) elif view == 'starships': repo_dict = item['name'] print(str(num) + " " + repo_di...
3
2016-07-01T14:50:21Z
[ "python", "list", "api", "off-by-one" ]
Trying to inherit from unittest.TestCase and another class
38,148,323
<p>I have a base class (which inherits <em>only</em> from <code>object</code>) with common tests for a set of sorting algorithms. Now, for each specific algorithm, I would like to create a test class which inherits both from <code>unittest.TestCase</code> and this class with common tests for all sorting algorithms.</p>...
0
2016-07-01T14:47:44Z
38,148,842
<p>Looks like you have overridden addTest method in SortingAlgoTests class</p>
0
2016-07-01T15:16:02Z
[ "python", "unit-testing", "multiple-inheritance", "python-unittest" ]
Trying to inherit from unittest.TestCase and another class
38,148,323
<p>I have a base class (which inherits <em>only</em> from <code>object</code>) with common tests for a set of sorting algorithms. Now, for each specific algorithm, I would like to create a test class which inherits both from <code>unittest.TestCase</code> and this class with common tests for all sorting algorithms.</p>...
0
2016-07-01T14:47:44Z
38,148,845
<p>I managed to solve the problem by modifying my <code>TestBubbleSort</code> to:</p> <pre><code>class TestBubbleSort(unittest.TestCase, SortingAlgoTests): def __init__(self, methodName="runTest"): unittest.TestCase.__init__(self, methodName) SortingAlgoTests.__init__(self, bubble_sort, True) </co...
0
2016-07-01T15:16:09Z
[ "python", "unit-testing", "multiple-inheritance", "python-unittest" ]
TypeError - What does this error mean?
38,148,337
<p>So, i've been writing this program that takes a HTMl file, replaces some text and puts the return back into a different file in a different directory.</p> <p>This error happened.</p> <pre><code> Traceback (most recent call last): File "/Users/Glenn/jack/HTML_Task/src/HTML Rewriter.py", line 19, in &lt;mod...
1
2016-07-01T14:48:34Z
38,148,408
<p>try to change this:</p> <pre><code>with open ("2016-06-06_UK_BackToSchool.html", "wt") as out_file </code></pre> <p>on this:</p> <pre><code>with open ("2016-06-06_UK_BackToSchool.html", "w") as out_file: </code></pre> <p>or this:</p> <pre><code>with open ("2016-06-06_UK_BackToSchool.html", "wb") as out_file: </...
0
2016-07-01T14:52:35Z
[ "python", "file", "typeerror" ]
TypeError - What does this error mean?
38,148,337
<p>So, i've been writing this program that takes a HTMl file, replaces some text and puts the return back into a different file in a different directory.</p> <p>This error happened.</p> <pre><code> Traceback (most recent call last): File "/Users/Glenn/jack/HTML_Task/src/HTML Rewriter.py", line 19, in &lt;mod...
1
2016-07-01T14:48:34Z
38,148,525
<pre><code>with open (os.path.join("/Users/Glenn/jack/HTML_Task/src", out_file)): </code></pre> <p>Here <code>out_file</code> if <code>TextIOWrapper</code>, not string.</p> <p><code>os.path.join</code> takes string as arguments.</p> <hr> <ol> <li>Do not use keywords name as variable. <code>file</code> is keyword.<...
1
2016-07-01T14:58:27Z
[ "python", "file", "typeerror" ]
coloring matplotlib scatterplot by third variable with log color bar
38,148,362
<p>I'm trying to make a scatterplot of two arrays/lists, one of which is the x coordinate and the other the y. I'm not having any trouble with that. However, I need to color-code these points based on their values at a specific point in time, based on data which I have in a 2d array. Also, this 2d array of data has a v...
0
2016-07-01T14:49:46Z
38,150,527
<p>If I understand the question (which I'm not at all sure off) here is the answer:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt %matplotlib inline fig = plt.figure(1) time = 2 #I'd like to specify time here. x = [1, 2, 3, 4, 5] y = [5, 4, 3, 2, 1] multi_array = np.asarray([[1, 1, 10, 100, 100...
1
2016-07-01T16:57:24Z
[ "python", "multidimensional-array", "matplotlib", "colorbar" ]
coloring matplotlib scatterplot by third variable with log color bar
38,148,362
<p>I'm trying to make a scatterplot of two arrays/lists, one of which is the x coordinate and the other the y. I'm not having any trouble with that. However, I need to color-code these points based on their values at a specific point in time, based on data which I have in a 2d array. Also, this 2d array of data has a v...
0
2016-07-01T14:49:46Z
38,151,769
<p>After some tinkering, and using information learned from user4421975's answer and the link in the comments, I've puzzled it out. In short, I used plt.scatter's norm feature/attribute/thingie to mess with the colors and make them logarithmic.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt fig = p...
0
2016-07-01T18:21:57Z
[ "python", "multidimensional-array", "matplotlib", "colorbar" ]
Measuring the length of a list with len() gives wrong results
38,148,378
<p>Help! I don't understand this. When I try to measure the length of a list in python 2.7 with len() I get the wrong result. </p> <p>Here's the code:</p> <pre><code> if len(fields) &gt; 0: fields_split = [] for i in fields: i = i.split(',') fields_split.append(i) ...
-3
2016-07-01T14:50:39Z
38,148,457
<p>Based off your outputs</p> <pre><code>[u'name,description'] 1 [[u'name', u'description']] [u'name,description'] 1 ... </code></pre> <p>The <code>len()</code> function returns the correct output. For the second example above, <code>[[u'name', u'description']]</code> has length of 1 because it is a 2D list. The firs...
1
2016-07-01T14:55:13Z
[ "python" ]
Measuring the length of a list with len() gives wrong results
38,148,378
<p>Help! I don't understand this. When I try to measure the length of a list in python 2.7 with len() I get the wrong result. </p> <p>Here's the code:</p> <pre><code> if len(fields) &gt; 0: fields_split = [] for i in fields: i = i.split(',') fields_split.append(i) ...
-3
2016-07-01T14:50:39Z
38,148,459
<p>Per split string, you are <em>appending</em> the resulting list to <code>fields_split</code>. So <code>fields_split</code> will always have the exact same number of elements as <code>fields</code> has, each element a separate list object. Those separate list objects will each have 1 or more strings.</p> <p>If you w...
2
2016-07-01T14:55:29Z
[ "python" ]
Measuring the length of a list with len() gives wrong results
38,148,378
<p>Help! I don't understand this. When I try to measure the length of a list in python 2.7 with len() I get the wrong result. </p> <p>Here's the code:</p> <pre><code> if len(fields) &gt; 0: fields_split = [] for i in fields: i = i.split(',') fields_split.append(i) ...
-3
2016-07-01T14:50:39Z
38,148,552
<p>I think you want this..</p> <pre><code>fields=u'name,description' if len(fields) &gt; 0: fields_split = fields.split(',') reindz = len(fields_split) print fields print reindz print fields_split </code></pre> <p>Result:</p> <pre><code>name,description 2 [u'name', u'description'] </code></pre>
0
2016-07-01T14:59:39Z
[ "python" ]
constructing a Unicode string
38,148,445
<p>I'm trying to construct and print a Unicode string with Python 3.x. So, for example, the following works fine:</p> <pre><code>a = '\u0394' print(a) Δ </code></pre> <p>But if I try to construct this by appending two strings, I have several problems:</p> <pre><code>a = '\u' File "&lt;stdin&gt;", line 1 SyntaxErr...
0
2016-07-01T14:54:38Z
38,148,499
<p><code>\uhhhh</code> is an escape sequence, a <em>notation</em> used in string literals. You can't construct that notation from parts, at least not directly like that.</p> <p>Generally, you'd use the <a href="https://docs.python.org/3/library/functions.html#chr" rel="nofollow"><code>chr()</code> function</a> to prod...
2
2016-07-01T14:57:24Z
[ "python", "python-3.x", "python-unicode" ]
pip install libxml2 failed
38,148,460
<p>I'm new to python .Im trying to install libxml2 since I come to know this is dependency for lxml. Facing issues like:</p> <pre><code>Could not find dependencies </code></pre> <p>Any idea how to install libxml2?</p> <p>My python version is 3.5.2</p> <p>thanks in advance</p>
0
2016-07-01T14:55:30Z
38,148,662
<p><a href="http://lxml.de/installation.html" rel="nofollow">Official docs</a> have steps for installation for Linux, Mac OS and Windows.</p> <p>To install lxml on Ubuntu you first will need to install binary dependencies:</p> <pre><code>sudo apt-get install libxml2-dev libxslt-dev python-dev </code></pre> <p>Then y...
0
2016-07-01T15:05:53Z
[ "python", "python-3.x" ]
Algorithm for generating partitions of number
38,148,478
<p>My goal is to get all partitions of a given number S decomposed by predefined values so that the sum is less than S and greater than 0.8S. For example, S = 1000, and we want to decompose 1000 into a sum of type 17x + 20y + 150z, so that 17x + 20y + 150z is less than 1000 and greater than 800. </p> <p>I've come acr...
1
2016-07-01T14:56:21Z
38,148,674
<p>From what I understand, you don't want to generate actual partitions of <code>S</code>, because then this wouldn't make sense:</p> <blockquote> <p>For example, S = 1000, and we want to decompose 1000 into a sum of type 17x + 20y + 150z, so that 17x + 20y + 150z is less than 1000 </p> </blockquote> <p>If it's les...
1
2016-07-01T15:06:40Z
[ "python", "algorithm" ]
Algorithm for generating partitions of number
38,148,478
<p>My goal is to get all partitions of a given number S decomposed by predefined values so that the sum is less than S and greater than 0.8S. For example, S = 1000, and we want to decompose 1000 into a sum of type 17x + 20y + 150z, so that 17x + 20y + 150z is less than 1000 and greater than 800. </p> <p>I've come acr...
1
2016-07-01T14:56:21Z
38,149,093
<p>You don't need a full partition algorithm here. You can find the numbers you want with simple looping. If you have a fixed number of coefficients, as given in the question, then you can just use a few <code>for</code> loops. If the number of coefficients can vary, then you'll need a more sophisticated solution.</p> ...
3
2016-07-01T15:30:35Z
[ "python", "algorithm" ]
Algorithm for generating partitions of number
38,148,478
<p>My goal is to get all partitions of a given number S decomposed by predefined values so that the sum is less than S and greater than 0.8S. For example, S = 1000, and we want to decompose 1000 into a sum of type 17x + 20y + 150z, so that 17x + 20y + 150z is less than 1000 and greater than 800. </p> <p>I've come acr...
1
2016-07-01T14:56:21Z
38,154,709
<p>Here is a recursive approach that, given a lower bound, <code>a</code>, an upper bound, <code>b</code>, and a list of coefficients, <code>nums</code>, returns a list of vectors of nonnegative integers which when multiplied by the respective coefficients and then summed, returns an sum between <code>a</code> and <cod...
2
2016-07-01T22:42:55Z
[ "python", "algorithm" ]
Setting an image at center of figure using matplotlib Figure.figimage
38,148,511
<p>I'm trying to set an image, a watermark essentially, at the center of a matplotlib Figure. I would like the center of the image to be at the center of the figure. The problem appears to be a difference between the figure size and dpi of 10" x 10" and 960 x 960 pixels and the saved image which has pixel dimensions of...
1
2016-07-01T14:57:53Z
38,157,449
<p>In order to get a 960x960 pixel figure out of a 10"x10" plot you also have to set the <code>dpi</code> keyword in <code>plt.savefig()</code> to 96 dpi. With e.g.:</p> <pre><code>plt.savefig('im.png', dpi=96) </code></pre> <p>The output is correct:</p> <p><a href="http://i.stack.imgur.com/59kxNm.png" rel="nofollow...
1
2016-07-02T07:00:15Z
[ "python", "image", "matplotlib", "figure" ]
How download and install pyEDFlib library to Python 2.7 on Windows 8
38,148,530
<p>I use Python 2.7 through Anaconda. Me need pyEDFlib library. I tried to download the link, but I do not understand how to use GitHub in this case.</p> <p><a href="https://github.com/holgern/pyedflib" rel="nofollow">https://github.com/holgern/pyedflib</a></p>
0
2016-07-01T14:58:41Z
38,149,533
<p>In either your command prompt or a bash shell you should be able to run,</p> <pre><code>pip install pyEDFlib </code></pre> <p>If you dont have the command <code>pip</code> just run,</p> <pre><code>python get-pip.py </code></pre> <p>I just did it on my computer and it worked. Hope this helps.</p> <p>============...
0
2016-07-01T15:53:29Z
[ "python", "python-2.7", "anaconda" ]
Iterating through multidimensional lists?
38,148,547
<p>Sorry if obvious question, I'm a beginner and my google-fu has failed me.</p> <p>I am writing a tool that searches through text for alliteration. I have a multi-dimensional list: [[e,a,c,h], [w,o,r,d], [l,o,o,k,s], [l,i,k,e], [t,h,i,s]]</p> <p>What I want is to iterate through the items in the main list, checking ...
3
2016-07-01T14:59:28Z
38,148,683
<p>In a normal for-each loop like you have, you only get access to one element at a time:</p> <pre><code>for x in lst: print("I can only see", x) </code></pre> <p>So you need to iterate over the indexes instead, for example:</p> <pre><code>for i in range(len(lst) - 1): print("current =", lst[i], "next =", ls...
0
2016-07-01T15:07:11Z
[ "python", "list", "indexing" ]
Iterating through multidimensional lists?
38,148,547
<p>Sorry if obvious question, I'm a beginner and my google-fu has failed me.</p> <p>I am writing a tool that searches through text for alliteration. I have a multi-dimensional list: [[e,a,c,h], [w,o,r,d], [l,o,o,k,s], [l,i,k,e], [t,h,i,s]]</p> <p>What I want is to iterate through the items in the main list, checking ...
3
2016-07-01T14:59:28Z
38,148,745
<p>I think you want something like this:</p> <pre><code>def alit_finder(multi_level_list): l=len(multi_level_list) for i in xrange(l-1): if multi_level_list[i][0] == multi_level_list[i + 1][0]: print multi_level_list[i], multi_level_list[i + 1] li=[['e','a','c','h'], ['w','o','r','d'], ['l...
0
2016-07-01T15:10:54Z
[ "python", "list", "indexing" ]
Iterating through multidimensional lists?
38,148,547
<p>Sorry if obvious question, I'm a beginner and my google-fu has failed me.</p> <p>I am writing a tool that searches through text for alliteration. I have a multi-dimensional list: [[e,a,c,h], [w,o,r,d], [l,o,o,k,s], [l,i,k,e], [t,h,i,s]]</p> <p>What I want is to iterate through the items in the main list, checking ...
3
2016-07-01T14:59:28Z
38,148,754
<p>You could use i as the index and x as the element of an enumerated list:</p> <pre><code>def alit_finder(multi_level_list): for i, x in enumerate(multi_level_list): if i == len(multi_level_list) - 1: break # prevent index out of range error if x[0] == multi_level_list[i + 1][0] and x != multi_level_l...
0
2016-07-01T15:11:24Z
[ "python", "list", "indexing" ]
Iterating through multidimensional lists?
38,148,547
<p>Sorry if obvious question, I'm a beginner and my google-fu has failed me.</p> <p>I am writing a tool that searches through text for alliteration. I have a multi-dimensional list: [[e,a,c,h], [w,o,r,d], [l,o,o,k,s], [l,i,k,e], [t,h,i,s]]</p> <p>What I want is to iterate through the items in the main list, checking ...
3
2016-07-01T14:59:28Z
38,232,285
<p>something like this will work:</p> <pre><code>matching_indices = [i for i, (w1, w2) in enumerate(zip(multi_level_list, multi_level_list[1:])) if w1[0] == w2[0]] </code></pre>
0
2016-07-06T19:30:34Z
[ "python", "list", "indexing" ]
Using readline() no error detected but no responding
38,148,560
<p>I met a problem when I try to handle a large number of html files. For each html file, I need to use <code>readline()</code> to catch some specified information(Only first ten lines or twenty lines). At the beginning, everything looks good, but couple hours later, there will be no reaction. No error detected. When I...
0
2016-07-01T14:59:57Z
38,148,692
<p><a href="http://i.stack.imgur.com/tiUaJ.jpg" rel="nofollow">Here is the traceback information</a> Please check this picture. Thanks.</p>
1
2016-07-01T15:07:40Z
[ "python", "sockets", "buffer", "readline" ]
python setup installing outside of activated virtualenv
38,148,620
<p>I have a setup code in python using setuptools, and I have the python code to install in /usr/share/mypackage (owned by root), but I'm trying to install the package as a non-privileged user. So, I create a virtual environment (with <code>virtualenv</code>) in a directory <code>$ENVDIR</code> owned by the user. Then,...
2
2016-07-01T15:02:57Z
38,155,555
<p>You cannot install as a non-priviledged user into <code>/usr/share</code> any workaround would violate unix permissions. To be fair, you should never ever install anything in <code>/usr/share</code> by default. <code>/usr/share</code> is the OS/distro territory and shall be not meddled with when installing softwar...
1
2016-07-02T01:07:56Z
[ "python", "linux", "debian", "setuptools", "packaging" ]
How to find the difference between two lists that contain lists in Python?
38,148,671
<p>If we have </p> <pre><code>X1=[[a,b,c],[a,e,t],[a,b,c]] </code></pre> <p>and </p> <pre><code>X2=[[a,b,c]] </code></pre> <p>I want to find the difference between X1 and X2 which is:</p> <pre><code>X3=X1-X2=[[a,b,c],[a,e,t]]. </code></pre> <p>So my output should contain two lists not one as I only want to remo...
0
2016-07-01T15:06:32Z
38,148,712
<p>As the error states, lists are unhashable (because they're mutable). Convert your list of lists into a list of tuples, which are hashable:</p> <pre><code>&gt;&gt;&gt; hash((1, 2, 3)) 2528502973977326415 &gt;&gt;&gt; hash([1, 2, 3]) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt;...
0
2016-07-01T15:08:57Z
[ "python", "list" ]
How to find the difference between two lists that contain lists in Python?
38,148,671
<p>If we have </p> <pre><code>X1=[[a,b,c],[a,e,t],[a,b,c]] </code></pre> <p>and </p> <pre><code>X2=[[a,b,c]] </code></pre> <p>I want to find the difference between X1 and X2 which is:</p> <pre><code>X3=X1-X2=[[a,b,c],[a,e,t]]. </code></pre> <p>So my output should contain two lists not one as I only want to remo...
0
2016-07-01T15:06:32Z
38,148,765
<p>So, <code>X3 = [a,e,t]</code>, right?</p> <p>There is no need to convert it to set. You can do this:</p> <p><code>result = [x for x in X1 if x not in X2]</code>.</p>
4
2016-07-01T15:11:54Z
[ "python", "list" ]
How to find the difference between two lists that contain lists in Python?
38,148,671
<p>If we have </p> <pre><code>X1=[[a,b,c],[a,e,t],[a,b,c]] </code></pre> <p>and </p> <pre><code>X2=[[a,b,c]] </code></pre> <p>I want to find the difference between X1 and X2 which is:</p> <pre><code>X3=X1-X2=[[a,b,c],[a,e,t]]. </code></pre> <p>So my output should contain two lists not one as I only want to remo...
0
2016-07-01T15:06:32Z
38,148,797
<p>lists are <em>unhashable</em> so they cannot be members of a <code>set</code>. You can convert the inner lists into a <code>frozenset</code>, so two sublists with the same items but different ordering are still considered same and then use a <a href="https://docs.python.org/2/library/collections.html#collections.Cou...
1
2016-07-01T15:13:47Z
[ "python", "list" ]
Python index issue, looking for prettier code
38,148,685
<p>my current code is like below, I'm using try and except to pass the exception from list indexing, length of "text" could be less than 3 sometimes. I'm looking for a prettier way. Please let me know your idea, thanks.</p> <pre><code>for item in items: text = item.splitlines() try: name = text[0] except: ...
-1
2016-07-01T15:07:20Z
38,148,805
<p>Here is one method:</p> <pre><code>text = item.splitlines() name, tag, age = (text + [""] * 3)[:3] </code></pre>
3
2016-07-01T15:14:16Z
[ "python" ]
Python index issue, looking for prettier code
38,148,685
<p>my current code is like below, I'm using try and except to pass the exception from list indexing, length of "text" could be less than 3 sometimes. I'm looking for a prettier way. Please let me know your idea, thanks.</p> <pre><code>for item in items: text = item.splitlines() try: name = text[0] except: ...
-1
2016-07-01T15:07:20Z
38,148,903
<p><code>itertools</code> has <code>izip_longest()</code>:</p> <pre><code>keys = ['name', 'tag', 'age'] name, tag, age = (item[1] for item in izip_longest(keys, text, fillvalue="")) </code></pre> <p>Arguably, this is a lot more useful handy when you want a <code>dict</code>:</p> <pre><code>dict(izip_longest(keys, te...
0
2016-07-01T15:19:13Z
[ "python" ]
pandas: reindex panel with dataframe index
38,148,769
<p>I have a panel with the <code>Items</code> index being days.</p> <pre><code>&lt;class 'pandas.core.panel.Panel'&gt; Dimensions: 1260 (items) x 6 (major_axis) x 6 (minor_axis) Items axis: 2011-06-27 00:00:00 to 2016-06-28 00:00:00 Major_axis axis: BP to XOM Minor_axis axis: BP to XOM </code></pre> <p>Index:</p> <p...
3
2016-07-01T15:11:58Z
38,148,950
<p>The reindexing fails due to the time component so you can access just the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.date.html" rel="nofollow">date</a> component of your datetimeIndex</p> <pre><code>pnl2 = pnl.reindex(df.index.date) </code></pre>
1
2016-07-01T15:22:11Z
[ "python", "pandas" ]
Ctypes - Passing a Void Pointer from Python
38,148,810
<p>I am accessing a C++ DLL using Python Ctypes on Windows 7. I have the documentation for the DLL, but I can't actually open it. I'm trying to use a C++ function that takes in a function, which in turn takes in an unsigned int and a void pointer. Here is a short code sample that fails:</p> <pre><code>import ctypes im...
0
2016-07-01T15:14:31Z
38,233,840
<p>You need to declare the argument types of the functions you call using <code>argtypes</code>. Since I don't know your exact API, here's an example:</p> <p>Windows C DLL code with a callback:</p> <pre><code>typedef void (*CB)(int a); __declspec(dllexport) void do_callback(CB func) { int i; for(i=0;i&lt;10...
0
2016-07-06T21:11:59Z
[ "python", "c++", "ctypes", "access-violation", "void-pointers" ]
How do I change the symbolic variable (tf.Variable) in tensorflow?
38,148,860
<p>I have written my self a tensorflow class as below, but I met some problem when I am trying to set some weight to zero after training manually in function <code>refine_init_weight</code>. In this function, I tried setting all numbers to zero once it is below some value and see how would the accuracy rate change. The...
1
2016-07-01T15:16:53Z
38,153,593
<p><em>(I'll just repost my comment as an answer)</em></p> <p>You need to run the assign operation you created, otherwise it is just added to the graph and never executed. </p> <pre><code>assign_op = self.input_layer.w.assign(refined_w) self.sess.run(assign_op) </code></pre> <hr> <p>If you want to do this in Tensor...
1
2016-07-01T20:40:20Z
[ "python", "machine-learning", "tensorflow", "deep-learning" ]
How to remove the extra row (or column) after transpose() in Pandas
38,148,877
<p>After using transpose on a dataframe there is always an extra row as a remainder from the initial dataframe's index for example:</p> <pre><code>import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({'fruit':['apple','banana'],'number':[3,5]}) &gt;&gt;&gt; df fruit number 0 apple 3 1 banana 5 &gt;&...
2
2016-07-01T15:17:46Z
38,875,658
<p>Instead of removing the extra index, why don't try setting the new index that you want and then use slicing ?</p> <p>step 1: Set the new index you want: <code>df.columns = df.iloc[0]</code> step 2: Create a new dataframe removing extra row. <code>df_new = df[1:]</code></p>
0
2016-08-10T14:03:05Z
[ "python", "csv", "pandas", "transpose" ]
Difference two dataframes based on two columns Python Panda
38,148,892
<pre><code>Df1 A B C 1 1 'a' 2 3 'b' 3 4 'c' Df2 A B C 1 1 'k' 5 4 'e' </code></pre> <p>Expected output (after difference and merge of Df1 and Df2) i.e. Df1-Df2 and then merge </p> <pre><code>output A B C 1 1 'a' 2 3 'b' 3 4 'c' 5 4 'e' </code></pre> <p>The dif...
0
2016-07-01T15:18:44Z
38,149,065
<p>try this:</p> <pre><code>In [44]: df1.set_index(['A','B']).combine_first(df2.set_index(['A','B'])).reset_index() Out[44]: A B C 0 1 1 'a' 1 2 3 'b' 2 3 4 'c' 3 5 4 'e' </code></pre>
4
2016-07-01T15:28:40Z
[ "python", "pandas", "dataframe" ]
Difference two dataframes based on two columns Python Panda
38,148,892
<pre><code>Df1 A B C 1 1 'a' 2 3 'b' 3 4 'c' Df2 A B C 1 1 'k' 5 4 'e' </code></pre> <p>Expected output (after difference and merge of Df1 and Df2) i.e. Df1-Df2 and then merge </p> <pre><code>output A B C 1 1 'a' 2 3 'b' 3 4 'c' 5 4 'e' </code></pre> <p>The dif...
0
2016-07-01T15:18:44Z
38,149,125
<p>It's an outer join, then merging in column C from df2 if a value is not known in df1:</p> <pre><code>dfx = df1.merge(df2, how='outer', on=['A', 'B']) dfx['C'] = dfx.apply( lambda r: r.C_x if not pd.isnull(r.C_x) else r.C_y, axis=1) dfx[['A', 'B', 'C']] =&gt; A B C 0 1 1 a 1 2 3 b 2 3 4 c 3 5 4 ...
1
2016-07-01T15:32:25Z
[ "python", "pandas", "dataframe" ]
Difference two dataframes based on two columns Python Panda
38,148,892
<pre><code>Df1 A B C 1 1 'a' 2 3 'b' 3 4 'c' Df2 A B C 1 1 'k' 5 4 'e' </code></pre> <p>Expected output (after difference and merge of Df1 and Df2) i.e. Df1-Df2 and then merge </p> <pre><code>output A B C 1 1 'a' 2 3 'b' 3 4 'c' 5 4 'e' </code></pre> <p>The dif...
0
2016-07-01T15:18:44Z
38,149,132
<p>Using concat and drop_duplicates:</p> <pre><code>output = pd.concat([df1, df2]) output = output.drop_duplicates(subset = ["A", "B"], keep = 'first') </code></pre> <p><strong>* Desired df: *</strong></p> <pre><code> A B C 0 1 1 a 1 2 3 b 2 3 4 c 1 5 4 e </code></pre>
1
2016-07-01T15:32:52Z
[ "python", "pandas", "dataframe" ]
Are there any guarantees about the splitting order of str.split()?
38,148,952
<p>According to <a href="https://docs.python.org/2.7/library/stdtypes.html#str.split" rel="nofollow">the Python 2.7 docs</a>, using <code>str.split()</code> with <code>maxsplit</code> specified will split a string up to <code>maxsplit</code> times. </p> <p>However, it never explicitly specifies that these splits will ...
1
2016-07-01T15:22:19Z
38,149,276
<p>If you're looking for guarantees that splitting with the <code>maxsplit</code> argument splits from left-to-right, you only need to look at the builtin <a href="https://hg.python.org/cpython/file/tip/Lib/test/string_tests.py#l359" rel="nofollow">python test suite</a>. </p> <p>Here's an excerpt:</p> <pre><code> ...
3
2016-07-01T15:40:00Z
[ "python", "string", "python-2.7", "split", "documentation" ]
Are there any guarantees about the splitting order of str.split()?
38,148,952
<p>According to <a href="https://docs.python.org/2.7/library/stdtypes.html#str.split" rel="nofollow">the Python 2.7 docs</a>, using <code>str.split()</code> with <code>maxsplit</code> specified will split a string up to <code>maxsplit</code> times. </p> <p>However, it never explicitly specifies that these splits will ...
1
2016-07-01T15:22:19Z
38,149,425
<p>CPython is considered to be the reference implementation of Python. According to CPython source code <code>str.split</code> is guaranteed to split in left-to-right order. You can look up how <code>str.split</code> is implemented, here is a link <a href="http://svn.python.org/view/python/tags/r271/Objects/stringlib/s...
2
2016-07-01T15:47:57Z
[ "python", "string", "python-2.7", "split", "documentation" ]
SMTP AUTH extension not supported by server - Sending emails through a private host in Django
38,148,954
<p>I registered a domain and a private email using namecheap.com. I am trying to send an email from this private email. However, I get the error in the title.</p> <p>In my settings.py, I have these settings:</p> <pre><code>EMAIL_HOST = 'mail.privateemail.com' EMAIL_HOST_USER = 'contact@mysite.com' EMAIL_HOST_PASSWORD...
0
2016-07-01T15:22:28Z
38,156,264
<p>This is happening because you have conflicting settings:</p> <pre><code>EMAIL_PORT = 587 # Port 587 is reserved for TLS EMAIL_USE_TLS = False # But you have disabled TLS </code></pre> <p>You either need to set <code>EMAIL_USE_TLS</code> to <code>True</code> or use the default port for unencrypted connecti...
0
2016-07-02T03:43:05Z
[ "python", "django", "django-email" ]
SMTP AUTH extension not supported by server - Sending emails through a private host in Django
38,148,954
<p>I registered a domain and a private email using namecheap.com. I am trying to send an email from this private email. However, I get the error in the title.</p> <p>In my settings.py, I have these settings:</p> <pre><code>EMAIL_HOST = 'mail.privateemail.com' EMAIL_HOST_USER = 'contact@mysite.com' EMAIL_HOST_PASSWORD...
0
2016-07-01T15:22:28Z
39,791,201
<p>I was searching answer for this since 4 hours. I still dont know why this configuration works for me, but yes, IT WORKS for me.</p> <p>I simply removed,</p> <pre><code>EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' </code></pre> <p>from my settings.py, and add below configuration in settings.py</p>...
0
2016-09-30T12:08:41Z
[ "python", "django", "django-email" ]
(psuedo) Randomly generated Matrix
38,148,984
<p>I want to create a matrix using the following arrays:</p> <pre><code>A = [1111,2222,3333] B = [20,25,26,27] C = [1.5,2.6,3.7,4.5,5.4,6.7,7.2,8.8,9.0,10.0,11.0,12.2] </code></pre> <p>Each value in A need to be mapped to all values in be once (each element in A will be attached to all four values in b) and from ther...
-1
2016-07-01T15:24:19Z
38,149,099
<p>Have a look at :</p> <pre><code>weights_h = [[random.random() for e in inputs[0]] for e in range(hiden_neurons)] </code></pre> <p>But really, you should probably use numpy.</p> <pre><code>In [9]: numpy.random.random((3, 3)) Out[9]: array([[ 0.37052381, 0.03463207, 0.10669077], [ 0.05862909, 0.8515325 , ...
1
2016-07-01T15:30:56Z
[ "python", "python-2.7", "python-interactive" ]
(psuedo) Randomly generated Matrix
38,148,984
<p>I want to create a matrix using the following arrays:</p> <pre><code>A = [1111,2222,3333] B = [20,25,26,27] C = [1.5,2.6,3.7,4.5,5.4,6.7,7.2,8.8,9.0,10.0,11.0,12.2] </code></pre> <p>Each value in A need to be mapped to all values in be once (each element in A will be attached to all four values in b) and from ther...
-1
2016-07-01T15:24:19Z
38,149,284
<p>You may use the <code>itertools</code> package</p> <pre><code>import itertools A = [1111,2222,3333] B = [20,25,26,27] C = [1.5,2.6,3.7,4.5,5.4,6.7,7.2,8.8,9.0,10.0,11.0,12.2] # create the product of A and B, i.e., [(1111,20), (1111,25), ..., (3333,27)] AB = itertools.product(A,B) # zip with C ABC = itertools.izi...
0
2016-07-01T15:40:32Z
[ "python", "python-2.7", "python-interactive" ]
IPython FITS file plotting gives different results
38,149,015
<p>I am facing a problem while running a script ( please find the code below ).</p> <p>I am trying to plot an array of values, write it into a FITS file format, read it back again and plot it ---> I don't get the same plots!</p> <p>If you could please help me with this it would be great.</p> <p>The following are the...
0
2016-07-01T15:26:07Z
38,151,814
<p>Actually it turns out to be that it's to do with the version of matplotlib. </p> <p>Answered by a developer of matplotlib - Jens Nielsen</p> <p>This doesn't occur on matplotlib version 1.51</p> <p>In version 2 beta 1, it seems that the FITS data is converted from float32 to big endian float8. Please look at the f...
0
2016-07-01T18:24:46Z
[ "python", "matplotlib", "astropy" ]
Recursively calling a method inside a class in python
38,149,141
<pre><code>class Example(object): def doSomething(self, num): if(num &lt; 10 ) : //print the number else : //call doSomething() again </code></pre> <p>Here how do I call the <code>doSomething</code> method in the <code>else</code> condition inside the method?</p>
-2
2016-07-01T15:33:12Z
38,149,251
<p>Call it with <code>self.doSomething(num-1)</code>, because <code>doSomething</code> would refer to a global function rather than the one in the class. Also put the <code>print</code> before the <code>if</code> so that it prints the number regardless of what it is (so you can see the numbers decreasing) and put a <co...
1
2016-07-01T15:38:19Z
[ "python", "recursion" ]
Beautifulsoup save links to list
38,149,203
<p>I'm trying to retrieve links from some website and save it to the list for further use. What I got so far (it's my .txt file where I store the output):</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;a class="active" href="/review/huerco-s-those-you-who-have-never-and-also-those-w/"&gt;Huerco S.&lt;span&gt;&lt;i&gt;For Tho...
-1
2016-07-01T15:35:51Z
38,149,253
<p>Your error is happening because <code>a</code> is a <code>Tag</code>, and you're trying to access the <em>"<strong>Tag</strong>th"</em> element of results instead of <em>"<strong>i</strong>th"</em> element, where <strong><em>i</em></strong> is some integer index or slice. What you can do instead, is define the list ...
5
2016-07-01T15:38:23Z
[ "python", "beautifulsoup" ]
How to ignore deleted records using dbf-module in python?
38,149,255
<p>I'm using dbf-module by Ethan Furman version 0.96.005 (latest one) in Python 2.7 using old-fashioned FoxPro2.x-tables. Since I want to ignore deleted records, I set <code>tbl.use_deleted = False</code> after assigning <code>tbl = dbf.Table(dbf_path)</code>. I tried to set this before and after opening the table doin...
2
2016-07-01T15:38:29Z
38,149,842
<p><code>use_deleted</code> and <code>has_been_deleted</code> no longer exist, and have been replaced with the function <code>is_deleted</code>.</p> <p>So your choices at this point are (assuming a <code>from dbf import is_deleted</code>):</p> <pre><code># check each record for rec in tbl: if is_deleted(rec): ...
3
2016-07-01T16:11:22Z
[ "python", "foxpro", "dbf" ]
Run a curl tlsv1.2 http get request in python?
38,149,259
<p>I have the following command that I run using curl in linux.</p> <pre><code>curl --tlsv1.2 --cert ~/aws-iot/certs/certificate.pem.crt --key ~/aws-iot/certs/private.pem.key --cacert ~/aws-iot/certs/root-CA.crt -X GET https://data.iot.us-east-1.amazonaws.com:8443/things/pi_3/shadow </code></pre> <p>This command retu...
0
2016-07-01T15:38:53Z
38,150,904
<p>After playing around with it on my own I was able to successfully do it in python using the requests library.</p> <pre><code>import requests s = requests.Session() r = s.get('https://data.iot.us-east-1.amazonaws.com:8443/things/pi_3/shadow', cert=('/home/pi/aws-iot/certs/certificate.pem.crt', '/home/pi/aws-iot...
0
2016-07-01T17:22:13Z
[ "python", "json", "http", "curl", "tls1.2" ]
Delete column(s) from very large CSV file using pandas or blaze
38,149,288
<p>I have a very large csv file (5 GB), so I do not want to load the whole thing into memory, and I want to delete one or more of its columns. I tried using the following code in blaze, but all it did was append the resulting columns to the existing csv file:</p> <pre><code>from blaze import Data, odo d = Data("myfile...
2
2016-07-01T15:40:57Z
38,149,391
<p>i would do it this way:</p> <pre><code>cols2keep = ['col1','col3','col4','col6'] # columns you want to have in the resulting CSV file chunksize = 10**5 # you may want to adjust it ... for chunk in pd.read_csv(filename, chunksize=chunksize, usecols=cols2keep): chunk.to_csv('output.csv', mode='a', index=False) ...
2
2016-07-01T15:46:21Z
[ "python", "csv", "pandas", "blaze" ]
Delete column(s) from very large CSV file using pandas or blaze
38,149,288
<p>I have a very large csv file (5 GB), so I do not want to load the whole thing into memory, and I want to delete one or more of its columns. I tried using the following code in blaze, but all it did was append the resulting columns to the existing csv file:</p> <pre><code>from blaze import Data, odo d = Data("myfile...
2
2016-07-01T15:40:57Z
38,149,829
<p>I deal with Large csv files a lot. Here is my solution:</p> <pre><code>import csv fname_in = r'C:\mydir\myfile_in.csv' fname_out = r'C:\mydir\myfile_out.csv' inc_f = open(fname_in,'r') #open the file for reading csv_r = csv.reader(inc_f) # Attach the csv "lens" to the input stream - default is excel dialect out...
1
2016-07-01T16:10:49Z
[ "python", "csv", "pandas", "blaze" ]
Delete column(s) from very large CSV file using pandas or blaze
38,149,288
<p>I have a very large csv file (5 GB), so I do not want to load the whole thing into memory, and I want to delete one or more of its columns. I tried using the following code in blaze, but all it did was append the resulting columns to the existing csv file:</p> <pre><code>from blaze import Data, odo d = Data("myfile...
2
2016-07-01T15:40:57Z
38,150,142
<p>You can use <a href="http://dask.pydata.org/en/latest/dataframe.html" rel="nofollow"><code>dask.dataframe</code></a>, which is syntactically similar to pandas, but does manipulations out-of-core so memory shouldn't be an issue. It also parallelizes the process automatically, so it should be fast.</p> <pre><code>im...
3
2016-07-01T16:29:53Z
[ "python", "csv", "pandas", "blaze" ]
Setting current user for required model field
38,149,319
<p>I have a model where one of the required fields is the currently signed in user. I do the following when creating a new record for the model:</p> <p>views.py</p> <pre><code>def post(self, request): bound_form = self.form_class(request.POST) if bound_form.is_valid(): new_position = bound_form.save()...
0
2016-07-01T15:42:23Z
38,149,458
<p>You should use <code>exclude=('user',)</code> in <code>class Meta:</code> of your <code>form</code>. @Daniel Roseman is also right.</p>
2
2016-07-01T15:49:36Z
[ "python", "django" ]
mido on Python 3.5.1: No module named 'mido'
38,149,341
<p>I'm trying to use mido with Python 3.5.1. I have successfully installed it (it says "successfully installed mido-1.1.14" in command prompt) but when I tried to import it in python, it gives me the message "ImportError: No module named 'mido'". I understand that mido targets Python 2.7 and 3.2, but does it really not...
3
2016-07-01T15:44:04Z
38,149,378
<p>Installing a module for one python version does not install it for the others.</p> <p>If you're using pip, run something like <code>pip3 install mido</code>. <code>pip</code> defaults to installing for Python 2, so you'll need to explicitly call <code>pip3</code>.</p>
0
2016-07-01T15:45:58Z
[ "python", "midi", "python-3.5" ]
Manual set up colormap for color-bar Matplotlib
38,149,398
<p>I would like to create the following colormaps.</p> <pre><code>mycolorbar1 = [dark-violet light-green dark-red dark-blue] mycolorbar2 = [dark-brown dark-red] </code></pre> <p>then I can use them in the following part of my code.</p> <pre><code>plt.tricontourf(triang1, Z1,v1,cmap=mycolorbar1, norm=plt.Normalize...
0
2016-07-01T15:46:41Z
38,151,461
<p>While the post my comment links to answers your question, it is probably over-complicated. There is a much more straightforward approach shown by Joe Kington in <a href="http://stackoverflow.com/questions/24997926/making-a-custom-colormap-using-matplotlib-in-python?lq=1">this post</a> that uses <code>LinearSegmented...
1
2016-07-01T18:01:31Z
[ "python", "matplotlib", "contour", "colorbar", "colormap" ]
Python use variable in another class
38,149,401
<p>I am new in Python, and I would like to know: Is possible use one variable in another class? </p> <p>For example:</p> <pre><code>class Hello: def function_a(self): x = 1 class World: def function_b(self): print(x) a = Hello() b = World() a.function_a() b.function_b() </code></pre> <p...
0
2016-07-01T15:46:54Z
38,149,475
<p>If you don't want to pass in the variable, you need to make it <code>global</code>:</p> <pre><code>class Hello: def function_a(self): global x x = 1 class World: def function_b(self): global x print(x) a = Hello() b = World() </code></pre> <hr> <pre><code>&gt;&gt;&gt; x...
1
2016-07-01T15:50:34Z
[ "python", "python-3.x" ]
Python use variable in another class
38,149,401
<p>I am new in Python, and I would like to know: Is possible use one variable in another class? </p> <p>For example:</p> <pre><code>class Hello: def function_a(self): x = 1 class World: def function_b(self): print(x) a = Hello() b = World() a.function_a() b.function_b() </code></pre> <p...
0
2016-07-01T15:46:54Z
38,149,518
<p>As it is, that can't be done. The simple option is to make x global by adding a <code>global x</code> line to the beginning of each function that uses it. </p> <p>The best practice would be to avoid globals and pass around objects which hold the shared variables:</p> <pre><code>class Hello: def function_a(sel...
3
2016-07-01T15:52:42Z
[ "python", "python-3.x" ]
Python use variable in another class
38,149,401
<p>I am new in Python, and I would like to know: Is possible use one variable in another class? </p> <p>For example:</p> <pre><code>class Hello: def function_a(self): x = 1 class World: def function_b(self): print(x) a = Hello() b = World() a.function_a() b.function_b() </code></pre> <p...
0
2016-07-01T15:46:54Z
38,149,634
<p>Not in that way. Python, like most modern languages, has scopes. You could use globals, but don't get in the habit of that because they are almost always bad practice. </p> <p>This is the way I would do it.</p> <pre><code>class Hello: def __init__(self, shared): self.shared = shared def function_a...
1
2016-07-01T15:59:07Z
[ "python", "python-3.x" ]
Press Button When This Number Appears - iMacros
38,149,432
<p>I happen to make a iMacros script for one of my web job but I think its not working pretty well as I thought.</p> <p>I just want iMacros to Click/Press a particular button when a numbers appear in the web window. In the sense I just want the trade to "Sell At Market" price when it is in Profit percentage. For examp...
-3
2016-07-01T15:48:34Z
38,160,763
<p>Try to play the following macro in loop mode with a very big 'Max' value (e.g. 99999):</p> <pre><code>SET !ERRORIGNORE YES SET !TIMEOUT_STEP 1 SEARCH SOURCE=REGEXP:"(\(\+25\.\d\d%\))" EXTRACT=$1 SET butPos EVAL("('{{!EXTRACT}}' == '') ? '' : 1;") TAG POS={{butPos}} TYPE=BUTTON ATTR=ID:sell_at_market SET !ERRORIGNOR...
0
2016-07-02T13:35:38Z
[ "java", "c#", "python", "imacros" ]
How do I reliably split a string in Python?
38,149,470
<p>In Perl I can do:</p> <pre><code>my ($x, $y) = split /:/, $str; </code></pre> <p>And it will work whether or not the string contains the pattern.</p> <p>In Python, however this won't work:</p> <pre><code>a, b = "foo".split(":") # ValueError: not enough values to unpack </code></pre> <p>What's the canonical way...
69
2016-07-01T15:50:23Z
38,149,500
<p>If you're splitting into just two parts (like in your example) you can use <a href="https://docs.python.org/3.5/library/stdtypes.html#str.partition"><code>str.partition()</code></a> to get a guaranteed argument unpacking size of 3: </p> <pre><code>&gt;&gt;&gt; a, sep, b = "foo".partition(":") &gt;&gt;&gt; a, sep, b...
100
2016-07-01T15:52:02Z
[ "python", "string", "python-3.x", "split" ]
How do I reliably split a string in Python?
38,149,470
<p>In Perl I can do:</p> <pre><code>my ($x, $y) = split /:/, $str; </code></pre> <p>And it will work whether or not the string contains the pattern.</p> <p>In Python, however this won't work:</p> <pre><code>a, b = "foo".split(":") # ValueError: not enough values to unpack </code></pre> <p>What's the canonical way...
69
2016-07-01T15:50:23Z
38,149,677
<p>Since you are on Python 3, it is easy. PEP 3132 introduced a welcome simplification of the syntax when assigning to tuples - <em>Extended iterable unpacking</em>. In the past, if assigning to variables in a tuple, the number of items on the left of the assignment must be exactly equal to that on the right. </p> ...
56
2016-07-01T16:01:42Z
[ "python", "string", "python-3.x", "split" ]
How do I reliably split a string in Python?
38,149,470
<p>In Perl I can do:</p> <pre><code>my ($x, $y) = split /:/, $str; </code></pre> <p>And it will work whether or not the string contains the pattern.</p> <p>In Python, however this won't work:</p> <pre><code>a, b = "foo".split(":") # ValueError: not enough values to unpack </code></pre> <p>What's the canonical way...
69
2016-07-01T15:50:23Z
38,149,856
<p><code>split</code> will always return a list. <code>a, b = ...</code> will always expect list length to be two. You can use something like <code>l = string.split(':'); a = l[0]; ...</code>. </p> <p>Here is a one liner: <code>a, b = (string.split(':') + [None]*2)[:2]</code></p>
15
2016-07-01T16:12:12Z
[ "python", "string", "python-3.x", "split" ]
How do I reliably split a string in Python?
38,149,470
<p>In Perl I can do:</p> <pre><code>my ($x, $y) = split /:/, $str; </code></pre> <p>And it will work whether or not the string contains the pattern.</p> <p>In Python, however this won't work:</p> <pre><code>a, b = "foo".split(":") # ValueError: not enough values to unpack </code></pre> <p>What's the canonical way...
69
2016-07-01T15:50:23Z
38,150,707
<p>You are always free to catch the exception.</p> <p>For example:</p> <pre><code>some_string = "foo" try: a, b = some_string.split(":") except ValueError: a = some_string b = "" </code></pre> <p>If assigning the whole original string to <code>a</code> and an empty string to <code>b</code> is the desire...
21
2016-07-01T17:09:00Z
[ "python", "string", "python-3.x", "split" ]
How do I reliably split a string in Python?
38,149,470
<p>In Perl I can do:</p> <pre><code>my ($x, $y) = split /:/, $str; </code></pre> <p>And it will work whether or not the string contains the pattern.</p> <p>In Python, however this won't work:</p> <pre><code>a, b = "foo".split(":") # ValueError: not enough values to unpack </code></pre> <p>What's the canonical way...
69
2016-07-01T15:50:23Z
38,167,236
<p>how about using regular expressions:</p> <pre><code>import re string = 'one:two:three:four' </code></pre> <p>in 3.X:</p> <pre><code>a *b = re.split(':', string) </code></pre> <p>in 2.X:</p> <pre><code>a, b = re.split(':', string)[0], re.split(':', string)[1:] </code></pre> <p>this way you can also use regular...
3
2016-07-03T06:12:19Z
[ "python", "string", "python-3.x", "split" ]
Using ols function with parameters that contain numbers/spaces
38,149,482
<p>I am having a lot of difficulty using the statsmodels.formula.api function </p> <pre><code> ols(formula,data).fit().rsquared_adj </code></pre> <p>due to the nature of the names of my predictors. The predictors have numbers and spaces etc in them which it clearly doesn't like. I understand that I need to us...
2
2016-07-01T15:51:23Z
38,167,185
<p>Right now you're starting with a list of terms that you want in your formula, then trying to paste them together into a complicated string, which patsy will parse and convert back into a list of terms. You can see the data structure that patsy generates for this kind of formula (<code>ModelDesc.from_formula</code> i...
0
2016-07-03T06:04:56Z
[ "python", "list", "pandas", "charts", "patsy" ]
Is it possible to put JavaScript code into a JS file through Python?
38,149,602
<pre><code>with open("C:scripts/CUAppVersion.js", 'a') as file: file.write("if [CUID] = -1 then" "function GetCUID() { return 0; }" "else" "function GetCUID() { return [CUID] });") </code></pre> <p>That is my code and it succesfully puts the JS into the JS file but it puts it on one line rather than as I type...
0
2016-07-01T15:57:16Z
38,149,638
<p>Add <code>\n</code> to the end of every line.</p> <pre><code>with open("C:scripts/CUAppVersion.js", 'a') as file: file.write("if [CUID] = -1 then\n" "function GetCUID() { return 0; }\n" "else\n" "function GetCUID() { return [CUID] });\n") </code></pre>
0
2016-07-01T15:59:42Z
[ "javascript", "python", "file" ]
Is it possible to put JavaScript code into a JS file through Python?
38,149,602
<pre><code>with open("C:scripts/CUAppVersion.js", 'a') as file: file.write("if [CUID] = -1 then" "function GetCUID() { return 0; }" "else" "function GetCUID() { return [CUID] });") </code></pre> <p>That is my code and it succesfully puts the JS into the JS file but it puts it on one line rather than as I type...
0
2016-07-01T15:57:16Z
38,149,682
<p>What about adding some endlines <code>\n</code>?</p> <pre><code>with open("C:scripts/CUAppVersion.js", 'a') as file: file.write("if [CUID] = -1 then\n" "function GetCUID() { return 0; }\n" "else\n" "function GetCUID() { return [CUID] });\n") </code></pre>
0
2016-07-01T16:01:53Z
[ "javascript", "python", "file" ]
Is it possible to put JavaScript code into a JS file through Python?
38,149,602
<pre><code>with open("C:scripts/CUAppVersion.js", 'a') as file: file.write("if [CUID] = -1 then" "function GetCUID() { return 0; }" "else" "function GetCUID() { return [CUID] });") </code></pre> <p>That is my code and it succesfully puts the JS into the JS file but it puts it on one line rather than as I type...
0
2016-07-01T15:57:16Z
38,149,686
<p>Use multiline strings.</p> <pre><code>with open("C:/scripts/CUAppVersion.js", 'a') as file: file.write(""" if [CUID] = -1 then function GetCUID() { return 0; } else function GetCUID() { return [CUID] }); """.strip()) </code></pre>
1
2016-07-01T16:02:00Z
[ "javascript", "python", "file" ]
While loop terminal waiting
38,149,616
<p>i have a file named <code>test.py</code>.</p> <pre><code>test3 = 1000000000 test = 0 xtest = True def enable(): while xtest: test += 1 if test &gt; test3: test3 += test3 * 3 </code></pre> <p>And a file named <code>testit.py</code>.</p> <pre><code>import test test.enable() </code...
-1
2016-07-01T15:57:53Z
38,149,679
<p>I'm not sure what your question is but to me that looks like an infinite loop. xtest, which is the variable responsible for stopping the loop, is never set to False inside the loop.</p>
0
2016-07-01T16:01:47Z
[ "python", "while-loop" ]
While loop terminal waiting
38,149,616
<p>i have a file named <code>test.py</code>.</p> <pre><code>test3 = 1000000000 test = 0 xtest = True def enable(): while xtest: test += 1 if test &gt; test3: test3 += test3 * 3 </code></pre> <p>And a file named <code>testit.py</code>.</p> <pre><code>import test test.enable() </code...
-1
2016-07-01T15:57:53Z
38,149,835
<p>simple i want to run it in background sorry for my english is not good, if i want to enabled via shell what must to do ?</p> <pre><code>import cmd import operator import test class Ec(cmd.Cmd): prompt = "testshell$ " intro = "Welcome to the testshell shell, type `help` to get started." def do_test(s...
0
2016-07-01T16:11:02Z
[ "python", "while-loop" ]
What is a good explanation of how to read the histogram feature of TensorBoard?
38,149,622
<p>Question is simple, <strong>how do you read those graphs</strong>? I read their explanation and it doesn't make sense to me.</p> <p>I was reading TensorFlow's <a href="https://github.com/tensorflow/tensorflow/blob/r0.9/tensorflow/tensorboard/README.md">newly updated readme file for TensorBoard</a> and in it it trie...
13
2016-07-01T15:58:16Z
38,173,831
<p>The lines that they are talking about are described below: <a href="http://i.stack.imgur.com/ENhlR.png"><img src="http://i.stack.imgur.com/ENhlR.png" alt="enter image description here"></a></p> <p>as for the meaning of percentile, check out the <a href="https://en.wikipedia.org/wiki/Percentile">wikipedia article</a...
9
2016-07-03T19:58:09Z
[ "python", "machine-learning", "statistics", "tensorflow" ]
VIM: EOF error when python code requires input
38,149,646
<p>I did setup Vim on my OS X machine, but when I try to execute a code</p> <pre><code>x=input("which one you like? ") print(x) </code></pre> <p>I get an error:</p> <p><a href="http://i.stack.imgur.com/Sc2Hc.png" rel="nofollow"><img src="http://i.stack.imgur.com/Sc2Hc.png" alt=""></a></p> <p>I should mention that t...
1
2016-07-01T16:00:07Z
38,500,101
<p>If you do <code>:w !python</code>, the standard input is a temporary file or pipe with your code, which <code>python</code> naturally reads to the end in order to execute the script, hence it's EOF when it gets to <code>input()</code>, and input is not from a terminal.<br> To solve this problem, insert a line</p> <...
0
2016-07-21T09:22:03Z
[ "python", "vim" ]
Installing pip on Bluehost
38,149,726
<p>I have successfully installed python 2.7.11 on a shared Bluehost server.</p> <p>In the home directory I installed get-pip.py When I run that now,</p> <pre><code># python get-pip.py Requirement already up-to-date: pip in ./python/lib/python2.7/site-packages </code></pre> <p>But when I try to run pip I get,</p> <p...
2
2016-07-01T16:04:52Z
38,150,981
<p>You can run <code>pip</code> by invoking the <code>-m</code> option when you use <code>python</code> to run <code>pip</code>. Suppose you want to use <code>pip</code> to install a Python package called "package-of-interest" from PyPI. Then, you can install it by running:</p> <pre><code>python -m pip install package...
2
2016-07-01T17:27:01Z
[ "python", "install", "pip" ]
3D plot aspect ratio [matplotlib]
38,149,736
<p>I am using the code written <a href="http://stackoverflow.com/a/15583431/4888158">here</a> to make a plot like this one below. </p> <p>The problem is, that I want to adjust an aspect ratio, namely, to stretch it along the z-axis, so that all the stacked images are more or less visible. Is there an easy way of doing...
3
2016-07-01T16:05:43Z
38,150,151
<p>Have you tried stretching your canvas in the vertical direction? For instance,</p> <pre><code>plt.figure(figsize=(5,10)) </code></pre> <p>or something similar should give you more space. I am not sure, though, if that will solve your problem.</p>
0
2016-07-01T16:30:23Z
[ "python", "matplotlib", "plot" ]
3D plot aspect ratio [matplotlib]
38,149,736
<p>I am using the code written <a href="http://stackoverflow.com/a/15583431/4888158">here</a> to make a plot like this one below. </p> <p>The problem is, that I want to adjust an aspect ratio, namely, to stretch it along the z-axis, so that all the stacked images are more or less visible. Is there an easy way of doing...
3
2016-07-01T16:05:43Z
38,150,278
<p>Maybe you can try </p> <pre><code>plt.figure.subplots_adjust(bottom = 0.05) </code></pre> <p>This will makes your figure have more space along the Z-axis, I guess that's what you want.</p> <p>Or you want</p> <pre><code>ax.set_xlim(xmin,xmax) </code></pre>
0
2016-07-01T16:38:42Z
[ "python", "matplotlib", "plot" ]
3D plot aspect ratio [matplotlib]
38,149,736
<p>I am using the code written <a href="http://stackoverflow.com/a/15583431/4888158">here</a> to make a plot like this one below. </p> <p>The problem is, that I want to adjust an aspect ratio, namely, to stretch it along the z-axis, so that all the stacked images are more or less visible. Is there an easy way of doing...
3
2016-07-01T16:05:43Z
38,153,328
<p>Looks like there is <em>no</em> “proper” way to do it, but we can try monkey-patching our way around the problem. Here’s the best kludge I could do:</p> <pre><code>from mpl_toolkits.mplot3d import proj3d def make_get_proj(self, rx, ry, rz): ''' Return a variation on :func:`~mpl_toolkit.mplot2d.axes3d...
1
2016-07-01T20:16:48Z
[ "python", "matplotlib", "plot" ]
Count rows from excel using python
38,149,816
<p>I first read the table like this:</p> <pre><code>xls = pd.ExcelFile("data.xlsx",header = None) df = xls.parse('data', header=None) </code></pre> <p>Here is the result:</p> <pre><code> 0 1 2 3 4 5 6 0 291672 84885 1 1 0.03980 0 9 1 266227 77261 0 0 2.47720 1 0 2 ...
-1
2016-07-01T16:10:18Z
38,150,158
<p>Your question is a little unclear, and might be improved if you provide us with a reproducible example that shows what you tried. However, I think this might be what you want?</p> <pre><code>import pandas as pd data = {'foo':[5,2,2,4,4], 'bar':[5,2,1,1,1], 'baz':[.2,.3,.4,.5,.6], 'foo1'...
0
2016-07-01T16:30:32Z
[ "python" ]
Text interpreted as boolean
38,149,827
<p>I am using pandas with read_csv. It interprets strings as boolean if all values are either "true" or "false". How can I prevent this?</p> <p>My <code>data.csv</code> file content:</p> <pre><code>String1,String2 true,false true,false true,true </code></pre> <p>Code</p> <pre><code>import pandas df = pandas.read_cs...
1
2016-07-01T16:10:48Z
38,149,920
<p>You can pass the dtype parameter as object:</p> <pre><code>df = pd.read_csv("test.csv", dtype="O") </code></pre> <p>This will treat all columns as objects. If you want to apply this only to those particular columns, you can pass a dictionary:</p> <pre><code>df = pd.read_csv("test.csv", dtype={"String1": "O", "Str...
1
2016-07-01T16:16:25Z
[ "python", "python-3.x", "pandas" ]
How to properly use the in-memory transport for unit tests
38,149,888
<p>I'm trying to write some tests where I produce a message to a queue and see if the message gets correctly consumed and handled in the application.</p> <p>For that I'm playing around with the kombu library and especially the in-memory Transport implementation.</p> <p>Still I can't get it working, that the produced ...
0
2016-07-01T16:14:34Z
38,515,082
<p>You'll want to adapt this to the code you're trying to test, but the basic thing you are looking for is the amqp URI for the in-memory controller, which is 'memory://'. As a really simple example:</p> <pre><code>conn = kombu.Connection("memory://") queue = conn.SimpleQueue('myqueue') queue.put('test') msg = queue....
1
2016-07-21T22:02:31Z
[ "python", "kombu" ]
Iterating again, prime factors loop, python
38,149,955
<p>I recently made a function in python that will give me all the factors of any number you choose in python. I would like to modify it now to only show the prime factors. The function I have currently is:</p> <pre><code>def prime_factors(n): L = [] i = range(1, n+1) for x in i: if n % x == 0: L.append(x) ...
0
2016-07-01T16:18:42Z
38,150,089
<p>You can use simply a function that return True/False for prime numbers</p> <pre><code>import math def is_prime(n): if n % 2 == 0 and n &gt; 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2)) def prime_factors(n): L = [] i = range(1, n+1) for x in i: i...
0
2016-07-01T16:26:24Z
[ "python", "loops", "python-3.x", "primes" ]
increment integer in python
38,150,006
<p>I wrote a simple function to read a file line by line, do some calculation and store the results in another file. However, when I output <code>count</code> in my function, instead of 0, 1, 2, 3; it becomes 6.21263888889e-05, 0.000141933611111, etc. I'm wondering what is the reason. </p> <pre><code>def CumulativePer...
1
2016-07-01T16:21:53Z
38,150,343
<p>I don't know the specifics of your application, but I would send the data to a list, and then use Python's slice notation to select every 1000th data point. </p> <p>Try the following snippet.</p> <pre><code>data = range(100) every_tenth = data[::10] </code></pre> <p>Also, you can eliminate the need to explicitly ...
1
2016-07-01T16:42:58Z
[ "python", "integer" ]
Spark streaming and performing operations on streamed dictionaries
38,150,079
<p>Curiously I want as a check to see the number of k, v pairs in a series of dictionaries that I am streaming in, however I find that I do not seem to be able to do this.</p> <pre><code>lines = ssc.socketTextStream("127.0.0.1", 5006) json_format = lines.flatMap(lambda recieved: json.loads(recieved)) dict_format = js...
1
2016-07-01T16:25:47Z
40,047,377
<p>Spark expects that the function provided to <a href="http://spark.apache.org/docs/latest/api/python/pyspark.streaming.html#pyspark.streaming.DStream.flatMap" rel="nofollow"><code>flatMap</code></a> will return a traversable/iterable result (such as a list) for each element it processes from the source RDD/DStream. T...
0
2016-10-14T15:54:29Z
[ "python", "apache-spark", "spark-streaming" ]
For loop accessing two iteration positions in an array
38,150,094
<p>I have the following code:</p> <pre><code>someList = ['a', 'b', 'c', 'd', 'e', 'f'] for i,j in enumerate(someList) step 2: print('%s, %s' % (someList[i], someList[i+1])) </code></pre> <p>My question is, is there any way to simplify the iteration over the array in order to avoid the <code>enumerate</code> part...
0
2016-07-01T16:26:34Z
38,150,159
<pre><code>for x, y in zip(someList, someList[1:]): print x, y </code></pre> <p>Standard technique.</p>
5
2016-07-01T16:30:35Z
[ "python", "arrays", "loops", "for-loop" ]
For loop accessing two iteration positions in an array
38,150,094
<p>I have the following code:</p> <pre><code>someList = ['a', 'b', 'c', 'd', 'e', 'f'] for i,j in enumerate(someList) step 2: print('%s, %s' % (someList[i], someList[i+1])) </code></pre> <p>My question is, is there any way to simplify the iteration over the array in order to avoid the <code>enumerate</code> part...
0
2016-07-01T16:26:34Z
38,155,036
<p>You can create two iterators, call next on the second and then zip which avoids the need to copy the list elements by slicing:</p> <pre><code>someList = ['a', 'b', 'c', 'd', 'e', 'f'] it1, it2 = iter(someList), iter(someList) next(it2) for a,b in zip(it1, it2): print(a, b) </code></pre>
1
2016-07-01T23:34:42Z
[ "python", "arrays", "loops", "for-loop" ]
How can I prevent an api call to a port on my machine from logging me out of my django app?
38,150,106
<p>I have a pair of django apps. One runs an api on one port (8001) and the other app runs a website (port 8000) where angularJS on the page consumes that api generated by the other app. There are reasons I've set it up this way. </p> <p>The apps don't share a user model. </p> <p>When I log in to the website and go t...
0
2016-07-01T16:27:00Z
38,150,165
<p>Make api server to use DRF <a href="http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication" rel="nofollow">token based authentication</a>.</p> <p>And to disable the Auth and SessionAuth middleware on a per view basis you will have to write custom middleware or decorator.</p>
0
2016-07-01T16:31:02Z
[ "python", "angularjs", "django" ]
How to align column of QTableView
38,150,196
<p>I have this code:</p> <pre><code>class ManifestModel(QtSql.QSqlTableModel): def __init__(self, parent=None, db=QtSql.QSqlDatabase()): super(ManifestModel, self).__init__(parent, db) def flags(self, index): if (index.column() == 4): return QtCore.Qt.ItemIsEnabled elif (in...
0
2016-07-01T16:32:27Z
38,152,227
<p>The aligment is handled in the <code>data()</code> method of the model. So try something like:</p> <pre><code>class ManifestModel(QtSql.QSqlTableModel): def data(self, index, role=QtCore.Qt.DisplayRole): if role == QtCore.Qt.TextAlignmentRole and index.column() == 3: return QtCore.Qt.Align...
1
2016-07-01T18:52:40Z
[ "python", "pyqt", "alignment", "pyqt5", "qtableview" ]
Set value of a row in a Pandas dataframe equal to that of a row in a different dataframe
38,150,251
<p>I have two dataframes, both have the same amount of columns and contain text data. The problem is that the data in the second dataframe is missing details:</p> <pre><code> A B 1 Bob Hoskins 2 Laura Hogan 3 Tom Jones A B 1 Bob x 2 Bob x 3 Bob x 4 Laura x 5 Laura...
2
2016-07-01T16:36:40Z
38,150,310
<p>Perform a left <code>join</code> on the second df:</p> <pre><code>output = df2.merge(df1, how = "left", on = "A") </code></pre> <p><strong>* desired df: *</strong></p> <pre><code> A B 0 Bob Hoskins 1 Bob Hoskins 2 Bob Hoskins 3 Laura Hogan 4 Laura Hogan 5 Tom Jones </code></...
3
2016-07-01T16:41:07Z
[ "python", "pandas" ]
Set value of a row in a Pandas dataframe equal to that of a row in a different dataframe
38,150,251
<p>I have two dataframes, both have the same amount of columns and contain text data. The problem is that the data in the second dataframe is missing details:</p> <pre><code> A B 1 Bob Hoskins 2 Laura Hogan 3 Tom Jones A B 1 Bob x 2 Bob x 3 Bob x 4 Laura x 5 Laura...
2
2016-07-01T16:36:40Z
38,150,320
<p>You can set <code>A</code> as index for the first data frame and then filter rows based on the index:</p> <pre><code>df.set_index('A').loc[df1.A].reset_index() # A B # 0 Bob Hoskins # 1 Bob Hoskins # 2 Bob Hoskins # 3 Laura Hogan # 4 Laura Hogan # 5 Tom Jones </code></pre>
2
2016-07-01T16:41:58Z
[ "python", "pandas" ]
How to return only the values that exist?
38,150,264
<p>I am parsing #data1 and #data2 from a ton of files. Some files don't have both though so when I return data1,data2 it results in: </p> <pre><code>UnboundLocalError: local variable 'data2' referenced before assignment </code></pre> <p>I've looked several other questions and I thought something like try/except looke...
1
2016-07-01T16:37:21Z
38,150,281
<p><code>data1</code> and <code>data2</code> are only defined depending on what your line starts with. If your line never started with <code>'#data2'</code>, <code>data2</code> never got defined.</p> <p>You can just initialize them both to be <code>None</code>s to get rid of your error:</p> <pre><code>def parse_file(...
3
2016-07-01T16:38:53Z
[ "python", "return" ]
Python input interpreter
38,150,289
<pre><code>test = input( '&gt; ').strip() if test == 'PRINT' : print( test ) else : print('FAILURE') </code></pre> <p>How do I get my mini interpreter to say HELLO WORLD if I type PRINT 'HELLO WORLD'</p>
-2
2016-07-01T16:39:30Z
38,150,475
<p>Try this:</p> <pre><code>test = input('&gt; ') command, _, args = test.partition(' ') if test else (None, None, None) if command == 'PRINT': print(args[1:-1]) else: print('FAILURE') </code></pre> <p>Running this and entering <code>PRINT 'HELLO WORLD'</code> will result in your shell printing out <code>'HEL...
0
2016-07-01T16:53:57Z
[ "python", "python-3.x" ]
Python input interpreter
38,150,289
<pre><code>test = input( '&gt; ').strip() if test == 'PRINT' : print( test ) else : print('FAILURE') </code></pre> <p>How do I get my mini interpreter to say HELLO WORLD if I type PRINT 'HELLO WORLD'</p>
-2
2016-07-01T16:39:30Z
38,150,478
<p>I think you want the <strong>split</strong> method of strings. You give it a dividing character; you get back a list of the divided strings. For instance,</p> <pre><code>divide = test.split("'") # Single quotation mark is the divider </code></pre> <p>Gives you the list</p> <pre><code>["PRINT ", "HELLO WORLD"] ...
0
2016-07-01T16:54:09Z
[ "python", "python-3.x" ]
How can I initialize a python threaded socketserver with another class?
38,150,308
<p>I am writing a python irc bot, and I would like to add a tcp server so the bot can echo messages sent to it in irc channels. I am using the python socketserver module so that it supports both linux and freebsd (I use both). I have a short testing script here:</p> <pre><code>#! /usr/bin/env python3 # -*- coding: utf...
0
2016-07-01T16:40:56Z
38,151,123
<p>Inside <code>TCPinput</code>, you are calling <code>serve_forever</code> within the main thread of control, causing it to block. Instead, you need to run the server within a separate thread. You can achieve this by deriving <code>TCPinput</code> from <code>threading.Thread</code>, setting <code>serve_forever</code> ...
1
2016-07-01T17:36:40Z
[ "python", "python-3.x" ]
Spark SQL "No input paths specified in jobs" when create DataFrame based on JSON file
38,150,311
<p>I am a beginner in Spark and I am trying to create a DataFrame based on the content of JSON file using PySpark by following the guide: <a href="http://spark.apache.org/docs/1.6.1/sql-programming-guide.html#overview" rel="nofollow">http://spark.apache.org/docs/1.6.1/sql-programming-guide.html#overview</a></p> <p>How...
0
2016-07-01T16:41:07Z
38,150,604
<p>If you are running your code on local mode then provide complete path of your file.<br> Suppose your file location is "/user/ABC/examples/src/main/resources/people.json". Then your code should be like this.</p> <pre><code>df =sqlContext.read.json("/user/ABC/examples/src/main/resources/people.json") </code></pre> <...
0
2016-07-01T17:02:17Z
[ "python", "json" ]
Spark SQL "No input paths specified in jobs" when create DataFrame based on JSON file
38,150,311
<p>I am a beginner in Spark and I am trying to create a DataFrame based on the content of JSON file using PySpark by following the guide: <a href="http://spark.apache.org/docs/1.6.1/sql-programming-guide.html#overview" rel="nofollow">http://spark.apache.org/docs/1.6.1/sql-programming-guide.html#overview</a></p> <p>How...
0
2016-07-01T16:41:07Z
39,789,349
<p>try to add file:// at the beginning of your absolute path: df = sqlContext.read.json("file:///user/ABC/examples/src/main/resources/people.json")</p>
0
2016-09-30T10:27:33Z
[ "python", "json" ]
Issue with Python new_word issue
38,150,317
<p>Don't see what I'm doing wrong here. </p> <p>On a new line after where you created the first variable:</p> <p>Create a new variable called new_word and set it equal to the concatenation of word, first, and pyg.</p> <p>Set new_word equal to the slice from the 1st index all the way to the end of new_word. Use <code...
1
2016-07-01T16:41:39Z
38,150,505
<p>Here is the solution :</p> <pre><code>pyg = 'ay' original = raw_input('Enter a word:') if len(original) &gt; 0 and original.isalpha(): print original else: print 'empty' word = original.lower() first = word[0] new_word = word + first + pyg newer_word = new_word[1:len(new_word)] """ u were forgett...
0
2016-07-01T16:56:01Z
[ "python" ]
Python - SkLearn Imputer usage
38,150,330
<p>I have the following question: I have a pandas dataframe, in which missing values are marked by the string <code>na</code>. I want to run an Imputer on it to replace the missing values with the mean in the column. According to the sklearn documentation, the parameter <code>missing_values</code> should help me with t...
2
2016-07-01T16:42:19Z
38,151,421
<p>Since you say you want to replace these <code>'na'</code> by a the mean of the column, I'm guessing the non-missing values are indeed floats. The problem is that pandas does not recognize the string <code>'na'</code> as a missing value, and so reads the column with dtype <code>object</code> instead of some flavor of...
0
2016-07-01T17:58:25Z
[ "python", "scikit-learn", "imputation" ]
Plotly python how to draw unbounded lines and spans?
38,150,362
<p>I am using plotly (the offline version) within an IPython notebook and I like it a lot. However I couldn't find a way to plot a vertical line or a vertical band.</p> <p>The equivalents in matplotlib are:</p> <pre><code>import matplotlib.plyplot as plt plt.axvline(x=0) plt.axvspan(xmin=0, xmax=1) </code></pre> <p>...
1
2016-07-01T16:45:07Z
38,598,450
<p>I'm just starting out with plotly myself, and so far I haven't found a good way to do this. But if you only need one horizontal or vertical line, the code below seems to be a workable hack, The idea is to use the default grid, but only plot a single grid line at the desired height. Include the following in your lay...
0
2016-07-26T19:34:15Z
[ "python", "plotly" ]
Plotly python how to draw unbounded lines and spans?
38,150,362
<p>I am using plotly (the offline version) within an IPython notebook and I like it a lot. However I couldn't find a way to plot a vertical line or a vertical band.</p> <p>The equivalents in matplotlib are:</p> <pre><code>import matplotlib.plyplot as plt plt.axvline(x=0) plt.axvspan(xmin=0, xmax=1) </code></pre> <p>...
1
2016-07-01T16:45:07Z
39,987,353
<p>I would use the 'shapes' option in the layout. For example, to get a vertical line at x = 6:</p> <pre><code>layout = {'title' : 'example', 'shapes' : [{'type' : 'line', 'x0' : 6, 'x1' : 6, 'y0' : 0, 'y1' : 10, 'width' : 1}]} </code></pre> <p>You could change...
0
2016-10-11T21:51:28Z
[ "python", "plotly" ]
Tornado Coroutine - Custom function
38,150,372
<p>I'm in the process of understanding coroutine from Tornado so let's keep everything simple and the more code you paste, the better.</p> <p>What I want is to make my homemade function async.</p> <p>All examples I could find in the documentation falls under the same "hidden" part: AsyncHTTPClient. I'm not looking to...
1
2016-07-01T16:46:02Z
38,151,497
<p>I've asked a similar question here: <a href="http://stackoverflow.com/questions/32148713/python-tornado-confused-how-to-convert-a-blocking-function-into-a-non-blocking">Python Tornado - Confused how to convert a blocking function into a non-blocking function</a></p> <p>The issue is that your function might be CPU b...
3
2016-07-01T18:03:46Z
[ "python", "asynchronous", "tornado" ]
Can't pickle <type 'cv2.BRISK'>: attribute lookup cv2.BRISK failed
38,150,402
<p>I'm trying to run multiple <a href="http://www.gnebehay.com/cmt/" rel="nofollow">CMT trackers</a> simultaneously. For that reason, I'm setting a Pool of threads:</p> <pre><code>import argparse import cv2 from multiprocessing import Pool import numpy as np import os import sys import time import VARtracker import u...
3
2016-07-01T16:47:40Z
38,509,409
<p>Try this code segment around your classes (this is not my code, credit to Steven Bethard) - this is a workaround to pickle classes; pickle is used by the multiprocessing module to send jobs to workers:</p> <pre><code>def _pickle_method(method): func_name = method.im_func.__name__ obj = method.im_self cl...
2
2016-07-21T16:18:35Z
[ "python", "multithreading", "opencv" ]
Can't pickle <type 'cv2.BRISK'>: attribute lookup cv2.BRISK failed
38,150,402
<p>I'm trying to run multiple <a href="http://www.gnebehay.com/cmt/" rel="nofollow">CMT trackers</a> simultaneously. For that reason, I'm setting a Pool of threads:</p> <pre><code>import argparse import cv2 from multiprocessing import Pool import numpy as np import os import sys import time import VARtracker import u...
3
2016-07-01T16:47:40Z
38,617,715
<p>I managed to solve it. Thanks to @Matt and @Yamaneko. Basically, I moved the block that reads the image into the worker function. Therefore, if the <em>pool size = 6</em> and there are six bounding boxes, each frame is going to be read six times (within each worker). That's the only way I have found to make it work....
2
2016-07-27T15:45:43Z
[ "python", "multithreading", "opencv" ]