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 |
|---|---|---|---|---|---|---|---|---|---|
Multiple stacked bar plot with pandas | 39,013,425 | <p>I am trying to make a multiple stacked bar plot with pandas but I'm running into issues. Here is a sample code:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a':[10, 20], 'b': [15, 25], 'c': [35, 40], 'd':[45, 50]}, index=['john', 'bob'])
ax = df[['a', 'c']].plot.bar(width=0.1, stacked=True)
ax=df[['b', ... | 1 | 2016-08-18T08:33:15Z | 39,014,192 | <p>You could do it by shifting the <code>position</code> parameter of a <code>bar-plot</code> so that they are adjacent to each other as shown:</p>
<pre><code>matplotlib.style.use('ggplot')
fig, ax = plt.subplots()
df[['a', 'c']].plot.bar(stacked=True, width=0.1, position=1.5, colormap="bwr", ax=ax, alpha=0.7)
df[['b... | 2 | 2016-08-18T09:11:16Z | [
"python",
"pandas",
"matplotlib"
] |
Python 3 throwing error for exception handling | 39,013,431 | <p>I started learning python last week and I'm unable to get what's wrong here:</p>
<pre><code>def add(x,y):
"""Adds 2 numbers and returns the result"""
return x+y
def sub(x,y):
"""Subtracts 2 numbers and returns the result"""
return x-y
a = int(input("Enter first number"))
b = int(input("Enter seco... | 0 | 2016-08-18T08:33:22Z | 39,013,472 | <p>You are trying to catch an <em>instance</em> of <code>ValueError()</code>, where Python expects you to filter on the <em>type</em>. Remove the call:</p>
<pre><code>except ValueError:
print ("Wrong choice")
</code></pre>
| 4 | 2016-08-18T08:35:27Z | [
"python",
"python-3.x",
"exception-handling"
] |
How to vary the arguments in multiprocessing.Pool | 39,013,433 | <p>I want to execeute yapsy-plugins with the help of multiprocessing in python. So far i've got a worker as follows:</p>
<pre><code>def mp_worker(plugin, importer, orgadb, regiondb, ispdb):
print(" Processs " + plugin.plugin_object.getOrigin + " running.")
processPlugin(plugin, importer, orgadb, regiondb, ispd... | 0 | 2016-08-18T08:33:36Z | 39,014,137 | <p>After a little time of testing i figured out how it would work, if it wouldnt be a yapsy plugin class:</p>
<pre><code> def mp_worker(importer, orgadb, regiondb, ispdb, plugin):
processPlugin(plugin, importer, orgadb, regiondb, ispdb)
def mp_handler(plugins, importer, orgadb, regiondb, ispdb):
p... | 0 | 2016-08-18T09:08:22Z | [
"python",
"python-3.x",
"multiprocessing"
] |
Absolute and relative import of Python modules: a matplotlib example | 39,013,453 | <p>Many questions have been asked regarding how to import Python modules, specifically on whether to use absolute or explicit relative import (<a href="http://stackoverflow.com/questions/4209641/absolute-vs-explicit-relative-import-of-python-module">here</a> for example).
The import style, as suggested by the Python S... | 0 | 2016-08-18T08:34:29Z | 39,018,696 | <p>An important thing to remember about the matplotlib code base is that it is very old (have git history back to 2003 and have lost another few years), large (>93k lines of python, 17k lines of c++), and has over 450 contributors.</p>
<p>Having a look at git-blame (off of the 2.x branch but the imports are pretty sta... | 1 | 2016-08-18T12:48:51Z | [
"python",
"matplotlib",
"import",
"module"
] |
Calculation not storing in DataFrame but works on print | 39,013,519 | <p>I have the following calculation:<br>
<code>np.maximum(0, np.prod([perf_asset, calc_arr['val']]) - amt_payout - np.prod([exposure, calc_arr['delta_1']]))</code></p>
<p>Written out, this would be: </p>
<pre><code>MAX(0, 0.8 Ã 105.015038 - 80 - TRUE Ã 5.3135)
MAX(0, 84.0120307692 - 80 - 5.3135)
= 0
</code></pre>
... | 1 | 2016-08-18T08:37:49Z | 39,013,956 | <p>I think you need <code>append</code> values to <code>list</code> - <code>stock_vals</code> and then assign it to column:</p>
<pre><code>stock_vals = []
for i in [0.0627,0.0627,0.0627,0.0627,0.0627,0.0627,0.0627,0.0627,0.0627,0.0627,0.0627,0.0627,0.0627,0.0627,0.0627,-0.053,-0.0698,-0.1011,-0.1767,-0.6271,-0.6271,-0... | 0 | 2016-08-18T08:59:46Z | [
"python",
"pandas",
"numpy"
] |
How to set QoS level 0 for mqtt publish messages in Python Azure IoT Hub Client SDK? | 39,013,564 | <p>I am using <a href="https://github.com/Azure/azure-iot-sdks" rel="nofollow">Azure</a> custom python SDK to connect to Azure IoT Hub. I am successfully able to connect to the Hub using MQTT but didn't find any way by which one can set QoS level 0 of publishing message. Also, I haven't found any documentation for Pyth... | 1 | 2016-08-18T08:40:43Z | 39,031,300 | <p>The official azure-iot-sdk python library only supports iothub_client. If you want to use the MQTT python SDK, there're at least two ways,</p>
<ol>
<li>Write MQTT library python wrapper for azure-umqtt-c library, it is located in <a href="https://github.com/Azure/azure-umqtt-c" rel="nofollow">here</a>. and has the ... | 1 | 2016-08-19T04:47:34Z | [
"python",
"azure",
"mqtt",
"azure-iot-hub"
] |
How to set QoS level 0 for mqtt publish messages in Python Azure IoT Hub Client SDK? | 39,013,564 | <p>I am using <a href="https://github.com/Azure/azure-iot-sdks" rel="nofollow">Azure</a> custom python SDK to connect to Azure IoT Hub. I am successfully able to connect to the Hub using MQTT but didn't find any way by which one can set QoS level 0 of publishing message. Also, I haven't found any documentation for Pyth... | 1 | 2016-08-18T08:40:43Z | 39,031,998 | <p>As addition, you also can use IronPython as Python runtime based on .NET framework, then you can integrate Python with Azure IoTHub SDK for C# if you are familiar with C# more than C, please see the <a href="http://ironpython.net/documentation/dotnet/" rel="nofollow">document</a> to know IronPython .NET integration.... | 0 | 2016-08-19T05:55:41Z | [
"python",
"azure",
"mqtt",
"azure-iot-hub"
] |
Efficiently find indices of all values in an array | 39,013,722 | <p>I have a very large array, consisting of integers between 0 and N, where each value occurs at least once.</p>
<p>I'd like to know, for each value <em>k</em>, all the indices in my array where the array's value equals <em>k</em>.</p>
<p>For example:</p>
<pre><code>arr = np.array([0,1,2,3,2,1,0])
desired_output = {... | 4 | 2016-08-18T08:48:25Z | 39,013,789 | <p>I don't know numpy but you could definitely do this in one iteration, with a defaultdict:</p>
<pre><code>indices = defaultdict(list)
for i, val in enumerate(arr):
indices[val].append(i)
</code></pre>
| 1 | 2016-08-18T08:51:48Z | [
"python",
"numpy"
] |
Efficiently find indices of all values in an array | 39,013,722 | <p>I have a very large array, consisting of integers between 0 and N, where each value occurs at least once.</p>
<p>I'd like to know, for each value <em>k</em>, all the indices in my array where the array's value equals <em>k</em>.</p>
<p>For example:</p>
<pre><code>arr = np.array([0,1,2,3,2,1,0])
desired_output = {... | 4 | 2016-08-18T08:48:25Z | 39,013,794 | <p>A pythonic way is using <code>collections.defaultdict()</code>:</p>
<pre><code>>>> from collections import defaultdict
>>>
>>> d = defaultdict(list)
>>>
>>> for i, j in enumerate(arr):
... d[j].append(i)
...
>>> d
defaultdict(<type 'list'>, {0: [0, ... | 2 | 2016-08-18T08:51:59Z | [
"python",
"numpy"
] |
Efficiently find indices of all values in an array | 39,013,722 | <p>I have a very large array, consisting of integers between 0 and N, where each value occurs at least once.</p>
<p>I'd like to know, for each value <em>k</em>, all the indices in my array where the array's value equals <em>k</em>.</p>
<p>For example:</p>
<pre><code>arr = np.array([0,1,2,3,2,1,0])
desired_output = {... | 4 | 2016-08-18T08:48:25Z | 39,013,922 | <p><strong>Approach #1</strong></p>
<p>Here's a vectorized approach to get those indices as list of arrays -</p>
<pre><code>sidx = arr.argsort()
unq, cut_idx = np.unique(arr[sidx],return_index=True)
indices = np.split(sidx,cut_idx)[1:]
</code></pre>
<p>If you want the final dictionary that corresponds each unique el... | 7 | 2016-08-18T08:57:50Z | [
"python",
"numpy"
] |
Efficiently find indices of all values in an array | 39,013,722 | <p>I have a very large array, consisting of integers between 0 and N, where each value occurs at least once.</p>
<p>I'd like to know, for each value <em>k</em>, all the indices in my array where the array's value equals <em>k</em>.</p>
<p>For example:</p>
<pre><code>arr = np.array([0,1,2,3,2,1,0])
desired_output = {... | 4 | 2016-08-18T08:48:25Z | 39,014,909 | <p>Fully vectorized solution using the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package:</p>
<pre><code>import numpy_indexed as npi
k, idx = npi.groupy_by(arr, np.arange(len(arr)))
</code></pre>
<p>On a higher level; why do you need these indices? Subsequent ... | 0 | 2016-08-18T09:43:19Z | [
"python",
"numpy"
] |
Google App Engine unable to resolve www.facebook.com | 39,013,932 | <h1>HACKY SOLUTION</h1>
<p>So I spent quite some time figuring out exactly WHY this went wrong, turns out I wasn't wrong at all. Google was. What ended up being the case, was that there's a bug in the development SDK for the App Engine.</p>
<p>To solve this (rediciously annoying) issue, you can do the following:</p>
... | 0 | 2016-08-18T08:58:30Z | 39,019,442 | <p>GAE supports sockets, but with some significant <a href="https://cloud.google.com/appengine/docs/python/sockets/#limitations_and_restrictions" rel="nofollow">Limitations and restrictions</a>.</p>
<p>The SDK is mimicking these limitations and restrictions, so tweaking it to use the real socket library instead of the... | 0 | 2016-08-18T13:25:48Z | [
"python",
"google-app-engine",
"dns"
] |
Parse a YAML with duplicate anchors in Python | 39,013,993 | <p>I'm just getting started with both YAML and Python and I'm trying to parse a YAML in Python which contains anchors and aliases.<br>
In this YAML I overwrite the anchors to make certain nodes have different values. </p>
<p>An example of my YAML:</p>
<pre><code>Some Colors: &some_colors
color_primary: &col... | 1 | 2016-08-18T09:01:13Z | 39,020,010 | <p>First of all, you are not doing anything wrong. PyYAML is doing something wrong here. This is most likely because dumping anchors with the same name would be an erroneous situation the the PyYAML dumper. If you have a Python structure that is self referential:</p>
<pre><code> a = dict(x=1)
a['y'] = a
</code></pre>... | 0 | 2016-08-18T13:51:08Z | [
"python",
"yaml"
] |
SECRET_KEY setting must not be empty | 39,014,009 | <p>I am getting Error when i run server in cmd</p>
<p>I am using Windows 7, Python Version 3.4.3 and
Django Version 1.8. </p>
<pre><code>>
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\man... | 2 | 2016-08-18T09:01:52Z | 39,014,031 | <p>I think the error message is pretty much self-explaining:
<code>django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.</code></p>
<p>You need to set SECRET_KEY in your settings.py file.</p>
| 1 | 2016-08-18T09:03:01Z | [
"python",
"django"
] |
SECRET_KEY setting must not be empty | 39,014,009 | <p>I am getting Error when i run server in cmd</p>
<p>I am using Windows 7, Python Version 3.4.3 and
Django Version 1.8. </p>
<pre><code>>
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\man... | 2 | 2016-08-18T09:01:52Z | 39,014,504 | <p>If SECRET_KEY is in setttings.py file then you are running different settings file.</p>
<p>use below command:</p>
<pre><code>python manage.py runserver --settings project_name.settings
</code></pre>
<p><code>project_name.settings</code> is path to your settings file.</p>
<p>You can also check it using <code>prin... | 0 | 2016-08-18T09:24:31Z | [
"python",
"django"
] |
SECRET_KEY setting must not be empty | 39,014,009 | <p>I am getting Error when i run server in cmd</p>
<p>I am using Windows 7, Python Version 3.4.3 and
Django Version 1.8. </p>
<pre><code>>
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python34\lib\site-packages\django\core\man... | 2 | 2016-08-18T09:01:52Z | 39,015,530 | <p>It was Django version incompatibility issue. When I installed 1.5 version and 1.9 version of django it is working but not with 1.10 and 1.8</p>
| 4 | 2016-08-18T10:12:49Z | [
"python",
"django"
] |
Particle Tracking by coordinates from txt file | 39,014,085 | <p>I have some particle track data from an OpenFoam simulation.
The data looks like this:</p>
<pre><code>0.005 0.00223546 1.52096e-09 0.00503396
0.01 0.00220894 3.92829e-09 0.0101636
0.015 0.00218103 5.37107e-09 0.0154245
.....
</code></pre>
<p>First row is time, then x, y ,z coordinates.
In my folder, I have a file ... | 2 | 2016-08-18T09:05:51Z | 39,014,392 | <p>Individual files would be easily loaded with something like:</p>
<pre><code>import numpy as np
t, x, y, z = np.loadtxt(filename, delimiter=' ', unpack=True)
</code></pre>
<p>Now there is an issue as you would like to index particule position with time, whereas Numpy will only accept integers as indices.</p>
<p>ed... | 0 | 2016-08-18T09:19:36Z | [
"python",
"numpy",
"matplotlib"
] |
Particle Tracking by coordinates from txt file | 39,014,085 | <p>I have some particle track data from an OpenFoam simulation.
The data looks like this:</p>
<pre><code>0.005 0.00223546 1.52096e-09 0.00503396
0.01 0.00220894 3.92829e-09 0.0101636
0.015 0.00218103 5.37107e-09 0.0154245
.....
</code></pre>
<p>First row is time, then x, y ,z coordinates.
In my folder, I have a file ... | 2 | 2016-08-18T09:05:51Z | 39,019,557 | <p>If you have regular time steps, you can use a pandas dataframe to find the difference </p>
<pre><code>import pandas as pd
dt = .005 #or whatever time difference you have
df = pd.read_csv(<a bunch of stuff indicating how to read the file>)
df['v_x'] = df.diff(<the x colum>)
df['v_x'] = df['v_x']/dt
</c... | 2 | 2016-08-18T13:30:56Z | [
"python",
"numpy",
"matplotlib"
] |
Particle Tracking by coordinates from txt file | 39,014,085 | <p>I have some particle track data from an OpenFoam simulation.
The data looks like this:</p>
<pre><code>0.005 0.00223546 1.52096e-09 0.00503396
0.01 0.00220894 3.92829e-09 0.0101636
0.015 0.00218103 5.37107e-09 0.0154245
.....
</code></pre>
<p>First row is time, then x, y ,z coordinates.
In my folder, I have a file ... | 2 | 2016-08-18T09:05:51Z | 39,020,087 | <p>You "almost" don't need numpy for that. I created a simple class hierarchy with some initial methods. You could improve from that if you like the approach. Note that I am creating from a string, you should use <code>for line in file</code> instead of the <code>string.split</code> way.</p>
<pre><code>import numpy
c... | 0 | 2016-08-18T13:54:51Z | [
"python",
"numpy",
"matplotlib"
] |
Break doesn't seem to break the for-loop | 39,014,132 | <p>My for-loop doesn't seem to break the for-loop and move on to the next d value. It takes 0.5 seconds when the range is 10000 but 0.8 when its 100000? But the range shouldn't matter when it should break long before getting above 100.
Here's my code:</p>
<pre><code>import math
d = 1
l = {}
while d < 10:
for ... | -1 | 2016-08-18T09:07:58Z | 39,014,440 | <p>The <code>break</code> is working just fine. However, you didn't find a solution for all values of <code>d</code>.</p>
<p>Add an <code>else:</code> suite to the <code>for</code> loop to show when no <code>break</code> was executed for that loop:</p>
<pre><code>while d < 10:
for y in range(0, 10000):
... | 0 | 2016-08-18T09:21:34Z | [
"python",
"for-loop",
"break"
] |
Cassandra driver error in installing | 39,014,212 | <p>I am getting following error in installing Cassandra driver for python. </p>
<pre><code>Command "c:\python33\python.exe -u -c "import setuptools, tokenize;__file__='c:\
\users\\vmasama\\appdata\\local\\temp\\pip-build-we10p7\\cassandra-driver\\setup
.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read()... | 0 | 2016-08-18T09:12:17Z | 39,132,448 | <p>I tried it in an environment missing compiler paths and observed something similar. I think it's a problem in setuptools error handling when it doesn't find what it's expecting. The easiest way I've found is to use the VS Command Prompt shortcut installed with Visual Studio:</p>
<blockquote>
<p>Perhaps the easies... | 0 | 2016-08-24T20:24:57Z | [
"python",
"python-3.x",
"cassandra",
"cassandra-2.0"
] |
Edit with IDLE not working | 39,014,407 | <p>My IDLE option in the right click menu has disappeared. I think it's because I use Python 3.5.2, but I installed Python 2.7.12 without uninstalling Python 3.5.2. Later I uninstalled Python 2.7.12 and from then on the .py files are opening in either Chrome but I cannot get it to open with IDLE. And the usual logo for... | 0 | 2016-08-18T09:20:06Z | 39,014,685 | <p><strong>Option 1:</strong>
Right click on any <code>.py</code> file and click <code>Open With</code> and click <code>choose default Program</code> or <code>Choose another app</code>. </p>
<p>From the list that appears after if you see <code>python.exe</code> choose that otherwise click <code>Choose another program<... | 0 | 2016-08-18T09:33:32Z | [
"python",
"python-idle"
] |
Python regular expression, using dots many times | 39,014,627 | <p>In python regular expressions, if I want to write 20 dots in a row because I want 20 characters, how can I do this in shorthand?</p>
| -4 | 2016-08-18T09:30:26Z | 39,014,729 | <p>use <code>'.{20}'</code></p>
<pre><code>In [15]: x = 'a' * 30 + '.' * 20 + 'b' * 30
In [16]: m = re.search('.{20}', x)
In [17]: m
Out[17]: <_sre.SRE_Match at 0x103ec3850>
</code></pre>
| 1 | 2016-08-18T09:35:42Z | [
"python",
"regex"
] |
Python regular expression, using dots many times | 39,014,627 | <p>In python regular expressions, if I want to write 20 dots in a row because I want 20 characters, how can I do this in shorthand?</p>
| -4 | 2016-08-18T09:30:26Z | 39,014,741 | <pre><code>print '.'*20
</code></pre>
<p>Searching in internet should solve your problem before posting that...</p>
| -1 | 2016-08-18T09:36:08Z | [
"python",
"regex"
] |
(centos6.6) before updating python2.7.3 ,it is python 2.6.6. When running pybot --version,errors came out | 39,014,670 | <p>(centos6.6) before updating python2.7.3 ,it is python 2.6.6. When running <code>pybot --version</code>, errors came out as follows.</p>
<p>I want to install the test environment of python 2.7.3 and robot framework 2.7.6 and paramiko-1.7.4 and pycrypto-2.6</p>
<blockquote>
<p>[root@localhost robotframework-2.7.6]... | 0 | 2016-08-18T09:33:09Z | 39,037,542 | <p>Reasons could be any of the following:</p>
<ol>
<li>Either the python files (at least one) have lost the formatting. Python is prone to formatting errors</li>
<li>At least one installation (python, Robo) doesn't have administrative privileges.</li>
<li>Environment variables (PATH, CLASSPATH, PYTHON PATH) are not se... | 0 | 2016-08-19T11:08:37Z | [
"python",
"linux",
"robotframework"
] |
(centos6.6) before updating python2.7.3 ,it is python 2.6.6. When running pybot --version,errors came out | 39,014,670 | <p>(centos6.6) before updating python2.7.3 ,it is python 2.6.6. When running <code>pybot --version</code>, errors came out as follows.</p>
<p>I want to install the test environment of python 2.7.3 and robot framework 2.7.6 and paramiko-1.7.4 and pycrypto-2.6</p>
<blockquote>
<p>[root@localhost robotframework-2.7.6]... | 0 | 2016-08-18T09:33:09Z | 39,104,313 | <p>I installed the zlib-devel and python-level with the help of yum, and recompiled the python, finally completed the test of installation. Thank you for your answer.</p>
| 0 | 2016-08-23T14:45:41Z | [
"python",
"linux",
"robotframework"
] |
install python modules in mac osx | 39,014,749 | <p>I am new to pyhton. I am using python 3.5 on mac os x el capitan.
I tried using the command 'pip install requests' in the python interpreter IDLE . But it throws invalid 'syntax error'.</p>
<p>I read about installing modules is only possible in command line.
So i moved to TERMINAL, but no command is working here al... | 0 | 2016-08-18T09:36:19Z | 39,015,203 | <p>Here is what you should do.</p>
<p>Use homebrew to install python 2.7 and 3.5 in a virtual environment.</p>
<p><code>pip install virtualenv</code>
Then make a directory called <code>virtualenvs</code> in your root folder and add local files with.</p>
<pre><code>cd virtualenvs
virtualenv venv
</code></pre>
<p>act... | 0 | 2016-08-18T09:57:53Z | [
"python",
"osx",
"module"
] |
install python modules in mac osx | 39,014,749 | <p>I am new to pyhton. I am using python 3.5 on mac os x el capitan.
I tried using the command 'pip install requests' in the python interpreter IDLE . But it throws invalid 'syntax error'.</p>
<p>I read about installing modules is only possible in command line.
So i moved to TERMINAL, but no command is working here al... | 0 | 2016-08-18T09:36:19Z | 39,015,841 | <p>Followed this guide.
<a href="https://docs.python.org/3/using/mac.html" rel="nofollow">https://docs.python.org/3/using/mac.html</a></p>
<p>Found python3.5 in usr/local/bin instead of the default usr/bin where the default 2.7 exists.</p>
<p>The 3.5 Package automatically genrates an alias for itself that is python3.... | 0 | 2016-08-18T10:28:36Z | [
"python",
"osx",
"module"
] |
Flask script windows subprocess and sys | 39,014,785 | <p>I have the following Ptyhon Flask script,</p>
<pre><code>from flask import Flask
import subprocess
import sys
app = Flask(__name__)
@app.route("/")
def hello():
return "index"
@app.route("/script")
def cmd():
cmd = [sys.executable, "C:\\Users\\JSm\\Project\\FlaskAutomation\\test.py"]
p = subprocess.P... | 1 | 2016-08-18T09:37:54Z | 39,015,234 | <p>I'm not very sure about windows environment, however if i use the same script and assuming i've <code>test.py</code> is present at given location, I get 500 internal server error if i go and access <code>/script</code>.</p>
<p>To make it successful, I've made following change,</p>
<pre><code>p = subprocess.Popen(c... | 0 | 2016-08-18T09:59:19Z | [
"python",
"flask"
] |
Battery Historian Error for Checking Power Consumption | 39,014,791 | <p>I want to check the power consumption of my app on an android device and I just came across this link <a href="https://developer.android.com/studio/profile/battery-historian.html" rel="nofollow">Battery Historian</a></p>
<p>I followed the above tutorial and every step is fine until I reached the last one.</p>
<p>W... | 1 | 2016-08-18T09:38:07Z | 39,016,115 | <p>From the docs:</p>
<blockquote>
<p>Next, make sure Python 2.7 (NOT Python 3!) is installed</p>
</blockquote>
<p>Install Python 2.7 to use the script and it should work fine.</p>
<p><a href="https://www.python.org/downloads/release/python-2712/" rel="nofollow">https://www.python.org/downloads/release/python-2712... | 2 | 2016-08-18T10:41:50Z | [
"android",
"python",
"python-3.x"
] |
Where does Python search for files when using open? | 39,014,865 | <p>I have the simplest file opening line in my code.</p>
<pre><code>file = open("file.txt", "r+")
</code></pre>
<p>Where does python search for files? The only location that works for me is </p>
<blockquote>
<p>C:/Users/<em>useraccount</em></p>
</blockquote>
<pre><code>file = open("file.txt", "w")
</code></pre>
... | 0 | 2016-08-18T09:41:30Z | 39,015,044 | <p>If you pass a relative path, like <code>file.txt</code>, Python will search for that file relative to the same directory where you are running the command from. </p>
<p>If you are in - <code>C:/Users/useraccount/</code> and you try to open <code>file.txt</code> then Python tries to open <code>C:/Users/useraccount/f... | 2 | 2016-08-18T09:50:08Z | [
"python"
] |
Where does Python search for files when using open? | 39,014,865 | <p>I have the simplest file opening line in my code.</p>
<pre><code>file = open("file.txt", "r+")
</code></pre>
<p>Where does python search for files? The only location that works for me is </p>
<blockquote>
<p>C:/Users/<em>useraccount</em></p>
</blockquote>
<pre><code>file = open("file.txt", "w")
</code></pre>
... | 0 | 2016-08-18T09:41:30Z | 39,015,063 | <p>If you use relative paths, they will be relative to the current working directory. To find out the current working directory, run the following code snippet from Python.</p>
<pre><code>import os
print os.getcwd()
</code></pre>
<p>To avoid this, specify the absolute path.</p>
| 1 | 2016-08-18T09:50:40Z | [
"python"
] |
Python: Count character in string which are following each other | 39,014,882 | <p>I have a string in which I want to count the occurrences of <code>#</code> following each other to replace them by numbers to create a increment.</p>
<p>For example:</p>
<pre><code>rawString = 'MyString1_test##_edit####'
for x in xrange(5):
output = doConvertMyString(rawString)
print output
MyString1_tes... | 1 | 2016-08-18T09:42:08Z | 39,015,141 | <pre><code>test_string = 'MyString1_test##_edit####'
def count_hash(raw_string):
str_list = list(raw_string)
hash_count = str_list.count("#") + 1
for num in xrange(1, hash_count):
new_string = raw_string.replace("####", "000" + str(num))
new_string = new_string.replace("##", "0" + str(num))... | -2 | 2016-08-18T09:54:52Z | [
"python",
"string"
] |
Python: Count character in string which are following each other | 39,014,882 | <p>I have a string in which I want to count the occurrences of <code>#</code> following each other to replace them by numbers to create a increment.</p>
<p>For example:</p>
<pre><code>rawString = 'MyString1_test##_edit####'
for x in xrange(5):
output = doConvertMyString(rawString)
print output
MyString1_tes... | 1 | 2016-08-18T09:42:08Z | 39,015,232 | <p>How about this-</p>
<pre><code>rawString = 'MyString1_test##_edit####'
splitString = rawString.split('_')
for i in xrange(10): # you may put any count
print '%s_%s%02d_%s%04d' % (splitString[0], splitString[1][0:4], i, splitString[2][0:4], i, )
</code></pre>
| 0 | 2016-08-18T09:59:13Z | [
"python",
"string"
] |
Python: Count character in string which are following each other | 39,014,882 | <p>I have a string in which I want to count the occurrences of <code>#</code> following each other to replace them by numbers to create a increment.</p>
<p>For example:</p>
<pre><code>rawString = 'MyString1_test##_edit####'
for x in xrange(5):
output = doConvertMyString(rawString)
print output
MyString1_tes... | 1 | 2016-08-18T09:42:08Z | 39,015,402 | <p>You can try this naive (and probably not most efficient) solution. It assumes that the number of <code>'#'</code> is fixed.</p>
<pre><code>rawString = 'MyString1_test##_edit####'
for i in range(1, 6):
temp = rawString.replace('####', str(i).zfill(4)).replace('##', str(i).zfill(2))
print(temp)
>> MyS... | 0 | 2016-08-18T10:06:55Z | [
"python",
"string"
] |
Python: Count character in string which are following each other | 39,014,882 | <p>I have a string in which I want to count the occurrences of <code>#</code> following each other to replace them by numbers to create a increment.</p>
<p>For example:</p>
<pre><code>rawString = 'MyString1_test##_edit####'
for x in xrange(5):
output = doConvertMyString(rawString)
print output
MyString1_tes... | 1 | 2016-08-18T09:42:08Z | 39,015,493 | <p>You may use <code>zfill</code> in the <code>re.sub</code> replacement to pad any amount of <code>#</code> chunks. <code>#+</code> regex pattern matches 1 or more <code>#</code> symbols. The <code>m.group()</code> stands for the match the regex found, and thus, we replace all <code>#</code>s with the incremented <cod... | 2 | 2016-08-18T10:10:52Z | [
"python",
"string"
] |
Python: Count character in string which are following each other | 39,014,882 | <p>I have a string in which I want to count the occurrences of <code>#</code> following each other to replace them by numbers to create a increment.</p>
<p>For example:</p>
<pre><code>rawString = 'MyString1_test##_edit####'
for x in xrange(5):
output = doConvertMyString(rawString)
print output
MyString1_tes... | 1 | 2016-08-18T09:42:08Z | 39,015,857 | <p>The code below converts the <code>rawString</code> to a format string, using <code>groupby</code> in a list comprehension to find groups of hashes. Each run of hashes is converted into a format directive to print a zero-padded integer of the appropriate width, runs of non-hashes are simply joined back together.</p>
... | 1 | 2016-08-18T10:29:12Z | [
"python",
"string"
] |
Heatmap correlation plot half with values number and half color map in seaborn | 39,014,907 | <p>In the previous versions of seaborn (<0.7) it was present the function <em>corrplot()</em>, which allowed to plot a correlation matrix such that half of the matrix is numeric and the other half is a color map. Now, seaborn (0.7.1) has just the <em>heatmap()</em> function, that doesn't have this function directly.... | 0 | 2016-08-18T09:43:19Z | 39,014,908 | <p>I have spend some time to do it, basically it require to overlap two heatmaps, where one makes use of a mask to cover half of the matrix. A code example is showed below.
'
import numpy as np
import pandas as pd
import seaborn
from matplotlib.colors import ListedColormap
from matplotlib.pylab impo... | 1 | 2016-08-18T09:43:19Z | [
"python",
"heatmap",
"correlation",
"seaborn"
] |
Django: how to query relations effectively | 39,015,062 | <p>I have a model "Booking" referencing to another model "Event" with a foreign key.</p>
<pre><code>class Event(models.Model):
title = models.CharField(_("title"), max_length=100)
class Booking(models.Model):
user = models.ForeignKey('auth.User', ..., related_name='bookings')
event = models.ForeignKey('Ev... | 0 | 2016-08-18T09:50:40Z | 39,015,179 | <p>You can do this in one line: <code>Event.objects.filter(bookings__user=self.request.user)</code></p>
| 2 | 2016-08-18T09:56:28Z | [
"python",
"django",
"performance",
"django-queryset",
"django-select-related"
] |
python mixing garmin timestamps | 39,015,119 | <p>I belong a garmin watch , to report statistic they have a sdk
in this SDK they have a timestamp in two format
one is a true timestamp on 32 bit
another is the lower part on 16 bit which must be combinate whith the first </p>
<p>I dont know to code this in Python Can somebody help me</p>
<p>here is their expla... | 0 | 2016-08-18T09:53:37Z | 39,016,857 | <p>I'm not sure of the result but I took them literally explanation
I shifted 32-bit timestamps of bits left 16 positions
then I shifted 16 places to the right and I made one or bitwise with the 16-bit timestamp</p>
| 0 | 2016-08-18T11:19:04Z | [
"python",
"timestamp",
"bit-shift"
] |
TKinter, Python - Creating TopLevel popups using iteration and then closing them again without killing root | 39,015,297 | <p>I am trying to create a program that allows the user to enter the real names of people from a list of obscure names. </p>
<p>I want the pop-up windows to be generated from a main root window. Once the user has entered the real name, the pop-up should close and then open the next obscure name in the list. </p>
<p>I... | 0 | 2016-08-18T10:02:27Z | 39,044,980 | <p>The issue is that <code>win.mainloop()</code> is blocking, so having it in the iteration means that nothing will happen until after the win has been closed.</p>
<p>however, just getting rid of <code>win.mainloop()</code> causes all of the popups to come up at once so we need a way to make it so that the next iterat... | 0 | 2016-08-19T17:45:49Z | [
"python",
"python-2.7",
"tkinter"
] |
Python Multiprocessing with Subprocess Flags fail to run | 39,015,354 | <p>When trying to run the following code I get </p>
<blockquote>
<p>OSError: [Errno 2] No such file or directory</p>
</blockquote>
<p>The strange issue is that when I try to run LS without any other flags such as -a, the subprocess run as intended with no errors. I also tried adding shell=True along with the flag -... | 1 | 2016-08-18T10:05:19Z | 39,016,770 | <p>Your problem is here:</p>
<pre><code>"ls -a".split("/")
</code></pre>
<p>This turns it into a list <code>["ls -a"]</code> which forces subprocess.call() to find a binary named "ls -a" which doesn't exist. subprocess.call() can be called two ways:</p>
<pre><code>subprocess.call("ls -a", shell=True) # argument pa... | 0 | 2016-08-18T11:14:33Z | [
"python",
"subprocess",
"python-multithreading",
"python-multiprocessing"
] |
Tensorflow gradients are always zero | 39,015,376 | <p>Tensorflow gradients are always zero with respect to conv layers that are after first conv layer. I've tried different ways to check that but gradients are always zero! Here is the small reproducible code that can be run to check that.</p>
<pre><code>from __future__ import absolute_import
from __future__ import div... | 0 | 2016-08-18T10:06:07Z | 39,017,739 | <p>What you compute is kind of weird. Let's examine the shapes in your model:</p>
<ul>
<li>input <code>x</code>: <code>[batch_size, 4, 2, 1]</code></li>
<li>1st convolution <code>conv</code>: <code>[batch_size, 4, 1, 1000]</code></li>
<li>1st max pool <code>pooling</code>: <code>[batch_size, 4, 1, 1]</code></li>
<li>2... | 1 | 2016-08-18T12:02:49Z | [
"python",
"tensorflow",
"mathematical-optimization",
"gradient-descent"
] |
Slicing strings pulled from HTML | 39,015,385 | <p>I pulled some data from a webpage using </p>
<pre><code>y = soup.find('td', attrs={'data'}).string
</code></pre>
<p>When I tried to use float() I got the error message that it was an invaled literal for float(). So I tried to find out what was wrong by using print(repr(y)).
That gave me the following result.</p>
... | 1 | 2016-08-18T10:06:23Z | 39,015,487 | <pre><code>>>> y = str(u'\r\n 450,990\r\n ')
>>> map(float, y.strip().split(','))
[450.0, 990.0]
>>> float(y.strip().replace(',',''))
450990.0
>>> float(y.strip().replace(',','.'))
450.99
</code></pre>
| 0 | 2016-08-18T10:10:42Z | [
"python",
"python-unicode"
] |
Avoiding string + integer addition when using recursive function | 39,015,523 | <p>I am trying to build a function(which uses function recursion) that scans a number, n, to look for a digit d, & if found, I would like to replace d with a specified number r, as shown in the code below. This code works fine but the output is in a string format. I have tried numerous ways to change it to output a... | 1 | 2016-08-18T10:12:25Z | 39,015,794 | <p>It's quite simple but you need some type conversions between <code>str</code> and <code>int</code>:</p>
<pre><code>def replace_digit(n, d, r):
number = str(n)
rest = str(replace_digit(int(number[1:]), d, r)) if len(number) > 1 else ""
digit = number[0]
digit = str(r) if digit == str(d) else digit... | 0 | 2016-08-18T10:26:20Z | [
"python",
"python-3.x",
"recursion"
] |
Avoiding string + integer addition when using recursive function | 39,015,523 | <p>I am trying to build a function(which uses function recursion) that scans a number, n, to look for a digit d, & if found, I would like to replace d with a specified number r, as shown in the code below. This code works fine but the output is in a string format. I have tried numerous ways to change it to output a... | 1 | 2016-08-18T10:12:25Z | 39,015,997 | <p>If you already have a working function why not just split the problem ?</p>
<pre><code>def replace(n, d, r):
def replace_digit(n, d, r): # doesn't change
return ...
return int(replace_digit(str(n), str(d), str(r))
</code></pre>
| 0 | 2016-08-18T10:35:47Z | [
"python",
"python-3.x",
"recursion"
] |
Avoiding string + integer addition when using recursive function | 39,015,523 | <p>I am trying to build a function(which uses function recursion) that scans a number, n, to look for a digit d, & if found, I would like to replace d with a specified number r, as shown in the code below. This code works fine but the output is in a string format. I have tried numerous ways to change it to output a... | 1 | 2016-08-18T10:12:25Z | 39,016,241 | <p>The solution is to wrap the return values with <code>int()</code> as has been already been stated in the comments and other answers.</p>
<p>But here's a version that doesn't use string manipulation at all. Just for fun.</p>
<pre><code>def replace_digit(n, d, r):
rest = n // 10 # all but the rightmost digit
... | 0 | 2016-08-18T10:47:54Z | [
"python",
"python-3.x",
"recursion"
] |
Avoiding string + integer addition when using recursive function | 39,015,523 | <p>I am trying to build a function(which uses function recursion) that scans a number, n, to look for a digit d, & if found, I would like to replace d with a specified number r, as shown in the code below. This code works fine but the output is in a string format. I have tried numerous ways to change it to output a... | 1 | 2016-08-18T10:12:25Z | 39,019,046 | <p>Instead of returning the concatenation try this:</p>
<pre><code>if number[i] == str(d):
new_number = number[:i] + str(r) + replace_digit(int(number[i+1:]),d,r)
else:
new_number = number[i] + replace_digit(int(number[i+1:]),d ,r)
return int(new_number)
</code></pre>
| 0 | 2016-08-18T13:05:46Z | [
"python",
"python-3.x",
"recursion"
] |
Avoiding string + integer addition when using recursive function | 39,015,523 | <p>I am trying to build a function(which uses function recursion) that scans a number, n, to look for a digit d, & if found, I would like to replace d with a specified number r, as shown in the code below. This code works fine but the output is in a string format. I have tried numerous ways to change it to output a... | 1 | 2016-08-18T10:12:25Z | 39,028,542 | <pre><code>def replace_digit(number, digit, replacement):
if number == 0:
return number # base case
quotient, remainder = divmod(number, 10)
if remainder == digit:
remainder = replacement
return replace_digit(quotient, digit, replacement) * 10 + remainder
print(replace_digit(96174... | 1 | 2016-08-18T22:36:13Z | [
"python",
"python-3.x",
"recursion"
] |
How to annotate a method that returns a specific type (or subtype) | 39,015,600 | <p>Please consider this snippet of python 3.5 code:</p>
<pre><code>class Foo:
pass
class Bar(Foo):
pass
class AbstractSomething:
def get_foobinator_type(self):
return Foo
</code></pre>
<p>I'd like to annotate (<a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">using PEP-0484 a... | 0 | 2016-08-18T10:16:23Z | 39,016,491 | <p>I think what you need is TypeVar from the typing module.</p>
<pre><code>from typing import TypeVar
class Foo:
pass
class Bar(Foo):
pass
T = TypeVar('T', bound=Foo)
class AbstractSomething:
def get_foobinator_type(self) -> T:
return Foo
</code></pre>
<p><a href="https://docs.python.org... | 0 | 2016-08-18T10:59:45Z | [
"python",
"python-3.x"
] |
How to annotate a method that returns a specific type (or subtype) | 39,015,600 | <p>Please consider this snippet of python 3.5 code:</p>
<pre><code>class Foo:
pass
class Bar(Foo):
pass
class AbstractSomething:
def get_foobinator_type(self):
return Foo
</code></pre>
<p>I'd like to annotate (<a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">using PEP-0484 a... | 0 | 2016-08-18T10:16:23Z | 39,017,178 | <p>As far as I understand, you really cannot. You're looking for a way to indicate the return <em>type</em> of a <strong>class</strong>; to check based on what the type of the class is, i.e its metaclass. </p>
<p>The problem with that is that a metaclass doesn't help a type checker evaluate what the inheritance of an ... | 1 | 2016-08-18T11:34:45Z | [
"python",
"python-3.x"
] |
Pandas bin and count | 39,015,635 | <p>I'm new to Pandas, please don't be too harsh ;) Let's assume my initial data frame looks like this:</p>
<pre><code>#::: initialize dictionary
np.random.seed(0)
d = {}
d['size'] = 2 * np.random.randn(100) + 3
d['flag_A'] = np.random.randint(0,2,100).astype(bool)
d['flag_B'] = np.random.randint(0,2,100).astype(bool)
... | 0 | 2016-08-18T10:18:30Z | 39,016,203 | <p>It can be achieved with multi-index groupbys, concatenating the results and unstacking:</p>
<pre><code>flag_A = df.groupby( [pd.cut( df['size'], bins),'flag_A'] ).count()['size'].to_frame()
flag_B = df.groupby( [pd.cut( df['size'], bins),'flag_B'] ).count()['size'].to_frame()
flag_C = df.groupby( [pd.cut( df['size'... | 3 | 2016-08-18T10:46:02Z | [
"python",
"pandas",
"count",
"histogram",
"bin"
] |
Pandas bin and count | 39,015,635 | <p>I'm new to Pandas, please don't be too harsh ;) Let's assume my initial data frame looks like this:</p>
<pre><code>#::: initialize dictionary
np.random.seed(0)
d = {}
d['size'] = 2 * np.random.randn(100) + 3
d['flag_A'] = np.random.randint(0,2,100).astype(bool)
d['flag_B'] = np.random.randint(0,2,100).astype(bool)
... | 0 | 2016-08-18T10:18:30Z | 39,017,407 | <p>You can apply your group to the DF then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow">pd.melt</a>:</p>
<pre><code>df['group'] = pd.cut(df['size'], bins=bins)
melted = pd.melt(df, id_vars='group', value_vars=['flag_A', 'flag_B', 'flag_C'])
</code></pre>
<p>Which'll ... | 2 | 2016-08-18T11:46:12Z | [
"python",
"pandas",
"count",
"histogram",
"bin"
] |
Mean of sum in a DataFrame with Python | 39,015,648 | <p>I create a DataFrame df1 which contains for each day of the week the number of activation time for each machine.</p>
<pre><code>machine1 38696 non-null float64
machine3 38697 non-null float64
machine5 38695 non-null float64
machine6 38695 non-null float64
machine7 38693 non-null float64
machine8 ... | 2 | 2016-08-18T10:19:07Z | 39,015,725 | <p>IIUC you can use:</p>
<pre><code>print (df.groupby('day_of_week').mean())
Machine1 Machine3 Machine5 Machine6 Machine7 Machine8
day_of_week
Fri 45.0 45.0 45.0 45.0 45.0 45.0
Mon 0.0 ... | 3 | 2016-08-18T10:22:45Z | [
"python",
"pandas",
"dataframe",
"group-by",
"mean"
] |
Evaluate sum of step functions | 39,015,649 | <p>I have a fairly large number (around 1000) of step functions, each with only two intervals. I'd like to sum them up and then find the maximum value. What is the best way to do this? I've tried out sympy, with code as follows:</p>
<pre><code>from sympy import Piecewise, piecewise_fold, evalf
from sympy.abc import x... | 2 | 2016-08-18T10:19:07Z | 39,015,929 | <p>What about using <a href="http://docs.sympy.org/latest/tutorial/basic_operations.html#substitution" rel="nofollow">substitution</a>? Try changing <code>sum_piecewise.evalf(0.2)</code> by <code>sum_piecewise.subs(x, 0.2)</code></p>
| 0 | 2016-08-18T10:32:54Z | [
"python",
"numpy",
"scipy",
"sympy"
] |
Evaluate sum of step functions | 39,015,649 | <p>I have a fairly large number (around 1000) of step functions, each with only two intervals. I'd like to sum them up and then find the maximum value. What is the best way to do this? I've tried out sympy, with code as follows:</p>
<pre><code>from sympy import Piecewise, piecewise_fold, evalf
from sympy.abc import x... | 2 | 2016-08-18T10:19:07Z | 39,016,605 | <p>As it appears that you consider numerical functions, it is better (in terms of performance) to work with Numpy. Here's one approach:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
np.random.seed(10)
S = 20 # number of piecewise functions
# generate S function parameters.
# For example, the k-t... | 2 | 2016-08-18T11:06:33Z | [
"python",
"numpy",
"scipy",
"sympy"
] |
Which selenium python package should I be using? | 39,015,690 | <p>I'm using <code>Python 3.5.1 |Anaconda 2.4.0 (x86_64) on a Mac OS X 10.11.6</code></p>
<p>Should I be using selenium-3.0.0b2 <a href="https://pypi.python.org/pypi/selenium" rel="nofollow">https://pypi.python.org/pypi/selenium</a></p>
<p>or should I be using selenium-2.53.6 <a href="https://pypi.python.org/pypi/sel... | 1 | 2016-08-18T10:21:19Z | 39,019,497 | <p>I guess, using pip is quite a good practice.
Also, as far as I know, your problems more likely will be about communication with selenium-standalone and your selenium, so firstly you should check which bunch is stable at the moment.</p>
| 1 | 2016-08-18T13:28:50Z | [
"python",
"selenium"
] |
Django query to annotate number of foreign keys matching certain value | 39,015,704 | <p>If I had the following related models:</p>
<pre><code>class User(models.Model):
...
class Identity(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT)
category = models.CharField(max_length=8, choices=IDENTITY_CATEGORIES)
...
</code></pre>
<p>How could I query for users with m... | 0 | 2016-08-18T10:21:52Z | 39,015,705 | <p>By applying <code>django.db.models.Sum</code>, here's one way of achieving it:</p>
<pre><code>from django.db.models import Case, IntegerField, Sum, When
def users_with_multiple_email_identities():
"""
Return a queryset of Users who have multiple email identities.
"""
return (
User.objects
... | 0 | 2016-08-18T10:21:52Z | [
"python",
"django",
"orm",
"django-queryset"
] |
dlib train_object_detector immense amounts of RAM usage | 39,015,782 | <p>I am using dlib's <em>train_object_detector</em> for face detection and I have roughly 6k images in a folder with which I am trying to train my model.</p>
<p>Also, I am using dlib's example python code(train_object_detector.py) for this purpose.</p>
<p>But the thing is, the program's RAM usage is insane. For rough... | 1 | 2016-08-18T10:25:47Z | 39,016,727 | <p>This is happening because you have a combination of big images and/or small bounding boxes. By default, dlib.train_simple_object_detector uses a detection window that is 6400 pixels in size. If images contain target boxes much smaller than this then those images are upsampled to make the objects big enough. </p>
... | 1 | 2016-08-18T11:12:58Z | [
"python",
"face-detection",
"dlib"
] |
How to test only one function with tox? | 39,015,885 | <p>I'm learning to write tests with tox. How do I test only one function with tox? For example if I want to test only <code>test_simple_backup_generation</code> from <code>tests/test_backup_cmd.py</code> of <code>django-backup</code> <a href="https://github.com/django-backup/django-backup" rel="nofollow">extension</a><... | 0 | 2016-08-18T10:30:36Z | 39,016,416 | <p>If you define a parameter <code>{posargs}</code> in your <code>tox.ini</code> you can pass in arguments during execution. In the case of py.test, where</p>
<pre><code>py.test -k test_simple_backup_generation
</code></pre>
<p>would only test one function:</p>
<pre><code>[tox]
envlist = py27,py35
[testenv]
deps=pyt... | 2 | 2016-08-18T10:55:51Z | [
"python",
"testing",
"automated-tests",
"tox"
] |
Comprehension to instantiate a boolean 2D array? | 39,015,925 | <p>I'm new to Python, thus the question,</p>
<p>So I'm trying to instantiate a 2D array/list with all false of the size str +1 rows and pattern +1 cols.</p>
<p>Here's my code,</p>
<pre><code>memo = []
for i in range(0, len(str) + 1):
memo[i] = [[False] for j in range(len(pattern) + 1)]
</code></pre>
<p>Now I'v... | 2 | 2016-08-18T10:32:44Z | 39,016,049 | <p>A one-liner would be <br/> <code>memo = [[False for j in range(len(pattern) + 1)] for i in range(len(str) + 1)]</code>.</p>
<p>As a side-note, keep in mind that using <code>str</code> as a variable name should be avoided as it shadows the built-in <code>str</code> type.</p>
<blockquote>
<p>if I just create the l... | 4 | 2016-08-18T10:38:24Z | [
"python",
"arrays",
"boolean"
] |
Comprehension to instantiate a boolean 2D array? | 39,015,925 | <p>I'm new to Python, thus the question,</p>
<p>So I'm trying to instantiate a 2D array/list with all false of the size str +1 rows and pattern +1 cols.</p>
<p>Here's my code,</p>
<pre><code>memo = []
for i in range(0, len(str) + 1):
memo[i] = [[False] for j in range(len(pattern) + 1)]
</code></pre>
<p>Now I'v... | 2 | 2016-08-18T10:32:44Z | 39,016,086 | <p>Using <a href="https://docs.python.org/2/library/itertools.html#itertools.repeat" rel="nofollow"><code>itertools.repeat</code></a> aproach, fully loaded in a generator:</p>
<pre><code>memo = itertools.repeat(itertools.repeat(False, xrange(len(pattern) + 1)), xrange(len(str) + 1))
</code></pre>
| 1 | 2016-08-18T10:40:37Z | [
"python",
"arrays",
"boolean"
] |
Comprehension to instantiate a boolean 2D array? | 39,015,925 | <p>I'm new to Python, thus the question,</p>
<p>So I'm trying to instantiate a 2D array/list with all false of the size str +1 rows and pattern +1 cols.</p>
<p>Here's my code,</p>
<pre><code>memo = []
for i in range(0, len(str) + 1):
memo[i] = [[False] for j in range(len(pattern) + 1)]
</code></pre>
<p>Now I'v... | 2 | 2016-08-18T10:32:44Z | 39,016,184 | <p>Depending on how big the 2d list is and what you plan to do with it, you might also consider using a <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html" rel="nofollow">numpy ndarray</a> to store the data:</p>
<pre><code>import numpy as np
memo = np.full((len(str) + 1, len(pattern) + 1),... | 1 | 2016-08-18T10:45:20Z | [
"python",
"arrays",
"boolean"
] |
Comprehension to instantiate a boolean 2D array? | 39,015,925 | <p>I'm new to Python, thus the question,</p>
<p>So I'm trying to instantiate a 2D array/list with all false of the size str +1 rows and pattern +1 cols.</p>
<p>Here's my code,</p>
<pre><code>memo = []
for i in range(0, len(str) + 1):
memo[i] = [[False] for j in range(len(pattern) + 1)]
</code></pre>
<p>Now I'v... | 2 | 2016-08-18T10:32:44Z | 39,016,453 | <p>A short hand way would be to write:</p>
<pre><code>ncols = 3 # len(string1) + 1
nrows = 4 # len(pattern1) + 1
memo = nrows * [ncols*[False]]
>>> [[False, False, False], [False, False, False], [False, False, False], [False, False, False]]
</code></pre>
<p>In this case the second part [ncols*[False]] ma... | 1 | 2016-08-18T10:57:45Z | [
"python",
"arrays",
"boolean"
] |
Comprehension to instantiate a boolean 2D array? | 39,015,925 | <p>I'm new to Python, thus the question,</p>
<p>So I'm trying to instantiate a 2D array/list with all false of the size str +1 rows and pattern +1 cols.</p>
<p>Here's my code,</p>
<pre><code>memo = []
for i in range(0, len(str) + 1):
memo[i] = [[False] for j in range(len(pattern) + 1)]
</code></pre>
<p>Now I'v... | 2 | 2016-08-18T10:32:44Z | 39,016,464 | <p>This is the shortest list comprehension I can think of:</p>
<pre><code>memo = [[False] * (len(pattern)+1) for i in range(len(str)+1)]
</code></pre>
<p>If you create the list and don't initialize it, it will be empty.</p>
<p>One alternative to work around having to do that would be to represent the 2D array as a <... | 1 | 2016-08-18T10:58:23Z | [
"python",
"arrays",
"boolean"
] |
Sort a column containing string in Pandas | 39,015,931 | <p>I am new to Pandas, and looking to sort a column containing strings and generate a numerical value to uniquely identify the string. My data frame looks something like this:</p>
<pre><code>df = pd.DataFrame({'key': range(8), 'year_week': ['2015_10', '2015_1', '2015_11', '2016_9', '2016_10','2016_3', '2016_9', '2016_... | 1 | 2016-08-18T10:33:04Z | 39,016,168 | <p>You can first convert <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> column <code>year_week</code>, then sort it by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><co... | 3 | 2016-08-18T10:44:41Z | [
"python",
"sorting",
"pandas",
"dataframe",
"categorical-data"
] |
How to find non-zero median/mean of multiple columns in pandas? | 39,016,017 | <p>I have a long list of columns for which I want to calculate non-zero median,mean & std in a one go. I cannot just delete rows with 0 based on 1 column because the value for another column in same column may not be 0.</p>
<p>Below is the code I currently have which calculates median,mean etc. including zero.</p>... | 1 | 2016-08-18T10:36:46Z | 39,016,522 | <p>You can temporarily replace 0's with NaNs. Then, pandas will ignore the NaNs while calculating medians.</p>
<pre><code>df_tmp.replace(0, np.nan).groupby(['id']).agg(agg_list_oper).reset_index()
</code></pre>
| 1 | 2016-08-18T11:01:06Z | [
"python",
"pandas",
"aggregate-functions",
"median",
"summarization"
] |
wxPython program - render HTML | 39,016,022 | <p>Is it possible to render HTML in a Python window, using wxPython as the GUI builder.</p>
<p>For example, I give a program the URL <a href="http://google.com" rel="nofollow">http://google.com</a> and then it loads up that domain name and renders it in a window below, but still in the confines of the Python program.<... | 0 | 2016-08-18T10:37:00Z | 39,021,695 | <p>Maybe it is simpler to check the <a href="https://www.wxpython.org/download.php" rel="nofollow">wxPython demo</a>. It contains two applied examples (search for html), one simple renderer (no CSS) and an advanced one which uses the rendering engine of the underlying platform to display HTML.</p>
| 0 | 2016-08-18T15:08:12Z | [
"python",
"wxpython"
] |
python callbacks vs exceptions in control flow | 39,016,028 | <p>What is more python for control flow, callbacks or exceptions? For example if i wrote a user login logic i can write it in this ways:</p>
<p>Exceptions</p>
<pre><code> try:
valid_data = validate(form)
try:
do_login(valid_data)
return SuccessLoginTemplate()
... | 1 | 2016-08-18T10:37:15Z | 39,016,436 | <p>IMO, you have 3 obvious contexts: 1 <code>try</code> and 2 distinct <code>except</code>s with all variables and stuff explicitly manipulated and passed while with callbacks you don't know from (unless you write docs or anything like this) expression at least what are the arguments for the callbacks you're passing. E... | 0 | 2016-08-18T10:56:54Z | [
"python",
"callback",
"control-flow"
] |
install a package with pip (or pip3) in python3 | 39,016,067 | <p>ubuntu 14.04</p>
<p>I'm new to python and I'm having trouble installing packages. I've looked at similar questions to mine, but it's hard to tell if it's relevant and up to date.</p>
<p>I'm not sure what I need to do to get this to work.</p>
<pre><code>pip --version
The program 'pip' is currently not installed. Y... | 1 | 2016-08-18T10:39:29Z | 39,016,181 | <p>If you have several versions of python, make sure to navigate in the directory of the python version you want to use, go to 'Scripts' folder and run the pip command there. Hope this works.</p>
| 0 | 2016-08-18T10:45:16Z | [
"python",
"ubuntu",
"pip"
] |
install a package with pip (or pip3) in python3 | 39,016,067 | <p>ubuntu 14.04</p>
<p>I'm new to python and I'm having trouble installing packages. I've looked at similar questions to mine, but it's hard to tell if it's relevant and up to date.</p>
<p>I'm not sure what I need to do to get this to work.</p>
<pre><code>pip --version
The program 'pip' is currently not installed. Y... | 1 | 2016-08-18T10:39:29Z | 39,016,437 | <p>It seems this package is not available on PyPi. What are you trying to install?
Your pip version is quite old - pip 1.5.4. <a href="https://pip.pypa.io/en/stable/" rel="nofollow">current version is 8.1.2</a>.</p>
<p>You can also use <code>pip install -v</code> to get more information while installing.</p>
| 0 | 2016-08-18T10:56:55Z | [
"python",
"ubuntu",
"pip"
] |
Service and version displayed via nmap scan for simple python socket server | 39,016,100 | <p>I've got a simple python socket server. Here's the code:</p>
<pre><code>import socket
host = "0.0.0.0" # address to bind on.
port = 8081
def listen_serv():
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port... | 0 | 2016-08-18T10:41:11Z | 39,037,482 | <p>Found a solution by sending the following line as the first message from the server</p>
<pre><code>c.send("HTTP/1.1 200 OK\r\nServer: Netscape-Enterprise/6.1\r\nDate: Fri, 19 Aug 2016 10:28:43 GMT\r\nContent-Type: text/html; charset=UTF-8\r\nConnection: close\r\nVary: Accept-Encoding\n\nContent-Length: 32092\r\n\n\... | 1 | 2016-08-19T11:05:45Z | [
"python",
"sockets",
"banner",
"nmap"
] |
How to drop a row from Pandas dataframe? | 39,016,158 | <p>This question is similar to <a href="http://stackoverflow.com/questions/14661701/how-to-drop-a-list-of-rows-from-pandas-dataframe">this question</a> posted before. However, I want to do something different, here is my <code>df</code>:</p>
<pre><code> pos event
A 4 d5
A 2 d3
B 3 d3
B 6... | 2 | 2016-08-18T10:44:08Z | 39,016,365 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with <code>|</code> (<code>or</code>):</p>
<pre><code>print (df[(df['event']!='d3') | (df.index != 'B')])
pos event
A 4 d5
A 2 d3
B 6 u3
</code></pre... | 3 | 2016-08-18T10:53:17Z | [
"python",
"pandas",
"indexing",
"dataframe"
] |
Replace multiline existing output in python | 39,016,202 | <p>In python 3 , there have been answers about how to replace an existing output with another.
These answers suggest the use of end='\r' ad in print('hello', end='\r')
This is working ofcourse, but it works only for one line .</p>
<p>In the program that I post below, I first output 5 lines which is the representatio... | 0 | 2016-08-18T10:45:58Z | 39,016,290 | <p>Unless you want to use curses (which is another big step), you cannot go back by several lines.</p>
<p>BUT what you can do is clear the screen and redisplay everything.</p>
<pre><code>print(chr(27) + "[2J")
</code></pre>
<p>clears the screen</p>
<p>(as stated in <a href="http://stackoverflow.com/questions/208450... | 0 | 2016-08-18T10:49:51Z | [
"python",
"python-2.7",
"python-3.x",
"ipython",
"jupyter-notebook"
] |
Replace multiline existing output in python | 39,016,202 | <p>In python 3 , there have been answers about how to replace an existing output with another.
These answers suggest the use of end='\r' ad in print('hello', end='\r')
This is working ofcourse, but it works only for one line .</p>
<p>In the program that I post below, I first output 5 lines which is the representatio... | 0 | 2016-08-18T10:45:58Z | 39,016,449 | <p>You can clear the screen before printing the board.</p>
<pre><code>def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
import os
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS... | 0 | 2016-08-18T10:57:39Z | [
"python",
"python-2.7",
"python-3.x",
"ipython",
"jupyter-notebook"
] |
Replace multiline existing output in python | 39,016,202 | <p>In python 3 , there have been answers about how to replace an existing output with another.
These answers suggest the use of end='\r' ad in print('hello', end='\r')
This is working ofcourse, but it works only for one line .</p>
<p>In the program that I post below, I first output 5 lines which is the representatio... | 0 | 2016-08-18T10:45:58Z | 39,016,920 | <p>What about trying to use a portable solution using terminal's clear command, for example:</p>
<pre><code>from __future__ import print_function
import os
class Game:
def __init__(self):
self.running = True
self.list1 = [' ' * 11, '|', ' ' * 7, '|', ' ' * 10]
def clear_sceen(self):
... | 0 | 2016-08-18T11:21:42Z | [
"python",
"python-2.7",
"python-3.x",
"ipython",
"jupyter-notebook"
] |
Python 2 and 3 in Powershell | 39,016,249 | <p>I have both versions on my PC because I'm working through different tutorials, (I'm still a noob). I've seen a couple of similar questions on here, but nothing specific to Powershell.</p>
<p>When I run <strong>python</strong> in Powershell it brings up 2.7, but how do I specify that I want Python 3? Are there other... | 1 | 2016-08-18T10:48:08Z | 39,016,480 | <p>You can install Python3 <a href="https://chocolatey.org/packages/python3" rel="nofollow">via Chocolatey</a>, AFAIK it will bring <code>python3</code> command into your realm. Do not forget to uninstall previously installed Python3 before it.</p>
<p>Also, you may try to create alias for Python3, see Microsoft <a hre... | 0 | 2016-08-18T10:59:04Z | [
"python",
"powershell"
] |
Python 2 and 3 in Powershell | 39,016,249 | <p>I have both versions on my PC because I'm working through different tutorials, (I'm still a noob). I've seen a couple of similar questions on here, but nothing specific to Powershell.</p>
<p>When I run <strong>python</strong> in Powershell it brings up 2.7, but how do I specify that I want Python 3? Are there other... | 1 | 2016-08-18T10:48:08Z | 39,017,335 | <p>The command "py" (if v2 is the default) or "py -2" should launch Python 2.7, "py -3" should launch Python 3. See <a href="http://stackoverflow.com/a/13328713/6683985">here</a> for the details.</p>
<p>I've found this <a href="http://stackoverflow.com/a/20371084/6683985">post</a> as well. It might be helpful.</p>
<p... | 2 | 2016-08-18T11:42:36Z | [
"python",
"powershell"
] |
Pandas dataframe If else with logical AND involving two columns | 39,016,405 | <p>How to add logical <code>AND</code> in a control statement involving two columns of a pandas dataframe i.e.</p>
<p>This works:</p>
<pre><code>def getContinent(row):
if row['Location'] in ['US','Canada']:
val = 'North America'
elif row['Location'] in['UK', 'Germany']:
val = 'Europe'
else... | 1 | 2016-08-18T10:55:08Z | 39,016,467 | <p>You need use <code>and</code> instead <code>&</code>:</p>
<pre><code>df = pd.DataFrame({'Sales': {0: 400, 1: 20, 2: 300},
'Location': {0: 'US', 1: 'UK', 2: 'Slovakia'}})
print (df)
Location Sales
0 US 400
1 UK 20
2 Slovakia 300
def getContinent(row):
if row... | 2 | 2016-08-18T10:58:33Z | [
"python",
"pandas",
"if-statement",
"dataframe",
"apply"
] |
AnalysisException: u"cannot resolve 'name' given input columns: [ list] in sqlContext in spark | 39,016,440 | <p>I tried a simple example like:</p>
<pre><code>data = sqlContext.read.format("csv").option("header", "true").option("inferSchema", "true").load("/databricks-datasets/samples/population-vs-price/data_geo.csv")
data.cache() # Cache data for faster reuse
data = data.dropna() # drop rows with missing values
data = data... | 0 | 2016-08-18T10:57:02Z | 39,024,551 | <p>I found the issue: some of the column names contain white spaces before the name itself.
So </p>
<pre><code>data = data.select(" timedelta", " shares").map(lambda r: LabeledPoint(r[1], [r[0]])).toDF()
</code></pre>
<p>worked.
I could catch the white spaces using </p>
<pre><code>assert " " not in ''.join(df.colum... | 0 | 2016-08-18T17:48:44Z | [
"python",
"apache-spark",
"linear-regression"
] |
How to contain an object and call its method in a class? | 39,016,463 | <p>I have two classes (<code>ClassA</code> and <code>ClassB</code>) and <code>ClassA</code> contains one object, <code>b</code>, that is an instance of <code>ClassB</code>. The question is that I can't call the <code>b</code>'s method in <code>Class A</code>.</p>
<pre><code>class ClassB(object):
def __init__(self)... | -2 | 2016-08-18T10:58:21Z | 39,016,508 | <p>By doing <code>__classb = classb</code> you are only defining a local <code>__classb</code> variable in the <code>__init__</code> method. </p>
<p>If you want <code>__classb</code> to be an instance attribute you will need to use <code>self</code>:</p>
<pre><code>self.__classb = classb
</code></pre>
<p>And then:</... | 3 | 2016-08-18T11:00:28Z | [
"python"
] |
How to contain an object and call its method in a class? | 39,016,463 | <p>I have two classes (<code>ClassA</code> and <code>ClassB</code>) and <code>ClassA</code> contains one object, <code>b</code>, that is an instance of <code>ClassB</code>. The question is that I can't call the <code>b</code>'s method in <code>Class A</code>.</p>
<pre><code>class ClassB(object):
def __init__(self)... | -2 | 2016-08-18T10:58:21Z | 39,016,547 | <p>You should create a attribute for a instance of class B in class A like that self.__classb.
Following code</p>
<pre><code> class ClassB(object):
def __init__(self):
print('Class B init ...')
def show(self):
print('Showing class b')
class ClassA(object):
def ... | 1 | 2016-08-18T11:02:32Z | [
"python"
] |
Asserting call with lambda | 39,016,487 | <p>I have this piece of code:</p>
<pre><code>from shutil import rmtree
def ook(path):
rmtree(path, onerror=lambda x, y, z: self._logger.warn(z[1]))
</code></pre>
<p>In my unit tests, I want to mock it so check that right <code>path</code> is passed:</p>
<pre><code>from mock import patch, ANY
@patch("rmtree")
d... | 0 | 2016-08-18T10:59:28Z | 39,016,617 | <p>I would do this with the <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_args" rel="nofollow"><code>call_args</code></a> and <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_count" rel="nofollow"><code>call_count</code></a> rather than direct... | 1 | 2016-08-18T11:07:14Z | [
"python",
"mocking",
"python-mock"
] |
Pygame - when i push a button and then another | 39,016,509 | <p>First of all, here is my code:</p>
<pre><code>while not crashed:
curr_event = pygame.event.get()
if (len(curr_event) == 2):
print curr_event[0],'\n',curr_event[1],'\n\n\n'
for event in curr_event:
if event.type == pygame.KEYUP and not len(curr_event) == 1:
continue
... | 0 | 2016-08-18T11:00:33Z | 39,018,581 | <p>Moving the mouse, pressing buttons and other actions counts as events and are put in the queue, so the code <code>if event.type == pygame.KEYUP and not len(curr_event) == 1: continue</code> might be unreliable.</p>
<h2>Solution</h2>
<p>You could check the state of the button (if it's being held down or not) rather... | 0 | 2016-08-18T12:43:50Z | [
"python",
"pygame"
] |
SPSS - Python functions in startup script | 39,016,549 | <p>Following up on <a href="http://stackoverflow.com/questions/35936239/quickly-import-custom-spss-commands-from-python">this question and it's answer</a>, I am trying to create an SPSS custom function in Python, to use in SPSS syntax. </p>
<p>I have a program that works well in a syntax:</p>
<pre><code>begin program... | 1 | 2016-08-18T11:02:41Z | 39,039,984 | <p>Standard syntax does not use Python code nor does it add Python functions to, say, the transformation system. If you have a Python module, its contents can be used directly by just importing that module. And don't worry about importing it multiple times as Python is smart about ignoring redundant imports.</p>
<p>... | 1 | 2016-08-19T13:12:45Z | [
"python",
"function",
"spss"
] |
Pandas: convert column of dataframe to datetime | 39,016,627 | <p>I have df </p>
<pre><code>ID month
0 0001ee12f919a1b570658024bb59d118 2014-02
1 0001ee12f919a1b570658024bb59d118 2014-03
2 0001ee12f919a1b570658024bb59d118 2014-04
3 0001ee12f919a1b570658024bb59d118 2014-05
4 0001ee12f919a1b57... | 1 | 2016-08-18T11:07:43Z | 39,016,651 | <p>You need to pass a format string <code>'%Y-%m'</code> as <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> can't deduce the format from your string:</p>
<pre><code>In [42]:
df['date'] = pd.to_datetime(df['month'], format='%Y-%m')
df
... | 1 | 2016-08-18T11:08:37Z | [
"python",
"datetime",
"pandas"
] |
Convert numpy matrix to python array | 39,016,638 | <p>Are there alternative or better ways to convert a numpy matrix to a python array than this?</p>
<pre><code>>>> import numpy
>>> import array
>>> b = numpy.matrix("1.0 2.0 3.0; 4.0 5.0 6.0", dtype="float16")
>>> print(b)
[[ 1. 2. 3.]
[ 4. 5. 6.]]
>>> a = array.array(... | 1 | 2016-08-18T11:08:03Z | 39,016,730 | <p>You could convert to a <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html" rel="nofollow"><code>NumPy array</code></a> and generate its flattened version with <code>.ravel()</code> or <code>.flatten()</code>. This could also be achieved by simply using the function <a href="http://docs.sci... | 0 | 2016-08-18T11:13:09Z | [
"python",
"arrays",
"numpy"
] |
Convert numpy matrix to python array | 39,016,638 | <p>Are there alternative or better ways to convert a numpy matrix to a python array than this?</p>
<pre><code>>>> import numpy
>>> import array
>>> b = numpy.matrix("1.0 2.0 3.0; 4.0 5.0 6.0", dtype="float16")
>>> print(b)
[[ 1. 2. 3.]
[ 4. 5. 6.]]
>>> a = array.array(... | 1 | 2016-08-18T11:08:03Z | 39,016,751 | <p>here is an example :</p>
<pre><code>>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.tolist()
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
</code></pre>
| -1 | 2016-08-18T11:13:50Z | [
"python",
"arrays",
"numpy"
] |
Python how to delete a line in a table | 39,016,758 | <p>I using Python and a function give me this output:</p>
<pre><code> [['2', 'prod1', 'Ela - Available'], ['2', 'prod1', 'Base - Replication logs']]
</code></pre>
<p>My goal it's to delete all lines contains "Available" with Python</p>
<p>So my goal it's to have:</p>
<pre><code>[['2', 'prod1', 'Base - Replication l... | 0 | 2016-08-18T11:14:08Z | 39,016,877 | <pre><code>>>> l = [['2', 'prod1', 'Ela - Available'], ['2', 'prod1', 'Base - Replication logs']]
>>> filter(lambda x: not any('Available' in y for y in x), l)
[['2', 'prod1', 'Base - Replication logs']]
</code></pre>
| 3 | 2016-08-18T11:19:57Z | [
"python"
] |
Python how to delete a line in a table | 39,016,758 | <p>I using Python and a function give me this output:</p>
<pre><code> [['2', 'prod1', 'Ela - Available'], ['2', 'prod1', 'Base - Replication logs']]
</code></pre>
<p>My goal it's to delete all lines contains "Available" with Python</p>
<p>So my goal it's to have:</p>
<pre><code>[['2', 'prod1', 'Base - Replication l... | 0 | 2016-08-18T11:14:08Z | 39,016,904 | <p>Try this :</p>
<pre><code>data = [['2', 'prod1', 'Ela - Available'], ['2', 'prod1', 'Base - Replication logs']]
output = [line for line in data if not 'Available' in str(line)]
print(output)
[['2', 'prod1', 'Base - Replication logs']]
</code></pre>
| 4 | 2016-08-18T11:21:05Z | [
"python"
] |
Minimize total distance between two sets of points in Python | 39,016,821 | <p>Given two sets of points in n-dimensional space, how can one map points from one set to the other, such that each point is only used once and the total euclidean distance between the pairs of points is minimized?</p>
<p>For example,</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
# create six po... | 2 | 2016-08-18T11:16:56Z | 39,017,677 | <p>There's a known algorithm for this, <a href="http://www.math.harvard.edu/archive/20_spring_05/handouts/assignment_overheads.pdf" rel="nofollow">The Hungarian Method For Assignment</a>, which works in time <em>O(n<sup>3</sup>)</em>. </p>
<p>In SciPy, you can find an implementation in <a href="http://docs.scipy.org/d... | 2 | 2016-08-18T11:59:32Z | [
"python",
"scipy",
"euclidean-distance"
] |
Minimize total distance between two sets of points in Python | 39,016,821 | <p>Given two sets of points in n-dimensional space, how can one map points from one set to the other, such that each point is only used once and the total euclidean distance between the pairs of points is minimized?</p>
<p>For example,</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
# create six po... | 2 | 2016-08-18T11:16:56Z | 39,019,606 | <p>An example of assigning (mapping) elements of one set to points to the elements of another set of points, such that the sum Euclidean distance is minimized.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
from scipy.optimize import linear_sum_assignment
np... | 1 | 2016-08-18T13:32:36Z | [
"python",
"scipy",
"euclidean-distance"
] |
How to remove duplicate links in text file? | 39,016,909 | <p>So I have a text file that inside looks like this:</p>
<pre><code>http://example.pl/folder/this_same1.avi
http://example.pl/folder/this_same1.avi
http://example.pl/folder/this_same2.avi
http://example.pl/folder/this_same2.avi
http://example.pl/folder/this_same3.avi
http://example.pl/folder/this_same3.avi
</code></p... | -3 | 2016-08-18T11:21:18Z | 39,017,003 | <p>Oh I've improved my answer: </p>
<pre><code>links = set()
with open('file.txt', 'r') as fp:
for line in fp.readlines():
links.add(line)
</code></pre>
<p>Then you can write back to the file:</p>
<pre><code>with open('file.txt', 'wb') as fp:
for line in links:
fp.write(line)
</code></pre>
<... | 1 | 2016-08-18T11:26:00Z | [
"python",
"parsing",
"hyperlink",
"duplicates",
"text-parsing"
] |
How to remove duplicate links in text file? | 39,016,909 | <p>So I have a text file that inside looks like this:</p>
<pre><code>http://example.pl/folder/this_same1.avi
http://example.pl/folder/this_same1.avi
http://example.pl/folder/this_same2.avi
http://example.pl/folder/this_same2.avi
http://example.pl/folder/this_same3.avi
http://example.pl/folder/this_same3.avi
</code></p... | -3 | 2016-08-18T11:21:18Z | 39,017,208 | <p>If that structure is consistent and order is important:</p>
<pre><code>links = fp.readlines()[::2]
</code></pre>
<p>If structure is not consistent, and order is important:</p>
<pre><code>links = []
for line in fp.readlines():
if line not in links:
links.append(line)
</code></pre>
<p>Then write to fil... | 0 | 2016-08-18T11:36:44Z | [
"python",
"parsing",
"hyperlink",
"duplicates",
"text-parsing"
] |
Django ORM not working for models | 39,016,998 | <p>I've a model Product and it has a sub model Variation for product variations. Now I am trying to add a Shop Model top of Products and I wish to get products listed uploaded by the Shop owner who created the shop. But I am getting an error. Following is my code:</p>
<pre><code>class Product(models.Model):
title ... | 0 | 2016-08-18T11:25:41Z | 39,018,379 | <p>This is strange but once I deleted all my migrations and db again...it worked. Thank you for help.</p>
| 0 | 2016-08-18T12:34:01Z | [
"python",
"django",
"django-models"
] |
How to join two list of tuples without duplicates | 39,017,018 | <p>I am running two queries to a database, the result i get from each, is a list of tuples which is perfect. I would like to join these into one list of tuples. These are examples of the tuples: </p>
<pre><code>list1 = [('abc', 1 ), ('def', 2) ... ]
list2 = [(1000, 'abc'), (2000, 'def' ), (3000, 'def') ... ]
</code... | 1 | 2016-08-18T11:26:34Z | 39,017,134 | <p>You don't need to append <code>i</code> inside the inner loop. Just once at the end of the outer loop.</p>
<pre><code>q = []
for i in list1:
for j in list2:
if i[0] == j[1]:
i = i + (j[0],)
q.append(i)
</code></pre>
<p>There was also a typo in the outer loop. It should be <code>list1</c... | 0 | 2016-08-18T11:32:47Z | [
"python",
"list",
"tuples",
"sql-server-express"
] |
How to join two list of tuples without duplicates | 39,017,018 | <p>I am running two queries to a database, the result i get from each, is a list of tuples which is perfect. I would like to join these into one list of tuples. These are examples of the tuples: </p>
<pre><code>list1 = [('abc', 1 ), ('def', 2) ... ]
list2 = [(1000, 'abc'), (2000, 'def' ), (3000, 'def') ... ]
</code... | 1 | 2016-08-18T11:26:34Z | 39,017,633 | <p>Using nested loops is ok if your lists are fairly small but it soon becomes inefficient for larger lists. Eg, if len(list1) == 10 and len(list2) == 20 the code inside the inner loop is executed 200 times. </p>
<p>Here's an algorithm that builds the desired list of tuples via a dictionary. The dictionary stores the ... | 5 | 2016-08-18T11:57:20Z | [
"python",
"list",
"tuples",
"sql-server-express"
] |
findAll doesn't work, nested tags | 39,017,243 | <p>I'm parsing through <a href="https://www.wired.com/2016/08/live-debate-whats-right-kind-intersection" rel="nofollow">this</a> page. I need to get text content - which is located in <code>p</code> tags. The general structure of the page is the following:</p>
<pre><code><html>
<body>
<artic... | -1 | 2016-08-18T11:38:04Z | 39,017,365 | <p>You should use something like this:</p>
<pre><code>for p in soupArticle.findAll("article", {"itemprop":"articleBody"}):
textList = p.find_all("p")
print(len(textList))
</code></pre>
<p>It probably would help.</p>
| 1 | 2016-08-18T11:44:34Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
findAll doesn't work, nested tags | 39,017,243 | <p>I'm parsing through <a href="https://www.wired.com/2016/08/live-debate-whats-right-kind-intersection" rel="nofollow">this</a> page. I need to get text content - which is located in <code>p</code> tags. The general structure of the page is the following:</p>
<pre><code><html>
<body>
<artic... | -1 | 2016-08-18T11:38:04Z | 39,017,389 | <p>Check the doc, are you sure it is findAll? <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all</a></p>
| -2 | 2016-08-18T11:45:29Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
findAll doesn't work, nested tags | 39,017,243 | <p>I'm parsing through <a href="https://www.wired.com/2016/08/live-debate-whats-right-kind-intersection" rel="nofollow">this</a> page. I need to get text content - which is located in <code>p</code> tags. The general structure of the page is the following:</p>
<pre><code><html>
<body>
<artic... | -1 | 2016-08-18T11:38:04Z | 39,017,953 | <p>The HTML that you see in your browser is not the same as the HTML that you would get if you retrieved it with <code>urllib</code>, <code>requests</code> or other HTTP client - assuming that that's how you obtain the HTML.</p>
<p>That's because the content that you are after is inserted dynamically into the document... | 1 | 2016-08-18T12:13:41Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.