title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Python: Adding another value to an existing key dictionary | 37,456,821 | <p>I am trying to take in all the files at a given path, and order them based on my data title names.
So my data title names are:</p>
<pre><code>data_titles = ['CPU','Physical_Disk','Memory','Network']
</code></pre>
<p>The files at this given path are named like <code>'CPU_data.txt'</code> and <code>'Memory_data.txt'... | 0 | 2016-05-26T09:30:06Z | 37,457,041 | <p>The problem is that your values are sometimes strings (e.g. for <code>Network</code>) and sometimes lists (e.g. for <code>Physical_Disk</code>). If you make sure that they are always lists you can easily append to them:</p>
<pre><code>data_titles = ['CPU','Physical_Disk','Memory','Network']
table_csv_files={}
listd... | 2 | 2016-05-26T09:40:26Z | [
"python",
"dictionary"
] |
Python: Adding another value to an existing key dictionary | 37,456,821 | <p>I am trying to take in all the files at a given path, and order them based on my data title names.
So my data title names are:</p>
<pre><code>data_titles = ['CPU','Physical_Disk','Memory','Network']
</code></pre>
<p>The files at this given path are named like <code>'CPU_data.txt'</code> and <code>'Memory_data.txt'... | 0 | 2016-05-26T09:30:06Z | 37,457,123 | <p><strong>According to Python <a href="https://docs.python.org/3.5/library/collections.html#collections.defaultdict]" rel="nofollow">documentation</a> it's better to use defaultdict(), see the answer by <em>Moses Koledoye</em></strong></p>
<p>You cannot append to a dictionary. You can append to a value corresponding ... | 0 | 2016-05-26T09:43:45Z | [
"python",
"dictionary"
] |
Python: Adding another value to an existing key dictionary | 37,456,821 | <p>I am trying to take in all the files at a given path, and order them based on my data title names.
So my data title names are:</p>
<pre><code>data_titles = ['CPU','Physical_Disk','Memory','Network']
</code></pre>
<p>The files at this given path are named like <code>'CPU_data.txt'</code> and <code>'Memory_data.txt'... | 0 | 2016-05-26T09:30:06Z | 37,457,167 | <h1>Dictionary[key] = new value</h1>
<p>here is a simple example of how you can add/update another value to an existing key in dictionary.</p>
<pre><code>my_dict = {'name': 'Rajiv Sharma', 'city': 'Delhi'}
print my_dict
my_dict['city'] = 'Kuala Lumpur'
print my_dict
</code></pre>
<p>output:</p>
<pre><code>{'city': ... | 0 | 2016-05-26T09:45:31Z | [
"python",
"dictionary"
] |
Python: Adding another value to an existing key dictionary | 37,456,821 | <p>I am trying to take in all the files at a given path, and order them based on my data title names.
So my data title names are:</p>
<pre><code>data_titles = ['CPU','Physical_Disk','Memory','Network']
</code></pre>
<p>The files at this given path are named like <code>'CPU_data.txt'</code> and <code>'Memory_data.txt'... | 0 | 2016-05-26T09:30:06Z | 37,457,482 | <p>Use a <code>defaultdict</code> whose default value is an empty <code>list</code>, then you can <code>append</code> to the dictionary values without worrying about which keys already exist in your dictionary.</p>
<pre><code>from collections import defaultdict
table_csv_files = defaultdict(list)
for file_names in o... | 2 | 2016-05-26T09:58:28Z | [
"python",
"dictionary"
] |
Substitute pixels of an image with other images yet retaining the image | 37,456,865 | <p>I have seen an image of a girl which is made up of multiple images of her.So I want to achieve the same thing using a python script.(I am completely new to image processing)</p>
<p>I am using pil library for this script.</p>
<pre><code>import sys,os
from PIL import Image
img = Image.open("DSC_0149.jpg")
pixels = i... | 1 | 2016-05-26T09:31:58Z | 37,457,125 | <p>So first you need to edit each pixel with this to change the color:</p>
<p>If it is rgb:</p>
<p>img.putpixel((10,15),(r,g,b))</p>
<p>or</p>
<p>faster: pixels[1, 1] = (r, g, b)</p>
<p>otherwise:</p>
<p><a href="http://stackoverflow.com/questions/3596433/is-it-possible-to-change-the-color-of-one-individual-pixel... | 0 | 2016-05-26T09:43:47Z | [
"python",
"image",
"python-imaging-library"
] |
Substitute pixels of an image with other images yet retaining the image | 37,456,865 | <p>I have seen an image of a girl which is made up of multiple images of her.So I want to achieve the same thing using a python script.(I am completely new to image processing)</p>
<p>I am using pil library for this script.</p>
<pre><code>import sys,os
from PIL import Image
img = Image.open("DSC_0149.jpg")
pixels = i... | 1 | 2016-05-26T09:31:58Z | 37,478,291 | <p>The best way to understand the whole process is to take time to read this code in the same language, it's around 200 lines:</p>
<p><a href="https://github.com/codebox/mosaic" rel="nofollow">https://github.com/codebox/mosaic</a></p>
<p>Hope it solve your problems</p>
| 0 | 2016-05-27T08:15:10Z | [
"python",
"image",
"python-imaging-library"
] |
create binary columns in a dataframe from condition on its value | 37,456,971 | <p>I have a dataframe that looks like this one: </p>
<pre><code>df = pd.DataFrame(np.nan, index=[0,1,2,3], columns=['A','B','C'])
df.iloc[0,0] = 'a'
df.iloc[1,0] = 'b'
df.iloc[1,1] = 'c'
df.iloc[2,0] = 'b'
df.iloc[3,0] = 'c'
df.iloc[3,1] = 'b'
df.iloc[3,2] = 'd'
df
out : A B C
0 a NaN NaN
1 b c ... | 0 | 2016-05-26T09:37:18Z | 37,457,490 | <p>You're looking for <code>get_dummies</code>. Here I choose to use the <code>.str</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get_dummies.html" rel="nofollow">version</a>:</p>
<pre><code>df.fillna('', inplace=True)
(df.A + '|' + df.B + '|' + df.C).str.get_dummies()
</code... | 4 | 2016-05-26T09:58:59Z | [
"python",
"pandas",
"dataframe"
] |
Easiest way to slice border particles in a 3D numpy array with variable border size | 37,457,067 | <p>Ok, so I am dealing with large 3D numpy arrays, I want to find the easiest way to set all the border values in the array (of size b) to zero...</p>
<p>So for example I have a filled 3D numpy array called labelled, at the moment I have something like this...</p>
<pre><code>labelled[[0,1,2,..b,-1,-2,-3,..-b],:,:] = ... | 0 | 2016-05-26T09:41:26Z | 37,457,386 | <p>This seems to work:</p>
<pre><code>x[ :b, :, :] = 0
x[-b:, :, :] = 0
x[:, :b, :] = 0
x[:, -b:, :] = 0
x[:, :, :b] = 0
x[:, :, -b:] = 0
</code></pre>
| 2 | 2016-05-26T09:54:11Z | [
"python",
"numpy",
"multidimensional-array",
"slice"
] |
Easiest way to slice border particles in a 3D numpy array with variable border size | 37,457,067 | <p>Ok, so I am dealing with large 3D numpy arrays, I want to find the easiest way to set all the border values in the array (of size b) to zero...</p>
<p>So for example I have a filled 3D numpy array called labelled, at the moment I have something like this...</p>
<pre><code>labelled[[0,1,2,..b,-1,-2,-3,..-b],:,:] = ... | 0 | 2016-05-26T09:41:26Z | 37,458,550 | <p>A bit more generic approach to create such indices that are to be set as zeros could be like so -</p>
<pre><code>zero_idx = np.hstack((np.arange(b+1),-np.arange(1,b+1)))
labelled[zero_idx,:,:] = 0
labelled[:,zero_idx,:] = 0
labelled[:,:,zero_idx] = 0
</code></pre>
<p>Sample run -</p>
<pre><code>In [153]: # Create... | 1 | 2016-05-26T10:44:12Z | [
"python",
"numpy",
"multidimensional-array",
"slice"
] |
String format python | 37,457,180 | <p>I'm trying to clean up a bad solution. I have a utils file, which contains some generic methods and a commands file, where I store a list of commands to use within the program. However, when trying to clean up files by using string format, I'm starting to run into problems.</p>
<pre><code># utils.py
import os
bin ... | 1 | 2016-05-26T09:46:01Z | 37,457,568 | <p>If you want to use braces in formatted string, you have to escape them, e.g. in your example use</p>
<pre class="lang-py prettyprint-override"><code>SOME_CMD = '{0} -p %s | tail -n +4 | awk \'{{print \$4}}\''.format(SOMETOOL)
</code></pre>
<p>-- note the double braces around <code>print \$4</code>.</p>
<p>On a re... | 1 | 2016-05-26T10:02:01Z | [
"python",
"linux",
"bash",
"coding-style"
] |
String format python | 37,457,180 | <p>I'm trying to clean up a bad solution. I have a utils file, which contains some generic methods and a commands file, where I store a list of commands to use within the program. However, when trying to clean up files by using string format, I'm starting to run into problems.</p>
<pre><code># utils.py
import os
bin ... | 1 | 2016-05-26T09:46:01Z | 37,457,812 | <p>If you have a complicated line with multiple replacements, you can do something like this:</p>
<pre><code># replacements
reps = {
'foo': 'aaa',
'bar': 'bbb',
'baz': 'ccc'
}
# string to format
s = '...{foo}...{bar}...{baz}...'
# format it
s2 = s.format(**reps)
# gives: '...aaa...bbb...ccc...'
</code><... | 1 | 2016-05-26T10:11:01Z | [
"python",
"linux",
"bash",
"coding-style"
] |
python TypeError: __new__() missing 1 required positional argument: 'namespace' | 37,457,207 | <p>I try to initialize class using</p>
<p><code>tsf = TimeSeriesFeature(cut_avg, interval)</code></p>
<p>but I got TypeError: __new__() missing 1 required positional argument: 'namespace'. </p>
<p>The init code of TimeSeriesFeature is below:</p>
<pre><code>class TimeSeriesFeature(BasicFeature):
def __init__(sel... | 1 | 2016-05-26T09:47:02Z | 37,458,411 | <p>The error you're getting is from the fact that instantiation of metaclass does not use it's <code>__init__</code> method, but rather it's <code>__new__</code> method which (excluding self) expects 3 arguments, last being said <em>namespace</em>.</p>
<p>As it stands now your class inherits from <code>ABCMeta</code> ... | 1 | 2016-05-26T10:38:21Z | [
"python",
"python-3.x"
] |
JSON dumped and reloaded fails to match the original structure | 37,457,224 | <p>MCVE (with py.test) </p>
<pre><code>import json
def test_minimum():
internal={}
internal[0]=""
external={}
with open("source.json", 'w') as outfile:
json.dump(internal, outfile)
with open('source.json', 'r') as f:
e... | 0 | 2016-05-26T09:47:36Z | 37,457,416 | <p>Integer and float keys are implicitly converted to strings when serializing to json. This minimal example clarifies it:</p>
<pre class="lang-py prettyprint-override"><code>>>> json.dumps({1: 2})
'{"1": 2}'
>>> json.dumps({'1': 2})
'{"1": 2}'
</code></pre>
<p>Obviously, two different Python objec... | 2 | 2016-05-26T09:55:17Z | [
"python",
"json"
] |
Dumping json data into elasticsearch through python | 37,457,267 | <p>I'm trying to dump some json data that I parsed from a csv file into elasticsearch. I've checked the data and its the right format. But for some reason I'm getting the error below. </p>
<pre><code>{
"error" : {
"root_cause" : [ {
"type" : "parse_exception",
"reason" : "Failed to derive xcontent"
... | 0 | 2016-05-26T09:49:23Z | 37,457,745 | <p>try to replace the _bulk with _update</p>
<pre><code>curl -XPUT 'http://192.168.99.100:9200/_update?pretty' --data-binary "@data.json"
</code></pre>
<p>Reference: <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html" rel="nofollow">https://www.elastic.co/guide/en/elasticsearch/... | 0 | 2016-05-26T10:08:18Z | [
"python",
"json",
"elasticsearch"
] |
Dumping json data into elasticsearch through python | 37,457,267 | <p>I'm trying to dump some json data that I parsed from a csv file into elasticsearch. I've checked the data and its the right format. But for some reason I'm getting the error below. </p>
<pre><code>{
"error" : {
"root_cause" : [ {
"type" : "parse_exception",
"reason" : "Failed to derive xcontent"
... | 0 | 2016-05-26T09:49:23Z | 37,473,739 | <p>The error you're getting is the same as in another question in which the problem was that the full path to the data file was not provided: <a href="http://stackoverflow.com/a/34672449/4973698">link to the answer to that question</a>.</p>
<p>In that case changing from:</p>
<pre><code>curl -XPUT 'http://192.168.99.1... | 0 | 2016-05-27T02:13:12Z | [
"python",
"json",
"elasticsearch"
] |
remove non ascii characters from csv file using Python | 37,457,277 | <p>I am trying to remove non-ascii characters from a file. I am actually trying to convert a text file which contains these characters (eg. hello§âÃ¥Â½Â¢Ã¦Ë Ã¤Âºâ 对æ¯âãâ¬â 花å) into a csv file.</p>
<p>However, I am unable to iterate through these characters and hence I want to remove them (i.e c... | 0 | 2016-05-26T09:50:01Z | 37,457,395 | <p>Variable assignment is not magically transferred to the original source; you have to build up a new list of your changed rows:</p>
<pre><code>import csv
txt_file = r"xxx.txt"
csv_file = r"xxx.csv"
in_txt = csv.reader(open(txt_file, "rb"), delimiter = '\t')
out_csv = csv.writer(open(csv_file, 'wb'))
out_txt = []
f... | 2 | 2016-05-26T09:54:33Z | [
"python",
"csv",
"unicode",
"ascii"
] |
End plot at last data point in pyplot time series | 37,457,333 | <p>I have a pyplot chart that looks a bit like this:</p>
<p><a href="http://i.stack.imgur.com/Takm8.png" rel="nofollow"><img src="http://i.stack.imgur.com/Takm8.png" alt="The chart in question"></a></p>
<p>How do I get the red and blue lines to stop at their last data point (May 13th and May 19th, respectively) inste... | 0 | 2016-05-26T09:52:19Z | 37,457,631 | <p>Hard to know what exactly is going on without having your data, but in general what you're trying to do should work if you are plotting <code>Series</code> which have <code>datetime</code> objects as index.</p>
<p>Consider:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
a = pd.Series(np.random... | 1 | 2016-05-26T10:04:14Z | [
"python",
"matplotlib"
] |
End plot at last data point in pyplot time series | 37,457,333 | <p>I have a pyplot chart that looks a bit like this:</p>
<p><a href="http://i.stack.imgur.com/Takm8.png" rel="nofollow"><img src="http://i.stack.imgur.com/Takm8.png" alt="The chart in question"></a></p>
<p>How do I get the red and blue lines to stop at their last data point (May 13th and May 19th, respectively) inste... | 0 | 2016-05-26T09:52:19Z | 37,462,332 | <p>Suppose <code>y</code> were</p>
<pre><code>In [27]: y = np.concatenate([[0,1,4,4,2,3], [4]*3]); y
Out[27]: array([0, 1, 4, 4, 2, 3, 4, 4, 4])
</code></pre>
<p>We'd like to remove the repeated 4's at the tail end of <code>y</code> so that it becomes</p>
<pre><code>array([0, 1, 4, 4, 2, 3, 4])
</code></pre>
<p>To ... | 1 | 2016-05-26T13:30:38Z | [
"python",
"matplotlib"
] |
pandas: reduce data frame to only specific chain of occurences | 37,457,505 | <p>Assume I have this data:</p>
<pre><code>>>> data = {'event': [0,1,1,2,1,0],
... 'val1': [1, 2, 3, 4, 5, 6]
... }
>>> df1 = pd.DataFrame(data, index = ['hash1', 'hash1', 'hash2',
'hash3', 'hash3', 'hash3'])
>>> df1
event val1
ha... | 1 | 2016-05-26T09:59:30Z | 37,457,613 | <p>You can filter the df prior to <code>groupby</code> on the index and then get the number of unique events using <code>nunique</code> and filter the orig df on the hashes that have more than a single unique entry:</p>
<pre><code>In [62]:
gp = df1[df1['event'] !=0].groupby(level=0)['event'].nunique()
df1.loc[gp[gp>... | 1 | 2016-05-26T10:03:27Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
How disable vertical camera rotation for 3d plot in Matplotlib? | 37,457,680 | <p>I have 3d plot surface. And I want disable vertical camera rotation for this plot.</p>
| 0 | 2016-05-26T10:06:09Z | 37,458,755 | <p>By default you may only disable mouse for your plot:</p>
<pre><code>from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.1)
# disable mouse
ax.disable_mouse_rotation()
ax.plot_wirefr... | 1 | 2016-05-26T10:52:09Z | [
"python",
"matplotlib",
"3d",
"mouseevent"
] |
How disable vertical camera rotation for 3d plot in Matplotlib? | 37,457,680 | <p>I have 3d plot surface. And I want disable vertical camera rotation for this plot.</p>
| 0 | 2016-05-26T10:06:09Z | 37,518,524 | <p>My solution:</p>
<pre><code>def disable_vert_rotation(event):
azim = ax.azim
ax.view_init(elev=0, azim=azim)
fig.canvas.mpl_connect('motion_notify_event', disable_vert_rotation)
</code></pre>
| 1 | 2016-05-30T05:58:10Z | [
"python",
"matplotlib",
"3d",
"mouseevent"
] |
Python: Why does my "variable += 1" not work as expected? | 37,457,817 | <pre><code>username = "neelkamath@gmail.com"
usernamelist = []
next = 0
while len(username) > 0:
for part in accumulate(username):
usernamelist.append(part)
next += 1
username = username[next:]
print(usernamelist)
</code></pre>
<p>I'm trying to output every part of the username (like "n", "ne", ... | 0 | 2016-05-26T10:11:13Z | 37,457,931 | <p>You don't need to increment <code>next</code> if you want to remove one character for each iteration of the while loop:</p>
<pre><code>username = "neelkamath@gmail.com"
usernamelist = []
while len(username) > 0:
for part in accumulate(username):
usernamelist.append(part)
username = username[1:]
p... | 3 | 2016-05-26T10:17:16Z | [
"python",
"loops",
"python-3.x",
"operators"
] |
Python: Why does my "variable += 1" not work as expected? | 37,457,817 | <pre><code>username = "neelkamath@gmail.com"
usernamelist = []
next = 0
while len(username) > 0:
for part in accumulate(username):
usernamelist.append(part)
next += 1
username = username[next:]
print(usernamelist)
</code></pre>
<p>I'm trying to output every part of the username (like "n", "ne", ... | 0 | 2016-05-26T10:11:13Z | 37,458,150 | <p>You would like to use a for-loop instead:</p>
<pre><code>username = "neelkamath@gmail.com"
usernamelist = []
for start in range(len(username)):
usernamelist.extend(accumulate(username[start:]))
print(usernamelist)
</code></pre>
<p>But <code>accumulate</code> is not very efficient. For large strings, use slicin... | 2 | 2016-05-26T10:26:39Z | [
"python",
"loops",
"python-3.x",
"operators"
] |
Python: Why does my "variable += 1" not work as expected? | 37,457,817 | <pre><code>username = "neelkamath@gmail.com"
usernamelist = []
next = 0
while len(username) > 0:
for part in accumulate(username):
usernamelist.append(part)
next += 1
username = username[next:]
print(usernamelist)
</code></pre>
<p>I'm trying to output every part of the username (like "n", "ne", ... | 0 | 2016-05-26T10:11:13Z | 37,458,938 | <p><code>a = "neelkamath@gmail.com"
for i in range(0, len(a) + 1):
print a[:i]
</code></p>
<p>Output</p>
<p><code>n
ne
nee
neel
neelk
neelka
neelkam
neelkama
neelkamat
neelkamath
neelkamath@
neelkamath@g
neelkamath@gm
neelkamath@gma
neelkamath@gmai
neelkamath@gmail
neelkamath@gmail.
neelkamath@gmail.c
neelkam... | 0 | 2016-05-26T10:59:46Z | [
"python",
"loops",
"python-3.x",
"operators"
] |
Python: Why does my "variable += 1" not work as expected? | 37,457,817 | <pre><code>username = "neelkamath@gmail.com"
usernamelist = []
next = 0
while len(username) > 0:
for part in accumulate(username):
usernamelist.append(part)
next += 1
username = username[next:]
print(usernamelist)
</code></pre>
<p>I'm trying to output every part of the username (like "n", "ne", ... | 0 | 2016-05-26T10:11:13Z | 37,458,994 | <p>The problem is that you are modifying «username» <em>from an already modified value</em>.</p>
<p>To better understand this, think that the line:</p>
<pre><code>username = username[next:]
</code></pre>
<p>is not picking a part of the original value (<em>neelkamath@gmail.com</em>), but from the already trimmed (i... | 2 | 2016-05-26T11:02:18Z | [
"python",
"loops",
"python-3.x",
"operators"
] |
Filtering DataFrame by finding exact word (not combined) in a column of strings | 37,457,827 | <p>My DataFrame has two columns:</p>
<pre><code>Name Status
a I am Good
b Goodness!!!
c Good is what i feel
d Not Good-at-all
</code></pre>
<p>I want to filter rows in which Status has a string 'Good' as its exact word, not combined with any other words or characters. So output will be:</p>
<pre><co... | 1 | 2016-05-26T10:11:46Z | 37,457,930 | <p>If you're defining "exact" to mean no other characters (including punctuation which defines a word boundary <code>\b</code>), you could instead check for a leading and trailing space and/or beginning/end anchors:</p>
<pre><code>>>> df[df['Status'].str.contains(r'(?:\s|^)Good(?:\s|$)')]
Name ... | 3 | 2016-05-26T10:17:14Z | [
"python",
"regex",
"pandas"
] |
Use sed command in python | 37,457,855 | <p>How to use subprocess.call() in python for long linux command. Like if I want to edit a file call records.txt by replacing all the comma with whitespace in linux shell, I can:</p>
<pre><code>tr ',' ' ' < records.txt
</code></pre>
<p>How to use that with python in subprocess.call().
Thanks</p>
| -2 | 2016-05-26T10:13:06Z | 37,458,476 | <p>records.txt:</p>
<pre><code>jflaskdzhuskajkdkhdsa,dakssdsd,s,a,sa,sas,s,,sas,wwq,wq,wq,w,q,wq,wq,,wq,wq,e,d,rdsa,s,aa,ews,,WQD,AS,SA,WRFDSS,
</code></pre>
<p>python file:</p>
<pre><code>import subprocess
subprocess.call("tr \',\' \' \' < records.txt", shell=True)
</code></pre>
<p>output:</p>
<pre><code>jflas... | -1 | 2016-05-26T10:40:46Z | [
"python",
"linux"
] |
NoReverseMatch in test | 37,457,905 | <p>I get this error in one of my tests:</p>
<pre><code>NoReverseMatch: Reverse for 'plan' with arguments '()' and
keyword arguments '{u'month': u'201604'}' not found.
1 pattern(s) tried: ['plan(/(?P<month>[0-9]+))?$']
</code></pre>
<p>The call was </p>
<pre><code>response = self.client.get(reverse('plan', kw... | 0 | 2016-05-26T10:15:23Z | 37,458,803 | <p>You need to make the outer argument non-capturing:</p>
<pre><code>url(r'^plan(?:/(?P<month>[0-9]+))?$', text, name='plan'),
</code></pre>
<p>Personally, I always find this confusing, so I prefer to have two url patterns. I would include a trailing slash in the urls as well:</p>
<pre><code>url(r'^plan/$', sp... | 2 | 2016-05-26T10:54:20Z | [
"python",
"django"
] |
How to stop django to store images path in sqlite3 database | 37,457,957 | <p>Following code work fine to store thumbnails images in /media/ directory. i want to store all images in following directory but django also save images path in database. Please let me know, how i can stop django to save their path and address in database ?</p>
<p><strong>model.py : Code</strong></p>
<pre><code>fr... | 0 | 2016-05-26T10:18:17Z | 37,458,258 | <p>I'm not clear about what you are trying to achieve but the solution is barely simple. Just get the file object and save...</p>
<p>oh.. one more thing just remove all the thumbnail in models.py and other files...</p>
<pre><code>def handle_uploaded_file(f):
destination = open('your_media_path/media/file.png', 'w... | 0 | 2016-05-26T10:31:43Z | [
"python",
"django",
"sqlite3"
] |
How to stop django to store images path in sqlite3 database | 37,457,957 | <p>Following code work fine to store thumbnails images in /media/ directory. i want to store all images in following directory but django also save images path in database. Please let me know, how i can stop django to save their path and address in database ?</p>
<p><strong>model.py : Code</strong></p>
<pre><code>fr... | 0 | 2016-05-26T10:18:17Z | 37,459,175 | <p>you have to override your form method , before save your validform , or you can handle with your code , you don't need to have model or form you can handle with </p>
<pre><code>image = request.FILES['myfile']
</code></pre>
<p>now you have your image you can save it directly without model </p>
<p>example reproduce... | 1 | 2016-05-26T11:10:35Z | [
"python",
"django",
"sqlite3"
] |
golang: read file generator | 37,458,080 | <p>I'm learning <em>go</em> language and try to rewrite some of my Python code using golang.
I wrote a generator function that reads a text file line by line and send (using <em>yield</em> keyword) only "valid" lines (blank lines are ignored, uncompleted lines are recomposed).</p>
<p>Sample file (myfile.txt):</p>
<pr... | 2 | 2016-05-26T10:23:36Z | 37,458,465 | <p>This is the <code>for</code> loop of your main which is the problem. With this syntax, here is what it does:</p>
<ol>
<li>Initialize <code>line</code> and <code>ok</code> with a first call to <code>vline()</code></li>
<li>If <code>ok</code> is true, run the loop once</li>
<li>Update something at the end of the bloc... | 0 | 2016-05-26T10:40:19Z | [
"python",
"go",
"generator"
] |
golang: read file generator | 37,458,080 | <p>I'm learning <em>go</em> language and try to rewrite some of my Python code using golang.
I wrote a generator function that reads a text file line by line and send (using <em>yield</em> keyword) only "valid" lines (blank lines are ignored, uncompleted lines are recomposed).</p>
<p>Sample file (myfile.txt):</p>
<pr... | 2 | 2016-05-26T10:23:36Z | 37,458,670 | <p>small change:</p>
<pre><code>func main() {
vline := validLines("myfile.txt")
line, ok := vline()
for ok {
fmt.Println(line)
line, ok = vline()
}
}
</code></pre>
| 0 | 2016-05-26T10:49:15Z | [
"python",
"go",
"generator"
] |
golang: read file generator | 37,458,080 | <p>I'm learning <em>go</em> language and try to rewrite some of my Python code using golang.
I wrote a generator function that reads a text file line by line and send (using <em>yield</em> keyword) only "valid" lines (blank lines are ignored, uncompleted lines are recomposed).</p>
<p>Sample file (myfile.txt):</p>
<pr... | 2 | 2016-05-26T10:23:36Z | 37,458,864 | <p>In Go you can use channels instead of yield, it's very convenient.</p>
<p>package main</p>
<pre><code>import (
"bufio"
"fmt"
"os"
"strings"
)
func ValidLines(filename string) (c chan string) {
c = make(chan string)
buff := ""
go func() {
file, err := os.Open(filename)
i... | 3 | 2016-05-26T10:57:04Z | [
"python",
"go",
"generator"
] |
Django Token Issue and Scopes | 37,458,387 | <p>I am developing an API which will be used by various level of users. This API is authenticated using Django OAuth2. Now what i want is to restrict the use of views based on scope. So if there is a view that performs some search then required scope should be 'search'. </p>
<p>For this purpose Django does provide cla... | 0 | 2016-05-26T10:37:29Z | 37,458,866 | <p>when you use OAuth2 you have token for check user authentication you can set your token in browser with cookie and save with session id
example : </p>
<pre><code>if 'x-auth-token' in request.session:
return HttpResponse("sorry you have account")
</code></pre>
<p>with this below example you can set your cookie... | 1 | 2016-05-26T10:57:07Z | [
"python",
"django",
"scope",
"oauth2"
] |
GPIO Momentary button controls relay | 37,458,569 | <p>I'm wondering if it's possible to have my momentary button control a relay in Python whilst I'm holding the button down?</p>
<p>In essence, when the button is pushed, the relay is on, and when the button is released, the relay is off.</p>
<p>Currently, I'm able to control the relay with a small python script, swit... | 0 | 2016-05-26T10:45:32Z | 37,459,633 | <p>Sure, this should do the trick. I didn't test it so it might need some minor edits.</p>
<pre><code>import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# Added a software pull-up here for increased stability
GPIO.setup(25, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(4, GPIO.OUT)
# The relay seems to be active low. Def... | 1 | 2016-05-26T11:31:11Z | [
"python",
"raspberry-pi",
"gpio"
] |
Excess inner html of all elements with a class using python selenium | 37,458,636 | <p>I am trying to fetch a html field from all the elements returned by <code>find_elements_by_class_name</code> method. I fetched all the elements with a given class-name from a webpage using the above method and stored the list in a variable, like:</p>
<pre><code>rows = self.driver.find_elements_by_css_selector('.ord... | 0 | 2016-05-26T10:47:59Z | 37,460,515 | <p>Your XPath is asking to find the strong element in the entire DOM, and the method will always return the first one it comes across, thus the repeated 1. Try using an XPath that is relative to the row element:</p>
<pre><code>'.//td[3]/a/strong'
</code></pre>
| 1 | 2016-05-26T12:12:12Z | [
"python",
"selenium"
] |
How can I extract the value of a given key? | 37,458,812 | <p>How can i extract abandonment from this string <code>('type=weaksubj len=1 word1=abandonment pos1=noun stemmed1=n priorpolarity=negative')</code>? </p>
<p>One possible way can be - </p>
<p>(This is a python Code) </p>
<pre><code>regexp = re.findall("word1=[a-zA-Z0-9]*",string)
</code></pre>
<p>But in the result ... | 1 | 2016-05-26T10:54:49Z | 37,460,247 | <p>You need to wrap the Group you want to return in brackets and then look up the group (0 in this case).</p>
<pre><code>res= re.search("word1=([a-zA-Z0-9]+?)",mystring)
whatyourelookingfor = res.group[0]
</code></pre>
| 1 | 2016-05-26T11:59:05Z | [
"python",
"regex"
] |
How can I extract the value of a given key? | 37,458,812 | <p>How can i extract abandonment from this string <code>('type=weaksubj len=1 word1=abandonment pos1=noun stemmed1=n priorpolarity=negative')</code>? </p>
<p>One possible way can be - </p>
<p>(This is a python Code) </p>
<pre><code>regexp = re.findall("word1=[a-zA-Z0-9]*",string)
</code></pre>
<p>But in the result ... | 1 | 2016-05-26T10:54:49Z | 37,460,511 | <p>If the key-value pairs are unique, and always have this same format, you can obtain the result you need with no regex by splitting and creating a dictionary:</p>
<pre><code>s = 'type=weaksubj len=1 word1=abandonment pos1=noun stemmed1=n priorpolarity=negative'
dct = dict([x.split("=") for x in s.split()])
print(dc... | 0 | 2016-05-26T12:12:00Z | [
"python",
"regex"
] |
Limit access api view decorator Django through post method | 37,458,823 | <p>I have a user group created which name is "Experts" and I have the Django's rest_framework installed too. I can access through api to my items and the comments of all items. Well, I should limit the post action through api to comments. This action just will be available to Experts' users. I have the following code a... | 0 | 2016-05-26T10:55:12Z | 37,459,374 | <pre><code>class MyViewset(ModelViewSet):
queryset = MyThing.objects.all()
serializer_class = MyThingSerializer
def update(self, request, pk=None, **kwargs):
self.permission_classes = [CustomPermission,]
return super(MyViewset, self).update(request, pk, **kwargs)
</code></pre>
| 0 | 2016-05-26T11:19:41Z | [
"python",
"django",
"django-rest-framework",
"restful-authentication"
] |
editingFinished of QlineEdit is emited a second time when a dialog is executed in the editingFinshed event | 37,458,898 | <p>When I connect the signal <code>editingFinished</code> of a <code>QLineEdit</code> to a function which inclued the execution of a <code>QDialog</code>, the signal <code>editingFinished</code> of the <code>QLineEdit</code> is emited a second time. That introduction doens't look very clear... The next example should h... | 0 | 2016-05-26T10:58:13Z | 37,469,498 | <p>the <code>editingFinished</code> signal is emitted, when the return or enter key is pressed or the line edit loses the focus <a href="http://doc.qt.io/qt-5/qlineedit.html#editingFinished" rel="nofollow">see documentation</a>. by <code>editingFinishedEvent</code> the focus changes from the line edit to the dialog and... | 1 | 2016-05-26T19:29:44Z | [
"python",
"pyqt"
] |
Error compiling OpenCV 3.0.0 into raspberry pi | 37,458,973 | <pre><code>CMakeFiles/opencv_imgproc.dir/src/floodfill.cpp.o: file not recognized: File truncated
collect2: error: ld returned 1 exit status
modules/imgproc/CMakeFiles/opencv_imgproc.dir/build.make:1353: recipe for target 'lib/libopencv_imgproc.so.3.0.0' failed
make[2]: *** [lib/libopencv_imgproc.so.3.0.0] Error 1
CMak... | 0 | 2016-05-26T11:01:27Z | 37,527,737 | <p>I don't know how to solve the error, but I have a compiled file for Python 3.4, <a href="https://www.dropbox.com/s/9p9eaqtvuzkdo5l/cv2.so?dl=0" rel="nofollow">download it</a> and put it in the directory /use/local/lib/python3.4/dist-packages, import it in terminal, it should work.</p>
| -2 | 2016-05-30T14:08:33Z | [
"python",
"opencv",
"recipe"
] |
Error compiling OpenCV 3.0.0 into raspberry pi | 37,458,973 | <pre><code>CMakeFiles/opencv_imgproc.dir/src/floodfill.cpp.o: file not recognized: File truncated
collect2: error: ld returned 1 exit status
modules/imgproc/CMakeFiles/opencv_imgproc.dir/build.make:1353: recipe for target 'lib/libopencv_imgproc.so.3.0.0' failed
make[2]: *** [lib/libopencv_imgproc.so.3.0.0] Error 1
CMak... | 0 | 2016-05-26T11:01:27Z | 37,544,723 | <p>Or you can carefully reinstall Raspbian and follow this <a href="http://www.pyimagesearch.com/2015/10/26/how-to-install-opencv-3-on-raspbian-jessie/" rel="nofollow">guide</a>, it has a really big chance to make an mistake.</p>
| 0 | 2016-05-31T11:39:10Z | [
"python",
"opencv",
"recipe"
] |
How to render characters in a textfield correctly in a JSON template | 37,459,023 | <p>I have created a Django application with a model with a <code>TextField</code>. When I use the admin interface, I can populate the <code>TextField</code> as such below:</p>
<p><a href="http://i.stack.imgur.com/ZWtjD.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZWtjD.png" alt="Admin interface with TextFiel... | 0 | 2016-05-26T11:03:23Z | 37,483,998 | <p>I managed to do it... So after further reading, I decided that using a template wasn't the best approach for rendering JSON data. I found I could use <code>JsonResponse</code> to handle the displaying of the JSON data correctly.</p>
<p>So here I have deleted my template and re-wrote my function in views.py to look ... | 0 | 2016-05-27T12:48:23Z | [
"python",
"django-models",
"django-templates",
"django-views",
"django-jsonfield"
] |
How to convert a list containing duplicate values to a dictionary with a list as the value? | 37,459,042 | <p>Let's say I have two lists generated by another function:</p>
<pre><code>test = [[0, 1], [0, 2], [1, 5], [1,6], [2, 0], [3, 99], [3, 89], [3, 79]]
test2 = [[1, 4], [4, 1]]
</code></pre>
<p>I want to convert them to associative arrays for quick lookup like so:</p>
<pre><code>test: {0: [1, 2], 1: [5,6], 2: [0], 3: ... | 3 | 2016-05-26T11:04:42Z | 37,459,172 | <p>Use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict"><code>collections.defaultdict</code></a>:</p>
<pre><code>>>> test = [[0, 1], [0, 2], [1, 5], [1,6], [2, 0], [3, 99], [3, 89], [3, 79]]
>>>
>>> from collections import defaultdict
>>> d = def... | 5 | 2016-05-26T11:10:18Z | [
"python",
"list-comprehension"
] |
How to convert a list containing duplicate values to a dictionary with a list as the value? | 37,459,042 | <p>Let's say I have two lists generated by another function:</p>
<pre><code>test = [[0, 1], [0, 2], [1, 5], [1,6], [2, 0], [3, 99], [3, 89], [3, 79]]
test2 = [[1, 4], [4, 1]]
</code></pre>
<p>I want to convert them to associative arrays for quick lookup like so:</p>
<pre><code>test: {0: [1, 2], 1: [5,6], 2: [0], 3: ... | 3 | 2016-05-26T11:04:42Z | 37,460,070 | <p>This seems like a perfect use case for <code>itertools.groupby</code>:</p>
<pre><code>test = [[0, 1], [0, 2], [1, 5], [1,6], [2, 0], [3, 99], [3, 89], [3, 79]]
import itertools
d = {k:[t[1] for t in g] for k,g in itertools.groupby(test, key=lambda t: t[0])}
print(d)
</code></pre>
<p>Note that <code>groupby</code... | 0 | 2016-05-26T11:49:39Z | [
"python",
"list-comprehension"
] |
How to convert a list containing duplicate values to a dictionary with a list as the value? | 37,459,042 | <p>Let's say I have two lists generated by another function:</p>
<pre><code>test = [[0, 1], [0, 2], [1, 5], [1,6], [2, 0], [3, 99], [3, 89], [3, 79]]
test2 = [[1, 4], [4, 1]]
</code></pre>
<p>I want to convert them to associative arrays for quick lookup like so:</p>
<pre><code>test: {0: [1, 2], 1: [5,6], 2: [0], 3: ... | 3 | 2016-05-26T11:04:42Z | 37,460,232 | <p>You could also do this by dictionary grouping, something like this:</p>
<pre><code> def list_to_dict(my_list):
d = {}
for pair in my_list:
first = pair[0]
second = pair[1]
if first not in d:
d[first] = []
d[first].append(second)
... | 1 | 2016-05-26T11:58:20Z | [
"python",
"list-comprehension"
] |
Regex for colorcoding strings | 37,459,059 | <p>I want to colorize strings in python, inserting start/stop color sequences before/after all numbers, as well as substrings marked with a control character ( % ). Lets assume <code>[</code> and <code>]</code> are start/stop color sequence</p>
<p>Currently, I match the string using two substitute iterations:</p>
<p>... | 1 | 2016-05-26T11:05:25Z | 37,460,374 | <p>There maybe other solutions but this may work. You need to install <strong><a href="https://pypi.python.org/pypi/regex" rel="nofollow"><code>regex</code></a></strong> library for using <strong><em>branch reset</em></strong> feature.</p>
<pre><code>>>> import regex as re
>>> x="Test 1.23: Some %str... | 2 | 2016-05-26T12:05:06Z | [
"python",
"regex"
] |
Python process on remote server need to ssh to other and continue running | 37,459,084 | <p>Is it possible to solve that a running Python process which is running on a remote server, ssh to other and then continue running?</p>
<pre><code>run in 192.168.100.1
|
ssh to there 192.168.100.2
|
run continuously on 192.168.100.2 and do other functions from py
</code></pre>
<p>I tried with subprocess call but wh... | 1 | 2016-05-26T11:06:16Z | 37,459,347 | <p>You need use RPC to call python function on remote server.</p>
<p>There are many libs around. Let's take <a href="https://rpyc.readthedocs.io/en/latest/" rel="nofollow">RPyC</a> lib for example:</p>
<pre><code>>>> import rpyc
>>> c = rpyc.classic.connect("localhost")
>>> c.execute("prin... | 0 | 2016-05-26T11:18:29Z | [
"python"
] |
Python process on remote server need to ssh to other and continue running | 37,459,084 | <p>Is it possible to solve that a running Python process which is running on a remote server, ssh to other and then continue running?</p>
<pre><code>run in 192.168.100.1
|
ssh to there 192.168.100.2
|
run continuously on 192.168.100.2 and do other functions from py
</code></pre>
<p>I tried with subprocess call but wh... | 1 | 2016-05-26T11:06:16Z | 37,459,478 | <p>You may os.system in your home server python script like that:</p>
<pre><code>...
os.system("ssh user@server2 /usr/bin/python2.7 remote_script.py")
...
</code></pre>
<p>Script on your home server will stuck until os.system is working.
However, ssh to server2 have to be implemented without password (by RSA keys).<... | 0 | 2016-05-26T11:23:50Z | [
"python"
] |
Function action on tkinter button and results on label | 37,459,090 | <p>I have this function and I need to build an interface for it.
It's a function that is searching some data in the log file.
This data needs to printed into Label.
1. Data (int ) needs to be user input.
2. Value from user input will be searched in the log file
3. Results from the log needs to printed on label. </p>
<... | 0 | 2016-05-26T11:06:37Z | 37,471,795 | <p>Your main problem seems to be that your button does not execute your <code>searcher</code> function as you expected.</p>
<p>The code for your button looks like this:</p>
<pre><code>self.button = tk.Button(self, text="Check IMEI", command=self.on_button)
</code></pre>
<p>While the function it's supposed to execute... | 0 | 2016-05-26T22:04:57Z | [
"python",
"python-3.x",
"tkinter"
] |
calculating angle between three points but only anticlockwise in python | 37,459,121 | <p>So I'm trying to calculate the angle between three points. for example</p>
<pre><code>a = [14, 140]
b = [13, 120]
c = [12, 130]
d = [11, 110]
|
| c a
|
| d b
|____________
</code></pre>
<p>say i want to calculate the angle between ABC i use the follow code</p>
<pre><code>#create vectors
ba = a - b
bc =... | 2 | 2016-05-26T11:08:24Z | 37,459,227 | <p>You are able to calculate the inner angle, but you want the reversed angle? why not just calculating <code>360 - angle</code></p>
| 0 | 2016-05-26T11:12:47Z | [
"python",
"math",
"angle"
] |
calculating angle between three points but only anticlockwise in python | 37,459,121 | <p>So I'm trying to calculate the angle between three points. for example</p>
<pre><code>a = [14, 140]
b = [13, 120]
c = [12, 130]
d = [11, 110]
|
| c a
|
| d b
|____________
</code></pre>
<p>say i want to calculate the angle between ABC i use the follow code</p>
<pre><code>#create vectors
ba = a - b
bc =... | 2 | 2016-05-26T11:08:24Z | 37,462,099 | <p>Now using <strong>angular cosine distance</strong> to calculate the angle between two vectors is quite good, but in your case it might be better to use <strong>arc tangent</strong> as mentioned in the comments.</p>
<p>Now assuming you want to calculate the counterclockwise angle between BCD, you can do this by usin... | 0 | 2016-05-26T13:21:20Z | [
"python",
"math",
"angle"
] |
Selecting a single article from a Panda list | 37,459,176 | <p>It might be a stupid question but it is driving me crazy. I have a corpus composed by 8807 articles:</p>
<pre><code>print(type(doc_set))
class 'pandas.core.series.Series'
print(len(doc_set))
8807
</code></pre>
<p>From this list, I just want to select the first one. I have tried <code>doc_set[1]</code>, but it retr... | 0 | 2016-05-26T11:10:39Z | 37,459,213 | <p>try to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iloc.html" rel="nofollow">iloc</a> locator:</p>
<pre><code>doc_set.iloc[0]
</code></pre>
<p>Docs [<code>iloc</code>]:</p>
<blockquote>
<p>Purely integer-location based indexing for selection by position.</p>
<p>.iloc[] ... | 1 | 2016-05-26T11:12:11Z | [
"python",
"list",
"pandas"
] |
Selecting a single article from a Panda list | 37,459,176 | <p>It might be a stupid question but it is driving me crazy. I have a corpus composed by 8807 articles:</p>
<pre><code>print(type(doc_set))
class 'pandas.core.series.Series'
print(len(doc_set))
8807
</code></pre>
<p>From this list, I just want to select the first one. I have tried <code>doc_set[1]</code>, but it retr... | 0 | 2016-05-26T11:10:39Z | 37,459,331 | <p>I think you have duplicity in <code>index</code>.</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iat.html" rel="nofollow"><code>iat</code></a> if you need select first value of <code>Series</code>:</p>
<pre><code>doc_set = pd.Series([8,9,10], index=[1,1,1])
print (doc_set)
... | 1 | 2016-05-26T11:17:39Z | [
"python",
"list",
"pandas"
] |
Remove Action Bar Icon Kivy | 37,459,178 | <p>I am having Code as above for my action bar in kivy</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>ActionBar:
background_color:0,191,255,0.5
pos_hint: {'top':1}
ActionView... | 1 | 2016-05-26T11:10:46Z | 37,459,573 | <p>It looks like disabling an icon is impossible.<br>
Reference: Kivy sources @ github (<a href="https://github.com/kivy/kivy/blob/856b305c0c876e53e802f1ac9ae16c21fa91ac1e/kivy/uix/actionbar.py#L214" rel="nofollow">https://github.com/kivy/kivy/blob/856b305c0c876e53e802f1ac9ae16c21fa91ac1e/kivy/uix/actionbar.py#L214</a>... | 1 | 2016-05-26T11:28:23Z | [
"python",
"android-actionbar",
"kivy"
] |
Remove Action Bar Icon Kivy | 37,459,178 | <p>I am having Code as above for my action bar in kivy</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>ActionBar:
background_color:0,191,255,0.5
pos_hint: {'top':1}
ActionView... | 1 | 2016-05-26T11:10:46Z | 37,461,504 | <p>It's a hack but since <code>kivy.uix.actionbar.ActionPrevious</code> is actually a subclass of <code>BoxLayout</code>, you can actually use method like <code>remove_widget()</code> or <code>clear_widgets()</code> to manipulate its content after you create it:</p>
<pre><code>from kivy.app import App
from kivy.uix.b... | 0 | 2016-05-26T12:55:29Z | [
"python",
"android-actionbar",
"kivy"
] |
Pandas - Absolute value for header row | 37,459,208 | <p>I have an issue reading some poorly structured excel templates.</p>
<p>I intend for my process to make use of a metadata file containing 4 fields: Filename, Type, Sheet ID, and Header row.</p>
<p>My process will read this metadata then pass it to the <code>pd.read_excel</code> function like so:</p>
<pre><code>pd.... | 1 | 2016-05-26T11:12:04Z | 37,461,944 | <p>If I understand correctly, the excel table looks like:</p>
<p><a href="http://i.stack.imgur.com/VGtXC.png" rel="nofollow"><img src="http://i.stack.imgur.com/VGtXC.png" alt="enter image description here"></a></p>
<p>If I read it like:</p>
<pre><code>df = pd.read_excel( 'tab.xlsx', sheetname='Sheet1' )
</code></pre... | 0 | 2016-05-26T13:14:53Z | [
"python",
"excel",
"pandas"
] |
libvirt: From state integer to string? | 37,459,324 | <p>I have this simple script to check the memory usage of virtual machines managed by libvirt.</p>
<p>How can I convert the integer for <code>state</code> from <code>dom.info()</code> to a human readable string?</p>
<pre><code>import libvirt
import re
import sys
def mem_total_kb():
meminfo = open('/proc/meminf... | 1 | 2016-05-26T11:17:32Z | 37,838,554 | <p>This bash script will fetch the list of <code>virDomainState</code> values (excluding <code>VIR_DOMAIN_LAST</code>) and their descriptions in JSON format:</p>
<pre><code>#!/bin/bash
HEADER=include/libvirt/libvirt-domain.h
get_header_file()
{
curl -s https://raw.githubusercontent.com/libvirt/libvirt/master/"$H... | 0 | 2016-06-15T14:39:02Z | [
"python",
"libvirt"
] |
libvirt: From state integer to string? | 37,459,324 | <p>I have this simple script to check the memory usage of virtual machines managed by libvirt.</p>
<p>How can I convert the integer for <code>state</code> from <code>dom.info()</code> to a human readable string?</p>
<pre><code>import libvirt
import re
import sys
def mem_total_kb():
meminfo = open('/proc/meminf... | 1 | 2016-05-26T11:17:32Z | 37,907,144 | <p>Looks like at least the enum constant names are exposed in the <code>libvirt</code> module. The following works for me...</p>
<pre><code>import libvirt
import pprint
import re
d = {}
for k, v in libvirt.__dict__.iteritems():
if re.match('VIR_DOMAIN_[A-Z]+$', k):
d[v] = k
pprint.pprint(d)
</code></pre>... | 2 | 2016-06-19T12:18:13Z | [
"python",
"libvirt"
] |
Using matplotlib *without* TCL | 37,459,386 | <p>Exactly what the title says. Is there a way to use the matplotlib library <em>without</em> installing TCL? Please don't tell me to bite the bullet and install TCL - I know how to do it but for my own (ok maybe silly) reasons I don't want to.</p>
<p>I don't care about displaying the plots, I only want to be able to ... | 3 | 2016-05-26T11:20:04Z | 37,460,093 | <p>Immediately after loading matplotlib, enter</p>
<pre><code>matplotlib.use('Agg')
</code></pre>
<p>Do this before loading <code>pyplot</code>, if at all.</p>
<p>By default, Matplotlib uses the <code>TkAgg</code> backend, which requires Tcl. If you don't want to display the plots, <code>Agg</code> is fine. Other ... | 4 | 2016-05-26T11:50:56Z | [
"python",
"numpy",
"matplotlib",
"tcl"
] |
Python: Detecting only specific string not it's variations for dictionary | 37,459,446 | <p>I am trying to take in all the files at a given path, and order them based on my data title names.
So my data title names are:</p>
<pre><code>data_titles = ['CPU','Physical_Disk','Memory','Network','Network#2']
</code></pre>
<p>The files at this given path are named like <code>'CPU_data.txt'</code> and <code>'Memo... | 1 | 2016-05-26T11:22:18Z | 37,459,576 | <p>It's because <code>Network</code> can be found in both <code>'Network_data.txt'</code> <em>and</em> <code>'Network#2_data.txt'</code>. You need more than that to get a unique match.</p>
<p>Since these two names can be distinguished by adding a <code>_</code>, you can easily fix this by changing the test to</p>
<pr... | 1 | 2016-05-26T11:28:35Z | [
"python",
"string",
"dictionary"
] |
uTorrent Automation using pywinauto | 37,459,473 | <p>I am trying out an utorrent automation using pywinauto lib. I want to add a torrent with URL. This option is under the file menu. I can get as far as opening uTorrent and then nothing happens. I used Swapy for generating this code. The box below opens only when I run the code in swapy. But when I save it into a file... | 1 | 2016-05-26T11:23:21Z | 37,460,279 | <p>uTorrent is spawning another process, this is how I got it:</p>
<pre><code>>>> app.windows_()
[]
>>> app.process
6096
>>> app.connect(title_re=u'^μTorrent.*(build \d+).*')
<pywinauto.application.Application object at 0x000000000405C240>
>>> app.process
4044L
</code></pre>
... | 0 | 2016-05-26T12:00:25Z | [
"python",
"pywinauto",
"utorrent"
] |
python help! invalid literal for int() with base 10: | 37,459,500 | <p>hi currently doing a code where the programe recalls two files one with positions of words the other words the following code combines them however when i change my code to be imported from a file i get the following error (if compressed_sentence[(int(i)-1)]==uncompressed: ValueError: invalid literal for int() with ... | -2 | 2016-05-26T11:25:01Z | 37,460,226 | <p>The issue is that the compressed_Positions are read wrongly. The file reads the contents as one string. That string is the entire contents of the text file.</p>
<p>The split operator makes a list of strings. The first element of that list is everything from the file until the first space and that appears to be</p>
... | 0 | 2016-05-26T11:58:02Z | [
"python"
] |
How to add values to row? | 37,459,572 | <p><strong>How to add values to row</strong> :</p>
<ol>
<li>I created one column in data frame and assign value to 0.</li>
<li>Written logic to update these now column value, but not reflecting. </li>
</ol>
<p><strong>Input:</strong></p>
<pre><code>>>> parafix_df = main_df[["line_width", "para_num", "bbox" ... | 2 | 2016-05-26T11:28:23Z | 37,459,671 | <p><strong>UPDATE:</strong></p>
<p>IIUC, you can do it this way:</p>
<pre><code>df.new_para_num = 1
In [210]: df.loc[df.line_width == df.line_width.max(), 'new_para_num'].cumsum() + 1
Out[210]:
2 2
3 3
6 4
7 5
8 6
9 7
13 8
14 9
15 10
18 11
19 12
20 13
21 14
24 ... | 1 | 2016-05-26T11:32:59Z | [
"python",
"pandas"
] |
Open a widget with button PyQt5 | 37,459,766 | <p>I have a button connected to a function called OpenSupplyWidget() which is supposed to start a QWidget class I have in another file (the file is SupplyWidget.py and is already imported).</p>
<pre><code>def OpenSupplyWidget(self):
sw = SupplyWidget()
sw.show()
</code></pre>
<p>The function only opens the wi... | 0 | 2016-05-26T11:36:52Z | 37,459,965 | <p>Try having the SupplyWidget outside of the OpenSupplyWidget-function. The sw probably gets destroyed because the function terminates.</p>
<pre><code>...
def __init__(self):
self.sw = SupplyWidget()
def OpenSupplyWidget(self):
self.sw.show()
..
</code></pre>
| 2 | 2016-05-26T11:45:06Z | [
"python",
"pyqt",
"pyqt5"
] |
How to detect file within folder with python? | 37,459,872 | <p>My code:</p>
<pre><code>name = "test.txt"
if os.path.isfile("../datafiles/"+name):
print "Error; File already exists"
</code></pre>
<p>the folder datafiles sits in the same directoy as the python file, i'm trying to check for a file inside that folder. The above code can't detect the file, what am I doing ... | 0 | 2016-05-26T11:41:20Z | 37,460,008 | <p>If <code>datafiles</code> resides in the same folder as your script.<br>
Then you can't do <code>../</code> because that steps "out" of the folder one step back..</p>
<p>Meaning if your script+datafiles sits in <code>/home/user/</code>, your script will check <code>/home/datafiles/test.txt</code>, and that doesn't ... | 0 | 2016-05-26T11:47:05Z | [
"python",
"directory",
"os.path"
] |
Create json array using list in python | 37,459,931 | <p>Suppose we have one data frame <code>df</code> </p>
<pre><code> id=['abc','xyz','lmn']
df=pd.DataFrame(id)
df.columns=['id']
print(df)
id
0 abc
1 xyz
2 lmn
</code></pre>
<p>I want to generate the following array from it </p>
<pre><code> idd=[ { 'id': 'abc' ,},
{'id': 'xyz',},
{'id':'... | 1 | 2016-05-26T11:43:35Z | 37,459,968 | <p>You could use method <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_dict.html" rel="nofollow"><code>to_dict</code></a> with <code>records</code>:</p>
<pre><code>In [61]: df
Out[61]:
id
0 abc
1 xyz
2 lmn
In [62]: df.to_dict('records')
Out[62]: [{'id': 'abc'}, {'id': 'xyz'}, {... | 4 | 2016-05-26T11:45:16Z | [
"python",
"arrays",
"list",
"pandas",
"dataframe"
] |
Unable to install PyRFC | 37,460,091 | <p>I would like to install pyrfc but the package doesn't seem to exist anymore:</p>
<pre><code>C:\>easy_install pyrfc-1.9.3-py2.7-win32.egg
Searching for pyrfc-1.9.3-py2.7-win32.egg
Reading https://pypi.python.org/simple/pyrfc-1.9.3-py2.7-win32.egg/
Couldn't find index page for 'pyrfc-1.9.3-py2.7-win32.egg' (maybe ... | 0 | 2016-05-26T11:50:46Z | 37,460,653 | <p>See <a href="https://github.com/SAP/PyRFC" rel="nofollow">https://github.com/SAP/PyRFC</a></p>
<p><strong>A prerequisite to download is having a customer or partner account on SAP Service Marketplace</strong> and if you are SAP employee please check SAP OSS note 1037575 - Software download authorizations for SAP em... | 0 | 2016-05-26T12:18:08Z | [
"python",
"saprfc"
] |
Unable to install PyRFC | 37,460,091 | <p>I would like to install pyrfc but the package doesn't seem to exist anymore:</p>
<pre><code>C:\>easy_install pyrfc-1.9.3-py2.7-win32.egg
Searching for pyrfc-1.9.3-py2.7-win32.egg
Reading https://pypi.python.org/simple/pyrfc-1.9.3-py2.7-win32.egg/
Couldn't find index page for 'pyrfc-1.9.3-py2.7-win32.egg' (maybe ... | 0 | 2016-05-26T11:50:46Z | 37,844,202 | <p>get it from github </p>
<p><a href="https://github.com/SAP/PyRFC/tree/master/dist" rel="nofollow">https://github.com/SAP/PyRFC/tree/master/dist</a></p>
<p>and use easy_install</p>
<p>C:\myprograms>easy_install C:\Users*****\PyRFC\dist\pyrfc-1.9.4-py2.7-win-amd
64.egg</p>
| 0 | 2016-06-15T19:30:43Z | [
"python",
"saprfc"
] |
Pad right multi-line string | 37,460,100 | <p>After finding this code snippet from <a href="http://stackoverflow.com/questions/5676646/fill-out-a-python-string-with-spaces">here</a></p>
<pre><code>'{0: <16}'.format('Hi')
</code></pre>
<p>I was able to right pad strings - which is what I'm after.
I've written a function to deal with multi-line strings, but ... | 0 | 2016-05-26T11:51:19Z | 37,460,280 | <p>The <code>max</code>-function exists, which eliminates your first loop. And <code>join</code> can be used to stick the lines together again:</p>
<pre><code>def r_pad_string(s):
lines = s.splitlines()
width = max(len(l) for l in lines)
return "\n".join(
line.ljust(width, ".")
for line in ... | 1 | 2016-05-26T12:00:28Z | [
"python",
"string",
"python-2.7",
"padding"
] |
Pad right multi-line string | 37,460,100 | <p>After finding this code snippet from <a href="http://stackoverflow.com/questions/5676646/fill-out-a-python-string-with-spaces">here</a></p>
<pre><code>'{0: <16}'.format('Hi')
</code></pre>
<p>I was able to right pad strings - which is what I'm after.
I've written a function to deal with multi-line strings, but ... | 0 | 2016-05-26T11:51:19Z | 37,460,284 | <pre><code>def r_pad_string2(s, fillchar='.'):
lines = s.splitlines()
max_len = max(len(l) for l in lines)
return '\n'.join(l.ljust(max_len, fillchar) for l in lines)
</code></pre>
<p>timings:</p>
<pre><code>In [12]: %timeit r_pad_string(myStr1)
100000 loops, best of 3: 5.38 µs per lo... | 1 | 2016-05-26T12:00:45Z | [
"python",
"string",
"python-2.7",
"padding"
] |
How do I activate datepicker widget on custom form field? | 37,460,305 | <p>For example, when I add custom ModelView:</p>
<pre><code>class TaskModelView(ModelView):
pass
flaskadmin = Admin(name='Flasky', template_mode='bootstrap3', index_view=MyAdminIndexView(),
base_template='admin/mymaster.html')
flaskadmin.add_views(TaskModelView(models.Task, db.session))
</cod... | 0 | 2016-05-26T12:01:37Z | 37,460,549 | <p>As far as I remember, you can use either jQuery datepicker for this, or WTForms one, and not a <code>flask.ext.admin.form</code>. </p>
<p>Admin form is intended to be hidden from the end user, and exposing its API to the public user is strongly prohibited. </p>
<p>There was a similar question <a href="http://stack... | 0 | 2016-05-26T12:13:44Z | [
"python",
"flask",
"datepicker",
"flask-admin"
] |
How do I activate datepicker widget on custom form field? | 37,460,305 | <p>For example, when I add custom ModelView:</p>
<pre><code>class TaskModelView(ModelView):
pass
flaskadmin = Admin(name='Flasky', template_mode='bootstrap3', index_view=MyAdminIndexView(),
base_template='admin/mymaster.html')
flaskadmin.add_views(TaskModelView(models.Task, db.session))
</cod... | 0 | 2016-05-26T12:01:37Z | 39,108,651 | <p>Your admin/analytic.html is not loading the javascript that handles the client side selection of dates. add the following to your template;</p>
<pre><code>{% block tail_js %}
<script src="/static/vendor/jquery.min.js" type="text/javascript">/script>
{# use /static/bootstrap2/js/bootstrap.min.js i... | 0 | 2016-08-23T18:49:27Z | [
"python",
"flask",
"datepicker",
"flask-admin"
] |
How does dependencies isolation between MongoDB and Django work? | 37,460,386 | <p>How does Isolation dependencies between mongdb and django work?</p>
<p>I have made several projects with JAVA/SPRING, and the recent days,
I am studying Python django .</p>
<p>I successed to get connection between django and sqlite, and few days ago,
when I tried to connect to mongodb, it is hard to seperate dep... | 1 | 2016-05-26T12:05:37Z | 37,460,628 | <blockquote>
<p>What if sqlite to Mongodb? only using different driver cannot make server work. e.g models.TextField(sqlite) -> models.StringField(mongodb). It is unavoidable, right? It seems difficult that solating dependencies completely between database and django</p>
</blockquote>
<p><code>TextField</code> and <... | 0 | 2016-05-26T12:17:00Z | [
"python",
"django",
"database",
"mongodb",
"dependencies"
] |
Raspberry button trigger Python script which should display in webpage | 37,460,395 | <p>I have a Raspberry PI with a button attached to it.
I run a Python script on it to detect when the button is pressed.
When the button is pressed, it increment a number in a text file.
I need to display this number on a web page (Apache) and to launch a sound.</p>
<p>For the moment, my python script change the index... | 0 | 2016-05-26T12:05:54Z | 38,390,340 | <p>Too little information to say something concrete, but here's how I'd get around to it given the main following limitation that the page is not dynamic (no ajax).</p>
<p>General outline:</p>
<p>Put the value from the text file in a identifiable field like</p>
<p><code><span id="myNumber">#the number from fi... | 0 | 2016-07-15T07:31:06Z | [
"javascript",
"python",
"html",
"apache",
"raspberry-pi"
] |
Tastypie: define authentication for all resources | 37,460,572 | <p>What is the best approach to define authentication/authorization for all tastypie resources? I have many resources and don't want to copy the authentication line every time. Right now, I defined a function
</p>
<pre class="lang-py prettyprint-override"><code>def create_auth():
return MultiAuthentication(ApiKeyA... | 0 | 2016-05-26T12:14:39Z | 37,664,355 | <p>You should do the <code>metametaclass</code> as recomended for both <a href="https://github.com/django-tastypie/django-tastypie/issues/98" rel="nofollow">tastypie</a> and <a href="https://docs.djangoproject.com/en/dev/topics/db/models/#meta-inheritance" rel="nofollow">django</a>.</p>
<pre><code>classs YourBaseResou... | 1 | 2016-06-06T18:24:11Z | [
"python",
"django",
"tastypie"
] |
Why can I import module bs4 or requests from python IDLE shell but not from the python interpreter? | 37,460,610 | <p>I can import module BeautifulSoup or requests without any problem when I run it from my script or do it directly in the python IDLE shell:</p>
<pre><code>Python 2.7.9 (default, Mar 8 2015, 00:52:26)
[GCC 4.9.2] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> import bs4
>... | 0 | 2016-05-26T12:16:26Z | 38,102,541 | <p>It is not really IDLE vs. Python shell on console but where the current working directory for the process is. Because in the directory from wich you start the console Python shell there is a <code>string.py</code> which âshadowsâ the <code>string</code> module from the standard library. Delete that <code>strin... | 1 | 2016-06-29T14:25:32Z | [
"python",
"import",
"module"
] |
Django conditional annotation count with filter (many-to-many) follower/following table | 37,460,639 | <p>This is a bit of a mind bender for me so I decided to ask for some help.</p>
<p>What I have is a standard user model and a table which tracks if users follow each other which has a <code>from_user</code>, <code>to_user</code>, and <code>following</code> values. The first to being foreignkeys to my user table the th... | 1 | 2016-05-26T12:17:22Z | 37,460,864 | <p>I think you're looking for <a href="https://docs.djangoproject.com/en/dev/ref/models/expressions/#django.db.models.F" rel="nofollow"><code>F</code> expressions</a>:</p>
<pre><code>from django.db.models import F
def get_queryset(self, request):
return AuthUser.objects.annotate(
followers_count=Sum(
... | 1 | 2016-05-26T12:27:33Z | [
"python",
"django",
"annotations",
"conditional"
] |
Python - Read and assign data from a .csv to pre-defined variables | 37,460,683 | <p>I am trying to read data from a CSV file (A), extract data, and write that to a different CSV file (B). In the new file B, I want to have two rows. The first row should contain all the predefined variables and row 2 should be filled with all the values that belong to the specific variable in row 1.</p>
<p>I hope an... | 0 | 2016-05-26T12:19:48Z | 37,463,152 | <p>You should open your file with the <code>csv</code> library, <code>semi-colon</code> separated and then compare the first column with the items in your definition. This pretty much does that:</p>
<pre><code>import csv
from collections import defaultdict
data = defaultdict(str)
#Make a list with the predefined var... | 0 | 2016-05-26T14:03:49Z | [
"python",
"csv"
] |
Python - Read and assign data from a .csv to pre-defined variables | 37,460,683 | <p>I am trying to read data from a CSV file (A), extract data, and write that to a different CSV file (B). In the new file B, I want to have two rows. The first row should contain all the predefined variables and row 2 should be filled with all the values that belong to the specific variable in row 1.</p>
<p>I hope an... | 0 | 2016-05-26T12:19:48Z | 37,491,169 | <p>It's nearly perfect! seems like there are some small problems.
In the result.csv i am missing the values of the following variables:</p>
<pre><code>step_time
step_length
cycle_time
stride_length
hh_base_support
swing_time
stance_time
single_supp_time
double_supp_time
toe_in_out
</code></pre>
<p>I... | 0 | 2016-05-27T19:44:57Z | [
"python",
"csv"
] |
Python logging: disable output to stdout | 37,460,714 | <p>I'm trying to make a program use only the SysLogHandler instance for logging and no other handlers. I expect it to not log to any files or stdout.</p>
<pre><code> self.logger = logging.getLogger(self.name)
syslog_handler = logging.handlers.SysLogHandler(
socktype=socket.AF_UNIX,
address='/de... | 0 | 2016-05-26T12:20:52Z | 37,460,958 | <p>You have different ways to do so:</p>
<p>-set logger.propagate to false.</p>
<ul>
<li><p>you can create tour own stream, like this:</p>
<p><a href="https://docs.python.org/2/library/io.html#io.StringIO" rel="nofollow">https://docs.python.org/2/library/io.html#io.StringIO</a></p></li>
</ul>
<p>And give it to your... | 1 | 2016-05-26T12:32:00Z | [
"python",
"python-3.x",
"logging",
"syslog",
"syslog-ng"
] |
Can't access mqlread API | 37,460,817 | <p>I am trying to access the mqlread API from Freebase but am getting a <code>"Not Found" 404</code>:</p>
<pre><code>api_key = open("freebaseApiKey").read()
mqlread_url = 'https://www.googleapis.com/freebase/v1/mqlread'
mql_query = '[{"mid": null,"name": null, "type": "/location/statistical_region","limit": 100}]'
cur... | 1 | 2016-05-26T12:25:57Z | 37,463,777 | <p>It was deprecated over a year ago. It was finally shut down May 2.</p>
<p><a href="https://groups.google.com/forum/#!topic/freebase-discuss/WEnyO8f7xOQ" rel="nofollow">https://groups.google.com/forum/#!topic/freebase-discuss/WEnyO8f7xOQ</a></p>
<p>The only source for this information now is the Freebase data dump.... | 2 | 2016-05-26T14:29:35Z | [
"python",
"json",
"freebase"
] |
how to read response in python and calling def | 37,460,881 | <p>I have a if statement which i am trying to replace a variable.
After replacing the variable how do i call def parse_again
Below are my code i am trying out my.</p>
<p>match4 is a string and rep1 too</p>
<p>rep1 variable is a global variable</p>
<pre><code>if results == "":
url = 'myapiIP'
postdat... | 1 | 2016-05-26T12:28:25Z | 37,474,801 | <p>You're working inside a class, so your eventual call to parse_again should be</p>
<pre><code>self.parse_again(response)
</code></pre>
| 0 | 2016-05-27T04:21:06Z | [
"python",
"json",
"request"
] |
Python for loop being skipped in program | 37,460,911 | <p>I am trying to write a python program that sends out questions and checks for answers. It has a while True loop in it which is broken when an answer is received. The file "players.txt" just contains a number which is the amount of players currently available to answer the question. The problem I am having with it is... | 0 | 2016-05-26T12:29:44Z | 37,461,054 | <p>What I understand is that you have in output :</p>
<pre><code>>> File: players.txt OPENED
</code></pre>
<p>But not :</p>
<pre><code>>> For Loop STARTED
</code></pre>
<p>That means that <code>range(int(myfile.read()))</code> is in fact an empty list. If I were you I would check my file and my method f... | 0 | 2016-05-26T12:36:13Z | [
"python",
"python-3.x",
"for-loop",
"while-loop"
] |
Python for loop being skipped in program | 37,460,911 | <p>I am trying to write a python program that sends out questions and checks for answers. It has a while True loop in it which is broken when an answer is received. The file "players.txt" just contains a number which is the amount of players currently available to answer the question. The problem I am having with it is... | 0 | 2016-05-26T12:29:44Z | 37,461,212 | <p>The "myfile.read()" is not working because the entire file is read in at this point</p>
<p>Use something like</p>
<pre><code>line=1
while(line):
line = myfile.readline()
for i in range(int(line)):
</code></pre>
| 0 | 2016-05-26T12:42:55Z | [
"python",
"python-3.x",
"for-loop",
"while-loop"
] |
Python for loop being skipped in program | 37,460,911 | <p>I am trying to write a python program that sends out questions and checks for answers. It has a while True loop in it which is broken when an answer is received. The file "players.txt" just contains a number which is the amount of players currently available to answer the question. The problem I am having with it is... | 0 | 2016-05-26T12:29:44Z | 37,461,314 | <p>The <code>.read</code> method returns the bytes read in string. So when you try <code>int(myfile.read())</code> it will provide an invalid literal for int() with base 10 (which is the string obtained by reading the file using myfile.read() )</p>
| 0 | 2016-05-26T12:47:04Z | [
"python",
"python-3.x",
"for-loop",
"while-loop"
] |
Python for loop being skipped in program | 37,460,911 | <p>I am trying to write a python program that sends out questions and checks for answers. It has a while True loop in it which is broken when an answer is received. The file "players.txt" just contains a number which is the amount of players currently available to answer the question. The problem I am having with it is... | 0 | 2016-05-26T12:29:44Z | 37,462,020 | <p>Just like Tony Vincent said. The read() returns the text that exists in the file which you cannot cast as an int. Change the int(myfile.read()) to len(myfile.read()) which will return the integer length of the string</p>
| 0 | 2016-05-26T13:18:03Z | [
"python",
"python-3.x",
"for-loop",
"while-loop"
] |
HTML colors in matplotlib | 37,460,934 | <p>How do I use html to change colors in a plot using matplotlib in python? I tried </p>
<pre><code>plt.plot(x,y,marker=".",color="#e0e0e0")
</code></pre>
<p>but this created the data points as "." but it also connects them with lines of #e0e0e0 color and I don't want these lines. I also tried </p>
<pre><code>plt.pl... | -2 | 2016-05-26T12:30:39Z | 37,461,472 | <p>If you want to only have markers and no connecting lines between points you can use either</p>
<pre><code>plt.plot(x, y, '.', color="#e0e0e0")
</code></pre>
<p>Here the third argument is a format string specifiying marker type and linestyle, and as no linestyle is specified no line is plotted. You can achieve the ... | 3 | 2016-05-26T12:54:01Z | [
"python",
"html",
"matplotlib"
] |
intercept attribute modifications in Python class | 37,460,966 | <p>I want to implement a class in Python where modifying a subset of its attributes leads to a specific class method being called. I see that Python offers many ways to achieve something what I want but I'm not sure which is the most Pythonic and minimalistic way to achieve this.</p>
<p>For instance, let's say we have... | 0 | 2016-05-26T12:32:14Z | 37,467,100 | <p>This is actually pretty easy with the new classes in Python, built on top of the <code>object</code> class :</p>
<pre><code>class Foo ( object ) :
def __setattr__ ( self, name, value ) :
self.bar( name, value )
object.__setattr__( self, name, value )
def bar ( self, name, value ) :
... | 0 | 2016-05-26T17:06:15Z | [
"python",
"attributes"
] |
Drop columns with similar names with over 50% nan in pandas | 37,461,082 | <p>I have a large pandas data-frame [df] with hundreds of column names.
I want to drop all columns that have over 50% NAN values but only those columns that have the word "test" in the columns title. Is there an easy way to do this & thank you for your help!</p>
| 2 | 2016-05-26T12:37:35Z | 37,461,216 | <p>IIUC you can do something like this:</p>
<pre><code>In [122]:
df = pd.DataFrame({'test':np.NaN, 'asd':0,'test 1':[0,1,np.NaN,3,4]})
df
Out[122]:
asd test test 1
0 0 NaN 0.0
1 0 NaN 1.0
2 0 NaN NaN
3 0 NaN 3.0
4 0 NaN 4.0
In [138]:
cols = df.columns[df.columns.str... | 4 | 2016-05-26T12:43:02Z | [
"python",
"pandas",
"dataframe"
] |
time-depending layout of graph in pyqtgraph | 37,461,116 | <p>Good time of day! I am trying to make tree-plot with time drawing, using <code>pyqtgraph</code> and have found only tutorial in <code>CustomGraphItem</code> and <code>QTimer</code> in pyqtgraph examples. I can't find a way how to make vertices and edges layout depend from time. I need to lay them out in some seconds... | 0 | 2016-05-26T12:39:01Z | 37,485,596 | <p>Because there are no answers, then I add - I did fix in the form of:</p>
<pre><code># -*- coding: utf-8 -*-
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
import random
# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)
w = pg.GraphicsWindow()
w.setWind... | 0 | 2016-05-27T14:08:20Z | [
"python",
"animation",
"pyqtgraph"
] |
Using Python & Pandas to turn flat list into matrix | 37,461,123 | <p>I have an csv file that looks like:</p>
<pre><code>A, 8.1, pass
B, 8.1, fail
A, 8.2, in-progress
B, 8.2, on-hold
C, 8.2, fail
...
F, 11.1, pass
</code></pre>
<p>That I want to turn into a file that looks like this:</p>
<pre><code>Area 8.1 8.2 8.3 9.1 9.2.............11.1
A Pass In-Pr Fail Pass O... | 1 | 2016-05-26T12:39:17Z | 37,461,264 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table()</a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow">pivot()</a> for that:</p>
<pre><code>In [253]: df.pivot_table(index='col1... | 0 | 2016-05-26T12:44:59Z | [
"python",
"pandas"
] |
Using Python & Pandas to turn flat list into matrix | 37,461,123 | <p>I have an csv file that looks like:</p>
<pre><code>A, 8.1, pass
B, 8.1, fail
A, 8.2, in-progress
B, 8.2, on-hold
C, 8.2, fail
...
F, 11.1, pass
</code></pre>
<p>That I want to turn into a file that looks like this:</p>
<pre><code>Area 8.1 8.2 8.3 9.1 9.2.............11.1
A Pass In-Pr Fail Pass O... | 1 | 2016-05-26T12:39:17Z | 37,461,956 | <h3>Setup</h3>
<pre><code>text = """A, 8.1, pass
B, 8.1, fail
A, 8.2, in-progress
B, 8.2, on-hold
C, 8.2, fail
F, 11.1, pass"""
df = pd.read_csv(StringIO(text), names=['Area', 'col1', 'col2'])
</code></pre>
<h3>Solution</h3>
<p>Use <code>set_index</code> and <code>unstack</code></p>
<pre><code>df.set_index(['Area'... | 0 | 2016-05-26T13:15:30Z | [
"python",
"pandas"
] |
Length of lists in array | 37,461,201 | <p>I'm using <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.spatial.cKDTree.query_ball_point.html" rel="nofollow">scipy.spatial.cKDTree.query_ball_point</a> to get the number of data points within a specific radius from each point in a grid layout.</p>
<p>It works but returns me an array of ... | 0 | 2016-05-26T12:42:27Z | 37,461,377 | <p>Call len() on each element in the array</p>
<p>ie</p>
<pre><code>lengths=[len(x) for x in myarray]
</code></pre>
| 2 | 2016-05-26T12:49:47Z | [
"python",
"numpy",
"scipy"
] |
Length of lists in array | 37,461,201 | <p>I'm using <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.spatial.cKDTree.query_ball_point.html" rel="nofollow">scipy.spatial.cKDTree.query_ball_point</a> to get the number of data points within a specific radius from each point in a grid layout.</p>
<p>It works but returns me an array of ... | 0 | 2016-05-26T12:42:27Z | 37,462,033 | <p>You can also use a more ''mathematical'' way:</p>
<pre><code>lengths = map(len, myarray)
</code></pre>
<p>It will return a <code>map</code> object you can iterate.</p>
| 1 | 2016-05-26T13:18:44Z | [
"python",
"numpy",
"scipy"
] |
Length of lists in array | 37,461,201 | <p>I'm using <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.spatial.cKDTree.query_ball_point.html" rel="nofollow">scipy.spatial.cKDTree.query_ball_point</a> to get the number of data points within a specific radius from each point in a grid layout.</p>
<p>It works but returns me an array of ... | 0 | 2016-05-26T12:42:27Z | 37,466,037 | <p>The docs for this function say it returns a</p>
<blockquote>
<p>If x is an array of points, returns an object array of <code>shape tuple</code> containing lists of neighbors</p>
</blockquote>
<p>where</p>
<blockquote>
<p>x : array_like, <code>shape tuple</code> + (self.m,)</p>
</blockquote>
<p>The talk of <c... | 2 | 2016-05-26T16:10:09Z | [
"python",
"numpy",
"scipy"
] |
Length of lists in array | 37,461,201 | <p>I'm using <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.spatial.cKDTree.query_ball_point.html" rel="nofollow">scipy.spatial.cKDTree.query_ball_point</a> to get the number of data points within a specific radius from each point in a grid layout.</p>
<p>It works but returns me an array of ... | 0 | 2016-05-26T12:42:27Z | 37,468,444 | <p>Sounds like you are looking for this: scipy.spatial.cKDTree.count_neighbors</p>
| 0 | 2016-05-26T18:24:45Z | [
"python",
"numpy",
"scipy"
] |
plot the 50 least frequent words with nltk | 37,461,239 | <p>How do I plot the 50 least frequent words?</p>
<p>Maybe I am thinking too complicated. Here's the way I get the words:</p>
<pre><code>distr = nltk.FreqDist(word for word in items)
words = distr .keys()
seldomwords = words [:50]
</code></pre>
<p>How do I plot this now?</p>
<p>With the <code>plot</code> function o... | 0 | 2016-05-26T12:43:59Z | 37,467,074 | <p>It's sort of strange but the simplest way is to </p>
<ul>
<li>first you have to extract the least common items from the <code>FreqDist</code> </li>
<li>then recreate the least common items and feed it back into a new FreqDist object</li>
<li>use <code>FreqDist.plot()</code> using the new FreqDist.</li>
</ul>
... | 1 | 2016-05-26T17:04:57Z | [
"python",
"plot",
"nlp",
"nltk"
] |
How can I reverse a section of a list using a loop in Python? | 37,461,321 | <p>I'm in need of a little help reversing a section of a list in Python <strong>using a loop.</strong></p>
<p>I have a list: <code>mylist = ['a', 'b', 'c', 'd', 'e', 'f']</code></p>
<p>Also have an index number, this number will tell where to start the reversing. For example, if the reverse-index number is 3, it need... | 2 | 2016-05-26T12:47:29Z | 37,461,398 | <p>You can simply use:</p>
<pre><code>def list_section_reverse(list1, reverse_index):
return list(reversed(list1[:reverse_index+1])) + list1[reverse_index+1:]
</code></pre>
<p><strong>Edit:</strong> The problem with your existing solution is that you keep reversing after <code>reverse_index</code>. If you <em>hav... | 2 | 2016-05-26T12:50:35Z | [
"python",
"list",
"function",
"loops",
"reverse"
] |
How can I reverse a section of a list using a loop in Python? | 37,461,321 | <p>I'm in need of a little help reversing a section of a list in Python <strong>using a loop.</strong></p>
<p>I have a list: <code>mylist = ['a', 'b', 'c', 'd', 'e', 'f']</code></p>
<p>Also have an index number, this number will tell where to start the reversing. For example, if the reverse-index number is 3, it need... | 2 | 2016-05-26T12:47:29Z | 37,461,966 | <p>You can try this. This makes use of no slicing, and can use either a while loop or for loop. </p>
<pre><code> def reversed_list(my_list, index):
result = []
list_copy = my_list.copy()
i = 0
while i < index+1:
result.append(my_list[i])
list_copy.remove(m... | 0 | 2016-05-26T13:15:46Z | [
"python",
"list",
"function",
"loops",
"reverse"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.