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
Move data from pyodbc to pandas
39,835,770
<p>I am querying a SQL database and I want to use pandas to process the data. However, I am not sure how to move the data. Below is my input and output. </p> <pre><code>import pyodbc import pandas from pandas import DataFrame cnxn = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\users\bart...
0
2016-10-03T16:01:04Z
39,835,930
<p>I was way over thinking this one!</p> <pre><code>cnxn = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\users\bartogre\desktop\CorpRentalPivot1.accdb;UID="";PWD="";') crsr = cnxn.cursor() for table_name in crsr.tables(tableType='TABLE'): print(table_name) cursor = cnxn.cursor() sql = "...
3
2016-10-03T16:10:51Z
[ "python", "pandas", "pyodbc" ]
Move data from pyodbc to pandas
39,835,770
<p>I am querying a SQL database and I want to use pandas to process the data. However, I am not sure how to move the data. Below is my input and output. </p> <pre><code>import pyodbc import pandas from pandas import DataFrame cnxn = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\users\bart...
0
2016-10-03T16:01:04Z
39,839,426
<p>Another, faster method. Please see data = pd.read_sql(sql, cnxn)</p> <pre><code>import pyodbc import pandas as pd from pandas import DataFrame from pandas.tools import plotting from scipy import stats import matplotlib.pyplot as plt import seaborn as sns cnxn = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.m...
0
2016-10-03T19:57:14Z
[ "python", "pandas", "pyodbc" ]
len(unicode string)
39,835,779
<pre><code>&gt;&gt;&gt; c='中文' &gt;&gt;&gt; c '\xe4\xb8\xad\xe6\x96\x87' &gt;&gt;&gt; len(c) 6 &gt;&gt;&gt; cu=u'中文' &gt;&gt;&gt; cu u'\u4e2d\u6587' &gt;&gt;&gt; len(cu) 2 &gt;&gt;&gt; s='𤭢' &gt;&gt;&gt; s '\xf0\xa4\xad\xa2' &gt;&gt;&gt; len(s) 4 &gt;&gt;&gt; su=u'𤭢' &gt;&gt;&gt; su u'\U00024b62' &gt;...
0
2016-10-03T16:01:33Z
39,835,844
<p>The Python <code>unicode</code> type holds <em>Unicode codepoints</em>, and is not meant to be an encoding. How Python does this internally is an implementation detail and not something you need to be concerned with most of the time. They are not UTF-16 code units, because UTF-16 is another codec you can use to enco...
0
2016-10-03T16:06:01Z
[ "python", "python-2.7", "unicode", "encoding", "utf-8" ]
array to tiff raster image with gdal
39,835,794
<p>Update </p> <p>i try to follow <a href="https://earthlab.github.io/python/DEM-slope-aspect-python/" rel="nofollow">this tutorial</a> </p> <p>but i dont know how can export to new tiff images slope/aspect with GDAL ?</p> <p>the full code :</p> <pre><code>from __future__ import division from osgeo import gdal from...
0
2016-10-03T16:02:40Z
39,835,884
<p>The error states exactly what the problem is. You are trying to multiply an <code>int</code> type by a <code>NoneType</code> (None). The most likely case is that <code>nodataval</code> is None, which would occur because the NoDataValue for filename's first raster band is not defined. Your print(nodataval) command sh...
1
2016-10-03T16:08:15Z
[ "python", "python-2.7", "numpy", "scipy" ]
re.search() if result is None
39,835,826
<p>How to make this pythonic?</p> <pre><code>def money_from_string(s): gold = re.search("([0-9]+)g", s) silver = re.search("([0-9]+)s", s) copper = re.search("([0-9]+)c", s) s = re.sub("[0-9]+g", "", s) s = re.sub("[0-9]+s", "", s) s = re.sub("[0-9]+c", "", s) assert (len(s.strip()) == 0) #...
0
2016-10-03T16:04:22Z
39,836,060
<p>If the value returned is <code>None</code>, you can simply check for none and replace it with <code>0</code>. This seems apt to what your are trying to do.</p> <pre><code>def money_from_string(s): gold = re.search("([0-9]+)g", s) silver = re.search("([0-9]+)s", s) copper = re.search("([0-9]+)c", s) ...
-1
2016-10-03T16:18:48Z
[ "python" ]
re.search() if result is None
39,835,826
<p>How to make this pythonic?</p> <pre><code>def money_from_string(s): gold = re.search("([0-9]+)g", s) silver = re.search("([0-9]+)s", s) copper = re.search("([0-9]+)c", s) s = re.sub("[0-9]+g", "", s) s = re.sub("[0-9]+s", "", s) s = re.sub("[0-9]+c", "", s) assert (len(s.strip()) == 0) #...
0
2016-10-03T16:04:22Z
39,836,194
<p>Here is how I would implement your program.</p> <p>Note:</p> <ul> <li>You must use <code>int()</code> to convert strings to integers</li> <li>I would separate the validation from the computation, but use the same regular expression in both cases.</li> <li>I would use a dictionary, not code, to hold the values of m...
1
2016-10-03T16:26:58Z
[ "python" ]
Auto indentation in VIM, version 7.4.52, Operating Sysytem :Ubuntu 14.04
39,835,836
<p>I am new to this programming world, currently I am reading from "Introduction to Computation and programming using Python " by John V Guttag , MIT press.</p> <p>How can I set the auto indentation on in VIM. What's happening now is that when I press enter after : it starts from new line.</p> <p>Is it possible ?</p...
0
2016-10-03T16:05:18Z
39,836,319
<p>Vim comes with several language indentation presets. To enable them, you need to add the following to Vim's user configuration file (<code>~/.vimrc</code>):</p> <pre><code>filetype indent plugin on </code></pre> <p>An easy way to do this from the terminal:</p> <pre><code>echo "filetype indent plugin on" &gt;&gt; ...
0
2016-10-03T16:34:59Z
[ "python", "vim" ]
Import tensorflow error
39,835,841
<p>I installed <strong>tensorflow</strong> using anaconda distribution and I am unable to use the same in python.</p> <p>When I import tensorflow using <code>import tensorflow</code> I get the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "...
0
2016-10-03T16:05:50Z
39,853,145
<p>You should uninstall tensorflow as well, and make sure protobuf is uninstalled. You can try <code>brew uninstall protobuf</code> as well. Then reinstall protobuf, and tensorflow. Tensorflow requires protobuf version 3.x</p> <pre><code>pip install 'protobuf&gt;=3.0.0a3' </code></pre> <p>You can test your protobu...
0
2016-10-04T13:05:57Z
[ "python", "osx", "python-2.7", "tensorflow" ]
curl command for an xmlrpc command
39,835,934
<p>so i have an XMLRPC server that has a command called start_apps</p> <p>normally from python I would run it like this</p> <pre><code>import xmlrpclib app=xmlrpclib.ServerProxy("http://localhost:6610/app_rpc") app.start_apps() </code></pre> <p>is there any way to call this method from a curl command?</p> <p>i'm i...
0
2016-10-03T16:11:11Z
39,836,925
<p>The following command will invoke the start_apps command by posting the XML data to the XMLRPC server:</p> <pre><code>curl -d "&lt;?xml version='1.0'?&gt;&lt;methodCall&gt;&lt;methodName&gt;start_apps&lt;/methodName&gt;&lt;/methodCall&gt;" http://localhost:6610/app_rpc </code></pre> <p>When invoked on Linux use si...
1
2016-10-03T17:14:23Z
[ "python", "curl", "xml-rpc" ]
Extracting information depending on user input from a dictionary
39,836,008
<p>I have the following information from a <a href="http://www.futbin.com/api?term=paul%20pogba" rel="nofollow">.json</a> loaded and stored in a variable <code>Data</code>:</p> <pre><code>Data = [ {u'rating': u'89', u'rare': u'1', u'name': u'Pogba', u'club_image': u'/content/fifa17/img/clubs/11.png', u'image': u'/...
0
2016-10-03T16:15:49Z
39,836,169
<p>Well in this case, you need to loop over your values and compare the one that has been input to the ones you already have, right?</p> <p>So <code>player_dict</code> is a list of dictionaries, and every dictionary contains properties about a player, of which <code>rating</code> is one. Also, let's say that <code>pla...
0
2016-10-03T16:25:37Z
[ "python", "json", "python-2.7", "dictionary" ]
Extracting information depending on user input from a dictionary
39,836,008
<p>I have the following information from a <a href="http://www.futbin.com/api?term=paul%20pogba" rel="nofollow">.json</a> loaded and stored in a variable <code>Data</code>:</p> <pre><code>Data = [ {u'rating': u'89', u'rare': u'1', u'name': u'Pogba', u'club_image': u'/content/fifa17/img/clubs/11.png', u'image': u'/...
0
2016-10-03T16:15:49Z
39,836,173
<p>You can use list comprehensions:</p> <pre><code>[record for record in Data if record.get("rating") == ratingWeWant] </code></pre> <p>where <code>ratingWeWant</code> is the rating you are searching for.</p> <p>That code will produce list of records from data that have specified rating, eg:</p> <p><code>[{u'rating...
0
2016-10-03T16:25:54Z
[ "python", "json", "python-2.7", "dictionary" ]
Extracting information depending on user input from a dictionary
39,836,008
<p>I have the following information from a <a href="http://www.futbin.com/api?term=paul%20pogba" rel="nofollow">.json</a> loaded and stored in a variable <code>Data</code>:</p> <pre><code>Data = [ {u'rating': u'89', u'rare': u'1', u'name': u'Pogba', u'club_image': u'/content/fifa17/img/clubs/11.png', u'image': u'/...
0
2016-10-03T16:15:49Z
39,836,315
<p>What you are trying to do is called a "lookup". Given a key (u'88', or other rating), you want a value (the dictionary where 'rating' is u'88'). A list object, like you currently have the dictionaries stored in, is not very good for such lookups, because you have to go through each index in the list, compare the rat...
0
2016-10-03T16:34:43Z
[ "python", "json", "python-2.7", "dictionary" ]
Extracting information depending on user input from a dictionary
39,836,008
<p>I have the following information from a <a href="http://www.futbin.com/api?term=paul%20pogba" rel="nofollow">.json</a> loaded and stored in a variable <code>Data</code>:</p> <pre><code>Data = [ {u'rating': u'89', u'rare': u'1', u'name': u'Pogba', u'club_image': u'/content/fifa17/img/clubs/11.png', u'image': u'/...
0
2016-10-03T16:15:49Z
39,836,704
<p>The other answers don't include your requirement that data should only be returned if the <code>rating</code> appears in <code>Data</code> once only.</p> <pre><code># First iterate over Data and count how many times that rating appears counter = {} for item in Data: rating = item['rating'] counter[rating] =...
0
2016-10-03T16:58:47Z
[ "python", "json", "python-2.7", "dictionary" ]
Replacing flask internal web server with Apache
39,836,011
<p>I have written a single user application that currently works with Flask internal web server. It does not seem to be very robust and it crashes with all sorts of socket errors as soon as a page takes a long time to load and the user navigates elsewhere while waiting. So I thought to replace it with Apache. </p> <p>...
0
2016-10-03T16:15:59Z
39,854,907
<p>This is the simple app with flask run on internal server: </p> <pre><code>from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() </code></pre> <p>To run it on apache server Check out <a href="http://flask.pocoo.org/docs/0.11/d...
0
2016-10-04T14:27:10Z
[ "python", "apache", "flask", "wsgi" ]
Reading serial and responding with Python
39,836,164
<p>Everyone, hello!</p> <p>I'm currently using trying to communicate with my Arduino (whom is hooked up my Raspberry Pi through Serial) and using the information in my Python script on my Raspberry Pi.</p> <p>That said, my Python script has to wait for the Arduino to report back it's data before I want the script to ...
0
2016-10-03T16:25:15Z
39,836,451
<p>use functions</p> <pre><code>def wait_for(ser,targetChar): resp = "" while True: tmp=ser.read(1) resp = resp + tmp if not tmp or tmp == targetChar: return resp first_resp = wait_for(ser,'a') second_resp = wait_for(ser,'c') while not second_resp.endswith('c'): print "RETR...
0
2016-10-03T16:43:37Z
[ "python", "pyserial" ]
Reading serial and responding with Python
39,836,164
<p>Everyone, hello!</p> <p>I'm currently using trying to communicate with my Arduino (whom is hooked up my Raspberry Pi through Serial) and using the information in my Python script on my Raspberry Pi.</p> <p>That said, my Python script has to wait for the Arduino to report back it's data before I want the script to ...
0
2016-10-03T16:25:15Z
39,838,771
<p>This worked out well for me to keep my while, and escape the block until I get what i want:</p> <pre><code>loop = 1 while loop == 1: message = ser.readline().rstrip() if message == "a": print "ready" continue if message == "b": print "Timeout" loop = 0 if message[0] == "c": print...
0
2016-10-03T19:11:27Z
[ "python", "pyserial" ]
Python Gtk3 set or change color for GdkPixbuf.Pixbuf from Gdk.RGBA or Gdk.Color
39,836,188
<p>How can I set or change the color of a GdkPixbuf.Pixbuf ?</p> <p>I can create and fill:</p> <pre><code>pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, False, 8, 32, 16) pixbuf.fill(0x000000) </code></pre> <p>But how to get a color from from Gdk.RGBA or Gdk.Color?</p> <p>edit:</p> <p>I tried so much thin...
0
2016-10-03T16:26:33Z
39,858,129
<p>Wow, this was very hard. I finally found an solution:</p> <pre><code>pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, True, 8, 16, 16) color = Gdk.color_parse("orange") fillr = (color.red / 256) &lt;&lt; 24 fillg = (color.green / 256) &lt;&lt; 16 fillb = (color.blue / 256) &lt;&lt; 8 fillcolor = fillr | fil...
0
2016-10-04T17:12:54Z
[ "python", "colors", "gtk3" ]
How to print only printable charcters in binary file (equvalent to strings under Linux)?
39,836,287
<p>I am undertaking conversion of my python application from python 2 to python 3. One of the functions which I use is to get the printable character out of binary file. I earlier used following function in python 2 and it worked great:</p> <pre><code>import string def strings(filename, min=4): with open(filename...
-2
2016-10-03T16:32:43Z
39,836,357
<p>In Python 3, opening a file in binary mode gives you <code>bytes</code> results. Iterating over a <code>bytes</code> object gives you <em>integers</em>, not characters, in the range 0 to 255 (inclusive). From the <a href="https://docs.python.org/3/library/stdtypes.html#bytes" rel="nofollow"><code>bytes</code> docume...
2
2016-10-03T16:37:36Z
[ "python", "string", "python-3.x" ]
How to print only printable charcters in binary file (equvalent to strings under Linux)?
39,836,287
<p>I am undertaking conversion of my python application from python 2 to python 3. One of the functions which I use is to get the printable character out of binary file. I earlier used following function in python 2 and it worked great:</p> <pre><code>import string def strings(filename, min=4): with open(filename...
-2
2016-10-03T16:32:43Z
39,837,691
<p> I am sure this will work. </p> <p>As a generator:</p> <pre class="lang-py prettyprint-override"><code>import string, _io def getPrintablesFromBinaryFile(path, encoding='cp1252'): global _io, string buffer = _io.BufferedReader(open(path, 'rb')) while True: byte = buffer.read(1) if byte...
-1
2016-10-03T18:01:24Z
[ "python", "string", "python-3.x" ]
BloomFilter is at capacity after 10 minutes
39,836,304
<p>I'm using <strong>Scrapy</strong> with a <strong>BloomFilter</strong> and after 10 minutes I have this error on loop :</p> <pre><code>2016-10-03 18:03:34 [twisted] CRITICAL: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/twisted/internet/task.py", line 517, in _oneWorkUnit re...
0
2016-10-03T16:34:09Z
39,836,342
<p>Use <a href="https://github.com/jaybaird/python-bloomfilter/blob/2bbe01ad49965bf759e31781e6820408068862ac/pybloom/pybloom.py#L287" rel="nofollow"><code>pybloom.ScalableBloomFilter</code></a> instead of <code>BloomFilter</code>.</p> <pre><code>from pybloom import ScalableBloomFilter from scrapy.utils.job import job_...
2
2016-10-03T16:36:28Z
[ "python", "web-scraping", "scrapy", "bloom-filter" ]
Comparing Arrays for Accuracy
39,836,318
<p>I've a 2 arrays:</p> <pre><code>np.array(y_pred_list).shape # returns (5, 47151, 10) np.array(y_val_lst).shape # returns (5, 47151, 10) np.array(y_pred_list)[:, 2, :] # returns array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 0., 0., ...
0
2016-10-03T16:34:57Z
39,836,606
<p>Sounds like you want something like this:</p> <pre><code>accuracy = (y_pred_list == y_val_lst).all(axis=(0,2)).mean() </code></pre> <p>...though since your arrays are clearly floating-point arrays, you might want to allow for numerical-precision errors rather than insisting on exact equality:</p> <pre><code>accur...
0
2016-10-03T16:53:02Z
[ "python", "arrays", "numpy" ]
Comparing Arrays for Accuracy
39,836,318
<p>I've a 2 arrays:</p> <pre><code>np.array(y_pred_list).shape # returns (5, 47151, 10) np.array(y_val_lst).shape # returns (5, 47151, 10) np.array(y_pred_list)[:, 2, :] # returns array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.], [ 0., 0., ...
0
2016-10-03T16:34:57Z
39,836,888
<p>You can find a lot of useful classification score in <code>sklearn.metrics</code>, particularly <code>accuracy_score()</code>. See the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html" rel="nofollow">doc here</a>, you would use it as:</p> <pre><code>import sklearn acc = ...
0
2016-10-03T17:11:40Z
[ "python", "arrays", "numpy" ]
Pandas missing rows when importing using delimiter ="|"
39,836,337
<p>I have a dataset with 51,347 rows. When import the data using pandas and set the delimiter to "|" , I lose 394 rows. </p> <pre><code> import pandas as pd df = pd.read_csv("Basin11.txt", sep='|', error_bad_lines=False, dtype={'Start Date': str, 'Greater Than/Less Than': str, 'Parameter Code': float, 'Start Time'...
2
2016-10-03T16:36:06Z
39,837,259
<p>I started going through your input file and found a number of errors that may be leading to the "missing rows".</p> <p>The comments line 3491 and 9805 have an opening <code>"</code> but is missing the closing <code>"</code>. This would cause matching issues, including the following rows as part of the comment body...
2
2016-10-03T17:33:49Z
[ "python", "pandas" ]
Simple Pygame animation stuttering
39,836,374
<p>I'm learning python <code>*\(^o^)/*</code></p> <p>I have a simple bouncing box window drawn using <code>Pygame</code>. Everything seems to be functioning properly, except for one minor annoyance. It stutters constantly! I have no idea what could be causing the stutter. I thought it might be lag, so I implemented a ...
0
2016-10-03T16:38:54Z
39,862,978
<p>This is a rewrite of your code that uses opengl instead for the rendering. The major changes are as follows:</p> <ol> <li>I used opengl immediate mode, which is out-of-date and deprecated, but is a lot easier to understand at first. Most of the gl calls are either in the player.draw() method or in the main loop.</l...
1
2016-10-04T22:54:01Z
[ "python", "pygame" ]
How to have beautiful soup fetch emails?
39,836,385
<p>Im working with beautiful soup and would like to grab emails to a depth of my choosing in my web scraper. Currently however I am unsure why my web scraping tool is not working. Everytime I run it, it does not populate the email list. </p> <pre><code>#!/usr/bin/python from bs4 import BeautifulSoup, SoupStrainer impo...
-1
2016-10-03T16:39:37Z
39,836,476
<p>You just need to look for the href's with mailto:</p> <pre><code>emails = [a["href"] for a in soup.select('a[href^=mailto:]')] </code></pre> <p>I presume <a href="https://www.google.com" rel="nofollow">https://www.google.com</a> is a placeholder for the actual site you are scraping as there are no mailto's to scr...
1
2016-10-03T16:45:04Z
[ "python", "email", "beautifulsoup" ]
Wait for a Request to complete - Python Scrapy
39,836,404
<p>I have a Scrapy Spider which scrapes a website and that website requires to refresh a token to be able to access them.</p> <pre><code>def get_ad(self, response): temp_dict = AppextItem() try: Selector(response).xpath('//div[@class="messagebox"]').extract()[0] print("Captcha found when scrapi...
3
2016-10-03T16:40:47Z
39,837,394
<p>This is how I would go on about it:</p> <pre><code>def get_p_token(self, response): # generate token ... yield Request(url = response.url, callback=self.no_captcha, method = "GET",priority=1, meta = response.meta, dont_filter=True) def get_ad(self, response): temp_dict = AppextItem() try: ...
0
2016-10-03T17:43:21Z
[ "python", "scrapy", "screen-scraping", "scrapy-spider" ]
PyMongo Only include field in document if value is not a NaN
39,836,449
<p>I have a significant amount of data that needs to be inserted into my MongoDB database using PyMongo. The data I have is currently stored in flat files and is sparse (i.e. many of the individual values are NaN). In Mongo DB I would like to not insert fields if values are NaN but I'm not sure how to do that (I should...
0
2016-10-03T16:43:28Z
39,927,306
<blockquote> <p>It's easy enough to check to see if one of my value's is NaN using <code>math.isnan()</code> but I can't figure out how to leave the entire field blank if that is the case.</p> </blockquote> <p>Based on your example code, you can do the following instead:</p> <pre><code># Create a strategy docum...
0
2016-10-08T00:00:23Z
[ "python", "mongodb", "insert", "pymongo", null ]
Appending letters to a list in a while loop
39,836,496
<p>I am trying to append the first word of a sentence to an empty list. The current code is below:</p> <pre><code>sentence = input("Enter sentence: ") subject = [] print (subject) x = 0 while True: letter = sentence[x] if letter != " ": print (letter) subject.append(letter) x = x + 1 ...
0
2016-10-03T16:46:24Z
39,836,558
<p>You'd better use <code>for</code> loop, it's less error-prone:</p> <pre><code>sentence = input('Enter sentence: ') subject = [] print(subject) for letter in sentence: if letter == ' ': break else: print(letter) subject.append(letter) print(subject) </code></pre> <p>If you want to...
1
2016-10-03T16:49:35Z
[ "python", "while-loop", "append" ]
Appending letters to a list in a while loop
39,836,496
<p>I am trying to append the first word of a sentence to an empty list. The current code is below:</p> <pre><code>sentence = input("Enter sentence: ") subject = [] print (subject) x = 0 while True: letter = sentence[x] if letter != " ": print (letter) subject.append(letter) x = x + 1 ...
0
2016-10-03T16:46:24Z
39,836,597
<p>Why not use the <code>split()</code> function instead of appending one letter at a time:</p> <pre><code>sentence = input("Enter sentence: ") split_sentence = sentence.split(" ") subject = [] subject.append(split_sentence[0]) print (subject) </code></pre> <p>or even more simplier:</p> <pre><code>sentence = input("...
0
2016-10-03T16:52:35Z
[ "python", "while-loop", "append" ]
Javascript implementation of Murmurhash3 to give the same result as Murmurhash3.cpp used by transform available in Python's sklearn
39,836,589
<p>(I am VERY sorry I am not allowed to add many URLs to help me better explain my problems in this post because I am new on StackOverflow and my StackOverflow account has very low privilege).</p> <p><strong>Summary</strong> </p> <p>Can anyone please guide me on how to modify <code>murmurhash3.js</code> (below) so th...
-1
2016-10-03T16:52:11Z
39,856,874
<p>Based on suggestions from @ChristopherOicles, I changed my <code>Javascript</code> code (my the header off my HTML code) to use <code>hashBytes</code> instead of <code>hashString</code> as shown below. I also noticed that I needed to change the returned value of <code>hashBytes</code> to its absolute value for my pu...
1
2016-10-04T15:58:15Z
[ "javascript", "python", "c++", "scikit-learn", "murmurhash" ]
Parsing UDP Packets
39,836,641
<p>I am building a UDP server to parse and verify incoming UDP packets. I am able to receive and parse packets but the header values are not what I expected. </p> <p>This is structure of incoming packet</p> <p>Packet ID ( 4 bytes )<br> Packet Sequence ( 4 bytes )<br> XOR Key ( 2 bytes )<br> Number of Checksums in...
2
2016-10-03T16:55:05Z
39,836,730
<p>Unfortunately the standard socket interface doesn't give you access to the data frames that your data arrive in, neither does it include the IP Datagram headers nor the TCP/UDP headers from the transport layer.</p> <p>To get hold of lower-level data you are forced to use the so-called <em>raw socket interface</em>,...
5
2016-10-03T17:01:03Z
[ "python", "python-2.7", "sockets", "networking", "udp" ]
How to do manual reload of file in iPython shell
39,836,702
<p>I have a file called sub.py, and I want to be able to call functions in it from the iPython shell. The iPython autoreload functionality has not been working very well, though. Sometimes it detects changes, sometimes it doesn't. </p> <p>Instead of debugging autoreload, I was wondering if there's a way to just manual...
0
2016-10-03T16:58:34Z
39,836,981
<p>I find my homebrewed <code>%reimport</code> to be very useful in this context:</p> <pre><code>def makemagic(f): name = f.__name__ if name.startswith('magic_'): name = name[6:] def wrapped(throwaway, *pargs, **kwargs): return f(*pargs,**kwargs) if hasattr(f, '__doc__'): wrapped.__doc__ = f.__doc__ ...
1
2016-10-03T17:18:27Z
[ "python", "ipython" ]
How does one add an item to GTK's "recently used" file list from Python?
39,836,725
<p>I'm trying to add to the "recently used" files list from Python 3 on Ubuntu.</p> <p>I am able to successfully <em>read</em> the recently used file list like this:</p> <pre><code>from gi.repository import Gtk recent_mgr = Gtk.RecentManager.get_default() for item in recent_mgr.get_items(): print(item.get_uri()) ...
12
2016-10-03T17:00:54Z
39,927,261
<p>A <code>Gtk.RecentManager</code> needs to emit the <code>changed</code> signal for the update to be written in a private attribute of the C++ class. To use a <code>RecentManager</code> object in an application, you need to start the event loop by calling <code>Gtk.main</code>:</p> <pre><code>from gi.repository impo...
10
2016-10-07T23:53:51Z
[ "python", "gtk", "pygtk", "gtk3" ]
Sampling from a Computed Multivariate kernel density estimation
39,836,779
<p>Say I have X and Y coordinates on a map and a non-parametric distribution of "hot zones" (e.g. degree of pollution on a geographic map positioned at X and Y coordinates). My input data are heat maps.</p> <p>I want to train a machine learning model that learns what a "hot zone" looks like, but I don't have a lot of ...
0
2016-10-03T17:04:16Z
39,840,955
<p>There are at least 3 high-quality kernel-density estimation implementations available for python:</p> <ul> <li><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html" rel="nofollow">scipy</a></li> <li><a href="http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.Ker...
1
2016-10-03T21:50:37Z
[ "python", "machine-learning", "statistics", "kernel-density" ]
Automate file downloading using a chrome extension
39,836,893
<p>I have a .csv file with a list of URLs I need to extract data from. I need to automate the following process: (1) Go to a URL in the file. (2) Click the chrome extension that will redirect me to another page which displays some of the URL's stats. (3) Click the link in the stats page that enables me to download the ...
0
2016-10-03T17:11:54Z
39,837,450
<p>There is a python package called mechanize. It helps you automate the processes that can be done on a browser. So check it out.I think mechanize should give you all the tools required to solve the problem.</p>
0
2016-10-03T17:46:19Z
[ "python", "automation", "imacros" ]
How to draw a precision-recall curve with interpolation in python?
39,836,953
<p>I have drawn a precision-recall curve using <code>sklearn</code> <code>precision_recall_curve</code>function and <code>matplotlib</code> package. For those of you who are familiar with precision-recall curve you know that some scientific communities only accept it when its interpolated, similar to this example <a hr...
4
2016-10-03T17:16:08Z
39,838,609
<p>A backward iteration can be performed to remove the increasing parts in <code>precision</code>. Then, vertical and horizontal lines can be plotted as specified in the answer of Bennett Brown to <a href="http://stackoverflow.com/questions/16930328/vertical-horizontal-lines-in-matplotlib">vertical &amp; horizontal lin...
1
2016-10-03T19:00:34Z
[ "python", "numpy", "matplotlib", "scikit-learn", "precision-recall" ]
How to draw a precision-recall curve with interpolation in python?
39,836,953
<p>I have drawn a precision-recall curve using <code>sklearn</code> <code>precision_recall_curve</code>function and <code>matplotlib</code> package. For those of you who are familiar with precision-recall curve you know that some scientific communities only accept it when its interpolated, similar to this example <a hr...
4
2016-10-03T17:16:08Z
39,862,264
<p><strong>@francis's</strong> solution can be vectorized using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.accumulate.html" rel="nofollow"><code>np.maximum.accumulate</code></a>.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt recall = np.linspace(0.0, 1.0, num=42) prec...
2
2016-10-04T21:44:27Z
[ "python", "numpy", "matplotlib", "scikit-learn", "precision-recall" ]
Generate Series with column names of DataFrame that match condition
39,837,029
<p>I have a data frame with many columns containing true/false values. E. g.</p> <pre><code>import pandas as pd data = pd.DataFrame([[True, True, False], [False, False, True], [True, False, True], [False, False, False], [True, True, F...
0
2016-10-03T17:20:44Z
39,837,205
<p>You can use <code>apply</code> method to loop through rows and use each row to subset the column names:</p> <pre><code>data.apply(lambda r: data.columns[r].tolist(), axis = 1) #0 [A, B] #1 [C] #2 [A, C] #3 [] #4 [A, B] #dtype: object </code></pre>
1
2016-10-03T17:31:06Z
[ "python", "pandas", "dataframe" ]
How to calculate the total time a log file covers in Python 2.7?
39,837,095
<p>So I have several log files, they are structured like this:</p> <pre><code>Sep 9 12:42:15 apollo sshd[25203]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=189.26.255.11 Sep 9 12:42:15 apollo sshd[25203]: pam_succeed_if(sshd:auth): error retrieving information about use...
0
2016-10-03T17:24:56Z
39,837,276
<p>If the entries are in a chronological order, you can just look at the first and at the last entry:</p> <pre><code>entries = lines.split("\n") first_date = entries[0].split("apollo")[0] last_date = entries[len(entries)-1].split("apollo")[0] </code></pre>
0
2016-10-03T17:35:08Z
[ "python" ]
How to calculate the total time a log file covers in Python 2.7?
39,837,095
<p>So I have several log files, they are structured like this:</p> <pre><code>Sep 9 12:42:15 apollo sshd[25203]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=189.26.255.11 Sep 9 12:42:15 apollo sshd[25203]: pam_succeed_if(sshd:auth): error retrieving information about use...
0
2016-10-03T17:24:56Z
39,837,383
<p>We don't have the year, so I took the current year. Read all the lines, convert the month to month index, and parse each date.</p> <p>Then sort it (so works even if logs mixed) and take first &amp; last item. Substract. Enjoy.</p> <pre><code>from datetime import datetime months = ["","Jan","Feb","Mar","Apr","May"...
0
2016-10-03T17:42:28Z
[ "python" ]
Building a Python script which runs Perl scripts. How to redirect stdout?
39,837,139
<p>I am writing a Python script that use some Perl scripts, but one of them uses stdout so I must use a redirection <code>&gt;</code> in bash to write this output to a file.</p> <p>All input and output files are text files.</p> <pre><code># -*- coding: utf-8 -*- import subprocess filename = input("What the name of ...
1
2016-10-03T17:27:11Z
39,838,479
<p>Here is an example of how you can use <code>bash</code> to redirect output to a file <code>test.txt</code>:</p> <pre><code>import subprocess #STAGE 2---------------------------------------------------------------------- subprocess.Popen(['bash', '-c', 'echo Hello &gt; test.txt']) #STAGE 3-----------------------...
0
2016-10-03T18:52:03Z
[ "python", "bash", "perl", "subprocess", "stdout" ]
Building a Python script which runs Perl scripts. How to redirect stdout?
39,837,139
<p>I am writing a Python script that use some Perl scripts, but one of them uses stdout so I must use a redirection <code>&gt;</code> in bash to write this output to a file.</p> <p>All input and output files are text files.</p> <pre><code># -*- coding: utf-8 -*- import subprocess filename = input("What the name of ...
1
2016-10-03T17:27:11Z
39,838,554
<p>I would handle the file in Python:</p> <pre><code>link = "stage2output" subprocess.call(["perl", "run_esearch.pl", filename, "result"]) with open(link, "w") as f: subprocess.call(["perl", "shrink.pl", "result"], stdout=f) subprocess.call(["perl", "shrink2.pl", link]) </code></pre> <p>On the off-chance that <co...
1
2016-10-03T18:57:06Z
[ "python", "bash", "perl", "subprocess", "stdout" ]
Building a Python script which runs Perl scripts. How to redirect stdout?
39,837,139
<p>I am writing a Python script that use some Perl scripts, but one of them uses stdout so I must use a redirection <code>&gt;</code> in bash to write this output to a file.</p> <p>All input and output files are text files.</p> <pre><code># -*- coding: utf-8 -*- import subprocess filename = input("What the name of ...
1
2016-10-03T17:27:11Z
39,842,384
<p>As far as I can tell, you have three Perl programs</p> <ul> <li><p><code>run_esearch.pl</code>, which expects two command-line parameters: the name of the input file and the name if the output file</p></li> <li><p><code>shrink.pl</code>, which expects a single command-line parameter: the name of the input file. It ...
2
2016-10-04T00:19:42Z
[ "python", "bash", "perl", "subprocess", "stdout" ]
Changing a global variable in a function without using global keyword
39,837,160
<p><a href="http://i.stack.imgur.com/EQUph.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/EQUph.jpg" alt="screenshot of code from a textbook"></a></p> <p>Here is my code:</p> <pre><code>def L_value_Change(k): global L L = k return L def applyF_filterG(L, f, g): L k = [] for i in L: ...
-1
2016-10-03T17:28:13Z
39,837,413
<p>You need the <code>global</code> keyword when you want to rebind the global variable to a different object. But you don't need it if all you want to do is change a mutable object. In your case <code>L</code> is a list and can be mutated in place with a slice operation <code>L[:] = k</code>. To demonstrate:</p> <pre...
1
2016-10-03T17:44:05Z
[ "python", "python-3.x" ]
Changing a global variable in a function without using global keyword
39,837,160
<p><a href="http://i.stack.imgur.com/EQUph.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/EQUph.jpg" alt="screenshot of code from a textbook"></a></p> <p>Here is my code:</p> <pre><code>def L_value_Change(k): global L L = k return L def applyF_filterG(L, f, g): L k = [] for i in L: ...
-1
2016-10-03T17:28:13Z
39,837,500
<p>Lists are <strong>mutable</strong> objects, and as such, to change them all you have to do is just pass them as an argument to the function. </p> <pre><code>def f(i): return i + 2 def g(i): return i &gt; 5 l = [0, -10, 5, 6, -4] def applyF_filterG(L, f, g): for val in L[:]: if not g(f(val)): ...
1
2016-10-03T17:48:54Z
[ "python", "python-3.x" ]
Changing a global variable in a function without using global keyword
39,837,160
<p><a href="http://i.stack.imgur.com/EQUph.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/EQUph.jpg" alt="screenshot of code from a textbook"></a></p> <p>Here is my code:</p> <pre><code>def L_value_Change(k): global L L = k return L def applyF_filterG(L, f, g): L k = [] for i in L: ...
-1
2016-10-03T17:28:13Z
39,845,975
<p>Here's my code which avoids mutating on the list that you're trying to iterate upon. </p> <pre><code>def applyF_filterG(L,f,g): """ Assumes L is a list of integers Assume functions f and g are defined for you. f takes in an integer, applies a function, returns another integer ...
0
2016-10-04T06:56:22Z
[ "python", "python-3.x" ]
Given a positive int, finds out how many numbers # from 1 to n inclusive evenly divide n
39,837,263
<p>The goal is to "find out how many numbers # from 1 to n inclusive evenly divide n" when given a positive int. Here is the code I have so far</p> <pre><code>def num_divisors(n): for i in n: if n &gt;= 1: answer = i // n return answer </code></pre> <p>I'm currently getting the error <code>'int'...
0
2016-10-03T17:34:12Z
39,837,291
<pre><code>for i in range(n): </code></pre> <p>This loops over all values from 0 to n-1</p> <p>EDIT: </p> <p>Your code is still flawed, and has other errors. You should have an accumulator counting the number of values which divide <code>n</code></p>
0
2016-10-03T17:36:02Z
[ "python" ]
Given a positive int, finds out how many numbers # from 1 to n inclusive evenly divide n
39,837,263
<p>The goal is to "find out how many numbers # from 1 to n inclusive evenly divide n" when given a positive int. Here is the code I have so far</p> <pre><code>def num_divisors(n): for i in n: if n &gt;= 1: answer = i // n return answer </code></pre> <p>I'm currently getting the error <code>'int'...
0
2016-10-03T17:34:12Z
39,837,388
<p>The working code is following</p> <pre><code>def num_divisors(n): count_d = 0 for i in range(1, n+1): if n % i == 0: count_d += 1 return count_d </code></pre>
0
2016-10-03T17:42:58Z
[ "python" ]
Given a positive int, finds out how many numbers # from 1 to n inclusive evenly divide n
39,837,263
<p>The goal is to "find out how many numbers # from 1 to n inclusive evenly divide n" when given a positive int. Here is the code I have so far</p> <pre><code>def num_divisors(n): for i in n: if n &gt;= 1: answer = i // n return answer </code></pre> <p>I'm currently getting the error <code>'int'...
0
2016-10-03T17:34:12Z
39,837,453
<p>Here is a one-liner that should do what you want:</p> <pre><code>sum(n % i == 0 for i in range(1, n + 1)) </code></pre> <p>Issues with your code:</p> <ul> <li>Trying to iterate over an int, instead of an iterator.</li> <li>Floor-dividing <code>i</code> by <code>n</code>, which will always give you 0</li> <li>Retu...
0
2016-10-03T17:46:26Z
[ "python" ]
Given a positive int, finds out how many numbers # from 1 to n inclusive evenly divide n
39,837,263
<p>The goal is to "find out how many numbers # from 1 to n inclusive evenly divide n" when given a positive int. Here is the code I have so far</p> <pre><code>def num_divisors(n): for i in n: if n &gt;= 1: answer = i // n return answer </code></pre> <p>I'm currently getting the error <code>'int'...
0
2016-10-03T17:34:12Z
39,838,634
<p>This code reduces the number of divisions to approx. sqrt(n). For example if 100 == 4 x 25, then also 100 == 25 x 4, so after testing 4 we don't have to test 25.</p> <pre><code>def num_divisors(n): num = 0 for i in range(1, n + 1): d, m = divmod(n, i) if d &lt; i: break if...
0
2016-10-03T19:02:06Z
[ "python" ]
how to remove high frequency contents from the image for inverse fourier transform
39,837,268
<p>I saw a couple of documents explaining this in opencv, however my objective is to do this with numpy &amp; scipy.</p> <p>I guess I have to mask the outer region of the spectrum with some sort of circle, as I masked the center of the spectrum with 60x60 rectangle for the low frequency filtering. But I couldn't under...
2
2016-10-03T17:34:39Z
39,837,494
<p>You can just substract the image with low frequencies removed from your original image:</p> <pre><code>original = np.copy(fshift) fshift[crow-30:crow+30, ccol-30:ccol+30] = 0 f_ishift= np.fft.ifftshift(original - fshift) </code></pre> <p><a href="http://i.stack.imgur.com/VjoXu.png" rel="nofollow"><img src="http://...
1
2016-10-03T17:48:18Z
[ "python", "numpy", "fft" ]
I would like to know how to iterate through df.column3 find match in df.column2 and add name of df.column1 based on matches to a new column df.column4
39,837,361
<p>Test data looks like: <code> Column1 Column2 Column3 johnny 100 900 matty 300 100 grapy 400 300 snapp 500 300 </code></p> <p>Expected Result:</p> <p><code> Column1 Column2 Column3 Column4 johnny 100 900 None matty 300 100 johnny grapy 400 300 matty snapp 500 ...
0
2016-10-03T17:41:09Z
39,837,637
<p>You could do this using a dictionnary of possible values :</p> <pre><code>df = pd.DataFrame([['matty', 300, 900], ['grapy', 400, 300], ['snapp', 500, 300]], columns=['Column1', 'Column2', 'Column3']) df = df.set_index('Column2') dic = df['Column1'].to_dict() df['Column4'] = [dic[n] if n in dic.keys() else None for...
1
2016-10-03T17:57:55Z
[ "python", "pandas" ]
I would like to know how to iterate through df.column3 find match in df.column2 and add name of df.column1 based on matches to a new column df.column4
39,837,361
<p>Test data looks like: <code> Column1 Column2 Column3 johnny 100 900 matty 300 100 grapy 400 300 snapp 500 300 </code></p> <p>Expected Result:</p> <p><code> Column1 Column2 Column3 Column4 johnny 100 900 None matty 300 100 johnny grapy 400 300 matty snapp 500 ...
0
2016-10-03T17:41:09Z
39,838,539
<p>If it doesn't work properly, its because you have duplicate values: </p> <pre><code>df['Column4'] = df.Column2.map(dict(zip(df.Column3, df.Column1))) </code></pre>
0
2016-10-03T18:56:19Z
[ "python", "pandas" ]
Python: Call a variable from a function to an if statement
39,837,402
<p>I am trying to practice my modular programming with this assignment. I found out how to call the variables into my main function, but for my if statement in evenOdd(), I am not sure how to call the value. I get the error 'randNum' is not defined.</p> <pre><code>from random import randint def genNumber(): randNu...
0
2016-10-03T17:43:32Z
39,837,535
<p>You can either define randNum in the global scope or just pass it as a variable to your evenOdd() function, like this evenOdd( randNum ).</p>
2
2016-10-03T17:50:39Z
[ "python", "function", "variables" ]
How to return False when using issubset and an empty set
39,837,416
<p>When I have two sets e.g.</p> <pre><code>s1 = set() s2 = set(['somestring']) </code></pre> <p>and I do </p> <pre><code>print s1.issubset(s2) </code></pre> <p>it returns <code>True</code>; so apparently, an empty set is always a subset of another set.</p> <p>For my analysis, it should actually return <code>F...
3
2016-10-03T17:44:18Z
39,837,467
<p>I would do that like this:</p> <pre><code>s1 &lt;= s2 if s1 else False </code></pre> <p>It should be faster, because it uses the built-in operators supported by sets rather than using more expensive function calls and attribute lookups. It's logically equivalent.</p>
4
2016-10-03T17:46:59Z
[ "python", "optimization", "set" ]
How to return False when using issubset and an empty set
39,837,416
<p>When I have two sets e.g.</p> <pre><code>s1 = set() s2 = set(['somestring']) </code></pre> <p>and I do </p> <pre><code>print s1.issubset(s2) </code></pre> <p>it returns <code>True</code>; so apparently, an empty set is always a subset of another set.</p> <p>For my analysis, it should actually return <code>F...
3
2016-10-03T17:44:18Z
39,837,492
<p>Instead of using an <code>if</code> you can force the result to be a <code>bool</code> by doing this:</p> <pre><code>def check_set(s1, s2): return bool(s1 and s1.issubset(s2)) </code></pre>
2
2016-10-03T17:48:10Z
[ "python", "optimization", "set" ]
How to return False when using issubset and an empty set
39,837,416
<p>When I have two sets e.g.</p> <pre><code>s1 = set() s2 = set(['somestring']) </code></pre> <p>and I do </p> <pre><code>print s1.issubset(s2) </code></pre> <p>it returns <code>True</code>; so apparently, an empty set is always a subset of another set.</p> <p>For my analysis, it should actually return <code>F...
3
2016-10-03T17:44:18Z
39,837,506
<p>Why not just return the value? That way, you avoid having to write <code>return True</code> or <code>return False</code>.</p> <pre><code>def check_set(s1, s2): return bool(s1 and s1.issubset(s2)) </code></pre>
1
2016-10-03T17:49:15Z
[ "python", "optimization", "set" ]
How to return False when using issubset and an empty set
39,837,416
<p>When I have two sets e.g.</p> <pre><code>s1 = set() s2 = set(['somestring']) </code></pre> <p>and I do </p> <pre><code>print s1.issubset(s2) </code></pre> <p>it returns <code>True</code>; so apparently, an empty set is always a subset of another set.</p> <p>For my analysis, it should actually return <code>F...
3
2016-10-03T17:44:18Z
39,837,564
<p>Instead of using an empty set, you could use a set with an empty value:</p> <p><code>s1 = set([''])</code> or <code>s1 = set([None])</code></p> <p>Then your <code>print</code> statement would work as you expected.</p>
-1
2016-10-03T17:52:38Z
[ "python", "optimization", "set" ]
How to return False when using issubset and an empty set
39,837,416
<p>When I have two sets e.g.</p> <pre><code>s1 = set() s2 = set(['somestring']) </code></pre> <p>and I do </p> <pre><code>print s1.issubset(s2) </code></pre> <p>it returns <code>True</code>; so apparently, an empty set is always a subset of another set.</p> <p>For my analysis, it should actually return <code>F...
3
2016-10-03T17:44:18Z
39,838,310
<p>You can take advantage of how Python evaluates the truthiness of an object <strong>plus</strong> how it short-circuits boolean <code>and</code> expressions with:</p> <pre><code>bool(s1) and s1 &lt;= s2 </code></pre> <p>Essentially this means: if <code>s1</code> is something not empty AND it's a subset of <code>s2<...
2
2016-10-03T18:41:34Z
[ "python", "optimization", "set" ]
Got an extra line on python plot
39,837,495
<p>i'm using pyplot to show the FFT of the signal 'a', here the code:</p> <pre><code>myFFT = numpy.fft.fft(a) x = numpy.arange(len(a)) fig2 = plt.figure(2) plt.plot(numpy.fft.fftfreq(x.shape[-1]), myFFT) fig2.show() </code></pre> <p>and i get this figure <a href="http://i.stack.imgur.com/21CFm.png" rel="nofollow"><im...
1
2016-10-03T17:48:25Z
39,837,748
<p>Have a look at <code>plt.plot(numpy.fft.fftfreq(x.shape[-1])</code>: the first and last points are the same, hence the graph "makes a loop"</p> <p>You can do <code>plt.plot(sorted(numpy.fft.fftfreq(x.shape[-1])),myFFT)</code> or <code>plt.plot(myFFT)</code></p>
0
2016-10-03T18:04:43Z
[ "python", "numpy", "matplotlib", "fft" ]
Got an extra line on python plot
39,837,495
<p>i'm using pyplot to show the FFT of the signal 'a', here the code:</p> <pre><code>myFFT = numpy.fft.fft(a) x = numpy.arange(len(a)) fig2 = plt.figure(2) plt.plot(numpy.fft.fftfreq(x.shape[-1]), myFFT) fig2.show() </code></pre> <p>and i get this figure <a href="http://i.stack.imgur.com/21CFm.png" rel="nofollow"><im...
1
2016-10-03T17:48:25Z
39,839,205
<p>Instead of <code>sorted</code>, you might want to use <code>np.fft.fftshift</code> to center you 0th frequency, this deals properly with odd- and even-size signals. Most importantly, you need to apply the transform on both x and y vectors you are plotting.</p> <pre><code>plt.plot(np.fft.fftshift(np.fft.fftfreq(x.sh...
0
2016-10-03T19:41:34Z
[ "python", "numpy", "matplotlib", "fft" ]
Converting List of Multidimensional Arrays to Single Multidimensional Array?
39,837,546
<p>Let Y be a list of 100 ndarrays, such that Y[i] is an ndarray of an image, its shape is 160x320x3.</p> <p>I want X no be an ndarrays that contains all the images, I do as follows:</p> <pre><code>x = [ y[i] for i in range(0,10) ] </code></pre> <p>But it produces a list of of 100 160X320X3 ndarrays. How can I modif...
0
2016-10-03T17:51:33Z
39,837,652
<p>Calling <code>np.array</code> on <code>Y</code> (i.e <code>np.array(Y)</code>) should turn the list of ndarrays into one ndarray, with the size of the first axis corresponding to the length of the list.</p> <p><em>Demo</em>:</p> <pre><code>&gt;&gt;&gt; x = np.array([[1,2], [3,4]]) &gt;&gt;&gt; c = [x,x] # list of ...
2
2016-10-03T17:58:40Z
[ "python", "numpy" ]
convert pgsql int array into python array
39,837,711
<p>I have numeric data (int) stored in pgsql as arrays. These are <code>x,y,w,h</code> for rectangles in an image e.g. <code>{(248,579),(1,85)}</code></p> <p>When reading to my python code (using psycopg) I get it as a string (?). I am now trying to find the best way to obtain a python array of ints from that string. ...
0
2016-10-03T18:02:43Z
39,837,972
<p>Assuming that you wouldn't be able to change the input format, you could remove any unneeded characters, then split on the <code>,</code>'s or do the opposite order.</p> <pre><code>data = '{(248,579),(1,85)}' data.translate(None, '{}()').split(',') </code></pre> <p>will get you a list of strings.</p> <p>And</p> ...
1
2016-10-03T18:19:32Z
[ "python", "arrays", "postgresql", "psycopg2" ]
convert pgsql int array into python array
39,837,711
<p>I have numeric data (int) stored in pgsql as arrays. These are <code>x,y,w,h</code> for rectangles in an image e.g. <code>{(248,579),(1,85)}</code></p> <p>When reading to my python code (using psycopg) I get it as a string (?). I am now trying to find the best way to obtain a python array of ints from that string. ...
0
2016-10-03T18:02:43Z
39,839,059
<p>If you mean the rectangle is stored in Postgresql as an array of points:</p> <pre><code>query = ''' select array[(r[1])[0],(r[1])[1],(r[2])[0],(r[2])[1]]::int[] from (values ('{"(248,579)","(1,85)"}'::point[])) s (r) ''' cursor.execute(query) print cursor.fetchone()[0] </code></pre> <p>Returns a Python in...
0
2016-10-03T19:31:32Z
[ "python", "arrays", "postgresql", "psycopg2" ]
Untraceable HTTP redirection?
39,837,713
<p>I'm currently working on a project to track products from several websites. I use a python scraper to retrieve all the URLs related to the listed products, and later, regularly check if these URLs are still active.</p> <p>To do so I use the Python requests module, run a get request and look at the response's status...
0
2016-10-03T18:02:45Z
39,837,840
<p>The page has a <a href="https://en.wikipedia.org/wiki/Meta_refresh" rel="nofollow">meta tag</a>, that redirects the page to the root URL:</p> <pre class="lang-html prettyprint-override"><code>&lt;meta http-equiv="refresh" content="0; URL=/" /&gt; </code></pre>
1
2016-10-03T18:10:25Z
[ "javascript", "python", "http", "redirect" ]
How do I hide a word in a random number matrix?
39,837,732
<p>I am a Python beginner and am stuck here. I have written the following program that generates a matrix of random numbers.</p> <pre><code>def randsq(size): for i in range(size): for j in range(size): print(random.randint(0,9), end = '') print() </code></pre> <p>Is there anyway I can ...
-1
2016-10-03T18:03:36Z
39,839,244
<p>Modified code:</p> <pre class="lang-python prettyprint-override"><code>import random def randsq(word): size = len(word) for i in range(size): for j in range(size): if i == j: # we are at a diagonal-value print(word[i], end='') # it's the i-th diag -&gt; choose i-th char...
1
2016-10-03T19:44:10Z
[ "python", "algorithm", "matrix", "crossword" ]
Pandas to_sql() performance - why is it so slow?
39,837,781
<p>I am running into performance issues with Pandas and writing DataFrames to an SQL DB. In order to be as fast as possible I use <a href="http://www.memsql.com/" rel="nofollow">memSQL</a> (it's like MySQL in code, so I don't have to do anything). I benchmarked my instance just now:</p> <pre><code>docker run --rm -it ...
0
2016-10-03T18:06:45Z
39,841,318
<p>In case someones gets a similar situation:</p> <p>I removed SQlalchemy and used the (deprecated) MySQL flavor for Pandas' <code>to_sql()</code> function. The speedup is more than 120 %. I don't recommend to use this, but it works for me at the moment.</p> <pre><code>import MySQLdb import mysql.connector from sqla...
0
2016-10-03T22:22:02Z
[ "python", "performance", "pandas", "memsql" ]
Simple Quiz - How Do I Link Variables?
39,837,837
<p>I'm stuck trying to figure out how to match the correct answer with the correct question. Right now if the user's answer is equal to any of the answers, it returns correct. Please help.</p> <pre><code>easy_question = "The capitol of West Virginia is __1__" medium_question = "The device amplifies a signal is an __2_...
-1
2016-10-03T18:10:16Z
39,837,898
<p>You will want to keep track of the <code>question</code>:</p> <pre><code>question = choose_difficulty(user_input) print(question) answer = input("What is your answer?") def check_answer(question, answer): if questions_and_answers[question] == answer: return "Correct" return "Incorrect" print(check_...
1
2016-10-03T18:14:49Z
[ "python" ]
Simple Quiz - How Do I Link Variables?
39,837,837
<p>I'm stuck trying to figure out how to match the correct answer with the correct question. Right now if the user's answer is equal to any of the answers, it returns correct. Please help.</p> <pre><code>easy_question = "The capitol of West Virginia is __1__" medium_question = "The device amplifies a signal is an __2_...
-1
2016-10-03T18:10:16Z
39,838,251
<p>The way I would do it: create 2 variables, x and y. If the users chooses "Easy", it sets x to 1, "Medium" sets it to 2 and so on. Then you ask him for an answer. The answer to the easy question, if correct, sets y to 1, on the medium to 2 and so on. Then you have a check if x == y. If yes, then he has answered corre...
-1
2016-10-03T18:37:43Z
[ "python" ]
Django - Problems with get_or_create()
39,838,013
<p>I'm facing problems using get_or_create() in my view. What I want to do is have the User get or create an instance of the Keyword model whenever he wants to add a keyword.</p> <p>I have a Keyword model that looks like this:</p> <pre><code>class Keyword(models.Model): word = models.CharField(max_length=30, uniq...
1
2016-10-03T18:21:47Z
39,848,938
<p>I do believe CreateView isn't the right class for this. You should use <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-editing/#updateview" rel="nofollow">UpdateView</a> instead and override the <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-single-object/#...
0
2016-10-04T09:37:35Z
[ "python", "django" ]
pandas read_csv() method supports zip archive reading but not to_csv() method supports zip archive saving
39,838,026
<p>Pandas 0.18 supports read_csv zip file as argument and reading zipped csv table correctly into data frame. But when i am trying to use to_csv() method to save data frame as zipped csv, i am getting error. According to official documentation, zip format not supported in to_csv() method. Any thoughts? Thank you.</p> ...
0
2016-10-03T18:22:17Z
39,851,453
<p>Indeed, zip format not supported in to_csv() method according to this <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow">official documentation</a>, the allowed values are ‘gzip’, ‘bz2’, ‘xz’.</p> <p>If you really want the 'zip' format, you can tr...
0
2016-10-04T11:45:07Z
[ "python", "csv", "pandas", "zip" ]
Find last possible page of Plask-SQLAlchemy paginate
39,838,028
<p>I am using paginate of sqlalchemy to paginate my query like following but in my front page I want to implement a next button (or a numerical page navigation links like 1,2,3,4..) and when it reaches at the last page I don't want to show user the next button (or know the maximum number of pages available in the page ...
0
2016-10-03T18:22:24Z
39,838,289
<p>Check out <a href="http://flask-sqlalchemy.pocoo.org/2.1/api/?highlight=paginate#flask.ext.sqlalchemy.Pagination" rel="nofollow"><code>Pagination</code></a> class docs.</p> <pre><code>query = (Blog.query.filter(Blog.title.like('%'+query+'%')) .paginate(page=start, per_page=size)) </code></pre> <...
0
2016-10-03T18:40:07Z
[ "python", "flask", "sqlalchemy", "flask-sqlalchemy" ]
All possibilities permutations of 0 and 1
39,838,211
<p>I want to list all possible permutations of 0 and 1 six times for probability reasons.</p> <p>I started out like this, thinking, it was a piece of cake; until all combinations are listed the code should keep on randomising the values. However once 0 and 1 are in the list it stops, i thought "for range in 6" would g...
0
2016-10-03T18:35:02Z
39,838,389
<p>I didn't understand if you are looking for a solution, or for a fix for your code. If you just look for a solution, you can do this much easier and more efficiently using <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow"><code>itertools</code></a> like so:</p> <pre><code>&g...
1
2016-10-03T18:46:38Z
[ "python", "permutation" ]
All possibilities permutations of 0 and 1
39,838,211
<p>I want to list all possible permutations of 0 and 1 six times for probability reasons.</p> <p>I started out like this, thinking, it was a piece of cake; until all combinations are listed the code should keep on randomising the values. However once 0 and 1 are in the list it stops, i thought "for range in 6" would g...
0
2016-10-03T18:35:02Z
39,838,456
<p>I understand you want to check in how many iterations you'll reach the 64 possible combinations. In that case this code does it:</p> <pre><code>import math import random combs = set() nb_iterations = 0 while len(combs)&lt;64: nb_iterations+=1 a = (tuple(random.randint(0,1) for _ in range(6))) if a in c...
0
2016-10-03T18:50:55Z
[ "python", "permutation" ]
Python writing (xlwt) to an existing Excel Sheet, drops charts and formatting
39,838,220
<p>Am using python to automate some tasks and ultimately write to an existing spreadsheet. Am using the xlwt, xlrd and xlutils modules. </p> <p>So the way I set it up is to open the file, make a copy, write to it and then save it back to the same file. When I do the last step, all excel formatting such as comments and...
1
2016-10-03T18:35:29Z
39,840,495
<p>Could you do this with win32com?</p> <pre><code>from win32com import client ... xl = client.Dispatch("Excel.Application") wb = xl.Workbooks.Open(r'\test\test2.xls') ws = wb.Worksheets[10] for i,e in enumerate(WSM_1V,1): ws.Cells[i][0].Value = float(e) wb.save wb.Close() xl.Quit() xl = None </code></pre>
0
2016-10-03T21:13:08Z
[ "python", "excel", "xlrd", "xlwt", "xlutils" ]
Python writing (xlwt) to an existing Excel Sheet, drops charts and formatting
39,838,220
<p>Am using python to automate some tasks and ultimately write to an existing spreadsheet. Am using the xlwt, xlrd and xlutils modules. </p> <p>So the way I set it up is to open the file, make a copy, write to it and then save it back to the same file. When I do the last step, all excel formatting such as comments and...
1
2016-10-03T18:35:29Z
39,840,505
<p>Using those packages, there is no way around losing the comments and charts, as well as many other workbook features. The <code>xlrd</code> package simply does not read them, and the <code>xlwt</code> package simply does not write them. <code>xlutils</code> is just a bridge between the other two packages; it can't r...
0
2016-10-03T21:13:44Z
[ "python", "excel", "xlrd", "xlwt", "xlutils" ]
How should I deal with file handles when I return a generator?
39,838,268
<p>I have this function in my code:</p> <pre><code>def load_fasta(filename): f = open(filename) return (seq.group(0) for seq in re.finditer(r"&gt;[^&gt;]*", f.read())) </code></pre> <p>This will leave the file open indefinitely, which isn't good practice. How do I close the file when the generator is exhauste...
0
2016-10-03T18:38:39Z
39,838,323
<p>Use <code>yield</code> instead of a single generator expression.</p> <pre><code>def load_fasta(filename): with open(filename) as f: for seq in re.finditer(r"&gt;[^&gt;]*", f.read()): yield seq.group(0) for thing in load_fasta(filename): ... </code></pre> <p>The <code>with</code> statem...
1
2016-10-03T18:42:07Z
[ "python", "functional-programming", "generator" ]
Reading multiple .csv files from different directories into pandas DataFrame
39,838,332
<p>My DataFrame has a index SubjectID, and each Subject ID has its own directory. In each Subject directory is a .csv file with info that I want to put into my DataFrame. Using my SubjectID index, I want to read in the header of the .csv file for every subject and put it into a new column in my DataFrame. </p> <p>Each...
0
2016-10-03T18:42:40Z
39,839,049
<p>Assuming your subject folders are in <code>mydirectory</code>, you can just create a list of all folders in the directory and then add the csv's into your filelist.</p> <pre><code>import os parent_dir = '/home/mydirectory' subject_dirs = [os.path.join(parent_dir, dir) for dir in os.listdir(parent_dir) if os.path.i...
0
2016-10-03T19:30:56Z
[ "python", "csv", "pandas", "dataframe", "operating-system" ]
Reading multiple .csv files from different directories into pandas DataFrame
39,838,332
<p>My DataFrame has a index SubjectID, and each Subject ID has its own directory. In each Subject directory is a .csv file with info that I want to put into my DataFrame. Using my SubjectID index, I want to read in the header of the .csv file for every subject and put it into a new column in my DataFrame. </p> <p>Each...
0
2016-10-03T18:42:40Z
39,839,347
<p>Consider the recursive method of <a href="https://www.tutorialspoint.com/python/os_walk.htm" rel="nofollow">os.walk()</a> to read all directories and files <em>top-down</em> (default=<code>TRUE</code>) or <em>bottom-up</em>. Additionally, you can use regex to check names to filter specifically for .csv files. </p> ...
0
2016-10-03T19:51:43Z
[ "python", "csv", "pandas", "dataframe", "operating-system" ]
Pandas Groupby Return Average BUT! exclude NaN
39,838,367
<p>So Im trying to make sense of the pandas groupby function and to reduce a large data frame I have. Here is an example:</p> <pre><code> A B 2016-09-23 19:36:08+00:00 NaN 34.0 2016-09-23 19:36:11+00:00 NaN 33.0 2016-09-23 19:36:12+00:00 24.1 NaN 2016-09-23 19:36:14+...
1
2016-10-03T18:44:32Z
39,838,422
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>resample</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tseries.resample.Resampler.mean.html" rel="nofollow"><code>Resampler.mean</code></a>, whi...
2
2016-10-03T18:49:17Z
[ "python", "pandas", "dataframe" ]
Django REST Framework prevent multiple validation queries in batch create
39,838,400
<p>When trying to do bulk inserts using Django/Django Rest Framework 3, the validation step is causing <code>n * related_model_fields</code> queries, which is causing a lot of unnecessary latency. </p> <p>In the example below, <code>Thing</code> has two related fields, one being user (added in the view), and the other...
0
2016-10-03T18:47:16Z
39,866,439
<p>You'll likely want to roll your own validators and replace the default's one. For example, on the <code>User</code> you'll have a UniqueValidator that will query the DB for existing <code>username</code>. You could remove it and deal with that constraint explicitly by yourself - done that for some batch import.</p>
0
2016-10-05T06:01:44Z
[ "python", "django", "django-rest-framework" ]
Write a program that asks the user for a string and then prints the string in upper case
39,838,416
<p>I am learning programming language by my own from (CEMC Python from scratch) and this is my first programming language. I spend more than 3 hour to solve this PROBLEM. Please help to solve this so I can get to know what I was doing wrong.</p>
-4
2016-10-03T18:48:30Z
39,838,523
<pre><code># python 2.x &gt;&gt;&gt;text = raw_input() # python 3.x &gt;&gt;&gt;text = input() &gt;&gt;&gt;print(text.upper()) </code></pre>
2
2016-10-03T18:55:24Z
[ "python" ]
How to do calculations in lists with *args in Python 3.5.1
39,838,419
<p>I'm not even sure how to ask this question; I've been doing programming for about a month and the progress I've made on this program is still a little bit above my head, so I'm sorry if the question is a little incomprehensible. I'm taking a programming class, but as far as I know, this program is just for my own fu...
3
2016-10-03T18:48:40Z
39,838,796
<p>The following pretty much does what you want. </p> <ul> <li><p>The tricky part is the computation of the intervals which was done using <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> to subtract the current item from the item at the next index, and sub...
0
2016-10-03T19:12:58Z
[ "python", "list", "python-3.x", "music", "args" ]
static files not detected Django 1.10
39,838,439
<p><strong>Problem</strong>: javascript and css files doesn't load.<br> I am using Django 1.10, my <code>settings.py</code> file looks like this:</p> <pre><code>STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR, "static_root") </code></pre> <p>I ...
2
2016-10-03T18:50:20Z
39,838,503
<p>You need to specify it in <code>urls.py</code> file as well</p> <pre><code># need these two additional imports from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ... ] # add this extra line of code urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_...
2
2016-10-03T18:54:21Z
[ "python", "django" ]
static files not detected Django 1.10
39,838,439
<p><strong>Problem</strong>: javascript and css files doesn't load.<br> I am using Django 1.10, my <code>settings.py</code> file looks like this:</p> <pre><code>STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR, "static_root") </code></pre> <p>I ...
2
2016-10-03T18:50:20Z
39,838,673
<p>If you're using <em>runserver</em> in Debug mode, you don't need to modify your URLs.</p> <p>Your settings look fine provided that your directory structure looks like:</p> <pre><code>- myProject - myProject - settings.py - static - ... </code></pre> <p>Have you remembered to add <code>{ load staticfiles...
0
2016-10-03T19:04:18Z
[ "python", "django" ]
Converting .lua table to a python dictionary
39,838,489
<p>I have this kind of input:</p> <pre><code> sometable = { ["a"] = { "a1", }, ["b"] = { "b1", ["b2"] = true, }, ["c"] = { "c1", ["c2"] = true, }, }, </code></pre> <p>And would like to convert it to some...
1
2016-10-03T18:53:09Z
39,838,703
<p>Look at this package: <a href="https://github.com/SirAnthony/slpp" rel="nofollow">https://github.com/SirAnthony/slpp</a>.</p> <pre><code>&gt;&gt;&gt; from slpp import slpp as lua &gt;&gt;&gt; code = """{ ["a"] = { "a1", }, ["b"] = { "b1", ["b2"] = true, }, ["c"] = { ...
2
2016-10-03T19:06:45Z
[ "python", "dictionary", "lua" ]
Why is Python logging framework losing messages?
39,838,616
<p>I have a Python 3.4 application that uses logging extensively. I have two FileHandlers and a StreamHandler registered. Everything works as expected except that sometimes, and it seems to happen after the <code>requests</code> library throws an exception, the log files lose all the accumulated messages and start with...
1
2016-10-03T19:00:43Z
39,841,337
<p>Your issue is that you chose the wrong <code>mode</code> for your <code>FileHandler</code>.</p> <p>The default mode of <code>FileHandler</code> is <code>a</code> which means appends new lines to the log file.</p> <blockquote> <p>class logging.FileHandler(filename, mode='a', encoding=None, delay=False)</p> </bloc...
0
2016-10-03T22:23:37Z
[ "python", "python-3.x", "logging", "python-requests", "error-logging" ]
Iterate over Pandas index pairs [0,1],[1,2][2,3]
39,838,758
<p>I have a pandas dataframe of lat/lng points created from a gps device. </p> <p>My question is how to generate a distance column for the distance between each point in the gps track line. </p> <p>Some googling has given me the haversine method below which works using single values selected using <code>iloc</code>, ...
0
2016-10-03T19:10:44Z
39,839,524
<p>are you looking for a result like this?</p> <pre><code> lat lon dist2next 0 -7.11873 113.72512 0.013232 1 -7.11873 113.72500 0.026464 2 -7.11873 113.72476 0.020951 3 -7.11873 113.72457 0.014335 4 -7.11873 113.72444 NaN </code></pre> <p>There's probably a clever way to use pandas.r...
1
2016-10-03T20:03:28Z
[ "python", "pandas" ]
Iterate over Pandas index pairs [0,1],[1,2][2,3]
39,838,758
<p>I have a pandas dataframe of lat/lng points created from a gps device. </p> <p>My question is how to generate a distance column for the distance between each point in the gps track line. </p> <p>Some googling has given me the haversine method below which works using single values selected using <code>iloc</code>, ...
0
2016-10-03T19:10:44Z
39,839,602
<p>I would recommande using a quicker variation of looping through a df such has</p> <pre><code>df_shift = df.shift(1) df = df.join(df_shift, l_suffix="lag_") log = [] for rows in df.itertuples(): log.append(haversine(rows.lng ,rows.lat, rows.lag_lng, rows.lag_lat)) pd.DataFrame(log) </code></pre>
0
2016-10-03T20:08:22Z
[ "python", "pandas" ]
Status code 400 on post message to influxdb
39,838,790
<p>I'm trying to post a json file to influxdb on my local host. This is the code:</p> <pre><code>import json import requests url = 'http://localhost:8086/write?db=mydb' files ={'file' : open('sample.json', 'rb')} r = requests.post(url, files=files) print(r.text) </code></pre> <p>This is what <code>sample.json</code> ...
0
2016-10-03T19:12:37Z
39,839,210
<p>Writing data with JSON was deprecated for performance reasons and has since been removed.</p> <p>See GitHub issue comments <a href="https://github.com/influxdata/influxdb/pull/2696#issuecomment-107043910" rel="nofollow">107043910</a>.</p>
0
2016-10-03T19:41:56Z
[ "python", "json", "post", "influxdb", "http-status-code-400" ]
Status code 400 on post message to influxdb
39,838,790
<p>I'm trying to post a json file to influxdb on my local host. This is the code:</p> <pre><code>import json import requests url = 'http://localhost:8086/write?db=mydb' files ={'file' : open('sample.json', 'rb')} r = requests.post(url, files=files) print(r.text) </code></pre> <p>This is what <code>sample.json</code> ...
0
2016-10-03T19:12:37Z
39,839,220
<p>I think that the fault maybe is that you just open the file but not read it. I mean since you want to post the content of the <code>json</code> object which is stored on the file, and not the file itself, it may be better to do that instead:</p> <pre><code>import json import requests url = 'http://localhost:8086/wr...
0
2016-10-03T19:42:45Z
[ "python", "json", "post", "influxdb", "http-status-code-400" ]
TypeError: 'tasks:meta:newtask' is not JSON serializable
39,838,792
<p>I am trying to dump this json - </p> <pre><code>{'total_run_count': 9, 'task': 'tasks.add', 'enabled': True, 'schedule': {'period': 'seconds', 'every': 3}, 'kwargs': {'max_targets': 100}, 'running': False, 'options': {}, 'delete_key': 'deleted:tasks:meta:newtask', 'name': b'tasks:meta:newtask', 'last_run_at': datet...
0
2016-10-03T19:12:48Z
39,838,894
<p>Notice how that item is displayed in the dictionary:</p> <pre><code>'name': b'tasks:meta:newtask' </code></pre> <p>That leading <code>b</code> indicates that 'tasks:meta:newtask' is a <em>byte string</em>, not a regular character string. JSON is telling you that it doesn't know how to handle a byte string object....
1
2016-10-03T19:19:00Z
[ "python" ]
TypeError: 'tasks:meta:newtask' is not JSON serializable
39,838,792
<p>I am trying to dump this json - </p> <pre><code>{'total_run_count': 9, 'task': 'tasks.add', 'enabled': True, 'schedule': {'period': 'seconds', 'every': 3}, 'kwargs': {'max_targets': 100}, 'running': False, 'options': {}, 'delete_key': 'deleted:tasks:meta:newtask', 'name': b'tasks:meta:newtask', 'last_run_at': datet...
0
2016-10-03T19:12:48Z
39,838,939
<p>The "name" value in your dict is a <code>bytes</code> object, not string. You have to decode it or you can write your <a href="https://docs.python.org/3/library/json.html#json.JSONEncoder" rel="nofollow">custom JSON encoder</a>:</p> <pre><code>import json def default(o): if isinstance(o, bytes): return...
1
2016-10-03T19:22:56Z
[ "python" ]
Python object is being referenced by an object I cannot find
39,838,793
<p>I am trying to remove an object from memory in python and I am coming across an object that it is not being removed. From my understanding if there is no references to the object the garbage collector will de-allocate the memory when it is run. However after I have removed all of the references if I run </p> <pre...
0
2016-10-03T19:12:49Z
39,839,810
<p>Okay thanks to cjhanks and user2357112 I came up with this answer</p> <p>The problem being that if you run the program the gc does not collect anything after each day even though there were things deleted</p> <p>To test if it is deleted I instead run</p> <pre><code>print len(gc.get_objects()) </code></pre> <p>e...
0
2016-10-03T20:23:37Z
[ "python", "object", "garbage-collection" ]
Python object is being referenced by an object I cannot find
39,838,793
<p>I am trying to remove an object from memory in python and I am coming across an object that it is not being removed. From my understanding if there is no references to the object the garbage collector will de-allocate the memory when it is run. However after I have removed all of the references if I run </p> <pre...
0
2016-10-03T19:12:49Z
39,839,824
<p><code>gc.get_referrers</code> takes one argument: the object whose referers it should find.</p> <p>I cannot think of any circumstance in which <code>gc.get_referrers</code> would return no results, because in order to send an object to <code>gc.get_referrers</code>, there has to be a reference to the object.</p> <...
0
2016-10-03T20:24:17Z
[ "python", "object", "garbage-collection" ]
How do I assign specific users to a user-uploaded file so they can modify it/delete it (Django + Apache)
39,838,861
<p>Im using django 1.10 + Apache in Linux. I've created a small webapp to upload documents (with dropzone.js) and want to implement the ability for a user to specify who can view/modify/delete a specific file but i can't figure out a way how. I attempted using a ManyToManyField but maybe im not understading the Field i...
0
2016-10-03T19:16:34Z
39,839,446
<p>You have a model and a view that hopefully works for adding new documents, you still have a number of steps to go. You'll need a place to assign users that can view/modify/delete your files. If you need to store access levels (view/delete...), your accessible_by will not suffice and you'll do well with a <strong><em...
0
2016-10-03T19:58:33Z
[ "python", "django", "apache", "file-upload", "permissions" ]
Wrote a plugin for BitBucket API calls. Unable to find my plugin when used in master.cfg
39,838,879
<p>I wrote a class that wrapped BitBucket API calls. Can confirm it worked standalone, however, when I add that python class to /master/buidlbot/changes/bitbucket.py. And add this class in master/setup.py</p> <pre><code> ('buildbot.changes.bitbucket', ['BitbucketPullrequestPoller', 'BitBucketBuildStatusAPIWrapper']), ...
0
2016-10-03T19:17:43Z
39,876,296
<p>Make sure you run </p> <pre><code>python &lt;path to buildbot repo&gt;/master/setup.py build python &lt;path to buildbot repo&gt;/master/setup.py install </code></pre>
0
2016-10-05T14:11:15Z
[ "python", "buildbot" ]
ANTLR error 134
39,838,986
<p>I'm trying to build Abstract Syntax Tree for Java in Python with antlr4 package. I've downloaded Java grammar from <a href="https://github.com/antlr/grammars-v4/blob/master/java8/Java8.g4" rel="nofollow">https://github.com/antlr/grammars-v4/blob/master/java8/Java8.g4</a></p> <p>I want to use that grammar file to pr...
0
2016-10-03T19:26:15Z
39,839,712
<p>Python has built-in function called <code>type</code>. Antlr4 prints an error for line 73 of the grammar:</p> <pre><code>type : primitiveType | referenceType ; </code></pre> <p>Looks like there is a name conflict and you have to rename <code>type</code> to something else in your grammar.</p>
1
2016-10-03T20:17:07Z
[ "java", "python", "antlr4" ]
Pcraster - python - reading stack of maps
39,838,987
<p>I have a stack of maps as follows:</p> <p><a href="http://i.stack.imgur.com/P9a5U.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/P9a5U.jpg" alt="list of .map files"></a></p> <p>They are the outputs of every 720 timesteps of a certain dynamic model I would like to import / read those maps as input of other ...
0
2016-10-03T19:26:17Z
39,840,212
<p>If the stack of maps is in a particular directory, you can use <code>os.path</code> and read all files in that directory.</p> <pre><code>from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] </code></pre> <p><code>onlyfiles</code> is a list of f...
0
2016-10-03T20:51:15Z
[ "python" ]
QTextEdit as a child node for QTreeWidgetItem?
39,839,006
<p>Is it possible to add a QTextEdit as a child in QTreeWidget?</p> <p>Here is my code we can create a QTreeWidget and add the columns:</p> <pre><code>self.treetext = QtGui.QTreeWidget(self.dockWidgetContents_2) self.treetext.setObjectName(_fromUtf8("treetext")) self.verticalLayout_2.addWidget(self.tr...
1
2016-10-03T19:27:59Z
39,840,794
<p>You can set a widget on any item in the tree using <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qtreewidget.html#setItemWidget" rel="nofollow"><code>setItemWidget</code></a></p> <pre><code>self.treetext.setItemWidget(item_1, 0, QTextEdit(self)) </code></pre> <p>If your tree widget items are editable, you can al...
0
2016-10-03T21:35:22Z
[ "python", "pyqt", "pyqt4", "qtextedit", "qtreewidget" ]