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
How to split string by space and treat special characters as a separate word in Python?
37,445,266
<p>Assume I have a string, </p> <pre><code>"I want that one, it is great." </code></pre> <p>I want to split up this string to be </p> <pre><code>["I", "want", "that", "one", ",", "it", "is", "great", "."] </code></pre> <p>Keeping special characters such as <code>",.:;"</code> and possibly other ones to be treated a...
1
2016-05-25T18:44:35Z
37,445,417
<p>You can use Regex and a simple list comprehension to do this. The regex will pull out words and separate punctuation, and the list comprehension will remove the blank spaces.</p> <pre><code>import re s = "I want that one, it is great. Don't do it." new_s = [c.strip() for c in re.split('(\W+)', s) if c.strip() != ''...
1
2016-05-25T18:53:24Z
[ "python", "python-2.7" ]
How to split string by space and treat special characters as a separate word in Python?
37,445,266
<p>Assume I have a string, </p> <pre><code>"I want that one, it is great." </code></pre> <p>I want to split up this string to be </p> <pre><code>["I", "want", "that", "one", ",", "it", "is", "great", "."] </code></pre> <p>Keeping special characters such as <code>",.:;"</code> and possibly other ones to be treated a...
1
2016-05-25T18:44:35Z
37,445,441
<p>I don't know of any functions that can do this but you could use a for loop.</p> <p>Something like this: word = "" wordLength = 0 for i in range(0, len(stringName)): if stringName[i] != " ": for x in range((i-wordLength), i): word += stringName[i] wordLengt...
0
2016-05-25T18:54:52Z
[ "python", "python-2.7" ]
How to split string by space and treat special characters as a separate word in Python?
37,445,266
<p>Assume I have a string, </p> <pre><code>"I want that one, it is great." </code></pre> <p>I want to split up this string to be </p> <pre><code>["I", "want", "that", "one", ",", "it", "is", "great", "."] </code></pre> <p>Keeping special characters such as <code>",.:;"</code> and possibly other ones to be treated a...
1
2016-05-25T18:44:35Z
37,445,513
<pre><code>In [70]: re.findall(r"[^,.:;' ]+|[,.:;']", "I want that one, it is great.") Out[70]: ['I', 'want', 'that', 'one', ',', 'it', 'is', 'great', '.'] In [76]: re.findall(r"[^,.:;' ]+|[,.:;']", "I don't.") Out[76]: ['I', 'don', "'", 't', '.'] </code></pre> <p>The regex <code>[^,.:;' ]+|[,.:;']</code> matches (1...
1
2016-05-25T18:58:49Z
[ "python", "python-2.7" ]
Pandas Cannot Create a DataFrame from a Numpy Array Of Timestamps
37,445,334
<p>I have a numpy array of Pandas Timestamps:</p> <pre><code>array([[Timestamp('2016-05-02 15:50:00+0000', tz='UTC', offset='5T'), Timestamp('2016-05-02 15:50:00+0000', tz='UTC', offset='5T'), Timestamp('2016-05-02 15:50:00+0000', tz='UTC', offset='5T')], [Timestamp('2016-05-02 17:10:00+0000', t...
2
2016-05-25T18:47:47Z
37,445,453
<p>I think you can use <code>list</code> comprehension:</p> <pre><code>import pandas as pd import numpy as np a =np.array([[pd.Timestamp('2016-05-02 15:50:00+0000', tz='UTC', offset='5T'), pd.Timestamp('2016-05-02 15:50:00+0000', tz='UTC', offset='5T'), pd.Timestamp('2016-05-02 15:50:00+0000', tz='UTC...
1
2016-05-25T18:55:21Z
[ "python", "arrays", "numpy", "pandas", "dataframe" ]
How to access the Django Model Instance from a Django Field
37,445,356
<p>I'm trying to make a Custom Field that can access it's Django Model to perform some work. Do Model Fields have this ability?</p> <p>Here is what I'd like to do, but the code is obviously not complete:</p> <pre><code>from django.db import models class MyField(models.Field): def __init__(self, *args, **kwargs...
2
2016-05-25T18:49:30Z
37,445,744
<p>I couldn't find anything obvious in the docs.</p> <p>From looking at the code in <code>django/db/models/fields/__init__.py</code> (v 1.9.6), <code>class Field</code> has an attribute called <code>model</code>, which appears to refer to the parent. I haven't dug any deeper, but that class definition has a lot of stu...
1
2016-05-25T19:12:42Z
[ "python", "django" ]
Importing modules from different directories
37,445,370
<p>What is the pythonic way for absolute importing modules located in different directories in Python 3? I am able to import modules by modifying the <code>sys.path</code> but that method is hackey.</p> <p>The alternative method, from what I've read, is to turn the project into a pip installable package. This is metho...
0
2016-05-25T18:50:38Z
37,445,467
<h2>Loading a script dynamically from anywhere via a given path</h2> <pre><code>import importlib.machinery import imp import os.path path = '/home/user/testscript' # without .py fname = os.path.basename(path) namespace = fname.replace(' ', '_').strip('\\/;,. ') loader = importlib.machinery.SourceFileLoader(namespa...
2
2016-05-25T18:56:23Z
[ "python", "python-3.x", "import", "packaging", "setup.py" ]
Importing modules from different directories
37,445,370
<p>What is the pythonic way for absolute importing modules located in different directories in Python 3? I am able to import modules by modifying the <code>sys.path</code> but that method is hackey.</p> <p>The alternative method, from what I've read, is to turn the project into a pip installable package. This is metho...
0
2016-05-25T18:50:38Z
37,447,622
<p>I struggled with this problem for a long time, and found the best method to create the <code>setup.py</code> file as you mentioned - don't worry, it's very easy. The basic one looks like this (<a href="https://docs.python.org/2/distutils/introduction.html#distutils-simple-example" rel="nofollow">taken from python do...
0
2016-05-25T21:06:12Z
[ "python", "python-3.x", "import", "packaging", "setup.py" ]
When embedding python in another application how do I import or call a function in a submodule (i.e. scipy.optimize.nnls)?
37,445,397
<p>First I'll restate the question: When embedding Python into a C/C++ application using <a href="https://docs.python.org/3.4/extending/embedding.html#compiling" rel="nofollow">python docs</a> and other resources. I discovered that you can import a module using</p> <pre><code>PyObject *pName = PyUnicode_FromString((ch...
2
2016-05-25T18:52:23Z
37,445,813
<p>Like the rarely-used built-in <code>__import__</code> function, when you <code>PyImport_Import</code> the name <code>scipy.optimize</code>, the import system does load the <code>scipy.optimize</code> module, but it returns <code>scipy</code> instead of <code>scipy.optimize</code>. You need to follow the attribute ch...
2
2016-05-25T19:16:15Z
[ "python", "c++", "numpy", "python-embedding" ]
When embedding python in another application how do I import or call a function in a submodule (i.e. scipy.optimize.nnls)?
37,445,397
<p>First I'll restate the question: When embedding Python into a C/C++ application using <a href="https://docs.python.org/3.4/extending/embedding.html#compiling" rel="nofollow">python docs</a> and other resources. I discovered that you can import a module using</p> <pre><code>PyObject *pName = PyUnicode_FromString((ch...
2
2016-05-25T18:52:23Z
37,445,831
<p>First of all, I've never use <code>PyImport_Import()</code>. I've always used <code>PyImport_ImportModule()</code>, which takes a <code>const char *</code> arg instead of a <code>PyObject *</code>. That should save some steps in your code.</p> <pre><code>PyObject *pModule = PyImport_ImportModule("scipy.optimize")...
1
2016-05-25T19:17:11Z
[ "python", "c++", "numpy", "python-embedding" ]
python: how to find a subset of one set that is closest to another
37,445,418
<p>I have the following optimization problem that I can solve by "brute force" but am wondering if someone has already implemented a solver that I could use to do it faster and more elegantly.</p> <p>I have two disjoint lists of integers. These are actually unique so I can say these are two sets. One is short with (<c...
1
2016-05-25T18:53:33Z
37,446,292
<p>I know you said these are lists, but is there any reason to not temporarily convert them to numpy arrays? This can be straight forward (in case you don't know how to do the conversion): </p> <pre><code>s = np.array(s) l = np.array(l) </code></pre> <p>From there, you can make use of the "searchsorted" function. M...
1
2016-05-25T19:44:09Z
[ "python", "algorithm", "optimization", "subset", "distance" ]
python: how to find a subset of one set that is closest to another
37,445,418
<p>I have the following optimization problem that I can solve by "brute force" but am wondering if someone has already implemented a solver that I could use to do it faster and more elegantly.</p> <p>I have two disjoint lists of integers. These are actually unique so I can say these are two sets. One is short with (<c...
1
2016-05-25T18:53:33Z
37,447,691
<p>The distance function could be critical. If you define the distance function as the absolute difference between the sum of elements in sets s and l2, then the problem is actually NP-hard. Essentially, you are trying to find a subset of set l whose sum is close to the sum of elements in s. And the subset-sum problem ...
0
2016-05-25T21:11:26Z
[ "python", "algorithm", "optimization", "subset", "distance" ]
Pandas - Replace NaN with two different values
37,445,466
<p>I'm trying to replace my NaN value in my DataFrame. I would like to replace 60% of the NaN by one value and 40% by another. I read the documentation of fillna method but I don't find.</p> <p>Any idea ?</p> <p>Thanks</p>
-2
2016-05-25T18:56:23Z
37,445,517
<p>you can do it this way:</p> <pre><code>df.loc[your_condition_for_60%] = df.fillna(10) df.loc[your_condition_for_40%] = df.fillna(20) </code></pre>
1
2016-05-25T18:59:07Z
[ "python", "pandas", "scikit-learn" ]
Pandas - Replace NaN with two different values
37,445,466
<p>I'm trying to replace my NaN value in my DataFrame. I would like to replace 60% of the NaN by one value and 40% by another. I read the documentation of fillna method but I don't find.</p> <p>Any idea ?</p> <p>Thanks</p>
-2
2016-05-25T18:56:23Z
37,446,393
<p>Create a boolean array that has a chance at 60/40 True/False the same size as the df you're filling. Then use <code>combine_first</code></p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(index=list('ABCDEFGHIJ'), columns=list('abcdefghij')) mask60 = np.random.rand(*df.shape) &gt; 0.6 value...
2
2016-05-25T19:50:05Z
[ "python", "pandas", "scikit-learn" ]
Rendering in looping using django
37,445,485
<p>The goal is rendering data to html using django every 5 second, but the problem is the looping does not working. This is the code:</p> <p><strong>view.py</strong></p> <pre><code>def form(request): try: file_name = request.FILES['files'].name nama = "uploads/" + file_name seq_act, num_obsv, observer, li...
2
2016-05-25T18:57:37Z
37,445,667
<p>If your goal is showing actual data, you can render page as usual (without loop) and reload page with JS:</p> <pre><code>&lt;script&gt; setTimeout(function() { window.location.reload() }, 5000); &lt;/script&gt; </code></pre>
0
2016-05-25T19:08:29Z
[ "python", "html", "django" ]
python print escape backslash
37,445,554
<p>I need python to generate exactly such string literal:</p> <pre><code>e.b=\"e\" </code></pre> <p>But I can't come up with idea how to do so. I was trying:</p> <pre><code>r'e.b=\"e\"' =&gt; e.b=\\"e\\" """e.b=\"e\"""" =&gt; e.b="e" </code></pre> <p>And many other possibilities but any ends up with...
2
2016-05-25T19:01:11Z
37,445,611
<p>Are you thinking of printing like this?</p> <pre><code>import re d = re.escape(r'e.b=\"e\"') print d </code></pre>
0
2016-05-25T19:04:36Z
[ "python", "string", "python-2.7" ]
python print escape backslash
37,445,554
<p>I need python to generate exactly such string literal:</p> <pre><code>e.b=\"e\" </code></pre> <p>But I can't come up with idea how to do so. I was trying:</p> <pre><code>r'e.b=\"e\"' =&gt; e.b=\\"e\\" """e.b=\"e\"""" =&gt; e.b="e" </code></pre> <p>And many other possibilities but any ends up with...
2
2016-05-25T19:01:11Z
37,445,612
<p>Well, you had it right the first time, except that you examined the <a href="http://stackoverflow.com/q/7784148/2096752"><code>repr</code></a> of the string you created, instead of the string itself:</p> <pre><code>s = r'e.b=\"e\"' s # this is the repr() of the string =&gt; 'e.b=\\"e\\"' print(repr(s)) =&gt; 'e.b=...
6
2016-05-25T19:04:37Z
[ "python", "string", "python-2.7" ]
Python Multiprocessing imap chunksize
37,445,763
<p>I would like to compare two folders with same path structure and same files in all the subfolders. The folder is quite big with size of about 80GB and file numbers of 8000.</p> <p>I would like to make sure each corresponding file pairs under two top directories have the same md5 checksum value. I wrote a simple tre...
2
2016-05-25T19:13:38Z
37,491,756
<p>It's the IO that limits the performance. The MD5 algorithm is now a too easy task for CPUs. The following code calculates MD5 performance in GB/s.</p> <pre><code>import time import hashlib from multiprocessing import Pool def worker(x): data = bytearray(xrange(256)) * 4 * 1024 md5 = hashlib.md5() for x...
0
2016-05-27T20:28:39Z
[ "python", "multiprocessing", "python-multiprocessing" ]
Why `heapq.merge(some_lists_of_iterators)` does not return an iterator of iterators?
37,445,804
<p>In the following code:</p> <pre><code>import heapq nums = [1,2,3] result = [set([])] bases = [] for n in nums: bases.append(set([n])) # Now bases is [set([1]), set([2]), set([3])] def gen (base): for r in result: if base != r: yield base | r # It yields set([]) unions base...
0
2016-05-25T19:15:52Z
37,445,876
<p>Have you tried changing: </p> <pre><code>itr1 = iter(map(gen, bases)) itr2 = heapq.merge(*map(gen, bases)) </code></pre> <p>to:</p> <pre><code>itr1 = iter(map(gen, bases)) itr2 = iter(heapq.merge(*map(gen, bases))) </code></pre>
0
2016-05-25T19:19:34Z
[ "python", "python-2.7", "iterator", "heap", "generator" ]
Pandas read_table error
37,445,855
<p>I am trying to read a tab delimited text file into a dataframe. </p> <p>This is the how the file looks in Excel: </p> <pre><code>CALENDAR_DATE ORDER_NUMBER INVOICE_NUMBER TRANSACTION_TYPE CUSTOMER_NUMBER CUSTOMER_NAME 5/13/2016 0:00 13867666 6892372 S 2026 ...
5
2016-05-25T19:18:35Z
37,445,919
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> with separator 2 and more whitespaces:</p> <pre><code>import pandas as pd import io temp=u"""CALENDAR_DATE ORDER_NUMBER INVOICE_NUMBER TRANSACTION_TYPE CUSTOMER_NUMBER ...
4
2016-05-25T19:22:15Z
[ "python", "mysql", "pandas" ]
Json error : "end is out of bounds"?
37,445,874
<p>I'm having an issue I can't understand. I sending a json data as string via Redis (as a queue) and the receiver is throwing the following error :</p> <pre><code>[ERROR JSON (in queue)] - {"ip": null, "domain": "somedomain.com", "name": "Some user name", "contact_id": 12345, "signature": "6f496a4eaba2c1ea4e371ea2c4...
0
2016-05-25T19:19:29Z
37,445,946
<p>You are loading <code>item[1]</code>, which is the second character of the string <code>items</code>:</p> <pre><code>&gt;&gt;&gt; json.loads('"') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/_...
4
2016-05-25T19:24:14Z
[ "python", "json" ]
<Response [200]> is not JSON serializable
37,445,886
<p>following the document conversion API example trying to use Flask to convert msword document to text, but it does not work.</p> <p>Here is the code</p> <pre><code>import os, json, requests from flask import Flask, jsonify from watson_developer_cloud import DocumentConversionV1 app = Flask(__name__) #create flas...
0
2016-05-25T19:20:18Z
37,820,539
<p>The documentation appears to be out of date. The object returned is a <a href="http://docs.python-requests.org/en/master/api/#requests.Response" rel="nofollow">Response</a> object, as seen in the <a href="http://docs.python-requests.org/en/master/" rel="nofollow">Requests</a> library. In my experience, you can just ...
0
2016-06-14T19:28:37Z
[ "python", "document-conversion" ]
Remove QSplitter line between widgets
37,445,896
<p>I am building a UI and I have a horizontal QSplitter with 2 widgets. I want to remove the line with the dots (.....) between the widgets. </p> <p>Here is an image to make it clear what I want removed. </p> <p><a href="http://i.stack.imgur.com/sUC61.png" rel="nofollow">the dots I want gone</a><br> here is some code...
0
2016-05-25T19:20:55Z
37,446,979
<p>I think you have applied a stylesheet somewhere in you code. To hide the image, try this:</p> <pre><code>self.mySplitter.setStyleSheet("QSplitter::handle { image: none; }") </code></pre> <p>Hope this helps!</p>
0
2016-05-25T20:25:33Z
[ "python", "pyqt", "qsplitter" ]
How to return HTTP 303 from python?
37,445,901
<p>This question comes from <a href="http://stackoverflow.com/questions/37399965/refresh-web-page-using-a-cgi-python-script">this one</a>.</p> <p>What I want is to be able to return the <code>HTTP 303</code> header from my python script, when the user clicks on a button. My script is very simple and as far as output i...
1
2016-05-25T19:21:14Z
37,447,075
<p>Typically browsers like to see <code>/r/n/r/n</code> at the end of an HTTP response.</p>
0
2016-05-25T20:31:35Z
[ "python", "python-2.7", "cgi", "http-status-codes", "http-status-code-303" ]
How to return HTTP 303 from python?
37,445,901
<p>This question comes from <a href="http://stackoverflow.com/questions/37399965/refresh-web-page-using-a-cgi-python-script">this one</a>.</p> <p>What I want is to be able to return the <code>HTTP 303</code> header from my python script, when the user clicks on a button. My script is very simple and as far as output i...
1
2016-05-25T19:21:14Z
37,468,554
<p>Assuming you are using cgi (<a href="https://docs.python.org/2/library/cgi.html" rel="nofollow">2.7</a>)(<a href="https://docs.python.org/3.5/library/cgi.html" rel="nofollow">3.5</a>)</p> <p>The example below should redirect to the same page. The example doesn't attempt to parse headers, check what POST was send, i...
0
2016-05-26T18:31:48Z
[ "python", "python-2.7", "cgi", "http-status-codes", "http-status-code-303" ]
Python sklearn.linear_model: LinearRegression() ValueError occured when .predict()
37,446,104
<p>My training matrix X has shape (5182, 19231) and y is a list of 1s and 0s with length 5182. My test matrix has shape (496, 5477). I stored them in seperate pickle files. Here is my code:</p> <pre><code>def read(pklFile1): f=open(pklFile1, 'rb') Y = cPickle.load(f) f.close() return Y if __name__ == '...
1
2016-05-25T19:33:33Z
37,446,231
<p>You trained a linar model on 19231 features, but want to predict some new sample with only 5477 features. <strong>That's not how linear models work (or most of the classifiers)</strong>. The number of features need to be the same!</p> <p>How should your linear model, which consists of a linear combination of 19231 ...
0
2016-05-25T19:40:58Z
[ "python", "machine-learning", "nlp", "scikit-learn", "linear-regression" ]
How to create a sorted list given two already sorted lists ( cannot modify either given lists )
37,446,249
<p>My goal is to create a function that takes 2 lists of sorted ints as arguments and creates a sorted merged list. The only problem is that I am not allowed to modify the 2 original lists ( and cant make duplicates to modify either ). Only allowed built-ins are range(), len(), index(), append(). So far I am stumped. ...
-1
2016-05-25T19:42:04Z
37,446,413
<p>That's fairly simple. Merge the lists using + and then use the sorted function.</p> <pre><code>merged = sorted(list1 + list2) </code></pre>
0
2016-05-25T19:51:44Z
[ "python", "list", "python-2.7", "function", "sorting" ]
How to create a sorted list given two already sorted lists ( cannot modify either given lists )
37,446,249
<p>My goal is to create a function that takes 2 lists of sorted ints as arguments and creates a sorted merged list. The only problem is that I am not allowed to modify the 2 original lists ( and cant make duplicates to modify either ). Only allowed built-ins are range(), len(), index(), append(). So far I am stumped. ...
-1
2016-05-25T19:42:04Z
37,446,739
<p>The code is actually a lot simpler than what you wrote. </p> <pre><code>def merge_lists(list1, list2): sortedList = [] pointer1 = 0 pointer2 = 0 while pointer1 &lt; len(list1) and pointer2 &lt; len(list2): if list1[pointer1] &lt; list2[pointer2]: sortedList.append(list1[pointer1...
1
2016-05-25T20:11:23Z
[ "python", "list", "python-2.7", "function", "sorting" ]
How to create a sorted list given two already sorted lists ( cannot modify either given lists )
37,446,249
<p>My goal is to create a function that takes 2 lists of sorted ints as arguments and creates a sorted merged list. The only problem is that I am not allowed to modify the 2 original lists ( and cant make duplicates to modify either ). Only allowed built-ins are range(), len(), index(), append(). So far I am stumped. ...
-1
2016-05-25T19:42:04Z
37,446,779
<p>Your for loop to iterate over both the lists and keep appending the smaller value and incrementing corresponding index is correct.</p> <pre><code> def merge_lists( list1, list2 ): sortedList = [] pointer1 = 0 pointer2 = 0 while pointer1 &lt; len( list1 ) and pointer2 &lt; len( list2 ...
0
2016-05-25T20:13:53Z
[ "python", "list", "python-2.7", "function", "sorting" ]
How to create a sorted list given two already sorted lists ( cannot modify either given lists )
37,446,249
<p>My goal is to create a function that takes 2 lists of sorted ints as arguments and creates a sorted merged list. The only problem is that I am not allowed to modify the 2 original lists ( and cant make duplicates to modify either ). Only allowed built-ins are range(), len(), index(), append(). So far I am stumped. ...
-1
2016-05-25T19:42:04Z
37,446,892
<p>The problem is in your <code>amountNumbersLeft1 = len( list1 ) - ( pointer1 - 1 )</code> line: In your second set of test data, the <code>len( list1 )</code> function will return 4. and the <code>pointer1</code> will be 3 since it's pointing to index 3. <code>(4 - ( 3 - 1))</code> is 2, which is the index you outpu...
0
2016-05-25T20:20:26Z
[ "python", "list", "python-2.7", "function", "sorting" ]
PyDev - how to include new apps in the project
37,446,282
<p>I have created a new app inside a django project using the command line: <code>python manage.py startapp name</code> and I'm using PyDev as my IDE for the first time.</p> <p>My problem is that I can't add this app to the project so I can begin to code. I have been reading some questions and answers but so far I cou...
0
2016-05-25T19:43:40Z
37,478,375
<p>I usually use the context menu (right click on project in project explorer) and choose django/start new app.</p>
0
2016-05-27T08:19:13Z
[ "python", "django", "eclipse" ]
Python Game if statement executing
37,446,457
<p>I'm working on the Python Pig Game as a hobby. My specific question is in regards to the second <code>if</code> statement. Why does it run when in the previous <code>if</code> statement I've set <code>player1roll = 'End Turn'</code>? </p> <pre><code>import random, easygui player1score = 0 player2score = 0 playe...
0
2016-05-25T19:54:41Z
37,446,575
<p>It's due to the operator precedence. AND binds tighter than OR, so your expression is evaluated as:</p> <pre><code> if dice1roll == 1 or (dice2roll == 1 and player2roll != 'End Turn'): </code></pre> <p>which is basically an <em>OR</em> operation of <em>True</em> and <em>False</em> if dice1roll equals 1</p> <p>R...
0
2016-05-25T20:01:50Z
[ "python" ]
Python Game if statement executing
37,446,457
<p>I'm working on the Python Pig Game as a hobby. My specific question is in regards to the second <code>if</code> statement. Why does it run when in the previous <code>if</code> statement I've set <code>player1roll = 'End Turn'</code>? </p> <pre><code>import random, easygui player1score = 0 player2score = 0 playe...
0
2016-05-25T19:54:41Z
37,446,585
<p>In this:</p> <pre><code>if dice1roll == 1 or dice2roll == 1 and player1roll != 'End Turn': </code></pre> <p>If <code>dice1roll == 1</code> is true, the entire statement passes due to the order of operations. Take a look at these groupings:</p> <pre><code>&gt;&gt;&gt; (1 or 0) and 0 0 &gt;&gt;&gt; 1 or (0 and 0) 1...
0
2016-05-25T20:02:22Z
[ "python" ]
Python Game if statement executing
37,446,457
<p>I'm working on the Python Pig Game as a hobby. My specific question is in regards to the second <code>if</code> statement. Why does it run when in the previous <code>if</code> statement I've set <code>player1roll = 'End Turn'</code>? </p> <pre><code>import random, easygui player1score = 0 player2score = 0 playe...
0
2016-05-25T19:54:41Z
37,446,768
<p>I suppose "the second if statement" you mention is this one:</p> <pre><code> if dice1roll == 1 or dice2roll == 1 and player1roll != 'End Turn': </code></pre> <p>the difference between this one and the one before is that the first one says "if A <strong>and</strong> B, do this", while the second says "if A <strong>...
0
2016-05-25T20:13:16Z
[ "python" ]
Summing items in an array -- in a DataFrame -- in a groupby
37,446,465
<p>I'm working on some code that shows the distribution of topic models over time. Right now, the dataframe looks something like this:</p> <pre><code>doc_id date topic_dist 1 2007-01-01 [.2,.5,.3] 2 2007-03-02 [.8,.1,.1] ... </code></pre> <p>My goal is to group the documents by date (by month, y...
1
2016-05-25T19:55:19Z
37,446,802
<h3>Setup</h3> <pre><code>import pandas as pd df = pd.DataFrame([[1, '2007-01-01', [.2, .5, .3]], [2, '2007-01-02', [.8, .5, .3]]], columns=['doc_id', 'date', 'topic_dist']) df.date = pd.to_datetime(df.date) df = df.set_index('date') </code></pre> <h3>Solution</h3> <pre><code>d...
1
2016-05-25T20:15:18Z
[ "python", "pandas" ]
Summing items in an array -- in a DataFrame -- in a groupby
37,446,465
<p>I'm working on some code that shows the distribution of topic models over time. Right now, the dataframe looks something like this:</p> <pre><code>doc_id date topic_dist 1 2007-01-01 [.2,.5,.3] 2 2007-03-02 [.8,.1,.1] ... </code></pre> <p>My goal is to group the documents by date (by month, y...
1
2016-05-25T19:55:19Z
37,447,100
<p>I may be doing something wrong, but @piRSquared's solution seems to break with the example DataFrame below when you group by one month. Though it does not break with a 12 month group. I guess it has to do with dates spanning over one year.</p> <p>Another option is to just cast the topic_dist column to Numpy arrays ...
1
2016-05-25T20:32:48Z
[ "python", "pandas" ]
Python: Check if named pipe has data
37,446,556
<p>I have a Python3 process on my Unix system always running, and I want to be able to randomly send data to it through a named pipe from other processes that only run occasionally. If the named pipe doesn't have data, I want my process to continue doing other things, so I need to check whether it has data <strong>with...
4
2016-05-25T20:00:57Z
37,447,115
<p>I would not use a named-pipe if you can change the clients' code, but <a href="http://man7.org/linux/man-pages/man7/unix.7.html" rel="nofollow">UNIX domain sockets</a> instead, because they support datagrams:</p> <pre><code>import errno, fcntl, os, socket </code></pre> <p>Server:</p> <pre><code># bind socket sock...
1
2016-05-25T20:33:36Z
[ "python", "named-pipes" ]
Python: Check if named pipe has data
37,446,556
<p>I have a Python3 process on my Unix system always running, and I want to be able to randomly send data to it through a named pipe from other processes that only run occasionally. If the named pipe doesn't have data, I want my process to continue doing other things, so I need to check whether it has data <strong>with...
4
2016-05-25T20:00:57Z
37,448,125
<p>This isn't really the answer, but in case it's useful to anyone, here's how I'm doing it with another thread.</p> <pre><code>class QueryThread(threading.Thread): def __init__(self, args=(), kwargs=None): threading.Thread.__init__(self, args=(), kwargs=None) self.daemon = True self.buf =...
0
2016-05-25T21:43:24Z
[ "python", "named-pipes" ]
Select upvote button on reddit with selenium python
37,446,563
<p>I was trying to send click to a reddit upvote button using the selenium in python but I am unable to select the upvote button "arrow up login-required access-required"</p> <p>HTML Code of upvote and downvote buttons :</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="sn...
-4
2016-05-25T20:01:05Z
37,446,877
<p>You're trying to click <code>&lt;div class="arrow up login-required access-required" data-event-action="upvote" role="button" aria-label="upvote" tabindex="0"&gt;&lt;/div&gt;</code> but both of the selectors you provided look unrelated. Your xpath try indicates a button (you want a div) and your 'by class name' try ...
2
2016-05-25T20:19:39Z
[ "python", "selenium" ]
Scipy Minimize Not Working
37,446,666
<p>I'm running the minimization below:</p> <pre><code>from scipy.optimize import minimize import numpy as np import math import matplotlib.pyplot as plt ### objective function ### def Rlzd_Vol1(w1, S): L = len(S) - 1 m = len(S[0]) # Compute log returns, size (L, m) LR = np.array([np.diff(np.log(S[:,j...
0
2016-05-25T20:06:47Z
37,462,515
<p><code>w1</code> is passed in as a (single entry) vector and not as scalar from the <code>minimize</code> routine. Try what happens if you define <code>w1 = np.array([0.2])</code> and then calculate <code>w = np.array([w1, 1.0 - w1])</code>. You'll see you get a 2x1 matrix instead of a 2 entry vector.</p> <p>To make...
2
2016-05-26T13:38:07Z
[ "python", "optimization", "scipy", "minimize" ]
Finding the element in one array corresponding to the maximum value in another
37,446,740
<p>How can I align the 4d z array and the 4d QCLOUD array and to then find out the z value of when QCLOUD max occurs? </p> <pre><code>print(z.shape) print(qcloud.shape) out: (6, 100, 128, 128) (6, 99, 128, 128) </code></pre>
0
2016-05-25T20:11:25Z
37,449,522
<p>Ignoring the fact that <code>(np.array(z.shape) &gt; np.array(qcloud.shape)).any()</code>, you want <code>argmax</code>:</p> <pre><code>idx = np.argmax(qcloud) result = z[tuple(idx)] </code></pre>
0
2016-05-26T00:06:29Z
[ "python", "numpy", "matplotlib", "scipy", "jupyter-notebook" ]
Python iterate from a dictionary with two values
37,446,785
<p>I have the following python dictionary, </p> <p><code>dict1 = {'fabric_ssh_hosts': ['192.168.3.44 192.168.3.45 192.168.3.46']}</code></p> <p>How can I iterate, to produce the following output?</p> <p><code>192.168.3.44</code></p> <p><code>192.168.3.45</code></p> <p><code>192.168.3.46</code></p>
-1
2016-05-25T20:14:13Z
37,446,835
<pre><code>for host in dict1['fabric_ssh_hosts'][0].split(): print host </code></pre> <p>Explanation: split(), when called with no arguments, splits on whitespace. dict1['fabric_ssh_hosts'] is a list, so [0] gets the first (and only) element of it. So that creates the list, which is iterated through.</p>
4
2016-05-25T20:16:54Z
[ "python" ]
Python iterate from a dictionary with two values
37,446,785
<p>I have the following python dictionary, </p> <p><code>dict1 = {'fabric_ssh_hosts': ['192.168.3.44 192.168.3.45 192.168.3.46']}</code></p> <p>How can I iterate, to produce the following output?</p> <p><code>192.168.3.44</code></p> <p><code>192.168.3.45</code></p> <p><code>192.168.3.46</code></p>
-1
2016-05-25T20:14:13Z
37,447,093
<p>I suspect something went wrong with your code. Why would you put all adresses in just one string and then put that into a list inside a dictionary?</p> <p>In case you really mean what you wrote something like that should work</p> <pre><code>dict1 = {'fabric_ssh_hosts': ['192.168.3.44 192.168.3.45 192.168.3.46']} ...
0
2016-05-25T20:32:25Z
[ "python" ]
Bulk download images from paths in .csv -> batch edit in GIMP -> upload -> gather links in .csv
37,446,827
<p>Shopify's bulk product upload feature is reasonably easy to use, but uploading images is always a struggle and I'd like to automate the process as much as possible.</p> <p>I get excel files from vendors with image links in them, I could copy the links directly into my shopify upload .csv, but then I get formatting ...
1
2016-05-25T20:16:35Z
37,499,896
<p>Yes, but:</p> <p>For 2) you don't need to use Gimp. There are libraries for this kind of simple image editing, such as the ImageMAgick toolbox (that has Python bindings)</p> <p>3) and 4) are likely the same, when you upload a file you should get a link (didn't look too closely at the DropBox API though). </p> <p>...
1
2016-05-28T13:59:30Z
[ "python", "csv", "shopify", "gimp" ]
web.py : Error loading multiple html files via iFrames
37,446,843
<p>I am learning <code>web.py</code> and trying out a application where <code>web.py</code> needs to load a <code>html</code> file having <code>iframes</code> that loads three different <code>html</code> files.</p> <p>The <code>index.html</code> file loads properly with desired results when launched directly from <co...
2
2016-05-25T20:17:21Z
37,570,529
<p>After digging through <code>web.py</code> documentation, all I needed to do was to provide file name with full path of <code>html</code> files in order to make them accessible via <code>urls</code>.</p> <p>I thought I would post here in case anyone else runs into similar issue.</p> <pre><code>""" url definition"""...
1
2016-06-01T13:44:04Z
[ "python", "html", "iframe", "web.py" ]
Can't create virtual env with pip in Ubuntu - No module named urllib3
37,446,883
<p>I am having the following problem when trying to create a virtual env on Ubuntu:</p> <pre><code>$ mkvirtualenv test New python executable in /home/ubuntu/.virtualenvs/test/bin/python Installing setuptools, pip, wheel... Complete output from command /home/ubuntu/.virtualenvs/test/bin/python - setuptools pip wheel:...
1
2016-05-25T20:20:02Z
38,038,071
<p>This seems to be an issue specific to using Anaconda. You can create a virtualenv with the default python: </p> <pre><code>mkvirtualenv test -p /usr/bin/python </code></pre>
0
2016-06-26T11:30:52Z
[ "python", "ubuntu", "pip" ]
How to pass an array from python to shell script and execute it?
37,446,911
<p>I have an array <code>HSPACE</code> which is defined inside a python script. I am trying to pass this array to a shell script "arraytest" and execute it from python itself. I am trying with the following piece of code but it doesnt seem to be working:</p> <pre><code>HSPACE=[0.01, 0.009, 0.008, 0.007] subprocess.cal...
0
2016-05-25T20:21:25Z
37,446,944
<p>The easy answer is to pass each array entry as a literal argv entry:</p> <pre><code>subprocess.call(['./arraytest'] + [str(s) for s in HSPACE], shell=False) </code></pre> <p>...thereafter...</p> <pre><code>#!/bin/bash printf 'hspace array entry: %q\n' "$@" </code></pre> <hr> <p>Another approach is to pass an ar...
3
2016-05-25T20:23:36Z
[ "python", "arrays", "bash" ]
If I have a list of character strings which are words separated by commas, how do I convert that into a DataFrame with word pairings and frequencies?
37,446,943
<p>Meta: Sorry about the badly phrased title, I'm really not sure how to describe what I'm asking in just one sentence.</p> <p>I have a list of strings which looks like this:</p> <pre><code>'word1, word2, word3' 'word2, word3' 'word4, word3, word1' 'word2, word4' </code></pre> <p>From that array I want to generate a...
0
2016-05-25T20:23:35Z
37,447,737
<p>You could iterate through the strings, split them on commas followed by a space, and use <code>IT.combinations</code> to form all pairs of words. A <code>collections.Counter</code> could be used to count the frequency of the pairs. And finally, the desired DataFrame could be built from the items in the <code>Counter...
1
2016-05-25T21:13:59Z
[ "python", "arrays", "pandas", "nlp" ]
Simple regex for simple xml string
37,446,964
<p>I have a string consisting of elements. Each element can contain "pear" or "apple". I can get all the elements using:</p> <pre><code>s = '&lt;tag&gt;uTSqUYRR8gapple&lt;/tag&gt;&lt;tag&gt;K9VGTZM3h8&lt;/tag&gt;&lt;tag&gt;pearTYysnMXMUc&lt;/tag&gt;&lt;tag&gt;udv5NZQdpzpearz5a4oS85mD&lt;/tag&gt;' import re; re.findall...
-2
2016-05-25T20:24:49Z
37,447,108
<p>Use a parser, ie <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"><code>BeautifulSoup</code></a> instead:</p> <pre><code>import re from bs4 import BeautifulSoup s = '&lt;tag&gt;uTSqUYRR8gapple&lt;/tag&gt;&lt;tag&gt;K9VGTZM3h8&lt;/tag&gt;&lt;tag&gt;pearTYysnMXMUc&lt;/tag&gt;&lt;tag&gt...
1
2016-05-25T20:33:12Z
[ "python", "regex", "xml" ]
Simple regex for simple xml string
37,446,964
<p>I have a string consisting of elements. Each element can contain "pear" or "apple". I can get all the elements using:</p> <pre><code>s = '&lt;tag&gt;uTSqUYRR8gapple&lt;/tag&gt;&lt;tag&gt;K9VGTZM3h8&lt;/tag&gt;&lt;tag&gt;pearTYysnMXMUc&lt;/tag&gt;&lt;tag&gt;udv5NZQdpzpearz5a4oS85mD&lt;/tag&gt;' import re; re.findall...
-2
2016-05-25T20:24:49Z
37,447,607
<p>Using a proper XML library will let you use XPath to encapsulate your query. For instance:</p> <pre><code>s = '&lt;root&gt;&lt;tag&gt;uTSqUYRR8gapple&lt;/tag&gt;&lt;tag&gt;K9VGTZM3h8&lt;/tag&gt;&lt;tag&gt;pearTYysnMXMUc&lt;/tag&gt;&lt;tag&gt;udv5NZQdpzpearz5a4oS85mD&lt;/tag&gt;&lt;/root&gt;' import lxml.etree root...
0
2016-05-25T21:05:10Z
[ "python", "regex", "xml" ]
how to change figure canvas size in matplotlib without altering plots?
37,446,970
<p>i would like to annotate panels of figures i am making with panel labels ("A", "B", ...") in matplotlib. for example i'd like to annotate a set of subplots with a large "A" in the upper left hand corner of the figure as in code below. how can i change the figure canvas to make this "A" visible? </p> <pre><code>f = ...
-1
2016-05-25T20:25:07Z
37,478,288
<p>Add <code>plt.subplots_adjust()</code>:</p> <pre><code>f = plt.figure(figsize=(5,5)) plt.subplot(2, 2, 1) # this "A" is clipped in the plot plt.annotate("A", xy = (-0.25, 1.1), xytext = (-0.25, 1.1), xycoords = 'axes fraction', textcoords = 'axes fraction', ...
1
2016-05-27T08:15:01Z
[ "python", "matplotlib" ]
different colors for rows in barh chart from pandas dataframe python
37,447,056
<p>I have the following pandas dataframe:</p> <pre><code> a b bob 23 25 john 13 21 paul 20 19 david 17 14 michael 14 24 neil 22 11 df.plot(kind='barh') </code></pre> <p>I used the pandas plot function. I want to make a barh chart with all the row...
1
2016-05-25T20:30:38Z
37,447,793
<p>It appears that Pandas only supports using the <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html#colormaps" rel="nofollow">colormap</a> attribute, which applies the same map to each row in your chart, e.g.:</p> <pre><code>df.plot(kind='barh', colormap='RdBu') </code></pre> <p>For your purpose...
3
2016-05-25T21:18:31Z
[ "python", "pandas", "matplotlib", "bar-chart" ]
Turtle Onkey - Enter Key
37,447,069
<p>Simple question, what is the term for the <kbd>Enter</kbd> key for <code>Turtle.Onkey()</code></p> <p>I've tried <code>turtle.onkey(check, 'Enter')</code> but I get the error:</p> <pre><code>TclError: bad event type or keysym "Enter" </code></pre> <p>So, I think that I have entered the wrong word for 'Enter'</p> ...
0
2016-05-25T20:31:07Z
37,841,040
<pre><code>turtle.onkey(check, 'return') </code></pre> <p>This should do it.</p>
0
2016-06-15T16:34:31Z
[ "python", "turtle-graphics" ]
Regex parse string in python
37,447,201
<p>I have various strings. I want to check if a string is firstly in the format of <code>xy:someword</code> and then retrieve the <code>someword</code> part. <code>xy</code> should be characters from a to z. </p> <p>For example:</p> <p><code>eu:road</code> should give me <code>road</code></p> <p><code>somestring 100...
-2
2016-05-25T20:39:24Z
37,447,277
<p>You can use a regex like <code>^[a-z]{2}:(\w+)$</code> and then use <code>group(1)</code> to get the content of the capturing group (<code>(...)</code>):</p> <pre><code>&gt;&gt;&gt; p = "^[a-z]{2}:(\w+)$" &gt;&gt;&gt; re.match(p, "eu:road").group(1) 'road' &gt;&gt;&gt; re.match(p, "road:eu") None </code></pre>
1
2016-05-25T20:44:42Z
[ "python", "regex" ]
Issue with PyCharm, Matplotlib and Anaconda on OS X - figure is all black
37,447,276
<p>I am using PyCharm Community 4.0.7</p> <p>I am using Anaconda2 4.0.0</p> <p>I am using OS X 10.11.4</p> <p>I have configured PyCharm to use Anaconda in the default settings (and can see the list of modules etc).</p> <p>When I try a simple test in python console:</p> <pre><code>import matplotlib.pyplot as plt pl...
0
2016-05-25T20:44:42Z
37,447,511
<p>well...seems like updating to PyCharm 4.5.5 fixed it...</p>
0
2016-05-25T20:59:50Z
[ "python", "matplotlib", "pycharm", "anaconda" ]
How to Add Temporary Attribute to Django Querysets and then Merge
37,447,338
<p>So I am trying to add a temporary attribute to two separate QuerySets from the same model, but it seems that as soon as I try to merge them together, the new fields disappear.</p> <p>Example:</p> <pre><code>class IndexView(View): def get(self, request): q1 = MyModel.objects.filter(points=0) q2 ...
0
2016-05-25T20:48:09Z
37,447,568
<p>There's no way you can do this, because when you do:</p> <pre><code>q = q1 | q2 </code></pre> <p>You were executing a new database query. There's no straightforward way for this, you could only query them all together then mark then respectively:</p> <pre><code>queryset = MyModel.objects.filter(Q(points=0) | Q(po...
0
2016-05-25T21:03:04Z
[ "python", "django", "list", "filter", "django-queryset" ]
How to Add Temporary Attribute to Django Querysets and then Merge
37,447,338
<p>So I am trying to add a temporary attribute to two separate QuerySets from the same model, but it seems that as soon as I try to merge them together, the new fields disappear.</p> <p>Example:</p> <pre><code>class IndexView(View): def get(self, request): q1 = MyModel.objects.filter(points=0) q2 ...
0
2016-05-25T20:48:09Z
37,517,141
<p>Django <a href="https://docs.djangoproject.com/en/1.9/ref/models/conditional-expressions/" rel="nofollow">conditional expressions</a> are your friends</p> <blockquote> <p>Conditional expressions let you use if ... elif ... else logic within filters, annotations, aggregations, and updates. A conditional expres...
0
2016-05-30T03:16:34Z
[ "python", "django", "list", "filter", "django-queryset" ]
dataframe representation of a rolling window
37,447,347
<p>I want a dataframe representation of of a rolling window. Instead of performing some operation on a rolling window, I want a dataframe where the window is represented in another dimension. This could be as a <code>pd.Panel</code> or <code>np.array</code> or a <code>pd.DataFrame</code> with a <code>pd.MultiIndex</c...
2
2016-05-25T20:48:43Z
37,448,165
<p>Disclaimers: </p> <p>First, I would not call the method you provide clunky. It is readable and you can easily generalize with a list comprehension to any window size. At the same time, this is somewhat of an open ended question that may have many solutions, including your own.</p> <p>/Disclaimers</p> <p>Here is o...
1
2016-05-25T21:45:32Z
[ "python", "numpy", "pandas" ]
Filtering before parsing with lxml
37,447,465
<p>I plan to use <code>lxml</code>to parse a large amount of xml documents (30+ gb). However, I only need to fully parse some of these documents. There are some identifying features of the documents I want such as <code>&lt;recordtype="2"&gt;</code>. <code>recordtype</code> values may span from <code>1-10</code>, for e...
-1
2016-05-25T20:56:03Z
37,448,143
<p><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">BeautifulSoup</a> has good documentation on how to extract features from html and xml files.</p> <p>I would suggest you use xml to extract the data. I do not know the format of your file. </p> <p>But if you need to use lxml <a href="ht...
0
2016-05-25T21:44:21Z
[ "python", "xml", "parsing" ]
Is there a more reliable drop-in replacement for mimetypes.guess_extension()?
37,447,541
<p>I'm up against the following (Python 2.7.10 on Ubuntu Trusty):</p> <pre><code>&gt;&gt;&gt; from mimetypes import guess_extension &gt;&gt;&gt; guess_extension('text/html') '.html' &gt;&gt;&gt; guess_extension('application/json') '.json' &gt;&gt;&gt; guess_extension('text/plain') '.ksh' &gt;&gt;&gt; guess_extension('...
0
2016-05-25T21:01:41Z
37,447,630
<p>If you're dealing with a fix set of mimetypes that <code>guess_extension</code> is getting wrong, put an override dictionary ahead of the guess.</p> <pre><code>known_extension = {'text/html': '.txt', ...} ... extension = known_extension.get(mimetype) or guess_extension(mimetype) </code></pre>
1
2016-05-25T21:06:47Z
[ "python", "mime-types" ]
Using Matplotlib's pick event properly
37,447,657
<p>I believe I am not using Matplotlib's pick events properly. In the following code, I create three disjoint orange disks of specified radius and position identified by an id number. </p> <p>I want to <strong>single</strong>-click on each of the disks and print out a message to the terminal identifying the disks, cen...
1
2016-05-25T21:08:46Z
37,462,794
<p>There are a number of ways to handle this. I've modified your code to try to show two possible ways (so it has extraneous code though matter which way you'd like to handle it). </p> <p><strong>Generally, I think you'd only attach a single <code>pick_event</code> handler, and that handler would need to determine w...
2
2016-05-26T13:49:31Z
[ "python", "matplotlib" ]
Python error using zipfile: 'list' object has no attribute 'tell'
37,447,658
<p>I'm trying to zip up only *.csv files in a directory with this code:</p> <pre><code>allFiles = os.listdir( dirName + apt + '/' ) csvList = [i for i in allFiles if i.endswith('.csv')] zf = zipfile.ZipFile([ dirName + apt + '.zip' ], mode='w') for f in csvList: a = dirName + apt + '/' + f zf.write( ...
0
2016-05-25T21:08:47Z
37,447,829
<p>This line:</p> <pre><code>zf = zipfile.ZipFile([ dirName + apt + '.zip' ], mode='w') </code></pre> <p>should be:</p> <pre><code>zf = zipfile.ZipFile(dirName + apt + '.zip', mode='w') </code></pre> <p>This is because <a href="https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile" rel="nofollow">ZipFile</...
0
2016-05-25T21:21:19Z
[ "python", "list", "zip", "attributeerror", "tell" ]
Get HTTP Response Status Code
37,447,698
<p>I'm using python and scapy to send HTTP request to a specific URL address. After sending it, I want to read the response status code (200, 401, 404, etc.).</p> <p>I used this method:</p> <pre><code>&gt;&gt;&gt; syn = IP(dst='www.google.com') / TCP(dport=80, flags='S') &gt;&gt;&gt; syn_ack = sr1(syn) &gt;&gt;&gt; g...
0
2016-05-25T21:11:55Z
37,449,101
<p>It's likely that your OS will send a RST packet automatically in response to the SYN+ACK received. By using sniff tool like wireshark, you can see that. </p> <p>The issue can be resolved by adding an iptables rules to suppress the outgoing RST</p> <pre><code>sudo iptables -A OUTPUT -p tcp --dport 80 --tcp-flags RS...
0
2016-05-25T23:13:32Z
[ "python", "http", "http-status-codes", "scapy" ]
Get HTTP Response Status Code
37,447,698
<p>I'm using python and scapy to send HTTP request to a specific URL address. After sending it, I want to read the response status code (200, 401, 404, etc.).</p> <p>I used this method:</p> <pre><code>&gt;&gt;&gt; syn = IP(dst='www.google.com') / TCP(dport=80, flags='S') &gt;&gt;&gt; syn_ack = sr1(syn) &gt;&gt;&gt; g...
0
2016-05-25T21:11:55Z
37,467,791
<p>By using sr1(), you can only receive the first packet responded from server, in some cases an "empty" ACK to acknowledge the data you sent, so you cannot find the HTTP response and the response code. My suggestion is to use sr() instead of sr1(), as follows:</p> <pre><code>reply = sr(request, multi=1, timeout=2) </...
1
2016-05-26T17:46:56Z
[ "python", "http", "http-status-codes", "scapy" ]
Python factorial by recursion
37,447,790
<p>When calculating factorial by recursion, why does this code work:</p> <pre><code>def factorial(x): if x == 1: return x return factorial(x - 1) * x </code></pre> <p>But this doesn't:</p> <pre><code>def factorial(x): if x == 1: return x return factorial(x) * (x - 1) </code></pr...
-3
2016-05-25T21:18:17Z
37,447,812
<p>The second code is infinitely recursive. You keep calling <code>factorial(x)</code> over and over again.</p> <p>The first version subtracts <code>1</code> from <code>x</code> each call, so eventually <code>x</code> will hit your base case, which is <code>x == 1</code>.</p>
2
2016-05-25T21:19:44Z
[ "python", "recursion" ]
Python factorial by recursion
37,447,790
<p>When calculating factorial by recursion, why does this code work:</p> <pre><code>def factorial(x): if x == 1: return x return factorial(x - 1) * x </code></pre> <p>But this doesn't:</p> <pre><code>def factorial(x): if x == 1: return x return factorial(x) * (x - 1) </code></pr...
-3
2016-05-25T21:18:17Z
37,447,869
<p>Well, when we define the factorial we said that <code>n! = n*(n-1)!</code>, on your second code, what you wrote was <code>n! = (n-1)*n!</code></p>
3
2016-05-25T21:24:04Z
[ "python", "recursion" ]
Python factorial by recursion
37,447,790
<p>When calculating factorial by recursion, why does this code work:</p> <pre><code>def factorial(x): if x == 1: return x return factorial(x - 1) * x </code></pre> <p>But this doesn't:</p> <pre><code>def factorial(x): if x == 1: return x return factorial(x) * (x - 1) </code></pr...
-3
2016-05-25T21:18:17Z
37,448,627
<p>It's hard to go through the stack trace that you failed to provide. Let's take a look at the expansion of each function for 3!</p> <p>First function:</p> <pre><code>factorial(3) factorial(2) * 3 factorial(1) * 2 * 3 1 * 2 * 3 </code></pre> <p>... which results in the expected answer, 6</p> <p>Second function:</...
1
2016-05-25T22:22:27Z
[ "python", "recursion" ]
pandas corr table column name behavior
37,447,860
<p>I'm calculating a corr table in pandas,</p> <pre><code>df = pd.DataFrame(np.random.rand(6, 6)) c = df.corr() </code></pre> <p>But when I try to change the name of the columns,</p> <pre><code>c.columns.name = 'col' </code></pre> <p>I get this,</p> <pre><code>col 0 1 2 3 4...
1
2016-05-25T21:22:50Z
37,447,891
<p>When you perform the <code>corr</code> method and produce the correlation matrix, you end up with a square matrix where the columns are the same as the rows. It's convenient to assign both the <code>index</code> and <code>columns</code> to be the same object. So <code>c.index</code> and <code>c.columns</code> are ...
1
2016-05-25T21:26:07Z
[ "python", "numpy", "pandas" ]
pandas corr table column name behavior
37,447,860
<p>I'm calculating a corr table in pandas,</p> <pre><code>df = pd.DataFrame(np.random.rand(6, 6)) c = df.corr() </code></pre> <p>But when I try to change the name of the columns,</p> <pre><code>c.columns.name = 'col' </code></pre> <p>I get this,</p> <pre><code>col 0 1 2 3 4...
1
2016-05-25T21:22:50Z
37,447,937
<p>if you are just after renaming the index, you can do it this way:</p> <pre><code>In [235]: c.rename_axis('col') Out[235]: 0 1 2 3 4 5 col 0 1.000000 -0.406438 0.715564 -0.354630 -0.313099 -0.723027 1 -0.406438 1.000000 -0.512059 -0.369779 -0.201501 0.44591...
1
2016-05-25T21:29:30Z
[ "python", "numpy", "pandas" ]
How to get VirtualEnv TensorFlow to work in PyCharm?
37,447,906
<p>So I installed tensorflow onto my mac through the main response from here: <a href="http://stackoverflow.com/a/33691154/6095482">http://stackoverflow.com/a/33691154/6095482</a></p> <p>This means that my tensorflow works in a virtualenv. I can run it through my terminal for scripting purposes, but was wondering if t...
1
2016-05-25T21:27:29Z
37,468,323
<p>You have installed <code>tensorflow</code> in a <code>virtualenv</code>, here's how to get PyCharm to use it:</p> <ol> <li><p>First you want to add that virtualenv you created and installed tensorflow in, as an interpreter in PyCharm. Please follow this guide from PyCharm makers: <a href="https://www.jetbrains.com/...
2
2016-05-26T18:18:03Z
[ "python", "ide", "virtualenv", "tensorflow" ]
Regexp to match random order words
37,447,983
<p>I have the following pseudo-DSL:</p> <pre><code>&lt; allow | deny &gt; &lt; tcp | udp | any &gt; src &lt; prefix | $ip | @hostgroup | any &gt; [ port number | range | @portgroup | any ] dst &lt; prefix | $ip | @hostgroup | any &gt; [ port number | range | @portgroup | any ] [ stateful ] [ expire YYYYMMDD ] [ ...
0
2016-05-25T21:33:15Z
37,448,205
<blockquote> <ol> <li>How can I match <code>stateful</code>, <code>expire &lt;value&gt;</code>, <code>log</code> if all 3 are optional but in case they are present I want to match them in separate groups.</li> </ol> </blockquote> <p>Use capture groups that have a <code>?</code> after them so that they will be op...
2
2016-05-25T21:48:12Z
[ "python", "regex" ]
How to load string in unicode using Textract library in Python?
37,448,074
<p>I'm using <a href="https://github.com/deanmalmgren/textract" rel="nofollow">Textract</a> and relatively new to Python and I would like to load a file in unicode string rather than utf-8. Is there a way to do that?</p> <p>I tried </p> <pre><code>text = textract.process(file) </code></pre> <p>But this loads a UTF-8...
1
2016-05-25T21:39:58Z
37,448,438
<p>Textract uses encoding to specify a particular output encoding (input encodings are inferred using <a href="http://chardet.readthedocs.io/en/latest/" rel="nofollow">chardet</a> </p> <p>Here are the Uncidoe options for encoding:</p> <pre><code>unicode_escape, unicode_internal, raw_unicode_escape text = textract.pr...
1
2016-05-25T22:06:19Z
[ "python", "python-2.7", "unicode" ]
I wish to create a translator using Python 3
37,448,106
<p>I am looking to create a translator with Python that converts English into Morse Code. I was able to get it working but would like to improve it.</p> <p>Here is what I have:</p> <pre><code>morse = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '...
-2
2016-05-25T21:42:33Z
37,448,738
<p>You can prompt users for input using the raw_input (python 2) or input (python 3) functions. The input to these functions is the prompt that is displayed, and the function returns what is entered. </p> <pre><code>&gt;stored_input = input('Please enter a line: ') Please enter a line: Some input &gt;print stored_inpu...
0
2016-05-25T22:33:20Z
[ "python", "morse-code" ]
Alternative to Bio.Entrez EFetch for downloading full genome sequences from NCBI
37,448,144
<p>My goal is to download full metazoan genome sequences from NCBI. I have a list of unique ID numbers for the genome sequences I need. I planned to use the Bio.Entrez module EFetch to download the data but learned today via the Nov 2, 2011 release notes (<a href="http://1.usa.gov/1TA5osg" rel="nofollow">http://1.usa.g...
1
2016-05-25T21:44:35Z
37,470,359
<p>Here is a script for you -- though you may need to tinker with it to make it work. Name the script whatever you prefer, but when you call the script do so as follows: python name_of_script[with .py extension] your_email_address. </p> <p>You need to add your email to the end of the call else it will not work. If you...
1
2016-05-26T20:26:33Z
[ "python", "biopython", "ncbi" ]
Minimum length in password for django form
37,448,147
<p>I am making a form in Django and I am using the "form.is_valid" to get all the error. Everything works except the minimum value for the password. I have following code for my form:</p> <pre><code>class RegisterationForm (forms.Form): first_name = forms.CharField(initial ='' ,widget=forms.TextInput(attrs={'class' :...
0
2016-05-25T21:44:44Z
37,448,810
<p>If <code>password</code> or <code>password2</code> is not valid, then they will not be in <code>cleaned_data</code>. You need to change your <code>clean</code> method to handle this. For example:</p> <pre><code>def clean(self): cleaned_data = super(RegisterationForm, self).clean() password = self.cleaned_da...
2
2016-05-25T22:40:39Z
[ "python", "django", "forms" ]
Force LaTeX font to match default matplotlib font
37,448,296
<p>I have seen this issue pop up here and there but have yet to find a suitable answer. </p> <p>When making a plot in matplotlib, the only way to insert symbols and math functions (like fractions, exponents, etc...) is to use TeX formatting. However, by default TeX formatting uses a different font AND italicizes the t...
1
2016-05-25T21:55:47Z
37,448,958
<p>For typesetting units, use the <a href="https://www.ctan.org/pkg/siunitx?lang=en" rel="nofollow"><code>siunitx</code></a> package (with <code>mode=text</code>) rather than math mode.</p> <p><strong>Update</strong>: The above is only valid when you have defined <code>text.usetex : True</code> in your rc settings.</p...
0
2016-05-25T22:57:01Z
[ "python", "matplotlib", "tex" ]
Force LaTeX font to match default matplotlib font
37,448,296
<p>I have seen this issue pop up here and there but have yet to find a suitable answer. </p> <p>When making a plot in matplotlib, the only way to insert symbols and math functions (like fractions, exponents, etc...) is to use TeX formatting. However, by default TeX formatting uses a different font AND italicizes the t...
1
2016-05-25T21:55:47Z
37,555,761
<p>It turns out the solution was rather simple and a colleague of mine had the solution. </p> <p>If I were to use this line of code to create a title:</p> <pre><code>fig.suptitle(r'$H_2$ Emission from GJ832') </code></pre> <p>The result would be "<em>H<sub>2</sub></em> Emission from GJ832" which is an illustration o...
0
2016-05-31T21:15:54Z
[ "python", "matplotlib", "tex" ]
Disable a Tkinter button when variables are at 0
37,448,340
<p>I'm learning python still so the rest of my code may be flawed but my main problem is I cant disable this button when the Wood and Stone variable are at 0. I've tried using a while statement that runs the <i>button.config(state=DISABLED)</i> command when <i>stone > 0 and wood > 0</i> but that didn't seem to work.</p...
1
2016-05-25T21:58:47Z
37,448,374
<p>I think that your problem is that your variable is 0 and not a negative number.</p> <p>So when you check if your variable is less than 0 it won't disable it because your variable is not smaller than 0, it is exactly 0. </p> <p>Try with this better</p> <pre><code>while True: if self.stone &lt; 1 and self.wood ...
0
2016-05-25T22:01:35Z
[ "python", "tkinter" ]
dataframe change size and the convert to panel python
37,448,420
<p>I have a question on how to change dataframe to a panel while changinig the dimensions of the dataframe. Originally I have a data frame with 2000 rows and 784 colmuns:</p> <pre><code>data=pd.DataFrame(np.random.randn(2000,784)) data.shape (2000, 784) </code></pre> <p>I would like to turn each column into a 28*28 d...
0
2016-05-25T22:04:25Z
37,448,504
<p>What seems to be the problem? This works:</p> <pre><code>import pandas as pd import numpy as np data = pd.DataFrame(np.random.randn(2000,784)) panel = pd.Panel(data.values.reshape(2000, 28, 28)) # In [49]: q.panel[42].shape # Out[49]: (28, 28) # In [51]: q.panel # Out[51]: # &lt;class 'pandas.core.panel.Panel'&...
1
2016-05-25T22:11:26Z
[ "python", "pandas", "dataframe", "panel", "reshape" ]
how to close python script without just activating "except" in try/except statement
37,448,535
<p>I have a python script running over some 50,000 items in a database, it takes about 10 seconds per item and I want to stop it.</p> <p>But, if i just press ctrl + C while the code is in the try except part, then my program enter the expect statement and delete that item then continue. The only way to close the progr...
1
2016-05-25T22:13:59Z
37,448,565
<pre><code>import signal import MySQLdb import sys ## Handle process signals: def sig_handler(signal, frame): global connection global cursor cursor.close() connection.close() exit(0) ## Register a signal to the handler: signal.signal(signal.SIGINT, sig_handler) class Database: # Your class...
0
2016-05-25T22:16:41Z
[ "python" ]
how to close python script without just activating "except" in try/except statement
37,448,535
<p>I have a python script running over some 50,000 items in a database, it takes about 10 seconds per item and I want to stop it.</p> <p>But, if i just press ctrl + C while the code is in the try except part, then my program enter the expect statement and delete that item then continue. The only way to close the progr...
1
2016-05-25T22:13:59Z
37,448,932
<p>The issue is because you are using a blanket <em>except</em> which is always a bad idea, if you catch specific exceptions then when you <code>KeyboardInterrupt</code> your script will stop:</p> <pre><code>for item in items: try: if is_item_gone(content) == 1: data = (item['id']) db.updat...
2
2016-05-25T22:53:53Z
[ "python" ]
how to close python script without just activating "except" in try/except statement
37,448,535
<p>I have a python script running over some 50,000 items in a database, it takes about 10 seconds per item and I want to stop it.</p> <p>But, if i just press ctrl + C while the code is in the try except part, then my program enter the expect statement and delete that item then continue. The only way to close the progr...
1
2016-05-25T22:13:59Z
37,448,981
<p>I would rewrite it like this:</p> <pre><code>try: # ... except KeyboardInterrupt: sys.exit(1) except Exception: # I would use a more specific exception here if you can. data = (item['id']) db.delete('...') </code></pre> <p>Or just </p> <pre><code>try: # ... except Exception: # I would use an...
1
2016-05-25T23:00:02Z
[ "python" ]
AWS DynamoDB Python - boto3 Key() methods not recognized (Query)
37,448,536
<p>I am using Lambda (Python) to query my DynamoDB database. I am using the boto3 library, and I was able to make an "equivalent" query:</p> <p>This script works:</p> <pre><code>import boto3 from boto3.dynamodb.conditions import Key, Attr import json def create_list(event, context): resource = boto3.resource('d...
1
2016-05-25T22:14:12Z
37,539,009
<p>From what I think: Your Partition Key is Number_Attribute, and so you cannot do a <code>gt</code> when doing a <code>query</code> (you can do an <code>eq</code> and that is it.)</p> <p>You can do a <code>gt</code> or <code>between</code> for your Sort Key when doing a <code>query</code>. It is also called Range ke...
0
2016-05-31T07:05:59Z
[ "python", "amazon-web-services", "amazon-dynamodb", "aws-lambda", "boto3" ]
Using python to convert bytearray to float
37,448,547
<p>I'm using python 2.7. Just wonder how to convert bytearray to 2 byte float numbers. The bytearray is: </p> <pre><code>In[13]: temp Out[13]: `bytearray(b'\xd8[\xda[\xd8[\xda[\xd1[\xe1[\xeb[\xed[\xe7[\xeb[\xe7[\xea[\xd6[\xd5[\xd8[\xd5[\xd4[\xd3[\xe9[\xe2[\xe3[\xe5[\xe6[\xe8[\xdc[\xe6[\xe4[\xe4[\xe8[\xe2[\xd3[\xdb[\xd...
1
2016-05-25T22:15:34Z
37,448,924
<p>You can use <code>numpy</code> <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.fromstring.html" rel="nofollow"><code>fromstring</code></a>:</p> <pre><code>import numpy as np # little-endian x = np.fromstring(buffer(temp), dtype='&lt;f2') # big-endian x = np.fromstring(buffer(temp), dtype...
1
2016-05-25T22:52:34Z
[ "python", "bit-manipulation", "bytearray" ]
Simple sum program in Python
37,448,551
<p>I just wrote this very simple Python script which finds the sum of two integers. I'm just trying to understand how the <code>return</code> values are assigned to variables:</p> <pre><code>def add(a,b): c = a + b return a return b return c first_number, second_number, result = add(3,4) print 'first...
0
2016-05-25T22:15:47Z
37,448,579
<p>Your problem is that the <code>return a</code> statement stops the routine and returns only one value, but the main program expects three values. Your other return statements are never executed.</p> <p>Instead, use just one <code>return</code> statement:</p> <pre><code>def add(a,b): c = a + b return a, b, ...
7
2016-05-25T22:17:45Z
[ "python", "sum" ]
Converting space-aligned text file into Pandas DataFrame
37,448,773
<p>I am quite new to pandas. I have a log text file. I am trying to grab few data point from the file. Below is the code that kind of gets me the desired data but not in desired format. I wanted Pandas data frame with two columns.</p> <pre><code>import os from collections import Counter import pandas as pd #print(os....
0
2016-05-25T22:36:45Z
37,449,846
<p>You can create a dataframe by creating a list of lists, and then use the dataframe constructor.</p> <p>Loop through each line of the file, like you've started doing, then split each line into the different columns. You can use <a href="https://docs.python.org/3/library/re.html#re.split" rel="nofollow">re.split</a> ...
1
2016-05-26T00:48:55Z
[ "python", "pandas", "dataframe" ]
Determine if specific type of object exists in a tuple
37,448,822
<p>Is there an easy way to check if a specific type of object exists in a <code>tuple</code>?</p> <p>There only way I can think is to iterate over the <code>tuple</code> and check every object, but knowing python I feel like there has to be a better way.</p>
0
2016-05-25T22:41:54Z
37,448,853
<p>I can't think of a better way than list comprehensions.</p> <pre><code>result = [x for x in mylist if type(x) is bool] </code></pre> <p>If anyone got a better solution I'm eager to see it.<br> But I'm betting my right sock on the fact that there's no other way than to involve a loop in any shape or form. In this c...
4
2016-05-25T22:45:23Z
[ "python", "tuples" ]
Determine if specific type of object exists in a tuple
37,448,822
<p>Is there an easy way to check if a specific type of object exists in a <code>tuple</code>?</p> <p>There only way I can think is to iterate over the <code>tuple</code> and check every object, but knowing python I feel like there has to be a better way.</p>
0
2016-05-25T22:41:54Z
37,448,857
<p>At the root of the problem you do have to iterate over the list. However, there are tools to make this easy, such as</p> <pre><code>if any(isinstance(x, &lt;class&gt;) for x in my_list): </code></pre> <p>At least this will short-circuit when you find the first one.</p>
6
2016-05-25T22:45:37Z
[ "python", "tuples" ]
Determine if specific type of object exists in a tuple
37,448,822
<p>Is there an easy way to check if a specific type of object exists in a <code>tuple</code>?</p> <p>There only way I can think is to iterate over the <code>tuple</code> and check every object, but knowing python I feel like there has to be a better way.</p>
0
2016-05-25T22:41:54Z
37,449,097
<p>This should work:</p> <pre><code>if any(map(lambda x: isinstance(x, SomeClass), my_tuple)): # do stuff </code></pre>
0
2016-05-25T23:13:05Z
[ "python", "tuples" ]
Determine if specific type of object exists in a tuple
37,448,822
<p>Is there an easy way to check if a specific type of object exists in a <code>tuple</code>?</p> <p>There only way I can think is to iterate over the <code>tuple</code> and check every object, but knowing python I feel like there has to be a better way.</p>
0
2016-05-25T22:41:54Z
37,449,316
<pre><code>type_you_are_checking_for in map(lambda x: type(x), your_objects_tuple) </code></pre> <p>examples:</p> <pre><code>&gt;&gt;&gt; str in map(lambda x: type(x), (1, "sfds")) True &gt;&gt;&gt; str in map(lambda x: type(x), (1, 2)) False </code></pre>
0
2016-05-25T23:38:33Z
[ "python", "tuples" ]
Group column in csv file by pandas
37,448,922
<p>I have data </p> <pre><code>ID,"day" 00051f002f5a0c179d7ce191ca2c6401,2016-03-01 00051f002f5a0c179d7ce191ca2c6401,2016-03-06 000700651343ff73c10212a095ab4091,2016-03-06 000700651343ff73c10212a095ab4091,2016-03-01 00102b98bd9e71da3cf23fd1f599408d,2016-03-01 </code></pre> <p>I try to print to every data list of uniq...
0
2016-05-25T22:52:25Z
37,449,876
<p>Those are numpy arrays, and the <code>...</code> is just because the list is long and numpy has a feature where it doesn't show you every element if the list is too long. The elements are there.</p> <p>If you want a list you can just use <code>list(elem)</code></p>
0
2016-05-26T00:53:45Z
[ "python", "csv", "pandas" ]
How to translate json data to python object - Flask
37,448,930
<p>I'm trying to do a web application using the OAuthlib to login with google, this is what the google object looks like:</p> <pre><code>google = oauth.remote_app('google', request_token_url=None, access_token_method='POST', request_token_params={'scope': 'email'}, access_token_url='https://accounts.go...
0
2016-05-25T22:53:40Z
37,449,092
<p><code>json.load</code> <a href="https://docs.python.org/2/library/json.html#json.load" rel="nofollow">reads from a file</a>. To decode a JSON <strong>string</strong>, use <code>json.loads</code>.</p> <p>However, according to <a href="https://developers.google.com/identity/protocols/OpenIDConnect#server-flow" rel="n...
3
2016-05-25T23:12:47Z
[ "python", "json", "oauth", "flask", "google-oauth2" ]
How to translate json data to python object - Flask
37,448,930
<p>I'm trying to do a web application using the OAuthlib to login with google, this is what the google object looks like:</p> <pre><code>google = oauth.remote_app('google', request_token_url=None, access_token_method='POST', request_token_params={'scope': 'email'}, access_token_url='https://accounts.go...
0
2016-05-25T22:53:40Z
37,449,496
<p>As @this-vidor said my id_token was a JWT not JSON, and I was finally able to decode it using a library called jwt, I used jwt.decode(resp['id_token'], verify=False) and it worked! Just posting this in case anyone had the same problem and wanted a solution. Thank you very much.</p> <p>For more information on <a hre...
0
2016-05-26T00:02:42Z
[ "python", "json", "oauth", "flask", "google-oauth2" ]
making a dictionary from a file with three columns
37,448,971
<p>If I am reading a file with three columns like so:</p> <pre><code>james 1.0 2.5 Tom 2.0 2.1 Ryan 3.0 2.5 </code></pre> <p>I can't figure out how to make just the first column the key of my dictionary (as strings) and the next 2 columns (as floating-point numbers) my values. I know how to ...
1
2016-05-25T22:59:00Z
37,449,022
<p>Essentially, read in the file, split on spaces, then create the dictionary using dictionary comprehension.</p> <pre><code>f = open("data.txt","r") lines = list(map(lambda x: x.split(" "), f.readlines())) f.close() some_dictionary = { line[0]: (float(line[1]), float(line[2])) for line in lines} </code></pre>
0
2016-05-25T23:04:43Z
[ "python", "dictionary" ]
making a dictionary from a file with three columns
37,448,971
<p>If I am reading a file with three columns like so:</p> <pre><code>james 1.0 2.5 Tom 2.0 2.1 Ryan 3.0 2.5 </code></pre> <p>I can't figure out how to make just the first column the key of my dictionary (as strings) and the next 2 columns (as floating-point numbers) my values. I know how to ...
1
2016-05-25T22:59:00Z
37,449,024
<p>How about:</p> <pre><code>with open(filename) as f: return {k:[v1,v2] for k,v1,v2 in (x.rstrip().split() for line in f)} </code></pre>
1
2016-05-25T23:04:54Z
[ "python", "dictionary" ]
making a dictionary from a file with three columns
37,448,971
<p>If I am reading a file with three columns like so:</p> <pre><code>james 1.0 2.5 Tom 2.0 2.1 Ryan 3.0 2.5 </code></pre> <p>I can't figure out how to make just the first column the key of my dictionary (as strings) and the next 2 columns (as floating-point numbers) my values. I know how to ...
1
2016-05-25T22:59:00Z
37,449,027
<pre><code>dict = {} f = open(file) for line in f: line = line.split() dict[line[0]] = line[1:] f.close() </code></pre>
1
2016-05-25T23:05:26Z
[ "python", "dictionary" ]
making a dictionary from a file with three columns
37,448,971
<p>If I am reading a file with three columns like so:</p> <pre><code>james 1.0 2.5 Tom 2.0 2.1 Ryan 3.0 2.5 </code></pre> <p>I can't figure out how to make just the first column the key of my dictionary (as strings) and the next 2 columns (as floating-point numbers) my values. I know how to ...
1
2016-05-25T22:59:00Z
37,449,030
<p>How about:</p> <pre><code>def makeDict(filename): with open(filename) as f: return {row[0]: [float(x) for x in row[1:]] for row in (line.rstrip().split() for line in f)} </code></pre> <p>To break it down ...here we are reading in the lines and splitting them on whitespace </p> <pre><c...
1
2016-05-25T23:05:47Z
[ "python", "dictionary" ]
Using Try/except with a QTimer
37,449,005
<p>I use a <code>QTimer</code> to start a method, which starts a timer. When I push a <code>QPushButton</code> I need to stop this timer and do another things. So, when I push the button i get this error:</p> <p><code>TypeError: 'instancemethod' object is not connected</code> </p> <p>How can I use a <code>try-except<...
0
2016-05-25T23:02:16Z
37,449,041
<p>as per <a href="https://docs.python.org/2/tutorial/errors.html" rel="nofollow">https://docs.python.org/2/tutorial/errors.html</a>, you should not include the string error message right after "except" but rather the ErrorType and then add the error message you want raised as follows:</p> <pre><code>try: #somethi...
1
2016-05-25T23:07:08Z
[ "python", "pyqt", "qtimer" ]
How to implement "login as" admin function with `stormpath-flask`
37,449,052
<p>I'm implementing a "login as" feature for our admin dashboard.</p> <p>Basically I'd love to allow our admins to see and use the website as if she has logged in as a specific customer. For example, if Trish rang us up and asked a question, our admin should be able to login as Trish and see exactly what Trish is seei...
1
2016-05-25T23:07:56Z
37,465,868
<p>I'm the author of this library, so wanted to hop in here =)</p> <p>The answer is yes: you can indeed transform a normal <code>Account</code> object into a valid Flask-Stormpath <code>User</code> object. Here's how:</p> <pre><code>from flask.ext.stormpath import login_user from flask.ext.stormpath.models import Use...
1
2016-05-26T16:02:05Z
[ "python", "flask", "stormpath" ]
Python: Is there a way to systematically open files in a script until a directory has been exhausted?
37,449,075
<p>I would like to write a script in Python that will systematically open files, but I'm not sure how that might happen. Essentially, I would like something like: </p> <pre><code>with open(file1) as thefile: #do stuff with open(file2) as the file: #do the same thing as before .... #does this until the directo...
0
2016-05-25T23:10:43Z
37,449,122
<p>Yes, there are many ways. One way is to iterate over the result of <code>glob.glob()</code>:</p> <pre><code>#UNTESTED import glob for filename in glob.glob('*'): with open(filename) as the_file: # do the thing </code></pre> <p>If you only wanted to operate on files with a particular naming pattern, you...
1
2016-05-25T23:15:02Z
[ "python", "file", "python-3.x", "with-statement" ]
Python: Is there a way to systematically open files in a script until a directory has been exhausted?
37,449,075
<p>I would like to write a script in Python that will systematically open files, but I'm not sure how that might happen. Essentially, I would like something like: </p> <pre><code>with open(file1) as thefile: #do stuff with open(file2) as the file: #do the same thing as before .... #does this until the directo...
0
2016-05-25T23:10:43Z
37,449,124
<p>The Python <strong>os</strong> package has a lot of great tools for working with the operating system, especially file and process management.</p> <pre><code>import os for f in os.listdir("."): with open(f) as the_file: </code></pre>
0
2016-05-25T23:15:16Z
[ "python", "file", "python-3.x", "with-statement" ]