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 |
|---|---|---|---|---|---|---|---|---|---|
Maya (Python): Running condition command and scriptJob command from within a module | 39,252,664 | <p>I'm creating a UI tool that loads during Maya's startup, and executes some modules AFTER VRay has initialized (otherwise an error is thrown). </p>
<p>A suggestion from my broader question <a href="http://stackoverflow.com/questions/38601706/maya-defer-a-script-until-after-vray-is-registered">here</a> has lead me t... | 0 | 2016-08-31T14:42:11Z | 39,253,465 | <p>try that, </p>
<pre><code>import os
import maya.cmds as mc
import maya.mel as mel
vray_plugin_path_2016 = os.path.join('C:', os.sep, 'Program Files', 'Autodesk', 'Maya2016', 'vray', 'plug-ins', 'vrayformaya.mll')
#-----------------------------------------------------------------------
def is_vray_loaded(*args):... | 1 | 2016-08-31T15:22:01Z | [
"python",
"condition",
"maya"
] |
Preselective dynamic modelChoicefields Django | 39,252,705 | <p>I have 3 models, which are connected by Foreign Key like this</p>
<pre><code>models.py
class Partner(models.Model):
partner_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
...
class Product(models.Model):
product_id = models.UUIDField(primary_key=True, default=uuid.uuid4, e... | 0 | 2016-08-31T14:44:00Z | 39,253,568 | <p>I do not have a lot of experience with ModelForms or ModelChoiceField, but what I've done here might help:</p>
<pre><code>class ProductDataForm(forms.Form):
partner_id= forms.ChoiceField(
choices = [ (u.id, u.id) for u in Partner.objects.all()]
)
</code></pre>
| 0 | 2016-08-31T15:27:25Z | [
"python",
"django"
] |
Counting duplicate characters | 39,252,731 | <p>I can't figure out why the last character in a string always gets omitted when I try the following:</p>
<pre><code>def duplicate_count(text):
num = 0
count = {}
for char in text:
print(count.items())
if char in count.keys():
count[char] += 1
else:
count [c... | -2 | 2016-08-31T14:45:12Z | 39,252,863 | <p>You only output the counts before a given character is added, so you will never see the final counts. You could move your print statement to after your <code>if</code> if you'd like to change that.</p>
<p>The other issue is that your program is only returning the duplicate count of the last entry in your dictionary... | 2 | 2016-08-31T14:51:30Z | [
"python",
"string",
"python-3.x"
] |
Counting duplicate characters | 39,252,731 | <p>I can't figure out why the last character in a string always gets omitted when I try the following:</p>
<pre><code>def duplicate_count(text):
num = 0
count = {}
for char in text:
print(count.items())
if char in count.keys():
count[char] += 1
else:
count [c... | -2 | 2016-08-31T14:45:12Z | 39,252,875 | <p>The last character doesn't get omitted, it has not yet been added to <code>count</code> when you call <code>print(count.items())</code>.</p>
| 2 | 2016-08-31T14:52:02Z | [
"python",
"string",
"python-3.x"
] |
Counting duplicate characters | 39,252,731 | <p>I can't figure out why the last character in a string always gets omitted when I try the following:</p>
<pre><code>def duplicate_count(text):
num = 0
count = {}
for char in text:
print(count.items())
if char in count.keys():
count[char] += 1
else:
count [c... | -2 | 2016-08-31T14:45:12Z | 39,253,106 | <p>In my opinion this could use some more segmentation. In my opinion you should not be focused on counting duplicate letters; you should narrow the scope of your function to identifying which letters occur, and how many times they occur. This can be easily stored in a dictionary variable.</p>
<p>Example:</p>
<pre><c... | 0 | 2016-08-31T15:03:25Z | [
"python",
"string",
"python-3.x"
] |
Get Access Token for Google Analytics Embed API server side authorization | 39,252,779 | <p>I am trying to set up server side authorization for Google Analytics Embed API. When I run this on the command line:</p>
<pre><code>sudo pip install --upgrade google-api-python-client
</code></pre>
<p>I get this message:</p>
<pre><code>The directory '/Users/XXXX/Library/Caches/pip/http' or its parent directory is... | 0 | 2016-08-31T14:47:52Z | 39,253,133 | <p>I think you might want to read this :
<a href="https://github.com/pypa/pip/issues/3165" rel="nofollow">https://github.com/pypa/pip/issues/3165</a></p>
<p>they say that you could do :</p>
<p>sudo pip install --ignore-installed six</p>
<p>sudo pip install --ignore-installed --upgrade google-api-python-client </p>
... | 1 | 2016-08-31T15:04:58Z | [
"python",
"command-line",
"google-analytics",
"sudo"
] |
How to in-place sort each sublist of a list in python | 39,252,802 | <p>I have a list of integers as such:</p>
<pre><code>[[12, 62, 49, 17, 99, 33, 47, 94, 58, 97, 75, 9], [46, 86, 95, 61, 80, 96, 14, 3,
43, 2, 22, 83], [54, 57, 52, 32, 87, 15, 18, 39, 8, 90, 56, 23, 84], [82, 30, 26,
31, 88, 37, 45, 79, 77, 66, 40, 51, 72]]
</code></pre>
<p>And I want a list back but each sublist i... | -1 | 2016-08-31T14:49:10Z | 39,252,878 | <pre><code>f = lambda lst: [lst[i].sort() for i in range(len(lst))].count(None)
</code></pre>
<p>This returns a number of successfully sorted lists.</p>
| 1 | 2016-08-31T14:52:17Z | [
"python"
] |
Problems with Python password checker | 39,252,996 | <p>I have created a password checker in Python. Here is the code that I have used:</p>
<pre><code>import easygui as eg
def pword():
global password
global lower
global upper
global integer
password = eg.enterbox(msg="Please enter your password")
length = len(password)
print(length)
lo... | -3 | 2016-08-31T14:57:23Z | 39,253,348 | <p>I fixed your indentation</p>
<p>Your code works, tested on Ubuntu 14.04 LTS</p>
<p><strong>EDIT:</strong></p>
<p>Also tested on Windows 7 32bit python 2.7.12
<a href="http://i.stack.imgur.com/CGoj8.png" rel="nofollow"><img src="http://i.stack.imgur.com/CGoj8.png" alt="enter image description here"></a></p>
<p>Ev... | 0 | 2016-08-31T15:16:02Z | [
"python",
"string",
"function",
"file",
"passwords"
] |
Python - Dictionary in class not functioning as expected | 39,253,073 | <p>I have a very basic class <code>Library</code>, and I initialize it with a passed in dictionary (key book name (string), value book shelf location (int)) with values already entered into it. The code looks like this:</p>
<pre><code>class Library(object):
def __init__(self, book_table):
self.book_table =... | 1 | 2016-08-31T15:01:43Z | 39,254,677 | <p>You are creating a <em>new</em> <code>Library</code> instance that you pass your existing instance into:</p>
<pre><code>print Library(libraries[0]).get_location("Book1")
# ^^^^^^^ ^^^^^^^^^^^^
# | \----------- an existing instance of Library
# A new instance of Library
</code></pre>
<p>This give... | 1 | 2016-08-31T16:28:01Z | [
"python",
"dictionary"
] |
Python - Dictionary in class not functioning as expected | 39,253,073 | <p>I have a very basic class <code>Library</code>, and I initialize it with a passed in dictionary (key book name (string), value book shelf location (int)) with values already entered into it. The code looks like this:</p>
<pre><code>class Library(object):
def __init__(self, book_table):
self.book_table =... | 1 | 2016-08-31T15:01:43Z | 39,254,724 | <p><code>Library(libraries[0])</code> you call <strong>init</strong> again</p>
<p>This code should works</p>
<pre><code>class Library(object):
def __init__(self, book_table):
self.book_table = book_table
def get_location(self, book_name):
if book_name in self.book_table: # ERROR RIGHT HERE
... | 0 | 2016-08-31T16:30:45Z | [
"python",
"dictionary"
] |
Separate binary data (blobs) in csv files | 39,253,186 | <p>Is there any safe way of mixing binary with text data in a (pseudo)csv file?</p>
<p>One naive and partial solution would be:</p>
<ul>
<li>using a compound field separator, made of more than one character (e.g. the <code>\a\b</code> sequence for example)</li>
<li>saving each field as either text or as binary data w... | 0 | 2016-08-31T15:07:30Z | 39,253,320 | <p>If you need everything in a single file, just use one of the methods to encode binary as printable ASCII, and add that results to the CSV vfieds (letting the CSV module add and escape quotes as needed).</p>
<p>One such method is <code>base64</code> - but even on Python's base64 codec, there are more efficient codec... | 2 | 2016-08-31T15:14:35Z | [
"python",
"csv",
"blob",
"binaryfiles",
"export-to-csv"
] |
How to prevent the left x axis from extending to the right x axis in matplotlib? | 39,253,464 | <p>I'm trying to create two histograms next to each other. My problem is the <code>x</code> labels for the left one is extending to the one on the right as shown below:
<a href="http://i.stack.imgur.com/oiosk.png" rel="nofollow"><img src="http://i.stack.imgur.com/oiosk.png" alt="enter image description here"></a></p>
... | 1 | 2016-08-31T15:22:00Z | 39,253,748 | <p>The issue is that your first subplot added with <code>ax1 = fig.add_subplot(1, 1, 1)</code> will fill the entire figure. The second subplot <code>ax2 = fig.add_subplot(1, 2, 2)</code> will span the right hand side, as if there was a first subplot to the left (which there isn't). What you should do if you want to ha... | 3 | 2016-08-31T15:37:15Z | [
"python",
"matplotlib",
"histogram"
] |
Python/Selenium, how to access html list without id, but has mutlitple list of same class on page | 39,253,578 | <p>I am new to Selenium and was wondering how to correctly find items in the html list below. The issue I am having is the html list does not have an 'id' directly, it is in a 'span' a couple of lines above. The page has a few of these an they all have the same class "selectUL". In this example case it is the "lang"... | 1 | 2016-08-31T15:27:53Z | 39,257,225 | <p>I think the easier way to do this is to look for <code>class="sel"</code> on the <code>LI</code>. That seems to indicate which option is selected. From there, you can grab the <code>A</code> inside and then the text inside the <code>A</code>. You can use a CSS Selector to find this element using "li.sel > a" then gr... | 1 | 2016-08-31T19:05:54Z | [
"python",
"selenium-webdriver"
] |
Scikit SVM error: X.shape[1] = 1 should be equal to 2 | 39,253,651 | <p>I am trying to use Scikit to train 2 features called: x1 and x2. Both these arrays are shape <code>(490,1)</code>. In order to pass in one <code>X</code> argument into <code>clf.fit(X,y)</code>, I used <code>np.concatenate</code> to produce an array shape <code>(490,2)</code>. The label array is composed of 1's and ... | 0 | 2016-08-31T15:31:37Z | 39,254,138 | <p>It's difficult to say without having the concrete values of <code>int_x</code>, <code>int_x2</code> and <code>close</code>. Indeed, if I try with <code>int_x</code>, <code>int_x2</code> and <code>close</code> randomly constructed as </p>
<pre><code>import numpy as np
from sklearn.svm import SVC
int_x = np.random.... | 0 | 2016-08-31T15:57:45Z | [
"python",
"scikit-learn",
"svm"
] |
Scikit SVM error: X.shape[1] = 1 should be equal to 2 | 39,253,651 | <p>I am trying to use Scikit to train 2 features called: x1 and x2. Both these arrays are shape <code>(490,1)</code>. In order to pass in one <code>X</code> argument into <code>clf.fit(X,y)</code>, I used <code>np.concatenate</code> to produce an array shape <code>(490,2)</code>. The label array is composed of 1's and ... | 0 | 2016-08-31T15:31:37Z | 39,255,194 | <p>I think I understand what was wrong with my code. </p>
<p>First, I should have created another variable, say <code>x</code> that defined the concatenation of <code>int_x</code> and <code>int_x2</code> and is shape: (490,2), which is the same shape as <code>close</code>. This came in handy later.</p>
<p>Next, the <... | 0 | 2016-08-31T17:00:23Z | [
"python",
"scikit-learn",
"svm"
] |
pandas.DataFrame.query keeping original multiindex | 39,253,672 | <p>I have a dataframe with multiindex:</p>
<pre><code>>>> df = pd.DataFrame(np.random.randint(0,5,(6, 2)), columns=['col1','col2'])
>>> df['ind1'] = list('AAABCC')
>>> df['ind2'] = range(6)
>>> df.set_index(['ind1','ind2'], inplace=True)
>>> df
col1 col2
ind1 i... | 2 | 2016-08-31T15:33:04Z | 39,253,751 | <p><code>df.loc[A]</code> returns you a DF (or a "view") with a regular ("single") index:</p>
<pre><code>In [12]: df.loc['A']
Out[12]:
col1 col2
ind2
0 1 1
1 0 3
2 1 2
</code></pre>
<p>so <code>.query()</code> will be applied on that DF with a regular index...</p>
| 1 | 2016-08-31T15:37:28Z | [
"python",
"pandas",
"dataframe",
"multi-index"
] |
Axis numerical offset in matplotlib | 39,253,742 | <p>I'm plotting something with matplotlib and it looks like this:</p>
<p><a href="http://i.stack.imgur.com/dvfOn.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/dvfOn.jpg" alt="enter image description here"></a></p>
<p>I can't seem to figure out why the x-axis is offset like it is...It looks like it's saying, ... | 0 | 2016-08-31T15:36:55Z | 39,253,913 | <p>You need to <code>import</code> certain formatters from <code>matplotlib.ticker</code>. Here is the <a href="http://matplotlib.org/api/ticker_api.html" rel="nofollow">full documentation to ticker</a></p>
<pre><code>from matplotlib.ticker import ScalarFormatter, FormatStrFormatter
ax.xaxis.set_major_formatter(Format... | 1 | 2016-08-31T15:45:10Z | [
"python",
"matplotlib",
"plot",
"axes",
"graphing"
] |
Axis numerical offset in matplotlib | 39,253,742 | <p>I'm plotting something with matplotlib and it looks like this:</p>
<p><a href="http://i.stack.imgur.com/dvfOn.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/dvfOn.jpg" alt="enter image description here"></a></p>
<p>I can't seem to figure out why the x-axis is offset like it is...It looks like it's saying, ... | 0 | 2016-08-31T15:36:55Z | 39,277,642 | <p>If you don't want to play the formatting game and would rather just display values directly in MHz, then you could simply rescale your data to be in MHz instead of Hz. Something like</p>
<pre><code>data['x'] /= 1000
</code></pre>
<p>and then add the 'MHz' to your axis label.</p>
| 0 | 2016-09-01T17:31:14Z | [
"python",
"matplotlib",
"plot",
"axes",
"graphing"
] |
Storing pandas dataframe in a local machine | 39,254,012 | <p>I have a pandas dataframe in the following format:</p>
<pre><code> File Hour
test1 0
test2 1
test1 1
</code></pre>
<p>I am trying to convert it to json and then store it in a local file location using the below command:</p>
<pre><code>df1.to_json("\home\user1\Desktop\jso... | -2 | 2016-08-31T15:50:52Z | 39,254,473 | <p>You can try to find your CSV file (if it was successfully written to disk, otherwise please post a full error stack) this way:</p>
<pre><code>In [40]: fn = '/home/user1/Desktop/jsonfiles/df1.json'
In [41]: df.to_json(fn)
In [42]: f = open(fn)
In [43]: import os
In [44]: print(os.path.abspath(f.name))
C:\temp\aa... | 0 | 2016-08-31T16:16:28Z | [
"python",
"pandas",
"dataframe"
] |
How to write common implementation of __str__ method for all my models in Django? | 39,254,057 | <p>I want all my models to override <code>__str__</code> method in similar fashion:</p>
<pre><code>class MyModel1(models.Model):
name = models.CharField(max_length=255)
def __init__(self):
self.to_show = 'name'
def _show(self):
if hasattr(self,self.to_show):
return str(getattr... | 1 | 2016-08-31T15:53:12Z | 39,254,097 | <p>You need to create an <a href="https://docs.djangoproject.com/en/1.10/topics/db/models/#abstract-base-classes" rel="nofollow"><em><code>abstract</code> model</em></a>:</p>
<pre><code>class ShowModel(models.Model):
name = models.CharField(max_length=255)
def __init__(self):
self.to_show = 'name'
... | 1 | 2016-08-31T15:55:23Z | [
"python",
"django",
"inheritance",
"django-models",
"abstract"
] |
python xarray indexing/slicing very slow | 39,254,093 | <p>I'm currently processing some ocean model outputs. At each time step, it has 42*1800*3600 grid points.</p>
<p>I found that the bottelneck in my program is the slicing, and calling xarray_built in method to extract the values. And what's more interesting, same syntax sometimes require a vastly differnt amount of tim... | 1 | 2016-08-31T15:55:07Z | 39,262,154 | <p>When you index a variable loaded from a netCDF file, xarray doesn't load it into memory immediately. Instead, we create a lazy array that supports any number of further differed indexing operations. This is true even if you aren't using <a href="http://dask.pydata.org/" rel="nofollow">dask.array</a> (triggered by se... | 1 | 2016-09-01T03:15:22Z | [
"python",
"numpy",
"netcdf",
"python-xarray"
] |
Posting XML using python requests | 39,254,125 | <p>I have the following code that posts xml to teamcity to create a new VCS root:</p>
<pre><code>def addVcsRoot(vcsRootId, vcsRootName, projectId, projectName, buildName, repoId, teamAdminUser, teamAdminPass):
headers = {'Content-type': 'application/xml'}
data = ("<?xml version=\"1.0\" encoding=\"UTF-8\" ... | 0 | 2016-08-31T15:57:08Z | 39,254,539 | <p>I am not going to rewrite it all but using str.format, kwargsa and triple quoted a string will make the code a lot less cluttered:</p>
<pre><code>def addVcsRoot(**kwargs):
headers = {'Content-type': 'application/xml'}
data = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<vcs-r... | 0 | 2016-08-31T16:20:01Z | [
"python",
"xml",
"post",
"teamcity",
"python-requests"
] |
Validating that all components required for an object to exist are present | 39,254,149 | <p>I need to write a script that gets a list of components from an external source and based on a pre-defined list it validates whether the service is complete. This is needed because the presence of a single component doesn't automatically imply that the service is present - some components are pre-installed even when... | -1 | 2016-08-31T15:58:18Z | 39,254,265 | <pre><code># Components that make up a complete service
serviceComponents = ['A','B']
# Input from JSON
data = ['B','A','C']
if all(item in data for item in serviceComponents):
print("All required components are present")
</code></pre>
| 1 | 2016-08-31T16:03:49Z | [
"python"
] |
Validating that all components required for an object to exist are present | 39,254,149 | <p>I need to write a script that gets a list of components from an external source and based on a pre-defined list it validates whether the service is complete. This is needed because the presence of a single component doesn't automatically imply that the service is present - some components are pre-installed even when... | -1 | 2016-08-31T15:58:18Z | 39,254,293 | <p><a href="https://docs.python.org/2/library/stdtypes.html#set" rel="nofollow"><strong>Built-in Set</strong></a> would serve for you, use <a href="https://docs.python.org/2/library/stdtypes.html#set.issubset" rel="nofollow">set.issubset</a> to identify that your required service components is subset of input data:</p>... | 1 | 2016-08-31T16:05:11Z | [
"python"
] |
Validating that all components required for an object to exist are present | 39,254,149 | <p>I need to write a script that gets a list of components from an external source and based on a pre-defined list it validates whether the service is complete. This is needed because the presence of a single component doesn't automatically imply that the service is present - some components are pre-installed even when... | -1 | 2016-08-31T15:58:18Z | 39,254,305 | <p>You could do it a few different ways:</p>
<pre><code>set(serviceComponents) <= set(data)
set(serviceComponents).issubset(data)
all(c in data for c in serviceComponents)
</code></pre>
<p>You can make it shorter, but you lose readability. What you have now is probably fine. I'd go with the first approach personal... | 1 | 2016-08-31T16:05:37Z | [
"python"
] |
Replicate a dataset with dask to all workers | 39,254,182 | <p>I am using dask with distributed scheduler. I am trying to replicate a dataset read through csv on s3 to all worker nodes. Example:</p>
<pre><code>from distributed import Executor
import dask.dataframe as dd
e= Executor('127.0.0.1:8786',set_as_default=True)
df = dd.read_csv('s3://bucket/file.csv', blocksize=None) ... | 0 | 2016-08-31T15:59:32Z | 39,255,082 | <p>This was a bug and has been resolved in <a href="https://github.com/dask/distributed/pull/473" rel="nofollow">https://github.com/dask/distributed/pull/473</a></p>
| 0 | 2016-08-31T16:52:35Z | [
"python",
"dask"
] |
Calculating mean for sub-set of dataframe based on unique row names | 39,254,203 | <p>I have a dataframe which looks like follows,</p>
<pre><code> df.head()
Sym P1 P2 P3 P4 P5 B1 B2 B3 B4 B5
AA 7.86 8.86 9.86 10.86 11.86 0.7768 1.7768 2.7768 3.7768 4.7768
AA 7.86 8.86 9.86 10.86 11.86 0.8664 1.8664 2.8664 3.8664 4.8664
AA 7.86 8.86 9.86 10.86 ... | 1 | 2016-08-31T16:00:29Z | 39,254,256 | <p>Use <code>filter</code> and <code>groupby</code></p>
<pre><code>transformed = df.filter(like='B').groupby(df.Sym).transform(np.mean)
df.loc[:, df.columns.str.contains('B')] = transformed
df
</code></pre>
<p><a href="http://i.stack.imgur.com/ZR3gL.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZR3gL.png" al... | 1 | 2016-08-31T16:02:59Z | [
"python",
"pandas",
"numpy"
] |
What is the most pythonic way to rebase prices based on a level of a multi index DataFrame? | 39,254,229 | <p>I have a mulit-index DataFrame that looks like this:</p>
<pre><code>In[114]: cdm
Out[114]:
Last TD
Date Ticker
1983-03-30 CLM83 29.40 44
CLN83 29.35 76
CLQ83 29.20 105
CLU83 28.95 139
CLV83 28.95 167
CLX... | 2 | 2016-08-31T16:01:35Z | 39,254,875 | <h3>Setup</h3>
<pre><code>from StringIO import StringIO
import pandas as pd
import numpy as np
text = """Date Ticker Last TD
1983-03-30 CLM83 29.40 44
1983-03-30 CLN83 29.35 76
1983-03-30 CLQ83 29.20 105
1983-03-30 CLU83 28.95 139
1983-03-30 CLV83 28.95 167
1983-03-30 CLX83 28.90 197
198... | 1 | 2016-08-31T16:40:19Z | [
"python",
"pandas",
"dataframe",
"multi-index",
"rebasing"
] |
How to use rmagic in Azure Notebooks? | 39,254,231 | <p>I am trying to get some data out of R snippet to Azure Python 3 Jupyter notebook (hosting is available for free at <a href="http://notebooks.azure.com" rel="nofollow">http://notebooks.azure.com</a>).</p>
<p>I tried the following in Python 3 notebook:</p>
<pre><code>%load_ext rmagic
</code></pre>
<p>then tried to ... | 0 | 2016-08-31T16:01:39Z | 39,268,025 | <p>@DmitryNogin, I reproduced the issue successfully. And according to the descprition below from <a href="https://ipython.org/ipython-doc/2/config/extensions/rmagic.html" rel="nofollow">here</a>, you need to use <code>%load_ext rpy2.ipython</code> instead of <code>%load_ext rmagic</code> in jupyter notebook now.</p>
... | 1 | 2016-09-01T09:40:59Z | [
"python",
"azure",
"jupyter"
] |
Finding the occurrence and position of a character in python | 39,254,319 | <p>I have a variable (var) with ids
I am interested in finding out the position of last occurrence of Z</p>
<p>I have tried to convert it to an array with their positions</p>
<pre><code> zf1=np.where(df2['Var']=="Z")
</code></pre>
<p>This will give me the result as </p>
<pre><code> (array([4,5,6,7,8,9,10,1... | 1 | 2016-08-31T16:06:32Z | 39,254,981 | <p><strong><em>Get Index values</em></strong></p>
<pre><code>df2.index[df2.Var.eq('Z') & df2.Var.ne(df2.Var.shift(-1))]
</code></pre>
<p><strong><em>Filter <code>df2</code></em></strong></p>
<pre><code>df2[df2.Var.eq('Z') & df2.Var.ne(df2.Var.shift(-1))]
</code></pre>
| 0 | 2016-08-31T16:46:11Z | [
"python",
"pandas",
"position",
"np",
"find-occurrences"
] |
Using PIL to open an image with a palette and save that image with the same palette | 39,254,339 | <p>So I am trying to convert a bmp to a NumPy array, store the array somewhere, and then convert it back into a bmp image at a later time. </p>
<pre><code>bmp = Image.open(fn_bmp)
data = np.array(bmp.convert('P', palette=Image.WEB))
</code></pre>
<p>This data is stored in another file temporarily and then I go to ret... | 0 | 2016-08-31T16:07:49Z | 39,258,561 | <p>In this case <code>Image.fromarray(data)</code> returns a greyscale image. When you convert this image to a different image mode it will remain greyscale!</p>
<p>Instead you have to supply color information in the form of a palette:</p>
<pre><code># first part
bmp = Image.open(fn_bmp)
bmp_P_web = bmp.convert('P', ... | 0 | 2016-08-31T20:35:10Z | [
"python",
"image",
"numpy",
"bitmap",
"python-imaging-library"
] |
SQLite3 & Py: Error Inserting hyphenated string | 39,254,365 | <p>I am doing a simple script in which Python reads a bunch of tab-separated files, and line by line enters the first item in the line onto an sqlite3 table. The process works well, except for the actual data. The data that is being sent to me is in the format 123-4567890-1234567 (3-7-7). Instead of seeing the full str... | 1 | 2016-08-31T16:09:04Z | 39,254,645 | <p>Bottom line is that you should not be using <code>str.format</code> for this as it is not secure and it is also, in your case, not producing the result you are expecting.</p>
<p>Fortunately, this problem was solved long ago. For you, just change your <code>c.execute</code> line to this:</p>
<pre><code>c.execute("I... | 1 | 2016-08-31T16:26:31Z | [
"python",
"sqlite3",
"insert-into"
] |
TypeError: __init__() takes exactly 1 argument (2 given) | 39,254,432 | <p>I'm trying to run the monasca-persister component in ubuntu, but there is an error with a file related with kafka, my kafka server is running well.</p>
<pre><code>Process Process-2:
commit_timeout=kafka_conf.max_wait_time_seconds)
File "/usr/local/lib/python2.7/dist-packages/monasca_common/kafka/consumer.py", line ... | 0 | 2016-08-31T16:13:40Z | 39,254,567 | <p>The <code>KafkaClient</code> class doesn't take any positional arguments. Pass in configuration as <em>keyword arguments</em>:</p>
<pre><code>self._kafka = kafka.client.KafkaClient(bootstrap_servers=kafka_url)
</code></pre>
<p>See the <a href="http://kafka-python.readthedocs.io/en/master/_modules/kafka/client_asyn... | 1 | 2016-08-31T16:21:52Z | [
"python",
"ubuntu",
"apache-kafka"
] |
Arduino to Python: How to import readings using ser.readline() into a list with a specified starting point? | 39,254,574 | <p>This is quite a specific query so please bear with me.</p>
<p>I have 14 ultrasonic sensors hooked to an Arduino sending live readings to the serial monitor (or Pi when I plug it in) . The readings are sent as follows, <em>with a new line between every 2 digits</em> (except Z). </p>
<blockquote>
<p>Z
62
61
... | 2 | 2016-08-31T16:22:28Z | 39,256,723 | <p>How about this? Note that your checks overallcount<30 and arraycount<15 should really be overallcount<=30 and arraycount<=15.</p>
<pre><code>import serial
ser = serial.Serial('/dev/ttyACM0',115200)
readings = [] # Array to store arrays of readings
reading_id = 1 # Id of current reading
random_lines_exp... | 0 | 2016-08-31T18:36:29Z | [
"python",
"arrays",
"raspberry-pi",
"uart",
"usart"
] |
Fetching live data from website's with continiously updating data | 39,254,581 | <p>I can easily get the data when I put <strong>html = urllib.request.urlopen(req)</strong> inside a while loop, but it takes about 3 seconds to get the data. So I thought, maybe if I put that outside, I can get it faster as it won't have to open the URL everytime, but this throws up an <strong>AttributeError: 'str' ob... | 0 | 2016-08-31T16:23:04Z | 39,254,975 | <p>if you want to fetching live you need to recall url periodically </p>
<pre><code>html = urllib.request.urlopen(req)
</code></pre>
<p>This one should be in a loop.</p>
<pre><code>import os
import urllib
import datetime
from bs4 import BeautifulSoup
import time
def soup():
url = "http://www.investing.com/indi... | 0 | 2016-08-31T16:45:49Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Fetching live data from website's with continiously updating data | 39,254,581 | <p>I can easily get the data when I put <strong>html = urllib.request.urlopen(req)</strong> inside a while loop, but it takes about 3 seconds to get the data. So I thought, maybe if I put that outside, I can get it faster as it won't have to open the URL everytime, but this throws up an <strong>AttributeError: 'str' ob... | 0 | 2016-08-31T16:23:04Z | 39,255,358 | <p>you reassign <code>html</code> to equal the UTF-8 string response then keep calling it like its an <code>IO</code> ... this code does not fetch new data from the server on every loop, <code>read</code> simply reads the bytes from the <code>IO</code> object, it doesnt make a new request.</p>
<p>you can speed up the ... | 0 | 2016-08-31T17:11:58Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
garbage collection in python | 39,254,624 | <p>For the below code, I am not able to clear the memory allocated for 'root' variable evan after 'del root' and gc.collect(). I understand that in python, garbage collection releases automatically. Is there any way I can clear it more?</p>
<pre><code>from __future__ import with_statement
import os
import sys
from mem... | 2 | 2016-08-31T16:25:38Z | 39,255,098 | <p>Unfortunately you can't do much except calling <code>gc.collect()</code> plus you can adopt good practice style like you used <code>del</code> to tell the <code>GC</code> that you don't want it anymore so it will be deleted when <code>GC</code> will come around and do it's job.</p>
<p>You should use <code>numpy</co... | 0 | 2016-08-31T16:53:31Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python sys.executable is empty | 39,254,684 | <p>I am testing out doing some shenanigans with <code>os.execve</code> and virtual environments. I am running into the problem where <code>sys.executable</code> is empty if I replace the current python process with another python subprocess.</p>
<p>The example below shows what's going on (run this inside a python shel... | 0 | 2016-08-31T16:28:24Z | 39,254,880 | <p>Python relies on <code>argv[0]</code> and several environment variables to determine <code>sys.executable</code>. When you pass an empty argv and environment, Python doesn't know how to determine its path. At the very least, you should provide <code>argv[0]</code>:</p>
<pre><code>os.execve('/usr/bin/python', ['/usr... | 1 | 2016-08-31T16:40:40Z | [
"python",
"execve"
] |
How to display images in Django 1.10 | 39,254,698 | <p>i am not good in django, i use Django 1.10 and now i have problem with image displaying. I read in this version some stuff has changed but i don't get it. Here is what i have now:</p>
<p>settings.py:</p>
<pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_DIR = os.path.join(BA... | 0 | 2016-08-31T16:29:09Z | 39,254,728 | <p>You have to put <code><img></code> tag</p>
<pre><code>{% block content%}
{{ car.name }}
<img src="{{ car.photo.url }}">
{% endblock %}
</code></pre>
<p><strong>Update</strong></p>
<pre><code>from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... ... | 4 | 2016-08-31T16:31:02Z | [
"python",
"django"
] |
Pandas - Group/bins of data per longitude/latitude | 39,254,704 | <p>I have a bunch of geographical data as below.
I would like to group the data by bins of .2 degrees in longitude AND .2 degree in latitude.</p>
<p>While it is trivial to do for either latitude or longitude, what is the most appropriate of doing this for both variables?</p>
<pre><code>|User_ID |Latitude |Longitude... | 1 | 2016-08-31T16:29:17Z | 39,277,772 | <p>How about this?</p>
<pre><code>step = 0.2
to_bin = lambda x: np.floor(x / step) * step
df["latbin"] = df.Latitude.map(to_bin)
df["lonbin"] = df.Longitude.map(to_bin)
groups = df.groupby(("latbin", "lonbin"))
</code></pre>
| 1 | 2016-09-01T17:40:15Z | [
"python",
"pandas",
"binning"
] |
How to parse C++ protobuf binary data by python protobuf? | 39,254,706 | <p>I use C++ protobuf to serialize data to string.</p>
<pre><code>/***** cpp code *****/
string serialized_data;
message_cpp.SerializeToString(&serialized_data);
</code></pre>
<p><strong>Question:</strong> can I parse <code>serialized_data</code> in python? and how?</p>
<p>I've tried the following code, but it d... | 0 | 2016-08-31T16:29:36Z | 39,261,223 | <p><code>ParseFromString</code> parses <em>into</em> the object it is called on. It doesn't return anything. Use it like:</p>
<pre><code>message = MyMessage()
message.ParseFromString(data)
print message
</code></pre>
| 2 | 2016-09-01T01:03:59Z | [
"python",
"c++",
"protocol-buffers"
] |
NumPy ndarray broadcasting - shape (X,) vs (X, 1) | 39,254,755 | <p>I have a NumPy <code>ndarray</code> which is shaped (32, 1024) and holds 32 signal measurements which I would like to combine into a single 1024 element long array, with a different weight for each of the 32. I was using <code>numpy.average</code> but my weights are complex and <code>average</code> performs a normal... | 3 | 2016-08-31T16:32:49Z | 39,254,816 | <p>On the question of why <code>(32,)</code> can't broadcast to <code>(32, 1024)</code>, it's because the shapes aren't aligned properly. To put it into a schematic, we have :</p>
<pre><code>weights : 32
data : 32 x 1024
</code></pre>
<p>We need to align the only axis, which is the first axis of <code>we... | 3 | 2016-08-31T16:36:55Z | [
"python",
"numpy",
"multidimensional-array",
"numpy-broadcasting"
] |
Solving polynomials with complex coefficients using sympy | 39,254,827 | <p>I'm very new to python so forgive me if this has a simple fix. I'm trying to solve polynomials with complex coefficients using sympy. I find that I get a blank output if k is 'too complicated'... I'm not quite sure how to define what that means just yet. As a first example consider this fourth order polynomial with ... | 5 | 2016-08-31T16:37:24Z | 40,092,834 | <p>As per the <a href="https://stackoverflow.com/questions/39254827/solving-polynomials-with-complex-coefficients-using-sympy/40092834#comment65851348_39254827">comment</a> of <a href="https://stackoverflow.com/users/6212875/stelios">Stelios</a>, you can use <a href="http://docs.sympy.org/0.7.1/modules/polys/reference.... | 0 | 2016-10-17T18:01:38Z | [
"python",
"numpy",
"math",
"sympy",
"polynomials"
] |
get a pivot from count using a 2d key | 39,254,844 | <p>I've got time series data that I'd like to get a count of actions that happened per day/hour combination</p>
<p>I'm using <code>Counter</code> object to get the counts as I process items line by line</p>
<pre><code> c = Counter()
for line in file
c.update([[yyyymmdd, hh]])
# or c[yyyymmdd,hh] += 1
</cod... | 1 | 2016-08-31T16:38:33Z | 39,260,272 | <p>Here is a naive and non-optimised approach for the pivot based on Counter:</p>
<pre><code>In [1]: from io import StringIO # Py2 from StringIO import StringIO
...: from datetime import datetime
...: from collections import Counter
...: import random
...:
In [2]: data = [] # generate some random data
... | 1 | 2016-08-31T22:55:49Z | [
"python",
"python-2.7"
] |
How to handle multiple inheritance in python when parent init functions accept different numbers of arguments | 39,254,940 | <p>I have a class that inherits from 2 other classes, one of which has accepts an init argument. How do I properly initialize the parent classes?</p>
<p>So far I have:</p>
<pre><code>class A(object):
def __init__(self, arg1):
self.arg1 = arg1
class B(object):
def __init__(self):
pass
class... | 0 | 2016-08-31T16:44:01Z | 39,255,396 | <p>You can call the <code>__init__</code> of the parent classes manually.</p>
<pre><code>class C(A, B):
def __init__(arg1):
A.__init__(self,arg1)
B.__init__(self)
</code></pre>
| 1 | 2016-08-31T17:14:43Z | [
"python",
"multiple-inheritance"
] |
Python Special Colon Inquiry | 39,254,947 | <pre><code>sortedWinnerIndices = winnerIndices[-numActive:][::-1]
</code></pre>
<p>Can someone tell me what is going on here? </p>
<p><code>WinnerIndices</code> is 2048 ints long, Numpy array. I read somewhere that <code>[::-1]</code> reverses the result but I still can't figure out how this function selects a subset... | -1 | 2016-08-31T16:44:27Z | 39,255,019 | <p>Break it up into steps. It's equivalent to:</p>
<pre><code>subset = winnerIndices[-numActive:]
sortedWinnerIndices = subset[::-1]
</code></pre>
<p>The first statement selects the last <code>numActive</code> elements in the array. The second line reverses it. So when you combine them you get the last <code>numActiv... | 1 | 2016-08-31T16:48:19Z | [
"python",
"numpy",
"operator-keyword",
"colon"
] |
Python Special Colon Inquiry | 39,254,947 | <pre><code>sortedWinnerIndices = winnerIndices[-numActive:][::-1]
</code></pre>
<p>Can someone tell me what is going on here? </p>
<p><code>WinnerIndices</code> is 2048 ints long, Numpy array. I read somewhere that <code>[::-1]</code> reverses the result but I still can't figure out how this function selects a subset... | -1 | 2016-08-31T16:44:27Z | 39,255,024 | <pre><code>winnerIndices[-numActive:]
</code></pre>
<p>Above takes a slice from <code>-numActive</code> index to the end of the original list</p>
<pre><code>x[::-1]
</code></pre>
<p>This reverses x</p>
| 1 | 2016-08-31T16:48:30Z | [
"python",
"numpy",
"operator-keyword",
"colon"
] |
Recursion: design a recursive function called replicate_recur which will receive two arguments: | 39,255,069 | <p>The below code is a recursive function which takes two arguments and return something like <code>[5,5,5]</code>.</p>
<pre><code>def recursive(times, data):
if not isinstance(times,int):
raise ValueError("times must be an int")
if not (isinstance(data,int) or isinstance(data, str)):
... | -4 | 2016-08-31T16:51:20Z | 39,255,244 | <p>Let's try to think how we would repeat any data item N times recursively:</p>
<ul>
<li>If <code>times</code> is 0 or less, we return an empty list, as per the requirements.</li>
<li>If <code>times</code> is greater than 0, we return list that has <code>data</code> ones and another <code>times - 1</code> repetitions... | 1 | 2016-08-31T17:03:43Z | [
"python",
"recursion"
] |
Recursion: design a recursive function called replicate_recur which will receive two arguments: | 39,255,069 | <p>The below code is a recursive function which takes two arguments and return something like <code>[5,5,5]</code>.</p>
<pre><code>def recursive(times, data):
if not isinstance(times,int):
raise ValueError("times must be an int")
if not (isinstance(data,int) or isinstance(data, str)):
... | -4 | 2016-08-31T16:51:20Z | 39,255,418 | <p>You can use a list to store the result of current recursive call.</p>
<pre><code>def replicate_recur(times, data, ret=None):
if not ret:
ret = []
ret.append(data)
times -= 1
if not times:
return ret
return replicate_recur(times, data, ret)
</code></pre>
| 0 | 2016-08-31T17:16:23Z | [
"python",
"recursion"
] |
Execute python 3 not python 2 | 39,255,099 | <p>I have installed python 2 after installing python 3.And now when I executing my python file by clicking on file (not by cmd) its run python 2 ,but I want python 3.
I have tried script:</p>
<pre><code>import sys
print (sys.version)
</code></pre>
<p>output was:</p>
<pre><code>2.7.11
</code></pre>
<p>Can someone he... | 0 | 2016-08-31T16:53:35Z | 39,255,365 | <p>If the current default windows application for <code>.py</code> files is currently <code>python2</code> (i.e. <code>C:\python27\python.exe</code>) and not the new <code>py.exe</code> launcher, you can just change the default windows application for the file type. Right-click on file -> properties -> click the chang... | 1 | 2016-08-31T17:12:22Z | [
"python",
"python-2.7",
"python-3.4"
] |
Execute python 3 not python 2 | 39,255,099 | <p>I have installed python 2 after installing python 3.And now when I executing my python file by clicking on file (not by cmd) its run python 2 ,but I want python 3.
I have tried script:</p>
<pre><code>import sys
print (sys.version)
</code></pre>
<p>output was:</p>
<pre><code>2.7.11
</code></pre>
<p>Can someone he... | 0 | 2016-08-31T16:53:35Z | 39,255,421 | <p>On <code>cmd</code> you can do <code>py -3</code> for python 3 and <code>py -2</code> for 2 but for click-starting the simplest way is to include a line <code>#! python2</code> or <code>#! python3</code>as first line in file.</p>
<p>You were on the right trach - it is mentioned in <a href="https://www.python.org/de... | 0 | 2016-08-31T17:16:31Z | [
"python",
"python-2.7",
"python-3.4"
] |
Execute python 3 not python 2 | 39,255,099 | <p>I have installed python 2 after installing python 3.And now when I executing my python file by clicking on file (not by cmd) its run python 2 ,but I want python 3.
I have tried script:</p>
<pre><code>import sys
print (sys.version)
</code></pre>
<p>output was:</p>
<pre><code>2.7.11
</code></pre>
<p>Can someone he... | 0 | 2016-08-31T16:53:35Z | 39,255,447 | <p>Assuming you have python3 installed, you can us <a href="https://docs.python.org/3/using/scripts.html" rel="nofollow">virtual environment mechanisms</a> built into python3 to prevent errors just like this. </p>
<p>I saw in the comments you are using Windows, so the following steps to ensure that you are using the i... | 0 | 2016-08-31T17:17:33Z | [
"python",
"python-2.7",
"python-3.4"
] |
How can I store many values in 1 variable, in python? | 39,255,249 | <p>I am doing a 10 x 10 stratified shuffle split cross validation.
As you can see in my code, at the end I get 10 results. I want the mean of these 10 results. So I added a variable: xSSSmean. But this one changes in every loop. So at the end it would have just stored the las value. So, how can I make it store the 10 v... | -1 | 2016-08-31T17:04:24Z | 39,256,774 | <pre><code>xSSSmean = [] #I create an empty list
for i in range(10):
sss = StratifiedShuffleSplit(y, 10, test_size=0.1, random_state=0)
scoresSSS = cross_validation.cross_val_score(clf, x, y , cv=sss)
print("Accuracy x fold SSS_RF: %0.2f (+/- %0.2f)" % (scoresSSS.mean(), scoresSSS.std()* 2)) #2 decimales
... | 2 | 2016-08-31T18:38:44Z | [
"python",
"numpy",
"scikit-learn"
] |
Add a panel to bar chart in matplotlib | 39,255,265 | <p>How can I add a panel containing (improvement percentage for each algorithm) to this bar chart? It should, for example, be located in top right-corner of the chart. I want to do this in order to be easier for the reader to see how much improvement each algorithm has compared to its non-greedy version.</p>
<p>The pa... | 1 | 2016-08-31T17:05:05Z | 39,266,707 | <p>add the following code just before <code>autolabel(rects1)</code> line. (I use python 3)</p>
<p>I used <a href="http://stackoverflow.com/questions/7045729/automatically-position-text-box-in-matplotlib">automatically position text box in matplotlib</a></p>
<pre><code>from matplotlib.offsetbox import AnchoredText
de... | 1 | 2016-09-01T08:42:52Z | [
"python",
"matplotlib",
"bar-chart"
] |
How to run Skulpt.org on localhost / local server by XAMPP | 39,255,274 | <p>Hi i want to measure execution time of basic operations like range etc. on Skulpt(Python in browser)
I know thath Skulpt.org have interactive console online, but the thing is that I want to do it on my local machine, on my local server created by XAMPP.</p>
<p>I have this simple code:</p>
<pre><code>import time
t... | 1 | 2016-08-31T17:05:46Z | 39,280,202 | <p>Here is answer.</p>
<pre><code><html>
<head>
<meta charset="utf-8">
<title>Skulpt</title>
<script src="skulpt.min.js" type="text/javascript"></script>
<script src="skulpt-stdlib.js" type="text/javascript"></script>
</head>
<body>
</body> ... | 0 | 2016-09-01T20:14:54Z | [
"python",
"server",
"skulpt"
] |
Inserting a row into a pandas dataframe based on row value? | 39,255,292 | <p>I have a DataFrame:</p>
<pre><code>df = pd.DataFrame({'B':[2,1,2],'C':['a','b','a']})
B C
0 2 'a'
1 1 'b'
2 2 'a'
</code></pre>
<p>I want to insert a row above any occurrence of 'b', that is a duplicate of that row but with 'b' changed to 'c', so I end up with this:</p>
<pre><code> B C
0 2 'a'
1 1 'b'
1 1 'c'
... | 4 | 2016-08-31T17:07:10Z | 39,255,882 | <p>Working at NumPy level, here's a vectorized approach -</p>
<pre><code>arr = df.values
idx = np.flatnonzero(df.C=='b')
newvals = arr[idx]
newvals[:,df.columns.get_loc("C")] = 'c'
out = np.insert(arr,idx+1,newvals,axis=0)
df_index = np.insert(np.arange(arr.shape[0]),idx+1,idx,axis=0)
df_out = pd.DataFrame(out,index=d... | 1 | 2016-08-31T17:42:20Z | [
"python",
"pandas",
"numpy",
"dataframe",
"insert"
] |
Inserting a row into a pandas dataframe based on row value? | 39,255,292 | <p>I have a DataFrame:</p>
<pre><code>df = pd.DataFrame({'B':[2,1,2],'C':['a','b','a']})
B C
0 2 'a'
1 1 'b'
2 2 'a'
</code></pre>
<p>I want to insert a row above any occurrence of 'b', that is a duplicate of that row but with 'b' changed to 'c', so I end up with this:</p>
<pre><code> B C
0 2 'a'
1 1 'b'
1 1 'c'
... | 4 | 2016-08-31T17:07:10Z | 39,255,896 | <p>Here's one way of doing it:</p>
<pre><code>duplicates = df[df['C'] == 'b'].copy()
duplicates['C'] = 'c'
df.append(duplicates).sort_index()
</code></pre>
| 3 | 2016-08-31T17:43:06Z | [
"python",
"pandas",
"numpy",
"dataframe",
"insert"
] |
When am I supposed to use del in python? | 39,255,371 | <p>So I am curious lets say I have a class as follows</p>
<pre><code>class myClass:
def __init__(self):
parts = 1
to = 2
a = 3
whole = 4
self.contents = [parts,to,a,whole]
</code></pre>
<p>Is there any benifit of adding lines </p>
<pre><code>del parts
del to
del a
del whol... | 3 | 2016-08-31T17:12:54Z | 39,255,472 | <p>Never, unless you are very tight on memory and doing something very bulky. If you are writing usual program, garbage collector should take care of everything.</p>
<p>If you are writing something bulky, you should know that <code>del</code> does not delete the object, it just dereferences it. I.e. variable no longer... | 8 | 2016-08-31T17:19:12Z | [
"python",
"memory-management"
] |
When am I supposed to use del in python? | 39,255,371 | <p>So I am curious lets say I have a class as follows</p>
<pre><code>class myClass:
def __init__(self):
parts = 1
to = 2
a = 3
whole = 4
self.contents = [parts,to,a,whole]
</code></pre>
<p>Is there any benifit of adding lines </p>
<pre><code>del parts
del to
del a
del whol... | 3 | 2016-08-31T17:12:54Z | 39,255,573 | <p>One use is to delete specific keys from a dictionary.</p>
<pre><code>>>>> food = {"apple": True, "banana": False}
>>>> del food['banana']
>>>> import json
>>>> json.dumps(food)
'{"apple": true}'
</code></pre>
<p>I use it all the time for cleaning up dictionaries befo... | -1 | 2016-08-31T17:24:57Z | [
"python",
"memory-management"
] |
SqlAlchemy commit after using update() function without using a session | 39,255,405 | <p>My selections work but my updates and deletes do not.</p>
<pre><code>db_jb = create_engine(jb)
self.jobs = Table('Job', MetaData(jb), autoload=True)
# select - works
ss = select(self.jobs).where(
self.jobs.c.job_guid == jobGuid
).limit(1)
rs = ss.execute()
rows = [r for r in rs]
rs.close()
# update - does not w... | 0 | 2016-08-31T17:15:28Z | 39,256,728 | <p>Did you try to execute <code>COMMIT</code> as a raw statement, like</p>
<pre><code>db_jb.execute('COMMIT')
</code></pre>
<p>You could also put <code>db_jb.execute('BEGIN')</code> just before <code>ss = ...</code> to explicitly start a transaction</p>
| 1 | 2016-08-31T18:36:48Z | [
"python",
"mysql",
"session",
"sqlalchemy",
"commit"
] |
Python CGI os.system causing malformed header | 39,255,498 | <p>I am running Apache/2.4.10 (Raspbian) and I am using python for CGI.
But when I try to use os.system in simple code I get this malformed header error:</p>
<pre><code>[Wed Aug 31 17:10:05.715740 2016] [cgid:error] [pid 3103:tid 1929376816] [client 192.168.0.106:59277] malformed header from script'play.cgi': Bad head... | 1 | 2016-08-31T17:20:21Z | 39,255,969 | <p>To see why the problem happened, try launching your script</p>
<pre><code>python webls.py > output
</code></pre>
<p>And than open <code>output</code> with some text editor. You will notice that your <code>Content-type: text/html</code> ended up being in the bottom of the file, which, of course, is wrong.</p>
<... | 1 | 2016-08-31T17:47:20Z | [
"python",
"apache",
"cgi"
] |
How to determine the dimensions of a mix of lists and arrays? | 39,255,523 | <p>Consider an object that is a list of arrays: </p>
<p><code>a=[array([1,2,3]),array(2,5,10,20)]</code></p>
<p>In its own funny way, this thing has two dimensions. The list itself is one dimension, and it contains objects which are 1D. Is there an easy way to distinguish between <code>a</code> above and a list like ... | 1 | 2016-08-31T17:21:57Z | 39,255,636 | <p>Here's my function:</p>
<pre><code>def dimens(x):
s=shape(x)
if len(s)==0:
return 0 #the input was a scalar
s2=shape(x[0])
if len(s2)==0:
return 1 #each element of the list was a scalar
else:
#each element of the list was a vector or array
if len(s2)==1:
... | 0 | 2016-08-31T17:28:46Z | [
"python",
"arrays",
"list",
"numpy"
] |
How to determine the dimensions of a mix of lists and arrays? | 39,255,523 | <p>Consider an object that is a list of arrays: </p>
<p><code>a=[array([1,2,3]),array(2,5,10,20)]</code></p>
<p>In its own funny way, this thing has two dimensions. The list itself is one dimension, and it contains objects which are 1D. Is there an easy way to distinguish between <code>a</code> above and a list like ... | 1 | 2016-08-31T17:21:57Z | 39,255,662 | <p>You can use <strong>isinstance</strong> method to distinguish between the two arrays</p>
<p>Lets consider the first list </p>
<pre><code>a = [1,2,3]
</code></pre>
<p>Here the first element is an integer hence <code>isinstance(a[0],int)</code> will return true</p>
<p>For the second array <code>b = [[1,2][3,4]]</c... | 0 | 2016-08-31T17:30:10Z | [
"python",
"arrays",
"list",
"numpy"
] |
How to determine the dimensions of a mix of lists and arrays? | 39,255,523 | <p>Consider an object that is a list of arrays: </p>
<p><code>a=[array([1,2,3]),array(2,5,10,20)]</code></p>
<p>In its own funny way, this thing has two dimensions. The list itself is one dimension, and it contains objects which are 1D. Is there an easy way to distinguish between <code>a</code> above and a list like ... | 1 | 2016-08-31T17:21:57Z | 39,255,678 | <pre><code>def dimens(l):
try:
size = len(l)
except TypeError: # not an iterable
return 0
else:
if size: # non-empty iterable
return 1 + max(map(dimens, l))
else: # empty iterable
return 1
print(dimens([[1,2,3],[2,5,10,[1,2]]]))
print(dimens(np.zeros(... | 2 | 2016-08-31T17:30:59Z | [
"python",
"arrays",
"list",
"numpy"
] |
Conda setuptools install changes shebangs to default python install | 39,255,544 | <p>I'm having an issue where packages installed via setuptools to python anaconda have shebangs rewritten to the wrong location.</p>
<p>I have installed python anaconda and setuptools package. I have verified that python executable points to the anaconda executable</p>
<pre><code>grant@DevBox2:/opt/content-analysis$ ... | 1 | 2016-08-31T17:23:14Z | 39,257,166 | <p>I finally figured out what has been causing all my issues getting python and dependencies properly installed:</p>
<p>Whenever <code>sudo</code> is invoked before an executable, in Debian the $PATH variable is automatically changed to a secure path lookup. Here is a demonstration:</p>
<pre><code>grant@DevBox2:/opt/... | 1 | 2016-08-31T19:02:52Z | [
"python",
"anaconda",
"setuptools",
"conda"
] |
Django ORM query with multiple joins | 39,255,696 | <p>I've been trying to come up with the django version of this query and I can't seem to get it.</p>
<pre><code>SELECT
*
FROM answer a
LEFT JOIN groups g
ON a.group_id = g.id
LEFT JOIN group_permissions gp
ON g.id = gp.group_id
WHERE gp.user_id = '77777';
</code></pre>
<p>I've been trying something like this:</... | 0 | 2016-08-31T17:31:45Z | 39,260,013 | <p>There is an implicit association django creates for you: <code>group_grouppermissions_set</code>. You can read about it in <a href="https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_one/" rel="nofollow">docs</a> about many-to-one relationship.</p>
<p>So your query will look like something like this:<... | 0 | 2016-08-31T22:31:48Z | [
"python",
"mysql",
"django",
"join",
"orm"
] |
How to serve no more that one HTTP request in python? | 39,255,865 | <p>I have a simple HTTP server setup like <a href="http://stackoverflow.com/a/11769969">this one</a>. It processes a slow 40 second request to open and then close gates (real metallic gates). If second HTTP query is made during execution of the first one, it is placed in queue and then executed after first run. I don't... | 0 | 2016-08-31T17:41:16Z | 39,255,926 | <p>You need to follow a different strategy designing your server service. You need to keep the state of the door either in memory or in a database. Then, each time you receive a request to do something on the door, you check the current state of the door in your persistence, and then you execute the action if it is p... | 1 | 2016-08-31T17:44:52Z | [
"python"
] |
How to serve no more that one HTTP request in python? | 39,255,865 | <p>I have a simple HTTP server setup like <a href="http://stackoverflow.com/a/11769969">this one</a>. It processes a slow 40 second request to open and then close gates (real metallic gates). If second HTTP query is made during execution of the first one, it is placed in queue and then executed after first run. I don't... | 0 | 2016-08-31T17:41:16Z | 39,256,041 | <p>In general, the idea you're looking for is called request <em>throttling</em>. There are lots of implementations of this kind of thing which shouldn't be hard to dig up out there on the Web: here's one for Flask, my microframework of choice - <a href="https://flask-limiter.readthedocs.io/en/stable/" rel="nofollow">h... | 0 | 2016-08-31T17:51:32Z | [
"python"
] |
How to serve no more that one HTTP request in python? | 39,255,865 | <p>I have a simple HTTP server setup like <a href="http://stackoverflow.com/a/11769969">this one</a>. It processes a slow 40 second request to open and then close gates (real metallic gates). If second HTTP query is made during execution of the first one, it is placed in queue and then executed after first run. I don't... | 0 | 2016-08-31T17:41:16Z | 39,267,163 | <p>'request_queue_size' seems to have no effect.
The solution was to make server multithreaded, and implement locking variable 'busy':</p>
<pre><code>from socketserver import ThreadingMixIn
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
from gpiozero import DigitalOutputDevice
import logging
fr... | 1 | 2016-09-01T09:03:01Z | [
"python"
] |
Subsetting python list into positive/negative movements/trends | 39,255,870 | <p>Sorry for creating this question but I have been stuck on this question for a while.</p>
<p>Basically I'm trying to take a list:</p>
<pre><code>numbers=[1, 2, -1, -2, 4, 5]
</code></pre>
<p>And subset this list into a list of list that display positive/negative movements (or trends)</p>
<p>The end result is to h... | 1 | 2016-08-31T17:41:39Z | 39,256,098 | <p>If change in trends always go through the sign change, you can "group" items based on a sign using <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby()</code></a>:</p>
<pre><code>>>> from itertools import groupby
>>>
>>> [li... | 1 | 2016-08-31T17:55:12Z | [
"python",
"list",
"python-2.7",
"trend"
] |
Subsetting python list into positive/negative movements/trends | 39,255,870 | <p>Sorry for creating this question but I have been stuck on this question for a while.</p>
<p>Basically I'm trying to take a list:</p>
<pre><code>numbers=[1, 2, -1, -2, 4, 5]
</code></pre>
<p>And subset this list into a list of list that display positive/negative movements (or trends)</p>
<p>The end result is to h... | 1 | 2016-08-31T17:41:39Z | 39,256,124 | <p>In python, one tends not to use the actual indexes in a list very often. Try a for-loop instead, plus a check to see whether the trend changed or not (this treats zero as a distinct trend from positive or negative - you can pretty simply change <code>same_direction</code> to group it one way or the other):</p>
<pre... | 1 | 2016-08-31T17:56:34Z | [
"python",
"list",
"python-2.7",
"trend"
] |
Subsetting python list into positive/negative movements/trends | 39,255,870 | <p>Sorry for creating this question but I have been stuck on this question for a while.</p>
<p>Basically I'm trying to take a list:</p>
<pre><code>numbers=[1, 2, -1, -2, 4, 5]
</code></pre>
<p>And subset this list into a list of list that display positive/negative movements (or trends)</p>
<p>The end result is to h... | 1 | 2016-08-31T17:41:39Z | 39,256,140 | <p>This is what I came up with. It is close to what you have but a little easier to read. I avoid having to increment the index counter <code>i</code> as much which is <em>probably</em> where you went wrong.</p>
<pre><code>n= [1,2,-1,-2,4,5]
out=[]
i=1
tmp=[n[0]]
while i < len(n):
if n[i] >= 0 and tmp[-1... | 0 | 2016-08-31T17:57:28Z | [
"python",
"list",
"python-2.7",
"trend"
] |
Subsetting python list into positive/negative movements/trends | 39,255,870 | <p>Sorry for creating this question but I have been stuck on this question for a while.</p>
<p>Basically I'm trying to take a list:</p>
<pre><code>numbers=[1, 2, -1, -2, 4, 5]
</code></pre>
<p>And subset this list into a list of list that display positive/negative movements (or trends)</p>
<p>The end result is to h... | 1 | 2016-08-31T17:41:39Z | 39,256,177 | <p>Here is a way to re-write this:</p>
<pre><code>
numbers=[1,2,-1,-2,4,5]
direction = True # positive or negative
prevdirection = True
res = [[numbers[0]]]
for previtem, item in zip(numbers[:-1], numbers[1:]):
direction = True if item - previtem > 0 else False
if direction != prevdirection:
res.a... | 2 | 2016-08-31T17:59:45Z | [
"python",
"list",
"python-2.7",
"trend"
] |
Subsetting python list into positive/negative movements/trends | 39,255,870 | <p>Sorry for creating this question but I have been stuck on this question for a while.</p>
<p>Basically I'm trying to take a list:</p>
<pre><code>numbers=[1, 2, -1, -2, 4, 5]
</code></pre>
<p>And subset this list into a list of list that display positive/negative movements (or trends)</p>
<p>The end result is to h... | 1 | 2016-08-31T17:41:39Z | 39,256,837 | <p>Here is my solution:</p>
<pre><code>numbers = [1,2,-1,-2,4,5, 3, 2]
subset = []
subset_list = []
subset.append(numbers[0])
forward = 1
for i in range(0, len(numbers) - 1):
if ( forward == 1 ):
if numbers[i] <= numbers[i+1]:
subset.append(numbers[i+1])
else:
subset_... | 0 | 2016-08-31T18:42:45Z | [
"python",
"list",
"python-2.7",
"trend"
] |
Unequal width binned histogram in python | 39,255,916 | <p>I have an array with probability values stored in it. Some values are 0. I need to plot a histogram such that there are equal number of elements in each bin. I tried using matplotlibs hist function but that lets me decide number of bins. How do I go about plotting this?(Normal plot and hist work but its not what is ... | 0 | 2016-08-31T17:44:28Z | 39,258,397 | <p>The task does not make much sense to me, but the following code does, what i understood as the thing to do.</p>
<p>I also think the last lines of the code are what you really wanted to do. Using different bin-widths to improve visualization (but don't target the distribution of equal amount of samples within each b... | 2 | 2016-08-31T20:23:38Z | [
"python",
"matplotlib",
"histogram",
"probability",
"bins"
] |
Call pip via Python Launcher | 39,256,004 | <p>I've installed Python 3.5 and 2.7 side by side on a Windows machine. Rather than messing around with my <code>PATH</code>, I'm using the Python Launcher to call different Python versions, for instance <code>py -2</code> if I want to use Python 2. My question is: how do I call the <code>pip</code> executable for that... | 3 | 2016-08-31T17:49:03Z | 39,256,048 | <p>You have to start <code>pip</code> as a module like</p>
<pre><code>py -2 -m pip install virtualenv
</code></pre>
<p>Actually if you do want to mess around with python-environments (like installing conflicting libraries for the same python-version) you should take a look a <a href="https://virtualenv.pypa.io/en/sta... | 5 | 2016-08-31T17:51:59Z | [
"python",
"pip"
] |
Applying functools.wraps to nested wrappers | 39,256,072 | <p>I have a base decorator that takes arguments but that also is built upon by other decorators. I can't seem to figure where to put the functools.wraps in order to preserve the full signature of the decorated function.</p>
<pre><code>import inspect
from functools import wraps
# Base decorator
def _process_arguments(... | 0 | 2016-08-31T17:53:05Z | 39,257,170 | <p>I experimented with this: </p>
<pre><code>>>> from functools import wraps
>>> def x(): print(1)
...
>>> @wraps(x)
... def xyz(a,b,c): return x
>>> xyz.__name__
'x'
>>> help(xyz)
Help on function x in module __main__:
x(a, b, c)
</code></pre>
<p>AFAIK, this has nothin... | 0 | 2016-08-31T19:03:02Z | [
"python",
"python-2.7",
"python-decorators",
"functools"
] |
Applying functools.wraps to nested wrappers | 39,256,072 | <p>I have a base decorator that takes arguments but that also is built upon by other decorators. I can't seem to figure where to put the functools.wraps in order to preserve the full signature of the decorated function.</p>
<pre><code>import inspect
from functools import wraps
# Base decorator
def _process_arguments(... | 0 | 2016-08-31T17:53:05Z | 39,259,648 | <p>direprobs was correct in that no amount of functools wraps would get me there. bravosierra99 pointed me to somewhat related examples. However, I couldn't find a single example of signature preservation on nested decorators in which the outer decorator takes arguments.</p>
<p>The <a href="http://www.artima.com/forum... | 0 | 2016-08-31T21:59:02Z | [
"python",
"python-2.7",
"python-decorators",
"functools"
] |
Can Python print only selected fields from SQLite table to a file | 39,256,106 | <p>Please forgive me if my terminology is not right. I have this:</p>
<pre><code>CREATE TABLE table1 (field1 TEXT, field2 TEXT, field3 TEXT);
</code></pre>
<p>I want to print only information from field1 and field3 for each row into a text file. What I've tried is:</p>
<pre><code>e = open("export.txt", "w+")
sqlF... | 0 | 2016-08-31T17:55:34Z | 39,257,477 | <p>IMHO you are not iterating on the correct object.</p>
<pre><code>for row in c.execute(sqlF1):
e.write('%s\n' % row)
</code></pre>
<p>See the examples in <a href="https://docs.python.org/2/library/sqlite3.html" rel="nofollow">the docs</a>.</p>
| 1 | 2016-08-31T19:21:42Z | [
"python",
"sqlite",
"io"
] |
Why the value read from properties file in python doesn't work | 39,256,121 | <p>I am brand new to Python. I have some python script which is accessed by other project to read some data from this python script.</p>
<p>Past:
If suppose I need to provide the version information for the other project from this python script, I was having a class variable which was hard coded and it was working fin... | 0 | 2016-08-31T17:56:25Z | 39,256,449 | <p>If the <code>version.properties</code> file will be in the same directory as your code, you can use this:</p>
<pre><code>import os
config.read(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'version.properties'))
</code></pre>
| 1 | 2016-08-31T18:18:19Z | [
"python"
] |
Checking WHAT is missing from a list when comparing it to another list python | 39,256,150 | <p>I am looking to see what is missing from a list (A) from list (B)</p>
<p>If I have the following list of strings:</p>
<p><code>A = ['4-5', '3-6', '3-3', '9-0']</code> and <code>B = ['4-4', '4-5', '3-3', '6-9', '5-5', '3-2', '6-6', '9-9', '9,0']</code> and want to check what is missing from A that is in list B. </p... | 1 | 2016-08-31T17:58:14Z | 39,256,243 | <p>I don't know what <code>4-5</code> means? is it a string, an operation?</p>
<p>Anyways, assuming it is whatever you meant it to be you can do as follows:</p>
<pre><code>A = [4-5,3-6,3-3, 9-0]
B = [4-4, 4-5, 3-3, 6-9, 5-5, 3-2, 6-6, 9-9, 9,0]
a = set(A)
b = set(B)
print b - a
</code></pre>
| 5 | 2016-08-31T18:04:08Z | [
"python",
"list",
"sorting"
] |
Checking WHAT is missing from a list when comparing it to another list python | 39,256,150 | <p>I am looking to see what is missing from a list (A) from list (B)</p>
<p>If I have the following list of strings:</p>
<p><code>A = ['4-5', '3-6', '3-3', '9-0']</code> and <code>B = ['4-4', '4-5', '3-3', '6-9', '5-5', '3-2', '6-6', '9-9', '9,0']</code> and want to check what is missing from A that is in list B. </p... | 1 | 2016-08-31T17:58:14Z | 39,256,244 | <p>Don't bother sorting. Use sets instead and calculate the difference:</p>
<pre><code>A = ['4-5','3-6','3-3', '9-0']
B = ['4-4', '4-5', '3-3', '6-9', '5-5', '3-2', '6-6', '9-9', '9','0']
print(set(B) - set(A))
>> {'0', '6-9', '9-9', '5-5', '3-2', '6-6', '4-4', '9'}
</code></pre>
<p>Your required out put was <... | 1 | 2016-08-31T18:04:16Z | [
"python",
"list",
"sorting"
] |
Checking WHAT is missing from a list when comparing it to another list python | 39,256,150 | <p>I am looking to see what is missing from a list (A) from list (B)</p>
<p>If I have the following list of strings:</p>
<p><code>A = ['4-5', '3-6', '3-3', '9-0']</code> and <code>B = ['4-4', '4-5', '3-3', '6-9', '5-5', '3-2', '6-6', '9-9', '9,0']</code> and want to check what is missing from A that is in list B. </p... | 1 | 2016-08-31T17:58:14Z | 39,256,268 | <p>You could do this:</p>
<pre><code>>>> A = ['4-5','3-6','3-3','9-0']
>>> B=['4-4','4-5','3-3','6-9','5-5','3-2','6-6','9-9','9','0']
>>> set(B)-set(A)
set(['5-5', '4-4', '9-9', '3-2', '0', '6-9', '9', '6-6'])
>>>
</code></pre>
| 0 | 2016-08-31T18:05:47Z | [
"python",
"list",
"sorting"
] |
Checking WHAT is missing from a list when comparing it to another list python | 39,256,150 | <p>I am looking to see what is missing from a list (A) from list (B)</p>
<p>If I have the following list of strings:</p>
<p><code>A = ['4-5', '3-6', '3-3', '9-0']</code> and <code>B = ['4-4', '4-5', '3-3', '6-9', '5-5', '3-2', '6-6', '9-9', '9,0']</code> and want to check what is missing from A that is in list B. </p... | 1 | 2016-08-31T17:58:14Z | 39,256,293 | <p>Simple in a list comprehension too. Not sure why you would sort the inputs, I don't see that it's really necessary, but I've sorted the output.</p>
<pre><code>A = ["4-5",'3-6','3-3', '9-0']
B = ['4-4', '4-5', '3-3', '6-9', '5-5', '3-2', '6-6', '9-9', '9','0']
new = sorted([x for x in B if x not in A])
</code></pre... | 0 | 2016-08-31T18:07:19Z | [
"python",
"list",
"sorting"
] |
Checking WHAT is missing from a list when comparing it to another list python | 39,256,150 | <p>I am looking to see what is missing from a list (A) from list (B)</p>
<p>If I have the following list of strings:</p>
<p><code>A = ['4-5', '3-6', '3-3', '9-0']</code> and <code>B = ['4-4', '4-5', '3-3', '6-9', '5-5', '3-2', '6-6', '9-9', '9,0']</code> and want to check what is missing from A that is in list B. </p... | 1 | 2016-08-31T17:58:14Z | 39,256,793 | <p>In most situations, the best way is to ignore the fact the data is sorted and just do <code>set(B) - set(A)</code>. Or <code>list(set(B) - set(A))</code> if you definitely need a list for the result.</p>
<p>However, that has a moderately large space overhead (approximately the sum of the sizes of the two input list... | 0 | 2016-08-31T18:39:46Z | [
"python",
"list",
"sorting"
] |
Trouble parsing XML with python | 39,256,162 | <p>I have parsed an XML file with BeautifulSoup in Python and I am having trouble extracting the data out of it. An example of the structure of the XML is below:</p>
<pre><code><Products page="0" pages="-1" records="27">
<Product id="ABC001">
<Name>This product name</Name>
<Cur>... | 0 | 2016-08-31T17:58:56Z | 39,256,414 | <p><code>id</code> is an attribute of <code>Product</code>, not a child element, so you access it with:</p>
<pre><code>p['id']
</code></pre>
| 1 | 2016-08-31T18:15:43Z | [
"python",
"xml",
"bs4"
] |
User login read from file failing compared to user input | 39,256,233 | <p>I'm writing a program that will verify a username:</p>
<pre><code>def user_login():
""" Login and create a username, maybe """
with open('username.txt', 'r') as f:
if f.readline() is "":
username = raw_input("First login, enter a username to use: ")
with open('username.txt', ... | 1 | 2016-08-31T18:03:51Z | 39,256,531 | <p>Opening the same file again in another nested context is not a good idea. Instead, open the file once in <em>append</em> mode, and use <code>f.seek(0)</code> to return to the start whenever you need to:</p>
<pre><code>def user_login():
""" Login and create a username, maybe """
with open('username.txt', 'a+... | 1 | 2016-08-31T18:24:08Z | [
"python",
"python-2.7",
"file",
"user-input"
] |
User login read from file failing compared to user input | 39,256,233 | <p>I'm writing a program that will verify a username:</p>
<pre><code>def user_login():
""" Login and create a username, maybe """
with open('username.txt', 'r') as f:
if f.readline() is "":
username = raw_input("First login, enter a username to use: ")
with open('username.txt', ... | 1 | 2016-08-31T18:03:51Z | 39,256,799 | <p>When you use <code>readline()</code> the first time the current file position is moved past the first record. A better way to find if the file is empty is to test it's size:</p>
<pre><code>import os.path
import sys
def user_login():
fname = 'username.txt'
""" Login and create a username, maybe """
i... | 1 | 2016-08-31T18:39:53Z | [
"python",
"python-2.7",
"file",
"user-input"
] |
How do I tell sqlalchemy to ignore certain (say, null) columns on INSERT | 39,256,258 | <p>I have a legacy database that creates default values for several columns using a variety of stored procedures. It would be more or less prohibitive to try and track down the names and add queries to my code, not to mention a maintenance nightmare.</p>
<p>What I would <em>like</em> is to be able to tell sqlalchemy t... | 4 | 2016-08-31T18:05:13Z | 39,258,819 | <p>Add a <a href="http://docs.sqlalchemy.org/en/latest/core/defaults.html#server-defaults" rel="nofollow">server side default</a> with <a href="http://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Column.params.server_default" rel="nofollow"><code>server_default</code></a> for <code>fnord</code>:</... | 2 | 2016-08-31T20:53:56Z | [
"python",
"postgresql",
"sqlalchemy"
] |
How to get classes labels from cross_val_predict used with predict_proba in scikit-learn | 39,256,287 | <p>I need to train a <a href="http://scikit-learn.org/dev/modules/generated/sklearn.ensemble.RandomForestClassifier.html" rel="nofollow">Random Forest classifier</a> using a 3-fold cross-validation. For each sample, I need to retrieve the prediction probability when it happens to be in the test set.</p>
<p>I am using ... | 2 | 2016-08-31T18:06:49Z | 39,260,489 | <p>Yes, they will be in sorted order; this is because <code>DecisionTreeClassifier</code> (which is the default <code>base_estimator</code> for <code>RandomForestClassifier</code>) <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/tree/tree.py#L193" rel="nofollow">uses <code>np.unique</code> to ... | 1 | 2016-08-31T23:22:50Z | [
"python",
"scikit-learn",
"cross-validation"
] |
GTK+ 3.0 Clipboard doesn't paste anything to my clipboard | 39,256,324 | <p>I've been using this script for testing.</p>
<pre><code>import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
board = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
board.set_text("hello there", -1)
board.store()
</code></pre>
<p>It does erase anything I have in my clipboard, but it doesn't add... | 2 | 2016-08-31T18:10:03Z | 39,259,503 | <p>I got it working, sort of. It seems like I've been able to import the <a href="https://pypi.python.org/pypi/xerox" rel="nofollow">xerox library</a> without GTK complaining, and it worked. It's still not the best solution, but at least it's a workarround.</p>
| 0 | 2016-08-31T21:46:05Z | [
"python",
"tkinter",
"gtk"
] |
how to print type of keys for a list in python pdb | 39,256,340 | <p>I'm learning pdb and I can print, or pp a list of objects but how can I print the type of key for each object? I can see it with pp, it looks like a byte array but I'd like to know the type. I suppose I could just print debug this but I'm curious if there's a smarter way to do it when using the debugger.</p>
| 0 | 2016-08-31T18:11:09Z | 39,256,658 | <p>Because you wrote</p>
<blockquote>
<p>type of key</p>
</blockquote>
<p>I'm assuming that you mean a dictionary. But you <em>do</em> also talk about a "list of objects", which could also mean</p>
<ul>
<li>a list of any kind of object</li>
<li>a list of dictionaries</li>
</ul>
<p>But I'll show you two options:</... | 1 | 2016-08-31T18:32:21Z | [
"python",
"pdb"
] |
How to evaluate and add string to numpy array element | 39,256,365 | <p>Have this piece of code that I am trying to optimize.
It uses list comprehensions and works. </p>
<pre><code>series1 = np.asarray(range(10)).astype(float)
series2 = series1[::-1]
ntup = zip(series1,series2)
[['', 't:'+str(series2)][series1 > series2] for series1,series2 in ntup ]
#['', '', '', '', '', 't:4.0',... | 4 | 2016-08-31T18:13:00Z | 39,256,811 | <p>We can use a vectorized approach based on </p>
<ul>
<li><p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.core.defchararray.add.html" rel="nofollow"><code>np.core.defchararray.add</code></a> for the string appending of <code>'t:'</code> with the valid strings, and</p></li>
<li><p><a href="http:/... | 2 | 2016-08-31T18:40:57Z | [
"python",
"string",
"performance",
"numpy"
] |
How to evaluate and add string to numpy array element | 39,256,365 | <p>Have this piece of code that I am trying to optimize.
It uses list comprehensions and works. </p>
<pre><code>series1 = np.asarray(range(10)).astype(float)
series2 = series1[::-1]
ntup = zip(series1,series2)
[['', 't:'+str(series2)][series1 > series2] for series1,series2 in ntup ]
#['', '', '', '', '', 't:4.0',... | 4 | 2016-08-31T18:13:00Z | 39,256,849 | <p>Your list comprehensions work just fine for lists, not really need to use arrays. And for operations like this arrays probably won't give any speed advantage.</p>
<pre><code>In [521]: series1=[float(i) for i in range(10)]
In [522]: series2=series1[::-1]
In [523]: [['', 't:'+str(s2)][s1 > s2] for s1,s2 in zip(se... | 1 | 2016-08-31T18:43:39Z | [
"python",
"string",
"performance",
"numpy"
] |
How to evaluate and add string to numpy array element | 39,256,365 | <p>Have this piece of code that I am trying to optimize.
It uses list comprehensions and works. </p>
<pre><code>series1 = np.asarray(range(10)).astype(float)
series2 = series1[::-1]
ntup = zip(series1,series2)
[['', 't:'+str(series2)][series1 > series2] for series1,series2 in ntup ]
#['', '', '', '', '', 't:4.0',... | 4 | 2016-08-31T18:13:00Z | 39,257,537 | <p>This works for me. Fully vectorized.</p>
<pre><code>import numpy as np
series1 = np.arange(10)
series2 = series1[::-1]
empties = np.repeat('', series1.shape[0])
ts = np.repeat('t:', series1.shape[0])
s2str = series2.astype(np.str)
m = np.vstack([empties, np.core.defchararray.add(ts, s2str)])
cmp = np.int64(series1 ... | 1 | 2016-08-31T19:26:14Z | [
"python",
"string",
"performance",
"numpy"
] |
How to Import compiled libs (pyd) in python | 39,256,378 | <p>I could not get a working example of importing a compiled library (pyd file) in Python.</p>
<p>I compiled the blender source code, result is a bpy.pyd file.
This file is placed in the python\lib folder.</p>
<p>In the source code I have
import bpy</p>
<p>The file is found at runtime, but I get a runtime error tha... | 0 | 2016-08-31T18:13:46Z | 39,298,240 | <p>Found the error:
the pyd file was compiled with a 32 bit Python, was called with a 64 bit Python </p>
| 0 | 2016-09-02T17:54:13Z | [
"python",
"python-3.x",
"bpy"
] |
How to make grid of album covers QT python | 39,256,446 | <p>Currently i am trying to do it with QTableWidget but i cant seem to adjust the width of the table to the parent element, so when resizing is made, the columns need to increase. QtableWidget is placed in QTabWidget in the first tab. For more info, it is a music player like that:
<a href="http://i.stack.imgur.com/gbvn... | 0 | 2016-08-31T18:18:06Z | 39,256,867 | <p>Problem kinda solved. I replaced the TableWidget with list widget in <code>IconMode</code> view mode. </p>
| 0 | 2016-08-31T18:44:42Z | [
"python",
"qt",
"pyqt",
"qt-designer"
] |
How to make grid of album covers QT python | 39,256,446 | <p>Currently i am trying to do it with QTableWidget but i cant seem to adjust the width of the table to the parent element, so when resizing is made, the columns need to increase. QtableWidget is placed in QTabWidget in the first tab. For more info, it is a music player like that:
<a href="http://i.stack.imgur.com/gbvn... | 0 | 2016-08-31T18:18:06Z | 39,259,134 | <p>The most flexible way to do this would be with a <code>QGraphicsView</code>. You would create a <code>QGraphicScene</code> the same width as the view and place all the album covers accordingly. Based on the size of each image and the padding between them, you can compute how many you can fit on a single line. </p... | 1 | 2016-08-31T21:15:59Z | [
"python",
"qt",
"pyqt",
"qt-designer"
] |
Docker image gives me "executable file not found in $PATH" when run from python | 39,256,458 | <p>I'm trying to run some commands inside a docker image in python. When I do:</p>
<pre><code>docker run --rm -v <some_dir>:/mnt --workdir /mnt frolvlad/alpine-oraclejdk8:slim sh -c "javac example.java && java example"
</code></pre>
<p>In console (kali linux) it runs fine and prints the result. When I t... | 0 | 2016-08-31T18:18:50Z | 39,274,148 | <p>You are passing one big string as the last parameter to Docker. Docker is trying to run a binary called <code>sh -c 'javac example.java && java example'</code> which obviously doesn't exist.</p>
<p>You want to run the <code>sh</code> binary with 2 arguments. <code>-c</code> and the shell script you want <c... | 0 | 2016-09-01T14:22:47Z | [
"python",
"linux",
"docker",
"console"
] |
Django get_object_or_404 is not defined | 39,256,511 | <p>I am developing a standalone application which uses ORM of django. In my main application, I am using django's module of get_object_or_404.</p>
<p>I have imported it with all its dependencies when I run the script, it gives me the error: </p>
<pre><code>Traceback (most recent call last):
File "/usr/local/lib/pyt... | 0 | 2016-08-31T18:23:15Z | 39,256,639 | <p>Try to remove this double import of "django.shortcuts".</p>
| 0 | 2016-08-31T18:31:09Z | [
"python",
"django",
"import"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.