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 |
|---|---|---|---|---|---|---|---|---|---|
Mix three vectors in a numpy array, then sort it | 38,156,241 | <p>I have 3 numpy.ndarray vectors, X, Y and intensity. I would like to mix it in an numpy array, then sort by the third column (or the first one). I tried the following code:</p>
<pre><code>m=np.column_stack((X,Y))
m=np.column_stack((m,intensity))
m=np.sort(m,axis=2)
</code></pre>
<p>Then I got the error: ValueError:... | 0 | 2016-07-02T03:37:58Z | 38,156,516 | <p>You are getting that error because you don't have an axis with a 2 index. Axes are zero-indexed. Regardless, np.sort will sort <strong>every</strong> column, or <strong>every</strong> row. Consider from the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html" rel="nofollow">docs</a>:</p>
<b... | 0 | 2016-07-02T04:33:09Z | [
"python",
"sorting",
"numpy"
] |
looking to # 50 being a win using edge case | 38,156,258 | <p>I have a small game and I would like 50 to produce a win but still keep the code as is how would use an edge case</p>
<pre><code>import random
roll = input('Press Enter to Spin the Wheel or Type Stop!')
while roll == "":
prize = random.randint(0, 100)
print ('Youre number is ', prize )
if prize < ... | 0 | 2016-07-02T03:42:16Z | 38,156,325 | <p>You should check if <code>prize</code> is <strong>equal to</strong> 50:</p>
<pre><code>if prize == 50:
print ('Congratulations! Youre a winner!')
else:
print ('Sorry, you didnt win. Try again')
</code></pre>
| 0 | 2016-07-02T03:53:40Z | [
"python"
] |
looking to # 50 being a win using edge case | 38,156,258 | <p>I have a small game and I would like 50 to produce a win but still keep the code as is how would use an edge case</p>
<pre><code>import random
roll = input('Press Enter to Spin the Wheel or Type Stop!')
while roll == "":
prize = random.randint(0, 100)
print ('Youre number is ', prize )
if prize < ... | 0 | 2016-07-02T03:42:16Z | 38,156,476 | <p>Your conditions are checking for numbers strictly greater and strictly less than 50. You need to change one of them be less strict and allow 50 to count as well:</p>
<pre><code>if prize < 50:
print ('Sorry, you didnt win. Try again')
if prize >= 50: # use >= to test if prize is greater th... | 1 | 2016-07-02T04:25:39Z | [
"python"
] |
Getting 'av_interleaved_write_frame(): Broken pipe' error | 38,156,265 | <p>I am trying this blog post.I am new to python, numpy as well as FFMPEG. I could not figure out what causes this issue.</p>
<p><a href="http://zulko.github.io/blog/2013/09/27/read-and-write-video-frames-in-python-using-ffmpeg/" rel="nofollow">http://zulko.github.io/blog/2013/09/27/read-and-write-video-frames-in-pyth... | 1 | 2016-07-02T03:43:14Z | 38,158,153 | <p>It is a programming error as this <a href="http://stackoverflow.com/questions/803265/getting-realtime-output-using-subprocess">answer</a> suggests. FFMPEG tries to write to stout after stout is closed because python program finished running. a while loop solved this problem.</p>
<pre><code>while true:
#for line in ... | 0 | 2016-07-02T08:31:15Z | [
"python",
"python-2.7",
"numpy",
"ffmpeg",
"video-streaming"
] |
How should I refer to class variables in Python? | 38,156,284 | <p>In Python I can refer to a class level variable with either <code>ClassName.class_var</code> or <code>self.class_var</code> from within a class. Now as long as I do not override the class level variables name within an object by creating an instance variable of the same name (which I find would be kind out silly), t... | 2 | 2016-07-02T03:45:49Z | 38,156,346 | <p>If you have only the one class and you only read the variable, you won't see a lot of difference.</p>
<p>If you take into account the possibility of subclasses that override <code>class_var</code>, then <code>self.class_var</code> will look in the current class first while <code>Foo.class_var</code> will continue t... | 4 | 2016-07-02T03:59:26Z | [
"python",
"class",
"variables"
] |
How should I refer to class variables in Python? | 38,156,284 | <p>In Python I can refer to a class level variable with either <code>ClassName.class_var</code> or <code>self.class_var</code> from within a class. Now as long as I do not override the class level variables name within an object by creating an instance variable of the same name (which I find would be kind out silly), t... | 2 | 2016-07-02T03:45:49Z | 38,156,418 | <p>The problem with using <code>Foo.class_var</code> from your example is in inheritance. You can see it illustrated here, beginning with your Foo() class:</p>
<pre><code>class Bar(Foo):
class_var = ['other','one','here']
In [2]: a = Foo(['one'])
In [3]: b = Bar(['one'])
In [4]: a.class_var
Out[4]: ['same', 'f... | 0 | 2016-07-02T04:16:08Z | [
"python",
"class",
"variables"
] |
reading text file and putting some characters in lists | 38,156,361 | <p>My objective is to transform this text in a textfile (all in 1 line):</p>
<pre><code>a b s d p
5 4 3 3 2
..........
....pp..s.
........s.
.a......s.
.a.....b..
.a.....b..
.a.....b..
.a.ddd.b..
..........
..........
</code></pre>
<p>And have an output: [['a', 'b', 's', 'd', 'p'],[5, 4, 3, 3, 2]]
But I get the follo... | 0 | 2016-07-02T04:03:56Z | 38,156,492 | <p>Right now, you are looping infinitely on the first character and appending it to your list. Your while loop will never stop since <code>'a' != '.'</code> will always be true.</p>
<p>If you just want the 2 first lines and the format will never change, you should use something simpler:</p>
<pre><code>def read_ship_d... | 0 | 2016-07-02T04:29:25Z | [
"python",
"list",
"text-files"
] |
reading text file and putting some characters in lists | 38,156,361 | <p>My objective is to transform this text in a textfile (all in 1 line):</p>
<pre><code>a b s d p
5 4 3 3 2
..........
....pp..s.
........s.
.a......s.
.a.....b..
.a.....b..
.a.....b..
.a.ddd.b..
..........
..........
</code></pre>
<p>And have an output: [['a', 'b', 's', 'd', 'p'],[5, 4, 3, 3, 2]]
But I get the follo... | 0 | 2016-07-02T04:03:56Z | 38,156,496 | <p>You're looping forever:</p>
<pre><code>for char in line:
while char != '.':
if char.isalpha():
ship_characters.append(str(char))
elif char.isnumeric():
ship_sizes.append(int(char))
</code></pre>
<p>You set the value of <code>char</code> for one iteration through <code>li... | 0 | 2016-07-02T04:29:58Z | [
"python",
"list",
"text-files"
] |
reading text file and putting some characters in lists | 38,156,361 | <p>My objective is to transform this text in a textfile (all in 1 line):</p>
<pre><code>a b s d p
5 4 3 3 2
..........
....pp..s.
........s.
.a......s.
.a.....b..
.a.....b..
.a.....b..
.a.ddd.b..
..........
..........
</code></pre>
<p>And have an output: [['a', 'b', 's', 'd', 'p'],[5, 4, 3, 3, 2]]
But I get the follo... | 0 | 2016-07-02T04:03:56Z | 38,156,578 | <p>Others have identified the reason for the memory error: an infinite loop.</p>
<p>Assuming that you require the first 2 lines from the file here is a better way to do it:</p>
<pre><code>def read_ship_data(game_file):
with open(game_file) as game_file:
return [line.split() for line in (next(game_file), n... | 0 | 2016-07-02T04:47:35Z | [
"python",
"list",
"text-files"
] |
Having trouble installing pip for Windows 10 on python 2.7 | 38,156,362 | <p>I have had lots of trouble downloading pip. I went and download the get-pip.py. I saved it to my desktop and ran the file. A window appeared for about 1.5 seconds and then disappears. I then tried to run the file through the python command line, I gave the command "python get-pip.py" and then I got:</p>
<p>Error:</... | 0 | 2016-07-02T04:04:09Z | 38,157,127 | <p>Are you using the correct version of pip? It's hard to figure out without more information, but you could be using the python 3 version of pip.</p>
<p>Easiest way: Install py2.7.9 with pip included.</p>
<p><a href="https://docs.python.org/2/installing/" rel="nofollow">https://docs.python.org/2/installing/</a></p>
| 0 | 2016-07-02T06:15:47Z | [
"python",
"pip"
] |
Date difference between consecutive rows - Pyspark Dataframe | 38,156,367 | <p>I have a table with following structure</p>
<pre><code>USER_ID Tweet_ID Date
1 1001 Thu Aug 05 19:11:39 +0000 2010
1 6022 Mon Aug 09 17:51:19 +0000 2010
1 1041 Sun Aug 19 11:10:09 +0000 2010
2 9483 Mon Jan 11 10:51:23 +0000 ... | 1 | 2016-07-02T04:04:50Z | 38,159,608 | <p>Like this:</p>
<pre><code>df.registerTempTable("df")
sqlContext.sql("""
SELECT *, CAST(date AS bigint) - CAST(lag(date, 1) OVER (
PARTITION BY user_id ORDER BY date) AS bigint)
FROM df""")
</code></pre>
| 1 | 2016-07-02T11:25:47Z | [
"python",
"apache-spark",
"pyspark",
"pyspark-sql"
] |
How do you insert a list in a sqlite3 database | 38,156,661 | <p>I only know how to enter strings and numbers, but is there a way to enter a list? Basically, I have a dictionary and each key is being put into the database. The value to each key is a list and I want this in the database as well. </p>
| 1 | 2016-07-02T05:03:43Z | 38,156,696 | <p>SQLite3 does not have array data type. (See <a href="https://www.sqlite.org/datatype3.html" rel="nofollow">Datatypes in SQLite version 3</a>)</p>
<p>But, you can serialize to insert it to sqlite3 table.</p>
<p>For example, you can convert the list into json string, and use the string to insert into the table. (<a ... | 1 | 2016-07-02T05:10:26Z | [
"python",
"sqlite3"
] |
How do you insert a list in a sqlite3 database | 38,156,661 | <p>I only know how to enter strings and numbers, but is there a way to enter a list? Basically, I have a dictionary and each key is being put into the database. The value to each key is a list and I want this in the database as well. </p>
| 1 | 2016-07-02T05:03:43Z | 38,156,759 | <p>With sqlite3 I was able to execute this script that drops a database and rewrites it with new data using a list named <code>data</code>. This may or may not answer your specific question:</p>
<pre><code>from views import db
from config import DATABASE_PATH
import sqlite3
from datetime import datetime
with sqlite3... | 0 | 2016-07-02T05:19:20Z | [
"python",
"sqlite3"
] |
Re-arrange the array contain endpoints to creat an closed polygon in Python | 38,156,689 | <p>For some purpose, I want to plot an polygon based on several latitude and longitude as endpoints which combined together. </p>
<p>The example data shows like this: </p>
<pre><code>fig=plt.figure()
ax = plt.gca()
x_map1, x_map2 = 114.166,114.996
y_map1, y_map2 = 37.798,38.378
map = Basemap(llcrnrlon=x_map1,llcrn... | -1 | 2016-07-02T05:09:11Z | 38,156,826 | <p>Not an answer yet, but I needed the ability to attach images.</p>
<p>The problem may be ill defined. For example, these two legitimate polygons have the same vertices.</p>
<p><a href="http://i.stack.imgur.com/h2aJe.png" rel="nofollow"><img src="http://i.stack.imgur.com/h2aJe.png" alt="polygon 1"></a>
<a href="http... | 1 | 2016-07-02T05:30:47Z | [
"python",
"matplotlib",
"gis",
"polygon",
"matplotlib-basemap"
] |
Re-arrange the array contain endpoints to creat an closed polygon in Python | 38,156,689 | <p>For some purpose, I want to plot an polygon based on several latitude and longitude as endpoints which combined together. </p>
<p>The example data shows like this: </p>
<pre><code>fig=plt.figure()
ax = plt.gca()
x_map1, x_map2 = 114.166,114.996
y_map1, y_map2 = 37.798,38.378
map = Basemap(llcrnrlon=x_map1,llcrn... | -1 | 2016-07-02T05:09:11Z | 38,164,896 | <p>Here is a way to solve what you want by linear algebra. Sorry but I am writing just the general guidelines. Nonetheless it should work.</p>
<ol>
<li>Write a function that accept two edges numbers j and k and check if there is an intersection. Note that you need to handle correctly the last to first vertices edge. Y... | 1 | 2016-07-02T22:15:04Z | [
"python",
"matplotlib",
"gis",
"polygon",
"matplotlib-basemap"
] |
How do I lock a python (.py) file for editing? | 38,156,726 | <p>I wrote an automation program which logs in to a website to perform a certain task. The .py file will be given to a number of users but I don't want them to be able to read the code and see the password used for logging in. How do I make sure that they can only execute the file but not read it?</p>
| 0 | 2016-07-02T05:14:21Z | 38,156,746 | <p>You can't do it. If you give a password to your users, no matter how much you try to hide it, it's always possible to find it out.</p>
<p>You can make it slightly more difficult to find out with encryption and obfuscation, but that only stops non-tech-savvy users. And those users probably wouldn't think to read thr... | 1 | 2016-07-02T05:17:02Z | [
"python",
"python-3.x",
"passwords",
"password-protection"
] |
How do I lock a python (.py) file for editing? | 38,156,726 | <p>I wrote an automation program which logs in to a website to perform a certain task. The .py file will be given to a number of users but I don't want them to be able to read the code and see the password used for logging in. How do I make sure that they can only execute the file but not read it?</p>
| 0 | 2016-07-02T05:14:21Z | 38,156,753 | <p>That is not possible. A Python file is simply a text file; to execute it, you need to be able to read it.</p>
<p>A good practice in these cases is to use environment variables (see <a href="http://andrewtorkbaker.com/using-environment-variables-with-django-settings" rel="nofollow">here</a> for an example). You can ... | 0 | 2016-07-02T05:18:17Z | [
"python",
"python-3.x",
"passwords",
"password-protection"
] |
How do I lock a python (.py) file for editing? | 38,156,726 | <p>I wrote an automation program which logs in to a website to perform a certain task. The .py file will be given to a number of users but I don't want them to be able to read the code and see the password used for logging in. How do I make sure that they can only execute the file but not read it?</p>
| 0 | 2016-07-02T05:14:21Z | 38,156,927 | <p>One possibility is to have a daemon (service) running which holds the password. That would be running under a restricted user to which normal security has been applied. The users should not be able to access anything under the daemon's user.</p>
<p>Users have a python program which communicates a login request to... | 0 | 2016-07-02T05:44:20Z | [
"python",
"python-3.x",
"passwords",
"password-protection"
] |
How do I lock a python (.py) file for editing? | 38,156,726 | <p>I wrote an automation program which logs in to a website to perform a certain task. The .py file will be given to a number of users but I don't want them to be able to read the code and see the password used for logging in. How do I make sure that they can only execute the file but not read it?</p>
| 0 | 2016-07-02T05:14:21Z | 38,157,983 | <p>Best way to do that would be as @cdarke offered, but a faster way would be to store the .py file in a hidden, password-protected folder.</p>
| 0 | 2016-07-02T08:09:38Z | [
"python",
"python-3.x",
"passwords",
"password-protection"
] |
Set the position of radio button and entry in same column but the result was not allign | 38,156,735 | <p>I was setting the position of my entry to be at the same row as the text"Specific Location" by using Grid Geometry Manager,but the final result turns out to be like <a href="http://i.stack.imgur.com/bugf0.jpg" rel="nofollow">this</a>.I just want to know why the position will not according to the setting and the ways... | 1 | 2016-07-02T05:15:57Z | 38,156,898 | <p>You need to draw location_ent inside the same container widget <code>self.radioframe</code> that holds the radiobuttons. This means you need to change:</p>
<p><code>location_ent =Entry(root)</code> </p>
<p><strong>to:</strong></p>
<p><code>location_ent =Entry(self.radioframe)</code>.</p>
<p><strong>Demo</strong>... | 1 | 2016-07-02T05:41:02Z | [
"python",
"tkinter",
"grid",
"geometry",
"entry"
] |
`mkvirtualenv` doesn't work after install anaconda Python | 38,156,805 | <p>Before I installed <code>anaconda</code>, I usually start project with <code>virtualenvwrapper</code> :</p>
<pre><code>mkvirtualenv --python=python3.5 myproject
workon pystagram myproject
</code></pre>
<p>where <code>which python3.5</code> shows, </p>
<pre><code>>> /usr/local/bin/python3.5
</code></pre>
<p... | 0 | 2016-07-02T05:27:16Z | 40,097,717 | <p>I had the same problem with my previous setup of virtualenv and virtualenvwrapper after installing Anaconda/iPython. The way I managed to get it to work is to activate only one at a time not both. The changes I made when I need virtualenv or virtualenvwrapper:</p>
<ol>
<li><p>edit .bash_profile<br>
<code>nano ~/.... | 0 | 2016-10-18T00:33:13Z | [
"python",
"virtualenv",
"anaconda",
"jupyter"
] |
opencv-python object detection | 38,156,827 | <p>I'm a beginner in opencv using python. I have many 16 bit gray scale images and need to detect the same object every time in the different images. Tried template matching in opencv python but needed to take different templates for different images which could be not desirable. Can any one suggest me any algorithm in... | 0 | 2016-07-02T05:30:48Z | 38,158,929 | <p>Your question is way too general. Feature matching is a very vast field.
The type of algorithm to be used totally depends on the object you want to detect, its environment etc.</p>
<p>So if your object won't change its size or angle in the image then use Template Matching.</p>
<p>If the image will change its size ... | 0 | 2016-07-02T10:06:13Z | [
"python",
"python-2.7",
"opencv"
] |
opencv-python object detection | 38,156,827 | <p>I'm a beginner in opencv using python. I have many 16 bit gray scale images and need to detect the same object every time in the different images. Tried template matching in opencv python but needed to take different templates for different images which could be not desirable. Can any one suggest me any algorithm in... | 0 | 2016-07-02T05:30:48Z | 38,674,476 | <p>u can try out sliding window method. if ur object is the same in all samples</p>
| 0 | 2016-07-30T13:30:47Z | [
"python",
"python-2.7",
"opencv"
] |
Need help passing data from one function to another | 38,156,858 | <p>I'm trying to pass the data from the accumulator variable "points" in the pyramid function to the statistics function. The way I tried doing just passes the original value of "points," which is 0. Also I want statistics to receive that and run separately from the pyramid function. The way it is now, the process t... | 0 | 2016-07-02T05:34:15Z | 38,157,758 | <p>A quick hack(but not the suggested way to do it) to make it work would be declare the variable <code>points</code> global inside the function <code>pyramid()</code></p>
<p>So it would become</p>
<pre><code>global points = 0
# and so on
</code></pre>
| 0 | 2016-07-02T07:37:22Z | [
"python",
"python-3.x"
] |
Need help passing data from one function to another | 38,156,858 | <p>I'm trying to pass the data from the accumulator variable "points" in the pyramid function to the statistics function. The way I tried doing just passes the original value of "points," which is 0. Also I want statistics to receive that and run separately from the pyramid function. The way it is now, the process t... | 0 | 2016-07-02T05:34:15Z | 38,159,115 | <p>So down below is pretty much your code provided just reworked into separate functions to remove duplicated code.</p>
<p>Now in the code below I have commented out lines of code and given them a number, these are the options you can ( but no limited to ) take. Depending on which method you choose comment out the lin... | 1 | 2016-07-02T10:31:03Z | [
"python",
"python-3.x"
] |
Check if a collection of edges forms a loop | 38,156,864 | <p>I'm looking for the best code to check if a collection of edges forms a closed loop.</p>
<p>The input data is an array of edges, with each edge (= line segment) being defined by it's two endpoints. For example: <code>[[1,2],[2,3],[3,4],[4,1]]</code> represents 4 edges: the first connecting point <code>1</code> with... | 0 | 2016-07-02T05:35:06Z | 38,156,904 | <p>The best way to go about this might be to create an array of big size (max edge coordinate size) where all values are initially -1. When you get an edge of the form [a,b], set array[a] = b. When trying to find out if its a loop, start at any index where value is not -1 and follow the value. So, from array[a]= b, you... | 0 | 2016-07-02T05:41:30Z | [
"python",
"mesh"
] |
Check if a collection of edges forms a loop | 38,156,864 | <p>I'm looking for the best code to check if a collection of edges forms a closed loop.</p>
<p>The input data is an array of edges, with each edge (= line segment) being defined by it's two endpoints. For example: <code>[[1,2],[2,3],[3,4],[4,1]]</code> represents 4 edges: the first connecting point <code>1</code> with... | 0 | 2016-07-02T05:35:06Z | 38,165,578 | <p>The following process would test if there are cycles. </p>
<p>Consider the dictionary with keys as the vertexes and the values as the list of vertexes adjacent to it. From [ [1,2],[2,3],[3,4],[4,1]] you have {1:[2,4],2:[1,3],3:[2,4],4:[1,3]}.</p>
<p>Process each vertex from the list of keys.
Find the first ve... | 0 | 2016-07-03T00:11:18Z | [
"python",
"mesh"
] |
Check if a collection of edges forms a loop | 38,156,864 | <p>I'm looking for the best code to check if a collection of edges forms a closed loop.</p>
<p>The input data is an array of edges, with each edge (= line segment) being defined by it's two endpoints. For example: <code>[[1,2],[2,3],[3,4],[4,1]]</code> represents 4 edges: the first connecting point <code>1</code> with... | 0 | 2016-07-02T05:35:06Z | 38,167,030 | <p>Here's an approach that uses NetworkX:</p>
<pre><code>import networkx as nx
edges = [[1,2], [2,3], [3,4], [4,1]]
g = nx.Graph()
g.add_edges_from(edges)
try:
cycle = nx.find_cycle(g)
cycle = set(map(frozenset, cycle))
edges = set(map(frozenset, edges))
if cycle == edges:
print("The edges fo... | 0 | 2016-07-03T05:28:20Z | [
"python",
"mesh"
] |
Bing Congitive Web Search API with Python 3 | 38,156,881 | <p>Hi Stackoverflow Community</p>
<p>I am attempting to access the new Bing Cognitive Search API through a Python 3 script. I was able to find threats on using Bing Search 2.0 (since depreciated) but wasn't able to identify an example for the new API with Python 3. I used the following code:</p>
<pre><code>import url... | 0 | 2016-07-02T05:38:07Z | 38,157,084 | <p>The authentication is not through basic auth but through custom header <code>Ocp-Apim-Subscription-Key</code>:</p>
<blockquote>
<p>Subscription key which provides access to this API.</p>
</blockquote>
<p>Which can be found in your <a href="https://www.microsoft.com/cognitive-services/en-US/subscriptions" rel="no... | 2 | 2016-07-02T06:08:59Z | [
"python",
"python-3.x",
"urllib",
"bing"
] |
Replace all occurrences that match regular expression | 38,156,956 | <p>I have a regular expression that searches for a string that contains <code>'.00.'</code> or <code>'.11.'</code> as follows:</p>
<pre><code>.*\.(00|11)\..*
</code></pre>
<p>What I would like to do is replace all occurrences that match the pattern with <code>'X00X'</code> or <code>'X11X'</code>. For example, the str... | 1 | 2016-07-02T05:47:51Z | 38,156,978 | <p><code>re.sub()</code> does replace all matches it finds, but your use of <code>.*</code> may have caused the regex to match too much (even other occurences of <code>.00.</code> etc.). Simply do:</p>
<pre><code>In [2]: re.sub(r"\.(00|11)\.", r"X\1X", ".00..0..11.")
Out[2]: 'X00X.0.X11X'
</code></pre>
<p>Note that p... | 2 | 2016-07-02T05:53:20Z | [
"python",
"regex"
] |
Pandas: cannot import name adjoin | 38,156,965 | <p>From Wes: </p>
<pre><code>def side_by_side(*objs, **kwds):
from pandas.core.common import adjoin
space = kwds.get('space', 4)
reprs = [repr(obj).split('\n') for obj in objs]
print adjoin(space, *reprs)
</code></pre>
<p>Apply below: </p>
<pre><code> import pandas as pd
df1 = pd.DataFrame(np.ran... | 1 | 2016-07-02T05:50:22Z | 38,157,370 | <p>I guess this function has been moved to <code>pandas.formats.printing</code>:</p>
<pre><code>In [69]: from pandas.formats.printing import adjoin
</code></pre>
| 1 | 2016-07-02T06:50:38Z | [
"python",
"pandas",
"pretty-print"
] |
OpenCv technique for recognising relationship between objects | 38,156,973 | <p>I am new to OpenCV but trying to solve the following problem:</p>
<p>Each "sprite" in the target images looks the same but the way they are arranged will differ:</p>
<p><a href="http://i.stack.imgur.com/xhGqi.png" rel="nofollow"><img src="http://i.stack.imgur.com/xhGqi.png" alt="Problem"></a></p>
<p>For now I am ... | 1 | 2016-07-02T05:52:19Z | 38,158,225 | <p>There are Two simple steps to solve this without using haar cascades.</p>
<ol>
<li><p>Binarize the image and apply findContours function on the image through which you can uniquely identify each sprite from this you could possibly find the no of sprite.</p></li>
<li><p>Now apply boundingRect function on the contour... | 1 | 2016-07-02T08:42:51Z | [
"python",
"opencv"
] |
OpenCv technique for recognising relationship between objects | 38,156,973 | <p>I am new to OpenCV but trying to solve the following problem:</p>
<p>Each "sprite" in the target images looks the same but the way they are arranged will differ:</p>
<p><a href="http://i.stack.imgur.com/xhGqi.png" rel="nofollow"><img src="http://i.stack.imgur.com/xhGqi.png" alt="Problem"></a></p>
<p>For now I am ... | 1 | 2016-07-02T05:52:19Z | 38,183,142 | <p>Sorry for taking such a long time.</p>
<p>As I mentioned earlier I didn't use boundingRect function. Rather I used another method to find the boundary of the sprite. I will explain the code below</p>
<p>Initially I've cropped the images as</p>
<p><a href="http://i.stack.imgur.com/541Jt.png" rel="nofollow"><img sr... | 1 | 2016-07-04T11:03:01Z | [
"python",
"opencv"
] |
For loop not iterating | 38,156,995 | <p>I am completely stumped on this bug. I'm trying to pull all of the menu items from this page <a href="https://www.alloresto.fr/restaurant-livraison-a-domicile/restaurant/pizza-mia/angers-centre-ville/particuliers/carte" rel="nofollow">https://www.alloresto.fr/restaurant-livraison-a-domicile/restaurant/pizza-mia/ange... | 0 | 2016-07-02T05:56:15Z | 38,157,199 | <p>get_menu(self,response) is a generator, as it makes use of the yield statement. </p>
<p>When a generator function is called, it returns a generator object, without beginning execution of the function. For your code to run, you need to use get_menu(self,response) either within a âforâ loop or by passing it to an... | 1 | 2016-07-02T06:26:41Z | [
"python",
"scrapy"
] |
Including a binary with a python module, is it good practice to do this? | 38,157,061 | <p>I am trying to write my first python module that can be easily distributed and installed on different machines (hopefully by just cloning the repository and running setup.py). The problem is that my module has a dependency on a small binary file; I am using the Selenium module as one of my dependencies and it needs ... | 3 | 2016-07-02T06:04:40Z | 38,170,185 | <p>Based on ivan_pozdeev and dmitryro's comments, this is the solution I have come up with at the moment:</p>
<p>Within my project directory is a folder bin/ with the subfolders linux32/, linux64/, mac32/, win32/. Inside each of those subfolders is the appropriate executable (chromedriver / cromedriver.exe).</p>
<p>I... | 1 | 2016-07-03T13:01:34Z | [
"python",
"module",
"packages",
"executable"
] |
Python multiprocessing for processes which are started separately | 38,157,142 | <p>Is ist possible somehow to use queues for proceses which are started comopletely separately (e.g. from command shell). In such cases multiprocessing package doesn't word, because the new process must be passed the queue in advance.</p>
| 0 | 2016-07-02T06:17:31Z | 38,157,201 | <p><a href="http://python-rq.org/" rel="nofollow">http://python-rq.org/</a> is your simplest option - considering you have or install Redis. </p>
| 0 | 2016-07-02T06:27:01Z | [
"python",
"queue"
] |
How to set a Django filter to select all | 38,157,157 | <p>I have a view in Django that will read a get request and its parameters and make a query based on the parameters. Currently my view looks like this:</p>
<pre><code>def getInventory(request):
c = request.GET.get('category', '')
g = request.GET.get('gender', '')
s = request.GET.get('size', '')
availa... | 0 | 2016-07-02T06:20:34Z | 38,157,214 | <p>You need to apply a filter only if you want to filter something. You could do something like this:</p>
<pre><code># Start off with a base queryset
available = Item.objects.all()
allowed_filters = ['category', 'gender', 'size']
for f in allowed_filters:
if request.GET.get(f):
available = available.filte... | 3 | 2016-07-02T06:28:53Z | [
"python",
"django"
] |
Parse a file - regex in python | 38,157,161 | <p>I want to export to a new txt file a list of URLs from another txt file.
The first txt file looks like this :</p>
<blockquote>
<p><a href="http://pastebin.com/raw/10hvUbTi" rel="nofollow">http://pastebin.com/raw/10hvUbTi</a> Emails: 631 Keywords: 0.0</p>
<p><a href="http://pastebin.com/raw/5f0bnCq9" rel="nof... | -1 | 2016-07-02T06:20:47Z | 38,157,329 | <p>You did not use regular expression at all. You merely tested whether the raw string is in the line or not. To use regex,</p>
<pre><code>pattern = re.compile(r'^\S*')
</code></pre>
<p>notice the <code>r</code> before pattern string there, it stands for raw string and is very important in regex.</p>
<p>To search fo... | 0 | 2016-07-02T06:45:33Z | [
"python",
"regex"
] |
Parse a file - regex in python | 38,157,161 | <p>I want to export to a new txt file a list of URLs from another txt file.
The first txt file looks like this :</p>
<blockquote>
<p><a href="http://pastebin.com/raw/10hvUbTi" rel="nofollow">http://pastebin.com/raw/10hvUbTi</a> Emails: 631 Keywords: 0.0</p>
<p><a href="http://pastebin.com/raw/5f0bnCq9" rel="nof... | -1 | 2016-07-02T06:20:47Z | 38,158,059 | <p>You could go for:</p>
<pre><code>import re
rx = re.compile(r'^(?P<email>[^|\n]+)', re.MULTILINE)
with open("emails.txt") as f:
raw_data = f.read()
emails = [match.group('email') for match in rx.finditer(raw_data)]
print emails
</code></pre>
<p>Obviously, <code>emails.txt</code> needs to be adjus... | 0 | 2016-07-02T08:19:45Z | [
"python",
"regex"
] |
Fortran gemm function on C-contiguous matrices | 38,157,215 | <p>I'm trying to do matrix multiplication using the fortran BLAS <code>gemm</code> function, see <a href="https://software.intel.com/en-us/node/468480" rel="nofollow">here</a>.</p>
<p>The signature of this function is, all the parameters' meaning could be found in the above link.</p>
<pre><code>call sgemm(transa, tra... | 3 | 2016-07-02T06:28:59Z | 38,157,257 | <p>If you want to use row-major matrix instead of Fortran style col-major, you could use the CBLAS API gemm. You can choose matrix storage layout with the first parameter. </p>
<p><a href="https://software.intel.com/en-us/node/520775" rel="nofollow">https://software.intel.com/en-us/node/520775</a></p>
<hr>
<p>Or yo... | 2 | 2016-07-02T06:35:29Z | [
"python",
"c",
"fortran",
"matrix-multiplication",
"blas"
] |
How to create dates using datetime based on day of the week? | 38,157,292 | <p>I want to write a block of code using <code>datetime</code> so that if <code>datetime.now()</code> is saturday or friday after 4pm, create a datetime object for 4pm on the friday which passed.</p>
<p>I have the following completed:</p>
<pre><code>from datetime import datetime
datenow = datetime.now()
if datenow.i... | 4 | 2016-07-02T06:40:20Z | 38,157,655 | <p>Try this:</p>
<pre><code>from datetime import timedelta
def mod_time(datenow):
if datenow.isoweekday() in [6,7]:#for Saturday or Sunday
print datenow
datenow -= timedelta(days=datenow.isoweekday()-5) #Going back to Friday
print datenow
datenow = datenow.replace(hour=16,minute=0,second=0,microseco... | 0 | 2016-07-02T07:25:27Z | [
"python",
"date",
"datetime"
] |
How to create dates using datetime based on day of the week? | 38,157,292 | <p>I want to write a block of code using <code>datetime</code> so that if <code>datetime.now()</code> is saturday or friday after 4pm, create a datetime object for 4pm on the friday which passed.</p>
<p>I have the following completed:</p>
<pre><code>from datetime import datetime
datenow = datetime.now()
if datenow.i... | 4 | 2016-07-02T06:40:20Z | 38,158,360 | <p>Full solution:</p>
<pre><code>def set_prev_iso_week_day(val, iso_week_day):
"""
Set ISO week day.
New date will be less or equal than input date.
:param val: datetime or date
:type val: datetime.datetime | datetime.date
:param iso_week_day: ISO week day to set
:type iso_week_day: int
... | 0 | 2016-07-02T08:59:45Z | [
"python",
"date",
"datetime"
] |
Doing columns with a for loop on a nested list | 38,157,295 | <p>I'm trying to get:</p>
<pre><code> 1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59... | 3 | 2016-07-02T06:40:54Z | 38,157,353 | <p>You can just use nested loops to print chunks out like that. Here's an example:</p>
<pre><code>for i in chunks:
for j in i:
print(j, end=" ")
print()
</code></pre>
| 1 | 2016-07-02T06:48:49Z | [
"python"
] |
Doing columns with a for loop on a nested list | 38,157,295 | <p>I'm trying to get:</p>
<pre><code> 1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59... | 3 | 2016-07-02T06:40:54Z | 38,157,426 | <p>This should produce exactly the same output as in the question:</p>
<pre><code>for chunk in chunks:
print(''.join(str(x).rjust(5 if i else 2) for i, x in enumerate(chunk)))
</code></pre>
<p><strong>Update:</strong> For every chunk it will first convert numbers to strings with <code>str</code> and then right ju... | 1 | 2016-07-02T06:57:36Z | [
"python"
] |
Doing columns with a for loop on a nested list | 38,157,295 | <p>I'm trying to get:</p>
<pre><code> 1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59... | 3 | 2016-07-02T06:40:54Z | 38,157,542 | <p>You can get the desired output using list comprehensions as below:</p>
<pre><code>print "\n".join([" ".join(format(j,'3d') for j in range(i,i+10)) for i in range(1,101,10)])
</code></pre>
<p>It formats the output using <code>format</code> and the list is joined using <code>str.join</code> function to produce the r... | 0 | 2016-07-02T07:12:37Z | [
"python"
] |
Sum django generated table values with JavaScript | 38,157,576 | <p>I have a table which is populated by a django for loop below. I have added some JavaScript to sum/add all the totals in the asset.by_item_weight column.</p>
<p>For some reason I am not getting the value returned in the totalCol td.</p>
<p>I have put the script tag at the bottom of this .html in the hope that the d... | 1 | 2016-07-02T07:17:26Z | 38,157,890 | <ul>
<li>Why do you iterate over <code>#sum_table td.totalCol</code> while you have only one?</li>
<li>Why do you prefill your array with a bunch of zeros?</li>
<li>Why do you use an array at all?</li>
</ul>
<p>Your code should rather look like this:</p>
<pre><code>var total = 0;
$('#sum_table tr td.rowDataSd').each(... | 1 | 2016-07-02T07:56:00Z | [
"javascript",
"jquery",
"python",
"html",
"django"
] |
Django _view_() takes 1 positional argument but 2 were given | 38,157,673 | <p>I have faced a problem with my django project.
It is as following: I had a simple regexp to match the users</p>
<pre><code>url(r'^users/\w+/$', views.user)
</code></pre>
<p>And it worked perfectly.</p>
<p>Then I changed the regexpt, because there was an update in users' logins, so now it is (I added the dot symb... | 0 | 2016-07-02T07:27:46Z | 38,157,695 | <p>As stated in the error message, your view needs to take a second parameter:</p>
<pre><code>def user(request, second_param):
return render(request, 'home/user_page.html')
</code></pre>
<p>This is because you added a group in the regex (the part between parenthesis) and Django passes any matched group as argumen... | 4 | 2016-07-02T07:30:39Z | [
"python",
"django"
] |
Split dataset into proportional subsets using numpy | 38,157,810 | <p>I wonder if there is function like this:</p>
<pre><code>my_fun(my_list, *arg)
</code></pre>
<ul>
<li>where arg is list or proportion</li>
<li>every element of *arg is float value between 0 and 1</li>
<li>sum of arg elements must <=1</li>
</ul>
<p>For example:</p>
<pre><code>my_list = ['a','b','c','d','f',1, 2... | 1 | 2016-07-02T07:44:10Z | 38,158,862 | <p>you could do something like:</p>
<pre><code>a = np.arange(100)
b = np.array([0.4, 0.4, 0.1])
for i in range(1, len(b)):
b[i] += b[i-1]
c = np.split(np.random.permutation(a), (b * len(a) + 0.5).astype(np.int))
</code></pre>
| 0 | 2016-07-02T10:00:06Z | [
"python",
"numpy"
] |
Split dataset into proportional subsets using numpy | 38,157,810 | <p>I wonder if there is function like this:</p>
<pre><code>my_fun(my_list, *arg)
</code></pre>
<ul>
<li>where arg is list or proportion</li>
<li>every element of *arg is float value between 0 and 1</li>
<li>sum of arg elements must <=1</li>
</ul>
<p>For example:</p>
<pre><code>my_list = ['a','b','c','d','f',1, 2... | 1 | 2016-07-02T07:44:10Z | 38,159,023 | <p>There seems to be no ready solution, but this would work:</p>
<pre><code>import numpy as np
def split_by_ratio(arr, *ratios):
arr = np.random.permutation(arr)
ind = np.add.accumulate(np.array(ratios) * len(arr)).astype(int)
return [x.tolist() for x in np.split(arr, ind)][:len(ratios)]
</code></pre>
<p... | 0 | 2016-07-02T10:18:52Z | [
"python",
"numpy"
] |
Assign a name to a tensor? | 38,157,831 | <p>Is there any way to assign a name to a tensor after it has been created?</p>
<p>I'm building up a neural network bit by bit in a loop, like so:</p>
<pre><code> def build_logit_pipeline(data):
# X --> *W1 --> +b1 --> relu --> *W2 --> +b2 ... --> softmax etc...
pipeline = data
... | 0 | 2016-07-02T07:47:08Z | 38,160,115 | <p>You cannot modify the name of a Tensor. </p>
<p>However, one easy trick to do what you want is to use <code>tf.identity</code> with the name you want:</p>
<pre><code>res = build_logit_pipeline(data)
res = tf.identity(res, name="your_name")
</code></pre>
| 1 | 2016-07-02T12:23:47Z | [
"python",
"tensorflow"
] |
How to implement mini-batch gradient descent in python? | 38,157,972 | <p>I have just started to learn deep learning. I found myself stuck when it came to gradient descent. I know how to implement batch gradient descent. I know how it works as well how mini-batch and stochastic gradient descent works in theory. But really can't understand how to implement in code.</p>
<pre><code>import n... | -1 | 2016-07-02T08:07:48Z | 38,176,770 | <p>This function returns the mini-batches given the inputs and targets:</p>
<pre><code>def iterate_minibatches(inputs, targets, batchsize, shuffle=False):
assert inputs.shape[0] == targets.shape[0]
if shuffle:
indices = np.arange(inputs.shape[0])
np.random.shuffle(indices)
for start_idx in ... | 0 | 2016-07-04T04:00:39Z | [
"python",
"machine-learning",
"neural-network",
"deep-learning",
"gradient-descent"
] |
How to improving a dictionary self-search comparison and merger | 38,158,150 | <p>I need to compare a dictionary to values to find all the values that match and add them out. The problem is that I have really large dictionaries and my code is really slow. Is there a better way to do this or to improve my code timing? </p>
<pre><code>import itertools
import copy
Dic = {
0: ['-1','A','B','p'... | 0 | 2016-07-02T08:30:50Z | 38,158,522 | <p>Okay, I have tried to understand your code and it seems that you are doing the equivalent of the following, which I hope is simpler, clearer and at least a bit more efficient:</p>
<pre><code>import itertools as it
def sign_to_num(val):
if val == '+':
return 1
elif val == '-':
return -1
... | 0 | 2016-07-02T09:19:20Z | [
"python",
"performance",
"dictionary",
"time"
] |
How to improving a dictionary self-search comparison and merger | 38,158,150 | <p>I need to compare a dictionary to values to find all the values that match and add them out. The problem is that I have really large dictionaries and my code is really slow. Is there a better way to do this or to improve my code timing? </p>
<pre><code>import itertools
import copy
Dic = {
0: ['-1','A','B','p'... | 0 | 2016-07-02T08:30:50Z | 38,176,569 | <p>I Played around with this code and using the previous answer I find a faster solution: </p>
<pre><code>def sign_to_num(val):
if val == '+':
return 1
elif val == '-':
return -1
return int(val)
def item_sum(left_val, right_val):
return sign_to_num(left_val) + sign_to_num(right_val)
def comp_dict_itsel... | 0 | 2016-07-04T03:30:31Z | [
"python",
"performance",
"dictionary",
"time"
] |
Twitter Streaming API not giving any results | 38,158,171 | <p>I'm running the following code to get tweets related to the below keywords.</p>
<pre><code>from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
access_token = "K"
access_token_secret = ""
consumer_key = ""
consumer_secret = ""
class StdOutListener(StreamListener):
... | 0 | 2016-07-02T08:33:56Z | 38,192,468 | <p>You're not handing the error cases properly. Try the following code:</p>
<p><code>Python 3</code> version:</p>
<pre><code>import time
import argparse
import os
import sys
import json
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from ... | 0 | 2016-07-04T21:31:54Z | [
"python",
"python-2.7",
"twitter",
"tweepy"
] |
Unable to get a single linebreak while sending email through Sendgrid | 38,158,192 | <p>I'm using <code>django.core.mail</code> to send email. I want to achieve a single linebreak at some points in the email, as shown here:</p>
<pre><code>Line 1
Line 2
Line 3
Line 4
</code></pre>
<p>I tried doing this using <code>\n</code> after <code>Line 1</code> and <code>Line 3</code>, and <code>\n\n</code> afte... | 1 | 2016-07-02T08:37:28Z | 38,159,026 | <p>This is happening because you're using Sendgrid, which <a href="https://sendgrid.com/docs/Classroom/Build/Format_Content/plain_text_emails_converted_to_html.html" rel="nofollow">in some cases will convert your plain text messages to HTML</a>. Most likely you have configured it to do open/click tracking and it cannot... | 2 | 2016-07-02T10:19:09Z | [
"python",
"django",
"email"
] |
How to print a Python attribute name? | 38,158,284 | <p>Say I'd like to create an introspection stanza, that displays available details of a function. <br>Something like the bottom of the following code:</p>
<pre><code>def sample(_range=4):
""" produce a range of integers """
for i in range(_range):
yield i
f = sample
for i in (f.__name__, f.__doc__, f.... | 0 | 2016-07-02T08:51:04Z | 38,158,353 | <p>If, as in your example, you know the names of the attributes you want, this would work:</p>
<pre><code>for fn in ('__name__', '__doc__', '__dict__', '__code__', '__defaults__', '__globals__', '__closure__'):
print(fn, getattr(f, fn))
</code></pre>
<p>If you are asking how to get the name when all you have is t... | 2 | 2016-07-02T08:59:08Z | [
"python",
"python-3.x",
"attributes",
"eval",
"introspection"
] |
How to print a Python attribute name? | 38,158,284 | <p>Say I'd like to create an introspection stanza, that displays available details of a function. <br>Something like the bottom of the following code:</p>
<pre><code>def sample(_range=4):
""" produce a range of integers """
for i in range(_range):
yield i
f = sample
for i in (f.__name__, f.__doc__, f.... | 0 | 2016-07-02T08:51:04Z | 38,158,380 | <p>Since you already have a list of the attributes, you could use <code>getattr</code> :</p>
<pre><code>for name in ['__name__', '__doc__', '__dict__', '__code__', '__defaults__', '__globals__', '__closure__']:
print('{} -> {}'.format(name, getattr(f, name)))
</code></pre>
| 1 | 2016-07-02T09:01:48Z | [
"python",
"python-3.x",
"attributes",
"eval",
"introspection"
] |
GTK3 reuse CSS state background colors | 38,158,289 | <p>I am porting a PyGTK2 app.</p>
<p>This app does things like this:</p>
<pre><code> self.normal_color = editor.style.base [Gtk.STATE_NORMAL]
self.insensitive_color = editor.style.base [Gtk.STATE_INSENSITIVE]
</code></pre>
<p>And sets it afterwards:</p>
<pre><code> if editable: self.editor.mod... | 1 | 2016-07-02T08:51:51Z | 38,216,561 | <p>The color you're looking for is probably <code>@base_color</code>, for historical reasons. GTK has always had a distinction between "base" colors (for text entry widgets) and "background" colors (for everything else.)</p>
<p>It's not quite documentation, but examples are available on <a href="https://developer.gnom... | 0 | 2016-07-06T04:57:39Z | [
"python",
"css",
"gtk3"
] |
PreOrder Traversal in Python Recursive mrethod | 38,158,405 | <p><a href="http://www.pythontutor.com/visualize.html#code=class+createTreeNode(%29%3A%0A++++def+__init__(self,value%29%3A%0A++++++++self.value%3Dvalue%0A++++++++self.left%3DNone%0A++++++++self.right%3DNone%0Adef+preOrderTraversal(root%29%3A%0A++++while(root%29%3A%0A++++++++print+root.value%0A++++++++preOrderTraversal(... | -1 | 2016-07-02T09:04:19Z | 38,158,584 | <p>Your code loops forever because you have <code>while(root)</code> in your <code>preOrderTraversal</code> function. Since you're not modifying <code>root</code> to anything falsey during the loop body, this will always run forever if <code>root</code> was not <code>None</code> to start with.</p>
<p>I think you want ... | 3 | 2016-07-02T09:26:33Z | [
"python",
"python-2.7"
] |
install dlib with python 3.5 on ubuntu 16 -- how to link proper libboost .so file | 38,158,486 | <p>I'm trying to install dlib version 19.0 on python 3.5 on a 64-bit ubuntu machine. So far I've done:</p>
<pre><code>sudo apt-get install libboost-all-dev
</code></pre>
<p>I downloaded <a href="http://dlib.net/" rel="nofollow">dlib version 19.0</a>, then</p>
<pre><code>tar xvjf dlib-19.0.tar.bz2
cd dlib-19.0
pytho... | 0 | 2016-07-02T09:13:40Z | 38,163,307 | <p>Since I'm using anaconda, I was able to use the package I found here: <a href="https://anaconda.org/menpo/dlib" rel="nofollow">https://anaconda.org/menpo/dlib</a></p>
<p>And in a terminal, executed: </p>
<pre><code>conda install -c menpo dlib=18.18
</code></pre>
<p>After that it worked! Thank sweet baby jimmy.</... | 1 | 2016-07-02T18:33:54Z | [
"python",
"linux",
"ubuntu",
"boost",
"dlib"
] |
must be str, not bytes | 'str' has no attribute 'decode' | 38,158,530 | <p>I have this simple code to extract from a mongo database:</p>
<pre><code>import sys
import codecs
import datetime
from pymongo import MongoClient
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
mongo_db = "database"
collectionId = "coll name"
def main(argv):
client = MongoClient("mongodb://localhost:27... | 0 | 2016-07-02T09:20:02Z | 38,159,120 | <pre><code>sys.stdout = codecs.getwriter('utf8')(sys.stdout)
</code></pre>
<p>This line changes the standard output, so it does different things than you normally see. In Python 3 you donât really need to care about converting things to utf8 since everything already is a unicode string.</p>
<p>If you remove that li... | 4 | 2016-07-02T10:31:59Z | [
"python",
"string",
"mongodb",
"python-3.x"
] |
Error while deleting a index in Elastic search | 38,158,531 | <p>I am working with Elastic search Python API. I created a index called "sample". But, facing an exception while trying to delete the same. Below is my approach.</p>
<p>Elastic search instance, </p>
<pre><code>es = Elasticsearch("abc.def.ghi.jkl:9300")
</code></pre>
<p>Checking whether the index exists </p>
<p... | 0 | 2016-07-02T09:20:02Z | 38,158,557 | <p>You need to use the port 9200, which is dedicated to HTTP communications not 9300 which is dedicated to TCP communications</p>
<pre><code>es = Elasticsearch("abc.def.ghi.jkl:9200")
^
|
change this
</code></pre>... | 2 | 2016-07-02T09:23:41Z | [
"python",
"elasticsearch",
"elasticsearch-py"
] |
How do I dump and load multiple python objects into and from a json file? | 38,158,551 | <p>I want to store several variables in a json file.</p>
<p>I know I can dump multiple variable like this-</p>
<pre><code>import json
with open('data.json', 'w') as fp:
json.dump(p_id,fp, sort_keys = True, indent = 4)
json.dump(word_list, fp, sort_keys = True, indent = 4)
.
.
.
</code></pre>
<p>B... | 0 | 2016-07-02T09:22:49Z | 38,158,617 | <p>You'd generally write <strong>one</strong> JSON object to a file; that object can contain your other objects:</p>
<pre><code>json_data = {
'p_id': p_id,
'word_list': word_list,
# ...
}
with open('data.json', 'w') as fp:
json.dump(json_data, fp, sort_keys=True, indent=4)
</code></pre>
<p>Now all you... | 1 | 2016-07-02T09:30:44Z | [
"python",
"json"
] |
Only allow certain number of seconds for ONE line of python | 38,158,574 | <p>I want to create a timer so that a particular line of code only has 60 seconds to process.</p>
<p>def foo():</p>
<pre><code> for i in xrange(10):
output = action(arg1, arg2)
print i
</code></pre>
<p>If this action takes more than 60 seconds, then don't print i, but just continue to next one. How can I... | 0 | 2016-07-02T09:25:35Z | 38,158,915 | <pre><code>import time
for i in xrange(10):
time_start = time.time()
output = action(arg1, arg2)
if time.time() - time_start <= 60:
print i
</code></pre>
| 0 | 2016-07-02T10:04:50Z | [
"python",
"timer",
"exception-handling",
"signals",
"multiprocess"
] |
KNN with TF-IDF Throwing "Reshape your data" Warnings with Cosine Similarity as a distance metric | 38,158,575 | <p>I am trying to do KNN using Cosine Similarity in SciKIt Learn but it keep throwing these warnings. Can someone explain what is the meaning of these and why is it only coming when I am trying to fit a KNN model with cosine similarity and not with any other distance metric?</p>
<p>Code:</p>
<pre><code>t0 = time.time... | 0 | 2016-07-02T09:25:39Z | 38,159,740 | <p>For me it does not make sense for this not to show with other metrics (like <code>linear_kernel</code>), I guess this is something they have forgotten(?) to update because both(<code>linear_kernel</code> and <code>cosine_similarity</code>) are kernel operations.</p>
<p>To the matter at hand , you are getting this e... | 0 | 2016-07-02T11:40:54Z | [
"python",
"scikit-learn",
"knn",
"cosine-similarity"
] |
Checking if any strings in one list are a substring in another list | 38,158,577 | <p>I know that if I just have two strings that checking using <code>x in y</code> will work. And that if I just wanted to check if a string is in any of the strings in a list I'd just use a <code>for</code> loop for that.</p>
<p>But what is the most pythonic/efficient way to check if any of the strings in the first l... | -3 | 2016-07-02T09:25:53Z | 38,158,690 | <p>I would say something like this:</p>
<pre><code>#python2
notPresent = set()
present = set()
listA = ['Rick', 'James']
listB = ['Rick', 'Ricky', 'Ryan', 'Jam', 'Jamesses', 'Jamboree']
#notPresent = ['Ryan','Jam','Jamboree']
#present = ['Rick','Ricky','Jamesses']
for b in listB:
for a in listA:
if a in b:
... | 0 | 2016-07-02T09:39:52Z | [
"python"
] |
Checking if any strings in one list are a substring in another list | 38,158,577 | <p>I know that if I just have two strings that checking using <code>x in y</code> will work. And that if I just wanted to check if a string is in any of the strings in a list I'd just use a <code>for</code> loop for that.</p>
<p>But what is the most pythonic/efficient way to check if any of the strings in the first l... | -3 | 2016-07-02T09:25:53Z | 38,158,708 | <p>You can do this with <a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow"><code>any</code></a> and a <a href="https://docs.python.org/2/library/functions.html#func-set" rel="nofollow"><code>set</code></a> comprehension:</p>
<pre><code>listA = ['Rick', 'James']
listB = ['Rick', 'Ricky', 'Rya... | 1 | 2016-07-02T09:42:15Z | [
"python"
] |
Checking if any strings in one list are a substring in another list | 38,158,577 | <p>I know that if I just have two strings that checking using <code>x in y</code> will work. And that if I just wanted to check if a string is in any of the strings in a list I'd just use a <code>for</code> loop for that.</p>
<p>But what is the most pythonic/efficient way to check if any of the strings in the first l... | -3 | 2016-07-02T09:25:53Z | 38,158,776 | <p>the fastest way is probably to turn the first list into a set</p>
<pre><code>setA = set(listA)
</code></pre>
<p>then, for each string in <code>listB</code>, check if any of its substrings are in <code>setA</code>.</p>
<pre><code>def substrings(s):
for i in range len(s)
for j in range i
yie... | 1 | 2016-07-02T09:49:34Z | [
"python"
] |
Django modelForm and html template - securiy concern | 38,158,652 | <p>In Django, We use modelForms to save data to DB. </p>
<p>Model class:</p>
<pre><code># myapp/models.py
from django.db import models
class MyModel(models.Model):
title = models.CharField(max_length=100)
</code></pre>
<p>ModelForm:</p>
<pre><code># myapp/forms.py
from django import forms
from .models import M... | 1 | 2016-07-02T09:34:48Z | 38,158,813 | <blockquote>
<p>Will this not pose a security risk? name of columns in DB are same as
input fields in html?</p>
</blockquote>
<p>I suppose if anyone would be able to query your database he would be able to view all tables and columns names in it, so hiding table and column names won't give any defense, it will giv... | 1 | 2016-07-02T09:55:14Z | [
"python",
"html",
"django",
"django-forms"
] |
Django modelForm and html template - securiy concern | 38,158,652 | <p>In Django, We use modelForms to save data to DB. </p>
<p>Model class:</p>
<pre><code># myapp/models.py
from django.db import models
class MyModel(models.Model):
title = models.CharField(max_length=100)
</code></pre>
<p>ModelForm:</p>
<pre><code># myapp/forms.py
from django import forms
from .models import M... | 1 | 2016-07-02T09:34:48Z | 38,162,498 | <p>I found another solution to keep different names for column in DB and field name in html.<br>
db_column.</p>
<pre><code>name = models.CharField(max_length=128, db_column="myname")
</code></pre>
<p>This way, 'name' will be used in code everywhere but in table column name will be 'myname'.</p>
| 0 | 2016-07-02T16:59:18Z | [
"python",
"html",
"django",
"django-forms"
] |
Python3 pip module, check if packages exist on PyPi | 38,158,672 | <p>I use the pip module in a python script to automate the installation of software / modules . How can I do to check if the (remote) software / module exists? I have found nothing in the pip module that allows to do that.</p>
<p>My code :</p>
<pre><code>class install_pip:
def __init__(self):
self._liste=... | 0 | 2016-07-02T09:37:14Z | 38,158,871 | <p>The following code will attempt to import a package (package is of type 'str'). If it is unable to import the package (i.e. it isn't installed) it will call Pip and attempt to install the package.</p>
<pre><code>import pip
def import_or_install(package):
try:
__import__(package)
print (package,... | 0 | 2016-07-02T10:01:00Z | [
"python",
"python-3.x",
"pip"
] |
Python while loop not working properly | 38,158,791 | <p>I am a complete beginner in python (2.7), and this program is supposed to take some students names and their marks in 3 subjects, and return the average of specified name. I did get the answer correctly(through another method), but this program isn't working properly and I want to know why. The main problem is that ... | 0 | 2016-07-02T09:52:36Z | 38,158,851 | <p>The <code>del</code> operator deletes only the sepcified index but moves the left objects to the front. That means you are skipping parts of the list.</p>
<p>Try that code:</p>
<pre><code>j=0
try:
while (j<3):
del marks[0]
j+=1
except:
print "okay!"
</code></pre>
<p>Another way to clean... | 0 | 2016-07-02T09:58:56Z | [
"python",
"list",
"python-2.7"
] |
Python while loop not working properly | 38,158,791 | <p>I am a complete beginner in python (2.7), and this program is supposed to take some students names and their marks in 3 subjects, and return the average of specified name. I did get the answer correctly(through another method), but this program isn't working properly and I want to know why. The main problem is that ... | 0 | 2016-07-02T09:52:36Z | 38,158,854 | <p>The loop is working properly, but your logic is flawed. Think about which <em>elements</em> you delete during iteration:</p>
<pre><code>[1, 2, 3]
# delete 1st element, i.e. 1
[2, 3]
# delete 2nd element, i.e. 3!!!
[2]
# delete 3rd element, which doesn't exist
</code></pre>
<p>Part of your problem is also that your... | 1 | 2016-07-02T09:59:31Z | [
"python",
"list",
"python-2.7"
] |
Iterating list with given index list in python | 38,158,840 | <p>I have a list <code>A = [-1, 2, 1, 2, 0, 2, 1, -3, 4, 3, 0, -1]</code> and <code>B = [0, 7, 11]</code>. List <code>B</code> shows the index of negative integer number index. </p>
<p>How can I return the sum of each slice of the list: For example sum of <code>A[0+1:7]</code> and <code>A[7+1:11]</code></p>
| 0 | 2016-07-02T09:57:45Z | 38,158,907 | <p>Using <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code></a>, you can convert <code>[0, 7, 11]</code> to the desired slice index pairs (<code>1:7</code> / <code>8:11</code>):</p>
<pre><code>>>> zip(B, B[1:]) # In Python 3.x, this will return an iterator.
[(0, 7)... | 4 | 2016-07-02T10:04:14Z | [
"python",
"list",
"loops"
] |
Iterating list with given index list in python | 38,158,840 | <p>I have a list <code>A = [-1, 2, 1, 2, 0, 2, 1, -3, 4, 3, 0, -1]</code> and <code>B = [0, 7, 11]</code>. List <code>B</code> shows the index of negative integer number index. </p>
<p>How can I return the sum of each slice of the list: For example sum of <code>A[0+1:7]</code> and <code>A[7+1:11]</code></p>
| 0 | 2016-07-02T09:57:45Z | 38,158,984 | <p>You can implement like using one line list comprehension.</p>
<pre><code>[sum(A[i+1:B[B.index(i)+1]]) if i != B[-1] else sum(A[i+1:-1]) for i in B]
</code></pre>
<p><strong>Result</strong></p>
<pre><code>[8, 7, 0]
</code></pre>
<p>If you don't want last slice sum use this.</p>
<pre><code>[sum(A[i+1:B[B.index(i)... | 1 | 2016-07-02T10:13:01Z | [
"python",
"list",
"loops"
] |
Python basic program to count the letters in a file | 38,158,878 | <p>I'm writing a program in Python for an online class in order to find the frequency of letters in a file. Thing is I keep getting spaces included in the final result too. How can I omit them? Here's my code: </p>
<pre><code>import string
name = raw_input('Enter a file name: ')
fhandle = open(name)
counts = dict()
fo... | 0 | 2016-07-02T10:01:20Z | 38,159,001 | <p><code>string.punctuation</code> contains <code>!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~</code> and no whitespace characters.</p>
<p>You should change your call to <code>translate()</code> to the following:</p>
<pre><code>line.translate(None,string.punctuation+string.whitespace+string.digits)
</code></pre>
<p>... | 4 | 2016-07-02T10:15:32Z | [
"python",
"python-2.7"
] |
Python basic program to count the letters in a file | 38,158,878 | <p>I'm writing a program in Python for an online class in order to find the frequency of letters in a file. Thing is I keep getting spaces included in the final result too. How can I omit them? Here's my code: </p>
<pre><code>import string
name = raw_input('Enter a file name: ')
fhandle = open(name)
counts = dict()
fo... | 0 | 2016-07-02T10:01:20Z | 38,159,007 | <p>If you don't want to print the letter if it is a blank space (and you don't want to change anything else in your code), then you can add one if statement in the last for loop:</p>
<pre><code>for count,letter in lst:
if letter != ' ':
print count,letter
</code></pre>
| 0 | 2016-07-02T10:16:01Z | [
"python",
"python-2.7"
] |
Python basic program to count the letters in a file | 38,158,878 | <p>I'm writing a program in Python for an online class in order to find the frequency of letters in a file. Thing is I keep getting spaces included in the final result too. How can I omit them? Here's my code: </p>
<pre><code>import string
name = raw_input('Enter a file name: ')
fhandle = open(name)
counts = dict()
fo... | 0 | 2016-07-02T10:01:20Z | 38,159,036 | <p>An elegant way to do this is to just use isalpha().
See line 11:</p>
<pre><code>import string
name = raw_input('Enter a file name: ')
fhandle = open(name)
counts = dict()
for line in fhandle:
line = line.strip()
line = line.translate(None,string.punctuation)
line = line.lower()
letters = list(line)
... | 0 | 2016-07-02T10:20:08Z | [
"python",
"python-2.7"
] |
How to react on failed transaction (Django) | 38,158,951 | <p>How to react on failed Django transaction? For example return some kind of error page or reload the page etc. </p>
<p>There is <code>with transaction.atomic()</code> in the code so in case that user has been saved but the problem occured during saving userprofile, everything will be rolled back.</p>
<p>But how to ... | 0 | 2016-07-02T10:09:45Z | 38,159,089 | <p>You can catch the exception (except-try) and return an error message/page.</p>
<pre><code> try:
with transaction.atomic():
request.user.first_name = cleaned['first_name']
request.user.last_name = cleaned['last_name']
request.user.userprofile.IBAN = cleaned['IBAN']
... | 0 | 2016-07-02T10:28:00Z | [
"python",
"django",
"transactions"
] |
iterate json logins in python | 38,158,997 | <p>i am attempting to automate logging in with python. the logins are stored in a json file for easier administrating those values without touching the python file.</p>
<p>my json file looks like this</p>
<pre><code>{
"carl":
{"name": "carlcarlson", "pw": "lenny"},
"lenny":
{"name": "lennylennards", "pw":"cr... | 0 | 2016-07-02T10:15:06Z | 38,159,054 | <p>Whether it's strings or numbers makes no difference at all. This is a dict, which in turn contains other dicts. To can get the values of the outer dict directly with <code>looog.values()</code>.</p>
| 0 | 2016-07-02T10:22:25Z | [
"python",
"json",
"loops",
"variables"
] |
iterate json logins in python | 38,158,997 | <p>i am attempting to automate logging in with python. the logins are stored in a json file for easier administrating those values without touching the python file.</p>
<p>my json file looks like this</p>
<pre><code>{
"carl":
{"name": "carlcarlson", "pw": "lenny"},
"lenny":
{"name": "lennylennards", "pw":"cr... | 0 | 2016-07-02T10:15:06Z | 38,159,058 | <p>You are just dealing with a <a href="https://docs.python.org/2/library/stdtypes.html#dict" rel="nofollow">dict</a>.</p>
<pre><code>looog = {u'carl': {u'name': u'carlcarlson', u'pw': u'lenny'}, u'lenny': {u'name': u'lennylennards', u'pw': u'crrrl'}}
for user,details in looog.items():
print(user)
print(detai... | 0 | 2016-07-02T10:22:47Z | [
"python",
"json",
"loops",
"variables"
] |
RabbitMQ: Dispatcher for messages that contain many tasks | 38,159,038 | <p>I am trying to distribute a message via RabbitMQ that contains many tasks:</p>
<pre><code>Producer --> RabbitMQ Exchange --> 10 Consumers
</code></pre>
<p>E.g.:
The User sends a message to the exchange that contains 1000 tasks. The exchange needs to distribute the tasks evenly to the consumers with the short... | 0 | 2016-07-02T10:20:29Z | 38,160,428 | <p>It sounds a lot simpler if you used a single queue, and had multiple consumers attached to that queue and leveraged <a href="https://www.rabbitmq.com/consumer-prefetch.html" rel="nofollow">Consumer Prefetch (QoS)</a>. This way you could send a 1000 messages to that queue, and have the available consumers pick up the... | 1 | 2016-07-02T12:59:42Z | [
"python",
"rabbitmq",
"pika"
] |
Scrapy: error downloading with proxies | 38,159,211 | <p>I am able to scrape pages without using a proxy. However, when I add proxies, scrapy either gives <code>Error downloading: Connection was refused by other side: 61: Connection refused</code>, or <code>[<twisted.python.failure.Failure twisted.internet.error.ConnectionLost: Connection to the other side was lost in ... | 0 | 2016-07-02T10:41:27Z | 38,207,612 | <p>Just for completeness... (I hate having to find answers in comments)</p>
<p>middleware.py should be changed to:</p>
<pre><code>import random
import base64
from settings import PROXIES
class ProxyMiddleware(object):
def process_request(self, request, spider):
proxy = random.choice(PROXIES)
if ... | 0 | 2016-07-05T15:45:16Z | [
"python",
"proxy",
"scrapy"
] |
Variables for width in Python format string | 38,159,243 | <p>In order to print a header for tabular data, I'd like to use only one format string <code>line</code> and one spec for column widths <code>w1, w2, w3</code> (or even <code>w = x, y, z</code> if possible.) </p>
<p>I've looked at <a href="http://stackoverflow.com/questions/9535954/python-printing-lists-as-tabular-da... | 1 | 2016-07-02T10:45:39Z | 38,159,271 | <p>Specifying <code>w[0]</code>, <code>w[1]</code>, <code>w[2]</code> should work if you defined <code>w = 8, 7, 10</code> and passed <code>w</code> as keyword argument like below:</p>
<pre><code>>>> head = 'eggs', 'bacon', 'spam'
>>> w = 8, 7, 10 # <--- list is also okay
>>> line = ' {... | 1 | 2016-07-02T10:48:49Z | [
"python",
"string",
"format"
] |
Variables for width in Python format string | 38,159,243 | <p>In order to print a header for tabular data, I'd like to use only one format string <code>line</code> and one spec for column widths <code>w1, w2, w3</code> (or even <code>w = x, y, z</code> if possible.) </p>
<p>I've looked at <a href="http://stackoverflow.com/questions/9535954/python-printing-lists-as-tabular-da... | 1 | 2016-07-02T10:45:39Z | 38,164,565 | <p>This is jonrsharpe's comment to my OP, worked out so as to visualise what's going on. </p>
<pre><code>line = ' {:{ul}>{w1}} {:{ul}>{w2}} {:{ul}>{w3}}'
under = 3 * '_'
head = 'sausage', 'rat', 'strawberry tart'
# manual dict
v = {'w1': 8, 'w2':5, 'w3': 17}
print line.format(*under, ul='_', **v)
# aut... | 0 | 2016-07-02T21:19:09Z | [
"python",
"string",
"format"
] |
NameError after packaging Python code | 38,159,295 | <p>I've been using IPython for sometime without ever having to package code. I glanced through the following pages and setup a directory structure for my modules and now use IPython to initiate the program.</p>
<p><a href="https://docs.python.org/3/reference/import.html" rel="nofollow">https://docs.python.org/3/refere... | 1 | 2016-07-02T10:51:27Z | 38,159,313 | <p>Add <code>import glob</code> in <code>getdata.py</code> (<strong>where the <code>glob</code> module is used</strong>), not in the <code>external.py</code>.</p>
<pre><code>import glob # <--
def funcname():
file_list = glob.glob("Data/")
def other_func():
x = x + 3
</code></pre>
| 1 | 2016-07-02T10:53:02Z | [
"python",
"python-module"
] |
How to get the div class which contains another specific div class in Python with Beautifulsoup? | 38,159,301 | <p>I have this kind of code:</p>
<pre><code><div class = first>
<div class = second>
<div class = fourth>
<div class = first>
<div class = second>
<div class = third>
<div class = first>
<div class = second>
<div class = fourth>
</code></pre>
<p... | 1 | 2016-07-02T10:51:54Z | 38,162,172 | <p>I presume when you say contains that you mean the <em>price div</em> is the parent of the refundable so look for the <em>refundable</em> divs and see if the parent is a div with the class name <em>price</em> you have what you need:</p>
<p>html = """
</p>
<pre><code><div cl... | 0 | 2016-07-02T16:23:37Z | [
"python",
"beautifulsoup"
] |
Dataframe Dealing With Missing Time Series Data | 38,159,309 | <p>My DataFrame is an array time series taken every minute over a period of ~60 days.</p>
<ol>
<li><p>First I want to segment the df into 24 hour periods.</p></li>
<li><p>Then I want to plot certain attributes as a waterfall chart, line graphs on top of each other.</p></li>
</ol>
<p>I'm thinking of using <code>iloc</... | 2 | 2016-07-02T10:52:27Z | 38,159,330 | <p>I think you should've meant this:</p>
<pre><code>for i in range(58)
df = timethingdf.iloc[809+i*3600:809+(i+1)*3600]
# Doing something with `df`
</code></pre>
| 1 | 2016-07-02T10:55:13Z | [
"python",
"pandas",
"matplotlib"
] |
Dataframe Dealing With Missing Time Series Data | 38,159,309 | <p>My DataFrame is an array time series taken every minute over a period of ~60 days.</p>
<ol>
<li><p>First I want to segment the df into 24 hour periods.</p></li>
<li><p>Then I want to plot certain attributes as a waterfall chart, line graphs on top of each other.</p></li>
</ol>
<p>I'm thinking of using <code>iloc</... | 2 | 2016-07-02T10:52:27Z | 38,163,020 | <p>I think what you want is <code>TimeGrouper</code>:</p>
<pre><code>data = {'date':['2004-1-2:10:10:00', '2004-1-2:10:11:00', '2004-1-1:11:11:00', '2004-1-1:11:13:00'], 'foo':[5,6,7,8]}
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d:%H:%M:%S')
df = df.set_index('date')
grouped = df.g... | 0 | 2016-07-02T17:59:34Z | [
"python",
"pandas",
"matplotlib"
] |
Learn Python The Hard Way ex32 | 38,159,314 | <p>I'm using <em>"Learn Python The Hard Way"</em> to learn programming. I had some problems in <a href="http://learnpythonthehardway.org/book/ex32.html" rel="nofollow">the thirty-second chapter</a>.</p>
<p>This is the content from the book:</p>
<pre><code>the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pe... | -1 | 2016-07-02T10:53:06Z | 38,159,346 | <p>Indenting (:</p>
<p>change</p>
<pre><code># now we can print them out too
for i in elements:
print "Element was: %d" % i
</code></pre>
<p>to</p>
<pre><code># now we can print them out too
for i in elements:
print "Element was: %d" % i
</code></pre>
<p>Because your current code runs that in the l... | 2 | 2016-07-02T10:56:05Z | [
"python",
"python-2.7"
] |
No query executing on a table in postgresql | 38,159,321 | <p>I have a table in PostgreSql-9.4 database called <code>orders_order</code>.
I am unable to run any kind of query on it. No matter what query I run on this table (for eg. <code>SELECT count(*) from orders_order;</code> or even <code>\d orders_order</code>), nothing happens, except cursor blinking on terminal.</p>
<... | 1 | 2016-07-02T10:53:45Z | 38,161,239 | <p>Most likely you are not terminating your query with a semicolon ;-)</p>
<p>Note that by default the PostgreSQL prompt has three pieces:</p>
<pre><code>[dbname][linestatus][is_superuser]
</code></pre>
<p>for example logged in as Postgres, new line, db is postgres:</p>
<pre><code>postgres=#
</code></pre>
<p>Logge... | 2 | 2016-07-02T14:31:53Z | [
"python",
"django",
"postgresql",
"psycopg2"
] |
applying the same operation to different dataframes | 38,159,342 | <p>couldnt find anything about this is python...
ive been working on three different datasets for some machine learning projects and it has been a bit of an arduous task typing out the same commands in exactly the same way for the same operation on a different data frame... it started with this:</p>
<pre><code>aviva ... | 2 | 2016-07-02T10:55:48Z | 38,159,657 | <p>Instead of three DataFrames, <code>aviva</code>, <code>admiral</code>, <code>three</code>, use one <code>dict</code> with keys of the same names which map to DataFrames:</p>
<pre><code>dfs = dict()
for filename, name in [('LON_AV_.csv', 'aviva'),
('LON_ADM.csv', 'admiral'),
... | 1 | 2016-07-02T11:31:59Z | [
"python",
"function",
"pandas",
"anonymous"
] |
applying the same operation to different dataframes | 38,159,342 | <p>couldnt find anything about this is python...
ive been working on three different datasets for some machine learning projects and it has been a bit of an arduous task typing out the same commands in exactly the same way for the same operation on a different data frame... it started with this:</p>
<pre><code>aviva ... | 2 | 2016-07-02T10:55:48Z | 38,159,989 | <p>i would do it this way:</p>
<pre><code>in_csv_template = 'data/LON_{}.csv'
out_csv_template = 'out/{}_x.csv'
out_label_template = 'out/{}_y.csv'
cfg = {
'aviva': 'AV_',
'admiral': 'ADM',
'three': 'III',
}
def process(fi_csv, fo_csv, fo_label, **kwargs):
df = pd.read_csv(fi_csv, **kwargs)
...
... | 0 | 2016-07-02T12:08:26Z | [
"python",
"function",
"pandas",
"anonymous"
] |
How to brighten a color in matplotlib | 38,159,348 | <p>Is there anyway to make a color a lot brighter in matplotlib?</p>
<p>I have the following color map:</p>
<pre><code> cmap = clr.LinearSegmentedColormap.from_list('red_yellow',
[(0,'#00001a'),
(0.59,'#e60000'),
... | 1 | 2016-07-02T10:56:09Z | 38,159,523 | <p>Easiest way i can think of is convert it to <a href="https://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB" rel="nofollow">HSL</a>, up the lightness, and then convert it back. If you're going to go down this route, i'd use the <a href="https://docs.python.org/2/library/colorsys.html" rel="nofollow">colorsys</a... | 1 | 2016-07-02T11:15:43Z | [
"python",
"matplotlib"
] |
Extracting javascript enabled data from page | 38,159,366 | <p>I am trying to extract coloured text in this <a href="http://de.vroniplag.wikia.com/wiki/Aaf/008" rel="nofollow">link</a>. I am using BeautifulSoup in python. The code is as follows:</p>
<pre><code>import time, urllib2, re
from bs4 import BeautifulSoup
url='http://de.vroniplag.wikia.com/wiki/Aaf/008'
def gethtml(li... | 1 | 2016-07-02T10:57:38Z | 38,159,503 | <p>You need to use library that can interpret javascript. For example using <a href="https://pypi.python.org/pypi/selenium" rel="nofollow"><code>selenium</code></a> because those elements with <code>fragmark1</code>, <code>fragmark2</code>, ... are created by the javascript.</p>
<pre><code>from selenium.webdriver impo... | 1 | 2016-07-02T11:13:55Z | [
"javascript",
"python",
"beautifulsoup",
"bs4"
] |
Python Django OneToOneField nullable value | 38,159,418 | <p>I'm extending the User model to a UserProfile model as below.</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
TYPE0 = 0
TYPE1 = 1
PROFILE_TYPE_CHOICES = (
(TYPE0, "Old"),
(TYPE1, "New"),
)
profile_type = models.PositiveSmallInteg... | 1 | 2016-07-02T11:02:58Z | 38,159,560 | <p>It seems that you have existing Type0User rows on your database. As a new column is being added, these rows need to have a default value so they can be populated.</p>
<p>If you are extending your design to support two kinds of users, I suggest add a field to your existing UserProfile model to differentiate the two ... | 0 | 2016-07-02T11:20:09Z | [
"python",
"django"
] |
Read temperature with MAX31855 Thermocouple Sensor on Windows IoT | 38,159,448 | <p>I am working on a Raspberry Pi 2 with Windows IoT. I want to connect the Raspberry Pi with a <a href="https://learn.adafruit.com/max31855-thermocouple-python-library/overview" rel="nofollow">MAX31855 Thermocouple Sensor</a> which I bought on Adafruit. There's a Python libary available on <a href="https://github.com/... | 0 | 2016-07-02T11:06:27Z | 38,173,660 | <p>The MAX31855 uses an SPI interface so you can use the <a href="https://msdn.microsoft.com/library/windows/apps/windows.devices.spi.spidevice.aspx" rel="nofollow">Windows.Devices.Spi.SpiDevice</a> class to read the data in C#.</p>
<p>Here's a Universal Windows Platform (UWP) sample app demonstrating using the SPI bu... | 1 | 2016-07-03T19:34:38Z | [
"c#",
"python",
"raspberry-pi",
"temperature",
"windowsiot"
] |
Read temperature with MAX31855 Thermocouple Sensor on Windows IoT | 38,159,448 | <p>I am working on a Raspberry Pi 2 with Windows IoT. I want to connect the Raspberry Pi with a <a href="https://learn.adafruit.com/max31855-thermocouple-python-library/overview" rel="nofollow">MAX31855 Thermocouple Sensor</a> which I bought on Adafruit. There's a Python libary available on <a href="https://github.com/... | 0 | 2016-07-02T11:06:27Z | 38,176,153 | <p>You'll need to do some porting work before using that python driver on raspberry pi with windows IoT core,</p>
<ol>
<li>Follow this sample <a href="https://developer.microsoft.com/en-us/windows/iot/win10/samples/pythonblinky" rel="nofollow">https://developer.microsoft.com/en-us/windows/iot/win10/samples/pythonblink... | 1 | 2016-07-04T02:24:22Z | [
"c#",
"python",
"raspberry-pi",
"temperature",
"windowsiot"
] |
Why need to use Flask extension, not just the bare library? | 38,159,457 | <p>Can somebody explain why you should Use a flask extension instead of a bare library?</p>
<p>For example, if you want to use mongoDB (or whatever) from Flask, it seems you need to do this:</p>
<pre><code>from flask.ext.pymongo import PyMongo
mongo = PyMongo(app)
</code></pre>
<p>and use this instance throughout th... | -3 | 2016-07-02T11:08:13Z | 38,159,511 | <blockquote>
<p>I'd like to know what are so special about the extensions.</p>
</blockquote>
<p>The PyMongo extension allows you to configure the Mongo connection using the same configuration mechanism used for the rest of Flask, see the <a href="https://flask-pymongo.readthedocs.io/en/latest/#configuration" rel="no... | 3 | 2016-07-02T11:14:21Z | [
"python",
"flask"
] |
Why need to use Flask extension, not just the bare library? | 38,159,457 | <p>Can somebody explain why you should Use a flask extension instead of a bare library?</p>
<p>For example, if you want to use mongoDB (or whatever) from Flask, it seems you need to do this:</p>
<pre><code>from flask.ext.pymongo import PyMongo
mongo = PyMongo(app)
</code></pre>
<p>and use this instance throughout th... | -3 | 2016-07-02T11:08:13Z | 38,442,847 | <p>Using the pymongo library instead of the flask-mongoengine extension gives you full access to all the db connection methods and also other utilities that might be somehow useful.</p>
<p>Instead, by using the flask-mongoengine extension, you will have a simplified "wrapper" around the pymongo library, which is safer... | 1 | 2016-07-18T17:38:26Z | [
"python",
"flask"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.