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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Dict Class empty result | 38,433,410 | <p>My datasource provides dicts, I would like to enricht the dicts and use them for something else.
But I can't get my head around the class to make a new dict, whatever I do, it always returns an empty dict.</p>
<pre><code>class car(dict):
def __init__(self, carId, data):
self.carId = carId
self.b... | -1 | 2016-07-18T09:42:01Z | 38,433,664 | <p>You need to change the <code>self.carId = carId</code> to <code>self[carId] = carId</code> . </p>
<p>Try this </p>
<pre><code>class car(dict):
def __init__(self, carId, data):
self[carId] = carId
self.brand = data['Brand']
self.type = data['Type']
def addColor(self, color):
... | 1 | 2016-07-18T09:53:01Z | [
"python"
] |
Custom Frame Duration for Animated Gif in Python ImageIO | 38,433,425 | <p>I've been playing around with animated gifs in Python, where the frames will be produced by a Raspberry Pi Camera located in a greenhouse. I have used the recommended imageio code from <a href="http://stackoverflow.com/a/35943809/859141">Almar's answer to a previous question</a> with success to create simple gifs. ... | 0 | 2016-07-18T09:42:42Z | 38,433,875 | <p><code>mimsave</code> does not accept 4 <em>positional</em> arguments. Anything beyond the 3rd argument must be provided as a <em>keyword argument</em>. In other words, you have to unpack <code>kargs</code> like so:</p>
<pre><code>imageio.mimsave(exportname, frames, 'GIF', **kargs)
</code></pre>
| 0 | 2016-07-18T10:03:26Z | [
"python",
"image",
"animation"
] |
Two differenet entities (a library and a command) with the same name | 38,433,433 | <p>I`m trying to use a library and a command with the same name (from another library). How would this be possible?
These are the the relevant bits in my code: </p>
<pre><code>import copy
</code></pre>
<p>and</p>
<pre><code>from xlutils.copy import copy
</code></pre>
<p>The error I get is: AttributeError: 'function... | 0 | 2016-07-18T09:42:55Z | 38,433,459 | <p>You could use an <em>alias</em> for the later:</p>
<pre><code>import copy
from xlutils.copy import copy as xlcopy
</code></pre>
<p><code>copy</code> from <code>xlutils</code> will now be masked as <code>xlcopy</code>, and calling <code>copy.deepcopy</code> will now refer to the builtin <code>copy</code> module.</p... | 2 | 2016-07-18T09:43:56Z | [
"python",
"copy",
"deep-copy"
] |
Python: PEP 8 class name as variable | 38,433,503 | <p>Which is the convention according to PEP 8 for writing variables that identify class names (not instances)?</p>
<p>That is, given two classes, <code>A</code> and <code>B</code>, which of the following statements would be the right one?</p>
<pre><code>target_class = A if some_condition else B
instance = target_clas... | 19 | 2016-07-18T09:45:48Z | 38,434,962 | <p>In lack of a specific covering of this case in PEP 8, one can make up an argument for both sides of the medal:</p>
<p>One side is: As <code>A</code> and <code>B</code> both are variables as well, but hold a reference to a class, use CamelCase (<code>TargetClass</code>) in this case.</p>
<p>Nothing prevents you fro... | 10 | 2016-07-18T10:58:05Z | [
"python",
"pep8"
] |
Python: PEP 8 class name as variable | 38,433,503 | <p>Which is the convention according to PEP 8 for writing variables that identify class names (not instances)?</p>
<p>That is, given two classes, <code>A</code> and <code>B</code>, which of the following statements would be the right one?</p>
<pre><code>target_class = A if some_condition else B
instance = target_clas... | 19 | 2016-07-18T09:45:48Z | 38,488,090 | <p>I personally think that whether the variable you mentioned, which holds a reference to a class, is defined as a temporary variable (for example in a procedure or function) or as a derivation from an existing class in the global spectrum has the most weight in the case of which one to use. So to summarise from the re... | 1 | 2016-07-20T18:24:14Z | [
"python",
"pep8"
] |
Python: PEP 8 class name as variable | 38,433,503 | <p>Which is the convention according to PEP 8 for writing variables that identify class names (not instances)?</p>
<p>That is, given two classes, <code>A</code> and <code>B</code>, which of the following statements would be the right one?</p>
<pre><code>target_class = A if some_condition else B
instance = target_clas... | 19 | 2016-07-18T09:45:48Z | 38,594,378 | <p>In case of doubt I would do the same as Python developers. They wrote the PEP-8 after all.</p>
<p>You can consider your line:</p>
<pre><code>target_class = A if some_condition else B
</code></pre>
<p>as an in-line form of the pattern:</p>
<pre><code>target_class = target_class_factory()
</code></pre>
<p>and the... | 1 | 2016-07-26T15:42:17Z | [
"python",
"pep8"
] |
Python: PEP 8 class name as variable | 38,433,503 | <p>Which is the convention according to PEP 8 for writing variables that identify class names (not instances)?</p>
<p>That is, given two classes, <code>A</code> and <code>B</code>, which of the following statements would be the right one?</p>
<pre><code>target_class = A if some_condition else B
instance = target_clas... | 19 | 2016-07-18T09:45:48Z | 38,607,663 | <p>I finally found some light in the <a href="https://www.python.org/dev/peps/pep-0008/#class-names" rel="nofollow">style guide</a>:</p>
<blockquote>
<p><strong>Class Names</strong></p>
<p>[...]</p>
<p>The naming convention for functions may be used instead in cases where the interface is documented and us... | 0 | 2016-07-27T08:26:32Z | [
"python",
"pep8"
] |
Naming DataFrames iteritively using items from a List + a string | 38,433,526 | <p>I have a list of names of countries.. and I have a large dataframe where one of the columns is ' COUNTRY ' (yes it has a space before and after the word country) I want to be create smaller DataFrames based on country names</p>
<pre><code>cleaned_df[cleaned_df[' COUNTRY ']==asia_country_list[1]]
</code></pre>
<p>s... | 0 | 2016-07-18T09:46:37Z | 38,433,710 | <p>I don't think you should do this, but if you really need it :</p>
<pre><code>exec(str("%s_data" % (asia_country_list[1])) +"= cleaned_df[cleaned_df[' COUNTRY ']==asia_country_list[1]]")
</code></pre>
<p>should work.
Using a dictionary is likely to solve your problem</p>
<pre><code> D={}
D["%s_data" % (asia_co... | 0 | 2016-07-18T09:55:30Z | [
"python"
] |
Python - Plotting vertical line | 38,433,584 | <p>I have a curve of some data that I am plotting using matplotlib. The small value x-range of the data consists entirely of NaN values, so that my curve starts abruptly at some value of x>>0 (which is not necessarily the same value for different data sets I have). I would like to place a vertical dashed line where t... | 1 | 2016-07-18T09:49:25Z | 38,433,637 | <p>Assuming you know where the curve begins, you can just use:</p>
<p><code>plt.plot((x1, x2), (y1, y2), 'r-')</code> to draw the line from the point <code>(x1, y1)</code> to the point <code>(x2, y2)</code> </p>
<p>Here in your case, <code>x1</code> and <code>x2</code> will be same, only <code>y1</code> and <code>y2<... | 2 | 2016-07-18T09:52:07Z | [
"python",
"matplotlib"
] |
Python - Plotting vertical line | 38,433,584 | <p>I have a curve of some data that I am plotting using matplotlib. The small value x-range of the data consists entirely of NaN values, so that my curve starts abruptly at some value of x>>0 (which is not necessarily the same value for different data sets I have). I would like to place a vertical dashed line where t... | 1 | 2016-07-18T09:49:25Z | 38,433,731 | <p>To plot vertical dashed line you have to set the same x value and make code like this (use '--' for dashed line or ':'):</p>
<pre><code>x = 100 # line at this x position
y0 = 0 # y limits of a line
y1 = 100
plt.plot((x,x),(y0,y1),'k--')
</code></pre>
| 1 | 2016-07-18T09:56:30Z | [
"python",
"matplotlib"
] |
Python - Plotting vertical line | 38,433,584 | <p>I have a curve of some data that I am plotting using matplotlib. The small value x-range of the data consists entirely of NaN values, so that my curve starts abruptly at some value of x>>0 (which is not necessarily the same value for different data sets I have). I would like to place a vertical dashed line where t... | 1 | 2016-07-18T09:49:25Z | 38,439,794 | <p>As an alternative, you can also use <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.vlines" rel="nofollow">plt.vlines</a> to draw a vertical line and provided that your data is in a numpy array and not a list, you can skip the for loop to determine the first non-NaN value and make use of <a href... | 2 | 2016-07-18T14:50:31Z | [
"python",
"matplotlib"
] |
Pandas .describe() only returning 4 statistics on int dataframe (count, unique, top, freq)... no min, max, etc | 38,433,672 | <p>Why could this be? My data seems pretty simple and straightforward, it's a 1 column dataframe of ints, but .describe only returns count, unique, top, freq... not max, min, and other expected outputs.</p>
<p>(Note .describe() functionality is as expected in other projects/datasets)</p>
| 0 | 2016-07-18T09:53:39Z | 38,433,736 | <p>It seems pandas doesn't recognize your data as int.</p>
<p>Try to do this explicitly:</p>
<pre><code>print(df.astype(int).describe())
</code></pre>
| 0 | 2016-07-18T09:56:41Z | [
"python",
"pandas"
] |
Numpy- How to create ROI iteratively in OpenCV python? | 38,433,774 | <p>I am trying to split an image in a grid of smaller images so that I can process each small image separately. For that I realized that I'll have to define each small image as an ROI and I can use it easily from there. </p>
<p>Now, my grid size is not fixed. I.e, if user inputs 5, I have to make a grid of 5x5. </p>... | 3 | 2016-07-18T09:58:28Z | 38,435,940 | <p>If you want to split your image using Numpy functions, take a look at <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_split.html" rel="nofollow">numpy.array_split</a>.</p>
<p>In your case you would write something like this:</p>
<pre><code>z = {}
count = 0
split1 = np.array_split(img, rh)
... | 3 | 2016-07-18T11:47:09Z | [
"python",
"opencv",
"numpy"
] |
Numpy- How to create ROI iteratively in OpenCV python? | 38,433,774 | <p>I am trying to split an image in a grid of smaller images so that I can process each small image separately. For that I realized that I'll have to define each small image as an ROI and I can use it easily from there. </p>
<p>Now, my grid size is not fixed. I.e, if user inputs 5, I have to make a grid of 5x5. </p>... | 3 | 2016-07-18T09:58:28Z | 38,439,875 | <p>For efficiency purposes, listed below is a vectorized approach using reshaping and permuting dimensions.</p>
<p>1) Let's define the input parameters and setup inputs :</p>
<pre><code>M = 5 # Number of patches along height and width
img_slice = img[:rh*M,:rw*M] # Slice out valid image data
</code></pre>
<p>2) The ... | 2 | 2016-07-18T14:54:17Z | [
"python",
"opencv",
"numpy"
] |
subprocess child traceback | 38,433,837 | <p>I want to access the traceback of a python programm running in a subprocess.</p>
<p><a href="https://docs.python.org/2/library/subprocess.html#exceptions" rel="nofollow">The documentation</a> says:</p>
<blockquote>
<p>Exceptions raised in the child process, before the new program has started to execute, will be ... | 3 | 2016-07-18T10:01:17Z | 38,435,432 | <p>As you're starting another Python process, you can also try to use the <code>multiprocessing</code> Python module ; by sub-classing the <code>Process</code> class it is quite easy to get exceptions from the target function:</p>
<pre><code>from multiprocessing import Process, Pipe
import traceback
import functools
... | 0 | 2016-07-18T11:21:29Z | [
"python",
"subprocess",
"traceback"
] |
Scrapy spider returns empty feed output in some cases | 38,433,843 | <p>I've written the following spider to scrape pages on <a href="http://www.funda.nl/" rel="nofollow">http://www.funda.nl/</a>:</p>
<pre><code>import re
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from funda.items import FundaItem
class FundaSpider(CrawlS... | 0 | 2016-07-18T10:01:44Z | 38,468,134 | <p>The problem is the regular expression you use to filter the urls, the <code>LinkExtractor</code> can not find any url matching it, but if you change it to <code>LinkExtractor(allow=r'(huis|appartement)-\d{8}')</code> (don't know if this is what you want) would give you something like:</p>
<pre><code>['http://www.fu... | 0 | 2016-07-19T20:41:58Z | [
"python",
"scrapy"
] |
Not able to redirect a Django form after submission | 38,433,883 | <p>I am a newbie to Django and a form I created is giving me a bit of trouble.</p>
<p>I have create a form in Django for user authentication and login. But the form is not redirecting to the link I've specified after hitting submit. I think this is because the <em>authentication</em> function in <code>views.py</code> ... | 0 | 2016-07-18T10:03:47Z | 38,434,412 | <p>There are a few issues here.</p>
<p>You correctly call <code>save</code> with commit=False, to allow you to set the hashed password before saving properly (as the comments state), but you never actually do so, so the user is saved with an unhashed password. This will never validate.</p>
<p>Similarly, you never set... | 0 | 2016-07-18T10:29:09Z | [
"python",
"django",
"forms"
] |
Python/Pandas find closest value above/below in one Column | 38,433,934 | <p>I have a large data frame (~1 million rows). I am ultimately going to be interpolating spectra between two age groups. However I need to first find the nearest values above and below any age I need to find. </p>
<p>The DataFrame briefly looks like this</p>
<pre><code> Age Wavelength Luminosity
1
1
1
4... | 2 | 2016-07-18T10:06:23Z | 38,434,231 | <p>IIUC and assuming sorted input array, you can do something like this -</p>
<pre><code>above = arr[np.searchsorted(arr,value,'left')-1]
below = arr[np.searchsorted(arr,value,'right')]
</code></pre>
<p>Sample runs -</p>
<p>Case 1: Without exact match for value</p>
<pre><code>In [17]: arr = np.array([1,1,1,4,4,4,4,... | 0 | 2016-07-18T10:20:21Z | [
"python",
"sorting",
"pandas",
"dataframe",
"astronomy"
] |
Python/Pandas find closest value above/below in one Column | 38,433,934 | <p>I have a large data frame (~1 million rows). I am ultimately going to be interpolating spectra between two age groups. However I need to first find the nearest values above and below any age I need to find. </p>
<p>The DataFrame briefly looks like this</p>
<pre><code> Age Wavelength Luminosity
1
1
1
4... | 2 | 2016-07-18T10:06:23Z | 38,434,747 | <p>I think you should use <code>bisect</code>, its a lot faster and is made for this purpose only.</p>
<pre><code>from bisect import *
arr = np.array([1,1,1,4,4,4,4,4,4,4,6,6])
value = 5
lower = arr[bisect_left(arr, value) - 1]
above = arr[bisect_right(arr, value)]
lower, above
</code></pre>
<p>Output - </p>
<pre><... | 1 | 2016-07-18T10:46:23Z | [
"python",
"sorting",
"pandas",
"dataframe",
"astronomy"
] |
Pandas to_datetime() issue with specific datetime format | 38,434,025 | <p>I would like to convert my dataframe from this string to a usable date-time format</p>
<pre><code>01/May/2016:06:38:13 +0100
</code></pre>
<p>I'm currently using <code>Python V 3.5.1 :: Anaconda 4.0.0(64-bit)</code></p>
| 0 | 2016-07-18T10:10:00Z | 38,434,610 | <pre><code>import time
from time import mktime
from datetime import datetime
df.time = df.time.apply(lambda x: datetime.fromtimestamp(mktime(time.strptime(x, '%d/%b/%Y:%I:%M:%S %z'))))
</code></pre>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">http://pandas.... | 1 | 2016-07-18T10:39:13Z | [
"python",
"pandas",
"nginx"
] |
Pandas to_datetime() issue with specific datetime format | 38,434,025 | <p>I would like to convert my dataframe from this string to a usable date-time format</p>
<pre><code>01/May/2016:06:38:13 +0100
</code></pre>
<p>I'm currently using <code>Python V 3.5.1 :: Anaconda 4.0.0(64-bit)</code></p>
| 0 | 2016-07-18T10:10:00Z | 38,435,281 | <p>From <a href="http://stackoverflow.com/questions/38434025/pandas-to-datetime-issue-with-specific-datetime-format#38434610">Joris</a> comment this should do it using <a href="https://pypi.python.org/pypi/python-dateutil" rel="nofollow">dateutil</a>:</p>
<pre><code>from dateutil.parser import parse
a='01/May/2016:06:... | 1 | 2016-07-18T11:13:58Z | [
"python",
"pandas",
"nginx"
] |
'Reversed' comparison operator in Python | 38,434,094 | <pre><code>class Inner():
def __init__(self, x):
self.x = x
def __eq__(self, other):
if isinstance(other, Inner):
return self.x == other.x
else:
raise TypeError("Incorrect type to compare")
class Outer():
def __init__(self, y):
self.y = Inner(y)
... | 4 | 2016-07-18T10:12:55Z | 38,434,369 | <p>Not to put too fine a point on it: <code>Inner.__eq__</code> is broken. At the very least, rather than throwing an error it should <a href="https://docs.python.org/3/library/constants.html#NotImplemented" rel="nofollow"><code>return NotImplemented</code></a>, which would allow Python to try the reverse comparison:</... | 1 | 2016-07-18T10:27:00Z | [
"python",
"comparison"
] |
How to replace columns of one csv with the columns from other csv using python. There are no column names | 38,434,153 | <p>Suppose i have two csv's</p>
<p>one.csv</p>
<pre><code>1,2,3,4
5,6,7,8
</code></pre>
<p>two.csv</p>
<pre><code>6,7,4,5
7,8,10,15
</code></pre>
<p>I have to replace last two columns from first file with last two columns of second file and output files should be</p>
<pre><code>1,2,4,5
5,6,10,15
</code></pre>
<p... | 0 | 2016-07-18T10:15:55Z | 38,434,333 | <p>This should work:</p>
<pre><code>import pandas as pd
df1 = pd.read_csv(csv1,usecols=[1,2,3,4 5,6], names=[1,2,3,4 5,6] header=None)
df2 = pd.read_csv(csv2,usecols=[10,15], names=[10,15] header=None)
df = pd.concat([df1, df2], ignore_index=True)
</code></pre>
<p>EDIT: In response to your comment with different dim... | 0 | 2016-07-18T10:25:08Z | [
"python",
"python-2.7",
"pandas"
] |
How to replace columns of one csv with the columns from other csv using python. There are no column names | 38,434,153 | <p>Suppose i have two csv's</p>
<p>one.csv</p>
<pre><code>1,2,3,4
5,6,7,8
</code></pre>
<p>two.csv</p>
<pre><code>6,7,4,5
7,8,10,15
</code></pre>
<p>I have to replace last two columns from first file with last two columns of second file and output files should be</p>
<pre><code>1,2,4,5
5,6,10,15
</code></pre>
<p... | 0 | 2016-07-18T10:15:55Z | 38,435,387 | <p>try this:</p>
<pre><code>In [10]: (pd.read_csv(fn1, header=None, usecols=[0,1])
....: .join(pd.read_csv(fn2, header=None, usecols=[2,3])))
Out[10]:
0 1 2 3
0 1 2 4 5
1 5 6 10 15
</code></pre>
<p>save back to csv:</p>
<pre><code>In [11]: (pd.read_csv(fn1, header=None, usecols=[0,1])
....... | 0 | 2016-07-18T11:19:23Z | [
"python",
"python-2.7",
"pandas"
] |
Why pip3 installing packages though can't import it? | 38,434,182 | <p>i have installed MySQLdb by pip3 but when i'm importing it, it is giving me error. why?</p>
<pre><code>pip3 install mysqlclient
Requirement already satisfied (use --upgrade to upgrade): mysqlclient in /usr/local/lib/python3.5/dist-packages
</code></pre>
<p>Now as you see it is already installed but when i'm import... | 1 | 2016-07-18T10:17:50Z | 38,435,593 | <p>There are two directories for python3 in my ubuntu one is usr/local/bin and one is usr/bin. pip3 is installing the modules for the python usr/bin but when i'm starting python3 in terminal it is starting the usr/local/bin so i changed the default python by </p>
<pre><code>alias python=/usr/bin/python3.5
</code></pre... | 1 | 2016-07-18T11:29:49Z | [
"python",
"python-3.x",
"pip",
"ubuntu-14.04",
"python-3.5"
] |
How to get specific value in dictionary python? | 38,434,209 | <p>I have dictionary like,</p>
<pre><code>"countries":{
"98":{
"uid":98,
"title":"Switzerland"
}
}
</code></pre>
<p>I want to get just value of "title" using <strong><em>json decoding method</em></strong>.</p>
<p><strong>Note:</strong> The value of "98" is dynamic so it changes everyt... | -5 | 2016-07-18T10:19:21Z | 38,434,870 | <p>I'm going to assume that the "dictionary" you're providing is a string in JSON format and that you want to decode it into a Python object (dictionary) THEN access tittle.</p>
<p>If that's the case, the json module is your friend!
Documentation: <a href="https://docs.python.org/3/library/json.html" rel="nofollow">ht... | 1 | 2016-07-18T10:52:51Z | [
"python",
"json",
"dictionary"
] |
How to get specific value in dictionary python? | 38,434,209 | <p>I have dictionary like,</p>
<pre><code>"countries":{
"98":{
"uid":98,
"title":"Switzerland"
}
}
</code></pre>
<p>I want to get just value of "title" using <strong><em>json decoding method</em></strong>.</p>
<p><strong>Note:</strong> The value of "98" is dynamic so it changes everyt... | -5 | 2016-07-18T10:19:21Z | 38,440,671 | <p>If you mean that you have several fields like <code>98</code> but they all contain a title, you could do this:</p>
<pre><code>titles = list()
for k in my_dict["countries"].keys():
if my_dict["countries"][k].has_key("title"):
titles.append(my_dict["countries"][k]["title"])
</code></pre>
<p>or, as sugg... | 1 | 2016-07-18T15:30:48Z | [
"python",
"json",
"dictionary"
] |
Why is quicksum very slow in SCIP python interface | 38,434,300 | <p>I'm using scip python interface on ubuntu. I am trying to add a constraint using quicksum:</p>
<pre><code>m.addCons(quicksum(covfinal[i,j]*weightVars[i]*weightVars[j] \
for i in I for j in J)<=z)
</code></pre>
<p>This step takes a long time for some reason. I have <code>I=range(2500)</code>, <code>J=r... | 0 | 2016-07-18T10:23:28Z | 38,452,576 | <p>Currently, there is no other way to add constraints than with the <code>addCons()</code> method. <code>quicksum()</code> dramatically decreases the necessary time compared to Python's builtin <code>sum()</code> because only one expression instance is created that is then iteratively updated with the single terms. Ot... | 0 | 2016-07-19T07:56:15Z | [
"python",
"scip"
] |
Testing Mongo with Docker | 38,434,301 | <p>given the following file for docker-compose </p>
<pre><code>version: '2'
services:
sut:
build: .
command: /bin/bash #nosetests
depends_on:
- mongo
mongo:
image: mongo
</code></pre>
<p>I try to connect to a mongo server on the fly. I didn't get very far with this ambitious plan. I assume t... | 1 | 2016-07-18T10:23:28Z | 38,434,555 | <p>Port <code>27017</code> is not published to your host machine so you can not connect to it from localhost. </p>
<p>You can change <code>mongo</code> block to</p>
<p><code>mongo:
image: mongo
ports:
- 27017:27017</code></p>
<p>Or connect from docker container via docker container name:</p>
<p><code... | 2 | 2016-07-18T10:36:22Z | [
"python",
"mongodb",
"unit-testing",
"docker",
"docker-compose"
] |
How to get a link from <a> python parser | 38,434,403 | <pre><code><a class="button button-mini" href="www.example-link.com.c"><b>TEXT</b></a>
</code></pre>
<p>I'm creating Python parser, and i need to get link from this tag. I tried this, but result was "None":</p>
<pre><code>link = table.find_all('td')[1].a.href
link = table.find_all('td')[1].a.l... | 1 | 2016-07-18T10:28:42Z | 38,435,031 | <p>I think that it's a pretty simple question where you are just missing parameters.
It should be written as:</p>
<pre><code>link = table.find_all('td')[1].a.get('href')
</code></pre>
<p><strong>Edit note</strong></p>
<p>Just noticed after answering that a user has responded to you as comment... Don't want to steal... | 1 | 2016-07-18T11:01:02Z | [
"python",
"python-3.x",
"html-parsing"
] |
updating user profile using django rest framework api | 38,434,478 | <p>I want to create an API where user can update their profile. In my case, a user can update his/her username and password. To change his/her profile, an API link should be <code>/api/change/usernameOfThatUser</code>. When I use a non-existing username in the link, I still get the userProfileChange API page, and the i... | 2 | 2016-07-18T10:32:11Z | 38,436,660 | <p>Maybe try doing something like this instead in your <strong>views.py</strong>?</p>
<pre><code>from rest_framework import generics, mixins, permissions
User = get_user_model()
class UserIsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method... | 3 | 2016-07-18T12:24:29Z | [
"python",
"django",
"api",
"django-rest-framework"
] |
Host Bokeh(Python) to Windows Server | 38,434,489 | <p>I have developed an app using bokeh(Python). App is working fine when I run this on my local machine using localhost:5006/myapp. I have Windows Machine. What is the procedure to host the app on my windows machine publicly. [Bokeh version 0.12.0]
(Please Don't Suggest for VM) </p>
| -1 | 2016-07-18T10:32:46Z | 38,459,693 | <p>Found Solution
on Windows open cmd and run </p>
<pre><code>cd C:\Python27\Scripts
</code></pre>
<p>then </p>
<pre><code>bokeh serve C:\Users\your-path\File_name.py --address=0.0.0.0 --host *
</code></pre>
<p>This is working for me.</p>
| 0 | 2016-07-19T13:13:35Z | [
"python",
"python-2.7",
"web-deployment",
"bokeh"
] |
Subclassing Future Class | 38,434,606 | <p>I would like to subclass the <a href="https://docs.python.org/3/library/concurrent.futures.html#future-objects" rel="nofollow">Future</a> class of the <code>concurrent</code> Python module.</p>
<p>The docs:</p>
<blockquote>
<p>The Future class encapsulates the asynchronous execution of a callable. Future instanc... | 0 | 2016-07-18T10:39:07Z | 38,437,446 | <p>The use of the <code>Future</code> concrete class is hard-wired into <code>Executor.submit()</code> (whether for <a href="https://hg.python.org/cpython/file/3.5/Lib/concurrent/futures/process.py#l445" rel="nofollow">processes</a> or <a href="https://hg.python.org/cpython/file/3.5/Lib/concurrent/futures/thread.py#l10... | 1 | 2016-07-18T13:03:27Z | [
"python",
"concurrency",
"concurrent.futures"
] |
Subclassing Future Class | 38,434,606 | <p>I would like to subclass the <a href="https://docs.python.org/3/library/concurrent.futures.html#future-objects" rel="nofollow">Future</a> class of the <code>concurrent</code> Python module.</p>
<p>The docs:</p>
<blockquote>
<p>The Future class encapsulates the asynchronous execution of a callable. Future instanc... | 0 | 2016-07-18T10:39:07Z | 38,606,048 | <p>Looking at the code, <a href="https://github.com/python/cpython/blob/3.5/Lib/concurrent/futures/process.py#L437-L456" rel="nofollow">ProcessPoolExecutor.submit()</a> and <a href="https://github.com/python/cpython/blob/3.5/Lib/concurrent/futures/thread.py#L104-L114" rel="nofollow">ThreadPollExecutor.submit()</a>, <co... | 1 | 2016-07-27T07:08:22Z | [
"python",
"concurrency",
"concurrent.futures"
] |
How to make a Luigi task generate an in-memory list as target | 38,434,799 | <p>I'm trying to write an etl pipeline using <a href="http://luigi.readthedocs.io/en/stable/index.html" rel="nofollow">luigi</a>. As far as I understand from the documentation a task in luigi can generate a target that can be either some type of file storage or a database. To decrese the processing time I would like to... | 0 | 2016-07-18T10:49:13Z | 38,435,426 | <p>I found out I can use a MockFile as a target. A good example:</p>
<p><a href="http://gouthamanbalaraman.com/blog/building-luigi-task-pipeline.html" rel="nofollow">http://gouthamanbalaraman.com/blog/building-luigi-task-pipeline.html</a></p>
| 0 | 2016-07-18T11:21:06Z | [
"python",
"etl",
"luigi"
] |
Why does python not replace words correctly from a data dictionary? | 38,434,821 | <pre><code>firstsentence=("an eye for an eye a tooth for a tooth")
def replace_all(firstsentence, stuff):
for i, j in stuff.items():
firstsentence = firstsentence.replace(i, j)
return firstsentence
stuff = {"a": "1", "eye": "2", "for":"3", "tooth": "5", "an": "6"}
test=replace_all(firstsentence, stuff)... | 0 | 2016-07-18T10:50:27Z | 38,434,921 | <p><code>'an'.replace('a', 1)</code> is run <strong>first</strong>, giving you <code>'1n'</code>. <code>'1n'.replace('an', 6)</code> is not going to replace <code>1n</code>.</p>
<p>Sort your replacements by length to ensure that <em>longer</em> matches are handled first:</p>
<pre><code>def replace_all(firstsentence, ... | 4 | 2016-07-18T10:55:59Z | [
"python"
] |
Why does python not replace words correctly from a data dictionary? | 38,434,821 | <pre><code>firstsentence=("an eye for an eye a tooth for a tooth")
def replace_all(firstsentence, stuff):
for i, j in stuff.items():
firstsentence = firstsentence.replace(i, j)
return firstsentence
stuff = {"a": "1", "eye": "2", "for":"3", "tooth": "5", "an": "6"}
test=replace_all(firstsentence, stuff)... | 0 | 2016-07-18T10:50:27Z | 38,435,273 | <p>First you should tokenize your line and extract words:</p>
<pre><code>firstsentence="an eye for an eye a tooth for a tooth"
wordslist = firstsentence.split(' ')
</code></pre>
<p>Then you should build set or unique words (perhaps you should lowerize em first):</p>
<pre><code>uwords = list(set([_.lower() for _ in ... | 0 | 2016-07-18T11:13:44Z | [
"python"
] |
S3Cmd doesn't work with S3 Ninja | 38,434,905 | <p>I'm trying to use my local s3ninja with s3cmd.
Every command like: <code>s3cmd ls s3://test</code> throws the same exceptions.</p>
<p>The s3cfg seems to be ok and the called endpoints are correct.</p>
<p>Was anyone able to use s3ninja with s3cmd? </p>
<p>PS: I know S3 isn't costly and there are many better ways t... | 6 | 2016-07-18T10:55:12Z | 39,238,227 | <p><code>s3cmd</code> at the moment forces api to be at <code>/</code>. On the other hand s3ninja does not allow to set it to '/'. I've proposed feature (<a href="https://github.com/s3tools/s3cmd/pull/781" rel="nofollow">PR 781</a>) to s3cmd to deal with - you could patch s3cmd by yourself.</p>
<p>Another solution wou... | 2 | 2016-08-30T22:47:07Z | [
"python",
"amazon-web-services",
"amazon-s3",
"s3cmd"
] |
S3Cmd doesn't work with S3 Ninja | 38,434,905 | <p>I'm trying to use my local s3ninja with s3cmd.
Every command like: <code>s3cmd ls s3://test</code> throws the same exceptions.</p>
<p>The s3cfg seems to be ok and the called endpoints are correct.</p>
<p>Was anyone able to use s3ninja with s3cmd? </p>
<p>PS: I know S3 isn't costly and there are many better ways t... | 6 | 2016-07-18T10:55:12Z | 39,256,213 | <p>This is my nginx proxy configuration that works perfectly with s3cmd and S3 Ninja. </p>
<pre><code>server {
listen 80;
server_name s3.eu-central-1.amazonaws.com;
location / {
proxy_pass http://127.0.0.1:9444/s3/;
}
}
</code></pre>
<p>With the following host configurati... | 0 | 2016-08-31T18:02:11Z | [
"python",
"amazon-web-services",
"amazon-s3",
"s3cmd"
] |
S3Cmd doesn't work with S3 Ninja | 38,434,905 | <p>I'm trying to use my local s3ninja with s3cmd.
Every command like: <code>s3cmd ls s3://test</code> throws the same exceptions.</p>
<p>The s3cfg seems to be ok and the called endpoints are correct.</p>
<p>Was anyone able to use s3ninja with s3cmd? </p>
<p>PS: I know S3 isn't costly and there are many better ways t... | 6 | 2016-07-18T10:55:12Z | 39,301,969 | <p>S3cmd uses AWS endpoints and not ready to work with S3-compatible interfaces. It fails when trying "get bucket location".</p>
<blockquote>
<pre><code>--bucket-location=BUCKET_LOCATION
</code></pre>
<p>Datacentre to create bucket in. As of now the datacenters are: US
(default), EU, us-west-1, and ap- southeas... | 0 | 2016-09-02T23:50:55Z | [
"python",
"amazon-web-services",
"amazon-s3",
"s3cmd"
] |
Apache creates file: how to control permissions | 38,434,914 | <p>My Django app via Apache creates log files: log.txt</p>
<p>The Owner and group of this file is "www-data"</p>
<pre><code>owner rwx
group r
all r
</code></pre>
<p>My python app has no read/write permissions to this log file. But I need the python app to have this permissions.</p>
<p>Now it is easy to manually cha... | 0 | 2016-07-18T10:55:40Z | 38,434,969 | <p>You may use <a href="https://docs.python.org/2/library/os.html#os.chmod" rel="nofollow">os.chmod()</a> to control the permissions of a given file, after creating the file you can execute:</p>
<pre><code>os.chmod("/path/to/file", 0o775)
</code></pre>
<p>The first argument being the path and the second argument is t... | 0 | 2016-07-18T10:58:17Z | [
"python",
"linux",
"django",
"apache",
"file-permissions"
] |
Simple lambda function with if statement using python | 38,435,139 | <p>I have 1,000 files; the start of each file all look like this:</p>
<pre><code>!dataset_description = Analysis of POF D119 mutation.
!dataset_type = Expression profiling by array
!dataset_pubmed_id = 17318176
!dataset_platform = GPL1322
</code></pre>
<p>The aim: I want to transform this information into a list so ... | 1 | 2016-07-18T11:07:10Z | 38,435,241 | <p>You certainly can have a lambda expression without an argument.</p>
<p>However, in this case, you should actually pass an argument: the line itself. That is the thing that you're operating on, therefore it should be passed into the function.</p>
<p>Your <code>if</code> statement does not work because an inline if ... | 2 | 2016-07-18T11:12:25Z | [
"python",
"lambda"
] |
Simple lambda function with if statement using python | 38,435,139 | <p>I have 1,000 files; the start of each file all look like this:</p>
<pre><code>!dataset_description = Analysis of POF D119 mutation.
!dataset_type = Expression profiling by array
!dataset_pubmed_id = 17318176
!dataset_platform = GPL1322
</code></pre>
<p>The aim: I want to transform this information into a list so ... | 1 | 2016-07-18T11:07:10Z | 38,435,270 | <p>It raises <code>SyntaxError</code>, because you're missing an <code>else</code> branch. The "expression if" or "inline if" has the syntax: <code><value to return when True> if <condition> else <value when False></code> You can't use <code>elif</code>.</p>
<p>So the code might look like this:</p>
... | 2 | 2016-07-18T11:13:41Z | [
"python",
"lambda"
] |
How is the Numpy "fill" method implemented? | 38,435,253 | <p>You see two equal arrays is created using Core Python methods and using Numpy methods:</p>
<pre><code>from time import time
import numpy as np
a = [3] * 100000
b = np.array(a)
</code></pre>
<p>The question is that how is that possible that Numpy is faster than Core Python methods in filling process:</p>
<p>Fill:... | 3 | 2016-07-18T11:13:04Z | 38,436,336 | <p>If you include the time to convert <code>a</code> into a numpy array, then the core python methods take about the same amount of the time.</p>
<pre><code>In [14]: %%timeit
....: a = [3] * 100000
....: for i in range(len(a)):
....: a[i] = 0
....:
100 loops, best of 3: 9.94 ms per loop
In [15]: %%tim... | 0 | 2016-07-18T12:08:36Z | [
"python",
"python-2.7",
"numpy"
] |
How is the Numpy "fill" method implemented? | 38,435,253 | <p>You see two equal arrays is created using Core Python methods and using Numpy methods:</p>
<pre><code>from time import time
import numpy as np
a = [3] * 100000
b = np.array(a)
</code></pre>
<p>The question is that how is that possible that Numpy is faster than Core Python methods in filling process:</p>
<p>Fill:... | 3 | 2016-07-18T11:13:04Z | 38,441,865 | <p>Your 2 'arrays' may have the same values, but they aren't stored in the same way</p>
<pre><code>a = [3] * 100000
b = np.array(a)
</code></pre>
<p><code>a</code>, as a list, consists of a 100000 pointers to the number <code>3</code> (stored else where in memory). <code>a[i]=0</code> changes one of those pointers t... | 0 | 2016-07-18T16:34:43Z | [
"python",
"python-2.7",
"numpy"
] |
How to get positional coordinates (nÃ2) for a uniformly spaced array? | 38,435,289 | <p>I am trying to make an array of line elements (23Ã23 grid) using the <a href="http://www.psychopy.org/api/visual/visual.html#psychopy.visual.ElementArrayStim" rel="nofollow"><code>ElementArrayStim</code></a> from PsychoPy. </p>
<p>For the <code>xys</code> parameter for positions of the line elements, I am trying t... | 1 | 2016-07-18T11:14:15Z | 38,435,966 | <p>Do you need to loop over both axis, appending each element to the array as you go ?</p>
<pre><code>fred=np.array([[],[]])
for column in xaxis:
for row in yaxis:
fred = np.append(fred, [[column], [row]], 1)
fred.shape
(2, 529)
</code></pre>
| 0 | 2016-07-18T11:48:37Z | [
"python",
"arrays",
"psychopy"
] |
How to get positional coordinates (nÃ2) for a uniformly spaced array? | 38,435,289 | <p>I am trying to make an array of line elements (23Ã23 grid) using the <a href="http://www.psychopy.org/api/visual/visual.html#psychopy.visual.ElementArrayStim" rel="nofollow"><code>ElementArrayStim</code></a> from PsychoPy. </p>
<p>For the <code>xys</code> parameter for positions of the line elements, I am trying t... | 1 | 2016-07-18T11:14:15Z | 38,436,375 | <p>You were very close, just needed to create a 3D array of coordinates from <code>xaxis</code> and <code>yaxis</code> and then reshape that 3D array to get a 529 rows à 2 columns 2D array as required:</p>
<pre><code>In [21]: xy = np.dstack(np.meshgrid(xaxis, yaxis)).reshape(-1, 2)
In [22]: xy
Out[22]:
array([[-220... | 3 | 2016-07-18T12:11:03Z | [
"python",
"arrays",
"psychopy"
] |
Python read LTspice plot export | 38,435,305 | <p>I'd like to plot some data from LTspice with Python and matplotlib, and I'm searching for a solution to import the exported plot data from LTspice in Python.</p>
<p>I found no way to do this using Pandas, since the format of the data looks like this:</p>
<pre><code>5.00000000000000e+006\t(2.84545891331278e+001dB,8... | 2 | 2016-07-18T11:15:28Z | 38,443,043 | <p>I am not familiar with exported plot data from LTspice, so I am assuming that the formatting of the example lines you provided are valid for all times. </p>
<p>Looking at the IO Tools section of the pandas-0.18 documentation (<a href="http://pandas.pydata.org/pandas-docs/stable/io.html" rel="nofollow">here</a>), I ... | 1 | 2016-07-18T17:51:57Z | [
"python",
"python-3.x",
"pandas",
"import",
"pspice"
] |
Python read LTspice plot export | 38,435,305 | <p>I'd like to plot some data from LTspice with Python and matplotlib, and I'm searching for a solution to import the exported plot data from LTspice in Python.</p>
<p>I found no way to do this using Pandas, since the format of the data looks like this:</p>
<pre><code>5.00000000000000e+006\t(2.84545891331278e+001dB,8... | 2 | 2016-07-18T11:15:28Z | 40,122,733 | <p>I have written a Python reader for LTSpice simulation output files, which you can find here: <a href="http://www2.ee.unsw.edu.au/~tlehmann/ltspy.py" rel="nofollow">LTSPy</a>. There are also some examples files on how to use the reader here: <a href="http://www2.ee.unsw.edu.au/~tlehmann/exltspy.zip" rel="nofollow">e... | 0 | 2016-10-19T05:18:31Z | [
"python",
"python-3.x",
"pandas",
"import",
"pspice"
] |
Python: How to display a dataframe using Tkinter | 38,435,395 | <p>I am new to Tkinter. I have tried a few widgets provided by Tkinter but cannot find a suitable way to display a dataframe. </p>
<p>I tried <code>Tkinter.Text</code>. I used <code>update()</code> instead of <code>mainloop()</code> because I would like to update <code>df</code> and display again. <code>mainloop()</co... | 0 | 2016-07-18T11:19:50Z | 38,472,572 | <p>I found <a href="https://github.com/datalyze-solutions/pandas-qt/blob/master/examples/BasicExample.py" rel="nofollow">pandas-qt</a> easy to use and the display is very fast. </p>
<p>There are some alternative solutions <a href="http://stackoverflow.com/questions/10636024/python-pandas-gui-for-viewing-a-dataframe-or... | 0 | 2016-07-20T04:52:50Z | [
"python",
"tkinter"
] |
Reload page if error "IndexError: list index out of range" occures | 38,435,669 | <p>I am scraping web pages and sometimes the age does not load correctly and the error occurs </p>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>This is because with the page not loading correctly it does not have the index. reloading the page solves this.</p>
<p>Is there away to add in ... | -1 | 2016-07-18T11:32:59Z | 38,436,274 | <p>You can add a try/exception error which will return some kind of variable to tell the page that it has not loaded properly then you can use javascript function <code>location.reload()</code> to reload the page.</p>
<p>For example:
In your Python Script:</p>
<pre><code>try:
'Your Code Goes Here'
except IndexErr... | 1 | 2016-07-18T12:05:30Z | [
"javascript",
"jquery",
"python",
"events"
] |
Reload page if error "IndexError: list index out of range" occures | 38,435,669 | <p>I am scraping web pages and sometimes the age does not load correctly and the error occurs </p>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>This is because with the page not loading correctly it does not have the index. reloading the page solves this.</p>
<p>Is there away to add in ... | -1 | 2016-07-18T11:32:59Z | 38,436,476 | <p>I think you need to make a little refactoring.
It should be something like this:</p>
<pre><code>def get_page(link):
# all code stuff for fetching page
# this code could return ether error code or throw Exception
return data
for link in links:
try:
result = get_page(link)
# here you need to ad... | 0 | 2016-07-18T12:15:19Z | [
"javascript",
"jquery",
"python",
"events"
] |
How to create an numpy array of labels from a numpy array of float? | 38,435,680 | <p>For example, I have </p>
<pre><code>arr=np.linspace(0,1,11)
</code></pre>
<p>and I want to mark numbers <code>n<0.25</code> label <code>"a"</code>, <code>n>0.75</code> label <code>"c"</code>, numbers between label <code>"b"</code>. the result would be </p>
<pre><code>array(['a', 'a', 'a', 'b', ..., 'c'])
</... | 2 | 2016-07-18T11:33:37Z | 38,435,944 | <p>NumPy arrays are homogeneous. You have to set type for label array</p>
<pre><code>import numpy as np
arr=np.linspace(0,1,11)
lbl=np.empty((arr.shape), dtype=object)
lbl[arr<.25]='a'
lbl[(arr>=.25) & (arr <=.75)] = 'b'
lbl[arr>.75]='c'
print arr
print lbl
</code></pre>
<p>Output:</p>
<pre><code>[ ... | 1 | 2016-07-18T11:47:16Z | [
"python",
"python-3.x",
"numpy"
] |
How to create an numpy array of labels from a numpy array of float? | 38,435,680 | <p>For example, I have </p>
<pre><code>arr=np.linspace(0,1,11)
</code></pre>
<p>and I want to mark numbers <code>n<0.25</code> label <code>"a"</code>, <code>n>0.75</code> label <code>"c"</code>, numbers between label <code>"b"</code>. the result would be </p>
<pre><code>array(['a', 'a', 'a', 'b', ..., 'c'])
</... | 2 | 2016-07-18T11:33:37Z | 38,435,961 | <p>For creating an array of three such groups, you could do something like this -</p>
<pre><code>ID = (arr>0.75)*1 + (arr>=0.25)
select_arr = np.array(['a','b','c'])
out = select_arr[ID]
</code></pre>
<p>Sample run -</p>
<pre><code>In [64]: arr # Modified from sample posted in question to include 0.75
Out[64]:... | 2 | 2016-07-18T11:47:56Z | [
"python",
"python-3.x",
"numpy"
] |
Python pandas DataFrame - Keep rows that have same information in 3 columns | 38,435,770 | <p>If have a python DataFrame that looks like this: </p>
<pre><code> ID_1 ID_2 haplotypeID locus
A1 A1 hap.1.1 KIRa
A1 A1 hap.1.2 KIRa
A2 A2 hap.2.1 KIRa
A2 A2 hap.2.2 KIRa
A3 A3 hap.1.1 KIRa
A4 A4 hap.2.2 KIRa
A4 A4 hap.1.2 KIRa
A1 A1 hap.1.1 KIRb
... | 0 | 2016-07-18T11:38:24Z | 38,435,853 | <p>Try this:</p>
<pre><code>df[df[['ID_1', 'ID_2', 'locus']].duplicated(keep=False)]
Out[449]:
ID_1 ID_2 haplotypeID locus
0 A1 A1 hap.1.1 KIRa
1 A1 A1 hap.1.2 KIRa
2 A2 A2 hap.2.1 KIRa
3 A2 A2 hap.2.2 KIRa
5 A4 A4 hap.2.2 KIRa
6 A4 A4 hap.1.2 KIRa
8 A... | 0 | 2016-07-18T11:42:30Z | [
"python",
"pandas",
"dataframe",
"duplicates"
] |
Python Page 404 not found | 38,435,832 | <p>New to Python, just starting up with a Issue reporting app which involves an API module.</p>
<p><strong>My Urls.py file:</strong></p>
<pre><code>urlpatterns = patterns('',
url(r'^api/', include('api.urls')),
)
</code></pre>
<p><strong>My api.urls file</strong></p>
<pre><code>urlpatterns = patterns('api.v1',
#... | 0 | 2016-07-18T11:41:28Z | 38,436,322 | <p>replace <code>url(r'^api/', include('api.urls')),
</code> with <code>url(r'', include('api.urls')),
</code></p>
| 1 | 2016-07-18T12:07:57Z | [
"python",
"django",
"django-urls"
] |
python elasticsearch use transport client | 38,435,845 | <p>I am newbie to elasticsearch, I know there is two official client elasticsearch supplies, but when I use the python elasticsearch, i can't find how to use the transport client..<br>
I read the whole doc which is as following:</p>
<pre><code>https://elasticsearch-py.readthedocs.io/en/master/index.html
</code></pre>... | 1 | 2016-07-18T11:42:04Z | 38,462,265 | <p>The transport client is written in Java, so the only way to use it from Python is by switching to Jython. </p>
| 1 | 2016-07-19T15:06:21Z | [
"python",
"elasticsearch",
"client",
"transport"
] |
Converting mnist data to lmdb with python results very large database | 38,435,906 | <p>I am currently playing the lenet model provided by caffe.</p>
<p>the example (which is in path/to/caffe/examples/mnist/convert_mnist_data.cpp provides a c++ program to convert the mnist data to lmdb.</p>
<p>I write a python program to do the same thing, but the size (480MB) of lmdb is much larger than the one conv... | 0 | 2016-07-18T11:45:38Z | 38,909,416 | <pre><code>env = lmdb.open('mnist_lmdb', map_size=1000*1000*1000)
</code></pre>
<p>The db size is mainly depend on the <code>map_size</code>,so you can reduce the <code>map_size</code> </p>
| 0 | 2016-08-12T03:26:35Z | [
"python",
"c++",
"caffe",
"pycaffe",
"lmdb"
] |
Finding an explicit word in a list using python | 38,436,046 | <p>I have a key-value (ID, tag) formatted CSV file containing the following:</p>
<p>1,art</p>
<p>2,fine art;masterpiece</p>
<p>3,modern art</p>
<p>4,artifact;artefact</p>
<p>5,article</p>
<p>My goal is to use python to return only IDs 1, 2, and 3, which are the tags with the word "art" explicitly within them. Whe... | 1 | 2016-07-18T11:52:48Z | 38,436,709 | <p>You could use a <a href="https://docs.python.org/3/library/re.html" rel="nofollow">regex</a> with a <code>\b</code> assertion:</p>
<pre><code>>>> import re
>>> pairs = ((1, "art"), (2, "fine art;masterpiece"), (3, "modern art"),
(4, "artifact;artefact"), (5, "article"))
>>> [... | 2 | 2016-07-18T12:27:25Z | [
"python",
"csv",
"parsing"
] |
Finding an explicit word in a list using python | 38,436,046 | <p>I have a key-value (ID, tag) formatted CSV file containing the following:</p>
<p>1,art</p>
<p>2,fine art;masterpiece</p>
<p>3,modern art</p>
<p>4,artifact;artefact</p>
<p>5,article</p>
<p>My goal is to use python to return only IDs 1, 2, and 3, which are the tags with the word "art" explicitly within them. Whe... | 1 | 2016-07-18T11:52:48Z | 38,436,798 | <p>You can use this code:</p>
<pre><code>lines = ['art', 'fine art;masterpiece', 'modern art', 'artifact;artefact', 'article']
for l in lines:
lis = [_.split(' ') for _ in l.split(';')] # Split the values.
lis = [item for sublist in lis for item in sublist] # Flatten the list.
print 'art' in lis # Check if... | 0 | 2016-07-18T12:31:35Z | [
"python",
"csv",
"parsing"
] |
Finding an explicit word in a list using python | 38,436,046 | <p>I have a key-value (ID, tag) formatted CSV file containing the following:</p>
<p>1,art</p>
<p>2,fine art;masterpiece</p>
<p>3,modern art</p>
<p>4,artifact;artefact</p>
<p>5,article</p>
<p>My goal is to use python to return only IDs 1, 2, and 3, which are the tags with the word "art" explicitly within them. Whe... | 1 | 2016-07-18T11:52:48Z | 38,436,958 | <p>You need to build a lookup index which implements your indexing logic. Read your file, parse each CSV line, and update a lookup index based on a <code>dict</code> for example. Each item in the lookup index should be normalized, lower case for example, and points to a list of IDs.</p>
<p>Here is a small snippet:</p>... | 1 | 2016-07-18T12:39:01Z | [
"python",
"csv",
"parsing"
] |
Finding an explicit word in a list using python | 38,436,046 | <p>I have a key-value (ID, tag) formatted CSV file containing the following:</p>
<p>1,art</p>
<p>2,fine art;masterpiece</p>
<p>3,modern art</p>
<p>4,artifact;artefact</p>
<p>5,article</p>
<p>My goal is to use python to return only IDs 1, 2, and 3, which are the tags with the word "art" explicitly within them. Whe... | 1 | 2016-07-18T11:52:48Z | 38,437,301 | <p>Simple and Sweet : use \b - Word Boundaries</p>
<pre><code>a = ['1,art','2,fine art;masterpiece','3,modern art','4,artifact,artefact','5,article']
for data in a:
output = re.search(r'\bart\b',data)
if 'art' in str(output):
ids = re.findall('\d+', data)
print(ids)
</code></pre>
| 0 | 2016-07-18T12:56:22Z | [
"python",
"csv",
"parsing"
] |
Print line with this substring only once python | 38,436,065 | <p>I have a problem. I have a text file with lots of strings.
I want to search only for those with my substring in it.
But it gives me all possible matches.
My code is: </p>
<pre><code>name = 'ok'
with open('C:/Users/Desktop/text.txt','r') as fin:
for line in fin:
if name in line:
p... | 0 | 2016-07-18T11:54:05Z | 38,436,317 | <p>You should in a way or another use a <a href="https://docs.python.org/2/library/stdtypes.html#set" rel="nofollow"><code>set()</code></a> of seen values (the numbers) to filter out future instances. Given that your file is sorted and every line is in the format of <code>tag = value</code>:</p>
<pre><code>name = 'ok'... | 1 | 2016-07-18T12:07:46Z | [
"python",
"regex",
"string"
] |
Python Indexing Tuples | 38,436,073 | <p>I am creating a function, this function when applied to a tuple it should return the even indexed element in the tuple. How comes it's not returning the fourth indexed element?</p>
<pre><code>def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
evenIndex = ()... | 1 | 2016-07-18T11:54:27Z | 38,436,140 | <p>Using <code>a.index</code> will return the index of the first occurrence of the item. You can't really count on that when the items in your tuple are not unique.</p>
<p>You should consider using <code>enumerate</code> instead:</p>
<pre><code>for i, v in enumerate(aTup):
if i % 2 == 0:
...
</code></pre>... | 4 | 2016-07-18T11:58:10Z | [
"python"
] |
Python Indexing Tuples | 38,436,073 | <p>I am creating a function, this function when applied to a tuple it should return the even indexed element in the tuple. How comes it's not returning the fourth indexed element?</p>
<pre><code>def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
evenIndex = ()... | 1 | 2016-07-18T11:54:27Z | 38,436,217 | <p>works fine for me. Tuples start indexes at 0. So if you have tuple:</p>
<blockquote>
<p>(0,1,2,3,4,5,6)</p>
</blockquote>
<p>it returns</p>
<blockquote>
<p>(0, 2, 4, 6)</p>
</blockquote>
<p>If you want 4th, youll need to change </p>
<pre><code>if i % 2 == 0:
</code></pre>
<p>into </p>
<pre><code>if i % 2 ... | 0 | 2016-07-18T12:02:00Z | [
"python"
] |
Issue with WebKit.WebView signals in for loop | 38,436,087 | <p>Hello i am new in Python and WebKit.
So i have created a simple Gtk app that loads in a WebKit.WebView a list of Internet pages and when a page is loaded there is a DOM binding to take the title of the site. this is happening through a for loop which loads the sites one by one. But at the first run of for loop the ... | 1 | 2016-07-18T11:55:20Z | 38,436,648 | <p>You cannot call functions that touch any UI, be it GTK+, WebKit, or what not, from a separate thread. You have to run them from the thread that calls <code>Gtk.main()</code>, perhaps using <code>GLib.idle_add()</code>.</p>
| 0 | 2016-07-18T12:23:53Z | [
"python",
"python-3.x",
"webkit",
"gtk",
"gtk3"
] |
Naming Columns of a dataset in python | 38,436,122 | <p>I have a dataset which consists of 1000 columns but is not labeled. I want to label them such as {A,B,C.....}. How can I do this in python ? Since the dataset is too large to name it manually.</p>
| 3 | 2016-07-18T11:57:24Z | 38,436,264 | <p>You can use the string conversions of their ASCII equivalent numbers to assign as the new column names. Now, two methods could be suggested to get those names and do the assignment.</p>
<p>Using <code>chr</code> on an array of ASCII equivalent numbers in a loop -</p>
<pre><code>df.columns=[chr(item) for item in 65... | 0 | 2016-07-18T12:04:37Z | [
"python",
"pandas"
] |
Extracting [0-9_]+ from a URL | 38,436,191 | <p>I've put together the following regular expression to extract image ID's from a URL:</p>
<pre><code>''' Parse the post details from the full story page '''
def parsePostFromPermalink(session, permalink):
r = session.get('https://m.facebook.com{0}'.format(permalink))
dom = pq(r.content)
# Parse the ima... | 0 | 2016-07-18T12:00:52Z | 38,436,290 | <p>This is the correct python code from Regex101. (There's a code generator on the left). Notice the lack of slashes on the outside of the regex... </p>
<pre><code>import re
p = re.compile(r'([\d_]+)n\.jpg')
test_str = u"https://scontent-lhr3-1.xx.fbcdn.net/v/t1.0-0/cp0/e15/q65/c3.0.103.105/p110x80/13700209_9373896263... | 1 | 2016-07-18T12:06:09Z | [
"python",
"regex"
] |
Extracting [0-9_]+ from a URL | 38,436,191 | <p>I've put together the following regular expression to extract image ID's from a URL:</p>
<pre><code>''' Parse the post details from the full story page '''
def parsePostFromPermalink(session, permalink):
r = session.get('https://m.facebook.com{0}'.format(permalink))
dom = pq(r.content)
# Parse the ima... | 0 | 2016-07-18T12:00:52Z | 38,436,310 | <p>Two problems:</p>
<ul>
<li>those enclosing <code>/.../</code> are not a part of <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow">Python regex syntax</a></li>
<li>you should use <a href="https://docs.python.org/3/library/re.html#re.search" rel="nofollow"><code>search</code... | 3 | 2016-07-18T12:07:29Z | [
"python",
"regex"
] |
python numpy mutate selection | 38,436,231 | <p>i encountered a strange bug(?) in numpy:
Given a nested array:</p>
<pre><code>p = np.asarray([[1., 2., 3.], [-4., -5., -6.], [1,2,-4]], dtype=np.float32)
</code></pre>
<p>which is</p>
<pre><code>array([[ 1., 2., 3.],
[-4., -5., -6.],
[ 1., 2., -4.]], dtype=float32)
</code></pre>
<p>i want to mutate the ... | 1 | 2016-07-18T12:02:49Z | 38,436,330 | <p>You've modified a copy of the original array. If you want to mutate original array you should use something like this:</p>
<pre><code>p[p[:, 2] <0, 2] *= -1
</code></pre>
| 0 | 2016-07-18T12:08:20Z | [
"python",
"arrays",
"numpy",
"selection"
] |
python numpy mutate selection | 38,436,231 | <p>i encountered a strange bug(?) in numpy:
Given a nested array:</p>
<pre><code>p = np.asarray([[1., 2., 3.], [-4., -5., -6.], [1,2,-4]], dtype=np.float32)
</code></pre>
<p>which is</p>
<pre><code>array([[ 1., 2., 3.],
[-4., -5., -6.],
[ 1., 2., -4.]], dtype=float32)
</code></pre>
<p>i want to mutate the ... | 1 | 2016-07-18T12:02:49Z | 38,436,341 | <p><code>p[boolean_array]</code> returns a copy, so you modify your copy but leave your original unchanged. You could use <code>np.where</code> instead for example. Something like <code>p[:,2] = np.where(p[:,2], p[:,2], -p[:,2])</code></p>
| 0 | 2016-07-18T12:08:47Z | [
"python",
"arrays",
"numpy",
"selection"
] |
python numpy mutate selection | 38,436,231 | <p>i encountered a strange bug(?) in numpy:
Given a nested array:</p>
<pre><code>p = np.asarray([[1., 2., 3.], [-4., -5., -6.], [1,2,-4]], dtype=np.float32)
</code></pre>
<p>which is</p>
<pre><code>array([[ 1., 2., 3.],
[-4., -5., -6.],
[ 1., 2., -4.]], dtype=float32)
</code></pre>
<p>i want to mutate the ... | 1 | 2016-07-18T12:02:49Z | 38,439,588 | <p>Reversing the order of your square brackets should fix it:</p>
<pre><code>p[:, 2][p[:, 2] < 0] *= -1
</code></pre>
<p>Boolean indexing returns a copy, unless you are doing an assignment to it, which you can achieve by making it be the last indexing operation. </p>
| 1 | 2016-07-18T14:41:51Z | [
"python",
"arrays",
"numpy",
"selection"
] |
Python (Flask) and MQTT listening | 38,436,412 | <p>I'm currently trying to get my Python (Flask) webserver to display what my MQTT script is doing. The MQTT script, In essence, it's subscribed to a topic and I would really like to categorize the info it gets and display/update it in real time. Something like a simple list displaying various the settings that gets up... | 0 | 2016-07-18T12:12:27Z | 38,436,995 | <p>I would make a separate service for the MQTT message handling. This service could process the messages received and store them (database, redis, simple inprogram memory) for access.</p>
<p>When a page in your flask app gets hit, you would connect to the service (or its storage) and process/display the information s... | 2 | 2016-07-18T12:40:44Z | [
"python",
"flask",
"mqtt"
] |
Why does my return statement ignore the rest of my code in a function in python? | 38,436,429 | <p>In my function, I type in a raw_input after my return statement and then I proceed to call my function. When I call my function the raw_input is totally ignored and only the return statement works.</p>
<pre><code> def game():
#This selects 5 community cards from the pick_community function
communi... | -10 | 2016-07-18T12:13:15Z | 38,436,478 | <p>Because a return statement gets out of the function, so the rest of the code wont execute</p>
| 1 | 2016-07-18T12:15:21Z | [
"python"
] |
Why does my return statement ignore the rest of my code in a function in python? | 38,436,429 | <p>In my function, I type in a raw_input after my return statement and then I proceed to call my function. When I call my function the raw_input is totally ignored and only the return statement works.</p>
<pre><code> def game():
#This selects 5 community cards from the pick_community function
communi... | -10 | 2016-07-18T12:13:15Z | 38,436,537 | <p>If you want to return first 3 values and then continue in code you can do it using <code>yield</code>. It basically inserts values into generator, then in the end return the whole generator.</p>
<p><a href="https://pythontips.com/2013/09/29/the-python-yield-keyword-explained/" rel="nofollow">https://pythontips.com/... | 2 | 2016-07-18T12:17:54Z | [
"python"
] |
Why does my return statement ignore the rest of my code in a function in python? | 38,436,429 | <p>In my function, I type in a raw_input after my return statement and then I proceed to call my function. When I call my function the raw_input is totally ignored and only the return statement works.</p>
<pre><code> def game():
#This selects 5 community cards from the pick_community function
communi... | -10 | 2016-07-18T12:13:15Z | 38,436,861 | <p>That: </p>
<pre><code>return first_3
</code></pre>
<p>returns and therefore ends the function.
The remaining code is just ignored, because you will never get past the return.</p>
| 2 | 2016-07-18T12:35:26Z | [
"python"
] |
Diagonal Wins aren't being detected Python | 38,436,732 | <p>I have created a Connect 4 game in Python using pygame. My board is:</p>
<pre><code>board = []
for row in range(6):
board.append([])
for column in range(7):
board[row].append(0)
</code></pre>
<p>Although when I have a diagonal win it doesn't seem to register. Can anyone see the issue with the algo... | 1 | 2016-07-18T12:28:32Z | 38,531,854 | <p>When you create the 6 rows, I assume that these are the y positions, and that the 7 elements you append to each row are the x positions. If this is the case, then your indexing in the code for diagonal win check is the reverse of the indexing when you populate the board. I would agree with Rawing in reversing the in... | 1 | 2016-07-22T17:02:35Z | [
"python",
"python-3.x",
"pygame"
] |
Python write in mkstemp() file | 38,436,987 | <p>I am creating a tmp file by using :</p>
<pre><code>from tempfile import mkstemp
</code></pre>
<p>I am trying to write in this file :</p>
<pre><code>tmp_file = mkstemp()
file = open(tmp_file, 'w')
file.write('TEST\n')
</code></pre>
<p>Indeed I close the file and do it proper but when I try to cat the tmp file, it... | 0 | 2016-07-18T12:40:24Z | 38,437,203 | <p><code>mkstemp()</code> returns a tuple with a file descriptor and a path. I think the issue is that you're writing to the wrong path. (You're writing to a path like <code>'(5, "/some/path")'</code>.) Your code should look something like this:</p>
<pre><code>from tempfile import mkstemp
fd, path = mkstemp()
# use ... | 2 | 2016-07-18T12:52:45Z | [
"python",
"mkstemp"
] |
MongoDB aggregate compare with previous document | 38,437,008 | <p>I have this query in Motor:</p>
<pre><code>history = yield self.db.stat.aggregate([
{'$match': {'user_id': user.get('uid')}},
{'$sort': {'date_time': -1}},
{'$project': {'user_id': 1, 'cat_id': 1, 'doc_id': 1, 'date_time': 1}},
{'$group': {
'_id': '$user_id',
... | 0 | 2016-07-18T12:41:10Z | 38,437,532 | <p>If you include some example documents from the "stat" collection I can give a more reliable answer. But with the information you've provided, I can guess. Add a stage something like:</p>
<pre><code>{'$group': {'_id': '$info.date', 'info': {'$first': '$info'}}}
</code></pre>
<p>That gives you each document in the r... | 0 | 2016-07-18T13:08:02Z | [
"python",
"mongodb",
"aggregation-framework",
"tornado-motor"
] |
Need to collate information from array in python, by finding match values that lie in different rows | 38,437,167 | <p>I'm looking to collate 2 entries into one for many columns in a data array, by checking to see if several values in the two entries are the same.</p>
<pre><code>0 A [[0.0, 0.5, 2.5, 2.5]
1 B [0.5, 1.0, 2.0, 2.0]
2 M [2.5, 2.5, 0.5, 0.0]
3 N ... | 0 | 2016-07-18T12:52:14Z | 38,437,515 | <p>Here's a way to find the index of each R2 value that you're after and create the final transformation to your specifications, edited based on our earlier dialogue in the comments below:</p>
<pre><code>#Input array
Arr1 = [[0.5, 0.5, 1, 1, 1.5, 1.5, 1.5, 5, 4.5, 4.5, 3.5, 2.5, 2, 1],
[0, 0, 0.5, 0.5, 1, 1,... | 1 | 2016-07-18T13:07:24Z | [
"python",
"arrays",
"numpy",
"pandas"
] |
Need to collate information from array in python, by finding match values that lie in different rows | 38,437,167 | <p>I'm looking to collate 2 entries into one for many columns in a data array, by checking to see if several values in the two entries are the same.</p>
<pre><code>0 A [[0.0, 0.5, 2.5, 2.5]
1 B [0.5, 1.0, 2.0, 2.0]
2 M [2.5, 2.5, 0.5, 0.0]
3 N ... | 0 | 2016-07-18T12:52:14Z | 38,437,769 | <p>Another approach to the problem might be slicing the data using the following function:</p>
<pre><code> import numpy as np
def transform(arr):
arr1 = arr[:,0:2]
arr1 = np.append(arr1,[arr[-1,2:]],axis=0)
return arr1
</code></pre>
<p>using given data:</p>
<pre><code> arr = np.array([[0.0, 0.5, ... | 0 | 2016-07-18T13:17:58Z | [
"python",
"arrays",
"numpy",
"pandas"
] |
Environmental variables from .env file not available during local migrations in django, heroku | 38,437,170 | <p>I have been developing on Heroku, using the <code>config</code> variables to store sensitive and other environmental variables. While developing locally, I have mirrored these variables in the <code>.env</code> file. </p>
<p>What I am finding now is the variables from the <code>.env</code> file do not load during... | 0 | 2016-07-18T12:52:24Z | 38,437,282 | <p><code>manage.py</code> doesn't know anything about your .env file. You'll need to run the command under something that does; either <a href="https://github.com/ddollar/foreman" rel="nofollow">Foreman</a>, which is what Heroku itself uses, or <a href="https://github.com/nickstenning/honcho" rel="nofollow">Honcho</a>,... | 1 | 2016-07-18T12:55:36Z | [
"python",
"django",
"postgresql",
"heroku",
"migration"
] |
Environmental variables from .env file not available during local migrations in django, heroku | 38,437,170 | <p>I have been developing on Heroku, using the <code>config</code> variables to store sensitive and other environmental variables. While developing locally, I have mirrored these variables in the <code>.env</code> file. </p>
<p>What I am finding now is the variables from the <code>.env</code> file do not load during... | 0 | 2016-07-18T12:52:24Z | 38,437,363 | <p>I finally figured out that simply running <code>python manage.py migrate</code> did nothing to load the <code>.env</code> file variables. You need to do run the commands in the <code>heroku local</code> environment:</p>
<pre><code>heroku local:run python manage.py migrate
</code></pre>
<p><a href="https://devcent... | 1 | 2016-07-18T12:59:34Z | [
"python",
"django",
"postgresql",
"heroku",
"migration"
] |
Filling a dataframe column based on multiple conditional choices | 38,437,189 | <p>I have a dataframe <code>data</code> which looks like:</p>
<pre><code>Holiday Report Action Power
0 0 0 1.345
0 0 0 1.345
1 0 0 0
0 0 0 1.345
0 0 0 1.345
0 1 0 0
0 ... | 1 | 2016-07-18T12:52:02Z | 38,437,397 | <p>You can subselect the rows by slicing, compare against 1 and use <code>any</code> with param <code>axis=1</code> and create a boolean mask passing to <code>loc</code> to set only those rows that meet the condition to <code>1</code> as desired:</p>
<pre><code>In [23]:
df.loc[(df.ix[:,:'Action'] == 1).any(axis=1), 'P... | 3 | 2016-07-18T13:01:17Z | [
"python",
"pandas"
] |
Filling a dataframe column based on multiple conditional choices | 38,437,189 | <p>I have a dataframe <code>data</code> which looks like:</p>
<pre><code>Holiday Report Action Power
0 0 0 1.345
0 0 0 1.345
1 0 0 0
0 0 0 1.345
0 0 0 1.345
0 1 0 0
0 ... | 1 | 2016-07-18T12:52:02Z | 38,437,865 | <p>Hope this helps using <code>np.where</code>:</p>
<pre><code>In[49]:df['Power']=np.where((df['Holiday']==1)|(df['Report']==1)|(df['Action']==1),1,df['Power'])
In[50]:df
Out[50]:
Holiday Report Action Power
0 0 0 0 1.345
1 0 0 0 1.345
2 1 0 0 1.000
3... | 1 | 2016-07-18T13:23:11Z | [
"python",
"pandas"
] |
QCheckBox state change PyQt4 | 38,437,347 | <p>I'm trying to implement a system in PyQt4 where unchecking a checkbox would call function disable_mod and checking it would call enable_mod. But even though state is changing the checkboxes call the initial function they started with. For this case if an already checked box was clicked it'd always keep calling the d... | 0 | 2016-07-18T12:58:45Z | 38,443,210 | <p>The problem is that you're only connecting the checkbox <code>stateChanged</code> signal once during initialization. After the state of the checkbox changes, you're not disconnecting the signal and reconnecting it to the correct slot.</p>
<p>You'll need to connect the <code>stateChanged</code> signal to an interme... | 2 | 2016-07-18T18:02:37Z | [
"python",
"qt",
"pyqt",
"qcheckbox"
] |
Pandas HDFStore.create_table_index not increasing select query speed, looking for a better way to search | 38,437,413 | <p>I have created an HDFStore.
The HDFStore contains a group <code>df</code> which is a table with 2 columns.
The first column is a <code>string</code> and second column is <code>DateTime</code>(which will be in sorted order).
The Store has been created using the following method:</p>
<pre><code>from numpy import ndar... | 4 | 2016-07-18T13:02:00Z | 38,441,386 | <p>I think your columns has already been indexed when you specified <code>data_columns=True</code>...</p>
<p>See this demo:</p>
<pre><code>In [39]: df = pd.DataFrame(np.random.randint(0,100,size=(10, 3)), columns=list('ABC'))
In [40]: fn = 'c:/temp/x.h5'
In [41]: store = pd.HDFStore(fn)
In [42]: store.append('tabl... | 2 | 2016-07-18T16:07:19Z | [
"python",
"pandas",
"hdfstore"
] |
find closest value pair in python list | 38,437,417 | <p>I have a dictionary as so:</p>
<pre><code>d = {'ID_1':[(10, 20), (40, 60), (125, 200)], 'ID_2': [(75, 100), (250, 300)]}
</code></pre>
<p>and a position and ID:</p>
<pre><code>pos = 70
IDed = ID_1
output = (40, 60)
pos = 90
IDed = ID_2
expected output = (75, 100)
pos = 39
IDed = ID_1
expected output = (40, 60)
... | 0 | 2016-07-18T13:02:08Z | 38,437,572 | <p>You were really close. Bellow is a working solution.</p>
<pre><code>d = {'ID_1': [(10, 20), (40, 60), (125, 200)], 'ID_2': [(75, 100), (250, 300)]}
pos = 70
IDed = 'ID_1'
closest = min(d[IDed], key=lambda x: min(abs(y - pos) for y in x)) if IDed in d else None
print(closest)
# (40, 60)
</code></pre>
<p>Th... | 4 | 2016-07-18T13:09:51Z | [
"python",
"list",
"dictionary"
] |
find closest value pair in python list | 38,437,417 | <p>I have a dictionary as so:</p>
<pre><code>d = {'ID_1':[(10, 20), (40, 60), (125, 200)], 'ID_2': [(75, 100), (250, 300)]}
</code></pre>
<p>and a position and ID:</p>
<pre><code>pos = 70
IDed = ID_1
output = (40, 60)
pos = 90
IDed = ID_2
expected output = (75, 100)
pos = 39
IDed = ID_1
expected output = (40, 60)
... | 0 | 2016-07-18T13:02:08Z | 38,437,625 | <p>I think that you want to find the couple which has the closest average with pos value...
So this is the answer:</p>
<pre><code>d = {'ID_1':[(10, 20), (40, 60), (125, 200)], 'ID_2': [(75, 100), (250, 300)]}
pos = 70
closest = (0, 0)
IDed = "ID_1"
for i in d.items():
if IDed == i[0]:
for x in i[1]:
... | 0 | 2016-07-18T13:12:01Z | [
"python",
"list",
"dictionary"
] |
Python - remap the values according to date | 38,437,431 | <p>I have 3 <code>tsv</code> files with different stock values on a slight different date. I need to compile all 3 stock values into 1 <code>tsv</code> file according to date. The problem is the 3 files have slight different date. For example, </p>
<pre><code>Stock1:
23 july 2009 - 10.03
24 july 2009 - 10.07
25 july 2... | 0 | 2016-07-18T13:02:37Z | 38,437,647 | <p>To answer your question how to iterate multiple files, use <code>fileinput.input()</code>.</p>
<pre><code>with fileinput.input(files=('spam.txt', 'eggs.txt')) as f:
for line in f:
process(line)
</code></pre>
| 0 | 2016-07-18T13:13:09Z | [
"python"
] |
Python - remap the values according to date | 38,437,431 | <p>I have 3 <code>tsv</code> files with different stock values on a slight different date. I need to compile all 3 stock values into 1 <code>tsv</code> file according to date. The problem is the 3 files have slight different date. For example, </p>
<pre><code>Stock1:
23 july 2009 - 10.03
24 july 2009 - 10.07
25 july 2... | 0 | 2016-07-18T13:02:37Z | 38,438,821 | <p>Using <code>pandas</code>, as you have mentioned its a <code>tsv</code> hope it helps:</p>
<pre><code>df1=pd.read_csv('filepath/stock1',sep='\t')
df
Out[31]:
0 1
0 23 july 2009 10.03
1 24 july 2009 10.07
2 25 july 2009 NaN
</code></pre>
<p>Similarly for the other two files as:</p>
<pre... | 0 | 2016-07-18T14:06:13Z | [
"python"
] |
Django - How do I delete single database entries on button click? | 38,437,483 | <p>I'm trying to set up a user profile where you can enter skills. Entering the skills and save them in the databse already works. Now I want to give the user the opportunity to delete every single one of them with a button click. I tried posting the ID of each skill on button click in the URL and read it out in my vie... | 0 | 2016-07-18T13:05:22Z | 38,437,832 | <p>You have forgotten to include dollar signs at the end of the regexes in your URL patterns. It should be:</p>
<pre><code>urlpatterns = [
url(r'^landing$', views.landing, name='landing'),
url(r'^neuigkeiten$', views.news, name='news'),
url(r'^profileinstellungen/$', views.profile_settings, name='profilein... | 0 | 2016-07-18T13:20:54Z | [
"python",
"django",
"django-models",
"django-templates",
"django-views"
] |
Django - How do I delete single database entries on button click? | 38,437,483 | <p>I'm trying to set up a user profile where you can enter skills. Entering the skills and save them in the databse already works. Now I want to give the user the opportunity to delete every single one of them with a button click. I tried posting the ID of each skill on button click in the URL and read it out in my vie... | 0 | 2016-07-18T13:05:22Z | 38,437,849 | <p>Try to change this :</p>
<pre><code><input href="{% url 'profileinstellungen' id=skill.id%}" type="submit" value="Löschen" name="delete-skill"/>
</code></pre>
<p>by this : </p>
<pre><code><input href="{% url 'profileinstellungen' %}{{skill.id}}" type="submit" value="Löschen" name="delete-skill"/>
</... | 0 | 2016-07-18T13:22:15Z | [
"python",
"django",
"django-models",
"django-templates",
"django-views"
] |
QGIS Python, pointer is null error | 38,437,541 | <p>I have this code that I got from this question: (<a href="http://gis.stackexchange.com/questions/190404/how-to-render-layer-into-png-in-a-standalone-application?rq=1">http://gis.stackexchange.com/questions/190404/how-to-render-layer-into-png-in-a-standalone-application?rq=1</a>).</p>
<p>When typing in the command t... | 1 | 2016-07-18T13:08:33Z | 38,513,314 | <p>I had this error once, and realized that I didn't have QGIS fully installed. Maybe uninstall and reinstall.</p>
| 0 | 2016-07-21T19:59:25Z | [
"python",
"qgis"
] |
implement jsonp request for python | 38,437,595 | <p>I am using a python rest api and want to fetch data from an api which gives me json response with a padding(jsonp request). I have seen few examples where javascript(jquery and angularjs) need to add a callback function for getting json. How to do the same with python?</p>
| 0 | 2016-07-18T13:10:54Z | 38,437,911 | <p>You don't need to, the padding is only needed in browser/JavaScript context to bypass certain security constraints. For Python usage just take the raw response, remove the padding and parse the remaining data accordingly.</p>
<pre><code>from json import loads
a = 'paddingFunction({"a":1,"b":2,"c":3,"d":4,"e":5})'
... | 2 | 2016-07-18T13:24:51Z | [
"python",
"jsonp"
] |
SWIG function with pointer struct | 38,437,615 | <p>Im new using SWIG to wrapped C shared library.</p>
<p>I have problem to call a C function with Struct pointer in python.</p>
<p>My files:</p>
<p><strong>ST_Param.h:</strong></p>
<pre><code>typedef struct {
unsigned int* device_Address;
....
....
unsigned int lock;
}ST_param_ST;
... | 1 | 2016-07-18T13:11:38Z | 38,439,536 | <p>You do this essentially the same way you do it in C: You first create a <code>ST_param_ST</code> struct and then pass this to the initialization function <code>ST_Param_Initialize()</code>. Here is an example in Python, assuming your module is called <code>ex</code>:</p>
<pre><code>>>> import ex
>>&g... | 2 | 2016-07-18T14:38:49Z | [
"python",
"c",
"pointers",
"struct",
"swig"
] |
Delete line in file | 38,437,619 | <p>I wanna show the lines in a file, let the user decide which line should be deleted and then write all lines back to the file, except the one the user wants to delete. </p>
<p>This is what I tried so far, but I'm kinda stuck.</p>
<pre><code>def delete_result():
text_file = open('minigolf.txt', 'r')
zork = 0... | 3 | 2016-07-18T13:11:44Z | 38,437,741 | <pre><code>line_number = 5 #for example
file = open("foo.txt")
cont = file.read()
cont = cont.splitlines()
cont.pop(line_number-1)
file.close()
file = open("foo.txt", "w")
cont= "\n".join(cont)
file.write(cont)
file.close()
</code></pre>
<p>If you do it with names; try that:</p>
<pre><code>file = open("foo.txt")
con... | 1 | 2016-07-18T13:17:05Z | [
"python"
] |
Delete line in file | 38,437,619 | <p>I wanna show the lines in a file, let the user decide which line should be deleted and then write all lines back to the file, except the one the user wants to delete. </p>
<p>This is what I tried so far, but I'm kinda stuck.</p>
<pre><code>def delete_result():
text_file = open('minigolf.txt', 'r')
zork = 0... | 3 | 2016-07-18T13:11:44Z | 38,438,062 | <p>This will solve your issue and give you a more robust way of handling user input:</p>
<pre><code>def delete_result():
with open('minigolf.txt', 'r') as f:
text_file = f.readlines()
# find newline char and strip from endings
if '\r' in text_file[0]:
if '\n' in text_file[0]:
n... | 0 | 2016-07-18T13:31:15Z | [
"python"
] |
Delete line in file | 38,437,619 | <p>I wanna show the lines in a file, let the user decide which line should be deleted and then write all lines back to the file, except the one the user wants to delete. </p>
<p>This is what I tried so far, but I'm kinda stuck.</p>
<pre><code>def delete_result():
text_file = open('minigolf.txt', 'r')
zork = 0... | 3 | 2016-07-18T13:11:44Z | 38,438,086 | <pre><code>def delete_result():
with open('minigolf.txt', 'r') as f:
results = f.readlines()
print(results)
user = raw_input('which user do you want to delete')
for res in results:
if user.lower() in res: # assumption that sara == Sara
results.remove(res)
... | 1 | 2016-07-18T13:32:40Z | [
"python"
] |
Delete line in file | 38,437,619 | <p>I wanna show the lines in a file, let the user decide which line should be deleted and then write all lines back to the file, except the one the user wants to delete. </p>
<p>This is what I tried so far, but I'm kinda stuck.</p>
<pre><code>def delete_result():
text_file = open('minigolf.txt', 'r')
zork = 0... | 3 | 2016-07-18T13:11:44Z | 38,438,523 | <p>A slight modification to danidee's answer for clarity</p>
<pre><code>def delete_result():
with open('minigolf.txt', 'r') as f:
results = f.readlines()
print "\n".join(results)
delete_player = raw_input ("Who's result do you want to delete?")
deleted = False
for res in results:
... | 1 | 2016-07-18T13:52:19Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.