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
Max recursion is not exactly what sys.getrecursionlimit() claims. How come?
38,265,839
<p>I've made a small function that will actually measure the max recursion limit:</p> <pre><code>def f(x): r = x try: r = f(x+1) except Exception as e: print(e) finally: return r </code></pre> <p>To know what to expect I've checked:</p> <pre><code>In [28]: import sys In [29]:...
27
2016-07-08T11:47:43Z
38,270,837
<p>I believe the confusion originates from the difference between the stack size you see when the error occurs and the limit. The thing is that the last call, that caused the crash, likely accounts for more than 1 frame for the stack, because it itself makes some function calls. And by the time you catch the exception,...
5
2016-07-08T15:52:08Z
[ "python", "recursion" ]
Implementing a queue for a digicode-like system
38,266,153
<p>I have a system with <code>QPushButtons</code> that is to work like a digicode doors. Each button has an ID (integer). When the last buttons you have pushed correspond to a given password, things happen (like the doors gets open).</p> <p>I'm thinking of using a queue to implement this, with a pointer to the last va...
2
2016-07-08T12:02:13Z
38,266,154
<p>The key is to read the password backwards, starting from the last value added. Check for each character/number in the password if it is correct. If you can read the password until the end, you're good. Here is what I'd go with :</p> <pre><code> def checkCorrect(self, password): pw = list(reversed(passwor...
2
2016-07-08T12:02:13Z
[ "python", "python-2.7", "queue", "pyside" ]
Multiple non-conjunctive conditions for list comprehension
38,266,165
<p>I have a list of 4-tuples. I want to check if it has at least one tuple with its 3rd element is equal to 'JJ' and at least one tuple with its 4th element is equal to 'nsubj'. However, these don't necessarily have to be the same tuple.</p> <p>So doing something like -</p> <pre><code>if (any([tup for tup in parse_tr...
2
2016-07-08T12:03:04Z
38,266,669
<p>You could group all 3rd and 4th elements from the tuples in the list into new tuples in another list using <code>zip</code> and then check for the elements directly from these new tuples:</p> <pre><code># say lst is your original list new_lst = zip(*lst) if 'JJ' in new_lst[2] and 'nsubj' in new_lst[3]: # your...
1
2016-07-08T12:27:30Z
[ "python", "list" ]
Multiple non-conjunctive conditions for list comprehension
38,266,165
<p>I have a list of 4-tuples. I want to check if it has at least one tuple with its 3rd element is equal to 'JJ' and at least one tuple with its 4th element is equal to 'nsubj'. However, these don't necessarily have to be the same tuple.</p> <p>So doing something like -</p> <pre><code>if (any([tup for tup in parse_tr...
2
2016-07-08T12:03:04Z
38,266,729
<p>I can't think of a purely boolean plus <code>any/all</code> solution to this. Without primitives, you can solve this with a custom comparison object that keeps state.</p> <pre><code>class MultiComp(object): def __init__(self, *conditions): self._conditions = conditions self._results = [False] * ...
1
2016-07-08T12:30:27Z
[ "python", "list" ]
Multiple non-conjunctive conditions for list comprehension
38,266,165
<p>I have a list of 4-tuples. I want to check if it has at least one tuple with its 3rd element is equal to 'JJ' and at least one tuple with its 4th element is equal to 'nsubj'. However, these don't necessarily have to be the same tuple.</p> <p>So doing something like -</p> <pre><code>if (any([tup for tup in parse_tr...
2
2016-07-08T12:03:04Z
38,267,535
<p>Maybe you can do something like using generators(which is more efficient) instead of lists per se. </p> <p>Is there any specific reason you need it to be done with only one list? </p> <pre><code>if any(True for tuple_list in list_of_tuple_lists if any(True for t in tuple_list if t[2]=='JJ') and any(True for t in t...
0
2016-07-08T13:08:00Z
[ "python", "list" ]
Is extending a Python list (e.g. l += [1]) guaranteed to be thread-safe?
38,266,186
<p>If I have an integer <code>i</code>, it is not safe to do <code>i += 1</code> on multiple threads:</p> <pre><code>&gt;&gt;&gt; i = 0 &gt;&gt;&gt; def increment_i(): ... global i ... for j in range(1000): i += 1 ... &gt;&gt;&gt; threads = [threading.Thread(target=increment_i) for j in range(10)] &gt;&gt;&gt;...
21
2016-07-08T12:04:03Z
38,266,364
<p>From <a href="http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm" rel="nofollow">http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm</a> :</p> <blockquote> <p>Operations that replace other objects may invoke those other objects’ <code>__del__</code> metho...
9
2016-07-08T12:13:54Z
[ "python", "multithreading", "thread-safety", "python-multithreading" ]
Is extending a Python list (e.g. l += [1]) guaranteed to be thread-safe?
38,266,186
<p>If I have an integer <code>i</code>, it is not safe to do <code>i += 1</code> on multiple threads:</p> <pre><code>&gt;&gt;&gt; i = 0 &gt;&gt;&gt; def increment_i(): ... global i ... for j in range(1000): i += 1 ... &gt;&gt;&gt; threads = [threading.Thread(target=increment_i) for j in range(10)] &gt;&gt;&gt;...
21
2016-07-08T12:04:03Z
38,320,815
<p>There isn't a happy ;-) answer to this. There's nothing guaranteed about any of it, which you can confirm simply by noting that the Python reference manual makes no guarantees about atomicity.</p> <p>In CPython it's a matter of pragmatics. As a snipped part of effbot's article says,</p> <blockquote> <p>In theo...
14
2016-07-12T05:42:11Z
[ "python", "multithreading", "thread-safety", "python-multithreading" ]
Numpy int array: Find indices of multiple target ints
38,266,259
<p>I have a large numpy array (<code>dtype=int</code>) and a set of numbers which I'd like to find in that array, e.g.,</p> <pre><code>import numpy as np values = np.array([1, 2, 3, 1, 2, 4, 5, 6, 3, 2, 1]) searchvals = [3, 1] # result = [0, 2, 3, 8, 10] </code></pre> <p>The <code>result</code> array doesn't have t...
5
2016-07-08T12:07:50Z
38,266,343
<p>Is this fast enough?</p> <pre><code>&gt;&gt;&gt; np.where(np.in1d(values, searchvals)) (array([ 0, 2, 3, 8, 10]),) </code></pre>
5
2016-07-08T12:12:44Z
[ "python", "arrays", "numpy" ]
Numpy int array: Find indices of multiple target ints
38,266,259
<p>I have a large numpy array (<code>dtype=int</code>) and a set of numbers which I'd like to find in that array, e.g.,</p> <pre><code>import numpy as np values = np.array([1, 2, 3, 1, 2, 4, 5, 6, 3, 2, 1]) searchvals = [3, 1] # result = [0, 2, 3, 8, 10] </code></pre> <p>The <code>result</code> array doesn't have t...
5
2016-07-08T12:07:50Z
38,266,533
<p>I would say <a href="http://stackoverflow.com/a/38266343/3293881">using <code>np.in1d</code></a> would be the intuitive solution to solve such a case. Having said that, based on <a href="http://stackoverflow.com/a/34945323/3293881"><code>this solution</code></a> here's an alternative with <a href="http://docs.scipy....
1
2016-07-08T12:21:53Z
[ "python", "arrays", "numpy" ]
Numpy int array: Find indices of multiple target ints
38,266,259
<p>I have a large numpy array (<code>dtype=int</code>) and a set of numbers which I'd like to find in that array, e.g.,</p> <pre><code>import numpy as np values = np.array([1, 2, 3, 1, 2, 4, 5, 6, 3, 2, 1]) searchvals = [3, 1] # result = [0, 2, 3, 8, 10] </code></pre> <p>The <code>result</code> array doesn't have t...
5
2016-07-08T12:07:50Z
38,267,170
<p>Can you avoid numpy all together? List concatenation should be much faster than relying on numpy's methods. This will still work even if <code>values</code> needs to be a numpy array.</p> <pre><code>result = [] for sv in searchvals: result += [i for i in range(len(values)) if values[i] == sv] </code></pre>
0
2016-07-08T12:50:57Z
[ "python", "arrays", "numpy" ]
Pandas.DataFrame slicing with multiple date ranges
38,266,461
<p>I have a datetime-indexed dataframe object with 100,000+ rows. I was wondering if there was a convenient way using pandas to get a subset of this dataframe that is within multiple date ranges.</p> <p>For example, let us say that we have two date ranges: <code>(datetime.datetime(2016,6,27,0,0,0), datetime.datetime(...
0
2016-07-08T12:18:48Z
38,267,232
<p>There are <a href="http://stackoverflow.com/a/29370182/190597">two main ways</a> to slice a DataFrame with a DatetimeIndex by date.</p> <ul> <li><p>by slices: <code>df.loc[start:end]</code>. If there are multiple date ranges, the single slices may be concatenated with <code>pd.concat</code>.</p></li> <li><p>by bool...
1
2016-07-08T12:54:15Z
[ "python", "datetime", "pandas", "dataframe" ]
Pandas.DataFrame slicing with multiple date ranges
38,266,461
<p>I have a datetime-indexed dataframe object with 100,000+ rows. I was wondering if there was a convenient way using pandas to get a subset of this dataframe that is within multiple date ranges.</p> <p>For example, let us say that we have two date ranges: <code>(datetime.datetime(2016,6,27,0,0,0), datetime.datetime(...
0
2016-07-08T12:18:48Z
38,341,083
<p>I feel the best option will be to use the direct checks rather than using loc function:</p> <pre><code>df = df[((df.index &gt;= '2016-6-27') &amp; (df.index &lt;= '2016-6-27 5:00')) | ((df.index &gt;= '2016-6-27 15:00') &amp; (df.index &lt; '2016-6-28'))] </code></pre> <p>It works for me.</p> <p>Major issue ...
0
2016-07-13T01:03:37Z
[ "python", "datetime", "pandas", "dataframe" ]
In SQLAlchemy is it possible to dump and load from a Table (not from a mapped class)?
38,266,556
<hr> <p><strong>TL;DR</strong> Using <a href="http://sqlalchemy.org" rel="nofollow">SQLAlchemy</a> is it possible to do a <a href="http://docs.sqlalchemy.org/en/rel_1_0/core/serializer.html#sqlalchemy.ext.serializer.dumps" rel="nofollow"><code>dumps(…)</code> and <code>load(…)</code></a> using a <a href="http://do...
0
2016-07-08T12:22:46Z
38,286,861
<p>After @univerio's comments I could better understand the situation and fixed, yay!</p> <p>The thing is that if the SQLAlchemy <code>dumps</code> receives a <code>Table</code> instance, the results are not related to the table, they are purely a <a href="http://docs.sqlalchemy.org/en/rel_1_0/orm/query.html#sqlalchem...
0
2016-07-09T22:24:30Z
[ "python", "sqlalchemy", "pickle" ]
binary search tree impelemntation in python
38,266,638
<p>I am trying to implement binary search tree but facing some problem in node insertion. can any one help me to point out what is wrong in my python program? addChild() function is not adding left child (4, "hans") correctly? is there problem in my recursive function ? thanks in advance.</p> <pre><code>class Node: ...
0
2016-07-08T12:26:34Z
38,267,013
<p>When <code>current is None</code>, you don't actually store the value in the tree but only in a local variable.</p> <p>This way it should work:</p> <pre><code>class BinaryTree: def __init__(self): self.root = None def addChild(self, key, value): current = self.root if current is No...
0
2016-07-08T12:43:07Z
[ "python" ]
Trying to add values in python but comes up with int not callable error
38,266,686
<p>I am trying to add multiple integers from a class in python however it comes up with the error:</p> <blockquote> <p>Traceback (most recent call last): File "G:/documents/Computing/Python/Fighter Game.py", line 53, in if player.health() + player.strength() + player.defence() + player.speed() == ...
0
2016-07-08T12:28:25Z
38,266,752
<p>You have two things that are called <code>self.health</code>; an integer and a method. This doesn't make sense.</p> <p>Instance variables are often prefixed with <code>_</code>, and set up in <code>__init__()</code>, at least this is the "old-school" simple way of doing it:</p> <pre><code>def __init__(self): sel...
4
2016-07-08T12:31:26Z
[ "python", "class", "python-3.x", "int" ]
How to do batch insertion on Neo4J with Python
38,266,707
<p>I have a code that insert many nodes and relationships:</p> <pre><code>from neo4jrestclient.client import GraphDatabase from neo4jrestclient import client import psycopg2 db = GraphDatabase("http://127.0.0.1:7474",username="neo4j", password="1234") conn = psycopg2.connect("\ dbname='bdTrmmTest'\ user='pos...
0
2016-07-08T12:29:05Z
38,268,946
<p>I haven't used Neo4j from Python, but I'm pretty sure the client works the same way as in other languages, and that means your code will generate a lot of distinct HTTP connections, manipulating the low-level node and relationship endpoints. That means lots of latency.</p> <p>It also generates lots of distinct quer...
0
2016-07-08T14:18:36Z
[ "python", "neo4j", "graph-databases", "batch-insert" ]
Creating a closed loop with vtkTubeFilter
38,266,711
<p><strong>What I want</strong>: Specify a set of points, specify the connectivity using <code>vtkCellArray</code> so that it becomes a closed circle, create a <code>vtkPolyData</code> from it and apply the <code>vtkTubeFilter</code> to give it some volume. </p> <p><strong>What I get:</strong> A loop that doesn't conn...
2
2016-07-08T12:29:28Z
38,512,578
<p>The tube filter does not support generating periodic tubes. You should be able to approximate the effect by making the seam (where tubes meet) collinear. So instead of</p> <pre><code>pts = vtk.vtkPoints() pts.SetNumberOfPoints(4) pts.SetPoint(0, 0.5, 0, 0) pts.SetPoint(1, 1, 0.5, 0) pts.SetPoint(2, 0.5, 1, 0) pts.S...
1
2016-07-21T19:13:44Z
[ "python", "python-3.x", "3d", "vtk" ]
Python meta/unpacking in a function
38,266,713
<p>I have a function (func1) that returns a 4-tuple of mixed strings and integers. I want to immediately pass these 4 values into a second function (func2). This is how I am doing it now:</p> <pre><code>var1, var2, var3, var4 = func1(input1) func2(var1, var2, var3, var4) </code></pre> <p>Functions don't unpack tuples...
0
2016-07-08T12:29:32Z
38,266,730
<p>Use the <a href="http://stackoverflow.com/q/2921847/2096752"><code>* operator</code></a>:</p> <pre><code>func2(*func1(input1)) </code></pre>
4
2016-07-08T12:30:27Z
[ "python", "syntax", "meta" ]
Python/Pandas/SKLearn - Writing to original JSON input
38,266,841
<p>I'm quite comfortable with working with Python, but I mostly used Pandas dataframes up until now. For a change, I'll have to work with JSON input now. I've found how I can load it into Python and Pandas <a href="http://stackoverflow.com/questions/35069876/working-with-json-nested-in-json-using-python-pandas">here</a...
0
2016-07-08T12:34:49Z
38,267,185
<p>Are you are trying to append to a json item?</p> <pre><code>data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 } ] print 'DATA:', repr(data) DATA: [{'a': 'A', 'c': 3.0, 'b': (2, 4)}] </code></pre> <p>Say you want to append f:var</p> <pre><code>data[0]['f'] = var print 'JSON', json.dumps(data) JSON:[{'a': 'A', 'c': 3.0, 'b':...
0
2016-07-08T12:51:48Z
[ "python", "json", "pandas" ]
PJLINK response is ambiguos
38,266,953
<p>I am trying to implement PJLINK protocol for my project. I have written a python script that talks over a socket with my projector on an assigned IP address and port no 4352 (default port number for PJLINK protocol) Here is the code snippet:</p> <pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
1
2016-07-08T12:40:20Z
38,568,824
<p>You missed this from the <a href="http://pjlink.jbmia.or.jp/english/data/5-1_PJLink_eng_20131210.pdf" rel="nofollow">PJLink Specifications</a>:</p> <blockquote> <h1>5. Authentication</h1> <h2>5.1. Authentication procedure</h2> <p>To enter into communication with each other using PJLINK commands, both th...
0
2016-07-25T13:15:49Z
[ "python", "sockets" ]
Incorrect square wave sampling using scipy
38,267,021
<p>Trying to plot 2Hz square wave sampled at 4Hz (see attached figure below). Why am I not getting a uniformity for sample encircled red which should IMO be at -1 marked by 2nd red arrow:</p> <p><a href="http://i.stack.imgur.com/e6iQ7.png" rel="nofollow"><img src="http://i.stack.imgur.com/e6iQ7.png" alt="enter image d...
0
2016-07-08T12:43:40Z
38,267,356
<p>That's because of normal floating point imprecision. You are attempting to sample the square wave right at the points where the jumps take place. This will be sensitive to the imprecision of floating point numbers.</p> <p>The value you circled is <code>s2t4[11]</code>, and <code>t4[11]</code> is 2.75. Take a loo...
4
2016-07-08T12:59:15Z
[ "python", "numpy", "matplotlib", "scipy", "signal-processing" ]
PySpark: calculate mean, standard deviation and those values around the mean in one step
38,267,051
<p>My raw data comes in a tabular format. It contains observations from different variables. Each observation with the variable name, the timestamp and the value at that time.</p> <blockquote> <p>Variable [string], Time [datetime], Value [float]</p> </blockquote> <p>The data is stored as Parquet in HDFS and loaded ...
1
2016-07-08T12:45:30Z
38,267,753
<p>This cannot work because when you execute</p> <pre><code>from pyspark.sql.functions import * </code></pre> <p>you shadow built-in <code>abs</code> with <code>pyspark.sql.functions.abs</code> which expects a column not a local Python value as an input.</p> <p>Also UDF you created doesn't handle <code>NULL</code> e...
1
2016-07-08T13:19:35Z
[ "python", "python-2.7", "apache-spark", "pyspark" ]
PySpark: calculate mean, standard deviation and those values around the mean in one step
38,267,051
<p>My raw data comes in a tabular format. It contains observations from different variables. Each observation with the variable name, the timestamp and the value at that time.</p> <blockquote> <p>Variable [string], Time [datetime], Value [float]</p> </blockquote> <p>The data is stored as Parquet in HDFS and loaded ...
1
2016-07-08T12:45:30Z
38,454,271
<p>The solution is to use the DataFrame.aggregateByKey function that aggregates the values per partition and node before shuffling that aggregate around the computing nodes where they are combined to one resulting value. </p> <p>Pseudo-code looks like this. It is inspired by <a href="http://www.learnbymarketing.com/61...
0
2016-07-19T09:16:12Z
[ "python", "python-2.7", "apache-spark", "pyspark" ]
How to write a dataset of Null Terminated Fixed Length Strings with h5py
38,267,076
<p>I have an example in C++ that I'm trying to reproduce using h5py, but it is not working as expected. I'm getting null padded strings with h5py where I expect null terminated strings.</p> <p>Here is my C++ driver...</p> <p><code>main.cpp</code></p> <pre><code>#include &lt;hdf5.h&gt; int main(void) { auto fil...
4
2016-07-08T12:46:35Z
38,428,528
<p><strong>Edit: found solution that works with 'vanilla' h5py below</strong></p> <p>In the h5py source there is the following <a href="https://github.com/h5py/h5py/blob/master/h5py/h5t.pyx#L1355" rel="nofollow">cython code</a>:</p> <pre><code>cdef TypeStringID _c_string(dtype dt): # Strings (fixed-length) cd...
1
2016-07-18T04:17:23Z
[ "python", "h5py" ]
Django save and return object at once (with a custom pk)
38,267,133
<p>I am creating the object of a model using custom create method <code>create_actor</code> like this:</p> <pre><code>class ActorsManager(models.QuerySet): def create_actor(self, email, actortype, locationid, primaryphone, actoruniversalid): actor = self.model(email=email, ...
2
2016-07-08T12:49:04Z
38,267,644
<p>Unless you created your <code>actors</code> table by hand, the <code>ActorID</code> will not automatically be set. Depending on your database backend, <code>None</code> may be treated the same as the empty string, and as such could be a valid primary key. I believe Django takes special measures to update the row i...
0
2016-07-08T13:14:05Z
[ "python", "django", "database", "django-models", "django-queryset" ]
Django save and return object at once (with a custom pk)
38,267,133
<p>I am creating the object of a model using custom create method <code>create_actor</code> like this:</p> <pre><code>class ActorsManager(models.QuerySet): def create_actor(self, email, actortype, locationid, primaryphone, actoruniversalid): actor = self.model(email=email, ...
2
2016-07-08T12:49:04Z
38,301,333
<p>As @knbk pointed out that only an AutoField can set the pk to an object and so the <em>pythonic</em> logic to retrieve the pk is not executed when its not an AutoField and so django doesn't know about it.</p> <p>After searching the django documentation I found an alternative to AutoField for UUIDs,an <a href="https...
0
2016-07-11T07:26:29Z
[ "python", "django", "database", "django-models", "django-queryset" ]
Pandas group data frame and sort by column value
38,267,145
<p>I am trying to group a data frame and sort it at the same time by the absolute value of a certain column.</p> <pre><code> groups values foo bar 75 A 3 1 2 77 B -3 31 34 112 A 4 0 4 129 C 50 5 3 134 C -60 44 5 </code></pre> <p>O...
0
2016-07-08T12:49:45Z
38,267,289
<p><strong>UPDATE2:</strong></p> <pre><code>In [433]: for g,x in grp: .....: print(g, x) .....: A groups values foo bar 112 A 4 0 4 77 A 3 1 2 B groups values foo bar 77 B -3 31 34 C groups values foo bar 134 C -60 44 5 129 ...
2
2016-07-08T12:56:21Z
[ "python", "pandas" ]
Python multiple installations and Ipython
38,267,187
<p>I try to run IPython from my shell</p> <pre><code>milenko@milenko-HP-Compaq-6830s:~$ ipython --pylab Python 2.7.11+ (default, Apr 17 2016, 14:00:29) ImportError: No module named matplotlib </code></pre> <p>I want to double-check</p> <pre><code>conda install matplotlib Fetching package metadata ....... Solving pa...
1
2016-07-08T12:51:49Z
38,267,270
<p>Looks like you're on linux. Assuming you are using bash, open /home/milenko/.bashrc and make sure that /home/milenko/miniconda2/...python.exe (where that is the full path to your python executable) is at the beginning of your path. Otherwise, calling ipython is probably opening a different python environment, whic...
1
2016-07-08T12:55:43Z
[ "python", "ipython" ]
Counting within Pandas apply() function
38,267,210
<p>I'm trying to iterate through a DataFrame and when a value changes, increment a counter, then set a new column equal to that value. I'm able to get this to work using a global counter, like so:</p> <pre><code>def change_ind(row): global prev_row global k if row['rep'] != prev_row: k = k+1 ...
1
2016-07-08T12:53:16Z
38,267,405
<p>You can achieve the same thing using <code>shift</code> and <code>cumsum</code> this will be significantly faster than looping:</p> <pre><code>In [107]: df = pd.DataFrame({'rep':[0,1,1,1,2,3,2,3,4,5,1]}) df Out[107]: rep 0 0 1 1 2 1 3 1 4 2 5 3 6 2 7 3 8 4 9 5 10 1 I...
3
2016-07-08T13:01:20Z
[ "python", "pandas" ]
Use pydbus library to send signal over a Session Bus
38,267,343
<p>I am working with <a href="https://github.com/LEW21/pydbus" rel="nofollow">pydbus</a> and I have already succeed in using it to listen signals on the session bus (on the "client side"). I would like to write the server side now where the program sends a signal everytime an action is triggered (for example when it wr...
0
2016-07-08T12:58:45Z
38,304,616
<p>The class responsible for signals is located in the <a href="https://github.com/LEW21/pydbus/blob/master/pydbus/generic.py" rel="nofollow">generic</a> module. It looks well enough documentated:</p> <pre><code>Static signal object You're expected to set it as a class property:: class A: SomethingHappen...
0
2016-07-11T10:25:30Z
[ "python", "dbus" ]
How to register MultipleModelAPIView?
38,267,427
<p>I use <a href="https://github.com/Axiologue/DjangoRestMultipleModels" rel="nofollow">DjangoRestMultipleModels</a> and try to register my <code>MultipleModelAPIView</code> this way:</p> <pre><code>router = DefaultRouter() router.register(r'category-filter', rest.CategoryFilterViewSet, base_name='category-filter') ur...
2
2016-07-08T13:02:52Z
38,267,640
<p>Get rid of</p> <pre><code>router.register(r'category-filter', rest.CategoryFilterViewSet, base_name='category-filter') </code></pre> <p>and specify</p> <pre><code>urlpatterns = [ ... # your other urls url(r'^category-filter/', rest.CategoryFilterViewSet), ... ] </code></pre> <p>as default route...
1
2016-07-08T13:13:49Z
[ "python", "django", "python-2.7" ]
Using Django ORM query How to annotate if multiple levels of foreign key hierarchy exists
38,267,489
<p>My Django models looks like</p> <pre><code>class Parent(models.Model): name = models.CharField(('name'), max_length=30) class Child(models.Model): parent = models.ForeignKey(Parent) name = models.CharField(('name'), max_length=30) class GrandChild(models.Model): child = models.ForeignKey(Child) ...
1
2016-07-08T13:05:34Z
38,269,577
<p>Try to use <code>distinct</code>:</p> <pre><code>Count('child', distinct=True) </code></pre> <p>More details by link:</p> <p><a href="https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#combining-multiple-aggregations" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#combining-...
1
2016-07-08T14:49:24Z
[ "python", "django", "django-orm", "django-annotate" ]
How to make Celery worker return results from task
38,267,525
<p>How to make <code>celery</code> worker return task results to flask? I have a flask app which calls a task. The task pulls data from database, plots line charts and returns html contents which is rendered on an html page. Without Celery the Flask app works fine and renders line chart on client side, but now I want t...
0
2016-07-08T13:07:24Z
38,270,163
<p>A better solution is simply to let the task run asynchronously using celery like it was intended to be used and use javascript on the page to poll the celery task periodically to see the status. </p> <p>First, when you create your celery task use the bind=True parameter. This allows you to pass <code>self</code> in...
0
2016-07-08T15:17:00Z
[ "python", "flask", "celery" ]
Django-nose test results and coverage not being gathered and displayed in sonar
38,267,543
<p>I have a django project, which is wrapped in a maven build which handles packaging and publishing, as well as generating docs and other lifecycle tasks.</p> <p>We have tests that are executed in django-nose that are exectued at the test phase of the maven lifecycle.</p> <pre><code>NOSE_ARGS = [ '--with-coverage'...
0
2016-07-08T13:08:19Z
38,268,517
<p>Based on your logs, it seems that the report paths are provided as absolute paths. Version 1.5 of the python plugin only accepts relative paths. That's a <a href="https://jira.sonarsource.com/browse/SONARPY-125" rel="nofollow">known limitation</a> which is going to be fixed in version 1.6. This new version is almos...
0
2016-07-08T13:56:51Z
[ "python", "django", "maven", "sonarqube", "code-coverage" ]
How to find an exact sequence of words in lists using Python 3?
38,267,630
<p>I am coding in Python 3 on a Windows platform.</p> <p>I am making a function that will pass in a user's inputted sentence which my function will then <code>.split()</code> and make it a list of each word that was in their original sentence.</p> <p>My function will also pass in a predefined list of word patterns th...
3
2016-07-08T13:13:21Z
38,268,182
<p>Why use sets at all? This is a pretty straightforward string operation:</p> <pre><code>def parse_text(message, keywords): newList = [] for keyword in keywords: if keyword in message: newList.append(keyword) return newList </code></pre> <p>or, using list comprehensions for more ...
2
2016-07-08T13:41:33Z
[ "python", "python-3.x" ]
How to find an exact sequence of words in lists using Python 3?
38,267,630
<p>I am coding in Python 3 on a Windows platform.</p> <p>I am making a function that will pass in a user's inputted sentence which my function will then <code>.split()</code> and make it a list of each word that was in their original sentence.</p> <p>My function will also pass in a predefined list of word patterns th...
3
2016-07-08T13:13:21Z
38,268,259
<p>This can easily be done by transforming your keywords list to a list of lists, and then check for lists which are sublist of your message words.</p> <pre><code>def is_sublist(sub_lst, lst): n = len(sub_lst) return any((sub_lst == lst[i:i + n]) for i in range(len(lst) - n + 1)) message = "Hello world yes an...
1
2016-07-08T13:45:19Z
[ "python", "python-3.x" ]
How to find an exact sequence of words in lists using Python 3?
38,267,630
<p>I am coding in Python 3 on a Windows platform.</p> <p>I am making a function that will pass in a user's inputted sentence which my function will then <code>.split()</code> and make it a list of each word that was in their original sentence.</p> <p>My function will also pass in a predefined list of word patterns th...
3
2016-07-08T13:13:21Z
38,268,265
<p>You could do something like:</p> <pre><code> def parse_text(message, keywords): return [kw for kw in keywords if kw in message] </code></pre>
0
2016-07-08T13:45:37Z
[ "python", "python-3.x" ]
Python Fanspeed Interpolation - Return wrong value
38,267,683
<p>At the moment i'm working with interpolation in python. You have a fan table with temperature and rpm. The input is a temperature and the output the new processed rpm value. I don't get the right value. Can you help me?</p> <pre><code>TABLE = [ (0, 0), (20, 10), (50, 30), (80, 90), (100, 100)] def interPolation(ta...
-1
2016-07-08T13:15:31Z
38,268,049
<p>I don't know what kind of interpolation you are doing but it seems you are trying to do linear interpolation, in that case you are applying a wrong formula here, 1st of all your formula is dimension wise incorrect. I have tried to correct that part, check it gives you the correct ans</p> <pre><code>data = [ (0, 0),...
0
2016-07-08T13:34:39Z
[ "python", "interpolation" ]
Python Fanspeed Interpolation - Return wrong value
38,267,683
<p>At the moment i'm working with interpolation in python. You have a fan table with temperature and rpm. The input is a temperature and the output the new processed rpm value. I don't get the right value. Can you help me?</p> <pre><code>TABLE = [ (0, 0), (20, 10), (50, 30), (80, 90), (100, 100)] def interPolation(ta...
-1
2016-07-08T13:15:31Z
38,268,095
<p>First of all i would suggest <strong>sorting</strong> the table just in case. The sorting would be done inside the function. </p> <p>If you do not sort it and it is provided in let's say <em>reverse</em> or <em>arbitrary</em> order (for whatever reason) your <code>if</code> and <code>elif</code> statements that che...
0
2016-07-08T13:37:27Z
[ "python", "interpolation" ]
How to save json containing dictionary within list into csv using python
38,267,719
<p>I have the following JSON:</p> <pre><code>"item": [ { "id": "3", "num": 0, "name": "de", "leve": { "label": [ "Ini", "Sec", "Coo" ...
-2
2016-07-08T13:17:41Z
38,267,831
<p>Please see <a href="http://stackoverflow.com/questions/1871524/how-can-i-convert-json-to-csv-with-python">this post</a> on the same problem </p> <p>You are going to have a problem with converting because of nested json objects, so you will need to flatten those first and then convert it to CSV </p>
0
2016-07-08T13:23:18Z
[ "python", "json", "csv" ]
How to save json containing dictionary within list into csv using python
38,267,719
<p>I have the following JSON:</p> <pre><code>"item": [ { "id": "3", "num": 0, "name": "de", "leve": { "label": [ "Ini", "Sec", "Coo" ...
-2
2016-07-08T13:17:41Z
38,268,312
<p>Here is the implementation but in your input <code>id 3</code> has a diffrent key <code>leve</code> instaed of <code>leveltip</code>. So i consider that as a wrong entry.</p> <pre><code>import csv file_name = 'out.csv' data = [(item['id'],item['name'],item['num'],item['leveltip']['label'][0],item['leveltip']['effec...
0
2016-07-08T13:47:34Z
[ "python", "json", "csv" ]
Fastest way to compare rows of two pandas dataframes?
38,267,763
<p>So I have two pandas dataframes, A and B. </p> <p>A is 1000 rows x 500 columns, filled with binary values indicating either presence or absence. </p> <p>B is 1024 rows x 10 columns, and is a full iteration of 0's and 1's, hence having 1024 rows.</p> <p>I am trying to find which rows in A, at a particular 10 colum...
2
2016-07-08T13:20:05Z
38,268,560
<p>You can do it in pandas by using loc or ix and telling it to find the rows where the ten columns are all equal. Like this:</p> <pre><code>A.loc[(A[1]==B[1]) &amp; (A[2]==B[2]) &amp; (A[3]==B[3]) &amp; A[4]==B[4]) &amp; (A[5]==B[5]) &amp; (A[6]==B[6]) &amp; (A[7]==B[7]) &amp; (A[8]==B[8]) &amp; (A[9]==B[9]) &amp; (A...
1
2016-07-08T13:59:28Z
[ "python", "pandas" ]
Fastest way to compare rows of two pandas dataframes?
38,267,763
<p>So I have two pandas dataframes, A and B. </p> <p>A is 1000 rows x 500 columns, filled with binary values indicating either presence or absence. </p> <p>B is 1024 rows x 10 columns, and is a full iteration of 0's and 1's, hence having 1024 rows.</p> <p>I am trying to find which rows in A, at a particular 10 colum...
2
2016-07-08T13:20:05Z
38,268,761
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> - output are indexes of <code>B</code>...
2
2016-07-08T14:09:48Z
[ "python", "pandas" ]
Fastest way to compare rows of two pandas dataframes?
38,267,763
<p>So I have two pandas dataframes, A and B. </p> <p>A is 1000 rows x 500 columns, filled with binary values indicating either presence or absence. </p> <p>B is 1024 rows x 10 columns, and is a full iteration of 0's and 1's, hence having 1024 rows.</p> <p>I am trying to find which rows in A, at a particular 10 colum...
2
2016-07-08T13:20:05Z
38,269,622
<p>We can abuse the fact that both dataframes have binary values <code>0</code> or <code>1</code> by collapsing the relevant columns from <code>A</code> and all columns from <code>B</code> into <code>1D</code> arrays each, when considering each row as a sequence of binary numbers that could be converted to decimal numb...
3
2016-07-08T14:51:17Z
[ "python", "pandas" ]
Fastest way to compare rows of two pandas dataframes?
38,267,763
<p>So I have two pandas dataframes, A and B. </p> <p>A is 1000 rows x 500 columns, filled with binary values indicating either presence or absence. </p> <p>B is 1024 rows x 10 columns, and is a full iteration of 0's and 1's, hence having 1024 rows.</p> <p>I am trying to find which rows in A, at a particular 10 colum...
2
2016-07-08T13:20:05Z
38,270,174
<p>In this special case, your rows of 10 zeros and ones can be interpreted as 10 digit binaries. If B is in order, then it can be interpreted as a range from 0 to 1023. In this case, all we need to do is take A's rows in 10 column chunks and calculate what its binary equivalent is.</p> <p>I'll start by defining a ra...
1
2016-07-08T15:17:41Z
[ "python", "pandas" ]
How to I list imported modules with their version?
38,267,791
<p>I need to list all imported modules together with their version. Some of my code only works with specific versions and I want to save the version of the packages, so that I can look it up again in the future. Listing the names of the packages works:</p> <pre><code>modules = list(set(sys.modules) &amp; set(globals()...
0
2016-07-08T13:21:41Z
38,267,901
<p>Because you have a list of strings of the module name, not the module itself. Try this:</p> <pre><code>for module_name in modules: module = sys.modules[module_name] print module_name, getattr(module, '__version__', 'unknown') </code></pre> <p>Note that not all modules follow the convention of storing the ...
1
2016-07-08T13:26:31Z
[ "python" ]
How to I list imported modules with their version?
38,267,791
<p>I need to list all imported modules together with their version. Some of my code only works with specific versions and I want to save the version of the packages, so that I can look it up again in the future. Listing the names of the packages works:</p> <pre><code>modules = list(set(sys.modules) &amp; set(globals()...
0
2016-07-08T13:21:41Z
38,268,153
<p>One of the issues I have had with huge legacy programs is where aliases have been used (<code>import thing as stuff</code>). It is also often good to know exactly which file is being loaded. I wrote this module a while ago which might do what you need:</p> <p>spection.py</p> <pre><code>""" Python 2 version 10.1....
0
2016-07-08T13:40:17Z
[ "python" ]
Following links in python assignment using Beautifulsoup
38,267,954
<p>I have this assignment for a python class where I have to start from a specific link at a specific position, then follow that link for a specific number of times. Supposedly the first link has the position 1. This is the link: <a href="http://python-data.dr-chuck.net/known_by_Fikret.html" rel="nofollow">http://pytho...
-3
2016-07-08T13:29:33Z
38,268,780
<p>Your BeautifulSoup import was wrong. I don't think it works with the code you show. Also your lower loop was confusing. You can get the list of urls you want by slicing the completely retrieved list.</p> <p>I've hardcoded your url in my code because it was easier than typing it in each run.</p> <p>Try this:</p>...
0
2016-07-08T14:10:31Z
[ "python", "python-2.7", "beautifulsoup" ]
Making an array of required dimension with 'nan' as remaining elements
38,268,015
<p>I have an array A of just n elements. Making it (n x 1) .Is there a chance of making it (n x n) by putting all other elements as 'nan'. so that A.shape gives me (n,n) . </p>
0
2016-07-08T13:32:46Z
38,268,943
<p>If there is any chance, that you could provide further information (such as what do you need it for), it would be great. Anyhow here is my solution: </p> <pre><code>import numpy as np #input array example = np.array([1,2,3,4,5]) #create a target matrix containing only 'nan' elements of size n*n target = np.ones(...
0
2016-07-08T14:18:26Z
[ "python", "python-2.7", "numpy" ]
Change in for-loop range by deleting a list element
38,268,017
<p>I am new to python and programming in general and currently learning the fundamentals. In the script below I am trying to check the number of letters in each list element and delete ones with five and more letters. I am using for-loop to achieve this but an issue is occurring because of the change in the number of l...
0
2016-07-08T13:32:48Z
38,268,063
<p>There is a sophisticated answer to your problem in this post: <a href="http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python">Remove items from a list while iterating in Python</a></p> <p>The easiest one is to create a new list only containing the elements you actually want.<...
-1
2016-07-08T13:35:31Z
[ "python", "string", "for-loop", "string-length", "del" ]
Change in for-loop range by deleting a list element
38,268,017
<p>I am new to python and programming in general and currently learning the fundamentals. In the script below I am trying to check the number of letters in each list element and delete ones with five and more letters. I am using for-loop to achieve this but an issue is occurring because of the change in the number of l...
0
2016-07-08T13:32:48Z
38,268,264
<p>The main problem with your code is that the <code>Y = ...</code> within the loop does <em>not</em> have an effect on the <code>Y</code> in <code>for i in Y</code>.</p> <pre><code>for i in Y: ... Y=range (0,q) </code></pre> <p>You <em>could</em> change your code to use a <code>while</code> loop, and man...
0
2016-07-08T13:45:36Z
[ "python", "string", "for-loop", "string-length", "del" ]
How to trigger an event after 30 seconds has passed in Django?
38,268,062
<p>I'm writing a game, and as a part of the game the protagonists will be killed if they cannot escape a room in 30 seconds. Is there a mechanism that allows me to do this in Django? My current solution is to</p> <pre><code>InformProtagonists("Escape in 30 seconds!") time.sleep(30); if protagonists in room: NotifyPr...
0
2016-07-08T13:35:30Z
38,268,366
<p>I'd use django just for the backend (pulling data from DB with an api and submitting data back if needed). </p> <p>And handle the rest with javascript and something like <a href="https://facebook.github.io/react/" rel="nofollow">react</a> and <a href="http://redux.js.org/" rel="nofollow">redux</a>.</p> <p>django i...
0
2016-07-08T13:50:11Z
[ "python", "django" ]
How to trigger an event after 30 seconds has passed in Django?
38,268,062
<p>I'm writing a game, and as a part of the game the protagonists will be killed if they cannot escape a room in 30 seconds. Is there a mechanism that allows me to do this in Django? My current solution is to</p> <pre><code>InformProtagonists("Escape in 30 seconds!") time.sleep(30); if protagonists in room: NotifyPr...
0
2016-07-08T13:35:30Z
38,268,647
<p>Django is a server-side web framework. You interact with it through network requests and responses. It's not really well suited for any part of real-time game development beyond managing your backend data.</p> <p>You probably just need to look at building your game with some front-end javascript.</p>
0
2016-07-08T14:04:07Z
[ "python", "django" ]
How to trigger an event after 30 seconds has passed in Django?
38,268,062
<p>I'm writing a game, and as a part of the game the protagonists will be killed if they cannot escape a room in 30 seconds. Is there a mechanism that allows me to do this in Django? My current solution is to</p> <pre><code>InformProtagonists("Escape in 30 seconds!") time.sleep(30); if protagonists in room: NotifyPr...
0
2016-07-08T13:35:30Z
38,291,602
<pre><code>import threading timer = threading.Timer(30.0, KillPlayers, [request, player]) timer.start() </code></pre>
0
2016-07-10T11:57:28Z
[ "python", "django" ]
Histogram in Python in functional way in O(n)
38,268,066
<p>Not sure how to formulate question properly, please correct me if I'm wrong.</p> <p>Say I want to make histogram in functional way in pure Python.</p> <pre><code>def add_value(bins, x): i = int(x // 10) return (*bins[:i], bins[i] + 1, bins[i + 1:]) def histogram(data): return reduce(data, add_value, (...
2
2016-07-08T13:35:53Z
38,269,196
<p>Let me start by saying I'm still learning my way around functional programming myself, so I'm no expert.</p> <p>To answer your first question, yes, I agree that your functional implementation is O(n^2), as you are rebuilding the entire tuple at each step.</p> <p>For your second question, here is a functional imple...
1
2016-07-08T14:30:39Z
[ "python", "functional-programming" ]
Histogram in Python in functional way in O(n)
38,268,066
<p>Not sure how to formulate question properly, please correct me if I'm wrong.</p> <p>Say I want to make histogram in functional way in pure Python.</p> <pre><code>def add_value(bins, x): i = int(x // 10) return (*bins[:i], bins[i] + 1, bins[i + 1:]) def histogram(data): return reduce(data, add_value, (...
2
2016-07-08T13:35:53Z
38,282,773
<p>As was mentioned, doing this in FP style is not ideal in Python. I'd first like to propose a variation on @bsa's approach, which is somewhat more readable, though:</p> <pre><code>def histo(sorted_data): return {bin: sum(1 for v in values) for bin, values in groupby(sorted_data)} </code></pre> <p>This at least ...
2
2016-07-09T14:21:06Z
[ "python", "functional-programming" ]
How should I upgrade pip on Ubuntu 14.04?
38,268,074
<p>I want to get the most recent version (8.1.2) of pip. I'm using Ubuntu 14.04 and python 2.7.6. The version of pip in the Ubuntu repositories is only 1.5.4 (and can't install things like numpy). How are you actually meant to upgrade pip? I've discovered a few ways; maybe they're all equivalent but it would be good t...
1
2016-07-08T13:36:22Z
38,268,244
<p>The most painless way that I found that works is to use install <code>virtualenv</code> and use <code>pip</code> inside a virtualenv. This does not even require you install <code>pip</code> at the system level (which you might have done by running <code>sudo apt-get install python-pip</code>):</p> <pre><code>sudo a...
0
2016-07-08T13:44:52Z
[ "python", "pip", "ubuntu-14.04" ]
python script ends between 2 for loops
38,268,401
<p>i'm pretty new to python and would like to copy some files from one location to another one and store some information within them inside a mysql database. I have to run the script 2 times until it works. After the first attempt it stops right after the first for-loop. Executing it a second time finishes everything....
0
2016-07-08T13:51:55Z
38,268,552
<pre><code>files = glob.glob(path) for file in files: # starting to scan the files with open(file, 'r') as f lines = f.read() output = re.search(r'error', lines) # regexp to search for 'error' if output: query = """INSERT INTO import (Fehler,Filename) VALUES ("1","%s")""" ...
0
2016-07-08T13:59:12Z
[ "python", "loops", "for-loop" ]
How to find the most important features learned during Deep Learning using CNN?
38,268,490
<p>I followed the tutorial given at this <a href="http://wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/" rel="nofollow">site</a>, which detailed how to perform text classification on the movie dataset using CNN. It utilized the movie review dataset to find predict positive and negative rev...
-2
2016-07-08T13:55:28Z
38,272,590
<p>A word of warning: if you can trace the classification back to specific input features, it's quite possible that CNN is the wrong ML paradigm for your application. Most text processing uses RNN, bag-of-words, bi-grams, and other simple linear combinations.</p> <p>The structure of a CNN is generally antithetical to...
1
2016-07-08T17:43:35Z
[ "python", "tensorflow", "theano", "deep-learning" ]
pandas, store multiple datasets in an h5 file with pd.to_hdf
38,268,599
<p>Say I have two dataframes, </p> <pre><code>import pandas as pd df1 = pd.DataFrame({'col1':[0,2,3,2],'col2':[1,0,0,1]}) df2 = pd.DataFrame({'col12':[0,1,2,1],'col22':[1,1,1,1]}) </code></pre> <p>Now <code>df1.to_hdf('nameoffile.h5', 'key_to_store','w',table=True)</code> successully stores <code>df1</code> but I wan...
1
2016-07-08T14:01:34Z
38,268,708
<p>You are using <code>'w'</code> which overwrites, by default the mode is <code>'a'</code> so you can just do:</p> <pre><code>df2.to_hdf('nameoffile.h5', 'key_to_store'',table=True) </code></pre> <p>Check the docs: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_hdf.html#pandas.Dat...
1
2016-07-08T14:07:06Z
[ "python", "pandas" ]
pandas, store multiple datasets in an h5 file with pd.to_hdf
38,268,599
<p>Say I have two dataframes, </p> <pre><code>import pandas as pd df1 = pd.DataFrame({'col1':[0,2,3,2],'col2':[1,0,0,1]}) df2 = pd.DataFrame({'col12':[0,1,2,1],'col22':[1,1,1,1]}) </code></pre> <p>Now <code>df1.to_hdf('nameoffile.h5', 'key_to_store','w',table=True)</code> successully stores <code>df1</code> but I wan...
1
2016-07-08T14:01:34Z
38,268,737
<p>I have used this in the past without issue:</p> <pre><code>store = pd.HDFStore(path_to_hdf) store[new_df_name] = df2 store.close() </code></pre> <p>So in your case you could try:</p> <pre><code>store = pd.HDFStore(path_to_hdf) store['df1'] = df1 store['df2'] = df2 store.close() </code></pre> <p>I used this in a ...
0
2016-07-08T14:08:40Z
[ "python", "pandas" ]
Extremum of a weird array in numpy (python3)
38,268,842
<p>I have an array that looks like this:</p> <pre><code>ar=[[[678,701]], [[680,702]], [[674,710]], ...] </code></pre> <p>I have to find extrema for each of the column (i.e., for these 678,680,674... and for 701,702,710,... independently).</p> <p>I tried to access these columns with something like this:</p> <p><c...
0
2016-07-08T14:13:14Z
38,269,016
<p>To find the extrema along particular axes, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.max.html" rel="nofollow">the <code>axis</code> parameter</a>:</p> <pre><code>import numpy as np ar = np.array([[[678,701]], [[680,702]], [[674,710]], ]) print ar.max(axis=0) # [[68...
1
2016-07-08T14:21:27Z
[ "python", "arrays", "python-3.x", "numpy" ]
Confusing documentation about axes in SciPy
38,268,907
<p>Here is an excerpt from SciPy <a href="http://docs.scipy.org/doc/numpy-1.10.1/glossary.html" rel="nofollow">documentation</a> (as of July 8, 2016):</p> <blockquote> <p><strong>along an axis</strong></p> <p>Axes are defined for arrays with more than one dimension. A 2-dimensional array has two corresponding a...
2
2016-07-08T14:16:52Z
38,268,990
<p>Consider this example.</p> <pre><code>&gt;&gt;&gt; print(a) [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] </code></pre> <p>To sum over columns: </p> <pre><code>&gt;&gt;&gt; a.sum(axis=0) array([18, 22, 26]) </code></pre> <p>Or, to sum over rows:</p> <pre><code>&gt;&gt;&gt; a.sum(axis=1) array([ 3, 12, 21, 3...
3
2016-07-08T14:20:38Z
[ "python", "arrays", "numpy" ]
Assigning the correct ID to a form?
38,269,153
<p>So I'm expanding on the official tutorial, and I'm trying to let a user create their own poll. I'm having trouble assigning the correct question_id to the choice, so the choice aligns in the database with the question and both can be read off. Here is my view:</p> <pre><code>def poll_create(request): if request...
0
2016-07-08T14:28:39Z
38,270,304
<p>Your code is a bit confusing because you are using the variable <code>poll</code> for questions and choices. It would be better to use <code>question</code> and <code>choice</code> instead.</p> <p>You should check that <em>both</em> forms are valid before you start saving, otherwise you can end up with a question w...
0
2016-07-08T15:24:11Z
[ "python", "django" ]
How would I put a dict {key: value} in it's designated key in a dictionary so that it is {key: {key: value}} after counting value
38,269,203
<p>I have a csv file where I am trying to count <code>row[3]</code> then connect it with <code>row[0]</code></p> <pre><code> row[0] row[3] 'A01' 'a' 'B02' 'a' 'A01' 'b' 'A01' 'a' 'B02' 'a' 'A01' 'a' </code></pre> <p>so that in the end it should be </p> ...
1
2016-07-08T14:30:53Z
38,269,290
<p>A <code>KeyError</code> is raised whenever you're requesting a key from a dictionary that does not exist.</p> <p>It looks like you're declaring the key as <code>'general_types'</code> and then are requesting it by the name <code>'general_type'</code>. Try this instead:</p> <pre><code>d['general_types'].setdefault(...
2
2016-07-08T14:35:32Z
[ "python", "python-2.7", "csv", "dictionary" ]
Python Imaging Library (PIL) source code
38,269,223
<p>I'm having trouble in finding PIL source code.</p> <p>The main page of the library <a href="http://www.pythonware.com/products/pil/" rel="nofollow">http://www.pythonware.com/products/pil/</a> does not have any link to git repositories.</p> <p>Is Pillow (<a href="https://github.com/python-pillow/Pillow" rel="nofoll...
0
2016-07-08T14:31:56Z
38,269,368
<p>No. I think it is difference project. <a href="https://pillow.readthedocs.io/en/latest/installation.html" rel="nofollow">https://pillow.readthedocs.io/en/latest/installation.html</a> When you want to install pillow, you must uninstall PIL</p>
0
2016-07-08T14:39:48Z
[ "python", "image-processing", "python-imaging-library" ]
Python Imaging Library (PIL) source code
38,269,223
<p>I'm having trouble in finding PIL source code.</p> <p>The main page of the library <a href="http://www.pythonware.com/products/pil/" rel="nofollow">http://www.pythonware.com/products/pil/</a> does not have any link to git repositories.</p> <p>Is Pillow (<a href="https://github.com/python-pillow/Pillow" rel="nofoll...
0
2016-07-08T14:31:56Z
38,269,451
<p>PIL was never ported to Python 3, so Pillow forked the project and took it over. Pillow has <a href="https://pypi.python.org/pypi/Pillow/2.7.0" rel="nofollow">since been back-ported</a> to Python 2, but if you are working with Python 3, you must use Pillow. They are essentially the same.</p> <p>If you want the <em>...
4
2016-07-08T14:43:35Z
[ "python", "image-processing", "python-imaging-library" ]
How does pandas calculate indexes?
38,269,303
<p>I want to include time series data in a dataframe from a csv. I use the following procedure:</p> <pre><code>path = [r'C:\data_' + str(x) + ".csv" for x in range(1150, 1177)] data_df = pd.concat(pd.read_csv(f, delimiter = ",", header = None) for f in path) data_df.head() </code></pre> <p><a href="http://i.stack.i...
2
2016-07-08T14:36:37Z
38,269,380
<p>There are duplicates in <code>indexes</code>, because each <code>index</code> of <code>DataFrame</code> starts from <code>0</code> in <code>concat</code> function.</p> <p>And as <a href="http://stackoverflow.com/questions/38269303/how-does-pandas-calculate-indexes/38269380#comment63958066_38269303">MaxU</a> comment...
2
2016-07-08T14:40:24Z
[ "python", "pandas", "indexing", "time-series" ]
SymPy: lambdified dot() with (3,n)-array
38,269,304
<p>I have a <code>lambdify</code>d sympy function with a <code>dot</code> product in it, e.g.,</p> <pre><code>import numpy as np import sympy class dot(sympy.Function): pass x = sympy.Symbol('x') a = sympy.Matrix([1, 1, 1]) f = dot(x, a) ff = sympy.lambdify((x), f, modules='numpy') x = np.random.rand(3) pr...
3
2016-07-08T14:36:38Z
38,296,603
<p>You're doing multiple odd things, but I can't tell how much of this is due to an oversimplified MCVE.</p> <p>First, a bit more elegant definition of your function:</p> <pre><code>import sympy as sym x = sym.Symbol('x') a = sym.Matrix([1, 1, 1]) dot = sym.Function('dot') f = dot(x, a) ff = sym.lambdify(x, f, ...
3
2016-07-10T21:25:54Z
[ "python", "numpy", "sympy" ]
How do I install a python module in a virtual environment?
38,269,331
<p>I am a beginner and read somewhere that we should always create virtual environments when working with Python. Therefore, I created a virtual environment using:</p> <pre><code>python -m virtualenv headlines </code></pre> <p>It copies all files with messages like </p> <pre><code>Using base prefix 'C:\\Program File...
0
2016-07-08T14:38:11Z
38,269,686
<p>I assume that you have already virtual environment folder successfully created.</p> <p>First of all, you should be "inside" in your virtualenv in order to use it, thus for linux environments:</p> <pre><code>~$ source ${your_venv_folder_name}/bin/activate </code></pre> <p>will cause command line look like this</p>...
0
2016-07-08T14:54:20Z
[ "python", "python-3.x", "pip", "virtualenv", "python-3.5" ]
Using python, move files with specific text to a new directory
38,269,474
<p>Fairly new to programming. Trying to make life easier for me here. I have a folder with several thousand simple txt files. Within the files, I am looking for certain key words so I can sort those files to three different folders. </p> <p>For example, one group of files will have the text "Example Text" printed twic...
0
2016-07-08T14:44:31Z
38,269,901
<p>The heart of such a program would probably look like this:</p> <pre><code>def count_phrase_occurrences(filename, phrase): ''' Return the number of times that a phrase appears in a file. ''' occurrences = 0 with open(filename, 'r') as fp: for line in fp: if phrase in line: ...
0
2016-07-08T15:04:52Z
[ "python" ]
Python requests library not sending correct params
38,269,527
<p>I am sending post request to an API. The API expects params in raw format.</p> <pre><code>headers = {"content-type" : "application/json"} url = "http://test.web.com/web_api/CreateHeader" params = {"param1" : "asd", "param2" : "asdd"} r = requests.post(url, data = json.dumps(params), headers = headers, auth = HTTPBa...
0
2016-07-08T14:47:12Z
38,269,727
<p>From your description the API seems to expect the data as json, so</p> <pre><code>r = requests.post(url, json=params, headers=headers) </code></pre> <p>should work.</p>
-1
2016-07-08T14:56:34Z
[ "python", "python-requests" ]
Adding a column to certain row in a data frame pandas
38,269,575
<p>I've got a dataframe which contains ids and emails. I also have a dictionary, which contain as a key the id and as a value a phone number. I want to iter on the dictionary and if the id is present in the dictionary then create a new column in the dataframe and add the phone number. I figured out how to see if the id...
0
2016-07-08T14:49:15Z
38,269,600
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a>:</p> <pre><code>df['new'] = df.id.map(mapping_id_phone) </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'id':[1,2,3]}) mapping_id_phone = {1: '123', 2:'456', 3:'789'} p...
0
2016-07-08T14:50:30Z
[ "python", "python-2.7", "pandas", "dataframe" ]
python flask-socketio TypeError: a bytes-like object is required, not 'str'
38,269,696
<p>I started to use Socketio, and I got a problem. I can't send a simple message to my flask session. My Java code:</p> <pre><code>import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import org.json.JSONException; import org.json.JSONObject; i...
2
2016-07-08T14:54:52Z
38,782,097
<p>I think you use python3 with the gevent and gevent-websocket plugin. gevent-websocket does not support python3 yet.</p> <p>You have to options here:</p> <ol> <li>Uninstall gevent and gevent-websocket and use eventlet.</li> <li><p>Fix the code geventwebsocket/handler.py at line 236. </p> <pre><code>if b'101' not i...
0
2016-08-05T05:58:50Z
[ "java", "android", "python", "flask", "flask-socketio" ]
Numpy float storage into Dataframe seems to be wrongly managed
38,269,770
<p>I just used this dataframe to test an algorithm for statistics: </p> <pre><code>d1=pd.DataFrame([[0.1,0.2],[0.3,0.4],[0.5,0.6],[0.7,0.8],[0.9,0.81],[0.91,0.82],[0.93,0.94],[0.95,0.96],[0.97,0.98],[0.99,1]]) </code></pre> <p>recalling:</p> <ul> <li><code>d1.iloc[0,1]</code> yields <code>0.20000000000000001</code><...
0
2016-07-08T14:58:41Z
38,273,949
<p>Using <code>np.array</code> rather than pandas, compare the display of one element:</p> <pre><code>x=np.array([[0.1,0.2],[0.3,0.4],[0.5,0.6],[0.7,0.8],[0.9,0.81],[0.91,0.82],[0.93,0.94],[0.95,0.96],[0.97,0.98],[0.99,1]]) x[0,1] Out[47]: 0.20000000000000001 float(x[0,1]) Out[48]: 0.2 np.float(x[0,1]) # np.float...
1
2016-07-08T19:19:28Z
[ "python", "numpy", "pandas", "floating-point", "precision" ]
Why does using str.format create unicode errors?
38,269,792
<p>I know that in Python 2 unicode errors are a mess, but what I don't understand is why <code>str.format</code> introduces them to an otherwise working situation. I was having trouble with some unicode characters, and testing out IDLE got me this:</p> <pre><code>&gt;&gt;&gt; s = u'\xef' &gt;&gt;&gt; print s ï &gt;&g...
0
2016-07-08T14:59:28Z
38,269,917
<p>Keep in mind that when you say</p> <pre><code>print '{}'.format(s) </code></pre> <p>the string you try to format with a unicode string is bytes (python2 str type). This:</p> <pre><code>print u'{}'.format(s) </code></pre> <p>works ok.</p>
2
2016-07-08T15:05:52Z
[ "python", "string", "unicode" ]
Pandas: group with TimeGrouper
38,269,802
<p>I have data </p> <pre><code>i,ID,url,used_at,active_seconds,domain,search_term 322015,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/antoninaribina,2015-12-31 09:16:05,35,vk.com,None 838267,0120bc30e78ba5582617a9f3d6dfd8ca,vk.com/feed,2015-12-31 09:16:38,54,vk.com,None 838271,0120bc30e78ba5582617a9f3d6dfd8ca,vk.co...
3
2016-07-08T14:59:59Z
38,269,976
<p>IIUC you need:</p> <pre><code>print (df.groupby('ID')['used_at'].diff().dt.seconds) 0 NaN 1 33.0 2 54.0 3 34.0 4 4.0 5 4.0 6 8.0 7 16.0 8 6.0 Name: used_at, dtype: float64 </code></pre> <p>If you wish to use <code>TimeGrouper</code>, you should first set a <code>Datetimeindex</code>...
3
2016-07-08T15:08:24Z
[ "python", "pandas" ]
Virtual environment wrong python version
38,269,830
<p>I am having a problem with virtual environment and mod_wsgi configuration.</p> <p>I have this in my apache configuration:</p> <pre><code>WSGIDaemonProcess myapp python-path=/mnt/myapp/current:/mnt/env/lib/python3.4/site-packages </code></pre> <p>which clearly states that I am using python3.4.</p> <p>But if I am ...
1
2016-07-08T15:01:27Z
38,283,850
<p>It looks like you're using the compiled version of <code>mod_wsgi</code>, which compiles in Python when you first built it, which may have been Python 3.4.0. It looks like what you'll want to do is recompile <code>mod_wsgi</code> against Python 3.4.3 this time, with a something like this:</p> <pre><code>wget -q "ht...
1
2016-07-09T16:23:11Z
[ "python", "apache", "mod-wsgi" ]
Tkinter- removing multiple selections from listbox
38,269,837
<p>I came here early and this guy help me with a code to have whats selected in the listbox</p> <pre><code>def selecionado(evt): global ativo a=evt.widget b=a.curselection() if len(b) &gt; 0: seleção=a.curselection()[0] sel_text=a.get(seleção) ativo=[a.get(i) for i in a.cu...
-1
2016-07-08T15:01:46Z
38,270,899
<p>Listbox deletion expects an index, not a list (or any other data type). Assuming <code>ativo</code> is a list of indexes (integers, specifically), <code>remover_membro</code> should look more like</p> <pre><code>for i in ativo: lista.delete(i) </code></pre> <p>If <code>ativo</code> isn't integers (i.e. it is t...
0
2016-07-08T15:55:38Z
[ "python", "file", "tkinter", "listbox" ]
Python: Parsing logical string into list of lists
38,269,929
<p>I get string of logical expressions from a database and need to put these into a list of lists for further evaluation. I already tried reading a lot about string parsing but could not find the answer so far. For easier understanding of the problem, here are 3 examples:</p> <pre><code>input_string1 = '((A OR B) AND ...
2
2016-07-08T15:06:26Z
38,271,257
<p>For the recursive nature of the expression, you can use the <code>Forward</code> element, and for the variable length clauses you can use <code>ZeroOrMore</code>. Based on your existing grammar:</p> <pre><code>expression = pp.Forward() atom = gene_id | pp.Group(l_brackets + expression + r_brackets) expression &lt;&...
1
2016-07-08T16:14:35Z
[ "python", "string", "list", "parsing" ]
Python: Parsing logical string into list of lists
38,269,929
<p>I get string of logical expressions from a database and need to put these into a list of lists for further evaluation. I already tried reading a lot about string parsing but could not find the answer so far. For easier understanding of the problem, here are 3 examples:</p> <pre><code>input_string1 = '((A OR B) AND ...
2
2016-07-08T15:06:26Z
38,271,967
<p>Here is a solution that gives the result you desire using a tokenizer and recursive descent parser. Unfortunately, I am not familiar with the <code>pyparsing</code> library so I did not use it.</p> <pre><code>s1 = '((A OR B) AND (C OR D)) OR E' s2 = '(A AND ( B OR C ) AND D AND E)' s3 = ' A OR ( B AND C ) OR D OR E...
2
2016-07-08T16:56:40Z
[ "python", "string", "list", "parsing" ]
For loop not working as intended
38,270,113
<p>I am in the middle of my course work and I am now having trouble with one of my for loops.</p> <pre><code>def update(): update=[] update1=[] with open('Stock2.txt','r') as stockFile: for eachLine in stockFile: eachLine=eachLine.strip().split() update.append(eachLine) update.remove(update[0])...
-2
2016-07-08T15:14:28Z
38,270,213
<p>You increment <code>count</code> outside the <code>if</code> that prints. Try this instead:</p> <pre><code>for eachList in update1: for eachItem in eachList: if eachItem != ' ': count+=1 print(count) </code></pre>
0
2016-07-08T15:19:25Z
[ "python" ]
For loop not working as intended
38,270,113
<p>I am in the middle of my course work and I am now having trouble with one of my for loops.</p> <pre><code>def update(): update=[] update1=[] with open('Stock2.txt','r') as stockFile: for eachLine in stockFile: eachLine=eachLine.strip().split() update.append(eachLine) update.remove(update[0])...
-2
2016-07-08T15:14:28Z
38,270,565
<p>If I put a <code>print update1</code> statement before your last <code>for</code> loop, i.e., before the statement <code>for eachList in update1:</code>, I get the following output:</p> <p><code>[['95820194', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'Windows-10-64bit', ' ', ' ', ' ', '119.99', ' ', ' ', ' ', ' ...
0
2016-07-08T15:38:12Z
[ "python" ]
I am trying to write a Python Script to Print a list of Files In Directory
38,270,136
<p>as the title would imply I am looking to create a script that will allow me to print a list of file names in a directory to a CSV file.</p> <p>I have a folder on my desktop that contains approx 150 pdf's. I'd like to be able to have the file names printed to a csv.</p> <p>I am brand new to Python and may be jumpi...
0
2016-07-08T15:15:32Z
38,270,600
<p>First off you will want to start by grabbing all of the files in the directory, then simply by writing them to a file.</p> <pre><code>from os import listdir from os.path import isfile, join import csv onlyfiles = [f for f in listdir("./") if isfile(join("./", f))] with open('file_name.csv', 'w') as print_to: ...
1
2016-07-08T15:39:44Z
[ "python", "csv" ]
I am trying to write a Python Script to Print a list of Files In Directory
38,270,136
<p>as the title would imply I am looking to create a script that will allow me to print a list of file names in a directory to a CSV file.</p> <p>I have a folder on my desktop that contains approx 150 pdf's. I'd like to be able to have the file names printed to a csv.</p> <p>I am brand new to Python and may be jumpi...
0
2016-07-08T15:15:32Z
38,270,719
<pre><code>import os csvpath = "csvfile.csv" dirpath = "." f = open("csvpath, "wb") f.write(",".join(os.listdir(dirpath))) f.close() </code></pre> <p>This may be improved to present filenames in way that you need, like for getting them back, or something. For instance, this most probably won't include unicode filename...
0
2016-07-08T15:45:28Z
[ "python", "csv" ]
I am trying to write a Python Script to Print a list of Files In Directory
38,270,136
<p>as the title would imply I am looking to create a script that will allow me to print a list of file names in a directory to a CSV file.</p> <p>I have a folder on my desktop that contains approx 150 pdf's. I'd like to be able to have the file names printed to a csv.</p> <p>I am brand new to Python and may be jumpi...
0
2016-07-08T15:15:32Z
38,270,876
<p>The following will create a csv file with all *.pdf files:</p> <pre><code>from glob import glob with open('/tmp/filelist.csv', 'w') as fout: # write the csv header -- optional fout.write("filename\n") # write each filename with a newline characer fout.writelines(['%s\n' % fn for fn in glob('/path/to...
0
2016-07-08T15:54:02Z
[ "python", "csv" ]
requests: post multipart/form-data
38,270,151
<p>My API:</p> <pre><code>class FileView(APIView): parser_classes = (MultiPartParser,) def post(self, request): do something with request.FILES.dict().iteritems() </code></pre> <p>My <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a> file:</p> <pre><code>try: headers...
1
2016-07-08T15:16:30Z
38,271,059
<p>Removed 'content-type' from the headers, now it works</p> <pre><code>try: headers = { 'authorization': "Basic ZXNlbnRpcmVcYdddddddddddddd", 'cache-control': "no-cache", } myfile = {"file": ("filexxx", open(filepath, "rb"))} response = requests.request("POST", verify=False, url=url, ...
1
2016-07-08T16:03:38Z
[ "python", "django-rest-framework", "python-requests" ]
Group by a list python
38,270,178
<p>I have the following list:<br></p> <pre><code>input=[(u'Number', u'Twenty', u'20.0'), (u'Number', u'five', u'5'), (u'fraction', u'one', u'1'), (u'fraction', u'in', u'/'), (u'fraction', u'five', u'5'), (u'Number', u'50 percent', u'50%')]&lt;br&gt; </code></pre> <p>I want to do a group by but with keeping same order...
0
2016-07-08T15:17:47Z
38,270,520
<p>After <em>grouping</em>, check on your group lengths to see which groups need modification (based on length), then <em>merge</em> non-duplicate words in the tuples in each group using <code>join</code>.</p> <p>This does it:</p> <pre><code>inp = [(u'Number', u'Twenty', u'20.0'), (u'Number', u'five', u'5'), (u'fract...
0
2016-07-08T15:35:33Z
[ "python", "list", "python-2.7", "tuples" ]
How to reduce the complexity of Longest repeated sequesnce
38,270,198
<p>Last week, I had an interview with Amazon. The interviewer asked the a question to findout longest repeated substring in <code>banana</code> If we will look into the string <code>banana</code>, we will see <code>ana</code> (repeated 2 times) is an overlapped repeated string. I could able to reach the solution but my...
1
2016-07-08T15:18:47Z
38,271,156
<p>The problem can be solved in <em>linear time</em> O(N) by using <a href="https://en.wikipedia.org/wiki/Suffix_tree" rel="nofollow">suffix trees</a>. A suffix tree is a tree that contains all suffices of a given text. Moreover they take time and space O(N) to build.</p> <p>The tree has edges labelled with substrings...
3
2016-07-08T16:09:29Z
[ "python", "algorithm" ]
How to reduce the complexity of Longest repeated sequesnce
38,270,198
<p>Last week, I had an interview with Amazon. The interviewer asked the a question to findout longest repeated substring in <code>banana</code> If we will look into the string <code>banana</code>, we will see <code>ana</code> (repeated 2 times) is an overlapped repeated string. I could able to reach the solution but my...
1
2016-07-08T15:18:47Z
38,271,671
<p>If I understand correctly, you grow the String temp in the order "b"-"ba"-..., then "a"-"an"-... so you are testing from the smallest to the largest parts.</p> <p>Do you have the possibility to avoid the worst case scenario systematically ?</p> <p>For exemple by dividing you string starting by 2 to K, K being the ...
1
2016-07-08T16:38:43Z
[ "python", "algorithm" ]
merging large data sets using Pandas
38,270,216
<p>I'm trying to merge two large DataFrames:</p> <ul> <li><code>myTable</code>, shape :(331994, 13). This first one contains trade data (12 columns) for several client codes (1 column)</li> <li><code>Referential</code>, shape (75546, 1). This second one contains a referential table with client codes as indexes and cli...
1
2016-07-08T15:19:33Z
38,270,303
<p>assuming that your <code>Referential</code> DF looks like as follows:</p> <pre><code> clientName 0 name1 1 name2 2 name3 </code></pre> <p>where the index corresponds to <code>ClientCode</code>, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" re...
2
2016-07-08T15:24:10Z
[ "python", "pandas", "merge" ]
Automatic tagging in django
38,270,260
<p>So I have this simple django Model called Post with some date about the user who posted a message and a message it self. </p> <pre><code>class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="posts",null=False) text = models.CharField(max_length=400) date_crea...
0
2016-07-08T15:21:57Z
38,270,400
<p>What I would suggest is to capture <strong>pre_save</strong> signal and create the tags which does not exist.</p>
1
2016-07-08T15:29:09Z
[ "python", "django", "django-models", "tags" ]
Print in python 2.7
38,270,376
<p>I have been using Python 2.7 for a while. Suddenly, I am getting errors with the print statement and it looks like I should now use Python 3.x syntax.</p> <pre><code>print 'hello world' File "&lt;ipython-input-462-d05d0c8adf1f&gt;", line 1 print 'hello world' ^ SyntaxError: invalid syntax prin...
0
2016-07-08T15:27:32Z
38,270,409
<p>Are you using the <code>print_function</code> future import?</p> <pre><code>from __future__ import print_function </code></pre> <p>That function backports the new print syntax to Python 2 code. It is usually used if a codebase should be runnable both on Python 2 and 3.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt;...
0
2016-07-08T15:29:38Z
[ "python", "python-2.7" ]
Length of list as condition in any function for list comprehension
38,270,412
<p>I want to use the length of my list for which I'm generating a list comprehension as a condition along with those in the list comprehension that is being passed to the any() function itself</p> <p>I could do this in two lines -</p> <pre><code>li = [1,2,3,4] lcond = [x for x in li if x &gt; 3] any(lcond) and len(lc...
0
2016-07-08T15:29:44Z
38,270,508
<p>You don't really need a list comprehension here.</p> <pre><code>if len(filter(lambda x: x &gt; 3, li)) &gt; 2: </code></pre> <p>In Python 3, you need to explicitly consume the generator returned by <code>filter</code>:</p> <pre><code>if len(list(filter(lambda x: x &gt; 3, li))) &gt; 2: </code></pre> <hr> <p>Act...
2
2016-07-08T15:35:04Z
[ "python", "list" ]
Length of list as condition in any function for list comprehension
38,270,412
<p>I want to use the length of my list for which I'm generating a list comprehension as a condition along with those in the list comprehension that is being passed to the any() function itself</p> <p>I could do this in two lines -</p> <pre><code>li = [1,2,3,4] lcond = [x for x in li if x &gt; 3] any(lcond) and len(lc...
0
2016-07-08T15:29:44Z
38,270,805
<p>If your list is a very large one I recommend you don't go through the whole list just for knowing if there are at least two items that satisfies the conditions.</p> <p>I suggest to use islice from itertolls applied over a generator like that:</p> <pre><code>test_list = [1,2,3,4] # Returns False len(list(itertools...
0
2016-07-08T15:49:36Z
[ "python", "list" ]
Python - How to read a csv files separated by commas which have commas within the values?
38,270,476
<p>The file has an URL which contain commas within it. For example: ~oref=<a href="https://tuclothing.tests.co.uk/c/Girls/Girls_Underwear_Socks&amp;Tights?INITD=GNav-CW-GrlsUnderwear&amp;title=Underwear,+Socks+&amp;+Tights" rel="nofollow">https://tuclothing.tests.co.uk/c/Girls/Girls_Underwear_Socks&amp;Tights?INITD=GNa...
0
2016-07-08T15:33:19Z
38,270,851
<p>It looks like, in this case, the only comma which you are having issues with is located in a URL. You could run your <code>csv</code> file through a preprocessor method which strips out commas in your URLs or URL encode them. </p> <p>Personally, I would opt for the URL encoding method which will convert the comma...
1
2016-07-08T15:52:34Z
[ "python", "csv" ]
Python - add information to items in a list thereby creating a list of tuples
38,270,480
<p>I have a list:</p> <pre><code>list1 = [1,2,3] </code></pre> <p>I'm looking up info for each item in the list via some arbitrary function, and want to add the results so the list becomes:</p> <pre><code>list1 = [(1,a),(2,b),(3,x)] </code></pre> <p>How to best accomplish this in Python3?</p> <pre><code>for item i...
3
2016-07-08T15:33:35Z
38,270,509
<p>If you have <code>list1 = [1,2,3]</code> and <code>list2 = [x,y,z]</code>, <code>zip(list1, list2)</code> will give you what you're looking for. You will need to iterate over the first list with the function to find <code>x, y, z</code> and put it in a list. </p> <p><code>zip(list1, list2)</code></p> <blockquote> ...
0
2016-07-08T15:35:07Z
[ "python", "list", "tuples" ]
Python - add information to items in a list thereby creating a list of tuples
38,270,480
<p>I have a list:</p> <pre><code>list1 = [1,2,3] </code></pre> <p>I'm looking up info for each item in the list via some arbitrary function, and want to add the results so the list becomes:</p> <pre><code>list1 = [(1,a),(2,b),(3,x)] </code></pre> <p>How to best accomplish this in Python3?</p> <pre><code>for item i...
3
2016-07-08T15:33:35Z
38,270,621
<p>It is not possible to assign a list item with the iteration variable (<code>item</code> in your case). In fact, there is nothing special about the variable <code>item</code> compared to an assignment with <code>=</code>. If the operation is intended to be in-place, you should do</p> <pre><code>for i, item in enumer...
3
2016-07-08T15:40:38Z
[ "python", "list", "tuples" ]
Python - add information to items in a list thereby creating a list of tuples
38,270,480
<p>I have a list:</p> <pre><code>list1 = [1,2,3] </code></pre> <p>I'm looking up info for each item in the list via some arbitrary function, and want to add the results so the list becomes:</p> <pre><code>list1 = [(1,a),(2,b),(3,x)] </code></pre> <p>How to best accomplish this in Python3?</p> <pre><code>for item i...
3
2016-07-08T15:33:35Z
38,270,637
<p>You need a list comprehension:</p> <pre><code>lst = [1,2,3] result = [(item, function(item)) for item in lst] </code></pre> <p>Using <code>list</code> as a name is not a good idea, you'll shadow the original <code>list</code> builtin making it inaccessible later in your code. </p> <p>In case you want to keep the ...
5
2016-07-08T15:41:23Z
[ "python", "list", "tuples" ]
Python - add information to items in a list thereby creating a list of tuples
38,270,480
<p>I have a list:</p> <pre><code>list1 = [1,2,3] </code></pre> <p>I'm looking up info for each item in the list via some arbitrary function, and want to add the results so the list becomes:</p> <pre><code>list1 = [(1,a),(2,b),(3,x)] </code></pre> <p>How to best accomplish this in Python3?</p> <pre><code>for item i...
3
2016-07-08T15:33:35Z
38,270,988
<p>It looks like you just want to change the values in the list to go from a single to a tuple containing the original value and the result of some lookup on that value. This should do what you want.</p> <pre><code>zzz = [1,2,3] i = 0 for num in zzz: zzz[i] = (num, somefunc(num)) i += 1 </code></pre> <p>runni...
1
2016-07-08T15:59:57Z
[ "python", "list", "tuples" ]