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
Bokeh: Interact with legend label text
39,049,622
<p>Is there any way to interactively change legend label text in Bokeh?</p> <p>I've read <a href="https://github.com/bokeh/bokeh/issues/2274" rel="nofollow">https://github.com/bokeh/bokeh/issues/2274</a> and <a href="http://stackoverflow.com/questions/32253900/how-to-interactively-display-and-hide-lines-in-a-bokeh-plo...
1
2016-08-20T01:24:20Z
39,071,084
<p>As of Bokeh <code>0.12.1</code> it does not look like this is currently supported. <code>Legend</code> objects have a <code>legends</code> property that maps the text to a list of glyphs:</p> <pre><code>{ "foo": [circle1], "bar": [line2, circle2] } </code></pre> <p>Ideally, you could update this <code>leg...
0
2016-08-22T03:41:05Z
[ "python", "bokeh" ]
How to import text data into excel columns based on spaces?
39,049,645
<p>I need to write a python code that takes the text between two blank lines in a .txt file and inserts said text into unique columns in Excel, pasting the headers only once. For example:</p> <pre><code>d1_type: shape: 2, order: false, relation: true, d2_type: shape: false, order: false, relation: t...
0
2016-08-20T01:29:41Z
39,051,479
<p>You could:</p> <ol> <li>Parse each chunk</li> <li>Convert each chunk into a dictionary</li> <li>Finally, generate a CSV using your list of dictionaries.</li> </ol> <p>You can then open the CSV in Excel. Something like the following.</p> <h1>Parse Chunks</h1> <p>Given a filename, generate chunks.</p> <pre><code>...
0
2016-08-20T07:05:56Z
[ "python", "excel" ]
Python-JSON - How to parse API output?
39,049,647
<p>I'm pretty new.</p> <p>I wrote this python script to make an API call from blockr.io to check the balance of multiple bitcoin addresses.</p> <p>The contents of btcaddy.txt are bitcoin addresses seperated by commas. For this example, let it parse <a href="http://btc.blockr.io/api/v1/address/info/1FQCJjV3JwoQVgRYVRm...
-2
2016-08-20T01:30:34Z
39,049,801
<p>Your question is clear, but your tries not.</p> <p>You said, you have a file, with at least, more than registry. So you need to retrieve the lines of this file.</p> <pre><code>with open("btcaddy.txt","r") as a: addresses = a.readlines() </code></pre> <p>Now you could iterate over registries and make a request...
1
2016-08-20T02:07:40Z
[ "python", "json" ]
Python-JSON - How to parse API output?
39,049,647
<p>I'm pretty new.</p> <p>I wrote this python script to make an API call from blockr.io to check the balance of multiple bitcoin addresses.</p> <p>The contents of btcaddy.txt are bitcoin addresses seperated by commas. For this example, let it parse <a href="http://btc.blockr.io/api/v1/address/info/1FQCJjV3JwoQVgRYVRm...
-2
2016-08-20T01:30:34Z
39,074,912
<p>You've done multiple things wrong in your code. Here's my fix. I recommend a for loop. </p> <pre><code>import json import urllib addresses = open("btcaddy.txt", "r").read() base_url = "http://btc.blockr.io/api/v1/address/info/" request = urllib.urlopen(base_url+addresses) result = json.loads(request.read())['data...
1
2016-08-22T08:43:47Z
[ "python", "json" ]
Using Python to edit the timestamps in a list? Convert POSIX to readable format using a function
39,049,665
<p>SECOND EDIT:</p> <p>Finished snippet for adjusting timezones and converting format. See correct answer below for details leading to this solution.</p> <pre><code>tzvar = int(input("Enter the number of hours you'd like to add to the timestamp:")) tzvarsecs = (tzvar*3600) print (tzvarsecs) def timestamp_to_str(tim...
1
2016-08-20T01:35:45Z
39,049,954
<p>Using your code as example, the var <code>datetime</code> store a list of string dates. So let's dissect the process in 3 steps, just for comprehension.</p> <p>Example</p> <pre><code>&gt;&gt;&gt; datetime = [timestamp["title"] for timestamp in timestamps] &gt;&gt;&gt; print(datetime) ['2:13 AM - 29 Sep 2015', '2:2...
1
2016-08-20T02:42:00Z
[ "python", "web-scraping", "timestamp", "list-comprehension" ]
Using Python to edit the timestamps in a list? Convert POSIX to readable format using a function
39,049,665
<p>SECOND EDIT:</p> <p>Finished snippet for adjusting timezones and converting format. See correct answer below for details leading to this solution.</p> <pre><code>tzvar = int(input("Enter the number of hours you'd like to add to the timestamp:")) tzvarsecs = (tzvar*3600) print (tzvarsecs) def timestamp_to_str(tim...
1
2016-08-20T01:35:45Z
39,050,310
<p>This is what I was thinking but not sure if this is what you're after:</p> <pre><code>&gt;&gt;&gt; timestamps = ["1:00 PM - 28 Sep 2015", "2:00 PM - 28 Sep 2016", "3:00 PM - 29 Sep 2015"] &gt;&gt;&gt; datetime = dict(enumerate(timestamps)) &gt;&gt;&gt; datetime {0: '1:00 PM - 28 Sep 2015', 1: '2:00 PM - 28 Sep 201...
0
2016-08-20T03:54:18Z
[ "python", "web-scraping", "timestamp", "list-comprehension" ]
Using Python to edit the timestamps in a list? Convert POSIX to readable format using a function
39,049,665
<p>SECOND EDIT:</p> <p>Finished snippet for adjusting timezones and converting format. See correct answer below for details leading to this solution.</p> <pre><code>tzvar = int(input("Enter the number of hours you'd like to add to the timestamp:")) tzvarsecs = (tzvar*3600) print (tzvarsecs) def timestamp_to_str(tim...
1
2016-08-20T01:35:45Z
39,090,597
<p>It seems you are looking for <code>datetime.timedelta</code> (<a href="https://docs.python.org/3.5/library/datetime.html#timedelta-objects" rel="nofollow">documentation here</a>). You can convert your inputs into <code>datetime.datetime</code> objects in various ways, for example, </p> <pre><code>timestamp = dateti...
0
2016-08-23T00:30:49Z
[ "python", "web-scraping", "timestamp", "list-comprehension" ]
Is it possible to make a wit.ai bot remember/reuse a context across stories?
39,049,703
<p>I am creating a chatbot using Wit.ai and am trying to achieve a more conversational style of interaction. Currently I have several stories that all require a location to function but are somewhat related. Here is an example of how I interact with my bot now:</p> <pre><code>What is the weather in Los Angeles, CA? Bo...
2
2016-08-20T01:47:14Z
39,340,512
<p>It should work the way you described it. Yes Wit doesn't update the context, so if you want to keep/remember something for later, you will have to use a client-side action to store it in the context. In you example, you will store the value of the entity wit/location in a context key, let's say <code>loc</code></p> ...
0
2016-09-06T04:09:42Z
[ "python", "wit.ai" ]
How to randomly assign values row-wise in a numpy array
39,049,716
<p>My google-fu has failed me! I have a 10x10 numpy array initialized to <code>0</code> as follows:</p> <pre><code>arr2d = np.zeros((10,10)) </code></pre> <p>For each row in <code>arr2d</code>, I want to assign 3 random columns to <code>1</code>. I am able to do it using a loop as follows:</p> <pre><code>for row in ...
4
2016-08-20T01:50:01Z
39,049,908
<p>I'm not sure how good this would be in terms of performance, but it's fairly concise.</p> <pre><code>arr2d[:, :3] = 1 map(np.random.shuffle, arr2d) </code></pre>
0
2016-08-20T02:32:06Z
[ "python", "numpy", "vectorization" ]
How to randomly assign values row-wise in a numpy array
39,049,716
<p>My google-fu has failed me! I have a 10x10 numpy array initialized to <code>0</code> as follows:</p> <pre><code>arr2d = np.zeros((10,10)) </code></pre> <p>For each row in <code>arr2d</code>, I want to assign 3 random columns to <code>1</code>. I am able to do it using a loop as follows:</p> <pre><code>for row in ...
4
2016-08-20T01:50:01Z
39,050,188
<p>Use answers from <a href="http://stackoverflow.com/questions/8505651/non-repetitive-random-number-in-numpy">this question</a> to generate non-repeating random numbers. You can use <code>random.sample</code> from Python's <code>random</code> module, or <code>np.random.choice</code>.</p> <p>So, just a small modificat...
0
2016-08-20T03:31:34Z
[ "python", "numpy", "vectorization" ]
How to randomly assign values row-wise in a numpy array
39,049,716
<p>My google-fu has failed me! I have a 10x10 numpy array initialized to <code>0</code> as follows:</p> <pre><code>arr2d = np.zeros((10,10)) </code></pre> <p>For each row in <code>arr2d</code>, I want to assign 3 random columns to <code>1</code>. I am able to do it using a loop as follows:</p> <pre><code>for row in ...
4
2016-08-20T01:50:01Z
39,050,972
<p>Once you have the <code>arr2d</code> initialized with <code>arr2d = np.zeros((10,10))</code>, you can use a vectorized approach with a <code>two-liner</code> like so -</p> <pre><code># Generate random unique 3 column indices for 10 rows idx = np.random.rand(10,10).argsort(1)[:,:3] # Assign them into initialized ar...
2
2016-08-20T05:58:25Z
[ "python", "numpy", "vectorization" ]
Python Sort not Working
39,049,752
<p>I have code to sort a list of tuples:</p> <pre><code>s = "betty bought a bit of butter but the butter was bitter" words = s.split() l = [] k = [] unique_words = sorted(set(words)) for word in unique_words: k.append(word) l.append(words.count(word)) z = zip(k,l) print z reversed(sorted(z, key=lambda x: x[...
2
2016-08-20T01:57:15Z
39,049,776
<p>It's almost correct - if you check help(reversed) in a Python REPL you'll find that it returns an iterator containing your sorted result based on your dict's values.</p> <p>If you want z to store your updated, reversed sorted list on count, you'll need to reassign z:</p> <pre><code>z = list(reversed(sorted(z, key=...
2
2016-08-20T02:03:21Z
[ "python", "python-2.7", "sorting" ]
Python Sort not Working
39,049,752
<p>I have code to sort a list of tuples:</p> <pre><code>s = "betty bought a bit of butter but the butter was bitter" words = s.split() l = [] k = [] unique_words = sorted(set(words)) for word in unique_words: k.append(word) l.append(words.count(word)) z = zip(k,l) print z reversed(sorted(z, key=lambda x: x[...
2
2016-08-20T01:57:15Z
39,049,777
<p><code>reversed</code> and <code>sorted</code> do not sort in-place; instead they return the newly sorted and reversed object. Change the second to last line to </p> <pre><code>z = list(reversed(sorted(z, key=lambda x: x[1]))) </code></pre> <p>and it will work. The <code>list</code> call is because <code>reversed<...
5
2016-08-20T02:03:23Z
[ "python", "python-2.7", "sorting" ]
Python Sort not Working
39,049,752
<p>I have code to sort a list of tuples:</p> <pre><code>s = "betty bought a bit of butter but the butter was bitter" words = s.split() l = [] k = [] unique_words = sorted(set(words)) for word in unique_words: k.append(word) l.append(words.count(word)) z = zip(k,l) print z reversed(sorted(z, key=lambda x: x[...
2
2016-08-20T01:57:15Z
39,049,778
<p>For an in-place sort, you should use <code>z.sort()</code>. </p> <p>If you insist on using <code>sorted</code>, then send the value back to <code>z</code>.</p> <p>So, use either,</p> <pre><code>z.sort(key = lambda x:x[1]) z.reverse() </code></pre> <p>Or,</p> <pre><code>z = reversed(sorted(z, key=lambda x: x[1])...
4
2016-08-20T02:03:33Z
[ "python", "python-2.7", "sorting" ]
Python Sort not Working
39,049,752
<p>I have code to sort a list of tuples:</p> <pre><code>s = "betty bought a bit of butter but the butter was bitter" words = s.split() l = [] k = [] unique_words = sorted(set(words)) for word in unique_words: k.append(word) l.append(words.count(word)) z = zip(k,l) print z reversed(sorted(z, key=lambda x: x[...
2
2016-08-20T01:57:15Z
39,049,806
<p>Least changes to your code:</p> <pre><code>s = "betty bought a bit of butter but the butter was bitter" words = s.split() l = [] k = [] unique_words = sorted(set(words)) for word in unique_words: k.append(word) l.append(words.count(word)) z = zip(k,l) print z z = sorted(z, key=lambda x: x[1] , reverse=Tr...
1
2016-08-20T02:08:21Z
[ "python", "python-2.7", "sorting" ]
Python Sort not Working
39,049,752
<p>I have code to sort a list of tuples:</p> <pre><code>s = "betty bought a bit of butter but the butter was bitter" words = s.split() l = [] k = [] unique_words = sorted(set(words)) for word in unique_words: k.append(word) l.append(words.count(word)) z = zip(k,l) print z reversed(sorted(z, key=lambda x: x[...
2
2016-08-20T01:57:15Z
39,049,830
<p>To count the words in the string, you can simply use <code>Counter</code> from <code>collections</code>. Then sort it in the descending order of counts.</p> <p>Your code can be shortened to</p> <pre><code>from collections import Counter s = "betty bought a bit of butter but the butter was bitter" c = Counter(i for...
1
2016-08-20T02:14:10Z
[ "python", "python-2.7", "sorting" ]
Adding jinja template dynamically
39,049,852
<p>I have a jinja template that is the only content inside a set of div tags.</p> <pre><code>&lt;div id="section0"&gt; {% include 'temppage.html' %} &lt;/div&gt; </code></pre> <p>When I press a button, I want to replace everything between the tags with something else. I was hoping to replace it with another jinja...
1
2016-08-20T02:19:17Z
39,050,351
<p>You could use a JS framework (such as Angular, React...) in order to achieve this...I am assuming you are trying to build a single page app?</p> <p>Otherwise, you will have to rely more on Javascript in order to change the HTML under you div depending on what you click. For example, if you have button 1, 2, 3. Each...
0
2016-08-20T04:01:23Z
[ "javascript", "python", "html", "jinja2" ]
Adding jinja template dynamically
39,049,852
<p>I have a jinja template that is the only content inside a set of div tags.</p> <pre><code>&lt;div id="section0"&gt; {% include 'temppage.html' %} &lt;/div&gt; </code></pre> <p>When I press a button, I want to replace everything between the tags with something else. I was hoping to replace it with another jinja...
1
2016-08-20T02:19:17Z
39,068,358
<p>As glls said, replacing the content can be used with,</p> <pre><code>document.getElementById("section0").innerHTML = "something"; </code></pre> <p>As for adding a jinja template dynamically, you need to replace the innerHTML with a multi-line string of the wanted jinja template, with is used with backticks, "`". S...
0
2016-08-21T19:59:52Z
[ "javascript", "python", "html", "jinja2" ]
Finding the area of intersection of multiple overlapping rectangles in Python
39,049,929
<p>I tried to using the algorithm shown here: <a href="https://discuss.leetcode.com/topic/15733/my-java-solution-sum-of-areas-overlapped-area" rel="nofollow">https://discuss.leetcode.com/topic/15733/my-java-solution-sum-of-areas-overlapped-area</a></p> <p>However, that algorithm only deals with finding the areas of on...
1
2016-08-20T02:37:30Z
39,050,030
<p><a href="http://toblerity.org/shapely/manual.html" rel="nofollow">Shapely</a> is a good library for stuff like this. </p> <pre><code>from shapely.geometry import box # make some rectangles (for demonstration purposes) rect1 = box(0,0,5,2) rect2 = box(0.5,0.5,3,3) rect3 = box(2.5,2.5,4,6) rect_list = [rect1, rect2...
2
2016-08-20T02:57:37Z
[ "python", "area", "rectangles" ]
Calling .recv(1024) and .send() twice, nothing happening (Python)
39,049,941
<p>I am trying to learn Socket coding right now, and I wrote a little piece of Process-to-Process communication. This is the Servercode:</p> <pre><code>import socket s = socket.socket() host = socket.gethostname() port = 17752 s.bind((host, port)) s.listen(5) while True: (client, address) = s.accept() print(a...
0
2016-08-20T02:39:30Z
39,050,401
<p>In you code each <code>connect</code> should have a matching <code>accept</code> on server side.<br> Your client <code>connect</code>s once per session, but the server <code>accept</code>s after each message, so at the point where the second <code>recv</code> is invoked the server is already trying to accept anothe...
0
2016-08-20T04:12:42Z
[ "python", "sockets", "process", "send", "recv" ]
Sublime Text 3 unable to import python module although importing from command line is possible?
39,050,042
<p>when I tried to build with python in ST3, I get an import error as I tried to do</p> <pre><code>import caffe </code></pre> <p>but when I simply ran on the terminal, typing</p> <pre><code>$ python &gt;&gt;&gt; import caffe </code></pre> <p>it works. On my sublime text 3 I still can import other modules like numpy...
1
2016-08-20T03:00:14Z
39,050,250
<p>You can add this before import caffe</p> <pre><code>import sys sys.path.insert(0, '/path_to_caffe_root/python') </code></pre>
1
2016-08-20T03:45:06Z
[ "python", "import", "sublimetext3", "sublimetext", "caffe" ]
Trigger Break Keyword Using Dictionary Python
39,050,046
<p>I'm trying to make do with Python's lack of a switch statement and make code more efficient by using a dictionary, but I can't quite get what I'm looking for. Here's a simplified version of the code I'm working with</p> <pre><code>def zero(): print("Yo") def one(): print("Hey") options = { 0: zero, ...
2
2016-08-20T03:01:13Z
39,050,056
<p>This is all you need:</p> <pre><code>while True: response = int(input("Number: ")) if response not in options: print("Not a valid response") else if response == 2: break else: options[response]() # invoke the corresponding function </code></pre> <p>Incidentally, storing fun...
0
2016-08-20T03:03:34Z
[ "python", "python-3.x", "dictionary", "switch-statement" ]
Trigger Break Keyword Using Dictionary Python
39,050,046
<p>I'm trying to make do with Python's lack of a switch statement and make code more efficient by using a dictionary, but I can't quite get what I'm looking for. Here's a simplified version of the code I'm working with</p> <pre><code>def zero(): print("Yo") def one(): print("Hey") options = { 0: zero, ...
2
2016-08-20T03:01:13Z
39,050,114
<p>There are a few ways you could do this.</p> <p>Here's a more robust version of @BingsF's clever answer (this one won't mask exceptions raised within the selected function):</p> <pre><code>class LoopBreak(Exception): pass def zero(): print("Yo") def one(): print("Hey") def two(): raise LoopBr...
1
2016-08-20T03:17:00Z
[ "python", "python-3.x", "dictionary", "switch-statement" ]
Trigger Break Keyword Using Dictionary Python
39,050,046
<p>I'm trying to make do with Python's lack of a switch statement and make code more efficient by using a dictionary, but I can't quite get what I'm looking for. Here's a simplified version of the code I'm working with</p> <pre><code>def zero(): print("Yo") def one(): print("Hey") options = { 0: zero, ...
2
2016-08-20T03:01:13Z
39,050,996
<p>You could define a <code>LoopBreak</code> exception, raise that in a <code>two</code> function, and catch it in the loop to <code>break</code>:</p> <pre><code>class LoopBreak(Exception): pass def zero(): print("Yo") def one(): print("Hey") def two(): raise LoopBreak options = { 0: zero, ...
2
2016-08-20T06:01:21Z
[ "python", "python-3.x", "dictionary", "switch-statement" ]
Writing a BytesIO object to a file, 'efficiently'
39,050,095
<p>So a quick way to write a bytesIO object to a file would be to just use:</p> <pre><code>with open('myfile.ext', 'wb') as f: f.write(myBytesIOObj.getvalue()) f.close() myBytesIOObj.close() </code></pre> <p>However, if I wanted to iterate over the myBytesIOObj as opposed to writing it in one chunk, how would I g...
1
2016-08-20T03:13:48Z
39,050,559
<p><code>shutil</code> has a utility that will write the file efficiently. It copies in chunks, defaulting to 16K. Any multiple of 4K chunks should be a good cross platform number. I chose 131072 rather arbitrarily because really the file is written to the OS cache in RAM before going to disk and the chunk size isn't t...
2
2016-08-20T04:44:26Z
[ "python", "io", "bytesio" ]
Implementing External Source Code Block in Lua
39,050,119
<p>I'm looking to write a Lua script and have it also execute something from Python source code as well, as if it went like so:</p> <pre><code>#!/bin/lua -- begin lua part print "Hello" -- begin python part Somehow_Executes_Python { print "Hello" #In python, of course } -- End Script </code></pre> <p>Getting the ...
2
2016-08-20T03:18:04Z
39,050,157
<p>There is a python-lua package called Lupa. Here's the <a href="https://pypi.python.org/pypi/lupa" rel="nofollow">documentation</a>. See if that helps.</p>
0
2016-08-20T03:24:42Z
[ "python", "lua" ]
Implementing External Source Code Block in Lua
39,050,119
<p>I'm looking to write a Lua script and have it also execute something from Python source code as well, as if it went like so:</p> <pre><code>#!/bin/lua -- begin lua part print "Hello" -- begin python part Somehow_Executes_Python { print "Hello" #In python, of course } -- End Script </code></pre> <p>Getting the ...
2
2016-08-20T03:18:04Z
39,050,254
<p>The simplest approach would be something along these lines:</p> <pre><code>#!/usr/bin/env lua local python = function(code) local file = assert(io.popen('python', 'w')) file:write(code) file:close() end -- begin lua part print "Hello from Lua" --begin python part python [=[ print "Hello from Python" ]=] ...
2
2016-08-20T03:45:52Z
[ "python", "lua" ]
How to modify/transform the column of a dataframe?
39,050,248
<p>I have an instance of <code>pyspark.sql.dataframe.DataFrame</code> created using </p> <pre><code>dataframe = sqlContext.sql("select * from table"). </code></pre> <p>One column is 'arrival_date' and contains a string. </p> <p>How do I modify this column so as to only take the first 4 characters from it and throw a...
-2
2016-08-20T03:44:39Z
39,053,815
<p>To extract first 4 characters from the <code>arrival_date</code> (StringType) column, create a <code>new_df</code> by using <code>UserDefinedFunction</code> (as you cannot modify the columns: they are immutable):</p> <pre><code>from pyspark.sql.functions import UserDefinedFunction, to_date old_df = spark.sql("SELE...
2
2016-08-20T11:51:52Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
How to modify/transform the column of a dataframe?
39,050,248
<p>I have an instance of <code>pyspark.sql.dataframe.DataFrame</code> created using </p> <pre><code>dataframe = sqlContext.sql("select * from table"). </code></pre> <p>One column is 'arrival_date' and contains a string. </p> <p>How do I modify this column so as to only take the first 4 characters from it and throw a...
-2
2016-08-20T03:44:39Z
39,065,383
<p>As stated by Orions, you can't modify a column, but you can override it. Also, you shouldn't need to create an user defined function, as there is a built-in function for extracting substrings:</p> <pre><code>from pyspark.sql.functions import * df = df.withColumn("arrival_date", df['arrival_date'].substr(0, 4)) </co...
2
2016-08-21T14:38:19Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql" ]
In python, does lock get automatically released when an exception happens?
39,050,277
<p>for example:</p> <pre><code>import threading lock = threading.Lock() with lock: some code that throws an exception </code></pre> <p>This is assuming that code that throws an exception isn't wrapped in a try except block.</p>
0
2016-08-20T03:49:34Z
39,052,041
<p>The whole point of using your lock as a context manager (<code>with lock:</code>) is for Python to notify that lock object when an exception occurs.</p> <p>So yes, the lock will unlock itself when an exception occurs because the <code>with</code> statement ensures it is notified of an exception.</p>
0
2016-08-20T08:19:28Z
[ "python", "locking" ]
Reordering rows in Python Pandas Dataframe
39,050,293
<p>I appended 3 rows to a dataframe with this code: <code>z = pandas.DataFrame.append(z, [{'Items': 'Foo'}, {'Items': 'Barr'}, {'Items': 'Options'}])</code> and got the below result:</p> <pre><code> Items Last 12 Months 0 Apple 48.674 1 Dragon Fruit 8.786 2 Milk 2.367 3 ...
1
2016-08-20T03:51:44Z
39,050,379
<p>How about <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow">reindex</a>?</p> <pre><code>In [4]: df Out[4]: Items Last 12 Months 0 Apple 48.674 1 Dragon Fruit 8.786 2 Milk 2.367 In [5]: z = pd.DataF...
1
2016-08-20T04:06:51Z
[ "python", "pandas" ]
Pandas Pivot Table formatting column names
39,050,318
<p>I used the <code>pandas.pivot_table</code> function on a pandas dataframe and my output looks like something simillar to this:</p> <pre><code> Winners Runnerup year 2016 2015 2014 2016 2015 2014 Country Sport ...
0
2016-08-20T03:55:21Z
39,050,508
<p>Try this:</p> <pre><code>df.columns=['{}_{}'.format(x,y) for x,y in zip(df.columns.get_level_values(0),df.columns.get_level_values(1))] </code></pre> <p><code>get_level_values</code> is what you need to get only one of the levels of the resulting multiindex.</p> <p>Side note: you might try working with the data a...
1
2016-08-20T04:35:29Z
[ "python", "pandas", "dataframe", "pivot-table", "data-munging" ]
Pandas Pivot Table formatting column names
39,050,318
<p>I used the <code>pandas.pivot_table</code> function on a pandas dataframe and my output looks like something simillar to this:</p> <pre><code> Winners Runnerup year 2016 2015 2014 2016 2015 2014 Country Sport ...
0
2016-08-20T03:55:21Z
39,050,811
<p>You can also use list comprehension:</p> <pre><code>df.columns = ['_'.join(col) for col in df.columns] print (df) Winners_2016 Winners_2015 Winners_2014 Runnerup_2016 \ Country Sport india badminton 1 1 ...
3
2016-08-20T05:32:16Z
[ "python", "pandas", "dataframe", "pivot-table", "data-munging" ]
Regular Expressions: Matching Song names in Python 3
39,050,359
<p>I'm currently working on a project to parse data from a music database and I'm creating a search function using regular expressions in python (version 3.5.1).</p> <p>I would like to create a regular expression to make the song names- songs without characters following the name and songs with feature details - but n...
0
2016-08-20T04:03:08Z
39,050,517
<p>Personally, I'd go with something like</p> <pre><code>^Work(?:\s+\(.+\))?$ </code></pre> <p>which will match your two provided test cases, but not the two you want to avoid. If you want to make it a but more specific regarding matching who the artist is, you can go with something like</p> <pre><code>^Work(?:\s+\(...
1
2016-08-20T04:36:58Z
[ "python", "regex", "python-3.x" ]
Balanced parentheses parser Python
39,050,372
<p>I am trying to make a balanced parentheses parser by using recursion and produce a tree.</p> <p>For example, if you pass in <code>'()()'</code> the tree would be constructed like this</p> <p>step 1</p> <pre><code> B | empty </code></pre> <p>step 2</p> <pre><code> B / | \ \ ( empty ) ...
0
2016-08-20T04:05:51Z
39,051,121
<p>I'm going to outline a second approach here, in the hopes that it provides you with some insight into why your current program isn't working. To be frank, I'm not certain what's going on - I initially thought that each right sibling indicated an additional parenthetical statement, but it seems like the tree's struct...
1
2016-08-20T06:20:29Z
[ "python" ]
Why is seconds not converting to hours and days
39,050,447
<p>I created a function to display how much time has elapsed, but for some reason the conditional statement does not return at specific statements after the first elif. Adding a print statement shows that the function is flowing however as objects are printed out. I am not sure why this is happening as the time elapsed...
0
2016-08-20T04:22:28Z
39,050,488
<p>You have a bug in the second branch.</p> <p>When you do <code>elif total_time &gt; 60 or total_time &lt;= 3600:</code> it will always pass. Since it didn't hit the first branch <code>total_time is &lt; 60</code> your time is >=60. Since you have an <code>or</code> in your second branch it will always(except for va...
1
2016-08-20T04:29:37Z
[ "python", "django", "datetime" ]
Why is seconds not converting to hours and days
39,050,447
<p>I created a function to display how much time has elapsed, but for some reason the conditional statement does not return at specific statements after the first elif. Adding a print statement shows that the function is flowing however as objects are printed out. I am not sure why this is happening as the time elapsed...
0
2016-08-20T04:22:28Z
39,050,489
<p>First up, you should fix the cases where you have gaps, such as <code>60</code> which will not be caught by <em>any</em> of the <code>if/elif</code> clauses. It should be <code>&lt; 60</code> the <code>&gt;= 60</code> in the first two condition checks.</p> <p>Additionally, all of those <code>or</code> keywords shou...
4
2016-08-20T04:30:05Z
[ "python", "django", "datetime" ]
Why is seconds not converting to hours and days
39,050,447
<p>I created a function to display how much time has elapsed, but for some reason the conditional statement does not return at specific statements after the first elif. Adding a print statement shows that the function is flowing however as objects are printed out. I am not sure why this is happening as the time elapsed...
0
2016-08-20T04:22:28Z
39,050,490
<p>You should be using <code>and</code> instead of <code>or</code> within your if statement - when it comes into the first or, it knows "yes I'm over 60 seconds", then doesn't care about the other statement because it's already hit a true. Hence, why it always displays in minutes.</p>
1
2016-08-20T04:30:07Z
[ "python", "django", "datetime" ]
Select rows where at least one value from the list of columns is not null
39,050,512
<p>I have a big dataframe with many columns (like 1000). I have a list of columns (generated by a script ~10). And I would like to select all the rows in the original dataframe where at least one of my list of columns is not null.</p> <p>So if I would know the number of my columns in advance, I could do something like...
3
2016-08-20T04:36:11Z
39,050,719
<p>Starting with this:</p> <pre><code>data = {'a' : [np.nan,0,0,0,0,0,np.nan,0,0, 0,0,0, 9,9,], 'b' : [np.nan,np.nan,1,1,1,1,1,1,1, 2,2,2, 1,7], 'c' : [np.nan,np.nan,1,1,2,2,3,3,3, 1,1,1, 1,1], 'd' : [np.nan,np.nan,7,9,6,9,7,np.nan,6, 6,7,6, 9,6]} df = pd.DataFrame(data...
1
2016-08-20T05:17:27Z
[ "python", "pandas" ]
Select rows where at least one value from the list of columns is not null
39,050,512
<p>I have a big dataframe with many columns (like 1000). I have a list of columns (generated by a script ~10). And I would like to select all the rows in the original dataframe where at least one of my list of columns is not null.</p> <p>So if I would know the number of my columns in advance, I could do something like...
3
2016-08-20T04:36:11Z
39,051,472
<p>Use the <code>thresh</code> parameter in the <code>dropna()</code> method. By setting <code>thresh=1</code>, you specify that if there is at least 1 non null item, don't drop it.</p> <pre><code>df = pd.DataFrame(np.random.choice((1., np.nan), (1000, 1000), p=(.3, .7))) list_of_cols = list(range(10)) df[list_of_co...
2
2016-08-20T07:05:13Z
[ "python", "pandas" ]
adding multiple columns to pandas simultaneously
39,050,539
<p>I'm new to pandas and trying to figure out how to add multiple columns to pandas simultaneously. Any help here is appreciated. Ideally I would like to do this in one step rather than multiple repeated steps...</p> <pre><code>import pandas as pd df = {'col_1': [0, 1, 2, 3], 'col_2': [4, 5, 6, 7]} df = pd....
2
2016-08-20T04:40:49Z
39,050,648
<p>With the use of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow">concat</a>:</p> <pre><code>In [128]: df Out[128]: col_1 col_2 0 0 4 1 1 5 2 2 6 3 3 7 In [129]: pd.concat([df, pd.DataFrame(columns = [ 'column_new_1', 'col...
1
2016-08-20T05:00:50Z
[ "python", "pandas" ]
adding multiple columns to pandas simultaneously
39,050,539
<p>I'm new to pandas and trying to figure out how to add multiple columns to pandas simultaneously. Any help here is appreciated. Ideally I would like to do this in one step rather than multiple repeated steps...</p> <pre><code>import pandas as pd df = {'col_1': [0, 1, 2, 3], 'col_2': [4, 5, 6, 7]} df = pd....
2
2016-08-20T04:40:49Z
39,050,916
<p>I agree, I would have expected your original syntax to work (I've run into that problem before). I think that doesn't work because it is ambiguous how your new data should be reproduced in your array (i.e., if <code>df</code> is 3x3, should the list of values be copied into all rows or all columns?).</p> <p>Here ar...
3
2016-08-20T05:49:15Z
[ "python", "pandas" ]
adding multiple columns to pandas simultaneously
39,050,539
<p>I'm new to pandas and trying to figure out how to add multiple columns to pandas simultaneously. Any help here is appreciated. Ideally I would like to do this in one step rather than multiple repeated steps...</p> <pre><code>import pandas as pd df = {'col_1': [0, 1, 2, 3], 'col_2': [4, 5, 6, 7]} df = pd....
2
2016-08-20T04:40:49Z
39,051,352
<p>use of list comprehension, <code>pd.DataFrame</code> and <code>pd.concat</code></p> <pre><code>pd.concat( [ df, pd.DataFrame( [[np.nan, 'dogs', 3] for _ in range(df.shape[0])], df.index, ['column_new_1', 'column_new_2','column_new_3'] ) ], axis=1) </code></pre...
1
2016-08-20T06:49:14Z
[ "python", "pandas" ]
Getting python string equivalence to work like SQL match
39,050,676
<p>I am trying to match two strings, <code>Serhat Kılıç</code> and <code>serhat kilic</code>. In SQL this is quite easy, as I can do:</p> <pre><code>select name from main_creditperson where name = 'serhat kılıç' union all select name from main_creditperson where name = 'serhat kilic'; === name Serhat Kılıç S...
0
2016-08-20T05:06:43Z
39,050,717
<p>I found this</p> <pre><code>def compare_words (str_1, str_2): return unidecode(str_1.decode('utf-8')) == str_2 </code></pre> <p>Tested on Python 2.7:</p> <pre><code>In[2]: from unidecode import unidecode In[3]: def compare_words (str_1, str_2): return unidecode(str_1.decode('utf-8')) == str_2 In[4]: pri...
0
2016-08-20T05:16:42Z
[ "python" ]
Getting python string equivalence to work like SQL match
39,050,676
<p>I am trying to match two strings, <code>Serhat Kılıç</code> and <code>serhat kilic</code>. In SQL this is quite easy, as I can do:</p> <pre><code>select name from main_creditperson where name = 'serhat kılıç' union all select name from main_creditperson where name = 'serhat kilic'; === name Serhat Kılıç S...
0
2016-08-20T05:06:43Z
39,050,884
<p>If you're OK with ASCII for everything, you can check <a href="http://stackoverflow.com/questions/816285/where-is-pythons-best-ascii-for-this-unicode-database">Where is Python&#39;s &quot;best ASCII for this Unicode&quot; database?</a> <a href="https://pypi.python.org/pypi/Unidecode" rel="nofollow"><code>Unidecode</...
1
2016-08-20T05:44:05Z
[ "python" ]
Python 3 -- range based assignment
39,050,829
<p>I have a dictionary:</p> <pre><code>BATTERY_LEVEL_TRANSFORMS = {(75, 101): "High", (30, 75): "Medium", (0, 30): "Low"} </code></pre> <p>and am trying to set a text indicator based on a battery value. Whichever key it is in the range of, the text will be assigned accordingly. Here's what I have:</p> <pre><code> ...
0
2016-08-20T05:35:22Z
39,050,974
<p>I actually think your solution is not bad. Here's my variation on it to make it a bit more readable:</p> <pre><code>BATTERY_LEVELS = ( (0, 30, 'Low'), (30, 75, 'Medium'), (75, 101, 'High'), ) def get_level_text(level): for low, high, level_text in BATTERY_LEVELS: if low &lt;= level &lt;= h...
1
2016-08-20T05:58:30Z
[ "python", "python-3.x", "range", "conditional" ]
Python 3 -- range based assignment
39,050,829
<p>I have a dictionary:</p> <pre><code>BATTERY_LEVEL_TRANSFORMS = {(75, 101): "High", (30, 75): "Medium", (0, 30): "Low"} </code></pre> <p>and am trying to set a text indicator based on a battery value. Whichever key it is in the range of, the text will be assigned accordingly. Here's what I have:</p> <pre><code> ...
0
2016-08-20T05:35:22Z
39,051,055
<p>instead using dictionary use this simple if else conditional statements.</p> <pre><code>battery_level=40;#assing battery level variable to this if(battery_level&gt;=0 and battery_level&lt;=30): battery_lable="Low"; elif(battery_level&gt;30 and battery_level&lt;=75): battery_lable="Medium"; elif(battery_leve...
-1
2016-08-20T06:11:38Z
[ "python", "python-3.x", "range", "conditional" ]
Python 3 -- range based assignment
39,050,829
<p>I have a dictionary:</p> <pre><code>BATTERY_LEVEL_TRANSFORMS = {(75, 101): "High", (30, 75): "Medium", (0, 30): "Low"} </code></pre> <p>and am trying to set a text indicator based on a battery value. Whichever key it is in the range of, the text will be assigned accordingly. Here's what I have:</p> <pre><code> ...
0
2016-08-20T05:35:22Z
39,051,076
<p>One option would be store the breakpoints between levels and level names to two sorted lists and use <a href="https://docs.python.org/2/library/bisect.html#bisect.bisect_right" rel="nofollow"><code>bisect.bisect_right</code></a> to do binary search on the breakpoints. Benefit of this approach would be that level ret...
2
2016-08-20T06:15:15Z
[ "python", "python-3.x", "range", "conditional" ]
Converting binary data to hex in python properly
39,050,836
<p>I'm working on a program that uses a BMP and a separate file for the transparency layer. I need to convert them into a PNG from that so I'm using PIL in python to do so. However, I need the data from the transparency file in hex so it can be added to the image. I am using the binascii.hexlify function to do that.</p...
2
2016-08-20T05:36:38Z
39,063,115
<p>If I understand your question correctly then your desired output should match <a href="http://i.stack.imgur.com/29Fp8.png" rel="nofollow">Data before processing in Hex editor</a>. I can obtain this with the following code:</p> <pre><code>with open('Input.alp', 'rb') as f: i = 0 for i, chunk in enumerate(it...
0
2016-08-21T10:18:28Z
[ "python", "python-2.7", "binascii" ]
Unresolved reference in Pycharm for importing modules in parent directory
39,050,845
<p>There was a similar question but not quite what I ran into so here we go:</p> <p>My directory structure:<br> ├── PycharmProjects<br> ____ ├── MyProject<br> _______ ├── main.py<br> _______ ├── ...<br> ___ ├── Tools<br> _______ ├── web.py </p> <p>To import web.py function...
0
2016-08-20T05:38:15Z
39,057,260
<p>I recommend the following, which I do, translated into your terms: put a file called, say, my_pycharm.pth into /Lib/site-packages with the following line.</p> <pre><code> &lt;drive&gt;:/path/to/PycharmProjects </code></pre> <p>This essentially appends the <em>contents</em> of /PycharmProjects to the contents of /s...
0
2016-08-20T18:07:41Z
[ "python", "ide", "pycharm", "python-idle" ]
"TypeError: Unsupported type <class 'list'> in write()"
39,050,951
<p>I wish to print 'out.csv' data in excel file when the condition is not uppercase. But the data in out.csv is list of data instead of string. How do I write the list to excel file without converting it to string? (As I have other file which may need to use list instead of string)</p> <p>Python version #3.5.1</p> <p...
3
2016-08-20T05:55:42Z
39,064,138
<blockquote> <p>How do I write the list to excel file without converting it to string</p> </blockquote> <p>You could either loop over the list and <code>write()</code> out each element or you could use the XlsxWriter <a href="http://xlsxwriter.readthedocs.io/worksheet.html#worksheet-write-row" rel="nofollow"><code>w...
0
2016-08-21T12:22:19Z
[ "python", "python-3.x", "xlsxwriter" ]
TypeError: 'connection' object is not callable in python using mysqldb
39,050,987
<pre><code>from flask import Flask from flask_restful import Resource, Api from flask_restful import reqparse from flask_mysqldb import MySQL mysql = MySQL() app = Flask(__name__) # MySQL configurations app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '' app.config['MYSQL_DB'] = 'itemlistdb' app.con...
0
2016-08-20T06:00:18Z
39,051,006
<p>Replace</p> <pre><code>conn = mysql.connect() cursor = conn.cursor() </code></pre> <p>with</p> <pre><code>conn = mysql.connection cursor = conn.cursor() </code></pre> <p>Read more at the Flask-MySQLdb’s <a href="http://flask-mysqldb.readthedocs.io/en/latest/" rel="nofollow">docs</a>.</p>
2
2016-08-20T06:03:36Z
[ "python", "mysql", "mysql-python" ]
JSON string parser without literals
39,051,049
<p>How to check if a string like this <code>{:[{},{}]}</code>, without any literals, can be represented as a JSON object or not?</p> <p>The input comes with the following constraints: 1. A JSON object should start with '{' and ends with a '}'. 2. The key and value should be separated by a ':'. 3. A ',' suggests an add...
1
2016-08-20T06:10:48Z
39,051,255
<p>The syntax spec for JSON <a href="http://www.json.org/" rel="nofollow">can be found here</a>.</p> <p>It indicates that the <code>[{},{}]</code> is legal, because <code>[]</code> has to contain 0 or more elements separated by <code>,</code>, and <code>{}</code> is a legal element. However, the first part of your exa...
2
2016-08-20T06:37:56Z
[ "python", "json", "python-2.7" ]
django retrieve multiple in query parameters
39,051,142
<p>My url has <code>http://127.0.0.1:8000/theme/category/?q=check,hello</code>, How to retrive values of query parameter</p> <p>When I try doing <code>query = request.GET.get('q')</code> I only get the <code>check</code> but <code>hello</code> is missing.</p> <p>Any help in getting both check and hello from query str...
1
2016-08-20T06:23:39Z
39,051,201
<p>You can use %2C, wich is the url-encoded value of ,.</p> <p>source : <a href="http://stackoverflow.com/questions/8359352/alternative-to-sending-comma-seperated-parameter-by-querystring">Alternative to sending comma seperated parameter by querystring</a></p>
1
2016-08-20T06:32:05Z
[ "python", "django", "query-parameters" ]
django retrieve multiple in query parameters
39,051,142
<p>My url has <code>http://127.0.0.1:8000/theme/category/?q=check,hello</code>, How to retrive values of query parameter</p> <p>When I try doing <code>query = request.GET.get('q')</code> I only get the <code>check</code> but <code>hello</code> is missing.</p> <p>Any help in getting both check and hello from query str...
1
2016-08-20T06:23:39Z
39,051,205
<p>For this urls:</p> <p><a href="http://example.com/blah/?myvar=123&amp;myvar=567" rel="nofollow">http://example.com/blah/?myvar=123&amp;myvar=567</a></p> <p>You can use <a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.QueryDict.getlist" rel="nofollow"><code>getlist()</code></a> like...
1
2016-08-20T06:32:53Z
[ "python", "django", "query-parameters" ]
How to serve media files on django production evironment?
39,051,206
<p>In me settings.py file :-</p> <pre><code>DEBUG = False BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' LOGIN_URL = '/login/' MEDIA_URL = '/media/' </code></pre> <p>In my urls.py file:-</p> <pre><code>urlpatterns += static...
2
2016-08-20T06:32:56Z
39,051,324
<p>Django is not made to serve media file in production environment. You must configure it directly from the web server.</p> <p>For example</p> <p>If you are using apache web server in production, add the below to your virtualhost configuration</p> <pre><code>Alias /media/ /path/to/media_file/ &lt;Directory /path/t...
1
2016-08-20T06:47:03Z
[ "python", "django" ]
How to serve media files on django production evironment?
39,051,206
<p>In me settings.py file :-</p> <pre><code>DEBUG = False BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' LOGIN_URL = '/login/' MEDIA_URL = '/media/' </code></pre> <p>In my urls.py file:-</p> <pre><code>urlpatterns += static...
2
2016-08-20T06:32:56Z
39,051,396
<p>You need to setup a server to serve static content on production. When only Debug is True, static content is served by Django. So you need to </p> <p>1) Setup a server</p> <p>2) Point server media path to STATIC_ROOT directory</p> <p>3) Run collectstatic command of django to collect all the static files to STATIC...
1
2016-08-20T06:55:41Z
[ "python", "django" ]
How to serve media files on django production evironment?
39,051,206
<p>In me settings.py file :-</p> <pre><code>DEBUG = False BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' LOGIN_URL = '/login/' MEDIA_URL = '/media/' </code></pre> <p>In my urls.py file:-</p> <pre><code>urlpatterns += static...
2
2016-08-20T06:32:56Z
39,051,643
<p>Django discourages to serve media files on production from the server. Use cloud services like amazon s3 to server your media files. See this <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/#serving-files-uploaded-by-a-user-during-development" rel="nofollow">Django doc serve media</a> then give th...
1
2016-08-20T07:28:07Z
[ "python", "django" ]
How to serve media files on django production evironment?
39,051,206
<p>In me settings.py file :-</p> <pre><code>DEBUG = False BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' LOGIN_URL = '/login/' MEDIA_URL = '/media/' </code></pre> <p>In my urls.py file:-</p> <pre><code>urlpatterns += static...
2
2016-08-20T06:32:56Z
39,167,220
<p>You can use S3 Amazon for static and media files. It will be better.</p> <hr> <p><strong>Problem with S3 Amazon</strong></p> <p>Making the S3 bucket appear as part of the file system has terrible performance and fails randomly. When we are copying a lot of files it can take 10, 15, or 20 minutes for the copying t...
0
2016-08-26T13:13:32Z
[ "python", "django" ]
How to trigger a signal when one widget comes within some distance/area of another widget?
39,051,247
<p>I want to create an area around a widget such that if any other widgets come in that area, the widget sends a signal. Calculating the distance between the widget and every other widget might be an option, but the problem is there might be several widgets and it might be tedious. Specifically speaking, the widget is ...
0
2016-08-20T06:37:16Z
39,067,099
<p>It seems as though you want <code>Widget1</code> to emit a signal when any other widget (e.g., <code>Widget2</code>) is moved such that it lands within the region of interest around <code>Widget1</code>. One way to do this is override the <em>moving</em> widgets' <code>moveEvent()</code> handler functions to notify ...
0
2016-08-21T17:45:09Z
[ "python", "qt", "pyqt", "widget", "position" ]
Filll in missing values in Pandas Dataframe wrong
39,051,292
<p>Suppose 'df' is dataframe object, 'ca' is one of the variables.</p> <pre><code>&gt;&gt;&gt; df.ca.value_counts() 0.0 176 1.0 65 2.0 38 3.0 20 ? 4 Name: ca, dtype: int64 </code></pre> <p>As you can see, I have four missing values. I want to fill in them. Using below code:</p> <pre><code>&gt;&...
2
2016-08-20T06:42:23Z
39,051,393
<p>Because <code>'?'</code> was one of your values, I know that <code>df.ca</code> is either <code>dtype</code> <code>object</code> or <code>string</code>. When you <code>replace('?', 0.)</code> you now have both string <code>'0.0'</code> and float <code>0.0</code>. After you convert all to float, you shouldn't have ...
1
2016-08-20T06:55:18Z
[ "python", "pandas", "dataframe" ]
Filll in missing values in Pandas Dataframe wrong
39,051,292
<p>Suppose 'df' is dataframe object, 'ca' is one of the variables.</p> <pre><code>&gt;&gt;&gt; df.ca.value_counts() 0.0 176 1.0 65 2.0 38 3.0 20 ? 4 Name: ca, dtype: int64 </code></pre> <p>As you can see, I have four missing values. I want to fill in them. Using below code:</p> <pre><code>&gt;&...
2
2016-08-20T06:42:23Z
39,051,421
<p>The following pretty much works too:</p> <pre><code>In [193]: df = pd.DataFrame({'ca': [0.0]*176 + [1.0]*65 + [2.0]*38 + [3.0]*20 + ['?']*4}) In [194]: df.ca.value_counts() Out[194]: 0.0 176 1.0 65 2.0 38 3.0 20 ? 4 Name: ca, dtype: int64 In [195]: df.loc[df.ca == '?', 'ca'] = 0.0 In [196]...
0
2016-08-20T06:57:33Z
[ "python", "pandas", "dataframe" ]
split a line of data with a constraint
39,051,433
<p>When I need to split a line of data I get following result:</p> <pre><code>&gt;&gt;&gt; s="MS Dhoni cricket captain 10000" &gt;&gt;&gt; val=s.split() &gt;&gt;&gt; print val ['MS', 'Dhoni', 'cricket', 'captain', '10000'] </code></pre> <p>But I expect code in the below manner:</p> <pre><code>['MS Dhoni', 'cricket',...
-1
2016-08-20T07:00:30Z
39,051,463
<p>That code does what you want</p> <pre><code>import re s="MS Dhoni cricket captain 10000" print(re.split("\s(?=[a-z0-9])",s)) </code></pre> <p>output:</p> <pre><code>['MS Dhoni', 'cricket', 'captain', '10000'] </code></pre> <p>Explanation: split according to spaces, but only if followed by a lowercase letter or...
2
2016-08-20T07:03:50Z
[ "python", "split" ]
SSIM / MS-SSIM for TensorFlow
39,051,451
<p>Is there a <strong>SSIM</strong> or even <strong>MS-SSIM</strong> implementation for <strong>TensorFlow</strong>? </p> <p>SSIM (<em>structural similarity index metric</em>) is a metric to measure image quality or similarity of images. It is inspired by human perception and according to a couple of papers, it is a m...
2
2016-08-20T07:02:34Z
39,053,516
<p>After a deep dive into some other python implemention, I could finally implement a running example in TensorFlow:</p> <pre><code>import tensorflow as tf import numpy as np def _tf_fspecial_gauss(size, sigma): """Function to mimic the 'fspecial' gaussian MATLAB function """ x_data, y_data = np.mgrid[-si...
3
2016-08-20T11:17:43Z
[ "python", "tensorflow", "metrics", "ssim" ]
how to download a file from s3 bucket with a temporary token in python
39,051,581
<p>I have a django web app and I want to allow it to download files from my s3 bucket. The files are not public. I have an IAM policy to access them. The problem is that I do <strong>NOT</strong> want to download the file on the django app server and then serve it to download on the client. That is like downloading twi...
0
2016-08-20T07:18:11Z
39,051,646
<p>With Boto (2), it should be really easy to generate time-limited download URLs, should your IAM policy have the proper permissions. I am using this approach to serve videos to logged-in users from private S3 bucket.</p> <pre><code>from boto.s3.connection import S3Connection conn = S3Connection('&lt;aws access key&g...
2
2016-08-20T07:28:17Z
[ "python", "amazon-s3" ]
Sending voice input from frontend (html) to backend
39,051,619
<p>I am trying to record voice from Chrome browser and have it sent to backend for converting it to text. I tried following articles:</p> <ol> <li><p><a href="http://codesamplez.com/programming/html5-web-speech-api" rel="nofollow">http://codesamplez.com/programming/html5-web-speech-api</a></p></li> <li><p><a href="htt...
-1
2016-08-20T07:24:11Z
39,056,903
<p>I could do it after following 2nd link in question. I sent post request to the same handle and it could grab it. Thanks.</p>
0
2016-08-20T17:26:40Z
[ "python", "html5", "browser", "flask" ]
How to pipe multi-line JSON Objects into separate python invocations
39,051,621
<p>I know the basics of piping stdin to downstream processes in the shell and as long as each line is treated individually, or as one single input, I can get my pipelines to work.</p> <p>But when I want to read 4 lines of stdin, do some processing, read 6 more lines, and do the same, my limited of understanding of pip...
0
2016-08-20T07:24:32Z
39,051,915
<p>I believe this approach would accomplish what you want. First, save your python script in a file, <code>my_script.py</code> for example. Then do the following:</p> <pre><code>cat geocodes.txt \ | xargs -I% sh -c "curl -s 'http://maps.googleapis.com/maps/api/geocode/json?latlng='%'&amp;sensor=true' | python my_sc...
1
2016-08-20T08:04:58Z
[ "python", "json", "node.js", "stdin", "xargs" ]
How to pipe multi-line JSON Objects into separate python invocations
39,051,621
<p>I know the basics of piping stdin to downstream processes in the shell and as long as each line is treated individually, or as one single input, I can get my pipelines to work.</p> <p>But when I want to read 4 lines of stdin, do some processing, read 6 more lines, and do the same, my limited of understanding of pip...
0
2016-08-20T07:24:32Z
39,059,856
<p>Have a look at:</p> <p><a href="http://trentm.com/json/#FEATURE-Grouping" rel="nofollow">http://trentm.com/json/#FEATURE-Grouping</a></p> <pre><code>Grouping can be helpful for "one JSON object per line" formats or for things such as: $ cat *.json | json -g ... </code></pre> <p>To install:</p> <pre><code>sudo n...
0
2016-08-21T00:27:41Z
[ "python", "json", "node.js", "stdin", "xargs" ]
How to pipe multi-line JSON Objects into separate python invocations
39,051,621
<p>I know the basics of piping stdin to downstream processes in the shell and as long as each line is treated individually, or as one single input, I can get my pipelines to work.</p> <p>But when I want to read 4 lines of stdin, do some processing, read 6 more lines, and do the same, my limited of understanding of pip...
0
2016-08-20T07:24:32Z
39,060,758
<p>You don't need python or node.js. <code>jq</code> is designed specifically for json filtering UNIX style:</p> <pre><code>sudo apt-get install jq </code></pre> <p>Then:</p> <pre><code>cat geocodes.txt \ | xargs -I% curl -s 'http://maps.googleapis.com/maps/api/geocode/json?latlng='%'&amp;sensor=true' \ | jq ...
0
2016-08-21T04:06:34Z
[ "python", "json", "node.js", "stdin", "xargs" ]
Probelm with py2neo and flask query
39,051,685
<p>I have issue in my application, I am trying to run a code in flask with py2neo. I have latest version of NEO4j and python2.7</p> <p>Here is my code for fucntion in USER class</p> <pre><code>class User: def __init__(self, username): self.username = username def find(self): user = gra...
0
2016-08-20T07:34:47Z
39,093,818
<p>In python 2.7 and py2neo version 3, we can not use query like this, we need to query like this one</p> <pre><code>selector = NodeSelector(graph) selected_user = selector.select("User", username=user) selected_prize = selector.select("Prize", pid=prize) selected_cat = selector.sel...
0
2016-08-23T06:27:55Z
[ "python", "flask", "neo4j", "py2neo" ]
django model create does not work
39,051,752
<p>I added a new model to my app named SocialProfile, which is responsible for keeping social-related properties of a user which has a one-to-one relationship with UserProfile model. This is the SocialProfile model in models.py:</p> <pre><code>class SocialProfile(models.Model): profile = models.OneToOneField('User...
1
2016-08-20T07:43:03Z
39,051,940
<p>You've overwritten the save method so that it never actually saves anything. You need to call the superclass method at the end:</p> <pre><code>def save(self, *args, **kwargs): if not self.pk: ... return super(SocialProfile, self).save(*args, **kwargs) </code></pre>
1
2016-08-20T08:07:26Z
[ "python", "django", "django-models" ]
Python Tornado Web Service Cron Restart How?
39,051,824
<p>Fail Code:</p> <pre><code>root = os.path.dirname(__file__) static_application = tornado.web.Application([ (r"/(.*)", tornado.web.StaticFileHandler, {"path": root, "default_filename": "Example.html"}) ]) if __name__ == "__main__": print "Starting Server..." static_application.listen(8080) torna...
0
2016-08-20T07:51:32Z
39,057,303
<p>Ok - so it turns out -> I was not patient enough... </p> <p>The above code, cron, html, javascript, and iptables all work flawlessly to achieve a server restart with tornado on port 8080 on an amazon web server. </p> <p>Epic celebration ensues</p>
0
2016-08-20T18:13:13Z
[ "python", "cron", "tornado", "iptables" ]
Deploying Flask in Openshift
39,051,871
<p>The following codes are working without any problem in my system's localhost... But ain't doing the job on OpenShift.. There is something wrong with my <strong>wsgi.py</strong>.. Do I have to pass my username and password using environment variables OR I've need to change the <em>localhost</em> ? </p> <p>The follo...
1
2016-08-20T07:58:56Z
39,054,128
<p>Yes, you do need to use Openshift's environment variables to set up the IP and port. </p> <p>Try adding in the below code to setup the proper IP and port depending if you are on OS or localhost. </p> <pre><code>Import os if 'OPENSHIFT_APP_NAME' in os.environ: #are we on OPENSHIFT? ip = os.environ...
0
2016-08-20T12:25:49Z
[ "python", "flask", "openshift", "pymongo", "wsgi" ]
Pygame--pygame can't run a pingpong collision game
39,051,973
<pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import pygame import sys class MyBallClass(pygame.sprite.Sprite): def __init__(self, image_file, speed, location): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(image_file) self.rect = self.image.get_rect() s...
3
2016-08-20T08:11:40Z
39,056,224
<p>I could rebuild your game, and fixed the problem.</p> <p>Try inverse condition here</p> <pre><code>if myball.rect.top &gt;= screen.get_rect().bottom: </code></pre> <p>and it works fine: I can hit the ball with the bat, make it bounce, ...</p> <p>I don't know why it took me so long ot figure it out: you lose the ...
1
2016-08-20T16:11:09Z
[ "python", "pygame" ]
Kivy--Plyer--Android--sending notification while app is not running
39,052,054
<p>I am writing a python app in kivy.</p> <p>the idea is to allow the user to make let the user make notes of bookings for certain dates, and then the program should send them a notification on that day about the booking.</p> <p>Theres probably a simple way to do this, I am using plyer.</p> <pre><code>from plyer imp...
10
2016-08-20T08:21:49Z
39,202,531
<p>I think you should take a look at the <a href="https://developer.android.com/reference/android/app/AlarmManager.html" rel="nofollow">Android AlarmManager</a>. If this is what you need, <a href="http://cheparev.com/kivy-receipt-notifications-and-service/" rel="nofollow">here</a> is an example for Kivy.</p> <blockquo...
1
2016-08-29T09:15:28Z
[ "android", "python", "notifications", "kivy" ]
Why doesn't this method, redefined at runtime, retain its value?
39,052,084
<p>I'm stuck on something I suspect is quite simple, but I just can't wrap my head around it. I'm trying to create a class with a method that can be redefined on the fly. I want to be able to do this for an arbitrary number of instances, but I'm only showing two here in order to keep things simple.</p> <p>Here is a MW...
1
2016-08-20T08:25:28Z
39,052,133
<p>It changes because you are modifying the <code>x</code> and <code>y</code> global variables, which are referred to by the <code>f</code> function you defined:</p> <pre><code>In [2]: a, b = Foo(3), Foo(5) In [3]: print(a.f(1), b.f(1)) 0 0 In [4]: x, y = a, b ...: x.f = lambda t: f(x, y, t) ...: print(a.f(1)...
0
2016-08-20T08:31:17Z
[ "python", "python-3.x", "global-variables" ]
upgrade scipy in redhat
39,052,087
<p>I'm trying to upgrade scipy on Redhat 6.7 using pip to local folder:</p> <pre><code>pip install --user --upgrade scipy </code></pre> <p>However, the following error pop out:</p> <pre><code>You are using pip version 7.1.0, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upg...
1
2016-08-20T08:25:35Z
39,052,195
<p>RedHat 6.7 comes with Python 2.6 and that is no longer supported by the latest version of numpy/scipy. Apart from that, on Linux, you should not mix packages installed with the package manager (using <code>yum</code>, <code>dnf</code>, <code>apt-get</code>, etc.) with packages installed from PyPI using <code>pip</co...
0
2016-08-20T08:38:41Z
[ "python", "scipy", "pip" ]
Serve from /tmp on Heroku with Cherrypy
39,052,097
<p>My site writes new <code>.html</code> files into <code>/tmp</code> after the dyno is created. The <code>cherrypy</code> app is in <code>/app</code> due to the Heroku's structure.</p> <p>This prevents me from routing the <code>.html</code> files created with Cherrypy. Any idea on how to do this?</p>
-2
2016-08-20T08:27:04Z
39,056,121
<p>Heroku's <a href="https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem" rel="nofollow">filesystem is ephemeral</a>:</p> <blockquote> <p>Each dyno gets its own ephemeral filesystem, with a fresh copy of the most recently deployed code. During the dyno’s lifetime its running processes can use the file...
2
2016-08-20T16:01:07Z
[ "python", "heroku", "cherrypy" ]
Modify code to capture values greater than - instead of exact match
39,052,132
<p>The following code works well for identifying whether a value is hit or missed over following rows and giving the output column showing the time the condition was met.</p> <pre><code>import datetime,numpy as np,pandas as pd; nan = np.nan; a = pd.DataFrame( {'price': {datetime.time(9, 0): 1, datetime.time(10, 0)...
4
2016-08-20T08:31:04Z
39,053,138
<p>Without modifying your code heavily, this is what I came up with:</p> <pre><code>import numpy as np for row,hit in hits.iterrows(): print ("row", row) print ("hit",hit) forwardRows = a[a.index.values &gt; row] targetHit = forwardRows[(hit['target1'] &lt;= forwardRows['price'].valu...
0
2016-08-20T10:36:45Z
[ "python", "pandas" ]
Modify code to capture values greater than - instead of exact match
39,052,132
<p>The following code works well for identifying whether a value is hit or missed over following rows and giving the output column showing the time the condition was met.</p> <pre><code>import datetime,numpy as np,pandas as pd; nan = np.nan; a = pd.DataFrame( {'price': {datetime.time(9, 0): 1, datetime.time(10, 0)...
4
2016-08-20T08:31:04Z
39,054,755
<p>Some ifs and thats all :D... </p> <pre><code>import datetime,numpy as np,pandas as pd; nan = np.nan; a = pd.DataFrame( {'price': {datetime.time(9, 0): 1, datetime.time(10, 0): 0, datetime.time(11, 0): 3, datetime.time(12, 0): 4, datetime.time(13, 0): 7, datetime.time(14, 0): 6, datetime.time(15, 0): 5...
1
2016-08-20T13:37:10Z
[ "python", "pandas" ]
grep No such file or directory with envoy.run
39,052,191
<p>I try to build script that execute some grep search in my logs and print the results. I try to use Envoy because is more easy than subprocess but when I execute grep command it gives me back an error of no such file o directory.</p> <p>The dir structure is easy:</p> <ul> <li>. # root of script</li> <li>test.py # s...
3
2016-08-20T08:38:25Z
39,066,853
<p>Why it works in terminal but not in envoy is related to globbing (<a href="http://www.tldp.org/LDP/abs/html/globbingref.html" rel="nofollow">bash example</a>).</p> <p>When you run in your terminal </p> <pre><code>grep 'cv=2' ./web_logs/log/log_* </code></pre> <p>bash will parse the command line and replace the st...
1
2016-08-21T17:19:42Z
[ "python", "grep", "envoy" ]
grep No such file or directory with envoy.run
39,052,191
<p>I try to build script that execute some grep search in my logs and print the results. I try to use Envoy because is more easy than subprocess but when I execute grep command it gives me back an error of no such file o directory.</p> <p>The dir structure is easy:</p> <ul> <li>. # root of script</li> <li>test.py # s...
3
2016-08-20T08:38:25Z
39,066,988
<p>@baptistemm is actually right in that since you're not running bash as part of your process the globbing is not working.</p> <p>However what's happening is a bit deeper.</p> <p>When you run a sub process it can be done by one of several system services (system calls).</p> <h1>Short Answer (TLDR;)</h1> <p>Here's...
1
2016-08-21T17:34:06Z
[ "python", "grep", "envoy" ]
Breaking out of a for loop inside of python string join() Method
39,052,197
<p>My code is :</p> <pre><code>maxlimit = 5 mystring = ' \r\n '.join([('' if (idx &gt;= maxlimit) else str(name)) for idx,name in enumerate(queryset)]) </code></pre> <p>How can I to break out of the for loop inside of <code>join()</code> method if <code>idx >= maxlimit</code> ?</p>
1
2016-08-20T08:38:48Z
39,052,276
<p>Well, you should use the <code>if</code> condition in the list comprehension instead:</p> <pre><code>mystring = ' \r\n '.join([str(name) for idx, name in enumerate(queryset) if idx &lt; maxlimit]) </code></pre> <p>This generates a list of 5 items only.</p> <p>But then it is easier to ju...
3
2016-08-20T08:51:12Z
[ "python", "string", "for-loop", "join", "break" ]
Bypassing conditions
39,052,321
<p>Can anybody understand why the following code fails?</p> <pre><code>def main(A): A.sort() B = A[:] ll = len(B) while ll &gt; 1: for i in range(ll): for n in range(i + 1, ll): if (B[i] + B[n]) % 2 == 0: B.remove(B[n]) B.remo...
-1
2016-08-20T08:57:26Z
39,052,368
<p>You are using recursion, calling <code>main(B)</code> again in the loop. When the recursive call returns, the loop from which you called it <em>continues on</em>.</p> <p>Moreover, you ignore the return value of the recursive calls. Since you use a <em>copy</em> of the list in each invocation of <code>main()</code>,...
1
2016-08-20T09:03:48Z
[ "python", "python-3.x", "if-statement", "while-loop" ]
Show if restaurant is open or not in current time and day
39,052,502
<p>I have two model one for restaurant and another for operating time. Operating time has foreign key relation with restaurant as operating time might be different in different days in a week. I wanted to show if the restaurant is open or closed in current time and in the current day. Will it be better to code this in ...
1
2016-08-20T09:23:57Z
39,052,578
<p>I'm working with django at my work place for about a month now and have been taught to not put any logic into the views. The view should be only to pass on the data from the database or post data to the database. The logic should be done in template tags. </p>
0
2016-08-20T09:33:45Z
[ "python", "django", "python-3.x", "django-models", "django-views" ]
How to write new pooling layer in TensorFlow?
39,052,545
<p>I'd like to write RMS pooling layer in TensorFlow. This is like <code>tf.nn.avg_pool()</code> but instead of doing simple average it should calculate RMS average.</p> <p>I'd like to write this using numpy initially; I don't care about it running on GPU (but later I would like to write a GPU version)</p>
0
2016-08-20T09:29:49Z
39,060,493
<p>Try</p> <pre><code>tf.sqrt(tf.nn.avg_pool(tf.square(value - \ tf.reduce_mean(value, reduction_indices=[0, 1, 2])), &lt;ksize&gt;, &lt;strides&gt;, &lt;padding&gt;)) </code></pre> <p>Note that l_2 pooling is commonly used and not RMS pooling.</p>
1
2016-08-21T03:03:23Z
[ "python", "neural-network", "tensorflow" ]
Django IntegrityError: no default value
39,052,606
<p>There is a longer SQL query that I need to run to migrate data from one table to another. It worked fine all the way up to this week when I migrated to Django 1.9.2 and Python 3.5. </p> <p>The problem is that the table has a field 'last_update' that is NULL by default. The table definition is</p> <pre><code>last_u...
1
2016-08-20T09:37:17Z
39,056,251
<p><code>updated = models.DateTimeField(default=None, auto_now=True, auto_now_add=False)</code></p> <p>this should work. i have used this before and it is working fine for me.</p>
0
2016-08-20T16:15:02Z
[ "python", "mysql", "django", "django-orm" ]
Django IntegrityError: no default value
39,052,606
<p>There is a longer SQL query that I need to run to migrate data from one table to another. It worked fine all the way up to this week when I migrated to Django 1.9.2 and Python 3.5. </p> <p>The problem is that the table has a field 'last_update' that is NULL by default. The table definition is</p> <pre><code>last_u...
1
2016-08-20T09:37:17Z
39,064,759
<p>I ended up modifying the table a few times. I didn't try the suggestion from Rohit, as the default=None. It started working again, after using multiple DB migrations.</p>
0
2016-08-21T13:33:05Z
[ "python", "mysql", "django", "django-orm" ]
python regression on time series
39,052,643
<p>I have a matrix containing 8 time series. </p> <p>I want to build a model between their values at time <code>t</code> and their values at time <code>t-1, t-2,..., t-k</code>.</p> <p>Let suppose for simplicity a linear model <code>sk.linear_model.LinearRegression</code> and the time series be: <code>X=np.random.nor...
-1
2016-08-20T09:41:29Z
39,058,255
<p>The short answer is that if you want to do serious time-series analysis with Python, you should probably use a specific libaray like <a href="http://statsmodels.sourceforge.net/stable/tsa.html" rel="nofollow">statsmodels.tsa</a>.</p> <p>However, if you are insistent on using sklearn, you're going to need to set up ...
0
2016-08-20T20:06:52Z
[ "python", "scikit-learn", "time-series" ]
Select from given level of MultiIndex Series
39,052,813
<p>How can I select all values where the 'displacement' (second level of MultiIndex) is above a certain value, say > 2?</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np dicts = {} index = np.linspace(1, 50) index[2] = 2.0 # Create a duplicate for later testing for n in range(5)...
0
2016-08-20T10:00:30Z
39,053,155
<pre><code>import pandas as pd import numpy as np dicts = {} index = np.linspace(1, 50) for n in range(5): dicts['test' + str(n)] = pd.Series(np.linspace(0, 20) ** (n / 5), index=index) s = pd.concat(dicts, names=('test', 'displacement')) displacement = s.index.get_level_...
0
2016-08-20T10:38:06Z
[ "python", "pandas" ]
python - regex on "°F" or "°C", and "-40" like symbols
39,052,991
<p>In python I am trying replace a text file in the following way:</p> <blockquote> <p>İmparatorluk zirvesini 15 ve 17'nin arasında, özelikle I. Süleyman döneminde 10.000'lerde yaşadı.</p> </blockquote> <p>-></p> <blockquote> <p>"İmparatorluk" "zirvesini" "15" "ve" "17'nin" "arasında", "özelikle" "...
0
2016-08-20T10:19:16Z
39,053,953
<p>Regex: <code>^|$|</code> will match the start of the string, the end of the string, or single spaces. You can use that to split the string, then join it with the necessary quotes.</p> <p>Here's the code I'd use for JavaScript; I hope you can figure out how to do the same in python.</p> <pre><code>"\"" + string.spl...
1
2016-08-20T12:07:31Z
[ "python", "regex" ]
Filtering and Ordering based on multiple request.GET parameters
39,053,048
<p>I'm currently stuck in trying to find a solution to my problem. So I have a URL which is like so: </p> <p><code>https://www.domain.com/forum/topic/</code></p> <p>In my template view, I have a form and an input which is responsible for searching for posts:</p> <pre><code>&lt;form method="GET" action=""&gt; &lt...
0
2016-08-20T10:27:44Z
39,053,386
<p>You need to keep track of your <code>GET</code> params, update your view to be:</p> <pre><code>def discussion(request, discussion): # &lt;&lt;- view name and var name both are same which might cause issues search_query = request.GET.get('q', '') sort = request.GET.get('sort', '') direction = request.GET...
1
2016-08-20T11:03:46Z
[ "python", "django", "sorting" ]
3d image compression with numpy
39,053,195
<p>I have a 3d numpy array representing an object with cells as voxels and the voxels having values from 1 to 10. I would like to compress the image (a) to make it smaller and (b) to get a quick idea later on of how complex the image is by compressing it to a minimum level of agreement with the original image.</p> <p>...
2
2016-08-20T10:42:33Z
39,056,212
<p>You could essentially apply the same principle to the 3D data without flattening it. There are some algorithms to separate N-dimensional matrices, such as the CP-ALS (using Alternating Least Squares) and this is implemented in the package <a href="https://github.com/mnick/scikit-tensor" rel="nofollow">sktensor</a>. ...
1
2016-08-20T16:10:14Z
[ "python", "arrays", "numpy", "compression", "svd" ]
Python redis client zrangebylex
39,053,223
<p>I want to perform the following command using the python client of redis</p> <pre><code>zrangebylex names_sorted_set [a "[a\xff\xff\xff\xff" </code></pre> <p>but in my code the following cases happen</p> <pre><code> name = request.GET.get('name', '') redis_con = redis.StrictRedis(settings.REDIS_HOST, setti...
0
2016-08-20T10:44:41Z
39,053,495
<p>this one worked</p> <pre><code> name = request.GET.get('name', '') redis_con = redis.StrictRedis(settings.REDIS_HOST, settings.REDIS_PORT) min = '[' + name max = bytearray('[') + \ bytearray(name, 'utf-8') + \ b'\xff\xff\xff\xff\xff\xff\xff\xff\xff' result = redis_con.zrangeby...
0
2016-08-20T11:15:32Z
[ "python", "redis", "sortedset" ]
How to solve ValueError: Index contains duplicate entries, cannot reshape
39,053,226
<p>I'm trying to unstack a MultiIndex Series so that I can plot the Series against one another.</p> <pre><code>import pandas as pd import numpy as np dicts = {} index = np.linspace(1, 50) index[2] = 2.0 index2 = index.copy() index2[3] = 3.0 for n in range(5): if n == 1: dicts['test' + str(n)] = pd.Serie...
1
2016-08-20T10:44:58Z
39,068,669
<p>You can set <code>append=True</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>DF.set_index</code></a> so that it avoids the default writing entries all over again during <code>unstack</code> operation. It only adds the entries not present...
0
2016-08-21T20:41:07Z
[ "python", "pandas", "matplotlib", "seaborn" ]
ValueError: AES key must be either 16, 24, or 32 bytes long PyCrypto 2.7a1
39,053,286
<p>I'm making programm for my school project and have one problem above. Here's my code:</p> <pre><code>def aes(): #aes os.system('cls') print('1. Encrypt') print('2. Decrypt') c = input('Your choice:') if int(c) == 1: #cipher os.system('cls') print("Let's encrypt, alr...
-1
2016-08-20T10:51:39Z
39,053,407
<p>The error is very clear. The key must be exactly of that size. <code>os.urandom</code> will return you the correct key. However this key is a <em>bytes</em> (binary string value). Furthermore, by using <code>str(secret)</code>, the value of <code>repr(secret)</code> is written into the file instead of <code>secret</...
3
2016-08-20T11:06:44Z
[ "python", "python-3.x", "cryptography", "pycrypto" ]
pandas groupby with a lambda parameter
39,053,348
<p>I can't understand the code:</p> <pre><code>pivot = pd.pivot_table(subset, values='count', rows=['date'], cols=['sample'], fill_value=0) by = lambda x: lambda y: getattr(y, x) grouped = pivot.groupby([by('year'),by('month')]).sum() </code></pre> <p><code>subset</code> in the code is a DataFrame which have a colu...
0
2016-08-20T10:58:53Z
39,056,523
<p>If a callable is passed to <code>groupby</code>, it is called on the <code>DataFrame</code>'s index, so this code is is grouping by the year and month of a datetimelike index.</p> <pre><code>In [55]: df = pd.DataFrame({'a': 1.0}, index=pd.date_range('2014-01-01', periods=13, freq='M')) ...
1
2016-08-20T16:46:24Z
[ "python", "pandas", "lambda" ]
recursive import in python
39,053,360
<p>in logging.py in my python library there are the lines:</p> <pre><code>import logging </code></pre> <p>and:</p> <pre><code>from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL </code></pre> <p>I don't understand the meaning of importing logging within logging.py and also where (DEBUG, INFO, WARNING, ERROR,...
-1
2016-08-20T11:00:27Z
39,053,405
<p>it's importing <code>logging</code> from python standard library, <a href="https://docs.python.org/2/library/logging.html" rel="nofollow">link</a>, </p> <p>also <a href="https://docs.python.org/2/library/logging.html#logging-levels" rel="nofollow">here</a> is log levels in that page (DEBUG, INFO, ...)</p>
0
2016-08-20T11:06:29Z
[ "python", "python-2.7", "import" ]
recursive import in python
39,053,360
<p>in logging.py in my python library there are the lines:</p> <pre><code>import logging </code></pre> <p>and:</p> <pre><code>from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL </code></pre> <p>I don't understand the meaning of importing logging within logging.py and also where (DEBUG, INFO, WARNING, ERROR,...
-1
2016-08-20T11:00:27Z
39,053,441
<p>It looks like someone has messed up the imports a little bit? :)</p> <p>In general, if you do</p> <p><code>import &lt;module&gt;</code></p> <p>You can refer to <em>all</em> its methods and objects as</p> <p><code>&lt;module&gt;.&lt;method&gt;</code></p> <p>Whereas if you do e.g,</p> <p><code>import &lt;method1...
0
2016-08-20T11:10:37Z
[ "python", "python-2.7", "import" ]
LCM of large numbers in python
39,053,393
<p>I'm using the formula "product of two number is equal to the product of their GCD and LCM".</p> <p>Here's my code :</p> <pre><code># Uses python3 import sys def hcf(x, y): while(y): x, y = y, x % y return x a,b = map(int,sys.stdin.readline().split()) res=int(((a*b)/hcf(a,b))) print(res) </cod...
0
2016-08-20T11:04:26Z
39,054,602
<p>Elaborating on the comments. In Python 3, true division, <code>/</code>, converts its arguments to floats. In your example, the true answer of <code>lcm(226553150, 1023473145)</code> is <code>46374212988031350</code>. By looking at <code>bin(46374212988031350)</code> you can verify that this is a 56 bit number. When...
1
2016-08-20T13:20:15Z
[ "python", "python-3.x", "math", "greatest-common-divisor", "lcm" ]