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
Value Error: negative dimensions are not allowed when merging
39,130,690
<p>I am merging 2 dataframes together. They are originally <code>.csv</code> files which are only 7 megabytes each (2 columns and 290,000 rows). I am merging like this:</p> <pre><code>merge=pd.merge(df1,df2, on=['POINTID'], how='outer') </code></pre> <p>and in 32-bit Anaconda I get:</p> <p><code>ValueError: negati...
1
2016-08-24T18:35:17Z
39,131,034
<p>On a 32-bit machine, the default NumPy integer dtype is <code>int32</code>. On a 64-bit machine, the default NumPy integer dtype is <code>int64</code>.</p> <p>The largest integers representable by an <code>int32</code> and <code>int64</code> are:</p> <pre><code>In [88]: np.iinfo('int32').max Out[88]: 2147483647 I...
5
2016-08-24T18:54:41Z
[ "python", "pandas" ]
result inconsistency in python
39,130,823
<p>I have two text files and the content are as under (<code>file1.txt</code> and <code>file2.txt</code> respectively);</p> <pre><code>MKKVEAIIRPFKLDEVKIALVNAGIVGMTVSEVRGFGRQKGQTERYRGSEYTVEFLQKLKVEIVVEDNQVDMVVDKIIAAARTGEIGDGKIFISPVEQVIRIRTGEKNTEAV </code></pre> <p>and</p> <pre><code>AQTVPYGIPLIKADKVQAQGYKGANVKVGIIDT...
0
2016-08-24T18:42:08Z
39,130,903
<pre><code>temp = data[x-20:x] </code></pre> <p>will give you</p> <pre><code>temp = data[36:56] </code></pre> <p>i.e. the characters 36 to 55 (included) of your string</p> <p>the string starts at character 0, so data[36] is indeed your second A, i.e. the 37th character of your string</p> <p>No bug here, just a cou...
0
2016-08-24T18:47:12Z
[ "python", "substring" ]
result inconsistency in python
39,130,823
<p>I have two text files and the content are as under (<code>file1.txt</code> and <code>file2.txt</code> respectively);</p> <pre><code>MKKVEAIIRPFKLDEVKIALVNAGIVGMTVSEVRGFGRQKGQTERYRGSEYTVEFLQKLKVEIVVEDNQVDMVVDKIIAAARTGEIGDGKIFISPVEQVIRIRTGEKNTEAV </code></pre> <p>and</p> <pre><code>AQTVPYGIPLIKADKVQAQGYKGANVKVGIIDT...
0
2016-08-24T18:42:08Z
39,130,988
<pre><code>with open('file1.txt', 'r') as myfile: x = 50 data=myfile.read() print data[x-20:x+21] </code></pre> <p>This takes a slice from position x-20 to position x+21. This will give you a slice of 41 chars.</p> <p>data2, 56 returns: <code>ASHTDLKVVGGASFVSGESYNTDGNGHGTHVAGTVAALDNT</code> - Your code is...
0
2016-08-24T18:51:55Z
[ "python", "substring" ]
result inconsistency in python
39,130,823
<p>I have two text files and the content are as under (<code>file1.txt</code> and <code>file2.txt</code> respectively);</p> <pre><code>MKKVEAIIRPFKLDEVKIALVNAGIVGMTVSEVRGFGRQKGQTERYRGSEYTVEFLQKLKVEIVVEDNQVDMVVDKIIAAARTGEIGDGKIFISPVEQVIRIRTGEKNTEAV </code></pre> <p>and</p> <pre><code>AQTVPYGIPLIKADKVQAQGYKGANVKVGIIDT...
0
2016-08-24T18:42:08Z
39,133,150
<p>Okay so if you check, index 50 in file 1 (first row) is <code>Y</code>, 20 elements from left start from <code>SEV...</code> which means starting from index 30. This is your result for file1, which you say is correct.</p> <pre><code>M K K V E A I I R P F K L D E V K I A L V ...
0
2016-08-24T21:15:10Z
[ "python", "substring" ]
Python - Printing numbers with spacing format
39,130,914
<p>Let's say I have an array of numbers where</p> <pre><code>list = [(4, 3, 7, 23),(17, 4021, 4, 92)] </code></pre> <p>and I want to print the numbers out in such a way so that the output looks somewhat like this:</p> <pre><code>[ 4 | 3 | 7 | 23 ] [ 17 | 4021 | 4 | 92 ] </code></pre> <p>Where the...
0
2016-08-24T18:47:52Z
39,131,038
<p>You can also use third-parties like <a href="https://pypi.python.org/pypi/PrettyTable" rel="nofollow"><code>PrettyTable</code></a> or <a href="https://pypi.python.org/pypi?name=texttable&amp;%3Aaction=display" rel="nofollow"><code>texttable</code></a>. Example using <code>texttable</code>:</p> <pre><code>import tex...
2
2016-08-24T18:55:24Z
[ "python", "string", "list", "format", "number-formatting" ]
Python - Printing numbers with spacing format
39,130,914
<p>Let's say I have an array of numbers where</p> <pre><code>list = [(4, 3, 7, 23),(17, 4021, 4, 92)] </code></pre> <p>and I want to print the numbers out in such a way so that the output looks somewhat like this:</p> <pre><code>[ 4 | 3 | 7 | 23 ] [ 17 | 4021 | 4 | 92 ] </code></pre> <p>Where the...
0
2016-08-24T18:47:52Z
39,131,158
<p>Here: </p> <pre><code>list = [[4, 3, 7, 23],[17, 4021, 4, 92]] for sublist in list: output = "[" for index, x in enumerate(sublist): output +='{:^6}'.format(x) if index != len(sublist)-1: output += '|' output +=']' print output </code></pre> <p>Output: </p> <pre>...
0
2016-08-24T19:01:52Z
[ "python", "string", "list", "format", "number-formatting" ]
Python - Printing numbers with spacing format
39,130,914
<p>Let's say I have an array of numbers where</p> <pre><code>list = [(4, 3, 7, 23),(17, 4021, 4, 92)] </code></pre> <p>and I want to print the numbers out in such a way so that the output looks somewhat like this:</p> <pre><code>[ 4 | 3 | 7 | 23 ] [ 17 | 4021 | 4 | 92 ] </code></pre> <p>Where the...
0
2016-08-24T18:47:52Z
39,131,213
<p><a href="https://docs.python.org/2/library/string.html#string.center" rel="nofollow">str.center</a> can make things easier.</p> <pre><code>for i in list: print '[ ' + ' | '.join([str(j).center(4) for j in i]) + ' ]' </code></pre> <p>Output:</p> <pre><code>[ 4 | 3 | 7 | 23 ] [ 17 | 4021 | 4 | ...
1
2016-08-24T19:04:59Z
[ "python", "string", "list", "format", "number-formatting" ]
Python TypeError: Incorrect padding when write to image
39,130,919
<p>I tired with this error. this is encoding base64 <a href="http://pastebin.com/16KSrNuL" rel="nofollow">http://pastebin.com/16KSrNuL</a> and i try to decode into image using this code</p> <pre><code>wf = open('/Users/me/base.txt', 'w') wf.write(data.get('base64')) wf.close() fp = open('/Users/me/base_result.png', '...
1
2016-08-24T18:48:09Z
39,131,001
<p>You need to remove the leading string i.e <em>data:image/png;base64,</em> to get the <em>base64</em> encoded data:</p> <pre><code>with open("/Users/me/base.txt") as f, open("/Users/me/base_result.png","wb") as out: out.write(f.read().split(",",1)[1].decode("base-64")) </code></pre> <p>When you do you get:</p> ...
2
2016-08-24T18:52:44Z
[ "python", "base64" ]
I can't call upon my variable which contains several words in it (if in variable:)
39,130,924
<p>I am trying to call upon a variable I created for an 'if' statement in Python. Here is a summed up version:</p> <pre><code>yes = ("yes", "y") question1 = input("Am I right?") if question1.lower() in yes: print ("you are correct") </code></pre> <p>but I get an error : </p> <pre><code>--'in &lt;string&gt;' require...
0
2016-08-24T18:48:18Z
39,131,041
<p>In python 2.x; you must use <code>raw_input</code> instead of <code>input</code> as <code>input()</code> actually evaluates the input as Python code. <code>raw_input()</code> returns the verbatim string entered by the user.</p> <pre><code>yes = ("yes", "y") question1 = raw_input("Am I right?") if question1.lower(...
-1
2016-08-24T18:55:33Z
[ "python" ]
How to define a member function of a class at the class level or at the level of instance objects?
39,130,950
<p>In Python 2.7, when defining a class, how can we define </p> <ul> <li><p>member functions at the level of class, i.e. its first argument is the class object, not an instance object of the class</p></li> <li><p>member functions at the level of the class' instance objects, i.e. its first argument is an instance objec...
0
2016-08-24T18:49:46Z
39,131,266
<blockquote> <p>The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.</p> <p>It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method...
2
2016-08-24T19:08:25Z
[ "python", "python-2.7" ]
ImportError: No module named '_version' when importing mechanize
39,130,957
<p>I installed mechanize via pip and get an errer when I import the module:</p> <pre><code>$ python Python 3.5.2 (default, Jun 28 2016, 08:46:01) [GCC 6.1.1 20160602] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import mechanize Traceback (most recent call last): File...
1
2016-08-24T18:50:06Z
39,131,141
<p>If you look at <a href="https://github.com/jjlee/mechanize/blob/master/setup.py#L38" rel="nofollow"><code>setup.py</code></a> you'll see <code>mechanize</code> is a <code>Python 2.x</code> package: </p> <pre><code>Programming Language :: Python Programming Language :: Python :: 2 Programming Language :: Python :: 2...
3
2016-08-24T19:00:45Z
[ "python", "python-3.x", "import", "mechanize" ]
python json, replacing values with key and value pairs
39,131,023
<p>in the following example I am trying to replace value of one key by the value of another key; but I tried multiple ways and it doesn't seem to work.</p> <p>following is my code</p> <pre><code>d = { "name" : "ABC", "type" : "Service", "clusterRef" : { "clusterName" : "ABCSTUFF" }, "serviceState" : "ST...
0
2016-08-24T18:53:44Z
39,131,891
<p>Here's a non-generic solution which works for your question:</p> <pre><code>d = { "name": "ABC", "type": "Service", "clusterRef": { "clusterName": "ABCSTUFF" }, "serviceState": "STARTED", "healthChecks": [{ "name": "STORAGE", "summary": "GOOD" }, { "name":...
1
2016-08-24T19:47:22Z
[ "python", "json" ]
zooming with NavigationToolbar does not work in matplotlib with pyqt
39,131,025
<p>i try to plot data using python 2.7, matplotlib, qt5 (version 5.7) and pyqt5. i took an example and adapted it to my needs. i see the NavigationToolbar gets added to the plot window, but the zooming does not work. i'm not sure what the second argument of NavigationToolbar object should be?</p> <pre class="lang-py...
0
2016-08-24T18:53:50Z
39,153,251
<p>here is how i fixed it if someone is interested as well:</p> <pre class="lang-py prettyprint-override"><code>import sys import matplotlib matplotlib.use("Qt5Agg") import numpy as np from numpy import arange, sin, pi from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar from matplo...
0
2016-08-25T19:23:55Z
[ "python", "matplotlib", "pyqt", "pyqt5" ]
AttributeError: 'account.invoice.refund' object has no attribute 'journal_id' - Odoo v9 community
39,131,039
<p>I'm having a hard time with a Odoo v9 module I'm adapting, for debit/credit notes.</p> <p>I'm fixing the bugs on it, so far, I have this issue right now, on this function:</p> <pre><code>def compute_refund(self, cr, uid, ids, mode='refund', context=None): """@param cr: the current row, from the database cursor...
0
2016-08-24T18:55:27Z
39,134,533
<p>Activate Developer mode, go to Settings -> Technical -> Database Structure -> Models and search for <code>account.invoice.refund</code> then check if this model has any field named <code>journal_id</code>. As I can see this field existed on v8 but does not exist on v9.</p> <p>You can check this on <a href="http://r...
2
2016-08-24T23:34:55Z
[ "python", "openerp", "odoo-9" ]
Using command line arguments in imported module
39,131,122
<p>I have script <code>download.py</code> with:</p> <pre><code>import argparse import models parser = argparse.ArgumentParser() parser.add_argument("--db_path", required=True) args = parser.parse_args() </code></pre> <p><code>models.py</code>:</p> <pre><code>import peewee database = peewee.SqliteDatabase("wee.db"...
0
2016-08-24T18:59:59Z
39,131,233
<p>All you have to do is pass your arg to the <code>SqliteDatabase</code> constructor.</p> <p>It seems like you're using Django. If that's the case, you could (and should) specify your database in <code>settings.py</code>, <a href="https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-DATABASES" rel="nofoll...
0
2016-08-24T19:06:13Z
[ "python", "python-3.x", "argparse", "peewee" ]
Using command line arguments in imported module
39,131,122
<p>I have script <code>download.py</code> with:</p> <pre><code>import argparse import models parser = argparse.ArgumentParser() parser.add_argument("--db_path", required=True) args = parser.parse_args() </code></pre> <p><code>models.py</code>:</p> <pre><code>import peewee database = peewee.SqliteDatabase("wee.db"...
0
2016-08-24T18:59:59Z
39,131,491
<p>Here's a possible solution:</p> <pre><code># download.py import argparse from models import DBManager parser = argparse.ArgumentParser() parser.add_argument("--db_path", required=True) args = parser.parse_args() DBManager(args.db_path) </code></pre> <hr> <pre><code># models.py import peewee class Artist(peewe...
0
2016-08-24T19:23:22Z
[ "python", "python-3.x", "argparse", "peewee" ]
Combine two columns of text with NaN in pandas
39,131,131
<p>I want to combine two columns as below</p> <pre><code>import numpy as np import pandas as pd data = pd.DataFrame({ 'a' : [np.nan, 'abc'], 'b' : ['abc', 'abc']}) data['c']=data['a']+' '+data['b'] data a b c 0 NaN abc NaN 1 abc abc abc abc </code></pre> <p>The problem is in NaN, i want get</p> ...
1
2016-08-24T19:00:16Z
39,131,225
<pre><code>&gt;&gt;&gt; data['c']=data['a'].fillna('') + ' ' + data['b'].fillna('') &gt;&gt;&gt; data a b c 0 NaN abc abc 1 abc abc abc abc </code></pre> <p>However, do note that <code>data['c'][0] == ' abc'</code>. You'd have to use <code>.str.strip()</code> to strip off whitespace if needed....
4
2016-08-24T19:05:53Z
[ "python", "pandas", "numpy", null ]
Python export list of folders & full path as JSON for JSTree
39,131,343
<p>I am trying to create a JSON file for jstree. But I'm having trouble getting this code to output the full path of the folders and only show folders. I am new to Python and would appreciate any insight! </p> <p>The goal is to have users select a folder and bring back the full path of that folder in JSTree. (Not ...
0
2016-08-24T19:12:46Z
39,131,887
<p>For me the following solution works: (you wanted only directories)</p> <pre><code>def get_list_of_dirs(path): output_dictonary = {} list_of_dirs = [os.path.join(path, item) for item in os.listdir(path) if os.path.isdir(os.path.join(path, item))] output_dictonary["text"] = path output_dictonary["type...
0
2016-08-24T19:47:04Z
[ "python", "json", "jstree" ]
How to receive uploaded file with Klein like Flask in python
39,131,368
<p>When setting up a Flask server, we can try to receive the file user uploaded by </p> <pre><code>imagefile = flask.request.files['imagefile'] filename_ = str(datetime.datetime.now()).replace(' ', '_') + \ werkzeug.secure_filename(imagefile.filename) filename = os.path.join(UPLOAD_FOLDER, filename_) imagefile.sav...
8
2016-08-24T19:14:26Z
39,438,647
<p>As <code>Liam Kelly</code> commented, the snippets from <a href="http://www.cristinagreen.com/uploading-files-using-twisted-web.html" rel="nofollow">this post</a> should work. Using <code>cgi.FieldStorage</code> makes it possible to easily send file metadata without explicitly sending it. A Klein/Twisted approach wo...
2
2016-09-11T17:13:56Z
[ "python", "web-services", "klein-mvc" ]
Machine Learning: Basics DepreciationWarning
39,131,424
<p>I'm running a basic machine learning tutorial code snippet (which compiles properly on the computer of the person teaching), and I can't seem to find what's wrong. I understand the question has been 'answered', but I can't seem to understand the answer.</p> <blockquote> <p>DeprecationWarning: Passing 1d arrays as...
0
2016-08-24T19:18:23Z
39,131,611
<p>Since your data has more than a single feature and it contains more than a single sample you are fine. This is just a warning and shouldn't interfere with the algorithm's behavior.</p>
0
2016-08-24T19:30:09Z
[ "python", "numpy", "matplotlib", "scikit-learn", "svm" ]
Python : IndexError: list index out of shape
39,131,559
<p>This piece of code works well when I used my earlier set of data. However Now I have added a couple more columns to the input data set and I am getting indexing errors. I am not exactly sure on how to fix this. Any inputs ? . The following code is giving me error:</p> <pre><code>with open("master_aggregated_monthly...
-3
2016-08-24T19:27:19Z
39,131,709
<p>You're creating an index based off of the length of <code>entry</code>, but using that index in <code>my_event.attributes</code>:</p> <pre><code>for i in range(3, len(entry)): ... except: ... my_event.attributes[i-3] += temp ... ... </code></pre> <p>This is probably the problem,...
0
2016-08-24T19:36:02Z
[ "python", "python-2.7", "indexing" ]
using a DataFrame with columns as named arguments to str.format()
39,131,620
<p>I have a DataFrame like:</p> <pre><code>import pandas as pd df = pd.DataFrame({'author':["Melville","Hemingway","Faulkner"], 'title':["Moby Dick","The Sun Also Rises","The Sound and the Fury"], 'subject':["whaling","bullfighting","a messed-up family"] }) </co...
1
2016-08-24T19:30:35Z
39,131,761
<pre><code>&gt;&gt;&gt; ["Some guy {author} wrote a book called {title} that uses " "{subject} as a metaphor for the human condition.".format(**x._asdict()) for x in df.itertuples(index=False)] ['Some guy Melville wrote a book called Moby Dick that uses whaling as a metaphor for the human condition.', 'Some g...
3
2016-08-24T19:39:05Z
[ "python", "pandas", "string-formatting" ]
using a DataFrame with columns as named arguments to str.format()
39,131,620
<p>I have a DataFrame like:</p> <pre><code>import pandas as pd df = pd.DataFrame({'author':["Melville","Hemingway","Faulkner"], 'title':["Moby Dick","The Sun Also Rises","The Sound and the Fury"], 'subject':["whaling","bullfighting","a messed-up family"] }) </co...
1
2016-08-24T19:30:35Z
39,132,305
<p>You could also use <code>DataFrame.iterrows()</code> like this:</p> <pre><code>["The book {title} by {author} uses " "{subject} as a metaphor for the human condition.".format(**x) for i, x in df.iterrows()] </code></pre> <p>Which is nice if you want to:</p> <ul> <li>use named arguments, so the order of u...
0
2016-08-24T20:13:45Z
[ "python", "pandas", "string-formatting" ]
Python Decryption using private key
39,131,630
<p>I have an encrypted string. The Encryption is done using java code. I decrypt the encrypted string using following java code</p> <pre><code>InputStream fileInputStream = getClass().getResourceAsStream( "/private.txt"); byte[] bytes = IOUtils.toByteArray(fileInputStream); private S...
-2
2016-08-24T19:31:13Z
39,150,602
<p>I figured out the solution:</p> <pre><code>from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA from base64 import b64decode rsa_key = RSA.importKey(open('private.txt', "rb").read()) verifier = PKCS1_v1_5.new(rsa_key) raw_cipher_data = b64decode(&lt;your cipher data&...
0
2016-08-25T16:39:57Z
[ "python", "cryptography" ]
Re ordering output from bash commands in python script
39,131,719
<p>I am working on a python script that deals with wifi access points. In the script I call os.system("iwlist wlan0 s") to scan the wireless APs nearby. There are only two pieces of info I need from each one: the name and the MAC address. I can grep the output to get a list of the names or the addresses, but is there a...
0
2016-08-24T19:37:00Z
39,132,358
<pre><code>import commands a = commands.getstatusoutput("iwlist wlp9s0 s | grep 'ESSID\|Address'|tr -s ' ' | cut -d'-' -f 2") for item in a[1].strip().split("Address:"): print('-'.join(item.replace('\n','').strip().split("ESSID:"))) </code></pre> <p>return:</p> <p>AA:11:DD:44:32:D7 -"Kolagh_nomap"</p> <p>BB:22:...
0
2016-08-24T20:17:29Z
[ "python", "linux", "bash" ]
Removing six.b from multiple files
39,131,755
<p>I have dozens of files in the project and I want to change all occurences of <code>six.b("...")</code> to <code>b"..."</code>. Can I do that with some sort of regex bash script?</p>
0
2016-08-24T19:38:49Z
39,131,881
<p>It's possible entirely in Python, But I would first make a backup of my project tree, and then:</p> <pre><code> import re import os indir = 'files' for root, dirs, files in os.walk(indir): for f in files: fname = os.path.join(root, f) with open(fname) as f: txt = f.read() t...
1
2016-08-24T19:46:40Z
[ "python", "bash" ]
Removing six.b from multiple files
39,131,755
<p>I have dozens of files in the project and I want to change all occurences of <code>six.b("...")</code> to <code>b"..."</code>. Can I do that with some sort of regex bash script?</p>
0
2016-08-24T19:38:49Z
39,133,891
<p>A relatively simple bash solution (change *.foo to *.py or whatever filename pattern suits your situation):</p> <pre><code>#!/bin/bash export FILES=`find . -type f -name '*.foo' -exec egrep -l 'six\.b\("[^\"]*"\)' {} \; 2&gt;/dev/null` for file in $FILES do cp $file $file.bak sed 's/six\.b(\(\"[^\"]*[^\\]\...
1
2016-08-24T22:21:53Z
[ "python", "bash" ]
Getting a 403 Client Error using tinys3 python package
39,131,766
<p>I'm getting a 403 Client Error when making an S3 connection on one of our production servers using the tinys3 python package. Any ideas? I think the credentials are right, as this script runs on my local machine without issue. </p> <p>I'm getting the same issue on a test script I wrote to help debug this. Pasted be...
1
2016-08-24T19:39:16Z
39,131,947
<p>If the machine's system clock is more than 15 minutes behind, you can get this error. The time is put into the request and checked by Amazon. Check the system time with the <code>date</code> command.</p> <p>This has been discussed by some other questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/24...
1
2016-08-24T19:51:48Z
[ "python", "amazon-s3" ]
Python: Elegant way to combine output variables of a function run many times
39,131,811
<p>I have a function that returns many output arrays of varying size.</p> <pre><code>arr1,arr2,arr3,arr4,arr5, ... = func(data) </code></pre> <p>I want to run this function many times over a time series of data, and combine each output variable into one array that covers the whole time series.</p> <p>To elaborate: I...
0
2016-08-24T19:42:08Z
39,131,951
<p>You can just make <code>arr1</code>, <code>arr2</code>, etc. a list of lists (of vectors or matrices or whatever). Then use a loop to iterate the results obtained from <code>func</code> and add them to the individual lists.</p> <pre><code>arrN = [[] for _ in range(N)] # N being number of results from func for t in...
2
2016-08-24T19:52:03Z
[ "python", "arrays", "numpy" ]
Python: Elegant way to combine output variables of a function run many times
39,131,811
<p>I have a function that returns many output arrays of varying size.</p> <pre><code>arr1,arr2,arr3,arr4,arr5, ... = func(data) </code></pre> <p>I want to run this function many times over a time series of data, and combine each output variable into one array that covers the whole time series.</p> <p>To elaborate: I...
0
2016-08-24T19:42:08Z
39,132,260
<p>Not sure if it counts as "elegant", but you can build a <code>list</code> of the result <code>tuple</code>s then use <code>zip</code> to group them into <code>tuple</code>s by return position instead of by call number, then optionally <code>map</code> to convert those <code>tuple</code>s to the final data type. For ...
0
2016-08-24T20:10:36Z
[ "python", "arrays", "numpy" ]
Python: Elegant way to combine output variables of a function run many times
39,131,811
<p>I have a function that returns many output arrays of varying size.</p> <pre><code>arr1,arr2,arr3,arr4,arr5, ... = func(data) </code></pre> <p>I want to run this function many times over a time series of data, and combine each output variable into one array that covers the whole time series.</p> <p>To elaborate: I...
0
2016-08-24T19:42:08Z
39,132,781
<p>This answer gives a solution using <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html" rel="nofollow">structured arrays</a>. It has the following requirement: Ggven a function <code>f</code> that returns <code>N</code> arrays, and the size of each of the returned arrays can be different -- <em>then for al...
0
2016-08-24T20:48:19Z
[ "python", "arrays", "numpy" ]
How to check if a column exists in a pandas MultiIndex
39,131,900
<p>Let's say I have a DataFrame with a MultiIndex of columns like this:</p> <pre><code>In [29]: df = pd.DataFrame([[0] * 8], columns = pd.MultiIndex.from_product( [['a', 'b'], [1, 2], [2000, 2001]]) ) In [30]: df Out[30]: a b 1 2 1 2 2000 2001 2000 2001 2000 2...
2
2016-08-24T19:48:07Z
39,131,965
<p>IIUC</p> <pre><code>df.xs(2, axis=1, level=1).groupby(axis=1, level=1).first().columns.values array([2000, 2001]) </code></pre> <p>Or</p> <pre><code>df.xs(2, axis=1, level=1).columns.get_level_values(level=1).unique() </code></pre>
5
2016-08-24T19:52:50Z
[ "python", "pandas", "multi-index" ]
Using a for loop to populate a dictionary
39,131,926
<p>I'm having some trouble generating the dictionary I've named "appInfo" using the code below. When it is run like this, only the last application number entered gets saved in the appInfo dictionary. It seems like it should be pretty easy, but I haven't been able to find a fix. I'm using Python 3.5.2.</p> <pre><code>...
1
2016-08-24T19:49:31Z
39,132,167
<p>Your array <strong>mo</strong> gets overwritten through each iteration of the while loop. When you loop through appDict.keys() <strong>mo</strong> only contains the most recent input. I think you meant to append to <strong>mo</strong> like this:</p> <pre><code>appDict={'AA':{'appType':'app name one','fileLoc':'C:\\...
1
2016-08-24T20:05:11Z
[ "python", "for-loop", "dictionary" ]
Extracting a section of a string in python with limitations
39,132,087
<p>I have a string output that looks like this:</p> <pre><code>Distance AAAB: ,0.13634,0.13700,0.00080,0.00080,-0.00066,.00001, Distance AAAC: ,0.12617,0.12680,0.00080,0.00080,-0.00063,, Distance AAAD: ,0.17045,0.16990,0.00080,0.00080,0.00055,, Distance AAAE: ,0.09330,0.09320,0.00080,0.00080,0.00010,, Distance AAAF: ,...
0
2016-08-24T19:59:42Z
39,132,269
<p>You could use <code>re</code> module. And making a function should be convenient.</p> <pre><code>import re def SearchDistance(pattern,text): pattern = pattern.replace(' ','\s') print re.findall(r'{0}.+'.format(pattern),a) SearchDistance('Distance AAAH',a) </code></pre> <p>Output:</p> <pre><code>['Distanc...
1
2016-08-24T20:11:19Z
[ "python", "python-3.x" ]
Extracting a section of a string in python with limitations
39,132,087
<p>I have a string output that looks like this:</p> <pre><code>Distance AAAB: ,0.13634,0.13700,0.00080,0.00080,-0.00066,.00001, Distance AAAC: ,0.12617,0.12680,0.00080,0.00080,-0.00063,, Distance AAAD: ,0.17045,0.16990,0.00080,0.00080,0.00055,, Distance AAAE: ,0.09330,0.09320,0.00080,0.00080,0.00010,, Distance AAAF: ,...
0
2016-08-24T19:59:42Z
39,132,309
<p>You can search your text by this script :</p> <pre><code>#fullText = YOUR STRING text = fullText.splitlines() for line in text: if line.startswith('Distance AAAH:'): print line </code></pre> <p>Output:<code>Distance AAAH: ,0.11404,0.11450,0.00120,0.00110,-0.00046,,</code></p>
1
2016-08-24T20:14:07Z
[ "python", "python-3.x" ]
Redirect print() to file in python 2.4
39,132,091
<p>I'm backporting a modern python script to 2.4 to make it compatible with stock RHEL 5.X. While most of the work has been fairly straight-forward, I can't figure out how to handle this case where I am appending to a file:</p> <pre><code>print("Foo",file=file("/tmp/bar",'ab')) </code></pre> <p>This is a very common...
3
2016-08-24T20:00:12Z
39,132,131
<p>The syntax is pretty awful:</p> <pre><code>print &gt;&gt; file('/tmp/bar', 'ab'), 'Foo' </code></pre> <p>Though of course you should rather write:</p> <pre><code>f = open('/tmp/bar', 'ab') try: print &gt;&gt; f, 'Foo' finally: f.close() </code></pre> <p>to make sure that the output is actually closed and...
3
2016-08-24T20:03:06Z
[ "python" ]
dataframe, set index from list
39,132,181
<p>Is it possible when creating a dataframe from a list, to set the index as one of the values?</p> <pre><code>import pandas as pd tmp = [['a', 'a1'], ['b',' b1']] df = pd.DataFrame(tmp, columns=["First", "Second"]) First Second 0 a a1 1 b b1 </code></pre> <p>And how I'd like it to l...
3
2016-08-24T20:06:10Z
39,132,236
<pre><code>&gt;&gt;&gt; pd.DataFrame(tmp, columns=["First", "Second"]).set_index('First', drop=False) First Second First a a a1 b b b1 </code></pre>
5
2016-08-24T20:09:12Z
[ "python", "pandas" ]
dataframe, set index from list
39,132,181
<p>Is it possible when creating a dataframe from a list, to set the index as one of the values?</p> <pre><code>import pandas as pd tmp = [['a', 'a1'], ['b',' b1']] df = pd.DataFrame(tmp, columns=["First", "Second"]) First Second 0 a a1 1 b b1 </code></pre> <p>And how I'd like it to l...
3
2016-08-24T20:06:10Z
39,132,290
<p>If you don't want index name:</p> <pre><code>df = pd.DataFrame(tmp, columns=["First", "Second"], index=[i[0] for i in tmp]) </code></pre> <p>Result:</p> <pre><code> First Second a a a1 b b b1 </code></pre>
3
2016-08-24T20:12:56Z
[ "python", "pandas" ]
django: how do I actually override admin site template
39,132,187
<p>I know this is asked and answered several times but I basically went over all the post on stack overflow and still couldn't get this to work. Right now I am just trying simply change the admin site title. I have the following:</p> <pre><code>#base_site.html {% extends "admin/base_site.html" %} {% block title %}{{ ...
0
2016-08-24T20:06:32Z
39,132,843
<p>use my_site/my_app/templates/admin/base_site.html </p> <blockquote> <p>put your app where you define this template before 'django.contrib.admin', in INSTALLED_APPS</p> </blockquote> <p><a href="http://stackoverflow.com/questions/4938491/django-admin-change-header-django-administration-text">link</a></p>
0
2016-08-24T20:53:50Z
[ "python", "django", "django-admin" ]
Python: SyntaxError using bitwise function
39,132,191
<p>I am trying to create a basic bitwise function that filters out a certain subset of my data for me.</p> <pre><code>&gt;&gt;&gt;heads=fits.open('datafile.fits') &gt;&gt;&gt;data=heads[1].data </code></pre> <p>Now, I need to mask out data points that are in a certain column and which are set to bit 0.</p> <pre><cod...
-1
2016-08-24T20:06:37Z
39,132,219
<p>equal comparsion is <code>==</code>:</p> <pre><code>ind=np.where(data['COLUMN_NAME'] &amp; (2**9) == 0) </code></pre>
1
2016-08-24T20:08:19Z
[ "python", "bitwise-operators", "bitwise-and" ]
Python: SyntaxError using bitwise function
39,132,191
<p>I am trying to create a basic bitwise function that filters out a certain subset of my data for me.</p> <pre><code>&gt;&gt;&gt;heads=fits.open('datafile.fits') &gt;&gt;&gt;data=heads[1].data </code></pre> <p>Now, I need to mask out data points that are in a certain column and which are set to bit 0.</p> <pre><cod...
-1
2016-08-24T20:06:37Z
39,132,239
<p>Could it be because you use '=' (assignment) instead of '==' (equality) in the call to 'where'?</p>
1
2016-08-24T20:09:19Z
[ "python", "bitwise-operators", "bitwise-and" ]
The spider doesn't go to the next page
39,132,263
<p>Spider code:</p> <pre><code>import scrapy from crawler.items import Item class DmozSpider(scrapy.Spider): name = 'blabla' allowed_domains = ['blabla'] def start_requests(self): yield scrapy.Request('http://blabla.org/forum/viewforum.php?f=123', self.parse) def parse(self, response): ...
0
2016-08-24T20:10:52Z
39,138,567
<p>You need to check following this.</p> <ol> <li>Check if the urls that you are trying to crawl is not Robots.txt, which you can find by looking into <a href="http://blabla.org/robots.txt" rel="nofollow">http://blabla.org/robots.txt</a>. By default scrapy obeys robots.txt. <em>It is recommended that you abide to robo...
1
2016-08-25T06:54:18Z
[ "python", "python-3.x", "scrapy", "scrapy-spider" ]
The spider doesn't go to the next page
39,132,263
<p>Spider code:</p> <pre><code>import scrapy from crawler.items import Item class DmozSpider(scrapy.Spider): name = 'blabla' allowed_domains = ['blabla'] def start_requests(self): yield scrapy.Request('http://blabla.org/forum/viewforum.php?f=123', self.parse) def parse(self, response): ...
0
2016-08-24T20:10:52Z
39,151,077
<p>The problem was that the response from the next page was a response for robots and did not contain any links.</p>
0
2016-08-25T17:09:55Z
[ "python", "python-3.x", "scrapy", "scrapy-spider" ]
Errors with django urls
39,132,285
<p>I'm getting an error 404 when i click the link on django, i have spent so much time trying to see what i'm doing wrong but no luck.</p> <p>here is my index.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Page Title&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;{{title}}&lt;/h...
0
2016-08-24T20:12:32Z
39,132,500
<p>Your <code>get_absolute_url</code> method returns URLs in the form <code>/posts/&lt;id&gt;</code> but your urlconf is expecting <code>/posts/detail/&lt;id&gt;</code>.</p> <p>Instead of hard-coding a URL like that in the method, you should use the <code>reverse</code> functionality:</p> <pre><code>from django.urls ...
1
2016-08-24T20:28:13Z
[ "python", "django", "django-models", "django-templates", "django-views" ]
Alternatives to looping in Pandas when you need to update a column based on another
39,132,367
<p>I have a <code>Pandas</code> <code>dataframe</code> with text dates that'd I like to convert to <code>datetime</code>. The problem is some of my text dates are bad data and thus can't be converted. In cases for which a date can't be converted, I want to update an <code>Error</code> column to a value of <code>True</c...
3
2016-08-24T20:18:34Z
39,132,408
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> with parameter <code>errors='coerce'</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html" rel="nofollow"><code>isnull</code><...
3
2016-08-24T20:21:31Z
[ "python", "python-2.7", "datetime", "pandas", "dataframe" ]
Alternatives to looping in Pandas when you need to update a column based on another
39,132,367
<p>I have a <code>Pandas</code> <code>dataframe</code> with text dates that'd I like to convert to <code>datetime</code>. The problem is some of my text dates are bad data and thus can't be converted. In cases for which a date can't be converted, I want to update an <code>Error</code> column to a value of <code>True</c...
3
2016-08-24T20:18:34Z
39,132,466
<p>You can skip the initial creation of <code>df</code> and construct it from the specific columns you need instead.</p> <pre><code># I push a list of first elements from data via a comprehension dates = pd.to_datetime([d[0] for d in data], format='%d%m%y', errors='coerce') # Construct df from scratch here df = pd.Da...
3
2016-08-24T20:26:25Z
[ "python", "python-2.7", "datetime", "pandas", "dataframe" ]
Python subtraction in for loop
39,132,429
<p>I am in need of some help doing some simple calculations in a for loop. I have two columns in the below example file. Column 1 is the date-time-hr-min-ss and column 2 is a value. I would like to print through the file and calculate the difference between the current value and the value of the previous hour. I attem...
0
2016-08-24T20:23:41Z
39,132,504
<pre><code>with open('datecount.txt') as data: prev = 0 for line in data: value = int(line.strip().split()[1]) print(value - prev) prev = value </code></pre> <p>It is a good idea to name the variables so that their names make sense. In other words, leave <code>x, y, z</code> in maths.</...
3
2016-08-24T20:28:29Z
[ "python", "parsing" ]
Python subtraction in for loop
39,132,429
<p>I am in need of some help doing some simple calculations in a for loop. I have two columns in the below example file. Column 1 is the date-time-hr-min-ss and column 2 is a value. I would like to print through the file and calculate the difference between the current value and the value of the previous hour. I attem...
0
2016-08-24T20:23:41Z
39,132,541
<p>Well if you can assume that each consecutive line in your file will be the hour following the previous hour, you don't need to even worry about messing with the time column. Just use this..</p> <pre><code>with open('datecount.txt') as data: z = 0 for line in data: x = (line.strip().split()) ...
1
2016-08-24T20:30:53Z
[ "python", "parsing" ]
Python Google Places Api
39,132,449
<p>I am trying to capture details of Starbucks shops in Coventry like Name,Location,Address and the google maps url, but I can't seem to wrap my head around the schedule (opening hours)</p> <pre><code>print place.details </code></pre> <p>will give you all the details on a JSON format, how do I keep just the opening ...
-2
2016-08-24T20:24:59Z
39,204,529
<p>try google places text search api to find place_id</p> <p><a href="https://maps.googleapis.com/maps/api/place/textsearch/json?query=StarbucksCoffee,GulsonRoad,CoventryUniversity,CoventryCV12JH,UK&amp;key=YOUR_API_KEY" rel="nofollow">https://maps.googleapis.com/maps/api/place/textsearch/json?query=StarbucksCoffee,Gu...
1
2016-08-29T10:55:06Z
[ "python", "json", "google-maps", "google-places-api" ]
How to interpret `scipy.stats.kstest` and `ks_2samp` to evaluate `fit` of data to a distribution?
39,132,469
<p><strong>I'm trying to evaluate/test how well my data fits a particular distribution.</strong> </p> <p>There are several questions about it and I was told to use either the <code>scipy.stats.kstest</code> or <code>scipy.stats.ks_2samp</code>. It seems straightforward, give it: (A) the data; (2) the distribution; a...
0
2016-08-24T20:26:40Z
39,133,792
<p>So the null-hypothesis for the KT test is that the distributions are the same. Thus, the lower your p value the greater the statistical evidence you have to reject the null hypothesis and <em>conclude the distributions are different</em>. The test only really lets you speak of your confidence that the distributions ...
1
2016-08-24T22:11:18Z
[ "python", "numpy", "machine-learning", "scipy", "statistics" ]
Non-standard distributions variables for KS testing?
39,132,537
<p>Could you use the kstest in scipy.stats for the non-standard distribution functions (ie. vary the DOF for Students t, or vary gamma for Cauchy)? My end goal is to find the max p-value and corresponding parameter for my distribution fit but that isn't the issue.</p> <p><strong>EDIT:</strong></p> <p><strong>"</stron...
2
2016-08-24T20:30:34Z
39,215,584
<p>It seems that what you really want to do is parameter estimation.Using the KT-test in this manner is not really what it is meant for. You should use the <code>.fit</code> method for the <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/stats.html#continuous-distributions" rel="nofollow">corresponding distrib...
1
2016-08-29T21:35:26Z
[ "python", "python-2.7", "scipy", "normal-distribution", "kolmogorov-smirnov" ]
Check if user input contains a word from an array - Python 3
39,132,563
<p>I am writing a code that asks a set amount of questions. I am trying to have the user input an answer and the code checks the users input for any word in a list of several words. </p> <pre><code>keywordlist = ("pain", "suffering", "hurt") question1 = input("how are you feeling?") if question1.lower() in keywordlis...
1
2016-08-24T20:32:10Z
39,132,606
<p>Splitting the string should work. You can split on spaces so each individual word ends up being an element in a list. Like so</p> <pre><code>keywordlist = ("pain", "suffering", "hurt") question1 = input("how are you feeling?") question_parts = question1.split(" ") for part in question_parts: if part.lower() in ...
0
2016-08-24T20:35:13Z
[ "python" ]
Check if user input contains a word from an array - Python 3
39,132,563
<p>I am writing a code that asks a set amount of questions. I am trying to have the user input an answer and the code checks the users input for any word in a list of several words. </p> <pre><code>keywordlist = ("pain", "suffering", "hurt") question1 = input("how are you feeling?") if question1.lower() in keywordlis...
1
2016-08-24T20:32:10Z
39,132,725
<p>Assuming that you want the user to input a sentence and want to check if any word is in the keyword list:</p> <pre><code>keywordlist = ("pain", "suffering", "hurt") question1 = input("how are you feeling?") input_words=question1.lower().split() for word in input_words: if word in keywordlist: print("som...
1
2016-08-24T20:43:39Z
[ "python" ]
Iterate through all files in a directory and find and replace text - Python
39,132,566
<p>Baby brand new. This was Frankenstein'ed together from a few similar topics, none of which seemed to cover the necessary step of nesting a find and replace inside a file loop. </p> <p>I am attempting to iterate through every file in a folder (not recursively, I only have one folder level) of a specific type (listed...
1
2016-08-24T20:32:17Z
39,132,623
<p>You should loop over the result of <code>glob</code> and not a tuple with the function object <code>glob</code>:</p> <pre><code>for filename in glob('*.LIC'): with fileinput.FileInput(filename, inplace=True, backup='.bak') as file: for line in file: print(line.replace('findText', 'replaceTex...
2
2016-08-24T20:36:28Z
[ "python", "python-3.x", "file-io", "glob" ]
Webscraping multiline cells in tables using CSS Selectors and Python
39,132,613
<p>So I'm webscraping a page (<a href="http://canoeracing.org.uk/marathon/results/burton2016.htm" rel="nofollow">http://canoeracing.org.uk/marathon/results/burton2016.htm</a>) where there are multiline cells in tables: <a href="http://i.stack.imgur.com/DHlLQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/DHlLQ....
2
2016-08-24T20:35:50Z
39,132,688
<p>The problem is that some of the cells contain multiple text nodes delimited by a <code>&lt;br&gt;</code>. In cases like this, <em>find all text nodes</em> and join them:</p> <pre><code>data1 = [", ".join(result.xpath("text()")) for result in rows] </code></pre> <p>For the provided rows in the screenshot, you woul...
2
2016-08-24T20:40:57Z
[ "python", "css", "web-scraping" ]
Python PYserial WxPython Threading
39,132,641
<p>Can any one please tell me whats wrong with this piece of code. </p> <p>When I press button 1 - everything is good. I want to press button2 - to stop the process started by button 1 and do an another process. I am unable to do it - MY GUI is going irresponsive. </p> <p>You are welcome to edit the serial communicat...
1
2016-08-24T20:37:34Z
39,149,329
<p>Don't use the <code>.join</code> commands. They are blocking the main thread.<br> See this SO question for an in depth description:<br> <a href="http://stackoverflow.com/questions/15085348/what-is-the-use-of-join-in-python-threading">what is the use of join() in python threading</a></p>
0
2016-08-25T15:34:07Z
[ "python", "multithreading", "wxpython", "pyserial" ]
Python PYserial WxPython Threading
39,132,641
<p>Can any one please tell me whats wrong with this piece of code. </p> <p>When I press button 1 - everything is good. I want to press button2 - to stop the process started by button 1 and do an another process. I am unable to do it - MY GUI is going irresponsive. </p> <p>You are welcome to edit the serial communicat...
1
2016-08-24T20:37:34Z
39,149,414
<p><code>Thread.join</code> will block until the thread terminates. If your GUI's event handlers are blocked and unable to return to the MainLoop then other events can not be received and dispatched, and so the application appears to be frozen.</p>
0
2016-08-25T15:37:37Z
[ "python", "multithreading", "wxpython", "pyserial" ]
Represent number as a bytes using 16-bit blocks
39,132,661
<p>I wish to convert a number like <code>683550</code> (0xA6E1E) to <code>b'\x1e\x6e\x0a\x00'</code>, where the number of bytes in the array is a multiple of 2 and where the len of the bytes object is only so long as it needs to be to represent the number.</p> <p>This is as far as I got:</p> <pre><code>"{0:0{1}x}".fo...
2
2016-08-24T20:38:55Z
39,132,879
<p>Use the <code>.tobytes</code>-method:</p> <pre><code>num = 683550 bytes = num.to_bytes((num.bit_length()+15)//16*2, "little") </code></pre>
2
2016-08-24T20:56:04Z
[ "python", "python-3.x" ]
Represent number as a bytes using 16-bit blocks
39,132,661
<p>I wish to convert a number like <code>683550</code> (0xA6E1E) to <code>b'\x1e\x6e\x0a\x00'</code>, where the number of bytes in the array is a multiple of 2 and where the len of the bytes object is only so long as it needs to be to represent the number.</p> <p>This is as far as I got:</p> <pre><code>"{0:0{1}x}".fo...
2
2016-08-24T20:38:55Z
39,134,342
<p>Using python3:</p> <pre class="lang-py prettyprint-override"><code>def encode_to_my_hex_format(num, bytes_group_len=2, byteorder='little'): """ @param byteorder can take the values 'little' or 'big' """ bytes_needed = abs(-len(bin(num)[2: ]) // 8) if bytes_needed % bytes_group_len: bytes_needed += by...
0
2016-08-24T23:09:16Z
[ "python", "python-3.x" ]
numpy array converted to pandas dataframe drops values
39,132,712
<p>I need to calculate statistics for each node of a 2D grid. I figured the easy way to do this was to take the cross join (AKA cartesian product) of two ranges. I implemented this using <code>numpy</code> as this function:</p> <pre><code>def node_grid(x_range, y_range, x_increment, y_increment): x_min = float(x_r...
2
2016-08-24T20:42:41Z
39,133,555
<p>I can't fully reproduce your code.</p> <p>But I find the problem is that you have to turn the lower and upper boundaries around in the <code>between</code> query. The following works for me:</p> <pre><code>print(node_df[(node_df.depth==10) &amp; node_df.xx.between(-31,-30)]) </code></pre> <p>when using:</p> <pre...
0
2016-08-24T21:49:13Z
[ "python", "pandas", "numpy" ]
numpy array converted to pandas dataframe drops values
39,132,712
<p>I need to calculate statistics for each node of a 2D grid. I figured the easy way to do this was to take the cross join (AKA cartesian product) of two ranges. I implemented this using <code>numpy</code> as this function:</p> <pre><code>def node_grid(x_range, y_range, x_increment, y_increment): x_min = float(x_r...
2
2016-08-24T20:42:41Z
39,133,567
<p>the "between" function demands that the first argument be less than the latter.</p> <p><code> In: print(node_df[(node_df.depth==10) &amp; node_df.xx.between(-31,-30)]) xx depth 116390 -31.0 10.0 116791 -30.9 10.0 117192 -30.8 10.0 117593 -30.7 10.0 117994 -30.6 10.0 118395 -30.5 10.0 118796 -...
1
2016-08-24T21:50:12Z
[ "python", "pandas", "numpy" ]
Increase Query Speed in Sqlite
39,132,715
<p>I am a very newbie in using python and sqlite. I am trying to create a script that reads a data from a table (rawdata) and then performs some calculations which is then stored in a new table. I am counting the number race that a player has won before that date at a particular track position and calculating the perce...
0
2016-08-24T20:42:51Z
39,133,431
<p>Sending and retrieving an SQL query is "expensive" in terms of time. The easiest way to speed things up would be to use SQL functions to reduce the number of queries.</p> <p>For example, the first two queries could be reduced to a single call using COUNT(), UNION, and Aliases.</p> <pre><code>SELECT COUNT(*) FROM ...
1
2016-08-24T21:38:38Z
[ "python", "sqlite" ]
Website forces scrapy redirect
39,132,733
<p>I keep on getting redirected from www.caribbeanjobs.com. I've programmed my spider to not obey the robot.txt, disabled cookies, tried meta=dont_redirect. What else can I do?</p> <p>This is my spider below:</p> <pre><code>import scrapy from tutorial.items import CaribbeanJobsItem class CaribbeanJobsSpider(scrapy....
1
2016-08-24T20:44:25Z
39,132,833
<p>Did you try setting an explicit <code>USER_AGENT</code> in your settings?</p> <p><a href="http://doc.scrapy.org/en/latest/topics/settings.html#user-agent" rel="nofollow">http://doc.scrapy.org/en/latest/topics/settings.html#user-agent</a></p> <p>Something like this might work as a starting point:</p> <pre><code>US...
2
2016-08-24T20:52:45Z
[ "python", "scrapy", "scrapy-spider" ]
Website forces scrapy redirect
39,132,733
<p>I keep on getting redirected from www.caribbeanjobs.com. I've programmed my spider to not obey the robot.txt, disabled cookies, tried meta=dont_redirect. What else can I do?</p> <p>This is my spider below:</p> <pre><code>import scrapy from tutorial.items import CaribbeanJobsItem class CaribbeanJobsSpider(scrapy....
1
2016-08-24T20:44:25Z
39,138,489
<p>You can specify handle_http_status. You can initialize this list post start_urls. </p> <pre><code>handle_http_status = ['303', '301'] </code></pre>
0
2016-08-25T06:49:45Z
[ "python", "scrapy", "scrapy-spider" ]
Simplest Group By / Sum in Pandas
39,132,739
<p>What's the simplest way to sum a two column pandas dataframe but keep it as a dataframe?</p> <p>I have a dataframe that looks like </p> <pre><code> sum1 sum2 0 8153.035 1132 1 12730.100 1559 2 10845.360 1268 3 6694.075 900 4 3740.105 608 5 3247.225 232 6 4579.725 646 7 9...
1
2016-08-24T20:45:03Z
39,132,762
<p>I was overthinking. Can just do </p> <pre><code>df = df.sum(axis=0) </code></pre>
0
2016-08-24T20:47:27Z
[ "python", "pandas", "group-by" ]
Simplest Group By / Sum in Pandas
39,132,739
<p>What's the simplest way to sum a two column pandas dataframe but keep it as a dataframe?</p> <p>I have a dataframe that looks like </p> <pre><code> sum1 sum2 0 8153.035 1132 1 12730.100 1559 2 10845.360 1268 3 6694.075 900 4 3740.105 608 5 3247.225 232 6 4579.725 646 7 9...
1
2016-08-24T20:45:03Z
39,132,791
<pre><code>df.sum().to_frame().T </code></pre> <p>Output:</p> <pre><code> sum1 sum2 0 112267.055 15255.0 </code></pre> <p>You could just do <code>df.sum()</code> to get the series</p> <pre><code>sum1 112267.055 sum2 15255.000 dtype: float64 </code></pre>
2
2016-08-24T20:48:55Z
[ "python", "pandas", "group-by" ]
Groupby value counts on the dataframe pandas
39,132,742
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame([ (1, 1, 'term1'), (1, 2, 'term2'), (1, 1, 'term1'), (1, 1, 'term2'), (2, 2, 'term3'), (2, 3, 'term1'), (2, 2, 'term1') ], columns=['id', 'group', 'term']) </code></pre> <p>I want to group it by <code>id</code> and <code>g...
5
2016-08-24T20:45:24Z
39,132,761
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>crosstab</code></a>:</p> <pre><code>print (pd.crosstab([df.id, df.group], df.term)) term term1 term2 term3 id group 1 1 2 1 0 2 0 1 ...
3
2016-08-24T20:47:25Z
[ "python", "pandas", "dataframe", "group-by", "crosstab" ]
Groupby value counts on the dataframe pandas
39,132,742
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame([ (1, 1, 'term1'), (1, 2, 'term2'), (1, 1, 'term1'), (1, 1, 'term2'), (2, 2, 'term3'), (2, 3, 'term1'), (2, 2, 'term1') ], columns=['id', 'group', 'term']) </code></pre> <p>I want to group it by <code>id</code> and <code>g...
5
2016-08-24T20:45:24Z
39,132,838
<p>using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table()</a> method:</p> <pre><code>In [22]: df.pivot_table(index=['id','group'], columns='term', aggfunc='size', fill_value=0) Out[22]: term term1 term2 term3 id group 1 1 2 1 ...
4
2016-08-24T20:53:14Z
[ "python", "pandas", "dataframe", "group-by", "crosstab" ]
Groupby value counts on the dataframe pandas
39,132,742
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame([ (1, 1, 'term1'), (1, 2, 'term2'), (1, 1, 'term1'), (1, 1, 'term2'), (2, 2, 'term3'), (2, 3, 'term1'), (2, 2, 'term1') ], columns=['id', 'group', 'term']) </code></pre> <p>I want to group it by <code>id</code> and <code>g...
5
2016-08-24T20:45:24Z
39,132,900
<p>I use <code>groupby</code> and <code>size</code></p> <pre><code>df.groupby(['id', 'group', 'term']).size().unstack(fill_value=0) </code></pre> <p><a href="http://i.stack.imgur.com/uEOMQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/uEOMQ.png" alt="enter image description here"></a></p> <hr> <h1>Timing</...
4
2016-08-24T20:57:41Z
[ "python", "pandas", "dataframe", "group-by", "crosstab" ]
Groupby value counts on the dataframe pandas
39,132,742
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame([ (1, 1, 'term1'), (1, 2, 'term2'), (1, 1, 'term1'), (1, 1, 'term2'), (2, 2, 'term3'), (2, 3, 'term1'), (2, 2, 'term1') ], columns=['id', 'group', 'term']) </code></pre> <p>I want to group it by <code>id</code> and <code>g...
5
2016-08-24T20:45:24Z
39,133,528
<p>Instead of remembering lengthy solutions, how about the one that pandas has built in for you:</p> <pre><code>df.groupby(['id', 'group', 'term']).count() </code></pre>
1
2016-08-24T21:46:53Z
[ "python", "pandas", "dataframe", "group-by", "crosstab" ]
Matching Unicode word boundaries in Python
39,132,743
<p>In order to match the Unicode word boundaries [as defined in the <a href="http://unicode.org/reports/tr29/#Word_Boundary_Rules">Annex #29</a>] in Python, I have been using the <code>regex</code> package with flags <code>regex.WORD | regex.V1</code> (<code>regex.UNICODE</code> should be default since the pattern is a...
12
2016-08-24T20:45:30Z
39,133,712
<p>1- <em>RIGHT SINGLE QUOTATION MARK <code>’</code></em> seems to be just simply missed in <a href="https://bitbucket.org/mrabarnett/mrab-regex/src/f21447bf288780d8dd9b1633820480484ce8f677/regex_3/regex/_regex.c?at=default&amp;fileviewer=file-view-default#_regex.c-1657" rel="nofollow">source file</a>:</p> <pre><co...
6
2016-08-24T22:02:52Z
[ "python", "regex", "python-3.x", "unicode" ]
need to improve accuracy in fsolve to find multiples roots
39,132,786
<p>I'm using this code to get the zeros of a nonlinear function. Most certainly, the function should have 1 or 3 zeros</p> <pre><code>import numpy as np import matplotlib.pylab as plt from scipy.optimize import fsolve [a, b, c] = [5, 10, 0] def func(x): return -(x+a) + b / (1 + np.exp(-(x + c))) x = np.linspace...
4
2016-08-24T20:48:45Z
39,133,446
<p>What you need is an automatic way to obtain good initial estimates of the roots of the function. This is in general a difficult task, however, for univariate, continuous functions, it is rather simple. The idea is to note that (a) this class of functions can be approximated to an arbitrary precision by a polynomial ...
2
2016-08-24T21:40:04Z
[ "python", "scipy", "mathematical-optimization" ]
need to improve accuracy in fsolve to find multiples roots
39,132,786
<p>I'm using this code to get the zeros of a nonlinear function. Most certainly, the function should have 1 or 3 zeros</p> <pre><code>import numpy as np import matplotlib.pylab as plt from scipy.optimize import fsolve [a, b, c] = [5, 10, 0] def func(x): return -(x+a) + b / (1 + np.exp(-(x + c))) x = np.linspace...
4
2016-08-24T20:48:45Z
39,133,895
<p>Between two stationary points (i.e., <code>df/dx=0</code>), you have one or zero roots. In your case it is possible to calculate the two stationary points analytically:</p> <pre><code>[-c + log(1/(b - sqrt(b*(b - 4)) - 2)) + log(2), -c + log(1/(b + sqrt(b*(b - 4)) - 2)) + log(2)] </code></pre> <p>So you have thre...
2
2016-08-24T22:22:16Z
[ "python", "scipy", "mathematical-optimization" ]
Adding numbers in a list except a specific number and the following number
39,132,819
<p>I am new to programming and I am trying to add up all the numbers in a given list except for the the number 13 and any number following the number 13. the problem that I am having is that if 13 is on the end of the list it won't add the first number. Any help would be appreciated. The code I have is as follows:</p...
3
2016-08-24T20:51:35Z
39,132,865
<p>In Python, an index of <code>-1</code> means the last item in a list. So, in your code, when <code>i</code> is <code>0</code> (the first number), it will not count it because the last item in the list is <code>13</code>.</p> <p>You can fix this with a simple check that <code>i &gt; 1</code> on that condition:</p> ...
2
2016-08-24T20:55:14Z
[ "python" ]
Adding numbers in a list except a specific number and the following number
39,132,819
<p>I am new to programming and I am trying to add up all the numbers in a given list except for the the number 13 and any number following the number 13. the problem that I am having is that if 13 is on the end of the list it won't add the first number. Any help would be appreciated. The code I have is as follows:</p...
3
2016-08-24T20:51:35Z
39,133,398
<p>My proposition:</p> <pre><code>def sum13(numbers): total = 0 skip = False for i, number in enumerate(numbers): if number == 13: skip = True continue if skip: skip = False continue total += number return total def test(): ...
0
2016-08-24T21:36:14Z
[ "python" ]
Why am I getting a break outside loop error for this python program but not for a similar program?
39,132,847
<p>I am new to coding and Stack Exchange. Please forgive any errors in terms of formatting questions (corrections are welcomed). My question is this. I am doing exercise 7-4 in "Python Crash Course". I have two programs that are very similar in terms of formatting and output. city_visits was the example given by the a...
1
2016-08-24T20:53:58Z
39,133,148
<p>Indentation is strict in Python. This:</p> <pre><code>if topping == "quit": break </code></pre> <p>should be this:</p> <pre><code>if topping == "quit": break </code></pre> <p>Very subtle, but very important in Python.</p>
0
2016-08-24T21:15:00Z
[ "python", "break" ]
Why am I getting a break outside loop error for this python program but not for a similar program?
39,132,847
<p>I am new to coding and Stack Exchange. Please forgive any errors in terms of formatting questions (corrections are welcomed). My question is this. I am doing exercise 7-4 in "Python Crash Course". I have two programs that are very similar in terms of formatting and output. city_visits was the example given by the a...
1
2016-08-24T20:53:58Z
39,133,315
<p>In Python, the scope of loops and <code>if/else</code> blocks is determined solely by indentation, so if your indentation is messed up -- as it seems to be the case in your code -- it will produce strange results, or not compile at all if certain elements like <code>break</code> are used in an unexpected context.</p...
1
2016-08-24T21:29:04Z
[ "python", "break" ]
Python Image Library: Image is turned by 90 degree?
39,132,878
<p>I have an image on my computer which has the dimensions width=1932 and height=2576. It was made with a smartphone and uses the "jpeg"-format.</p> <p>If i open the image with any tool i like it is shown correctly.</p> <p>I tried to open it with python:</p> <pre><code>from PIL import Image img_in = Image.open(input...
2
2016-08-24T20:55:59Z
39,132,990
<p>When you do a portrait picture with your smartphone and a landscape picture, both will be done with the same coordinate system, that is, relative to the orientation of the imaging sensor in your phone.</p> <p>However, the phone's gyroscope detects the rotation of the device, so it "knows" whether it is a portrait o...
1
2016-08-24T21:03:40Z
[ "python", "image", "python-imaging-library" ]
k-means / x-means (or other?) clustering in pandas/python
39,132,880
<p>I have a dataframe that can be reconstructed from the dict below. </p> <p>The dataframe represents <code>23 statistics (X1-X23)</code> for various cities around the world. Each city occupies a single row in the dataframe with the 23 statistics as separate columns. </p> <p>My actual df has <code>~6 million</code> ...
1
2016-08-24T20:56:17Z
39,133,382
<p>I don't know what you mean by "for further processing" but here is a super simple explanation to get you started.</p> <p>1) get the data into a dataframe (pandas) with the variables (x1-x23) across the top (column headers) and each row representing a different city (so that your df.head() shows x1-x23 for column he...
1
2016-08-24T21:34:35Z
[ "python", "pandas", "k-means" ]
changing shapes (pro)
39,132,905
<p>Hi I am new to programming and I am trying to write a code that will gather information from the input and apply it to the triangle.</p> <p>This is my code so far</p> <pre><code>steps = int(input("Size: ")) print('/\\') for i in range(steps - 1): print(" "*i+" \\") print(steps * "__" ) </code></pre> <p>sup...
1
2016-08-24T20:57:59Z
39,133,144
<p>Here's something I think will work. One key thing is that you aren't drawing the left side for all rows after the first, nor account for additional left space needed to align your triangle.</p> <pre><code>steps = int(input('Size: ')) for i in range(steps): left_space = steps - i - 1 inner_space = i pri...
1
2016-08-24T21:14:52Z
[ "python" ]
changing shapes (pro)
39,132,905
<p>Hi I am new to programming and I am trying to write a code that will gather information from the input and apply it to the triangle.</p> <p>This is my code so far</p> <pre><code>steps = int(input("Size: ")) print('/\\') for i in range(steps - 1): print(" "*i+" \\") print(steps * "__" ) </code></pre> <p>sup...
1
2016-08-24T20:57:59Z
39,133,205
<p>Here is my code:</p> <pre><code>steps=input("Size: ") for i in range(steps): j=steps-i-1 print ' '*j+"/"+' '*i+' '*i+'\\' print '-'*(steps*2+1) </code></pre> <p>Which is the same thing as below:</p> <pre><code>steps=input("Size: ") for i in range(steps): j=steps-i-1 print ' '*j+"/"+' '*(i*2)+'\\...
2
2016-08-24T21:20:25Z
[ "python" ]
How to implement a queue system that is shared between separate python processes?
39,132,981
<p>We have a python script that is kicked off after a user enters some data in a web form. The entire script takes 10-20 minutes to complete. A user can technically kick off 10 of these within 10 seconds if they so chose. If this happens, we'll have 10 of the same python scripts running at once and causing each other t...
1
2016-08-24T21:03:04Z
39,133,126
<p>Welcome to the wild world of distributing your computation!</p> <p>Implementing your own queuing system (even in Python) can lead to a world of hurt. A very popular, enterprise-grade and open source message queuing application is RabbitMQ. They have a <a href="http://www.rabbitmq.com/tutorials/tutorial-one-python.h...
2
2016-08-24T21:13:29Z
[ "python", "web-services", "queue" ]
How to keep a sorted list while entering data into it in Python
39,133,033
<p>I have a list of lists which need to be sorted based on the length of the lists. What I am doing now is first inserting the lists into the main list and then sort the main list giving <code>key=len</code>. This steps will take a total time of <code>n + nlg(n)</code>. Is it possible to maintain a sorted list while en...
1
2016-08-24T21:06:48Z
39,133,388
<p>It depends on the data structure you are using:</p> <ul> <li><a href="https://en.wikipedia.org/wiki/Dynamic_array" rel="nofollow">Dynamic Array</a> <ul> <li>Finding the right index on a sorted array is <code>O(log n)</code> using a bisect</li> <li>Inserting is <code>O(n)</code> as you have to shift everything</li>...
1
2016-08-24T21:35:19Z
[ "python", "list", "sorting", "asymptotic-complexity" ]
Set membership in Python
39,133,053
<p>I have a tuple x such that <code>x = (1, 2)</code> and I have a set z. Suppose I do this:</p> <pre><code>z = set(x) 1 in z # True 2 in z # True x in z # False </code></pre> <p>Why does this happen and how can I add tuples to a set and preserve their properties as tuples?</p>
-1
2016-08-24T21:08:10Z
39,133,074
<p>Pass tuples to your set constructor. If you would pass it like this:</p> <pre><code>x = ((1, 2), ) z = set(x) 1 in z # False 2 in z # False (1, 2) in z # True </code></pre>
0
2016-08-24T21:10:10Z
[ "python", "set" ]
Set membership in Python
39,133,053
<p>I have a tuple x such that <code>x = (1, 2)</code> and I have a set z. Suppose I do this:</p> <pre><code>z = set(x) 1 in z # True 2 in z # True x in z # False </code></pre> <p>Why does this happen and how can I add tuples to a set and preserve their properties as tuples?</p>
-1
2016-08-24T21:08:10Z
39,133,077
<p>Try doing any of these instead:</p> <ul> <li><code>z = {x}</code></li> <li><code>z = set([x])</code></li> <li><code>z = set(); z.add(x)</code></li> <li><code>z = set(); z.update([x])</code></li> </ul>
1
2016-08-24T21:10:16Z
[ "python", "set" ]
Confusion about variables in python
39,133,088
<p>I am trying to implement heapsort but I am getting unexpected results. I think this is due to something I don't understand about how Python handles variables (I am talking about side effects). Here's the code:</p> <pre><code>from math import * def parent(i): return floor((i+1)/2)-1 def left(i): return 2*i...
3
2016-08-24T21:10:57Z
39,133,159
<p>At the start of the function, the list <code>A</code> inside the function is the same as the list outside of the function, and any modifications made to one will be reflected in the other (it's a mutable object).</p> <p>When you do an assignment to a list, you're substituting a new list object for the old list obje...
2
2016-08-24T21:16:18Z
[ "python" ]
Confusion about variables in python
39,133,088
<p>I am trying to implement heapsort but I am getting unexpected results. I think this is due to something I don't understand about how Python handles variables (I am talking about side effects). Here's the code:</p> <pre><code>from math import * def parent(i): return floor((i+1)/2)-1 def left(i): return 2*i...
3
2016-08-24T21:10:57Z
39,133,165
<pre><code>A = C + A[k-1:n] </code></pre> <p>This is the line responsible for the behaviour you're seeing. By setting A equal to A[0:k-1] + A[k-1:n] you are making a copy of all of A's elements. If you want your changes to persist within the list you passed in you must assign the list to all the elements of A like so:...
1
2016-08-24T21:16:45Z
[ "python" ]
Confusion about variables in python
39,133,088
<p>I am trying to implement heapsort but I am getting unexpected results. I think this is due to something I don't understand about how Python handles variables (I am talking about side effects). Here's the code:</p> <pre><code>from math import * def parent(i): return floor((i+1)/2)-1 def left(i): return 2*i...
3
2016-08-24T21:10:57Z
39,133,472
<p>The following implementation shows a rewrite of your code but includes an alternate solution above the last call to the <code>print</code> function. The commented-out line may replace the line directly above it, or you may choose to return <code>a</code> at the end of the <code>heap_sort</code> function and rebind t...
1
2016-08-24T21:42:07Z
[ "python" ]
Apply same selection (cut) to multiple dataframes
39,133,121
<p>My question is about making selections in <code>pandas</code> (python.)</p> <p>As you know, one can apply a <code>selection</code> (or 'cut') to a dataframe by doing</p> <pre><code>df = df[df.area &gt; 10] </code></pre> <p>if you wanted to (say) select all rows whose column value of <code>area</code> was greater ...
1
2016-08-24T21:13:16Z
39,133,196
<p>I can get something similar</p> <pre><code>cut = lambda df: df[df.area &gt; 10] cut(df) </code></pre> <p>Per @root</p> <pre><code>cut = 'area &gt; 10' df.query(cut) </code></pre> <p>Per @ayhan</p> <pre><code>cut = lambda x: x.area &gt; 10 df[cut] </code></pre> <hr> <h3>Timing</h3> <p><strong><em>100 rows</em...
5
2016-08-24T21:19:22Z
[ "python", "pandas", "filter" ]
Embedding Python in C: Passing a two dimensional array and retrieving back a list
39,133,222
<p>I want to pass a list of arrays (or a 2D array) such as <code>[[1,2,3],[4,5,6]]</code> from C to a Python script which computes and returns a list. What possible changes would be required to the embedding <a href="https://docs.python.org/3/extending/embedding.html#pure-embedding" rel="nofollow">code</a> in order to ...
1
2016-08-24T21:21:50Z
39,176,243
<p>I think what you want to do is to pass in some Lists, have them converted to C arrays and then back to Lists before returning to Python.</p> <p>The Lists are received in C as a pointer to a PyObject, so to get the data from you'll have to use <a href="https://docs.python.org/3.4/extending/extending.html" rel="nofol...
0
2016-08-27T00:13:20Z
[ "python", "c", "arrays", "python-c-api", "python-embedding" ]
Share a variable between two files?
39,133,230
<p>What is a mechanism in Python by which I can do the following:</p> <p>file1.py:</p> <pre><code>def getStatus(): print status </code></pre> <p>file2.py:</p> <pre><code>status = 5 getStatus() # 5 status = 1 getStatus() # 1 </code></pre> <p>The function and the variable are in two different files and I'd like ...
-2
2016-08-24T21:22:15Z
39,231,803
<p>You can share variables without making them global by putting them in a module. Anybody who imports the module gets the <em>same</em> module object, so its contents are shared; changes made at one location show up in all the others.</p> <p>notglobal.py:</p> <pre><code>status = 0 </code></pre> <p>get.py:</p> <pre...
2
2016-08-30T15:38:29Z
[ "python" ]
Numpy array multiplication of LDL^T factorization of symmetric matrix
39,133,279
<p>Suppose I have an "LDL^T" decomposition of a symmetric, positive-semidefinite matrix A (<code>numpy</code> array), and I would like to multiply all factors together to obtain A.</p> <p>What is the most efficient way to achieve this?</p> <p>Currently, I am doing (D is available as "vector"): <code>np.dot(np.dot...
2
2016-08-24T21:26:15Z
39,133,425
<p><strong>Approach #1</strong></p> <p>We could use <code>elementwise multiplication</code> and then <code>matrix-multiplication</code>. This basically replaces <code>np.dot(L, np.diag(D))</code> with a direct <code>element-wise multiplication</code> for hopefully some speedup. So, with it, the implementation would be...
2
2016-08-24T21:38:08Z
[ "python", "performance", "numpy" ]
Weights and Bias from Trained Meta Graph
39,133,285
<p>I have successfully exported a re-trained InceptionV3 NN as a TensorFlow meta graph. I have read this protobuf back into python successfully, but I am struggling to see a way to export each layers weight and bias values, which I am assuming is stored within the meta graph protobuf, for recreating the nn outside of T...
2
2016-08-24T21:26:40Z
39,134,460
<p>The <code>MetaGraphDef</code> proto doesn't actually contain the values of the weights and biases. Instead it provides a way to associate a <code>GraphDef</code> with the weights stored in one or more checkpoint files, written by a <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/state_ops.html#Sav...
3
2016-08-24T23:24:04Z
[ "python", "tensorflow", "protocol-buffers", "protoc" ]
django user permissions not showing in production
39,133,380
<p>I have a wierd problem , In production I can't see user permissions list in django admin and after openning group edit page it's show noting and page language transform to another language .</p> <p>I have some cusotm permission define in app models .</p> <p>what I done ?</p> <ol> <li>sync my local database with p...
1
2016-08-24T21:34:09Z
39,143,766
<p>Problem was from os default encoding , I had some unicod permission names in my table and it's wont load and error happened . </p> <p>so I just add this three line in my wsgi.py </p> <pre><code>import sys reload(sys) sys.setdefaultencoding('utf8') </code></pre>
0
2016-08-25T11:14:22Z
[ "python", "django", "gunicorn", "supervisord" ]
Python 3.5 OpenSSL error
39,133,428
<p>SO I am was working with <a href="https://github.com/errbotio/errbot" rel="nofollow">errbot</a> and fired up a virtualenv with python3.5. When I run the errbot command I get this error </p> <pre><code>from OpenSSL import crypto File "/Users/me/workspace/chatbotv2/chatbot_venv3/lib/python3.5/site-packages/OpenSSL/...
1
2016-08-24T21:38:32Z
39,171,768
<p>Upgrade your pip. pip 8.1+ will download a binary wheel that will have cryptography precompiled. If you want to compile it yourself the correct environment variables for homebrew can also be found in the docs on the <a href="https://cryptography.io/en/latest/installation/" rel="nofollow">installation</a> page.</p>
1
2016-08-26T17:29:19Z
[ "python", "osx", "python-3.x", "ssl", "errbot" ]
Continuous Interpolation in MATLAB?
39,133,448
<p>I have a set of data that I would like to get an interpolating function for. MATLAB's interpolating functions seem to only return values at a finer set of discrete points. However, for my purposes, I need to be able to look up the function value for <em>any</em> input. What I'm looking for is something like SciPy's ...
1
2016-08-24T21:40:11Z
39,133,530
<p>That appears to be what <a href="http://www.mathworks.com/help/matlab/ref/ppval.html" rel="nofollow"><code>ppval</code></a> is for. It looks like many of the <a href="http://www.mathworks.com/help/matlab/1-d-interpolation.html" rel="nofollow">1D interpolation functions</a> have a <code>pp</code> variant that plugs ...
2
2016-08-24T21:47:03Z
[ "python", "matlab", "input", "interpolation", "data-analysis" ]
Trying to write and read multiple lines on a JSON File on python
39,133,505
<p>I'm writing a random script to make a student name be linked with a grade on a dictionary, it's simple, for writing on a file, i'm using a JSON module:</p> <pre><code>import json for i in range(1000): finalMedia = {"name":"name", "media":media} json.dump(finalMedia, open("xtext.txt",'w')) txt.write("\n"...
0
2016-08-24T21:45:10Z
39,133,531
<pre><code>data = map(json.loads,open("xtext.txt")) </code></pre> <p>each line is a json structure ... but when together as a single file thats not valid json</p> <p>although really you should just write the json.dump once</p> <pre><code>medias = [{"name":"name", "media":media} for name,media in all_media] json.dump...
3
2016-08-24T21:47:07Z
[ "python", "json" ]
Writing a Twisted Client to send looping GET request to multiple API calls and record response
39,133,507
<p>I haven't done twisted programming in a while so I'm trying to get back into it for a new project. I'm attempting to set up a twisted client that can take a list of servers as an argument, and for each server it sends an API GET call and writes the return message to a file. This API GET call should be repeated ever...
0
2016-08-24T21:45:19Z
39,136,513
<p>Look what the cat dragged in!</p> <blockquote> <p>So how do I create multiple call agent</p> </blockquote> <p>Use <a href="http://treq.readthedocs.io/en/latest/index.html" rel="nofollow"><code>treq</code></a> you dingus :D. You rarely want to get tangled up with the <code>Agent</code> class.</p> <blockquote> ...
1
2016-08-25T04:02:18Z
[ "python", "api", "client", "twisted" ]
Identifying collections from pair wise combinations
39,133,511
<p>I have a list of tuples that identifies pair wise relations between items.</p> <pre><code>[(1,2), (2,3), (3,1), (4,5), (5,4), (6,7)] </code></pre> <p>I want to look across the tuples and collapse them into unique collections as below (maybe as a hash map - any other efficient data structures?):</p> <pre><code>{a:...
0
2016-08-24T21:45:35Z
39,133,910
<p>You basically want to find connected components. For that there is a function <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.connected_components.html" rel="nofollow">connected_components</a> in scipy. You just have to reinterpret your data a bit:</p> <pre><code>l = [(1,2), (2,3),...
2
2016-08-24T22:24:21Z
[ "python", "algorithm" ]
Return multiple HttpResponse objects that are Excel spreadsheets
39,133,529
<p>The desired outcome is to export a spreadsheet of all users in the database, but rather than export them all at once - break up the users into 3 groups and export each of these groups as a spread sheet.</p> <p>I am using xlsxwriter and StringIO</p> <p>Thus far the code is returning only the first HttpResponse obje...
1
2016-08-24T21:46:58Z
39,134,274
<p>You <strong>can not return multiple HttpResponse</strong> object with single API call. However as a workaround, you can:</p> <ul> <li><p><strong>Approach 1: <em>If content is going to be always dynamic and file reference is not needed in future</em></strong>: Make multiple request each returning <code>HttpResponse<...
1
2016-08-24T23:00:20Z
[ "python", "django", "export", "xlsxwriter" ]