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
Python version of h=area() in Matlab
38,858,506
<p>I asked a related question yesterday and fortunately got my answer from jlarsch quickly. But now I am stuck with the next part, which starts with the <code>h=area()</code> line. I'd like to know the python version of the <code>area()</code> function, via which I will be able to set the colors. Could someone shed ...
-1
2016-08-09T19:01:18Z
38,858,647
<p>You probably want <code>plt.fill()</code>. A huge amount of graph types at <a href="http://matplotlib.org/gallery.html" rel="nofollow">Matplotlib Gallery</a></p>
0
2016-08-09T19:09:03Z
[ "python" ]
Python version of h=area() in Matlab
38,858,506
<p>I asked a related question yesterday and fortunately got my answer from jlarsch quickly. But now I am stuck with the next part, which starts with the <code>h=area()</code> line. I'd like to know the python version of the <code>area()</code> function, via which I will be able to set the colors. Could someone shed ...
-1
2016-08-09T19:01:18Z
38,858,722
<p>The pretty much exact equivalent of MATLAB's <a href="http://www.mathworks.com/help/matlab/ref/area.html" rel="nofollow">Area plot</a> is matplotlib's <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.stackplot" rel="nofollow">stackplot</a>. Here is the first MATLAB example from the above link re...
0
2016-08-09T19:14:16Z
[ "python" ]
How to use subprocess to interact with a python script
38,858,650
<p>I'm writing an IDE for python, in python, and need to use subprocess to intereact with a user's script.</p> <p>I am completely new to using subprocess and not sure what I'm doing here. I've created a test snippet representing what I'm trying to do:</p> <pre><code>from subprocess import Popen,PIPE,STDOUT import tki...
1
2016-08-09T19:09:13Z
38,858,764
<p>You have to flush stdout regularly, because, if the script is not connected to a terminal, the output is not automatically flushed:</p> <pre><code>import sys print("Hello World") print("Enter a Number: ") stdout.flush() inp = input() print(inp) </code></pre> <p>and you have to terminate the input by return <code>\...
2
2016-08-09T19:18:03Z
[ "python", "python-3.x", "subprocess", "python-3.4", "popen" ]
How to use subprocess to interact with a python script
38,858,650
<p>I'm writing an IDE for python, in python, and need to use subprocess to intereact with a user's script.</p> <p>I am completely new to using subprocess and not sure what I'm doing here. I've created a test snippet representing what I'm trying to do:</p> <pre><code>from subprocess import Popen,PIPE,STDOUT import tki...
1
2016-08-09T19:09:13Z
38,858,766
<p><strong>Remove <code>shell=True</code></strong>. Currently you are <em>not</em> executing the script at all, but just launching a <code>python</code> interactive interpreter.</p> <p>The problem is that <a href="http://stackoverflow.com/a/21029310/510937">when you use <code>shell=True</code> the way in which the fir...
2
2016-08-09T19:18:06Z
[ "python", "python-3.x", "subprocess", "python-3.4", "popen" ]
use loop to query overpass api
38,858,664
<p>I have a csv file of bounding boxes, that I loaded using pandas in python. The dataframe is <em>df</em> and the column name is <em>coord</em>. Does anyone know how I could create a loop to pass the list to my overpass api query?</p> <p>I tried this:</p> <pre><code>import time import overpass api = overpass.API(tim...
0
2016-08-09T19:09:54Z
38,860,535
<p>There are a couple of this wrong here mainly with your approach:</p> <ol> <li><code>coords = [df['coord'][0:10]]</code> is not required. You can replace that with a simpler <code>df['coord'].tolist()</code></li> <li>You are initializing <code>params</code> with an empty list and then immediately after with a string...
0
2016-08-09T21:14:03Z
[ "python", "api", "loops", "pandas", "overpass-api" ]
Adding defaultdicts together on key then dividing them
38,858,684
<p>I have a dictionary of 1000+ default dicts, I want to iterate through each default dict, sum them up on key and then divide by the count to get the average value per key.</p> <p>Each default dict has the same keys, i.e.</p> <pre><code>{'A': 0.0, 'B': 1.0, 'C': 1.0, 'D': 1.0, 'E': 1.0} {'A': 2.0, 'B': 1.2, 'C': 3.0...
2
2016-08-09T19:11:20Z
38,858,729
<p>Iterate over one dictionary's keys and values and add the value to the value of the corresponding key in the other dictionary.<br> Example:</p> <pre><code>dict1 = {'A': 0.0, 'B': 1.0, 'C': 1.0, 'D': 1.0, 'E': 1.0} dict2 = {'A': 2.0, 'B': 1.2, 'C': 3.0, 'D': 1.0, 'E': 3.0} for key,value in dict1.iteritems(): dic...
0
2016-08-09T19:15:09Z
[ "python", "dictionary" ]
Adding defaultdicts together on key then dividing them
38,858,684
<p>I have a dictionary of 1000+ default dicts, I want to iterate through each default dict, sum them up on key and then divide by the count to get the average value per key.</p> <p>Each default dict has the same keys, i.e.</p> <pre><code>{'A': 0.0, 'B': 1.0, 'C': 1.0, 'D': 1.0, 'E': 1.0} {'A': 2.0, 'B': 1.2, 'C': 3.0...
2
2016-08-09T19:11:20Z
38,858,837
<p>You can simplify this a bit using <code>collections.Counter</code>:</p> <pre><code>summed_dict = collections.Counter() for d in partial_dicts: summed_dict.update(d) # Use .viewitems or .iteritems instead of .items on Py2 average_dict = {k: v / len(partial_dicts) for k, v in summed_dict.items()} </code></pre>
3
2016-08-09T19:22:12Z
[ "python", "dictionary" ]
Adding defaultdicts together on key then dividing them
38,858,684
<p>I have a dictionary of 1000+ default dicts, I want to iterate through each default dict, sum them up on key and then divide by the count to get the average value per key.</p> <p>Each default dict has the same keys, i.e.</p> <pre><code>{'A': 0.0, 'B': 1.0, 'C': 1.0, 'D': 1.0, 'E': 1.0} {'A': 2.0, 'B': 1.2, 'C': 3.0...
2
2016-08-09T19:11:20Z
38,858,868
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html" rel="nofollow"><code>pandas.Series</code></a> to perform the <em>averaging</em> of both dictionary values, then convert the series back to a dictionary:</p> <pre><code>import pandas as pd a = pd.Series({'A': 2.0, 'B': 1....
3
2016-08-09T19:24:25Z
[ "python", "dictionary" ]
Adding defaultdicts together on key then dividing them
38,858,684
<p>I have a dictionary of 1000+ default dicts, I want to iterate through each default dict, sum them up on key and then divide by the count to get the average value per key.</p> <p>Each default dict has the same keys, i.e.</p> <pre><code>{'A': 0.0, 'B': 1.0, 'C': 1.0, 'D': 1.0, 'E': 1.0} {'A': 2.0, 'B': 1.2, 'C': 3.0...
2
2016-08-09T19:11:20Z
38,858,907
<p>How about using a dictionary comprehension with <code>sum</code>:</p> <pre><code>d1 = {'A': 0.0, 'B': 1.0, 'C': 1.0, 'D': 1.0, 'E': 1.0} d2 = {'A': 2.0, 'B': 1.2, 'C': 3.0, 'D': 1.0, 'E': 3.0} dicts = {"d1": d1, "d2": d2} n = len(dicts) res = {k: sum(d[k] for d in dicts.values()) / n for k in d1} # {'A': 1.0, 'B': ...
5
2016-08-09T19:26:37Z
[ "python", "dictionary" ]
Adding defaultdicts together on key then dividing them
38,858,684
<p>I have a dictionary of 1000+ default dicts, I want to iterate through each default dict, sum them up on key and then divide by the count to get the average value per key.</p> <p>Each default dict has the same keys, i.e.</p> <pre><code>{'A': 0.0, 'B': 1.0, 'C': 1.0, 'D': 1.0, 'E': 1.0} {'A': 2.0, 'B': 1.2, 'C': 3.0...
2
2016-08-09T19:11:20Z
38,858,931
<p>Regarding your data as a dict of dicts, then this is how I would do it (pretty functional approach):</p> <pre><code> d = {1: {'A': 0.0, 'B': 1.0, 'C': 1.0, 'D': 1.0, 'E': 1.0}, 2: {'A': 2.0, 'B': 1.2, 'C': 3.0, 'D': 1.0, 'E': 3.0}} import functools def add_dicts(d1, d2): return {k:d1[k]+d2[k] for k in d1} d...
1
2016-08-09T19:28:40Z
[ "python", "dictionary" ]
Ignore missing file while downloading with Python urllib2
38,858,697
<p><strong>Issue:</strong> As the title states I am downloading data via ftp from NOAA based on the year and the day. I have configured my script to go through a range of years and download data for each day. However the script is getting hung up on days where no file exists. What happens is it just keeps reloading the...
1
2016-08-09T19:12:22Z
38,858,990
<p>I guess when you stand up walk away and get some coffee things become clear. Apparently something was getting hung up in my while statement (still unsure why). When I took that out and added <em>pass</em> instead of <em>continue</em> it behaved correctly.</p> <p>Here's what it looks like now:</p> <pre><code>for fn...
1
2016-08-09T19:31:55Z
[ "python", "python-2.7", "urllib2" ]
Ignore missing file while downloading with Python urllib2
38,858,697
<p><strong>Issue:</strong> As the title states I am downloading data via ftp from NOAA based on the year and the day. I have configured my script to go through a range of years and download data for each day. However the script is getting hung up on days where no file exists. What happens is it just keeps reloading the...
1
2016-08-09T19:12:22Z
38,859,032
<p>On the <code>except</code>, use <code>pass</code> instead of <code>continue</code>, since it can only be used inside loops(<code>for</code>, <code>while</code>). </p> <p>With that you won't need to do handle the missing files, since Python will just ignore the error and keep going.</p>
1
2016-08-09T19:34:08Z
[ "python", "python-2.7", "urllib2" ]
Python - Faster way to load several images?
38,858,704
<p>one of the tasks on my project is to load a dataset (chars74k) and set the label for each image. In this implementation, I already have a matrix with other images and a list with their respective labels. In order to do the task, I wrote the following code:</p> <pre><code>#images: (input/output)matrix of images #lab...
2
2016-08-09T19:13:08Z
38,862,273
<p>After some research, I was able to improve the code in this way:</p> <pre><code>def loadChars74k(images, labels, path): # list of directories dirlist = [ item for item in os.listdir(path) if os.path.isdir(os.path.join(path, item)) ] # for each subfolder, open all files, append to list of images x and s...
0
2016-08-10T00:03:27Z
[ "python", "numpy" ]
multiple python UDP socket & UI
38,858,802
<p>I am very new to python and still in reading phase. I have two question here to discuss. I need to develop an python base user interface using <code>tkinter</code> which should run on Raspberry Pi2. On the background process I need to create multiple UDP socket server &amp; clients which is also python based. </p> ...
0
2016-08-09T19:20:25Z
38,859,214
<ol> <li><p>Python can use <code>select</code> too: see <a href="https://docs.python.org/3.4/library/select.html?highlight=select.select#select.select" rel="nofollow">https://docs.python.org/3.4/library/select.html?highlight=select.select#select.select</a> The <code>FD_SET</code> stuff is handled for you; you just prov...
1
2016-08-09T19:45:57Z
[ "python", "sockets", "widget", "udp" ]
Django: How to unit test Update Views/Forms
38,859,266
<p>I'm trying to unit test my update forms and views. I'm using Django Crispy Forms for both my Create and Update Forms. UpdateForm inherits CreateForm and makes a small change to the submit button text. The CreateView and UpdateView are very similar. They have the same model, template, and success_url. They differ in ...
0
2016-08-09T19:48:51Z
38,860,446
<p>When pre-populating a <code>ModelForm</code> with an object that has already been created you can use the <code>instance</code> keyword argument to pass the object to the form.</p> <pre><code>form = SomeForm(instance=my_obj) </code></pre> <p>This can be done in a test, such as in the OP&lt; or in a view to edit an...
1
2016-08-09T21:07:28Z
[ "python", "django", "forms", "unit-testing" ]
Extracting text without tags of HTML with Beautifulsoup Python
38,859,271
<p>I try to extract this part of text but i don't figure it out how to do it, i'm working with several html files locally.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><cod...
0
2016-08-09T19:49:05Z
38,859,382
<p>Now you can put HTML_TEXT as the html you got from scrapping the url.</p> <pre><code>y = BeautifulSoup(HTML_TEXT) c = y.find('body').findAll(text=True, recursive=False) for i in c: print i </code></pre>
0
2016-08-09T19:56:28Z
[ "python", "web-scraping", "beautifulsoup" ]
Logistic regression multiclass classification with Python API
38,859,302
<p>currently the Python API does not yet support multi class classification within Spark, but will in the future as it is described on the Spark page <a href="http://spark.apache.org/docs/latest/mllib-linear-methods.html#classification" rel="nofollow">1</a>. </p> <p>Is there any release date or any chance to run it wi...
1
2016-08-09T19:51:19Z
38,860,140
<p>scikit-learn's <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html" rel="nofollow">LogisticRegression</a> offers a <code>multi_class</code> parameter. From the docs:</p> <blockquote> <p>Multiclass option can be either ‘ovr’ or ‘multinomial’. If the option...
3
2016-08-09T20:47:09Z
[ "python", "classification", "logistic-regression" ]
Python minidom: #text node disappears when appending it to new parent node
38,859,341
<p>I have XML that looks like this:</p> <pre><code>&lt;example&gt; &lt;para&gt; &lt;phrase&gt;child_0&lt;/phrase&gt; child_1 &lt;phrase&gt;child_2&lt;/phrase&gt; &lt;/para&gt; &lt;/example&gt; </code></pre> <p>and I want it to look like this:</p> <pre><code>&lt;foo&gt; &lt;ph...
0
2016-08-09T19:54:06Z
39,174,563
<p>Well, here I am, answering my own question.</p> <p>The <code>appendChild()</code> function <strong>removes</strong> the child node from the <code>&lt;para&gt;</code> list of nodes, so you will be effectively skipping every other element as the index gets out of sync with each iteration. The solution is to append a ...
0
2016-08-26T21:00:55Z
[ "python", "xml", "minidom" ]
Break out of loop if GPIO doesn't toggle in time
38,859,353
<p>I'm changing some inputs to a device with relays, and I'm expecting at some point to break the firmware. The question is, when will this happen?</p> <p>So, to determine if the firmware breaks, I'm monitoring some LEDs that normally blink during normal operation. I know that they will lock up in whatever state the...
0
2016-08-09T19:54:51Z
38,859,605
<p>From the <a href="https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/" rel="nofollow">gpio</a> module, create a threaded callback function that fires every time a rising (or falling, etc...) edge is detected.</p> <p>Then using <a href="https://docs.python.org/3/library/signal.html#signal.alarm" rel="nofoll...
0
2016-08-09T20:12:11Z
[ "python", "timer", "raspberry-pi", "interrupt", "gpio" ]
Tweepy - Multiple User Search
38,859,362
<p>Trying to perform what I thought was a very basic exercise. I have a list of 7000+ customers and I want to import some of their attributes from twitter. I am trying to figure out how to input several user names into my tweepy query, but I am not getting any luck with below. </p> <pre><code>#!/usr/bin/python import ...
0
2016-08-09T19:55:16Z
38,859,454
<p>You will have to do it in a loop, you will make list of users and get user instance for all one by one in loop.</p> <pre><code>#!/usr/bin/python import tweepy import csv #Import csv import os # Consumer keys and access tokens, used for OAuth consumer_key = 'MINE' consumer_secret = 'MINE' access_token = 'MINE' acce...
1
2016-08-09T20:02:05Z
[ "python", "python-2.7", "twitter", "tweepy", "api-design" ]
Python groupby apply returning odd dataframe
38,859,397
<p>Here is my function:</p> <pre><code>def calculate_employment_two_digit_industry(df): df['intersection'] = df['racEmpProb'] * df['wacEmpProb'] df['empProb'] = df['intersection'] / df['intersection'].sum() df['newEmp'] = df['empProb'] * df['Emp'] df = df[['h_zcta', 'w_zcta', 'indID', 'newEmp', 'empPr...
2
2016-08-09T19:57:47Z
38,859,602
<p>You need <code>.reset_index(drop=True)</code></p> <p>That is:</p> <pre><code>final = testDf.groupby(['h_zcta', 'w_zcta', '1_digit']).apply( calculate_employment_two_digit_industry).reset_index(drop=True) &gt;&gt;&gt; final.index RangeIndex(start=0, stop=4, step=1) </code></pre>
2
2016-08-09T20:12:05Z
[ "python", "pandas", "group-by" ]
class which reads the file content
38,859,426
<p>I'd like to write class which reads the *.csv file and parse it using the pandas library. I'm wondering where I should initialize df. </p> <pre><code>#!/usr/bin/env python import pandas as pd import os class ParseDataBase(object): def __init__(self, name_file): self.name_file = name_file ...
2
2016-08-09T19:59:49Z
38,859,481
<p>the attribute <code>df</code> gets assigned in the <code>read_file</code> method. You are trying to access that attribute prior to it existing.</p> <p>I'd do this:</p> <pre><code>#!/usr/bin/env python import pandas as pd import os class ParseDataBase(object): def __init__(self, name_file): ...
2
2016-08-09T20:03:36Z
[ "python", "pandas" ]
class which reads the file content
38,859,426
<p>I'd like to write class which reads the *.csv file and parse it using the pandas library. I'm wondering where I should initialize df. </p> <pre><code>#!/usr/bin/env python import pandas as pd import os class ParseDataBase(object): def __init__(self, name_file): self.name_file = name_file ...
2
2016-08-09T19:59:49Z
38,859,483
<p>You aren't assigning <code>self.df</code> unless you run <code>read_file()</code>, which you aren't.</p> <pre><code>def main(): x = ParseDataBase('something.csv') x.read_file() x.dispaly_file() </code></pre>
1
2016-08-09T20:03:43Z
[ "python", "pandas" ]
python for ele in list[:] and for ele in list difference?
38,859,472
<p>So there's a problem in leetcode that's pretty simple but the solution is incorrect for the second: (OG question: Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.</p> <p>For example, given nums = [0, 1, 0, 3, 12], after calling you...
-1
2016-08-09T20:02:49Z
38,862,004
<p>You can both not copy the list and not modify the list while it's being looped over:</p> <pre><code>class Solution(object): def moveZeroes(self, numbers): """ :type numbers: List[int] :rtype: void Do not return anything, modify numbers in-place instead. """ k = 0 ...
0
2016-08-09T23:29:10Z
[ "python", "list", "for-loop", "data-structures" ]
python for ele in list[:] and for ele in list difference?
38,859,472
<p>So there's a problem in leetcode that's pretty simple but the solution is incorrect for the second: (OG question: Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.</p> <p>For example, given nums = [0, 1, 0, 3, 12], after calling you...
-1
2016-08-09T20:02:49Z
38,862,072
<p>You can't modify a list while looping over it. It's illegal in Python. </p> <p><code>[:]</code> makes an independent copy of the list to loop over.</p> <p>But the question requires you to not make a copy of the list, so both solutions are incorrect. </p> <p>I won't tell you exactly how to fix it because I want yo...
0
2016-08-09T23:37:05Z
[ "python", "list", "for-loop", "data-structures" ]
Installing guppy with pip3 issues
38,859,593
<p>I am trying to install <a href="https://pypi.python.org/pypi/guppy/" rel="nofollow">guppy</a>. My program uses python3 so I must use pip3 exclusively. When I run:</p> <pre><code>pip3 install guppy </code></pre> <p>I get:</p> <pre><code>src/sets/sets.c:77:1: error: expected function body after function declarator ...
1
2016-08-09T20:11:10Z
38,860,927
<p>Unfortunately it seems that <code>guppy</code> library works only for Python 2.x. An alternative could be <a href="http://mg.pov.lt/objgraph/" rel="nofollow">objgraph</a></p>
1
2016-08-09T21:43:51Z
[ "python", "python-3.x" ]
Linking to brew openssl via python virtualenvwrapper
38,859,693
<p>Running <code>openssl version</code> returns the standard openssl on OS El Capitan, <code>OpenSSL 0.9.8zh</code> in <code>/usr/bin/openssl</code>.</p> <p>I've installed the latest via brew <code>brew install openssl</code>. Various post/articles recommended manually symlinking to <code>/usr/local/bin/openssl</code>...
0
2016-08-09T20:18:30Z
38,948,507
<p>In the end I used <code>brew install python3 --with-brewed-openssl</code>, then ran <code>brew link python3</code> to symlink it to <code>/usr/local/bin/python3</code> and then used <code>mkvirtualenv --python=/usr/local/bin/python3 [projectname]</code> to use the brewed python(that uses the brewed openssl), now whe...
0
2016-08-15T02:23:12Z
[ "python", "ssl", "openssl", "virtualenv", "homebrew" ]
Joining parts of lists with specific tags and creating a new list in Python
38,859,823
<p>I am new to Python, and I faced with a problem. I used StanfordNER in Python to tag a text , the output of the name entities are like the following:</p> <pre><code>[('Micheal', 'PERSON'), ('Jaf', 'PERSON'), ('Bin', 'PERSON'), ('Aloo', 'PERSON'), ('and', 'O'), ('Purno', 'PERSON'), ('Yusgiantoro', 'PERSON'), (...
1
2016-08-09T20:27:02Z
38,860,014
<p>What you have posted in the question is not a valid python object. It is most probably a <code>str</code> version of something. The snippet below assumes the first element of every word is converted to a string.</p> <p>The idea is to use <code>itertools.groupby</code>. It groups adjacent elements according a given ...
2
2016-08-09T20:38:51Z
[ "python", "list" ]
Joining parts of lists with specific tags and creating a new list in Python
38,859,823
<p>I am new to Python, and I faced with a problem. I used StanfordNER in Python to tag a text , the output of the name entities are like the following:</p> <pre><code>[('Micheal', 'PERSON'), ('Jaf', 'PERSON'), ('Bin', 'PERSON'), ('Aloo', 'PERSON'), ('and', 'O'), ('Purno', 'PERSON'), ('Yusgiantoro', 'PERSON'), (...
1
2016-08-09T20:27:02Z
38,860,033
<p>you could do</p> <pre><code>last=None grouped=[] for word,t in myList: if t==last: grouped[-1].append(word) else: grouped.append([t,word]) last=t person_names=[" ".join(i[1:]) for i in grouped if i[0]=="PERSON"] </code></pre>
0
2016-08-09T20:40:16Z
[ "python", "list" ]
Multiple forms submitting with single view - Django
38,859,842
<p>I have two ModelForms submitting from a single view. One model is a ForeignKey of another. At this point, the form will add to the DB, but not as expected. Instead of adding a Course and a Section (with course field populated with the newly-created Course), I'm getting a Course and Section that are linked, but with ...
0
2016-08-09T20:27:58Z
38,860,097
<p>Solution:</p> <p>Instead of using the <code>instance</code> argument, use <code>prefix</code>:</p> <pre><code>def IndexView(request,Course_id,Section_id): if request.method == "GET": this_course = Course.objects.get(pk=Course_id) active_courses = Course.objects.all().filter(Active=True).exclud...
1
2016-08-09T20:44:33Z
[ "python", "django", "forms", "django-forms" ]
Multiple forms submitting with single view - Django
38,859,842
<p>I have two ModelForms submitting from a single view. One model is a ForeignKey of another. At this point, the form will add to the DB, but not as expected. Instead of adding a Course and a Section (with course field populated with the newly-created Course), I'm getting a Course and Section that are linked, but with ...
0
2016-08-09T20:27:58Z
38,860,098
<p>Both models have a <code>Name</code> field, so both forms contain an input with identical <code>name</code> attribute. When Django encounters two POST parameters with the same name, it binds the last one's value to all fields by that name. Long story short - change field names in your models so they are different.</...
0
2016-08-09T20:44:39Z
[ "python", "django", "forms", "django-forms" ]
Multiple forms submitting with single view - Django
38,859,842
<p>I have two ModelForms submitting from a single view. One model is a ForeignKey of another. At this point, the form will add to the DB, but not as expected. Instead of adding a Course and a Section (with course field populated with the newly-created Course), I'm getting a Course and Section that are linked, but with ...
0
2016-08-09T20:27:58Z
38,860,105
<p>Since your <code>Course</code> and <code>Section</code> both have an attribute called <code>Name</code>, I am betting that your form has two fields with the attributes <code>id = "id_Name"</code> and <code>name = "Name"</code>.</p>
0
2016-08-09T20:44:59Z
[ "python", "django", "forms", "django-forms" ]
Python: Read Data file with variable number of rows per observation
38,859,916
<p>I have to work with a dataset that contains multiple lines per observation. The number of rows per observation can vary. The file is structured so that information is not repeated. </p> <p>The file contains a segment ID, which relates the output to a specific piece of information. Here is a sample of the file l...
0
2016-08-09T20:33:39Z
38,860,698
<p>Here is a quick solution using <code>Pandas</code> </p> <pre><code>import pandas as pd df = pd.DataFrame() with open("file.txt", "r") as f: f.next() for row,line in enumerate(f): info = line.split() if info[0] == '1': client = info[1] else: df[row] = [clien...
1
2016-08-09T21:24:49Z
[ "python", "data-files" ]
Skipping 'FILE' which didn't exist, or couldn't be read error
38,860,016
<p>I'm trying to create a workflow where I take a directory that contains a list of input files and runs them through a command line tool and outputs the results into an output directory. It should be really simple, and I have gotten it to work ... mostly.</p> <p>The problem is that whenever I give it a input <strong>...
0
2016-08-09T20:38:58Z
38,860,885
<p>Try changing this:</p> <pre><code>fastq_directory = os.listdir("{}".format(inputDir)) fastq_files = [] for file in fastq_directory: fastq_files.append(file) </code></pre> <p>To this:</p> <pre><code>fastq_directory = os.listdir("{}".format(inputDir)) fastq_files = [] for file in fastq_directory: fa...
2
2016-08-09T21:40:20Z
[ "python", "workflow", "bioinformatics" ]
python can't use a property defined in the super (father) class
38,860,053
<p>This is my code</p> <pre><code>class ElasticsearchController(object): def __init__(self): self.es = Elasticsearch(['blabla'], port=9200) class MasterDataIndexController(ElasticsearchController): def __init__(self): self.indexName = "bbbbb" def search(self, query): return s...
1
2016-08-09T20:41:29Z
38,860,085
<p>You are not initialising your super classes.</p> <pre><code>class ElasticsearchController(object): def __init__(self): self.es = Elasticsearch(['a.b.c.d'], port=1234) class MasterDataIndexController(ElasticsearchController): def __init__(self): super(MasterDataIndexController, self).__i...
4
2016-08-09T20:43:33Z
[ "python" ]
python can't use a property defined in the super (father) class
38,860,053
<p>This is my code</p> <pre><code>class ElasticsearchController(object): def __init__(self): self.es = Elasticsearch(['blabla'], port=9200) class MasterDataIndexController(ElasticsearchController): def __init__(self): self.indexName = "bbbbb" def search(self, query): return s...
1
2016-08-09T20:41:29Z
38,860,090
<p>You can't use <code>super</code> like that. <code>super</code> will give you access to the super class, but you should not use it as a shortcut for <code>self</code>. Depending if you use python or python 3, you can call <code>super(MyClass, self)</code> or just <code>super()</code>. You can use this during initiali...
3
2016-08-09T20:43:51Z
[ "python" ]
Create random numpy matrix of same size as another.
38,860,095
<p>This question <a href="http://stackoverflow.com/questions/35967907/how-to-make-a-new-numpy-array-same-size-as-a-given-array-and-fill-it-with-a-scal">here</a> was useful, but mine is slightly different. </p> <p>I am trying to do something simple here, I have a numpy matrix <strong>A</strong>, and I simply want to cr...
1
2016-08-09T20:44:18Z
38,860,153
<p><code>np.random.randn</code> takes the shape of the array as its input which you can get directly from the <code>shape</code> property of the first array. You have to unpack <code>a.shape</code> with the <a class='doc-link' href="http://stackoverflow.com/documentation/python/4282/list-destructuring-aka-packing-and-...
2
2016-08-09T20:47:44Z
[ "python", "arrays", "numpy", "random" ]
How to assign multiple values to an array of strings in python
38,860,135
<p>I'm reading a file line by line and am trying to parse a part of each line and do stuff with it. the Info that I'm trying to parse are 25 strings</p> <p>I was trying to do </p> <pre><code>for i in info: Consequence=i[0] IMPACT=i[1] . . HGNC_ID = i[24] </code></pre> <p>but obviously there's a better ...
-2
2016-08-09T20:47:02Z
38,860,253
<p>There does not seem to be much wrong with your first version of the code. I don't know why you think there "obviously" should be a better way.</p> <p>One thing you can do to make this a little clearer is:</p> <pre><code>if len(info) == 25: Consequence, IMPACT , . . ., HGNC_ID = info elif len(info) == 24: ...
0
2016-08-09T20:54:44Z
[ "python", "arrays", "for-loop" ]
Python can't import WMI under special circumstance
38,860,185
<p>I've created a standalone exe Windows service written in Python and built with pyInstaller. When I try to import wmi, an exception is thrown. </p> <p>What's really baffling is that I can do it without a problem if running the code in a foreground exe, or a foreground python script, or a python script running as a ...
1
2016-08-09T20:50:20Z
38,879,523
<p>I tried solving this countless ways. In the end, I threw in the towel and had to just find a different means of achieving the same goals I had with wmi. </p> <p>Apparently that invalid syntax error is thrown when trying to create an object with an invalid "moniker name", which can simply mean the service, applica...
0
2016-08-10T17:03:13Z
[ "python", "service", "wmi", "pyinstaller" ]
Which package to install based only on import line
38,860,246
<p>I am very new to Python, and I am attempting to reproduce an <a href="https://www.quantstart.com/articles/Forex-Trading-Diary-1-Automated-Forex-Trading-with-the-OANDA-API" rel="nofollow">example</a> (not necessary to answer the question). If all I have is <code>import threading</code> from within the code I assumed ...
0
2016-08-09T20:54:23Z
38,860,324
<p>The first hit on google (search: python threading) actually gave me:</p> <p><a href="https://docs.python.org/2/library/threading.html" rel="nofollow">https://docs.python.org/2/library/threading.html</a> (the URL itself already indicate it)</p> <p>This means it's a library module so it should be already available t...
1
2016-08-09T20:59:39Z
[ "python" ]
How to set chunk size of netCDF4 in python?
38,860,344
<p>I can see the default chunking setting in netCDF4 library, but I have no idea how to change the chunk size.</p> <pre><code>from netCDF4 import Dataset volcgrp = Dataset('datasets/volcano.nc', 'r') data = volcgrp.variables['abso4'] print data.shape print data.chunking() &gt;(8, 96, 192) &gt;[1, 96, 192] </code><...
1
2016-08-09T21:00:54Z
38,873,786
<p>You can use <a href="http://xarray.pydata.org/en/stable/dask.html" rel="nofollow">xarray</a> to read the netcdf file and set chunks, e.g. </p> <pre><code>import xarray as xr ds = xr.open_dataset('/datasets/volcano.nc', chunks={'time': 10}) </code></pre>
2
2016-08-10T12:42:56Z
[ "python", "netcdf", "chunks", "chunking", "netcdf4" ]
pandas plot a specific column to be used as both x and y axis?
38,860,428
<p>I have a dataframe that looks like the below:</p> <p>I want to <code>plot company_id</code> as the x axis and <code>count(company_id)</code> for the y axis. I also want to stack it by category of <code>open</code> and <code>close</code>.</p> <p>The code doesnt show any output and runs infinitely.</p> <pre><code>d...
1
2016-08-09T21:06:16Z
38,861,142
<p>If you're able to use <code>seaborn</code> as suggested in a comment you could do this:</p> <pre><code>import seaborn as sns, matplotlib.pyplot as plt df = {'company_id': {0: 255, 1: 255, 2: 182, 3: 182, 4: 81}, 'time': {0: 1379312026, 1: 1379312086, 2: 1379312926, 3: 1379313046, 4: 1379314006}, 'per...
2
2016-08-09T22:03:24Z
[ "python", "pandas", "plot" ]
Python math.pow() losing calculation percision
38,860,496
<p>My code:</p> <pre><code>import math def calculate(operator, firstValue, secondValue): if operator == '^': toReturn = math.pow(firstValue, secondValue) . . . return toReturn . . . new = calculate('^', 19, 19) print(' is ' + str(new)) workingStack.append(int(new)) print('New stack is ' + str(...
-2
2016-08-09T21:10:50Z
38,860,544
<p><code>math.pow</code> does a floating point calculation with finite precision, use the power-operator instead:</p> <pre><code>def calculate(operator, firstValue, secondValue): if operator == '^': toReturn = firstValue ** secondValue return toReturn </code></pre>
3
2016-08-09T21:14:43Z
[ "python", "precision" ]
How to install a custom, local Python Package with Anaconda?
38,860,547
<p>I have Anaconda2 running smoothly on Eclipse's PyDev environment. </p> <p>I have received a custom package from a colleague in the form of a folder with a "library" sub-directory that contains many ".pyc" files (which I presume are the function files) and a "<strong>init</strong>.py" file. But no matter what I do, ...
0
2016-08-09T21:14:52Z
38,860,631
<p>Pyc are precompiled files, you dont need them. You should simply import package folder with</p> <pre><code>import folder-name </code></pre>
0
2016-08-09T21:19:41Z
[ "python", "eclipse", "local", "pydev", "anaconda" ]
Openpyxl Copy Time, returns -1
38,860,565
<p>I am trying to great an excel file that has is the combination of multiple excel files. However, when I copy a cell with a value 00:00, and append it to the master excel file, excel thinks the time is for the year 1899?</p> <p>Here is my code:</p> <pre><code>def excel_graphs_all(day, users): chart_wb = Workboo...
-1
2016-08-09T21:16:02Z
38,865,669
<p>What do you mean by value <code>00:00</code>? Excel uses formatting and not typing for dates and times. From the specification: </p> <blockquote> <p>When using the 1900 date system, which has a base date of 30th December 1899, a serial date- time of 1.5 represents midday on the 31st December 1899</p> </blockq...
0
2016-08-10T06:20:52Z
[ "python", "excel", "python-2.7", "datetime", "openpyxl" ]
Why not serving static files with Django in a production environment?
38,860,601
<p>I came across the following example for <code>settings.py</code>:</p> <pre><code>if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) </code></pre> <p>and was told:</p> <blockquote> <p>The static() helper function is suitable for development but not for productio...
2
2016-08-09T21:17:59Z
38,861,145
<p>Django is not very fast or efficient for serving static files. To quote the Django docs, "This method is grossly inefficient and probably insecure, so it is unsuitable for production." It is better to use tools that are specifically designed for serving static content. There are extensive instructions for how to set...
3
2016-08-09T22:03:30Z
[ "python", "django", "apache", "static", "settings" ]
Python CSV File writing contents to file
38,860,662
<p>I am trying to write and append values to CSV file. Whenever I am executing the script Header values are printing multipletimes. When I open the excel sheet I see</p> <p><img src="http://i.stack.imgur.com/Hsg0l.png" alt="enter image description here"></p> <p>Instead of</p> <p><img src="http://i.stack.imgur.com/2f...
1
2016-08-09T21:22:42Z
38,861,000
<p>If you're executing the same code multiple times, you'll end up with multiple calls to <code>writer.writeheader()</code>. This is the cause for the header being repeated in your resulting file.</p> <p>Instead of calling the code multiple times (and opening the same file over and over, appending each time), you coul...
0
2016-08-09T21:49:22Z
[ "python", "csv" ]
Multiple kwargs in a function call?
38,860,676
<p>I have a simple function which is called like this:</p> <pre><code>arbitrary_function(**kwargs1, **kwargs2, **kwargs3) </code></pre> <p>It seems to compile fine on my local installation (python 3.5.1) but throws a SyntaxError when I compile it on a docker with python 3.4.5.</p> <p>I'm not too sure why this behavi...
4
2016-08-09T21:23:43Z
38,860,834
<p>That's a new feature introduced in Python 3.5. If you have to support Python 3.4, you're basically stuck with the <code>update</code> loop.</p> <p>People have their own favored variations on how to combine multiple dicts into one, but the only one that's really a major improvement over the <code>update</code> loop ...
1
2016-08-09T21:35:58Z
[ "python" ]
Multiple kwargs in a function call?
38,860,676
<p>I have a simple function which is called like this:</p> <pre><code>arbitrary_function(**kwargs1, **kwargs2, **kwargs3) </code></pre> <p>It seems to compile fine on my local installation (python 3.5.1) but throws a SyntaxError when I compile it on a docker with python 3.4.5.</p> <p>I'm not too sure why this behavi...
4
2016-08-09T21:23:43Z
38,861,724
<p>One workaround <a href="https://www.python.org/dev/peps/pep-0448/#rationale" rel="nofollow">mentioned in the rationale for PEP448</a> (which introduced that Python feature) is to use <a href="https://docs.python.org/3/library/collections.html#collections.ChainMap" rel="nofollow"><code>collections.ChainMap</code></a>...
0
2016-08-09T22:58:28Z
[ "python" ]
What is Pandas doing here that my indexes [0] and [1] refer to the same value?
38,860,772
<p>I have a dataframe with these indices and values:</p> <pre><code>df[df.columns[0]] 1 example 2 example1 3 example2 </code></pre> <p>When I access df[df.columns[0]][2], I get "example1". Makes sense. That's how indices work. </p> <p>When I access df[df.columns[0]], however...
3
2016-08-09T21:31:02Z
38,860,909
<p>You are probably causing pandas to switch between <code>.iloc</code> (index based) and <code>.loc</code> (label based) indexing.</p> <p>All arrays in Python are 0 indexed. And I notice that indexes in your DataFrame are starting from 1. So when you run <code>df[df.column[0]][0]</code> pandas realizes that there is ...
5
2016-08-09T21:42:20Z
[ "python", "pandas" ]
Tkinter mysterious binding issue
38,860,828
<p>I have a bound key combination :</p> <pre><code>self.parent.bind_all('&lt;Control-n&gt;', self.next_marked) </code></pre> <p>It is supposed to take me to the next tag in a text widget whose parent is a frame.</p> <pre><code>def next_marked(self, skip=False): print (len(self.text.tag_ranges('definition'))) ...
2
2016-08-09T21:35:05Z
38,861,328
<p>The problem seems to be that <code>&lt;Control-n&gt;</code> is already bound to "go to next line" on the <code>Text</code> class, and if there are multiple bindings, <a href="http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm" rel="nofollow">they will all be executed, in a specific order</a>:</p> <blockq...
4
2016-08-09T22:18:52Z
[ "python", "python-2.7", "tkinter" ]
compatible Android AudioEncoder and pydub decoder
38,861,012
<p>I am recording an audio in android in mp3 format and to do that I am using <code>MPEG_4</code> as an Output Format while <code>AAC</code> as an AudioEncoder and It does record an audio.</p> <p>The problem is when I am using that file for further processing in python pydub it could not decode the audio amd gives me ...
0
2016-08-09T21:50:33Z
38,918,790
<p>ffmpeg returning an error means something went wrong while ffmpeg was running (so it's not an issue with finding the ffmpeg executable)</p> <p>pydub uses creates temporary files and passes the path to those files to ffmpeg, so it's possible that some kind of file system restriction is the reason.</p> <p>You can <a...
0
2016-08-12T13:07:31Z
[ "android", "python", "audio", "ffmpeg", "pydub" ]
How can I test the standard input and standard output in Python Script with a Unittest test?
38,861,101
<p>I'm trying to test a Python script (2.7) where I work with the standar input (readed with raw_input() and writed with a simple print) but I don't find how do this and I'm sure that this issue is very simple.</p> <p>This is a very very very resume code of my script:</p> <pre><code>def example(): number = raw_in...
3
2016-08-09T21:59:04Z
38,861,365
<p>Typical techniques involve mocking the standard <code>sys.stdin</code> and <code>sys.stdout</code> with your desired items. If you do not care for Python 3 compatibility you can just use the <code>StringIO</code> module, however if you want forward thinking and is willing to restrict to Python 2.7 and 3.3+, support...
3
2016-08-09T22:21:38Z
[ "python", "io", "python-unittest" ]
Regular expressions in python to match Twitter handles
38,861,170
<p>I'm trying to use regular expressions to capture all Twitter handles within a tweet body. The challenge is that I'm trying to get handles that</p> <ol> <li>Contain a specific string</li> <li>Are of unknown length</li> <li>May be followed by either <ul> <li>punctuation</li> <li>whitespace</li> <li>or the end of st...
1
2016-08-09T22:05:25Z
38,861,225
<p>It seems you are trying to match strings starting with <code>@</code>, then having 0+ word chars, then <code>handle</code>, and then again 0+ word chars.</p> <p>Use</p> <pre><code>r'@\w*handle\w*' </code></pre> <p>or - to avoid matching <code>@</code>+word chars in emails:</p> <pre><code>r'\B@\w*handle\w*' </cod...
2
2016-08-09T22:10:36Z
[ "python", "regex", "twitter" ]
Regular expressions in python to match Twitter handles
38,861,170
<p>I'm trying to use regular expressions to capture all Twitter handles within a tweet body. The challenge is that I'm trying to get handles that</p> <ol> <li>Contain a specific string</li> <li>Are of unknown length</li> <li>May be followed by either <ul> <li>punctuation</li> <li>whitespace</li> <li>or the end of st...
1
2016-08-09T22:05:25Z
38,861,247
<p>Matches only handles that contain this range of characters -> <code>/[a-zA-Z0-9_]/</code>.</p> <pre><code>s = "@123handle what is your problem @handle123?" print re.findall(r'\B(@[\w\d_]+)', s) &gt;&gt;&gt; ['@123handle', '@handle123'] s = '@The quick brown fox@jumped over the LAAZY @_dog.' &gt;&gt;&gt; ['@The', '@...
1
2016-08-09T22:11:58Z
[ "python", "regex", "twitter" ]
Find the index of certain values in a data frame and put it as a separate column
38,861,180
<p>In the following data frame DF, Users have different values for Movies and Exist columns. For example, user 2 has 10 values and User 5 has 9 values. I want the position of the first 'True' value for Exist column (relative to the user vector length) divided to the user vector length to be put in a separate data fram...
2
2016-08-09T22:06:07Z
38,861,235
<p><strong><em>Option 1</em></strong></p> <pre><code>def first_ratio(x): x = x.reset_index(drop=True) i = x.any() * (x.idxmax() + 1.) l = len(x) return i / l df.groupby('User').Exist.apply(first_ratio).rename('Location').to_frame() User 2 0.500000 5 0.888889 Name: Exist, dtype: float64 </code><...
3
2016-08-09T22:10:57Z
[ "python", "pandas", "dataframe" ]
Comparing two CSV files and searching for similar items
38,861,232
<p>I'm still new to Python and I'm trying to adapt this code to work for me from <a href="http://stackoverflow.com/questions/5268929/python-comparing-two-csv-files-and-searching-for-similar-items">this post</a>. </p> <p>The difference between that post and what I'm looking for is that I am looking to concatenate the e...
2
2016-08-09T22:10:54Z
38,861,450
<p>Use pandas.read_csv and merge on "Signature" columns </p> <pre><code>import pandas as pd hosts_df = pd.read_csv("hosts.csv ") masterlist_df = pd.read_csv("masterlist.csv") results = masterlist_df.merge(hosts_df, on="Signature", how="outer") results.to_csv("results.csv") </code></pre>
2
2016-08-09T22:30:09Z
[ "python", "csv", "concatenation" ]
How to join integers intervals in python?
38,861,290
<p>I have used the module intervals (<a href="http://pyinterval.readthedocs.io/en/latest/index.html" rel="nofollow">http://pyinterval.readthedocs.io/en/latest/index.html</a>)</p> <p>And created an interval from a set or start, end tuples:</p> <pre><code>intervals = interval.interval([1,8], [7,10], [15,20]) </code></p...
2
2016-08-09T22:15:38Z
38,861,520
<p>I came up with the following program:</p> <pre><code>ls = [[1,8], [7,10], [15,20]] ls2 = [] prevList = ls[0] for lists in ls[1:]: if lists[0] &lt;= prevList[1]+1: prevList = [prevList[0], lists[1]] else: ls2.append(prevList) prevList = lists ls2.append(prevList) print ls2 # prints [...
0
2016-08-09T22:36:30Z
[ "python", "intervals" ]
How to join integers intervals in python?
38,861,290
<p>I have used the module intervals (<a href="http://pyinterval.readthedocs.io/en/latest/index.html" rel="nofollow">http://pyinterval.readthedocs.io/en/latest/index.html</a>)</p> <p>And created an interval from a set or start, end tuples:</p> <pre><code>intervals = interval.interval([1,8], [7,10], [15,20]) </code></p...
2
2016-08-09T22:15:38Z
38,861,631
<p>The intervals module <a href="http://pyinterval.readthedocs.io/en/latest/index.html" rel="nofollow">pyinterval</a> is used for real numbers, not for integers. If you want to use objects, you can create an integer interval class or you can also code a program to join integer intervals using the interval module:</p> ...
1
2016-08-09T22:48:14Z
[ "python", "intervals" ]
Pandas : in case of duplicate values, remove the row with a particular value in another column
38,861,323
<p>I have a dataset :</p> <pre><code>id url keep_anyway field 1 A.com Yes X 2 A.com Yes Y 3 B.com No Y 4 B.com No X 5 C.com No X </code></pre> <p>I want to <strong>remove "url" duplicates with conditions</strong> :</p> <ol> <li>Ke...
0
2016-08-09T22:18:32Z
38,861,379
<p>Try this:</p> <pre><code>import numpy as np duplicates = df.duplicated(subset='url') keep_anyway_bool = df['keep_away'] == 'Yes' # (credit @acushner for pointing this out) field_bool = df['field'] == 'X' # (credit @acushner for pointing this out) df[np.invert(duplicates) | keep_anyway_bool | field_bool] </code><...
1
2016-08-09T22:22:58Z
[ "python", "pandas" ]
Converting string into datetime: ValueError in python
38,861,395
<p>i check many <strong>StackOverflow</strong> questions. But can't solve this problem...</p> <pre><code>import pandas as pd from datetime import datetime import csv username = input("enter name: ") with open('../data/%s_tweets.csv' % (username), 'rU') as f: reader = csv.reader(f) your_list = list(reader) fo...
0
2016-08-09T22:24:48Z
39,178,372
<p><code>ValueError: time data 'date' does not match format '%d-%m-%Y %I:%M:%S'</code></p> <p><em>'date'</em> is not a Date String. That's why python can not convert this string into DateTime format. I check in my .csv file, and there i found the 1st line of the date list is not a date string, is a column head. I rem...
0
2016-08-27T06:56:01Z
[ "python", "python-2.7", "datetime" ]
What exactly did I do wrong with this script?
38,861,407
<p>I am trying to run this script</p> <pre><code>from schoolclass import School import elasticsearch import elasticsearch_dsl as srch import mysql.connector as mdb es = elasticsearch.Elasticsearch() cnx = mdb.connect(user= 'root', password= '*****', host= '127.0.0.1', database= 'sync-helper') cursor = cnx.cursor(), qu...
-2
2016-08-09T22:26:15Z
38,861,438
<p>A <code>SyntaxError</code> means that somewhere in your code a statement is hasn't been constructed properly. In your case, <code>zips.append(str(z[0])</code> is missing a closing parenthesis. A good place to look when you have a <code>SyntaxError</code> is the line before the one indicated.</p>
1
2016-08-09T22:29:24Z
[ "python", "python-2.7" ]
Pandas: Multi-index apply function between column and index
38,861,415
<p>I have a multi-index dataframe that look like this:</p> <pre><code>In[13]: df Out[13]: Last Trade Date Ticker 1983-03-30 CLM83 1983-05-18 CLN83 1983-06-17 CLQ83 1983-07-18 CLU83 1983-08-19 CLV83 1983-09-16 CLX83 1983-10-18 ...
2
2016-08-09T22:26:45Z
38,861,500
<p>Use <code>df.index.to_series().str.get(0)</code> to get at first level of index.</p> <pre><code>(df['Last Trade'].dt.month - df.index.to_series().str.get(0).dt.month) + \ (df['Last Trade'].dt.year - df.index.to_series().str.get(0).dt.year) * 12 Date Ticker 1983-03-30 CLM83 2 CLN83 3 ...
3
2016-08-09T22:34:23Z
[ "python", "pandas", "apply", "attributeerror", "multi-index" ]
Pandas: Multi-index apply function between column and index
38,861,415
<p>I have a multi-index dataframe that look like this:</p> <pre><code>In[13]: df Out[13]: Last Trade Date Ticker 1983-03-30 CLM83 1983-05-18 CLN83 1983-06-17 CLQ83 1983-07-18 CLU83 1983-08-19 CLV83 1983-09-16 CLX83 1983-10-18 ...
2
2016-08-09T22:26:45Z
38,861,514
<p>Try this instead of your function:</p> <h1>Option 1</h1> <h2>You get an integer number</h2> <pre><code>def monthdelta(row): trade = row['Last Trade'].year*12 + row['Last Trade'].month date = row['Date'].year*12 + row['Date'].month return trade - date df.reset_index().apply(monthdelta, axis=1) </code>...
3
2016-08-09T22:35:58Z
[ "python", "pandas", "apply", "attributeerror", "multi-index" ]
Regex match inner '.'
38,861,419
<p>I would like to remove an inner sentence based on one word. So instead of just 'start' I would like the regex statement to return 'start.stop.'.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = 'start.stop.do nice.' &gt;&gt;&gt; re.sub(r'\..*nice.*', '', s) 'start' </code></pre>
1
2016-08-09T22:27:07Z
38,861,465
<p>You need a <a href="http://www.regular-expressions.info/charclass.html" rel="nofollow"><em>negated character class</em></a> instead of <code>.*</code> to refuse of matching the dots in other sentences. And in order to preserving the last dot, you can use a <a href="http://www.regular-expressions.info/lookaround.html...
1
2016-08-09T22:31:05Z
[ "python", "regex", "string", "python-3.x" ]
Unix timestamp to iso 8601 time format
38,861,426
<blockquote> <p>When i convert unix time 1463288494 to isoformat i get 2016-05-14T22:01:34. How can I get the output including the -07:00. In this format 2016-05-14T22:01:34-07:00</p> </blockquote> <pre><code>from datetime import datetime t = int("1463288494") print(datetime.fromtimestamp(t).isoformat()) </code></p...
0
2016-08-09T22:27:48Z
38,861,784
<p>You can pass a <code>tzinfo</code> instance representing your timezone offset to <code>fromtimestamp()</code>. The problem then is how to get the <code>tzinfo</code> object. The easiest way is to use the <a href="https://pypi.python.org/pypi/pytz" rel="nofollow"><code>pytz</code></a> module which provides a <code>tz...
0
2016-08-09T23:03:50Z
[ "python", "python-2.7", "python-3.x" ]
Splitting a list into uneven groups?
38,861,457
<p>I know how to split a list into even groups, but I'm having trouble splitting it into uneven groups. </p> <p>Essentially here is what I have: some list, let's call it <code>mylist</code>, that contains x elements.</p> <p>I also have another file, lets call it second_list, that looks something like this:</p> <pre>...
11
2016-08-09T22:30:37Z
38,861,547
<p>This solution keeps track of how many items you've written. It will crash if the sum of the numbers in the <code>second_list</code> is longer than <code>mylist</code></p> <pre><code>total = 0 listChunks = [] for j in range(len(second_list)): chunk_mylist = mylist[total:total+second_list[j]] listChunks.appen...
1
2016-08-09T22:39:18Z
[ "python", "list", "python-2.7", "split", "sublist" ]
Splitting a list into uneven groups?
38,861,457
<p>I know how to split a list into even groups, but I'm having trouble splitting it into uneven groups. </p> <p>Essentially here is what I have: some list, let's call it <code>mylist</code>, that contains x elements.</p> <p>I also have another file, lets call it second_list, that looks something like this:</p> <pre>...
11
2016-08-09T22:30:37Z
38,861,562
<p>Using <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/737/list-comprehensions#t=201608092238264469378">list-comprehensions</a> together with <a class='doc-link' href="http://stackoverflow.com/documentation/python/1494/list-slicing-selecting-parts-of-lists#t=2016080922392932...
4
2016-08-09T22:40:32Z
[ "python", "list", "python-2.7", "split", "sublist" ]
Splitting a list into uneven groups?
38,861,457
<p>I know how to split a list into even groups, but I'm having trouble splitting it into uneven groups. </p> <p>Essentially here is what I have: some list, let's call it <code>mylist</code>, that contains x elements.</p> <p>I also have another file, lets call it second_list, that looks something like this:</p> <pre>...
11
2016-08-09T22:30:37Z
38,861,604
<pre><code>subgroups = [] start=0 for i in second_list: subgroups.append(mylist[start:start + i]) start = i + start </code></pre> <p>At the end <code>subgroups</code> will contain the desired lists</p> <p>Example run:</p> <pre><code>&gt;&gt;&gt; mylist = [1,2,3,4,5,6,7,8,9,10,11,12] &gt;&gt;&gt; second_list = [2...
1
2016-08-09T22:44:22Z
[ "python", "list", "python-2.7", "split", "sublist" ]
Splitting a list into uneven groups?
38,861,457
<p>I know how to split a list into even groups, but I'm having trouble splitting it into uneven groups. </p> <p>Essentially here is what I have: some list, let's call it <code>mylist</code>, that contains x elements.</p> <p>I also have another file, lets call it second_list, that looks something like this:</p> <pre>...
11
2016-08-09T22:30:37Z
38,861,665
<p>You can create an iterator and <a href="https://docs.python.org/dev/library/itertools.html#itertools.islice"><em>itertools.islice</em></a>:</p> <pre><code>mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] seclist = [2,4,6] from itertools import islice it = iter(mylist) sliced =[list(islice(it, 0, i)) for i in secl...
12
2016-08-09T22:51:36Z
[ "python", "list", "python-2.7", "split", "sublist" ]
Splitting a list into uneven groups?
38,861,457
<p>I know how to split a list into even groups, but I'm having trouble splitting it into uneven groups. </p> <p>Essentially here is what I have: some list, let's call it <code>mylist</code>, that contains x elements.</p> <p>I also have another file, lets call it second_list, that looks something like this:</p> <pre>...
11
2016-08-09T22:30:37Z
38,861,811
<p>A numpythonic approach:</p> <pre><code>&gt;&gt;&gt; lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] &gt;&gt;&gt; sec = [2, 4, 5] &gt;&gt;&gt; np.split(lst, np.cumsum(sec)) [array([0, 1]), array([2, 3, 4, 5]), array([ 6, 7, 8, 9, 10]), array([11])] </code></pre> <p>And here is a Python3.X approach using <code>itert...
5
2016-08-09T23:06:17Z
[ "python", "list", "python-2.7", "split", "sublist" ]
Loop Through Folder - Extract Heading 1 From Documents - Extract to New Document
38,861,532
<p>I am trying to extract heading 1 from documents stored in a directory.</p> <p>I am extremely new to python, so my experience is extremely limited.</p> <p>My code below does not work, it has syntax and structural errors. </p> <p>The code returns an error document not defined.</p> <pre><code>import os from docx ...
0
2016-08-09T22:37:59Z
38,864,245
<p>To get a list of files that you can iterate over, you could use:</p> <pre><code>import os os.chdir("path/to/files") lists_of_files = os.listdir(os.getcwd()) </code></pre> <p>and then</p> <pre><code>for i in list_of_files: #extract heading from file i </code></pre> <p>For extracting the headers, you can use p...
0
2016-08-10T04:27:14Z
[ "python", "docx", "python-docx" ]
Subset chains within powerset in python
38,861,589
<p>If I've enumerated the powerset of the alphabet, for example, as 0,...,1&lt;&lt;26-1.</p> <p>For a given number in that range, I want to know what all of its subsets are. I can do something a bit inefficient like:</p> <pre><code>def find_subset_chain(subset): return [i for i in subset if i &amp; subset == i] ...
0
2016-08-09T22:42:44Z
38,861,833
<p>We can find the least significant set bit of a number as</p> <pre><code>n &amp; -n </code></pre> <p>and we can use that to "count down" the subsets of a set represented as a bitmask by repeatedly clearing the least significant set bit and restoring all less-significant set bits from the original number:</p> <pre>...
1
2016-08-09T23:08:36Z
[ "python", "performance", "optimization" ]
How to assign a sequential label to pandas groupby?
38,861,600
<p>I start with the following pandas dataframe, I wish to group each day, and make a new column called 'label', which labels the group with a sequential number. How do I do this?</p> <pre><code>df = pd.DataFrame({'val': [10,40,30,10,11,13]}, index=pd.date_range('2016-01-01 00:00:00', periods=6, freq='12H' ) ) # df['la...
1
2016-08-09T22:43:42Z
38,861,691
<p>Try this:</p> <pre><code>df = pd.DataFrame({'val': [10,40,30,10,11,13]}, index=pd.date_range('2016-01-01 00:00:00', periods=6, freq='12H' ) ) </code></pre> <p>If you just want to group by date:</p> <pre><code>df['label'] = df.groupby(df.index.date).grouper.group_info[0] + 1 print(df) </code></pre> <p>To group by...
3
2016-08-09T22:53:37Z
[ "python", "pandas" ]
How to assign a sequential label to pandas groupby?
38,861,600
<p>I start with the following pandas dataframe, I wish to group each day, and make a new column called 'label', which labels the group with a sequential number. How do I do this?</p> <pre><code>df = pd.DataFrame({'val': [10,40,30,10,11,13]}, index=pd.date_range('2016-01-01 00:00:00', periods=6, freq='12H' ) ) # df['la...
1
2016-08-09T22:43:42Z
38,883,582
<p>maybe a more simpler and intuitive approach is this:</p> <pre><code>df['label'] = df.groupby(df.index.day).keys </code></pre>
0
2016-08-10T21:08:45Z
[ "python", "pandas" ]
Numpy .shuffle gives the same results each time
38,861,686
<p>I am attempting to take a pandas DataFrame, take out 1 column, shuffle the contents of that column, then place it back into the DataFrame and return it. This is the code used:</p> <pre><code>def randomize(self, data, column): '''Takes in a pandas database and randomizes the values in column. data is the pa...
4
2016-08-09T22:53:20Z
38,862,368
<p><strong><em>Your code</em></strong></p> <pre><code>def randomize(data, column): df1 = data.copy() newcol = list(data[column]) np.random.shuffle(newcol) df1[column] = newcol return df1 </code></pre> <p><strong><em>My <code>df</code></em></strong></p> <pre><code>df = pd.DataFrame(np.arange(25).r...
1
2016-08-10T00:18:19Z
[ "python", "pandas", "numpy", "random" ]
Send css over python socket server
38,861,763
<p>I have created a small python html server, but I am having issues sending external css and javascript. The html transfers as it should and inline css works fine. The chrome developer tool responds with this error: </p> <blockquote> <p>Resource interpreted as Stylesheet but transferred with MIME type text/plain:...
3
2016-08-09T23:01:55Z
38,861,808
<p>Add this line to your response string right beneath the 200 OK line:</p> <pre><code>Content-Type: text/css </code></pre> <p>What's happening is that Chrome is attempting to interpret the HTML you sent as as stylesheet, which you want. But, when you send it, you're sending with a content header that's telling chrom...
2
2016-08-09T23:06:14Z
[ "python", "html", "sockets" ]
Need to write a string with exponent to file
38,861,771
<p>I need to write feet cubed (ft**3) to a file that will be read by another program, where the 3 is a superscript. When I cut and paste the text I need from an example input file (like this: ft³) and try to save the script it says:</p> <p>"Encoding file [filename] using "ascii" encoding will result in information lo...
0
2016-08-09T23:02:27Z
38,861,876
<pre><code>with open('some_file.txt','wb'): # save non-ascii bytes (superscript 3 might even work with just 'w') f.write('Units ft\xb3\n') #\xb3 is the superscript 3 in utf8 encoding </code></pre> <p>you can do this which will be recognized by <em>most</em> test editors</p>
0
2016-08-09T23:13:39Z
[ "python", "ascii" ]
Need to write a string with exponent to file
38,861,771
<p>I need to write feet cubed (ft**3) to a file that will be read by another program, where the 3 is a superscript. When I cut and paste the text I need from an example input file (like this: ft³) and try to save the script it says:</p> <p>"Encoding file [filename] using "ascii" encoding will result in information lo...
0
2016-08-09T23:02:27Z
39,089,769
<p>Joran's option works for my text editors, but unfortunately comes across as a replacement character (�) when I try to open the input file with the program. The program uses Micr$oft <a href="https://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.90).aspx" rel="nofollow">File.ReadAllLines</a> method, so it should b...
0
2016-08-22T22:39:56Z
[ "python", "ascii" ]
Need to write a string with exponent to file
38,861,771
<p>I need to write feet cubed (ft**3) to a file that will be read by another program, where the 3 is a superscript. When I cut and paste the text I need from an example input file (like this: ft³) and try to save the script it says:</p> <p>"Encoding file [filename] using "ascii" encoding will result in information lo...
0
2016-08-09T23:02:27Z
39,131,304
<p>Okay, problem solved. Thanks for pointing me in the right direction Joran. Although I'm not sure why I have to <code>.encode('utf8')</code> the string, since as you state <code>\xb3</code> is already in utf8. But I tried and tried and it won't work without the <code>.encode('utf8')</code>.</p> <p>In the second post...
0
2016-08-24T19:11:00Z
[ "python", "ascii" ]
finding the max per id and creating a new column in pandas
38,861,804
<p>So, I have a pandas dataframe like this:</p> <pre><code>id, counts 1, 20 1, 21 1,15 1, 24 2,12 2,42 2,9 3,43 ... id, counts, label 1, 20, 0 1, 21, 0 1,15, 0 1, 24, 1 # because 24 is the highest count for id 1 2,12, 0 2,42, 1 # because 42 is the highest count for id 2 2,9, 0 3,43, ... </code></pre> <p>How do i do...
-3
2016-08-09T23:05:55Z
38,861,867
<pre><code>maxes = df.groupby('id').counts.max().rename('Max').reset_index() df1 = df.merge(maxes, how='left') df['Max'] = (df1.counts == df1.Max) * 1 df </code></pre> <p><a href="http://i.stack.imgur.com/7kDx0.png" rel="nofollow"><img src="http://i.stack.imgur.com/7kDx0.png" alt="enter image description here"></a></p...
4
2016-08-09T23:12:34Z
[ "python", "pandas" ]
finding the max per id and creating a new column in pandas
38,861,804
<p>So, I have a pandas dataframe like this:</p> <pre><code>id, counts 1, 20 1, 21 1,15 1, 24 2,12 2,42 2,9 3,43 ... id, counts, label 1, 20, 0 1, 21, 0 1,15, 0 1, 24, 1 # because 24 is the highest count for id 1 2,12, 0 2,42, 1 # because 42 is the highest count for id 2 2,9, 0 3,43, ... </code></pre> <p>How do i do...
-3
2016-08-09T23:05:55Z
38,861,911
<p>This seems to work:</p> <pre><code>df['label'] = 0 df['label'].iloc[df.groupby('id').apply(lambda x: x['counts'].argmax()).values] = 1 </code></pre> <p>But it is so ugly! And does not follow good coding practices... I'll try to improve it.</p> <hr> <p>If you like the below line, upvote <a href="http://stackoverf...
3
2016-08-09T23:19:45Z
[ "python", "pandas" ]
finding the max per id and creating a new column in pandas
38,861,804
<p>So, I have a pandas dataframe like this:</p> <pre><code>id, counts 1, 20 1, 21 1,15 1, 24 2,12 2,42 2,9 3,43 ... id, counts, label 1, 20, 0 1, 21, 0 1,15, 0 1, 24, 1 # because 24 is the highest count for id 1 2,12, 0 2,42, 1 # because 42 is the highest count for id 2 2,9, 0 3,43, ... </code></pre> <p>How do i do...
-3
2016-08-09T23:05:55Z
38,862,031
<p>Try this: </p> <pre><code> df["label"] = np.where( df.index.isin((df2.groupby("id")["counts"].idxmax())),1,0) id counts label 0 1 20 0 1 1 21 0 2 1 15 0 3 1 24 1 4 2 12 0 5 2 42 1 6 2 9 0 7 3 43 1 </code></pre> ...
1
2016-08-09T23:32:47Z
[ "python", "pandas" ]
tkinter debugging with Spyder
38,861,824
<p>I am using tkinter to build a GUI app with anaconda python and spyder on OSX. I can't get a prompt in the ipython console while my tkinter window is open. I can set a breakpoint and get into the debugger, but after that Spyder will shortly freeze or crash. </p> <p>Here is sample code that fails: </p> <pre><code>f...
1
2016-08-09T23:07:15Z
38,866,871
<p>Try changing frame.pack() to frame.grid() in this gui you don't really need to use grid for geometry, though. So might just want to change Button().grid() to Button().pack().</p>
0
2016-08-10T07:29:38Z
[ "python", "debugging", "tkinter", "spyder" ]
Python and Ctypes: Not getting expected offsets
38,861,906
<p>I am converting an app from VB.NET to Python 3.4 and am running into problems calling a function within a DLL file using ctypes. For that particular function, two structures are passed in byref. For one structure, the field offsets are not working out as needed. The last field's offset ends up being off. That ma...
0
2016-08-09T23:18:44Z
38,905,355
<p>12+15*4 <em>is</em> 72, so the VB.NET structure skips those 4 bytes, maybe to guarantee that the array is null terminated. Without knowing the actual struct definition from the called library it's hard to say. You could just add an additional 4 byte padding field.</p> <p>To control the alignment of the members you ...
0
2016-08-11T20:16:11Z
[ "python", "ctypes" ]
tkinter canvas color not changing
38,861,916
<p>I have a two tkinter canvas which needs to change color based on the data which I receive from other module. basically 0,1 Ex: canvas1 to black and canvas2 to green if 1 is received and viceversa if 0 is received.</p> <p>I have used multiprocessing queue technique to receive the data, but when I tried to apply the ...
0
2016-08-09T23:20:05Z
38,868,730
<p>As you mentioned yourself already, you are creating instances of <code>MainWindow</code> class all over in your <code>do_something</code>.</p> <p>Second, the <code>do_something</code> function call is a bit strange for me. I would prefer </p> <pre><code>def do_something(queue): t = MainWindow() t.changeLig...
1
2016-08-10T09:02:33Z
[ "python", "canvas", "tkinter" ]
Pandas - Propogating variance
38,861,934
<p>For data of the form</p> <pre><code>mean var count 31.5910645161 747.570011484 310 45.7 350.0658 2 77.2548205128 4968.46005809 195 166.830361446 13755.5734253 166 40.29 208.8968 2 254.35 15204.1922 2 4.81 0.0 ...
2
2016-08-09T23:22:34Z
38,861,989
<blockquote> <pre><code>Parameters ---------- arg : function or dict Function to use for aggregating groups. If a function, must either work when passed a DataFrame or when passed to DataFrame.apply. If passed a dict, the keys must be DataFrame column names. Accepted Combinations are: - string cy...
1
2016-08-09T23:28:01Z
[ "python", "pandas" ]
Attempting to read from two serial ports at once
38,861,980
<p>I am trying to read from two serial ports at once. Each connected device spits out a line of data. I read the data from each port as a list and then concatenate the list and print it out as one line.</p> <p>If I read each port individually, the data updates fine. But the second I attempt to read from both, it lags ...
0
2016-08-09T23:27:14Z
38,862,051
<p>just check to see if your serial port has bytes to read before you try to read it ...</p> <pre><code>while 1 : timestamp = "%f" % time.time() print(timestamp) if serA.inWaiting(): # only read if there is something waiting to be read arduino = serA.readline().rstrip('\n') data_listA = ard...
1
2016-08-09T23:35:01Z
[ "python" ]
Attempting to read from two serial ports at once
38,861,980
<p>I am trying to read from two serial ports at once. Each connected device spits out a line of data. I read the data from each port as a list and then concatenate the list and print it out as one line.</p> <p>If I read each port individually, the data updates fine. But the second I attempt to read from both, it lags ...
0
2016-08-09T23:27:14Z
38,874,247
<p>Using <code>inwaiting()</code> unfortunately did not work for me. I ended up having to use threading. A basic example for people who might encounter my problem is shown below.</p> <pre><code>import serial import Queue import threading queue = Queue.Queue(1000) serA = serial.Serial('/dev/arduino', 230400) serT = s...
0
2016-08-10T13:03:08Z
[ "python" ]
Raw sql to json in Django, with Datetime and Decimal MySql columns
38,862,016
<p>I am using Ajax to make some requests from client to server, I am using DJango and I have used some Raw Sql queries before, but all of my fields was Int, varchar and a Decimal, for the last one I had an enconding problem, but I overrided the "default" property of Json and everything worked. </p> <p>But that was bef...
2
2016-08-09T23:30:13Z
38,862,204
<p>Sorry, was my bad, i'm using JQuery ajax method, and in the "success" part I forgot to stop using <code>json.parse</code> to print the data in the console, the data was json already, that's why I had that <code>line 1 column 1 error</code>. My code worked exactly like it was posted here. If someone want to know how ...
0
2016-08-09T23:53:36Z
[ "python", "mysql", "json", "django" ]
Convert unicode base notation to string in python
38,862,034
<p>I have a data in form of <code>2\u2070iPSC</code>. which is actually <code>2⁰iPSC</code>. how do i convert <code>2\u2070iPSC</code> to 2⁰iPSC using python. </p>
1
2016-08-09T23:32:52Z
38,862,071
<p>You need to add <code>u</code> as prefix in order to set it as unicode string.</p> <pre><code>unicode_string = u'2\u2070iPSC' print(unicode_string) &gt;&gt; 2⁰iPSC </code></pre>
0
2016-08-09T23:37:02Z
[ "python", "unicode" ]
Convert unicode base notation to string in python
38,862,034
<p>I have a data in form of <code>2\u2070iPSC</code>. which is actually <code>2⁰iPSC</code>. how do i convert <code>2\u2070iPSC</code> to 2⁰iPSC using python. </p>
1
2016-08-09T23:32:52Z
38,862,192
<p>As a unicode string the data already is <code>2⁰iPSC</code>. I think that you are concerned about its display.</p> <p>The code point <code>\u2070</code> <em>is</em> <code>⁰</code>:</p> <pre><code>&gt;&gt;&gt; import unicodedata &gt;&gt;&gt; unicodedata.name(u'\u2070') 'SUPERSCRIPT ZERO' </code></pre> <p>If yo...
2
2016-08-09T23:51:57Z
[ "python", "unicode" ]
Xlwings fails to import UDFs
38,862,066
<p>So, I have an Excel workbook that I originally created on Windows 7 running Anaconda 4.1.1 (Python 3.5) and Excel 2013. Everything was working great in that environment. I am now trying to work on it remotely using a computer running Windows 10, Anaconda 4.1.1, and Excel 2016. I downloaded the workbook and its corre...
0
2016-08-09T23:36:18Z
38,901,756
<p>So I ended up just starting a new project in xlwings on the new machine, copying over the python code into the new .py file, importing the UDFs, then copying the entire workbook from the old (non-functioning) book to the new one, where the UDFs worked fine. I'm still not sure what the error was or why it was happeni...
0
2016-08-11T16:30:14Z
[ "python", "xlwings" ]
How do I add more python modules to my yocto/openembedded project?
38,862,088
<p>I wish to add more python modules to my yocto/openembedded project but I am unsure how to? I wish to add flask and its dependencies.</p> <p>Anyone able to help me on this?</p> <p>Thanks,</p> <p>Tim</p>
0
2016-08-09T23:38:56Z
38,865,389
<p>In your Image recipe you can add a Python module by adding it to the <code>IMAGE_INSTALL</code> variable:</p> <pre><code>IMAGE_INSTALL += "python-numpy" </code></pre> <p>You can find possible modules for example by searching for them with wildcards:</p> <pre><code>find -name *python*numpy*bb </code></pre> <p>in ...
0
2016-08-10T06:03:18Z
[ "python", "linux", "yocto", "bitbake", "openembedded" ]
How do I add more python modules to my yocto/openembedded project?
38,862,088
<p>I wish to add more python modules to my yocto/openembedded project but I am unsure how to? I wish to add flask and its dependencies.</p> <p>Anyone able to help me on this?</p> <p>Thanks,</p> <p>Tim</p>
0
2016-08-09T23:38:56Z
38,865,576
<p>The OE layer index at layers.openembedded.org lists all known layers and the recipes they contain, so searching that should bring up the meta-python layer that you can add to your build and use recipes from.</p>
1
2016-08-10T06:15:56Z
[ "python", "linux", "yocto", "bitbake", "openembedded" ]
How do I share Protocol Buffer .proto files between multiple repositories
38,862,101
<p>We are considering using <a href="https://developers.google.com/protocol-buffers/" rel="nofollow">Protocol Buffers</a> for communicating between a python &amp; a node.js service that each live in their own repos. </p> <p>Since the <code>.proto</code> files must be accessible to both repos, how should we share the <...
2
2016-08-09T23:41:03Z
38,866,138
<p>This depends on your development process.</p> <p>A git subtree / submodule seems like a sensible solution for most purposes. If you had more downstream projects, publishing a ready-made module would make sense, as then the protobuf generator wouldn't be needed for every project.</p>
2
2016-08-10T06:48:06Z
[ "python", "node.js", "git", "protocol-buffers" ]
How do I share Protocol Buffer .proto files between multiple repositories
38,862,101
<p>We are considering using <a href="https://developers.google.com/protocol-buffers/" rel="nofollow">Protocol Buffers</a> for communicating between a python &amp; a node.js service that each live in their own repos. </p> <p>Since the <code>.proto</code> files must be accessible to both repos, how should we share the <...
2
2016-08-09T23:41:03Z
38,881,998
<p>We, in the same situation, used 3 repos: server-side was written in c++, client-side in actionscript 3, and protobufs was in the third, and was used both of them. For a big team, and big project I think it was a good choice.</p>
0
2016-08-10T19:30:06Z
[ "python", "node.js", "git", "protocol-buffers" ]
Read-write lock with only one underlying lock?
38,862,104
<p>I've written a read-write lock using Python's concurrency primitives (I think!). Every implementation I've read on SO or elsewhere seems to use 2 locks -- one for reads, and another for writes. My implementation contains only one monitor for reads, but I may be missing something crucial -- can anyone confirm that th...
1
2016-08-09T23:41:26Z
38,867,835
<p>You are not using a single lock. <br>You are using a <strong>lock and a condition variable</strong></p> <pre><code>self.read_lock = t.Condition(t.Lock()) </code></pre> <p>A condition variable is a concurrency primitive too. A more complex one than a lock.</p> <p><strong>note :</strong> please do not call a condit...
1
2016-08-10T08:19:12Z
[ "python", "multithreading", "concurrency", "locking" ]
Flask cannot raise HTTP exception after try catching Runtime error
38,862,144
<p>When I try to raise a HTTP exception status code 400 it only prints the json error message on the browser but does not state <code>HTTP/1.1 400 BAD REQUEST</code> in the console like it is supposed to. The exception raising works for all other parts of my program but it doesn't work when I do it in a try-catch for a...
0
2016-08-09T23:46:21Z
38,863,378
<p>You should use the <code>abort</code> function of flask, something like:</p> <pre><code>from flask import abort @app.route("/some_route") def some_route(): try: # do something except SomeException: abort("Some message", 400) </code></pre>
0
2016-08-10T02:34:23Z
[ "python", "flask", "exception-handling" ]
Determine dependencies
38,862,163
<p>I have a large file with several lines, where each line is a <code>&lt;project name&gt;: &lt;dependencies&gt;, &lt;dependencies1&gt;</code> list. </p> <p><code> AAA: BBB, CCC, DDD BBB: EEE, FFF DDD: CCC CCC: GGG: DDD EEE: FFF FFF </code></p> <p>The projects needs to ordered such such that its dependencies are met...
-1
2016-08-09T23:49:02Z
38,863,172
<p>The trick with this is recursively finding all dependencies in order to establish their priorities. Try the code below, you can simply run it providing the file containing the dependencies:</p> <pre><code>#!/usr/bin/env python2.7 import re import string import sys import unittest from collections import OrderedDic...
-1
2016-08-10T02:10:58Z
[ "python" ]