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
Replace currency symbol by word in Python
38,229,011
<p>I have a file of about 50000 tweets and I want to replace all the currency symbols by words so that <code>$10</code> becomes <code>10 dollars.</code></p> <p>How can I do that in Python?</p> <p>I can find the symbols using a regex: <code>[$][0-9]+</code>. I am not sure how to replace that by words and and also int...
-1
2016-07-06T16:26:45Z
38,229,127
<p><code>re.sub(..)</code> is your friend.</p> <pre><code>&gt;&gt;&gt; re.sub(r"\$(\d+)", r"\1 dollars", "$10") '10 dollars' </code></pre>
4
2016-07-06T16:32:18Z
[ "python", "regex", "python-2.7" ]
Trying to break a while loop serial readline () function in python 2.7 tkinter using a Button. Reading data from aruduino Mega
38,229,013
<p>I am trying break a while loop that prints the serial readline() function in my program. I have a quit button set up but this freezes the program when I press it. I am looking for a way to make this QUIT button function properly when I press it. Any help would be greatly appreciated. </p> <pre><code>import serial ...
1
2016-07-06T16:26:51Z
38,229,597
<p>You need to modify your <code>createWidgets()</code> method this way:</p> <pre><code> def createWidgets(self): self.QUIT = Button(self, text='QUIT', bg='red', command=quit) self.QUIT.pack(side=LEFT) self.DATA_READ = Button(self, text='Data Read', command=self.feed_data) self.DATA_...
0
2016-07-06T16:59:48Z
[ "python", "python-2.7", "tkinter", "arduino", "serial-port" ]
Understanding this line: list_of_tuples = [(x,y) for x, y, label in data_one]
38,229,059
<p>As you've already understood I'm a beginner and am trying to understand what the "Pythonic way" of writing this function is built on. I know that other threads might include a partial answer to this, but I don't know what to look for since I don't understand what is happening here.</p> <p>This line is a code that m...
10
2016-07-06T16:29:11Z
38,229,283
<p>This is called a list comprehension. It's similar to a loop and can often accomplish the same task, but will generate a list with the results. The general format is <code>[operation for variable in iterable]</code>. For example,</p> <p><code>[x**2 for x in range(4)]</code> would result in <code>[0, 1, 4, 9]</code>....
3
2016-07-06T16:41:46Z
[ "python", "numpy", "list-comprehension" ]
Understanding this line: list_of_tuples = [(x,y) for x, y, label in data_one]
38,229,059
<p>As you've already understood I'm a beginner and am trying to understand what the "Pythonic way" of writing this function is built on. I know that other threads might include a partial answer to this, but I don't know what to look for since I don't understand what is happening here.</p> <p>This line is a code that m...
10
2016-07-06T16:29:11Z
38,229,389
<p>Both ways are correct and work. You could probably relate the first way with the way things are done in C and other languages. This is, you basically run a for loop to go through all of the values and then append it to your list of tuples. </p> <p>The second way is more pythonic but does the same. If you take a loo...
8
2016-07-06T16:47:46Z
[ "python", "numpy", "list-comprehension" ]
Understanding this line: list_of_tuples = [(x,y) for x, y, label in data_one]
38,229,059
<p>As you've already understood I'm a beginner and am trying to understand what the "Pythonic way" of writing this function is built on. I know that other threads might include a partial answer to this, but I don't know what to look for since I don't understand what is happening here.</p> <p>This line is a code that m...
10
2016-07-06T16:29:11Z
38,229,435
<pre><code>list_of_tuples = [(x,y) for x, y, label in data_one] </code></pre> <p><code>(x, y)</code> is a <a href="http://www.tutorialspoint.com/python/python_tuples.htm"><code>tuple</code></a> &lt;-- linked tutorial.</p> <p>This is a list <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk">comprehe...
13
2016-07-06T16:50:54Z
[ "python", "numpy", "list-comprehension" ]
Understanding this line: list_of_tuples = [(x,y) for x, y, label in data_one]
38,229,059
<p>As you've already understood I'm a beginner and am trying to understand what the "Pythonic way" of writing this function is built on. I know that other threads might include a partial answer to this, but I don't know what to look for since I don't understand what is happening here.</p> <p>This line is a code that m...
10
2016-07-06T16:29:11Z
38,229,488
<p>The action is essentially the same. In newer Python interpreters the scope of the variables in the list comprehension is narrower (<code>x</code> can't be seen outside the comprehension).</p> <pre><code>list_of_tuples = [] for x, y, label in data_one: list_of_tuples.append( (x,y) ) list_of_tuples = [(x,y) for...
4
2016-07-06T16:53:47Z
[ "python", "numpy", "list-comprehension" ]
Understanding this line: list_of_tuples = [(x,y) for x, y, label in data_one]
38,229,059
<p>As you've already understood I'm a beginner and am trying to understand what the "Pythonic way" of writing this function is built on. I know that other threads might include a partial answer to this, but I don't know what to look for since I don't understand what is happening here.</p> <p>This line is a code that m...
10
2016-07-06T16:29:11Z
38,229,700
<p>The "improved" version uses a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>. This makes the code <a href="https://en.wikipedia.org/wiki/Declarative_programming" rel="nofollow">declarative</a> (describing what you want) rather than <a href="...
4
2016-07-06T17:05:37Z
[ "python", "numpy", "list-comprehension" ]
How to evaluate beta distribution only once in python?
38,229,126
<p>In a simulation that I am running I have to draw many many values from the same beta distribution. Currently, I am using</p> <pre><code>import random ... for i in range(n_Aa): h = random.betavariate(a, b) // With some values for 'a' and 'b' ... </code></pre> <p>This code, however, is very slow. I think it is...
0
2016-07-06T16:32:18Z
38,229,209
<p>You can try numpy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html" rel="nofollow">random.beta</a>. It seems to be a lot faster:</p> <pre><code>import random import numpy as np n = 10**6 %timeit [random.betavariate(2, 3) for _ in range(n)] 1 loop, best of 3: 3.83 s per loop %t...
2
2016-07-06T16:37:23Z
[ "python", "random", "beta-distribution" ]
How to scrape PHP Ajax using Python?
38,229,200
<p>I'm a beginner with python, I'm trying build a python program that will scrape product descriptions from <a href="http://turnpikeshoes.com/shop/TCF00003" rel="nofollow">http://turnpikeshoes.com/shop/TCF00003</a>. Python has many libraries and I'm sure many approaches to achieving my goal. I've done a few successful ...
2
2016-07-06T16:36:46Z
38,229,470
<p>You should try selenium in this case if you want to scrape javascript content:</p> <pre><code>from selenium import webdriver import time driver = webdriver.PhantomJS() driver.get("http://turnpikeshoes.com/shop/TCF00003") time.sleep(5) LongDsc = driver.find_element_by_class_name("productLongDescription").text pri...
1
2016-07-06T16:52:45Z
[ "python", "ajax", "screen-scraping" ]
How to scrape PHP Ajax using Python?
38,229,200
<p>I'm a beginner with python, I'm trying build a python program that will scrape product descriptions from <a href="http://turnpikeshoes.com/shop/TCF00003" rel="nofollow">http://turnpikeshoes.com/shop/TCF00003</a>. Python has many libraries and I'm sure many approaches to achieving my goal. I've done a few successful ...
2
2016-07-06T16:36:46Z
38,230,502
<p>The shop performs a POST request to itself during loading with the URL as parameter in the form data. Here is a little script using <em>requests.Session</em> which first opens the shop and then sends the POST request to get the product information. It simulates the steps a browser would do - saving the cookies from ...
0
2016-07-06T17:48:15Z
[ "python", "ajax", "screen-scraping" ]
How to scrape PHP Ajax using Python?
38,229,200
<p>I'm a beginner with python, I'm trying build a python program that will scrape product descriptions from <a href="http://turnpikeshoes.com/shop/TCF00003" rel="nofollow">http://turnpikeshoes.com/shop/TCF00003</a>. Python has many libraries and I'm sure many approaches to achieving my goal. I've done a few successful ...
2
2016-07-06T16:36:46Z
38,733,319
<p>This one worked for me.</p> <pre><code>from selenium import webdriver ff = webdriver.PhantomJS() ff.get(url) ff.find_element_by_xpath("//span[@itemprop='price']").get_attribute("content") </code></pre> <p>Thanks!</p>
0
2016-08-03T02:19:08Z
[ "python", "ajax", "screen-scraping" ]
How to implement decorator on object oriented program in python
38,229,255
<p>Have a question on decorators. I am trying to understand the decorator concept in python but got stuck at the use of decorators in classes. <strong>with_class.py</strong></p> <pre><code>class decorate: def __init__(self,f): self.f = f def __call__(self) self.f() @decorate def foo():...
0
2016-07-06T16:40:04Z
38,229,499
<p>What</p> <pre><code>@decorate def foo(): print "inside foo" </code></pre> <p>does is equivalent to</p> <pre><code>def foo(): print "inside foo" foo = decorate(foo) </code></pre> <p>So <code>foo</code> is the name that the decorated function (an object of class <code>decorate</code>, really) is bound to ...
2
2016-07-06T16:54:20Z
[ "python", "python-2.7" ]
How to sum time in a dataframe
38,229,357
<p>I have a dataframe of time data in the format</p> <pre><code>hh:mm:ss hh:mm:ss </code></pre> <p>(type string)</p> <p>I need to be able to sum the values (to acquire total time) in a few of the columns. I'm wondering if anyone has any recommendations on the best way to do this and get the sum in the same format.<...
2
2016-07-06T16:46:11Z
38,229,585
<p>You can do this using timedelta:</p> <pre><code>import pandas as pd import datetime data = {'t1':['01:15:31', '00:47:15'], 't2':['01:13:02', '00:51:33'] } def make_delta(entry): h, m, s = entry.split(':') return datetime.timedelta(hours=int(h), minutes=int(m)...
2
2016-07-06T16:59:20Z
[ "python", "datetime", "pandas" ]
How to sum time in a dataframe
38,229,357
<p>I have a dataframe of time data in the format</p> <pre><code>hh:mm:ss hh:mm:ss </code></pre> <p>(type string)</p> <p>I need to be able to sum the values (to acquire total time) in a few of the columns. I'm wondering if anyone has any recommendations on the best way to do this and get the sum in the same format.<...
2
2016-07-06T16:46:11Z
38,229,627
<p>Maybe try using <code>datetime.timedelta</code>?</p> <pre><code>import re from datetime import timedelta _TIME_RE = re.compile(r'(\d+):(\d+):(\d+)') def parse_timedelta(line): # Invalid lines (such as blank) will be considered 0 seconds m = _TIME_RE.match(line) if m is None: return timedelta()...
1
2016-07-06T17:01:37Z
[ "python", "datetime", "pandas" ]
How to sum time in a dataframe
38,229,357
<p>I have a dataframe of time data in the format</p> <pre><code>hh:mm:ss hh:mm:ss </code></pre> <p>(type string)</p> <p>I need to be able to sum the values (to acquire total time) in a few of the columns. I'm wondering if anyone has any recommendations on the best way to do this and get the sum in the same format.<...
2
2016-07-06T16:46:11Z
38,229,878
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow"><code>to_timedelta</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sum.html" rel="nofollow"><code>sum</code></a>:</p> <pre><code>import pandas as pd df = ...
3
2016-07-06T17:14:45Z
[ "python", "datetime", "pandas" ]
Can not apply flatMap on RDD
38,229,383
<p>In PySpark, for each element of an RDD, I'm trying to get an array of <code>Row</code> elements.Then I want to convert the result into a DataFrame.</p> <p>I have the following code:</p> <pre><code> simulation = housesDF.flatMap(lambda house: goThroughAB(jobId, house)) print simulation.toDF().show() </code></pre...
-1
2016-07-06T16:47:17Z
38,231,019
<p>First, you are not printing on the driver but on Spark executors. As you know, the executors are remote processes which execute Spark tasks in parallel. They do print that line but on their own console. You don't know which executor runs a certain partition and you should never rely on print statements in a distribu...
0
2016-07-06T18:17:42Z
[ "python", "apache-spark", "pyspark" ]
Can not apply flatMap on RDD
38,229,383
<p>In PySpark, for each element of an RDD, I'm trying to get an array of <code>Row</code> elements.Then I want to convert the result into a DataFrame.</p> <p>I have the following code:</p> <pre><code> simulation = housesDF.flatMap(lambda house: goThroughAB(jobId, house)) print simulation.toDF().show() </code></pre...
-1
2016-07-06T16:47:17Z
38,234,384
<p>This code is not correct. <code>results += simulate(jobId, house, a, b)</code> would try to concatenate row and fail. If you don't see <code>TypeError</code> it is not reached and your code fails somewhere else, probably when you create <code>housesDF</code>.</p>
0
2016-07-06T21:50:53Z
[ "python", "apache-spark", "pyspark" ]
Can not apply flatMap on RDD
38,229,383
<p>In PySpark, for each element of an RDD, I'm trying to get an array of <code>Row</code> elements.Then I want to convert the result into a DataFrame.</p> <p>I have the following code:</p> <pre><code> simulation = housesDF.flatMap(lambda house: goThroughAB(jobId, house)) print simulation.toDF().show() </code></pre...
-1
2016-07-06T16:47:17Z
38,246,677
<p>The key issue, as pointed out by others, is <code>results += simulate(jobId, house, a, b)</code> which won't work when <code>simulation</code> returns a Row object. You could try to make <code>results</code> a <code>list</code> then use <code>list.append</code>. But why not <code>yield</code>?</p> <pre><code>def go...
-1
2016-07-07T13:24:14Z
[ "python", "apache-spark", "pyspark" ]
Download file from Google Drive with the discovery API
38,229,385
<p>I'm using the following methods across my app to interact with numerous Google Discovery-based APIs:</p> <pre><code>service, flags = sample_tools.init( sys.argv, 'drive', 'v3', __doc__, __file__, scope='https://www.googleapis.com/auth/drive') try: self.data = service.files().get( fileId = file_...
0
2016-07-06T16:47:23Z
38,238,475
<p>What you're looking for is <a href="https://developers.google.com/drive/v3/web/manage-downloads" rel="nofollow">Downloading a file using alt=media</a>.</p> <blockquote> <p>To download files, you make an authorized HTTP GET request to the file's resource URL and include the query parameter <code>alt=media</code>...
1
2016-07-07T06:02:37Z
[ "python", "google-drive-sdk" ]
Python loops: Making them more general
38,229,390
<p>I am working on converting data in a date format to a new ID based on other information in the spreadsheet. I want to also add _2,_3, etc. based on subsequent events in the same day. So if there are 3 cases of 20101212 in the dateID, the last 2 events would have a _2 and _3 modified onto the ID.</p> <p>How can I ...
-1
2016-07-06T16:47:48Z
38,229,507
<p>without being able to test against some data, try this:</p> <pre><code>dateID = [some list of strings in date format] GS = [some list of 2 letter strings to append to corresponding dates] #len(GS) = len(dateID) caseID = [] y = collections.Counter(dateID) #len(y) &lt; len(dateID) j = 0 for i in range(len(y)): ...
1
2016-07-06T16:54:47Z
[ "python", "loops", "collections" ]
Python loops: Making them more general
38,229,390
<p>I am working on converting data in a date format to a new ID based on other information in the spreadsheet. I want to also add _2,_3, etc. based on subsequent events in the same day. So if there are 3 cases of 20101212 in the dateID, the last 2 events would have a _2 and _3 modified onto the ID.</p> <p>How can I ...
-1
2016-07-06T16:47:48Z
38,229,536
<p>A simple solution would be to loop as many times as <code>num_iter</code>. Something like</p> <pre><code>base_string = sorted(y.iteritems())[i][0] for iter in range(num_iter): case = base_string + GS[j] case += '_{0}'.format(iter + 1) if iter &gt; 0 else '' caseID.append(case) j += 1 </code></pre> ...
2
2016-07-06T16:56:18Z
[ "python", "loops", "collections" ]
How to read irregular text file as a dataframe in Pandas
38,229,517
<pre><code>My file contains texts in the following format: &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . </code></pre> <p...
1
2016-07-06T16:55:23Z
38,229,778
<p>The <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv()</code></a> with backslash as an <em>escape character</em> actually works for me well on both your data samples:</p> <pre><code>df = pd.read_csv("input.txt", sep=" ", header=None, escapechar="\\")...
1
2016-07-06T17:09:28Z
[ "python", "parsing", "pandas" ]
How to read irregular text file as a dataframe in Pandas
38,229,517
<pre><code>My file contains texts in the following format: &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . </code></pre> <p...
1
2016-07-06T16:55:23Z
38,229,945
<p>This works even in the cases you label as giving irregular readings.</p> <pre><code>import re import pandas as pd col1 = [] col2 = [] col3 = [] with open('input.txt', 'r') as f: for line in f: g = re.match(r'^&lt;(.*)&gt; &lt;(.*)&gt; "(.*)"', line).groups() col1.append(g[0]) col2.appen...
0
2016-07-06T17:18:42Z
[ "python", "parsing", "pandas" ]
How to read irregular text file as a dataframe in Pandas
38,229,517
<pre><code>My file contains texts in the following format: &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . </code></pre> <p...
1
2016-07-06T16:55:23Z
38,234,539
<p>Eh, did I miss something? Why not just use <code>split()</code>?</p> <pre><code># -*- coding: utf-8 -*- sample = """\ &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . &lt;string1&gt; &lt;string2&gt; "some text as a paragraph" . &lt;string1&gt;...
0
2016-07-06T22:03:36Z
[ "python", "parsing", "pandas" ]
pyspark, Compare two rows in dataframe
38,229,659
<p>I'm attempting to compare one row in a dataframe with the next to see the difference in timestamp. Currently the data looks like:</p> <pre><code> itemid | eventid | timestamp ---------------------------- 134 | 30 | 2016-07-02 12:01:40 134 | 32 | 2016-07-02 12:21:23 125 | 30 | 2016-07-02 ...
1
2016-07-06T17:03:17Z
38,230,813
<p>Yes, you're using <code>map</code> function in a wrong way. <code>map</code> operates on a single element at the time. You can try to use window functions like this:</p> <pre><code>from pyspark.sql.functions import col, lag from pyspark.sql.window import Window df = ( sc.parallelize([ (134, 30, "2016-0...
2
2016-07-06T18:04:59Z
[ "python", "pyspark" ]
pyspark, Compare two rows in dataframe
38,229,659
<p>I'm attempting to compare one row in a dataframe with the next to see the difference in timestamp. Currently the data looks like:</p> <pre><code> itemid | eventid | timestamp ---------------------------- 134 | 30 | 2016-07-02 12:01:40 134 | 32 | 2016-07-02 12:21:23 125 | 30 | 2016-07-02 ...
1
2016-07-06T17:03:17Z
38,232,116
<p>I managed to solve it using mapPartitions:</p> <pre><code>def findOutage(items): outages = [] lastStamp = None for item in items: if lastStamp and (lastStamp - item.stamp).total_seconds() &gt; 14400: outages.append({"item": item.itemid, "start": item.sta...
0
2016-07-06T19:20:07Z
[ "python", "pyspark" ]
Confused about AttributeError in Python
38,229,726
<p>I am trying to do the following project: </p> <p>Imagine you have started up a small restaurant and are trying to make it easier to take and calculate orders. Since your restaurant only sells 9 different items, you assign each one to a number, as shown below.</p> <pre><code>Chicken Strips - $3.50 French Fries - $2...
0
2016-07-06T17:06:58Z
38,229,772
<p>Why are you accessing Menu_Item here? That's the class itself; the item that you've got from the list is called <code>food</code>.</p>
0
2016-07-06T17:09:11Z
[ "python", "class", "error-handling", "attributes" ]
Confused about AttributeError in Python
38,229,726
<p>I am trying to do the following project: </p> <p>Imagine you have started up a small restaurant and are trying to make it easier to take and calculate orders. Since your restaurant only sells 9 different items, you assign each one to a number, as shown below.</p> <pre><code>Chicken Strips - $3.50 French Fries - $2...
0
2016-07-06T17:06:58Z
38,229,866
<p><code>Menu_Item</code> is the class. You attempted to access an attribute of the class. Think of a class like a blueprint for a house. You asked for the street address for the blueprint.</p> <p>In Python, you're supposed to name classes with <code>CamelCase</code> by convention and PEP 8. So, <code>MenuItem</code> ...
0
2016-07-06T17:13:52Z
[ "python", "class", "error-handling", "attributes" ]
Confused about AttributeError in Python
38,229,726
<p>I am trying to do the following project: </p> <p>Imagine you have started up a small restaurant and are trying to make it easier to take and calculate orders. Since your restaurant only sells 9 different items, you assign each one to a number, as shown below.</p> <pre><code>Chicken Strips - $3.50 French Fries - $2...
0
2016-07-06T17:06:58Z
38,230,046
<p>You've got several problems here. Most notably the one pointed out by Daniel Roseman and uoɥʇʎPʎzɐɹC. However, after fixing that issue you will still have problems with your code. </p> <p>In <code>take_order()</code> you need to move <code>return count</code> outside of your for loop otherwise you will retur...
0
2016-07-06T17:24:22Z
[ "python", "class", "error-handling", "attributes" ]
Confused about AttributeError in Python
38,229,726
<p>I am trying to do the following project: </p> <p>Imagine you have started up a small restaurant and are trying to make it easier to take and calculate orders. Since your restaurant only sells 9 different items, you assign each one to a number, as shown below.</p> <pre><code>Chicken Strips - $3.50 French Fries - $2...
0
2016-07-06T17:06:58Z
38,231,365
<p>In addition to the useful answers you received, I just wanted to point out that you can solve this problem with a simple function, without having to define a new class (the project didn't require that, according to what you wrote).</p> <p>To begin with, you can create a dictionary of the items on the menu and their...
0
2016-07-06T18:35:49Z
[ "python", "class", "error-handling", "attributes" ]
Beginner Python Keyboard GUI setup
38,229,742
<p>I am beginning GUI in Python 3.5, and I am trying to setup a simple qwerty keyboard. Based on the examples, I tried the following code</p> <pre><code>from tkinter import Tk, Label, RAISED, Button, Entry self.window = Tk() #Keyboard labels = [['q','w','e','r','t','y','u','i','o','p'], ['a'...
2
2016-07-06T17:08:01Z
38,229,901
<p>Your issue is in the line <code>n -= 1</code>. Every time a label is created, you make <code>n</code> one less- after the first whole row, <code>n==0</code>, and thus the range is 0>0, and ranges never include the high bound- <code>for c in range(0)</code> will just drop from the loop (as it has looped through all t...
1
2016-07-06T17:16:01Z
[ "python", "user-interface", "tkinter", "keyboard" ]
Beginner Python Keyboard GUI setup
38,229,742
<p>I am beginning GUI in Python 3.5, and I am trying to setup a simple qwerty keyboard. Based on the examples, I tried the following code</p> <pre><code>from tkinter import Tk, Label, RAISED, Button, Entry self.window = Tk() #Keyboard labels = [['q','w','e','r','t','y','u','i','o','p'], ['a'...
2
2016-07-06T17:08:01Z
38,230,292
<p>Is this what you want it to do? Let me know if you need me to explain it further but basically what I'm doing is first filling the columns in each row. So row remains 0 and then as I loop through the column (the inner list) I fill in each of the keys, then on to the next row and etc. </p> <pre><code>from tkinte...
0
2016-07-06T17:37:49Z
[ "python", "user-interface", "tkinter", "keyboard" ]
Get cells indexes of raster file inside a rasterized border line in python
38,229,834
<p>I have a closed line made of raster cells of which I know the indexes (col and raw of each cell stored in a list). List is like -</p> <p><a href="http://i.stack.imgur.com/a2Hid.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/a2Hid.jpg" alt="enter image description here"></a></p> <p>I would like to get the i...
0
2016-07-06T17:12:27Z
38,233,589
<p>One way to approach this is to implement your own (naive) algorithm, which was my first idea. One the other hand, why reinvent the wheel: </p> <p>One can easily see that the problem can be interpreted as a black and white (raster/pixel) image. Then the outer and inner area form the background (black) while the bord...
0
2016-07-06T20:52:34Z
[ "python", "indexing", "polygon", "raster" ]
How to avoid AttributeError: '_tkinter.tkapp' object has no attribute 'PassCheck'
38,229,857
<p>I have read previous posts regarding this error but could not identify what i was doing wrong.Please can someone help me understand what i am doing wrong,thank you.</p> <pre><code> from tkinter import * class Passwordchecker(): def __init__(self): self= Tk() self.geometry("200x200") se...
1
2016-07-06T17:13:32Z
38,230,617
<h1>What triggered the error?</h1> <p>You get this error message:</p> <pre><code>AttributeError: '_tkinter.tkapp' object has no attribute 'PassCheck' </code></pre> <p>Because when an instance of <code>Passwordchecker()</code> is initialized, it stumbles on the <code>mainloop()</code> method of your <code>__init__()<...
1
2016-07-06T17:54:52Z
[ "python", "tkinter" ]
Use urllib or requests to get data from URL
38,229,924
<p>I am trying to use urllib, urllib2 or requests in order to get specific data from a site. I use Python2.7. I keep getting an error:</p> <pre><code>requests.exceptions.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590) </code></pre> <p>This is my code with requests:</p> <pre>...
0
2016-07-06T17:17:35Z
38,233,662
<blockquote> <p>All of them in macs with Yosemite or ElCapitan...</p> </blockquote> <p>These versions still come with OpenSSL 0.9.8 so my guess is that your python is linked against this version of OpenSSL (python does not use the native TLS stack in OS X). But since the server only supports ECDHE ciphers and these ...
2
2016-07-06T20:57:48Z
[ "python", "python-requests", "urllib" ]
How check for a specific sprite class in a list
38,229,936
<p>This is my current inventory system and I am working on having it register when an item has been picked up, but I am having trouble getting the program to register when the sprite class has been added to the list.</p> <pre><code>import pygame import Constants import item_sys clock = pygame.time.Clock() screen = pyg...
0
2016-07-06T17:18:12Z
38,244,941
<p>Your <code>if j == item_sys.Item1</code> check will fail because it is not checking the <em>type</em> of <code>j</code> equals <em>class type</em>. Rather, it is checking if the <em>value/object</em> <code>j</code> equals <em>class type</em>.</p> <p>So, what you need to do is get <code>j</code>s <em>type</em>. To d...
0
2016-07-07T12:00:31Z
[ "python", "pygame", "python-3.4" ]
Array and __rmul__ operator in Python Numpy
38,229,953
<p>In a project, I created a class, and I needed an operation between this new class and a real matrix, so I overloaded the <code>__rmul__</code> function like this</p> <pre><code>class foo(object): aarg = 0 def __init__(self): self.aarg = 1 def __rmul__(self,A): print(A) return...
5
2016-07-06T17:19:07Z
38,230,576
<p><strong>The behaviour is expected.</strong></p> <p>First of all you have to understand how an operation like <code>x*y</code> is actually executed. The python interpreter will <strong>first</strong> try to compute <code>x.__mul__(y)</code>. If this call returns <code>NotImplemented</code> it will <strong>then</stro...
4
2016-07-06T17:52:48Z
[ "python", "arrays", "numpy" ]
Array and __rmul__ operator in Python Numpy
38,229,953
<p>In a project, I created a class, and I needed an operation between this new class and a real matrix, so I overloaded the <code>__rmul__</code> function like this</p> <pre><code>class foo(object): aarg = 0 def __init__(self): self.aarg = 1 def __rmul__(self,A): print(A) return...
5
2016-07-06T17:19:07Z
40,046,253
<p>I could not explain the underlying problem as precise as Bakuriu, but there might be another solution. </p> <p>You can force numpy to use your evaluation method by defining <code>__array_priority__</code>. As explained <a href="http://docs.scipy.org/doc/numpy/reference/ufuncs.html" rel="nofollow">here</a> in the nu...
0
2016-10-14T14:58:38Z
[ "python", "arrays", "numpy" ]
lambdify: Allow limited flexibility in variable names in user defined functions
38,229,989
<p>I know how to use <code>sympy.utilities.lambdify</code> to parse user-defined functions into lambdas like this:</p> <pre><code>f = lambdify(('x',), 'x**2 - 4*x') </code></pre> <p>and I know that I can make it accept a function of <code>t</code> instead using</p> <pre><code>f = lambdify(('t',), 't**2 - 4*t') </cod...
2
2016-07-06T17:21:11Z
38,238,012
<p>I recommend first converting the string to a SymPy expression using <code>sympify</code>. </p> <p>You can then get the variable(s) from the expression using <code>free_symbols</code>, like</p> <pre><code>In [1]: (t**2 - 4*t).free_symbols Out[1]: set([t]) </code></pre>
3
2016-07-07T05:21:31Z
[ "python", "sympy" ]
Constructor Arguments Error when Declaring an Instance of a Class
38,230,017
<p>I was working on a class to control the power of two DC motors with the Raspberry Pi using the imported <code>RPi.GPIO</code> library. The code is as followed:</p> <pre><code>import RPi.GPIO as GPIO class Motor: def _init_(self, MotorPin): self.MotorControlPin = MotorPin GPIO.setmode(GPIO.BOAR...
0
2016-07-06T17:22:34Z
38,230,205
<p>The name of the constructor method in Python is <code>__init__</code>, with two underscores at the beginning and two at the end. Your code defines <code>_init_</code> instead, which as far as Python is concerned is just another ordinary method with no bearing on object construction.</p>
1
2016-07-06T17:33:17Z
[ "python", "raspberry-pi" ]
Repeat Program & Changing CSS Selector
38,230,043
<p>I'm so new to writing Python that I'm not even sure how to search for the answer I seek, my apologies for certainly requesting information that readily exists.</p> <p>I'm writing a program that pulls account numbers from an excel spreadsheet, opens the account information in a browser, scrapes information from the ...
0
2016-07-06T17:24:06Z
38,230,246
<p>You definitely need a loop. Use the <code>iter_rows()</code> to iterate over the worksheet row by row:</p> <pre><code>for row in sheet.iter_rows(row_offset=1): # start with row 2 cells = list(row) account_number = cells[0].value </code></pre> <p>Then, you can use string formatting to dynamically construct...
0
2016-07-06T17:35:14Z
[ "python", "excel", "web-scraping", "screen-scraping" ]
single pass data transformation using dask to do same as basic pandas example
38,230,044
<p>Im trying to understand how <a href="http://dask.pydata.org/en/latest/dataframe-api.html#dataframe-methods" rel="nofollow">dask</a> can help me do data transformation on a huge dataset. The task I need to perform is as the example below in pandas.</p> <pre><code>import pandas as pd pdf = pd.DataFrame({'ID': ['A', '...
1
2016-07-06T17:24:11Z
38,232,489
<p>here is my attempt to do it a single pass:</p> <pre><code>In [125]: pd.concat([df.ID, (df[vals1] &gt; 1), (df[vals2] &lt; 4)], axis=1).assign(ONES=1).groupby('ID').sum() Out[125]: VAL1 VAL2 VAL3 VAL4 ONES ID A 1.0 1.0 0.0 0.0 2 B 0.0 4.0 4.0 4.0 4 C 2.0 2.0 0.0 0.0 2 D...
0
2016-07-06T19:43:43Z
[ "python", "pandas", "dask" ]
single pass data transformation using dask to do same as basic pandas example
38,230,044
<p>Im trying to understand how <a href="http://dask.pydata.org/en/latest/dataframe-api.html#dataframe-methods" rel="nofollow">dask</a> can help me do data transformation on a huge dataset. The task I need to perform is as the example below in pandas.</p> <pre><code>import pandas as pd pdf = pd.DataFrame({'ID': ['A', '...
1
2016-07-06T17:24:11Z
38,240,793
<p>Given MaxUs answere I came up with the following, however I do not know if this is done in a single pass with dask??</p> <pre><code>import pandas as pd pdf = pd.DataFrame({'ID': ['A', 'B', 'C', 'D', 'A', 'B', 'B', 'B', 'C'], 'VAL1': [0,1,4,1,4,1,1,1,4], 'VAL2': [0,3,4,3,4,3,3...
0
2016-07-07T08:28:29Z
[ "python", "pandas", "dask" ]
3D scatter plot with 2D histogram at sides
38,230,074
<p>I would like to make a 3D scatterplot with with the 2D projections at each side. Something like the following:</p> <p><a href="http://i.stack.imgur.com/Eb2FP.png" rel="nofollow"><img src="http://i.stack.imgur.com/Eb2FP.png" alt="3D scatter"></a></p> <p>The scatterplot has been created with:</p> <pre><code>fig = p...
4
2016-07-06T17:25:55Z
38,231,893
<p>Use <code>plot_surface()</code>:</p> <pre><code>ax.scatter(x,y,z, marker='.', c='r') h, yedges, zedges = np.histogram2d(y, z, bins=50) h = h.transpose() normalized_map = plt.cm.Blues(h/h.max()) yy, zz = np.meshgrid(yedges, zedges) xpos = min(x)-2 # Plane of histogram xflat = np.full_like(yy, xpos) p = ax.plot_s...
1
2016-07-06T19:05:30Z
[ "python", "matplotlib", "3d" ]
lambda function replace column name with name_with_spaces
38,230,117
<p>I have some code:</p> <pre><code>df.groupby(['Image','Roi']).apply(lambda x: x.loc[~(x.duplicated(['Total']) &amp; x.Total.isnull())]) </code></pre> <p>I wish to replace "Total" with a longer PANDAS column name which includes spaces, but this raises a syntax error:</p> <pre><code>df.groupby(['Image','Roi']).apply...
1
2016-07-06T17:28:14Z
38,230,207
<p>Don't use a <em>dot</em> when accessing an array element:</p> <pre><code>x.['Total size'].isnull() ^ </code></pre> <p>Instead, just follow with bracket:</p> <pre><code>x['Total size'].isnull() </code></pre>
3
2016-07-06T17:33:23Z
[ "python", "pandas" ]
How to add values from two different columns of pandas dataframe
38,230,143
<p>How to add first rows from two different columns of a dataframe together, such that if column A's first row is <code>NaN</code>, replace with value from <code>balance</code>'s first row, otherwise, add column A's first row and <code>balance</code>'s first row. And so likewise column B. The idea is using <code>balnce...
1
2016-07-06T17:29:27Z
38,230,319
<p>IIUC you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.combine_first.html" rel="nofollow"><code>combine_first</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>fillna</code></a> if need replace <code>NaN</c...
2
2016-07-06T17:39:01Z
[ "python", "pandas" ]
Django extending user model tutorial isn't work for me
38,230,170
<p>I've use this tutorial and do exactly what they do: <a href="https://docs.djangoproject.com/ja/1.9/topics/auth/customizing/#extending-the-existing-user-model" rel="nofollow">https://docs.djangoproject.com/ja/1.9/topics/auth/customizing/#extending-the-existing-user-model</a></p> <p>my model.py:</p> <pre><code>from ...
1
2016-07-06T17:31:08Z
38,230,376
<p>Could it possible that you didn't register Chess model?</p> <p>Try add <code>admin.site.register(Chess, ChessAdmin)</code> at the bottom of admin.py. Of course you might have to create a simple ChessAdmin for display first.</p>
0
2016-07-06T17:41:34Z
[ "python", "django", "model", "user", "extend" ]
Django extending user model tutorial isn't work for me
38,230,170
<p>I've use this tutorial and do exactly what they do: <a href="https://docs.djangoproject.com/ja/1.9/topics/auth/customizing/#extending-the-existing-user-model" rel="nofollow">https://docs.djangoproject.com/ja/1.9/topics/auth/customizing/#extending-the-existing-user-model</a></p> <p>my model.py:</p> <pre><code>from ...
1
2016-07-06T17:31:08Z
38,233,135
<p>You need to update your <code>Chess</code> model and add <code>related_name</code> to the <code>user</code> property.</p> <pre><code>class Chess(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="chess_board") # Other Stuff </code></pre> <p>Now you can easily access <c...
0
2016-07-06T20:25:33Z
[ "python", "django", "model", "user", "extend" ]
Securely transfer a banch of files from one Heroku app to another
38,230,178
<p>I need to setup a Heroku app (python) which would perform scheduled tasks that include fetching a set of data (.csv an .html) files from other Heroku app (ROR) and returning a result back to that app. </p> <p>Also it should be restricted only to my app to be able to connect to the ROR app because it deals with sens...
0
2016-07-06T17:31:37Z
38,232,752
<p>I would suggest writing a secured JSON or XML API to transfer the data from app to app,. Once the data is received I would then generate the .csv or .html files from the received data. It keeps things clean and easy to modify for future revisions because now you'll have an API to interact with.</p>
1
2016-07-06T20:00:31Z
[ "python", "ruby-on-rails", "heroku", "transfer" ]
Python While Loop Syntax
38,230,190
<pre><code>class Solution: def display(self,head): current = head while current: print(current.data,end=' ') current = current.next </code></pre> <p>Hello, I am having some difficulties understanding the above while loop, AFAIK you need to have a condition with a while loop...
1
2016-07-06T17:32:38Z
38,230,258
<p>Your loop can be considered as</p> <pre><code>while current is not None: </code></pre> <p>because the parser will try to interpret current as a boolean (and None, empty list/tuple/dict/string and 0 evaluate to False)</p>
0
2016-07-06T17:35:46Z
[ "python", "loops", "while-loop" ]
Python While Loop Syntax
38,230,190
<pre><code>class Solution: def display(self,head): current = head while current: print(current.data,end=' ') current = current.next </code></pre> <p>Hello, I am having some difficulties understanding the above while loop, AFAIK you need to have a condition with a while loop...
1
2016-07-06T17:32:38Z
38,230,275
<p>The <code>while current:</code> syntax literally means <code>while bool(current) == True:</code>. The value will be converted to bool first and than compared to <code>True</code>. In python everyting converted to bool is <code>True</code> unless it's <code>None</code>, <code>False</code>, zero or an empty collection...
6
2016-07-06T17:36:44Z
[ "python", "loops", "while-loop" ]
Python While Loop Syntax
38,230,190
<pre><code>class Solution: def display(self,head): current = head while current: print(current.data,end=' ') current = current.next </code></pre> <p>Hello, I am having some difficulties understanding the above while loop, AFAIK you need to have a condition with a while loop...
1
2016-07-06T17:32:38Z
38,230,282
<p>The value of the variable <code>current</code> is the condition. If it's truthy, the loop continues, if it's falsy the loop stops. The expectation is that in the last element in the linked list, <code>next</code> will contain a falsy value. I assume that value is <code>None</code>, and in that case the loop is equiv...
0
2016-07-06T17:37:15Z
[ "python", "loops", "while-loop" ]
python: combine 2 ordered lists into list of tuples
38,230,209
<p>I have 2 lists that I want to combine into a single list of tuples, so that order is maintained and the <code>result[i]</code> is <code>(first[i], second[i])</code>. Assume that the two lists will always be of the same size. Is there a way to do this using list comprehension? So for example:</p> <pre><code>&gt;&...
0
2016-07-06T17:33:30Z
38,230,237
<p>Use zip:</p> <pre><code>list(zip(first, second)) Out[384]: [(1, 4), (2, 5), (3, 6)] </code></pre>
6
2016-07-06T17:34:54Z
[ "python", "list", "list-comprehension" ]
python: combine 2 ordered lists into list of tuples
38,230,209
<p>I have 2 lists that I want to combine into a single list of tuples, so that order is maintained and the <code>result[i]</code> is <code>(first[i], second[i])</code>. Assume that the two lists will always be of the same size. Is there a way to do this using list comprehension? So for example:</p> <pre><code>&gt;&...
0
2016-07-06T17:33:30Z
38,230,249
<p>You can use the built-in <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow">zip</a> function:</p> <pre><code>&gt;&gt;&gt; first = [1,2,3] &gt;&gt;&gt; second = [4,5,6] &gt;&gt;&gt; list(zip(first, second)) [(1,4), (2,5), (3,6)] </code></pre>
2
2016-07-06T17:35:21Z
[ "python", "list", "list-comprehension" ]
python: combine 2 ordered lists into list of tuples
38,230,209
<p>I have 2 lists that I want to combine into a single list of tuples, so that order is maintained and the <code>result[i]</code> is <code>(first[i], second[i])</code>. Assume that the two lists will always be of the same size. Is there a way to do this using list comprehension? So for example:</p> <pre><code>&gt;&...
0
2016-07-06T17:33:30Z
38,230,251
<p>Python has a function for that:</p> <pre><code>&gt;&gt;&gt; zip(first, second) [(1, 4), (2, 5), (3, 6)] </code></pre> <p>zippedy-doo-dah</p>
5
2016-07-06T17:35:26Z
[ "python", "list", "list-comprehension" ]
python: combine 2 ordered lists into list of tuples
38,230,209
<p>I have 2 lists that I want to combine into a single list of tuples, so that order is maintained and the <code>result[i]</code> is <code>(first[i], second[i])</code>. Assume that the two lists will always be of the same size. Is there a way to do this using list comprehension? So for example:</p> <pre><code>&gt;&...
0
2016-07-06T17:33:30Z
38,230,288
<p>Use izip:</p> <pre><code>&gt;&gt;&gt; first = [1,2,3] &gt;&gt;&gt; second = [4,5,6] &gt;&gt;&gt; from itertools import izip &gt;&gt;&gt; gen = izip(first, second) &gt;&gt;&gt; [(i, j) for i, j in gen] [(1, 4), (2, 5), (3, 6)] </code></pre>
0
2016-07-06T17:37:41Z
[ "python", "list", "list-comprehension" ]
python: combine 2 ordered lists into list of tuples
38,230,209
<p>I have 2 lists that I want to combine into a single list of tuples, so that order is maintained and the <code>result[i]</code> is <code>(first[i], second[i])</code>. Assume that the two lists will always be of the same size. Is there a way to do this using list comprehension? So for example:</p> <pre><code>&gt;&...
0
2016-07-06T17:33:30Z
38,230,289
<pre><code>&gt;&gt;&gt; first = [1,2,3] &gt;&gt;&gt; second = [4,5,6] &gt;&gt;&gt; list =zip(first,second) &gt;&gt;&gt; list [(1, 4), (2, 5), (3, 6)] </code></pre> <p>or also for lists instead of tuple, using numpy</p> <pre><code>&gt;&gt;&gt; lista = [first,second] &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.arra...
1
2016-07-06T17:37:42Z
[ "python", "list", "list-comprehension" ]
Django: 'unicode' object has no attribute 'tzinfo' error using django-pyodbc-azure
38,230,267
<p>I have been asked to create a simple web front-end for an internal MSSQL database. I'm using django-pyodbc-azure .</p> <p>I finally got everything configured and running but now when I try to log in to the admin page I get a <strong>'unicode' object has no attribute 'tzinfo'</strong> error. I tried the suggestion <...
0
2016-07-06T17:36:19Z
38,235,387
<p>The solution was posted by miyamoto. I had to add the line <strong>'use_legacy_datetime': True</strong> to my database connection options in Django, and then I had to manually change all of the Datetime2 columns in my database over to Datetime. </p> <p>More info on the solution can be found <a href="http://stackove...
0
2016-07-06T23:25:04Z
[ "python", "django", "unicode", "tzinfo", "django-pyodbc-azure" ]
django sqlite to postgresql ProgrammingError when migrate
38,230,354
<p>I've seen quite some posts about this but none helped me so far. I have a working django application and I want to go from sqlite to postgresql database. For that, I am following the djangogirls tutorial which is great, until some error occurs.</p> <p>I have downloaded postgresql on my pc for development, then I do...
1
2016-07-06T17:40:47Z
38,231,012
<p>You could <a href="https://docs.djangoproject.com/en/1.9/ref/django-admin/#dumpdata" rel="nofollow"><code>dump</code> your data into json</a>, remove your sqlite file then migrate your project with <a href="http://stackoverflow.com/questions/5394331/how-to-setup-postgresql-database-in-django">postgres set up as a DB...
0
2016-07-06T18:17:27Z
[ "python", "django", "postgresql", "sqlite", "database-migration" ]
django sqlite to postgresql ProgrammingError when migrate
38,230,354
<p>I've seen quite some posts about this but none helped me so far. I have a working django application and I want to go from sqlite to postgresql database. For that, I am following the djangogirls tutorial which is great, until some error occurs.</p> <p>I have downloaded postgresql on my pc for development, then I do...
1
2016-07-06T17:40:47Z
38,249,378
<p>Well, finally I found one small post on stackoverflow that said that psycopg2 should be in INSTALLED_APPS in my settings.py. I added it a ran again </p> <pre><code>python manage.py migrate </code></pre> <p>and it worked fine! Thanks to those who answered though, it's really appreciated!</p> <p>Though now I get t...
0
2016-07-07T15:23:13Z
[ "python", "django", "postgresql", "sqlite", "database-migration" ]
django sqlite to postgresql ProgrammingError when migrate
38,230,354
<p>I've seen quite some posts about this but none helped me so far. I have a working django application and I want to go from sqlite to postgresql database. For that, I am following the djangogirls tutorial which is great, until some error occurs.</p> <p>I have downloaded postgresql on my pc for development, then I do...
1
2016-07-06T17:40:47Z
38,266,155
<p>So I post this as an answer because it is too long for a comment: </p> <p>I commented out the code in apps.py that uses my model (it probably uses it before migrating so the model does not exist yet. Then I ran makemigrations, and I got: </p> <pre><code>Migrations for 'carte_interactive': 001_initial.py: ...
0
2016-07-08T12:02:15Z
[ "python", "django", "postgresql", "sqlite", "database-migration" ]
Is there a way, in Django, to define routes using Flask-style route syntax?
38,230,405
<p>Setting aside any strongly-held feelings about Django vs Flask, I have a <em>whole bunch</em> of Flask-style routes I'd like to convert to Django. They look like your usual Flask routes:</p> <pre><code>'/foo/&lt;spam&gt;/&lt;int:eggs&gt;/' </code></pre> <p>This gets even more complex with converters in Flask like ...
3
2016-07-06T17:42:57Z
38,230,454
<p>Have not personally used it, but this sounds exactly what you are asking about - <a href="https://github.com/afg984/django-fsu" rel="nofollow"><code>django-fsu</code></a>:</p> <blockquote> <p>Flask-Style URL Patterns for Django</p> </blockquote> <p>I would though still try to stick to Django URL-routing style an...
1
2016-07-06T17:45:41Z
[ "python", "django", "flask", "django-urls" ]
How to replace columns with matching name
38,230,406
<p>I know this might be very simple, but I can't figure out how to do it.</p> <p>I have a df with several columns I want to replace, but lets say I have a df like this:</p> <pre><code>df1: A B 0 a 22 1 b 44 2 c 100 3 d 6 4 e 12 </code></pre> <p>And another df</p> <pre><code>df2: B 0 11 1 ...
2
2016-07-06T17:43:00Z
38,230,433
<p>If length and indexes are same of both <code>df</code>:</p> <pre><code>df1['B'] = df2.B </code></pre> <p>If need only add values:</p> <pre><code>df1['B'] = df2.B.values </code></pre> <p>If need replace more columns:</p> <pre><code>df1 = pd.DataFrame({'A':[1,2,3], 'B':[3,5,6], ...
4
2016-07-06T17:44:44Z
[ "python", "pandas" ]
How to replace columns with matching name
38,230,406
<p>I know this might be very simple, but I can't figure out how to do it.</p> <p>I have a df with several columns I want to replace, but lets say I have a df like this:</p> <pre><code>df1: A B 0 a 22 1 b 44 2 c 100 3 d 6 4 e 12 </code></pre> <p>And another df</p> <pre><code>df2: B 0 11 1 ...
2
2016-07-06T17:43:00Z
38,230,918
<p>The code below is crude, and could be improved, but tell me if does what you want first. Supposing that you have one dataframe's length superior to the other:</p> <pre><code>def replace(dfa, dfb): a_ = [match for match in df1.columns.values if match in df2.columns.values] if len(dfa.columns) &gt; len(dfb.co...
2
2016-07-06T18:11:05Z
[ "python", "pandas" ]
good way to generalize multiple try except
38,230,448
<p>I have 15 try except statements in a for loop in the code. I think that it can be generalized but I am not able to get to the solution. How can I do it. </p> <pre><code>for item in results: try: a = item.something() except: a = "" try: b = item.something2() except: ...
0
2016-07-06T17:45:27Z
38,230,509
<p>Without changing your data:</p> <pre><code>def try_something(callable): try: return callable() except: return "" a = try_something(item.something) </code></pre> <p>Remember that you can freely pass a callable (function or method) as a parameter to a Python function. This utilizes that. How...
2
2016-07-06T17:48:48Z
[ "python", "exception-handling", "try-catch", "except", "generalization" ]
good way to generalize multiple try except
38,230,448
<p>I have 15 try except statements in a for loop in the code. I think that it can be generalized but I am not able to get to the solution. How can I do it. </p> <pre><code>for item in results: try: a = item.something() except: a = "" try: b = item.something2() except: ...
0
2016-07-06T17:45:27Z
38,336,776
<p>The current accepted answer would only work if the callable did not take any arguments, to execute a small snippet and suppress a certain error it might raise it would be easier to use a context manager:</p> <pre><code>class catch: def __init__(self,err_type): valid = True if isinstance(err_type...
1
2016-07-12T18:51:10Z
[ "python", "exception-handling", "try-catch", "except", "generalization" ]
openCV2 not displaying image correctly (grey area added)
38,230,485
<p>My goal is to simply display image using openCV2. Here is the code:</p> <pre><code>import cv2 img2 = cv2.imread('opencv_logo.png') cv2.imshow('img2', img2) cv2.waitKey(0) cv2.destroyAllWindows() </code></pre> <p>Here is how original image looks: <a href="http://i.stack.imgur.com/3eXaJ.png" rel="nofollow"><img src...
0
2016-07-06T17:47:23Z
38,240,413
<p>I've observed that the opencv highgui windows have some minimum width.</p> <p>If your image is smaller than that minimum window size, the rest of the space is filled with whatever is in the window buffer atm. This might not be a problem, if you always render images of same (too small) size, but it might give unwant...
1
2016-07-07T08:04:13Z
[ "python", "opencv" ]
The best way to implement a pure newsletter in django?
38,230,548
<p>My django service is a pure newsletter service. The user need not have a password. All the user needs to do is provide an email address. We will be sending the email periodically. </p> <p>So the user does not have to provide the username and password. But having an email confirmation step is important. </p> <p>The...
-3
2016-07-06T17:50:59Z
38,254,487
<p>It is sad that stackoverflow is lot less friendly than it used to be. I did wade through a considerable amount of plugins before finding what I needed. For anyone who is looking for something similar, check out <a href="https://github.com/bitmazk/django-newsletter-signup" rel="nofollow" title="django-newsletter-sign...
0
2016-07-07T20:14:43Z
[ "python", "django", "registration", "newsletter", "django-registration" ]
Python get request returning different HTML than view source
38,230,605
<p>I'm trying to extract the fanfiction from an Archive of Our Own URL in order to use the NLTK library to do some linguistic analysis on it. However every attempt at scraping the HTML from the URL is returning everything BUT the fanfic (and the comments form, which I don't need).</p> <p>First I tried with the built i...
1
2016-07-06T17:54:03Z
38,230,682
<p>The last approach is a step into the right direction if you need the complete page source with all the JavaScript executed and async requests made. You are just missing one thing - you need to <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow">give PhantomJS time</a> to load the...
1
2016-07-06T17:58:13Z
[ "python", "selenium", "web-scraping", "beautifulsoup", "phantomjs" ]
Python get request returning different HTML than view source
38,230,605
<p>I'm trying to extract the fanfiction from an Archive of Our Own URL in order to use the NLTK library to do some linguistic analysis on it. However every attempt at scraping the HTML from the URL is returning everything BUT the fanfic (and the comments form, which I don't need).</p> <p>First I tried with the built i...
1
2016-07-06T17:54:03Z
38,231,098
<p>Alexce has explained why your code did not give you what you want, if all you want is the text which is available in the source if you add the param <code>view_adult=true</code>:</p> <pre><code>import requests from bs4 import BeautifulSoup url = "http://archiveofourown.org/works/6846694?view_adult=true" r= reques...
1
2016-07-06T18:22:02Z
[ "python", "selenium", "web-scraping", "beautifulsoup", "phantomjs" ]
Why are my pyplot subplots only taking up half of the figure?
38,230,679
<p>I am creating two subplots, side by side, and for some reason they will only fill the top half of the figure. </p> <pre><code>grid = {'width_ratios':[3,1],'height_ratios':[1,1]} self.fig, self.axes = plt.subplots(1,2, sharey=True, gridspec_kw=grid) </code></pre> <p>And here is what it looks like once I plot everyt...
0
2016-07-06T17:58:06Z
38,230,821
<p>By declaring <code>'height_ratios':[1,1]</code> you are creating two rows of <code>subplots</code>; similarly <code>'height_ratios':[1,1,1]</code> will give you three rows, et cetera. So simply write <code>'height_ratios':[1]</code>, or leave out <code>height_ratios</code>, and it is fixed.</p> <p><s>It's seems str...
1
2016-07-06T18:05:22Z
[ "python", "matplotlib" ]
Getting to work rock, paper, scissors game in Python
38,230,721
<p>I am trying to make a rock, paper, scissors python program, but I cant get it to work. Can anybody help me? PS: I am using Python 3.5</p> <p>I start by importing <code>random</code> and telling Python to run different programs depending on the result from <code>random.randint(1,3)</code></p> <pre><code>import rand...
-1
2016-07-06T18:00:04Z
38,230,774
<p>You are taking raw_input as <code>use_choice</code> and comparing <code>user_choice</code>. The variable names are different.</p>
0
2016-07-06T18:02:36Z
[ "python" ]
Running Python Script, without Console, omni-solution
38,230,828
<p>I have a project program,</p> <pre><code>main.py </code></pre> <p>and I want to have the possibility to execute it in 3 different ways, per executable / script.</p> <pre><code>1 py main.py 2 pyw main.py 3 py main.py bd / pyw main.py bd </code></pre> <p>If it would only be on my system, it wouldn't be an issue,...
-1
2016-07-06T18:05:57Z
38,235,556
<p>for a scrip that execute other scrip, look at the <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">subprocess module</a> </p> <p>to help you processing command-line arguments you can check <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">argparse module</a> if you d...
0
2016-07-06T23:43:35Z
[ "python", "shell", "command-line", "argv" ]
Replace values in netCDF file using python
38,230,923
<p>I would like to replace all the -999.0 values in the foll. netCDF file by 0.0. The file is here: <a href="https://www.dropbox.com/s/ohh7tntzm2pj1uw/all_SSP3_BaU_NoCC.nc?dl=0" rel="nofollow">https://www.dropbox.com/s/ohh7tntzm2pj1uw/all_SSP3_BaU_NoCC.nc?dl=0</a></p> <p>here's my function:</p> <pre><code>def modify_...
2
2016-07-06T18:11:28Z
38,386,833
<p>You opened the file in append mode (<code>r+</code>), which will only allow new values to be added. There really is no read/write mode because data sets grow huge quickly. You have two options:</p> <ul> <li><p>Read the dataset, open a new file (mode is <code>w</code>, clobber is True), write to it with modificat...
1
2016-07-15T02:07:28Z
[ "python", "netcdf4" ]
python numpy csv header in column not row
38,230,928
<p>I have a script which produces a 15x1096 array of data using </p> <pre><code>np.savetxt("model_concentrations.csv", model_con, header="rows:','.join(sources), delimiter=",") </code></pre> <p>Each of the 15 rows corresponds to a source of emissions, while each column is 1 day over 3 years. If at all possible I woul...
1
2016-07-06T18:11:50Z
38,231,286
<p>Labels for rows and columns is one of main reasons for the existence of pandas.</p> <pre><code>import pandas as pd # Assemble your source labels in a list sources = ['2per', '3rd_pvd', '3rd_unpvd', '4rai_rd', '4rai_yd', '5rmo', '6hea', ...] # Create a pandas DataFrame wrapping your numpy array df = pd....
2
2016-07-06T18:32:12Z
[ "python", "csv", "numpy" ]
Generating a CSRF token manually with Flask WTF-Forms
38,231,010
<p>I'd like to create and fill out a Flask WTF-Form using only python code. However, the form doesn't automatically generate a CSRF token when I create it with python code. Is there any way to do this manually?</p> <p>The form in question: </p> <pre><code>from flask_wtf import Form from wtforms import StringField f...
1
2016-07-06T18:17:21Z
38,231,773
<p>Since you're not using CSRF protection, disable it. You can also pass <code>request.args</code> as the source of data.</p> <pre><code>form = URLForm(request.args, csrf_enabled=False) </code></pre>
1
2016-07-06T18:58:00Z
[ "python", "flask", "wtforms", "flask-wtforms", "csrf-protection" ]
Tensorflow Model Evaluation is based on batch size
38,231,013
<p>I have a graph in TensorFlow which I've trained based on a batch size of 32 observations over hundreds of epochs. I now want to to predict some new data based on the trained graph so I've saved it and reloaded it but I'm forced to always pass in the same amount of observations as my batch size because I've declared ...
0
2016-07-06T18:17:27Z
38,231,085
<p>You can define your placeholders to have flexible size on one of the dimensions by using <code>None</code> instead of a specific number like this:</p> <pre><code>x = tf.placeholder(tf.float32, shape=[None, self.image_height, self.image_width, 1], name="data") y_ = tf.placeholder(tf.float32, shape=[None, num_label...
2
2016-07-06T18:21:20Z
[ "python", "machine-learning", "tensorflow" ]
Tensorflow Model Evaluation is based on batch size
38,231,013
<p>I have a graph in TensorFlow which I've trained based on a batch size of 32 observations over hundreds of epochs. I now want to to predict some new data based on the trained graph so I've saved it and reloaded it but I'm forced to always pass in the same amount of observations as my batch size because I've declared ...
0
2016-07-06T18:17:27Z
38,231,164
<p>My approach would have been to define batch_size as a tf.variable and then feed the value of the batchsize you want to use when running the session. This has worked fine for me in the past, but I guess the solution by <a href="http://stackoverflow.com/users/118173/styrke">Stryke</a> would be more elegant.</p>
1
2016-07-06T18:25:40Z
[ "python", "machine-learning", "tensorflow" ]
Average number of retweets a user gets on his tweet on twitter
38,231,022
<p>I have a list of 5000 twitter user ids, Now, I want to get avg number of retweets/favs a user gets on his tweets. </p> <pre><code>max(total_retweets,total_favs)/total_tweets </code></pre> <p>I also want to get the number of mentions that a user got per tweet he did.</p> <pre><code>total_mentions/total_tweets </co...
0
2016-07-06T18:17:56Z
38,235,446
<p>To achieve this, you need to use <a href="http://tweepy.readthedocs.io/en/v3.5.0/api.html#API.user_timeline" rel="nofollow">Tweepy user_timeline</a> which will return you at max 100 tweets/retweets from the timeline, assuming that that many tweets are available to return. </p> <p>Do not forget to turn on the <code>...
0
2016-07-06T23:31:11Z
[ "python", "twitter", "tweepy" ]
Netsuite namespace issues
38,231,035
<p>I'm currently working on a side project using python and NetSuite Webservices. I've been able to send off a request for data centers successfully. I'm using the element tree import to parse the xml requests and responses. No matter what I try to grab one of the urls below I end up getting no value and I'm assuming t...
0
2016-07-06T18:18:57Z
38,251,129
<p>It looks like you should probably try:</p> <pre><code>xml.find('{urn:messages_2016_1.platform.webservices.netsuite.com}webservicesDomain') </code></pre> <p>or </p> <pre><code>ns = {'nsp': 'urn:messages_2016_1.platform.webservices.netsuite.com'} xml.find('nsp:webservicesDomain', ns) </code></pre>
0
2016-07-07T16:50:59Z
[ "python", "web-services", "netsuite" ]
Trying to read an ADC with Cython on an RPi 2 b+ via SPI (MCP3304, MCP3204, or MCP3008)?
38,231,123
<p>I'd like to read differential voltage values from an <a href="http://www.farnell.com/datasheets/1486116.pdf" rel="nofollow">MCP3304</a> (5v VDD, 3.3v Vref, main channel = 7, diff channel = 6) connected to an <a href="https://www.raspberrypi.org/products/model-b-plus/" rel="nofollow">RPi 2 b+</a> as close as possible...
0
2016-07-06T18:23:42Z
38,232,861
<p>There is probably no need to create an MCP3304 object for each iteration. Also conversion from float to string can be delayed.</p> <pre><code>s = [] mcp = MCP3304(channel = 7, diff = True) for i in range(25000): v = mcp.value * 3.3 s.append(v) out = '\n'.join('{:.2f}'.format(v) for v in s) + '\n' </code><...
2
2016-07-06T20:07:41Z
[ "python", "cython", "sensor", "raspberry-pi2", "adc" ]
Annotating Python print() output with comments
38,231,131
<p>Given a Python script with <code>print()</code> statements, I'd like to be able to run through the script and insert a comment after each statement that shows the output from each. To demonstrate, take this script named <code>example.py</code>:</p> <pre><code>a, b = 1, 2 print('a + b:', a + b) c, d = 3, 4 print(...
3
2016-07-06T18:24:14Z
38,234,036
<p>Thanks to feedback from @Lennart, I've <strong>almost</strong> got it working... It iterates through line-by-line, clumping lines into longer and longer blocks as long as the current block contains a <code>SyntaxError</code> when fed to <code>exec()</code>. Here it is in case it's of use to anyone else:</p> <pre>...
1
2016-07-06T21:25:25Z
[ "python", "python-3.x", "comments", "stdout", "code-formatting" ]
Annotating Python print() output with comments
38,231,131
<p>Given a Python script with <code>print()</code> statements, I'd like to be able to run through the script and insert a comment after each statement that shows the output from each. To demonstrate, take this script named <code>example.py</code>:</p> <pre><code>a, b = 1, 2 print('a + b:', a + b) c, d = 3, 4 print(...
3
2016-07-06T18:24:14Z
38,448,238
<p>You can make it a lot easier by using an existing python parser to extract top level statements from your code. The <a href="https://docs.python.org/3.4/library/ast.html" rel="nofollow">ast</a> module in the standard library for example. However, ast loses some information like comments.</p> <p>Libraries built with...
1
2016-07-19T01:31:40Z
[ "python", "python-3.x", "comments", "stdout", "code-formatting" ]
Annotating Python print() output with comments
38,231,131
<p>Given a Python script with <code>print()</code> statements, I'd like to be able to run through the script and insert a comment after each statement that shows the output from each. To demonstrate, take this script named <code>example.py</code>:</p> <pre><code>a, b = 1, 2 print('a + b:', a + b) c, d = 3, 4 print(...
3
2016-07-06T18:24:14Z
38,507,680
<p>Have you considered using the <code>inspect</code> module? If you are willing to say that you always want the annotations next to the top most call, and the file you are annotating is simple enough, you can get reasonable results. The following is my attempt, which overrides the built in print function and looks at ...
5
2016-07-21T14:58:15Z
[ "python", "python-3.x", "comments", "stdout", "code-formatting" ]
Annotating Python print() output with comments
38,231,131
<p>Given a Python script with <code>print()</code> statements, I'd like to be able to run through the script and insert a comment after each statement that shows the output from each. To demonstrate, take this script named <code>example.py</code>:</p> <pre><code>a, b = 1, 2 print('a + b:', a + b) c, d = 3, 4 print(...
3
2016-07-06T18:24:14Z
38,554,236
<p>It looks like <code>except SyntaxError</code> isn't a sufficient check for a full function, as it will finish the block a the first line which doesn't create a syntax error. What you want is to make sure the whole function is encompassed in the same block. To accomplish this:</p> <ul> <li><p>check if the current bl...
1
2016-07-24T16:28:43Z
[ "python", "python-3.x", "comments", "stdout", "code-formatting" ]
How can I fix a 403 forbidden on an apache server using Django?
38,231,133
<p>I get the following error when I try to access my website:</p> <p><code>Forbidden. You don't have permission to access / on this server.</code></p> <p>My virtual host file looks like the following:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerAdmin webmaster@localhost DocumentRoot /var/www/html ...
0
2016-07-06T18:24:22Z
38,286,698
<p>Below is how I fixed (with a lot of help) the problem. This answer assumes you have the following project structure:</p> <pre><code>~/myproject - myproject - ... - settings.py - wsgi.py - myapp - ... - static - myapp - ... </code></pre> <p><em>Digression</em...
0
2016-07-09T21:55:49Z
[ "python", "django", "apache", "ubuntu" ]
Python: Subprocess "call" function can't find path
38,231,176
<p>I have a python program that needs to run a bash command on a server. The program works when I run a bash command in my local directory like this:</p> <p><code>import subprocess from subprocess import call call(['bash', 'Script_Test.sh'])</code></p> <p>However, after SSH'ing to a server and running a similar line ...
1
2016-07-06T18:26:19Z
38,243,773
<h2>Making Sure Your Script is Ready for Execution</h2> <ol> <li>Give your script a shebang line</li> </ol> <p>First things first, it is <a href="http://stackoverflow.com/a/25202821/5209610">important that you include a shebang line</a> in your script on Unix-like systems. I recommend, <a href="http://stackoverflow.c...
0
2016-07-07T10:59:04Z
[ "python", "bash", "shell", "ssh", "subprocess" ]
In a LoginRequiredMixin How to receive the redirect_field_name
38,231,232
<p>Got this from the documentation:</p> <pre><code>class MyView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to' </code></pre> <p>But in my <code>loginView(FormView)</code> I can not find the way to receive and use the "redirect_to" var within the <code>form_valid()</code> ...
0
2016-07-06T18:29:37Z
38,231,407
<p>You can retrieve <code>redirect_to</code> from <code>request.GET</code>, so in your CBV method you can use <code>self.request.GET.get('redirect_to')</code>.</p> <p>Note that <strong>it might not be safe to redirect to a url fetched from the query string</strong>. For example, it could link to a different domain. Dj...
0
2016-07-06T18:38:04Z
[ "python", "django" ]
In a LoginRequiredMixin How to receive the redirect_field_name
38,231,232
<p>Got this from the documentation:</p> <pre><code>class MyView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to' </code></pre> <p>But in my <code>loginView(FormView)</code> I can not find the way to receive and use the "redirect_to" var within the <code>form_valid()</code> ...
0
2016-07-06T18:29:37Z
38,254,551
<p>I removed the <code>get</code> method and added the <code>get_context_data</code> instead:</p> <pre><code>def get_context_data(self, **kwargs): context = super(Login_vw, self).get_context_data(**kwargs) context['next'] = self.request.GET.get('redirect_to') return context </code></pre> <p>an...
0
2016-07-07T20:19:28Z
[ "python", "django" ]
Bulk rename of Pandas DF columns using 'try'
38,231,252
<p>I have a data set that has variable column names. I would like to rename the columns it using <code>df.rename(columns={})</code> command.</p> <p>Since some columns don't always appear in the DF I often raise exceptions. Is there a way to couple <code>try</code> with the rename command?</p> <p>ie something like thi...
1
2016-07-06T18:30:21Z
38,231,307
<p><code>rename()</code> will ignore not existing columns:</p> <p>Demo:</p> <pre><code>In [11]: df Out[11]: a b c 0 2 2 9 1 3 5 5 2 0 8 0 3 9 8 1 4 2 2 3 In [12]: df.rename(columns={'a':'AA','b':'BB','z':'ZZ'}) Out[12]: AA BB c 0 2 2 9 1 3 5 5 2 0 8 0 3 9 8 1 4 2 2 3...
3
2016-07-06T18:33:25Z
[ "python", "pandas", "dataframe" ]
copying strings to the list in Python
38,231,261
<p>I have a list <code>data</code>, and I am reading lines from it.</p> <pre><code>item = user = channel = time = [] with open('train_likes.csv') as f: data = csv.reader(f) readlines = f.readlines() </code></pre> <p>I want to split each line into single string elements and append each element to a one of 2 ot...
3
2016-07-06T18:30:51Z
38,231,326
<p>When you write <code>item=user=channel=time=[]</code>, you are creating only one object, with 4 aliases. So appending to <code>item</code> is the same as appending to <code>user</code>. Instead you should write</p> <pre><code>item, user, channel, time = [], [], [], [] </code></pre> <p>or simply</p> <pre><code>ite...
7
2016-07-06T18:34:09Z
[ "python", "string", "list", "copy", "append" ]
copying strings to the list in Python
38,231,261
<p>I have a list <code>data</code>, and I am reading lines from it.</p> <pre><code>item = user = channel = time = [] with open('train_likes.csv') as f: data = csv.reader(f) readlines = f.readlines() </code></pre> <p>I want to split each line into single string elements and append each element to a one of 2 ot...
3
2016-07-06T18:30:51Z
38,231,498
<p>As @Greg points out, you are creating one list object and assigning it to four variables.</p> <p>You don't appear to use <code>channel</code> or <code>time</code> in your code, however. In addition, this is a more memory efficient way to read your file. You are reading each line separately instead of the whole fi...
3
2016-07-06T18:43:11Z
[ "python", "string", "list", "copy", "append" ]
Having trouble getting my http server to recognize and run python scripts
38,231,278
<p>I've created a local address http webserver that will hopefully be able to open both HTML webpages and python scripts that create HTML webpages, but I keep getting a 501 error because I can't figure out how to get the webserver to recognize the code correctly. Another note: I'm coding on Windows, I'm not using Cygwi...
0
2016-07-06T18:31:32Z
38,231,886
<p>Try changing the extension to .cgi on your python file and see if that helps. You'll probably want to use something like bottle.py or django tho if you're running python on a webserver. Bottle is easier to learn but with fewer features.</p> <p><a href="http://bottlepy.org/docs/dev/index.html" rel="nofollow">http://...
0
2016-07-06T19:04:58Z
[ "python", "html", "http", "server", "shebang" ]
AttributeError : int object has no attribute
38,231,300
<pre><code>class Point(object): ''' A point on a grid at location x, y ''' def __init__(self, x, y): self.X=x self.Y=y def __str__(self): return "X=" + str(self.X), "Y=" + str(self.Y) def __add__(self, other): if not isinstance(other, Point): raise Type...
0
2016-07-06T18:32:56Z
38,231,410
<p>First of all I can't reproduce the exact error you show, but I believe that is some sort of a "typo". You are trying to add a <code>list</code> instance to a <code>Point</code> instance, while the <code>__add__</code> method of the later throws the error whenever you try to add anything that is not a <code>Point</co...
3
2016-07-06T18:38:12Z
[ "python" ]
AttributeError : int object has no attribute
38,231,300
<pre><code>class Point(object): ''' A point on a grid at location x, y ''' def __init__(self, x, y): self.X=x self.Y=y def __str__(self): return "X=" + str(self.X), "Y=" + str(self.Y) def __add__(self, other): if not isinstance(other, Point): raise Type...
0
2016-07-06T18:32:56Z
38,232,106
<p>You may have a comma instead of a plus. Look at</p> <pre><code>def __str__(self): return "X=" + str(self.X), "Y=" + str(self.Y) </code></pre> <p>Which should be</p> <pre><code>def __str__(self): return "X=" + str(self.X) + ", Y=" + str(self.Y) </code></pre> <p>At least on python3 when I correct it your c...
0
2016-07-06T19:19:10Z
[ "python" ]
measure length of silence at beginning of audio file (wav)
38,231,328
<p>I went through all post about measuring silence, unfortunately I have not been able to find a solution for my problem.</p> <p>I have about 3000 audio files. Each file is 10 second long and is a recording of someone saying a word at loud. </p> <p>I need to know how long it took for them to say the word (= silence b...
1
2016-07-06T18:34:12Z
38,231,854
<p>You could use the lovely <a href="https://github.com/jiaaro/pydub" rel="nofollow">pydub</a> library by @jiarro:</p> <pre><code>from pydub import AudioSegment from os import listdir from os.path import isfile, join def get_silence(audio, threshold, interval): "get length of silence in seconds from a wav file" ...
0
2016-07-06T19:02:57Z
[ "python", "audio", "unity3d" ]
How to get gevent websockets working?
38,231,357
<p>I am using <a href="https://bitbucket.org/noppo/gevent-websocket" rel="nofollow">geventwebsockets</a> but can't even get the example app to work. The code below gives me the error: </p> <blockquote> <p>Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py", line 884,...
0
2016-07-06T18:35:33Z
39,576,978
<p>Does it work for you </p> <p>if you add the echo_app</p> <pre><code>def echo_app(environ, start_response): websocket = environ.get("wsgi.websocket") if websocket is None: return http_handler(environ, start_response) try: while True: message = websocket.receive() ...
0
2016-09-19T15:36:40Z
[ "python", "websocket", "gevent" ]
Dividing a for loop for each process
38,231,420
<p>I have this code:</p> <pre><code>def loop(): alphabet = string.digits + string.letters for key in itertools.product(alphabet, repeat=6): ... </code></pre> <p>I am using 4 processes using this code: </p> <pre><code>if __name__ == '__main__': jobs = [] for i in range(4): p = multiprocess...
3
2016-07-06T18:38:40Z
38,231,630
<p>It sounds like each task only requires a small amount of data, so try using <code>multiprocessing.Pool</code> to create <a href="https://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers" rel="nofollow">a pool of workers</a>. It will start a pool of worker processes, and send a chunk of items to...
0
2016-07-06T18:50:05Z
[ "python", "multithreading", "multiprocessing" ]
Dividing a for loop for each process
38,231,420
<p>I have this code:</p> <pre><code>def loop(): alphabet = string.digits + string.letters for key in itertools.product(alphabet, repeat=6): ... </code></pre> <p>I am using 4 processes using this code: </p> <pre><code>if __name__ == '__main__': jobs = [] for i in range(4): p = multiprocess...
3
2016-07-06T18:38:40Z
38,231,780
<p>You need to divide the workload <em>beforehand</em> and pass it in to your function when you call <code>Process</code>. Generally speaking, this can be a hard problem, but in your case it's pretty trivial since you're just generating cartesian products -- simply slice off the first character and attach it separately...
1
2016-07-06T18:58:31Z
[ "python", "multithreading", "multiprocessing" ]
Combining pandas rows where for different columns different actions are required
38,231,462
<p>I am trying to combine certain rows but not with a common operation for all columns. I want the rows where pbheadid and wpadr are equal as in other row combined. Here the pickqty should be summed and the other columns should be copy pasted from the last entry or the highest pickdtm, but it is sorted so last entry wi...
2
2016-07-06T18:41:14Z
38,231,559
<p>IIUC you can do this:</p> <pre><code>In [21]: (df.groupby(['pbheadid','wpadr']) ....: .agg({'pickqty':'sum', 'artid':'last', 'pbcarid':'last', 'pickdtm':'last'}) ....: .reset_index() ....: ) Out[21]: pbheadid wpadr artid pickqty pbcarid pickdtm 0 76079450 523-370p 370944 1 61...
1
2016-07-06T18:46:29Z
[ "python", "pandas" ]