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
Call python script from vba with wsh
39,356,710
<p>I need to call a python script from vba which works fine by using the shell.</p> <pre><code>Sub CallPythonScript() Call Shell("C:\Program Files (x86)\Python27\python.exe C:\Users\Markus\BrowseDirectory.py") End Sub </code></pre> <p>But when I try using wsh (because of the wait funcionality) it just won't...
2
2016-09-06T19:46:29Z
39,357,131
<p>The interpreter cannot possibly distinguish directories containing spaces from real arguments unless you protect the directories with quotes.</p> <p>A workaround, which is actually a better solution, relies on the fact that Python associates <code>.py</code> extension with the installed python interpreter.</p> <p>...
1
2016-09-06T20:15:10Z
[ "python", "vba", "excel-vba", "wsh" ]
Organize a list of unique integers and create ranges/summaries when possible
39,356,754
<p>I am trying to setup a function or a class to store unique integers with abilities to add,remove or check for existence. This of course can be easily achieved using normal set. The tricky part here is displaying of ranges. I mean, if I have all the numbers between 100 and 20000 I don't want to display a huge list al...
0
2016-09-06T19:49:16Z
39,358,148
<p>As people in the comments say, most of your operations are simple list operation. However, if your data contains ranges (e.g. 3008-3015), it then becomes a different story. The reason is that you need some sort of decoding to what that range means. I wrote a simple code using only functions (no classes) that will do...
1
2016-09-06T21:30:06Z
[ "python", "integer", "set" ]
Organize a list of unique integers and create ranges/summaries when possible
39,356,754
<p>I am trying to setup a function or a class to store unique integers with abilities to add,remove or check for existence. This of course can be easily achieved using normal set. The tricky part here is displaying of ranges. I mean, if I have all the numbers between 100 and 20000 I don't want to display a huge list al...
0
2016-09-06T19:49:16Z
39,358,657
<p>Since you did not specify what you mean by formatting, I'm assuming you mean sorting a list of numbers based upon their value in ascending order. Also, I modified your list and removed the dashes between certain numbers.</p> <p>With that being said, what I believe you're asking for is the <code>sorted()</code> func...
0
2016-09-06T22:16:57Z
[ "python", "integer", "set" ]
Organize a list of unique integers and create ranges/summaries when possible
39,356,754
<p>I am trying to setup a function or a class to store unique integers with abilities to add,remove or check for existence. This of course can be easily achieved using normal set. The tricky part here is displaying of ranges. I mean, if I have all the numbers between 100 and 20000 I don't want to display a huge list al...
0
2016-09-06T19:49:16Z
39,430,955
<p>Okay, first of all - thanks everyone for your efforts. Much appreciated.</p> <p>Here is the solution I ended up with. I have simply used a class to extend a set &amp; modifying the output of it.</p> <pre><code>class vlans(set): def check(self,number): if number in self: return True def __str__(self...
0
2016-09-10T21:56:18Z
[ "python", "integer", "set" ]
pythonic way to return object based on parameter type
39,356,761
<p>I have a simple class that can operate on a variety of base classes (strings, list, file... handed to it in Python3.x and return the same type. For now, I am using <code>isinstance</code> for type checking though have read all the admonishments of doing so.</p> <p>My question is what is the pythonic way of writing ...
2
2016-09-06T19:49:55Z
39,356,803
<p>Rather than checking the actual <em>type</em> of the object, you should check the <em>behavior</em> of the object.</p> <p>What I mean by that is rather than</p> <pre><code>isinstance(foo, str) or isinstance(foo, list) or ... </code></pre> <p>You are more interested in whether it is a sequence, meaning it has defi...
2
2016-09-06T19:52:38Z
[ "python" ]
Python - Selenium AttributeError: list object has no attribute find_element_by_xpath
39,356,818
<p>I am attempting to perform some scraping of nutritional data from a website, and everything seems to be going swimmingly so far, until I run into pages that are formatted slightly different. </p> <p>Using selenium and a line like this, returns an empty list:</p> <pre><code>values = browser.find_elements_by_class_n...
2
2016-09-06T19:53:43Z
39,358,595
<p>Actually <code>find_elements()</code> returns either list of <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement" rel="nofollow"><code>WebElement</code></a> or empty list. You're storing this result into a list variable name <code>data</code>.</p> <blockquote> <p>At...
1
2016-09-06T22:10:44Z
[ "python", "selenium", "web-scraping" ]
how to get the elapsed time while interacting with other functions in a text-based application in python
39,356,838
<p>So I created this project that records football (soccer) stats. Up to now it records only corner and free kicks but I want to record the possession time between the 2 teams. My main problem is that when I try to keep possession time, the other functions won't work. Here's what I've tried:</p> <pre><code>import time...
0
2016-09-06T19:55:01Z
39,357,768
<p>Given that (as you said in comments) that code is called repeatedly in loops, you have two issues.</p> <ul> <li><code>elapsed_home</code> is being set in the <code>'away_team'</code> branch instead of the <code>'home_team'</code> branch. Simple enough to fix, just move that up a few lines.</li> <li>All of your vari...
1
2016-09-06T21:00:34Z
[ "python", "input", "output", "text-based" ]
how to get the elapsed time while interacting with other functions in a text-based application in python
39,356,838
<p>So I created this project that records football (soccer) stats. Up to now it records only corner and free kicks but I want to record the possession time between the 2 teams. My main problem is that when I try to keep possession time, the other functions won't work. Here's what I've tried:</p> <pre><code>import time...
0
2016-09-06T19:55:01Z
39,359,110
<p>Check this one</p> <pre><code>elapsed_home = 0 elapsed_away = 0 start_home = 0 start_away = 0 ball_home = False ball_away = True # Assumimg that away team has the starting kick def body(): global elapsed_home, elapsed_away, start_home, start_away, ball_home, ball_away while True: choice = input("")...
1
2016-09-06T23:16:24Z
[ "python", "input", "output", "text-based" ]
Find nth least value in multiple numpy arrays
39,356,887
<p>In numpy, I can find which 2D array is the least of all 3 2D arrays as follows:</p> <pre><code>mat_a = np.random.random((5, 5)) mat_b = np.random.random((5, 5)) mat_c = np.random.random((5, 5)) bigmat = np.stack((mat_a, mat_b, mat_c)) # this is a 3, 5, 5 array minima = np.argmin(bigmat, axis=0) # contains a 5x5 arr...
0
2016-09-06T19:57:45Z
39,357,337
<p>I'll bet <code>np.argsort()</code> is the most efficient way.</p> <p>FYI, here's an interesting thing you can do with array indexing that will also solve your problem (though less efficiently):</p> <pre><code>max_value = np.max(bigmat) maskmat = np.array([minima == i for i in xrange(bigmat.shape[0])]) bigmat[maskm...
0
2016-09-06T20:28:26Z
[ "python", "numpy" ]
How to catch error from QtMultimedia in Python?
39,356,904
<p>I created application in PyQt + QtMultimedia that plays videos. When QtMultimedia can not find backend for playing videos (on Linux it's Gstreamer) it shows this error in terminal:</p> <p><code>defaultServiceProvider::requestService(): no service found for - "org.qt-project.qt.mediaplayer"</code></p> <p>However Py...
0
2016-09-06T19:58:50Z
39,370,873
<p>The warning is probably shown using <code>qWarning()</code>, so you should be able to use <a href="http://doc.qt.io/qt-5/qtglobal.html#qInstallMessageHandler" rel="nofollow"><code>qInstallMessageHandler</code></a> (part of <code>PyQt5.QtCore</code> in PyQt) to catch them.</p>
0
2016-09-07T13:12:00Z
[ "python", "qt", "pyqt" ]
How to catch error from QtMultimedia in Python?
39,356,904
<p>I created application in PyQt + QtMultimedia that plays videos. When QtMultimedia can not find backend for playing videos (on Linux it's Gstreamer) it shows this error in terminal:</p> <p><code>defaultServiceProvider::requestService(): no service found for - "org.qt-project.qt.mediaplayer"</code></p> <p>However Py...
0
2016-09-06T19:58:50Z
39,610,484
<p>Take a look at <a href="http://doc.qt.io/qt-5/qmediaplayer.html#mediaStatusChanged" rel="nofollow">the docs</a>.</p> <p>The problem you describle should be emitting the signal:</p> <pre><code>QMediaPlayer::mediaStatusChanged(QMediaPlayer::MediaStatus status) </code></pre> <p>where status = QMediaPlayer::ServiceMi...
0
2016-09-21T07:48:37Z
[ "python", "qt", "pyqt" ]
I have no idea why the score is keep increasing when the Sprite object is destroyed?
39,357,006
<p>I am now trying to make a mini game that making a user to dodge all falling pizzas from the sky. However, after a pizza touches the bottom of the graphic screen, the score of user keep increases infinitely, and I have no idea why is it happening. Please help me to fix this problem.</p> <pre><code>from livewires imp...
0
2016-09-06T20:05:15Z
39,357,790
<p>Instances are removed by the garbage collector as soon as there are no more references to it, so there still must be a reference to it... here;</p> <pre><code>pizza = Pizza(x = self.pizza_x, top = 0) # pizza is still referring to it! games.screen.add(pizza) </code></pre> <p>Try placing 'pizza = None' under the 'ga...
1
2016-09-06T21:02:20Z
[ "python", "object", "sprite" ]
NUMPY Implementation of AES significantly slower than pure python
39,357,146
<p>I am looking at re-implementing the SlowAES code (<a href="http://anh.cs.luc.edu/331/code/aes.py" rel="nofollow">http://anh.cs.luc.edu/331/code/aes.py</a>) to try and take advantage of the native array support of numpy. I'm getting what, to me, is the counter-intuitive result that the pure Python of SlowAES is much...
2
2016-09-06T20:16:17Z
39,357,537
<p>The simple answer is that there's a lot of overhead in creating arrays. So operations on small lists usually are faster than equivalent ones on arrays. That's especially true if the array version is iterative like the list one. For large arrays, operations using compiled methods, will be faster.</p> <p>These 4 '...
1
2016-09-06T20:43:28Z
[ "python", "numpy", "aes" ]
Python: match lists in two lists of lists
39,357,414
<p>I have two lists of lists. The first is composed of lists formatted as follows:</p> <pre><code>listInA = [id, a1, a2, a3] </code></pre> <p>The second is composed of lists formatted similarly, with the id first:</p> <pre><code>listInB = [id, b1, b2, b3] </code></pre> <p>Neither list is sorted, and they are not of...
0
2016-09-06T18:21:20Z
39,357,532
<p>You can create a dictionary using dict comprehension from the second list of lists from ID to list. Then, create your new list using list comprehension, appending the list based on IDs.</p> <pre><code>listA = [ [1, 'a', 'b', 'c'], [2, 'd', 'e', 'f'], ] listB = [ [2, 'u', 'v', 'w'], [1, 'x', 'y', 'z'...
3
2016-09-06T20:43:05Z
[ "python", "join", "list" ]
Python: match lists in two lists of lists
39,357,414
<p>I have two lists of lists. The first is composed of lists formatted as follows:</p> <pre><code>listInA = [id, a1, a2, a3] </code></pre> <p>The second is composed of lists formatted similarly, with the id first:</p> <pre><code>listInB = [id, b1, b2, b3] </code></pre> <p>Neither list is sorted, and they are not of...
0
2016-09-06T18:21:20Z
39,357,607
<p>The fact that the lists are not sorted and are not of equal length increases the difficulty of coming up with an efficient solution to the problem. However, a quick and dirty solution that would work in the end is definitely still feasible.</p> <p>The ID seems to be first in both lists. Since this is the case, then...
0
2016-09-06T20:49:12Z
[ "python", "join", "list" ]
How to create a file in a folder
39,357,516
<p>How can i create a <code>.pck</code> file in a folder in Python? The name of the folder is example I tried:</p> <pre><code>file = open("\example\file.pck","wb") </code></pre> <p>But it says: </p> <blockquote> <p>OSError: [Errno 22] Invalid argument: '\example\x0cile.pck'</p> </blockquote> <p>EDIT: Solved! The ...
-1
2016-09-06T20:41:53Z
39,357,538
<p>Use forward slashes</p> <pre><code>open("/example/file.pck", "wb") </code></pre> <p>Your problem is likely that backslashes were being interpreted as <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="nofollow">escape sequences</a>. </p>
3
2016-09-06T20:43:32Z
[ "python" ]
How to create a file in a folder
39,357,516
<p>How can i create a <code>.pck</code> file in a folder in Python? The name of the folder is example I tried:</p> <pre><code>file = open("\example\file.pck","wb") </code></pre> <p>But it says: </p> <blockquote> <p>OSError: [Errno 22] Invalid argument: '\example\x0cile.pck'</p> </blockquote> <p>EDIT: Solved! The ...
-1
2016-09-06T20:41:53Z
39,357,636
<p>You need to use forward slashes and also it seems that the <code>example</code> folder you trying to access doesn't exist. That's probably because you wanted to enter relative address but you entered an absolute one. So it should be:</p> <p><code>open("example/file.pck", "wb")</code></p>
0
2016-09-06T20:50:31Z
[ "python" ]
How to create a file in a folder
39,357,516
<p>How can i create a <code>.pck</code> file in a folder in Python? The name of the folder is example I tried:</p> <pre><code>file = open("\example\file.pck","wb") </code></pre> <p>But it says: </p> <blockquote> <p>OSError: [Errno 22] Invalid argument: '\example\x0cile.pck'</p> </blockquote> <p>EDIT: Solved! The ...
-1
2016-09-06T20:41:53Z
39,357,666
<p>Paths can be tricky, especially if you want to run your code on Unix-based and Windows systems. You can avoid many problems by using <code>os.path</code> which generates paths that will work on any os. </p> <p>To open a new file use the 'w+' option instead of 'rw'.</p> <p>In your case:</p> <pre><code>import os fi...
0
2016-09-06T20:52:51Z
[ "python" ]
Python create dictionary type variable out of row items in wxListCtrl
39,357,571
<p>in my wxPython app I have a wxListCtrl which I populate with some data. Is there a way I can then use the ListCtrl row items to create a dictionary variable</p> <p>say my list control has 4 rows in it with columns:- Rush(y/n), Subject, ReceivedDateTime</p> <p>I want to create a dictionary variable like below:-</p>...
0
2016-09-06T20:46:25Z
39,383,151
<p>Just loop through the rows, and retrieve the data as in:</p> <pre><code>def get_dict(self): data = {} count = self.list_ctrl.GetItemCount() for row in range(count): data[row + 1] = tuple([self.list_ctrl.GetItem(itemId=row, col=c).GetText() for c in range(3)]) return data </code></pre>
0
2016-09-08T05:26:05Z
[ "python", "dictionary", "wxpython", "listctrl" ]
HOG Descriptor using Python + OpenCV
39,357,574
<p>I am trying to implement HOG Descriptor with OpenCV to detect Pedestrians in a <a href="https://www.youtube.com/watch?v=p_GKeQvlFlA" rel="nofollow">video</a>. I am currently using the pre-made dataset by OpenCV <code>hogcascade_pedestrians.xml</code>. Unfortuntley the documentation on this part is very poor on the i...
0
2016-09-06T20:46:42Z
39,387,128
<pre><code>HOGCascade = cv2.HOGDescriptor() </code></pre> <p>If you want to use this <code>.xml</code>, You have lots of preparation work to do. </p> <p>When u finally get the available descriptor, you should replace the <code>cv2.HOGDescriptor_getDefaultPeopleDetector()</code> in <code>setSVMDetector(cv2.HOGDescript...
0
2016-09-08T09:21:29Z
[ "python", "python-2.7", "opencv", "image-processing", "opencv3.1" ]
Import vs import on circular import?
39,357,737
<p>I read <a href="http://stackoverflow.com/questions/7336802/how-to-avoid-circular-imports-in-python/37126790#37126790">this post</a> about how to prevent circular import in python. I don't understand a claim in the post: </p> <pre><code>import package.a # Absolute import and import a # Implicit relative import (dep...
1
2016-09-06T20:58:32Z
39,475,551
<p>After some search, I figure out the answer myself.</p> <p>Essentially, circular import is a problem for <code>from … import …</code> because it returns the imported module only after the module code is executed.</p> <p>To illustrate, assume we have import a in b.py and import b in a.py. For <code>import a</cod...
0
2016-09-13T17:11:59Z
[ "python", "python-2.7", "import" ]
Replace cell value in pandas dataframe where value is 'NaN' with value from another/same dataframe
39,357,828
<p>The following pandas dataframe df1 was generated:</p> <pre><code>df1 = pd.DataFrame(data = {'Value': [1.989920, 'NaN', -9.363819, 'NaN'], 'Group-Index' : [6, 6, 7, 7], 'Group-Order' : [2, 2, 2, 2], 'Index' : [221, 225, 222, 222] }) Value Group-Index Group-Order Index 221 1.989920 6...
2
2016-09-06T21:05:18Z
39,357,939
<pre><code>vnull = df1.Value.isnull() mrg_cols = ['Group-Index', 'Group-Order'] df1.loc[vnull, 'Value'] = df2.merge(df1.loc[vnull, mrg_cols]).Value.values df1 </code></pre> <p><a href="http://i.stack.imgur.com/mKHHX.png" rel="nofollow"><img src="http://i.stack.imgur.com/mKHHX.png" alt="enter image description here"><...
2
2016-09-06T21:13:48Z
[ "python", "pandas" ]
Get file name before downloading
39,357,863
<p>I'm trying to build a scraper in python and only want to download new episodes of a podcast. The problem is that I don't know what the file names will be until after the file is downloaded. Is there a way to get the file name before downloading?</p> <p><code>def download(path, fileName): if(not os.path.exists(f...
-2
2016-09-06T21:07:52Z
39,358,010
<p>I'm guessing that url to podcast redirects you to another url. Then you can use <code>requests</code> to get the final url</p> <pre><code>import requests final_url = requests.head(url_to_podcast, allow_redirects=True).url </code></pre> <p>and then get the filename from the final url</p> <pre><code>filename = fina...
-2
2016-09-06T21:19:32Z
[ "python", "beautifulsoup", "wget" ]
Pandas DENSE RANK
39,357,882
<p>I'm dealing with pandas dataframe and have a frame like this:</p> <pre><code>Year Value 2012 10 2013 20 2013 25 2014 30 </code></pre> <p>I want to make an equialent to DENSE_RANK () over (order by year) function. to make an additional column like this:</p> <pre><code> Year Value Rank 2012 10 1 ...
3
2016-09-06T21:09:18Z
39,357,944
<p>You can convert the year to categoricals and then take their codes (adding one because they are zero indexed and you wanted the initial value to start with one per your example).</p> <pre><code>df['Rank'] = df.Year.astype('category').cat.codes + 1 &gt;&gt;&gt; df Year Value Rank 0 2012 10 1 1 2013 ...
2
2016-09-06T21:14:05Z
[ "python", "sql", "pandas" ]
Pandas DENSE RANK
39,357,882
<p>I'm dealing with pandas dataframe and have a frame like this:</p> <pre><code>Year Value 2012 10 2013 20 2013 25 2014 30 </code></pre> <p>I want to make an equialent to DENSE_RANK () over (order by year) function. to make an additional column like this:</p> <pre><code> Year Value Rank 2012 10 1 ...
3
2016-09-06T21:09:18Z
39,358,100
<p>Use <code>pd.Series.rank</code> with <code>method='dense'</code></p> <pre><code>df['Rank'] = df.Year.rank(method='dense').astype(int) df </code></pre> <p><a href="http://i.stack.imgur.com/67n7I.png" rel="nofollow"><img src="http://i.stack.imgur.com/67n7I.png" alt="enter image description here"></a></p>
3
2016-09-06T21:26:19Z
[ "python", "sql", "pandas" ]
Pandas DENSE RANK
39,357,882
<p>I'm dealing with pandas dataframe and have a frame like this:</p> <pre><code>Year Value 2012 10 2013 20 2013 25 2014 30 </code></pre> <p>I want to make an equialent to DENSE_RANK () over (order by year) function. to make an additional column like this:</p> <pre><code> Year Value Rank 2012 10 1 ...
3
2016-09-06T21:09:18Z
39,368,586
<p>The fastest solution is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html" rel="nofollow"><code>factorize</code></a>:</p> <pre><code>df['Rank'] = pd.factorize(df.Year)[0] + 1 </code></pre> <p><strong>Timings</strong>:</p> <pre><code>#len(df)=40k df = pd.concat([df]*10000).reset_...
0
2016-09-07T11:23:35Z
[ "python", "sql", "pandas" ]
Performance comparison between type casting procedures
39,357,888
<p>I am reading lines from a file and want to convert them to a integer list.The file has one million lines.So,I was just wondering which procedure will make it faster.say, <code>lst=['10','12','31','41','15']</code> is the current line which has been read from the file. I can do the casting using map function,like- <c...
-1
2016-09-06T21:09:47Z
39,358,036
<p><code>[int(x, 10) for x in lst]</code> is at least significantly faster than your two ways:</p> <pre><code>&gt;&gt;&gt; from timeit import timeit &gt;&gt;&gt; setup = "lst = ['10','12','31','41','15']" &gt;&gt;&gt; timeit('map(int, lst)', setup) 4.454881024529442 &gt;&gt;&gt; timeit('[int(x) for x in lst]', setup...
0
2016-09-06T21:21:39Z
[ "python", "casting" ]
Read CSV file and only keep some lines according to values in list (Python)
39,358,016
<p>I will reformulate the problem I had previously stated:</p> <p>I am currently trying to only read about 26 million rows from a file that has about 600 million. I currently have a list with those 26 million rows that I am interested. </p> <p>My solution is as follows:</p> <pre><code>## list_ is a list of indices w...
-6
2016-09-06T21:20:14Z
39,358,121
<p>If you only want to check whether a value is in that list, the best time is O(1) for each check. You probably want to use hashset instead of a list. You can google hashset in python to see some example, like <a href="http://stackoverflow.com/questions/26724002/contains-of-hashsetinteger-in-python">this</a> or see th...
0
2016-09-06T21:28:26Z
[ "python" ]
Inserting a stop statement
39,358,022
<p>How can I get this program to stop at when the number <strong>13</strong> is entered?</p> <pre><code>print "\t:-- Enter a Multiplication --: \n" x = ("Enter the first number: ") y = ("Enter your second number to multiply by: ") for total in range(1, 12): x = input("Enter...
-2
2016-09-06T21:20:39Z
39,358,597
<p>If I understand what you are trying to do here, I think an if statement would be a better solution. Something like this:</p> <pre><code>print("Enter a multiplication") x = int(input("Enter a number: ")) y = int(input("Multiplied by this: ")) def multiply(x, y): if 1 &lt; x &lt; 13 and 1 &lt; y &lt; 13: ...
0
2016-09-06T22:10:51Z
[ "python" ]
Inserting a stop statement
39,358,022
<p>How can I get this program to stop at when the number <strong>13</strong> is entered?</p> <pre><code>print "\t:-- Enter a Multiplication --: \n" x = ("Enter the first number: ") y = ("Enter your second number to multiply by: ") for total in range(1, 12): x = input("Enter...
-2
2016-09-06T21:20:39Z
39,401,248
<p>You used a <strong>for</strong> loop; this is appropriate when you know <em>before you enter the loop</em> how many times you want to execute it. This is not the problem you have. Instead, use a <strong>while</strong> loop; this keeps going until a particular condition occurs.</p> <p>Try something like this:</p> ...
0
2016-09-08T22:44:35Z
[ "python" ]
python - different encoding results by setting the "encoding" parameter in diff. functions
39,358,024
<p>I have a function like </p> <pre><code>f = open('workfile', 'r', encoding='utf-8') df = pandas.read_csv(...) </code></pre> <p>, which opens a csv file. When I tried to set the <code>encoding</code> parameter to <code>read_csv</code> function, I got other encoding results, than by setting the parameter to <code>ope...
0
2016-09-06T21:20:42Z
39,358,856
<p>This is what happens in your program</p> <pre><code>f = open('workfile', 'r', encoding='utf-8') # 1 df = pandas.read_csv(f, encoding=e) # 2 </code></pre> <p>(1) The file is told to decode bytes using the encoding 'utf-8'. If you print the representation of the file handle f it will show something like </p> <pre><...
0
2016-09-06T22:44:15Z
[ "python", "pandas", "character-encoding" ]
Range as dictionary key in Python
39,358,092
<p>So, I had an idea that I could use a range of numbers as a key for a single value in a dictionary.</p> <p>I wrote the code bellow, but I cannot get it to work. Is it even possible?</p> <pre><code> stealth_roll = randint(1, 20) # select from a dictionary of 4 responses using one of four ranges. ## not w...
8
2016-09-06T21:25:26Z
39,358,118
<p>Yes, you can, only if you convert your <code>range</code> lists as immutable <code>tuple</code>, so they are hashable and accepted as keys of your dictionary:</p> <pre><code>stealth_check = { tuple(range(1, 6)) : 'You are about as stealthy as thunderstorm.', </code></pre> <p>EDIT: actually it works...
3
2016-09-06T21:28:15Z
[ "python", "dictionary", "range" ]
Range as dictionary key in Python
39,358,092
<p>So, I had an idea that I could use a range of numbers as a key for a single value in a dictionary.</p> <p>I wrote the code bellow, but I cannot get it to work. Is it even possible?</p> <pre><code> stealth_roll = randint(1, 20) # select from a dictionary of 4 responses using one of four ranges. ## not w...
8
2016-09-06T21:25:26Z
39,358,140
<p>It is possible on Python 3 — and on Python 2 if you use <code>xrange</code> instead of <code>range</code>:</p> <pre><code>stealth_check = { xrange(1, 6) : 'You are about as stealthy as thunderstorm.', #... } </code></pre> <p>However, the way you're trying to use it it won't work. ...
5
2016-09-06T21:29:43Z
[ "python", "dictionary", "range" ]
Range as dictionary key in Python
39,358,092
<p>So, I had an idea that I could use a range of numbers as a key for a single value in a dictionary.</p> <p>I wrote the code bellow, but I cannot get it to work. Is it even possible?</p> <pre><code> stealth_roll = randint(1, 20) # select from a dictionary of 4 responses using one of four ranges. ## not w...
8
2016-09-06T21:25:26Z
39,358,170
<pre><code>stealth_check = { 0 : 'You are about as stealthy as thunderstorm.', 1 : 'You tip-toe through the crowd of walkers, while loudly calling them names.', 2 : 'You are quiet, and deliberate, but still you smell.', 3 : 'You move like a...
1
2016-09-06T21:33:19Z
[ "python", "dictionary", "range" ]
Range as dictionary key in Python
39,358,092
<p>So, I had an idea that I could use a range of numbers as a key for a single value in a dictionary.</p> <p>I wrote the code bellow, but I cannot get it to work. Is it even possible?</p> <pre><code> stealth_roll = randint(1, 20) # select from a dictionary of 4 responses using one of four ranges. ## not w...
8
2016-09-06T21:25:26Z
39,358,345
<p>You can't build a dictionary directly from a range, unless you want the range itself to be the key. I don't think you want that. To get individual entries for each possibility within the range:</p> <pre><code>stealth_check = dict( [(n, 'You are about as stealthy as thunderstorm.') ...
2
2016-09-06T21:48:15Z
[ "python", "dictionary", "range" ]
Range as dictionary key in Python
39,358,092
<p>So, I had an idea that I could use a range of numbers as a key for a single value in a dictionary.</p> <p>I wrote the code bellow, but I cannot get it to work. Is it even possible?</p> <pre><code> stealth_roll = randint(1, 20) # select from a dictionary of 4 responses using one of four ranges. ## not w...
8
2016-09-06T21:25:26Z
39,358,354
<p>This approach will accomplish what you want, and the last line will work (assumes Py3 behavior of <code>range</code> and <code>print</code>):</p> <pre><code>def extend_dict(d, value, x): for a in x: d[a] = value stealth_roll = randint(1, 20) # select from a dictionary of 4 responses using one of four r...
2
2016-09-06T21:48:52Z
[ "python", "dictionary", "range" ]
Range as dictionary key in Python
39,358,092
<p>So, I had an idea that I could use a range of numbers as a key for a single value in a dictionary.</p> <p>I wrote the code bellow, but I cannot get it to work. Is it even possible?</p> <pre><code> stealth_roll = randint(1, 20) # select from a dictionary of 4 responses using one of four ranges. ## not w...
8
2016-09-06T21:25:26Z
39,430,659
<p>The following is probably maximally efficient in mapping a randint to one of a set of fixed category strings with fixed probability.</p> <pre><code>from random import randint stealth_map = (None, 0,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2,3,3,3,3) stealth_type = ( 'You are about as stealthy as thunderstorm.', 'You tip...
0
2016-09-10T21:19:21Z
[ "python", "dictionary", "range" ]
Range as dictionary key in Python
39,358,092
<p>So, I had an idea that I could use a range of numbers as a key for a single value in a dictionary.</p> <p>I wrote the code bellow, but I cannot get it to work. Is it even possible?</p> <pre><code> stealth_roll = randint(1, 20) # select from a dictionary of 4 responses using one of four ranges. ## not w...
8
2016-09-06T21:25:26Z
39,781,091
<p>Thank you everyone for your responses. I kept hacking away, and I came up with a solution that will suit my purposes quite well. It is most similar to the suggestions of @PaulCornelius.</p> <pre><code>stealth_roll = randint(1, 20) # select from a dictionary of 4 responses using one of four ranges. # only one resolu...
0
2016-09-29T22:40:05Z
[ "python", "dictionary", "range" ]
SQLAlchemy poor performance on iterating
39,358,120
<p>The following block of code queries a table with ~2000 rows. The loop takes 20s to execute! From my limited knowledge, I don't think I'm doing 2000 queries, just the one, but perhaps I'm not understanding the '.' operator and what it's doing behind the scenes. How can I fix this loop to run more quickly? Is there a ...
0
2016-09-06T21:28:25Z
39,358,344
<p>Each time you access <code>.component</code> another SQL query is emitted.</p> <p>You can read more at <a href="http://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html" rel="nofollow">Relationship Loading Techniques</a>, but to load it all at once you can change your query to the following:</p> <pre><c...
2
2016-09-06T21:48:12Z
[ "python", "python-2.7", "sqlalchemy" ]
Django reverse is giving me some trouble
39,358,180
<p>My problem is that when reverse is called it throws the following exception</p> <p>Reverse for '/documentation/' with arguments '(3,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []</p> <p>Here is my urls.py</p> <pre><code>url(r'^documentation/$', views.view1), url(r'^documentation/([0-9])/$', views...
-2
2016-09-06T21:33:58Z
39,358,799
<p>Reverse uses the URL name and you declared the name as <code>name='documentation'</code> but we can see you are using <code>'/documentation/'</code> instead:</p> <pre><code>File "C:\Users\Pa\Desktop\Nueva carpeta\ag\Ag\scheduler\views.py" in documentation 82. url = reverse('/documentation/', args=(3,)) </...
-1
2016-09-06T22:37:30Z
[ "python", "django" ]
Ipython notebook matplotlib gui backends dlopen import error on osx
39,358,184
<p>On OSX 10.11.6 using Anaconda python 2.7 when switching to (any) gui matplotlib backend from <code>%matplotlib inline</code> in jupyter ipython notebook generates:</p> <blockquote> <p>ImportError: dlopen(/Users/.../anaconda2/lib/python2.7/site-packages/PyQt4/QtGui.so, 2): Library not loaded: @rpath/libpng16.1...
1
2016-09-06T21:34:38Z
39,565,789
<p>Problem was solved after I did this:</p> <pre><code>conda update libpng </code></pre> <p>Which resulted in:</p> <pre><code>The following packages will be UPDATED: libpng: 1.6.17-0 --&gt; 1.6.22-0 </code></pre>
0
2016-09-19T05:12:58Z
[ "python", "matplotlib", "pyqt4", "anaconda", "jupyter-notebook" ]
How to install Bloomberg API Library for Python 2.7 on Mac OS X
39,358,397
<p>I'm trying to setup my Mac OS X system to use the <code>pdblp</code> Python library which requires me to first install the <a href="https://www.bloomberglabs.com/api/libraries/" rel="nofollow">Bloomberg Open API libary for Python</a>. After cloning the git repo and running <code>python setup.py install</code>, I get...
0
2016-09-06T21:52:32Z
40,048,982
<p>You also need to install the <a href="https://bloomberg.bintray.com/BLPAPI-Experimental-Generic/blpapi_cpp_3.8.1.1-darwin.tar.gz" rel="nofollow">C/C++ libraries</a> and then set BLPAPI_ROOT to the location of the <code>libblpapi3_32.so</code> or <code>libblpapi3_64.so</code> files. For example:</p> <pre><code>cd /s...
0
2016-10-14T17:36:29Z
[ "python", "osx", "python-2.7", "bloomberg" ]
Using pjsip in daemon mode with python twisted
39,358,407
<p>I am trying to run simple pjsip application in daemon mode. I have combined this library with python twisted. Script works fine when I run it in shell &amp; can make call. But when I use it with twisted's Application framework, I get following error.</p> <pre><code>Object: {Account &lt;sip:192.168.0.200:5060&gt;}, ...
0
2016-09-06T21:52:59Z
39,571,824
<p>This issue resolved after I set sound devices.</p>
0
2016-09-19T11:13:47Z
[ "python", "twisted", "sip", "daemon", "pjsip" ]
Running unittest discover ignoring specific directory
39,358,442
<p>I'm looking for a way of running <code>python -m unittest discover</code>, which will discover tests in, say, directories A, B and C. However, directories A, B and C have directories named <code>dependencies</code> inside each of them, in which there are also some tests which, however, I don't want to run.</p> <p>I...
1
2016-09-06T21:56:28Z
39,359,096
<p>It would seem that <code>python -m unittest</code> descends into module directories but not in other directories.</p> <p>It quickly tried the following structure</p> <pre><code>temp + a - test_1.py + dependencies - test_a.py </code></pre> <p>With the result </p> <pre><code>&gt;python -m unittest discov...
-1
2016-09-06T23:14:41Z
[ "python", "python-2.7", "python-unittest" ]
Why Pandas Series resample function generated an unexpected start_time after resampling?
39,358,594
<p>I have a time series data in pandas, I wanna calculate the number of data in different bins by using resampling function of pandas with a specified frequency. </p> <p>The pandas series looks like something below if you use :</p> <pre><code>test_data.head(10) </code></pre> <p>You will get the results (only show to...
0
2016-09-06T22:10:42Z
39,400,829
<p>I think you are correct in that this should be achieved with the <code>base</code> argument. Unfortunately, I also cannot find a way to easily anchor the resampling with the original first datetimeindex (in your case, '2015-11-29 23:28:50') instead of a calculated one ('2015-11-29 22:42:18').</p> <p>As a workaround...
0
2016-09-08T22:00:30Z
[ "python", "pandas", "time-series" ]
Python Pandas df.ix not performing as expected
39,358,602
<p>Here is my function:</p> <pre><code> def clean_zipcodes(df): df.ix[df['workCountryCode'].str.contains('USA') &amp; \ df['workZipcode'].astype(str).str.len() &gt; 5, 'workZipcode'] = \ df['workZipcode'].astype(int).floordiv(10000) df.ix[df['contractCountryCode'].str.contains('USA') &amp; \ df['cont...
0
2016-09-06T22:11:08Z
39,360,547
<pre><code>In [2]: import pandas as pd In [3]: testDf = pd.DataFrame({'unique_transaction_id' : ['1', '1', '1'], ...: 'workZipcode' : [838431000, 991631000, 99163], ...: 'contractZipcode' : [838431000, 991631000, 99163], ...: ...
1
2016-09-07T02:53:49Z
[ "python", "pandas", "testing" ]
expected speedup Numba/CUDA versus Numpy
39,358,635
<p>I'm new to Numba and CUDA and have done measurements to compare cuda jitted functions to Numpy on a few basic examples. For example,</p> <pre><code>@cuda.jit("void(float32[:])") def gpu_computation(array): pos = cuda.grid(1) if pos &lt; array.size: array[pos] = array[pos] ** 2.6 </code></pre> <p>co...
-2
2016-09-06T22:14:53Z
39,359,102
<p>Double precision arithmetic throughput of your GTX 775M is <a href="http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#arithmetic-instructions" rel="nofollow">1/24th of the single precision throughput</a>. As Python does not have a single precision type, you need to use <a href="http://numba.pydata.org/...
2
2016-09-06T23:15:10Z
[ "python", "cuda", "numba" ]
duplicate events action in django admin
39,358,644
<p>I have a duplicate records function in my django admin.py, and in someway it works, but the weird things is that i have must duplicate this function outside and inside the modelAdmin... </p> <pre><code>def duplicate_event(ModelAdmin, request, queryset): for object in queryset: object.id = None o...
0
2016-09-06T22:15:49Z
39,358,763
<p>Your indentation level is wrong, it should be:</p> <pre><code>class ProductAdmin(ImageCroppingMixin, admin.ModelAdmin): def duplicate_event(ModelAdmin, request, queryset): for object in queryset: object.id = None object.save() duplicate_event.short_description = "Duplica Reco...
0
2016-09-06T22:34:02Z
[ "python", "django", "backend" ]
Pandas Insert a row above the Index and the Series data in a Dataframe
39,358,661
<p>I ve been around several trials, nothing seems to work so far. I have tried <code>df.insert(0, "XYZ", 555)</code> which seemed to work until it did not for some reasons i am not certain.</p> <p>I understand that the issue is that Index is not considered a Series and so, df.iloc[0] does not allow you to insert data ...
2
2016-09-06T22:17:43Z
39,358,942
<p>if you want to insert a row <strong>before</strong> the first row, you can do it this way:</p> <p>data:</p> <pre><code>In [57]: df Out[57]: id var 0 a 1 1 a 2 2 a 3 3 b 5 4 b 9 </code></pre> <p>adding one row:</p> <pre><code>In [58]: df.loc[df.index.min() - 1] = ['z', -1] In [59]: df Out[...
2
2016-09-06T22:54:23Z
[ "python", "pandas", "indexing", "dataframe", "row" ]
How to use Django Models in Javascript with AngularJS
39,358,684
<p>I'm working with django and AngularJS and I want to use my objects I create in Django in my javascript file. </p> <p>in my models.py (django) I make my object:</p> <pre><code>from django.db import models class Cashflow(models.Model): index = models.FloatField(); value = models.FloatField(); date = mo...
0
2016-09-06T22:19:59Z
39,386,326
<p>you need to change the model object to Json object by serializing first.</p> <p>I can show some code for you.</p> <pre><code>results = [] objects = one_table.object.all() for i in objects: results.append({'field1: i.value1', 'field2': i.value2}) return HttpResponse(json.dumps(results)) </code></pre>
0
2016-09-08T08:40:42Z
[ "javascript", "python", "angularjs", "django" ]
Including an AND statement in a Python List Comprehension
39,358,699
<p>I'm trying to create a function for an array. The array will go in and if the value is 0 it will be put to the back of the list. My function works most of the time, but the only issue is that the Boolean value False keeps getting interpreted as 0. I've created an AND statement to differentiate 0 and False, but it is...
-1
2016-09-06T22:27:51Z
39,358,801
<p>It is probably a bad idea to try to make a semantic distinctions between <code>0</code> and <code>False</code> when filtering a list, but if you have a good reason to do so there are a couple of ways that might work in your situation.</p> <p>A somewhat hackish approach which works in CPython is to use <code>is</cod...
0
2016-09-06T22:37:32Z
[ "python", "arrays", "list-comprehension" ]
Including an AND statement in a Python List Comprehension
39,358,699
<p>I'm trying to create a function for an array. The array will go in and if the value is 0 it will be put to the back of the list. My function works most of the time, but the only issue is that the Boolean value False keeps getting interpreted as 0. I've created an AND statement to differentiate 0 and False, but it is...
-1
2016-09-06T22:27:51Z
39,358,923
<p>A loop alternative to your list comprehension. It still modifies the list. As noted by others <code>x is 0</code> simplifies the distinction between <code>0</code> and <code>False</code>:</p> <pre><code>In [106]: al=[0, 1, 2, False, True, 3,0,10] In [107]: for i,x in enumerate(al): ...: if x is 0: ....
1
2016-09-06T22:52:09Z
[ "python", "arrays", "list-comprehension" ]
For a particular ID, check for every 3 mins and set a flag in python
39,358,727
<p>Suppose I am having data as follows, The data has three columns ID, date and Time,</p> <pre><code>ID date Time 1 8/20/2016 20:27:25 1 8/20/2016 20:29:04 1 8/20/2016 20:29:05 1 8/20/2016 20:38:38 1 8/20/2016 20:38:38 2 8/20/2016 14:24:53 3 8/20/2016 21:18:37 3 8/20/2016 21:1...
-1
2016-09-06T22:29:40Z
39,359,221
<p>The first to do would be to put the data in useful data structure: I chose a list of sets. These records would first need to be grouped by their (id, date) which is an easy task using the <code>groupby</code> function of <code>itertools</code>. </p> <p>If the data came from a database, you could run such grouping i...
1
2016-09-06T23:31:32Z
[ "python", "python-2.7", "python-3.x" ]
Python: Greyscale image: Make everything white, except for black pixels
39,358,729
<p>I tried to open (already greyscale) images and change all non-black pixels to white pixels. I implemented the following code:</p> <pre><code>from scipy.misc import fromimage, toimage from PIL import Image import numpy as np in_path = 'E:\\in.png' out_path = 'E:\\out.png' # Open gray-scale image img = Image.open(i...
0
2016-09-06T22:29:50Z
39,360,008
<p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.toimage.html" rel="nofollow">toimage</a> expects a byte array, so convert to uint8 not int:</p> <pre><code>imp_arr = (np.ceil(imp_arr / 255.0) * 255.0).astype('uint8') </code></pre> <p>I seems to work for <code>int</code> if there is a mix of ...
2
2016-09-07T01:29:22Z
[ "python", "image", "performance" ]
Disconnecting from WiFi using python (Windows)
39,358,765
<p>I can connect to a WiFi network using: </p> <pre><code>process = subprocess.Popen( 'netsh wlan connect {0}'.format(wifi_network), shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE) stdout, stderr = process.communicate() </code></pre> <p>I was wondering if there was a similar way to ...
1
2016-09-06T22:34:12Z
39,364,152
<p>Look at <strong>"netsh wlan disconnect"</strong>: <a href="https://technet.microsoft.com/en-us/library/cc755301(v=ws.10).aspx#bkmk_wlanDisConn" rel="nofollow">Netsh Commands for Wireless Local Area Network</a></p>
0
2016-09-07T07:50:17Z
[ "python", "subprocess", "wifi" ]
Receving an error when trying to use the pandas read_html function
39,358,775
<p>I'm really new to python and pandas so I could be making a simple mistake.</p> <p>I'm trying to run the code below:</p> <pre><code>import quandl import pandas as pd df3 = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states') print(df3) </code></pre> <p>I have installed pandas as well quandl throu...
0
2016-09-06T22:35:14Z
39,378,308
<p>I fixed the problem. I moved the file that I wanted to install from <code>Downloads</code> to <code>LocalDisk/Users/My_name</code>. Inside the right directory, <code>PIP</code> was able to locate and install it for some reason. Thanks for the responses.</p>
0
2016-09-07T20:15:51Z
[ "python", "windows", "python-2.7", "pandas", "pip" ]
Login to https website using Python
39,358,781
<p>I'm new to posting on stackoverflow so please don't bite! I had to resort to making an account and asking for help to avoid banging my head on the table any longer...</p> <p>I'm trying to login to the following website <a href="https://account.socialbakers.com/login" rel="nofollow">https://account.socialbakers.com/...
1
2016-09-06T22:35:55Z
39,358,943
<p>Two things to look out. One, try to use s.post and second you need to check in the browser if there is any other value the form is sending by looking at the network tab. </p>
0
2016-09-06T22:54:25Z
[ "python", "python-requests" ]
Login to https website using Python
39,358,781
<p>I'm new to posting on stackoverflow so please don't bite! I had to resort to making an account and asking for help to avoid banging my head on the table any longer...</p> <p>I'm trying to login to the following website <a href="https://account.socialbakers.com/login" rel="nofollow">https://account.socialbakers.com/...
1
2016-09-06T22:35:55Z
39,359,180
<p>Form is not sending password in clear text. It is encrypting or hashing it before sending. When you type password <code>aaaa</code> in form via network it sends</p> <p><code>b3744bb9a8adb2d67cfdf79095bd84f5e77500a76727e6d73eef460eb806511ba73c9f765d4b3738e0b1399ce4a4c4ac3aed17fff34e0ef4037e9be466adec61</code> </p> ...
0
2016-09-06T23:27:09Z
[ "python", "python-requests" ]
Login to https website using Python
39,358,781
<p>I'm new to posting on stackoverflow so please don't bite! I had to resort to making an account and asking for help to avoid banging my head on the table any longer...</p> <p>I'm trying to login to the following website <a href="https://account.socialbakers.com/login" rel="nofollow">https://account.socialbakers.com/...
1
2016-09-06T22:35:55Z
39,359,295
<p>Checked the website. It is sending the SHA3 hash of the password instead of sending as plaintext. You can see this in line 111 of <a href="https://account.socialbakers.com/js/script.js" rel="nofollow">script.js</a> which is included in the main page as :</p> <pre><code>&lt;script src="/js/script.js"&gt;&lt;/script&...
1
2016-09-06T23:40:54Z
[ "python", "python-requests" ]
capturing a result in a variable
39,358,811
<p>I am just getting my head around functions in Python (only been learning Python for 6 months) and I'm stuck on some code which is not working. It says total is not defined, nameerror. Reading through some posts I think I need to store total in a variable but I don't know where. Can you do this in the return statemen...
1
2016-09-06T22:39:02Z
39,358,871
<p>On line 83, you are sending the variable <code>total</code> to the function export_data(ans1,ans2,ans3,total) which is not defined within your while loop. Assuming that your total is <code>ans1+ans2+ans3</code> before sending the value, add the line,</p> <pre><code>total = ans1+ans2+ans3 </code></pre> <p>That shou...
1
2016-09-06T22:46:43Z
[ "python", "function", "csv" ]
capturing a result in a variable
39,358,811
<p>I am just getting my head around functions in Python (only been learning Python for 6 months) and I'm stuck on some code which is not working. It says total is not defined, nameerror. Reading through some posts I think I need to store total in a variable but I don't know where. Can you do this in the return statemen...
1
2016-09-06T22:39:02Z
39,358,878
<p>Your total is defined only within the function <code>run_model</code>. When that function returns, you cannot reference <code>total</code> again, since its gone <a href="http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html" rel="nofollow">out of scope</a>. The variable is now "unbound", and tha...
1
2016-09-06T22:47:17Z
[ "python", "function", "csv" ]
capturing a result in a variable
39,358,811
<p>I am just getting my head around functions in Python (only been learning Python for 6 months) and I'm stuck on some code which is not working. It says total is not defined, nameerror. Reading through some posts I think I need to store total in a variable but I don't know where. Can you do this in the return statemen...
1
2016-09-06T22:39:02Z
39,436,551
<p>def export_data(ans1,ans2,ans3): total = ans1 + ans2 + ans3 # total is available inside of export_data table = [ans1, ans2, ans3,total]</p> <pre><code>nameoffile = input('what would you like to call the filename') nameoffile = open(nameoffile+".csv","w") csv_file_ref = csv.writer(nameoffile) csv_file_ref.w...
0
2016-09-11T13:22:17Z
[ "python", "function", "csv" ]
check if an IP is within a range of CIDR in Python
39,358,869
<p>I know there are some similar questions up here, but they mostly either want to find the range itself (which uses some libraries, like the example that stackoverflow says is a dupe of my question) and is in another language.</p> <p>I have a way to convert the subnet into the beginning and the end of the range of ip...
0
2016-09-06T22:46:08Z
39,358,930
<p>Your code compares strings, not numbers. I would suggest using tuples instead:</p> <pre><code>&gt;&gt;&gt; ip_range = [(1,1,0,0), (1,1,255,255)] &gt;&gt;&gt; testip = (1,1,2,2) &gt;&gt;&gt; testip &gt; ip_range[0] and testip &lt; ip_range[1] True &gt;&gt;&gt; testip = (1,3,1,1) &gt;&gt;&gt; testip &gt; ip_range[0] ...
3
2016-09-06T22:53:11Z
[ "python", "ip" ]
check if an IP is within a range of CIDR in Python
39,358,869
<p>I know there are some similar questions up here, but they mostly either want to find the range itself (which uses some libraries, like the example that stackoverflow says is a dupe of my question) and is in another language.</p> <p>I have a way to convert the subnet into the beginning and the end of the range of ip...
0
2016-09-06T22:46:08Z
39,358,935
<p>This doesn't work in general, because string comparison is in collating order, not the numerical values of the four fields. For instance, '1.1.2.2' > '1.1.128.1' -- the critical spot in the 5th character, '1' vs '2'.</p> <p>If you want to compare the fields, try separating into lists:</p> <pre><code>ip_vals = [in...
1
2016-09-06T22:53:35Z
[ "python", "ip" ]
check if an IP is within a range of CIDR in Python
39,358,869
<p>I know there are some similar questions up here, but they mostly either want to find the range itself (which uses some libraries, like the example that stackoverflow says is a dupe of my question) and is in another language.</p> <p>I have a way to convert the subnet into the beginning and the end of the range of ip...
0
2016-09-06T22:46:08Z
39,358,983
<p>You can't really do string comparisons on a dot separated list of numbers because your test will simply fail on input say <code>1.1.99.99</code> as <code>'9'</code> is simply greater than <code>'2'</code></p> <pre><code>&gt;&gt;&gt; '1.1.99.99' &lt; '1.1.255.255' False </code></pre> <p>So instead you can convert t...
2
2016-09-06T22:59:31Z
[ "python", "ip" ]
check if an IP is within a range of CIDR in Python
39,358,869
<p>I know there are some similar questions up here, but they mostly either want to find the range itself (which uses some libraries, like the example that stackoverflow says is a dupe of my question) and is in another language.</p> <p>I have a way to convert the subnet into the beginning and the end of the range of ip...
0
2016-09-06T22:46:08Z
39,359,495
<p>In Python 3.3 and later, you should be using the <code>ipaddress</code> module.</p> <pre><code>from ipaddress import ip_network, ip_address net = ip_network("1.1.0.0/16") print(ip_address("1.1.2.2") in net) # True </code></pre>
1
2016-09-07T00:06:02Z
[ "python", "ip" ]
How do I Parse XML Elements and get values with Python 2.7
39,358,925
<p>API Response:<a href="http://iss.ndl.go.jp/api/opensearch?isbn=9784334770051" rel="nofollow">http://iss.ndl.go.jp/api/opensearch?isbn=9784334770051</a> Hello, thanks for help yesterday. However when I attempt to get value from Elements I always get empty value as response. I were refereed this <a href="http://stacko...
1
2016-09-06T22:52:29Z
39,359,979
<p>Your code needs a slight modification, add <code>.//</code> to your expression in the <em>findall</em> call, the root node is the <em>rss</em> node and the <em>dc:title's</em> are descendants not direct children of the <em>rss</em> node so you need to search through the doc:</p> <pre><code>import xml.etree.ElementT...
0
2016-09-07T01:25:38Z
[ "python", "xml", "xml-parsing" ]
Python - Graphing contents of mutliple files
39,358,958
<p>I have lists of ~10 corresponding input files containing columns of tab separated data approx 300 lines/datapoints each. </p> <p>I'm looking to plot the contents of each set of data such that I have a 2 plots for each set of data one is simply of x vs (y1,y2,y3,...) and one which is transformed by a function e.g. x...
2
2016-09-06T22:56:29Z
39,359,547
<p>Basically, I think you should put all your code in the readloop, because that will work easily. There's a slightly different way of using matplotlib that makes it easy to use the existing organization of your data AND write shorter code. Here's a toy, but complete, example: </p> <pre><code>import matplotlib.pyplot ...
0
2016-09-07T00:12:51Z
[ "python", "matplotlib" ]
Multithreading to Scrap Yahoo Finance
39,358,982
<p>I'm running a program to pull some info from Yahoo! Finance. It runs fine as a <code>For</code> loop, however it takes a long time (about 10 minutes for 7,000 inputs) because it has to process each <code>request.get(url)</code> individually (or am I mistaken on the major bottlenecker?)</p> <p>Anyway, I came across ...
-1
2016-09-06T22:59:26Z
39,359,155
<p>If you look carefully at the error you will notice that it doesn't show one url but all the urls you appended, enclosed with brackets. Indeed the last line of your code actually call your method fetch_data with the full array as a parameter, which does't make sense. If you remove this last line the code runs just fi...
2
2016-09-06T23:22:57Z
[ "python", "multithreading", "yahoo-finance" ]
Align python arrays with missing data
39,359,061
<p>I have some time series data, say:</p> <pre><code># [ [time] [ data ] ] a = [[0,1,2,3,4],['a','b','c','d','e']] b = [[0,3,4]['f','g','h']] </code></pre> <p>and I would like an output with some filler value, lets say None for now:</p> <pre><code>a_new = [[0,1,2,3,4],['a','b','c','d','e']] b_new = [[0,1,2,3,4],['f'...
4
2016-09-06T23:09:43Z
39,359,133
<p>How about this? (I'm assuming your definition of <code>b</code> was a typo, and I'm also assuming you know in advance how many entries you want.)</p> <pre><code>&gt;&gt;&gt; b = [[0,3,4], ['f','g','h']] &gt;&gt;&gt; b_new = [list(range(5)), [None] * 5] &gt;&gt;&gt; for index, value in zip(*b): b_new[1][index] = val...
4
2016-09-06T23:20:35Z
[ "python", "numpy" ]
Align python arrays with missing data
39,359,061
<p>I have some time series data, say:</p> <pre><code># [ [time] [ data ] ] a = [[0,1,2,3,4],['a','b','c','d','e']] b = [[0,3,4]['f','g','h']] </code></pre> <p>and I would like an output with some filler value, lets say None for now:</p> <pre><code>a_new = [[0,1,2,3,4],['a','b','c','d','e']] b_new = [[0,1,2,3,4],['f'...
4
2016-09-06T23:09:43Z
39,359,776
<p>smarx has a fine answer, but <a href="http://pandas.pydata.org/pandas-docs/stable/index.html" rel="nofollow">pandas</a> was made exactly for things like this. </p> <pre><code># your data a = [[0,1,2,3,4],['a','b','c','d','e']] b = [[0,3,4],['f','g','h']] # make an empty DataFrame (can do this faster but I'm going ...
1
2016-09-07T00:51:29Z
[ "python", "numpy" ]
Align python arrays with missing data
39,359,061
<p>I have some time series data, say:</p> <pre><code># [ [time] [ data ] ] a = [[0,1,2,3,4],['a','b','c','d','e']] b = [[0,3,4]['f','g','h']] </code></pre> <p>and I would like an output with some filler value, lets say None for now:</p> <pre><code>a_new = [[0,1,2,3,4],['a','b','c','d','e']] b_new = [[0,1,2,3,4],['f'...
4
2016-09-06T23:09:43Z
39,363,673
<p>Here's a vectorized <em>NumPythonic</em> approach -</p> <pre><code>def align_arrays(A): time, data = A time_new = np.arange(np.max(time)+1) data_new = np.full(time_new.size, None, dtype=object) data_new[np.in1d(time_new,time)] = data return time_new, data_new </code></pre> <p>Sample runs -</...
0
2016-09-07T07:24:20Z
[ "python", "numpy" ]
passing directory with spaces in it from raw_input to os.listdir(path) in Python
39,359,071
<p>I've looked at a few posts regarding this topic but haven't seen anything specifically fitting my usage. <a href="http://stackoverflow.com/questions/36555950/spaces-in-directory-path-python">This one looks to be close</a> to the same issue. They talk about escaping the escape characters.</p> <p>My issue is that I w...
0
2016-09-06T23:11:13Z
39,359,201
<p>Your problem is most likely not with the code you present, but with the input you gave. The message </p> <blockquote> <p>the system can't find the path specified "LAS Data\*.*"</p> </blockquote> <p>suggest that you (or the user) entered the directory together with a wildcard for files. A directory with the name ...
2
2016-09-06T23:29:30Z
[ "python", "python-2.7", "escaping" ]
passing directory with spaces in it from raw_input to os.listdir(path) in Python
39,359,071
<p>I've looked at a few posts regarding this topic but haven't seen anything specifically fitting my usage. <a href="http://stackoverflow.com/questions/36555950/spaces-in-directory-path-python">This one looks to be close</a> to the same issue. They talk about escaping the escape characters.</p> <p>My issue is that I w...
0
2016-09-06T23:11:13Z
39,359,306
<blockquote> <p>I don't quite understand what the [<code>path = r"%s" % directory</code>] line is doing</p> </blockquote> <p>It creates a copy <code>path</code> of <code>directory</code>:</p> <pre><code>&gt;&gt;&gt; directory = raw_input() LAS Data &gt;&gt;&gt; path = r"%s" % directory &gt;&gt;&gt; path == directo...
1
2016-09-06T23:41:41Z
[ "python", "python-2.7", "escaping" ]
From stat().st_mtime to datetime?
39,359,245
<p>What is the most idiomatic/efficient way to convert from a modification time retrieved from <code>stat()</code> call to a <code>datetime</code> object? I came up with the following (python3):</p> <pre><code>from datetime import datetime, timedelta, timezone from pathlib import Path path = Path('foo') path.touch() ...
3
2016-09-06T23:35:09Z
39,359,270
<p>Try <a href="https://docs.python.org/3.5/library/datetime.html#datetime.date.fromtimestamp" rel="nofollow">datetime.fromtimestamp(statResult.st_mtime)</a></p> <p>e.g.</p> <pre><code>mod_timestamp = datetime.fromtimestamp(path.getmtime(&lt;YOUR_PATH_HERE&gt;)) </code></pre>
1
2016-09-06T23:38:25Z
[ "python", "python-3.x", "datetime", "stat", "pathlib" ]
Add new columns to pandas dataframe based on other dataframe
39,359,272
<p>I'm trying to set a new column (two columns in fact) in a pandas dataframe, with the data comes from other dataframe.</p> <p>I have the following two dataframes (they are example for this purpose, the original dataframes are so much bigger):</p> <pre><code>In [116]: df0 Out[116]: A B C 0 0 1 0 1 2 3...
2
2016-09-06T23:38:30Z
39,359,665
<p>This is a basic application of <code>merge</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow">docs</a>):</p> <pre><code>import pandas as pd df2 = pd.merge(df0,df1, left_index=True, right_index=True) </code></pre>
2
2016-09-07T00:32:47Z
[ "python", "pandas", "dataframe", "machine-learning", "data-science" ]
Python Google Admin SDK 403 Error
39,359,291
<p>I am attempting to retrieve all the members of a group but am receiving an error.</p> <p>Here is my code:</p> <pre><code># -*- coding: utf-8 -*- from __future__ import print_function import httplib2 import os from apiclient import discovery import oauth2client from oauth2client import client from oauth2client im...
1
2016-09-06T23:40:07Z
39,360,057
<p>I obviously can't read.</p> <p>Solved this by deleting credentials from ~/.credentials/</p>
0
2016-09-07T01:38:47Z
[ "python", "api", "sdk", "admin" ]
Tell python to access resources above the path of the script
39,359,359
<p>If you run a script from /tmp/myfolder/myscript/, and want to access a resource in myfolder, how do you do that in python?</p> <p>I did get the file path with <code>__file__</code>, (I was told to not use it because it may not always be populated) but I can't do like in bash, where I "cd .." to get to the previous...
2
2016-09-06T23:48:03Z
39,359,406
<p>Python does understand <code>cd</code>: <code>os.chdir()</code>. I am not sure exactly what you are trying to do, but you can try:</p> <pre><code>import os os.chdir('..') </code></pre> <p>This will change your working directory to the one above the current one (just like <code>cd ..</code>).</p> <p>You can also u...
1
2016-09-06T23:54:45Z
[ "python" ]
Tell python to access resources above the path of the script
39,359,359
<p>If you run a script from /tmp/myfolder/myscript/, and want to access a resource in myfolder, how do you do that in python?</p> <p>I did get the file path with <code>__file__</code>, (I was told to not use it because it may not always be populated) but I can't do like in bash, where I "cd .." to get to the previous...
2
2016-09-06T23:48:03Z
39,359,419
<p>I am unclear about exactly what you are talking about, but I infer that you are talking about intra-package references. You can read more about it <a href="https://docs.python.org/3/tutorial/modules.html" rel="nofollow">here</a>, but the general concept is you use <code>from .. import module</code> when trying to im...
1
2016-09-06T23:56:04Z
[ "python" ]
How to use yaml.load_all with fileinput.input?
39,359,390
<p>Without resorting to <code>''.join</code>, is there a Pythonic way to use PyYAML's <code>yaml.load_all</code> with <code>fileinput.input()</code> for easy streaming of multiple documents from multiple sources?</p> <p>I'm looking for something like the following (non-working example):</p> <pre><code># example.py im...
3
2016-09-06T23:52:22Z
39,360,463
<p>The problem with <code>fileinput.input</code> is that the resulting object doesn't have a <code>read</code> method, which is what <code>yaml.load_all</code> is looking for. If you're willing to give up <code>fileinput</code>, you can just write your own class that will do what you want:</p> <pre><code>import sys ...
3
2016-09-07T02:41:55Z
[ "python", "pyyaml" ]
How to use yaml.load_all with fileinput.input?
39,359,390
<p>Without resorting to <code>''.join</code>, is there a Pythonic way to use PyYAML's <code>yaml.load_all</code> with <code>fileinput.input()</code> for easy streaming of multiple documents from multiple sources?</p> <p>I'm looking for something like the following (non-working example):</p> <pre><code># example.py im...
3
2016-09-06T23:52:22Z
39,361,580
<p>Your <code>minimal_adapter</code> should take a <code>fileinput.FileInput</code> as a parameter and return an object which <code>load_all</code> can use. <code>load_all</code> either takes as an argument a string, but that would require concatenating the input, or it expects the argument to have a <code>read()</code...
2
2016-09-07T05:06:08Z
[ "python", "pyyaml" ]
Type and default input value of a Click.option in --help option
39,359,420
<p>How can I show the default input value in @Click.option in --help option of a program.</p> <p>Thank you.</p>
0
2016-09-06T23:56:06Z
39,359,671
<p>Pass <code>show_default=True</code> in the <code>click.option</code> decorator when defining an option. This will display default value in the help when the program is called with <code>--help</code> option. For example -</p> <pre><code>#hello.py import click @click.command() @click.option('--count', default=1, he...
0
2016-09-07T00:34:44Z
[ "python", "python-click" ]
Closing Selenium Browser that was Opened in a Child Process
39,359,481
<p>Here's the situation:</p> <p>I create a child process which opens and deals with a webdriver. The child process is finicky and might error, in which case it would close immediately, and control would be returned to the main function. In this situation, however, the browser would still be open (as the child proces...
0
2016-09-07T00:04:30Z
39,397,438
<p>I found a solution:</p> <p>In foo(), get the process ID of the webdriver when you open a new browser. Add the process ID to the queue. Then in the main function, add time.sleep(60) to wait for a minute, then get the process ID from the queue and use a try-except to try and close the particular process ID.</p> <p...
0
2016-09-08T18:01:20Z
[ "python", "selenium", "webdriver", "queue", "multiprocessing" ]
not getting expected result from sql query select python
39,359,548
<p>I am trying to select from a specific row and then column in SQL. I want to find a specific user_name row and then select the access_id from the row. </p> <p>Here is all of my code. </p> <pre><code>import sys, ConfigParser, numpy import MySQLdb as mdb from plaid.utils import json class SQLConnection: """Used ...
0
2016-09-07T00:13:07Z
39,359,565
<p>try changing this line:</p> <pre><code>return self.cur.fetchall </code></pre> <p>to </p> <pre><code>return self.cur.fetchall() </code></pre> <p>Without the parentheses after the method name, you are returning a reference to that method itself, not running the method.</p>
2
2016-09-07T00:16:13Z
[ "python", "mysql", "sql" ]
How can I reverse parts of sentence in python?
39,359,599
<p>I have a sentence, let's say:</p> <p>The quick brown fox jumps over the lazy dog</p> <p>I want to create a function that takes 2 arguments, a sentence and a list of things to ignore. And it returns that sentence with the reversed words, however it should ignore the stuff I pass to it in a second argument. This is ...
4
2016-09-07T00:21:28Z
39,359,682
<p>Instead of placeholders, why not just initially reverse any phrase that you want to be around the right way, then reverse the whole string:</p> <pre><code>def main(sentence, ignores): for phrase in ignores: reversed_phrase = ' '.join([word[::-1] for word in phrase.split()]) sentence = sentence.r...
0
2016-09-07T00:36:35Z
[ "python", "python-3.x" ]
How can I reverse parts of sentence in python?
39,359,599
<p>I have a sentence, let's say:</p> <p>The quick brown fox jumps over the lazy dog</p> <p>I want to create a function that takes 2 arguments, a sentence and a list of things to ignore. And it returns that sentence with the reversed words, however it should ignore the stuff I pass to it in a second argument. This is ...
4
2016-09-07T00:21:28Z
39,359,689
<p>I'm the first person to recommend avoiding regular expressions, but in this case, the complexity of doing without is greater than the complexity added by using them:</p> <pre><code>import re def main(sentence, ignores): # Dedup and allow fast lookup for determining whether to reverse a component ignores = ...
0
2016-09-07T00:37:20Z
[ "python", "python-3.x" ]
How can I reverse parts of sentence in python?
39,359,599
<p>I have a sentence, let's say:</p> <p>The quick brown fox jumps over the lazy dog</p> <p>I want to create a function that takes 2 arguments, a sentence and a list of things to ignore. And it returns that sentence with the reversed words, however it should ignore the stuff I pass to it in a second argument. This is ...
4
2016-09-07T00:21:28Z
39,359,805
<p>Just another idea, reverse every word and then reverse the ignores right back:</p> <pre><code>&gt;&gt;&gt; from functools import reduce &gt;&gt;&gt; def main(sentence, ignores): def r(s): return ' '.join(w[::-1] for w in s.split()) return reduce(lambda s, i: s.replace(r(i), i), ignores, ...
0
2016-09-07T00:56:25Z
[ "python", "python-3.x" ]
How can I reverse parts of sentence in python?
39,359,599
<p>I have a sentence, let's say:</p> <p>The quick brown fox jumps over the lazy dog</p> <p>I want to create a function that takes 2 arguments, a sentence and a list of things to ignore. And it returns that sentence with the reversed words, however it should ignore the stuff I pass to it in a second argument. This is ...
4
2016-09-07T00:21:28Z
39,364,477
<p>I have attempted to solve the issue of overlapping ignore phrases e.g. <code>['brown fox', 'quick brown']</code> raised by @PadraicCunningham.</p> <p>There's obviously a lot more looping and code feels less pythonic so I'd be interested in feedback on how to improve this.</p> <pre><code>import re def _span_combin...
0
2016-09-07T08:07:27Z
[ "python", "python-3.x" ]
python pandas.Series.str.contains WHOLE WORD
39,359,601
<p>df (Pandas Dataframe) has three rows.</p> <pre><code>col_name "This is Donald." "His hands are so small" "Why are his fingers so short?" </code></pre> <p>I'd like to extract the row that contains "is" and "small".</p> <p>If I do</p> <pre><code>df.col_name.str.contains("is|small", case=False) </code></pre> <p>Th...
4
2016-09-07T00:21:34Z
39,359,724
<p>Your way (with /b) didn't work for me. I'm not sure why you can't use the logical operator and (&amp;) since I think that's what you actually want. </p> <p>This is a silly way to do it, but it works:</p> <pre><code>mask = lambda x: ("is" in x) &amp; ("small" in x) series_name.apply(mask) </code></pre>
0
2016-09-07T00:43:55Z
[ "python", "regex", "pandas", "dataframe" ]
python pandas.Series.str.contains WHOLE WORD
39,359,601
<p>df (Pandas Dataframe) has three rows.</p> <pre><code>col_name "This is Donald." "His hands are so small" "Why are his fingers so short?" </code></pre> <p>I'd like to extract the row that contains "is" and "small".</p> <p>If I do</p> <pre><code>df.col_name.str.contains("is|small", case=False) </code></pre> <p>Th...
4
2016-09-07T00:21:34Z
39,359,789
<p>No, the regex <code>/bis/b|/bsmall/b</code> will fail because you are using <code>/b</code>, not the <code>\b</code> that means "word boundary".</p> <p>Change that and you get a match. I would recommend using</p> <pre><code>\b(is|small)\b </code></pre> <p>That regex is a little faster and a little more legible, a...
4
2016-09-07T00:54:05Z
[ "python", "regex", "pandas", "dataframe" ]
python pandas.Series.str.contains WHOLE WORD
39,359,601
<p>df (Pandas Dataframe) has three rows.</p> <pre><code>col_name "This is Donald." "His hands are so small" "Why are his fingers so short?" </code></pre> <p>I'd like to extract the row that contains "is" and "small".</p> <p>If I do</p> <pre><code>df.col_name.str.contains("is|small", case=False) </code></pre> <p>Th...
4
2016-09-07T00:21:34Z
39,359,856
<p>First, you may want to convert everything to lowercase, remove punctuation and whitespace and then convert the result into a set of words.</p> <pre><code>import string df['words'] = [set(words) for words in df['col_name'] .str.lower() .str.replace('[{0}]*'.format(string.punctuation), '') .str.strip...
1
2016-09-07T01:05:29Z
[ "python", "regex", "pandas", "dataframe" ]
Access all elements at given x, y position in 3-dimensional numpy array
39,359,621
<pre><code>mat_a = np.random.random((5, 5)) mat_b = np.random.random((5, 5)) mat_c = np.random.random((5, 5)) bigmat = np.stack((mat_a, mat_b, mat_c)) # this is a 3, 5, 5 array for (x, y, z), value in np.ndenumerate(bigmat): print (x, y, z) </code></pre> <p>In the example above, how can I loop so that I iterate o...
3
2016-09-07T00:25:13Z
39,359,818
<p>The required result can be obtained by slicing, e.g.:</p> <pre><code>for x in range(5): for y in range(5): print (bigmat[:,x,y]) </code></pre>
1
2016-09-07T00:58:33Z
[ "python", "numpy" ]
Access all elements at given x, y position in 3-dimensional numpy array
39,359,621
<pre><code>mat_a = np.random.random((5, 5)) mat_b = np.random.random((5, 5)) mat_c = np.random.random((5, 5)) bigmat = np.stack((mat_a, mat_b, mat_c)) # this is a 3, 5, 5 array for (x, y, z), value in np.ndenumerate(bigmat): print (x, y, z) </code></pre> <p>In the example above, how can I loop so that I iterate o...
3
2016-09-07T00:25:13Z
39,359,850
<p>Simon's answer is fine. If you reshape things properly you can get them all in a nice array without any looping. </p> <pre><code>In [33]: bigmat Out[33]: array([[[ 0.51701737, 0.90723012, 0.42534365, 0.3087416 , 0.44315561], [ 0.3902181 , 0.59261932, 0.21231607, 0.61440961, 0.24910501], [ 0...
2
2016-09-07T01:04:04Z
[ "python", "numpy" ]
Access all elements at given x, y position in 3-dimensional numpy array
39,359,621
<pre><code>mat_a = np.random.random((5, 5)) mat_b = np.random.random((5, 5)) mat_c = np.random.random((5, 5)) bigmat = np.stack((mat_a, mat_b, mat_c)) # this is a 3, 5, 5 array for (x, y, z), value in np.ndenumerate(bigmat): print (x, y, z) </code></pre> <p>In the example above, how can I loop so that I iterate o...
3
2016-09-07T00:25:13Z
39,360,093
<p>There is a function that generates all indices for a given shape, <code>ndindex</code>. </p> <pre><code>for y,z in np.ndindex(bigmat.shape[1:]): print(y,z,bigmat[:,y,z]) 0 0 [ 0 25 50] 0 1 [ 1 26 51] 0 2 [ 2 27 52] 0 3 [ 3 28 53] 0 4 [ 4 29 54] 1 0 [ 5 30 55] 1 1 [ 6 31 56] ... </code></pre> <p>For a simple ...
3
2016-09-07T01:45:27Z
[ "python", "numpy" ]
Access all elements at given x, y position in 3-dimensional numpy array
39,359,621
<pre><code>mat_a = np.random.random((5, 5)) mat_b = np.random.random((5, 5)) mat_c = np.random.random((5, 5)) bigmat = np.stack((mat_a, mat_b, mat_c)) # this is a 3, 5, 5 array for (x, y, z), value in np.ndenumerate(bigmat): print (x, y, z) </code></pre> <p>In the example above, how can I loop so that I iterate o...
3
2016-09-07T00:25:13Z
39,360,877
<p>If you don't actually need to stack the arrays, and only want to iterate over all three arrays, element-wise, <em>at once</em>, <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.nditer.html" rel="nofollow">numpy.nditer</a> works - I'm still fuzzy on all its parameters I don't know if it is any fast...
0
2016-09-07T03:42:36Z
[ "python", "numpy" ]
Single-valued array to rgba array using custom color map in Python
39,359,693
<p>I have code that, given a normalized array, gives an rgba array using a predefined colormap - <code>jet</code> in the example below.</p> <pre><code>import numpy as np from matplotlib import cm #arr_orig assumed to be normalized, real array. arr_color = np.uint8(cm.jet(arr_orig) * 255) </code></pre> <p>I have also...
-1
2016-09-07T00:38:19Z
39,360,904
<p>The following worked:</p> <pre><code>arr_color = cm.ScalarMappable(cmap = custom_colormap).to_rgba(arr_orig, bytes = True) </code></pre>
0
2016-09-07T03:46:42Z
[ "python", "matplotlib", "colors", "colormap" ]
Finding all posts without tags in Django Postgres ArrayField
39,359,702
<p>Just like what my title says, I want to see all my posts without any tags. However none of the following ORM is working:</p> <pre><code>x = PostTagging.obejcts.filter(tags=[]) x = PostTagging.objects.filter(tags__len=0) </code></pre> <p>All I get as a return is:</p> <pre><code>&lt;QuerySet []&gt; </code></pre> <...
0
2016-09-07T00:40:39Z
39,359,735
<p><code>PostTagging.objects.filter(tags__isnull=True)</code> is the best way</p>
1
2016-09-07T00:45:18Z
[ "python", "django", "postgresql" ]
Save A Matplotlib Figure to A File Along with Displaying it on The Browser Django
39,359,743
<p>I am very new to Django and the following is a detailed explanation of the problem I am trying to resolve using Django Python. </p> <p><strong>Problem:-</strong></p> <p>Upload a multiple csv files (<strong>five files total</strong>) and then take those files and construct five figures corresponding to the uploaded...
2
2016-09-07T00:46:34Z
39,362,441
<p>UPDATE: If you want to draw the graph only when "Graphing" is clicked, then name your input type, hence:</p> <pre><code>&lt;input type="submit" value="Graphing" name="graphing"/&gt; </code></pre> <p>and then you can check whether it has been clicked in your view:</p> <pre><code>if request.POST.get('graphing'): #b...
0
2016-09-07T06:17:59Z
[ "python", "django", "matplotlib" ]
Incorporating Lmtool into PocketSphinx?
39,359,766
<p>I am trying to create a simple way to add new keywords into PocketSphinx. The idea is to have a temporary text file that can be used to (via a script) add a word (or phrase) automatically added to the <code>corpus.txt</code>, <code>dictionary.dic</code> and <code>language_model.lm</code>.</p> <p>Currently the best ...
1
2016-09-07T00:49:50Z
39,360,291
<p>You have few choice, If you want to generate dict and language model locally on Raspberry Pi (Model 2B at least) </p> <p>For Language Model generation, you can use either</p> <ol> <li><p><a href="https://github.com/skerit/cmusphinx/tree/master/cmuclmtk" rel="nofollow">CMUCLMTK</a> or</p></li> <li><p><a href="http:...
1
2016-09-07T02:15:11Z
[ "python", "pocketsphinx" ]
Removing white space and colon
39,359,816
<p>I have a file with a bunch of numbers that have white spaces and colons and I am trying to remove them. As I have seen on this forum the function <code>line.strip.split()</code> works well to achieve this. Is there a way of removing the white space and colon all in one go? Using the method posted by Lorenzo I have t...
0
2016-09-07T00:58:10Z
39,360,196
<p>I think the above syntax is not correct, but anyways as per your question, you can use replace function present in python.</p> <p>When reading each line as a string from that file you can do something like, </p> <pre><code>train = [] with open('/Users/sushant.moon/Downloads/dexter_train.data') as f: list = f.r...
2
2016-09-07T02:01:21Z
[ "python", "numpy" ]