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
Python Slice a List Using a List of Multiple Tuples
39,617,956
<p>I have a list of numbers that I would like to slice the range of numbers that is given from a list of multiple tuples. For example, I have a list that looks like:</p> <pre><code>my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0,] </code></pre> <p>I also have a list of tuples that are...
1
2016-09-21T13:27:48Z
39,618,092
<p>You can use the builtin <a href="https://docs.python.org/2/library/functions.html#slice" rel="nofollow">slice</a> as follows</p> <pre><code>my_list = [5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0] my_tups = [(5, 9), (14, 18)] my_list2 = [my_list[slice(*o)] for o in my_tups] print(my_list2) ...
1
2016-09-21T13:33:23Z
[ "python", "list", "tuples", "slice" ]
Python Slice a List Using a List of Multiple Tuples
39,617,956
<p>I have a list of numbers that I would like to slice the range of numbers that is given from a list of multiple tuples. For example, I have a list that looks like:</p> <pre><code>my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0,] </code></pre> <p>I also have a list of tuples that are...
1
2016-09-21T13:27:48Z
39,618,094
<p>You could also use <code>slice</code> with <a href="https://docs.python.org/2/library/itertools.html#itertools.starmap" rel="nofollow"><code>itertools.starmap</code></a>:</p> <pre><code>from itertools import starmap my_list = [ 5., 8., 3., 0., 0., 1., 3., 4., 8., 13., 0., 0., 0., 0., 21., 34., 25., 91., 61., 0., 0...
0
2016-09-21T13:33:24Z
[ "python", "list", "tuples", "slice" ]
Python Slice a List Using a List of Multiple Tuples
39,617,956
<p>I have a list of numbers that I would like to slice the range of numbers that is given from a list of multiple tuples. For example, I have a list that looks like:</p> <pre><code>my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0,] </code></pre> <p>I also have a list of tuples that are...
1
2016-09-21T13:27:48Z
39,618,116
<p>This should do the trick:</p> <pre><code>for a, b in my_tups: print(my_list[a:b]) </code></pre> <p>Instead of printing you can do something else with the list.</p>
0
2016-09-21T13:34:03Z
[ "python", "list", "tuples", "slice" ]
Python Slice a List Using a List of Multiple Tuples
39,617,956
<p>I have a list of numbers that I would like to slice the range of numbers that is given from a list of multiple tuples. For example, I have a list that looks like:</p> <pre><code>my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0,] </code></pre> <p>I also have a list of tuples that are...
1
2016-09-21T13:27:48Z
39,618,169
<p>Using list comprehension:</p> <pre><code>my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0,] my_tups = [(5,9), (14,18)] new_list = [my_list[i:j] for i,j in my_tups] </code></pre> <hr> <p>After your comment:</p> <pre><code>my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 3...
3
2016-09-21T13:36:29Z
[ "python", "list", "tuples", "slice" ]
Python Slice a List Using a List of Multiple Tuples
39,617,956
<p>I have a list of numbers that I would like to slice the range of numbers that is given from a list of multiple tuples. For example, I have a list that looks like:</p> <pre><code>my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0,] </code></pre> <p>I also have a list of tuples that are...
1
2016-09-21T13:27:48Z
39,618,288
<p>You can do something like this on a list comprehension</p> <pre><code>slices = [my_list[x:y] for x, y in my_tups if x &lt; len(my_list) and y &lt; len(my_list)] </code></pre>
0
2016-09-21T13:41:28Z
[ "python", "list", "tuples", "slice" ]
Python - separate duplicate objects into different list
39,618,210
<p>So let say I have this class:</p> <pre><code>class Spam(object): def __init__(self, a): self.a = a </code></pre> <p>And now I have these objects:</p> <pre><code>s1 = Spam((1, 1, 1, 4)) s2 = Spam((1, 2, 1, 4)) s3 = Spam((1, 2, 1, 4)) s4 = Spam((2, 2, 1, 4)) s5 = Spam((2, 1, 1, 8)) s6 = Spam((2, 1,...
0
2016-09-21T13:38:09Z
39,618,362
<p>I would group together the objects in a dictionary, using the <code>a</code> attribute as the key. Then I would separate them by the size of the groups.</p> <pre><code>import collections def separate_dupes(seq, key_func): d = collections.defaultdict(list) for item in seq: d[key_func(item)].append(i...
2
2016-09-21T13:44:03Z
[ "python", "duplicates", "unique" ]
Python - separate duplicate objects into different list
39,618,210
<p>So let say I have this class:</p> <pre><code>class Spam(object): def __init__(self, a): self.a = a </code></pre> <p>And now I have these objects:</p> <pre><code>s1 = Spam((1, 1, 1, 4)) s2 = Spam((1, 2, 1, 4)) s3 = Spam((1, 2, 1, 4)) s4 = Spam((2, 2, 1, 4)) s5 = Spam((2, 1, 1, 8)) s6 = Spam((2, 1,...
0
2016-09-21T13:38:09Z
39,618,416
<p>If you add an <code>__eq__</code> method to <code>Spam</code>, defined as</p> <pre><code>def __eq__(self, other): return self.a == other.a </code></pre> <p>then you can do this quite simply with something like</p> <pre><code># you can inline this if you want, just wanted to give it a name def except_at(elems,...
1
2016-09-21T13:46:18Z
[ "python", "duplicates", "unique" ]
Python - separate duplicate objects into different list
39,618,210
<p>So let say I have this class:</p> <pre><code>class Spam(object): def __init__(self, a): self.a = a </code></pre> <p>And now I have these objects:</p> <pre><code>s1 = Spam((1, 1, 1, 4)) s2 = Spam((1, 2, 1, 4)) s3 = Spam((1, 2, 1, 4)) s4 = Spam((2, 2, 1, 4)) s5 = Spam((2, 1, 1, 8)) s6 = Spam((2, 1,...
0
2016-09-21T13:38:09Z
39,618,672
<p>Using <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>, these are the keys that are common to more than one:</p> <pre><code>import collections common = [k for (k, v) in collections.Counter([o.a for o in objects]).items() if v &gt; ...
0
2016-09-21T13:56:29Z
[ "python", "duplicates", "unique" ]
Python - separate duplicate objects into different list
39,618,210
<p>So let say I have this class:</p> <pre><code>class Spam(object): def __init__(self, a): self.a = a </code></pre> <p>And now I have these objects:</p> <pre><code>s1 = Spam((1, 1, 1, 4)) s2 = Spam((1, 2, 1, 4)) s3 = Spam((1, 2, 1, 4)) s4 = Spam((2, 2, 1, 4)) s5 = Spam((2, 1, 1, 8)) s6 = Spam((2, 1,...
0
2016-09-21T13:38:09Z
39,618,675
<p>One way to do this, if the list of objects isn't too large, is to sort the list of objects and then apply <code>groupby</code> to it to get the duplicates. To sort the list we supply a key function that extracts the value of the object's <code>.a</code> attribute.</p> <pre><code>from operator import attrgetter from...
0
2016-09-21T13:56:44Z
[ "python", "duplicates", "unique" ]
Python Django populate() isn't reentrant
39,618,364
<p>I've had a program that has been running fine for months. I've been trying to install Postfix on the server this morning and suddenly start getting an error on the site. Here is the traceback</p> <pre><code>mod_wsgi (pid=11948): Target WSGI script '/var/www/zouzoukos/zouzoukos/wsgi.py$ mod_wsgi (pid=11948): Excep...
0
2016-09-21T13:44:04Z
39,618,850
<p>This error basically means that something is already tried to mess with <code>app_config</code> ordered dict from <code>Apps</code> class before django was able to setup installed apps properly in first place. Check <code>django.apps.registry.Apps#populate</code>, it sais:</p> <pre><code># app_config should be pris...
0
2016-09-21T14:03:27Z
[ "python", "django" ]
Python Django populate() isn't reentrant
39,618,364
<p>I've had a program that has been running fine for months. I've been trying to install Postfix on the server this morning and suddenly start getting an error on the site. Here is the traceback</p> <pre><code>mod_wsgi (pid=11948): Target WSGI script '/var/www/zouzoukos/zouzoukos/wsgi.py$ mod_wsgi (pid=11948): Excep...
0
2016-09-21T13:44:04Z
39,620,676
<p>I tried the approach from @valentjjedi and then I tired manage.py and got a different error indicating a MySQL-python issue so I uninstalled and reinstalled and it worked</p> <pre><code>env/bin/pip uninstall mysql-python env/bin/pip install mysql-python </code></pre>
0
2016-09-21T15:24:55Z
[ "python", "django" ]
BeautifulSoup HTML Table Parsing for the tags without classes
39,618,388
<p>I have this html table: I need to get specific data from this table and assign it to a variable, I do not need all the information. flag = "United Arab Emirates", home_port="Sharjah" etc. Since there are no 'class' on html elements, how do we extract this data. </p> <pre><code> r = requests.get('http://marit...
2
2016-09-21T13:44:40Z
39,618,492
<p>Go over all the <code>th</code> elements in the table, get the text and the following <code>td</code> sibling's text:</p> <pre><code>from pprint import pprint from bs4 import BeautifulSoup data = """your HTML here""" soup = BeautifulSoup(data, "html.parser") result = {header.get_text(strip=True): header.find_ne...
2
2016-09-21T13:49:34Z
[ "python", "html", "beautifulsoup" ]
BeautifulSoup HTML Table Parsing for the tags without classes
39,618,388
<p>I have this html table: I need to get specific data from this table and assign it to a variable, I do not need all the information. flag = "United Arab Emirates", home_port="Sharjah" etc. Since there are no 'class' on html elements, how do we extract this data. </p> <pre><code> r = requests.get('http://marit...
2
2016-09-21T13:44:40Z
39,619,209
<p>I would do something like this:</p> <pre><code>html = """ &lt;your table&gt; """ from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') flag = soup.find("th", string="Flag").find_next("td").get_text(strip=True) home_port = soup.find("th", string="Home port").find_next("td").get_text(...
0
2016-09-21T14:18:28Z
[ "python", "html", "beautifulsoup" ]
Simulating multi-user to operate PostgreSQL by Python?
39,618,478
<p>I want to compare my distributed database and postgresql. So I need to simulate multi-user SQL operations on postgresql using Python.</p> <p>Can I use the <code>mutliprocessing</code> module?</p> <p>here is my code</p> <pre><code> # encoding=utf-8 import datetime import multiprocessing import psycopg2 def exe(...
0
2016-09-21T13:48:56Z
39,619,169
<p>You can use the <code>random</code> function to generate random 'ST_MAKEENVELOPE` qualifiers this is assuming they belong to some range. And then use the random function to get 5 different ID's of ST_MAKEENVELOPE.</p> <p>Another thing you can just use <code>for cmd in range(5):</code> instead of creating a list and...
1
2016-09-21T14:16:46Z
[ "python", "postgresql", "parallel-processing" ]
Python Sockets, Advanced Chat Box
39,618,547
<p>I want to create a server that <strong>handles</strong> a lot of clients at the same time (<strong>handles</strong>: receiving data from clients and sending data to all clients at the same time!!!)</p> <p>Actually i'm trying to create a chat box. The program will work like this:</p> <p>1) There's going to be a ser...
0
2016-09-21T13:51:30Z
39,619,882
<p>Multithreading is great when the different clients are independant of each other: you write your code as if only one client existed and you start a thread for each client.</p> <p>But here, what comes from one client must be send to the others. One thread per client will certainly lead to a synchronization nightmare...
1
2016-09-21T14:50:40Z
[ "python", "multithreading", "sockets" ]
Python Sockets, Advanced Chat Box
39,618,547
<p>I want to create a server that <strong>handles</strong> a lot of clients at the same time (<strong>handles</strong>: receiving data from clients and sending data to all clients at the same time!!!)</p> <p>Actually i'm trying to create a chat box. The program will work like this:</p> <p>1) There's going to be a ser...
0
2016-09-21T13:51:30Z
39,622,680
<p><em>This my final program and works like a charm.</em></p> <p><strong>Server.py</strong></p> <p>import socket, select</p> <p>class Server:</p> <pre><code>def __init__(self, ip = "", port = 5050): '''Server Constructor. If __init__ return None, then you can use self.error to print the specified error ...
0
2016-09-21T17:12:59Z
[ "python", "multithreading", "sockets" ]
django admin custom view in model properties
39,618,586
<p>I have such models:</p> <pre><code>class Product(models.Model): ... id = models.IntegerField(unique=True) ... class Question(models.Model): product = models.ForeignKey(Product, related_name='question', null=True) answer = models.ForeignKey(Answer, related_name='question', blank=True, null=True)...
0
2016-09-21T13:53:11Z
39,619,301
<p>You'll need to create a custom <strong>ModelAdmin</strong> for <strong>Questions</strong> and override the <strong>form</strong> property, as explained at <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref...
1
2016-09-21T14:21:46Z
[ "python", "django", "django-models", "django-admin", "django-views" ]
Impute missing data, while forcing correlation coefficient to remain the same
39,618,648
<p>Consider the following (excel) dataset:</p> <pre><code>m | r ----|------ 2.0 | 3.3 0.8 | | 4.0 1.3 | 2.1 | 5.2 | 2.3 | 1.9 2.5 | 1.2 | 3.0 2.0 | 2.6 </code></pre> <p><strong>My goal is to fill in missing values using the following condition:</strong></p> <blockquote> <p>Denote as R the pa...
7
2016-09-21T13:55:39Z
39,622,066
<p>This is how I would approach it, with an implementation in R provided: </p> <p>There is not a unique solution for imputing the missing data points, such that the pairwise correlation of the complete (imputed) data is equal to the pairwise correlation of the incomplete data. So to find a 'good' solution rather than ...
5
2016-09-21T16:38:12Z
[ "python", "matlab", "julia-lang" ]
Pandas convert columns type from list to np.array
39,618,678
<p>I'm trying to apply a function to a pandas dataframe, such a function required two np.array as input and it fit them using a well defined model.</p> <p>The point is that I'm not able to apply this function starting from the selected columns since their "rows" contain list read from a JSON file and not np.array.</p>...
0
2016-09-21T13:56:46Z
39,619,291
<p>Use <code>apply</code> to convert each element to it's equivalent array:</p> <pre><code>df['col1'] = df['col1'].apply(lambda x: np.array(x)) type(df['col1'].iloc[0]) numpy.ndarray </code></pre> <p>Data:</p> <pre><code>df = pd.DataFrame({'col1': [[1,2,3],[0,0,0]]}) df </code></pre> <p><a href="http://i.stack.img...
2
2016-09-21T14:21:17Z
[ "python", "pandas", "numpy", "dataframe", "casting" ]
Converting list of list to dictionary
39,618,805
<p>I have the following list of list:</p> <pre><code>[[u'3', u'4'], [u'4', u'5'], [u'7', u'8'], [u'1', u'2'], [u'2', u'3'], [u'6', u'7'], [u'5', u'6']] </code></pre> <p>I want to obtain:</p> <pre><code>{3:'4', 4:'5', 7:'8', 1:'2', 2:'3', 6:'7', 5:'6'} </code></pre> <p>List could be long, so it needs to be more effi...
-4
2016-09-21T14:02:02Z
39,618,854
<p>You can use a <em>dictionary comprehension</em>:</p> <pre><code>&gt;&gt;&gt; l = [[u'3', u'4'], [u'4', u'5'], [u'7', u'8'], [u'1', u'2'], [u'2', u'3'], [u'6', u'7'], [u'5', u'6']] &gt;&gt;&gt; {int(key): value for key, value in l} {1: u'2', 2: u'3', 3: u'4', 4: u'5', 5: u'6', 6: u'7', 7: u'8'} </code></pre> <p>Not...
3
2016-09-21T14:03:43Z
[ "python", "algorithm", "list", "dictionary" ]
Converting list of list to dictionary
39,618,805
<p>I have the following list of list:</p> <pre><code>[[u'3', u'4'], [u'4', u'5'], [u'7', u'8'], [u'1', u'2'], [u'2', u'3'], [u'6', u'7'], [u'5', u'6']] </code></pre> <p>I want to obtain:</p> <pre><code>{3:'4', 4:'5', 7:'8', 1:'2', 2:'3', 6:'7', 5:'6'} </code></pre> <p>List could be long, so it needs to be more effi...
-4
2016-09-21T14:02:02Z
39,618,860
<pre><code>my_dict = {} for item in my_list: my_dict[int(item[0])] = item[1] </code></pre>
1
2016-09-21T14:03:56Z
[ "python", "algorithm", "list", "dictionary" ]
Plotting timestampt data from CSV using matplotlib
39,618,881
<p>I am trying to plot data from a csv file using matplotlib. There is 1 column against a timestamp:</p> <pre><code>26-08-2016 00:01 0.062964691 26-08-2016 00:11 0.047209214 26-08-2016 00:21 0.047237823 </code></pre> <p>I have only been able to create a simple plot using only integers using the code below, w...
0
2016-09-21T14:04:33Z
39,619,423
<p>Here's my example for this problem:</p> <pre><code>import pandas as pd from io import StringIO from datetime import datetime %matplotlib inline import matplotlib import matplotlib.pyplot as plt data_file = StringIO(""" time,value 26-08-2016 00:01,0.062964691 26-08-2016 00:11,0.047209214 26-08-2016 00:21,0.04723782...
0
2016-09-21T14:28:05Z
[ "python", "csv", "matplotlib", "plot" ]
Why does the floating-point value of 4*0.1 look nice in Python 3 but 3*0.1 doesn't?
39,618,943
<p>I know that most decimals don't have an exact floating point representation (<a href="http://stackoverflow.com/questions/588004">Is floating point math broken?</a>).</p> <p>But I don't see why <code>4*0.1</code> is printed nicely as <code>0.4</code>, but <code>3*0.1</code> isn't, when both values actually have ugly...
148
2016-09-21T14:07:21Z
39,619,388
<p><code>repr</code> (and <code>str</code> in Python 3) will put out as many digits as required to make the value unambiguous. In this case the result of the multiplication <code>3*0.1</code> isn't the closest value to 0.3 (0x1.3333333333333p-2 in hex), it's actually one LSB higher (0x1.3333333333334p-2) so it needs mo...
73
2016-09-21T14:26:14Z
[ "python", "floating-point", "rounding", "floating-accuracy", "ieee-754" ]
Why does the floating-point value of 4*0.1 look nice in Python 3 but 3*0.1 doesn't?
39,618,943
<p>I know that most decimals don't have an exact floating point representation (<a href="http://stackoverflow.com/questions/588004">Is floating point math broken?</a>).</p> <p>But I don't see why <code>4*0.1</code> is printed nicely as <code>0.4</code>, but <code>3*0.1</code> isn't, when both values actually have ugly...
148
2016-09-21T14:07:21Z
39,619,467
<p>The simple answer is because <code>3*0.1 != 0.3</code> due to quantization (roundoff) error (whereas <code>4*0.1 == 0.4</code> because multiplying by a power of two is usually an "exact" operation).</p> <p>You can use the <code>.hex</code> method in Python to view the internal representation of a number (basically,...
287
2016-09-21T14:30:11Z
[ "python", "floating-point", "rounding", "floating-accuracy", "ieee-754" ]
Why does the floating-point value of 4*0.1 look nice in Python 3 but 3*0.1 doesn't?
39,618,943
<p>I know that most decimals don't have an exact floating point representation (<a href="http://stackoverflow.com/questions/588004">Is floating point math broken?</a>).</p> <p>But I don't see why <code>4*0.1</code> is printed nicely as <code>0.4</code>, but <code>3*0.1</code> isn't, when both values actually have ugly...
148
2016-09-21T14:07:21Z
39,623,207
<p>Here's a simplified conclusion from other answers.</p> <blockquote> <p>If you check a float on Python's command line or print it, it goes through function <code>repr</code> which creates its string representation.</p> <p>Starting with version 3.2, Python's <code>str</code> and <code>repr</code> use a complex...
19
2016-09-21T17:42:10Z
[ "python", "floating-point", "rounding", "floating-accuracy", "ieee-754" ]
Why does the floating-point value of 4*0.1 look nice in Python 3 but 3*0.1 doesn't?
39,618,943
<p>I know that most decimals don't have an exact floating point representation (<a href="http://stackoverflow.com/questions/588004">Is floating point math broken?</a>).</p> <p>But I don't see why <code>4*0.1</code> is printed nicely as <code>0.4</code>, but <code>3*0.1</code> isn't, when both values actually have ugly...
148
2016-09-21T14:07:21Z
39,633,884
<p>Not really specific to Python's implementation but should apply to any float to decimal string functions.</p> <p>A floating point number is essentially a binary number, but in scientific notation with a fixed limit of significant figures.</p> <p>The inverse of any number that has a prime number factor that is not ...
5
2016-09-22T08:25:23Z
[ "python", "floating-point", "rounding", "floating-accuracy", "ieee-754" ]
Deprecated Scikit-learn module prevents joblib from loading it
39,618,985
<p>I have a Hidden Markov Model that has been pickled with joblib using the sklearn.hmm module. Apparently, in version 0.17.x this module has been deprecated and moved to hmmlearn. I am unable to load the model and I get the following error:</p> <blockquote> <p>ImportError: No module named 'sklearn.hmm'</p> </blockq...
0
2016-09-21T14:08:53Z
39,621,200
<p>After reverting to scikit-learn 0.16.x, I just needed to install OpenBlas for Ubuntu. It appears that the problem was more a feature of the operating system rather than Python.</p>
0
2016-09-21T15:49:27Z
[ "python", "scikit-learn", "joblib" ]
Why look ahead is returning matches for time-stamp
39,619,098
<p>Trying to write a script in python for some post processing. I have a file that contains messages with a time-stamp. I want to extract all the messages into a list.<br> Regex - start from message until next time-stamp. </p> <pre><code>findallItems = re.findall(r'(?s)((?&lt;=message).*?(?=((\d{4})\-((0[1-9])|(1[0-2...
1
2016-09-21T14:13:48Z
39,619,230
<p>You need to remove unnecessary capturing parentheses and convert others to non-capturing:</p> <pre><code>findallItems = re.findall(r'(?s)(?&lt;=message).*?(?=(?:\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-2])|\Z))', fileread) </code></pre> <p>See <a href="https://regex101.com/r/yE7iF1/1" rel="nofollow">this regex demo</...
1
2016-09-21T14:19:03Z
[ "python", "regex" ]
Cast to Array failed with moongoose and dict
39,619,118
<p>I have a problem to insert a data with mongoose in mongodb </p> <p>Here is my db.js model : </p> <pre><code>var Appointment = new Schema({ date: Date, coach: ObjectId, complement: String, isOwner: Boolean, fiter : ObjectId, fiters: [ { user: ObjectId, isOwner: Boolean, sta...
1
2016-09-21T14:14:48Z
39,630,674
<p>Your Python script is only sending the keys of the dictionary for <code>fiters</code>, try to add <code>.items()</code> to send 2-tuples. I'm not exactly sure which format your ORM expects.</p> <p>If that doesn't work, JSON can also be used to pass complex structures through POST.</p>
1
2016-09-22T05:07:02Z
[ "python", "node.js", "express" ]
Cast to Array failed with moongoose and dict
39,619,118
<p>I have a problem to insert a data with mongoose in mongodb </p> <p>Here is my db.js model : </p> <pre><code>var Appointment = new Schema({ date: Date, coach: ObjectId, complement: String, isOwner: Boolean, fiter : ObjectId, fiters: [ { user: ObjectId, isOwner: Boolean, sta...
1
2016-09-21T14:14:48Z
39,637,911
<p>the answer was to send json instead of data :</p> <pre><code>appointment = { "_id":idFiter, "date": "2016-09-25T00:00:00.0000000Z", "coach":"57dfd22f7f8effc700bfa16f", "fiters" : [ { "user": "57da891db39797707093c6e1", "isOwner": False, "status": "invite", "invit...
1
2016-09-22T11:35:11Z
[ "python", "node.js", "express" ]
Plotting direction field in python
39,619,128
<p>I want to plot direction field for a simple equation: </p> <pre><code>y' = 3 − 2y </code></pre> <p>I have found similar Matlab problem <a href="http://www.math.tamu.edu/~efendiev/math442_spring04/matlabode.pdf" rel="nofollow">here</a> (1.3). But I do not know how to rewrite it to python. My last try is: </p> ...
0
2016-09-21T14:15:10Z
39,619,305
<p><code>dx</code> and <code>dy</code> must be of the same shape as <code>X</code> and <code>Y</code>.</p> <p>Currently, you have a shape of <code>(14, 20)</code> for <code>X</code>, <code>Y</code> and <code>dy</code>, but <code>(10,10)</code> for <code>dx</code>. </p> <p>If you change the line defining <code>dx</cod...
2
2016-09-21T14:21:56Z
[ "python", "matlab", "numpy", "matplotlib", "scipy" ]
Plotting direction field in python
39,619,128
<p>I want to plot direction field for a simple equation: </p> <pre><code>y' = 3 − 2y </code></pre> <p>I have found similar Matlab problem <a href="http://www.math.tamu.edu/~efendiev/math442_spring04/matlabode.pdf" rel="nofollow">here</a> (1.3). But I do not know how to rewrite it to python. My last try is: </p> ...
0
2016-09-21T14:15:10Z
39,620,591
<p>You could also use the <a href="https://en.wikipedia.org/wiki/Streamlines,_streaklines,_and_pathlines" rel="nofollow">streamlines</a> of the filed to give a nice impression of the flow, and colour the curves according to some property of the field (dy in this case). Look at the following example:</p> <pre><code>nx,...
2
2016-09-21T15:20:44Z
[ "python", "matlab", "numpy", "matplotlib", "scipy" ]
Django saving in a model with User field
39,619,133
<p>I have token auth implemented in django and my models looks like-</p> <pre><code>class Portfolio(models.Model): owner = models.ForeignKey(User, verbose_name='User', null=True) company = models.TextField(null=True) volume = models.IntegerField(blank=True) date = models.DateField(null=True) </code></pre> <p>...
0
2016-09-21T14:15:25Z
39,619,215
<p>Your <code>user_is</code> is a <code>User</code> model instance which is not <em>saved</em> in the database:</p> <pre><code>user_is = User(username=user) # ??? username != user </code></pre> <hr> <p>Why not do:</p> <pre><code>user_is = User.objects.get(username=request.user.username) </code></pre> <p>Or make <c...
0
2016-09-21T14:18:36Z
[ "python", "django" ]
Django saving in a model with User field
39,619,133
<p>I have token auth implemented in django and my models looks like-</p> <pre><code>class Portfolio(models.Model): owner = models.ForeignKey(User, verbose_name='User', null=True) company = models.TextField(null=True) volume = models.IntegerField(blank=True) date = models.DateField(null=True) </code></pre> <p>...
0
2016-09-21T14:15:25Z
39,619,312
<p>It's because you didn't save your user e.g. it doesn't have an id in database. Also you need a <code>User</code> instance and not <code>QuerySet</code> which you'll get from calling <code>User.objects.filter(username=request.user)</code>.</p> <p>Try to:</p> <pre><code>user_is = User.objects.get(username=request.us...
0
2016-09-21T14:22:15Z
[ "python", "django" ]
Measure border overlap between numpy 2d regions
39,619,187
<p>I have a large numpy 2d (10000,10000) with many regions (clustered cells with the same cell value). Wat I want is to merge neighbouring regions which are showing more than 35% border overlap. This overlap should be measured by dividing the size of the common border with the neighbour, by the total border size of the...
1
2016-09-21T14:17:29Z
39,634,445
<p>Take a look at this <a href="http://stackoverflow.com/questions/39346545/count-cells-of-adjacent-numpy-regions/39348877#39348877">Count cells of adjacent numpy regions</a> for inspiration. Deciding how to merge based on such information is a problem with multiple answers I think; it may not have a unique solution de...
1
2016-09-22T08:53:18Z
[ "python", "arrays", "numpy", "multidimensional-array", "vectorization" ]
Python date comparison with string output/format
39,619,219
<p>I'm currently trying to writing a script to automate a function at work, but I'm not intimately familiar with Python. I'm trying to take a XML dump and compare a specific entry's date to see if the time has passed or not.</p> <p>The date is in a particular format, given:</p> <pre><code>&lt;3-letter Month&gt; &lt;D...
0
2016-09-21T14:18:43Z
39,619,771
<p>You should use combination of gmtime (for GMT time),mktime and datetime.</p> <pre><code>from time import gmtime,mktime from datetime import datetime s = "May 14 20:11:20 2014 GMT" f = "%b %d %H:%M:%S %Y GMT" dt = datetime.strptime(s, f) gmt = datetime.fromtimestamp(mktime(gmtime())) if dt&lt;gmt: print(dt) els...
1
2016-09-21T14:43:57Z
[ "python", "date", "time", "scripting" ]
/bin/sh: line 62: to: command not found
39,619,221
<p>I have a python code in which I am calling a shell command. The part of the code where I did the shell command is:</p> <pre><code>try: def parse(text_list): text = '\n'.join(text_list) cwd = os.getcwd() os.chdir("/var/www/html/alenza/hdfs/user/alenza/sree_account/sree_project/src/core/da...
0
2016-09-21T14:18:47Z
39,619,413
<p>You rarely, if ever, want to combine passing a list argument with <code>shell=True</code>. Just pass the string:</p> <pre><code>synnet_output = subprocess.check_output("echo '%s' | syntaxnet/demo.sh 2&gt;/dev/null"%(text,), shell=True) </code></pre> <p>However, you don't really need a shell pipeline here.</p> <pr...
1
2016-09-21T14:27:44Z
[ "python", "json", "shell", "hadoop", "subprocess" ]
/bin/sh: line 62: to: command not found
39,619,221
<p>I have a python code in which I am calling a shell command. The part of the code where I did the shell command is:</p> <pre><code>try: def parse(text_list): text = '\n'.join(text_list) cwd = os.getcwd() os.chdir("/var/www/html/alenza/hdfs/user/alenza/sree_account/sree_project/src/core/da...
0
2016-09-21T14:18:47Z
39,624,197
<p>There was a problem with some special characters appearing in the text string that i was inputting to <code>demo.sh</code>. I solved this by storing <code>text</code> into a temporary file and sending the contents of that file to <code>demo.sh</code>.</p> <p>That is: </p> <pre><code>try: def parse(text_list): ...
0
2016-09-21T18:40:02Z
[ "python", "json", "shell", "hadoop", "subprocess" ]
Laplacian sharpening - grey image as result
39,619,222
<p>As many people before me, I am trying to implement an example of image sharpening from Gonzalez and Woods "Digital image processing" book.</p> <p>I create a negative Laplacian kernel (-1, -1, -1; -1, 8, -1; -1, -1,-1) and convolve it with the image, then subtract the result from the original image. (I also tried ta...
1
2016-09-21T14:18:48Z
39,620,430
<p>It seems to me that part of the problem has to do with how you are rescaling <code>Lap</code>. I don't think you want to subtract the minimum first - sharpening should decrease the intensity of some pixels as well as increasing that of others. You may also wish to play around with the scaling factor you multiply <co...
0
2016-09-21T15:14:11Z
[ "python", "image-processing", "scipy" ]
Laplacian sharpening - grey image as result
39,619,222
<p>As many people before me, I am trying to implement an example of image sharpening from Gonzalez and Woods "Digital image processing" book.</p> <p>I create a negative Laplacian kernel (-1, -1, -1; -1, 8, -1; -1, -1,-1) and convolve it with the image, then subtract the result from the original image. (I also tried ta...
1
2016-09-21T14:18:48Z
39,659,905
<p>After correcting the code as <strong>ali_m</strong> advised, I apply local histogram equalization - it slows down the code and also adds dependency on the OpenCV library, but the resulting image looks fine.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import scipy.mis...
0
2016-09-23T11:40:23Z
[ "python", "image-processing", "scipy" ]
need to click on particular object on website to load more content multiple time using python and chrome driver
39,619,256
<h1>need to click on particular object multiple times but it is executing only once. please help me</h1> <pre><code> from selenium import webdriver from selenium.webdriver.common.keys import Keys import time chrome_path=r"C:\Users\Bhanwar\Desktop\New folder (2)\chromedriver.exe" driver =webdriver.Chrome...
0
2016-09-21T14:19:44Z
39,622,637
<p>I think that the line <code>driver.implicitly_wait(10)</code> doesn't actually make the driver wait at that time, and because there is an element with a css selector of <code>.loadmore</code> in the page the whole time, that element may be getting clicked faster than the page can handle. Another way to check would b...
0
2016-09-21T17:10:28Z
[ "python", "google-chrome", "selenium" ]
Integer parameter in pandas DataFrame.drop function
39,619,295
<p>In following line of code</p> <pre><code> X = np.array(df.drop(['label'], 1)) </code></pre> <p>Could you please explain what does number <code>1</code> do? </p> <p>From documentation I understand that <code>DataFrame.drop</code> function drops desired column named <code>'label'</code> from dataframe and returns n...
1
2016-09-21T14:21:22Z
39,619,316
<p>It is parameter <code>axis</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>drop</code></a>. It is same as <code>axis=1</code>. And it means you need remove columns from <code>DataFrame</code> which are specify in first parameter <code>labels</...
2
2016-09-21T14:22:24Z
[ "python", "pandas", "dataframe", "int", "multiple-columns" ]
How to perform a left join in SQLALchemy?
39,619,353
<p>I have a SQL query which perfroms a series of left joins on a few tables:</p> <pre><code>SELECT &lt;some attributes&gt; FROM table1 t1 INNER JOIN table2 t2 ON attr = 1 AND attr2 = 1 LEFT JOIN table3 t3 ON t1.Code = t2.Code AND t3.Date_ = t1.Date_ LEFT JOIN tabl4 t4 ON t4.Code = t1.code AND t4.Date_ = ...
0
2016-09-21T14:24:26Z
39,669,377
<p>The isouter=True flag will produce a <code>LEFT OUTER JOIN</code> which is the same as a <code>LEFT JOIN</code>.</p>
0
2016-09-23T20:53:28Z
[ "python", "sql", "sqlalchemy" ]
Django Tables2 Display Multiple Tables
39,619,369
<p>I've got user records that have related(ish) course and enrollment records. I want to click on a user and see raw data from the user table, course table, and enrollment table in the same page.</p> <p>The process breaks down when I attempt to render the tables.</p> <p>views.py:</p> <pre><code>def explore_related(...
0
2016-09-21T14:25:05Z
39,619,749
<p>If you use custom table classes, you need to use a <strong>RequestConfig</strong> object to properly set-up the table.</p> <p>In your example, it should be enough to add</p> <pre><code>RequestConfig(request, paginate=False).configure(userTable) RequestConfig(request, paginate=False).configure(courseTable) RequestC...
0
2016-09-21T14:42:40Z
[ "python", "django", "django-tables2" ]
Read and Write file from MS Azure using Python
39,619,379
<p>I am newbie to Python and Spark, I am trying to load file from Azure to table. Below is my simple code. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import os import...
0
2016-09-21T14:25:35Z
39,653,591
<p>@Miruthan, As far as I know, If we'd like to read data from WASB into Spark, the URL syntax is as following :</p> <pre><code>wasb[s]://&lt;containername&gt;@&lt;accountname&gt;.blob.core.windows.net/&lt;path&gt; </code></pre> <p>Meanwhile, due to Azure Storage Blob (WASB) is used as the storage account associated ...
0
2016-09-23T06:01:27Z
[ "python", "azure", "apache-spark", "pyspark" ]
Replace multiple lines after pattern in python?
39,619,471
<p>I want to write a python script to replace first word in multiple lines after my pattern, by now I can only replace 1 line after my pattern, how can it replace more lines? Let's say 3 lines. </p> <p>lines.txt (input file, pattern"section 2") :</p> <pre><code>section 1 line 1 line 2 line 3 line 4 endsection section...
0
2016-09-21T14:30:16Z
39,620,135
<pre><code>list_of_words_to_replace = ['mod','apple','xxx'] with open('E:/lines.txt') as fin, open('E:/lines_mod.txt', 'w') as fout: flag = 0 counter = 0 # &lt;&lt;&lt;&lt;------- added a counter for line in fin: if flag == 1: counter += 1 #&lt;&lt;&lt;&lt;-------- increasing counter b...
0
2016-09-21T15:00:22Z
[ "python", "python-2.7" ]
Replace multiple lines after pattern in python?
39,619,471
<p>I want to write a python script to replace first word in multiple lines after my pattern, by now I can only replace 1 line after my pattern, how can it replace more lines? Let's say 3 lines. </p> <p>lines.txt (input file, pattern"section 2") :</p> <pre><code>section 1 line 1 line 2 line 3 line 4 endsection section...
0
2016-09-21T14:30:16Z
39,620,853
<p>You need to revisit your flag update criteria to match the expected output.</p> <p>Since you set <code>flag = 1</code> for the <code>if line.find('section 2') != -1</code> condition, it will modify only one line following the matched line.</p> <p>Since you mention you want to replace more lines, you can probably a...
0
2016-09-21T15:33:07Z
[ "python", "python-2.7" ]
How to find file path for specific file for multiple folders
39,619,574
<p>The title doesn't really explain it well, so I'll try to explain it better here. I'm not expecting to be spoon-fed, but I'd like to be pointed in the right direction as to how I would do this.</p> <p>I have one folder, let's call it A.</p> <p>A has 100 other folders in, that have the folder name as just a complete...
0
2016-09-21T14:35:21Z
39,620,619
<p>What you require can be achieved with the 'find' command on the shell.</p> <p>After changing into the main directory with all the subdirectories, to get the relative path, execute:</p> <pre><code>find -name *.bsp ./1/aa.bsp ./2/bb.bsp ./3/cc.bsp </code></pre> <p>And for absolute path, execute:</p> <pre><code>fin...
0
2016-09-21T15:22:03Z
[ "python" ]
struct.unpack(struct.pack(float)) has roundoff error?
39,619,636
<p>When testing my library, <a href="https://github.com/construct/construct" rel="nofollow">Construct</a>, I found out that tests fail when numbers are built then parsed back to a float. Should floats not be represented exactly as in-memory floats?</p> <pre><code>In [14]: d = struct.Struct("&lt;f") In [15]: d.unpack(...
0
2016-09-21T14:37:48Z
39,619,662
<p>Floating point is inherently imprecise, but you are packing a double-precision float (<code>binary64</code>) into a single-precision (<code>binary32</code>) space there. See <a href="https://en.wikipedia.org/wiki/IEEE_floating_point#Basic_and_interchange_formats" rel="nofollow"><em>Basic and interchange formats</em>...
3
2016-09-21T14:38:59Z
[ "python", "floating-point", "pack" ]
csv.reader read from Requests stream: iterator should return strings, not bytes
39,619,676
<p>I'm trying to stream response to <code>csv.reader</code> using <code>requests.get(url, stream=True)</code> to handle quite big data feeds. My code worked fine with <code>python2.7</code>. Here's code:</p> <pre><code>response = requests.get(url, stream=True) ret = csv.reader(response.iter_lines(decode_unicode=True)...
5
2016-09-21T14:39:44Z
39,620,977
<p>I'm guessing you could wrap this in a <code>genexp</code> and feed decoded lines to it:</p> <pre><code>from contextlib import closing with closing(requests.get(url, stream=True)) as r: f = (line.decode('utf-8') for line in r.iter_lines()) reader = csv.reader(f, delimiter=',', quotechar='"') for row in ...
2
2016-09-21T15:38:30Z
[ "python", "django", "python-3.x", "csv", "python-requests" ]
How to read django autocomplete lights value to generate choices dynamically?
39,619,709
<p>Hey i would like to get the value of django autocomplete light in the model form and generate choices for the next fields accordingly.</p> <pre><code>class GroupPropertiesForm(forms.ModelForm): &lt;strike&gt;fields['equipment_grade']: forms.ChoiceField( choices=[(o.id, str(o)) for...
0
2016-09-21T14:41:03Z
39,762,980
<p>This is not the correct way to implement this functionality, autocomplete light will provide information as a forward for the next attribute as they have written <a href="https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#filtering-results-based-on-the-value-of-other-fields-in-the-form" rel="no...
1
2016-09-29T06:32:26Z
[ "python", "django", "django-forms", "django-admin", "django-autocomplete-light" ]
How to convert a Numpy matrix into a Sympy
39,619,718
<p>I have constructed a randomly generated matrix of a specified size and that part works great. Give it a row and column size and boom a matrix of whole numbers from 0 to 100. More recently I tried to perform a sympy operation to a numpy matrix and python kept crashing on me. I soon learned that operations from sympy ...
-2
2016-09-21T14:41:22Z
39,621,887
<p><strong>TL;DR</strong> Perform <code>sympy.Matrix(numpy_matrix)</code></p> <p>From comments, I suggest this</p> <h1>Converting NumPy matrix to SymPy matrix</h1> <pre><code>import math import numpy as SHIT import sympy as GARBAGE from sympy import * from sympy import Matrix from sympy.utilities.lambdify import lam...
0
2016-09-21T16:28:03Z
[ "python", "numpy", "matrix", "sympy" ]
Python Pandas select rows based on membership of another collection (set)
39,619,799
<p>Suppose I have a <code>DataFrame</code> constructed as follows:</p> <pre><code>import pandas import numpy column_names = ["name", "age", "score"] names = numpy.random.choice(["Jorge", "Xavier", "Joaquin", "Juan", "Jose"], 50) ages = numpy.random.randint(0, 100, 50) scores = numpy.random.rand(50) df = pandas.DataFr...
1
2016-09-21T14:45:03Z
39,619,839
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a>:</p> <pre><code>print (df.loc[df["name"].isin(["Xavier", "Joaquin"]), :]) age name score 1 66 Joaquin 0.767056 2 17 Joaquin 0.721369 7 53 Joaquin 0...
2
2016-09-21T14:46:59Z
[ "python", "pandas", "indexing", "set", "condition" ]
Can Django collectstatic overwrite old files?
39,619,900
<p>In my deb postinst file:</p> <pre><code>PYTHON=/usr/bin/python PYTHON_VERSION=`$PYTHON -c 'import sys; print sys.version[:3]'` SITE_PACKAGES=/opt/pkgs/mypackage/lib/python$PYTHON_VERSION/site-packages export PYTHONPATH=$SITE_PACKAGES echo "collect static files" $PYTHON manage.py collectstatic --noinput </code></pr...
0
2016-09-21T14:51:28Z
39,640,609
<p>(Added here, maybe someone will have same problems with mine.) Yes.</p> <p>The timestamp of css files in /opt/pkgs/mypropject/lib/python2.7/site-packages/mypropject-py2.7.egg/myapp/static/css (directory A) is the time when package building finished, not the time when css files installed.</p> <p>But the timestamp o...
0
2016-09-22T13:35:37Z
[ "python", "css", "django", "debian", "deb" ]
Django-Haystack(elasticsearch) Autocomplete giving results for substring in search term
39,619,944
<p>I have a search index with elasticsearch as backend:</p> <pre><code>class MySearchIndex(indexes.SearchIndex, indexes.Indexable): ... name = indexes.CharField(model_attr='name') name_auto = indexes.NgramField(model_attr='name') ... </code></pre> <p>Suppose I have following values in elasticsearc...
0
2016-09-21T14:53:15Z
39,654,127
<p>Customize your elasticsearch backend settings with <a href="https://github.com/rhblind/django-hesab" rel="nofollow">django-hesab</a></p> <p>The default settings of django-hesab will return the exact search result. </p>
0
2016-09-23T06:37:20Z
[ "python", "django", "elasticsearch", "django-haystack" ]
Is this the most efficient and accurate way to extrapolate using scipy?
39,619,960
<p>I have a set of data points over time, but there is some missing data and the data is not at regular intervals. In order to get a full data set over time at regular intervals I did the following:</p> <pre><code>import pandas as pd import numpy as np from scipy import interpolate x = data['time'] y = data['shares'...
0
2016-09-21T14:54:14Z
39,620,414
<p>You should apply interpolation function only once, like this</p> <pre><code>new_data = f(time) </code></pre> <p>If you need values at regular intervals fill_value='extrapolate' is redundant, because it is just interpolation. You may use 'extrapolate' if your new interval is wider than original one. But it is bad p...
1
2016-09-21T15:13:42Z
[ "python", "numpy", "scipy" ]
Python regex freezes with small input string
39,619,973
<p>I am using regular expressions on a bunch of wikipedia pages. Actually working really good for the first like 20 pages, but then it suddenly freezes without me seeing a reason. Interrupting the script delivers this:</p> <pre><code>File "imageListFiller.py", line 30, in getImage foundImage = re.search(urlRegex, str(...
2
2016-09-21T14:54:38Z
39,620,170
<p>The <code>$-_</code> part in your pattern created a range matching uppercase letters and digits, and even more chars. Since other alternative branches in the group could match at the same location (like <code>[a-zA-Z]</code>) that led to a time out / catastrophic backtracking issue.</p> <p>You need to just concat a...
1
2016-09-21T15:02:27Z
[ "python", "regex", "freeze" ]
Pycharm cannot find installed packages: keras
39,620,014
<p>I installed pycharm-2016.1.4 in my PC running Ubuntu 14.04. I have installed keras (a python package) using <code>pip install keras</code> and pycharm <strong>can</strong> find it <strong>before</strong>. But it <strong>cannot</strong> find keras <strong>now</strong>. I do not modify any settings, so this problem ma...
1
2016-09-21T14:56:26Z
39,635,116
<p>This is strange, but you can install Keras directly through Pycharm.</p> <p>You can follow this steps:</p> <ul> <li>Go to <strong>Settings -> Project -> Project Interpreter</strong> </li> <li>Click on <strong>plus icon</strong> in the top-right corner</li> <li>Search <strong>Keras</strong> and press on <strong>Ins...
2
2016-09-22T09:24:01Z
[ "python", "python-2.7", "pycharm", "keras" ]
Pycharm cannot find installed packages: keras
39,620,014
<p>I installed pycharm-2016.1.4 in my PC running Ubuntu 14.04. I have installed keras (a python package) using <code>pip install keras</code> and pycharm <strong>can</strong> find it <strong>before</strong>. But it <strong>cannot</strong> find keras <strong>now</strong>. I do not modify any settings, so this problem ma...
1
2016-09-21T14:56:26Z
39,673,259
<p>I do not know what happened, but the problem solved with the following steps.</p> <ol> <li>Uninstall old keras </li> <li>Re-install keras: <code>pip install keras</code></li> </ol> <p>Then I can <code>import keras</code> in pycharm.</p> <p><strong>NOTE:</strong> It is strange since I have keras installed but cann...
0
2016-09-24T06:26:29Z
[ "python", "python-2.7", "pycharm", "keras" ]
Type of variable changes based on access?
39,620,023
<p>I have a directed graph structure consisting of nodes and edges both of which subclass an Event parent class. Depending on external events, edges can either be active or inactive. I then find all the directed paths from a given node to the root node, but I really only care about the nodes along the way, not the edge...
0
2016-09-21T14:56:45Z
39,620,120
<p>You have your list comprehension order wrong. Nested loops are listed from <em>left to right</em>.</p> <p>So the expression</p> <pre><code>[type(n) for n in path for path in lst] </code></pre> <p>is executed as</p> <pre><code>for n in path: for path in lst: type(n) </code></pre> <p>so <code>n</code>...
3
2016-09-21T15:00:02Z
[ "python", "types", "list-comprehension" ]
Converting between projections using pyproj in Pandas dataframe
39,620,105
<p>This is undoubtedly a bit of a "can't see the wood for the trees" moment. I've been staring at this code for an hour and can't see what I've done wrong. I know it's staring me in the face but I just can't see it!</p> <p>I'm trying to convert between two geographical co-ordinate systems using Python.</p> <p>I have ...
0
2016-09-21T14:59:33Z
39,620,728
<p>When you do <code>df[['newLong','newLat']] = df.apply(convertCoords,axis=1)</code>, you are indexing the columns of the <code>df.apply</code> output. However, the column order is arbitrary because your series was defined using a dictionary (which is inherently unordered).</p> <p>You can opt to return a Series with ...
2
2016-09-21T15:27:07Z
[ "python", "python-3.x", "pandas", "gis", "proj" ]
Importing my package from a Django management command
39,620,143
<p>I've written a package which was originally a command-line tool, but I've decided that for Django it should be run from a management command. I've installed my external package (called <code>codequal</code>) using <code>pip install --editable</code>, and I can successfully use <code>manage.py shell</code> to import ...
0
2016-09-21T15:00:54Z
39,620,231
<p>The problem is that your file (codequal.py) has the same name that the module. You need to change one of them. I recomended the file inside the app:</p> <pre><code>/home/path/to/django/project/some_app/management/commands/codequal.py </code></pre> <p>to</p> <pre><code>/home/path/to/django/project/some_app/managem...
2
2016-09-21T15:05:52Z
[ "python", "django", "setuptools", "django-management-command" ]
SciPy Minimize with monotonically decreasing Xs constraint
39,620,149
<p>I am looking to do a strenuous optimization in which I use SciPy to optimize discount factors for bond cashflows (application less important, but if interested). So essentially I take multiple known values 'P', where P[i] is a function of C[i] known constant, and array X (X[j]=x(t) where x is a function of time). wh...
1
2016-09-21T15:01:14Z
39,621,270
<p>Let's try </p> <pre><code>def con(x): for i in range(len(x)-1): if x[i] &lt;= x[i+1]: return -1 return 1 cons=({'type':'ineq','fun': con}) </code></pre> <p>This should reject lists that aren't set up like you want, but I'm not sure is scipy is going to like it.</p>
0
2016-09-21T15:52:57Z
[ "python", "optimization", "scipy" ]
sklearn Logistic Regression with n_jobs=-1 doesn't actually parallelize
39,620,185
<p>I'm trying to train a huge dataset with sklearn's logistic regression. I've set the parameter n_jobs=-1 (also have tried n_jobs = 5, 10, ...), but when I open htop, I can see that it still uses only one core.</p> <p>Does it mean that logistic regression just ignores the n_jobs parameter?</p> <p>How can I fix this?...
0
2016-09-21T15:03:31Z
39,620,443
<p>the parallel process backend also depends on the solver method. if you want to utilize multi core, the <code>multiprocessing</code> backend is needed. </p> <p>but solver like 'sag' can only use <code>threading</code> backend.</p> <p>and also mostly, it can be blocked due to a lot of pre-processing.</p>
0
2016-09-21T15:14:52Z
[ "python", "python-2.7", "parallel-processing", "scikit-learn", "logistic-regression" ]
Derive a Google Form View ID from the Definition ID
39,620,273
<p>When I define a form, it has the url:</p> <p><a href="https://docs.google.com/a/domain.com/forms/d/1d2Y9R9JJwymtjEbZI6xTMLtS9wB7GDMaopTQeNNNaD0/edit" rel="nofollow">https://docs.google.com/a/domain.com/forms/d/1d2Y9R9JJwymtjEbZI6xTMLtS9wB7GDMaopTQeNNNaD0/edit</a></p> <p>I finish adding the questions I want the for...
0
2016-09-21T15:07:50Z
39,665,908
<p>Use Google Apps Script to publish a Web App (or use the Execution API) to leaverage the "getPublishedUrl" function</p> <pre><code>function doGet(theRequest){ var theDefinitionId = theRequest.parameters.formId; var thePublishedUrl = myAPI_(theDefinitionId); var output = ContentService.createTextOutput(thePubli...
0
2016-09-23T16:53:07Z
[ "python", "google-form" ]
How do I add a custom field to logstash/kibana?
39,620,302
<p>I am using <a href="https://github.com/vklochan/python-logstash" rel="nofollow">python-logstash</a> in order to write to logstash. It offers the option to add extra fields but problem is that all fields are under the <code>message</code> field. What I want to accomplish is adding a new field at the higher level. </...
0
2016-09-21T15:08:41Z
39,650,991
<p>From reading the python-logstash documentation, they refer to "extra" fields and say they "add extra fields to logstash message", which seems like exactly what you want!</p> <pre><code># add extra field to logstash message extra = { 'test_string': 'python version: ' + repr(sys.version_info), 'test_boolean'...
0
2016-09-23T00:57:14Z
[ "python", "logstash" ]
Optimal bulk query size for multiSearch in ElasticSearch
39,620,328
<p>I am trying to query elasticsearch with multisearch , but it doesn't seems to improve the time a lot.</p> <p>For approx <strong>70k queries</strong> , time taken by different bulk_sizes are :</p> <p>For <strong>single search</strong> for every item time taken = <strong>2611s</strong></p> <p>For <strong>multisearc...
0
2016-09-21T15:09:46Z
39,624,742
<p>The number of concurrent searches is limited by the Search Thread Pool. </p> <p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-threadpool.html" rel="nofollow">https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-threadpool.html</a></p> <blockquote> <p>For coun...
1
2016-09-21T19:11:48Z
[ "python", "algorithm", "elasticsearch" ]
Web Scraping with Javascript Contents using Python PyQt
39,620,351
<p>I am now performing a task of scraping content systematically from a course list which seems to be rendered by javascript. I followed some scripts using PyQt4 on the web but failed (which I copied below). More precisely, the script works at some websites with javascript which loads content with clicking on its speci...
3
2016-09-21T15:10:50Z
39,621,672
<p>Look into using selenium Library! I have scraped multiple websites with this library. People state that it is slow, but for my purposes it works great.</p> <p>Also if your kinda new to web scraping, look into what Xpaths are for scraping elements that would otherwise be difficult to get to. With Xpath, all you need...
0
2016-09-21T16:16:03Z
[ "javascript", "python", "web-scraping", "pyqt" ]
Django filter with two hops over ForeignKeys
39,620,374
<p>In Django, is it possible to do something like this?</p> <p><code>foo = Account.objects.filter(owner__address__zipcode='94704').get()</code></p> <p>with the following premises:</p> <ul> <li>Account has an <code>Owner</code> foreign key to an Owner model.</li> <li>Owner has an <code>Address</code> foreign key to a...
0
2016-09-21T15:11:29Z
39,620,525
<p>Yes, this is supported in Django ORM. </p> <p>The feature is <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">documented here</a>. </p>
0
2016-09-21T15:18:15Z
[ "python", "django", "django-models" ]
My code scrapes data reliably on my machine, but not others
39,620,387
<p>I use Ubuntu 16.04, and I created a code that takes in an eBay link and scrapes the amount of units of that product sold, if the information is available. My version looks like this:</p> <pre><code>import requests from bs4 import BeautifulSoup def sold(url): soup = BeautifulSoup(requests.get(url).text, 'html.par...
0
2016-09-21T15:12:08Z
39,620,720
<p>I don't know how you got it to work on your machine but to search for a tag with multiple classes, you're supposed to pass in as a list whose elements are the names of the classes you're interested in. like this:</p> <pre><code>soup.find('span', attrs={'class':["qtyTxt", "vi-bboxrev-dsplblk", "vi-qty-fixAlignment"]...
0
2016-09-21T15:26:46Z
[ "python", "web-scraping", "ebay" ]
the k-fold test can get result just by itself?
39,620,395
<p>My problem is when i comment the pipe_lr in the first line, I can still get accuracy score. It make me so confused, I think it should report an error why? It looks like it don't need the definition of the pipe_lr. This the relevant part. <a href="http://i.stack.imgur.com/l0xbB.png" rel="nofollow">enter image descrip...
-1
2016-09-21T15:12:31Z
39,623,745
<p>The short answer is <strong>no, it cannot</strong>. Your code will not run without <code>pipe_lr</code> line. The only reason for it to run without it is because you ran it in some peculiar environment, like ipython notebook, and previously you ran the same code <strong>with</strong> this line, thus it still persist...
0
2016-09-21T18:14:09Z
[ "python", "machine-learning", "scikit-learn" ]
Dividing every value in one list by every value in another list
39,620,517
<p>I am writing a function to find all the rational zeros of a polynomial and in need to divide each number in a list by each number in a list Ex.</p> <pre><code>list1 = [1,2,3,4,5,6,10,12,15,20,30,60] list2 = [1,2,3,6] zeros = [1/1,2/1,3/1,4/1,...,1/2,2/2,3/2,4/2,...1/3,2/3,3/3,4/3,etc...] </code></pre> <p>How woul...
-1
2016-09-21T15:17:50Z
39,620,654
<pre><code>zeros = [] for i in list1: zeros.extend([i/j for j in list2]) </code></pre>
0
2016-09-21T15:23:46Z
[ "python", "math" ]
Dividing every value in one list by every value in another list
39,620,517
<p>I am writing a function to find all the rational zeros of a polynomial and in need to divide each number in a list by each number in a list Ex.</p> <pre><code>list1 = [1,2,3,4,5,6,10,12,15,20,30,60] list2 = [1,2,3,6] zeros = [1/1,2/1,3/1,4/1,...,1/2,2/2,3/2,4/2,...1/3,2/3,3/3,4/3,etc...] </code></pre> <p>How woul...
-1
2016-09-21T15:17:50Z
39,620,856
<p>You can achieve it by using <code>itertools.product()</code> and <code>map()</code></p> <pre><code>&gt;&gt;&gt; from itertools import product &gt;&gt;&gt; from operator import div &gt;&gt;&gt; a = [1,2,3,4,5,6,10,12,15,20,30,60] &gt;&gt;&gt; b = [1,2,3,6] &gt;&gt;&gt; map(lambda x: div(x[1], x[0]), product(a, b)) [...
-1
2016-09-21T15:33:20Z
[ "python", "math" ]
Dividing every value in one list by every value in another list
39,620,517
<p>I am writing a function to find all the rational zeros of a polynomial and in need to divide each number in a list by each number in a list Ex.</p> <pre><code>list1 = [1,2,3,4,5,6,10,12,15,20,30,60] list2 = [1,2,3,6] zeros = [1/1,2/1,3/1,4/1,...,1/2,2/2,3/2,4/2,...1/3,2/3,3/3,4/3,etc...] </code></pre> <p>How woul...
-1
2016-09-21T15:17:50Z
39,620,966
<p>All I needed were nested for loops</p> <pre><code>list1 = [1,2,3,4,5,6,10,12,15,20,30,60] list2 = [1,2,3,6] zeros = [] for x in list1: for y in list2: zeros.append(x/y) print(zeros) </code></pre> <p>output: <code>[1.0, 0.5, 0.3333333333333333, 0.16666666666666666, 2.0, 1.0, 0.6666666666666666, 0.33333...
0
2016-09-21T15:37:41Z
[ "python", "math" ]
Dividing every value in one list by every value in another list
39,620,517
<p>I am writing a function to find all the rational zeros of a polynomial and in need to divide each number in a list by each number in a list Ex.</p> <pre><code>list1 = [1,2,3,4,5,6,10,12,15,20,30,60] list2 = [1,2,3,6] zeros = [1/1,2/1,3/1,4/1,...,1/2,2/2,3/2,4/2,...1/3,2/3,3/3,4/3,etc...] </code></pre> <p>How woul...
-1
2016-09-21T15:17:50Z
39,621,974
<p>A solution without itertools, for whomever may want it:</p> <p>To get this result:</p> <pre><code>list1 = [1,2,3,4,5,6,10,12,15,20,30,60] list2 = [1,2,3,6] zeros = [1/1,2/1,3/1,4/1,...,1/2,2/2,3/2,4/2,...1/3,2/3,3/3,4/3,etc...] </code></pre> <p><strong>English Explanation</strong></p> <p>You can iterate a varia...
0
2016-09-21T16:32:30Z
[ "python", "math" ]
Python, why is my probabilistic neural network (PNN) always predicting zeros?
39,620,547
<p>I'm working with Python 2.7.5 on Linux CentOS 7 machine. I'm trying to apply a <strong>probabilistic neural network (PNN)</strong> my dataset, to solve a <strong>binary classification problem</strong>.</p> <p>I'm using the following Python packages: numpy, sklearn, neupy.algorithms. I'm trying to follow <a href="ht...
8
2016-09-21T15:18:56Z
39,719,772
<p>I have tried your code and it seems to me that your network predicts both classes: </p> <pre><code>import numpy as np from sklearn.cross_validation import StratifiedKFold from neupy.algorithms import PNN fileName="dataset_file.csv" TARGET_COLUMN=35 from numpy import genfromtxt input_dataset_data = genfromtxt(file...
4
2016-09-27T08:29:19Z
[ "python", "numpy", "scikit-learn", "neural-network", "neupy" ]
Import scipy on webserver online
39,620,559
<p>I'm running my python matplotlib script online. I have an error like this:</p> <pre><code>Traceback (most recent call last): File "heatmap.py", line 8, in &amp;lt;module&amp;gt; from scipy.stats.kde import gaussian_kde ImportError: No module named scipy.stats.kde </code></pre> <p>I think that <code>scipy</co...
-1
2016-09-21T15:19:28Z
39,675,289
<p>Scipy was missing on my server, need to install it manually. Solved in this way.</p>
0
2016-09-24T10:23:03Z
[ "python", "matplotlib", "scipy" ]
PEP8 style for decorators exceeding recommended line length
39,620,577
<p>I have been tinkering with <a href="https://github.com/pyinvoke/invoke" rel="nofollow">Invoke</a>, but I came across something that is quite an odd case that there seems to be no real PEP guideline for it.</p> <p>Invoke lets you define your own CLI arguments for whatever tasks you define, and you can optionally pro...
0
2016-09-21T15:20:05Z
39,620,750
<p>You'd just break up the decorator expression into many lines the same way you'd break up any other function call. One example could be:</p> <pre><code>@task(help={ 'name1': 'Name of Person 1', 'name2': 'Name of Person 2', 'name3': 'Name of Person 3'}) def hi(ctx, name1, name2, name3): """Say hi to ...
2
2016-09-21T15:28:07Z
[ "python", "python-decorators", "pep8", "pyinvoke" ]
Positioning the exponent of tick labels when using scientific notation in matplotlib
39,620,700
<p>I am looking for a way to change the position of the exponent on an axis when using scientific notation. I got stuck at this problem already a few times. I know already that the default formatter is the <code>ScalarFormatter</code> but it has no option to access the exponent somehow.</p> <p>There is a <a href="http...
1
2016-09-21T15:25:43Z
39,622,229
<p>To access the list of <a href="http://matplotlib.org/api/text_api.html#matplotlib.text.Text" rel="nofollow">Text objects</a> you can use a method of that class, e.g. <code>get_text()</code>:</p> <pre><code>print([s.get_text() for s in ax2.get_xmajorticklabels()]) </code></pre> <p>However, the result of that is</p>...
0
2016-09-21T16:47:35Z
[ "python", "matplotlib" ]
Spark: How to "reduceByKey" when the keys are numpy arrays which are not hashable?
39,620,767
<p>I have an RDD of (key,value) elements. The keys are NumPy arrays. NumPy arrays are not hashable, and this causes a problem when I try to do a <code>reduceByKey</code> operation.</p> <p>Is there a way to supply the Spark context with my manual hash function? Or is there any other way around this problem (other than ...
2
2016-09-21T15:29:01Z
39,621,058
<p>The simplest solution is to convert it to an object that is hashable. For example:</p> <pre><code>from operator import add reduced = sc.parallelize(data).map( lambda x: (tuple(x), x.sum()) ).reduceByKey(add) </code></pre> <p>and convert it back later if needed.</p> <blockquote> <p>Is there a way to supply ...
2
2016-09-21T15:42:58Z
[ "python", "numpy", "apache-spark", "pyspark" ]
How can I add a pylint config file for Visual Studio 2015?
39,620,834
<p>I've been using and loving the Python Tools for Visual Studio. <a href="https://www.visualstudio.com/en-us/features/python-vs.aspx" rel="nofollow">https://www.visualstudio.com/en-us/features/python-vs.aspx</a> New to Python, but I've been using VS for a very long time and it has been very quick to get up and running...
0
2016-09-21T15:32:10Z
39,620,835
<p>Took awhile, but I found through trial and error that you can place a .pylintrc file in the project or solution folder and pylint will pick it up.</p> <p>To create this file, open a command window and type</p> <pre><code>pylint --generate-rcfile &gt; .pylintrc </code></pre> <p>You can then move that file to the r...
0
2016-09-21T15:32:10Z
[ "python", "visual-studio", "visual-studio-2015", "pylint" ]
A query in SQLite3 with python
39,620,874
<p>I'm testing a query with python and sqlite3. First method works fine, but second is not working. It is about the defined type of variable containing the resgisters in <code>DB</code>:</p> <pre><code>import sqlite3 def insertar(): db1=sqlite3.connect('tabla.db') print("Estas en la funcion insertar") ...
0
2016-09-21T15:34:05Z
39,620,935
<blockquote> <p><code>db2row_factory = sqlite3.Row</code></p> </blockquote> <p>This is the problematic line. Instead you meant to set the <code>row_factory</code> factory on the <code>db2</code> connection instance:</p> <pre><code>db2.row_factory = sqlite3.Row </code></pre> <p>Then, all the fetched rows would be n...
1
2016-09-21T15:36:03Z
[ "python", "sqlite3" ]
With pytest, why do inherited test methods not give proper assertion output?
39,620,910
<p>I am working on an application that has a command line interface that I would like to test using pytest. My idea was to define test classes like</p> <pre><code>class TestEchoCmd(Scenario): commands = [ "echo foo" ] stdout = "foo\n" </code></pre> <p>and then use a class with a test method to do ...
2
2016-09-21T15:35:13Z
39,621,521
<p>Found the answer myself: Pytest likes to rewrite the <code>assert</code> statements in the Python AST to add the more explicit output. This rewriting occurs (among other places) in classes that it deems to contain test methods, i.e., ones whose names start with <code>Test</code>. If a test method is inherited from a...
1
2016-09-21T16:06:38Z
[ "python", "inheritance", "py.test" ]
Replace/Add a class file to subfolder in jar using python zipfile command
39,621,003
<p>I have a jar file and I have a path which represents a location inside Jar file. </p> <p>Using this location I need to replace class file inside jar(Add a class file in some cases).I have class file inside another folder which is present where jar is present(This class file i have to move to Jar).</p> <p>Code whic...
0
2016-09-21T15:39:30Z
39,621,045
<p>Specify <code>arcname</code> to change the name of the file in the archive.</p> <pre><code>import zipfile import os zf = zipfile.ZipFile(os.path.normpath(r'D:\mystuff\test.jar'),mode='a') try: print('adding testclass.class') zf.write(os.path.normpath(r'D:\mystuff\testclass.class'),arcname="com.XYZ/ABC/...
0
2016-09-21T15:42:22Z
[ "python", "jar", "cmd", "zip" ]
adding a list of menu items in a django session
39,621,174
<p>I have the user menu in an object list, and I want to put it into the django sesion. I've trying but django tells me </p> <pre><code>'list' object has no attribute '_meta' </code></pre> <p>actually this is the object that represents a item in the menu</p> <pre><code>class MenuItem(object): def __init__(self, ...
0
2016-09-21T15:47:56Z
39,621,546
<p>This is happening because the object you're trying to store in the session is not serializable.</p> <p>You can test with with</p> <pre><code>import json json.dumps(MenuItem(1, "hi", "some_link")) </code></pre> <p>Which gives</p> <pre><code>MenuItem object at ... is not JSON serializable </code></pre> <p>One thi...
1
2016-09-21T16:08:09Z
[ "python", "django", "session", "menu" ]
os.rename returning winerror 2
39,621,199
<p>I'm trying to a script to rename to the date that it was sent as an email(which is the first part of the script but doesn't matter for this part) then to rename, and sort it into a 'Complete' folder. This is what my code looks like</p> <p>Edit - I have all the imported stuff way up at the top and i didnt show it, b...
0
2016-09-21T15:49:25Z
39,621,246
<p>2 errors:</p> <ol> <li><p>You are not in the current directory</p></li> <li><p>You just cannot have slashes in the names. The filesystem won't allow it as it is (alternately) used to separate path parts.</p></li> </ol> <p>First, generate the date directly with underscores:</p> <pre><code>now1 = (str(now.day) + '_...
0
2016-09-21T15:51:55Z
[ "python", "python-3.x" ]
Is it possible to show a link in Django to admins only?
39,621,264
<p>is it possible to test in Django if the logged in user is an admin? And just in this case to show a link normal users can't see? </p> <p>Thanks<br> Croghs</p>
0
2016-09-21T15:52:34Z
39,621,308
<p>There's a builtin method for that. (Depending on what you call an admin though)</p> <p><strong><a href="https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.models.User.is_superuser" rel="nofollow">user.is_superuser</a></strong> ?</p> <p>You may even want <code>user.is_staff</code>, again, ...
1
2016-09-21T15:55:23Z
[ "python", "django" ]
Python Numpy - What is numpy.numarray?
39,621,298
<p>When experimenting with Numpy, I found:</p> <pre><code>In [1]: numpy.numarray Out[1]: 'removed' In [2]: type(numpy.numarray) Out[2]: str </code></pre> <p>What is <code>numpy.numarray</code>? What is it's purpose in Numpy? Why does it only say <code>'removed'</code>?</p>
1
2016-09-21T15:54:56Z
39,621,370
<p><a href="https://wiki.python.org/moin/NumArray" rel="nofollow"><code>numarray</code></a> was a predecessor of <code>numpy</code>. A long time ago, there were several packages (<code>numarray</code>, <code>numeric</code>), which had lots of overlap, and eventually were superceded by <code>numpy</code>.</p> <p>(Wikip...
1
2016-09-21T15:59:19Z
[ "python", "string", "numpy" ]
How to not parse periods with sklearn TfidfVectorizer?
39,621,351
<p>I just picked up sklearn so pardon my blatant ignorance :)...Right now I am trying to figure out how TfidfVectorizer works and how to avoid splitting on periods. </p> <pre><code>from sklearn.feature_extraction.text import TfidfVectorizer docs= ("'CSC.labtrunk', 'CSC.datacenter', 'CSC.netbu', 'CSC.asr5k.general',...
0
2016-09-21T15:58:07Z
39,623,684
<p>Not sure if It is proper convention, but I used list of strings rather than tuple of strings and got desired output.</p> <p>sample data:</p> <pre><code>data = ["'CSC.labtrunk', 'CSC.datacenter', 'CSC.netbu', 'CSC.asr5k.general', 'CSC.ena', 'CSC.embu'", "'CSC.ena'", "'CSC.embu', 'CSC.security', 'CSC.ena'", "'CSC.em...
0
2016-09-21T18:10:31Z
[ "python", "string", "scikit-learn", "vectorization" ]
How do you get at a value in a list of lists /replace it with a dictionary value?
39,621,399
<p>I need to get at a value in a list of lists. The list in question is called 'newdetails'. It's contents are below</p> <pre><code>[['12345670', 'Iphone 9.0', '500', '5', '3', '5'], ['12121212', 'Samsung Laptop', '900', '5', '3', '5']] </code></pre> <p>I found that print(newdetails[0]) prints the entire first list. ...
1
2016-09-21T16:00:53Z
39,621,454
<p>If you have a list of lists </p> <pre><code>data = [['12345670', 'Iphone 9.0', '500', '5', '3', '5'], ['12121212', 'Samsung Laptop', '900', '5', '3', '5']] </code></pre> <p>Then as you've found <code>data[0]</code> will return the first list in the list. And then if you want the first item again then <cod...
0
2016-09-21T16:03:32Z
[ "python", "list", "dictionary" ]
How do you get at a value in a list of lists /replace it with a dictionary value?
39,621,399
<p>I need to get at a value in a list of lists. The list in question is called 'newdetails'. It's contents are below</p> <pre><code>[['12345670', 'Iphone 9.0', '500', '5', '3', '5'], ['12121212', 'Samsung Laptop', '900', '5', '3', '5']] </code></pre> <p>I found that print(newdetails[0]) prints the entire first list. ...
1
2016-09-21T16:00:53Z
39,621,461
<p>For multidimensional arrays use <a href="http://www.numpy.org/" rel="nofollow">numpy</a> library.</p> <p>In python, simply use nested lists indexing:</p> <pre><code>&gt;&gt;&gt; x = [['12345670', 'Iphone 9.0', '500', '5', '3', '5'], ['12121212', 'Samsung Laptop', '900', '5', '3', '5']] &gt;&gt;&gt; x[0] ['12345670...
0
2016-09-21T16:03:48Z
[ "python", "list", "dictionary" ]
How do you get at a value in a list of lists /replace it with a dictionary value?
39,621,399
<p>I need to get at a value in a list of lists. The list in question is called 'newdetails'. It's contents are below</p> <pre><code>[['12345670', 'Iphone 9.0', '500', '5', '3', '5'], ['12121212', 'Samsung Laptop', '900', '5', '3', '5']] </code></pre> <p>I found that print(newdetails[0]) prints the entire first list. ...
1
2016-09-21T16:00:53Z
39,621,539
<p>Let's say you are having a list of <code>key</code>s mapped to corresponding element in the sub-list mentioned by you in the question. Below is the sample code to achieve that:</p> <pre><code>my_list = [['12345670', 'Iphone 9.0', '500', '5', '3', '5'], ['12121212', 'Samsung Laptop', '900', '5', '3', '5']] my_key = ...
0
2016-09-21T16:07:47Z
[ "python", "list", "dictionary" ]
comparing parts of lines in two tsv files in python
39,621,474
<p>So I want to sum/analyse values pertaining to a given line in one file which match another file. The format of the first file I wish to compare against is:</p> <pre><code>Acetobacter cibinongensis Acetobacter Acetobacteraceae Rhodospirillales Proteobacteria Bacteria Acetobacter ghanensis Acetobacte...
1
2016-09-21T16:04:26Z
39,621,575
<p>The root cause is that you consume <code>file2</code> at the first iteration, then it always iterate over nothing.</p> <p>Quick fix: read file2 fully and put it in a list. However, this is rather inefficient in terms of speed (O(N^2): double loop). Could be better if creating a dictionary with key = tuple of the 6 ...
0
2016-09-21T16:09:52Z
[ "python", "csv", "compare" ]
Match multiple times a group in a string
39,621,578
<p>i'am trying to use regular expression. I have this string that has to be matched</p> <pre><code> influences = {{hlist |[[Plato]] |[[Aristotle]] |[[Socrates]] |[[David Hume]] |[[Adam Smith]] |[[Cicero]] |[[John Locke]]}} {{hlist |[[Saint Augustine]] |[[Saint Thomas Aquinas]] |[[Saint Thomas More]] |[[Richard Hook...
2
2016-09-21T16:10:07Z
39,621,712
<p>You can use a list comprehension with some regular expressions:</p> <pre><code>import re string = """ influences = {{hlist |[[Plato]] |[[Aristotle]] |[[Socrates]] |[[David Hume]] |[[Adam Smith]] |[[Cicero]] |[[John Locke]]}} {{hlist |[[Saint Augustine]] |[[Saint Thomas Aquinas]] |[[Saint Thomas More]] |[[Richard...
0
2016-09-21T16:18:25Z
[ "python", "regex" ]
django email username and password
39,621,594
<p>I'm implementing a contact form for one of my sites. One thing I'm not sure I understand completely is why you need <code>EMAIL_HOST_USER</code> and <code>EMAIL_HOST_PASSWORD</code>.</p> <p>The user would only need to provide his/her email address, so what is the <code>EMAIL_HOST_USER</code> referring to then and w...
1
2016-09-21T16:11:13Z
39,628,967
<p>You set <strong>EMAIL_HOST</strong> and <strong>EMAIL_PORT</strong> just for sending emails to your user.</p> <blockquote> <p>Mail is sent using the SMTP host and port specified in the EMAIL_HOST and EMAIL_PORT settings. The EMAIL_HOST_USER and EMAIL_HOST_PASSWORD settings, if set, are used to authenticate to the...
0
2016-09-22T01:41:37Z
[ "python", "django", "email", "smtp", "webfaction" ]
How to use a colormap from pyplot.jl as a function in julia-lang
39,621,637
<p>What would be the way to get in Julia-lang, something similar to</p> <pre><code>import numpy as np import matplotlib.pyplot as plt i = 0, f = 255, N = 100 colors = [ plt.cm.viridis(x) for x in np.linspace(i, f, N) ] </code></pre> <p>in Python? Generally speaking, I am looking for a way to get the RGB list from a c...
2
2016-09-21T16:13:52Z
39,622,304
<p>This is easiest using PlotUtils (which is re-exported on <code>using Plots</code>):</p> <pre><code>julia&gt; using PlotUtils julia&gt; cm = cgrad(:viridis); julia&gt; colors = [cm[i] for i in linspace(0,1,10)] 10-element Array{ColorTypes.RGBA{Float64},1}: RGBA{Float64}(0.267004,0.004874,0.329415,1.0) RGBA{Float...
3
2016-09-21T16:51:52Z
[ "python", "matplotlib", "colors", "julia-lang" ]
how to create a for loop for this case in python?
39,621,698
<p>maybe the title seems strange, but i'm bloqued for certain times searching how to create a for loop of this case:</p> <p>I have a list of lists having this format :</p> <pre><code> data=[['nature', author1, author2, ...author n] ['sport', author1, author2, ....author n] .... ] </code></pre> <p...
-1
2016-09-21T16:17:37Z
39,621,849
<pre><code>ary_grp_Example = [["AA1", "BB1"], ["CC2", "DD2"],["EE3","FF3"]] ### Dimension as a three column matrix array (list) ary_grp_Example.pop(0) ## Kill the first record leaving two #Loop through by row (x) for int_CurCount in range(0,len(ary_grp_Example)): print ("Row: " + str(int_CurCount) ...
0
2016-09-21T16:25:48Z
[ "python", "django", "for-loop" ]
how to create a for loop for this case in python?
39,621,698
<p>maybe the title seems strange, but i'm bloqued for certain times searching how to create a for loop of this case:</p> <p>I have a list of lists having this format :</p> <pre><code> data=[['nature', author1, author2, ...author n] ['sport', author1, author2, ....author n] .... ] </code></pre> <p...
-1
2016-09-21T16:17:37Z
39,622,460
<p>Is what you want something along these lines?</p> <pre><code>&gt;&gt;&gt; data=[['nature', 'author1', 'author2', 'author3'],['sport', 'author1', 'author2', 'author3'],['Horses', 'author1', 'author2']] &gt;&gt;&gt; for i in range(len(data)): for x in range(1, len(data[i])): print data[i][0], data...
0
2016-09-21T17:00:25Z
[ "python", "django", "for-loop" ]
how to create a for loop for this case in python?
39,621,698
<p>maybe the title seems strange, but i'm bloqued for certain times searching how to create a for loop of this case:</p> <p>I have a list of lists having this format :</p> <pre><code> data=[['nature', author1, author2, ...author n] ['sport', author1, author2, ....author n] .... ] </code></pre> <p...
-1
2016-09-21T16:17:37Z
39,623,566
<p>Convert it to a dictionary, and then iterate over the key pairs</p> <pre><code>data = [['foo', 1, 2, 3], ['bar', 2,3,4]] dat = {i[0]: i[1:] for i in data } for k, v in dat.items(): print("{0}: {1}".format(k, v)) Output bar: [2, 3, 4] foo: [1, 2, 3] </code></pre> <p>except.... <em>dont do this</em>.</...
0
2016-09-21T18:03:09Z
[ "python", "django", "for-loop" ]
python loadtxt with exotic format of table
39,621,800
<p>I have a file from simulation which reads like :</p> <pre><code>5.2000 -0.01047 -0.02721 0.823400 -0.56669 1.086e-5 2.109e-5 -1.57e-5 -3.12e-5 0.823400 -0.56669 -0.02166 -0.01949 -2.28e-5 -2.66e-5 1.435e-5 1.875e-5 1.086e-5 2.109e-5 -2.28e-5 -2.66e-5 -0.01878 -0.01836 0.820753 -0.57065 -1.57e-5...
2
2016-09-21T16:23:30Z
39,625,664
<p>If the "tables" are always 4x8 then it may be easier to read the data in as a 1D array, then index/reshape this in order to get the output you desire:</p> <pre><code># to get s you could do something like s = open(fname, 'r').read() s = """ 5.2000 -0.01047 -0.02721 0.8234 -0.56669 1.086e-5 2.109e-5 -1.57e-5...
1
2016-09-21T20:06:52Z
[ "python", "numpy" ]