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
Passing variable for module import and use
39,070,053
<p>so I am trying to use a variable brand which is selected by the user. The variable is then to be used to call a given module in Python. currently on line 7 you can see 'apple.solutions()'. However, I essentially want to be able to use something on the lines 'brand.solutions()' - although I know this will not work as...
0
2016-08-22T00:38:47Z
39,070,515
<pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import apple, android, windows brands = ["apple", "android", "windows"] def selector(brands, query): if query in brands: exec("import %s as brand" % query) else: brand = None return brand def Main(): query = raw_input("E...
0
2016-08-22T02:06:23Z
[ "python", "arrays", "variables", "parameter-passing", "python-module" ]
Python Looping through File and downloading Images
39,070,060
<p>I am trying to loop through a text file with different website links to download the images. I also want them to have a unique file name. Just a loop counter as you see so the three images would be <code>1.jpg</code>, <code>2.jpg</code>, <code>3.jpg</code>. Yet I am only getting the last image and the file is named ...
1
2016-08-22T00:40:14Z
39,082,132
<p>rewrite the code by indenting the last two lines thus</p> <pre><code>import urllib input_file = open('Urls1.txt','r') x=0 for line in input_file: URL= line urllib.urlretrieve(URL, str(x) + ".jpg") x+=1 </code></pre> <p>Indentation is significant in Python. Without it, the last two statements are only ...
1
2016-08-22T14:28:09Z
[ "python" ]
Python re replace group values
39,070,119
<p>I have a regular expression through which I want to replace values with those values minus 10. The re is:</p> <pre><code>re.compile(r'&lt;stuff[^\&gt;]*translate\((?P&lt;x&gt;\d*),(?P&lt;y&gt;\d*)\)"/&gt;') </code></pre> <p>I want to replace the x and y groups. To do this, I want to use <code>re.sub</code> and pas...
1
2016-08-22T00:52:22Z
39,070,188
<p>The <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><code>re.sub</code> docs</a> show a good example of using a replacer function. In your case, this would work:</p> <pre class="lang-python prettyprint-override"><code>import re def less10(string): return int(string) - 10 def replacer...
0
2016-08-22T01:10:01Z
[ "python", "regex", "replace" ]
boxplot (from seaborn) would not plot as expected
39,070,135
<p><strong>The boxplot would not plot as expected. This is what it actually plotted:</strong> <a href="http://i.stack.imgur.com/rAdwz.png" rel="nofollow"><img src="http://i.stack.imgur.com/rAdwz.png" alt="enter image description here"></a></p> <p><strong>This is what it is supposed to plot:</strong> <a href="http://i....
2
2016-08-22T00:56:32Z
39,070,235
<p>I would first create pandas DF out of <code>scores</code>:</p> <pre><code>import pandas as pd In [15]: scores Out[15]: [array([ 0.8757764 , 0.86335404, 0.75625 , 0.85 , 0.86875 , 0.81875 , 0.79375 , 0.79245283, 0.8490566 , 0.85534591]), array([ 0.89440994, 0.8447205 , 0.79375 , 0.85 ...
2
2016-08-22T01:16:31Z
[ "python", "arrays", "python-2.7", "scikit-learn", "seaborn" ]
Difference between <type 'generator'> and <type 'xrange'>
39,070,168
<p>I have seen in a lot of posts/materials saying xrange(num) is a generator/iterator. I have a couple of questions regarding that.</p> <ol> <li>I want to know the exact difference between type 'xrange' and type 'generator'</li> <li><p>If xrange is an iterator/generator, it is supposed to have .next() method. I do not...
3
2016-08-22T01:05:08Z
39,070,192
<p><code>xrange</code> is an iterable, so you can call <code>iter</code> to get an iterator out of it.</p> <pre><code>&gt;&gt;&gt; x = xrange(20) &gt;&gt;&gt; iterator = iter(x) &gt;&gt;&gt; for i in iterator: ... if i == 6: break ... &gt;&gt;&gt; iterator.next() 7 </code></pre>
4
2016-08-22T01:10:04Z
[ "python", "iterator", "generator" ]
Difference between <type 'generator'> and <type 'xrange'>
39,070,168
<p>I have seen in a lot of posts/materials saying xrange(num) is a generator/iterator. I have a couple of questions regarding that.</p> <ol> <li>I want to know the exact difference between type 'xrange' and type 'generator'</li> <li><p>If xrange is an iterator/generator, it is supposed to have .next() method. I do not...
3
2016-08-22T01:05:08Z
39,070,721
<p>Also, you should understand that an iterator and an generator are not the same thing. An <em>iterable</em> is any Python object that implements an <code>__iter__</code> method that returns an <em>iterator</em>. An iterator also must implement an <code>__iter__</code> method but also a <code>next</code> method (<code...
1
2016-08-22T02:46:45Z
[ "python", "iterator", "generator" ]
Forcing response charset in CherryPy
39,070,269
<p>I want to specify the HTTP response charset by modifying the <code>Content-Type</code> header. However, it doesn't work.</p> <p>Here is a short example:</p> <pre><code>#coding=utf-8 import cherrypy class Website: @cherrypy.expose() def index(self): cherrypy.response.headers['Content-Type']='text/p...
0
2016-08-22T01:22:38Z
39,070,736
<p>All right. Solved this problem by tampering <code>cherrypy.response.header_list</code> directly.</p> <pre><code>#coding=utf-8 import cherrypy def set_content_type(): header=(b'Content-Type',cherrypy.response._content_type.encode()) for ind,(key,_) in enumerate(cherrypy.response.header_list): if ke...
0
2016-08-22T02:49:31Z
[ "python", "character-encoding", "cherrypy" ]
TypeError: unorderable types: str() <= int()
39,070,317
<p>I am trying to take a list, <code>share_list</code>, and then cycle through the list one by one and produce an output tailored to the result. I have two problems: I don't know how to cycle through the list using a <code>for</code> loop, and I am getting this error:</p> <pre class="lang-none prettyprint-override"><c...
0
2016-08-22T01:34:47Z
39,070,373
<p>The reason to this is that the function <code>check_pb_ratio.get_price_book()</code> returns a string, not an int. Python doesn't want to know the similarity between '1' and 1.<br> So, the way to fix it is: add <code>int()</code> or <code>float()</code> around <code>check_pb_ratio.get_price_book()</code></p>
0
2016-08-22T01:45:03Z
[ "python", "typeerror", "python-3.5" ]
TypeError: unorderable types: str() <= int()
39,070,317
<p>I am trying to take a list, <code>share_list</code>, and then cycle through the list one by one and produce an output tailored to the result. I have two problems: I don't know how to cycle through the list using a <code>for</code> loop, and I am getting this error:</p> <pre class="lang-none prettyprint-override"><c...
0
2016-08-22T01:34:47Z
39,070,379
<p>Thanks to @Rawing</p> <p>This code now works, I just need to fix a NoneType issue. Thanks!</p> <pre><code>from yahoo_finance import Share share_list = ['AAPL', 'GEVO', 'PTX'] for ticker in share_list: check_pb_ratio = Share(ticker) if float(check_pb_ratio.get_price_book()) &lt;= 1: print(str(ch...
0
2016-08-22T01:46:10Z
[ "python", "typeerror", "python-3.5" ]
Pandas - Merge two data frames, create new column, append values to array
39,070,329
<p>I am looking to merge two data frames on the same <code>id</code> in each dataframe, but to create a new column and append any values in a specified column to an array in the new dataframe column. I would expect to see multiple matching ids in the second data frame. </p> <p>Here is an example to clarify what I am l...
2
2016-08-22T01:36:06Z
39,070,346
<p>try this:</p> <pre><code>In [35]: pd.merge(df1, df2.groupby('ID').Tag.apply(list).reset_index(), on='ID', how='left') Out[35]: ID X1 X2 X3 Tag 0 2 1 1 2 [Two] 1 1 0 1 1 [One, Two] 2 0 2 1 2 NaN 3 1 0 2 2 [One, Two] 4 0 0 2 2 NaN </code></...
1
2016-08-22T01:39:27Z
[ "python", "pandas", "dataframe" ]
Pandas - Merge two data frames, create new column, append values to array
39,070,329
<p>I am looking to merge two data frames on the same <code>id</code> in each dataframe, but to create a new column and append any values in a specified column to an array in the new dataframe column. I would expect to see multiple matching ids in the second data frame. </p> <p>Here is an example to clarify what I am l...
2
2016-08-22T01:36:06Z
39,070,466
<pre><code>&gt;&gt;&gt; df1.join(df2.groupby('ID').Tag.apply(lambda group: list(group)), on='ID') ID X1 X2 X3 Tag 0 1 1 0 2 [One, Two] 1 0 1 0 1 NaN 2 0 1 2 2 NaN 3 1 2 2 0 [One, Two] 4 2 1 0 0 [Two] </code></pre>
0
2016-08-22T02:00:24Z
[ "python", "pandas", "dataframe" ]
How can I move a sprite using the keyboard with Pythons PyGame?
39,070,388
<p>I am making a remake of a video game to learn pygame and livewires. I am using livewires because it seems to be a good way to have the background graphics loaded with a sprite. </p> <p>I am trying to have a pre-loaded sprite move horizontally, while staying mobile on the correct location (in this case it is 50 pix...
-1
2016-08-22T01:47:24Z
39,071,457
<p>It seems much simpler to me if you just use Pygame or use Livewires. Dont' try to force two modules to work together if they were not meant to. Besides, the Livewires's intro page says that the module is meant to be an <strong>add-on</strong> to a Python course, not a stand-alone game module. I recommend that you ju...
2
2016-08-22T04:31:26Z
[ "python", "pygame", "livewires" ]
How to write python script to read two excel worksheets and delete any repeats in one if both have values?
39,070,409
<p>I have 2 worksheets in excel. They both contain 3 columns a,b and c. I need to delete any row in worksheet 1 if the data items for columns a,b,c are the same between the two worksheets. How would I do this using the Pandas python library?</p> <pre><code>import pandas as pd ws1 = pd.read_excel(pathname/worksheet1.xl...
-2
2016-08-22T01:51:01Z
39,070,443
<p>Try this (assuming that worksheets list1 and list 2 - two separate excel files):</p> <pre><code>df1 = pd.read_excel('/path/to/file_name1.xlsx') df2 = pd.read_excel('/path/to/file_name2.xlsx') df1 = df1[~df1.email.isin(df2.email)] </code></pre> <p>The third line of code removes those rows from <code>df1</code> whi...
2
2016-08-22T01:55:42Z
[ "python", "excel", "pandas", "dataframe" ]
Get text between two closed tags XML - Python
39,070,427
<p>I downloaded my Foursquare data and it comes in KML format. I'm parsing through it as an XML file with Python and cannot figure out how to get the text between the closed a tag and closed description tag. (It's the text that I typed when I checked in, in the example below it's "FINALLY HERE!! With Sonya and co" bu...
1
2016-08-22T01:52:58Z
39,070,499
<p>Have you tried using sub-strings?</p> <p>Lets say that all of your xml is in the variable "foo" for example.</p> <pre><code>foo = '&lt;description&gt;@&lt;a href="https://foursquare.com/v/hummus-grill/4aab4f71f964a520625920e3"&gt;hummus grill&lt;/a&gt;- FINALLY HERE!! With Sonya and co&lt;/description&gt;' </code>...
0
2016-08-22T02:05:00Z
[ "python", "xml" ]
Get text between two closed tags XML - Python
39,070,427
<p>I downloaded my Foursquare data and it comes in KML format. I'm parsing through it as an XML file with Python and cannot figure out how to get the text between the closed a tag and closed description tag. (It's the text that I typed when I checked in, in the example below it's "FINALLY HERE!! With Sonya and co" bu...
1
2016-08-22T01:52:58Z
39,070,535
<p>The following works for me:</p> <pre><code>In [44]: description = [] In [45]: for d in dom.getElementsByTagName('description'): ....: description.append(d.firstChild.nextSibling.nextSibling.data.encode('utf-8')) ....: In [46]: description Out[46]: ['- FINALLY HERE!! With Sonya and co'] </code></pre...
0
2016-08-22T02:10:59Z
[ "python", "xml" ]
Python - Post File to Django With Extra Data
39,070,568
<p>I'm trying to have my django rest framework app accept file uploads. The uploads should be accompanied by additional data that is descriptive of the file and is necessary for post-processing. Uploading the file seems to work fine, however, I can't seem to get the django app to access the other data. For example, I h...
0
2016-08-22T02:17:08Z
39,071,806
<p>This line </p> <pre><code>r = requests.post(url,files=files,data=,headers=headers) </code></pre> <p>You seem to be missing assigning data to data=.</p>
0
2016-08-22T05:16:11Z
[ "python", "django" ]
python input EOFError after set io encoding as utf8
39,070,621
<p>Python Version :3.5<br> OS Version: Windows7</p> <p>After I set environment variable <code>PYTHONIOENCODING=utf-8</code>, I can print some utf8 string (like love symbol \u2665, Korea words and Japanese words) as I expect.<br> (Before that i can only input Chinese word with gbk encoding but its totally worked fine.)...
1
2016-08-22T02:28:16Z
39,071,930
<p>What kind of compiler and terminal are you using?</p> <p>In Python 3.5 IDLE, this works fine:</p> <pre><code>key=input('输入:') </code></pre> <p>And in Python 2.7 IDLE, this works fine:</p> <pre><code>key=raw_input('输入:') </code></pre> <p>But in sublime Text 3, i should use this to declare using utf-8:</...
0
2016-08-22T05:30:12Z
[ "python", "encoding", "utf-8", "eof" ]
Python How to run two loops at the same time?
39,070,641
<p>So simpley put I want different objects to have there own tick loop code running independintley of eatchother. (As in one tickloop does not stop all other tick loops in my app) </p> <p>Ive created a basic module that has a class for shapes and a main body for spawning them however the tickloop of the class holds up...
0
2016-08-22T02:31:54Z
39,070,826
<p>I don't understand what your code is doing, but my suggestion is to use threading: <a href="https://pymotw.com/2/threading/" rel="nofollow">https://pymotw.com/2/threading/</a></p>
0
2016-08-22T03:01:21Z
[ "python", "loops" ]
Python How to run two loops at the same time?
39,070,641
<p>So simpley put I want different objects to have there own tick loop code running independintley of eatchother. (As in one tickloop does not stop all other tick loops in my app) </p> <p>Ive created a basic module that has a class for shapes and a main body for spawning them however the tickloop of the class holds up...
0
2016-08-22T02:31:54Z
39,070,933
<p>Roughly speaking, there are three ways to accomplish what you want. Which is best depends greatly on what exactly you're trying to do with each independent unit, and what performance constraints and requirements you have.</p> <p>The first solution is to have an independent loop that simply calls the <code>tick()</c...
1
2016-08-22T03:18:29Z
[ "python", "loops" ]
Variable error in Python
39,070,643
<p>I'm in a Python course and can't figure out why my code won't work: </p> <pre class="lang-py prettyprint-override"><code>import os def rename_files(): file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank") for file_name in file_list: os.rename(file_name, file_name.translate(None,"0123456789")) rename_files...
0
2016-08-22T02:32:40Z
39,070,656
<p>This is an indentation error. Your <code>for</code> loop is outside of the scope of <code>rename_files()</code> since it was not indented. It should be:</p> <pre><code>import os def rename_files(): file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank") for file_name in file_list: os.rename(file_nam...
2
2016-08-22T02:35:04Z
[ "python", "variables" ]
Variable error in Python
39,070,643
<p>I'm in a Python course and can't figure out why my code won't work: </p> <pre class="lang-py prettyprint-override"><code>import os def rename_files(): file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank") for file_name in file_list: os.rename(file_name, file_name.translate(None,"0123456789")) rename_files...
0
2016-08-22T02:32:40Z
39,070,657
<p>Let's walk-through your code:</p> <pre><code>def rename_files(): file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank") </code></pre> <p>In you <code>rename_files()</code> function, you have defined a function that returns nothing. You have set a local scoped <code>file_list</code> that will be released and ca...
0
2016-08-22T02:35:19Z
[ "python", "variables" ]
Variable error in Python
39,070,643
<p>I'm in a Python course and can't figure out why my code won't work: </p> <pre class="lang-py prettyprint-override"><code>import os def rename_files(): file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank") for file_name in file_list: os.rename(file_name, file_name.translate(None,"0123456789")) rename_files...
0
2016-08-22T02:32:40Z
39,070,658
<p>You need to indent your for loop so its within the body of your <code>rename_file</code> function:</p> <pre><code>import os def rename_files(): file_list = os.listdir(r"C:\Users\Kyle\Desktop\prank") for file_name in file_list: os.rename(file_name, file_name.translate(None,"0123456789")) rename_fi...
0
2016-08-22T02:35:21Z
[ "python", "variables" ]
Odd behavior in Fibonacci series in python 3?
39,070,729
<p>This does not print the correct Fibonacci series i.e. 1 1 2 3 5 8... </p> <pre><code>print ('Fibonacci series...') a,b = 0,1 while b&lt;50: print(b) a=b b = a+b </code></pre> <p>This does print the correct Fibonacci series. Aren't these two code snippets the same logically ? Please help, I am really confused. <...
-2
2016-08-22T02:48:13Z
39,070,757
<pre><code>a=b b = a+b </code></pre> <p>in the first code sample is equivalent to <code>b = b * 2</code>. Instead you want <code>b += original_value(a)</code>. So you either need to do tuple assignment, as in the second code sample (<code>a,b = b, a+b</code>), or use a temp variable:</p> <pre><code>temp = a a = b b +...
2
2016-08-22T02:51:54Z
[ "python", "python-2.7", "python-3.x" ]
Odd behavior in Fibonacci series in python 3?
39,070,729
<p>This does not print the correct Fibonacci series i.e. 1 1 2 3 5 8... </p> <pre><code>print ('Fibonacci series...') a,b = 0,1 while b&lt;50: print(b) a=b b = a+b </code></pre> <p>This does print the correct Fibonacci series. Aren't these two code snippets the same logically ? Please help, I am really confused. <...
-2
2016-08-22T02:48:13Z
39,070,801
<p>Firstly, there is an indentation error in the first code snippet. The last two lines should be indented so they are executed within the <code>while</code> loop.</p> <pre><code>print ('Fibonacci series...') a,b = 0,1 while b&lt;50: print(b) a = b b = a+b </code></pre> <p>However, this still won't produce the cor...
4
2016-08-22T02:57:44Z
[ "python", "python-2.7", "python-3.x" ]
Tracking an object via OpenCV
39,070,794
<p>I am trying to track an object and mask or Hide it (a CODE in this case) using OpenCV and Python. As example I am using this video , the code will showing on 1min19s : <a href="https://www.dropbox.com/s/eu01hxoxmd3ns5f/capture-3.mp4?dl=0" rel="nofollow">https://www.dropbox.com/s/eu01hxoxmd3ns5f/capture-3.mp4?dl=0</...
0
2016-08-22T02:56:48Z
39,070,948
<p>Tracking is much more complex than searching the similar colour. OpenCV has implemented some tracking algorithms, what you need to do is to use the existing apis to solve the problem. <a href="http://docs.opencv.org/3.1.0/d2/d0a/tutorial_introduction_to_tracker.html" rel="nofollow" title="Here">Here</a> is an introd...
0
2016-08-22T03:20:43Z
[ "python", "opencv" ]
License plate Detection from car camera
39,070,837
<p>I am using Python and Opencv. I am doing a project to recognize the license plate from a car camera.</p> <p>I have tried to use <code>Canny()</code>, but I still cant recognize the plate.</p> <p>Here is the frame I captured. <a href="http://i.stack.imgur.com/rSu3d.jpg" rel="nofollow"><img src="http://i.stack.imgur...
2
2016-08-22T03:02:56Z
39,071,471
<p>You could use minimal bounding rectangle of the convex hull to calculate the "rectangleness" of your candidate contours (in the latest version of openCV you can use <code>cv2.boxPoints</code> to calculate <code>rectPoints</code>):</p> <pre><code>def rectangleness(hull): rect = cv2.boundingRect(hull) rectPoi...
1
2016-08-22T04:33:13Z
[ "python", "image", "opencv", "image-processing" ]
How can I use get_next_by_FOO() in django?
39,070,840
<p>I am building blog website and trying to put <code>next</code> and <code>prev</code> buttons for next post and previous post respectively.</p> <p>In the official document, it explains <code>get_next_by_FOO(**kwargs)</code> and <code>where FOO is the name of the field. This returns the next and previous object with ...
0
2016-08-22T03:03:20Z
39,071,005
<p><code>get_next_by_FOO</code> works on the date field, think of it like "get me the next record ordered by the date (or datetime) field <em>FOO</em>".</p> <p>So <em>FOO</em> is the name of a date or datetime field.</p> <p>In your model, you can say "get me the next record based on timestamp", and this would be <cod...
1
2016-08-22T03:29:40Z
[ "python", "django", "blogs" ]
Python: Killing children's children process
39,070,857
<p>I have a process that calls:</p> <pre><code>p=multiprocessing.Process(target=func_a) </code></pre> <p>Then <code>func_a</code> starts a subprocess:</p> <pre><code>subprocess.Popen(["nc", "-l", "-p", str(dport)], stdout=open(os.devnull, "w")) </code></pre> <p>My problem is that when I call p.terminate(), it only ...
1
2016-08-22T03:06:19Z
39,073,176
<p>Register a handler with signal.signal like this:</p> <pre><code>#!/usr/bin/env python import signal import sys def signal_handler(signal, frame): #iterate over your subprocess and kill them sys.exit(0) signal.signal(signal."the signal", signal_handler) print('Press Ctrl+C') signal.pause() </code></p...
1
2016-08-22T07:05:16Z
[ "python", "subprocess", "multiprocessing", "signals", "kill" ]
Python: Killing children's children process
39,070,857
<p>I have a process that calls:</p> <pre><code>p=multiprocessing.Process(target=func_a) </code></pre> <p>Then <code>func_a</code> starts a subprocess:</p> <pre><code>subprocess.Popen(["nc", "-l", "-p", str(dport)], stdout=open(os.devnull, "w")) </code></pre> <p>My problem is that when I call p.terminate(), it only ...
1
2016-08-22T03:06:19Z
39,074,190
<p>I found a way to <strong>make sure the sub-process is killed before the multiprocessing process is killed</strong>:</p> <p>Create a class like this:</p> <pre><code>import subprocess import multiprocessing import time import os class MyProcess(multiprocessing.Process): def __init__(self): super(MyProce...
1
2016-08-22T08:03:55Z
[ "python", "subprocess", "multiprocessing", "signals", "kill" ]
read line from match string in file .. python
39,070,861
<p>I have this script that prints pool names from a F5 config file.. I want to run this on multiple F5 config files.. I want to be able to read from ^pool|^} (pool OR } bring start of line)... At the moment i am getting my desired output as i am telling the script to read from line 2348.. </p> <p>I want to eliminate t...
0
2016-08-22T03:06:48Z
39,072,419
<p>It is not completely clear what you want, but I'll try to guess. You are trying to get members for each pool. You didn't mention anything about <code>seenrule</code> - so I dropped it.</p> <p>If you don't want to parse this data structure, and if top-level block always and exlusively ends with line <code>'}\n'</cod...
0
2016-08-22T06:14:04Z
[ "python", "regex" ]
4 spaces for Indentation - Syntax error
39,070,917
<p>I'm using 4 spaces for indentation, but get a Syntax error. When I use the indentation in the Text editor, works fine. The text editor creates just 1 block, that I'm unable to edit it. Are spaces not able to be used as indentation?</p> <pre><code>def replace_line(file_name, line_num, text): try: lin...
1
2016-08-22T03:16:10Z
39,071,022
<p>If you're getting Syntax Error because of indentations it is most probably related to the fact that your code includes both <em>TABS</em> and <em>SPACES</em> as methods of indentation. Even though the code might appear to be be indented the same amount from the left, a <em>TAB</em> is a single symbol, whereas the sa...
6
2016-08-22T03:32:13Z
[ "python", "indentation" ]
4 spaces for Indentation - Syntax error
39,070,917
<p>I'm using 4 spaces for indentation, but get a Syntax error. When I use the indentation in the Text editor, works fine. The text editor creates just 1 block, that I'm unable to edit it. Are spaces not able to be used as indentation?</p> <pre><code>def replace_line(file_name, line_num, text): try: lin...
1
2016-08-22T03:16:10Z
39,085,312
<p>Throwing an exception: pass solves it. It is not needed when using indentation from a Text editor. That's weird.</p>
0
2016-08-22T17:21:50Z
[ "python", "indentation" ]
updating a deep key in a Nested JSON file
39,070,919
<p>I have a json file which looks like this:</p> <pre><code>{ "email": "abctest@xxx.com", "firstName": "name01", "surname": "Optional" "layer01": { "key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4", "layer02": { "key1": "val...
0
2016-08-22T03:16:14Z
39,095,509
<p>As much as I'd like to help you out, I find your code confusing, but I'll do my best. Here it goes</p> <p>For starters, by <code>temp= template</code> do you mean to do <code>temp= copy.deepcopy(template)</code>? Remember to <code>import copy</code> <a href="https://docs.python.org/2/library/copy.html" rel="nofollo...
0
2016-08-23T07:59:52Z
[ "python", "json" ]
updating a deep key in a Nested JSON file
39,070,919
<p>I have a json file which looks like this:</p> <pre><code>{ "email": "abctest@xxx.com", "firstName": "name01", "surname": "Optional" "layer01": { "key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4", "layer02": { "key1": "val...
0
2016-08-22T03:16:14Z
39,136,967
<p>Your algorithm is really close but there's a few things in it that complicate things unnecessarily. This makes it easy to miss the key line that's causing the problem:</p> <pre><code>template.update(temp) </code></pre> <p>temp is the child-most dictionary of the template but here you set the original template to ...
0
2016-08-25T04:59:28Z
[ "python", "json" ]
Isolating the background of a video with objects of interest present in the initial frame using openCV
39,070,929
<p>I'm using OpenCV to locate moving cars from a traffic cam. The video I'm working with starts off with the objects of interest in the initial frame. My question is how would I go about isolating the background without any of the vehicles, to serve as the frame of origin for subsequent motion detection. </p> <pre><c...
-1
2016-08-22T03:17:55Z
39,091,849
<p>To solve the problem you described, you should look more into object detection and classification. Locating moving cars is not particularly a background subtraction problem. An example of using Haar Cascades can be found here: <a href="https://github.com/andrewssobral/vehicle_detection_haarcascades" rel="nofollow">h...
0
2016-08-23T03:26:21Z
[ "python", "opencv" ]
How to subtract timestamps from two seperate columns, then enter this data into the table
39,070,975
<p>I am attempting to create a sign-in, sign-out program using python and mysql on a raspberry pi. I have so far successfully created a system for registering, signing in, and signing out, but am having trouble with the final component. I am trying to subtract the two separate time-stamps (signin, signout) using TIMEST...
0
2016-08-22T03:25:27Z
39,070,997
<p>You need an <code>update</code> query not <code>INSERT</code></p> <pre><code>UPDATE attendance SET `minutes` = TIMESTAMPDIFF(MINUTE, signin, signout); </code></pre>
0
2016-08-22T03:28:21Z
[ "python", "mysql", "raspberry-pi" ]
If-statement seemingly ignored by Write operation
39,071,078
<p>What I am trying to do here is write the latitude and longitude of the sighting of a pokemon to a text file if it doesn't already exist. Since I am using an infinite loop, I added an if-state that prevents an already existent pair of coordinates to be added. Note that I also have a list Coordinates that stores the s...
-1
2016-08-22T03:40:21Z
39,071,158
<p>You need to put your <code>Sighting</code> and <code>Coordinates</code> variables outside of the <code>while</code> loop if you do not want them to reset on every iteration.</p> <p>However, there are a lot more things wrong with the code. Without trying it, here's what I spot:</p> <ol> <li>You have no exit conditi...
2
2016-08-22T03:51:20Z
[ "python" ]
If-statement seemingly ignored by Write operation
39,071,078
<p>What I am trying to do here is write the latitude and longitude of the sighting of a pokemon to a text file if it doesn't already exist. Since I am using an infinite loop, I added an if-state that prevents an already existent pair of coordinates to be added. Note that I also have a list Coordinates that stores the s...
-1
2016-08-22T03:40:21Z
39,071,393
<p>Try this:</p> <pre><code>#!/usr/bin/env python import urllib2 import json pokemon_url = 'https://pogo.appx.hk/top' pokemon = urllib2.urlopen(pokemon_url) pokeset = json.load(pokemon) Coordinates = [None] * 100 for num in range(len(pokeset)): if pokeset[num]['pokemon_name'] == 'Aerodactyl': Lat = p...
0
2016-08-22T04:24:38Z
[ "python" ]
django.db.utils.OperationalError: no such table: auth_user
39,071,093
<p>After I install Django-userena,there is an error my django version :1.9.5 I just install django-userena step by step ,but when i migrate it ,an error happend and I don't how to solve it.</p> <pre><code> Traceback (most recent call last): File "manage.py", line 12, in &lt;module&gt; execute_from_command_lin...
0
2016-08-22T03:42:03Z
39,944,429
<pre><code>./manage.py migrate </code></pre> <p>if your Django version is 1.9 or lower, use</p> <pre><code>./manage.py syncdb </code></pre> <p>then </p> <pre><code>python manage.py createsuperuser </code></pre> <p>more details on <a href="https://github.com/django/django/blob/master/django/contrib/auth/forms.py" r...
0
2016-10-09T14:00:04Z
[ "python", "django", "django-guardian", "django-userena" ]
Upload and rename two different files in two different folders using django?
39,071,125
<p>I could upload two different files in the same folder using django. But I have to upload it to two different folders and also rename the files I uploaded as target.{file_extension} and probe.{file_extension}.I have no idea as I am a beginner to django.Could anyone please help me with my issue. My codes are:</p> <p...
0
2016-08-22T03:45:32Z
39,071,371
<p>if you check django docs for <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.FileField.upload_to" rel="nofollow">FileField</a> you see upload_to supports custom method:</p> <p>(from django docs)</p> <pre><code>def user_directory_path(instance, filename): # file will be upload...
2
2016-08-22T04:21:18Z
[ "python", "django" ]
key error: 'x' --> adding key value pair in for loop, key being char
39,071,156
<p>I am a beginner in python and I am trying to solve a coding problem, got this error. Don't understand why ? I went through a couple of Q/A's here but they don't seem to solve my problem. Essentially what I am trying to do is iterate over a string, through its characters and fill these characters in a dictionary. Wit...
-3
2016-08-22T03:51:02Z
39,071,226
<p>You need to check if <code>i</code> is in <code>charCounter</code> before you try to retrieve it:</p> <pre><code>if i in charCounter: charCounter[i] += 1 else: charCounter[i] = 1 </code></pre> <p>Or alternatively:</p> <pre><code>if charCounter.get(i): ... </code></pre>
0
2016-08-22T04:01:29Z
[ "python", "dictionary", "key" ]
key error: 'x' --> adding key value pair in for loop, key being char
39,071,156
<p>I am a beginner in python and I am trying to solve a coding problem, got this error. Don't understand why ? I went through a couple of Q/A's here but they don't seem to solve my problem. Essentially what I am trying to do is iterate over a string, through its characters and fill these characters in a dictionary. Wit...
-3
2016-08-22T03:51:02Z
39,071,590
<pre><code>if charCounter[i]: </code></pre> <p>throws <code>KeyError</code> if the key does not exist. What you want to do isuse <code>if i in charCounter:</code> instead:</p> <pre><code>if i in char_counter: char_counter[i] += 1 else: char_counter[i] = 1 </code></pre> <p>Alternatively you could use <code>ge...
0
2016-08-22T04:47:32Z
[ "python", "dictionary", "key" ]
OneHotEncoder confusion in scikit learn
39,071,205
<p>Using in Python 2.7 (miniconda interpreter). Confused by the example below about <code>OneHotEncoder</code>, confused why <code>enc.n_values_</code> output is <code>[2, 3, 4]</code>? If anyone could help to clarify, it will be great.</p> <p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.preproces...
0
2016-08-22T03:58:11Z
39,071,305
<p><code>n_values</code> is the number of values per feature.</p> <p>In this example,</p> <pre><code>X = 0 0 3 1 1 0 0 2 1 1 0 2 </code></pre> <p>(X's shape is [n_samples, n_feature])</p> <p>For the first feature, there are 2 values: 0, 1;</p> <p>For the second feature, there are 3 values: 0, 1, 2.</p>...
1
2016-08-22T04:12:28Z
[ "python", "python-2.7", "machine-learning", "scikit-learn", "one-hot-encoding" ]
Apply a function that manipulates a dataframe to a groupby
39,071,248
<p>I have a dataframe that has an index and a couple of other columns. The value in the index are not unique (in fact they repeat many times. Each index can be repeated ~10-20 times). Basically imagine something like this:</p> <pre><code>import random random.seed(4) arr = [[random.randint(1, 4)] + [random.random() for...
1
2016-08-22T04:04:25Z
39,073,246
<p>Let's start by using <code>pd.cut</code> across the entire <code>df_</code> to start.</p> <pre><code>cat = pd.cut(df_.values.flatten(), [-np.inf, .25, .75, np.inf]) cat_arr = cat.get_values().reshape(df_.shape) cat_df = pd.DataFrame(cat_arr, df_.index, df_.columns) </code></pre> <p><strong><em>Take a look</em></st...
1
2016-08-22T07:08:45Z
[ "python", "pandas" ]
Apply a function that manipulates a dataframe to a groupby
39,071,248
<p>I have a dataframe that has an index and a couple of other columns. The value in the index are not unique (in fact they repeat many times. Each index can be repeated ~10-20 times). Basically imagine something like this:</p> <pre><code>import random random.seed(4) arr = [[random.randint(1, 4)] + [random.random() for...
1
2016-08-22T04:04:25Z
39,081,635
<p>Reposting my comment as answer. It uses group by index with a custom agglomeration function based on numpy.</p> <pre><code>from __future__ import division import numpy as np import pandas as pd import random random.seed(4) arr = [[random.randint(1, 4)] + [random.random() for _ in xrange(3)]\ for i in xrange(10...
0
2016-08-22T14:04:25Z
[ "python", "pandas" ]
Parsing tweets' text out of "Status" wrapper in json file
39,071,262
<p>I used this tweepy-based <a href="https://gist.github.com/yanofsky/5436496" rel="nofollow">code</a> to pull the tweets of a given user by user_id. I then saved a list of all tweets of a given user (alltweets) to a json file as follows. Note that without "repr", i wasn't able to dump the alltweets list into json file...
0
2016-08-22T04:06:50Z
39,131,778
<p>Maybe not the prettiest solution but you could just declare <code>Status</code> as a <code>dict</code> and then <code>eval</code> the list (the whole content of the files).</p> <pre><code>Status = dict f = open(fname, 'r') data = eval(f.read()) f.close() for status in data: """ do your stuff""" </code></pre>
0
2016-08-24T19:39:58Z
[ "python", "tweepy" ]
Solving Non-Linear Differential Equation Sympy
39,071,334
<p>This code only works for solving the differential equation v_equation if v(t) isn't squared. When I squared it it returned the error PolynomialDivisionFailed. Is there another way of doing this with Sympy or should I find a different python package for doing these sorts of calculations.</p> <pre><code>from sympy im...
2
2016-08-22T04:16:47Z
39,073,773
<p>From my experience with symbolic math packages, I would not recommend performing (symbolic) calculations using floating point constants. It is better to define equations using symbolic constants, perform calculations as far as possible, and then substitute with numerical values. </p> <p>With this approach, Sympy ca...
3
2016-08-22T07:38:26Z
[ "python", "numpy", "sympy" ]
Get the number of same string in a list
39,071,351
<p>I want to get the no. of same string in a list</p> <p>Example</p> <pre><code>list = ['jack','jeen','jeen'] number_of_jeen = getnumber('jeen',list) print(number_of_jeen) </code></pre> <p>Output</p> <pre><code>2 </code></pre> <p>I have tried this so far</p> <pre><code>def getnumber(string_var,list): if any...
0
2016-08-22T04:19:15Z
39,071,441
<p>There's a built-in method <code>count</code> that does this.</p> <pre><code>number_of_jeen = list.count('jeen') </code></pre>
6
2016-08-22T04:29:59Z
[ "python" ]
Get the number of same string in a list
39,071,351
<p>I want to get the no. of same string in a list</p> <p>Example</p> <pre><code>list = ['jack','jeen','jeen'] number_of_jeen = getnumber('jeen',list) print(number_of_jeen) </code></pre> <p>Output</p> <pre><code>2 </code></pre> <p>I have tried this so far</p> <pre><code>def getnumber(string_var,list): if any...
0
2016-08-22T04:19:15Z
39,071,461
<p>Try just using a simple counter function. The idea is to loop through the list you have. In each iteration you are checking whether or not the name you are looking at is equal to 'jeen' in this case. If it is increment your counter, otherwise just move onto the next name. Below is an example:</p> <pre><code>listNam...
-2
2016-08-22T04:32:07Z
[ "python" ]
Get the number of same string in a list
39,071,351
<p>I want to get the no. of same string in a list</p> <p>Example</p> <pre><code>list = ['jack','jeen','jeen'] number_of_jeen = getnumber('jeen',list) print(number_of_jeen) </code></pre> <p>Output</p> <pre><code>2 </code></pre> <p>I have tried this so far</p> <pre><code>def getnumber(string_var,list): if any...
0
2016-08-22T04:19:15Z
39,071,530
<p>try this.it will work 100%</p> <pre><code>list=["jhon","jack","jack"] def get_count(list,name): return list.count(name) length=get_count(list,"jhon") print length </code></pre>
-2
2016-08-22T04:40:21Z
[ "python" ]
Get the number of same string in a list
39,071,351
<p>I want to get the no. of same string in a list</p> <p>Example</p> <pre><code>list = ['jack','jeen','jeen'] number_of_jeen = getnumber('jeen',list) print(number_of_jeen) </code></pre> <p>Output</p> <pre><code>2 </code></pre> <p>I have tried this so far</p> <pre><code>def getnumber(string_var,list): if any...
0
2016-08-22T04:19:15Z
39,071,987
<p>Use <code>Counter</code> from <code>collections</code>:</p> <pre><code>list = ['jack','jeen','jeen'] count = Counter(list) print(count['jeen']) </code></pre>
4
2016-08-22T05:36:07Z
[ "python" ]
Python MySQL Bulk Insertion Error with Character Encode
39,071,397
<p>I Start new Project in <strong>Python</strong> with <strong>MySQL</strong>.</p> <p>I just try to insert millions of record from <strong>CSV</strong> to <strong>MySQL</strong> through <strong>MySQLdb</strong> package. </p> <p><strong>My Code:</strong></p> <pre><code> import pandas as pd import MySQLdb #Connect...
0
2016-08-22T04:24:56Z
39,074,778
<p>I would let the pandas take care of encoding and you don't need to loop through your DF. Let's do it pandas way:</p> <pre><code>import pandas as pd import MySQLdb #Connect with MySQL db = MySQLdb.connect('localhost','root','****','MY_DB') cur = db.cursor() #Reading CSV df = pd.read_csv('/home/shankar/LAB/Python/...
1
2016-08-22T08:36:31Z
[ "python", "mysql", "csv", "pandas", "mysql-python" ]
Syntax error when there's a newline after an or operator
39,071,401
<p>This is OK:</p> <pre><code>if 'something' in data['meta']: &lt;do something&gt; </code></pre> <p>This is a syntax error. Why?</p> <pre><code>if ('something' in data['meta']) or ('something_else' in data['meta']): &lt;do something&gt; </code></pre> <p>The interpreter hands this out:</p> <pre><code> File...
-3
2016-08-22T04:25:24Z
39,071,436
<p>Newlines are important. Python needs to know how to parse things. For the second code snippet, you are separating the <code>if</code> into two lines, and Python doesn't like that since it looks like a separate command. Two common ways to span multiple lines is using a backslash or parentheses. For example, both of t...
8
2016-08-22T04:29:43Z
[ "python" ]
Syntax error when there's a newline after an or operator
39,071,401
<p>This is OK:</p> <pre><code>if 'something' in data['meta']: &lt;do something&gt; </code></pre> <p>This is a syntax error. Why?</p> <pre><code>if ('something' in data['meta']) or ('something_else' in data['meta']): &lt;do something&gt; </code></pre> <p>The interpreter hands this out:</p> <pre><code> File...
-3
2016-08-22T04:25:24Z
39,071,449
<p>That is a syntax error because Python expects your <code>if</code> statement to end on that line, and with <code>:</code>. </p> <p>However an expression such as this boolean one can continue to another line provided that you either</p> <ul> <li>you end the first line in backslash (<code>\</code>) character</li> <l...
4
2016-08-22T04:30:22Z
[ "python" ]
Syntax error when there's a newline after an or operator
39,071,401
<p>This is OK:</p> <pre><code>if 'something' in data['meta']: &lt;do something&gt; </code></pre> <p>This is a syntax error. Why?</p> <pre><code>if ('something' in data['meta']) or ('something_else' in data['meta']): &lt;do something&gt; </code></pre> <p>The interpreter hands this out:</p> <pre><code> File...
-3
2016-08-22T04:25:24Z
39,071,450
<p>breaking of line from "or" should be enclosed in brackets like:</p> <pre><code>if ('something' in data['meta'] or 'something_else' in data['meta']): &lt;do something&gt; </code></pre>
0
2016-08-22T04:30:37Z
[ "python" ]
Syntax error when there's a newline after an or operator
39,071,401
<p>This is OK:</p> <pre><code>if 'something' in data['meta']: &lt;do something&gt; </code></pre> <p>This is a syntax error. Why?</p> <pre><code>if ('something' in data['meta']) or ('something_else' in data['meta']): &lt;do something&gt; </code></pre> <p>The interpreter hands this out:</p> <pre><code> File...
-3
2016-08-22T04:25:24Z
39,071,474
<p>try code like this:</p> <pre><code>if ('something' in data['meta']) or ('something_else' in data['meta']): &lt;do something&gt; </code></pre>
-1
2016-08-22T04:33:26Z
[ "python" ]
Rectangle(quadrilateral) Detection by ConvexHull
39,071,418
<p>I want to detect the <strong>rectangle</strong> from an image. </p> <p>I used <code>cv2.findContours()</code> with <code>cv2.convexHull()</code> to filter out the irregular polygon.</p> <p>Afterwards, I will use the <strong>length of hull</strong> to determine whether the contour is a rectangle or not. </p> <pre>...
2
2016-08-22T04:27:15Z
39,073,169
<p>Well, This is not the right way to extract rectangles. Since we are talking basics here, I would suggest you to take the inversion of the image and apply Sobel in X and Y direction and then run the findcontours function. Then with this you will be able to get lot of rectangles that you can filter out. You will hav...
3
2016-08-22T07:04:40Z
[ "python", "opencv", "image-processing", "geometry" ]
Rectangle(quadrilateral) Detection by ConvexHull
39,071,418
<p>I want to detect the <strong>rectangle</strong> from an image. </p> <p>I used <code>cv2.findContours()</code> with <code>cv2.convexHull()</code> to filter out the irregular polygon.</p> <p>Afterwards, I will use the <strong>length of hull</strong> to determine whether the contour is a rectangle or not. </p> <pre>...
2
2016-08-22T04:27:15Z
39,107,558
<p>It isn't so easy to fit a rectangle to a convex polygon.</p> <p>You can try to find the minimum area or minimum perimeter rectangle by rotating calipers (<a href="https://en.wikipedia.org/wiki/Rotating_calipers" rel="nofollow">https://en.wikipedia.org/wiki/Rotating_calipers</a>).</p> <p>Then by comparing the areas...
0
2016-08-23T17:38:10Z
[ "python", "opencv", "image-processing", "geometry" ]
How to get number of rows in a grouped-by category in pandas
39,071,426
<p>In <code>pandas</code>, I have (<code>app_categ_events</code> is a <code>dataframe</code>):</p> <pre><code>&gt; print(app_categ_events.label_id.unique().shape) &gt; print(app_categ_events.category.unique().shape) Out: (492,) (458,) </code></pre> <p>I want to look at the <code>label_category</code>’s that have m...
3
2016-08-22T04:28:33Z
39,071,541
<p>We <code>transform</code> the dataset to create the 'count_rows' column after grouping by 'category', 'label_id' </p> <pre><code>app_categ_events['count_rows'] = app_categ_events.groupby(['category', 'label_id'])['label_id'].transform('count') print(app_categ_events) # category label_id count_...
3
2016-08-22T04:41:24Z
[ "python", "pandas" ]
How to get number of rows in a grouped-by category in pandas
39,071,426
<p>In <code>pandas</code>, I have (<code>app_categ_events</code> is a <code>dataframe</code>):</p> <pre><code>&gt; print(app_categ_events.label_id.unique().shape) &gt; print(app_categ_events.category.unique().shape) Out: (492,) (458,) </code></pre> <p>I want to look at the <code>label_category</code>’s that have m...
3
2016-08-22T04:28:33Z
39,071,587
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#filtration" rel="nofollow">filtration</a> to return the desired results.</p> <pre><code>df = pd.DataFrame({'label_id': [1, 1, 2, 3], 'category': ['a', 'b', 'b', 'c']}) df.groupby(['category']).filter(lambda group: len...
2
2016-08-22T04:47:15Z
[ "python", "pandas" ]
How to get number of rows in a grouped-by category in pandas
39,071,426
<p>In <code>pandas</code>, I have (<code>app_categ_events</code> is a <code>dataframe</code>):</p> <pre><code>&gt; print(app_categ_events.label_id.unique().shape) &gt; print(app_categ_events.category.unique().shape) Out: (492,) (458,) </code></pre> <p>I want to look at the <code>label_category</code>’s that have m...
3
2016-08-22T04:28:33Z
39,073,545
<p><strong><em>Given:</em></strong></p> <pre><code>app_categ_events = pd.DataFrame({'category': ['a', 'a', 'b', 'b'], 'label_id': [1, 1, 2, 3]}) </code></pre> <p><strong><em>Solution:</em></strong></p> <pre><code># identify categories with greater than 1 number of related label_id's ...
1
2016-08-22T07:26:31Z
[ "python", "pandas" ]
regarding a deprecation warning message in Python
39,071,480
<p>When running a python program involving the following function, <code>image[x,y] = 0</code> gives the following error message. What does that mean and how to solve it? Thanks.</p> <p>Warning</p> <pre><code>VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in th...
0
2016-08-22T04:33:47Z
39,071,615
<p>The warning is saying not to use floats to index your array; use <code>np.int</code> instead of <code>np.floor</code></p>
0
2016-08-22T04:51:09Z
[ "python", "numpy", "scipy" ]
Pika can connect to RabbitMq on ubuntu, but not work on Centos?
39,071,494
<p>The same code can work on Ubuntu, not work on Centos! Firewall already closed!</p> <p>Ubuntu 16.04, python version 3.5.2. </p> <p>Centos 7,python version 3.5.2.</p> <p>Ubuntu and centos are the newly installed in virtualbox! RabbitMq config tls!</p> <p>On Centos, if connect rabbitmq disable ssl is OK, but...
0
2016-08-22T04:35:19Z
39,120,233
<p>My server certificate uses md5WithRSAEncryption as the signature algorithm</p> <p><a href="https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Security_Guide/sec-Using_OpenSSL.html" rel="nofollow">redhat document about openssl</a></p> <p>I updated algorithm to SHA256. I works OK! :)</p> ...
0
2016-08-24T10:04:01Z
[ "python", "ubuntu", "centos", "rabbitmq", "python-pika" ]
How to convert list [a, b, c] to python slice index[:a, :b :c]?
39,071,610
<p>For example, I'm having a group of multi-dimension arrays. I want to write a method to specify the size of the slice for this array such as:</p> <pre><code>slice = data[:a, :b, :c] </code></pre> <p>Because I could only get a list of [a, b, c]. I want to know how can I convert this list to slice index. Or is there ...
3
2016-08-22T04:49:57Z
39,071,627
<p>Use the <a href="https://docs.python.org/3/library/functions.html#slice" rel="nofollow">slice()</a> function.</p> <pre><code>my_list = [a, b, c] my_slices = tuple(slice(x) for x in my_list) my_slice = data[my_slices] </code></pre> <p>(I updated the variable names to avoid shadowing the builtins by mistake.)</p> <...
5
2016-08-22T04:53:15Z
[ "python", "arrays", "list" ]
numpy reshape confusion with negative shape values
39,071,630
<p>Always confused how numpy reshape handle negative shape parameter, here is an example of code and output, could anyone explain what happens for reshape [-1, 1] here? Thanks.</p> <p>Related document, using Python 2.7.</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofol...
0
2016-08-22T04:53:24Z
39,071,682
<p><code>-1</code> is used to infer one missing length from the other. For example reshaping <code>(3,4,5)</code> to <code>(-1,10)</code> is equivalent to reshaping to <code>(6,10)</code> because <code>6</code> is the only length that makes sense form the other inputs. </p>
1
2016-08-22T04:59:38Z
[ "python", "python-2.7", "numpy", "machine-learning", "scikit-learn" ]
numpy reshape confusion with negative shape values
39,071,630
<p>Always confused how numpy reshape handle negative shape parameter, here is an example of code and output, could anyone explain what happens for reshape [-1, 1] here? Thanks.</p> <p>Related document, using Python 2.7.</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofol...
0
2016-08-22T04:53:24Z
39,071,706
<p>From <code>reshape</code> docs:</p> <blockquote> <p>One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.</p> </blockquote> <p>In your case it is used for the common task of transforming the (3,) <code>S</code> into a (3,1) array. I think in t...
1
2016-08-22T05:03:36Z
[ "python", "python-2.7", "numpy", "machine-learning", "scikit-learn" ]
Is it possible to run caffe models on the data-set which is not stored in data-source like LMDB?
39,071,870
<p>I have 2 sets of image patches data i.e. training and testing sets. Both of these have been written to LMDB files. I am running convolutional neurall network on this data using Caffe.</p> <p>The problem is that the data stored on hard disk is occupying considerable amount of space and is hampering my efforts to int...
1
2016-08-22T05:23:46Z
39,091,710
<p>You can write your own python data layer. See discussions <a href="https://groups.google.com/forum/#!topic/caffe-users/aEGXQRFutc8" rel="nofollow">here</a> and implementation for of input data layer for video stream <a href="https://github.com/LisaAnne/lisa-caffe-public/blob/lstm_video_deploy/examples/LRCN_activity_...
0
2016-08-23T03:09:03Z
[ "python", "caffe", "conv-neural-network", "lmdb" ]
Is it possible to run caffe models on the data-set which is not stored in data-source like LMDB?
39,071,870
<p>I have 2 sets of image patches data i.e. training and testing sets. Both of these have been written to LMDB files. I am running convolutional neurall network on this data using Caffe.</p> <p>The problem is that the data stored on hard disk is occupying considerable amount of space and is hampering my efforts to int...
1
2016-08-22T05:23:46Z
39,097,123
<p>Other than defining custom python layers, you can use the following options:</p> <ul> <li><p>use <code>ImageData</code> layer: it has a source parameter (source: name of a text file, with each line giving an image filename and label)</p></li> <li><p>use <code>MemoryData</code> layer: using which you can load input ...
0
2016-08-23T09:15:38Z
[ "python", "caffe", "conv-neural-network", "lmdb" ]
pass the contents of a file as a parameter in python
39,071,915
<p>I am trying to download the files based on their ids. How can I download the files if i have their IDS stored in a text file. Here's what I've done so far</p> <pre><code>import urllib2 #code to read a file comes here uniprot_url = "http://www.uniprot.org/uniprot/" # constant Uniprot Namespace def get_fasta(id):...
3
2016-08-22T05:28:35Z
39,071,945
<p><a href="https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow"><code>.readlines()</code></a> returns a list of lines in file. According to an oficial documentation you can also amend it</p> <blockquote> <p>For reading lines from a file, you can loop over the file object. Thi...
3
2016-08-22T05:31:49Z
[ "python", "parsing" ]
PEP 8 E211 issue raised. Not sure why
39,071,967
<p>My code:</p> <pre><code>if 'certainField' in myData['meta']['loc']: something = myData['meta'] \ &lt;- PEP8 E11 raised for this ['loc'] \ &lt;- PEP8 E11 raised for this ['certainField'] \ &lt;- PEP8 E11 raised for this ['thefield'] </code></p...
3
2016-08-22T05:34:05Z
39,072,055
<p>You can wrap your statement into parenthesis and remove <kbd>\</kbd></p> <pre><code>if 'certainField' in myData['meta']['loc']: something = (myData['meta'] ['loc'] ['certainField'] ['thefield']) </code></pre> <p><hr> Here is an excerpt form <a href="https://ww...
1
2016-08-22T05:42:17Z
[ "python" ]
How to convert a single column Pandas DataFrame into Series
39,072,010
<p>I have the following data frame:</p> <pre><code>import pandas as pd d = {'gene' : ['foo','bar'],'score' : [4., 3.,]} df = pd.DataFrame(d) df.set_index('gene',inplace=True) </code></pre> <p>Which make:</p> <pre><code>In [56]: df Out[56]: score gene foo 4 bar 3 In [58]: type(df) Out[58]: pandas.co...
2
2016-08-22T05:37:38Z
39,072,042
<p>Try swapping the indices in the brackets:</p> <pre><code>df.iloc[:,0] </code></pre> <p>This should work.</p>
3
2016-08-22T05:41:07Z
[ "python", "pandas" ]
How to convert a single column Pandas DataFrame into Series
39,072,010
<p>I have the following data frame:</p> <pre><code>import pandas as pd d = {'gene' : ['foo','bar'],'score' : [4., 3.,]} df = pd.DataFrame(d) df.set_index('gene',inplace=True) </code></pre> <p>Which make:</p> <pre><code>In [56]: df Out[56]: score gene foo 4 bar 3 In [58]: type(df) Out[58]: pandas.co...
2
2016-08-22T05:37:38Z
39,072,156
<pre><code>s = df.squeeze() &gt;&gt;&gt; s gene foo 4 bar 3 Name: score, dtype: float64 </code></pre> <p>To get it back to a dataframe:</p> <pre><code>&gt;&gt;&gt; s.to_frame() score gene foo 4 bar 3 </code></pre>
5
2016-08-22T05:52:58Z
[ "python", "pandas" ]
Adding arbitrary number of arguments to subclass?
39,072,069
<pre><code>class Restaurant(): def __init__(self, restaurant_name, cuisine_type): """ initializing name and cuisine attributes""" self.name = restaurant_name self.c_type = cuisine_type self.number_served = 0 class IceCreamStand(Restaurant): """represents aspects of a type of resta...
0
2016-08-22T05:43:27Z
39,072,147
<p>You can add a <code>*</code> before <code>flavors</code> to get all remaining positional arguments into that list.</p> <hr> <p>Actually, I'd recommend that you wouldn't use multiple positional arguments for flavors. Pass a <code>list</code> in instead:</p> <pre><code>def __init__(self, restaurant_name, cuisine_ty...
1
2016-08-22T05:51:43Z
[ "python", "class", "inheritance" ]
Position of Matplotlib Pyplot bar chart labels not consistent with nan values
39,072,221
<p>I'm plotting bar charts of data that contains missing values (np.nan). It seems as though when the np.nan value appears in the last category, the x-axis ticks are positioned differently than when there are no np.nans or when the NaN values are in a different position.</p> <pre><code>import numpy as np import matpl...
0
2016-08-22T05:58:59Z
39,072,319
<p>I found one solution:</p> <p>replace the y1, y2, y3 arrays with <code>np.nan_to_num(y1)</code> ...etc</p>
0
2016-08-22T06:07:13Z
[ "python", "matplotlib", "bar-chart", "axis-labels" ]
Position of Matplotlib Pyplot bar chart labels not consistent with nan values
39,072,221
<p>I'm plotting bar charts of data that contains missing values (np.nan). It seems as though when the np.nan value appears in the last category, the x-axis ticks are positioned differently than when there are no np.nans or when the NaN values are in a different position.</p> <pre><code>import numpy as np import matpl...
0
2016-08-22T05:58:59Z
39,072,390
<p>If you need a specific range on the plot, you can just set it explicitly. After each block add, e.g.</p> <pre><code>ax.set_xlim(-0.5, years.size - 0.5) </code></pre> <p><a href="http://i.stack.imgur.com/rpgfZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/rpgfZ.png" alt="enter image description here"></a><...
2
2016-08-22T06:12:08Z
[ "python", "matplotlib", "bar-chart", "axis-labels" ]
Uiautomator for android TV
39,072,244
<p>I'm using Uiautomator tool in python for android phone. But , now I'm interested using it on android TV.</p> <p>I did the setup for android tv same as that of android phone. But I found that message_app.click()will not work in TV.</p> <p>Below is my code snippet</p> <pre><code>from uiautomator import Device d = D...
0
2016-08-22T06:00:46Z
39,402,408
<p>On Android TV, users primarily use the DPad to navigate and click on elements.</p> <p>You can use <a href="https://developer.android.com/reference/android/support/test/uiautomator/UiDevice.html#pressDPadDown()" rel="nofollow">UiDevice.pressDPadDown()</a> (or up, left, right, etc) to change focus and <a href="https:...
0
2016-09-09T01:16:04Z
[ "android", "python", "ui-automation", "android-uiautomator" ]
How to wrap child methods multiple times in an inheritance tree?
39,072,269
<p>In a framework, I often want to provide a base class that the framework user sub classes. The base class provides controlled access to the base class. One way to accomplish this is to provide unimplemented methods with different names, for example by adding an underscore as prefix:</p> <pre><code>class Base: d...
3
2016-08-22T06:03:16Z
39,074,114
<p>Does this give you what you want?</p> <pre><code>import abc class Base(object): __metaclass__ = abc.ABCMeta def calculate(self): result = self.doCalculate() if 3 &lt; result &lt; 7: # do whatever validation you want return result else: raise ValueError() ...
2
2016-08-22T07:59:12Z
[ "python", "python-3.x", "inheritance", "design-patterns", "frameworks" ]
How to wrap child methods multiple times in an inheritance tree?
39,072,269
<p>In a framework, I often want to provide a base class that the framework user sub classes. The base class provides controlled access to the base class. One way to accomplish this is to provide unimplemented methods with different names, for example by adding an underscore as prefix:</p> <pre><code>class Base: d...
3
2016-08-22T06:03:16Z
39,074,497
<p>I think the question focuses on different points where behavior extension in an intermediate class can happen. The intermediate class obviously shall refine the "<em>control</em>" part here. </p> <h1>1st Solution</h1> <p>Mostly this can be done the classical way by just overriding the "safe" method - particularly...
1
2016-08-22T08:21:09Z
[ "python", "python-3.x", "inheritance", "design-patterns", "frameworks" ]
Tkinter : How to change position of text on image
39,072,285
<p>I have developed some application on my laptop with python and tkinter. Then, I was stuck at some point. Question is : how can I change text position on image.</p> <pre><code>import tkinter as tk from PIL import Image, ImageTk path_to_pic = "....." root = tk.Tk() pic = Image.open(path_to_pic) tkpic = ImageTk.Photo...
0
2016-08-22T06:04:16Z
39,072,871
<p>You can move text horizontally and vertically by adding spaces and '\n's respectively, to any side(s) of the text you wish:</p> <pre><code>text = "caption \n\n\n\n\n\n\n" </code></pre> <p>This will put "caption" at the top left of the text.</p>
0
2016-08-22T06:46:50Z
[ "python", "tkinter" ]
Implement comparison operator for Enum type in python3
39,072,301
<p>I'm really beginner in Python, so please forgive me if this is something obvious. </p> <p>I have an enum class, and I want to be able to compare the members. Below code seems to do what I want ( but not how I want )</p> <pre><code>import enum class AB(enum.Enum): a=1 b=2 c=3 d=4 e=5 @cla...
2
2016-08-22T06:05:28Z
39,072,454
<p>The <code>__le__</code> method should be called as a member function of the LHS operand and takes the RHS operand as its parameter.</p> <p>However it's not clear from your code which member variables of an <code>AB</code> object should be used in the comparison, so I can't really write the code for you.</p> <p>Ro...
1
2016-08-22T06:17:19Z
[ "python", "python-3.x", "enums" ]
Implement comparison operator for Enum type in python3
39,072,301
<p>I'm really beginner in Python, so please forgive me if this is something obvious. </p> <p>I have an enum class, and I want to be able to compare the members. Below code seems to do what I want ( but not how I want )</p> <pre><code>import enum class AB(enum.Enum): a=1 b=2 c=3 d=4 e=5 @cla...
2
2016-08-22T06:05:28Z
39,072,494
<p>Thanks to @Rawing and @machine yearning,</p> <pre><code>import enum class AB(enum.Enum): a=1 b=2 c=3 d=4 e=5 def __le__(self, other): return(self.value &lt;= other.value) if AB.c &lt;= AB.d: print('Do this') else: print('Do that') </code></pre>
0
2016-08-22T06:20:38Z
[ "python", "python-3.x", "enums" ]
Implement comparison operator for Enum type in python3
39,072,301
<p>I'm really beginner in Python, so please forgive me if this is something obvious. </p> <p>I have an enum class, and I want to be able to compare the members. Below code seems to do what I want ( but not how I want )</p> <pre><code>import enum class AB(enum.Enum): a=1 b=2 c=3 d=4 e=5 @cla...
2
2016-08-22T06:05:28Z
39,072,500
<p><code>Enum</code> subclasses are somewhat special in that all enumeration values become <em>instances</em> of the class (with a few tweaks). This does mean you can 'just' define a normal method on the <code>Enum</code> subclass and they'll be available on each enumeration value.</p> <p>This applies to special metho...
3
2016-08-22T06:20:47Z
[ "python", "python-3.x", "enums" ]
Display wrong Result in different Excel sheet Python
39,072,514
<p>I wish to have 1 python file that can display the results in different Excel sheet, now I able to list out 3 tabs with 3 worksheets,but for/if loop at second sheet that show me empty result. I able to get the results correct in first sheet but not second sheet.</p> <pre><code>for module in data: #Go to first sheet ...
-9
2016-08-22T06:21:46Z
39,162,563
<pre><code>if len(MY_MODULE[0])==3: #Length in Scrum Field pass else: worksheet2.write_row(row, col, MY_MODULE) row += 1 if MY_MODULE[0]in ('TPI','SCN','ARR','FUN','MIO','CLK','HTD','SIO','PTH'): #Name in Scrum Field pass else: worksheet2.write_row(row, col, MY_MODULE) row += 1 </code></pre> <p>Here tw...
1
2016-08-26T09:09:14Z
[ "python", "python-3.x", "worksheet", "xlsxwriter" ]
Sending values from one python script to another from different computer
39,072,750
<p>So, I have 2 raspberry pi's. I need to be able to transfer objects (simple single int value) across from one to the other.</p> <p>The programs are python. One is basically just acting as a controller for the other.</p> <p>Will the client/ server model work for something like that (from multiprocessing module), or ...
-1
2016-08-22T06:39:58Z
39,073,259
<p>I would suggest you google the python socket module: <a href="https://docs.python.org/2/library/socket.html" rel="nofollow">https://docs.python.org/2/library/socket.html</a></p> <p>I used it t send values from a server to my android device, so I guess it should work with two rasbberries . There is a good youtube tu...
0
2016-08-22T07:09:22Z
[ "python", "raspberry-pi3" ]
how to draw a font's glyphs using svg?
39,072,794
<p>I'm trying to draw all glyphs of a ttf font file. I have created a XML file using TTX and parsed it with python to write html file and create SVG. but SVG doesn't support curves with more than two control points so the outlines are not what they should be.</p> <p>How can I fix this? or is there any other way to dra...
0
2016-08-22T06:43:02Z
39,085,693
<p>Truetype fonts don't use cubic beziers. They use quadratic beziers. So if you see a sequence of points: "on, off, off on", that is not a cubic bezier with two end points and two control points. That is actually a quadratic bezier with two endpoints ("on curve" points), two control points ("off curve" points), and ...
1
2016-08-22T17:46:36Z
[ "python", "html", "svg", "fonts", "bezier-curve" ]
How to solve " django.db.utils.OperationalError: FATAL: password authentication failed for user "Oeloun-pc" " in Pycharm Windows?
39,072,802
<p>Below is my screenshot of PyCharm including settings.py and pg_hba.conf file.</p> <p>PyCharm with pg_hba.conf screen:</p> <p><a href="http://i.stack.imgur.com/tM6YQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/tM6YQ.png" alt="enter image description here"></a></p>
1
2016-08-22T06:43:25Z
39,073,136
<p>Use </p> <pre><code>'USER': 'admin', </code></pre> <p>instead of </p> <pre><code>'USERNAME': 'admin', </code></pre>
0
2016-08-22T07:02:48Z
[ "python", "django", "postgresql" ]
Parse out part of URL using regex in Python
39,073,067
<p>I want to parse out a part of URL using regex operation. This might be old question. But I am new to regex and searched so much for my requirement and not able to find it. I know ParseURL can be used here. But my URLs are not properly structured to use that. Suppose my URL is as follows,</p> <pre><code>url = https:...
0
2016-08-22T06:59:10Z
39,073,163
<p>You can use <code>re.search()</code> to get the desired substring and then replace all <code>+</code> with spaces with <code>str.replace()</code>:</p> <pre><code>re.search(r'/&amp;q=([^&amp;]*)', url).group(1).replace('+', ' ') </code></pre> <ul> <li><code>re.search(r'/&amp;q=([^&amp;]*)', url).group(1)</code> get...
3
2016-08-22T07:04:23Z
[ "python", "regex", "python-2.7" ]
storing and retriving lists from files
39,073,072
<p>I have a very big list of lists. One of my programs does this :</p> <pre><code>power_time_array = [[1,2,3],[1,2,3]] # In a short form with open (file_name,'w') as out: out.write (str(power_time_array)) </code></pre> <p>Now another independent script need to read this list of lists back.</p> <p>How do I d...
3
2016-08-22T06:59:42Z
39,073,217
<p>You can serialize your list to json and deserialize it back. This really doesn't change anything in representation, your list is already valid json:</p> <pre><code>import json power_time_array = [[1,2,3],[1,2,3]] # In a short form with open (file_name,'w') as out: json.dump(power_time_array, out) </code></p...
3
2016-08-22T07:07:12Z
[ "python", "list" ]
storing and retriving lists from files
39,073,072
<p>I have a very big list of lists. One of my programs does this :</p> <pre><code>power_time_array = [[1,2,3],[1,2,3]] # In a short form with open (file_name,'w') as out: out.write (str(power_time_array)) </code></pre> <p>Now another independent script need to read this list of lists back.</p> <p>How do I d...
3
2016-08-22T06:59:42Z
39,073,252
<p>Use <a href="https://docs.python.org/2.7/library/json.html" rel="nofollow">Json</a> library to efficiently read and write structured information (in the form of JSON) to a text file.</p> <ul> <li>To write data on the file, use <a href="https://docs.python.org/2.7/library/json.html#json.load" rel="nofollow">json.dum...
3
2016-08-22T07:09:02Z
[ "python", "list" ]
storing and retriving lists from files
39,073,072
<p>I have a very big list of lists. One of my programs does this :</p> <pre><code>power_time_array = [[1,2,3],[1,2,3]] # In a short form with open (file_name,'w') as out: out.write (str(power_time_array)) </code></pre> <p>Now another independent script need to read this list of lists back.</p> <p>How do I d...
3
2016-08-22T06:59:42Z
39,073,893
<p>It will be faster:</p> <pre><code>from ast import literal_eval power_time_array = [[1,2,3],[1,2,3]] with open(file_name, 'w') as out: out.write(repr(power_time_array)) with open(file_name,'r') as app_trc_file: power_trace_of_application.append(literal_eval(app_trc_file.read())) </code></pre>
0
2016-08-22T07:44:59Z
[ "python", "list" ]
How to adress data imported with pandas?
39,073,123
<p>I am using pandas to import some .dta file and numpy/sklearn to do some statistics on the set. I call the data <code>sample</code> I do the following: </p> <pre><code># import neccessary packages import pandas as pd import numpy as np import sklearn as skl # import data and give a little overview (col = var1-v...
4
2016-08-22T07:01:57Z
39,073,307
<p>See this contrived example. Usually I don't like messing with <code>locals()</code> and <code>globals()</code> but I don't see a cleaner way:</p> <pre><code>class A: def __init__(self): self.var1 = 1 self.var2 = 2 obj = A() locals().update(obj.__dict__) print(var1) print(var2) &gt;&gt; 1 2...
4
2016-08-22T07:12:04Z
[ "python", "variables", "pandas", "error-handling" ]
python 3.5 tkinter.listbox change size
39,073,213
<p>Could anyone advise me what's wrong go with the following code? I try to build a tkinker.listbox with dimensions can be changed with .config command, yet failed. Instead, it produce the error of "AttributeError: 'MovListbox' object has no attribute 'tk'" The code is attached below for your reference. </p> <p>Many t...
0
2016-08-22T07:07:06Z
39,074,442
<p>I've made a few modifications to your code; it's probably not exactly what you want, but you should find it helpful.</p> <p>The Listbox width and height options are not pixel measurements; they specify dimensions in terms of characters, so <code>height=12</code> makes the Listbox 12 text lines high, and <code>width...
1
2016-08-22T08:18:02Z
[ "python", "python-3.x", "tkinter", "listbox" ]
Django/Python: UnboundLocalError. where is my mistake?
39,073,308
<p>models.py</p> <pre><code>class Revistapresei(models.Model): titlulArticol = models.CharField(max_length=300) textArticol = models.TextField() dataArticol = models.DateField(blank=True, null=True) linkArticol = models.CharField(blank=True, max_length=200) STIRIINTERNE = 'Interne' STIRIEXTERN...
-1
2016-08-22T07:12:11Z
39,073,422
<p>In your function <code>revistaPresei_detail(request, pk)</code> you have a wrong parameter in the call <code>revistaPresei = get_object_or_404(revistaPresei, pk=pk)</code>.</p> <p><code>get_object_or_404</code> wants the class name as the first parameter so you have to use <code>revistaPresei = get_object_or_404(Re...
1
2016-08-22T07:18:43Z
[ "python", "django", "view" ]
Calling a function from another python script with a while loop
39,073,408
<p>I have a python script with a function and a while loop and I want to call this function from another python script which also has a while loop. Here is an example script:</p> <p>script1.py:</p> <pre><code>global printline printline = abc def change(x): global printline printline = x while True: glob...
0
2016-08-22T07:18:01Z
39,073,681
<p>When you do <code>from script1 import change</code>, it executes all the top-level code in <code>script1.py</code>. So it executes the <code>while True:</code> block, which loops infinitely, and it never returns back to <code>script2.py</code>.</p> <p>You need to split up <code>script1.py</code> so that you can imp...
1
2016-08-22T07:33:14Z
[ "python" ]
Calling a function from another python script with a while loop
39,073,408
<p>I have a python script with a function and a while loop and I want to call this function from another python script which also has a while loop. Here is an example script:</p> <p>script1.py:</p> <pre><code>global printline printline = abc def change(x): global printline printline = x while True: glob...
0
2016-08-22T07:18:01Z
39,076,946
<p>Thanks. I'll try that and see if it works.</p>
0
2016-08-22T10:18:11Z
[ "python" ]
"python.exe has stopped working" crash, FigureCanvasTkAgg.show()
39,073,595
<p>I am running an Anaconda environment with python 3.4, on Windows 7 <code>canvas.show()</code> is causing my python code to crash: </p> <p><strong>EDIT</strong> : my last example was missing the mainloop() function, so I recreated a better example from sentdex's youtube tutorial <a href="https://www.youtube.com/watc...
0
2016-08-22T07:28:58Z
39,076,290
<p>I was able to reproduce the problem after adding <code>from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg</code></p> <p>After adding <code>root.mainloop()</code> there was no crashing.</p>
0
2016-08-22T09:47:59Z
[ "python", "matplotlib", "tkinter", "anaconda" ]
Numpy: Negative Execution Time for exponentiation operation
39,073,699
<p>I am multiplying two large matrices, and it turns out the operation is faster when I first perform exponentiation on the first input:</p> <pre><code>import time import numpy as np a = np.asarray(np.random.uniform(-1,1, (100,40000)), dtype=np.float32) b = np.asarray(np.random.uniform(-1,1, (40000,20000)), dtype=np....
2
2016-08-22T07:34:12Z
39,077,685
<p>I suspect this to be a matter of memory-caching, since inverting the order of the executions</p> <pre><code>import time import numpy as np a = np.asarray(np.random.uniform(-1,1, (100,4000)), dtype=np.float32) b = np.asarray(np.random.uniform(-1,1, (4000,20000)), dtype=np.float32) start = time.time() d1 = np.dot(n...
1
2016-08-22T10:54:21Z
[ "python", "numpy", "numeric", "execution-time", "exponentiation" ]
Numpy: Negative Execution Time for exponentiation operation
39,073,699
<p>I am multiplying two large matrices, and it turns out the operation is faster when I first perform exponentiation on the first input:</p> <pre><code>import time import numpy as np a = np.asarray(np.random.uniform(-1,1, (100,40000)), dtype=np.float32) b = np.asarray(np.random.uniform(-1,1, (40000,20000)), dtype=np....
2
2016-08-22T07:34:12Z
39,077,915
<p>What you are seeing is the reason why you would never run an operation only once when you are benchmarking, which is kind of what you are attempting here. Many things will affect the result you are seeing when you're only doing it once. In this case, probably some caching-effect. Also, the b array is so much bigger ...
2
2016-08-22T11:04:30Z
[ "python", "numpy", "numeric", "execution-time", "exponentiation" ]
Python2 - Summing "for" loop output
39,073,840
<p>I'm trying to make a script that takes a balances of multiple addresses from a json file and adds them together to make a final balance.</p> <p>This is the code so far -</p> <pre><code>import json from pprint import pprint with open('hd-wallet-addrs/addresses.json') as data_file: data = json.load(data_fil...
0
2016-08-22T07:42:30Z
39,073,881
<p>You can use <code>sum</code> function and list comprehension:</p> <pre><code>sum([float(b['balance']) for b in balance]) </code></pre>
0
2016-08-22T07:44:33Z
[ "python", "json", "python-2.7", "for-loop" ]
Python2 - Summing "for" loop output
39,073,840
<p>I'm trying to make a script that takes a balances of multiple addresses from a json file and adds them together to make a final balance.</p> <p>This is the code so far -</p> <pre><code>import json from pprint import pprint with open('hd-wallet-addrs/addresses.json') as data_file: data = json.load(data_fil...
0
2016-08-22T07:42:30Z
39,073,905
<p>Most pythonic way to achieve this will be:</p> <pre><code>final_balance = sum(map(float, [balance['balance'] for balance in data])) </code></pre> <p><a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow">map()</a> will convert the list of <code>str</code> numbers to <code>float</code> number...
1
2016-08-22T07:45:43Z
[ "python", "json", "python-2.7", "for-loop" ]