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
How Do I Start Pulling Apart This Block of JSON Data?
38,978,428
<p>I'd like to make a program that makes offline copies of math questions from Khan Academy. I have a huge 21.6MB text file that contains data on all of their exercises, but I have no idea how to start analyzing it, much less start pulling the questions from it.</p> <p><a href="http://pastebin.com/x8xjS1kx" rel="nofol...
0
2016-08-16T15:06:56Z
38,979,645
<p>Ok, the repeated pattern appears to be this: <a href="http://pastebin.com/4nSnLEFZ" rel="nofollow">http://pastebin.com/4nSnLEFZ</a></p> <p>To get an idea of the structure of the response, you can use <a href="http://jsonlint.com/" rel="nofollow">JSONlint</a> to copy/paste portions of your string and 'validate'. Eve...
1
2016-08-16T16:07:01Z
[ "python", "json", "khan-academy" ]
How to get n longest entries of DataFrame?
38,978,432
<p>I'm trying to get the n longest entries of a dask DataFrame. I tried calling <a href="http://%20http://dask.pydata.org/en/latest/dataframe-api.html#dask.dataframe.DataFrame.nlargest" rel="nofollow">nlargest</a> on a dask DataFrame with two columns like this:</p> <pre><code>import dask.dataframe as dd df = dd.read_...
2
2016-08-16T15:07:01Z
38,979,064
<p>I tried to reproduce your problem but things worked fine. Can I recommend that you produce a <a href="http://stackoverflow.com/help/mcve">Minimal Complete Verifiable Example</a>?</p> <h3>Pandas example</h3> <pre><code>In [1]: import pandas as pd In [2]: df = pd.DataFrame({'x': ['a', 'bb', 'ccc', 'dddd']}) In [3...
0
2016-08-16T15:36:48Z
[ "python", "dask" ]
Creating uniform random quaternion and multiplication of two quaternions
38,978,441
<p>I have a python (NumPy) function which creates a uniform random quaternion. I would like to get two quaternion multiplication as 2-dimensional returned array from the same or an another function. The formula of quaternion multiplication in my recent case is Q1*Q2 and Q2*Q1. Here, <code>Q1=(w0, x0, y0, z0)</code> and...
1
2016-08-16T15:07:28Z
38,979,399
<p>A 2-Dimensional Array is an array like this: foo[0][1]</p> <p>You don't need to do that. Multiplying two quaternions yields one single quaternion. I don't see why you would need a two-dimensional array, or how you would even use one.</p> <p>Just have a function that takes two arrays as arguments:</p> <pre><code>...
0
2016-08-16T15:54:27Z
[ "python", "numpy", "2d", "quaternions" ]
Creating uniform random quaternion and multiplication of two quaternions
38,978,441
<p>I have a python (NumPy) function which creates a uniform random quaternion. I would like to get two quaternion multiplication as 2-dimensional returned array from the same or an another function. The formula of quaternion multiplication in my recent case is Q1*Q2 and Q2*Q1. Here, <code>Q1=(w0, x0, y0, z0)</code> and...
1
2016-08-16T15:07:28Z
38,982,314
<p>A simple rendition of your request would be:</p> <pre><code>In [70]: def multQ(Q1,Q2): ...: w0,x0,y0,z0 = Q1 # unpack ...: w1,x1,y1,z1 = Q2 ...: return([-x1*x0 - y1*y0 - z1*z0 + w1*w0, x1*w0 + y1*z0 - z1*y0 + ...: w1*x0, -x1*z0 + y1*w0 + z1*x0 + w1*y0, x1*y0 - y1*x0 + z1*w0 + ....
0
2016-08-16T18:45:11Z
[ "python", "numpy", "2d", "quaternions" ]
cx_Freeze giving error when using fuzzywuzzy
38,978,457
<p>I have built a tkinter GUI for survey entry in python3.4 that uses a number of packages. I then need to compile it to an executable so that I can put it on a coworkers machine (we both are on windows7 platform) I've structured my setup.py to look like:</p> <pre><code>from cx_Freeze import setup, Executable import s...
0
2016-08-16T15:08:05Z
38,979,113
<p>Found the solution - <code>python-Levenshtein</code> needs to be installed. Got mine from gohlke's repository: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-levenshtein" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-levenshtein</a> - make sure you have the platform that matches your p...
0
2016-08-16T15:39:40Z
[ "python", "python-3.x", "python-3.4", "cx-freeze", "fuzzywuzzy" ]
How to create pandas dataframe variable/column based on two or more other variables?
38,978,461
<p>I have a pandas dataframe, e.g.:</p> <pre><code>Col1 Col2 A 1 B 2 C 3 </code></pre> <p>I understand how to create a Col3 based on say the value of Col2:</p> <pre><code>df['Col3'] = (df['Col2'] &lt;= 1).astype(int) </code></pre> <p>But ... How about if the new column was based on two variables, as in...
3
2016-08-16T15:08:32Z
38,978,508
<p>You can try double <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p> <pre><code>df['Col4'] = np.where((df['Col2'] == 1) &amp; (df['Col3'] == 1), 'X', np.where((df['Col2'] == 1) &amp; (df['Col3'] == 2), 'Y', 'Z')) </co...
1
2016-08-16T15:11:32Z
[ "python", "pandas", "dataframe" ]
How to create pandas dataframe variable/column based on two or more other variables?
38,978,461
<p>I have a pandas dataframe, e.g.:</p> <pre><code>Col1 Col2 A 1 B 2 C 3 </code></pre> <p>I understand how to create a Col3 based on say the value of Col2:</p> <pre><code>df['Col3'] = (df['Col2'] &lt;= 1).astype(int) </code></pre> <p>But ... How about if the new column was based on two variables, as in...
3
2016-08-16T15:08:32Z
38,978,774
<p>You can initialize the column with your final <code>else</code> value (e.g. <code>Z</code>) and then check each condition:</p> <pre><code>df['Col4'] = 'Z' df.loc[(df.Col1 == 1) &amp; (df.Col3 == 1), 'Col4'] = 'X' df.loc[(df.Col2 == 1) &amp; (df.Col3 == 2), 'Col4'] = 'Y' </code></pre>
0
2016-08-16T15:24:49Z
[ "python", "pandas", "dataframe" ]
Select preceding/following-sibling XPath
38,978,641
<p>I am using Selenium with Python and I wanna select the html before hr tag. Here's the code I have:</p> <pre><code>&lt;div id="wikipage"&gt; &lt;div id="wikipage-inner"&gt; &lt;h1&gt;Berkeley&lt;/h1&gt; &lt;p&gt;&lt;span&gt;&lt;strong&gt;Title1&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Address: &l...
-1
2016-08-16T15:18:36Z
38,992,521
<h3>If you have fixed numbers of <code>&lt;p&gt;</code> nodes you can try this xpath:</h3> <pre><code>//hr[x]/preceding-sibling::p[position()&lt;=y] </code></pre> <p>Where <strong>x</strong> is position of your <code>&lt;hr/&gt;</code> tag and <strong>y</strong> is number of <code>&lt;p&gt;</code> tags before <code>&...
1
2016-08-17T09:15:22Z
[ "python", "selenium", "xpath" ]
How to protect an object using a lock in Python?
38,978,652
<p>I've come accross functionality which required the following pattern:</p> <pre><code>from threading import Lock the_list = [] the_list_lock = Lock() </code></pre> <p>and to use it:</p> <pre><code>with the_list_lock: the_list.append("New Element") </code></pre> <p>Unfortunately, this does not require me to ...
1
2016-08-16T15:19:10Z
38,978,949
<p>My current solution (the one I talk about in the question) looks like this:</p> <pre><code>import threading class HidingLock(object): def __init__(self, obj, lock=None): self.lock = lock or threading.RLock() self._obj = obj def __enter__(self): self.lock.acquire() return se...
0
2016-08-16T15:31:50Z
[ "python", "multithreading", "locks" ]
How to protect an object using a lock in Python?
38,978,652
<p>I've come accross functionality which required the following pattern:</p> <pre><code>from threading import Lock the_list = [] the_list_lock = Lock() </code></pre> <p>and to use it:</p> <pre><code>with the_list_lock: the_list.append("New Element") </code></pre> <p>Unfortunately, this does not require me to ...
1
2016-08-16T15:19:10Z
38,980,569
<p>I think the reason there's nothing in the standard library is because for it to be there it would need to make cast iron access guarantees. To provide anything less would give a <strong>false sense of security</strong> that could lead to just as many concurrency issues.</p> <p>It's also nearly impossible to make th...
3
2016-08-16T16:59:16Z
[ "python", "multithreading", "locks" ]
How to protect an object using a lock in Python?
38,978,652
<p>I've come accross functionality which required the following pattern:</p> <pre><code>from threading import Lock the_list = [] the_list_lock = Lock() </code></pre> <p>and to use it:</p> <pre><code>with the_list_lock: the_list.append("New Element") </code></pre> <p>Unfortunately, this does not require me to ...
1
2016-08-16T15:19:10Z
38,983,084
<p>What about creating a <code>shared_list</code> that has a <code>list</code> and implements the desired class methods using a <code>threading.Lock</code>:</p> <pre><code>import threading class SharedList(object): def __init__(self, iterable=None): if iterable is not None: self.list = list(it...
0
2016-08-16T19:35:05Z
[ "python", "multithreading", "locks" ]
Comparing two list and returning the indices of the matched items with python
38,978,662
<p>I have two lists</p> <pre><code>a = [1.1, 2.2, 5.6, 7.8,7.8, 8.6,10.2] b = [2.2, 1.4, 1.99, 7.88, 7.8] </code></pre> <p>I want both lists to be compared and the indices of entities which delivered the same value with reference to the list a. There can be multiple hits in list a.</p> <p>The results is</p> <pre><c...
0
2016-08-16T15:19:46Z
38,978,754
<p>You can create a utility dictionary mapping the items to the list of positions in the <code>a</code> list:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; &gt;&gt;&gt; a = [1.1, 2.2, 5.6, 7.8,7.8, 8.6,10.2] &gt;&gt;&gt; b = [2.2, 1.4, 1.99, 7.88, 7.8] &gt;&gt;&gt; &gt;&gt;&gt; d = defau...
2
2016-08-16T15:23:52Z
[ "python", "list", "comparison" ]
Comparing two list and returning the indices of the matched items with python
38,978,662
<p>I have two lists</p> <pre><code>a = [1.1, 2.2, 5.6, 7.8,7.8, 8.6,10.2] b = [2.2, 1.4, 1.99, 7.88, 7.8] </code></pre> <p>I want both lists to be compared and the indices of entities which delivered the same value with reference to the list a. There can be multiple hits in list a.</p> <p>The results is</p> <pre><c...
0
2016-08-16T15:19:46Z
38,978,880
<pre><code>checker ={} for i,item in enumerate(a): checker[item] = checker.get(item,[]) +[i] reduce(lambda x,y:x+y, [checker[i] for i in b if i in checker]) [1, 3, 4] </code></pre>
0
2016-08-16T15:29:26Z
[ "python", "list", "comparison" ]
Comparing two list and returning the indices of the matched items with python
38,978,662
<p>I have two lists</p> <pre><code>a = [1.1, 2.2, 5.6, 7.8,7.8, 8.6,10.2] b = [2.2, 1.4, 1.99, 7.88, 7.8] </code></pre> <p>I want both lists to be compared and the indices of entities which delivered the same value with reference to the list a. There can be multiple hits in list a.</p> <p>The results is</p> <pre><c...
0
2016-08-16T15:19:46Z
38,980,550
<p>A variation on the other answers. My first thought was to turn <code>b</code> into a set then test for membership - sets are good for membership testing.</p> <pre><code>&gt;&gt;&gt; a = [1.1, 2.2, 5.6, 7.8,7.8, 8.6,10.2] &gt;&gt;&gt; b = [2.2, 1.4, 1.99, 7.88, 7.8] &gt;&gt;&gt; &gt;&gt;&gt; b = set(b) &gt;&gt;&gt...
2
2016-08-16T16:57:59Z
[ "python", "list", "comparison" ]
Python how to delete list of items with a blacklist not to delete
38,978,687
<p>I have a utility to delete a list of projects, but I want to know how I can add a black list filter of projects not to delete.</p> <p>This is what I have right now, I run the script a few times changing the if "Languages" in project: line to delete different projects.</p> <pre><code>def delete_projects(): proj...
0
2016-08-16T15:20:59Z
38,978,753
<p>It's relatively simple to create a new list containing only the elements whose names are in the blacklist:</p> <pre><code>projects = [project for project in projects if project not in blacklist] </code></pre> <p>When the blacklist contains patterns, however, the condition may need to be more complex. One way to ex...
2
2016-08-16T15:23:50Z
[ "python" ]
Python how to delete list of items with a blacklist not to delete
38,978,687
<p>I have a utility to delete a list of projects, but I want to know how I can add a black list filter of projects not to delete.</p> <p>This is what I have right now, I run the script a few times changing the if "Languages" in project: line to delete different projects.</p> <pre><code>def delete_projects(): proj...
0
2016-08-16T15:20:59Z
38,978,772
<p>You could use Python's <a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow"><code>any</code></a>:</p> <pre><code>BLACKLIST = {'languages'} def delete_projects(): projects = get_projects() for project in projects: if any(term in project for term in BLACKLIST): delete...
0
2016-08-16T15:24:42Z
[ "python" ]
Python how to delete list of items with a blacklist not to delete
38,978,687
<p>I have a utility to delete a list of projects, but I want to know how I can add a black list filter of projects not to delete.</p> <p>This is what I have right now, I run the script a few times changing the if "Languages" in project: line to delete different projects.</p> <pre><code>def delete_projects(): proj...
0
2016-08-16T15:20:59Z
38,978,846
<p>You can simply use a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> like this:</p> <pre><code>projects = [p for p in get_projects() if p in to_keep] </code></pre> <p>If you want to select the objects that are not in a list simply do:</p> ...
0
2016-08-16T15:27:58Z
[ "python" ]
Python how to delete list of items with a blacklist not to delete
38,978,687
<p>I have a utility to delete a list of projects, but I want to know how I can add a black list filter of projects not to delete.</p> <p>This is what I have right now, I run the script a few times changing the if "Languages" in project: line to delete different projects.</p> <pre><code>def delete_projects(): proj...
0
2016-08-16T15:20:59Z
38,979,009
<pre><code>import re black_list_of_regex = ['order-.*', 'normal_name'] print([project for project in projects for reg in black_list_of_regex if re.match(reg, project)]) </code></pre> <p>Remember if you want to match full name you should use start/end string regexp <code>^</code>, <code>$</code> in your regular express...
0
2016-08-16T15:34:18Z
[ "python" ]
Python how to delete list of items with a blacklist not to delete
38,978,687
<p>I have a utility to delete a list of projects, but I want to know how I can add a black list filter of projects not to delete.</p> <p>This is what I have right now, I run the script a few times changing the if "Languages" in project: line to delete different projects.</p> <pre><code>def delete_projects(): proj...
0
2016-08-16T15:20:59Z
38,979,126
<p>If <code>projects</code> are strings, and you have a <code>blacklist</code> then you can do:</p> <pre><code>set(projects) - set(blacklist) </code></pre> <p>You can create the black list by:</p> <pre><code>blacklist = [project for project in projects if 'Languages' in project] </code></pre> <p><strong>Another</st...
0
2016-08-16T15:40:18Z
[ "python" ]
ValueError: invalid literal for int() with base 10: - CharField
38,978,761
<p>I'm trying to add an object to my database with models. But getting an error. As I understand <code>CharField</code> are strings? And the error complains that it's an invalid integer?</p> <pre><code>from django.shortcuts import HttpResponse from Cr.models import User def index(request): a = User('Ra', 'sen') ...
0
2016-08-16T15:24:20Z
38,978,813
<p><code>a = User('Ra', 'sen')</code> </p> <p>The first positional argument is used for the <code>pk</code>. When creating a model you should use keyword arguments:</p> <p><code>a = User(username='Ra', password='sen')</code></p>
3
2016-08-16T15:26:41Z
[ "python", "django" ]
Referencing keys in a Python dictionary for CSV reader
38,978,769
<p>new to python and trying to build a simple CSV reader to create new trades off an existing instrument. Ideally, I'd like to build a dictionary to simplify the parameters required to set up a new trade (instead of using row[1], [2], [3], etc, I'd like to replace with my headers that read Value Date, Trade Date, Price...
1
2016-08-16T15:24:35Z
38,979,695
<p>The <code>csv</code> module already provides this functionality with the <code>csv.DictReader</code> object. </p> <pre><code>with open('C:\Users\Yina.Huang\Desktop\export\TradeBooking.csv', 'rb') as f: reader = csv.DictReader(f) for row in reader: NewTrade = acm.FTrade() NewTrade....
1
2016-08-16T16:09:29Z
[ "python", "csv", "dictionary", "key" ]
Exporting data to csv python
38,978,776
<p>When I use the following code below, my data gets exported but its all in one column going all the way down, any help?</p> <pre><code>b = open('tester.csv', 'wb') a = csv.writer(b) while (count &lt; x): tags = str(data['alerts'][count] ['tags']).replace("u\"","\"").replace("u\'","\'") a.writerows(strList) </...
0
2016-08-16T15:24:55Z
38,979,298
<p>Given your data, I fail to see how this could go wrong, unless your data doesn't actually look like this. </p> <pre><code>&gt;&gt;&gt; data = [['hi', 'yes', 'bye', 'def'], ['hi', 'ast', 'cnx', 'vplex'], ['ever', 'as', 'no', 'qwerty', 'redi'], ['no', 'yes', 'qwerty'], ['redi', 'google'], ['redi', 'asdf', 'asdfef'...
0
2016-08-16T15:49:30Z
[ "python", "csv", "export-to-csv" ]
Python memory when plotting figures in a loop
38,978,920
<p>I am trying to print a sequence of images in a code loop. I will ultimately need to print around 1000 to show how my system varies with time. I have reviewed the methods outlined in <a href="http://stackoverflow.com/questions/2364945/matplotlib-runs-out-of-memory-when-plotting-in-a-loop">Matplotlib runs out of memor...
0
2016-08-16T15:30:47Z
38,980,600
<p>Here is one stripped example of what you can do. As pointed out by Ajean, you should NOT import plt every time as you did! It is enough once. Also, do not delete the figure and create a new one...it is better to use the same figure and just replace the data. </p> <pre><code>import numpy as np import matplotlib.p...
1
2016-08-16T17:00:55Z
[ "python", "matplotlib" ]
Code exit status 255
38,978,925
<p>I have written the below code for getting the only unique element in a given integer array.</p> <pre><code>def lonelyinteger(a): for x in a: answer = a.count(x) if(a.count(x) &lt; 2) answer=x return answer if __name__ == '__main__': a = input() b = map(int, raw_input().st...
-1
2016-08-16T15:31:01Z
38,978,954
<p>You are missing the <code>:</code> at the end of that line.</p>
2
2016-08-16T15:32:03Z
[ "python" ]
Code exit status 255
38,978,925
<p>I have written the below code for getting the only unique element in a given integer array.</p> <pre><code>def lonelyinteger(a): for x in a: answer = a.count(x) if(a.count(x) &lt; 2) answer=x return answer if __name__ == '__main__': a = input() b = map(int, raw_input().st...
-1
2016-08-16T15:31:01Z
38,979,087
<p>Correct code below this (your code modified):</p> <pre><code>def lonelyinteger(a): # added a : that was missing in the for # loop (syntax error) for x in a: answer = a.count(x) if(a.count(x) &lt; 2): answer=x return answer if __name__ == '__main__': a = input() b ...
-1
2016-08-16T15:38:05Z
[ "python" ]
Clear chatterbot database
38,979,022
<p>I'm trying to use Chatterbot (<a href="http://chatterbot.readthedocs.io/" rel="nofollow">http://chatterbot.readthedocs.io/</a>) for a simple chat AI, but I have a few problems.</p> <p>I'm trying to create my own database for it. But it seems that it has it cached somewhere, I can't clear it's database to completely...
0
2016-08-16T15:34:50Z
38,979,326
<p>Oh, stupid me. The file 'database.db' was under my nose, in the same folder as my python file.</p>
2
2016-08-16T15:50:46Z
[ "python" ]
Multiple simultaneous HTTP requests
38,979,024
<p>I'm trying to take a list of items and check for their status change based on certain processing by the API. The list will be manually populated and can vary in number to several thousand.</p> <p>I'm trying to write a script that makes multiple simultaneous connections to the API to keep checking for the status cha...
0
2016-08-16T15:34:58Z
38,979,364
<p>In the code, the list is only read once. Should be something like</p> <pre><code>try: while True: for value in open('valuelist.txt'): fullUrl = requestURLBase + "?key=" + apiKey + "&amp;value=" + value.strip() + "&amp;years=" print fullUrl q.put(fullUrl) q.joi...
0
2016-08-16T15:53:00Z
[ "python", "multithreading", "api", "rest", "python-multithreading" ]
Python ValueError: embedded null byte when reading png file from bash pipe
38,979,075
<pre><code>from PIL import Image from subprocess import Popen, PIPE scr = Image.open(Popen.communicate(Popen(['import','-w','0x02a00001','png:-'], stdout=PIPE))[0]) </code></pre> <p>File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2258, in open fp = builtins.open(filename, "rb") ValueError: embedded null ...
0
2016-08-16T15:37:13Z
38,981,166
<p>Try first to load raw data into a <code>BytesIO</code> container:</p> <pre><code>from io import BytesIO from PIL import Image from subprocess import Popen, PIPE data = Popen.communicate(Popen(['import','-w','0x02a00001','png:-'], stdout=PIPE))[0] scr = Image.open(BytesIO(data)) </code></pre>
2
2016-08-16T17:36:18Z
[ "python", "linux", "bash" ]
How to guarantee repartitioning in Spark Dataframe
38,979,098
<p>I'm pretty new to Apache Spark and I'm trying to repartition a dataframe by U.S. State. I then want to break each partition into its own RDD and save to a specific location:</p> <pre><code>schema = types.StructType([ types.StructField("details", types.StructType([ types.StructField("state", types.StringType...
1
2016-08-16T15:38:51Z
38,986,150
<p>There is nothing unexpected going on here. Spark is using hash of the partitioning key (positive) modulo number of partitions to distribute rows between partitions and with 50 partitions you'll get a significant number of duplicates:</p> <pre><code>from pyspark.sql.functions import expr states = sc.parallelize([ ...
2
2016-08-16T23:51:05Z
[ "python", "apache-spark", "pyspark", "partitioning" ]
please fix following multithreading code in python
38,979,141
<pre><code> import time from threading import thread def myfunc(i): #Each thread runs this function print "sleep from thread %d" % i time. Sleep(5) print "woke up from thread %d" % i return for i in range(10): # Create 10 Thread objects t = Thread(target=myfunc, args=(i,)) t.start() #S...
-2
2016-08-16T15:41:17Z
38,979,275
<p>For the error you are pointing out, this is because the import statement should be like so :<br> <code>from threading import time</code> </p>
0
2016-08-16T15:48:15Z
[ "python", "multithreading", "python-multithreading" ]
what are the differences between import and extends in Flask?
38,979,155
<p>I am reading 《Flask web development》. in Example 4-3,</p> <pre><code>{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} </code></pre> <p>I'd like to know: What are the differences between extends and import?(I think they are quite similar in usage.) In which situation,I will use extends or im...
3
2016-08-16T15:42:15Z
38,979,410
<p>There <em>is</em> a difference. <code>{% extends parent.html %}</code> allows you to render <code>parent.html</code> and also override <code>{% block %}</code>'s defined in it while <code>{% import %}</code> just allows you to access template variables.</p> <p>So example template is extends <code>base.html</code> a...
1
2016-08-16T15:55:11Z
[ "python", "flask", "jinja2" ]
what are the differences between import and extends in Flask?
38,979,155
<p>I am reading 《Flask web development》. in Example 4-3,</p> <pre><code>{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} </code></pre> <p>I'd like to know: What are the differences between extends and import?(I think they are quite similar in usage.) In which situation,I will use extends or im...
3
2016-08-16T15:42:15Z
38,979,535
<blockquote> <p>By default, included templates are passed the current context and imported templates are not. <a href="http://By%20default,%20included%20templates%20are%20passed%20the%20current%20context%20and%20imported%20templates%20are%20not." rel="nofollow">Jinja documentation</a></p> </blockquote> <p>By defa...
0
2016-08-16T16:01:45Z
[ "python", "flask", "jinja2" ]
what are the differences between import and extends in Flask?
38,979,155
<p>I am reading 《Flask web development》. in Example 4-3,</p> <pre><code>{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} </code></pre> <p>I'd like to know: What are the differences between extends and import?(I think they are quite similar in usage.) In which situation,I will use extends or im...
3
2016-08-16T15:42:15Z
38,980,052
<p>When you <code>extend</code> another template the template controls you (the called controls the caller) - only named blocks in the "parent" template will be rendered:</p> <pre><code>{% extends "base.html" %} {% block main_content %} Only shows up if there is a block called main_content in base.html. {% endblock ma...
3
2016-08-16T16:31:01Z
[ "python", "flask", "jinja2" ]
How to remote click on links from a 3rd party website
38,979,170
<p>I have a problem that I am trying to conceptualize whether possible or not. Nothing too fancy (i.e. remote login or anything etc.)</p> <p>I have Website A and Website B. </p> <p>On website A a user selects on a few links from website B, i would like to then remotely click on behalf of the user on the link (as Webs...
0
2016-08-16T15:42:53Z
38,979,448
<p>IF you want to interact to anorher webservice the resolution is send post/get request and parse response Question is what is your goal?</p>
0
2016-08-16T15:57:26Z
[ "javascript", "jquery", "python", "cookies" ]
Need help in Radix sort
38,979,220
<p>I am having a problem in creating a list I am done with the logic part for radix sort . Here is the code:</p> <pre><code>import math a = [4, 15, 7, 3, 6, 22, 45, 82] a1 = [[] for _ in xrange(len(a))] a2 = [[] for _ in xrange(len(a))] a3 = [[] for _ in xrange(len(a))] a4 = [[] for _ in xrange(len(a))] b = [[] fo...
-1
2016-08-16T15:45:26Z
38,979,376
<p>Each <code>b[?]</code> is an array of integers, so <code>b[k][t]</code> will be an integer, but you are trying to take its length in <code>if len(b[k][t])==0:</code>.</p> <p>The only way to avoid having empty elements of <code>a2</code> is to not use an array; for example, a dictionary.</p>
0
2016-08-16T15:53:44Z
[ "python", "radix-sort" ]
Dynamically created inputs then getting data from inputs with flask
38,979,227
<p>I wrote some HTML and Javascript to create a table that has input fields that appear. Here is a picture of the <a href="http://i.stack.imgur.com/xJDFR.png" rel="nofollow">HTML Table</a>. When the user keeps clicking the button to add more it looks like this: <a href="http://i.stack.imgur.com/gLagy.png" rel="nofollow...
1
2016-08-16T15:45:45Z
38,983,699
<p>Maybe try this repository: <a href="https://github.com/sebkouba/dynamic-flask-form" rel="nofollow">https://github.com/sebkouba/dynamic-flask-form</a> Works fine out of box.</p>
1
2016-08-16T20:15:38Z
[ "javascript", "python", "html", "input", "flask" ]
Dynamically created inputs then getting data from inputs with flask
38,979,227
<p>I wrote some HTML and Javascript to create a table that has input fields that appear. Here is a picture of the <a href="http://i.stack.imgur.com/xJDFR.png" rel="nofollow">HTML Table</a>. When the user keeps clicking the button to add more it looks like this: <a href="http://i.stack.imgur.com/gLagy.png" rel="nofollow...
1
2016-08-16T15:45:45Z
39,003,383
<p>I noticed that if you want to have all dynamically created inputs with the same name that they must be a different name from the first input field that is not dynamically created. So, I named the first input s0 and the rest of the dynamically created inputs s1. I can then call request.form.get() on s0 and can call r...
1
2016-08-17T17:58:16Z
[ "javascript", "python", "html", "input", "flask" ]
Dynamically created inputs then getting data from inputs with flask
38,979,227
<p>I wrote some HTML and Javascript to create a table that has input fields that appear. Here is a picture of the <a href="http://i.stack.imgur.com/xJDFR.png" rel="nofollow">HTML Table</a>. When the user keeps clicking the button to add more it looks like this: <a href="http://i.stack.imgur.com/gLagy.png" rel="nofollow...
1
2016-08-16T15:45:45Z
39,003,708
<p>I don´t know much about flask, but with this code, you can get the array of objects and insert them one by one with your server logic.</p> <p><a href="https://jsfiddle.net/8gdun4j0/" rel="nofollow">https://jsfiddle.net/8gdun4j0/</a></p> <p>PS: used jquery</p> <pre><code> arrayObject=[]; $("#subButon").on("click...
1
2016-08-17T18:17:31Z
[ "javascript", "python", "html", "input", "flask" ]
Django-registration Forbidden (403) CSRF verification failed. Request aborted
38,979,332
<p>After installing django-registration-redux I have an 403 CSRF Error each time I try to register. Here is my form.html:</p> <pre><code>{% extends "base.html" %} {% load i18n %} {% load crispy_forms_tags %} {% block content %} &lt;div class="space"&gt;&lt;/div&gt; &lt;div class="space"&gt;&lt;/div&gt; &lt;div clas...
0
2016-08-16T15:51:08Z
39,362,984
<p>I have the same problem after i update my django from 1.8 to 1.10. downgrading to 1.8 fix the problem (for now).. </p>
1
2016-09-07T06:49:23Z
[ "python", "django", "django-registration", "django-csrf" ]
Python3 -m /path/to/file is giving me an error, whereas python -m /path/to/file is not
38,979,362
<p>I have been using the mod option on the command line with python (Python 2.7.X) for a while, and I am now switching to Python 3.</p> <pre><code>python -m path/to/file </code></pre> <p>Now when I try to do the same procedure, but with Python 3, literally the same line:</p> <pre><code>python3 -m path/to/file </code...
1
2016-08-16T15:52:52Z
38,979,444
<p>Python3 won't look for Python2 modules. You need to install modules specifically for Python3.</p> <p>To give a concrete example: Under Debian, package python-numpy installs to <code>/usr/lib/python2.7/dist-packages/numpy/</code> whereas package python3-numpy installs to <code>/usr/lib/python3/dist-packages/numpy/</...
0
2016-08-16T15:57:14Z
[ "python", "python-3.x", "module", "options", "mod" ]
Python3 -m /path/to/file is giving me an error, whereas python -m /path/to/file is not
38,979,362
<p>I have been using the mod option on the command line with python (Python 2.7.X) for a while, and I am now switching to Python 3.</p> <pre><code>python -m path/to/file </code></pre> <p>Now when I try to do the same procedure, but with Python 3, literally the same line:</p> <pre><code>python3 -m path/to/file </code...
1
2016-08-16T15:52:52Z
38,979,755
<p>The usage is not:</p> <pre><code>$ python -m path/to/file </code></pre> <p>but rather </p> <pre><code>$ python -m package.subpackage.module </code></pre> <p>The <code>-m</code> flag adds the current directory on your path, otherwise it looks for the module to open the program with. For example, Python 2:</p> <...
1
2016-08-16T16:13:10Z
[ "python", "python-3.x", "module", "options", "mod" ]
Print list of lists in Python in specific order
38,979,363
<p>I have this list:</p> <pre><code>vshape = [['0','1','1'],['1','0','1'],['1','1','0'],['1','0','1'],['0','1','1']] </code></pre> <p>I need to print out every item in specific order - one line of vshape[0][0], vshape[1][0], vshape[2][0], vshape[3][0], and vshape[4][0]; followed by line of vshape[0][1], vshape[1][1]...
0
2016-08-16T15:52:58Z
38,979,433
<p>Use <code>zip</code>:</p> <pre><code>for r in zip(*vshape): print(''.join(r)) # 01110 # 10101 # 11011 </code></pre>
2
2016-08-16T15:56:39Z
[ "python", "python-2.7" ]
Print list of lists in Python in specific order
38,979,363
<p>I have this list:</p> <pre><code>vshape = [['0','1','1'],['1','0','1'],['1','1','0'],['1','0','1'],['0','1','1']] </code></pre> <p>I need to print out every item in specific order - one line of vshape[0][0], vshape[1][0], vshape[2][0], vshape[3][0], and vshape[4][0]; followed by line of vshape[0][1], vshape[1][1]...
0
2016-08-16T15:52:58Z
38,979,655
<p>perhaps easier to understand with transpose, using numpy.</p> <pre><code>for r in np.array(vshape).T: print(''.join(r)) </code></pre>
0
2016-08-16T16:07:41Z
[ "python", "python-2.7" ]
Print list of lists in Python in specific order
38,979,363
<p>I have this list:</p> <pre><code>vshape = [['0','1','1'],['1','0','1'],['1','1','0'],['1','0','1'],['0','1','1']] </code></pre> <p>I need to print out every item in specific order - one line of vshape[0][0], vshape[1][0], vshape[2][0], vshape[3][0], and vshape[4][0]; followed by line of vshape[0][1], vshape[1][1]...
0
2016-08-16T15:52:58Z
38,980,007
<pre><code>vshape = [['0','1','1'],['1','0','1'],['1','1','0'],['1','0','1'], ['0','1','1']] for i in range(3): for j in range(5): print (vshape[j][i], end=' ') print() </code></pre> <blockquote> <p><em>This is one of my most used methods to print out patterns. In this, I use two nested for loops.</e...
2
2016-08-16T16:28:05Z
[ "python", "python-2.7" ]
Trouble With Python Code
38,979,400
<p>I am taking the introduction to computer science class at Udacity and for one of the assignments I must write code that will take all the links from a webpage. Here is the code</p> <pre><code>def get_next_target(page): start_link = page.find('&lt;a href=') while True: if start_link == -1: ...
0
2016-08-16T15:54:31Z
38,979,661
<pre><code>def get_next_target(page, start=0): """ function find link in part of page """ start_link = page[start:].find('&lt;a href=') if start_link == -1: x, y = None, None return x, y start_quote = page.find('"', start_link) end_quote = page.find('"', start_quote + 1) url = pa...
0
2016-08-16T16:07:53Z
[ "python" ]
Dryscrape Form & Scraping Issue
38,979,513
<p>I am trying to submit a form and retrieve some data with dryscrape but when I execute the program, I get the error: </p> <pre><code>Traceback (most recent call last): File "easyjettest.py", line 22, in &lt;module&gt; originairport_field.set(originairport) AttributeError: 'NoneType' object has no attribute '...
1
2016-08-16T16:00:31Z
38,979,649
<p>Check in which line the error is taking place ,probably any of the variables <code>originairport_field</code>, <code>destinationairport_field</code>, <code>odate_field</code> ,<code>rdate_field</code>,<code>adults_field</code> is assigned none.</p> <p>By the way from where does the <code>session</code> in the lines...
1
2016-08-16T16:07:21Z
[ "python", "web-scraping" ]
why the result of blob detection does not change after the change of parameters?
38,979,551
<p>I got the program of blob detection in the following website: <a href="https://www.learnopencv.com/blob-detection-using-opencv-python-c/" rel="nofollow">https://www.learnopencv.com/blob-detection-using-opencv-python-c/</a></p> <p>It is quiet useful,but i found nothing change in the result after i change the paramet...
0
2016-08-16T16:02:40Z
38,982,057
<p>You change parameters but they are not used by the detector. Set them and then set up the detector:</p> <pre><code>import cv2 import numpy as np # Read image im = cv2.imread('blob.jpg', cv2.IMREAD_GRAYSCALE) # Setup SimpleBlobDetector parameters. params = cv2.SimpleBlobDetector_Params() # Change thresholds param...
0
2016-08-16T18:29:15Z
[ "python", "opencv", "blob" ]
count increase by number, not digits
38,979,600
<p>In this python function the file number increases by one when saving. It does it from filename1 to filename10 correctly and then jumps to 111, 1112, 11113 and so forth instead of continuing with filename11. Where does it go wrong?</p> <pre><code>for f in notepad.getFiles(): ...
0
2016-08-16T16:05:16Z
38,979,658
<p>The offending line is here:</p> <pre><code>filename = filename[:-1] + str(counter) </code></pre> <p>You trim off <strong>one</strong> character and add the counter. This works great for filenames when the counter is a single digit:</p> <pre><code>filename8 -&gt; filename + 9 filename9 -&gt; filename + 10 </code><...
5
2016-08-16T16:07:48Z
[ "python", "string" ]
Python - write x rows of csv file to json file
38,979,603
<p>I have a csv file, which I need to write to json files in rows of 1000. The csv file has around 9,000 rows, so ideally I'd like to end up with 9 separate json files of consecutive data.</p> <p>I know how to write a csv file to json - what I've been doing:</p> <pre><code>csvfile = open("C:\\Users\Me\Desktop\data\da...
1
2016-08-16T16:05:23Z
38,979,883
<p>This will read the file <code>data.csv</code> once and will create separate json files with id <code>data_1.json</code> through <code>data_9.json</code> since there are 9000 rows. </p> <p>Also as long as the number of rows in <code>data.csv</code> is multiple of 1000, it will create <code>number_of_rows/1000</code>...
-1
2016-08-16T16:20:55Z
[ "python", "json", "csv" ]
Python - write x rows of csv file to json file
38,979,603
<p>I have a csv file, which I need to write to json files in rows of 1000. The csv file has around 9,000 rows, so ideally I'd like to end up with 9 separate json files of consecutive data.</p> <p>I know how to write a csv file to json - what I've been doing:</p> <pre><code>csvfile = open("C:\\Users\Me\Desktop\data\da...
1
2016-08-16T16:05:23Z
38,980,017
<p>Read the whole CSV file into a list or rows, then write slices of length 1000 to JSON files.</p> <pre><code>import csv import json input_file = 'C:\\Users\\Me\\Desktop\\data\\data.csv' output_file_template = 'C:\\Users\\Me\\Desktop\\data\\data_{}.json' with open(input_file, 'r', encoding='utf8') as csvfile: r...
2
2016-08-16T16:28:23Z
[ "python", "json", "csv" ]
Python - write x rows of csv file to json file
38,979,603
<p>I have a csv file, which I need to write to json files in rows of 1000. The csv file has around 9,000 rows, so ideally I'd like to end up with 9 separate json files of consecutive data.</p> <p>I know how to write a csv file to json - what I've been doing:</p> <pre><code>csvfile = open("C:\\Users\Me\Desktop\data\da...
1
2016-08-16T16:05:23Z
38,980,557
<p>Instead of reading the whole CSV file, you can iterate (less memory usage).</p> <p>For instance, here is a simple iteration of the rows:</p> <pre><code>with open(input_file, 'r', encoding='utf8') as csvfile: reader = csv.DictReader(csvfile, delimiter=',') for row in reader: print(row) </code></pre>...
2
2016-08-16T16:58:42Z
[ "python", "json", "csv" ]
Python - write x rows of csv file to json file
38,979,603
<p>I have a csv file, which I need to write to json files in rows of 1000. The csv file has around 9,000 rows, so ideally I'd like to end up with 9 separate json files of consecutive data.</p> <p>I know how to write a csv file to json - what I've been doing:</p> <pre><code>csvfile = open("C:\\Users\Me\Desktop\data\da...
1
2016-08-16T16:05:23Z
38,985,568
<p>There is no reason to use a Dictreader, the regular <em>csv.reader</em> will do fine. You can also just use <em>itertool.islice</em> on the reader object to slice the data into <code>n</code> rows and dump each collection to a new file:</p> <pre><code>from itertools import islice, count import csv import json ...
0
2016-08-16T22:39:12Z
[ "python", "json", "csv" ]
python tkinter import portability
38,979,637
<p>I'm running the same very small python script from both my work computer at home and a server at work that that computer RDPs to. The server uses the company standard python 2 and I have been using python 3 at home. Recently I decided to use the same script to do the same job on both. Everything is the same and work...
0
2016-08-16T16:06:41Z
38,997,734
<p>The <code>2to3</code> program will perform (some, but not always perfect) translation of your program to Python 3. The trick is to write the code in such a way that your Python 2 <em>does</em> get successfully (and correctly) converted. </p> <p>I'd recommend you take a look at <a href="https://github.com/mitsuhiko/...
1
2016-08-17T13:15:20Z
[ "python", "tkinter" ]
python tkinter import portability
38,979,637
<p>I'm running the same very small python script from both my work computer at home and a server at work that that computer RDPs to. The server uses the company standard python 2 and I have been using python 3 at home. Recently I decided to use the same script to do the same job on both. Everything is the same and work...
0
2016-08-16T16:06:41Z
38,998,266
<p>Check the Python version and treat according to the case:</p> <pre><code>import sys if sys.version_info[0] &gt; 2: from tkinter import * else: from Tkinter import * </code></pre>
1
2016-08-17T13:37:57Z
[ "python", "tkinter" ]
python tkinter import portability
38,979,637
<p>I'm running the same very small python script from both my work computer at home and a server at work that that computer RDPs to. The server uses the company standard python 2 and I have been using python 3 at home. Recently I decided to use the same script to do the same job on both. Everything is the same and work...
0
2016-08-16T16:06:41Z
38,999,134
<p>or try importing both of them :-)</p> <pre><code>try: from tkinter import * except ImportError: from Tkinter import * </code></pre>
0
2016-08-17T14:13:16Z
[ "python", "tkinter" ]
python finding the 1's in a bitmask
38,979,660
<p>I have a number of nodes that can be grouped to respond to commands via a bitmask. For example: NodeA is in groups 1 and 5. When asked which groups it belongs to, it answers with 17 of which the binary equivalent is '0b10001'. A node in groups 2, 7 and 9 would tell me it belongs to group 322 ('0b101000010'). I nee...
3
2016-08-16T16:07:51Z
38,979,854
<p>Use bit operations (and loops!):</p> <pre><code>&gt;&gt;&gt; for i in range(16): ... if grp &amp; (1&lt;&lt;i): ... print('Group', i+1) </code></pre>
2
2016-08-16T16:18:35Z
[ "python", "bitmask" ]
python finding the 1's in a bitmask
38,979,660
<p>I have a number of nodes that can be grouped to respond to commands via a bitmask. For example: NodeA is in groups 1 and 5. When asked which groups it belongs to, it answers with 17 of which the binary equivalent is '0b10001'. A node in groups 2, 7 and 9 would tell me it belongs to group 322 ('0b101000010'). I nee...
3
2016-08-16T16:07:51Z
38,979,917
<p>You just need to use some basic <a href="https://wiki.python.org/moin/BitwiseOperators" rel="nofollow">bitwise operators</a>.</p> <p>Here's an example:</p> <pre><code>def findbits(num): for i in range(16): if num &amp; 1 &lt;&lt; i: print("Group {0}".format(i + 1)) </code></pre> <p>And the results:</p...
2
2016-08-16T16:23:13Z
[ "python", "bitmask" ]
Import Error When Running File
38,979,716
<p><a href="http://i.stack.imgur.com/DoOj7.png" rel="nofollow">enter image description here</a>When running a Python file I keep getting the following traceback error in IDLE:</p> <pre><code> File "D:\jmz study\project1\MINI PROJECT\sandhi-splitter-master\sandhi-splitter-master\sandhisplitter\tests\test_splitter.py...
-3
2016-08-16T16:10:59Z
38,981,665
<p>Looks like you've got a syntax error given that <a href="https://github.com/libindic/sandhi-splitter" rel="nofollow"><strong>this</strong></a> is the right version of the library you are using. </p> <p>Try using <code>from sandhisplitter import Sandhisplitter</code> instead.</p> <p>Here is an example straight from...
1
2016-08-16T18:06:58Z
[ "python" ]
Cast a very long string as an integer or Long Integer in PySpark
38,979,733
<p>I'm working with a string column which is 38 characters long and is actually numerical.</p> <p>for e.g. id = '678868938393937838947477478778877.....' ( 38 characters long). </p> <p>How do I cast it into a long integer ? I have tried cast function with IntegerType, LongType and DoubleType and when i try to show the...
0
2016-08-16T16:12:11Z
38,981,178
<p>Long story short you simply don't. Spark <code>DataFrame</code> is a JVM object which uses following types mapping:</p> <ul> <li><code>IntegerType</code> -> <code>Integer</code> with <code>MAX_VALUE</code> equal 2 ** 31 - 1</li> <li><code>LongType</code> -> <code>Long</code> with <code>MaxValue</code> equal 2 ** 6...
1
2016-08-16T17:37:21Z
[ "python", "python-2.7", "apache-spark", "pyspark" ]
Python: Excel to Web to PDF
38,979,791
<p>I'm new to programming and am searching for the best way to pull PDFs of a series of water bills from a city website. I have been able to open the webpage and been able to open an account using an account numbers from an excel list, however, I am having trouble <strong>creating a loop</strong> to run through all acc...
0
2016-08-16T16:14:56Z
38,983,419
<p>Couldn't find a nice way to download the PDF but here's everything but:</p> <pre><code> import openpyxl from selenium import webdriver workbook = openpyxl.load_workbook('WaterBills.xlsx') sheet = workbook.get_sheet_by_name('Sheet1') column_a = sheet.columns[0] accou...
1
2016-08-16T19:57:29Z
[ "python", "excel", "loops", "pdf" ]
How to upload multiple answers with image bytestring data?
38,979,810
<p>According to Consumer Surveys docs, the <code>questions[].images[].data</code> field takes a bytes datatype.</p> <p>I'm using Python 3 for implementation, but the API is giving errors like <code>Invalid ByteString</code> or bytes type <code>is not JSON serializable.</code></p> <p>I'm using the following code:</p> ...
1
2016-08-16T16:16:09Z
38,982,761
<p>You need to use web-safe/URL-safe encoding. Here's some documentation on doing this in Python: <a href="https://pymotw.com/2/base64/#url-safe-variations" rel="nofollow">https://pymotw.com/2/base64/#url-safe-variations</a></p> <p>In your case, this would look like</p> <pre><code>img_data = base64.urlsafe_b64encode(...
2
2016-08-16T19:13:09Z
[ "python", "google-surveys" ]
Avoid duplicate result Multithread Python
38,979,880
<p><br > I'm trying to make my actual crawler Multithread.<br > When I set the Multithread, several instance of the function will be started.</p> <p><strong>Exemple :</strong></p> <p>If my function I use <code>print range(5)</code> and I will have <code>1,1,2,2,3,3,4,4,5,5</code> if I have 2 Thread.</p> <p>How can c...
1
2016-08-16T16:20:33Z
38,980,193
<p>Have the page number be an argument to the <code>trade_spider</code> function. </p> <p>Call the function in each process with a different page number so that each thread gets a unique page.</p> <p>For example:</p> <pre><code>import multiprocessing def trade_spider(page): url = "http://stackoverflow.com/quest...
1
2016-08-16T16:37:53Z
[ "python", "multithreading" ]
Avoid duplicate result Multithread Python
38,979,880
<p><br > I'm trying to make my actual crawler Multithread.<br > When I set the Multithread, several instance of the function will be started.</p> <p><strong>Exemple :</strong></p> <p>If my function I use <code>print range(5)</code> and I will have <code>1,1,2,2,3,3,4,4,5,5</code> if I have 2 Thread.</p> <p>How can c...
1
2016-08-16T16:20:33Z
38,981,186
<p>Try this:</p> <pre><code>from multiprocessing import Process, Value import time max_pages = 100 shared_page = Value('i', 1) arg_list = (max_pages, shared_page) process_list = list() for x in range(2): spider_process = Process(target=trade_spider, args=arg_list) spider_process.daemon = True spider_proce...
1
2016-08-16T17:38:03Z
[ "python", "multithreading" ]
Django password and password confirmation validation
38,979,919
<p>I'm having a little trouble validating two fields (password and password confirmation) in the same form.</p> <p>The thing is that after validating password with a method I've created, when I try to validate password confirmation, I no longer have access to this variable, and <code>password = self.cleaned_data['pass...
1
2016-08-16T16:23:33Z
38,979,961
<p>You can test for multiple fields in the <code>clean()</code> method.</p> <p>Example:</p> <pre><code>def clean(self): cleaned_data = super(NewAccountForm, self).clean() password = cleaned_data.get('password') password_confirm = cleaned_data.get('password_confirm ') if password and password_confirm...
2
2016-08-16T16:25:22Z
[ "python", "django" ]
python encoding issue, searching tweets
38,979,928
<p>I have written the following code to crawl tweets with 'utf-8' encoding: </p> <pre><code>kws=[] f=codecs.open("keywords", encoding='utf-8') kws = f.readlines() f.close() print kws for kw in kws: timeline_endpoint ='https://api.twitter.com/1.1/search/tweets.json?q='+kw+'&amp;count=100&amp;lang=fr' p...
0
2016-08-16T16:24:03Z
38,980,285
<p>There may be latin-1 encoded string in some Twitter feeds. To deal with those, you need to decode them from latin-1 to unicode and then you encode it utf-8:</p> <pre><code>my_on_data(json.dumps(tweet.decode("latin-1").encode('utf-8'))) </code></pre>
-1
2016-08-16T16:43:11Z
[ "python", "encoding", "urllib", "tweepy" ]
python encoding issue, searching tweets
38,979,928
<p>I have written the following code to crawl tweets with 'utf-8' encoding: </p> <pre><code>kws=[] f=codecs.open("keywords", encoding='utf-8') kws = f.readlines() f.close() print kws for kw in kws: timeline_endpoint ='https://api.twitter.com/1.1/search/tweets.json?q='+kw+'&amp;count=100&amp;lang=fr' p...
0
2016-08-16T16:24:03Z
38,980,694
<p>Okay, here is the solution using a different search approach:</p> <pre><code>auth = tweepy.OAuthHandler("k1", "k2") auth.set_access_token("k3", "k4") api = tweepy.API(auth) for kw in kws: max_tweets = 10 searched_tweets = [status for status in tweepy.Cursor(api.search, q=kw.encode('utf-8'))...
0
2016-08-16T17:07:03Z
[ "python", "encoding", "urllib", "tweepy" ]
How to properly wrap a C library with Python CFFI
38,979,947
<p>I am trying to wrap a very simple C library containing only two .C source files: <em>dbc2dbf.c</em> and <em>blast.c</em></p> <p>I am doing the following (from the documentation):</p> <pre><code>import os from cffi import FFI blastbuilder = FFI() ffibuilder = FFI() with open(os.path.join(os.path.dirname(__file__), ...
1
2016-08-16T16:24:52Z
39,018,217
<p>Here is the solution (tested):</p> <pre><code>import os from cffi import FFI ffibuilder = FFI() PATH = os.path.dirname(__file__) with open(os.path.join(PATH, 'c-src/dbc2dbf.c'),'r') as f: ffibuilder.set_source("_readdbc", f.read(), libraries=["c"], ...
0
2016-08-18T12:27:18Z
[ "python", "c", "python-cffi" ]
python parsing json response
38,979,973
<p>I'm a newb with JSON and am trying to understand how to parse a JSON response. In the example below, I'd like to know how to retrieve the value of 'issueId':'executions':'id'? in the example below it is '8195'.....</p> <pre><code>r = requests.get(baseURL + getExecutionsForIssueId + id, auth=('user','pass')) data = ...
0
2016-08-16T16:26:14Z
38,980,085
<p>Your <code>JSON</code> object is just a dictionary in Python. Access the values you need like so:</p> <p><code>data['executions']</code> yields an array of similar dictionary objects, assuming your <code>JSON</code> response is typed as you intended. </p> <pre><code>executions = data['executions'] order_id = execu...
0
2016-08-16T16:32:27Z
[ "python", "json" ]
Implement bias neurons neural network
38,980,018
<p>I implemented bias units for my neural network with gradient descent. But I'm not 100% sure If I've implemented it the right way. Would be glade if you can quickly look through my code. Only the parts with </p> <blockquote> <p>if bias:</p> </blockquote> <p>are important.</p> <p>And my second question: Shouldn't...
0
2016-08-16T16:28:24Z
38,985,160
<p><strong>In relation with the derivatives...</strong></p> <p>If you are using the <code>tanh</code> activation function, i.e. <a href="https://en.wikipedia.org/wiki/Hyperbolic_function#Derivatives" rel="nofollow">the derivative is:</a> <code>y' = 1 - y^2</code>. The <code>tanh</code> is commonly used because it is z...
0
2016-08-16T22:00:03Z
[ "python", "neural-network", "backpropagation", "gradient-descent", "bias-neuron" ]
Looking for the equivalent of dictcursor in flaskext.mysql
38,980,044
<p>I've written a Python Flask app, and initially used MySQLdb to access MySQL. Later I've switched to flaskext.mysql for the same purposes, but now when I use this module I cannot see how to get a dictionary structured cursor.</p> <p>When I using the MySQLdb module I was using the following line to open a dictionary ...
1
2016-08-16T16:30:02Z
38,980,156
<p><a href="https://github.com/cyberdelia/flask-mysql/blob/master/flaskext/mysql.py#L58" rel="nofollow"><code>mysql.get_db()</code></a> would result into your "connection" object, you can do:</p> <pre><code>import MySQLdb as mdb cur = mysql.get_db().cursor(mdb.cursors.DictCursor) </code></pre> <p>Or, you can also se...
1
2016-08-16T16:36:17Z
[ "python", "mysql", "flask" ]
drop labels created by agg(['sum','count'])
38,980,138
<p>I have a df that can be reconstructed as pd.DataFrame(dict):</p> <pre><code> city d1 d2 d3 d4 date 2014-05-01 sfo 4.26 6.58 2.32 -4.87 2014-05-01 yyz 2.90 6.64 24.78 -50.55 2014-05-01 yvr 2.90 6.64 24.78 -50.55 2014-05-01 dfw 4.06 6.5...
1
2016-08-16T16:35:29Z
38,980,223
<pre><code>monthly_agg = monthly_agg.loc[:, pd.IndexSlice[:,'sum']] monthly_agg.columns = monthly_agg.columns.droplevel(1) monthly_agg Out: d1 d2 d3 d4 city date dfw 2014-05-31 4.06 6.54 2.40 -4.06 pdx 2014-05-31 9.96 6.66 30.35 64.24 sfo 2014-0...
3
2016-08-16T16:39:42Z
[ "python", "pandas", "aggregate" ]
Set Seaborn PairGrid x-axis with 2 different value ranges
38,980,179
<p>[The resolution is described below.]</p> <p>I'm trying to create a PairGrid. The X-axis has at least 2 different value ranges, although even when 'cvar' below is plotted by itself the x-axis overwrites itself. </p> <p>My question: is there a way to tilt the x-axis labels to be vertical or have fewer x-axis labels ...
0
2016-08-16T16:37:26Z
39,020,838
<p>I finally figured it out. I added "plt.xticks( rotation= -45 )" to the original code above. More can be fund on the MatPlotLib site <a href="http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html?highlight=xticks%20rotation" rel="nofollow">here</a>. </p>
0
2016-08-18T14:28:32Z
[ "python", "seaborn" ]
Python exception while parsing json to avro schema: avro.schema.SchemaParseException: No "type" property
38,980,367
<p>I read a record from a file and convert it into a dictionary. Later I convert that dictionary to json format so that I could further try to convert it to an avro schema. </p> <p>Here is my code snippet so far:-</p> <pre><code>import json from avro import schema, datafile, io def json_to_avro(): fo = open(...
0
2016-08-16T16:47:15Z
38,995,327
<p>This happens because the parameter in <code>schema.parse()</code> function has to be avro-schema (not a record itself) like here (<a href="https://avro.apache.org/docs/1.8.0/gettingstartedpython.html" rel="nofollow">https://avro.apache.org/docs/1.8.0/gettingstartedpython.html</a>):</p> <pre><code>schema = avro.sche...
1
2016-08-17T11:25:30Z
[ "python", "json", "dictionary", "avro" ]
Tkinter python append lines in separate file
38,980,446
<p>I have no formal programming experience so please forgive my lack of terminology and program structure. Stackoverflow has been a tremendous help. This is my first question so please be gentle.</p> <p>I have been tasked with writing a GUI. As of now, I works well and I have over 3500 lines of code and multiple files...
0
2016-08-16T16:51:43Z
38,980,536
<p>You need to make one small change: Open the file with the 'a' flag, for append:</p> <pre><code> f = open('c:\Python\code.txt', 'a') </code></pre>
1
2016-08-16T16:57:11Z
[ "python", "tkinter" ]
Choosing only non-zeros from a long list of numbers in text file
38,980,459
<p>I have a text file with a long list of numbers. I would like to choose only the non-zeros and make another text file. </p> <p>This is a portion of the input file:</p> <pre><code>0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000E+00 0.00000...
-2
2016-08-16T16:52:29Z
38,982,908
<p>You're using regex again where you don't need to. You're also doing something exceedingly bizarre where you're using <code>islice</code> on the file. That's also unnecessary. You could just do this:</p> <pre><code>import io file = io.StringIO('''...
0
2016-08-16T19:23:05Z
[ "python", "list", "numbers" ]
How can I get virtualenv to work?
38,980,505
<p>I have this weird error:</p> <pre class="lang-none prettyprint-override"><code>Path:\To\My\Command&gt;virtualenv . Fatal error in launcher: Unable to create process using '"D:\Python27\python.exe" "F:\Python27\Scripts\virtualenv.exe" .' </code></pre> <p>Thing is, I don't have a <code>D:\Python27\python.exe</...
0
2016-08-16T16:55:23Z
38,980,572
<p>Sounds like your environmental variable path is messed up. Try setting it up again for F:\, you can find directions here: <a href="http://stackoverflow.com/questions/6318156/adding-python-path-on-windows-7">Adding Python Path on Windows 7</a></p>
0
2016-08-16T16:59:27Z
[ "python", "windows", "environment-variables", "virtualenv" ]
Moving desired row to the top of pandas Data Frame
38,980,507
<p>In <code>pandas</code>, how can I copy or move a row to the top of the Data Frame without creating a copy of the Data Frame?</p> <p>For example, I managed to do almost what I want with the code below, but I have the impression that there might be a better way to accomplish this:</p> <pre><code>import pandas as pd ...
1
2016-08-16T16:55:25Z
38,980,670
<p>Okay, I think I came up with a solution. By all means, please feel free to add your own answer if you think yours is better:</p> <pre><code>import numpy as np df.ix[3] = np.nan df Probe Sequence 0 Test1 AATGCGT 1 Test2 TGCGTAA 2 Test3 ATGCATG 3 NaN NaN df = df.shift(1) Probe Sequence 0 N...
0
2016-08-16T17:05:37Z
[ "python", "pandas" ]
Moving desired row to the top of pandas Data Frame
38,980,507
<p>In <code>pandas</code>, how can I copy or move a row to the top of the Data Frame without creating a copy of the Data Frame?</p> <p>For example, I managed to do almost what I want with the code below, but I have the impression that there might be a better way to accomplish this:</p> <pre><code>import pandas as pd ...
1
2016-08-16T16:55:25Z
38,987,227
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>pandas.concat</code></a>:</p> <pre><code>pd.concat([df.iloc[[n],:], df.drop(n, axis=0)], axis=0) </code></pre>
2
2016-08-17T02:32:44Z
[ "python", "pandas" ]
Moving desired row to the top of pandas Data Frame
38,980,507
<p>In <code>pandas</code>, how can I copy or move a row to the top of the Data Frame without creating a copy of the Data Frame?</p> <p>For example, I managed to do almost what I want with the code below, but I have the impression that there might be a better way to accomplish this:</p> <pre><code>import pandas as pd ...
1
2016-08-16T16:55:25Z
38,988,241
<p>Try this, You are not making a copy of dataframe,:</p> <pre><code>df["new"] = range(1,len(df)+1) Probe Sequence new 0 Test1 AATGCGT 1 1 Test2 TGCGTAA 2 2 Test3 ATGCATG 3 df.ix[2,'new'] = 0 df.sort_values("new").drop('new', axis=1) Probe Sequence 2 Test3 ATGCATG 0 Test1 AATGCGT 1 Test2...
1
2016-08-17T04:42:16Z
[ "python", "pandas" ]
Python Eve fails to run on newly created droplet
38,980,541
<pre><code>Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import eve &gt;&gt;&gt; from eve import Eve &gt;&gt;&gt; eve &lt;module 'eve' from '/usr/local/lib/python2.7/dist-packages/eve/__init__.pyc'&gt; &gt;&gt;&gt; app = Eve() Traceback (most recent call last): File "&lt;stdin&gt...
1
2016-08-16T16:57:24Z
38,994,674
<p>You need to have a <code>settings.py</code> file on the same directory as your application, or you need to pass the path to <code>settings.py</code> with key <code>settings</code> in you app initialization. Check the <a href="http://python-eve.org/quickstart.html#a-minimal-application" rel="nofollow">quickstart</a> ...
1
2016-08-17T10:55:32Z
[ "python", "python-2.7", "digital-ocean", "eve" ]
What does Random Forest do with unseen data?
38,980,544
<p>When I built my random forest model using scikit learn in python, I set a condition (where clause in sql query) so that the training data only contain values whose value is greater than 0.</p> <p>I am curious to know how random forest handles test data whose value is less than 0, which the random forest model has n...
0
2016-08-16T16:57:42Z
38,980,686
<p>They will be treated in the same manner as the minimal value already encountered in the training set. RF is just a bunch of voting decision trees, and (basic) DTs can only form decisions in form of "if feature X is > then T go left, otherwise go right". Consequently, if you fit it to data which, for a given feature,...
0
2016-08-16T17:06:31Z
[ "python", "machine-learning", "scikit-learn", "random-forest", "scikits" ]
Django: Dynamic "table of contents" based on HTML tags
38,980,558
<p>I have a model with a <code>TextField</code> that users can populate with HTML. Now I want Django to render a dynamic "Table Of Contents", so that when a <code>&lt;h&gt;</code> tag is used, django automatically adds that to a list. Bonus points if a nested list is also possible.</p> <p>I've thought about using incl...
0
2016-08-16T16:58:47Z
39,007,699
<p>I have never done this exactly...but here is how I would start off.</p> <h3>Get the HTML</h3> <p>First things first - get the user to add the HTML. Possibly install tinyMCE, use tinyMCE's HTML field. The user can copy and paste HTML or add HTML content using tinyMCE's WYSIWUG.</p> <h3>Generate a DOM object</h3> ...
0
2016-08-17T23:23:55Z
[ "python", "django", "python-3.x" ]
Numpy convert list of 3D variable size volumes to 4D array
38,980,582
<p>I'm working on a neural network where I am augmenting data via rotation and varying the size of each input volume. </p> <p>Let me back up, the input to the network is a 3D volume. I generate variable size 3D volumes, and then pad each volume with zero's such that the input volume is constant. Check <a href="http://...
0
2016-08-16T17:00:01Z
38,981,230
<p>As I understood this part</p> <pre><code>k = 0 for z in range(z_min, z_max): l = 0 for x in range(x_min, x_max): m = 0 for y in range(y_min, y_max): if j == 0: #input volume try: temp_volume[k][l][m] = input_matrix[z][x][y] ...
1
2016-08-16T17:40:36Z
[ "python", "arrays", "numpy", "3d", "4d" ]
Simple calculation function not working
38,980,604
<p>I have the following code but I cannot get it to work:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import pandas as pd def test_calc(date, price, performance): test = pd.DataFrame(columns=('date'), index=('date')) test['date'] = date test['new_value'] = price * (1 + performance) ...
1
2016-08-16T17:01:24Z
38,980,723
<p>Use <code>list</code> at <code>pd.DataFrame(columns=[], index=[])</code></p> <pre><code>def test_calc(date, price, performance): test = pd.DataFrame(columns=['date'], index=['date']) test['date'] = date test['new_value'] = price * (1 + performance) return(test) </code></pre>
1
2016-08-16T17:08:40Z
[ "python", "pandas" ]
Export and Download a list to csv file using Python
38,980,610
<p>I have a list:</p> <pre><code>lista.append(rede) </code></pre> <p>When I print it , is showing:</p> <pre><code>[{'valor': Decimal('9000.00'), 'mes': 'Julho', 'nome': 'ALFANDEGA 1'}, {'valor': Decimal('12000.00'), 'mes': 'Julho', 'nome': 'AMAZONAS SHOPPING 1'}, {'valor': Decimal('600.00'), 'mes': 'Agosto', 'nome':...
-3
2016-08-16T17:01:40Z
38,980,878
<p>You can use this code to transform your data to csv : </p> <pre><code>def Decimal(value): #quick and dirty deal with your Decimal thing in the json return value data = [{'valor': Decimal('9000.00'), 'mes': 'Julho', 'nome': 'ALFANDEGA 1'}, {'valor': Decimal('12000.00'), 'mes': 'Julho', 'nome': 'AMAZONAS SHO...
0
2016-08-16T17:18:21Z
[ "python" ]
Pandas setting multi-index on columns
38,980,714
<p>If I have a simple dataframe:</p> <pre><code>print(a) one two three 0 A 1 a 1 A 2 b 2 B 1 c 3 B 2 d 4 C 1 e 5 C 2 f </code></pre> <p>I can easily create a multi-index on the rows by issuing:</p> <pre><code>a.set_index(['one', 'two']) three one two...
3
2016-08-16T17:08:06Z
38,981,203
<p>I think the short answer is <strong>NO</strong>. To have multi-index columns, the dataframe should have two (or more) rows to be converted into headers (like columns for multi-index rows). If you have this kind of dataframe, creating multi-index header is not so difficult. It can be done in a very long line of code,...
-1
2016-08-16T17:39:14Z
[ "python", "pandas", "dataframe" ]
Pandas setting multi-index on columns
38,980,714
<p>If I have a simple dataframe:</p> <pre><code>print(a) one two three 0 A 1 a 1 A 2 b 2 B 1 c 3 B 2 d 4 C 1 e 5 C 2 f </code></pre> <p>I can easily create a multi-index on the rows by issuing:</p> <pre><code>a.set_index(['one', 'two']) three one two...
3
2016-08-16T17:08:06Z
38,981,251
<p>Yes! It's called transposition.</p> <pre><code>a.set_index(['one', 'two']).T </code></pre> <p><a href="http://i.stack.imgur.com/S1jTq.png" rel="nofollow"><img src="http://i.stack.imgur.com/S1jTq.png" alt="enter image description here"></a></p> <hr> <p>Let's borrow from @ragesz's post because they used a much be...
1
2016-08-16T17:41:36Z
[ "python", "pandas", "dataframe" ]
Pandas setting multi-index on columns
38,980,714
<p>If I have a simple dataframe:</p> <pre><code>print(a) one two three 0 A 1 a 1 A 2 b 2 B 1 c 3 B 2 d 4 C 1 e 5 C 2 f </code></pre> <p>I can easily create a multi-index on the rows by issuing:</p> <pre><code>a.set_index(['one', 'two']) three one two...
3
2016-08-16T17:08:06Z
38,982,066
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> followed by a series of manipulations on the dataframe to get the desired form:</p> <pre><code>df_pivot = pd.pivot_table(df, index=['one', 'two'], values='three', aggfunc...
1
2016-08-16T18:29:40Z
[ "python", "pandas", "dataframe" ]
Python - input floating point paramater list
38,980,736
<p>I'm getting floating point parameters from user in a script and wondering if there is a better/effecient way including an option like if user only supplies one parameter (or no at all), is there any way that i default the remaining two as 0.0? And may be some better way to store in file</p> <pre><code>#inside a loo...
0
2016-08-16T17:09:23Z
38,980,810
<p>Updated to address index out of range error:</p> <pre><code># use python ternary operator to set default value # index goes out of range #c = x[2] if x[2] is not None else 0 # use array length instead b = x[1] if len(x) &gt;= 2 else 0 c = x[2] if len(x) &gt;= 3 else 0 file=open(inputFile, 'a+') # string concatenat...
2
2016-08-16T17:14:49Z
[ "python", "file", "floating-point" ]
Python - input floating point paramater list
38,980,736
<p>I'm getting floating point parameters from user in a script and wondering if there is a better/effecient way including an option like if user only supplies one parameter (or no at all), is there any way that i default the remaining two as 0.0? And may be some better way to store in file</p> <pre><code>#inside a loo...
0
2016-08-16T17:09:23Z
38,980,827
<p>You could check the length of the list returned by line.split(' ') to see how many you got, and go from there. Or you could check if an entry in the list is None before assigning it.</p> <p>For writing to files, the best thing to do is to set the structure of your data and then call write only once, as that is what...
1
2016-08-16T17:15:34Z
[ "python", "file", "floating-point" ]
Python - input floating point paramater list
38,980,736
<p>I'm getting floating point parameters from user in a script and wondering if there is a better/effecient way including an option like if user only supplies one parameter (or no at all), is there any way that i default the remaining two as 0.0? And may be some better way to store in file</p> <pre><code>#inside a loo...
0
2016-08-16T17:09:23Z
38,980,911
<p>Why don't you use a list to hold an arbitrary number of variables?</p> <pre><code>floats = [float(var) if var else 0. for var in raw_input("Enter three parm values: ").split(' ')] with open(inputFile, 'a+') as f: f.write(name + '\t' + ' '.join(str(f) for f in floats) + '\n') </code></pre> <p>If you ...
3
2016-08-16T17:20:25Z
[ "python", "file", "floating-point" ]
Python - input floating point paramater list
38,980,736
<p>I'm getting floating point parameters from user in a script and wondering if there is a better/effecient way including an option like if user only supplies one parameter (or no at all), is there any way that i default the remaining two as 0.0? And may be some better way to store in file</p> <pre><code>#inside a loo...
0
2016-08-16T17:09:23Z
38,980,970
<pre><code>#use length of list for checking the input and continue with your operation line = raw_input("Enter three parm values: ") x=line.split(' ') a=b=c=0 fa=fb=fc=0.0 listLen = len(x) if(listLen == 3): a, b, c = x[0], x[1], x[2] elif(listLen == 2): a, b = x[0], x[1] elif(listLen == 1): a = x[0] </code...
1
2016-08-16T17:24:44Z
[ "python", "file", "floating-point" ]
Python Matplotlib FuncAnimation.save() only saves 100 frames
38,980,794
<p>I am trying to save an animation I've created with the FuncAnimation class in Matplotlib. My animation is more complicated, but I get the same error when I try to save the simple example given <a href="http://stackoverflow.com/questions/16732379/stop-start-pause-in-python-matplotlib-animation">here</a>.</p> <pre><c...
0
2016-08-16T17:14:00Z
38,988,092
<pre><code>ani = animation.FuncAnimation(fig, simPoints, simData, blit=False, interval=10, repeat=True, save_count=200) </code></pre> <p>will solve the ploblem.</p> <p>Internally, <code>save</code> only saves a fixed number of frames. If you pass in a fixed length sequence or a number...
2
2016-08-17T04:23:22Z
[ "python", "animation", "matplotlib" ]
Python External Classes
38,980,813
<p>It looks simple, but I could not find a solution.</p> <p>I display the problem below with the simplest example I could come up with.</p> <p>(My classes are quiet more complex ;) )</p> <p><strong>file A.py</strong></p> <pre><code>import os, sys import B from B import * class _A(): def __init__(self,someVars):...
0
2016-08-16T17:14:55Z
38,981,256
<p>There is no need to first <code>import X</code>, then <code>from X import Y</code>. If you need Y (even if <code>Y</code> is <code>*</code>) do just <code>from X import Y</code>. This might be the cause of 2 times execution.</p> <p>Also why have cyclic dependencies between modules <code>A -&gt; B, B -&gt; A</code>?...
0
2016-08-16T17:42:10Z
[ "python", "class", "external", "python-module" ]
Python External Classes
38,980,813
<p>It looks simple, but I could not find a solution.</p> <p>I display the problem below with the simplest example I could come up with.</p> <p>(My classes are quiet more complex ;) )</p> <p><strong>file A.py</strong></p> <pre><code>import os, sys import B from B import * class _A(): def __init__(self,someVars):...
0
2016-08-16T17:14:55Z
38,981,584
<p>Because of cyclic dependency you are facing the import error, you can continue your work as: </p> <p><em>File A.py:</em></p> <pre><code>import os, sys #Below two import lines does cyclic dependency between file A and B which is wrong and will give import error, #commenting below two lines will resolve your import...
0
2016-08-16T18:02:07Z
[ "python", "class", "external", "python-module" ]
Sharing code between python files
38,980,899
<p>Lets say I have the following files:</p> <pre><code>-- classes.py -- main.py -- commands.py -- output.py </code></pre> <p><code>main.py</code> is the master file which uses the code from <code>classes</code>, <code>commands</code>, and <code>output</code>. <code>commands</code> takes objects defined in <code>class...
2
2016-08-16T17:19:49Z
38,980,990
<p>You have to import them to any file that will be using them, otherwise it will not work. That is because each file is a module, and each module has its own scope.</p>
-2
2016-08-16T17:25:44Z
[ "python", "python-3.x", "python-import" ]
Sharing code between python files
38,980,899
<p>Lets say I have the following files:</p> <pre><code>-- classes.py -- main.py -- commands.py -- output.py </code></pre> <p><code>main.py</code> is the master file which uses the code from <code>classes</code>, <code>commands</code>, and <code>output</code>. <code>commands</code> takes objects defined in <code>class...
2
2016-08-16T17:19:49Z
38,983,916
<blockquote> <p>The question: do I need to import each of these modules in each of the files that depend on them? i.e.: do I need to import output in both classes, commands, and main?</p> </blockquote> <p>Yes, this is the way to go.</p> <blockquote> <p>Or would the fact that classes, output, and commands are ...
0
2016-08-16T20:29:31Z
[ "python", "python-3.x", "python-import" ]
Analyzing data from continuous input stream (recording) in Python, multiprocessing?
38,980,940
<p>I am analyzing data coming from recording with my microphone in real-time. So far I have been doing this in a linear fashion:</p> <ul> <li>Record one second (takes 1s)</li> <li>Analyze the data (takes for example 50 ms)</li> <li>Record one second</li> <li>Analyze the data</li> </ul> <p>And so forth. This obviously...
0
2016-08-16T17:22:50Z
38,981,468
<p>Simple producer/consumer implementation. </p> <p>While it's true moving data back and forth induces overhead and increases memory use, as long as the same data is not needed by more than one process that overhead is minimal. Try it and find out :) Can adjust memory footprint by changing the queue and pool size numb...
1
2016-08-16T17:55:58Z
[ "python", "multiprocessing", "audio-recording" ]
Multiple URLs in text file - BeautifulSoup Scraping
38,981,017
<p>I have a text file <code>urls.txt</code> in the same directory as my <code>script.py</code></p> <p><code>urls.txt</code> has a list of multiple urls, one per line. </p> <p>I am attempting to scrape all the urls in one shot and pull out the contents of a particular <code>div</code> </p> <p>This <code>div</code> oc...
-2
2016-08-16T17:26:58Z
38,981,080
<p>Seems like a small identation error: Look at this block:</p> <pre><code>for url in urls: site = urlopen(url) soup = BeautifulSoup(site, "lxml") for item in soup.find_all("div", {"class": "vm-product-descr-container-1"}): print item.text </code></pre> <p>Change it to this one:</p> <pre><code>for...
0
2016-08-16T17:30:46Z
[ "python", "beautifulsoup" ]
How do I get the dot product but without the summation
38,981,194
<p>consider array's <code>a</code> and <code>b</code></p> <pre><code>a = np.array([ [-1, 1, 5], [-2, 3, 0] ]) b = np.array([ [1, 1, 0], [0, 2, 3], ]) </code></pre> <p>Looking at</p> <pre><code>d = a.T.dot(b) d array([[-1, -5, -6], [ 1, 7, 9], [ 5, 5, 0]]) </...
4
2016-08-16T17:38:29Z
38,981,589
<p>Here's one way:</p> <pre><code>In [219]: a Out[219]: array([[-1, 1, 5], [-2, 3, 0]]) In [220]: b Out[220]: array([[1, 1, 0], [0, 2, 3]]) In [221]: a.T[:,None,:] * b.T[None,:,:] Out[221]: array([[[-1, 0], [-1, -4], [ 0, -6]], [[ 1, 0], [ 1, 6], [ 0, ...
6
2016-08-16T18:02:34Z
[ "python", "numpy" ]