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 |
|---|---|---|---|---|---|---|---|---|---|
Web Scraping Python using Google Chrome extension | 39,104,480 | <p>Hi I am a Python newbie and I am webscrapping a webpage. </p>
<p>I am using the Google Chrome Developer Extension to identify the class of the objects I want to scrape. However, my code returns an empty array of results whereas the screenshots clearly show that that those strings are in the HTML code.
<a href="http... | 0 | 2016-08-23T14:52:57Z | 39,104,831 | <p>Converted my comment to an answer...</p>
<p>Make sure the data you are expecting is actually there. Use <code>print(soup.prettify())</code> to see what was actually returned from the request. Depending on how the site works, the data you are looking for may only exist in the browser after the javascript is proces... | 0 | 2016-08-23T15:09:24Z | [
"javascript",
"python"
] |
NumPy performance: uint8 vs. float and multiplication vs. division? | 39,104,562 | <p>I have just noticed that the execution time of a script of mine nearly halves by only changing a multiplication to a division.</p>
<p>To investigate this, I have written a small example:</p>
<pre><code>import numpy as np ... | 12 | 2016-08-23T14:57:01Z | 39,106,626 | <p>It's the very first operation that will typically take longer before "warming up" (e.g. memory allocated, caching).</p>
<p>See the same effect using the reverse order of dividing and multiplying:</p>
<pre><code>>>> print_time("arrdiv", timeit.timeit("arrdiv(arr2)", "from __main__ import arrdiv, arr2", num... | -2 | 2016-08-23T16:42:20Z | [
"python",
"performance",
"python-2.7",
"numpy"
] |
NumPy performance: uint8 vs. float and multiplication vs. division? | 39,104,562 | <p>I have just noticed that the execution time of a script of mine nearly halves by only changing a multiplication to a division.</p>
<p>To investigate this, I have written a small example:</p>
<pre><code>import numpy as np ... | 12 | 2016-08-23T14:57:01Z | 39,163,473 | <p>It's because you multiply an int by a float and store the result as an int.
Try your arr_mult and arr_div tests with different integer or float values for the multiplication / division. Especially, compare multiplying by '2' and multiplying by '2.'</p>
| -1 | 2016-08-26T09:53:34Z | [
"python",
"performance",
"python-2.7",
"numpy"
] |
NumPy performance: uint8 vs. float and multiplication vs. division? | 39,104,562 | <p>I have just noticed that the execution time of a script of mine nearly halves by only changing a multiplication to a division.</p>
<p>To investigate this, I have written a small example:</p>
<pre><code>import numpy as np ... | 12 | 2016-08-23T14:57:01Z | 39,174,057 | <p>The problem is your assumption, that you measure the time needed for division or multiplication, which is not true. You are measuring the overhead needed for a division or multiplication. </p>
<p>One has really to look at the exact code to explain every effect, which can vary from version to version. This answer ca... | 5 | 2016-08-26T20:15:24Z | [
"python",
"performance",
"python-2.7",
"numpy"
] |
NumPy performance: uint8 vs. float and multiplication vs. division? | 39,104,562 | <p>I have just noticed that the execution time of a script of mine nearly halves by only changing a multiplication to a division.</p>
<p>To investigate this, I have written a small example:</p>
<pre><code>import numpy as np ... | 12 | 2016-08-23T14:57:01Z | 39,182,139 | <p>This answer only looks at vectorised operations, as the reason for the other operations being slow has been answered by <a href="http://stackoverflow.com/a/39174057/529630">ead</a>.</p>
<p>A lot of "optimisations" are based on old hardware. The assumptions that meant that optimisations held true on older hardware d... | 2 | 2016-08-27T14:19:02Z | [
"python",
"performance",
"python-2.7",
"numpy"
] |
Django Rest Framework Recursive Nested Parent Serialization | 39,104,575 | <p>I have a model with a self referential field called parent.
Model:</p>
<pre><code>class Zone(BaseModel):
name = models.CharField(max_length=200)
parent = models.ForeignKey('self', models.CASCADE, blank=True, null=True, related_name='children')
def __unicode__(self):
return self.name
</code></pr... | 0 | 2016-08-23T14:57:47Z | 39,105,821 | <p>Try use <a href="http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield" rel="nofollow">SerializerMethodField</a> here:</p>
<pre><code>def get_parent(self, obj):
# query what your want here.
</code></pre>
<p>I'm not sure D-R-F has build-in methods for this, but you can use query to get wh... | 1 | 2016-08-23T15:56:48Z | [
"python",
"django",
"recursion",
"serialization",
"django-rest-framework"
] |
Django Rest Framework Recursive Nested Parent Serialization | 39,104,575 | <p>I have a model with a self referential field called parent.
Model:</p>
<pre><code>class Zone(BaseModel):
name = models.CharField(max_length=200)
parent = models.ForeignKey('self', models.CASCADE, blank=True, null=True, related_name='children')
def __unicode__(self):
return self.name
</code></pr... | 0 | 2016-08-23T14:57:47Z | 39,122,426 | <p>Ok, I got it working like that.</p>
<pre><code>class ZoneSerializer(ModelSerializer):
parent = SerializerMethodField()
class Meta:
model = Zone
fields = ('id', 'name', 'project', 'parent',)
def get_parent(self, obj):
if obj.parent is not None:
return ZoneSerializer(... | 0 | 2016-08-24T11:44:29Z | [
"python",
"django",
"recursion",
"serialization",
"django-rest-framework"
] |
Setting up BGP Layer Using Scapy | 39,104,621 | <p>I am trying to use Scapy to send packets that have a BGP layer</p>
<p>I am currently stuck on a rudimentary part of this problem because I am unable to set up the BGP layer. I followed the instructions to set up the regular IP and TCP Layer.</p>
<p>Eg:</p>
<pre><code>>>a=IP(src="192.168.1.1",dst="192.168.1.... | 0 | 2016-08-23T15:00:21Z | 39,107,539 | <p>Just going to try and help here. I have zero experience with BGP type packets, but... I copied the bgp.py file from the link you provided into scapy/layers. Using ls() I found the following:</p>
<pre><code>BGPAuthenticationData : BGP Authentication Data
BGPErrorSubcodes : BGP Error Subcodes
BGPHeader : BGP head... | 0 | 2016-08-23T17:37:00Z | [
"python",
"networking",
"scapy",
"bgp"
] |
label in kivy doesn't update in while loop | 39,104,655 | <p>I'm trying to make a timer that updates a label to see the current amount of time remaining. I have a button that when you press should start the 2 min timer. For some reason the label doesn't update. Is there something wrong with the way I am doing this?</p>
<p>Here is my code:</p>
<pre><code>import time
from ki... | 0 | 2016-08-23T15:01:34Z | 39,104,845 | <p>Kivy's graphics can't update until your while loop finishes - during the loop, only the content of the loop is run (repeatedly), and Kivy's normal functions are blocked.</p>
<p>You should instead use <code>Clock.schedule_interval</code> to run computations every frame without blocking other functions, or run your w... | 1 | 2016-08-23T15:10:03Z | [
"python",
"kivy"
] |
Geopandas Dataframe Points to Polygons | 39,104,710 | <p>I have a geopandas dataframe made up of an id and a geometry column which is populated by 2D points. I want to join the points for each unique id to create a polygon, so that my new dataframe will have polygons as its geometry. My code currently looks something like this:</p>
<pre><code>polygons = geopandas.GeoData... | 0 | 2016-08-23T15:04:07Z | 39,154,164 | <p>I have achieved something similar with the <code>groupby</code> function. Assuming your points are actually Shapely <code>Point</code> objects, and are sorted in the right order, you can try something like this.</p>
<pre><code>import pandas as pd
import geopandas as gp
from shapely.geometry import Point, Polygon
#... | 1 | 2016-08-25T20:23:32Z | [
"python",
"pandas",
"shapely",
"geopandas"
] |
Pandas replace with default value | 39,104,730 | <p>I have a pandas dataframe I want to replace a certain column conditionally.</p>
<p>eg:</p>
<pre><code> col
0 Mr
1 Miss
2 Mr
3 Mrs
4 Col.
</code></pre>
<p>I want to map them as</p>
<pre><code>{'Mr': 0, 'Mrs': 1, 'Miss': 2}
</code></pre>
<p>If there are other titles now available in the dict then I want t... | 2 | 2016-08-23T15:04:57Z | 39,104,759 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> rather as <code>replace</code>, because faster, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>fillna</code></a>... | 3 | 2016-08-23T15:06:20Z | [
"python",
"pandas",
"replace",
"dataframe",
"condition"
] |
How do I join the args of a function to form a string? | 39,104,787 | <p>I am trying to obtain a string from the attributes of the <code>changegame</code> function in order to change the status of a bot i'm developing.</p>
<pre><code>async def changegame(*game_chosen: str):
"""Changes the game the bot is playing"""
game_str = discord.Game(name=game_chosen)
try:
await... | 0 | 2016-08-23T15:07:18Z | 39,104,861 | <p>To solve your initial issue, try a simple join:</p>
<pre><code>' '.join(map(str, game_chosen))
</code></pre>
<p>However, your bigger problem is:</p>
<pre><code>game_str = discord.Game(name=game_chosen)
</code></pre>
<p>Here you are passing a <em>tuple</em> to <code>discord.Game</code>, are you sure this is right... | 1 | 2016-08-23T15:10:43Z | [
"python"
] |
Partial substitution / removing characters within regex matches | 39,104,792 | <p>I'm trying to remove the characters <code>\/<>~?`%</code> if they appear within three <code>&lt;</code>'s and <code>&gt;</code>'s.</p>
<p>For the string:</p>
<p><code><html><body>Multiple &lt;&lt;&lt;parameter&gt;&gt;&gt; options %to &lt;&lt;&lt;test/ve... | 0 | 2016-08-23T15:07:41Z | 39,104,793 | <p>The solution I went with was using the original <code><<<.*>>></code> regex and the <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><code>repl</code> as a function</a> option for <code>re.sub</code>:</p>
<pre><code>>>> def illrepl(matchobj):
... return ''.joi... | 2 | 2016-08-23T15:07:41Z | [
"python",
"regex",
"string",
"substitution"
] |
Why make lists unhashable? | 39,104,841 | <p>A common issue on SO is <a href="https://stackoverflow.com/questions/39081807/python-2-d-list-how-to-make-a-set/39081956#39081956">removing duplicates from a list of lists</a>. Since lists are unhashable, <code>set([[1, 2], [3, 4], [1, 2]])</code> throws <code>TypeError: unhashable type: 'list'</code>. Answers to ... | 3 | 2016-08-23T15:09:57Z | 39,104,966 | <p>You seem to confuse mutability with rebinding. <code>a += 1</code> assigns a <strong>new object</strong>, the <code>int</code> object with the numeric value 1235, to <code>a</code>. Under the hood, for immutable objects like <code>int</code>, <code>a += 1</code> is just the same as <code>a = a + 1</code>.</p>
<p>Th... | 9 | 2016-08-23T15:14:57Z | [
"python",
"list",
"hash"
] |
pandas dataframe get rows based on matched strings in cells | 39,104,860 | <p>Given the following data frame</p>
<pre class="lang-none prettyprint-override"><code>+-----+----------------+--------+---------+
| | A | B | C |
+-----+----------------+--------+---------+
| 0 | hello@me.com | 2.0 | Hello |
| 1 | you@you.com | 3.0 | World |
| 2 | us@... | 2 | 2016-08-23T15:10:42Z | 39,105,906 | <p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.findall.html" rel="nofollow">findall</a> function which takes regular expressions.</p>
<pre><code>msk = df.apply(lambda x: x.str.findall(r'[Hh](i|ello)')).any(axis=1)
df[msk]
+---|------------|------|---------+
| | ... | 2 | 2016-08-23T16:01:15Z | [
"python",
"pandas",
"dataframe"
] |
pandas dataframe get rows based on matched strings in cells | 39,104,860 | <p>Given the following data frame</p>
<pre class="lang-none prettyprint-override"><code>+-----+----------------+--------+---------+
| | A | B | C |
+-----+----------------+--------+---------+
| 0 | hello@me.com | 2.0 | Hello |
| 1 | you@you.com | 3.0 | World |
| 2 | us@... | 2 | 2016-08-23T15:10:42Z | 39,109,496 | <p>Using <code>stack</code> to avoid <code>apply</code></p>
<pre><code>df.loc[df.stack().str.match(r'[Hh](i|ello)').unstack().any(1)]
</code></pre>
<p><a href="http://i.stack.imgur.com/wj6D4.png" rel="nofollow"><img src="http://i.stack.imgur.com/wj6D4.png" alt="enter image description here"></a></p>
<p>Using <code>m... | 3 | 2016-08-23T19:45:06Z | [
"python",
"pandas",
"dataframe"
] |
unicode issue in python when writing to file | 39,104,863 | <p>I have an csv sheet that i read it like this:</p>
<pre><code> with open(csvFilePath, 'rU') as csvFile:
reader = csv.reader(csvFile, delimiter= '|')
numberOfMovies = 0
for row in reader:
title = row[1:2][0]
</code></pre>
<p>as you see, i am taking the value of <code>title</code>... | 0 | 2016-08-23T15:10:46Z | 39,105,077 | <p>The normal csv library can have difficulty writing unicode to files. I suggest you use the <a href="https://pypi.python.org/pypi/unicodecsv/0.14.1" rel="nofollow">unicodecsv</a> library instead of the csv library. It supports writing unicode to CSVs.</p>
<p>Practically speaking, just write: </p>
<pre><code>import... | 2 | 2016-08-23T15:20:47Z | [
"python",
"unicode"
] |
Comparing rows of pandas dataframe and find intersection? | 39,104,869 | <p>I have a df :</p>
<pre><code>year name_list
2009 [sam,maj,mak]
2010 [sam, mak, ali, mo, za]
2011 [mp,ki]
</code></pre>
<p>I would like to compare each row in terms of name_list and count how many new names are added/deleted each year.
Expected results:</p>
<pre><code> year name_list added_count rem... | 0 | 2016-08-23T15:11:12Z | 39,109,260 | <p>First two lines are to initialize 2009 values to zero. Assumes that the years are in chronological order and the years are in the index and not a separate column. Also assumes no duplicate values for the names in column 'name_list'. </p>
<pre><code>df.loc[2009,'added_count'] = 0
df.loc[2009,'removed_count'] = 0
for... | 1 | 2016-08-23T19:28:25Z | [
"python",
"pandas",
"compare",
"rows"
] |
completely delete a list in python | 39,104,917 | <p>I'm using python 2, and trying to <strong>delete two lists</strong>.
Here is the code:</p>
<pre><code>test_data1 = [img for img in glob.glob("/location/of/images/*png")]
test_data0 = [img for img in glob.glob("/location/of/other_images/*png")]
test_data = test_data1 + test_data0
</code></pre>
<p>Every list of imag... | 2 | 2016-08-23T15:12:56Z | 39,104,973 | <p>You can use list concatenation to remove the need for the intermediate lists</p>
<pre><code>test_data = []
test_data += [img for img in glob.glob("/location/of/images/*png")]
test_data += [img for img in glob.glob("/location/of/other_images/*png")]
</code></pre>
<p>Also I'm not sure what the overall design of your... | 4 | 2016-08-23T15:15:13Z | [
"python",
"list",
"python-2.7",
"memory"
] |
completely delete a list in python | 39,104,917 | <p>I'm using python 2, and trying to <strong>delete two lists</strong>.
Here is the code:</p>
<pre><code>test_data1 = [img for img in glob.glob("/location/of/images/*png")]
test_data0 = [img for img in glob.glob("/location/of/other_images/*png")]
test_data = test_data1 + test_data0
</code></pre>
<p>Every list of imag... | 2 | 2016-08-23T15:12:56Z | 39,105,097 | <p>You could use <a href="https://docs.python.org/2/tutorial/datastructures.html#more-on-lists" rel="nofollow"><code>extend()</code></a>. This will instantiate a list and populate it with those items, and extend will append that list to <code>test_data</code>. This way, the only place in memory that the lists exist in ... | 2 | 2016-08-23T15:21:51Z | [
"python",
"list",
"python-2.7",
"memory"
] |
completely delete a list in python | 39,104,917 | <p>I'm using python 2, and trying to <strong>delete two lists</strong>.
Here is the code:</p>
<pre><code>test_data1 = [img for img in glob.glob("/location/of/images/*png")]
test_data0 = [img for img in glob.glob("/location/of/other_images/*png")]
test_data = test_data1 + test_data0
</code></pre>
<p>Every list of imag... | 2 | 2016-08-23T15:12:56Z | 39,105,109 | <p>The option of adding new data to array as in other answers works, but if you want to keep having two arrays and adding them, consider using garbage collector.</p>
<p>Python has a garbage collector, that will delete the objects when they are no longer in use (i.e. when the object is unreachable and is not referenced... | 0 | 2016-08-23T15:22:39Z | [
"python",
"list",
"python-2.7",
"memory"
] |
completely delete a list in python | 39,104,917 | <p>I'm using python 2, and trying to <strong>delete two lists</strong>.
Here is the code:</p>
<pre><code>test_data1 = [img for img in glob.glob("/location/of/images/*png")]
test_data0 = [img for img in glob.glob("/location/of/other_images/*png")]
test_data = test_data1 + test_data0
</code></pre>
<p>Every list of imag... | 2 | 2016-08-23T15:12:56Z | 39,105,465 | <p>In fact, each list store <strong>references to string</strong>, but not strings itself.</p>
<p>I'm pretty sure, the used memory is about 1M x 4 (for 32 bits architecture) or 1M x 8 (for 64 bits architecture).</p>
<p>I suggest you to do profiling, see <a href="http://stackoverflow.com/questions/110259/which-python-... | -1 | 2016-08-23T15:40:21Z | [
"python",
"list",
"python-2.7",
"memory"
] |
Pylint AttributeError: 'module' object has no attribute 'append' | 39,104,919 | <p>I was configuring my new laptop (macbook pro) and everything was fine until I wanted to try my pylint command.</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/bin/pylint", line 11, in <module>
load_entry_point('pylint==1.6.4', 'console_scripts', 'pylint')()
File "/usr/local/lib/pyth... | 1 | 2016-08-23T15:12:58Z | 39,115,354 | <blockquote>
<p>Hi, can you show the value of init-hook from the configuration file you are using? What happen is that you have configured, somehow, init-hook with some invalid code. You can see this in your traceback through the last exec call, which happens only when init-hook is provided. Seeing its value could le... | 0 | 2016-08-24T05:50:41Z | [
"python",
"osx",
"pylint"
] |
Pandas, map two dataframes, count based on condition | 39,104,928 | <p>I have written some code to map the ids of two dataframes and if a condition matches then create a count in a specified column in the existing dataframe, I am looking for a more efficient way of calculating it. </p>
<p><strong>Sample Data</strong></p>
<pre><code>import numpy as np
import pandas as pd
d = {'ID' : p... | 1 | 2016-08-23T15:13:17Z | 39,105,187 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>crosstab</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>:</p>
<pre><code>print (pd.crosstab(df1.ID, df1.Tag)) ... | 1 | 2016-08-23T15:27:26Z | [
"python",
"pandas",
"dataframe"
] |
Multiply each block of a block matrix with different coefficient in NumPy | 39,104,999 | <p>Suppose I have a <code>(4*n)*(4*n)</code> block matrix, and I would like to multiply each block of <code>(n*n)</code> with a different coefficient from a corresponding <code>(4*4)</code> matrix - what is the way to do it in NumPy?</p>
<p>For example, I have:</p>
<pre><code>>>> mat
matrix([[1, 1, 1, 1],
... | 3 | 2016-08-23T15:16:52Z | 39,105,464 | <p>One way would be to construct a (4*n)*(4*n) block matrix from <code>x</code>:</p>
<pre><code>result = np.multiply(mat, np.kron(x, np.ones((n,n))))
</code></pre>
| 3 | 2016-08-23T15:40:20Z | [
"python",
"numpy",
"matrix",
"linear-algebra"
] |
Multiply each block of a block matrix with different coefficient in NumPy | 39,104,999 | <p>Suppose I have a <code>(4*n)*(4*n)</code> block matrix, and I would like to multiply each block of <code>(n*n)</code> with a different coefficient from a corresponding <code>(4*4)</code> matrix - what is the way to do it in NumPy?</p>
<p>For example, I have:</p>
<pre><code>>>> mat
matrix([[1, 1, 1, 1],
... | 3 | 2016-08-23T15:16:52Z | 39,106,830 | <p>Here's a vectorized approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> -</p>
<pre><code>m1,n1 = x.shape
m2,n2 = mat.shape
out = (mat.reshape(m1,m2//m1,n1,n2//n1)*x[:,None,:,None]).reshape(m2,n2)
</code></pre>
<p>Sample run -</p>... | 2 | 2016-08-23T16:55:37Z | [
"python",
"numpy",
"matrix",
"linear-algebra"
] |
Selenium Python 2.7 - asserting non-ascii characters | 39,105,019 | <p>I'm having an issue when asserting two non-ascii values. One is coming from a csv file and the other one obtained from an element in the html:</p>
<pre><code><h1 class="LoginElement">ç»å½</h1>
</code></pre>
<p>I'm using selenium to get the text</p>
<pre><code>w_msg = driver.find_element(By.CSS_SELEC... | 2 | 2016-08-23T15:18:14Z | 39,117,607 | <p>Python is trying to convert your <code>str</code> to a Unicode to carry out the comparison. Unfortunately, Python 2.x is designed to err on the side of caution and only decode your string using ASCII.</p>
<p>You need to decode <code>txt</code> to a Unicode using the appropriate encoding of the CSV file so Python do... | 2 | 2016-08-24T08:00:31Z | [
"python",
"unicode",
"py.test"
] |
Regular expression for coordinates in Python | 39,105,104 | <p>I don't have much experience with regexps, so need to ask the question here. </p>
<p>I'm uploading a database for a learning algorithm. There are five variables: iteration, label, vector of pixel intensities, vector of coordinates and bounding box cordinates. </p>
<p>I've uploaded vector of pixels this way:</p>
<... | 0 | 2016-08-23T15:22:28Z | 39,105,729 | <p>Does this do what you're looking for? </p>
<pre><code>re.findall(r'(\(\d+, \d+\))', coord_string)
</code></pre>
| 1 | 2016-08-23T15:52:50Z | [
"python",
"regex",
"list"
] |
How to find min value of another column greater than current column Pandas | 39,105,282 | <p>I am sure this is an easy one, but how do I find the minimum value of a column that is greater than the value in the current column? Also, how do I find the maximum value of a column less that the value in the current column?</p>
<pre><code>from io import StringIO
import io
text = """Order starttime ... | 0 | 2016-08-23T15:31:42Z | 39,105,595 | <p>You can try something like this:</p>
<pre><code>df.endtime.apply(lambda x: min(df.starttime[df.starttime > x]) if len(df.starttime[df.starttime > x]) != 0 else np.nan)
# 0 2016-03-01 14:31:10.806
# 1 2016-03-01 14:31:10.790
# 2 2016-03-01 14:31:10.806
# 3 NaT
# Name: endtime, dtyp... | 1 | 2016-08-23T15:46:09Z | [
"python",
"pandas",
"dataframe",
"aggregate",
"min"
] |
Merging several csv files and storing the file names as a variable - Python | 39,105,342 | <p>I am trying to append several csv files into a single csv file using python while adding the file name (or, even better, a sub-string of the file name) as a new variable. All files have headers. The following script does the trick of merging the files, but does not cover the file name as variable issue:</p>
<pre><c... | 0 | 2016-08-23T15:34:05Z | 39,105,436 | <p>Simple changes will achieve what you want:
For the first line</p>
<pre><code>outputfile.write(line) -> outputfile.write(line+',file')
</code></pre>
<p>and later</p>
<pre><code>outputfile.write(line+','+filenames[i])
</code></pre>
| 0 | 2016-08-23T15:38:47Z | [
"python",
"csv"
] |
Merging several csv files and storing the file names as a variable - Python | 39,105,342 | <p>I am trying to append several csv files into a single csv file using python while adding the file name (or, even better, a sub-string of the file name) as a new variable. All files have headers. The following script does the trick of merging the files, but does not cover the file name as variable issue:</p>
<pre><c... | 0 | 2016-08-23T15:34:05Z | 39,105,877 | <p>You can use Python's <code>csv</code> module to parse the CSV files for you, and to format the output. Example code (untested):</p>
<pre><code>import csv
with open(output_filename, "wb") as outfile:
writer = None
for input_filename in filenames:
with open(input_filename, "rb") as infile:
... | 0 | 2016-08-23T15:59:47Z | [
"python",
"csv"
] |
Python: adding values to columns in a text file | 39,105,352 | <p>I have a text file that looks like:</p>
<pre><code>0.0 3 0.1273
4.0 3 -0.0227
8.0 3 0.1273
</code></pre>
<p>I want to change this so that it prints out column1 and column2 and replaces the values in column3 to '1' for each row. So I want the output file to look like:</p>
<pre><code>0.0 3 1
4.0 ... | 0 | 2016-08-23T15:34:31Z | 39,105,902 | <p>Recall that tuple is immutable. You can't change the value.
So when you do <code>data = col1, col2, col3</code> then <code>data</code>'s value cannot be changed. Just simply assign <code>data</code> directly with <code>col1, col2, 1</code>. </p>
| 1 | 2016-08-23T16:00:59Z | [
"python",
"text-files"
] |
Spread function calls evenly over time in Python | 39,105,380 | <p>Let's say i have a function in Python and it's pretty fast so i can call it in a loop like 10000 times per second.</p>
<p>I'd like to call it, for example, 2000 times per second but with even intervals between calls (not just call 2000 times and wait till the end of the second). How can i achieve this in Python? </... | 0 | 2016-08-23T15:36:04Z | 39,105,597 | <p>You can use the built-in <a href="https://docs.python.org/2/library/sched.html" rel="nofollow"><code>sched</code></a> module which implements a general purpose scheduler.</p>
<pre><code>import sched, time
# Initialize the scheduler
s = sched.scheduler(time.time, time.sleep)
# Define some function for the schedule... | 0 | 2016-08-23T15:46:13Z | [
"python"
] |
Python setuptools don't give me permission to execute script | 39,105,468 | <p>I'm running the following from the package dir:</p>
<pre><code>sudo ./setup.py develop
# or
sudo python setup.py develop
</code></pre>
<p>The package contains two executables. <code>setup.py</code> places them in <code>/usr/bin/</code>, but when I'm trying to run them, it fails with:</p>
<pre><code>-bash: /usr/bi... | 0 | 2016-08-23T15:40:29Z | 39,119,762 | <p>I found <a href="http://unix.stackexchange.com/questions/166948/why-is-my-pip-installed-python-script-not-executable-for-everyone">answer</a> on <a href="https://unix.stackexchange.com">https://unix.stackexchange.com</a>.</p>
<p>This helped:</p>
<pre><code>sudo umask 002
</code></pre>
| 0 | 2016-08-24T09:44:16Z | [
"python",
"pip",
"package-managers"
] |
Python raw input function for tax calculation | 39,105,532 | <p>I am trying to make a simple calculator for working out the tax due on a salary. Please see the code below:</p>
<p>I keep getting this error and I don't know what is wrong, please help :) thanks!</p>
<pre><code>Traceback (most recent call last):
File "python", line 13
elif salary > 11000 and salary < 4... | 0 | 2016-08-23T15:43:13Z | 39,105,714 | <p>As the comments have already stated, your indentation is incorrect. See below:</p>
<pre><code>def taxes(salary):
salary >= 0
tax = 0
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary <... | 0 | 2016-08-23T15:52:11Z | [
"python"
] |
Python raw input function for tax calculation | 39,105,532 | <p>I am trying to make a simple calculator for working out the tax due on a salary. Please see the code below:</p>
<p>I keep getting this error and I don't know what is wrong, please help :) thanks!</p>
<pre><code>Traceback (most recent call last):
File "python", line 13
elif salary > 11000 and salary < 4... | 0 | 2016-08-23T15:43:13Z | 39,105,770 | <p>Steps to correct your code</p>
<p>step1 : the salary data type should be of int, to correct..use the following code</p>
<hr>
<p>step 2: Indentation is compulsory in python, so indent your code very well</p>
<hr>
<p>step 3: Add an else statement after the conditional statements</p>
<hr>
<p>step 4: indent retur... | 1 | 2016-08-23T15:54:40Z | [
"python"
] |
Python raw input function for tax calculation | 39,105,532 | <p>I am trying to make a simple calculator for working out the tax due on a salary. Please see the code below:</p>
<p>I keep getting this error and I don't know what is wrong, please help :) thanks!</p>
<pre><code>Traceback (most recent call last):
File "python", line 13
elif salary > 11000 and salary < 4... | 0 | 2016-08-23T15:43:13Z | 39,105,995 | <p>That because there are indent error in line number 12, now you can just copy pust this :</p>
<p>note : <code>salary > 11000 and salary < 43000</code> equivalent to <code>11000 < salary < 43000</code> in python:</p>
<pre><code>salary = raw_input ("What is your salary?")
print "So your gross annu... | 0 | 2016-08-23T16:05:13Z | [
"python"
] |
Python raw input function for tax calculation | 39,105,532 | <p>I am trying to make a simple calculator for working out the tax due on a salary. Please see the code below:</p>
<p>I keep getting this error and I don't know what is wrong, please help :) thanks!</p>
<pre><code>Traceback (most recent call last):
File "python", line 13
elif salary > 11000 and salary < 4... | 0 | 2016-08-23T15:43:13Z | 39,107,742 | <p>It felt like there was a better way of doing this, so I came up with an alternative route:</p>
<pre><code>tax_bands = [11000, 43000, 150000]
tax_amts = [0.2, 0.4, 0.45]
salary = 43001
</code></pre>
<p>Placing the thresholds and amounts into a list means that you can change them more easily if you need to.</p>
<p>... | 0 | 2016-08-23T17:49:07Z | [
"python"
] |
Python opening XML remotely for reading and parsing | 39,105,545 | <p>I am attempting to open a xml file remotely for reading and parsing but getting an error when I try to use it. When I print it also starts with some unrecognized characters. Can you please help point me in the right direction so that I can open xml file remotely and parse the data?</p>
<p>XML File:</p>
<pre><code... | 0 | 2016-08-23T15:43:47Z | 39,106,364 | <p>The first two bytes in your example file are a Unicode <a href="https://en.wikipedia.org/wiki/Byte_order_mark" rel="nofollow">Byte Order Marker</a> indicating the file is encoded as UTF-8.</p>
<p>It seems lxml trips over this. Just slice the first two bytes off, lxml will detect the correct encoding from the Doctyp... | 0 | 2016-08-23T16:26:24Z | [
"python",
"xml",
"parsing"
] |
Conda (Python) Virtual Environment is not Portable from Windows to Linux | 39,105,596 | <p>On my Windows 10 machine, I created a virtual environment using the following command:</p>
<pre><code>>conda env export > environment.yml
</code></pre>
<p>I tried re-creating the virtual environment using the yml file on the Windows system and it worked fine. Then I transferred environment.yml to my Linux m... | 1 | 2016-08-23T15:46:10Z | 39,106,886 | <p>It looks like you are fetching packages compiled with Microsoft Visual C/C++ Compiler (the <code>vc</code> part of the name).
Those packages won't be ABI compatible from Linux as you are trying to do. Simply target the packages that are not Windows-specific.</p>
| 1 | 2016-08-23T16:58:24Z | [
"python",
"linux",
"virtualenv",
"anaconda",
"conda"
] |
Simple list creation | 39,105,667 | <p>I'm new on python and I have a problem</p>
<p>I have a word and i want in return a list like that:
outlist = ["word1, word2, word3, ecc....]
this is what I tried:</p>
<pre><code>numberlist=list(range(1,1000))
numberlist=(','.join("'{0}'".format(x) for x in numberlist))
list=["word" + number for number in numberl... | 0 | 2016-08-23T15:49:46Z | 39,105,708 | <p>Your use of <code>join</code> is wrong. The simplest solution would be:</p>
<pre><code>print ["word" + str(i) for i in range(1, 1000)]
</code></pre>
<p>This gives:</p>
<pre><code>In [4]: ["word" + str(k) for k in range(5)]
Out[4]: ['word0', 'word1', 'word2', 'word3', 'word4']
</code></pre>
<p><code>join</code> i... | 4 | 2016-08-23T15:51:52Z | [
"python"
] |
Python regex finding phrases in same line | 39,105,698 | <p>I have transcripts like this:</p>
<pre class="lang-none prettyprint-override"><code>speaker1 (caller): hello.
speaker2 (agent): thank you for calling.
speaker1 (caller): I need some help with my account 3429.
speaker2 (agent): Sure let me help.
</code></pre>
<p>They are of the form 'speakerN (caller or agent)'. I... | 1 | 2016-08-23T15:51:33Z | 39,105,831 | <p>Regex only produces non-overlapping matches. So you can't have <code>speaker</code> occuring twice in your pattern. You need to put it inside a lookahead:</p>
<pre><code>speaker\d+ (\([^(]*?)(?=\s+speaker\d+|$)
</code></pre>
<p>This will capture the text in group 1.</p>
<p><a href="https://regex101.com/r/kY1bQ1/1... | 1 | 2016-08-23T15:57:36Z | [
"python",
"regex"
] |
Python regex finding phrases in same line | 39,105,698 | <p>I have transcripts like this:</p>
<pre class="lang-none prettyprint-override"><code>speaker1 (caller): hello.
speaker2 (agent): thank you for calling.
speaker1 (caller): I need some help with my account 3429.
speaker2 (agent): Sure let me help.
</code></pre>
<p>They are of the form 'speakerN (caller or agent)'. I... | 1 | 2016-08-23T15:51:33Z | 39,106,102 | <p>use <code>aList = re.findall('speaker\d+\s(.*?)(?=\sspeaker|$)', transcript)</code></p>
<p><code>.*?</code> will stop matching right away when it finds another occurrence of speaker, while <code>.*</code> will keep matching any character till the last occurrence. Hope it helps.</p>
<p>Edit: speaker\d+, . will matc... | 0 | 2016-08-23T16:11:05Z | [
"python",
"regex"
] |
understanding the size and structure of multi-dimensional array | 39,105,846 | <p>When reading an open source program, a function outputs the following multi-dimensional array. The output is referred to as <code>batch</code>. <code>print(batch)</code> generates the following output. In order to know exactly the structure of this output. I tried <code>print(batch.shape)</code>, which generates the... | 0 | 2016-08-23T15:58:10Z | 39,106,654 | <p>A tuple, like a Python list, has a <code>len</code> property</p>
<pre><code>len(batch) # probably gives 2
</code></pre>
<p>You can look at the properties of the elements of tuple with iteration</p>
<pre><code>for arr in batch:
print(arr.shape)
print(arr.dtype)
</code></pre>
<p>Or</p>
<pre><code> [arr.sh... | 0 | 2016-08-23T16:44:14Z | [
"python",
"numpy",
"scipy"
] |
Reflecting points in a bar graph using matplotlib | 39,105,884 | <p>long time lurker for programming questions, first time poster.</p>
<p>I am writing some code where I am making a bar graph of a bunch of values, some of which are negative and some of which are positive- <a href="http://i.stack.imgur.com/VaimT.png" rel="nofollow">plot here</a></p>
<p>In short, what I want to do is... | 3 | 2016-08-23T16:00:00Z | 39,106,147 | <p>As I mentioned in my comment, maybe this will clarify</p>
<pre><code>>>> x = list(range(100))
>>> x[0:30]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
>>> x[30:0]
[]
>>> x[30:0:-1]
[30, 29, 28, 27, 26, 25, 24, 23, ... | 1 | 2016-08-23T16:14:09Z | [
"python",
"matplotlib"
] |
Reflecting points in a bar graph using matplotlib | 39,105,884 | <p>long time lurker for programming questions, first time poster.</p>
<p>I am writing some code where I am making a bar graph of a bunch of values, some of which are negative and some of which are positive- <a href="http://i.stack.imgur.com/VaimT.png" rel="nofollow">plot here</a></p>
<p>In short, what I want to do is... | 3 | 2016-08-23T16:00:00Z | 39,106,665 | <p>Each time you call <code>plt.bar</code>, if your first argument is an array of length <strong>n</strong> (the set of abscissas), then your second argument must be an array of length <strong>n</strong> (the set of ordinates).</p>
<p>In your case, your set of abscissas is by construction an array of length 99, hence ... | 0 | 2016-08-23T16:44:54Z | [
"python",
"matplotlib"
] |
Python: BeautifulSoup: CSS rule to select elements only if have two classes and share the same first one | 39,105,944 | <p>i have these elements in the HTML I want to parse:</p>
<pre><code> <td class="line"> GARBAGE </td>
<td class="line text"> I WANT THAT </td>
<td class="line heading"> I WANT THAT </td>
<td class="line"> GARBAGE </td>
</code></pre>
<p>How can I make a CSS select... | 3 | 2016-08-23T16:02:55Z | 39,106,039 | <p>You can chain CSS classes for a class selector.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.line {
color: green;
}
.line.text {
color: red;
}
.line.headi... | 0 | 2016-08-23T16:08:07Z | [
"python",
"html",
"css-selectors",
"beautifulsoup"
] |
Python: BeautifulSoup: CSS rule to select elements only if have two classes and share the same first one | 39,105,944 | <p>i have these elements in the HTML I want to parse:</p>
<pre><code> <td class="line"> GARBAGE </td>
<td class="line text"> I WANT THAT </td>
<td class="line heading"> I WANT THAT </td>
<td class="line"> GARBAGE </td>
</code></pre>
<p>How can I make a CSS select... | 3 | 2016-08-23T16:02:55Z | 39,106,207 | <p>If you know all the other possible class names in advance, you can list them all. It's cumbersome, especially if you have <em>many</em> possible class names, but it's the single most reliable method.</p>
<p>Otherwise, if you can ensure that elements with only the "line" class don't have any whitespace in their clas... | 3 | 2016-08-23T16:16:44Z | [
"python",
"html",
"css-selectors",
"beautifulsoup"
] |
Python: BeautifulSoup: CSS rule to select elements only if have two classes and share the same first one | 39,105,944 | <p>i have these elements in the HTML I want to parse:</p>
<pre><code> <td class="line"> GARBAGE </td>
<td class="line text"> I WANT THAT </td>
<td class="line heading"> I WANT THAT </td>
<td class="line"> GARBAGE </td>
</code></pre>
<p>How can I make a CSS select... | 3 | 2016-08-23T16:02:55Z | 39,108,518 | <p>What <a href="http://stackoverflow.com/a/39106207/771848">@BoltClock suggested</a> is generally a correct way to approach the problem with CSS selectors. The only problem is that <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow"><code>BeautifulSoup</code> supports a <em>li... | 3 | 2016-08-23T18:40:46Z | [
"python",
"html",
"css-selectors",
"beautifulsoup"
] |
Best way to parse arguments in a REST api | 39,105,997 | <p>I am building a Rest API based on flask Restful. And I'm troubled what would be the best way to parse the arguments I am waiting for. </p>
<p>The info:</p>
<p>Table Schema: </p>
<pre><code>-----------------------------------------
| ID | NAME | IP | MAIL | OS | PASSWORD |
-----------------------------------------... | 0 | 2016-08-23T16:05:35Z | 39,107,310 | <p>It's not a good idea to let your database api catch errors. Repeated DB access will hamper performance.</p>
<p>Best case scenario, if you can error check the json at the client, do it.
Error check a json in python anyhow. You must always assume that the network
is compromised and you will get garbage values/ malici... | 0 | 2016-08-23T17:23:28Z | [
"python",
"rest",
"flask-restful"
] |
Best way to parse arguments in a REST api | 39,105,997 | <p>I am building a Rest API based on flask Restful. And I'm troubled what would be the best way to parse the arguments I am waiting for. </p>
<p>The info:</p>
<p>Table Schema: </p>
<pre><code>-----------------------------------------
| ID | NAME | IP | MAIL | OS | PASSWORD |
-----------------------------------------... | 0 | 2016-08-23T16:05:35Z | 39,902,270 | <p>Why you don't consider to use a library like <a href="http://marshmallow.readthedocs.io/en/latest/" rel="nofollow">marchmallow</a> since the flask-restful documentation suggest it? It will answer your problems in a proper and non custom why like if you would right the validation from scratch.</p>
| 1 | 2016-10-06T17:30:33Z | [
"python",
"rest",
"flask-restful"
] |
Capture output from external command and write it to a file | 39,106,032 | <p>I am trying to create a script that calls on a linux command from my Ubuntu server and prints the output of aforementioned command to txt files. This is literally the first script I've ever written, I just started learning python recently. I want 3 files in 3 separate folders with filenames unique to date.</p>
<p... | -3 | 2016-08-23T16:07:37Z | 39,106,185 | <p>You can do this instead:</p>
<pre><code>import time
import subprocess as sp
timestr = time.strftime("%Y%m%d")
fs = "/path/1/" + timestr
ft = "/path/2/" + timestr
fc = "/path/3/" + timestr
f1 = open(fs + '.txt', 'w')
rc = sp.call("svn info svn://url", stdout=f1, stderr=sp.STDOUT)
f1.close()
f2 = open(ft + '.txt'... | 0 | 2016-08-23T16:15:47Z | [
"python",
"linux",
"ubuntu",
"svn",
"scripting"
] |
Capture output from external command and write it to a file | 39,106,032 | <p>I am trying to create a script that calls on a linux command from my Ubuntu server and prints the output of aforementioned command to txt files. This is literally the first script I've ever written, I just started learning python recently. I want 3 files in 3 separate folders with filenames unique to date.</p>
<p... | -3 | 2016-08-23T16:07:37Z | 39,109,668 | <p>I figured it out after all. The following works great!</p>
<pre><code>## This will get the last revision number overall in repository ##
import os
sfo = os.popen("svn info svn://url1 | grep Revision")
sfo_output = sfo.read()
tco = os.popen("svn info svn://url2 | grep Revision")
tco_output = tco.read()
fco = os.po... | 0 | 2016-08-23T19:56:10Z | [
"python",
"linux",
"ubuntu",
"svn",
"scripting"
] |
Integer list to ranges | 39,106,236 | <p>I need to convert a list of ints to a string containing all the ranges in the list.
So for example, the output should be as follows:</p>
<pre><code>getIntRangesFromList([1,3,7,2,11,8,9,11,12,15]) -> "1-3,7-9,11-12,15"
</code></pre>
<p>So the input is not sorted and there can be duplicate values. The lists range... | 2 | 2016-08-23T16:18:43Z | 39,106,411 | <p>This could be a task for the <a href="https://docs.python.org/3/library/itertools.html" rel="nofollow"><code>itertools</code></a> module.</p>
<pre><code>import itertools
list_num = [1, 2, 3, 7, 8, 9, 11, 12, 15]
groups = (list(x) for _, x in
itertools.groupby(list_num, lambda x, c=itertools.count(): x - ... | 1 | 2016-08-23T16:29:18Z | [
"python",
"algorithm",
"python-2.7"
] |
Integer list to ranges | 39,106,236 | <p>I need to convert a list of ints to a string containing all the ranges in the list.
So for example, the output should be as follows:</p>
<pre><code>getIntRangesFromList([1,3,7,2,11,8,9,11,12,15]) -> "1-3,7-9,11-12,15"
</code></pre>
<p>So the input is not sorted and there can be duplicate values. The lists range... | 2 | 2016-08-23T16:18:43Z | 39,107,192 | <pre><code>def _to_range(l, start, stop, idx, result):
if idx == len(l):
result.append((start, stop))
return result
if l[idx] - stop > 1:
result.append((start, stop))
return _to_range(l, l[idx], l[idx], idx + 1, result)
return _to_range(l, start, l[idx], idx + 1, result)
... | 0 | 2016-08-23T17:16:12Z | [
"python",
"algorithm",
"python-2.7"
] |
Integer list to ranges | 39,106,236 | <p>I need to convert a list of ints to a string containing all the ranges in the list.
So for example, the output should be as follows:</p>
<pre><code>getIntRangesFromList([1,3,7,2,11,8,9,11,12,15]) -> "1-3,7-9,11-12,15"
</code></pre>
<p>So the input is not sorted and there can be duplicate values. The lists range... | 2 | 2016-08-23T16:18:43Z | 39,108,612 | <p>I'll concentrate in performance that is your main issue. I'll give 2 solutions:</p>
<p>1) If the boundaries of the integers stored is between A and B, and you can create an array of booleans(even you can choose an array of bits for expand de range you can storage) with (B - A + 2) elements, e.g. A = 0 and B = 1 000... | 0 | 2016-08-23T18:47:01Z | [
"python",
"algorithm",
"python-2.7"
] |
Integer list to ranges | 39,106,236 | <p>I need to convert a list of ints to a string containing all the ranges in the list.
So for example, the output should be as follows:</p>
<pre><code>getIntRangesFromList([1,3,7,2,11,8,9,11,12,15]) -> "1-3,7-9,11-12,15"
</code></pre>
<p>So the input is not sorted and there can be duplicate values. The lists range... | 2 | 2016-08-23T16:18:43Z | 39,110,382 | <p>The fastest one I could come up, which tests about 10% faster than your solution on my machine (according to timeit):</p>
<pre><code>def _ranges(l):
if l:
l.sort()
return ''.join([(str(l[i]) + ('-' if l[i] + 1 == l[i + 1] else ','))
for i in range(0, len(l) - 1) if l[i - 1] + 2 != l[i... | 0 | 2016-08-23T20:47:04Z | [
"python",
"algorithm",
"python-2.7"
] |
Python Numpy - attach three arrays to form a matrix or 3D array | 39,106,248 | <p>This is my simple of piece of code</p>
<p>Everything is a numpy array. I welcome manipulation using lists too.</p>
<pre><code>a = [1,2,3,4,5]
b = [3,2,2,2,8]
c = ['test1', 'test2', 'test3','test4','test5']
</code></pre>
<p>expected Outcome: </p>
<pre><code>d = [ 1, 2, 3, 4, 5;
3, 2, 2, 2, 8;
'test1... | 1 | 2016-08-23T16:19:15Z | 39,106,280 | <p>Check out the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow">concat method.</a></p>
<pre><code>>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
[3, 4],
[5, 6]]... | 0 | 2016-08-23T16:21:20Z | [
"python",
"arrays",
"numpy"
] |
Python Numpy - attach three arrays to form a matrix or 3D array | 39,106,248 | <p>This is my simple of piece of code</p>
<p>Everything is a numpy array. I welcome manipulation using lists too.</p>
<pre><code>a = [1,2,3,4,5]
b = [3,2,2,2,8]
c = ['test1', 'test2', 'test3','test4','test5']
</code></pre>
<p>expected Outcome: </p>
<pre><code>d = [ 1, 2, 3, 4, 5;
3, 2, 2, 2, 8;
'test1... | 1 | 2016-08-23T16:19:15Z | 39,106,416 | <p>Adam's <a href="http://stackoverflow.com/q/39106248/6748857">answer</a> using <code>numpy.concat</code> is also correct, but in terms of specifying the exact shape you are expecting â rows stacked vertically â you'll want to look at <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html" ... | 0 | 2016-08-23T16:29:31Z | [
"python",
"arrays",
"numpy"
] |
Python Numpy - attach three arrays to form a matrix or 3D array | 39,106,248 | <p>This is my simple of piece of code</p>
<p>Everything is a numpy array. I welcome manipulation using lists too.</p>
<pre><code>a = [1,2,3,4,5]
b = [3,2,2,2,8]
c = ['test1', 'test2', 'test3','test4','test5']
</code></pre>
<p>expected Outcome: </p>
<pre><code>d = [ 1, 2, 3, 4, 5;
3, 2, 2, 2, 8;
'test1... | 1 | 2016-08-23T16:19:15Z | 39,106,501 | <p>Your <code>a</code>,<code>b</code>,<code>c</code> are lists; you'd have to use <code>np.array([1,2,3])</code> to get an array, and it will display as <code>[1 2 3]</code> (without the commas).</p>
<p>Simply creating a new list from those lists produces a list of lists</p>
<pre><code>In [565]: d=[a,b,c]
In [566]: d... | 0 | 2016-08-23T16:34:23Z | [
"python",
"arrays",
"numpy"
] |
Cassandra model paging with REST API | 39,106,256 | <p>I have model as.</p>
<pre><code># File: models.py
from uuid import uuid4
from cassandra.cqlengine.models import Model
from cassandra.cqlengine import columns
class StudentModel(Model):
__table_name__ = 'students'
id = columns.UUID(primary_key=True, default=uuid4)
name = columns.Text(index=True, requi... | 0 | 2016-08-23T16:19:32Z | 39,110,483 | <p>Currently, there is no efficient way to do pagination with CQLEngine. Using QuerySet slicing works, but be aware that previous pages will still be materialized internally in the result cache. So, this can lead to memory issues and it also affect the request performance. I've created a ticket to analyze a way to fill... | 2 | 2016-08-23T20:52:59Z | [
"python",
"api",
"model",
"cassandra"
] |
Not all objects transferring from one list to another in beginner grid-based game | 39,106,339 | <p>This has been driving me nuts.</p>
<p>I'm developing a grid-based movement engine for a game. Character instances move around using the "move" function, which reduces their internal moves_left variable by 1 every time. </p>
<pre><code>def move(self, direction): #how characters move around
if self.coll... | 0 | 2016-08-23T16:24:46Z | 39,106,445 | <p>You shouldnât iterate over an array youâre mutating, which is causing this problem. Instead:</p>
<pre><code>arr = Map.no_moves[:] # copy
for item in arr:
if item.moves_left == 0:
Map.no_moves.remove(item)
Map.can_move.append(item)
</code></pre>
<hr>
<p>Note that this concept applies to alm... | 2 | 2016-08-23T16:30:48Z | [
"python",
"arrays",
"python-3.x",
"oop",
"pygame"
] |
How convert list element to list? | 39,106,363 | <p>Original cat looks like this:</p>
<pre><code>cat = ['a','a,b,c','c,d,e,f']
</code></pre>
<p>I want to convert it to:</p>
<pre><code>cat = [['a'],['a','b','c'],['c','d','e','f']]
</code></pre>
| 2 | 2016-08-23T16:26:21Z | 39,106,407 | <p>You just need to <a href="https://docs.python.org/3/library/stdtypes.html#str.split" rel="nofollow">split</a> each string:</p>
<pre><code>result = [s.split(',') for s in cat]
</code></pre>
| 2 | 2016-08-23T16:29:15Z | [
"python",
"string",
"list",
"python-3.x"
] |
How convert list element to list? | 39,106,363 | <p>Original cat looks like this:</p>
<pre><code>cat = ['a','a,b,c','c,d,e,f']
</code></pre>
<p>I want to convert it to:</p>
<pre><code>cat = [['a'],['a','b','c'],['c','d','e','f']]
</code></pre>
| 2 | 2016-08-23T16:26:21Z | 39,106,424 | <p>Try This:</p>
<pre><code>cat = ['a','a,b,c','c,d,e,f']
newlist = [a.split(',') for a in cat]
print(newlist)
>>> [['a'], ['a', 'b', 'c'], ['c', 'd', 'e', 'f']]
</code></pre>
| 1 | 2016-08-23T16:29:49Z | [
"python",
"string",
"list",
"python-3.x"
] |
How convert list element to list? | 39,106,363 | <p>Original cat looks like this:</p>
<pre><code>cat = ['a','a,b,c','c,d,e,f']
</code></pre>
<p>I want to convert it to:</p>
<pre><code>cat = [['a'],['a','b','c'],['c','d','e','f']]
</code></pre>
| 2 | 2016-08-23T16:26:21Z | 39,106,434 | <p>You can achieve this by <code>list comprehension</code> as:</p>
<pre><code>>>> cat = ['a','a,b,c','c,d,e,f']
>>> [c.split(',') for c in cat]
[['a'], ['a', 'b', 'c'], ['c', 'd', 'e', 'f']]
</code></pre>
<p><strong>Alternatively</strong>, you may also use <code>lambda</code> function with <code>map... | 4 | 2016-08-23T16:30:28Z | [
"python",
"string",
"list",
"python-3.x"
] |
converting simple SOAP client code from php to python | 39,106,428 | <p>so here is my php code </p>
<pre><code> $client = new SoapClient('https://someservice.com/Tokens.xml', array('soap_version' => SOAP_1_1));
$params['merchantId'] = 'ABC';
$params['invoiceNo'] = 1;
$result = $client->__soapCall("MakeToken", array($params));
$token = $result->MakeTokenRe... | 1 | 2016-08-23T16:30:05Z | 39,117,425 | <p>Assuming <code>MakeToken</code> is the name of the method provided by the service, you need to call <code>client.service.MakeToken(merchantId='ABC', invoiceNo=1)</code></p>
<p>Have a look at the documentation at <a href="https://fedorahosted.org/suds/wiki/Documentation" rel="nofollow">https://fedorahosted.org/suds/... | 0 | 2016-08-24T07:51:17Z | [
"python",
"django",
"soap"
] |
Changing tag in a HTML when parsed with Beautifulsoup | 39,106,482 | <p>I'm trying to crawl a <a href="http://www.allocine.fr/film/fichefilm_gen_cfilm=144185.html" rel="nofollow">webpage</a> using beautiful soup but I got a problem with a tag that is mysteriously changing from what is displayed in my browser and what I receive in my terminal.
<a href="http://i.stack.imgur.com/Px4qZ.png"... | 2 | 2016-08-23T16:33:20Z | 39,111,521 | <p>There are a few of issues, some tags are created using <em>Javascript</em>, there are actually two tags that have a <em>title="Bandes-annonces"</em>, what you see in your output is the first occurrence with obfuscated data which is <em>base-64</em> encoded with substring(s) embedded, you can see in one of the Js fun... | 2 | 2016-08-23T22:16:19Z | [
"python",
"html",
"python-2.7",
"beautifulsoup",
"web-crawler"
] |
Create a queryset to compare two models | 39,106,528 | <p>I'm just new using Django. I just created my models and migrate information to my sqlite3 database using the .cvs import module. This are my modules:</p>
<pre><code>class Backlog(models.Model):
sales_order = models.CharField(max_length=30)
po_number = models.CharField(max_length=30)
order_number = model... | 0 | 2016-08-23T16:35:56Z | 39,109,169 | <p>Ok well given your current models, here is a possible solution to the problem you are having:</p>
<pre><code>for backlog in Backlog.objects.all():
try:
material = Material.objects.get(product_id = backlog.product_id)
if material.tan_id[0:2] == '74':
# Classify as 1
elif mater... | 1 | 2016-08-23T19:21:49Z | [
"python",
"django",
"django-models",
"django-views"
] |
Inserting object in excel using Python | 39,106,532 | <p>I want to insert a Image(object) in MS-Excel Report which i am generating using openpyxl utility. Is there a way to do it using some python utility?</p>
| 0 | 2016-08-23T16:36:20Z | 39,106,569 | <p>Openpyxl allows you to write images into your Excel files! Here it is in the <a href="http://openpyxl.readthedocs.io/en/2.4/api/openpyxl.drawing.image.html" rel="nofollow">official documentation</a>.</p>
<pre><code>import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
picture = openpyxl.drawing.Image('/p... | 3 | 2016-08-23T16:38:34Z | [
"python",
"pywin32",
"openpyxl",
"win32com",
"xlwt"
] |
Pandas: change values in column | 39,106,660 | <p>I have dataframe </p>
<pre><code>ID RuCitySize qsex age ranges url used_at active_seconds
f78f67101c3aeb099212b8aa9a95dfd2 500-млн ÐенÑкий 18-24 lada.ru 03.01.2016 20:18 66.25557348
f78f67101c3aeb099212b8aa9a95dfd2 500-млн ÐенÑкий 18-24 lada.ru/cars/vesta/sedan/tth.html 03.0... | 0 | 2016-08-23T16:44:29Z | 39,108,595 | <p>you can do it this way:</p>
<pre><code>In [33]: df1['new'] = (df1['active_seconds'] *
....: pd.merge(df1, df2,
....: on=['qsex', 'age ranges', 'RuCitySize'],
....: how='left')['FOM_quota'])
In [34]: df1[['active_seconds','new']]
Out[34]:
activ... | 1 | 2016-08-23T18:46:22Z | [
"python",
"pandas"
] |
Weird output when calculating fractions of a square root | 39,106,666 | <p>I'm trying to find the continued fractions of any non-square number (until it repeats).</p>
<p>For example: input: <code>23 = [4; 1,3,1,8]</code></p>
<p>my code works for many numbers (even though it's very clumsy).
It works for 23 where it outputs: </p>
<pre><code>[4, 1, 3, 1, 8, 1, 3, 1]
</code></pre>
<p>(Igno... | 0 | 2016-08-23T16:44:56Z | 39,109,577 | <p>What you have is a precision error. These calculations are extremely precise, meaning they require many binary digits to represent. The finite floating point precision that your computer uses is sometimes not enough to do this accurately. Somewhere along the line, the behavior of how this inaccuracy is handled in... | 0 | 2016-08-23T19:50:51Z | [
"python",
"python-3.x",
"math",
"output"
] |
Rows are still present after calling delete() in SQLAlchemy | 39,106,687 | <p>I want to have a Flask route that deletes all instances of a SQLAlchemy model, <code>VisitLog</code>. I call <code>VisitLog.query.delete()</code>, then redirect back to the page, but the old entries are still present. There was no error. Why weren't they deleted?</p>
<pre><code>@app.route('/log')
def log():
... | 3 | 2016-08-23T16:46:01Z | 39,106,794 | <p>Just like other write operations, you must commit the session after executing a bulk delete.</p>
<pre><code>VisitLog.query.delete()
db.session.commit()
</code></pre>
| 2 | 2016-08-23T16:53:02Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] |
how to merge two dataframes if the index and length both do not match? | 39,106,717 | <p>i have two data frames predictor_df and solution_df like this :</p>
<pre><code>predictor_df
</code></pre>
<p>1000 A B C
1001 1 2 3
1002 4 5 6
1003 7 8 9
1004 Nan Nan Nan</p>
<pre><code>and a solution_df
</code></pre>
<p>0 D
1 10
2 11
... | 0 | 2016-08-23T16:48:12Z | 39,107,890 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> with <code>drop=True</code> which resets the index to the default integer index.</p>
<pre><code>pd.concat([df_1.reset_index(drop=True), df_2.reset_index(drop=Tr... | 1 | 2016-08-23T18:00:13Z | [
"python",
"pandas"
] |
How can I "fix" floating numbers in python by intelligently choosing the correct decimal place to round to? | 39,106,733 | <p>I've seen many discussions here about rounding floating values in python or similar topics, but I have a related problem that I want a good solution for.</p>
<p>Context:</p>
<p>I use the netCDF4 python library to extract data from NetCDF files. My organization keeps a precision attribute on variables within these ... | 1 | 2016-08-23T16:48:59Z | 39,107,265 | <p>For rounding the values to <code>float</code> with 2 decimal precision, you may use below code:</p>
<pre><code>>>> x = [0.0099999, 0.00000999, 0.99999]
>>> ['%.2f' % i for i in x]
['0.01', '0.00', '1.00']
</code></pre>
<p>OR, you may use <code>format</code> as:</p>
<pre><code>>>> ["{0:.... | 0 | 2016-08-23T17:20:59Z | [
"python"
] |
How can I "fix" floating numbers in python by intelligently choosing the correct decimal place to round to? | 39,106,733 | <p>I've seen many discussions here about rounding floating values in python or similar topics, but I have a related problem that I want a good solution for.</p>
<p>Context:</p>
<p>I use the netCDF4 python library to extract data from NetCDF files. My organization keeps a precision attribute on variables within these ... | 1 | 2016-08-23T16:48:59Z | 39,109,875 | <p>Thanks to Benjamin for linking another post in the comments above to the solution I was looking for. A better way to word my question is that I want to operate on float values such that only 1 significant digit is retained.</p>
<p>Simple examples:</p>
<pre><code>0.00999 -> 0.01
0.09998 -> 0.1
0.00099 ->... | 1 | 2016-08-23T20:09:49Z | [
"python"
] |
"AS" syntax in sqlite throwing error in python | 39,106,825 | <p>I am trying to query based on distance in an sqlite database using some math. Accuracy of the results isn't that important, so I have the following:</p>
<pre><code>SELECT * AS distance FROM items ORDER BY ((location_lat-lat)*(location_lat-lat)) + ((location_lng - lng)*(location_lng - lng)) ASC
</code></pre>
<p>I t... | -1 | 2016-08-23T16:55:16Z | 39,106,862 | <p>Because your <code>SQL</code> syntax is wrong. Use instead:</p>
<pre><code>SELECT * FROM items ORDER BY ((location_lat-lat)*(location_lat-lat)) + ((location_lng - lng)*(location_lng - lng)) ASC
</code></pre>
<p><strong>Explanation:</strong> Since <code>*</code> returns all the columns within your table and <code>A... | 0 | 2016-08-23T16:57:26Z | [
"python",
"python-2.7",
"sqlite",
"sqlite3",
"coordinates"
] |
Express time elapsed between element of an array of date in hour min second using python | 39,106,832 | <p>I have a list of time creation of files obtained using os.path.getmtime</p>
<pre><code>time_creation_sorted
Out[45]:
array([ 1.47133334e+09, 1.47133437e+09, 1.47133494e+09,
1.47133520e+09, 1.47133577e+09, 1.47133615e+09,
1.47133617e+09, 1.47133625e+09, 1.47133647e+09])
</code></pre>
... | 1 | 2016-08-23T16:55:49Z | 39,107,151 | <p>Check out timedelta objects, it gives difference between two dates or times</p>
<p><a href="https://docs.python.org/2/library/datetime.html#timedelta-objects" rel="nofollow">https://docs.python.org/2/library/datetime.html#timedelta-objects</a></p>
| 0 | 2016-08-23T17:13:30Z | [
"python",
"datetime",
"time",
"difference"
] |
Express time elapsed between element of an array of date in hour min second using python | 39,106,832 | <p>I have a list of time creation of files obtained using os.path.getmtime</p>
<pre><code>time_creation_sorted
Out[45]:
array([ 1.47133334e+09, 1.47133437e+09, 1.47133494e+09,
1.47133520e+09, 1.47133577e+09, 1.47133615e+09,
1.47133617e+09, 1.47133625e+09, 1.47133647e+09])
</code></pre>
... | 1 | 2016-08-23T16:55:49Z | 39,107,175 | <p>You need to rearrange some parts of your code in order to get the desired output.</p>
<p>First you should convert the time stamps to <code>datetime</code> objects which differences result into so called <code>timedelta</code> objects. The <code>__str__()</code> representation of those <code>timedelta</code> objects... | 2 | 2016-08-23T17:15:02Z | [
"python",
"datetime",
"time",
"difference"
] |
How can I display argparse help information for parameters in argument subgroups? | 39,106,834 | <p><strong>I'm putting together an <code>argparse</code> parser where I want to have multiple levels of sub-grouping:</strong></p>
<pre><code>Parser
|
|- Option A
|- Option B
|- Group 1
| |- Option 1.A
| |- Subgroup 1.2
| |- Mutually-Exclusive Group 1.2.1
| | |- MEG Option 1.2.1.A
| | |- MEG Option 1.2... | 0 | 2016-08-23T16:56:01Z | 39,107,208 | <p>We've discussed this in other SO questions, but the simple answer is that <code>argument groups</code> do not nest. <code>mutually exclusive groups</code> can nest in an argument group for display purposes, but they don't nest for parsing or testing</p>
<p>Argument groups only affect the help display. Actions add... | 1 | 2016-08-23T17:17:28Z | [
"python",
"python-3.x",
"argparse"
] |
Microsoft Emotion API can i use it to create application for pc in visual studio with python? | 39,106,903 | <p>I'm trying to build an app with microsoft-cognitive emotion API, as python is my preferred programming language just wanted to know if this could be done in visual studio would love to learn more about it. </p>
| -2 | 2016-08-23T16:59:13Z | 39,150,315 | <p>There is python code available on GitHub that demonstrates calling the Emotion API: <a href="https://github.com/Microsoft/Cognitive-Emotion-Python" rel="nofollow">https://github.com/Microsoft/Cognitive-Emotion-Python</a>. It comes in the form of a Jupyter notebook, but it should be a good place to get started noneth... | 1 | 2016-08-25T16:23:52Z | [
"python",
"microsoft-cognitive"
] |
Parsing txt file into csv | 39,107,103 | <p>i need to parse some .txt file into .csv!
Let's begin... Text file looks like that:</p>
<blockquote>
<p>COMPACT3</p>
<p>GPS_START_TIME 2010 4 15 00 00 0.0000</p>
<p>0.0000 10 G16 G02 G29 G31 G30 G12 G10 G21 G05 G24</p>
<p>0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000... | -4 | 2016-08-23T17:10:38Z | 39,107,366 | <p>you'll find how to read and write files here :</p>
<p>for python2.7 : <a href="https://docs.python.org/2/tutorial/inputoutput.html" rel="nofollow">https://docs.python.org/2/tutorial/inputoutput.html</a></p>
<p>for python3 : <a href="https://docs.python.org/3/tutorial/inputoutput.html" rel="nofollow">https://docs.p... | 0 | 2016-08-23T17:26:49Z | [
"python",
"csv",
"parsing"
] |
Is a python dict's len() atomic with respect to the GIL? | 39,107,220 | <p>I'm asking about CPython, python2.7. Say I have a <code>dict</code>, and a few threads that will insert values from time to time by calling <code>add()</code>:</p>
<pre><code>d = {}
dlock = threading.Lock()
def add(key, value):
with dlock:
d[key] = value
</code></pre>
<p>Is it safe to get the size of t... | 4 | 2016-08-23T17:17:54Z | 39,107,346 | <p>I wouldn't recommend it, but yeah, the GIL will protect that. There's no opportunity for the GIL to be released during the <code>len</code> call.</p>
| 1 | 2016-08-23T17:25:18Z | [
"python",
"python-2.7",
"cpython"
] |
Python tkinter lisbox bold | 39,107,336 | <p>I am trying to bold all of the entries for my python tkinter listbox.</p>
<p>I have a list and it enters it into a listbox:</p>
<p><code>listbox4.insert(END, Words)</code>
Does anyone know the code to bold these entries?</p>
| 1 | 2016-08-23T17:24:50Z | 39,107,472 | <pre><code>from Tkinter import *
import tkFont
sf= tkFont.Font(family='Helvetica', size=36, weight='bold')
lb = Listbox(root , bd=1, height=10, font=sf)
</code></pre>
| 1 | 2016-08-23T17:32:53Z | [
"python",
"user-interface",
"tkinter"
] |
Python tkinter lisbox bold | 39,107,336 | <p>I am trying to bold all of the entries for my python tkinter listbox.</p>
<p>I have a list and it enters it into a listbox:</p>
<p><code>listbox4.insert(END, Words)</code>
Does anyone know the code to bold these entries?</p>
| 1 | 2016-08-23T17:24:50Z | 39,107,536 | <p>you can configure the Font used by the listbox object for all of the text</p>
<p>assuming you are using python 3 and tkinter the code would be like follows (replace the import line with <code>import tkFont</code> on python 2)</p>
<pre><code>from tkinter import font
listbox4.insert(END, Words)
bolded = font.Font(w... | 1 | 2016-08-23T17:36:56Z | [
"python",
"user-interface",
"tkinter"
] |
Flanker: MimePart is not iterable | 39,107,435 | <p>I'm a noob and using Flanker to parse emails.
<a href="https://github.com/mailgun/flanker" rel="nofollow">https://github.com/mailgun/flanker</a></p>
<p>I'm getting a Not Iterable error that I just can't seem to figure out. I've read tons of pages about lists, but I just can't get it to work. I'm hopeful I can get... | 0 | 2016-08-23T17:31:05Z | 39,107,507 | <p><code>attachmenttype</code> may be printed a string but it is not a string,more a structure containing some properties. However, since you can print it, you're halfway there. Just convert it to a string using <code>str</code> and compare that.</p>
<p>Fix your code like this. I couldn't test it but I don't see how i... | 1 | 2016-08-23T17:34:58Z | [
"python",
"email",
"parsing"
] |
How to do a transpose a dataframe group by key on pandas? | 39,107,512 | <p>I have this table from my database and I need a transpose group by survey_id</p>
<pre><code>id answer survey_id question_number questionid
216 0.0 69 3 2.0
217 3.0 69 4 3.0
218 0.0 69 5 4.0
219 0.... | -3 | 2016-08-23T17:35:29Z | 39,108,054 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add_prefix.html" rel="nofollow"><code>add_prefix</code></a> and <a href="http://pandas.pydata.... | 1 | 2016-08-23T18:11:12Z | [
"python",
"pandas",
"dataframe",
"analytics"
] |
python + arduino controlling DC Motor | 39,107,576 | <p>Hi This is my Arduino code, since I want the loop only once, I used the while(1) {} construct in the void loop() </p>
<pre><code>int motorPin = 3;
int motorDir = 12;
int motorBr = 9;
void setup() {
//pinMode(motorPin, OUTPUT);
pinMode(motorBr, OUTPUT);
pinMode(motorDir, OUTPUT);
if (Serial.available() &g... | 0 | 2016-08-23T17:39:31Z | 39,108,105 | <p>try this :</p>
<pre><code>import serial
import time
ser = serial.Serial('COM3', 9600, timeout=1) #here you may add write_timeout=1 to avoid indefinite blocking on failing flush
time.sleep(2)
ser.write('1')
ser.flush() #force the physical write
#time.sleep(2) #no need to sleep as flush was blocking
ser.close()
... | 0 | 2016-08-23T18:14:54Z | [
"python",
"arduino",
"serial-port"
] |
python + arduino controlling DC Motor | 39,107,576 | <p>Hi This is my Arduino code, since I want the loop only once, I used the while(1) {} construct in the void loop() </p>
<pre><code>int motorPin = 3;
int motorDir = 12;
int motorBr = 9;
void setup() {
//pinMode(motorPin, OUTPUT);
pinMode(motorBr, OUTPUT);
pinMode(motorDir, OUTPUT);
if (Serial.available() &g... | 0 | 2016-08-23T17:39:31Z | 39,108,187 | <p>Your Python code is sending the string '1', but your arduino code is looking for the number 1. Try changing the arduino code to this</p>
<pre><code>Serial.read() == 0x31
</code></pre>
<p>and</p>
<pre><code>Serial.read() == 0x30
</code></pre>
<p>Those are the ASCII codes for the '1' and '0' respectively</p>
<p>... | 0 | 2016-08-23T18:20:15Z | [
"python",
"arduino",
"serial-port"
] |
add new columns with conditions to a dataframe using python | 39,107,610 | <p>I create a dataframe df_energy :</p>
<pre><code>df_energy=pd.read_csv('C:/Users/Demonstrator/Downloads/power.csv', delimiter=';', parse_dates=[0], infer_datetime_format = True)
</code></pre>
<p>with this structure : </p>
<pre><code> df_energy.info()
</code></pre>
<blockquote>
<pre><code><class 'pandas.core.fr... | 0 | 2016-08-23T17:41:17Z | 39,108,161 | <p>you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">np.where</a> from <a href="http://www.numpy.org/" rel="nofollow">numpy</a> as:<br>
Sample df:</p>
<pre><code>Out[71]:
TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR SITE \
0 2015-07-31 23:00:... | 3 | 2016-08-23T18:18:57Z | [
"python",
"pandas",
"dataframe"
] |
unicodecsv doesn't read unicode csv file | 39,107,654 | <p>This is the line I'm trying to read:</p>
<pre><code>with open('u.item', 'w') as demofile:
demofile.write(
"543|Mis\xe9rables, Les (1995)|01-Jan-1995||"
"http://us.imdb.com/M/title-exact?Mis%E9rables%2C%20Les%20%281995%29|
"0|0|0|0|0|0|0|0|1|0|0|0|1|0|0|0|0|0|0\n"
)
</code></pre>
<p>... | -2 | 2016-08-23T17:43:58Z | 39,107,801 | <p>I found the problem</p>
<p>the file is encoded latin-1 not utf 8</p>
<p>this solves the problem</p>
<pre><code>reader = csv.reader(csvFile, encoding='latin-1', delimiter= '|')
</code></pre>
| 1 | 2016-08-23T17:53:53Z | [
"python",
"python-2.7",
"unicode"
] |
Random Http error while using Youtube api to get comments through python | 39,107,772 | <p>on a random basis getting random Http errors while trying to get comments from predefined videos with YouTube API v3 on python. The case: giving list of video ids and comments are downloaded for each one until python throws error, and process stops. If i reload program it might stuck on the same or on another video ... | 0 | 2016-08-23T17:51:47Z | 39,146,984 | <p>Silly mistake was made. Instead of API used error identifier in 'exception'</p>
<pre><code>...
except HttpError, err:
...
</code></pre>
<p>Urlib2 one was used</p>
<pre><code>...
except urllib2.HTTPError, err:
...
</code></pre>
<p>The simple solution was just to ignore and repeat until success. However, still not... | 0 | 2016-08-25T13:41:40Z | [
"python",
"http-error",
"youtube-v3-api"
] |
Flower doesn't display all workers for celery | 39,107,835 | <p>I am running celery on two servers with one redis as a broker.</p>
<p>Celery start command looks like following:</p>
<pre><code>celery multi start 2 -A app_name
</code></pre>
<p>Flower start command:</p>
<pre><code>celery flower -A app_name --address=10.41.31.210 --port=5555
</code></pre>
<p>In flower's output ... | 0 | 2016-08-23T17:56:10Z | 39,107,887 | <p>You have to also pass <code>--basic_auth=<username>:<password></code> param while starting flower. Here <code>username</code> and <code>password</code> are of rabbitMQ user.</p>
<p>In case you do not have user, you may create it via:</p>
<pre><code>sudo rabbitmqctl add_user <username> <passwor... | 0 | 2016-08-23T18:00:09Z | [
"python",
"celery",
"flower"
] |
Efficiently finding the closest coordinate pair from a set in Python | 39,107,896 | <p><strong>The Problem</strong></p>
<p>Imagine I am stood in an airport. Given a geographic coordinate pair, how can one efficiently determine which airport I am stood in?</p>
<p><strong>Inputs</strong></p>
<ul>
<li>A coordinate pair <code>(x,y)</code> representing the location I am stood at.</li>
<li>A set of coord... | 2 | 2016-08-23T18:00:36Z | 39,107,994 | <p>From this <a href="http://codereview.stackexchange.com/questions/28207/finding-the-closest-point-to-a-list-of-points">SO question</a>:</p>
<pre><code>import numpy as np
def closest_node(node, nodes):
nodes = np.asarray(nodes)
deltas = nodes - node
dist_2 = np.einsum('ij,ij->i', deltas, deltas)
re... | 1 | 2016-08-23T18:07:32Z | [
"python",
"coordinates",
"distance",
"closest"
] |
Efficiently finding the closest coordinate pair from a set in Python | 39,107,896 | <p><strong>The Problem</strong></p>
<p>Imagine I am stood in an airport. Given a geographic coordinate pair, how can one efficiently determine which airport I am stood in?</p>
<p><strong>Inputs</strong></p>
<ul>
<li>A coordinate pair <code>(x,y)</code> representing the location I am stood at.</li>
<li>A set of coord... | 2 | 2016-08-23T18:00:36Z | 39,108,426 | <p>If your coordinates are unsorted, your search can only be improved slightly assuming it is <code>(latitude,longitude)</code> by filtering on latitude first as for earth</p>
<blockquote>
<p>1 degree of latitude on the sphere is 111.2 km or 69 miles</p>
</blockquote>
<p>but that would not give a huge speedup.</p>
... | 1 | 2016-08-23T18:35:26Z | [
"python",
"coordinates",
"distance",
"closest"
] |
Efficiently finding the closest coordinate pair from a set in Python | 39,107,896 | <p><strong>The Problem</strong></p>
<p>Imagine I am stood in an airport. Given a geographic coordinate pair, how can one efficiently determine which airport I am stood in?</p>
<p><strong>Inputs</strong></p>
<ul>
<li>A coordinate pair <code>(x,y)</code> representing the location I am stood at.</li>
<li>A set of coord... | 2 | 2016-08-23T18:00:36Z | 39,109,296 | <pre><code>>>> from scipy import spatial
>>> airports = [(10,10),(20,20),(30,30),(40,40)]
>>> tree = spatial.KDTree(airports)
>>> tree.query([(21,21)])
(array([ 1.41421356]), array([1]))
</code></pre>
<p>Where 1.41421356 is the distance between the queried point and the nearest neig... | 1 | 2016-08-23T19:31:04Z | [
"python",
"coordinates",
"distance",
"closest"
] |
Stack columns above value labels in pandas pivot table | 39,107,997 | <p>Given a dataframe that looks like:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({
'Key1': ['one', 'one', 'two', 'three'] * 3,
'Key2': ['A', 'B', 'C'] * 4,
'Value1': np.random.randn(12),
'Value2': np.random.randn(12)
... | 2 | 2016-08-23T18:07:41Z | 39,108,110 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.swaplevel.html" rel="nofollow"><code>MultiIndex.swaplevel</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a>:</p>
<pre>... | 4 | 2016-08-23T18:15:09Z | [
"python",
"pandas"
] |
Python FuncAnimation not recognizing update | 39,108,035 | <p>I'm learning how to animate in python for one of my projects and I'm basing my code off of the following example from <a href="http://eli.thegreenplace.net/2016/drawing-animated-gifs-with-matplotlib" rel="nofollow">here</a>.</p>
<p>My adaption of their code goes as follows:</p>
<pre><code>import numpy as np
import... | 0 | 2016-08-23T18:09:52Z | 39,113,212 | <pre><code>import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def update(i, ln):
i = i+1
x = i
y = i ** 2
x_data = ln.get_xdata()
y_data = ln.get_ydata()
ln.set_data(np.concatenate(([x], x_data)),
... | 0 | 2016-08-24T01:49:38Z | [
"python",
"animation",
"matplotlib"
] |
Mouse clicker program without autohotkey? | 39,108,113 | <p>I am a total programming newb and am trying to find a way to automate a mouse click once every 5 seconds for 5 minutes at a specific location to automatically run a licensed program many times. My work computer does not allow installation of autohotkey, but I was able to install Python v3.5 (v2.7 will not install). ... | 0 | 2016-08-23T18:15:32Z | 39,108,648 | <p>Why not just write a Python script that would open and close the program using <a href="https://docs.python.org/3/library/subprocess.html#popen-objects" rel="nofollow">Popen</a>?</p>
<pre><code>import subprocess, time
def run_program():
program = subprocess.Popen("path/to/file.exe")
program.terminate()
wh... | 0 | 2016-08-23T18:49:06Z | [
"python"
] |
I want to drop_duplicates from TextFileReader and save what remains into separate files | 39,108,147 | <p>So, I'm iterating over chunks in huge pandas' TextFileReader object and for each chunk I do drop_duplicates, then to_csv. Unfortunately, when I tried save everything in one file, it crashed after the file reached 4GB. I assumed I have to create couple of smaller csv's, that won't exceed 4GB size.</p>
<p>Now I'm tes... | 2 | 2016-08-23T18:17:51Z | 39,109,013 | <p>This works for me.</p>
<h3>Initialize <code>'test.csv'</code></h3>
<pre><code>df = pd.DataFrame(np.random.choice((1, 0), (200, 2)), columns=list('ab'))
df.insert(0, 'label', np.random.choice(list('ABCDE'), 200))
df.to_csv('test.csv', index=None)
</code></pre>
<h3>Process for 1 file</h3>
<pre><code># Initialize ... | 1 | 2016-08-23T19:12:24Z | [
"python",
"pandas"
] |
Resizing Quad Frame Video from Cap | 39,108,278 | <p>Hi I have this block of code that was suggested to me and I am trying to modify it using the Cap set for width and height to adjust the overall size of the quad display however every other run it throws this ValueError: could not broadcast input array from shape (240,320) into shape (480,640). Of course the numbers ... | 0 | 2016-08-23T18:24:51Z | 39,126,932 | <p>Moving the cap.set and the color shapes to after the read location fixes my problem.</p>
<pre><code>import numpy as np
import cv2
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
while(True):
ret, frame = cap.read()
cap.set(cv2.CAP_PROP_FRAME_WIDTH, int(640 *.5))
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, in... | 0 | 2016-08-24T15:03:00Z | [
"python",
"opencv"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.