title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Add yticks to marginals in Seaborn JointGrid
39,111,000
<p>There doesn't seem to be any examples in the documentation for <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.JointGrid.html" rel="nofollow"><code>JointGrid</code></a> or <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.jointplot.html#seaborn.jointplot" rel="nofoll...
0
2016-08-23T21:31:40Z
39,111,336
<p>This plots something, but i'm not sure how to interpret these results (or how they were calculated; the right one does not look like a density).</p> <pre><code> import matplotlib.pyplot as plt import seaborn as sns tips = sns.load_dataset('tips') g = sns.JointGrid(x='total_bill', y='tip', data=tips...
2
2016-08-23T21:59:04Z
[ "python", "matplotlib", "seaborn" ]
nth item in List to dictionary python
39,111,016
<p>I am trying to create a dictionary from every nth element of a list with list's original index as key. So for example:</p> <pre><code>l = [1,2,3,4,5,6,7,8,9] </code></pre> <p>Now running </p> <pre><code>dict(enumerate(l)).items() </code></pre> <p>gives me:</p> <pre><code>dict_items([(0, 1), (1, 2), (2, 3), (3,...
1
2016-08-23T21:32:51Z
39,111,054
<p>Use <a href="https://docs.python.org/2/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice()</code></a> on the <code>enumerate()</code> object:</p> <pre><code>from itertools import islice dict(islice(enumerate(l), None, None, 2)).items() </code></pre> <p><code>islice()</code> gives you...
4
2016-08-23T21:34:52Z
[ "python", "dictionary", "enumeration", "python-3.5" ]
Debugging Python Segmentation Fault occurring in .so file
39,111,037
<p>I am currently running into a bug when accessing a shared object library using Ctypes, code is below. The strange thing is it occurs on rare occasion. I am able to use the API most of them time but on some occasions it produces a seg fault. </p> <p>Because it doesn't happen frequently I'd prefer not to use gdb to g...
0
2016-08-23T21:33:41Z
39,111,635
<p><code>ulimit -c</code> tells the current maximum core size, <code>ulimit -c unlimited</code> sets it to, well, unlimited (you may also want to explore <code>/etc/security/limits.conf</code> and your environment, like <code>~/.bashrc</code>, for that matter).</p> <p>Regarding stack trace print, there's a <a href="ht...
0
2016-08-23T22:25:09Z
[ "python", "debugging", "segmentation-fault", "ctypes", "traceback" ]
Using python to scrape contents of jsp webpage
39,111,147
<p>Using Python and the requests library, I have a list of zip codes, and from these I would like to compile a list of nearby CVS store addresses for each. I can extract the address field without a problem, but I cannot dynamically generate the next page since there is no "&amp;zip=77098" (or equivalent) in the URL. ...
1
2016-08-23T21:43:01Z
39,131,684
<p>There quite a bit whole to going on, first you need to get the coordinates for the zip code you enter so you can use them later to post to the url the gives you the search results:</p> <pre><code>urlx = 'http://www.cvs.com/store-locator/store-locator-landing.jsp' headers = { 'user-agent': 'Mozilla/5.0 (Windows ...
1
2016-08-24T19:34:35Z
[ "python", "web-scraping", "python-requests" ]
Moving rows of data within pandas dataframe to end of last column
39,111,249
<p>Python newbie, please be gentle. I have data in two "middle sections" of a multiple Excel spreadsheets that I would like to isolate into one pandas dataframe. Below is a link to a data screenshot. Within each file, my headers are in Row 4 with data in Rows 5-15, Columns B:O. The headers and data then continue with h...
2
2016-08-23T21:51:16Z
39,112,583
<p>If all of your Excel files have the same number of rows and this is a one time operation, you could simply hard code those numbers in your <code>read_excel</code>. If not, it will be a little tricky, but you pretty much follow the same procedure:</p> <pre><code>for file_ in allFiles: top = pd.read_excel(file_, ...
1
2016-08-24T00:16:50Z
[ "python", "excel", "pandas", "dataframe" ]
Moving rows of data within pandas dataframe to end of last column
39,111,249
<p>Python newbie, please be gentle. I have data in two "middle sections" of a multiple Excel spreadsheets that I would like to isolate into one pandas dataframe. Below is a link to a data screenshot. Within each file, my headers are in Row 4 with data in Rows 5-15, Columns B:O. The headers and data then continue with h...
2
2016-08-23T21:51:16Z
39,119,954
<p>you can do it this way:</p> <pre><code>df1 = pd.read_excel(file_,sheetname="Data1", parse_cols="B:O",index_col=None, header=3, skip_rows=3) df2 = pd.read_excel(file_,sheetname="Data1", parse_cols="B:L",index_col=None, header=20, skip_rows=20) # pay attention at `axis=1` df = pd.concat([df1,df2], axis=1) </code></pr...
0
2016-08-24T09:52:47Z
[ "python", "excel", "pandas", "dataframe" ]
Automate google play search items in a list
39,111,251
<p>I am working on a python project where I need to find out what are the apps that the company owns. For example, I have a list:</p> <pre><code>company_name = ['Airbnb', 'WeFi'] </code></pre> <p>I would like to write a python function/ program to do the following:</p> <p>1 . have it <strong>automatically</strong> ...
0
2016-08-23T21:51:23Z
39,112,347
<p>I've written a little demo that may help you to achieve your goal. I used requests and Beautiful Soup. It's not exactly what you wanted but it can be adapted easily.</p> <pre><code>import requests import bs4 company_name = "airbnb" def get_company(company_name): r = requests.get("https://play.google.com/store/...
0
2016-08-23T23:46:33Z
[ "python", "function", "web-scraping", "automation", "web-crawler" ]
Resizing recommendation On Google DataCloud
39,111,274
<p>I have set up a cluster of 24 high-memory CPUs (1 master: 8 vCPUs and 2 workers: 8 vCPUs). In the recommendation bar at the bottom of the first picture is adviced to resize the master-node to 10 CPUs, so 2 additional CPUs, because the master is overutilized. Nevertheless the graph in the first picture shows I have n...
0
2016-08-23T21:54:04Z
39,186,680
<p>Unfortunately, as mentioned in <a href="http://stackoverflow.com/questions/39073032/how-i-dynamically-upgrade-workers-cpu-ram-disk-in-dataproc">this related answer</a> Dataproc doesn't currently support live reconfiguring of the already-running Hadoop/Spark services when you resize machines through the Google Comput...
1
2016-08-27T23:26:15Z
[ "python", "apache-spark", "apache-spark-sql", "google-cloud-dataproc" ]
How do I convert a MultiIndex to type string
39,111,347
<p>consider the MultiIndex <code>idx</code></p> <pre><code>idx = pd.MultiIndex.from_product([range(2013, 2016), range(1, 5)]) </code></pre> <p>When I do</p> <pre><code>idx.to_series().str.join(' ') </code></pre> <p>I get</p> <pre><code>2013 1 NaN 2 NaN 3 NaN 4 NaN 2014 1 NaN 2 ...
4
2016-08-23T22:00:11Z
39,111,524
<p>I'm not sure it's the most elegant way, but it should work:</p> <pre><code>idx.get_level_values(0).astype(str).values + ' ' + idx.get_level_values(1).astype(str).values </code></pre>
2
2016-08-23T22:16:34Z
[ "python", "pandas", "multi-index" ]
How do I convert a MultiIndex to type string
39,111,347
<p>consider the MultiIndex <code>idx</code></p> <pre><code>idx = pd.MultiIndex.from_product([range(2013, 2016), range(1, 5)]) </code></pre> <p>When I do</p> <pre><code>idx.to_series().str.join(' ') </code></pre> <p>I get</p> <pre><code>2013 1 NaN 2 NaN 3 NaN 4 NaN 2014 1 NaN 2 ...
4
2016-08-23T22:00:11Z
39,111,543
<p>Something like this?</p> <pre><code>idx.to_series().apply(lambda x: '{0}-{1}'.format(*x)) </code></pre>
3
2016-08-23T22:17:32Z
[ "python", "pandas", "multi-index" ]
How do I convert a MultiIndex to type string
39,111,347
<p>consider the MultiIndex <code>idx</code></p> <pre><code>idx = pd.MultiIndex.from_product([range(2013, 2016), range(1, 5)]) </code></pre> <p>When I do</p> <pre><code>idx.to_series().str.join(' ') </code></pre> <p>I get</p> <pre><code>2013 1 NaN 2 NaN 3 NaN 4 NaN 2014 1 NaN 2 ...
4
2016-08-23T22:00:11Z
39,112,164
<p>A general solution using <code>starmap</code> from <code>itertools</code></p> <pre><code>from itertools import starmap def flat2(midx, sep=''): fstr = sep.join(['{}'] * midx.nlevels) return pd.Index(starmap(fstr.format, midx)) </code></pre> <hr> <h3>Demonstration</h3> <pre><code>midx = pd.MultiIndex.fro...
1
2016-08-23T23:22:11Z
[ "python", "pandas", "multi-index" ]
How do I convert a MultiIndex to type string
39,111,347
<p>consider the MultiIndex <code>idx</code></p> <pre><code>idx = pd.MultiIndex.from_product([range(2013, 2016), range(1, 5)]) </code></pre> <p>When I do</p> <pre><code>idx.to_series().str.join(' ') </code></pre> <p>I get</p> <pre><code>2013 1 NaN 2 NaN 3 NaN 4 NaN 2014 1 NaN 2 ...
4
2016-08-23T22:00:11Z
39,138,897
<p>The fastest are list comprehensions:</p> <pre><code>print (['{} {}'.format(i[1], i[0]) for i in idx]) print ([' '.join((str(i[0]), str(i[1]))) for i in idx]) </code></pre> <p><strong>Timings</strong>:</p> <pre><code>In [21]: %timeit (['{} {}'.format(i[1], i[0]) for i in idx]) The slowest run took 4.68 times longe...
1
2016-08-25T07:13:04Z
[ "python", "pandas", "multi-index" ]
Bokeh web server app at localhost to html file
39,111,369
<p>I have been working with <code>bokeh web server</code>.</p> <p>I created a web app, using my own data and following this example: <a href="https://github.com/bokeh/bokeh/blob/master/examples/app/movies/main.py" rel="nofollow">https://github.com/bokeh/bokeh/blob/master/examples/app/movies/main.py</a></p> <p>I alrea...
1
2016-08-23T22:02:25Z
39,111,847
<p>If your app makes calls to actual python libraries (e.g. <code>numpy</code> and <code>pandas</code> that you show above) in any of its event callbacks (in fact, if it even has any <code>on_change</code> callbacks <em>at all</em>), then it is not possible to make a "standalone HTML file" (i.e. that can be simply uplo...
1
2016-08-23T22:46:34Z
[ "python", "python-3.x", "pandas", "bokeh" ]
Tensorflow: chaining tf.gather() produces IndexedSlices warning
39,111,373
<p>I'm running into an issue where chaining <code>tf.gather()</code> indexing produces the following warning:</p> <pre><code>/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/gradients.py:90: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of ...
0
2016-08-23T22:02:59Z
39,131,434
<p>The gradient <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/array_grad.py#L277" rel="nofollow">function</a> of the <code>tf.gather</code> operation returns <code>IndexedSlices</code> typed value. In your program, the input the second <code>tf.gather</code> is the result of a <cod...
2
2016-08-24T19:19:31Z
[ "python", "neural-network", "tensorflow" ]
Python - iterate over JSON results
39,111,376
<p>In order to get <code>energy</code> values, I am trying to iterate over this <code>JSON</code> result:</p> <pre><code>[{u'track_href': u'https://api.spotify.com/v1/tracks/7603o589huckPbiELnUKgu', u'analysis_url': u'https://api.spotify.com/v1/audio-analysis/7603o589huckPbiELnUKgu', u'energy': 0.526, u'liveness': 0.0...
0
2016-08-23T22:03:06Z
39,111,484
<p>It is because within your JSON array, at some place instead of dictionary a <code>None</code> value is present. You may eliminate it via:</p> <pre><code>[x['energy'] for x in features if x] </code></pre>
3
2016-08-23T22:13:20Z
[ "python", "json", "iteration" ]
Replace string by matching using regular expression python
39,111,379
<p>Original String:</p> <pre><code>necessary information Leave a Comment unnecessary information </code></pre> <p>Required String:</p> <pre><code>necessary information </code></pre> <p>I have multiple strings that are in the above mentioned 'Original String' format. I want to remove the 'Leave a Comment' and 'unnec...
0
2016-08-23T22:03:23Z
39,111,448
<pre><code>&gt;&gt;&gt; s 'necessary information Leave a Comment unnecessary information' &gt;&gt;&gt; re.sub(r'\sLeave a Comment.*', '', s) 'necessary information' </code></pre>
0
2016-08-23T22:09:04Z
[ "python", "regex" ]
Parse out a URL with regex operation in python
39,111,429
<p>I have data as follows,</p> <p>data</p> <pre><code>url http://hostname.com/part1/part2/part3/a+b+c+d http://m.hostname.com/part3.html?nk!e+f+g+h&amp;_junk http://hostname.com/as/ck$st=f+g+h+k+i/ http://www.hostname.com/p-l-k?wod=q+w+e+r+t africa </code></pre> <p>I want to check for first + symbol in the url and m...
3
2016-08-23T22:07:33Z
39,111,537
<p>So the appropriate regex that shall parse the required characters you wanted is <code>((.\+)+.)</code> I am using Javascript regex here. But, You should be able to implement in py as well.</p> <p>This regex shall extract you <code>a+b+c+d</code> from your first url. It will need to be processed a little bit more to...
1
2016-08-23T22:17:13Z
[ "python", "regex", "python-2.7", "python-3.x", "pyspark" ]
Parse out a URL with regex operation in python
39,111,429
<p>I have data as follows,</p> <p>data</p> <pre><code>url http://hostname.com/part1/part2/part3/a+b+c+d http://m.hostname.com/part3.html?nk!e+f+g+h&amp;_junk http://hostname.com/as/ck$st=f+g+h+k+i/ http://www.hostname.com/p-l-k?wod=q+w+e+r+t africa </code></pre> <p>I want to check for first + symbol in the url and m...
3
2016-08-23T22:07:33Z
39,111,583
<p>Here is the expression that works for your sample use cases:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; &gt;&gt;&gt; l = [ ... "http://hostname.com/part1/part2/part3/a+b+c+d", ... "http://m.hostname.com/part3.html?nk!e+f+g+h&amp;_junk", ... "http://hostname.com/as/ck$st=f+g+h+k+i/", ... "htt...
1
2016-08-23T22:21:09Z
[ "python", "regex", "python-2.7", "python-3.x", "pyspark" ]
how to generate n random integers of k digits
39,111,489
<p>Is there a way to create n random integers of k digits.</p> <p>For example.. 2000 random integers comprising of <code>[0, 2, 3]</code></p> <p>My trick was to use a random number of generator and then assign values based on the the ranges?</p> <p>But was wondering if there is a better way to do this in python?</p>...
-2
2016-08-23T22:13:56Z
39,111,517
<p>Now after your edit, it is clear what you want. You want discrete-sampling of some elements within a container.</p> <p>Just prepare your classes and do this:</p> <pre><code>import numpy as np classes = [0, 2, 3] samples = np.random.choice(classes, 2000) </code></pre> <p>If you want some specific probabilities:</p...
1
2016-08-23T22:16:12Z
[ "python" ]
how to generate n random integers of k digits
39,111,489
<p>Is there a way to create n random integers of k digits.</p> <p>For example.. 2000 random integers comprising of <code>[0, 2, 3]</code></p> <p>My trick was to use a random number of generator and then assign values based on the the ranges?</p> <p>But was wondering if there is a better way to do this in python?</p>...
-2
2016-08-23T22:13:56Z
39,111,565
<p>You may achieve it via <code>list comprehension</code>. In order to show the result I am using <code>20</code>. Change it to <code>2000</code> as per your requirement.</p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; x = 20 &gt;&gt;&gt; [random.choice([0, 2, 3]) for i in range(20)] [2, 2, 3, 2, 0, 2, 3, 2, 3,...
1
2016-08-23T22:19:10Z
[ "python" ]
how to generate n random integers of k digits
39,111,489
<p>Is there a way to create n random integers of k digits.</p> <p>For example.. 2000 random integers comprising of <code>[0, 2, 3]</code></p> <p>My trick was to use a random number of generator and then assign values based on the the ranges?</p> <p>But was wondering if there is a better way to do this in python?</p>...
-2
2016-08-23T22:13:56Z
39,111,590
<p>From the sounds of it, it looks like you want to generate a sequence of length <code>n</code> using only the values found within the list <code>k</code>.</p> <p>Python's <code>random.choice</code> function combined with list comprehension is perfect for this.</p> <p>The following function will generate a list of l...
3
2016-08-23T22:21:42Z
[ "python" ]
how to generate n random integers of k digits
39,111,489
<p>Is there a way to create n random integers of k digits.</p> <p>For example.. 2000 random integers comprising of <code>[0, 2, 3]</code></p> <p>My trick was to use a random number of generator and then assign values based on the the ranges?</p> <p>But was wondering if there is a better way to do this in python?</p>...
-2
2016-08-23T22:13:56Z
39,111,734
<p>You're willing to use numpy, so I'd recommend you use <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.random.choice.html" rel="nofollow">np.random.choice</a>, ie:</p> <pre><code>import numpy as np N = 2000 print[np.random.choice([0, 2, 3], p=[1/3.0, 1/3.0, 1/3.0]) for x in range(N)] </code><...
1
2016-08-23T22:35:37Z
[ "python" ]
how to generate n random integers of k digits
39,111,489
<p>Is there a way to create n random integers of k digits.</p> <p>For example.. 2000 random integers comprising of <code>[0, 2, 3]</code></p> <p>My trick was to use a random number of generator and then assign values based on the the ranges?</p> <p>But was wondering if there is a better way to do this in python?</p>...
-2
2016-08-23T22:13:56Z
39,111,891
<pre><code>import numpy as np N = 10 # Generate three vectors of n size zeros = np.zeros((N,), dtype = np.int) twos = np.zeros((N,), dtype = np.int) + 2 threes = np.zeros((N,), dtype = np.int) + 3 # Permutate all together df = [] df = np.append(df, [zeros, twos, threes]) df_shuffled = np.random.shuffle(df) print(df) <...
0
2016-08-23T22:50:32Z
[ "python" ]
Python Pyserial - Threading
39,111,502
<p>Python 2.7</p> <p>This is the code I have. Could you please tell me whats wrong. This is the beast I could come up with after studying threading for over two days continuously.</p> <p>The serial communications work when I dont use threading. </p> <pre><code>import threading import time import sys import serial im...
0
2016-08-23T22:15:21Z
39,111,685
<p>You are not properly syncing the threads. I suggest putting the <code>ser</code> object into the global namespace and using a lock, mutex or semaphore to prevent the two threads from accessing the single <code>ser</code> object at the same time. </p> <p>Python Module of the Week explains it best <a href="https://py...
0
2016-08-23T22:29:50Z
[ "python", "multithreading", "pyserial" ]
Python Pyserial - Threading
39,111,502
<p>Python 2.7</p> <p>This is the code I have. Could you please tell me whats wrong. This is the beast I could come up with after studying threading for over two days continuously.</p> <p>The serial communications work when I dont use threading. </p> <pre><code>import threading import time import sys import serial im...
0
2016-08-23T22:15:21Z
39,116,187
<p>Example for using lock</p> <pre><code>import threading import time import sys import serial import os import time def Task1(lck,ser): while 1: print "Inside Thread 1" lck.acquire() ser.write('\x5A\x03\x02\x02\x02\x09') # Byte ArrayTo Control a MicroProcessing Unit b = ser.read...
0
2016-08-24T06:46:19Z
[ "python", "multithreading", "pyserial" ]
python, list compare, ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
39,111,589
<p>Here is my python code:</p> <pre><code>def ava_check(nodes_group,child_list): ava_list=nodes_group[:] if nodes_group[1] in child_list: return None else: for a in nodes_group: if a in child_list: ava_list.remove(a) ava_list.remove(nodes_group[n...
0
2016-08-23T22:21:36Z
39,111,823
<p>One (or more) of the values in your <code>nodes_group</code> list is a <code>numpy</code> array, not a float or tuple like you show in your example data. You can't use the test <code>a in some_list</code> if <code>a</code> is an array, because an array's <code>==</code> operator doesn't return a <code>bool</code> va...
1
2016-08-23T22:44:30Z
[ "python", "arrays", "list", "numpy" ]
How to build model in DynamoDB if each night I need to process the daily records and then delete them?
39,111,598
<p>I need to store some daily information in DynamoDB. Basically, I need to store user actions: UserID, StoreID, ActionID and Timestamp. Each night I would like to process the information generated that day, do some aggregations, some reports, and then I can safely deleted those records. How should I model this? I mean...
0
2016-08-23T22:22:11Z
39,114,304
<p>You can use RabbitMQ to schedule jobs asynchronously. This would be faster than multiple DB queries. Basically, this tool allows you to create a job queue (Containing UserID, StoreID &amp; Timestamp) where workers can remove (at midnight if you want) and create your reports (or whatever your heart desires).</p> <p>...
1
2016-08-24T04:13:00Z
[ "python", "database-design", "amazon-dynamodb" ]
PyQt: QListView in connection with QTexEdit
39,111,600
<p>I have a QListView and a QTextEdit on a form and I would like to get them working together, as follows: if a checkbox is checked, the index of the respective item in the QlistView should be displayed in tbe QTextEdit; if the checkbox is unchecked, the value should be deleted from the QTextEdit. The indexes should be...
0
2016-08-23T22:22:16Z
39,111,865
<p>Since you're defining <code>onclick</code> outside of a class definition, there's no <code>self</code> (which refers to an instance of the class) either. Define it as a regular function instead:</p> <pre><code>@QtCore.pyqtSlot(QtCore.QModelIndex) def onclick(index): editbox.setText(str(index.row())) </code></pr...
0
2016-08-23T22:48:27Z
[ "python", "pyqt4" ]
Could not convert string to float: ...Sometimes
39,111,629
<p>I'm having some strange things happen when converting strings to floats in a loop.</p> <p>So when I use the following code exactly it writes: </p> <pre><code>[1468436874000, 0.00254071495719], [1468528803000, 0.00341349353996], [1468688596000, 0.000853373384991], [1468871365000, 0.00256012015497], </code></pre> <...
0
2016-08-23T22:24:29Z
39,111,888
<p>Debug by printing the values of <code>avgprice</code> and <code>avgsqft</code> in your code. You are getting some <code>string</code> as it's value which can not be converted to float</p>
0
2016-08-23T22:50:14Z
[ "python", "zip" ]
Hooking Python code using Detours
39,111,709
<p>I built a simple Python gui application("App.py") that I am trying to hook using detours. My understanding is that Python should use Windows dll's at some point and I am trying to hook these function calls.</p> <p>For that purpose I am using detours withdll.exe :</p> <pre><code>withdll.exe /d:"myDLL.dll" "myprogra...
0
2016-08-23T22:32:20Z
39,275,794
<p>I looked through detours withdll.exe source code and found out that it can take command line arguments, the issue was solved using:</p> <pre><code>withdll.exe /d:"myDLL.dll" "pathtopython/Python.exe" "pathtoscript/myscript.py" </code></pre>
0
2016-09-01T15:40:24Z
[ "python", "windows", "dll", "code-injection", "detours" ]
Ansible: given a list of ints in a variable, define a second list in which each element is incremented
39,111,787
<p>Let's assume that we have an Ansible variable that is a <code>list_of_ints</code>.</p> <p>I want to define an <code>incremented_list</code>, whose elements are obtained incrementing by a fixed amount the elements of the first list.</p> <p>For example, if this is the first variable:</p> <pre><code>--- # file: some...
2
2016-08-23T22:40:38Z
39,112,215
<p>This will do it:</p> <pre><code>--- - hosts: localhost connection: local vars: incremented_list: [] list_of_ints: - 1 - 7 - 8 incr: 100 tasks: - set_fact: incremented_list: "{{ incremented_list + [ item + incr ] }}" no_log: False with_items: "{{ list_of_ints...
2
2016-08-23T23:28:31Z
[ "python", "functional-programming", "ansible", "jinja2" ]
Sort an item in a list of tuples in the values of a dictionary with Python
39,111,798
<p>I'm trying to sort the first item in a list of tuples in the value of a dictionary. </p> <p>Here is my dictionary:</p> <pre><code>d = {'key_': (('2', 'a'), ('3', 'b'), ('4', 'c'), ('1', 'd'))} </code></pre> <p>I want the sorted output to look like this:</p> <pre><code>d2 = {'key_': (('1', 'd'), ('2', 'a'), ('3',...
0
2016-08-23T22:41:41Z
39,111,822
<p><code>d.values()</code> return the list of all the values present within the dictionary. But here you want to sort the list which is present as value corresponding to <code>key_</code> key. So, you have to call the sorted function as:</p> <pre><code># Using tuple as your example is having tuple instead of list &gt;...
2
2016-08-23T22:44:12Z
[ "python", "sorting", "dictionary" ]
pyqt QTreeWidgetItem double click connect
39,111,880
<p>Is it possible to connect a doubleclick event to a QTreeWidgetItem?</p> <p>Something like this:</p> <pre><code>def test(self): print("hello") childItem = QTreeWidgetItem() childItem.doubleClicked.connect(self.test) </code></pre>
0
2016-08-23T22:49:32Z
39,112,026
<p>The signal you want is called <code>itemDoubleClicked</code> and belongs to <code>QTreeWidget</code> itself:</p> <pre><code>from PyQt4 import QtGui def handler(item, column_no): print(item, column_no) def main(): app = QtGui.QApplication(sys.argv) win = QtGui.QTreeWidget() items = [QtGui.QTreeWid...
1
2016-08-23T23:06:14Z
[ "python", "pyqt" ]
Python 3.4 64-bit download
39,111,886
<p>How can I download Anaconda with previous Python versions like Python 3.4 64-bit.</p> <p>The reason is Bloomberg API is only available up to 3.4 and 3.5 is not out yet.</p>
0
2016-08-23T22:50:11Z
39,111,945
<p>I recommend installing the newest Anaconda version and using <strong>virtual-environments</strong>. This way, you would set up a <em>Python 3.4</em> environment.</p> <p>This is documented <a href="http://conda.pydata.org/docs/using/envs.html" rel="nofollow">here</a>. There are also <a href="http://conda.pydata.org/...
1
2016-08-23T22:56:26Z
[ "python", "anaconda" ]
Adding values to sequentially spaced list in python?
39,111,903
<p>I am fairly new to Python and am confused how to represent the following code from Matlab into Python:</p> <pre><code>P = [2:35,50,100,200] </code></pre> <p>In Matlab, this will spit out: P = [2,3,...,35,50,100,200] ; however, I can't seem to figure out how to easily add values to an a list with sequential numberi...
0
2016-08-23T22:51:18Z
39,111,921
<p>Vanilla python doesn't have a dedicated syntax for this ... If you're working with lists, you need 2 steps:</p> <pre><code>lst = list(range(2, 36)) # for python2.x, you don't need `list(...)` lst.extend([50, 100, 200]) </code></pre> <p>If you have the "bleeding edge" (python3.5), <a href="https://www.python.org/d...
5
2016-08-23T22:53:44Z
[ "python", "list", "range" ]
Adding values to sequentially spaced list in python?
39,111,903
<p>I am fairly new to Python and am confused how to represent the following code from Matlab into Python:</p> <pre><code>P = [2:35,50,100,200] </code></pre> <p>In Matlab, this will spit out: P = [2,3,...,35,50,100,200] ; however, I can't seem to figure out how to easily add values to an a list with sequential numberi...
0
2016-08-23T22:51:18Z
39,111,946
<p>If you're fortunate enough to use Python 3.5, you can use <a href="https://docs.python.org/3/whatsnew/3.5.html#whatsnew-pep-448" rel="nofollow"><em>additional unpacking generalizations</em></a> (from <a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow">PEP 448</a>) with <code>range</code>:</p> <pre><c...
4
2016-08-23T22:56:27Z
[ "python", "list", "range" ]
How do you serve a dynamically downloaded image to a browser using flask?
39,111,906
<p>I'm working with an IP camera. I can use a URL such as this one to grab a static image off the camera:</p> <p><a href="http://Username:Password@IP_of_Camera:Port/streaming/channels/1/picture" rel="nofollow">http://Username:Password@IP_of_Camera:Port/streaming/channels/1/picture</a></p> <p>What I want to do is have...
0
2016-08-23T22:51:36Z
39,112,024
<pre><code>import requests url = "http://Username:Password@IP_of_Camera:Port/streaming/channels/1/picture" response = requests.get(url) if response.status_code == 200: f = open("/your/static/dir/temp.png", 'wb') f.write(response.content) f.close() </code></pre> <p><code>{{ url_for('static' filename="temp.p...
1
2016-08-23T23:06:08Z
[ "python", "flask" ]
How do you serve a dynamically downloaded image to a browser using flask?
39,111,906
<p>I'm working with an IP camera. I can use a URL such as this one to grab a static image off the camera:</p> <p><a href="http://Username:Password@IP_of_Camera:Port/streaming/channels/1/picture" rel="nofollow">http://Username:Password@IP_of_Camera:Port/streaming/channels/1/picture</a></p> <p>What I want to do is have...
0
2016-08-23T22:51:36Z
39,112,044
<p>I would add a masking route on flask that fetches and serves the image directly. Lets say <code>domain.com/image/user1/cam1</code> </p> <p>Your server would typically make a http request to the camera and once it receives a response, you can straight up serve it as a <code>Response</code> object with appropriate mi...
3
2016-08-23T23:08:03Z
[ "python", "flask" ]
discord channel link in message
39,111,931
<p>Using discord.py, I am making a bot to send users a direct message if a keyword of their choosing is mentioned.</p> <p>Everything is working, except I just want to add the channel they were mentioned in to the message. Here is my code:</p> <pre><code> print("SENDING MESSAGE") sender = '{0.author.nam...
0
2016-08-23T22:54:27Z
39,119,899
<p>In Discord: there is channel mention. Try that way, do <code>message.channel.mention</code> instead of <code>message.channel.name</code> it should able to link a channel in PM or everywhere.</p> <p>Source: <a href="http://discordpy.readthedocs.io/en/latest/api.html#discord.Channel.mention" rel="nofollow">Discord D...
1
2016-08-24T09:50:10Z
[ "python", "bots" ]
Differentiating between compressed .gz files and archived tar.gz files properly?
39,112,008
<p>What is the proper way to deal with differentiating between a plain compressed file in gzip or bzip2 format (eg. .gz) and a tarball compressed with gzip or bzip2 (eg. .tar.gz) Identification using suffix extensions is not a reliable option as it's possible files may end up renamed.</p> <p>Now on the command line I...
0
2016-08-23T23:03:19Z
39,112,429
<p>It is very likely a tar file if the uncompressed data at offset 257 is "ustar", <em>or</em> if the uncompressed data in its entirety is 1024 zero bytes (an empty tar file).</p> <p>You can read just the first 1024 bytes of the uncompressed data using <code>z = zlib.decompressobj()</code> or <code>z = bz2.BZ2Decompr...
0
2016-08-23T23:59:22Z
[ "python", "compression", "archive", "python-magic" ]
Python filtering strings
39,112,053
<p>I´m trying to make a python script to rename the subtitles file (.srt) with the filename of the video file corresponding to that episode, so when I open it in VLC the subtitles are already loaded.</p> <p>So far I´ve succeeded in getting all the file names from the videos and subs into strings on two separate list...
-3
2016-08-23T23:08:42Z
39,112,089
<p>You can use <a href="https://docs.python.org/2.7/library/functions.html#zip" rel="nofollow"><code>zip</code></a> to make the pairs, <em>if</em> the sorted lists for <code>videoPaths</code> and <code>subsPaths</code> are correct in the they correspond to each other. ie First episode video and subtitles are both the f...
2
2016-08-23T23:14:13Z
[ "python" ]
Constructing Zipf Distribution with matplotlib, trying to draw fitted line
39,112,063
<p>I have a list of paragraphs, where I want to run a zipf distribution on their combination. </p> <p>My code is below:</p> <pre><code>from itertools import * from pylab import * from collections import Counter import matplotlib.pyplot as plt paragraphs = " ".join(targeted_paragraphs) for paragraph in paragraphs: ...
0
2016-08-23T23:10:10Z
39,112,844
<p>I don't know what <code>targeted_paragraphs</code> looks like, but I got your error using:</p> <pre><code>targeted_paragraphs = ['a', 'b', 'c'] </code></pre> <p>Based on that it looks like the problem is in how you set up the <code>for</code> loop. You're indexing <code>ranks</code> and <code>frequencies</code> us...
1
2016-08-24T00:56:29Z
[ "python", "python-2.7", "matplotlib", "itertools" ]
Parallelizing a for loop with map and reduce in spark with pyspark
39,112,109
<p>In my application, I am creating different data-frames from data in different locations on S3, and then trying to merge the dataframes into a single dataframes. Right now I am using a for loop for this. But I have a feeling this can be done in a much more efficient way using map and reduce functions in pyspark. Here...
0
2016-08-23T23:15:49Z
39,112,355
<p>Actually iterative <code>union</code>, although suboptimal, is not the biggest issue here. Much more serious problem is introduced by schema inference (<code>inferschema = "true"</code>).</p> <p>It not only makes data frame creation not lazy but also requires a separate data scan just for inference. If you know sch...
1
2016-08-23T23:48:36Z
[ "python", "apache-spark", "pyspark" ]
Use Selenium to click a 'Load More' button until it doesn't exist (Youtube)
39,112,138
<p>I am trying to write a python script that goes to a youtube channel. Clicks on the Video Tab. Then Scrapes the webpage for content. I am all fine for scraping the content, until... I get to the load more button. The python script I have manages to click the load more button once but it never presses it again :'( How...
-1
2016-08-23T23:18:51Z
39,304,871
<p>you can use following code for scrolling</p> <pre><code>from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as...
0
2016-09-03T08:29:20Z
[ "python", "selenium" ]
What's the standard way to document a namedtuple?
39,112,163
<p>Looking to clean up some code by using a namedtuple to hold multiple variables for passing through a number of functions. Below is a simplified example (I actually have a few more additional arguments).</p> <p>Before:</p> <pre><code>def my_function(session_cass, session_solr, session_mysql, some_var, another): """...
0
2016-08-23T23:22:09Z
39,112,787
<p>I am not familiar with Google style guide, but how about this:</p> <p>for a namedtuple or tuple or list or whatever that is interchangeable I would go for something like this</p> <pre><code>def my_function(sessions, some_var, another): """Blah blah. Args: sessions (sequence): A sequence of length ...
1
2016-08-24T00:49:10Z
[ "python", "code-documentation" ]
How do I pass a scalar via a TensorFlow feed dictionary
39,112,176
<p>My TensorFlow model uses <code>tf.random_uniform</code> to initialize a variable. I would like to specify the range when I begin training, so I created a placeholder for the initialization value.</p> <pre><code>init = tf.placeholder(tf.float32, name="init") v = tf.Variable(tf.random_uniform((100, 300), -init, init)...
0
2016-08-23T23:24:20Z
39,112,432
<p><strong>TL;DR:</strong> Define <code>init</code> with a scalar shape as follows:</p> <pre><code>init = tf.placeholder(tf.float32, shape=(), name="init") </code></pre> <p>This looks like an unfortunate implementation detail of <a href="https://github.com/tensorflow/tensorflow/blob/cc3153a7a0a23533d14ead34db37e4ccd7...
1
2016-08-23T23:59:41Z
[ "python", "machine-learning", "tensorflow" ]
Python/NumPy first occurrence of masked subarray
39,112,189
<p>I would like to find the occurrences of a subarray in a numpy array, but with a "wildcard". </p> <pre><code>a = np.array([1, 2, 3, 4, 5]) b = np.ma.array([2, 99, 4], mask=[0, 1, 0]) </code></pre> <p>The idea is that searching for b in a gives a match because 99 is masked.</p> <p>More specifically, I hoped that th...
0
2016-08-23T23:26:06Z
39,112,647
<p>Use <code>np.ma.equal</code> instead of <code>==</code> - see end.</p> <p>========================</p> <p>A masked array consists of a <code>data</code> array and a mask array. Often the masked array is used in other operations by 'filling' the masked values with something innocuous, or by compressing them out. ...
1
2016-08-24T00:27:06Z
[ "python", "arrays", "numpy" ]
restframework 'tuple' object has no attribute '_meta'
39,112,252
<p>Django throws the next exception:</p> <p>restframework 'tuple' object has no attribute '_meta'</p> <p>Model</p> <pre><code>class BDetail(models.Model): lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) class Meta: # managed = False db_table = 'b_...
0
2016-08-23T23:33:06Z
39,112,322
<p>You are having the <code>,</code> after the name of <code>BDetail</code> model in <code>BDetailSerializer</code> serializer. Removing that and your code will work.</p> <p><strong>Suggesstion</strong>: Inherit <code>serializers.ModelSerializer</code> in your <code>BDetailSerializer</code> serializer instead of <code...
0
2016-08-23T23:43:32Z
[ "python", "django", "python-2.7", "django-rest-framework", "django-rest-framework-gis" ]
ploting and save multiple functions in the same file matplotlib
39,112,291
<p>I want to save 6 graphs in one page using matplotlib. The graphs are each a call of a a function and came up with this code below to test before saving it:</p> <pre><code>def save_plot (output_DF, path = None): fig = plt.figure(1) sub1 = fig.add_subplot(321) plt.plot(plot_BA(output_DF)) sub2 = fig.a...
0
2016-08-23T23:38:16Z
39,113,014
<p>Try something like this:</p> <pre><code>import matplotlib.pyplot as plt import random def function_to_call(func_name, ax): data = range(10) random_x_label = random.choice('abcdefghijk') random_y_label = random.choice('abcdefghijk') random.shuffle(data) # demonstration ax.plot(data) ax.set...
0
2016-08-24T01:21:38Z
[ "python", "matplotlib" ]
Python 3.5 ImportError: dynamic module does not define module export function (PyInit_cv2)
39,112,321
<p>This is what I'm getting when i try to import cv2 into python3.5 IDLE. I'm using OpenCV 3.1.0 Python3.5.2 Ubuntu 16.04</p> <p>I tried lots of installing methods but no one solved my problem, i had the import working on terminal but it just stopped as well. Anyone might have a solution?</p> <pre><code>import cv2 T...
0
2016-08-23T23:43:30Z
39,112,441
<p>For python3, you need to provide python a <code>init</code> method as entrance,</p> <p>which is in <code>cv.py</code> I guess. But in my case, </p> <p>this file did not exist. I copied own from <a href="https://code.google.com/p/ctypes-opencv/source/browse/trunk/src/ctypes_opencv/cv.py?r=236" rel="nofollow">google...
0
2016-08-24T00:00:33Z
[ "python", "python-3.x", "opencv", "ubuntu" ]
Putting 2 dimensional numpy arrays into a 3 dimensional array
39,112,372
<p>I want to keep adding numpy arrays to another array in python. let's say I have the following arrays:</p> <pre><code>arraytotal = np.array([]) array1 = np.array([1,1,1,1,1]) array2 = np.array([2,2,2,2,2]) </code></pre> <p>and I want to append array1 and array2 into arraytotal. However, when I use:</p> <pre><code...
-1
2016-08-23T23:51:28Z
39,112,576
<p>You should append the arrays onto a regular python list and then convert the list to a numpy array at the end:</p> <pre><code>import numpy as np total = [] for i in range(5,15): thisArray = np.arange(i) total.append(thisArray) total = np.asarray(total) </code></pre> <p>That loop makes a 2D array; you'd nes...
-1
2016-08-24T00:16:20Z
[ "python", "arrays", "python-2.7", "numpy", "multidimensional-array" ]
Putting 2 dimensional numpy arrays into a 3 dimensional array
39,112,372
<p>I want to keep adding numpy arrays to another array in python. let's say I have the following arrays:</p> <pre><code>arraytotal = np.array([]) array1 = np.array([1,1,1,1,1]) array2 = np.array([2,2,2,2,2]) </code></pre> <p>and I want to append array1 and array2 into arraytotal. However, when I use:</p> <pre><code...
-1
2016-08-23T23:51:28Z
39,313,960
<p>Unfortunately, there is no way to manipulate arrays quite like that. Instead, make a list with the same name, and append the two arrays and change it to a numpy array like so:</p> <pre><code>arraytotal[] array1 = np.array([1,1,1,1,1]) arraytotal.append[array1] np.array(arraytotal) </code></pre>
0
2016-09-04T05:55:37Z
[ "python", "arrays", "python-2.7", "numpy", "multidimensional-array" ]
Django: "referenced before assignment" but only for some variables
39,112,401
<p>I'm writing a small app in Django and I'm keeping the state saved in a few variables I declare out of the methods in views.py. Here is the important part of this file:</p> <pre><code>from app.playerlist import fullList auc_unsold = fullList[:] auc_teams = [] auc_in_progress = [] auc_current_turn = -1 print(auc_in_p...
-1
2016-08-23T23:55:02Z
39,118,960
<p>You should absolutely not be doing this, either your original code or your proposed solution with <code>global</code>.</p> <p>Anything at module level will be shared across requests, not only for the current user but for <em>all</em> users for that process. So everyone will see the same auction, etc.</p> <p>The re...
1
2016-08-24T09:06:29Z
[ "python", "django" ]
Django Static image File Failed to load resource
39,112,412
<p><strong>FIXED</strong> This was my solution, in the main programs urls.py I had to add these lines.</p> <p>from django.conf import settings from django.conf.urls.static import static</p> <p>urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)</p> <p>I have an model called Item within there...
0
2016-08-23T23:56:44Z
39,112,499
<p>In your <code>settings.py</code></p> <pre><code>BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_URL = '/static/' </code></pre> <p>and read this <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/" rel="nofollow">document</a>...
0
2016-08-24T00:07:26Z
[ "python", "django", "django-models", "django-templates", "django-views" ]
Django Static image File Failed to load resource
39,112,412
<p><strong>FIXED</strong> This was my solution, in the main programs urls.py I had to add these lines.</p> <p>from django.conf import settings from django.conf.urls.static import static</p> <p>urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)</p> <p>I have an model called Item within there...
0
2016-08-23T23:56:44Z
39,112,528
<p>you have:</p> <pre><code>upload_to='items' </code></pre> <p>but:</p> <pre><code>{{ item.img.url }} </code></pre> <p>should that be?</p> <pre><code>{{ items.img.url }} </code></pre>
0
2016-08-24T00:10:44Z
[ "python", "django", "django-models", "django-templates", "django-views" ]
Where (and what) can I find in local Google Chrome sql databses?
39,112,419
<p>I'm trying to work my way through the book "Violent Python", and I'm on chapter 3... The exercise walks you through writing some Python scripts to grab Firefox data from the locally stored sql dbs - cool stuff! But now I want to see if I can do the same for Chrome. I've seen on some websites that I should be able...
-1
2016-08-23T23:57:19Z
39,112,640
<p>If you are on windows you'll find the sqlite db for chrome history here:</p> <pre><code>C:\Users\%USERNAME%\AppData\Local\Google\Chrome\User Data\Default\History </code></pre> <p>On Linux:</p> <pre><code>/home/$USER/.config/google-chrome/Default/History </code></pre> <p>On MacOS-X:</p> <pre><code>/Users/$USER/L...
1
2016-08-24T00:25:43Z
[ "python", "sqlite", "google-chrome", "sqlite3" ]
'module' object has no attribute 'TK'
39,112,426
<p>I'm a beginner of learning GUI. </p> <p>My python version is 2.7 and I'm using Windows.</p> <p>I've searched tkinter in folder there is only one python file which is in <code>C:\python27</code>.</p> <p>Here is my code:</p> <pre><code>import Tkinter as tk class Electronic_Signature_User_Program(tk.TK): def ...
-2
2016-08-23T23:58:55Z
39,112,442
<p>In the very first line of code you have <code>TK</code> where it should be <code>Tk</code>.</p>
0
2016-08-24T00:00:50Z
[ "python", "user-interface", "tkinter" ]
How to include non PyPi packages for virtualenv requirements file?
39,112,466
<p>Is there a way to include packages/modules not available through pip in the requirements file so that the project is portable? </p> <p>The default version of lxml seems to have issues with pypy so I need to use a <a href="https://github.com/aglyzov/lxml" rel="nofollow">custom fork</a>. </p> <p>The problem is I nee...
0
2016-08-24T00:02:41Z
39,112,477
<p>You can by using <a href="https://pip.pypa.io/en/latest/user_guide/#id9" rel="nofollow">the listed git packages syntax</a>, you would need to add the following line to your requirements.txt</p> <pre><code>-e git://github.com/aglyzov/lxml.git#egg=lxml </code></pre>
2
2016-08-24T00:04:50Z
[ "python", "pip", "virtualenv", "pypy" ]
TypeError: unsupported operand type(s) for -: 'str' and 'str'?
39,112,489
<p>I'm new to programming and can't figure out how to fix this error:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "/Users/aubreyoleary/Documents/Cashier.py", line 31, in &lt;module&gt; changePennies = int((amountReceived - amountDue) * 100) TypeError: unsupported...
0
2016-08-24T00:06:26Z
39,112,505
<p>That mean '6' - '4' won't work because they are both strings. You first need to convert the string values to numbers:</p> <pre><code>changePennies = int(round((float(amountReceived) - float(amountDue)) * 100, 0)) </code></pre>
1
2016-08-24T00:08:45Z
[ "python", "python-3.x" ]
TypeError: unsupported operand type(s) for -: 'str' and 'str'?
39,112,489
<p>I'm new to programming and can't figure out how to fix this error:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "/Users/aubreyoleary/Documents/Cashier.py", line 31, in &lt;module&gt; changePennies = int((amountReceived - amountDue) * 100) TypeError: unsupported...
0
2016-08-24T00:06:26Z
39,112,512
<p>It is because data type of <code>amountReceived</code> and <code>amountDue</code> is string. You have to typecast it to <code>float</code> before you perform arithematic <code>-</code> operation.</p> <p>Instead of <code>int((amountReceived - amountDue) * 100)</code>, use:</p> <pre><code>changePennies = int(float(a...
0
2016-08-24T00:09:21Z
[ "python", "python-3.x" ]
How to write list to csv, with each item on a new row
39,112,491
<p>I am having trouble writing a list of items into a csv file, with each item being on a new row. Here is what I have, it does what I want, except it is putting each letter on a new row...</p> <pre><code>import csv data = ['First Item', 'Second Item', 'Third Item'] with open('output.csv', 'w', newline='') as csv...
0
2016-08-24T00:06:41Z
39,112,550
<p>Use a nested list: <code>writer.writerows([[i]])</code>. Explanation from <a href="http://stackoverflow.com/questions/14134237/writing-data-from-a-python-list-to-csv-row-wise">writing data from a python list to csv row-wise</a>:</p> <blockquote> <p><code>.writerow</code> takes an iterable and uses each element of...
2
2016-08-24T00:13:33Z
[ "python", "csv" ]
Jupyter iPython Notebook and Command Line yield different results
39,112,504
<p>I have the following Python 2.7 code: </p> <pre><code>def average_rows2(mat): ''' INPUT: 2 dimensional list of integers (matrix) OUTPUT: list of floats Use map to take the average of each row in the matrix and return it as a list. Example: &gt;&gt;&gt; average_rows2([[4, 5, 2, 8], [3, ...
1
2016-08-24T00:08:44Z
39,112,581
<p>It seems like your command line is running Python 3. The builtin <code>map</code> returns a list in Python 2, but an iterator (a <code>map</code> object) in Python 3. To turn the latter into a list, apply the <code>list</code> constructor to it:</p> <pre><code># Python 2 average_rows2([[4, 5, 2, 8], [3, 9, 6, 7]]) ...
5
2016-08-24T00:16:38Z
[ "python" ]
For Loop at Python
39,112,509
<p>My goal is to create a for-loop code that will return an output like the following:</p> <pre><code>list(indicator.values())[0], list(indicator.values())[1], list(indicator.values())[2], list(indicator.values())[3], ... ... list(indicator.values())[98], list(indicator.values())[99], </code></pre> <p>However when I ...
-3
2016-08-24T00:09:11Z
39,112,569
<p>Use <code>range()</code> with <code>for</code> to iterate it from 0 to 100. For example:</p> <pre><code>for i in range(100): print i # prints number from 1 to 100 </code></pre>
0
2016-08-24T00:15:56Z
[ "python", "for-loop" ]
For Loop at Python
39,112,509
<p>My goal is to create a for-loop code that will return an output like the following:</p> <pre><code>list(indicator.values())[0], list(indicator.values())[1], list(indicator.values())[2], list(indicator.values())[3], ... ... list(indicator.values())[98], list(indicator.values())[99], </code></pre> <p>However when I ...
-3
2016-08-24T00:09:11Z
39,112,575
<p>read this <a href="http://pythoncentral.io/pythons-range-function-explained/" rel="nofollow">document</a></p> <p>and try this code</p> <pre><code>x = range(0,100) for item in x: list(indicator.values())[item] </code></pre>
0
2016-08-24T00:16:13Z
[ "python", "for-loop" ]
For Loop at Python
39,112,509
<p>My goal is to create a for-loop code that will return an output like the following:</p> <pre><code>list(indicator.values())[0], list(indicator.values())[1], list(indicator.values())[2], list(indicator.values())[3], ... ... list(indicator.values())[98], list(indicator.values())[99], </code></pre> <p>However when I ...
-3
2016-08-24T00:09:11Z
39,112,595
<p>Use this code:</p> <pre><code>x = 100 for item in range(x): print(list(indicator.values())[item])] </code></pre>
3
2016-08-24T00:19:12Z
[ "python", "for-loop" ]
For Loop at Python
39,112,509
<p>My goal is to create a for-loop code that will return an output like the following:</p> <pre><code>list(indicator.values())[0], list(indicator.values())[1], list(indicator.values())[2], list(indicator.values())[3], ... ... list(indicator.values())[98], list(indicator.values())[99], </code></pre> <p>However when I ...
-3
2016-08-24T00:09:11Z
39,113,909
<p>For -- in -- is python's way of iterating (going through) something iterable (something that can be gone through). For example a list and a dictionary are iterable. The range function creates <strong>a list</strong> with given parameters, making an integer (which is not itself iterable) iterable. </p>
0
2016-08-24T03:26:39Z
[ "python", "for-loop" ]
Python is not recognizing text file that is in the same directory?
39,112,522
<p>My current project tree:</p> <pre><code>redditbot/ -- commands/ ----__init__.py ----comment_cache.txt ----readcomments.py --mainbot.py </code></pre> <p>What I am attempting to do is read the comment_cache.txt file via <code>open('comment_cache.txt')</code>in the readcomments.py file., but for some reas...
-1
2016-08-24T00:10:13Z
39,114,145
<p>I am assuming that <code>mainbot.py</code> is the entry point from where you run your application, so </p> <p><strong>Problem I</strong></p> <p>based on your project tree, the file should be available at path</p> <pre><code>open('commands/comment_cache.txt') </code></pre> <p><strong>Problem II</strong></p> <blo...
0
2016-08-24T03:53:53Z
[ "python", "python-3.x", "relative-path", "reddit", "praw" ]
Django Form Not updating
39,112,555
<p>I'm trying to update a form in Django. I have the following: </p> <p><strong>models.py</strong></p> <pre><code>from django.db import models from django.core.urlresolvers import reverse class List(models.Model): def get_absolute_url(self): return reverse('view_list', args=[self.id]) # Create your mode...
0
2016-08-24T00:13:57Z
39,112,700
<p>I'm assuming you are saying that you don't see the changes in your browser. So i suggest you clear your browser's cache and reload the page. If you go to the manage section of the browser developer tools and select the option to not store cache when dev tools is activated. Cache can be a pain when you forget it exis...
1
2016-08-24T00:34:54Z
[ "python", "django", "forms", "refresh" ]
.build_release/lib/libcaffe.so: undefined reference to `boost::python::import(boost::python::str)'
39,112,578
<p>I get this error with Python2.7 and Ubuntu15.10:</p> <pre><code>jalal@klein:~/computer_vision/py-faster-rcnn/caffe-fast-rcnn$ make -j8 &amp;&amp; make pycaffe CXX/LD -o .build_release/tools/compute_image_mean.bin CXX/LD -o .build_release/tools/upgrade_net_proto_binary.bin CXX/LD -o .build_release/tools/convert_ima...
1
2016-08-24T00:16:28Z
39,129,554
<p>Installing Boost from the source worked for me! After downloading the Boost source code from its official website:</p> <pre><code>sudo ./bootstrap.sh --prefix=/usr/local ./b2 sudo ./b2 install </code></pre>
1
2016-08-24T17:26:47Z
[ "python", "c++", "ubuntu", "boost", "caffe" ]
How do I set TensorFlow RNN state when state_is_tuple=True?
39,112,622
<p>I have written an <a href="https://github.com/wpm/tfrnnlm" rel="nofollow">RNN language model using TensorFlow</a>. The model is implemented as an <code>RNN</code> class. The graph structure is built in the constructor, while <code>RNN.train</code> and <code>RNN.test</code> methods run it.</p> <p>I want to be able t...
1
2016-08-24T00:22:34Z
39,917,340
<p>One problem with a Tensorflow placeholder is that you can only feed it with a Python list or Numpy array (I think). So you can't save the state between runs in tuples of LSTMStateTuple. </p> <p>I solved this by saving the state in a tensor like this</p> <p><code>initial_state = np.zeros((num_layers, 2, batch_size,...
2
2016-10-07T12:29:24Z
[ "python", "machine-learning", "tensorflow" ]
Save line in file to list
39,112,645
<pre><code>file = input('Name: ') with open(file) as infile: for line in infile: for name in infile: name print(name[line]) </code></pre> <p>So if a user were to pass a file of vertical list of sentences, how would I save each sentence to its own list?</p> <p>Sample input:</p> <p...
4
2016-08-24T00:26:49Z
39,112,738
<p>I think this is what you need:</p> <pre><code>with open(file) as infile: for line in infile.readlines(): print [line] # list of all the lines in the file as list </code></pre> <p>If the content of file is as:</p> <pre><code>hi hello cat dog </code></pre> <p>It will <code>print</code>:</p> <...
0
2016-08-24T00:40:59Z
[ "python", "python-3.x" ]
Save line in file to list
39,112,645
<pre><code>file = input('Name: ') with open(file) as infile: for line in infile: for name in infile: name print(name[line]) </code></pre> <p>So if a user were to pass a file of vertical list of sentences, how would I save each sentence to its own list?</p> <p>Sample input:</p> <p...
4
2016-08-24T00:26:49Z
39,112,753
<pre><code>sentence_lists = [] with open('file') as f: for s in f: sentence_lists.append([s.strip()]) </code></pre> <p><hr> simplified as per <code>idjaw</code>:</p> <pre><code>with open('file') as f: sentence_list = [[s.strip()] for s in f] </code></pre>
3
2016-08-24T00:43:12Z
[ "python", "python-3.x" ]
Save line in file to list
39,112,645
<pre><code>file = input('Name: ') with open(file) as infile: for line in infile: for name in infile: name print(name[line]) </code></pre> <p>So if a user were to pass a file of vertical list of sentences, how would I save each sentence to its own list?</p> <p>Sample input:</p> <p...
4
2016-08-24T00:26:49Z
39,112,767
<pre><code>&gt;&gt;&gt; [line.split() for line in open('File.txt')] [['hi'], ['hello'], ['cat'], ['dog']] </code></pre> <p>Or, if we want to be more careful about making sure that the file is closed:</p> <pre><code>&gt;&gt;&gt; with open('File.txt') as f: ... [line.split() for line in f] ... [['hi'], ['hello'], [...
6
2016-08-24T00:45:36Z
[ "python", "python-3.x" ]
Can I create a new column based on when the value changes in another column?
39,112,689
<p>Let s say I have this <code>df</code></p> <pre><code>print(df) DATE_TIME A B 0 10/08/2016 12:04:56 1 5 1 10/08/2016 12:04:58 1 6 2 10/08/2016 12:04:59 2 3 3 10/08/2016 12:05:00 2 2 4 10/08/2016 12:05:01 3 4 5 10/08/2016 12:05:02 3 6 6 10/08/2016 12:05:03 1 3 7 10/08/201...
3
2016-08-24T00:33:07Z
39,112,754
<p>You can use the <em>shift-cumsum</em> pattern.</p> <pre><code>df['C'] = (df.A != df.A.shift()).cumsum() &gt;&gt;&gt; df DATE_TIME A B C 0 10/08/2016 12:04:56 1 5 1 1 10/08/2016 12:04:58 1 6 1 2 10/08/2016 12:04:59 2 3 2 3 10/08/2016 12:05:00 2 2 2 4 10/08/2016 12:05:01 3 4 ...
5
2016-08-24T00:43:30Z
[ "python", "pandas", "uniqueidentifier" ]
Volume Slider using Tkinter
39,112,692
<p>I'm new to coding, and I am attempting to create a juke box for a school project, but I'm struggling to create a slider that will edit the volume. I'm just unsure where to start to get the volume to actually change as I move the slider. I'm using VLC lib. </p> <pre><code>import vlc import random from tkinter import...
0
2016-08-24T00:33:28Z
39,113,802
<p>Set the <code>command</code> parameter when creating the <code>Scale</code> widget:</p> <pre><code>def set_volume(v): global vol global player # either get the new volume from given argument v (type: str): # value = int(v) # or get it directly from Scale widget (type: int) value = vol.get() ...
0
2016-08-24T03:11:50Z
[ "python", "tkinter", "python-3.5" ]
Volume Slider using Tkinter
39,112,692
<p>I'm new to coding, and I am attempting to create a juke box for a school project, but I'm struggling to create a slider that will edit the volume. I'm just unsure where to start to get the volume to actually change as I move the slider. I'm using VLC lib. </p> <pre><code>import vlc import random from tkinter import...
0
2016-08-24T00:33:28Z
39,118,051
<p>My mate was able to help me with this by simply adding self in the required paramaters of the function, no clue why it helps and thanks everyone for trying, much appreciated. </p> <pre><code>def show_value(self): global player i = vol.get() player.audio_set_volume(i) vol = Scale(window,from_ = 0,to = 1...
0
2016-08-24T08:21:51Z
[ "python", "tkinter", "python-3.5" ]
Python script fails using launchd and Selenium
39,112,707
<p>I'm trying to run a simple script using launchd in OS X 10.10.5 but the job fails. I think it has something to do with permissions/privileges not set correctly?</p> <p>This is the error code it throws up:</p> <blockquote> <p>Traceback (most recent call last): File "/Users/John/Documents/AutoRun/OpenTwitter.p...
1
2016-08-24T00:35:50Z
39,136,015
<p>I've managed to get it to work by putting the geckodriver in /usr/bin </p> <ol> <li>Move the file to /usr/bin directory: sudo mv chromedriver /usr/bin</li> <li>Goto /usr/bin directory and you would need to run something like "chmod a+x geckodriver" to mark it executable.</li> </ol> <p>I think it was having trouble...
0
2016-08-25T02:59:21Z
[ "python", "python-2.7", "selenium", "launchd", "selenium-firefoxdriver" ]
How To Make a Window in Python without GUI toolkits
39,112,734
<p>I'm curious, as making a window with Tkinter really does seem to easy. Does Python have an alert thing similar to javascript by default?</p>
-2
2016-08-24T00:40:34Z
39,124,747
<p>There is no graphical alert in python. Tkinter is the default python GUI interface. If all you need is an alert, that's less than a dozen lines of code. Here's a python 3 example:</p> <pre><code>import tkinter as tk import tkinter.messagebox def alert(message): root = tk.Tk() root.withdraw() tkinter.me...
1
2016-08-24T13:30:30Z
[ "python", "user-interface" ]
Python program fails on Windows but not on Linux
39,112,761
<p>The program below triggers a UnicodeEncodeError on my Windows 10 machine (running Python 3.5.2) but no error at all on my Linux machine (running Python 3.3.2).</p> <pre><code>#!/usr/bin/python import logging str ="Antonín Dvořák" logging.basicConfig(filename='log.txt', level=logging.INFO) logging.info(str) </cod...
4
2016-08-24T00:44:22Z
39,112,928
<p>Instead of a file name, you could pass a stream whose encoding is specified:</p> <pre><code>logging.basicConfig( stream=open('log.txt', 'w', encoding='utf-8'), level=logging.INFO ) </code></pre> <p>As for the cause, it's probably trying to open the target file using your current locale's encoding (CP1252, ...
3
2016-08-24T01:09:52Z
[ "python", "python-3.x" ]
Python program fails on Windows but not on Linux
39,112,761
<p>The program below triggers a UnicodeEncodeError on my Windows 10 machine (running Python 3.5.2) but no error at all on my Linux machine (running Python 3.3.2).</p> <pre><code>#!/usr/bin/python import logging str ="Antonín Dvořák" logging.basicConfig(filename='log.txt', level=logging.INFO) logging.info(str) </cod...
4
2016-08-24T00:44:22Z
39,112,951
<p>Theh default encoding of Windows (cp1252 in your case) is different from Linux (usually utf8), so you have to specify the encoding you want.</p> <p>Below didn't work in Python 3.3 (still used cp1252) but did with 3.5 so it looks like a bug in 3.3. I used <code>utf-8-sig</code> because many Windows text editors def...
4
2016-08-24T01:12:55Z
[ "python", "python-3.x" ]
Removing every third item from list
39,112,805
<p>I want to remove every 3rd item from list. For Example:</p> <pre><code>list1 = list(['a','b','c','d','e','f','g','h','i','j']) </code></pre> <p>After removing indexes which are multiple of three the list will be:</p> <pre><code>['a','b','d','e','g','h','j'] </code></pre> <p>How can I achieve this?</p>
-3
2016-08-24T00:51:18Z
39,112,824
<pre><code>[v for i, v in enumerate(list1) if (i + 1) % 3 != 0] </code></pre> <p>It seems like you want the third item in the list, which is actually at index 2, gone. This is what the <code>+1</code> is for.</p>
1
2016-08-24T00:53:19Z
[ "python" ]
Removing every third item from list
39,112,805
<p>I want to remove every 3rd item from list. For Example:</p> <pre><code>list1 = list(['a','b','c','d','e','f','g','h','i','j']) </code></pre> <p>After removing indexes which are multiple of three the list will be:</p> <pre><code>['a','b','d','e','g','h','j'] </code></pre> <p>How can I achieve this?</p>
-3
2016-08-24T00:51:18Z
39,112,837
<p>You may use <code>enumerate()</code>:</p> <pre><code>&gt;&gt;&gt; x = ['a','b','c','d','e','f','g','h','i','j'] &gt;&gt;&gt; [i for j, i in enumerate(x) if (j+1)%3] ['a', 'b', 'd', 'e', 'g', 'h', 'j'] </code></pre> <p><em>Alternatively</em>, you may create the copy of list and delete the values at interval. For ex...
6
2016-08-24T00:55:00Z
[ "python" ]
How to patch method io.RawIOBase.read with unittest?
39,112,854
<p>I've recently learned about <code>unittest.monkey.patch</code> and its variants, and I'd like to use it to unit test for atomicity of a file read function. However, the patch doesn't seem to have any effect.</p> <p>Here's my set-up. The method under scrutiny is roughly like so (abriged):</p> <pre><code>#local_stor...
0
2016-08-24T00:58:45Z
39,183,945
<p>I've finally found a solution myself.</p> <p>The problem is that <code>mock</code> can't mock any methods of objects that are written in C. One of these is the <code>RawIOBase</code> that I was encountering.</p> <p>So indeed the solution was to mock <code>open</code> to return a wrapper around <code>RawIOBase</cod...
0
2016-08-27T17:36:05Z
[ "python", "unit-testing", "mocking", "monkeypatching", "python-unittest.mock" ]
How to find the number of ways to get 21 in Blackjack?
39,112,897
<p>Some assumptions: </p> <ol> <li>One deck of 52 cards is used</li> <li>Picture cards count as 10</li> <li>Aces count as 1 or 11</li> <li>The order is not important (ie. Ace + Queen is the same as Queen + Ace)</li> </ol> <p>I thought I would then just sequentially try all the possible combinations and see which ones...
3
2016-08-24T01:04:57Z
39,113,041
<p>divide and conquer by leveraging the knowledge that if you have 13 and pick a 10 you only have to pick cards to sum to 3 left to look at ... be forwarned this solution might be slow(took about 180 seconds on my box... it is definately non-optimal) ..</p> <pre><code>def sum_to(x,cards): if x == 0: # if there is ...
4
2016-08-24T01:24:25Z
[ "python", "oop", "combinations", "blackjack", "playing-cards" ]
How to find the number of ways to get 21 in Blackjack?
39,112,897
<p>Some assumptions: </p> <ol> <li>One deck of 52 cards is used</li> <li>Picture cards count as 10</li> <li>Aces count as 1 or 11</li> <li>The order is not important (ie. Ace + Queen is the same as Queen + Ace)</li> </ol> <p>I thought I would then just sequentially try all the possible combinations and see which ones...
3
2016-08-24T01:04:57Z
39,113,661
<p>Before worrying about the suits and different cards with value <code>10</code> lets figure out how many different value combinations resulting to <code>21</code> there are. For example <code>5, 5, 10, 1</code> is one such combination. The following function takes in <code>limit</code> which is the target value, <cod...
1
2016-08-24T02:52:12Z
[ "python", "oop", "combinations", "blackjack", "playing-cards" ]
How to find the number of ways to get 21 in Blackjack?
39,112,897
<p>Some assumptions: </p> <ol> <li>One deck of 52 cards is used</li> <li>Picture cards count as 10</li> <li>Aces count as 1 or 11</li> <li>The order is not important (ie. Ace + Queen is the same as Queen + Ace)</li> </ol> <p>I thought I would then just sequentially try all the possible combinations and see which ones...
3
2016-08-24T01:04:57Z
39,178,939
<p>So I decided to write the script that every possible viable hand can be checked. The total number comes out to be 188052. Since I checked every possible combination, this is the exact number (as opposed to an estimate):</p> <pre><code>import itertools as it big_list = [] def deck_set_up(m): special = {8:'a2345...
1
2016-08-27T08:09:58Z
[ "python", "oop", "combinations", "blackjack", "playing-cards" ]
Parse hierarchical XML tags
39,112,938
<p>Need to parse hierarchical tags from XML and get the tag's value in desired output</p> <p><strong>Input</strong></p> <pre><code>&lt;doc&gt; &lt;pid id="231"&gt; &lt;label key=""&gt;Electronics&lt;/label&gt; &lt;desc/&gt; &lt;cid id="122"&gt; &lt;label key=""&gt;TV&lt;/label&gt; ...
0
2016-08-24T01:10:23Z
39,113,929
<p>We are going to use 3 pieces: find all of the elements in the order in which they occur, get the depth of each one, build a bread crumb based on the depth and order.</p> <pre><code>from lxml import etree xml = etree.fromstring(xml_str) elems = xml.xpath(r'//label') #xpath expression to find all '&lt;label ...&gt; ...
2
2016-08-24T03:28:21Z
[ "python", "xml", "xml-parsing", "ipython" ]
Django isn't serving static files
39,112,961
<p>I'm working with an existing (and previously functional) Django site. We recently upgraded from Django 1.8.13 to 1.10 and our WSGI is Gunicorn. It works fine when hosted from my development machine, but when deployed, all static resources (on the admin and the main site) yield 404's with the message, <code>Directory...
0
2016-08-24T01:14:06Z
39,113,150
<p>Try to change os.path.join(PROJECT_DIR, '../static') to os.path.join(PROJECT_DIR, 'static') and STATIC_ROOT = os.path.join(PROJECT_DIR, '../static_resources') to STATIC_ROOT = os.path.join(PROJECT_DIR, 'static_resources'). It will solve your problem.</p>
0
2016-08-24T01:40:37Z
[ "python", "django", "web", "static", "resources" ]
Django isn't serving static files
39,112,961
<p>I'm working with an existing (and previously functional) Django site. We recently upgraded from Django 1.8.13 to 1.10 and our WSGI is Gunicorn. It works fine when hosted from my development machine, but when deployed, all static resources (on the admin and the main site) yield 404's with the message, <code>Directory...
0
2016-08-24T01:14:06Z
39,114,105
<p>Django does not serve static files in production mode (DEBUG=False). On a production deployment that's the job of the webserver. To resolve the problem:</p> <ul> <li>run <code>python manage.py collectstatic</code></li> <li>in your web server configuration point the <code>/static</code> folder to the static folder o...
1
2016-08-24T03:48:43Z
[ "python", "django", "web", "static", "resources" ]
Django isn't serving static files
39,112,961
<p>I'm working with an existing (and previously functional) Django site. We recently upgraded from Django 1.8.13 to 1.10 and our WSGI is Gunicorn. It works fine when hosted from my development machine, but when deployed, all static resources (on the admin and the main site) yield 404's with the message, <code>Directory...
0
2016-08-24T01:14:06Z
39,132,796
<p>The answer was very subtle. When I upgraded Django to 1.9 and ran the server, it gave the following warning:</p> <p><code>?: (urls.W001) Your URL pattern '^static/(?P&lt;path&gt;.*)$' uses include with a regex ending with a '$'. Remove the dollar from the regex to avoid problems including URLs.</code></p> <p>In <c...
0
2016-08-24T20:49:24Z
[ "python", "django", "web", "static", "resources" ]
removing rows with any column containing NaN, NaTs, and nans
39,112,973
<p>Currently I have data as below:</p> <pre><code>df_all.head() Out[2]: Unnamed: 0 Symbol Date Close Weight 0 4061 A 2016-01-13 36.515889 (0.000002) 1 4062 AA 2016-01-14 36.351784 0.000112 2 4063 AAC 2016-01-15 36.351784 (0.000004) 3 4064 AAL 2...
3
2016-08-24T01:15:45Z
39,113,037
<p>You can use</p> <pre><code>df_all.replace({'nan': None})[~pd.isnull(df_all).any(axis=1)] </code></pre> <p>This is because <code>isnull</code> recognizes both <code>NaN</code> and <code>NaT</code> as "null" values. </p>
3
2016-08-24T01:24:12Z
[ "python", "pandas", "dataframe", null ]
removing rows with any column containing NaN, NaTs, and nans
39,112,973
<p>Currently I have data as below:</p> <pre><code>df_all.head() Out[2]: Unnamed: 0 Symbol Date Close Weight 0 4061 A 2016-01-13 36.515889 (0.000002) 1 4062 AA 2016-01-14 36.351784 0.000112 2 4063 AAC 2016-01-15 36.351784 (0.000004) 3 4064 AAL 2...
3
2016-08-24T01:15:45Z
39,113,201
<p>Since, the symbol '<code>nan'</code> is not caught by <code>dropna()</code> or <code>isnull()</code>. You need to cast the symbol<code>'nan'</code> as <code>np.nan</code></p> <p>Try this:</p> <pre><code> df["symbol"] = np.where(df["symbol"]=='nan',np.nan, df["symbol"] ) df.dropna() </code></pre>
0
2016-08-24T01:48:23Z
[ "python", "pandas", "dataframe", null ]
Unique items in list of sets
39,112,992
<p>If I have list of sets:</p> <pre><code>&gt;&gt;&gt; lst = [{1, 2}, {0, 1}, {1, 2}] </code></pre> <p>How to return unique items?</p> <p>Trying well known <code>set()</code> does not work:</p> <pre><code>&gt;&gt;&gt; set(lst) TypeError: unhashable type: 'set' </code></pre>
-1
2016-08-24T01:18:30Z
39,113,013
<p>You may achieve this by:</p> <pre><code>&gt;&gt;&gt; lst = [{1, 2}, {0, 1}, {1, 2}] &gt;&gt;&gt; set(frozenset(s) for s in lst) set([frozenset([1, 2]), frozenset([0, 1])]) </code></pre> <p>Check <a href="https://docs.python.org/2.4/lib/types-set.html" rel="nofollow">Frozen Set</a> document for more information....
0
2016-08-24T01:21:20Z
[ "python" ]
Unique items in list of sets
39,112,992
<p>If I have list of sets:</p> <pre><code>&gt;&gt;&gt; lst = [{1, 2}, {0, 1}, {1, 2}] </code></pre> <p>How to return unique items?</p> <p>Trying well known <code>set()</code> does not work:</p> <pre><code>&gt;&gt;&gt; set(lst) TypeError: unhashable type: 'set' </code></pre>
-1
2016-08-24T01:18:30Z
39,113,025
<p>If by "unique items" you mean unique sets, you could just use <code>frozenset</code>, which is a hashable but immutable version of <code>set</code>. You could either build your sets as <code>frozenset</code> objects initially, or if you need to mutate them, do something like:</p> <pre><code>uniques = set(frozenset(...
2
2016-08-24T01:22:46Z
[ "python" ]
Unique items in list of sets
39,112,992
<p>If I have list of sets:</p> <pre><code>&gt;&gt;&gt; lst = [{1, 2}, {0, 1}, {1, 2}] </code></pre> <p>How to return unique items?</p> <p>Trying well known <code>set()</code> does not work:</p> <pre><code>&gt;&gt;&gt; set(lst) TypeError: unhashable type: 'set' </code></pre>
-1
2016-08-24T01:18:30Z
39,113,053
<pre><code>def get_unique_sets(l): unique_sets = [] for s in l: if s not in unique_sets: unique_sets.append(s) return unique_sets lst = [{1, 2}, {0, 1}, {1, 2}] print(get_unique_sets(lst)) </code></pre> <p><strong>Output</strong></p> <pre><code>[{1, 2}, {0, 1}] </code></pre>
0
2016-08-24T01:26:41Z
[ "python" ]
Unique items in list of sets
39,112,992
<p>If I have list of sets:</p> <pre><code>&gt;&gt;&gt; lst = [{1, 2}, {0, 1}, {1, 2}] </code></pre> <p>How to return unique items?</p> <p>Trying well known <code>set()</code> does not work:</p> <pre><code>&gt;&gt;&gt; set(lst) TypeError: unhashable type: 'set' </code></pre>
-1
2016-08-24T01:18:30Z
39,113,054
<pre><code>&gt;&gt;&gt; reduce(lambda a, b: a.union(b), lst) {0, 1, 2} </code></pre> <p><strong>EDIT</strong></p> <p>Given that the OP appears to want unique subsets:</p> <pre><code>&gt;&gt;&gt; set(tuple(sorted(s)) for s in lst) {(0, 1), (1, 2)} </code></pre>
1
2016-08-24T01:26:46Z
[ "python" ]
Unique items in list of sets
39,112,992
<p>If I have list of sets:</p> <pre><code>&gt;&gt;&gt; lst = [{1, 2}, {0, 1}, {1, 2}] </code></pre> <p>How to return unique items?</p> <p>Trying well known <code>set()</code> does not work:</p> <pre><code>&gt;&gt;&gt; set(lst) TypeError: unhashable type: 'set' </code></pre>
-1
2016-08-24T01:18:30Z
39,113,068
<pre><code>In [8]: lst = [{1, 2}, {0, 1}, {1, 2}] In [9]: reduce(set.union, lst) Out[9]: {0, 1, 2} </code></pre> <h3>Edit:</h3> <p>A better version of above:</p> <pre><code>In [1]: lst = [{1, 2}, {0, 1}, {1, 2}] In [2]: set.union(*lst) Out[2]: {0, 1, 2} </code></pre>
2
2016-08-24T01:28:31Z
[ "python" ]
Unique items in list of sets
39,112,992
<p>If I have list of sets:</p> <pre><code>&gt;&gt;&gt; lst = [{1, 2}, {0, 1}, {1, 2}] </code></pre> <p>How to return unique items?</p> <p>Trying well known <code>set()</code> does not work:</p> <pre><code>&gt;&gt;&gt; set(lst) TypeError: unhashable type: 'set' </code></pre>
-1
2016-08-24T01:18:30Z
39,113,192
<p>Do your input list items have to be sets or could they be tuples instead?</p> <p><code>set()</code> works on tuples in my test (py 2.7): </p> <pre><code>&gt;&gt;&gt; lst = [(1,2), (0,1), (1,2)] &gt;&gt;&gt; set(lst) set([(1, 2), (0, 1)]) </code></pre> <p>If your input is always a list of sets, you can just do a t...
0
2016-08-24T01:47:04Z
[ "python" ]
SQLAlchemy - override orm.Query.count for a database without subselect
39,113,016
<p>I am using sqlalchemy with a database that doesn't support subselects. What that means is that something like this wouldn't work (where <code>Calendar</code> is a model inheriting a declarative base):</p> <pre><code> Calendar.query.filter(uuid=uuid).count() </code></pre> <p>I am trying to override the <code>count...
0
2016-08-24T01:21:54Z
39,165,945
<p>From the SQLAlchemy documentation:</p> <blockquote> <p>For fine grained control over specific columns to count, to skip the usage of a subquery or otherwise control of the FROM clause, or to use other aggregate functions, use func expressions in conjunction with query(), i.e.:</p> </blockquote> <pre><code>from s...
0
2016-08-26T12:06:38Z
[ "python", "sqlalchemy", "crate" ]
Pymel: How do I extract these vector floats from a complex .TXT file?
39,113,050
<p>I am having trouble wrapping my head around how I would extract the float values from a complex text file in Pymel. I am not a programmer, I am an artist, however I am in need of creating a script for a specific workflow process and I have a beginner level knowledge of python.</p> <p>My goal: to create objects in 3...
0
2016-08-24T01:25:50Z
39,113,119
<p>First, you probably do not want to be splitting on that massive string of spaces. In fact what you almost certainly want is to just use <code>line.split()</code> with no arguments, as this will split apart all text on any kind, and any amount, of whitespace. i.e:</p> <pre><code>&gt;&gt;&gt; 'A B C\t\n\t D'.s...
0
2016-08-24T01:35:06Z
[ "python", "vector", "pymel" ]