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
reading corresponding columns using python
38,915,758
<p>I have the output in the format :</p> <pre><code>Neighbor InQ OutQ Up/Down State 10.230.3.2 0 0 33w5d 1177 10.230.4.2 0 0 33w4d 1175 125.62.173.253 0 0 8w3d 2637 125.62.173.254 0 0 1w3d 2657 </code></pre> <p>I want to read the Neighbor(e.g ...
0
2016-08-12T10:29:24Z
38,917,796
<p>I've never used Pandas before but I read Nehal's linked documentation and based this solution on <a href="http://stackoverflow.com/a/38916031/1636276">his answer</a>. This is in response to your comment:</p> <blockquote> <p>Can I add the data to df via a text file? Because I have a lot of data like this and manua...
0
2016-08-12T12:17:25Z
[ "python" ]
Yahtzee using Asciitable, need to assign player points
38,915,790
<p>I'm currently working on a yahtzee board, but I'm walking into problems I have a hard time figuring out, my code is looking like this currently:</p> <pre><code>from terminaltables import AsciiTable class Player: def __init__(self,name): self.name=name self.ones=0 self.twos=0 sel...
1
2016-08-12T10:30:39Z
38,918,578
<p>You need to use a single list of strings/numbers that doesn't contain other lists for each row. Currently: <code>['Ettor',spelarlista[1:i],","],</code> looks something like <code>'Ettor',['James', 'Alfred',","],</code> when you want it to look more like <code>'Ettor', 0, 0, 0</code>.</p> <p>(Note that I don't know ...
1
2016-08-12T12:58:11Z
[ "python" ]
How to run python script results on Flask
38,915,855
<p>I have created an app.py and index.html file. My problem is that I want to execute a python script with the input I gathered from POST when submit is clicked, and then display the script output on the same or different html page. I used CGI and Flask. I do not fully know how to proceed. I research online, but couldn...
-1
2016-08-12T10:33:08Z
38,917,884
<p>Since you want to execute another Python script... If you are able to <code>import</code> the other script then you can just use something like the following to call it and store the results - assuming the other script is a value-returning function.</p> <pre><code>from othermodule import function_to_run ... # where...
1
2016-08-12T12:21:56Z
[ "python", "html", "python-2.7", "web", "flask" ]
TensorFlow multithreading StatusNotOK
38,915,892
<p>I'm trying to implement a decoupled training queue in tensorflow</p> <p>at the very beginning im initilizing the graph</p> <pre><code>def init(self,restore,network_name): self.sess = tf.InteractiveSession() (some other stuff) self.data_a = tf.placeholder(tf.float32, [1,9]) self.data_b = tf.place...
0
2016-08-12T10:35:04Z
38,916,953
<p>Ok it appears it that tf.graph was not thread safe for this operation in version 0.7.1 <a href="https://github.com/tensorflow/tensorflow/commit/acac487ac4ebaa6edb3e3f866d41cbd12546a107" rel="nofollow">https://github.com/tensorflow/tensorflow/commit/acac487ac4ebaa6edb3e3f866d41cbd12546a107</a></p> <p>after upgrading...
0
2016-08-12T11:31:39Z
[ "python", "multithreading", "tensorflow" ]
Write a pandas data frame to HDF5
38,915,917
<p>I'm processing large number of files in python and need to write the output (one dataframe for each input file) in <code>HDF5</code> directly. I am wondering what is the best way to write <code>pandas</code> data frame from my script to <code>HDF5</code> directly in a fast way? I am not sure if any python module lik...
1
2016-08-12T10:36:43Z
38,918,732
<p>It's difficult to give you a good answer to this rather generic question.</p> <p>It's not clear how are you going to use (read) your HDF5 files - do you want to select data conditionally (using <code>where</code> parameter)?</p> <p>fir of all you need to open a store object:</p> <pre><code>store = pd.HDFStore('/p...
0
2016-08-12T13:04:43Z
[ "python", "hadoop", "pandas", "dataframe" ]
How to remove duplicates and display unique values in backend (i.e. run time). while run this code what we ll give specific column that is removed
38,915,997
<pre><code>import re import pandas as pd # my imports from job_processing.utils import * def get_duplication(rule): try: return re.compile(rule.duplication, re.UNICODE) except re.error: raise re.error def run_duplication(rule, df, column): cols = dict() cols["dirty"] = get_column_nam...
-2
2016-08-12T10:40:57Z
38,916,040
<p>It looks like need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a>:</p> <pre><code>df1 = df.drop_duplicates(subset=[0]) print (df1) 0 1 2 3 4 0 Jason Miller 42 4 25 1 Tina Ali 36 31...
0
2016-08-12T10:43:05Z
[ "python", "django", "python-3.x", "pandas" ]
Pandas start generating Run-time warning error and require restart
38,916,188
<pre><code>import numpy as np import pandas as pd tempdata = np.random.random(10) myseries = pd.Series(tempdata) newseries = myseries[2:6] </code></pre> <p>Now if I put <strong>newseries</strong> in <strong>pd.Series</strong> and want to re-index(I know indexing is immutable) it with some alphabets I encounter fo...
0
2016-08-12T10:50:55Z
38,916,547
<p>I don't get the same error. Since the indices 'a', 'b' etc are not in the orginal series, they get a NaN value, and the numbers are lost.</p> <p>I think you want to discard the old index and start with a new one, So you can do</p> <pre><code>newseries = pd.Series(newseries.values, index = ['a','b','c','d']) </code...
1
2016-08-12T11:09:46Z
[ "python", "python-2.7", "python-3.x", "pandas" ]
Unable to fetch Table from BeautifulSoup
38,916,518
<pre><code>from BeautifulSoup import BeautifulSoup import urllib2 url = 'http://www.data.jma.go.jp/obd/stats/etrn/view/monthly_s3_en.php?block_no=47401&amp;view=1' html = urllib2.urlopen(url).read() soup = BeautifulSoup(html) table = soup.find('table') print table </code></pre> <p>Expected table is not result...
0
2016-08-12T11:07:18Z
38,916,683
<p>There's more than one table in the HTML. Get the second table with:</p> <pre><code>tables = soup.findAll('table') print tables[1] # the second table </code></pre> <p>Or you can go directly to the table by its CSS class:</p> <pre><code>from bs4 import BeautifulSoup table = soup.find_all('table', class_='data2_...
1
2016-08-12T11:17:29Z
[ "python", "beautifulsoup", "urllib2" ]
Unable to fetch Table from BeautifulSoup
38,916,518
<pre><code>from BeautifulSoup import BeautifulSoup import urllib2 url = 'http://www.data.jma.go.jp/obd/stats/etrn/view/monthly_s3_en.php?block_no=47401&amp;view=1' html = urllib2.urlopen(url).read() soup = BeautifulSoup(html) table = soup.find('table') print table </code></pre> <p>Expected table is not result...
0
2016-08-12T11:07:18Z
38,916,696
<p>First off, use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"><em>bs4</em></a> <em>beaufifulsoup3</em> is no longer maintained, also the table you want has the class <code>*data2_s*</code>, calling <code>find("table")</code> just gets the first table on the page which is not what you...
1
2016-08-12T11:18:02Z
[ "python", "beautifulsoup", "urllib2" ]
Python grep code much slower than command line's grep
38,916,645
<p>I'm just grepping some Xliff files for the pattern <code>approved="no"</code>. I have a Shell script and a Python script, and the difference in performance is huge (for a set of 393 files, and a total of 3,686,329 lines, 0.1s user time for the Shell script, and 6.6s for the Python script).</p> <p>Shell: <code>grep ...
2
2016-08-12T11:16:13Z
38,917,139
<p>Grep is actually a very clever piece of software, it does not just do a regex search per line. It utilizes the <a href="https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm" rel="nofollow">Boyer-Moore</a> algorithm. See <a href="https://lists.freebsd.org/pipermail/freebsd-current/2010-August/019...
1
2016-08-12T11:42:43Z
[ "python", "performance", "grep" ]
Python grep code much slower than command line's grep
38,916,645
<p>I'm just grepping some Xliff files for the pattern <code>approved="no"</code>. I have a Shell script and a Python script, and the difference in performance is huge (for a set of 393 files, and a total of 3,686,329 lines, 0.1s user time for the Shell script, and 6.6s for the Python script).</p> <p>Shell: <code>grep ...
2
2016-08-12T11:16:13Z
38,918,877
<p>Python, being an interpreted language vs. a compiled C version of <code>grep</code> will always be slower.</p> <p>Apart from that your Python implementation is <em>not</em> the same as your <code>grep</code> example. It is not returning the matching lines, it is merely testing to see if the pattern matches the char...
1
2016-08-12T13:11:21Z
[ "python", "performance", "grep" ]
Python grep code much slower than command line's grep
38,916,645
<p>I'm just grepping some Xliff files for the pattern <code>approved="no"</code>. I have a Shell script and a Python script, and the difference in performance is huge (for a set of 393 files, and a total of 3,686,329 lines, 0.1s user time for the Shell script, and 6.6s for the Python script).</p> <p>Shell: <code>grep ...
2
2016-08-12T11:16:13Z
38,975,809
<p>Another source of slowness here is calling <code>re.search</code> inside a loop. This will <em>recompile</em> the regex for every single line.</p> <p>Try instead:</p> <pre><code>pattern = re.compile(pattern) while True: ... if pattern.search(line): ... </code></pre>
0
2016-08-16T13:06:39Z
[ "python", "performance", "grep" ]
Regular expression finditer: search twice on the same symbols
38,916,664
<p>I need to find matches in the text and get its positions. For example, I have to find "hello hello" in the text. When the text is "hello hello world hello hello", it's ok, I get the positions 0-11 and 18-29. But when the text is "hello hello hello world", I get only one position - 0-11. But I have to find the both o...
1
2016-08-12T11:16:57Z
38,917,807
<p>I think you can try <strong>below expression</strong> than regexp, looks not that good but might solve your problem:</p> <p>Expression:</p> <pre><code> [pos for pos, char in enumerate(string) if string[pos:].find(pattern) == 0] </code></pre> <p>It gives list output with positions of the pattern in string.</p> <p...
0
2016-08-12T12:18:15Z
[ "python", "regex" ]
Regular expression finditer: search twice on the same symbols
38,916,664
<p>I need to find matches in the text and get its positions. For example, I have to find "hello hello" in the text. When the text is "hello hello world hello hello", it's ok, I get the positions 0-11 and 18-29. But when the text is "hello hello hello world", I get only one position - 0-11. But I have to find the both o...
1
2016-08-12T11:16:57Z
38,917,809
<p>Your question is still lacking a bit in clarity of what you wish to do, but I'll take a stab at it:</p> <p>Regex to find repetitions without consumption:</p> <pre><code>([a-zA-Zа-яА-Я]+)(?= (\1)) </code></pre> <p>Regex to find <code>hello</code> <code>beautiful</code> and <code>world</code> with specific numb...
0
2016-08-12T12:18:22Z
[ "python", "regex" ]
how to handle web SQL queries and xml replies in Python
38,916,674
<p>I have a distant database on which I can send SQL select queries through a web service like this:</p> <pre><code>http://aa.bb.cc.dd:85/SQLWEB?query=select+*+from+machine&amp;output=xml_v2 </code></pre> <p>which returns </p> <pre><code>&lt;Query&gt; &lt;SQL&gt;&lt;/SQL&gt; &lt;Fields&gt; &lt;MACHIN...
0
2016-08-12T11:17:13Z
38,916,962
<p><strong>First of all, querys in the url it's a horrible idea for security.</strong></p> <p>Use xml libs to parse the xml, and then iterate over the result to add to the db.</p> <pre><code>import xml.etree.ElementTree as ET tree = ET.parse('xml file') root = tree.getroot() # root = ET.fromstring(country_data_as...
0
2016-08-12T11:31:59Z
[ "python", "web-services", "xml-parsing" ]
Facebook data pull: how do I pull data before a specific date in python?
38,916,706
<p>I need to pull facebook data on or before 4th August 2016. I have used </p> <pre><code>import facebook user = 'nbcolympics' graph = facebook.GraphAPI(access_token) profile = graph.get_object(user) posts = graph.get_connections(profile['id'], 'posts') feeds = graph.get_connections(profile['id'], 'feed') </code></pre...
0
2016-08-12T11:18:32Z
38,917,403
<p>Based on the suggestion from CBroe, the timestamp could be added in the main command to extract data as per specific dates.</p> <pre><code>until_date_timestamp = int(datetime.strptime('04/08/2016', '%d/%m/%Y').strftime("%s")) graph = facebook.GraphAPI(access_token) profile = graph.get_object(user) posts = graph.get...
0
2016-08-12T11:57:50Z
[ "python", "facebook", "api" ]
Python library for handling linux's audit.log?
38,916,777
<p>I'm searching for a library that I could import to my python (3.5) code to ease the processing of audit.log (on my CentOS6 it is /var/log/audit/audit.log). I'm thinking about a library that processes the log lines as python arrays for example, enables the querying/filtering in it in a human way without writing all t...
-1
2016-08-12T11:21:58Z
38,916,954
<p>You can install the package: <code>setroubleshoot-server</code></p> <p>Then look at the file <code>/bin/sealert</code> which is a python program and does a lot of stuff with <code>audit.log</code> based on the flags.</p>
0
2016-08-12T11:31:39Z
[ "python", "linux", "audit" ]
Python library for handling linux's audit.log?
38,916,777
<p>I'm searching for a library that I could import to my python (3.5) code to ease the processing of audit.log (on my CentOS6 it is /var/log/audit/audit.log). I'm thinking about a library that processes the log lines as python arrays for example, enables the querying/filtering in it in a human way without writing all t...
-1
2016-08-12T11:21:58Z
38,956,161
<p>As I didn't found a library nor did anyone suggest one, so I have come up with this function using a binary provided by the audit's package:</p> <pre><code>def read_audit(before,now,user): auparam = " -sc EXECVE" cmd = "ausearch -ts " + before.strftime('%H:%M:%S') + " -te " + now.strftime('%H:%M:%S') + " -u...
0
2016-08-15T13:38:09Z
[ "python", "linux", "audit" ]
Python 3 json.loads - json.decoder error
38,916,901
<p>I'm trying to parse a json but it doesn't work. I remove the try and except in my code so you can see the Error Massege.</p> <pre><code>import sqlite3 import json import codecs conn = sqlite3.connect('geodata.sqlite') cur = conn.cursor() cur.execute('SELECT * FROM Locations') fhand = codecs.open('where.js','w', "...
0
2016-08-12T11:28:04Z
38,916,966
<p>You are converting a <code>bytes</code> value to a string the wrong way here:</p> <pre><code>data = str(row[1]) </code></pre> <p>You forced it to be a <code>str()</code> object, but for <code>bytes</code> objects that'll <em>include</em> the <code>b</code> prefix and quotes, because <code>bytes</code> objects don'...
0
2016-08-12T11:32:15Z
[ "python", "python-3.x" ]
python pandas get index boundaries from a series of Booleans
38,917,076
<p>I am trying cut videos based on some caracteristics. My current strategy leads on a <code>pandas</code> series of booleans for each frame, indexed by timestamp. <code>True</code> to keep it, <code>False</code> to dump it.</p> <p>As I plan to cut videos, i need to extract boundaries from this list, so that i can tel...
0
2016-08-12T11:38:39Z
38,918,102
<p>You could use <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.measurements.label.html" rel="nofollow"><code>scipy.ndimage.label</code></a> to identify the clusters of <code>True</code>s:</p> <pre><code>In [102]: ts Out[102]: 0.069347 False 0.131956 False 0.143948 False 0....
0
2016-08-12T12:34:19Z
[ "python", "pandas" ]
python pandas get index boundaries from a series of Booleans
38,917,076
<p>I am trying cut videos based on some caracteristics. My current strategy leads on a <code>pandas</code> series of booleans for each frame, indexed by timestamp. <code>True</code> to keep it, <code>False</code> to dump it.</p> <p>As I plan to cut videos, i need to extract boundaries from this list, so that i can tel...
0
2016-08-12T11:38:39Z
38,918,167
<p>I would use a Dataframe rather than a Series (it actually works with a Series as well). </p> <pre><code>df acquisitionTs Value 0 0.577331 False 1 0.611298 False 2 0.645255 False 3 0.679218 False 4 0.716538 False 5 0.784453 True 6 0.784453 True 7 ...
1
2016-08-12T12:37:46Z
[ "python", "pandas" ]
Join two lists into one dictionary
38,917,113
<p>These are my lists (both lists have the same length - 43 indices):</p> <pre><code>list1 = [u'UMTS', u'UMTS', u'UMTS', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM'...
0
2016-08-12T11:41:15Z
38,917,184
<p>You can use <code>collections.defaultdict()</code> and <code>zip()</code> function:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; &gt;&gt;&gt; d = defaultdict(list) &gt;&gt;&gt; &gt;&gt;&gt; for i, j in zip(list1, list2): ... d[i].append(j) ... &gt;&gt;&gt; d defaultdict(&lt;ty...
2
2016-08-12T11:45:12Z
[ "python", "python-2.7" ]
Join two lists into one dictionary
38,917,113
<p>These are my lists (both lists have the same length - 43 indices):</p> <pre><code>list1 = [u'UMTS', u'UMTS', u'UMTS', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM'...
0
2016-08-12T11:41:15Z
38,917,295
<p>You can implement like this.</p> <pre><code>result = {} for i in set(list1): result.update({i:[]}) for i,j in zip(list1,list2): result[i].append(j) </code></pre> <p><strong>Result</strong> </p> <pre><code>{u'UMTS': [u'60000', u'60000', u'60000'], u'GSM': [u'118629', u'118629', u'118629', u'118629', u'11...
1
2016-08-12T11:51:44Z
[ "python", "python-2.7" ]
Join two lists into one dictionary
38,917,113
<p>These are my lists (both lists have the same length - 43 indices):</p> <pre><code>list1 = [u'UMTS', u'UMTS', u'UMTS', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM'...
0
2016-08-12T11:41:15Z
38,917,516
<p>Tried with a single for loop. Isn't this what you want?</p> <pre><code>&gt;&gt;&gt; for i in range(0,len(list1)): ... if(mydict.get(list1[i]) is None): ... mydict[list1[i]]=[list2[i]] ... else: ... mydict[list1[i]].append(list2[i]) ... &gt;&gt;&gt; mydict {u'UMTS': [u'60000', u'60000...
1
2016-08-12T12:03:55Z
[ "python", "python-2.7" ]
How can I create a slice object for Numpy array?
38,917,173
<p>I've tried to find a neat solution to this, but I'm slicing several 2D arrays of the same shape in the same manner. I've tidied it up as much as I can by defining a list containing the 'x,y' center e.g. <code>cpix = [161, 134]</code> What I'd like to do is instead of having to write out the slice three times like s...
2
2016-08-12T11:44:52Z
38,917,247
<p>Yes you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.s_.html" rel="nofollow"><code>numpy.s_</code></a>:</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; a = np.arange(10).reshape(2, 5) &gt;&gt;&gt; &gt;&gt;&gt; m = np.s_[0:2, 3:4] &gt;&gt;&gt; &gt;&gt;&gt; a[m] array([[3], [8]]) <...
4
2016-08-12T11:48:56Z
[ "python", "arrays", "numpy" ]
Conditionally extracting rows of CSV files?
38,917,226
<p>I have a CSV file that looks like this:</p> <pre class="lang-none prettyprint-override"><code>Germany,1928,Food Iceland,1943,Oil France,1923,Plastics Russia,1901,Steal South Africa,1932,Silver Russia,1905,Gold Brazil,1901,Platinum </code></pre> <p>I want it to search through the first column and pull a row if it h...
-1
2016-08-12T11:47:48Z
38,917,308
<p>Try <a href="http://book.pythontips.com/en/latest/map_filter.html" rel="nofollow">filter</a>:</p> <pre><code>&gt;&gt;&gt; filter(lambda x: x[0] == 'Russia', datalist) [['Russia', '1901', 'Steal'], ['Russia', '1905', 'Gold']] </code></pre>
1
2016-08-12T11:52:13Z
[ "python", "csv" ]
Insert in sqlite python doesn't change table
38,917,254
<p>I'm create simple class for SQLite datadase and when I'm insert new row table doesn't change.</p> <p>DB.py</p> <pre><code>import sqlite3 class DB: def __init__(self, **kwargs): self.db = sqlite3.connect('passwods.db') self.c = self.db.cursor() self.c.execute('CREATE TABLE IF NOT EXISTS...
2
2016-08-12T11:49:18Z
38,917,917
<p>Your method <code>getAll</code> has no return statement. If you add it, you can see that the table actually changes:</p> <pre><code>def getAll(self): self.c.execute("SELECT * FROM passwords") return self.c.fetchall() </code></pre>
1
2016-08-12T12:23:30Z
[ "python", "sqlite" ]
BeautifulSoup: 'ResultSet' object has no attribute 'find_all'
38,917,302
<pre><code>from bs4 import BeautifulSoup import urllib2 url = 'http://www.data.jma.go.jp/obd/stats/etrn/view/monthly_s3_en.php?block_no=47401&amp;view=1' html = urllib2.urlopen(url).read() soup = BeautifulSoup(html) table = soup.find_all('table', class_='data2_s') rows = table.find_all('tr') print rows rows ...
0
2016-08-12T11:51:56Z
38,917,836
<p>Try this:</p> <pre><code>rows = table[0].find_all('tr') </code></pre> <p>Since <code>find_all</code> appears to return a Python <code>list</code>, you were trying to call <code>find_all</code> on a <code>list</code>, which doesn't have such a method.</p> <p>To get your resulting list(<code>rows</code>) into CSV f...
0
2016-08-12T12:19:49Z
[ "python", "csv", "beautifulsoup" ]
Recursively searching for specific filenames in Python 3.x
38,917,455
<p>I am currently using Python 3.x. I am looking to recursively search directories for two specific filenames. I know that each of the two filenames will exist in some of the directories. If one of the files exists, the other will. Once the files are identified, I then want to extract them to a list but somehow link th...
2
2016-08-12T12:00:22Z
38,917,608
<p>You should use the <a href="https://docs.python.org/3/library/glob.html#glob.iglob"><code>glob</code></a> module for that, specifically <code>glob.iglob(pathname, recursive=True)</code> for large directories.</p>
5
2016-08-12T12:08:38Z
[ "python", "python-3.x" ]
Iterating through a list of Pandas DF's to then iterate through each DF's row
38,917,604
<p>This may be a slightly insane question... I've got a single Pandas DF of articles which I have then split into multiple DF's so each DF only contains the articles from a particular year. I have then put these variables into a list called <code>box_of_years</code>.</p> <pre><code>indexed_df = article_db.set_index('d...
2
2016-08-12T12:08:11Z
38,917,870
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.year.html" rel="nofollow"><code>year</code></a> with custom function:</p> <pre>...
2
2016-08-12T12:21:26Z
[ "python", "pandas", "nltk" ]
Change text color of kivy ListView ListItemButton
38,917,678
<p>I'm trying to change the color of the text displayed on each of my buttons in a python kivy ListView object.</p> <p>My kivy code looks as follows (nothing much in my python code):</p> <pre><code>#:kivy 1.9.1 #:import BoxLayout kivy.uix.boxlayout.BoxLayout #:import ListAdapter kivy.adapters.listadapter.ListAdapter ...
0
2016-08-12T12:11:42Z
38,917,882
<p>Found an answer:</p> <p><a href="https://groups.google.com/forum/#!topic/kivy-users/LcLj02Qd2PY" rel="nofollow">https://groups.google.com/forum/#!topic/kivy-users/LcLj02Qd2PY</a></p> <pre><code>&lt;ListItemButton&gt;: selected_color: 200, 200, 200, 1 deselected_color: 0, 0, 0, 1 color: 0, 0, 0, 1 </c...
0
2016-08-12T12:21:51Z
[ "python", "listview", "kivy", "kivy-language" ]
running file opening dialog of server using tkFileDialog on client
38,917,741
<p>I am trying to make a simple system to transfer a file from server to client. I want to show the client a file open dialog using tkFileDialog. The problem is when I run the client &amp; server the dialog box gets opened in server rather than client. I thought about send the object of tkFileDialog via </p> <p><code>...
0
2016-08-12T12:14:43Z
38,919,540
<p>The file dialog works only for the system that opens it. You can't use it to pick files on a remote system. </p>
0
2016-08-12T13:45:53Z
[ "python", "python-2.7", "sockets", "tkinter", "operating-system" ]
Understanding VIew evaluation in Django
38,917,766
<p>I build web application with Django REST Framework. There is one simple view, which return reference Information with db fields.<br> <code>resources.py:</code></p> <pre><code>RESOURCES = { 'genres': GenreSerializer(Genre.objects.all(), many=True).data, 'authors': AuthorSerializer(Author.objects.all(), many=...
1
2016-08-12T12:15:55Z
38,918,358
<p>this is more related to python than to django. Let's say you hava file <code>lib.py</code></p> <pre><code>def say_hello(): print "hello" GREETINGS = { "hello": say_hello() } </code></pre> <p>now go to another python file (or the shell) and just import your <code>lib.py</code>, you'll print "hello" to the ...
2
2016-08-12T12:47:17Z
[ "python", "django", "django-rest-framework" ]
How to understand how workers are being used up in gunicorn
38,917,847
<p>I basically would like to know how gunicorn workers work. I have a server with 4 workers on a machine, with 4GB RAM, and 2 CPU and having nginx as the frontend serving requests and reverse proxy. I have simultaneous requests being sent to the server. </p> <ol> <li><p>I wish to know how the workers are being used up...
0
2016-08-12T12:20:18Z
38,919,375
<p>Short answer: Depends on the worker type and gunicorn configuration.</p> <p>Long answer:</p> <ol> <li>Yes, as long as there are workers available. When gunicorn is started, the <code>-w</code> option configures the number of workers, implementation of which varies depending on worker type. Some worker types use th...
1
2016-08-12T13:37:30Z
[ "python", "linux", "nginx", "flask", "gunicorn" ]
How indexing works in Pandas?
38,917,945
<p>I am new to python. This seems like a basic question to ask. But I really want to understand what is happening here </p> <pre><code>import numpy as np import pandas as pd tempdata = np.random.random(5) myseries_one = pd.Series(tempdata) myseries_two = pd.Series(data = tempdata, index = ['a','b','c','d','e']) myse...
6
2016-08-12T12:25:27Z
38,920,717
<p>When you are attempting to slice with <code>myseries[something]</code>, the <code>something</code> is often ambiguous. You are highlighting a case of that ambiguity. In your case, pandas is trying to help you out by guessing what you mean.</p> <pre><code>myseries_one[0] #As expected Out[74]: 0.29129291112626043 <...
5
2016-08-12T14:44:22Z
[ "python", "pandas" ]
Convert HTML into CSV
38,917,958
<p>I want to convert a HTML table as obtained from the script below into a CSV file, but got type error as follows:</p> <blockquote> <p>TypeError: sequence item 0: expected string, Tag found</p> </blockquote> <pre><code>from bs4 import BeautifulSoup import urllib2 url = 'http://www.data.jma.go.jp/obd/stats/etrn/v...
1
2016-08-12T12:26:26Z
38,918,435
<p>Use the <code>csv</code> module from Python to do this. You can obviously write more columns if you want, but the idea is that you're writing a <code>list</code> to the csv file. There are other options that you can specify in the <code>writer()</code> method if you'd like to quote things, escape things, etc.</p> <...
1
2016-08-12T12:51:22Z
[ "python", "csv", "beautifulsoup" ]
Convert HTML into CSV
38,917,958
<p>I want to convert a HTML table as obtained from the script below into a CSV file, but got type error as follows:</p> <blockquote> <p>TypeError: sequence item 0: expected string, Tag found</p> </blockquote> <pre><code>from bs4 import BeautifulSoup import urllib2 url = 'http://www.data.jma.go.jp/obd/stats/etrn/v...
1
2016-08-12T12:26:26Z
38,918,560
<p>Here is another way without using <code>csv</code> module:</p> <pre><code>fp=open('data.csv','w') for row in rows[:-1]: # Removed last row as it has empty cells that gives error which can also be resolved if needed fp.write(row.get_text(',') + '\n') fp.close() </code></pre> <p>You can directly open data.c...
0
2016-08-12T12:57:11Z
[ "python", "csv", "beautifulsoup" ]
Convert HTML into CSV
38,917,958
<p>I want to convert a HTML table as obtained from the script below into a CSV file, but got type error as follows:</p> <blockquote> <p>TypeError: sequence item 0: expected string, Tag found</p> </blockquote> <pre><code>from bs4 import BeautifulSoup import urllib2 url = 'http://www.data.jma.go.jp/obd/stats/etrn/v...
1
2016-08-12T12:26:26Z
38,919,491
<p>This is a job for the csv lib, getting each td inside each row and extracting the text, it will handle where there are missing values in each row:</p> <pre><code>from bs4 import BeautifulSoup import urllib2 import csv url = 'http://www.data.jma.go.jp/obd/stats/etrn/view/monthly_s3_en.php?block_no=47401&amp;view=1'...
1
2016-08-12T13:43:34Z
[ "python", "csv", "beautifulsoup" ]
Create new tokens and tuples from existing ones based on conditions
38,917,962
<p>This is very related to a <a href="http://stackoverflow.com/questions/38509239/need-to-remove-items-from-both-a-list-and-a-dictionary-of-tuple-value-pairs-at-s/38512276?noredirect=1#comment65178650_38512276">previous question</a> but I am having difficulties adapting for my use case.</p> <p>I have a sentence: <code...
1
2016-08-12T12:26:47Z
38,918,244
<p>This should work (if I understood correctly):</p> <pre><code>token_by_index = dict(enumerate(oldTokens)) groups = numberTokenIDs.keys() + locationTokenIDs.keys() for group in groups: token_by_index[group[0]] = ''.join(token_by_index.pop(index) for index in group) newTokens...
1
2016-08-12T12:42:10Z
[ "python", "loops", "tuples", "token", "tokenize" ]
Read random chunks from text file
38,918,219
<p>For a deep learning model I need to load my data by batches. For every epoch (full iteration over all the data) every row needs to be passed once, but it's important that the data is fed in a random order to the algorithm. My dataset is too big to read it fully in memory. It's sequence data with a variable length, t...
0
2016-08-12T12:40:44Z
38,919,973
<p>Build an index of the lines in memory (which requires a single pass through the file, but not all in memory) and then you can access lines randomly and fast. </p> <p>This isn't robust (no validation/range-checking, etc.) but:</p> <pre><code>import sys BUFFER_LEN = 1024 def findNewLines(s): retval = [] las...
2
2016-08-12T14:04:45Z
[ "python", "out-of-memory", "deep-learning" ]
Why does setup.py sweeps the content of the namespace before installing?
38,918,246
<p>I'm using namespaces with setuptools to distribute a same module in two different repositories. The goal is to get <code>mymodule.one</code> and <code>mymodule.two</code> installed, knowing that the content of <code>one</code> and <code>two</code> comes from different repos. But it looks like two <code>setup.py</cod...
0
2016-08-12T12:42:15Z
38,919,020
<p>There are two requirements for using name spaces correctly.</p> <ol> <li><code>__init__.py</code> of modules declare a name space</li> <li>setup.py defines <em>unique</em> name for each module</li> </ol> <p>The contents of both <code>__init__.py</code> files should be:</p> <pre><code>__import__('pkg_resources').d...
1
2016-08-12T13:20:18Z
[ "python", "python-3.x", "namespaces", "setuptools", "distutils" ]
change color for first level of contourf
38,918,306
<p>I'm using this script to plot a Ramachandran plot (the kind of plot is not really relevant here, what matters is the outputted graph):</p> <pre><code>#!/usr/bin/python # coding: utf-8 """ Script to plot a heat map of the dihedral angles http://stackoverflow.com/questions/26351621/turn-hist2d-output-into-contours-i...
0
2016-08-12T12:44:40Z
38,923,013
<p>Will a mask work, with everything below 15 in white?</p> <pre><code>from numpy import ma counts_masked = ma.masked_where(counts&lt;15, counts) plt.contourf(counts_masked.transpose(), 10, extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()]) </code></pre> <p>Or, another option might be:</p> <pre><code>levels =...
0
2016-08-12T16:54:51Z
[ "python", "matplotlib", "graph" ]
change color for first level of contourf
38,918,306
<p>I'm using this script to plot a Ramachandran plot (the kind of plot is not really relevant here, what matters is the outputted graph):</p> <pre><code>#!/usr/bin/python # coding: utf-8 """ Script to plot a heat map of the dihedral angles http://stackoverflow.com/questions/26351621/turn-hist2d-output-into-contours-i...
0
2016-08-12T12:44:40Z
38,927,126
<p>I actually found the answer an hour ago, based on this question: <a href="http://stackoverflow.com/questions/11386054/python-matplotlib-change-default-color-for-values-exceeding-colorbar-range">Python matplotlib change default color for values exceeding colorbar range</a></p> <p>I just wanted to do the opposite, so...
0
2016-08-12T22:11:51Z
[ "python", "matplotlib", "graph" ]
Concurrency with subprocess module. How can I do this?
38,918,337
<p>The code below works but each time you run a program, for example the notepad on target machine, the prompt is stuck until I quit the program.</p> <p>How to run multiple programs at the same time on target machine? I suppose it can be achieved with either the threads or subprocess modules, but I still can not use t...
9
2016-08-12T12:46:02Z
38,919,320
<p>Try something like:</p> <pre><code>import socket import time import subprocess import select IP = '192.168.1.33' PORT = 443 def connect(IP,PORT): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IP,PORT)) s.send('[!] Conexao recebida\n') return s except Except...
7
2016-08-12T13:35:26Z
[ "python", "python-3.x", "python-multithreading", "python-multiprocessing" ]
Pyspark: Using repartitionAndSortWithinPartitions with multiple sort Critiria
38,918,342
<p>Assuming I am having the following RDD:</p> <pre><code>rdd = sc.parallelize([('a', (5,1)), ('d', (8,2)), ('2', (6,3)), ('a', (8,2)), ('d', (9,6)), ('b', (3,4)),('c', (8,3))]) </code></pre> <p>How can I use <code>repartitionAndSortWithinPartitions</code> and sort by x[0] and after x[1][0]. Using the following I sor...
1
2016-08-12T12:46:29Z
38,918,964
<p>It is possible but you'll have to include all required information in the composite key:</p> <pre class="lang-py prettyprint-override"><code>from pyspark.rdd import portable_hash n = 2 def partitioner(n): """Partition by the first item in the key tuple""" def partitioner_(x): return portable_hash(...
3
2016-08-12T13:16:49Z
[ "python", "apache-spark", "pyspark" ]
import opencv in python
38,918,478
<p>I want to install opencv on Windows 7 64 bit and I'm using Python 3.5.1 32-bit. I downloaded the .whl file for opencv as said in the answer in this question: <a href="https://stackoverflow.com/questions/20953273/install-opencv-for-python-3-3">Install opencv for Python 3.3</a> given by @user3731622. But when I try to...
1
2016-08-12T12:53:39Z
38,918,565
<p>Are you sure it's <em>bumpy</em> in the error you get? <code>multiarray</code> is a part of <code>numpy</code>. In this post: <a href="http://stackoverflow.com/questions/20518632/importerror-numpy-core-multiarray-failed-to-import">ImportError: numpy.core.multiarray failed to import</a> the solution is to install <co...
0
2016-08-12T12:57:24Z
[ "python", "opencv" ]
Slice DataFrame using pandas Timestamp on DatetimeIndex
38,918,507
<p>I am reading a csv-file into a pandas DataFrame from disk and want to slice/filter the DataFrame based on the index timestamp.</p> <p>This is what I've got so far:</p> <pre><code>INDEX_COL_NAME = 'Zeit' DELIM_SIGN = ';' DECIMAL_SIGN = ',' KEEP_COLUMNS = [-2] ENCODING = 'ISO-8859-1' DATE = (2016, 8, 11) START = (1...
0
2016-08-12T12:55:13Z
38,923,756
<p>The indexing seems to be fine (you can also use <code>pd.Timestamp</code> or just strings for slicing instead of datetime objects).</p> <p>The issue is with day-month order. IIUC, strings <code>11.08.2016</code> are converted to November 8th instead of August 11th. Adding the argument <code>dayfirst=True</code> to ...
1
2016-08-12T17:46:22Z
[ "python", "datetime", "pandas", "dataframe", "timestamp" ]
Python: extract a 2D array from a 3D array
38,918,514
<p>I have a 3D numpy array (1L, 420L, 580L) the 2nd and 3rd dimension is a gray scale image that I want to display using openCV. How do I pull the 2D array from the 3D array?</p> <p>I created a short routine to do this, but I bet there is a better way.</p> <pre><code># helper function to remove 1st dimension def pull...
0
2016-08-12T12:55:31Z
38,918,887
<p>If you always only have the first dimension == 1, then you could simply reshape the array...</p> <pre><code>if in_array.shape[0] == 1: return in_array.reshape(in_array.shape[1:]) </code></pre> <p>otherwise, you can use numpy's advanced list slicing...</p> <pre><code>else: return in_array[0,:,:] </code></p...
1
2016-08-12T13:12:06Z
[ "python", "arrays", "opencv", "numpy" ]
Decode MULTIPLE objects JSON objects from a file to a python dictionary with (raw_decode)
38,918,525
<p>New in python :)</p> <p>I want to decode a long json file containing multiple objects to a python dictionary then process it to a database.</p> <p>Here,is my code</p> <pre><code>file=open('hi.json',encoding='utf-8') def readin(): return file.read(2048) def parse(): decoder = json.JSONDecoder(strict=False)...
1
2016-08-12T12:56:01Z
38,919,843
<p>You are only fetching the first value returned from <code>imputd</code>, as Rawing said. You need to iterate over the entire sequence it can return.</p> <pre><code>def main(): imputd = parse() objs = list(imputd) # Get them all, not just the first with open("output.txt", "w") as output: # Enco...
0
2016-08-12T13:58:23Z
[ "python", "json", "object", "decode" ]
Optimizing a binary tree function, huffman trees
38,918,619
<p>So the scenario is someone you know gives you a huffman tree but its not optimal (I know all huffman trees are optimal, just if it were hypothetically not optimal but does follow the huffman style of only leaves having values). </p> <p>The function should improve the tree as much as possible without changing the ac...
1
2016-08-12T13:00:21Z
39,282,167
<p>From the <a href="https://en.wikipedia.org/wiki/Huffman_coding#Compression" rel="nofollow">basic technique</a> of constructing Huffman Trees, the nodes whose value are least probable are the first ones to be linked to a parent node. Those nodes appear deeper within the Huffman Trees than any other nodes in them. Fro...
0
2016-09-01T23:13:57Z
[ "python", "function", "optimization", "tree", "huffman-coding" ]
Pandas: pivot table
38,918,623
<p>I have df:</p> <pre><code>ID,url,used_at,active_seconds,domain,search_engine,diff_time,period,code, category 08cd0141663315ce71e0121e3cd8d91f,market.yandex.ru/product/12858630?hid=91491&amp;track=fr_same,2016-03-20 23:19:49,6,yandex.ru,None,78.0,515,100.0, Search system 08cd0141663315ce71e0121e3cd8d91f,market.yande...
3
2016-08-12T13:00:35Z
38,918,957
<p>It looks like need:</p> <pre><code>table = pd.pivot_table(df, values='domain', index=['ID'], columns=['category'], aggfunc=lambda x: x.nunique()) print (table) category Internet shop Search system \ ID ...
2
2016-08-12T13:16:14Z
[ "python", "pandas", "dataframe", "unique", "pivot-table" ]
pandas invalid literal for long() with base 10 error
38,918,653
<p>I am trying to do: <code>df['Num_Detections'] = df['Num_Detections'].astype(int)</code></p> <p>And i get following error: </p> <blockquote> <p>ValueError: invalid literal for long() with base 10: '12.0'</p> </blockquote> <p>My data looks looks following:</p> <pre><code>&gt;&gt;&gt; df['Num_Detections'].head()...
0
2016-08-12T13:01:53Z
38,918,706
<p>There is some value, which cannot be converted to <code>int</code>.</p> <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow"><code>to_numeric</code></a> and get <code>NaN</code> where is problematic value:</p> <pre><code>df['Num_Detections'] = pd.to_n...
1
2016-08-12T13:03:44Z
[ "python", "pandas", "dataframe", "casting", "int" ]
applying dynamic solution to Pyqt5 connection
38,918,725
<p>Here is one simple code from Zetcode.com, that I am studying:</p> <pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial In this example, we create a skeleton of a calculator using a QGridLayout. author: Jan Bodnar website: zetcode.com last edited: January 2015 """ import sys from Py...
1
2016-08-12T13:04:30Z
38,918,997
<p>With <code>lambda</code> or <code>functools.partial</code>, you can do just that:</p> <pre><code>def on.click(self, numb): button_list[numb].setEnabled(False) </code></pre> <p>Invoke with <code>lambda</code>:</p> <pre><code>button_list[1].clicked.connect(lambda: self.on_click(1)) </code></pre> <p>Or with <co...
0
2016-08-12T13:18:38Z
[ "python", "user-interface", "dynamic", "pyqt5" ]
Smartsheet Cell History check
38,918,841
<p>My goal is to pull a cell's history if it was modified after a user specified date. However, since the cell history call is so big, I don't really want to request the entire cell history until after I check the dates. This is my code at current. </p> <pre><code>#get the cell history action = smartsheet.Cells.get_c...
0
2016-08-12T13:09:30Z
38,928,521
<p>You could do a <a href="http://smartsheet-platform.github.io/api-docs/?python#get-sheet" rel="nofollow">GET sheet</a> request first and use that to see the last modified dates of the rows. For rows that are last modified based on your given date. Then you'll know it is worth getting the cell history. This would work...
0
2016-08-13T02:07:55Z
[ "python", "date", "smartsheet-api" ]
Custom formset validation not working in django
38,918,867
<p>In my formset I would like to check each reading against a target if the reading is larger than the target do not save to db. For some reason I can't get this to work correctly because it still allows me to save. Any help would be greatly appreciated!</p> <p>all in views.py </p> <pre><code> #custom formset val...
0
2016-08-12T13:10:54Z
38,919,196
<p>The Django docs on <a href="https://docs.djangoproject.com/en/1.10/topics/forms/formsets/#custom-formset-validation" rel="nofollow">custom formset validation</a> show that you should create a <code>clean</code> method.</p> <p>You have named your method <code>insp_clean</code>, so Django will never call it. Rename t...
1
2016-08-12T13:29:15Z
[ "python", "django", "validation" ]
Finding all the bounding rectangles of all non-transparent regions in PIL
38,918,891
<p>I have a transparent-background image with some non-transparent text.</p> <p>And I want to find all the bounding boxes of each individual word in the text.</p> <p>Here is the code about creating a transparent image and draw some text ("Hello World", for example) , after that, do affine transform and thumbnail it.<...
1
2016-08-12T13:12:23Z
38,921,416
<p>For what you want to do you need to label the individual words and then compute the bounding box of each object with the same label. The most straigh forward approach here is just taking the min and max positions of the pixels that make up that word. The labeling is a little bit more difficult. For example you could...
0
2016-08-12T15:23:03Z
[ "python", "numpy", "image-processing", "python-imaging-library", "bounding-box" ]
Project Euler #17 Python - "Number letter counts"
38,918,947
<p>Here is the question:</p> <p>If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.</p> <p>If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?</p> <p>NOTE: Do not co...
-1
2016-08-12T13:16:04Z
38,919,144
<p>The code seems reasonable enough. I didn't put much thought into your definition of <code>u</code>, <code>t</code>, and <code>h</code>, but it seems correct. The only thing I noticed you are missing is the "one" from "one thousand".</p>
2
2016-08-12T13:26:51Z
[ "python", "list", "math" ]
Modify a specific x-axis tick label in python
38,918,971
<p>I am an undergrad newbie to the Python pyplot. What I want to do is to plot a function against a sequence, for example, <code>x = [1,2,3,4,5]</code>. </p> <p>The <code>pyplot.plot</code> function naturally gives a nice figure. But I want to replace on the x-axis the tick label "2" by a string say "key point" and at...
-2
2016-08-12T13:17:10Z
38,919,537
<p>This is how you do it:</p> <pre><code>from matplotlib import pyplot as plt x = [1,2,3,4,5] y = [1,2,0,2,1] plt.clf() plt.plot(x,y,'o-') ax = plt.gca() # grab the current axis ax.set_xticks([1,2,3]) # choose which x locations to have ticks ax.set_xticklabels([1,"key point",2]) # set the labels to display at those ...
0
2016-08-12T13:45:52Z
[ "python", "matplotlib" ]
Loop in python for moving averages based on condition
38,919,003
<p>i have 5 weeks sales data of product and store combination. Out of the 5 weeks , first three of them can be on promotions. Either 1st is on promotion, or 2nd or 3rd or all three or none of them are on promotions. so in total 8 conditions will be there. now i want to calculate a moving average kind of thing in pytho...
-2
2016-08-12T13:18:58Z
38,919,317
<p>would this make any sense?</p> <pre><code>sales_new[1] = average(sales_old[1],sales_old[2]) sales_new[2] = average(sales_old[1],sales_old[2],sales_old[3]) sales_new[3] = average(sales_old[2],sales_old[3],sales_old[4]) sales_new[4] = average(sales_old[3],sales_old[4],sales_old[5]) sales_new[5] = average(sales_old[4]...
0
2016-08-12T13:35:24Z
[ "python", "loops", "python-3.x", "for-loop" ]
Loop in python for moving averages based on condition
38,919,003
<p>i have 5 weeks sales data of product and store combination. Out of the 5 weeks , first three of them can be on promotions. Either 1st is on promotion, or 2nd or 3rd or all three or none of them are on promotions. so in total 8 conditions will be there. now i want to calculate a moving average kind of thing in pytho...
-2
2016-08-12T13:18:58Z
38,922,747
<p>At the time of writing, my edit to your question is still pending and you haven't confirmed whether I've understood your business rules correctly. Assuming I have, here's a solution I've tried to put together for you:</p> <pre><code>from typing import Generator, Dict, List, Tuple import numpy TOTAL_WEEKS = 5 de...
1
2016-08-12T16:36:07Z
[ "python", "loops", "python-3.x", "for-loop" ]
Regression: Test data for prediction requires class value? in Weka
38,919,132
<p>M5P tree model from weka.classifiers: python-weka-wrapper Each row in my arff file consists of 6 attributes with 6th attribute being the target variable for which the model is being trained. I am using weka.core.converters.ArffLoader to the arff file to train. After the training, if i want to make predictions with...
0
2016-08-12T13:26:14Z
38,920,295
<p>If you want <em>validation</em>, you should definitely provide target values; how does the algorithm know how well it's done otherwise? But if you just want it to predict on that set, it seems the best way is to fill the target spot with '?', so that the data still has the 6 attributes, with the target simply marke...
0
2016-08-12T14:22:45Z
[ "python", "weka" ]
Regression: Test data for prediction requires class value? in Weka
38,919,132
<p>M5P tree model from weka.classifiers: python-weka-wrapper Each row in my arff file consists of 6 attributes with 6th attribute being the target variable for which the model is being trained. I am using weka.core.converters.ArffLoader to the arff file to train. After the training, if i want to make predictions with...
0
2016-08-12T13:26:14Z
38,926,364
<p>You can use the <a href="http://weka.sourceforge.net/doc.dev/weka/filters/unsupervised/attribute/Add.html" rel="nofollow">Add</a> filter to introduce a new attribute. By default, this filter will mark all values of the new attribute as missing ("?"). Just make sure that the name of this new attribute and, in case of...
1
2016-08-12T20:58:10Z
[ "python", "weka" ]
Optimize 4D Numpy array construction
38,919,189
<p>I have a 4D array <code>data</code> of shape (50,8,2048,256) which are 50 groups containing 8 2048x256 pixel images. <code>times</code> is an array of shape (50,8) giving the time that each image was taken.</p> <p>I calculate a 1st order polynomial fit at each pixel for all images in each group, giving me an array...
1
2016-08-12T13:28:47Z
38,930,042
<p>Regarding the speed I see a lot of loops which is what should and often can be avoided due to the beauty of numpy. If I understand your problem fully you want to fit a first order polynom on 50 groups of 8 data points 2048 * 256 times. So for the fit the shape of your image does not play a role. So my suggestion is ...
0
2016-08-13T06:49:23Z
[ "python", "arrays", "numpy", "optimization", "slice" ]
Exporting data from python to text file using petl package in python
38,919,246
<p>I am trying to extract raw data from a text file and after processing the raw data, I want to export it to another text file. Below is the python code I have written for this process. I am using the "petl" package in python 3 for this purpose. 'locations.txt' is the raw data file.</p> <pre><code>import glob, os fr...
0
2016-08-12T13:31:37Z
39,088,838
<p>The template parameter to the toext function is not optional there is no default format for how the rows are written in this case, you must provide a template. Check the doc for toext here for an example: <a href="https://petl.readthedocs.io/en/latest/io.html#text-files" rel="nofollow">https://petl.readthedocs.io/e...
0
2016-08-22T21:15:46Z
[ "python", "etl" ]
Error while calling function through C DLL
38,919,272
<p>I have a DLL in which the following is the header and .c file: </p> <pre><code>//demo.h #define vers 0x1 __declspec export void getversion(ulong * version); //demo.c #include"demo.h" void getversion(ulong * version) { *version=(ulong)vers; } </code></pre> <p>The python script that I had written for calling the DL...
0
2016-08-12T13:33:11Z
38,919,408
<p>I think is this what you should do:</p> <pre><code>mydll = cdll.demo # just a simpler way to load the dll, not the solution yet ver = c_ulong() mydll.getversion(byref(ver)) print(ver.value) </code></pre>
0
2016-08-12T13:38:43Z
[ "python", "c", "dll", "ctypes" ]
Error while calling function through C DLL
38,919,272
<p>I have a DLL in which the following is the header and .c file: </p> <pre><code>//demo.h #define vers 0x1 __declspec export void getversion(ulong * version); //demo.c #include"demo.h" void getversion(ulong * version) { *version=(ulong)vers; } </code></pre> <p>The python script that I had written for calling the DL...
0
2016-08-12T13:33:11Z
38,920,415
<p>Here's a fully working example for windows&amp;vs, if you wanna try on linux you just need to change your datatypes and get rid of the windows headers:</p> <p><strong>demo.h</strong></p> <pre><code>#include &lt;windows.h&gt; ULONG g_version = 0x3; __declspec(dllexport) void set_version(ULONG version); __declspec...
0
2016-08-12T14:28:32Z
[ "python", "c", "dll", "ctypes" ]
Error while calling function through C DLL
38,919,272
<p>I have a DLL in which the following is the header and .c file: </p> <pre><code>//demo.h #define vers 0x1 __declspec export void getversion(ulong * version); //demo.c #include"demo.h" void getversion(ulong * version) { *version=(ulong)vers; } </code></pre> <p>The python script that I had written for calling the DL...
0
2016-08-12T13:33:11Z
38,962,712
<p>Your code isn't calling <code>getversion</code>. Your code creates a default <code>ulong()</code> (which is initialized to zero) and printing it.</p> <pre><code>version=c_ulong() print("Version=",version.value) </code></pre> <p>Here's working code:</p> <pre><code>from ctypes import * mydll = CDLL('demo.dll') my...
1
2016-08-15T20:41:12Z
[ "python", "c", "dll", "ctypes" ]
Test if a string contain a combination of a known string and unknown number in python
38,919,376
<p>If I have a string for example <code>line= "hello world 2"</code> and the number <code>2</code> can be any number so line could be <code>"hello world 4"</code> is there a way to test that using in operand, I am thinking of something like that </p> <pre><code>if "world %n" in line </code></pre> <p>but that is not...
1
2016-08-12T13:37:40Z
38,919,440
<pre><code>import re if re.search("world \d", line): ... </code></pre> <p>This uses a quick, simple <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regular expression</a> to check the line contains the word 'world' followed by a space followed by any number. </p>
0
2016-08-12T13:40:37Z
[ "python", "python-3.x", "find" ]
How to give a name to test?
38,919,394
<p>How do I give a name to unit test in Django?</p> <p>With RSpec I would do something like </p> <pre><code>it 'has a name!' do # do something end </code></pre> <p>But is it possible with Django so I can see normal names in PyCharm instead of this:</p> <p><a href="http://i.stack.imgur.com/QJyu2.png" rel="nofollow...
1
2016-08-12T13:38:26Z
38,919,658
<p>You could use a comment above the method name <code># ...</code> and set the the test suite verbosity to 2. This will print a description along with the test like so:</p> <p><code>&lt;test name&gt; test that so and so happens ... ok</code></p>
1
2016-08-12T13:50:17Z
[ "python", "django", "unit-testing", "integration-testing", "django-testing" ]
nginx connection timeout error with python, django and uwsgi
38,919,471
<p>I have setup a django + uwsgi + nginx server according to <a href="https://tghw.com/blog/multiple-django-and-flask-sites-with-nginx-and-uwsgi-emperor" rel="nofollow">https://tghw.com/blog/multiple-django-and-flask-sites-with-nginx-and-uwsgi-emperor</a></p> <p>The pages work fine when they return quickly. But I have...
0
2016-08-12T13:42:30Z
38,920,246
<p>Nginx is telling you that your upstream (uWSGI) has timed-out, so adjusting the timeout in Nginx's config won't help.</p> <p>Try adjusting the internal socket time-out. In your <code>uswgi.ini</code>, add:</p> <p><code>socket-timeout = 60</code></p> <p>P.S I see that you've looked at the 14th request out of 25. A...
0
2016-08-12T14:19:26Z
[ "python", "django", "nginx", "uwsgi" ]
How to skip blank line while taking input from user in python?
38,919,489
<p>I want to skip blank line (no value entered by user). I get this error.</p> <pre><code> Traceback (most recent call last): File "candy3.py", line 16, in &lt;module&gt; main() File "candy3.py", line 5, in main num=input() File "&lt;string&gt;", line 0 ^ SyntaxError: unexpected EOF while parsing </...
0
2016-08-12T13:43:31Z
38,919,660
<p>Use raw_input, and convert manually. This is also more save. For a full explaination, see <a href="https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#input.28.29" rel="nofollow">here</a>. For example, you could use the code below to skip anything which is not an integer.</p> <pre><code>x = None while...
0
2016-08-12T13:50:22Z
[ "python", "user-input" ]
How to skip blank line while taking input from user in python?
38,919,489
<p>I want to skip blank line (no value entered by user). I get this error.</p> <pre><code> Traceback (most recent call last): File "candy3.py", line 16, in &lt;module&gt; main() File "candy3.py", line 5, in main num=input() File "&lt;string&gt;", line 0 ^ SyntaxError: unexpected EOF while parsing </...
0
2016-08-12T13:43:31Z
38,919,782
<p>The behaviour you're getting is expected, read the <a href="https://docs.python.org/3/library/functions.html#input" rel="nofollow">input</a> docs.</p> <blockquote> <p>input([prompt])</p> <p>If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads...
0
2016-08-12T13:55:54Z
[ "python", "user-input" ]
Python - Dealing with Input Prompt in a Subprocesses
38,919,496
<p>I'm trying to get a python script on a remotely deployed embedded Linux device to execute an scp command. Executing the command is simple, but if the target server is not listed in the 'known_hosts' file, scp throws a warning that needs to be interacted with. Banging my head against this for days, and I can't solv...
0
2016-08-12T13:43:50Z
38,920,579
<p>The problem is likely that <code>scp</code> doesn't communicate using stdin/stdout/stderr in this case, but directly via the terminal.</p> <p>You can find a lot of similar questions as well as way to deal with it by searching for something like <code>scp input</code> on stackoverflow.</p> <p>Started subprocesses w...
0
2016-08-12T14:37:53Z
[ "python", "pipe", "subprocess", "popen" ]
How to parse oracle jdbc ezconnect with python
38,919,499
<p>I've tried to search ways how to parse with python an oracle jdbc string which can be in different formats, but didn't find anythng.</p> <p>Problem:</p> <p>Input string can be based on different patterns:</p> <ul> <li>jdbc:oracle:thin:@//hostname.example.ru:1521/database.example.ru</li> <li>jdbc:oracle:thin:@host...
0
2016-08-12T13:43:57Z
38,968,786
<p>I've read oracle docs about EZCONNECT syntax and wrote regex to parse it. The second string is a short version of standard jdbc pattern so i unified those regexp strings within one class to parse each variant.</p> <p>So here's jdbc connection string parser:</p> <pre><code># -*- coding: utf-8 -*- import re class...
0
2016-08-16T07:19:30Z
[ "python", "oracle", "parsing", "jdbc" ]
python - comparing a newly written file with filecmp.cmp() always returns False?
38,919,521
<p>I must be making a stupid mistake here, because this <em>should</em> be working. I'm thinking the file is staying open or something, and it's driving me nuts. </p> <p>This is for some regression test cases I have where I'm comparing generated output of a script ran against mock files to known good output files (key...
0
2016-08-12T13:44:58Z
38,919,745
<p>I'd suggest you add a <code>wait</code> to your subprocess to wait for it to complete</p> <pre><code>with open(out_file, 'wb') as out: p=subprocess.Popen(cmd.split(), stdout=out, stderr=subprocess.PIPE) p.wait() </code></pre> <p>If you don't wait, the subprocess starts, taking the file <code>out</code> as ...
1
2016-08-12T13:54:26Z
[ "python" ]
python - comparing a newly written file with filecmp.cmp() always returns False?
38,919,521
<p>I must be making a stupid mistake here, because this <em>should</em> be working. I'm thinking the file is staying open or something, and it's driving me nuts. </p> <p>This is for some regression test cases I have where I'm comparing generated output of a script ran against mock files to known good output files (key...
0
2016-08-12T13:44:58Z
38,920,342
<p>It doesn't matter that you opened the output file object as a context manager. It wouldn't even matter if you explicitly, manually closed the file object.</p> <p>That's because when you hand a Python file object to <code>subprocess.Popen()</code>, all it takes from that file object is the <em>file handle</em>, an i...
2
2016-08-12T14:25:13Z
[ "python" ]
Correlation: make a graph
38,919,546
<p>I have dataframe and I try to print graph. I use</p> <pre><code>df = pd.read_excel('resp1.xlsx') corr = df.corr() sns.set(context="paper", font="monospace") df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0) f, ax = plt.subplots(figsize=(12, 9)) sns.heatmap(corr, vmax=.8, square=True) networ...
0
2016-08-12T13:46:13Z
38,919,697
<p>I'm not sure, but I think those %1 errors are related to mixing 64 bit and 32 bit of app/dll. You also have the <code>win32</code> hint. Perhaps you use a 64 bit python with 32 bit package (pandas or other) or the opposite.</p>
0
2016-08-12T13:51:58Z
[ "python", "pandas", "matplotlib", "seaborn" ]
Do the Templates in django need to move to public while using Passenger
38,919,709
<p>Very familiar with python and Flask, but just getting started with Django.</p> <p><strong>ENVIRONMENT</strong></p> <p>Dreamhost, Django 1.9 (i think), python 2.7.3, Passenger </p> <p><strong>PROBLEM STMT</strong></p> <p>I have my app working and can generate an index page using HttpResponse straight from views.p...
0
2016-08-12T13:52:46Z
38,920,236
<p>The items in the <code>DIRS</code> list should be the full path, for example:</p> <pre><code>'DIRS': ['/path/to/CTracker/CTracker/templates'], </code></pre> <p>The Django settings file should have a <code>BASE_DIR</code> defined. You can use this with <code>os.path.join</code> to avoid hardcoding the full path.</p...
1
2016-08-12T14:18:49Z
[ "python", "django", "passenger" ]
Pymongo $in Query Not Working
38,919,756
<p>Seeing some strange behavior in Pymongo <code>$in</code> query. Looking for records that meet the following query:</p> <pre><code>speciesCollection.find({"SPCOMNAME":{"$in":['paddlefish','lake sturgeon']}}) </code></pre> <p>The query returns no records.</p> <p>If I change it to find_one the it works returning th...
4
2016-08-12T13:54:52Z
38,920,164
<p>I think you have a typo or some other error in your program as I just did a test with your sample data and query and it works - see the GIF</p> <p>Below is my test code which connects to the database called <code>so</code> and the collection <code>speciesCollection</code>, maybe you find the error in yours with it ...
3
2016-08-12T14:14:51Z
[ "python", "mongodb", "pymongo", "pymongo-3.x" ]
Get package version for conda meta.yaml from source file
38,919,840
<p>I'm trying to reorganize my python package versioning so I only have to update the version in one place, preferably a python module or a text file. For all the places I need my version there seems to be a way to load it from the source <code>from mypkg import __version__</code> or at least parse it out of the file a...
3
2016-08-12T13:58:13Z
39,009,038
<p>There are lots of ways to get to your endpoint. Here's what conda itself does...</p> <p>The source of truth for conda's version information is <code>__version__</code> in <code>conda/__init__.py</code>. It can be loaded programmatically within python code as <code>from conda import __version__</code> as you sugge...
1
2016-08-18T02:25:58Z
[ "python", "conda" ]
Second queue is not defined [python]
38,919,877
<p>I have a 3 processes running in one script. Process 1 passes data to Process 2, and then Process 2 passes data to Process 3. When I put data to queue2, error occurs that "Global name "queue2" is not defined", I am stuck on this error now...</p> <pre><code>if __name__ == '__main__': queue1 = mp.Queue() queue2 = mp....
0
2016-08-12T13:59:36Z
38,920,026
<p>Just as you passed <code>queue1</code> to <code>f2</code>, you also need to pass <code>queue2</code>.</p>
1
2016-08-12T14:07:15Z
[ "python", "multiprocessing" ]
Second queue is not defined [python]
38,919,877
<p>I have a 3 processes running in one script. Process 1 passes data to Process 2, and then Process 2 passes data to Process 3. When I put data to queue2, error occurs that "Global name "queue2" is not defined", I am stuck on this error now...</p> <pre><code>if __name__ == '__main__': queue1 = mp.Queue() queue2 = mp....
0
2016-08-12T13:59:36Z
38,920,057
<p>You can declare the queues as global:</p> <pre><code>def f2(q): global queue2 a = q.get() queue2.put(b) </code></pre>
0
2016-08-12T14:09:01Z
[ "python", "multiprocessing" ]
Second queue is not defined [python]
38,919,877
<p>I have a 3 processes running in one script. Process 1 passes data to Process 2, and then Process 2 passes data to Process 3. When I put data to queue2, error occurs that "Global name "queue2" is not defined", I am stuck on this error now...</p> <pre><code>if __name__ == '__main__': queue1 = mp.Queue() queue2 = mp....
0
2016-08-12T13:59:36Z
38,920,137
<p>This works : </p> <pre><code>import multiprocessing as mp queue1 = mp.Queue() queue2 = mp.Queue() def f1(q): x = 5 # do something to a get x q.put(x) def f2(in_queue, out_queue): a = in_queue.get() b = a + 2 # do something to a, to produce b out_queue.put(b) def f3(q): c = q.ge...
0
2016-08-12T14:13:13Z
[ "python", "multiprocessing" ]
How to return data from an API in Django?
38,920,003
<p>Im trying to learn how to use APIs in Django and I want to return some simple data from one within a web page in html. The API is Mozscape and when running it in a terminal one can obtain the score of a website out of 100 like so:</p> <pre><code>from mozscape import Mozscape client = Mozscape( 'api_user_id', ...
0
2016-08-12T14:06:09Z
38,920,227
<p>You can use:</p> <pre><code>return HttpResponse(json.dumps(data), content_type='application/json') </code></pre> <p>instead of render the form. Only you need to import json in the header and create an empty dict named "data".</p>
1
2016-08-12T14:18:23Z
[ "python", "json", "django", "api" ]
How to return data from an API in Django?
38,920,003
<p>Im trying to learn how to use APIs in Django and I want to return some simple data from one within a web page in html. The API is Mozscape and when running it in a terminal one can obtain the score of a website out of 100 like so:</p> <pre><code>from mozscape import Mozscape client = Mozscape( 'api_user_id', ...
0
2016-08-12T14:06:09Z
38,920,286
<p>I suggest this approach:</p> <pre><code>import requests response = requests.get(url) json_response = response.json() score = json_response['key_name'] </code></pre> <p>You can then simply render a template, add the score to the template context and display the value using {{ }}.</p> <p>You may also want to defi...
1
2016-08-12T14:22:33Z
[ "python", "json", "django", "api" ]
numpy vectorize max over segments of array
38,920,043
<p>How can I get rid of the python for loop? t is not uniformly spaced in general (just in the simple example). Solutions using pandas are also fine.</p> <pre><code>import numpy as np n = 100 t = np.arange(n) y = np.arange(n) edges = np.array([2., 5.5, 19, 30, 50, 72, 98]) indices = np.searchsorted(t, edges) maxe...
2
2016-08-12T14:08:11Z
38,920,668
<p>reduceat does the job nicely. I didn't know about that functionality 30 minutes ago.</p> <pre><code>maxes = np.maximum.reduceat(y, indices)[:-1] </code></pre>
3
2016-08-12T14:41:47Z
[ "python", "numpy", "vectorization" ]
PyInstaller on mac can't find libpython2.7
38,920,076
<p>I am trying to make a binary version of a Python script using PyInstaller 2.0. I am using a basic "hello world" tkinter script but imported a few dependencies that i need for a project to test Pyinstaller out. I am on a mac running Yosemite 10.10.5. This is my script:</p> <pre><code>#!/usr/bin/env python from Tkin...
1
2016-08-12T14:09:56Z
39,001,061
<p>Firstly, I see you are using conda. I ran into the exact same issue on Mac, specifically:</p> <pre><code>ERROR: Can not find path ./libpython2.7.dylib </code></pre> <p>trying to deploy an app I put together in a conda environment. </p> <p>After a lot of Googling and reading, I found that the current PyInstaller...
1
2016-08-17T15:46:05Z
[ "python", "exe", "pyinstaller" ]
Showing default required message after customizing template
38,920,133
<p>guys. I'm learning to use Django and I'm facing some issues: I created some required field forms, made some changes in the template because and the default required message no longer is shown when the field is left empty.</p> <p>Here is my code in forms.py:</p> <pre><code>class CreateProjectForm(forms.Form): proje...
0
2016-08-12T14:13:03Z
38,920,447
<p>If you <a href="https://docs.djangoproject.com/en/1.10/topics/forms/#looping-over-the-form-s-fields" rel="nofollow">loop over the form's fields in the template</a>, then you need to include the errors manually with <code>{{ field.errors }}</code>.</p> <pre><code>&lt;form class="form-horizontal" role="form" action="...
0
2016-08-12T14:30:31Z
[ "python", "django" ]
subprocess.call on long standing process
38,920,161
<p>I'm using subprocess.call to run an external ffmpeg process that usually takes 1hr approx. What I see is that apparently after some time (for example 20min) my program is closed without returning from subprocess.call.</p> <p>Example:</p> <pre><code>import subprocess try: ret = subprocess.call(['ffmpeg', 'param1'...
0
2016-08-12T14:14:46Z
38,921,168
<p>You might be running out of memory. Linux starts killing processes when the system is about to overflow. And it can kill the parent process rather than the offending <code>ffmpeg</code> process. Check your <code>dmesg</code> and syslog records.</p>
0
2016-08-12T15:08:39Z
[ "python" ]
Using "-t" option inside a requirements.txt file
38,920,244
<p>When I have, for example, a <code>requirements-dev.txt</code> and a <code>requirements.txt</code>, I know I can have <code>-r requirements.txt</code> inside <code>requirements-dev.txt</code>, for example, and running <code>pip install -r requirements-dev.txt</code> would install packages from both files.</p> <p>Tha...
1
2016-08-12T14:19:21Z
38,921,011
<pre><code>pip install -r requirements.txt -t /path/to/install </code></pre> <p>This should work. It worked for me.</p> <p>If you want different modules to be installed to different locations, then I think you might have to put them into multiple requirements text files. This is at least as far as I know</p>
1
2016-08-12T15:00:08Z
[ "python", "python-2.7", "pip" ]
assigning values in each column to be the sum of that column
38,920,257
<p>I have DataFrame and I am trying to assign all values in each column to be the sum of that column.</p> <pre><code>x = pd.DataFrame(data = [[1,2],[3,4],[5,6],[7,8],[9,10]],index=[1,2,3,4,5],columns=['a','b']) x a b 1 1 2 2 3 4 3 5 6 4 7 8 5 9 10 </code></pre> <p>the output should be</p> <pre><c...
4
2016-08-12T14:20:23Z
38,920,525
<p>I don't know exactly what you're trying to do but you can do something with list comprehension, like <code>f = lambda x : [column.sum() for column in x]</code></p>
0
2016-08-12T14:34:48Z
[ "python", "pandas", "lambda" ]
assigning values in each column to be the sum of that column
38,920,257
<p>I have DataFrame and I am trying to assign all values in each column to be the sum of that column.</p> <pre><code>x = pd.DataFrame(data = [[1,2],[3,4],[5,6],[7,8],[9,10]],index=[1,2,3,4,5],columns=['a','b']) x a b 1 1 2 2 3 4 3 5 6 4 7 8 5 9 10 </code></pre> <p>the output should be</p> <pre><c...
4
2016-08-12T14:20:23Z
38,920,570
<pre><code>for col in df: df[col] = df[col].sum() </code></pre> <p>or a slower solution that doesn't use looping...</p> <pre><code>df = pd.DataFrame([df.sum()] * len(df)) </code></pre> <p><strong>Timings</strong></p> <p>@jezrael Thanks for the timings. This does them on a larger dataframe and includes the for ...
5
2016-08-12T14:37:21Z
[ "python", "pandas", "lambda" ]
assigning values in each column to be the sum of that column
38,920,257
<p>I have DataFrame and I am trying to assign all values in each column to be the sum of that column.</p> <pre><code>x = pd.DataFrame(data = [[1,2],[3,4],[5,6],[7,8],[9,10]],index=[1,2,3,4,5],columns=['a','b']) x a b 1 1 2 2 3 4 3 5 6 4 7 8 5 9 10 </code></pre> <p>the output should be</p> <pre><c...
4
2016-08-12T14:20:23Z
38,920,899
<p>Another faster numpy solution with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html" rel="nofollow"><code>numpy.tile</code></a>:</p> <pre><code>print (pd.DataFrame(np.tile(x.sum().values, (len(x.index),1)), columns=x.columns, index=x.index)) ...
5
2016-08-12T14:54:07Z
[ "python", "pandas", "lambda" ]
assigning values in each column to be the sum of that column
38,920,257
<p>I have DataFrame and I am trying to assign all values in each column to be the sum of that column.</p> <pre><code>x = pd.DataFrame(data = [[1,2],[3,4],[5,6],[7,8],[9,10]],index=[1,2,3,4,5],columns=['a','b']) x a b 1 1 2 2 3 4 3 5 6 4 7 8 5 9 10 </code></pre> <p>the output should be</p> <pre><c...
4
2016-08-12T14:20:23Z
38,921,315
<p>Using <code>transform</code></p> <pre><code>x.stack().groupby(level=1).transform('sum').unstack() </code></pre> <p><a href="http://i.stack.imgur.com/Kh785.png" rel="nofollow"><img src="http://i.stack.imgur.com/Kh785.png" alt="enter image description here"></a></p>
3
2016-08-12T15:17:22Z
[ "python", "pandas", "lambda" ]
assigning values in each column to be the sum of that column
38,920,257
<p>I have DataFrame and I am trying to assign all values in each column to be the sum of that column.</p> <pre><code>x = pd.DataFrame(data = [[1,2],[3,4],[5,6],[7,8],[9,10]],index=[1,2,3,4,5],columns=['a','b']) x a b 1 1 2 2 3 4 3 5 6 4 7 8 5 9 10 </code></pre> <p>the output should be</p> <pre><c...
4
2016-08-12T14:20:23Z
38,921,627
<p>If your DataFrame consists of numbers, you can directly change its values:</p> <pre><code>df.values[:] = df.sum() </code></pre>
4
2016-08-12T15:33:20Z
[ "python", "pandas", "lambda" ]
Given coordinates for the location of players on a football pitch. What is the simplest method for finding groups of players?
38,920,431
<p>I thought something like having a 2d array where the location of players is marked with say a "1" and everywhere else is "0". The algorithm would determine how many groups they form. Definition of a group would be minimum 2 players who are beside each other. Thus, a group would be where a 1 has another 1 immediately...
-1
2016-08-12T14:29:20Z
38,929,139
<p>Create links between players that you know to be adjacent to each other and then run <a href="https://en.wikipedia.org/wiki/Disjoint-set_data_structure" rel="nofollow">https://en.wikipedia.org/wiki/Disjoint-set_data_structure</a>. (a.k.a Union-find)</p>
0
2016-08-13T04:18:38Z
[ "python", "algorithm" ]
Using JQuery to get JSON from Flask is returning null sometimes
38,920,585
<p>So I am developing on oracle Linux Server release 6.6 and I recently switched over to Apache 2.4 for my web server. I am developing a Flask web service so I was using Flask's local WSGI server to do all my debugging. </p> <p>In the application, i have a form and when you click the submit button, it does a JQuery $....
1
2016-08-12T14:38:04Z
39,059,335
<p>So i fixed the issue after like a week of digging. Looks like my requests were getting cancelled before returning back to the webpage. So what i did was a e.preventDefault() in my JavaScript function.</p> <p>so in my html i change it to</p> <p><code>&lt;form onsubmit="restoreDB(event)"&gt;</code></p> <p>and in my...
0
2016-08-20T22:42:03Z
[ "javascript", "jquery", "python", "apache", "flask" ]
linux detect system shutdown early in python
38,920,677
<p>I've been working on a monitoring script for a raspberry pi that i'm running as a headless server. As part of that I want it to react to a shutdown event. I tried using the <code>signal</code> module, and it does react and call my shutdown routine, however it happens very late into the shutdown routine, I'd like to ...
1
2016-08-12T14:42:10Z
38,920,825
<p>Don't react. <em>Schedule</em>.</p> <p>Unixoid systems have well-established mechanisms for starting and stopping services when starting up and shutting down. Just add one of these to be stopped when your system shuts down; you can typically even define an order at which these shutdown scripts can be called.</p> <...
1
2016-08-12T14:49:21Z
[ "python", "linux", "python-3.x", "shutdown" ]
unable to catch exception on connection pymysql
38,920,764
<pre><code>@classmethod def getSwDataPass(self, uid, pw, dbname='swdata', _count=0): result = None if dbname == '': dbname = input('Could not find a database by the name swdata. Please provide the database name : ') if dbname == '' or dbname is None: print('There was a problem conne...
1
2016-08-12T14:46:21Z
38,921,491
<p>Try to assign <code>pymysql.cursors.DictCursor</code> to a variable before calling the function:</p> <pre><code>try: cursor = pymysql.cursors.DictCursor connection = pymysql.connect(host='localhost', user=uid, password=pw, ...
1
2016-08-12T15:27:07Z
[ "python", "exception-handling", "pymysql" ]
Python - close windows if exists in order in tkinter
38,920,785
<pre><code> from tkinter import * class Main(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): global canvas self.parent.title('Python') self.pack(fill = BOTH, expand = 1) c...
1
2016-08-12T14:47:17Z
38,921,101
<p>Add your windows to a list as you create them, then destroy the windows in the order that you added them. </p> <pre><code>windows = [] root = Tk() ex = Main(root) root.geometry('700x500') windows.append(root) root2 = Tk() ex2 = Main2(root2) root2.geometry('500x500') windows.append(root2) def d(): for window ...
0
2016-08-12T15:05:23Z
[ "python", "class", "tkinter", "window", "try-except" ]