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
Add additional line to QTableView object at a given position
40,053,267
<p>In my Gui I creats a QTableView with a QStandardItemModel and I would like to add either an additional row or column at a given position.</p> <pre><code>class Output(object): def __init__(self): ''' ''' self.tabs = QtGui.QTabWidget() self.group_box = QtGui.QGroupBox('Example') def r...
0
2016-10-14T23:14:16Z
40,053,416
<p>Untested, but try holding a reference to your model<br> then call the appropriate methods of the model (insertRow, insertColumn).<br> The effect of these methods will be apparent in the view. E.g.:</p> <pre><code>table_view = QtGui.QTableView() table_view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) table_view...
1
2016-10-14T23:34:38Z
[ "python", "qt", "pyside" ]
Getting error on if and elif
40,053,366
<p>Does anyone know why I keep getting an error with this section of my code?</p> <pre><code> if db_orientation2 =="Z": a="/C=C\" elif db_orientation2=="E": a="\C=C\" </code></pre> <p>This is the error:</p> <pre><code>File "&lt;ipython-input-7-25cda51c429e&gt;", line 11 a="/C=C\" ...
1
2016-10-14T23:26:21Z
40,053,376
<p>String literals cannot end with a backslash. You'll have to double it:</p> <pre><code>a="/C=C\\" # ^ </code></pre> <p>The highlighting of your code also clearly shows the problem.</p>
4
2016-10-14T23:28:14Z
[ "python" ]
Python: sorting the lists of dictionary based on the indices of one list
40,053,399
<p>So I have dict like the following:</p> <pre><code>dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]} </code></pre> <p>How can I sort the lists in <code>dict1</code> based on the indices that would sort one of the lists. Such as the sorted indices of list </p> <pre><code>[11, 10, 9, 8, 7] </code></pre> <p>which ...
1
2016-10-14T23:32:34Z
40,053,451
<p>One way would be to compute the index list and apply it to all lists:</p> <pre><code>&gt;&gt;&gt; dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]} &gt;&gt;&gt; basis = dict1[2] &gt;&gt;&gt; indexes = sorted(range(len(basis)), key=basis.__getitem__) &gt;&gt;&gt; for lst in dict1.values(): lst[:] = [lst[i]...
4
2016-10-14T23:39:03Z
[ "python", "list", "dictionary" ]
Python: sorting the lists of dictionary based on the indices of one list
40,053,399
<p>So I have dict like the following:</p> <pre><code>dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]} </code></pre> <p>How can I sort the lists in <code>dict1</code> based on the indices that would sort one of the lists. Such as the sorted indices of list </p> <pre><code>[11, 10, 9, 8, 7] </code></pre> <p>which ...
1
2016-10-14T23:32:34Z
40,053,494
<p>Sort using enumerate to get the sorted indexes and just use the indexes to sort the other lists:</p> <pre><code>from operator import itemgetter dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]} l = [i for i, _ in sorted(enumerate(dict1[2]), key=itemgetter(1))] for v in dict1.values(): v[:] = (v[i] for i in...
1
2016-10-14T23:44:41Z
[ "python", "list", "dictionary" ]
Python: sorting the lists of dictionary based on the indices of one list
40,053,399
<p>So I have dict like the following:</p> <pre><code>dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]} </code></pre> <p>How can I sort the lists in <code>dict1</code> based on the indices that would sort one of the lists. Such as the sorted indices of list </p> <pre><code>[11, 10, 9, 8, 7] </code></pre> <p>which ...
1
2016-10-14T23:32:34Z
40,054,577
<p>Using <a href="https://docs.python.org/2/library/operator.html#operator.itemgetter" rel="nofollow"><code>itemgetter</code></a> in a <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">dictionary comprehension</a></p> <pre><code>&gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; order = [4, 3, ...
0
2016-10-15T03:21:06Z
[ "python", "list", "dictionary" ]
OpenGL - Show Texture Only
40,053,433
<p>I'm working on a 2D isometric game, using pygame and pyopengl.</p> <p>I'm drawing sprites as quads, with a texture. I managed to get the alpha transparency to work for the texture, but the quad itself is still filled in a solid color (whatever colour gl pipeline is set with at the time). </p> <p>How do I hide the ...
-1
2016-10-14T23:36:27Z
40,056,514
<p>Well, either use <em>blending</em>, so that the alpha value actually has effect on opacity. Or use alpha testing, so that incoming fragments with an alpha below/above a certain threshold are discarded.</p> <p>Blending requires to sort geometry back to front. And given what you want to do alpha testing may be the ea...
2
2016-10-15T07:49:12Z
[ "python", "opengl" ]
OpenGL - Show Texture Only
40,053,433
<p>I'm working on a 2D isometric game, using pygame and pyopengl.</p> <p>I'm drawing sprites as quads, with a texture. I managed to get the alpha transparency to work for the texture, but the quad itself is still filled in a solid color (whatever colour gl pipeline is set with at the time). </p> <p>How do I hide the ...
-1
2016-10-14T23:36:27Z
40,057,459
<p>The colored background behind your tiles is probably due to this line when you set up your texture:</p> <pre><code>glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) </code></pre> <p>Just remove this as the default texture environment settings are probably fine for standard tile rendering. As an example of w...
2
2016-10-15T09:40:52Z
[ "python", "opengl" ]
Python Indexing not returning expected value
40,053,486
<p>I am trying to return the value M from Mr. Smith but whenever I run my code below it returns ''</p> <pre><code>&gt;&gt;&gt;name = input("Please input your name: ") Please input your name: Mr. Smith &gt;&gt;&gt; if name == name.find(' ') and name.isalpha(): get_initial = name[0] &gt;&gt;&gt;get_initial '' </cod...
0
2016-10-14T23:43:48Z
40,053,621
<p>I see a lot of problems in this proposed code.</p> <p>First of all, <code>input()</code> evaluates the input string as a python expression and that's not what you want, you need to use <code>raw_input()</code> instead. Second, <code>isalpha()</code> won't return True if input includes '.' or spaces, so you need to ...
0
2016-10-15T00:04:01Z
[ "python" ]
Python Indexing not returning expected value
40,053,486
<p>I am trying to return the value M from Mr. Smith but whenever I run my code below it returns ''</p> <pre><code>&gt;&gt;&gt;name = input("Please input your name: ") Please input your name: Mr. Smith &gt;&gt;&gt; if name == name.find(' ') and name.isalpha(): get_initial = name[0] &gt;&gt;&gt;get_initial '' </cod...
0
2016-10-14T23:43:48Z
40,053,625
<p>python 3 </p> <pre><code> name = input("Please input your name: ") c=name.strip()[0] if c.isalpha(): print(c) </code></pre> <p>python 2 :</p> <pre><code>&gt;&gt;&gt; name = raw_input("Please input your name: ") Please input your name: Hisham &gt;&gt;&gt; c=name.strip()[0] &gt;&gt;&gt; if c.isa...
2
2016-10-15T00:04:20Z
[ "python" ]
Python Indexing not returning expected value
40,053,486
<p>I am trying to return the value M from Mr. Smith but whenever I run my code below it returns ''</p> <pre><code>&gt;&gt;&gt;name = input("Please input your name: ") Please input your name: Mr. Smith &gt;&gt;&gt; if name == name.find(' ') and name.isalpha(): get_initial = name[0] &gt;&gt;&gt;get_initial '' </cod...
0
2016-10-14T23:43:48Z
40,053,640
<p>Assuming you have to find the first character of a name....</p> <pre><code>def find_initial(name): i = 0 initial_name_size = len(name) while True: name = name[i:] if name.isalpha(): get_initial = name[0] return get_initial else: i = i+1 ...
0
2016-10-15T00:06:53Z
[ "python" ]
Django unapply migration
40,053,515
<p>I have a custom made migration:</p> <pre><code>class Migration(migrations.Migration): dependencies = [('blah', 'my_previous_migration'),] operations = [ migrations.RunSQL( sql=[("SQL HERE")], reverse_sql=[("SQL UNDO HERE")]) ] </code></pre> <p>This migration is already...
0
2016-10-14T23:47:43Z
40,053,751
<p>Let's call the snippet <code>accident</code> and the additional one <code>fix</code>.</p> <p>When writing custom SQL migrations you should usually provide the reverse part otherwise you can not roll it back to prior state without loosing the integrity of your schema and/or data.</p> <p><code>accident</code> should...
1
2016-10-15T00:26:02Z
[ "python", "django", "migration" ]
APScheduler - ImportWarning but code still runs. What is wrong?
40,053,575
<p>My code follows the example from <a href="http://apscheduler.readthedocs.io/en/latest/modules/triggers/interval.html#examples" rel="nofollow">APScheduler Docs</a> but I changed its format to follow mine. It works no problem. "Hello World" is printed every 10 seconds.</p> <pre><code>#! /usr/bin/python import datet...
0
2016-10-14T23:56:31Z
40,056,516
<p>It was <code>praw</code>.</p> <p>I imported it to the test script behind <code>datetime</code> and <code>from apscheduler.schedulers.blocking import BlockingScheduler</code> and it ran error free. </p> <p>I then moved it in front of the latter and it threw the errors.</p> <p>In order to run error free from <code>...
0
2016-10-15T07:49:17Z
[ "python", "apscheduler" ]
Python Regular Expression [\d+]
40,053,653
<p>I am working on regular expression python, I came across this problem.</p> <p>A valid mobile number is a ten digit number starting with a 7,8 or 9. my solution to this was :</p> <pre><code>if len(x)==10 and re.search(r'^[7|8|9]+[\d+]$',x): </code></pre> <p>for which i was getting error. later I changed it to</p> ...
2
2016-10-15T00:08:05Z
40,053,690
<p><code>[\d+]</code> = one digit (<code>0-9</code>) or <code>+</code> character.</p> <p><code>\d+</code> = one or more digits.</p>
3
2016-10-15T00:14:07Z
[ "python", "regex" ]
Python Regular Expression [\d+]
40,053,653
<p>I am working on regular expression python, I came across this problem.</p> <p>A valid mobile number is a ten digit number starting with a 7,8 or 9. my solution to this was :</p> <pre><code>if len(x)==10 and re.search(r'^[7|8|9]+[\d+]$',x): </code></pre> <p>for which i was getting error. later I changed it to</p> ...
2
2016-10-15T00:08:05Z
40,055,254
<p>You could also do:</p> <pre><code>if re.search(r'^[789]\d{9}$', x): </code></pre> <p>letting the regex handle the <code>len(x)==10</code> part by using explicit lengths instead of unbounded repetitions.</p>
1
2016-10-15T05:18:43Z
[ "python", "regex" ]
Python Regular Expression [\d+]
40,053,653
<p>I am working on regular expression python, I came across this problem.</p> <p>A valid mobile number is a ten digit number starting with a 7,8 or 9. my solution to this was :</p> <pre><code>if len(x)==10 and re.search(r'^[7|8|9]+[\d+]$',x): </code></pre> <p>for which i was getting error. later I changed it to</p> ...
2
2016-10-15T00:08:05Z
40,055,675
<p>I think a general explanation about <code>[]</code> and <code>+</code> is what you need. </p> <p><code>[]</code> will match with a single character specified inside.<br> Eg: <code>[qwe]</code> will match with <code>q</code>, <code>w</code> or <code>e</code>. </p> <p><strong>If you want to enter an expression ins...
0
2016-10-15T06:16:46Z
[ "python", "regex" ]
Object Detection OpenCV-Python does not work
40,053,655
<p>For several days I am have been trying to build my own object classification program using Python-Open cv and Haar Cascade.</p> <p>After creating the samples, here is how train the system:</p> <pre><code> opencv_traincascade -data classifier -vec samples.vec -bg negatives.txt -numStages 12 -minHitRate 0.999 -maxFa...
0
2016-10-15T00:08:39Z
40,062,710
<p>Your desired parameters were acheived: "-minHitRate 0.999 -maxFalseAlarmRate 0.5".</p> <p>You have (according the table you show above): HitRate=1 and FalseAlarmRate=0.441667, that's why training stopped.</p>
0
2016-10-15T18:27:57Z
[ "python", "opencv" ]
How to plot two level x-axis labels for a histogram?
40,053,660
<p>Is there a way to do the same of this two x-axis labels but for a histogram plot? <a href="http://stackoverflow.com/questions/31803817/how-to-add-second-x-axis-at-the-bottom-of-the-first-one-in-matplotlib/40053591#40053591">How to add second x-axis at the bottom of the first one in matplotlib.?</a></p> <p>I want t...
1
2016-10-15T00:09:13Z
40,060,879
<p>just replace your <code>hist</code> call by:</p> <pre><code>n, bins, patches = ax1.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5) </code></pre> <p>Check the <a href="http://matplotlib.org/api/axes_api.html" rel="nofollow">documentation for <code>Axes</code></a> to see what member functions are available...
0
2016-10-15T15:28:31Z
[ "python", "matplotlib", "histogram", "axis" ]
using a tail and a buffer to get last K lines in a file
40,053,673
<p>I was given this buffer and told to make a reverse input that get the last K lines in a file. From what I've been trying to do, every time I tried to run the code it says that used is not an attribute of Input. Can someone please tell me why this keeps happening? Thank you in advance.</p> <pre><code>class Input: de...
1
2016-10-15T00:11:48Z
40,053,750
<p>Try indenting...</p> <pre><code>class Input: def __init___( self, file ): self.file = file # must open( &lt;filename&gt;, "rb" ) self.length = 0 self.used = 0 self.buffer = "" def read( self ): if self.used &lt; self.length: # if something in buffer c = ...
-1
2016-10-15T00:26:01Z
[ "python", "file", "buffer", "tail" ]
using a tail and a buffer to get last K lines in a file
40,053,673
<p>I was given this buffer and told to make a reverse input that get the last K lines in a file. From what I've been trying to do, every time I tried to run the code it says that used is not an attribute of Input. Can someone please tell me why this keeps happening? Thank you in advance.</p> <pre><code>class Input: de...
1
2016-10-15T00:11:48Z
40,053,800
<p>I'm going to go out on a limb here and try guessing that the problem is that you are using the wrong name for the <code>__init__</code> magic method (as noticed by <a href="https://stackoverflow.com/users/459745/hai-vu">Hai Vu</a>). Notice that there are three trailing underscores in your code instead of two.</p> <...
2
2016-10-15T00:33:46Z
[ "python", "file", "buffer", "tail" ]
Django: How to use AJAX to check if username exists on registration form?
40,053,752
<p>When the user enters a username, I want to check the db if that username already exists and display an error message. How would I do that without refreshing the page? With AJAX?</p> <p>registration_form.html</p> <pre><code>&lt;div class="container-fluid userformcontainer"&gt; &lt;div class="row"&gt; &lt;di...
0
2016-10-15T00:26:03Z
40,053,980
<p>You can build your form manually (at least the username field) as per django documentation below:</p> <p><a href="https://docs.djangoproject.com/en/1.10/topics/forms/#rendering-fields-manually" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/forms/#rendering-fields-manually</a></p> <p>Then you can set...
0
2016-10-15T01:10:34Z
[ "python", "ajax", "django" ]
binary tree issue: unorderable types: str() < int()
40,053,801
<p>I am trying to create a binary tree. I am testing what I have with the test code at the bottom but I receive the error message "elif var &lt; here._variable: TypeError: unorderable types: str() &lt; int()" any insight would be great</p> <pre><code>class vartree: class Node: __slots__= "_left", "_value...
0
2016-10-15T00:33:52Z
40,053,847
<p>The problem is that one is an integer and the other a string at the line at which error occurs. After analyzing your code, i think i know why this is happening. Do this:</p> <p>In your _insert() function, change this line: </p> <pre><code> return self.Node(None, val, var, None) </code></pre> <p>to this: </p> <...
1
2016-10-15T00:43:39Z
[ "python" ]
How would I use Dask to perform parallel operations on slices of NumPy arrays?
40,053,875
<p>I have a numpy array of coordinates of size n_slice x 2048 x 3, where n_slice is in the tens of thousands. I want to apply the following operation on each 2048 x 3 slice separately</p> <pre><code>import numpy as np from scipy.spatial.distance import pdist # load coor from a binary xyz file, dcd format n_slice, n...
2
2016-10-15T00:49:31Z
40,054,094
<h3><code>map_blocks</code></h3> <p>The <a href="http://dask.pydata.org/en/latest/array-api.html#dask.array.core.map_blocks" rel="nofollow">map_blocks</a> method may be helpful:</p> <pre><code>dcoor.map_blocks(pdist) </code></pre> <h3>Uneven arrays</h3> <p>It looks like you're doing a bit of fancy slicing to insert...
2
2016-10-15T01:35:29Z
[ "python", "arrays", "numpy", "parallel-processing", "dask" ]
Extract JSON object
40,053,964
<p>I have a JSON file that looks like this:</p> <pre><code>[ "{'_filled': False,\n 'affiliation': u'Postdoctoral Scholar, University of California, Berkeley',\n 'citedby': 113,\n 'email': u'@berkeley.edu',\n 'id': u'4bahYMkAAAAJ',\n 'interests': [u'3D Shape',\n u'Shape from Texture',\n u'Sh...
0
2016-10-15T01:06:51Z
40,054,017
<pre><code>import json import ast json_data = open("output.json") data = json.load(json_data) print ast.literal_eval(data[0])['citedby'] </code></pre>
1
2016-10-15T01:18:44Z
[ "python", "json" ]
What regular expression selects a string between two "*" characters
40,054,031
<p>I want to select text between two * characters in a file and am having trouble forming the regular expression to do so.</p> <p>For example with a file like the following:</p> <pre><code>* Apple Are good * Banana Are great * Cauliflower Are bad </code></pre> <p>It would select 3 different groups</p> <p>Apple ...
-1
2016-10-15T01:21:06Z
40,054,057
<p>Regular expressions aren't even necessary here. Just use <code>str.split</code> and <code>str.strip</code>:</p> <pre><code>&gt;&gt;&gt; f = '''* Apple ... Are good ... ... * Banana ... Are great ... ... * Cauliflower ... Are bad''' &gt;&gt;&gt; for line in f.split('*'): ... if line.strip(): ... prin...
2
2016-10-15T01:28:27Z
[ "python", "regex" ]
Import file from another app in Django 1.10
40,054,066
<p>I'm trying to import a file from another app, and I get this error:</p> <pre><code>Unhandled exception in thread started by &lt;function wrapper at 0x7fe7bc281d70&gt; Traceback (most recent call last): File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapp...
0
2016-10-15T01:30:46Z
40,054,163
<p>in setting try to add this line after BASE_DIR <code>sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))</code> dont forget <code>import os import sys</code></p>
1
2016-10-15T01:50:17Z
[ "python", "django", "django-1.10" ]
parallel ping using gevent
40,054,079
<p>I am new to python and I am trying to run this code to want parallel ping of multiple machines.but I can not ping all IP concurrently. seems it run one after another .can some one please guide me on how can i ping multiple server concurrently.</p> <pre><code>import gevent import urllib2 import os from gevent import...
2
2016-10-15T01:32:33Z
40,054,236
<p><code>os.system</code> is not patched, but <a href="https://docs.python.org/3/library/subprocess.html#subprocess.call" rel="nofollow"><code>subprocess.call</code></a> is patched; Replace <code>os.system</code> with <code>subprocess.call</code> (You can also use <a href="https://docs.python.org/3/library/subprocess.h...
0
2016-10-15T02:06:36Z
[ "python", "gevent" ]
parallel ping using gevent
40,054,079
<p>I am new to python and I am trying to run this code to want parallel ping of multiple machines.but I can not ping all IP concurrently. seems it run one after another .can some one please guide me on how can i ping multiple server concurrently.</p> <pre><code>import gevent import urllib2 import os from gevent import...
2
2016-10-15T01:32:33Z
40,054,250
<p>The problem is that <code>os.system("ping -c 5 " + switch)</code> is running synchronously, because the function is blocking. You should try to do it in different processes.</p> <p>Here is a concurrent code that does the same.</p> <pre><code>from multiprocessing import Process import os def print_head(i): swi...
0
2016-10-15T02:10:11Z
[ "python", "gevent" ]
Unable to run code through python file or jupyter (ipython notebook), working successfully through terminal python
40,054,142
<p>I have this python code:</p> <pre><code>#!/usr/bin/env python import pyodbc from pandas import * conn = pyodbc.connect("DSN=drill64", autocommit=True) cursor = conn.cursor() </code></pre> <p>which on running as a .py file aur running through ipython notebook gives me the below error</p> <pre><code>Traceback (most...
0
2016-10-15T01:44:52Z
40,054,184
<p>Ok, I was able to solve it by changing permission to .py file <code>chmod +x TestingDrillQuery.py</code></p>
0
2016-10-15T01:55:41Z
[ "python", "odbc", "pyodbc" ]
Editing a value in a DataFrame
40,054,147
<p>I'm trying to:</p> <p>Import a CSV of UPC codes into a dataframe. If the UPC code is 11 characters , append '0' to it. Ex: 19962123818 --> 019962123818</p> <p>This is the code:</p> <pre><code> #check UPC code length. If 11 characters, adds '0' before. If &lt; 11 or &gt; 13, throws Error for index, row in clean_d...
1
2016-10-15T01:46:40Z
40,054,276
<p>Can I suggest a different method? </p> <pre><code>#identify the strings shorter than 11 characters fix_indx = clean_data.UPC.astype(str).str.len()&lt;11 #append these strings with a '0' clean_data.loc[fix_indx] = '0'+clean_data[fix_indx].astype(str) </code></pre> <p>To fix the others, you can similarly do:</p> <...
4
2016-10-15T02:14:25Z
[ "python", "csv", "pandas", "dataframe" ]
Editing a value in a DataFrame
40,054,147
<p>I'm trying to:</p> <p>Import a CSV of UPC codes into a dataframe. If the UPC code is 11 characters , append '0' to it. Ex: 19962123818 --> 019962123818</p> <p>This is the code:</p> <pre><code> #check UPC code length. If 11 characters, adds '0' before. If &lt; 11 or &gt; 13, throws Error for index, row in clean_d...
1
2016-10-15T01:46:40Z
40,054,360
<p>According to <code>iterrows</code>documentation:</p> <blockquote> <ol start="2"> <li>You should <strong>never modify</strong> something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it wil...
1
2016-10-15T02:32:35Z
[ "python", "csv", "pandas", "dataframe" ]
Editing a value in a DataFrame
40,054,147
<p>I'm trying to:</p> <p>Import a CSV of UPC codes into a dataframe. If the UPC code is 11 characters , append '0' to it. Ex: 19962123818 --> 019962123818</p> <p>This is the code:</p> <pre><code> #check UPC code length. If 11 characters, adds '0' before. If &lt; 11 or &gt; 13, throws Error for index, row in clean_d...
1
2016-10-15T01:46:40Z
40,059,261
<p>I finally fixed it. Thanks again for the vectorized idea. If anyone has this issue in the future, here's the code I used. Also, see <a href="http://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe">this post</a> for more info.</p> <pre><code>UPC_11_char = clean_data.UPC.astype(...
0
2016-10-15T12:54:12Z
[ "python", "csv", "pandas", "dataframe" ]
Get wget to never time out or catch timeout on python
40,054,167
<p>I am using python 2.7 with the wget module. <a href="https://pypi.python.org/pypi/wget" rel="nofollow">https://pypi.python.org/pypi/wget</a></p> <p>The URL to download is not responsive sometimes. It can take ages to download and when this happens, <code>wget</code> times out. How can I get wget to never time out ...
1
2016-10-15T01:50:47Z
40,054,214
<p>You could use <a href="http://docs.python-requests.org/en/latest/" rel="nofollow">requests</a> instead:</p> <pre><code>requests.get(url_download) </code></pre> <p>if you don't specify a timeout argument it never times out.</p>
0
2016-10-15T02:02:10Z
[ "python", "python-2.7", "wget" ]
Include multiple headers in python requests
40,054,357
<p>I have this HTTPS call in curl below;</p> <pre><code>header1="projectName: zhikovapp" header2="Authorization: Bearer HZCdsf=" bl_url="https://BlazerNpymh.com/api/documents?pdfDate=$today" curl -s -k -H "$header1" -H "$header2" "$bl_url" </code></pre> <p>I would like to write an equivalent python call using reque...
1
2016-10-15T02:32:18Z
40,054,376
<p>In <code>request.get()</code> the <a href="http://docs.python-requests.org/en/master/user/quickstart/#custom-headers" rel="nofollow"><code>headers</code></a> argument should be defined as a dictionary, a set of key/value pairs. You've defined a set (a unique list) of strings instead.</p> <p>You should declare your ...
1
2016-10-15T02:37:14Z
[ "python", "python-2.7", "curl", "python-requests" ]
Element Tree find output empty text
40,054,420
<p>I have a problem using Element Tree to extract the text.</p> <p>My format of my xml file is</p> <pre><code>&lt;elecs id = 'elecs'&gt; &lt;elec id = "CLM-0001" num = "0001"&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;/elec&g...
0
2016-10-15T02:47:00Z
40,054,813
<p>If you actually mean 'any way' you could use lxml.</p> <pre><code>&gt;&gt;&gt; from io import StringIO &gt;&gt;&gt; html = StringIO('''\ ... &lt;elecs id = 'elecs'&gt; ... &lt;elec id = "CLM-0001" num = "0001"&gt; ... &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; ... &lt;elec-text&...
0
2016-10-15T04:03:49Z
[ "python", "xml", "elementtree" ]
Element Tree find output empty text
40,054,420
<p>I have a problem using Element Tree to extract the text.</p> <p>My format of my xml file is</p> <pre><code>&lt;elecs id = 'elecs'&gt; &lt;elec id = "CLM-0001" num = "0001"&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;/elec&g...
0
2016-10-15T02:47:00Z
40,055,313
<p>You can simply find elements that directly contains the text by name i.e <code>elec-text</code> in this case :</p> <pre><code>&gt;&gt;&gt; elec_texts = tree.findall('.//elec-text') &gt;&gt;&gt; for elec_text in elec_texts: ... print elec_text.text ... ...
1
2016-10-15T05:27:04Z
[ "python", "xml", "elementtree" ]
Python insert variable to mysql via mysql.connector
40,054,426
<p>I am trying to create one python script to insert data into mysql, but I got an error when I try to test it.</p> <p>This is how I create the table:</p> <pre><code>CREATE TABLE aaa ( id MEDIUMINT NOT NULL AUTO_INCREMENT, data CHAR(30) NOT NULL, PRIMARY KEY (id) ); </code></pre> <p>This is my python ...
0
2016-10-15T02:47:54Z
40,054,688
<p>replace <code>,</code> with <code>%</code> in <code>"INSERT INTO aaa(data) VALUES (%s)", (curr_time)</code> it should be <code>"INSERT INTO aaa(data) VALUES (%s)"%(curr_time)</code></p>
0
2016-10-15T03:37:55Z
[ "python", "mysql" ]
Python - utility program to check module availability
40,054,462
<p>Is there a command line(preferably) utility program that lists all <code>major</code> versions of python that come bundled with a particular module in that version's library? </p> <p>For example <code>json</code> module is only available in versions 2.6+</p> <p>So running this utility should list:</p> <pre><code>...
0
2016-10-15T02:57:02Z
40,056,605
<p>There is no such built-in command.</p> <p>If having an internet connection is not an issue you can simply check the url at <code>https://docs.python.org/&lt;version-number&gt;/library/&lt;module-name&gt;.html</code>:</p> <pre><code>from urllib.request import urlopen from urllib.error import HTTPError def has_mod...
1
2016-10-15T07:59:45Z
[ "python", "python-3.x" ]
scikit-learn vectorizing with big dataset
40,054,473
<p>I have 9GB of segmented documents on my disk and my vps only has 4GB memory.</p> <p>How can I vectorize all the data set without loading all the corpus at initialization? Is there any sample code? </p> <p>my code is as follows:</p> <pre><code>contents = [open('./seg_corpus/' + filename).read() for fil...
1
2016-10-15T02:59:20Z
40,056,620
<p>Try this, instead of loading all texts into memory you can pass only handles to files into <code>fit</code> method, but you must specify <code>input='file'</code> in <code>CountVectorizer</code> constructor.</p> <pre><code>contents = [open('./seg_corpus/' + filename) for filename in filenames] vectorizer = ...
1
2016-10-15T08:01:08Z
[ "python", "numpy", "machine-learning", "scikit-learn" ]
How to create a DataFrame series as a sub-string of a DataFrame Index?
40,054,615
<p>I have a Pandas DataFrame which has a 5-digit string as its index (the index is a 5 digit zip code). I'd need to create another series in the DataFrame which is the first three characters of the index (i.e. the 3-Digit zip code).</p> <p>As an example, if the index for a row is "32779", I'd like the new series' valu...
1
2016-10-15T03:26:44Z
40,054,811
<p>This worked:</p> <pre><code>fte5['Zip3'] = fte5.index.get_level_values(0) fte5['Zip3'] = fte5['Zip3'].astype(str).apply(lambda x: x[:3]) </code></pre>
0
2016-10-15T04:03:15Z
[ "python", "pandas", "dataframe" ]
How to create a DataFrame series as a sub-string of a DataFrame Index?
40,054,615
<p>I have a Pandas DataFrame which has a 5-digit string as its index (the index is a 5 digit zip code). I'd need to create another series in the DataFrame which is the first three characters of the index (i.e. the 3-Digit zip code).</p> <p>As an example, if the index for a row is "32779", I'd like the new series' valu...
1
2016-10-15T03:26:44Z
40,054,917
<p>The bracket operator on strings is exposed through <code>str.slice</code> function:</p> <pre><code>fte5.index.astype(str).str.slice(0,3) </code></pre>
2
2016-10-15T04:22:03Z
[ "python", "pandas", "dataframe" ]
How to create a DataFrame series as a sub-string of a DataFrame Index?
40,054,615
<p>I have a Pandas DataFrame which has a 5-digit string as its index (the index is a 5 digit zip code). I'd need to create another series in the DataFrame which is the first three characters of the index (i.e. the 3-Digit zip code).</p> <p>As an example, if the index for a row is "32779", I'd like the new series' valu...
1
2016-10-15T03:26:44Z
40,055,494
<p>consider the <code>pd.DataFrame</code> <code>fte5</code></p> <pre><code>fte5 = pd.DataFrame(np.ones((3, 2)), ['01234', '34567', '56789'], ['X', 'Y']) fte5 </code></pre> <p><a href="https://i.stack.imgur.com/1AHww.png" rel="nofollow"><img src="https://i.stack.imgur.com/1AHww.png" alt="enter image description here">...
0
2016-10-15T05:50:51Z
[ "python", "pandas", "dataframe" ]
How to save code file on GitHub and run on Jupyter notebook?
40,054,672
<p>With GitHub we can store our code online, and with Jupyter notebook we can execute only a segment of our Python code. I want to use them together. I am able to edit code with Jupyter notebook that is stored on my computer. But, I am unable to find a way to run a code that stored on GitHub. So, do you know a way to d...
-1
2016-10-15T03:34:52Z
40,054,705
<p>Github is a tool for version and source control, you will need to get a copy of the code to a local environment.</p> <p>There is a beginner's tutorial <a href="http://readwrite.com/2013/09/30/understanding-github-a-journey-for-beginners-part-1/" rel="nofollow">here</a></p> <p>Once that you have set up a github acc...
1
2016-10-15T03:40:43Z
[ "python", "git", "github", "jupyter-notebook" ]
Strange behaviour of delete dictionary operation on nested dictionary
40,054,685
<pre><code>#!/usr/bin/python import numpy as np td={} d = {} for col in ['foo','bar','baz']: for row in ['a','b','c','d']: td.setdefault(row, np.random.randn()) d.setdefault(col, td) print d del d['foo']['c'] print d </code></pre> <p>output:</p> <pre><code>{'baz': {'a': -1.6340274257732716, 'c':...
0
2016-10-15T03:36:55Z
40,054,709
<p>You are setting each value in <code>d</code> to reference the same copy of <code>td</code>. If you want the copies to be distinct, you'll need to create more than one <code>td</code> dictionary.</p> <p>Try this:</p> <pre><code>#!/usr/bin/python import numpy as np d = {} for col in ['foo','bar','baz']: td = {}...
0
2016-10-15T03:41:15Z
[ "python" ]
Python: HTTPConnectionPool(host='%s', port=80):
40,054,711
<pre><code>import requests import urllib3 from time import sleep from sys import argv script, filename = argv http = urllib3.PoolManager() datafile = open('datafile.txt','w') crawl = "" with open(filename) as f: mylist = f.read().splitlines() def crawlling(x): for i in mylist: domain = ("http://" + "%s")...
1
2016-10-15T03:41:39Z
40,060,810
<p>This line is the problem:</p> <pre><code>crawl = http.request('GET','%s',preload_content=False) % domain </code></pre> <p>Right now you're trying to make a request to the domain <code>%s</code> which is not a valid domain, hence the error "Name or service not known".</p> <p>It should be:</p> <pre><code>crawl = ...
0
2016-10-15T15:22:12Z
[ "python", "web-scraping", "python-requests", "urllib3" ]
Python TypeError: unsupported operand type(s) for -: 'str' and 'str'
40,054,715
<p>I am trying to convert the following code written in Python 2 to code that is compatible with Python 3. I am receiving the following error:</p> <blockquote> <p>File "C:/Users/brand/AppData/Local/Programs/Python/Python35-32/Ch‌​ange Maker.py", </p> <p>line 5, in CHANGE = MONEY - PRICE</p> <p>TypeErr...
0
2016-10-15T03:42:35Z
40,054,741
<p><code>input()</code> in Python 3 is equivalent to <code>raw_input()</code> in Python 2. Thus, <code>PRICE</code> and <code>MONEY</code> are strings, not integers as you are expecting.</p> <p>To fix this, change them to integers:</p> <pre><code>PRICE = int(input("Price of item: ")) MONEY = int(input("Cash tendered...
4
2016-10-15T03:48:55Z
[ "python" ]
Python TypeError: unsupported operand type(s) for -: 'str' and 'str'
40,054,715
<p>I am trying to convert the following code written in Python 2 to code that is compatible with Python 3. I am receiving the following error:</p> <blockquote> <p>File "C:/Users/brand/AppData/Local/Programs/Python/Python35-32/Ch‌​ange Maker.py", </p> <p>line 5, in CHANGE = MONEY - PRICE</p> <p>TypeErr...
0
2016-10-15T03:42:35Z
40,054,891
<p><code>input</code> returns a string in Python 3</p> <p>Also for money I would recommend <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow"><code>decimal</code></a> due to <a href="https://docs.python.org/2/tutorial/floatingpoint.html" rel="nofollow"><code>float</code> lack of precision</a></p> ...
0
2016-10-15T04:17:05Z
[ "python" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:...
0
2016-10-15T03:47:18Z
40,054,782
<p>You can try something like</p> <pre><code>the_string = "38.00,SALE ,15.20" floats = [] for possible_float in the_string.split(','): try: floats.append (float (possible_float.strip()) except: pass print floats </code></pre>
0
2016-10-15T03:56:18Z
[ "python", "string" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:...
0
2016-10-15T03:47:18Z
40,054,810
<pre><code>def extract_nums(text): for item in text.split(','): try: yield float(item) except ValueError: pass print list(extract_nums("38.00,SALE ,15.20")) print list(extract_nums("69.99")) </code></pre> <hr> <pre><code>[38.0, 15.2] [69.99] </code></pre> <p>However by us...
2
2016-10-15T04:02:59Z
[ "python", "string" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:...
0
2016-10-15T03:47:18Z
40,054,831
<p>Try a list comprehension: </p> <pre><code>just_floats = [i for i in your_list.split(',') if i.count('.') == 1] </code></pre> <p>first you split the string where the commas are, then you filter through the string and get rid of values that don't have a decimal place</p>
0
2016-10-15T04:06:26Z
[ "python", "string" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:...
0
2016-10-15T03:47:18Z
40,054,851
<p>You said you're only interested in floats at the start and end of the string, so assuming it's comma-delimited:</p> <pre><code>items = the_string.split(',') try: first = float(items[0]) except (ValueError, IndexError): pass try: second = float(items[-1]) except (ValueError, IndexError): pass </code>...
0
2016-10-15T04:09:50Z
[ "python", "string" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:...
0
2016-10-15T03:47:18Z
40,054,882
<p>You could also use regex to do this</p> <pre><code>import re s = "38.00,SALE ,15.20" p = re.compile(r'\d+\.\d+') # Compile a pattern to capture float values floats = [float(i) for i in p.findall(s)] # Convert strings to float print floats </code></pre> <p>Output:</p> <pre><code>[38.0, 15.2] </code></pre>
2
2016-10-15T04:15:37Z
[ "python", "string" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:...
0
2016-10-15T03:47:18Z
40,054,890
<pre><code>import re map(float, filter(lambda x: re.match("\s*\d+.?\d+\s*", x) , input.split(",")) </code></pre> <p>Input : <code>input = '38.00,SALE ,15.20'</code> Output: <code>[38.0, 15.2]</code></p> <p>Input : <code>input = '38.00,SALE ,15.20, 15, 34.'</code> Output: <code>[38.0, 15.2, 15.0, 34.0]</code>...
0
2016-10-15T04:17:02Z
[ "python", "string" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:...
0
2016-10-15T03:47:18Z
40,055,072
<p>Split the input, check if each element is numeric when the period is removed, convert to float if it is.</p> <pre><code>def to_float(input): return [float(x) for x in input.split(",") if unicode(x).replace(".", "").isdecimal()] </code></pre>
0
2016-10-15T04:51:09Z
[ "python", "string" ]
R-Python : how to eliminate specific rows and columns?
40,054,765
<p>Take this <strong>R</strong> demo as an example : </p> <pre><code>df &lt;- matrix(1:100, nrow = 10, ncol = 10) </code></pre> <p><em>df</em> :</p> <pre><code>&gt; df [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 11 21 31 41 51 61 71 81 91 [2,] 2 12 22 32 42 52...
1
2016-10-15T03:52:23Z
40,055,105
<p>Try this (careful with the indices):</p> <pre><code>Try this: matrix = [] for row in range(0,100,10): column = [i for i in range(row,row+10)] matrix.append(column) columns_to_remove = [1,2,8] rows_to_remove = [4,5,9] for i in rows_to_remove: matrix.pop(i) for remaining_rows in matrix: for remove_co...
0
2016-10-15T04:56:25Z
[ "python" ]
R-Python : how to eliminate specific rows and columns?
40,054,765
<p>Take this <strong>R</strong> demo as an example : </p> <pre><code>df &lt;- matrix(1:100, nrow = 10, ncol = 10) </code></pre> <p><em>df</em> :</p> <pre><code>&gt; df [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 11 21 31 41 51 61 71 81 91 [2,] 2 12 22 32 42 52...
1
2016-10-15T03:52:23Z
40,055,907
<p>You could do this:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,100,size=(10, 10)), columns=list('ABCDEFGHIJ')) row_i= df.index.isin(range(1,8)) col_i=df.index.isin(range(2,7)) df.iloc[~row_i,~col_i] </code></pre> <p>Be careful of the index as it starts from 0 in python.</p>
1
2016-10-15T06:44:42Z
[ "python" ]
R-Python : how to eliminate specific rows and columns?
40,054,765
<p>Take this <strong>R</strong> demo as an example : </p> <pre><code>df &lt;- matrix(1:100, nrow = 10, ncol = 10) </code></pre> <p><em>df</em> :</p> <pre><code>&gt; df [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 11 21 31 41 51 61 71 81 91 [2,] 2 12 22 32 42 52...
1
2016-10-15T03:52:23Z
40,068,568
<p>After checking <a href="https://community.modeanalytics.com/python/tutorial/pandas-dataframe/" rel="nofollow">select data from data frame</a>,I think this solution may be easier to understand : </p> <p>E.g. <code>3 * 3</code> DataFrame, eliminate rows <code>1,2</code>, columns <code>0,1</code>: </p> <pre><code>imp...
0
2016-10-16T08:54:06Z
[ "python" ]
numpy.load() wrong magic string error
40,054,872
<p>I have two files. One creates a <code>numpy</code> array in compressed sparse row format</p> <pre><code>from sklearn.feature_extraction.text import TfidfTransformer import pdb def stem_document(document): translatedict = "" stemmer = PorterStemmer() for word in string.punctuation: translatedict...
1
2016-10-15T04:13:56Z
40,079,904
<p>I encountered similar issue before.</p> <p>Changing</p> <pre><code>open('matrix/matrix.npy', 'w') ... open('matrix/matrix.npy', 'r') </code></pre> <p>to</p> <pre><code>open('matrix/matrix.npy', 'wb') ... open('matrix/matrix.npy', 'rb') </code></pre> <p>solved my problem.</p>
0
2016-10-17T06:37:11Z
[ "python", "numpy" ]
Python urlopen "expected string or buffer"
40,054,894
<p>I am getting the "expected string or buffer" error in my simple python file. I am trying to get the titles of reddit articles written down.</p> <pre><code>from urllib import urlopen import re worldNewsPage = urlopen("https://www.reddit.com/r/worldnews/") collectTitle = re.compile('&lt;p class="title"&gt;&lt;a.*&...
0
2016-10-15T04:17:59Z
40,054,905
<p>Change</p> <pre><code>worldNewsPage = urlopen("https://www.reddit.com/r/worldnews/") </code></pre> <p>to</p> <pre><code>worldNewsPage = urlopen("https://www.reddit.com/r/worldnews/").read() </code></pre> <p>Also <a href="http://stackoverflow.com/a/1732454/1219006">don't use <code>regex</code> to parse <code>html...
1
2016-10-15T04:19:47Z
[ "python", "rss" ]
Python urlopen "expected string or buffer"
40,054,894
<p>I am getting the "expected string or buffer" error in my simple python file. I am trying to get the titles of reddit articles written down.</p> <pre><code>from urllib import urlopen import re worldNewsPage = urlopen("https://www.reddit.com/r/worldnews/") collectTitle = re.compile('&lt;p class="title"&gt;&lt;a.*&...
0
2016-10-15T04:17:59Z
40,055,536
<p>Urlopen is an object so you have to call the method read to get the contents you downloaded (like files).</p>
0
2016-10-15T05:57:01Z
[ "python", "rss" ]
Dynamic IMDb scrapper to see ranked personalities
40,054,914
<p>I want to create an online dynamic ranklist of actors/directors from their IMDb data. I have used BeautifulSoup previously to create an offline version for movies. But as it is over 2 years old, the top 250 rankings have changed.</p> <p>Is there a specific recommended method to create an online ranker? I hear about...
-4
2016-10-15T04:20:46Z
40,054,948
<p>IMDB releases data in plain text and you do not need to scrape it - <a href="http://www.imdb.com/interfaces" rel="nofollow">http://www.imdb.com/interfaces</a>. Diffs are released weekly. (So that the whole does not need to be downloaded again and again)</p>
1
2016-10-15T04:28:20Z
[ "python", "web-scraping", "imdb" ]
How do you install Tensorflow on Windows?
40,054,935
<p>I am trying to install Tensorflow on Windows. </p> <p>I have Anaconda 4.2.0. I tried running </p> <pre><code>conda create -n tensorflow python=3.5 </code></pre> <p>in my command prompt. This seemed to do something, but I'm not sure what this accomplished. It created a folder within the Anaconda3 program in my use...
2
2016-10-15T04:26:06Z
40,055,000
<p>The syntax of the command is <code>conda create -n &lt;name_of_new_env&gt; &lt;packages&gt;</code>. As a result, you created a clean environment named <code>tensorflow</code> with only Python 3.5 installed. Since <code>conda search tensorflow</code> returned nothing, you will have to use <code>pip</code> or some oth...
2
2016-10-15T04:38:46Z
[ "python", "tensorflow" ]
How do you install Tensorflow on Windows?
40,054,935
<p>I am trying to install Tensorflow on Windows. </p> <p>I have Anaconda 4.2.0. I tried running </p> <pre><code>conda create -n tensorflow python=3.5 </code></pre> <p>in my command prompt. This seemed to do something, but I'm not sure what this accomplished. It created a folder within the Anaconda3 program in my use...
2
2016-10-15T04:26:06Z
40,064,285
<p>I was able to run it under the Windows 10 linux subsystem (<a href="https://msdn.microsoft.com/en-us/commandline/wsl/install_guide" rel="nofollow">https://msdn.microsoft.com/en-us/commandline/wsl/install_guide</a>)</p> <p>Which is basically a linux environment within windows.</p>
0
2016-10-15T21:14:06Z
[ "python", "tensorflow" ]
Creating nested dictionary using python
40,055,008
<p>I am having a data for nodes in csv format. I want to create a dictionary for the analysis. The data I have looks like </p> <pre><code>Init node Term node Capacity 1 2 25900.20064 1 3 23403.47319 2 1 25900.20064 2 6 4958.180928 3 1 23403.47319 3 4 17110.52372 ...
0
2016-10-15T04:40:01Z
40,055,147
<p>Try this loop:</p> <pre><code>sheet = workbook.sheet_by_index(0) d = {} for rows in range(sheet.nrows): a = sheet.cell_value(rows, 0) b = sheet.cell_value(rows, 1) c = sheet.cell_value(rows, 2) d.setdefault(a, {})[b] = c d.setdefault(b, {})[a] = c </code></pre>
1
2016-10-15T05:03:17Z
[ "python", "dictionary", "hyperlink", "nodes" ]
Pygame responds incorrectly to button clicks
40,055,096
<p>I'm having an issue with pygame. I've set up a window that randomly places circles across the screen very quickly, just for testing purposes. There are also three buttons: play/pause (switches back and forth, stops circles from appearing) and an increase speed and decrease speed button. I'm not very experienced with...
0
2016-10-15T04:54:45Z
40,093,414
<p>"pygame.event.get()" takes one event at a time, and *clears it** from the list of events that need to be processed.</p> <p>So, more specifically, pygame.event.get() returns each event only <strong>once</strong>.</p> <p>Take a look at the following code:</p> <pre><code>clicked = False for event in pygame.event.get...
0
2016-10-17T18:39:15Z
[ "python", "button", "pygame" ]
Python: Why can't I assign new value to an array in this case?
40,055,177
<pre><code>import numpy as np data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53']]) data[0,0] = data[0,0] + "_1" </code></pre> <p><strong>data[0,0]</strong> is <strong>'Height'</strong>, and I want to replace it with <strong>'Height_1'</strong>. But the code above doesn't work. It returned...
3
2016-10-15T05:07:22Z
40,055,245
<p>specify an <strong>object</strong> type for your array, such as:</p> <pre><code>a = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53']],dtype=object) </code></pre> <p>Then, <code>a[0][0]+='_1'</code> will do the trick, you will get:</p> <pre><code>array([['Height_1', 'Weight'], ['165...
3
2016-10-15T05:17:48Z
[ "python", "arrays", "numpy", "variable-assignment" ]
Python: Why can't I assign new value to an array in this case?
40,055,177
<pre><code>import numpy as np data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53']]) data[0,0] = data[0,0] + "_1" </code></pre> <p><strong>data[0,0]</strong> is <strong>'Height'</strong>, and I want to replace it with <strong>'Height_1'</strong>. But the code above doesn't work. It returned...
3
2016-10-15T05:07:22Z
40,055,250
<p>The problem is your array is of <code>dtype('&lt;U6')</code></p> <pre><code>&gt;&gt;&gt; data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53']]) &gt;&gt;&gt; data.dtype dtype('&lt;U6') &gt;&gt;&gt; </code></pre> <p>It will automatically truncate:</p> <pre><code>&gt;&gt;&gt; data[0,0] = ...
4
2016-10-15T05:18:16Z
[ "python", "arrays", "numpy", "variable-assignment" ]
python error returning a variable but it prints fine
40,055,277
<p>Trying to figure out this why I'm getting this error about not declaring a variable.</p> <p>this works fine:</p> <pre><code> def findLargestIP(): for i in tagList: #remove all the spacing in the tags ec2Tags = i.strip() #seperate any multiple tags ...
-1
2016-10-15T05:22:00Z
40,055,337
<p>When a function returns a value, it has to be assigned to a value to be kept. Variables defined inside a function (like <code>b</code> in the example below) <strong>only exist inside the function and cannot be used outside the function</strong>.</p> <pre><code>def test(a): b=a+1 return b test(2) # Returns 3...
3
2016-10-15T05:30:35Z
[ "python", "function", "loops" ]
python error returning a variable but it prints fine
40,055,277
<p>Trying to figure out this why I'm getting this error about not declaring a variable.</p> <p>this works fine:</p> <pre><code> def findLargestIP(): for i in tagList: #remove all the spacing in the tags ec2Tags = i.strip() #seperate any multiple tags ...
-1
2016-10-15T05:22:00Z
40,055,380
<p>It's because <code>largestIP</code> only exists in the scope of your <code>findLargestIP</code> function.</p> <p>Since this function returns a value but you simply call it without assigning to a new variable, this value gets "lost" afterwards.</p> <p>You should try something like:</p> <pre><code>def findLargestIP...
1
2016-10-15T05:35:48Z
[ "python", "function", "loops" ]
Why do i get this error "TypeError: 'int' object is not callable"?
40,055,370
<pre><code>def diameter(Points): '''Given a list of 2d points, returns the pair that's farthest apart.''' diam,pair = max([((p[0]-q[0])**2 + (p[1]-q[1])**2, (p,q)) for p,q in rotatingCalipers(Points)]) return pair n=int(input()) a=[] max=0 for i in xrange(n): m,n=map(int,raw_in...
0
2016-10-15T05:34:03Z
40,055,491
<p>From the Traceback it's clear than you are trying to call <code>int</code> object, So <code>rotatingCalipers</code> may be declared as integer in your code. </p> <p>See this example you will understand the error,</p> <pre><code>In [1]: a = (1,2,3) In [2]: list(a) Out[1]: [1, 2, 3] In [3]: list = 5 In [4]: list(a) ...
1
2016-10-15T05:49:39Z
[ "python", "python-2.7" ]
Python multiprocessing Pool.imap throws ValueError: list.remove(x): x not in list
40,055,378
<p>I have a very simple test fixture that instantiate and close a test class 'APMSim' in different threads, the class is not picklable, so I have to use multiprocessing Pool.imap to avoid them being transferred between processes:</p> <pre><code>class APMSimFixture(TestCase): def setUp(self): self.pool = m...
0
2016-10-15T05:35:40Z
40,055,477
<p><code>multiprocessing</code> is re-raising an exception from your worker function/child process in the parent process, but it loses the traceback in the transfer from child to parent. Check your worker function, it's that code that's going wrong. It might help to take whatever your worker function is and change:</p>...
1
2016-10-15T05:47:31Z
[ "python", "python-2.7", "python-multiprocessing", "python-unittest" ]
Flask-restful API not accepting json
40,055,384
<p>I am trying to learn how to do apis. I copied everything from the book exactly but i am unable to post to the api. I tried posting <code>{'name':'holy'}</code> as raw data in <code>postman</code>( an json posting tool) to api and I get the vladation help message error"No Name provided":but when i try <code>name=hol...
0
2016-10-15T05:36:00Z
40,062,569
<p>Your code should work - you have to specify the request header <code>Content-Type: application/json</code>. The reason why is because <code>flask-restful</code>'s <code>reqparse</code> module tries to parse <a href="http://flask-restful-cn.readthedocs.io/en/0.3.5/reqparse.html#argument-locations" rel="nofollow">its ...
2
2016-10-15T18:14:40Z
[ "python", "rest", "api", "flask-restful" ]
Unable to get OpenCV 3.1 FPS over ~15 FPS
40,055,428
<p>I have some extremely simple performance testing code below for measuring the FPS of my webcam with OpenCV 3.1 + Python3 on a Late 2011 Macbook Pro:</p> <pre><code>cap = cv2.VideoCapture(0) count = 0 start_time = time.perf_counter() end_time = time.perf_counter() while (start_time + 1) &gt; end_time: count += 1...
0
2016-10-15T05:41:23Z
40,067,019
<p>IT'S NOT ANSWER. Since the comment in original question is too long for your attention. I post outside instead. </p> <p>First, it's normal when CV_CAP_PROP_FPS return 0. OpenCV for Python just a wrapper for OpenCV C++. As far as I know, this property only works for video file, not camera. You have to calculate FPS ...
1
2016-10-16T04:58:59Z
[ "python", "c++", "opencv", "video", "camera" ]
Syntax Error with Django, WSGI, and Apache
40,055,541
<p>I am getting a weird error while trying to run my Django site under Apache using mod_wsgi. I have been working on this for hours to no avail.</p> <p>FYI: I am also using Mezzanine.</p> <p>Log:</p> <pre><code>[Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] mod_wsgi (pid=15554): Target WSGI script '/opt/my...
1
2016-10-15T05:57:51Z
40,055,573
<pre><code>[Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] File "/usr/lib/python2.6/site-packages/django/utils/lru_cache.py", line 28 [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] fasttypes = {int, str, frozenset, type(None)}, [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] ...
2
2016-10-15T06:01:29Z
[ "python", "django", "apache", "mod-wsgi" ]
Python pexpect scripts run without error,but there are no outputs in output file
40,055,592
<p>I want to put the results of 'ls /home' into mylog1.txt through ssh.So,I can check it on my computer.When I run the script,there is no error,there is no output in mylog1.txt。</p> <blockquote> <pre><code>#!/usr/bin/env python import pexpect import sys child=pexpect.spawn('ssh shiyanlou@192.168.42.2') fout=file('m...
1
2016-10-15T06:04:07Z
40,055,650
<p>pexpect is good to intereact with an application.</p> <p>But if you simply want ssh and execute some command, i will advice you to try out <a href="http://www.paramiko.org/" rel="nofollow">Paramiko</a></p>
0
2016-10-15T06:13:22Z
[ "python", "linux", "devops", "pexpect" ]
Python pexpect scripts run without error,but there are no outputs in output file
40,055,592
<p>I want to put the results of 'ls /home' into mylog1.txt through ssh.So,I can check it on my computer.When I run the script,there is no error,there is no output in mylog1.txt。</p> <blockquote> <pre><code>#!/usr/bin/env python import pexpect import sys child=pexpect.spawn('ssh shiyanlou@192.168.42.2') fout=file('m...
1
2016-10-15T06:04:07Z
40,058,575
<p>You have to wait until the <code>ls</code> command finishes, just like when you are interacting with the terminal. See following example (I'm using public key auth for ssh so no password prompt):</p> <pre class="lang-none prettyprint-override"><code>[STEP 106] # cat foo.py import pexpect shell_prompt = 'bash-[.0-9...
0
2016-10-15T11:41:34Z
[ "python", "linux", "devops", "pexpect" ]
Django returning static HTML in views.py?
40,055,632
<p>So I have a standard <code>Django</code> project with a basic view that returns a simple HTML confirmation statement. Would it be plausible for me to define all of my HTML in the view itself as a really long string and return that using <code>HttpResponse()</code> I know it's a bit <code>unorthodox</code>, but this ...
0
2016-10-15T06:10:33Z
40,055,641
<p>Most people dont use this because it mixes Python with HTML and gets very messy and out of hand very quickly</p>
0
2016-10-15T06:11:39Z
[ "python", "html", "django", "http", "httpresponse" ]
Django returning static HTML in views.py?
40,055,632
<p>So I have a standard <code>Django</code> project with a basic view that returns a simple HTML confirmation statement. Would it be plausible for me to define all of my HTML in the view itself as a really long string and return that using <code>HttpResponse()</code> I know it's a bit <code>unorthodox</code>, but this ...
0
2016-10-15T06:10:33Z
40,055,667
<p>You can use built-in <a href="https://docs.djangoproject.com/en/1.10/ref/templates/api/#django.template.Template.render" rel="nofollow">template renderer</a> to get works filters/templatetags/etc </p>
0
2016-10-15T06:15:37Z
[ "python", "html", "django", "http", "httpresponse" ]
Python concurrent.futures - method not called
40,055,652
<p>I am running a local django server with the following code: </p> <pre><code>import concurrent.futures media_download_manager = concurrent.futures.ProcessPoolExecutor(max_workers=2) def hello(): print "hello" for i in range(1, 1000): print "submitting task " media_download_manager.map(hello) </code><...
0
2016-10-15T06:13:27Z
40,055,710
<p><a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.map" rel="nofollow">The <code>Executor.map</code> function</a> is intended to pass arguments from an iterable(s) to a mapping function. You didn't provide any iterables so it doesn't run (and your function takes no argumen...
1
2016-10-15T06:20:17Z
[ "python", "django", "multithreading" ]
Python concurrent.futures - method not called
40,055,652
<p>I am running a local django server with the following code: </p> <pre><code>import concurrent.futures media_download_manager = concurrent.futures.ProcessPoolExecutor(max_workers=2) def hello(): print "hello" for i in range(1, 1000): print "submitting task " media_download_manager.map(hello) </code><...
0
2016-10-15T06:13:27Z
40,055,997
<p>First, you are using <code>map</code> instead of <code>submit</code>. The former is a way similar to the built-in <code>map</code> function to map arguments to a function that you want to run asynchronically on all of them. You used <code>map</code> with <code>i+1</code> instead of an iterable (e.g. <code>[i+1]</co...
1
2016-10-15T06:53:47Z
[ "python", "django", "multithreading" ]
How is Django able to grant reserved port numbers?
40,055,676
<p>Using this command </p> <blockquote> <p><code>python manage.py runserver 0.0.0.0:8000</code></p> </blockquote> <p>we can host a Django server locally on any port.So a developer can use reserved and privileged port numbers say</p> <blockquote> <p><code>python manage.py runserver 127.0.0.1:80</code></p> </block...
1
2016-10-15T06:17:05Z
40,055,695
<p>You should use a proper server instead of Django's test server such as <code>nginx</code> or <code>apache</code> to run the server in production on port <code>80</code>. Running something like <code>sudo python manage.py runserver 0.0.0.0:80</code> is not recommended at all.</p>
1
2016-10-15T06:19:06Z
[ "python", "django", "port" ]
How is Django able to grant reserved port numbers?
40,055,676
<p>Using this command </p> <blockquote> <p><code>python manage.py runserver 0.0.0.0:8000</code></p> </blockquote> <p>we can host a Django server locally on any port.So a developer can use reserved and privileged port numbers say</p> <blockquote> <p><code>python manage.py runserver 127.0.0.1:80</code></p> </block...
1
2016-10-15T06:17:05Z
40,063,068
<p>Port 80 has no magical meaning, it is not "reserved" or "privileged" on your server (besides most likely requiring root privileges to access, as others have mentioned). It is just a regular port that was chosen to be a default for http, so you don't have to write <code>google.com:80</code> every time in your browser...
1
2016-10-15T19:03:16Z
[ "python", "django", "port" ]
Append/concatenate Numpy array to Numpy array
40,055,737
<p>I have two np arrays, one is 1 dimensional, and the other it between 0 and 8 dimensional. I'm trying to append the multidimensional array onto the other array, as you would with a list. I've tried <code>np.append(1dim, multidim)</code> and <code>np.concatenate([1dim, multidim])</code> but neither have worked.</p> ...
0
2016-10-15T06:23:58Z
40,056,265
<p>Your example output shows a (1x8) array concatenated with an (Nx8) array to form an (N+1 x 8) array. </p> <p>If you want to create a "thing" where the first element is the 1-D array and the second element is the N-D array, a list or tuple is your bet. Numpy doesn't really have a great facility for this.</p> <p>If ...
3
2016-10-15T07:20:51Z
[ "python", "numpy" ]
Append/concatenate Numpy array to Numpy array
40,055,737
<p>I have two np arrays, one is 1 dimensional, and the other it between 0 and 8 dimensional. I'm trying to append the multidimensional array onto the other array, as you would with a list. I've tried <code>np.append(1dim, multidim)</code> and <code>np.concatenate([1dim, multidim])</code> but neither have worked.</p> ...
0
2016-10-15T06:23:58Z
40,058,195
<p>You have to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html" rel="nofollow">numpy.append</a> or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow">numpy.concatenate</a>. But careful about the shape of your array. For your case you ha...
0
2016-10-15T11:00:14Z
[ "python", "numpy" ]
Append/concatenate Numpy array to Numpy array
40,055,737
<p>I have two np arrays, one is 1 dimensional, and the other it between 0 and 8 dimensional. I'm trying to append the multidimensional array onto the other array, as you would with a list. I've tried <code>np.append(1dim, multidim)</code> and <code>np.concatenate([1dim, multidim])</code> but neither have worked.</p> ...
0
2016-10-15T06:23:58Z
40,058,338
<p>Or you can do it manually for any shape </p> <pre><code>blank= [ ] #create a blank list a=1D array blank.append(a) b=nD array for i in range(len(b)): blank.append(b[i]) answer=np.array(blank) </code></pre>
0
2016-10-15T11:15:52Z
[ "python", "numpy" ]
while connecting to a host using fabric in python, getting a prompt(Login password for 'root':) asking for root password
40,055,761
<p>In python file code is something like this: with settings(host_string=elasticIP, key_filename = '/path/to/keyfile.pem', user = 'root', use_ssh_config = False): run("any command")</p> <p>After executing this, a prompt appears in console stating "Login password for 'root':" As we dont have a password for this us...
0
2016-10-15T06:27:54Z
40,074,457
<p>When you are using <code>settings</code>, don’t use <code>run</code>, use <code>execute</code>.</p> <pre><code>from fabric.decorators import task from fabric.operations import run, execute def my_command(): run('echo "hello fabric!"') @task def my_task(): with settings(host_string=elasticIP, key_filenam...
0
2016-10-16T19:23:36Z
[ "python", "shell", "unix", "root", "fabric" ]
while connecting to a host using fabric in python, getting a prompt(Login password for 'root':) asking for root password
40,055,761
<p>In python file code is something like this: with settings(host_string=elasticIP, key_filename = '/path/to/keyfile.pem', user = 'root', use_ssh_config = False): run("any command")</p> <p>After executing this, a prompt appears in console stating "Login password for 'root':" As we dont have a password for this us...
0
2016-10-15T06:27:54Z
40,084,005
<p>I diged more into this issue and finally got an answer: file :/etc/ssh/ssh_config holds a property 'UserKnownHostsFile' and 'StrictHostKeyChecking' these properties should be addressed as : StrictHostKeyChecking no UserKnownHostsFile=/dev/null UserKnownHostsFile defines the storing of ssh and some metadata regardin...
0
2016-10-17T10:29:15Z
[ "python", "shell", "unix", "root", "fabric" ]
Python 3: How do I get one class to modify values in an instance of another class?
40,055,765
<p>I am learning to code in Python and am writing a short program with three classes as practice. The first class uses instances of the second and third classes as attributes. I am trying to get a method in the third class change a value in an instance of itself as well as in an instance of the second class. So far I h...
0
2016-10-15T06:28:26Z
40,056,740
<p>You have a hierarchy on classes of this Class_a | | Class_b Class_c</p> <p>now you have done making changes in Class_c and it affects Class_a with regard to the c_attribute component.</p> <p>This technique is very advanced, and I am surprised you learn it as a beginner.</p> <p>However, this is accessible ...
0
2016-10-15T08:17:33Z
[ "python", "class", "attributes" ]
Removing elements from an array that are in another array
40,055,835
<p>Say I have these 2D arrays A and B.</p> <p>How can I remove elements from A that are in B.</p> <pre><code>A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]]) B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]]) #output = [[1,1,2], [1,1,3]] </code></pre> <hr> <p>To be more precise, I would...
11
2016-10-15T06:36:16Z
40,055,892
<p>If you want to do it the numpy way,</p> <pre><code>import numpy as np A = np.array([[1, 1, 1,], [1, 1, 2], [1, 1, 3], [1, 1, 4]]) B = np.array([[0, 0, 0], [1, 0, 2], [1, 0, 3], [1, 0, 4], [1, 1, 0], [1, 1, 1], [1, 1, 4]]) A_rows = A.view([('', A.dtype)] * A.shape[1]) B_rows = B.view([('', B.dtype)] * B.shape[1]) ...
3
2016-10-15T06:43:10Z
[ "python", "arrays", "numpy" ]
Removing elements from an array that are in another array
40,055,835
<p>Say I have these 2D arrays A and B.</p> <p>How can I remove elements from A that are in B.</p> <pre><code>A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]]) B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]]) #output = [[1,1,2], [1,1,3]] </code></pre> <hr> <p>To be more precise, I would...
11
2016-10-15T06:36:16Z
40,055,928
<p>there is a easy solution with <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehension</a>,</p> <pre><code>A = [i for i in A if i not in B] </code></pre> <p>Result</p> <pre><code>[[1, 1, 2], [1, 1, 3]] </code></pre> <p>List comprehension it's not removing the elemen...
4
2016-10-15T06:47:34Z
[ "python", "arrays", "numpy" ]
Removing elements from an array that are in another array
40,055,835
<p>Say I have these 2D arrays A and B.</p> <p>How can I remove elements from A that are in B.</p> <pre><code>A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]]) B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]]) #output = [[1,1,2], [1,1,3]] </code></pre> <hr> <p>To be more precise, I would...
11
2016-10-15T06:36:16Z
40,055,932
<p>Another non-numpy solution:</p> <pre><code>[i for i in A if i not in B] </code></pre>
3
2016-10-15T06:48:09Z
[ "python", "arrays", "numpy" ]
Removing elements from an array that are in another array
40,055,835
<p>Say I have these 2D arrays A and B.</p> <p>How can I remove elements from A that are in B.</p> <pre><code>A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]]) B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]]) #output = [[1,1,2], [1,1,3]] </code></pre> <hr> <p>To be more precise, I would...
11
2016-10-15T06:36:16Z
40,056,135
<p>Here is a Numpythonic approach with <em>broadcasting</em>:</p> <pre><code>In [83]: A[np.all(np.any((A-B[:, None]), axis=2), axis=0)] Out[83]: array([[1, 1, 2], [1, 1, 3]]) </code></pre> <p>Here is a timeit with other answer:</p> <pre><code>In [90]: def cal_diff(A, B): ....: A_rows = A.view([('', A....
9
2016-10-15T07:07:33Z
[ "python", "arrays", "numpy" ]
Removing elements from an array that are in another array
40,055,835
<p>Say I have these 2D arrays A and B.</p> <p>How can I remove elements from A that are in B.</p> <pre><code>A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]]) B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]]) #output = [[1,1,2], [1,1,3]] </code></pre> <hr> <p>To be more precise, I would...
11
2016-10-15T06:36:16Z
40,056,251
<p>Based on <a href="http://stackoverflow.com/a/38674038/3293881"><code>this solution</code></a> to <a href="http://stackoverflow.com/questions/38674027/find-the-row-indexes-of-several-values-in-a-numpy-array"><code>Find the row indexes of several values in a numpy array</code></a>, here's a NumPy based solution with l...
9
2016-10-15T07:19:03Z
[ "python", "arrays", "numpy" ]
I am trying to print some predefined sequence in python
40,055,852
<p>I am trying to add to more paragraph but getting error? I am able to print first three paragraph but while I trying to add to more paragraph getting error. Can anyone please correct?</p> <p>Input file:</p> <pre><code>HETATM10910 C4B NAD A 363 60.856 -58.575 149.282 1.00 40.44 C HETATM10911 O4B ...
0
2016-10-15T06:38:41Z
40,055,953
<p>In your code</p> <pre><code>for i in range(len(atomIDs)-n+1): for j in range(len(i)-n+1): for k in range(len((j))-n+1): for l in range(n): </code></pre> <p>you take the length of <code>i</code> and <code>j</code>. These are integers (obtained from range), and as the error you receive states...
0
2016-10-15T06:49:45Z
[ "python", "python-2.7", "python-3.x", "bioinformatics" ]
Playing MP3s in Python - Automatically handling varied sampling frequencies
40,056,024
<p>I am writing a python program to practice and test my Mandarin oral comprehension. It selects a random mp3 from my designated directory and plays it (then does more stuff after). I am using pygame to play these mp3s, but my problem is my current setup requires explicit declaration of the sampling frequency of the ...
0
2016-10-15T06:57:37Z
40,056,701
<p>You can use <a href="http://eyed3.nicfit.net/" rel="nofollow">eyeD3</a>:</p> <pre><code>import eyed3 e = eyed3.load(filename) print e.info.sample_freq </code></pre>
1
2016-10-15T08:09:54Z
[ "python", "pygame", "mp3", "frequency", "sampling" ]
python program freezes after client connects
40,056,046
<p>I have this python program which uses flask for video streaming( sequence of independent JPEG pictures). I know I should debug this myself first but as soon as the client connects index.html only shows a broken image icon and the computer freezes. I have tried -</p> <ul> <li>Running it on linux where it runs fine....
0
2016-10-15T06:59:57Z
40,056,948
<p>It appears that you might want to double check the routes to the image files from app.py, i.e. make sure they're in the same directory or if they're in an /images directory, double check the path to the files or that they are there to begin with.</p> <p>As a test, (git) clone Miguel's project and run it and see whe...
0
2016-10-15T08:43:56Z
[ "python", "windows", "python-3.x", "flask", "mjpeg" ]
Maximum distance between points in a convex hull
40,056,061
<p>I am solving a problem in which I need to find the maximum distance between two points on a plane (2D) .So there is an O(n^2) approach in which I calculate distance between every point in the graph . I also implemented a convex hull algorithm now my approach is I compute convex hull in O(nlogn) and then use the O(n^...
2
2016-10-15T07:00:56Z
40,057,533
<p>Once you have a convex hull, you can find two furthest points in linear time. </p> <p>The idea is to keep two pointers: one of them points to the current edge (and is always incremented by one) and the other one points to a vertex.</p> <p>The answer is the maximum distance between end points of an edge and the ver...
1
2016-10-15T09:50:36Z
[ "python", "algorithm", "python-2.7", "convex-hull" ]
Did numpy override == operator, because i can't understand follow python code
40,056,209
<pre><code>image_size = 28 num_labels = 10 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels train_datas...
1
2016-10-15T07:15:28Z
40,056,270
<p>In numpy, the <code>==</code> operator means something different when comparing two numpy arrays (as is being done in that line of note), so yes, it is overloaded in that sense. It compares the two numpy arrays elementwise and returns a boolean numpy array of the same size as the two inputs. The same is true for oth...
3
2016-10-15T07:21:47Z
[ "python", "numpy" ]
Did numpy override == operator, because i can't understand follow python code
40,056,209
<pre><code>image_size = 28 num_labels = 10 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels train_datas...
1
2016-10-15T07:15:28Z
40,056,282
<p>For Numpy arrays the <code>==</code> operator is a element-wise operation which returns a boolean array. The <code>astype</code> function transforms the boolean values <code>True</code> to <code>1.0</code> and <code>False</code> to <code>0.0</code> as stated in the comment.</p>
1
2016-10-15T07:22:54Z
[ "python", "numpy" ]
Did numpy override == operator, because i can't understand follow python code
40,056,209
<pre><code>image_size = 28 num_labels = 10 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels train_datas...
1
2016-10-15T07:15:28Z
40,061,909
<p><a href="https://docs.python.org/3/reference/expressions.html#value-comparisons" rel="nofollow">https://docs.python.org/3/reference/expressions.html#value-comparisons</a> describes value comparisons like <code>==</code>. While the default comparison is an <code>identity</code> <code>x is y</code>, it first checks i...
0
2016-10-15T17:08:30Z
[ "python", "numpy" ]
How does numpy broadcasting perform faster?
40,056,275
<p>In the following question, <a href="http://stackoverflow.com/a/40056135/5714445">http://stackoverflow.com/a/40056135/5714445</a></p> <p>Numpy's broadcasting provides a solution that's almost 6x faster than using np.setdiff1d() paired with np.view(). How does it manage to do this?</p> <p>And using <code>A[~((A[:,No...
6
2016-10-15T07:22:13Z
40,057,999
<p>I would try to answer the second part of the question.</p> <p>So, with it we are comparing :</p> <pre><code>A[np.all(np.any((A-B[:, None]), axis=2), axis=0)] (I) </code></pre> <p>and </p> <pre><code>A[~((A[:,None,:] == B).all(-1)).any(1)] </code></pre> <p>To compare with a matching perspective against the firs...
5
2016-10-15T10:39:59Z
[ "python", "numpy" ]