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
Error in QuickSort implementation
38,727,749
<p>The code is linked here : <a href="http://ideone.com/eba7CB" rel="nofollow">http://ideone.com/eba7CB</a> <br>I can't seem to find the error. Any help and criticism are appreciated.<br></p> <pre><code>ar = [] def quick(l, r): if (r-l) &lt;= 1: return pivot = ar[l] i = l+1 for j in range(l+1...
-6
2016-08-02T18:16:40Z
38,728,459
<p>replace quick(i+1,r) by: quick(i,r)</p>
0
2016-08-02T18:58:05Z
[ "python", "python-2.7", "sorting", "quicksort" ]
Creating individual columns to write to new csv
38,727,770
<p>A CSV returns the following values</p> <pre><code>"1,323104,564382" "2,322889,564483" "3,322888,564479" "4,322920,564425" "5,322942,564349" "6,322983,564253" "7,322954,564154" "8,322978,564121" </code></pre> <p>How would i take the " marks off each end of the rows, it seems to make individual columns when i do thi...
0
2016-08-02T18:17:32Z
38,727,871
<p>How do you open the file? If you are trying to treat a read only file like a string, it's obviously not going to work. If you're working with CSV files, instead of trying to reinvent the wheel you could probably skip all of this parsing and just use the csv package. </p>
0
2016-08-02T18:23:54Z
[ "python", "csv" ]
Creating individual columns to write to new csv
38,727,770
<p>A CSV returns the following values</p> <pre><code>"1,323104,564382" "2,322889,564483" "3,322888,564479" "4,322920,564425" "5,322942,564349" "6,322983,564253" "7,322954,564154" "8,322978,564121" </code></pre> <p>How would i take the " marks off each end of the rows, it seems to make individual columns when i do thi...
0
2016-08-02T18:17:32Z
38,727,913
<p>It seems strictly easier to peel the quotes off first, and then feed it to the csv reader, which simply takes any iterable over lines as input.</p> <pre><code>import csv import sys f = open(sys.argv[1]) contents = f.read().replace('"', '') reader = csv.reader(contents.splitlines()) for x,y,z in reader: prin...
0
2016-08-02T18:26:26Z
[ "python", "csv" ]
Creating individual columns to write to new csv
38,727,770
<p>A CSV returns the following values</p> <pre><code>"1,323104,564382" "2,322889,564483" "3,322888,564479" "4,322920,564425" "5,322942,564349" "6,322983,564253" "7,322954,564154" "8,322978,564121" </code></pre> <p>How would i take the " marks off each end of the rows, it seems to make individual columns when i do thi...
0
2016-08-02T18:17:32Z
38,727,966
<p>Assuming every line is wrapped by two double quotes, we can do this:</p> <pre><code>f = open("filename.csv", "r") newlines = [] for line in f: # we could use a list comprehension, but for simplicity, we won't. newlines.append(line[1:-1]) f.close() f2 = open("filename.csv", "w") for index, line in enumerate(f2...
0
2016-08-02T18:29:15Z
[ "python", "csv" ]
Nosetests not seeing test classes that unittest discover does
38,727,784
<p>I have what I can only consider a very odd problem with the way nosetests identifies classes that are valid tests classes.</p> <p>I'm initialising a test class as a generic <code>type</code> with specific inheritance from a base tests class by using:</p> <pre><code>def random_test_class(n): print "Generating %...
0
2016-08-02T18:18:17Z
38,737,042
<p>When deciding whether or not to include methods in tests, Nose checks the <em>name of the function</em> that implements the method rather than the attribute name. Change you <code>make_test</code> so that the test created has a name that Nose will pick up.</p> <pre><code>def make_test(genre, ss, ps): def test(s...
1
2016-08-03T07:26:08Z
[ "python", "python-2.7", "unit-testing", "nose", "python-unittest" ]
ImportError: No module named 'UserString' in pyspark
38,727,861
<p>When I run spark using python3 on cluster. This error keeps come up:</p> <pre><code>py4j.protocol.Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.collectAndServe. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 10 in stage 0.0 failed 4 times, most rec...
0
2016-08-02T18:23:19Z
38,746,632
<blockquote> <p>I know that in python3 "UserString" is not a module anymore it is a part of the collections module. But I cannot fix it.</p> </blockquote> <p>Why cannot you fix it? Instead of </p> <pre><code>import UserString </code></pre> <p>can you try</p> <pre><code>from collections import UserString </code></...
0
2016-08-03T14:36:05Z
[ "python", "apache-spark", "mapreduce", "pyspark" ]
How to access MultiIndex column after groupby in pandas?
38,727,863
<p>With a single-indexed dataframe, the columns are available in the group by object: </p> <pre><code>df1 = pd.DataFrame({'a':[2,2,4,4], 'b': [5,6,7,8]}) df1.groupby('a')['b'].sum() -&gt; a 2 11 4 15 </code></pre> <p>But in a MultiIndex dataframe when not grouping by level, the columns are no longer accessibl...
3
2016-08-02T18:23:27Z
38,728,733
<p>Adding a comma after your <code>('c','b')</code> tuple seems to work: </p> <pre><code>df.groupby([('c','a')])[('c','b'),].sum() </code></pre> <p>I'm guessing that without the comma, pandas is just interpreting them as separate items.</p>
2
2016-08-02T19:14:56Z
[ "python", "pandas", "grouping", "multi-index" ]
How to access MultiIndex column after groupby in pandas?
38,727,863
<p>With a single-indexed dataframe, the columns are available in the group by object: </p> <pre><code>df1 = pd.DataFrame({'a':[2,2,4,4], 'b': [5,6,7,8]}) df1.groupby('a')['b'].sum() -&gt; a 2 11 4 15 </code></pre> <p>But in a MultiIndex dataframe when not grouping by level, the columns are no longer accessibl...
3
2016-08-02T18:23:27Z
38,729,152
<p>Maybe this helps explain the syntax:</p> <pre><code>df.groupby([('c','a')]).sum() c d b a b (c, a) 2 11 4 11 4 15 8 15 df.groupby([('c','a')])[('c','b'),('d','b')].sum() c d b b (c, a) 2 11 11 4 15 15 </code></pre>
0
2016-08-02T19:40:48Z
[ "python", "pandas", "grouping", "multi-index" ]
Split python string every nth character iterating over starting character
38,727,914
<p>I'm trying to find an elegant way to split a python string every nth character, iterating over which character to start with.</p> <p>For example, suppose I have a string containing the following:</p> <pre><code>ANDTLGY </code></pre> <p>I want to split the string into a set of 3 characters looking like this:</p> ...
1
2016-08-02T18:26:27Z
38,727,978
<pre><code>a='ANDTLGY' def nlength_parts(a,n): return map(''.join,zip(*[a[i:] for i in range(n)])) print nlength_parts(a,3) </code></pre> <p>hopefully you can explain to the professor how it works ;) </p>
3
2016-08-02T18:30:03Z
[ "python", "string", "loops" ]
Split python string every nth character iterating over starting character
38,727,914
<p>I'm trying to find an elegant way to split a python string every nth character, iterating over which character to start with.</p> <p>For example, suppose I have a string containing the following:</p> <pre><code>ANDTLGY </code></pre> <p>I want to split the string into a set of 3 characters looking like this:</p> ...
1
2016-08-02T18:26:27Z
38,728,030
<p>Simple way is to use <a class='doc-link' href="http://stackoverflow.com/documentation/python/1019/string-formatting/7681/string-slicing#t=201608021833540090269">string slicing</a> together with <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/737/list-comprehensions#t=201608...
5
2016-08-02T18:33:24Z
[ "python", "string", "loops" ]
Split python string every nth character iterating over starting character
38,727,914
<p>I'm trying to find an elegant way to split a python string every nth character, iterating over which character to start with.</p> <p>For example, suppose I have a string containing the following:</p> <pre><code>ANDTLGY </code></pre> <p>I want to split the string into a set of 3 characters looking like this:</p> ...
1
2016-08-02T18:26:27Z
38,728,072
<p>how about</p> <pre><code>a='ANDTLGY' def chopper(s,chop=3): if len(s) &lt; chop: return [] return [s[0:chop]] + chopper(s[1:],chop) </code></pre> <p>this returns</p> <pre><code>['AND', 'NDT', 'DTL', 'TLG', 'LGY'] </code></pre>
2
2016-08-02T18:35:47Z
[ "python", "string", "loops" ]
Simple way to run sklearn function with n_jobs > 1 inside parallel pool
38,727,931
<p>Is there some ways to run sklearn (supporting n_jobs argument) inside parallel loop? When I try to run sklearn function with n_jobs >1 inside multiprocessing.Pool, I've got the warning</p> <pre><code>UserWarning: Multiprocessing-backed parallel loops cannot be nested, setting n_jobs=1 for s in split_list(seeds, n...
0
2016-08-02T18:26:57Z
38,744,445
<p>This Warning comes from <code>joblib</code>, the multiprocessing library used in <code>sklearn</code>. It occurs as its parallel mechanism relies on <code>multiprocessing.Pool</code> which uses <code>daemonic</code> workers that cannot spawn subprocess. </p> <p>I don't see any simple way to by pass this restrictio...
0
2016-08-03T13:01:34Z
[ "python", "python-2.7", "parallel-processing", "multiprocessing", "nested-loops" ]
python dict in comma separated csv file
38,728,058
<p>Python dict is in a format like this: </p> <pre><code>'{"a":1, "b":2, "c":3}' </code></pre> <p>Notice it use comma to separate different key:value pairs.</p> <p>The problem is I have a CSV file, which is separate columns by comma too : </p> <pre><code>' "id", "gender", "age", "name" "001", "male...
0
2016-08-02T18:34:55Z
38,728,783
<p>You can change the delimiter that <code>read_csv</code> uses. If you can change the csv files to use a semicolon for separating columns, you can then use <code>read_csv(file.csv, sep=';'...)</code> </p> <p>Alternatively you can fix the quoting from </p> <pre><code>"001", "male", "14", "{"first":"Mike", "...
0
2016-08-02T19:17:46Z
[ "python", "csv", "pandas", "dictionary" ]
django - how to bind records of table with calculated count values from another table
38,728,128
<p>In my application I have a list of trainings. One field on this list should display number of booking for each of training. To show what I mean I prepared SQL query:</p> <pre><code>SELECT * FROM club_training a LEFT JOIN (SELECT training_id, count(*) FROM club_booking group by training_id) b ON a.id = b.training_id...
2
2016-08-02T18:38:49Z
38,734,881
<p>I would approach from the other direction: <code>each_training.booking_set.count()</code></p> <p>Also, I'm not sure it fits your database goals, but if I understand what you are looking for, you could set it up like this:</p> <p><strong>models.py</strong></p> <pre><code>class Training(models.Model): ... &...
0
2016-08-03T05:13:30Z
[ "python", "sql", "django" ]
django - how to bind records of table with calculated count values from another table
38,728,128
<p>In my application I have a list of trainings. One field on this list should display number of booking for each of training. To show what I mean I prepared SQL query:</p> <pre><code>SELECT * FROM club_training a LEFT JOIN (SELECT training_id, count(*) FROM club_booking group by training_id) b ON a.id = b.training_id...
2
2016-08-02T18:38:49Z
38,734,992
<pre><code> for each_training in context['trainings']: each_training.diff = each_training.availability - each_training.counter each_training.counter = Booking.objects.filter(training_id=each_training.id).count() # just modify this line return context </code></pre>
1
2016-08-03T05:21:16Z
[ "python", "sql", "django" ]
Recursive algorithm - extend vs creating new list with '+'
38,728,182
<p>So I have a recursive function below that keeps replacing <code>'_'</code> characters with each lowercase letter in the alphabet, until all combinations of those possible lowercase letters are substituted for the <code>'_'</code> characters.</p> <p><strong>Simple Example</strong>: </p> <blockquote> <p><code>repl...
1
2016-08-02T18:42:24Z
38,728,256
<pre><code>res = res + repl #using += works, due to extending being a mutation (same list referenced at each call) </code></pre> <p>This line is the issue, as you seem to have guessed. Each time, in the recursive call, it assigns a <em>new local list</em>, which doesn't keep the reference to the old one, so the caller...
0
2016-08-02T18:47:12Z
[ "python", "algorithm", "recursion", "combinations" ]
Recursive algorithm - extend vs creating new list with '+'
38,728,182
<p>So I have a recursive function below that keeps replacing <code>'_'</code> characters with each lowercase letter in the alphabet, until all combinations of those possible lowercase letters are substituted for the <code>'_'</code> characters.</p> <p><strong>Simple Example</strong>: </p> <blockquote> <p><code>repl...
1
2016-08-02T18:42:24Z
38,728,322
<p>better to not modify the function arguments but build with the returned values (more functional style). With slight modification of your code it works as intended.</p> <p>import string</p> <pre><code>def repl_underscores(letters): res = list() if '_' not in letters: return res repl = [letters.replace(...
1
2016-08-02T18:51:24Z
[ "python", "algorithm", "recursion", "combinations" ]
Recursive algorithm - extend vs creating new list with '+'
38,728,182
<p>So I have a recursive function below that keeps replacing <code>'_'</code> characters with each lowercase letter in the alphabet, until all combinations of those possible lowercase letters are substituted for the <code>'_'</code> characters.</p> <p><strong>Simple Example</strong>: </p> <blockquote> <p><code>repl...
1
2016-08-02T18:42:24Z
38,728,358
<p>Just use a function without recursion:</p> <pre><code>from itertools import combinations_with_replacement, chain def repl_underscores(letters): result = [] for chars in combinations_with_replacement(string.lowercase, letters.count('_')): chars = chain(chars,['']) result.append(''.join(a+nex...
-1
2016-08-02T18:53:31Z
[ "python", "algorithm", "recursion", "combinations" ]
Returning string matches between two lists for a given number of elements in a third list
38,728,204
<p>I've got a feeling that I will be told to go to the 'beginner's guide' or what have you but I have this code here that goes</p> <pre><code>does = ['my','mother','told','me','to','choose','the'] it = ['my','mother','told','me','to','choose','the'] work = [] while 5 &gt; len(work): for nope in it: if nop...
11
2016-08-02T18:43:57Z
38,728,248
<p>You could try something like this:</p> <pre><code>for nope in it: if len(work) &lt; 5 and nope in does: work.append(nope) else: break </code></pre> <p>The problem with your code is that it does the check of the work's length, after having looped through all the items of <code>it</code> and havi...
8
2016-08-02T18:46:38Z
[ "python", "list", "set-intersection" ]
Returning string matches between two lists for a given number of elements in a third list
38,728,204
<p>I've got a feeling that I will be told to go to the 'beginner's guide' or what have you but I have this code here that goes</p> <pre><code>does = ['my','mother','told','me','to','choose','the'] it = ['my','mother','told','me','to','choose','the'] work = [] while 5 &gt; len(work): for nope in it: if nop...
11
2016-08-02T18:43:57Z
38,728,337
<p>You can do:</p> <pre><code>does = ['my','mother','told','me','to','choose','the'] it = ['my','mother','told','me','to','choose','the'] work = [] for nope in it: if nope in does: work.append(nope) work = work[:4] print (work) </code></pre> <p>It's just making the list without checking the length, then c...
1
2016-08-02T18:52:22Z
[ "python", "list", "set-intersection" ]
Returning string matches between two lists for a given number of elements in a third list
38,728,204
<p>I've got a feeling that I will be told to go to the 'beginner's guide' or what have you but I have this code here that goes</p> <pre><code>does = ['my','mother','told','me','to','choose','the'] it = ['my','mother','told','me','to','choose','the'] work = [] while 5 &gt; len(work): for nope in it: if nop...
11
2016-08-02T18:43:57Z
38,728,359
<p>Alternatively, to stay a little closer to your original logic:</p> <pre><code>i = 0 while 4 &gt; len(work) and i &lt; len(it): nope = it[i] if nope in does: work.append(nope) i += 1 # ['my', 'mother', 'told', 'me', 'to'] </code></pre>
1
2016-08-02T18:53:41Z
[ "python", "list", "set-intersection" ]
Returning string matches between two lists for a given number of elements in a third list
38,728,204
<p>I've got a feeling that I will be told to go to the 'beginner's guide' or what have you but I have this code here that goes</p> <pre><code>does = ['my','mother','told','me','to','choose','the'] it = ['my','mother','told','me','to','choose','the'] work = [] while 5 &gt; len(work): for nope in it: if nop...
11
2016-08-02T18:43:57Z
39,804,847
<p>Just for fun, here's a one-liner with no imports: </p> <pre><code>does = ['my', 'mother', 'told', 'me', 'to', 'choose', 'the'] it = ['my', 'mother', 'told', 'me', 'to', 'choose', 'the'] work = [match for match, _ in zip((nope for nope in does if nope in it), range(4))] </code></pre>
0
2016-10-01T09:08:30Z
[ "python", "list", "set-intersection" ]
RarFile Python Module
38,728,243
<p>I am trying to make a simple bruteforcer for rar files. My code is...</p> <pre><code>import rarfile file = input("Password List Directory: ") rarFile = input("Rar File: ") passwordList = open(file,"r") for i in passwordList: try : rarfile.read(rarFile, psw=i) print('[+] Password Found: '+i)...
0
2016-08-02T18:46:28Z
38,728,449
<p>The real problem here is that you are catching all exceptions, not just the one you want. So use <code>except rarfile.PasswordRequired:</code> That will show you that the error is not a missing password. Instead there is no function <code>read</code> in the rarfile module.</p> <p>Have a look at some <a href="https...
1
2016-08-02T18:57:34Z
[ "python", "python-3.x", "zipfile", "rar" ]
Pandas cannot load data, csv encoding mystery
38,728,366
<p>I am trying to load a dataset into pandas and cannot get seem to get past step 1. I am new so please forgive if this is obvious, I have searched previous topics and not found an answer. The data is mostly in Chinese characters, which may be the issue.</p> <p>The .csv is very large, and can be found here: <a href="h...
1
2016-08-02T18:53:51Z
38,744,675
<p>It seems that there's something very wrong with the input file. There are encoding errors throughout.</p> <p>One thing you <em>could</em> do, is to read the CSV file as a binary, decode the binary string and replace the erroneous characters.</p> <p>Example (<a href="http://stackoverflow.com/a/20014805/3165737">sou...
0
2016-08-03T13:11:37Z
[ "python", "pandas", "chardet" ]
Not being able to import modules using Python
38,728,379
<p>I've tried importing modules and I've only had bad luck until now. None of my imports work as Python doesn't seem to be able to find them. If I do paste the import directory on the same folder as my script it'll run but otherwise it won't.</p> <p>I ran:</p> <pre><code>sys.path </code></pre> <p>And got this awkwar...
-7
2016-08-02T18:54:27Z
38,728,456
<p>I would guess that you are trying to import a non-standard library. If that is what you want to do, you have to first run </p> <pre><code>pip install foo </code></pre> <p>in your system's appropriate console. On windows that would be either cmd or powershell.</p>
1
2016-08-02T18:57:59Z
[ "python" ]
Not being able to import modules using Python
38,728,379
<p>I've tried importing modules and I've only had bad luck until now. None of my imports work as Python doesn't seem to be able to find them. If I do paste the import directory on the same folder as my script it'll run but otherwise it won't.</p> <p>I ran:</p> <pre><code>sys.path </code></pre> <p>And got this awkwar...
-7
2016-08-02T18:54:27Z
38,728,489
<p>This question is poorly constructed and there is not enough information provided. But....if you are importing a module for use in your code, you should be writing something like...</p> <pre><code> import 'module' module.usemodule(whatever) </code></pre>
-1
2016-08-02T18:59:42Z
[ "python" ]
How to Check if a Value in a Column is Present in the Following Row?
38,728,425
<p>I have the following dataframe that I want to do some manipulation over it:</p> <pre><code> AutoStudyID DiagDate DiagName 0 34 2010-09-23 Lung 1 34 2001-01-01 Skin 2 48 2008-01-01 Brain </code></pre> <p>How can I use the power of pandas to check for the case where a...
-1
2016-08-02T18:56:37Z
38,728,795
<p>the following will check whether the value in the next row (for numeric and datetime dtypes) is the same?</p> <pre><code>In [203]: df.AutoStudyID.diff() == 0 Out[203]: 0 False 1 True 2 False Name: AutoStudyID, dtype: bool In [204]: df[df.AutoStudyID.diff() == 0] Out[204]: AutoStudyID DiagDate DiagN...
1
2016-08-02T19:18:55Z
[ "python", "pandas", "indexing", "dataframe" ]
How to Check if a Value in a Column is Present in the Following Row?
38,728,425
<p>I have the following dataframe that I want to do some manipulation over it:</p> <pre><code> AutoStudyID DiagDate DiagName 0 34 2010-09-23 Lung 1 34 2001-01-01 Skin 2 48 2008-01-01 Brain </code></pre> <p>How can I use the power of pandas to check for the case where a...
-1
2016-08-02T18:56:37Z
38,729,006
<p>Iterate over the rows with <code>iterrows()</code> and compare the field AutoStudyID with the last value found.</p> <pre><code>last = None for i, row in df.iterrows(): if last == df['AutoStudyID'][i]: print('I found it in position: %s' % i) else: last = df['AutoStudyID'][i] </code></pre>
0
2016-08-02T19:31:45Z
[ "python", "pandas", "indexing", "dataframe" ]
How to Check if a Value in a Column is Present in the Following Row?
38,728,425
<p>I have the following dataframe that I want to do some manipulation over it:</p> <pre><code> AutoStudyID DiagDate DiagName 0 34 2010-09-23 Lung 1 34 2001-01-01 Skin 2 48 2008-01-01 Brain </code></pre> <p>How can I use the power of pandas to check for the case where a...
-1
2016-08-02T18:56:37Z
38,729,094
<p>Try adding a new column with the following AutoStudyID:</p> <pre><code>df['next'] = df.AutoStudyID.shift(-1) df AutoStudyID DiagDate DiagName next 0 34 2010-09-23 Lung 34 1 34 2001-01-01 Skin 48 2 48 2008-01-01 Brain NaN </code></pre> <p>Each row w...
1
2016-08-02T19:37:14Z
[ "python", "pandas", "indexing", "dataframe" ]
Python Method not returning string
38,728,462
<p>I am trying to return a string from one of my methods. The method is called in my <code>__init__</code> method. The command I have in my <code>__init__</code> is:</p> <pre><code>self.downloadHTTP() </code></pre> <p>I then in the method do this, the print is there for testing to show that the string is valid before...
-1
2016-08-02T18:58:28Z
38,942,684
<p>Thank you for your input in the comments. The problem was that I was essentially printing the object and that I was performing all my tasks in the <strong>INIT</strong> function. I solved this by separating the download into a method then returning the string in that method.</p>
0
2016-08-14T13:24:12Z
[ "python" ]
Inputs not a sequence wth RNNs and TensorFlow
38,728,501
<p>I have some very basic lstm code with tensorflow and python, where my code is </p> <p><code>output = tf.nn.rnn(tf.nn.rnn_cell.BasicLSTMCell(10), input_flattened, initial_state=tf.placeholder("float", [None, 20]))</code></p> <p>where my input flattened is shape <code>[?, 5, 22501]</code></p> <p>I'm getting the err...
0
2016-08-02T19:00:59Z
38,740,100
<p>I think when you use the tf.nn.rnn function it is expecting a list of tensors and not just a single tensor. You should unpack input in the time direction so that it is a list of tensors of shape [?, 22501]. You could also use tf.nn.dynamic_rnn which I think can handle this unpack for you.</p>
1
2016-08-03T09:48:43Z
[ "python", "neural-network", "tensorflow", "recurrent-neural-network" ]
python office365 create meeting event
38,728,602
<p>I have this python code below to create a meeting event, and it is working. I plan to incorporate this script with the Web Form submision where user enters some basic information such as Subject, attendees, and meeting date/time, and then the Python script will create a meeting event based on submitted info from the...
1
2016-08-02T19:06:15Z
38,730,234
<p>You can get user's timezone offset from UTC with JavaScript on the client and then pass this value to the server during form submission. See <a href="http://stackoverflow.com/a/1809974/1438906">this</a> answer.</p> <p>UPDATE:</p> <p>Assuming your user's locale is set up correctly, <code>getTimezoneOffset()</code> ...
1
2016-08-02T20:52:23Z
[ "python", "office365" ]
Django how to relate a foreign key object on form save
38,728,669
<p>How can I create a relationship between my object and foreign key from a form submit? You can skip down to the very last line of code to see my issue.</p> <h2>edit</h2> <p>My user will not have an option to select the related model object. The related model object will be exclusively the one identified by the <cod...
0
2016-08-02T19:10:31Z
38,728,880
<p>I finally see what are you trying to do, it's pretty easy:</p> <pre><code>contact = contact_form.save() # link contact to activity here, activity pk is 'id' activity = Activity.objects.get(id=id) contact.activity.add(activity) </code></pre> <p>I was confused before because you have <code>id</code> as view function...
2
2016-08-02T19:24:24Z
[ "python", "django" ]
Combine pandas dataframe cells in case of identical values
38,728,705
<p>I'm trying to make a new dataframe where, if a 'type' occurs more than once, the contents of the 'country' cells and the 'year' cells of those rows are combined in one row (the 'how' column behaves like the 'type' column: if the types are similar, the hows are as well).</p> <p>My pd dataframe looks as follows, df:<...
2
2016-08-02T19:12:30Z
38,728,741
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow"><code>groupby/agg</code></a> with <code>', '.join</code> as the aggregator:</p> <pre><code>import pandas as pd df = pd.DataFrame({'country': ['UK', 'GER', 'USA', 'AUS', 'CAN', 'SA', 'RU'], 'how': ['S', 'D', 'D', 'F', 'R', 'L', 'L...
3
2016-08-02T19:15:23Z
[ "python", "pandas" ]
Combine pandas dataframe cells in case of identical values
38,728,705
<p>I'm trying to make a new dataframe where, if a 'type' occurs more than once, the contents of the 'country' cells and the 'year' cells of those rows are combined in one row (the 'how' column behaves like the 'type' column: if the types are similar, the hows are as well).</p> <p>My pd dataframe looks as follows, df:<...
2
2016-08-02T19:12:30Z
38,728,859
<p>To get a list in each cell as opposed to a string</p> <pre><code>def proc_df(df): df = df[['country', 'year']] return pd.Series(df.T.values.tolist(), df.columns) df.groupby(['how', 'type']).apply(proc_df) </code></pre> <p><a href="http://i.stack.imgur.com/5JNXm.png" rel="nofollow"><img src="http://i.stack...
1
2016-08-02T19:23:06Z
[ "python", "pandas" ]
pandas install issues in gitlab and docker
38,728,722
<pre><code>Collecting numpy (from -r requirements.txt (line 21)) Downloading numpy-1.11.1.zip (4.7MB) Collecting pandas (from -r requirements.txt (line 22)) Downloading pandas-0.18.1.tar.gz (7.3MB) Complete output from command python setup.py egg_info: Download error on https://pypi.python.org/simple/numpy/...
0
2016-08-02T19:14:19Z
38,741,547
<p><code>pip</code> is unable to verify the certificate. You need to manually say which certificate it should use to verify it.</p> <p>This should work:</p> <pre><code>pip --cert /etc/ssl/certs/DigiCert_High_Assurance_EV_Root_CA.pem install -r requirements.txt </code></pre>
0
2016-08-03T10:53:16Z
[ "python", "pandas", "numpy", "continuous-integration", "gitlab" ]
How do I figure out the variance explained in tfidf matrix with kmeans?
38,728,828
<p>I am fairly new with working with text data.</p> <p>I have a data frame of about 300,000 unique product names and I am trying to use k means to cluster similar names together. I used sklearn's tfidfvectorizer to vectorize the names and convert to a tf-idf matrix.</p> <p>Next I ran k means on the tf-idf matrix with...
1
2016-08-02T19:21:05Z
39,806,161
<p>You should convert your <code>tfidf_matrix</code> (which is sparse) into a proper array.</p> <pre><code>D_k = [cdist(tfidf_matrix.toarray(), cent) for cent in centroids] </code></pre> <p>This worked for me.</p>
1
2016-10-01T11:38:49Z
[ "python", "scikit-learn", "k-means", "tf-idf" ]
Why is it possible to have low loss, but also very low accuracy, in a convolutional neural network?
38,728,895
<p>I am new to machine learning and am currently trying to train a convolutional neural net with 3 convolutional layers and 1 fully connected layer. I am using a dropout probability of 25% and a learning rate of 0.0001. I have 6000 150x200 training images and 13 output classes. I am using tensorflow. I am noticing ...
1
2016-08-02T19:25:16Z
38,736,628
<p>That is because <strong>Loss</strong> and <strong>Accuracy</strong> are two totally different things (well at least logically)!</p> <p>Consider an example where you have defined <code>loss</code> as:</p> <pre><code>loss = (1-accuracy) </code></pre> <p>In this case when you try to minimize <code>loss</code>, <code...
2
2016-08-03T07:05:01Z
[ "python", "machine-learning", "tensorflow", "deep-learning" ]
seaborn to replace a matplotlib
38,728,896
<p>I am trying to make a plot with <code>seaborn</code>, of a simple plot that I have done it with <code>patplotlib</code></p> <pre><code> import matplotlib.pyplot as plt radius = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] area = [3.14159, 12.56636, 28.27431, 50.26544, 78.53975, 113.09724] square = [1.0, 4.0, 9.0, 16....
-3
2016-08-02T19:25:14Z
38,729,316
<p>Use it like this, your plots will look nicer as compared to default matplotlib plots :</p> <pre><code>import seaborn as sb import matplotlib.pyplot as plt sb.set_style("darkgrid") radius = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] area = [3.14159, 12.56636, 28.27431, 50.26544, 78.53975, 113.09724] square = [1.0, 4.0, 9.0, 16...
-1
2016-08-02T19:51:26Z
[ "python", "matplotlib", "seaborn" ]
Make an image background transparent
38,728,907
<p>I have an image with an orange and a white background. I want to make the white background transparent. The code below uses grabcut to make a mask. I then split the image into rgb channels and apply the mask on the alpha channel. You'll see from images below that post-grabcut and mask images are OK. I haven't been a...
1
2016-08-02T19:26:00Z
38,732,889
<p>according to an older SO question, imshow doesn't actually support alpha channels <a href="http://jepsonsblog.blogspot.com/2012/10/overlay-transparent-image-in-opencv.html" rel="nofollow">http://jepsonsblog.blogspot.com/2012/10/overlay-transparent-image-in-opencv.html</a> but this is an old post and support <strong>...
1
2016-08-03T01:24:22Z
[ "python", "opencv", "image-processing", "computer-vision", "transparency" ]
Python parse txt file, PEST output, jacobian.txt
38,728,942
<p>We are stuck trying to find a way to parse a tricky text file that is produced by a PEST analysis using Python. It shows measurements of 63 different variables for over 30,000 observations. Here's an example of the output (3/>30,000 shown)</p> <pre><code> cmfa cmfb cmfc ...
0
2016-08-02T19:28:28Z
38,730,870
<p>A way to parse the file that you have provided(independent of number of rows in file) using simple python, better implementations can be done using regular expressions but i would leave it for you to try further:</p> <pre><code>#Importing required libraries import numpy as np import csv #Open input file with open(...
1
2016-08-02T21:35:45Z
[ "python", "parsing" ]
Python parse txt file, PEST output, jacobian.txt
38,728,942
<p>We are stuck trying to find a way to parse a tricky text file that is produced by a PEST analysis using Python. It shows measurements of 63 different variables for over 30,000 observations. Here's an example of the output (3/>30,000 shown)</p> <pre><code> cmfa cmfb cmfc ...
0
2016-08-02T19:28:28Z
38,756,941
<p>You can use a <code>mmap</code> and a regex to parse the file without having to read in the entire file into memory. </p> <p>Something like:</p> <pre><code>import re import mmap import os size=os.stat(fn_in).st_size with open(fn_in, "r") as fin, open(fn_out, "w") as fout: data = mmap.mmap(fin.fileno(), size,...
0
2016-08-04T01:03:42Z
[ "python", "parsing" ]
Passing xPath as argument to Scrapy
38,728,973
<p>I'm trying to write a generic crawler for a single webpage which is called with the following arguments:</p> <ul> <li>Allowed Domains</li> <li>URL to be crawled</li> <li>xPath to extract the price within the webpage</li> </ul> <p>The URL and allowed domains arguments seem to be working correctly but I can't get th...
0
2016-08-02T19:29:52Z
38,729,003
<p>Have <code>xpath_string</code> as an <em>instance variable</em> instead:</p> <pre><code>import scrapy from Spotlite.items import SpotliteItem class GenericSpider(scrapy.Spider): name = "generic" def __init__(self, start_url=None, allowed_domains=None, xpath_string=None, *args, **kwargs): super(Generic...
0
2016-08-02T19:31:32Z
[ "python", "scrapy" ]
Passing xPath as argument to Scrapy
38,728,973
<p>I'm trying to write a generic crawler for a single webpage which is called with the following arguments:</p> <ul> <li>Allowed Domains</li> <li>URL to be crawled</li> <li>xPath to extract the price within the webpage</li> </ul> <p>The URL and allowed domains arguments seem to be working correctly but I can't get th...
0
2016-08-02T19:29:52Z
38,731,907
<p>Adding the variable to initial class declaration fixed the problem.</p> <pre><code>import scrapy from spotlite.items import SpotliteItem class GenericSpider(scrapy.Spider): name = "generic" xpath_string = "" def __init__(self, start_url, allowed_domains, xpath_string, *args, **kwargs): super(Gene...
0
2016-08-02T23:15:28Z
[ "python", "scrapy" ]
Pytest parametrize class tests
38,729,007
<p>I have an array of objects that I need to run for each tests inside my test class. I want to parametrize every test function in a TestClass. The end goal is to have something resembling:</p> <pre><code>@pytest.mark.parametrize('test_input', [1, 2, 3, 4]) class TestClass: def test_something1(self, test_input): ...
0
2016-08-02T19:31:46Z
38,752,047
<p>I have solved it. I was overcomplicating it; instead of using a mark I can use a fixture function that passes in parameters.</p> <p>Before I found the answer (Without parametrize):</p> <pre><code>class TestClass: def test_something(self): for i in example_params: print(i) </code></pre> <p>...
0
2016-08-03T19:24:06Z
[ "python", "python-3.x", "py.test" ]
What does an empty parenthesis "()" in logging config dictionary mean?
38,729,099
<p>I am playing around with the <a href="https://github.com/exoscale/python-logstash-formatter" rel="nofollow">Python Logstash Formatter</a> and <a href="https://github.com/exoscale/python-logstash-formatter/wiki/Configuration-and-making-it-work-in-Python" rel="nofollow">in its wiki</a> it recommended setting the follo...
1
2016-08-02T19:37:37Z
38,729,253
<p>If you check out the <a href="https://docs.python.org/3.4/library/logging.config.html#user-defined-objects" rel="nofollow">python docs for logging</a>, you'll see this:</p> <blockquote> <p>Objects to be configured are described by dictionaries which detail their configuration. In some places, the logging system w...
3
2016-08-02T19:47:21Z
[ "python", "logging", "logstash" ]
Python code to find the sum of common elements in two sequences of integers in a range
38,729,109
<p>"""A better Python code to find find the sum of common elements in two sequences #of integers in a range ??"""</p> <pre><code>#F() constructs a sequence: def F(): bot=int(input("Enter start value:")) #start value top = int(input("Enter stop value:")) #stop value L=range(bot,top+1) return(L) #...
0
2016-08-02T19:38:10Z
38,729,943
<p>If your solution is working, Why looking for a "better Python code"? Your code is good enough. The only change I would do is the list <code>res</code>. You don't really need it:</p> <pre><code>def G(L1, L2): total = 0 for x in L1: if x in L2: total += x return total </code></pre> <p...
1
2016-08-02T20:32:02Z
[ "python" ]
Anaconda using Using both Python 2.x and Python 3.x in IPython Notebook
38,729,113
<p>using the instructions <a href="http://stackoverflow.com/questions/30492623/using-both-python-2-x-and-python-3-x-in-ipython-notebook">here</a> Using nb_conda_kernels I almost have it going,, but I seem to have only the very basic Python Interpreter in my environments. What I want is a full Anaconda environment for e...
0
2016-08-02T19:38:49Z
38,741,109
<p>What you probably want to do is to create a environment with some predefined set of packages. From the command line, and possibly outside any conda environment, try something like (<code>py2</code> can indeed any name you want):</p> <pre><code>conda create --name py2 python=2 anaconda </code></pre> <p>See <a href=...
0
2016-08-03T10:33:17Z
[ "python", "anaconda", "conda" ]
Python function deletes my var?
38,729,213
<p>I have the following code:</p> <pre><code>def moveServo(x, y): print x print y s1.ChangeDutyCycle(x) s2.ChangeDutyCycle(y) print "Successfull" print x print y @app.route('/cameramove/', methods=['GET']) def cameramove(): ret_data = True x = request.args.get('x') y = request...
0
2016-08-02T19:44:28Z
38,738,726
<p>I ended up using:</p> <pre><code>float(request.args.get('x')) </code></pre>
0
2016-08-03T08:47:42Z
[ "python", "function", "variables" ]
For loop supposed to print 4 rows. it only prints one
38,729,225
<p>I have a list called <strong>deck</strong>, which has 104 elements. I want to create a for loop, that displays images on a canvas in a simple GUI (that can only be run on CodeSkulptor, the link to my program's here: <a href="http://www.codeskulptor.org/#user41_kgywoL4h56_1.py" rel="nofollow">http://www.codeskulptor....
0
2016-08-02T19:45:08Z
38,729,508
<p>You forgot about your <code>center_s[0]</code> and <code>center_s[0]</code> coordinates. They are growing constantly. You need to set them to zero, e.g like this:</p> <pre><code>if center_d[0] &gt;= WIDTH: center_s[0] = 41 center_d[0] = 41 center_s[1] += height center_d[1] += height </code></pre>
2
2016-08-02T20:04:40Z
[ "python", "python-2.7", "for-loop" ]
Age Classifier python program
38,729,247
<pre class="lang-python prettyprint-override"><code>print("Welcome to the Age Classifier program") person_age=(float(input("Enter the person's Age")) if person_age&lt;=1 or person_age&gt;0: print("Person is an infant") elif person_age&gt;1 or person_age&lt;13: print("Person is a child") elif person_age...
1
2016-08-02T19:47:01Z
38,729,267
<p>You have unbalanced parentheses.</p> <pre><code>person_age=float(input("Enter the person's Age")) </code></pre> <p>It would probably be a better idea, though, to make this an integer:</p> <pre><code>person_age=int(input("Enter the person's Age")) </code></pre>
1
2016-08-02T19:48:21Z
[ "python", "syntax" ]
Age Classifier python program
38,729,247
<pre class="lang-python prettyprint-override"><code>print("Welcome to the Age Classifier program") person_age=(float(input("Enter the person's Age")) if person_age&lt;=1 or person_age&gt;0: print("Person is an infant") elif person_age&gt;1 or person_age&lt;13: print("Person is a child") elif person_age...
1
2016-08-02T19:47:01Z
38,729,331
<p>The error in your first line is primarily due to the parenthesis:</p> <pre><code>person_age=(float(input("Enter the person's Age")) # 3 opening, 2 closing. </code></pre> <p>Change this to:</p> <pre><code>person_age=(float(input("Enter the person's Age"))) </code></pre> <p>Also, you have a logical error. The <cod...
2
2016-08-02T19:52:17Z
[ "python", "syntax" ]
I want to randomly select items from a list and add them to another list without replacement
38,729,272
<p>I'm trying to randomly select items from a list and add them to another list.</p> <p>The list of elements I'm choosing from looks like this:</p> <pre><code>data=[2,3,4,7,8,12,17,24,27,33,35,36,37,38,40,43,44,50,51,54] </code></pre> <p>I want to randomly take an element from this list and add it to one of four lis...
3
2016-08-02T19:48:38Z
38,729,341
<p>You can use <code>random.sample</code>:</p> <pre><code> data=[2,3,4,7,8,12,17,24,27,33,35,36,37,38,40,43,44,50,51,54] random.sample(data, 5) # [27, 12, 33, 24, 17] </code></pre> <p>To get a nested list of it, use a list comprehension</p> <pre><code> [random.sample(data, 5) for _ in range(5)] # [[40, 35, 24, 54...
0
2016-08-02T19:52:48Z
[ "python", "list", "random", "sample" ]
I want to randomly select items from a list and add them to another list without replacement
38,729,272
<p>I'm trying to randomly select items from a list and add them to another list.</p> <p>The list of elements I'm choosing from looks like this:</p> <pre><code>data=[2,3,4,7,8,12,17,24,27,33,35,36,37,38,40,43,44,50,51,54] </code></pre> <p>I want to randomly take an element from this list and add it to one of four lis...
3
2016-08-02T19:48:38Z
38,729,376
<pre><code>import random data=[2,3,4,7,8,12,17,24,27,33,35,36,37,38,40,43,44,50,51,54] random.shuffle(data) lists = [data[i:i+len(data)/4] for i in range(0, len(data), len(data)/4)] print(lists) </code></pre> <p>Randomly pulling from your initial list will have the same effect as shuffling then pulling in order. Spli...
3
2016-08-02T19:56:04Z
[ "python", "list", "random", "sample" ]
I want to randomly select items from a list and add them to another list without replacement
38,729,272
<p>I'm trying to randomly select items from a list and add them to another list.</p> <p>The list of elements I'm choosing from looks like this:</p> <pre><code>data=[2,3,4,7,8,12,17,24,27,33,35,36,37,38,40,43,44,50,51,54] </code></pre> <p>I want to randomly take an element from this list and add it to one of four lis...
3
2016-08-02T19:48:38Z
38,729,502
<p>You could try this, modifying the ranges inside the <code>d</code> function to tune to the number elements you want.</p> <pre><code>import random def f(data): val = random.choice(data) ix = data.index(val) data.pop(ix) return val, data def d(data): topholder = [] m = len(data)/4 for i ...
0
2016-08-02T20:03:57Z
[ "python", "list", "random", "sample" ]
I want to randomly select items from a list and add them to another list without replacement
38,729,272
<p>I'm trying to randomly select items from a list and add them to another list.</p> <p>The list of elements I'm choosing from looks like this:</p> <pre><code>data=[2,3,4,7,8,12,17,24,27,33,35,36,37,38,40,43,44,50,51,54] </code></pre> <p>I want to randomly take an element from this list and add it to one of four lis...
3
2016-08-02T19:48:38Z
38,729,520
<p>another shuffle based but ensuring the all sub lists have the same size in case number of elements is not divisible to number of lists (try 7 for example).</p> <pre><code>from random import shuffle def split(data, n): size=int(len(data)/n); for i in range(0, n*size, size): yield data[i:i+size] ...
0
2016-08-02T20:05:29Z
[ "python", "list", "random", "sample" ]
I want to randomly select items from a list and add them to another list without replacement
38,729,272
<p>I'm trying to randomly select items from a list and add them to another list.</p> <p>The list of elements I'm choosing from looks like this:</p> <pre><code>data=[2,3,4,7,8,12,17,24,27,33,35,36,37,38,40,43,44,50,51,54] </code></pre> <p>I want to randomly take an element from this list and add it to one of four lis...
3
2016-08-02T19:48:38Z
38,730,541
<p>This is a dynamic function that returns a list of list where each list starts with a specified value. The amount of nested lists is determined by the amount of <em>starting_values</em>.</p> <pre><code>import random def get_random_list(element_list, starting_values, size_per_group): num_of_groups = len(starting...
0
2016-08-02T21:12:16Z
[ "python", "list", "random", "sample" ]
How to run a Python script in Node.js synchronously?
38,729,300
<p>I am running the following Python script in Node.js through <a href="https://github.com/extrabacon/python-shell" rel="nofollow">python-shell</a>:</p> <pre><code>import sys import time x=0 completeData = ""; while x&lt;800: crgb = ""+x; print crgb completeData = completeData + crgb + "@"; time.sleep(.000...
0
2016-08-02T19:50:53Z
38,729,571
<p>As this is asynchronous, add an end callback (found in the documentation) instead of instructions at top level</p> <pre><code>// end the input stream and allow the process to exit pyshell.end(function (err) { if (err) throw err; console.log ("Now reading data"); }); </code></pre>
0
2016-08-02T20:08:48Z
[ "python", "node.js" ]
Conditionally Select and Set Column Values
38,729,313
<p>I have two dataframes. I need to copy the values of df2.faults column to df1.faults column based on the values of unit and date.</p> <p>The two dataframes have different lengths. df1 has possible duplicates of (unit,date) contrary to df2. An example that mimics my dataset:</p> <pre><code> df1 = pd.DataFrame({'...
2
2016-08-02T19:51:19Z
38,729,595
<p>Simple, use a left merge :</p> <pre><code>df1 = pd.merge(df1,df2,how='left',on=['date','unit']) df1 = date faults_x unit faults_y 0 2016-06-14 None x 76 1 2016-06-14 None x 76 2 2016-06-15 None x 12 3 2016-06-16 None x 30 4 2016-06-16 None...
4
2016-08-02T20:10:27Z
[ "python", "python-3.x", "pandas" ]
Sort by one column's values, keeping rows grouped by another column's value
38,729,321
<p>I have two (hundreds) df's that are generated and then concatenated, which I would then like to sort while keeping the rows with identical column <code>D</code> names in the original order:</p> <pre><code>In [120]: df_list[0] Out[120]: A B C D 0 0.564678 0.598355 0.606693 MA0835 1 0...
4
2016-08-02T19:51:43Z
38,729,920
<p>Use the <code>keys</code> argument in <code>pd.concat</code></p> <pre><code>keys = [(df.A.iloc[0], i) for i, df in enumerate(list_of_dfs)] pd.concat(list_of_dfs, keys=keys) \ .sort_index(ascending=[False, True, True]) \ .reset_index(drop=True) </code></pre> <p><a href="http://i.stack.imgur.com/5j6Yu.png" r...
3
2016-08-02T20:30:28Z
[ "python", "sorting", "pandas" ]
How to pass an extra parameter to authenticate function when using django.views.login?
38,729,330
<p>I have an authentication back-end which looks like this</p> <pre><code>class Backend(object): def authenticate(self, username=None, password=None): # Do stuff </code></pre> <p>My url handler looks like this</p> <pre><code>url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'logi...
1
2016-08-02T19:52:16Z
38,729,617
<p>I believe that you are asking about writing custom authentication backend and defining your own <code>authenticate</code> method in it.</p> <p>Is so, check <a href="https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#writing-an-authentication-backend" rel="nofollow">Django documentation</a>. As said ther...
1
2016-08-02T20:11:32Z
[ "python", "django" ]
How to pass an extra parameter to authenticate function when using django.views.login?
38,729,330
<p>I have an authentication back-end which looks like this</p> <pre><code>class Backend(object): def authenticate(self, username=None, password=None): # Do stuff </code></pre> <p>My url handler looks like this</p> <pre><code>url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'logi...
1
2016-08-02T19:52:16Z
38,729,914
<p>You need to subclass the <code>AuthenticationForm</code>, and override the <code>clean</code> method so that it calls <code>authenticate</code> with your extra parameter.</p> <p>Then, in your urls.py, pass your <code>authentication_form</code> to the login view.</p>
0
2016-08-02T20:30:15Z
[ "python", "django" ]
Executing a local shell function on a remote host over ssh using Python
38,729,374
<p>My <code>.profile</code> defines a function</p> <pre><code>myps () { ps -aef|egrep "a|b"|egrep -v "c\-" } </code></pre> <p>I'd like to execute it from my python script</p> <pre><code>import subprocess subprocess.call("ssh user@box \"$(typeset -f); myps\"", shell=True) </code></pre> <p>Getting an error ba...
2
2016-08-02T19:55:58Z
38,729,761
<p>The original command was not interpreting the <code>;</code> before <code>myps</code> properly. Using <code>sh -c</code> fixes that, but... ( please see Charles Duffy comments below ).</p> <p>Using a combination of single/double quotes sometimes makes the syntax easier to read and less prone to mistakes. With that ...
0
2016-08-02T20:21:19Z
[ "python", "ksh" ]
Executing a local shell function on a remote host over ssh using Python
38,729,374
<p>My <code>.profile</code> defines a function</p> <pre><code>myps () { ps -aef|egrep "a|b"|egrep -v "c\-" } </code></pre> <p>I'd like to execute it from my python script</p> <pre><code>import subprocess subprocess.call("ssh user@box \"$(typeset -f); myps\"", shell=True) </code></pre> <p>Getting an error ba...
2
2016-08-02T19:55:58Z
38,730,287
<pre><code>script=''' . ~/.profile # load local function definitions so typeset -f can emit them ssh user@box ksh -s &lt;&lt;EOF $(typeset -f) myps EOF ''' import subprocess subprocess.call(['ksh', '-c', script]) # no shell=True </code></pre> <hr> <p>There are a few pertinent items here:</p> <ul> <li><p>The dotfile...
1
2016-08-02T20:56:10Z
[ "python", "ksh" ]
Executing a local shell function on a remote host over ssh using Python
38,729,374
<p>My <code>.profile</code> defines a function</p> <pre><code>myps () { ps -aef|egrep "a|b"|egrep -v "c\-" } </code></pre> <p>I'd like to execute it from my python script</p> <pre><code>import subprocess subprocess.call("ssh user@box \"$(typeset -f); myps\"", shell=True) </code></pre> <p>Getting an error ba...
2
2016-08-02T19:55:58Z
38,744,502
<p>I ended up using this.</p> <pre><code>import subprocess import sys import re HOST = "user@" + box COMMAND = 'my long command with many many flags in single quotes' ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND], shell=False, stdout=subprocess.PIPE, ...
1
2016-08-03T13:03:44Z
[ "python", "ksh" ]
Should Python modules import the modules they semantically depend on?
38,729,393
<p>Should Python modules <code>import</code> the modules they semantically depend on?</p> <p>For example:</p> <p>module <code>a</code>:</p> <pre><code>class A(object): ... def foo(self): ... </code></pre> <p>module <code>b</code>:</p> <pre><code>import a def f(a_instance): a_instance.foo() ...
1
2016-08-02T19:57:47Z
38,729,523
<p><code>b</code> semantically depends on <em>nothing</em>.</p> <p>quite literally, the only thing that <code>def f</code> depends on is that <code>a_instance</code> produces an attribute <code>.foo</code> that is a callable. Full stop.</p> <p>It doesn't matter if you pass in <code>A()</code> or <code>AChild()</code>...
5
2016-08-02T20:05:39Z
[ "python" ]
Pivot with Pandas Python to get booleans
38,729,448
<p>I have the following csv: <a href="https://github.com/antonio1695/Python/blob/master/nearBPO/facturas.csv" rel="nofollow">https://github.com/antonio1695/Python/blob/master/nearBPO/facturas.csv</a></p> <p>From which I created a dataframe with the following code:</p> <pre><code>import pandas as pd df = pd.read_csv("...
2
2016-08-02T20:01:07Z
38,729,800
<p>You can use</p> <pre><code>pd.concat([df2['UUID'], df2['Desc'].str.join('___').str.get_dummies('___')], axis=1) </code></pre> <p>It returns something like this:</p> <pre><code>Out: UUID SERVICIO POR HORA \ 0 0019A60D-78F8-E341-8D3E-9786201FE017 0 1 003B8...
3
2016-08-02T20:23:18Z
[ "python", "pandas", "dataframe", "merge", "pivot" ]
Apply condition on pandas columns to create a boolen indexing array
38,729,550
<p>I want to drop specific rows from a pandas dataframe. Usually you can do that using something like</p> <pre><code>df[df['some_column'] != 1234] </code></pre> <p>What <code>df['some_column'] != 1234</code> does is creating an indexing array that is indexing the new df, thus letting only rows with value <code>True</...
4
2016-08-02T20:07:38Z
38,729,819
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#special-use-of-the-operator-with-list-objects" rel="nofollow"><code>query</code></a> for this purpose:</p> <pre><code>df.query('some_column != list(my_dict.keys()') </code></pre>
1
2016-08-02T20:24:12Z
[ "python", "pandas" ]
Apply condition on pandas columns to create a boolen indexing array
38,729,550
<p>I want to drop specific rows from a pandas dataframe. Usually you can do that using something like</p> <pre><code>df[df['some_column'] != 1234] </code></pre> <p>What <code>df['some_column'] != 1234</code> does is creating an indexing array that is indexing the new df, thus letting only rows with value <code>True</...
4
2016-08-02T20:07:38Z
38,729,821
<p>What you're looking for is <code>isin()</code></p> <pre><code>import pandas as pd df = pd.DataFrame([[1, 2], [1, 3], [4, 6],[5,7],[8,9]], columns=['A', 'B']) In[9]: df Out[9]: df A B 0 1 2 1 1 3 2 4 6 3 5 7 4 8 9 mydict = {1:'A',8:'B'} df[df['A'].isin(mydict.keys())] Out[11]: A B 0 1 2 1 1 3...
2
2016-08-02T20:24:19Z
[ "python", "pandas" ]
Apply condition on pandas columns to create a boolen indexing array
38,729,550
<p>I want to drop specific rows from a pandas dataframe. Usually you can do that using something like</p> <pre><code>df[df['some_column'] != 1234] </code></pre> <p>What <code>df['some_column'] != 1234</code> does is creating an indexing array that is indexing the new df, thus letting only rows with value <code>True</...
4
2016-08-02T20:07:38Z
38,729,844
<p>You can use the function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow"><code>isin()</code></a> to select rows whose column value is in an iterable.</p> <h3>Using lists:</h3> <pre><code>my_list = ['my', 'own', 'data'] df.loc[df['column'].isin (my_list)] </...
1
2016-08-02T20:25:57Z
[ "python", "pandas" ]
File paths within my Python script fail when launching via double-click (Windows 10)
38,729,569
<p>I have a python script that reads and writes to files that are located relative to it, in directories above and beside it. When I run my script via Cygwin using</p> <pre><code>python script.py </code></pre> <p>The program works perfectly. However, when I run it by navigating through the windows GUI to my file and ...
0
2016-08-02T20:08:36Z
38,729,615
<p><strong>[edit]</strong> the other answer is correct(at least i suspect) but i will leave this here in the hopes that it helps the op in the future with path problems ... and doing something like this is just generally good practice</p> <hr> <p>use</p> <pre><code>BASEPATH = os.path.abspath(os.path.dirname(__file__...
4
2016-08-02T20:11:30Z
[ "python", "windows", "cmd", "cygwin" ]
File paths within my Python script fail when launching via double-click (Windows 10)
38,729,569
<p>I have a python script that reads and writes to files that are located relative to it, in directories above and beside it. When I run my script via Cygwin using</p> <pre><code>python script.py </code></pre> <p>The program works perfectly. However, when I run it by navigating through the windows GUI to my file and ...
0
2016-08-02T20:08:36Z
38,729,661
<p>The problem is not the current directory. It is correct when double clicking on the icon</p> <p>The problem is: Cygwin commands are not in the windows path</p> <p>You are using python, so don't run simple copy commands like this, which make your script non-portable and subject to variations, requiring installation...
2
2016-08-02T20:15:20Z
[ "python", "windows", "cmd", "cygwin" ]
How to show a Django auth user field in a custom admin list display
38,729,587
<p>I am using the Django auth user model along with a custom user profile model. The user profile admin looks like this:</p> <pre><code>class UserProfileAdmin(admin.ModelAdmin): list_display = ['user', 'first_login', 'project', 'type'] class Meta: model = UserProfile </code></pre> <p>The user profile ...
1
2016-08-02T20:09:58Z
38,729,740
<p>It is possible if you define say <code>wrapped_is_active</code> method in your custom admin model with signature like:</p> <pre><code>def wrapped_is_active(self, item): if item: return item.user.is_active wrapped_is_active.boolean = True </code></pre> <p>You should specify that method in your list_disp...
1
2016-08-02T20:19:47Z
[ "python", "django" ]
How to show a Django auth user field in a custom admin list display
38,729,587
<p>I am using the Django auth user model along with a custom user profile model. The user profile admin looks like this:</p> <pre><code>class UserProfileAdmin(admin.ModelAdmin): list_display = ['user', 'first_login', 'project', 'type'] class Meta: model = UserProfile </code></pre> <p>The user profile ...
1
2016-08-02T20:09:58Z
38,729,877
<p>it's possible : I made changes in your code have a look :</p> <pre><code>class UserProfileAdmin(admin.ModelAdmin): list_display = ['user', 'first_login', 'project', 'type','is_active'] class Meta: model = UserProfile class UserProfile(models.Model): user = models.OneToOneField(User) first_...
0
2016-08-02T20:28:00Z
[ "python", "django" ]
How to execute code asynchronously in Twisted Klein?
38,729,711
<p>I have two functions in my python Twisted Klein web service:</p> <pre><code>@inlineCallbacks def logging(data): ofile = open("file", "w") ofile.write(data) yield os.system("command to upload the written file") @APP.route('/dostuff') @inlineCallbacks def dostuff(): yield logging(data) print "che...
6
2016-08-02T20:18:16Z
38,846,221
<p>The 'yield' statement doesn't make things happen asynchronously. It just defers execution of the function containing it and returns a generator object that can later be used to iterate a sequence.</p> <p>So dostuff() is going to return a generator object. Nothing will happen until that generator object is iterated ...
1
2016-08-09T08:55:23Z
[ "python", "web-services", "asynchronous", "twisted", "klein-mvc" ]
How to execute code asynchronously in Twisted Klein?
38,729,711
<p>I have two functions in my python Twisted Klein web service:</p> <pre><code>@inlineCallbacks def logging(data): ofile = open("file", "w") ofile.write(data) yield os.system("command to upload the written file") @APP.route('/dostuff') @inlineCallbacks def dostuff(): yield logging(data) print "che...
6
2016-08-02T20:18:16Z
38,889,392
<p>To make your code async you need to use <a href="https://twistedmatrix.com/documents/current/core/howto/defer.html" rel="nofollow">Twisted Deferreds</a> as <a href="http://klein.readthedocs.io/en/latest/examples/deferreds.html" rel="nofollow">described here</a>. Deferreds give you an API for asynchronous code execut...
3
2016-08-11T07:00:31Z
[ "python", "web-services", "asynchronous", "twisted", "klein-mvc" ]
Chrome Web Push Notification with Encrypted Payload in Python
38,729,729
<p>Can someone please explain how to send Web Push Notification with Payload for Chrome using Curl/Python ?</p> <p>This is the code I am trying: </p> <p>Code: </p> <pre><code>fcm_url = "https://fcm.googleapis.com/fcm/send" headers = {'Content-Type': 'application/json'} headers.update({'Authorization': 'key=' + f...
0
2016-08-02T20:19:22Z
38,741,821
<p><strong>Working Code</strong></p> <pre><code>fcm_url = "https://fcm.googleapis.com/fcm/send" encoded = {'body': "i\x87\xb7W\xee\xd6QzL\xb6Q\xfe\xf5=t\xc4D[\xfe\xe3+g\xb7\x86\xdd\x81\xb9I\xffX\x99\x9b\x85$x\x80\xc6\x88\xe3\xbcm\x91\xff\x17a\x87C\x81\xf0\xbd\xb3}Y\xc8\xdb:\x14\x02\xf2R\xe7\x12\xcb\x1c\x0f\x13...
1
2016-08-03T11:05:11Z
[ "python", "django", "google-chrome", "push-notification", "google-cloud-messaging" ]
Writing numbers into a file- check code
38,729,810
<p>I'm taking my first ever CS class and I have an assignment due Friday. I just wanted someone to check my code and make sure it works/follows the directions.</p> <p>Instructions:</p> <p><strong>Write a program that:</strong></p> <p>1) gets the name of a text file of numbers from the user. Each number in the file ...
-1
2016-08-02T20:23:37Z
38,729,915
<p>Although this isn't a code review site, I'll give you some pointers.</p> <ol> <li>You never get a filename from the user - you should probably add that. It will be something like <code>filename = input('Enter filename: ')</code></li> <li>You overwrite the <code>even.txt</code> and <code>odd.txt</code> each time you...
0
2016-08-02T20:30:16Z
[ "python", "python-3.x", "file-writing" ]
pandas pivot_table keep index
38,729,856
<p>i have a dataframe :</p> <pre><code> day_bucket label numeric_value 0 2011-01-21 birds 4 1 2011-01-22 birds 0 2 2011-01-23 birds 7 3 2011-01-24 birds 3 </code></pre> <p>I want to pivot this dataframe so that i have a column <code>birds</code> with the...
2
2016-08-02T20:26:50Z
38,729,983
<p><code>set_index</code> with <code>append</code></p> <pre><code>df.set_index(['day_bucket', 'label'], append=True) \ .rename_axis([None, None, None]).squeeze().unstack() </code></pre> <p><a href="http://i.stack.imgur.com/zq7zb.png" rel="nofollow"><img src="http://i.stack.imgur.com/zq7zb.png" alt="enter image desc...
3
2016-08-02T20:35:21Z
[ "python", "pandas", "pivot", "pivot-table" ]
pandas pivot_table keep index
38,729,856
<p>i have a dataframe :</p> <pre><code> day_bucket label numeric_value 0 2011-01-21 birds 4 1 2011-01-22 birds 0 2 2011-01-23 birds 7 3 2011-01-24 birds 3 </code></pre> <p>I want to pivot this dataframe so that i have a column <code>birds</code> with the...
2
2016-08-02T20:26:50Z
38,730,306
<p>In the meantime i also came up with a result</p> <pre><code>pd.pivot_table(df, values='numeric_value', index=[df.index.values,'day_bucket'],columns='label').reset_index('day_bucket') label day_bucket mortality_birds 0 2011-01-21 4 1 2011-01-22 0 2 2011-01-23 ...
0
2016-08-02T20:57:35Z
[ "python", "pandas", "pivot", "pivot-table" ]
Converting dictionary with known indices to a multidimensional array
38,729,912
<p>I have a dictionary with entries labelled as <code>{(k,i): value, ...}</code>. I now want to convert this dictionary into a 2d array where the value given for an element of the array at position <code>[k,i]</code> is the value from the dictionary with label <code>(k,i)</code>. The length of the rows will not necessa...
4
2016-08-02T20:30:08Z
38,730,099
<p>Here's an approach -</p> <pre><code># Get keys (as indices for output) and values as arrays idx = np.array(d.keys()) vals = np.array(d.values()) # Get dimensions of output array based on max extents of indices dims = idx.max(0)+1 # Setup output array and assign values into it indexed by those indices out = np.zer...
3
2016-08-02T20:43:03Z
[ "python", "numpy", "dictionary" ]
Converting dictionary with known indices to a multidimensional array
38,729,912
<p>I have a dictionary with entries labelled as <code>{(k,i): value, ...}</code>. I now want to convert this dictionary into a 2d array where the value given for an element of the array at position <code>[k,i]</code> is the value from the dictionary with label <code>(k,i)</code>. The length of the rows will not necessa...
4
2016-08-02T20:30:08Z
38,730,781
<p>There is a dictionary-of-keys sparse format that can be built from a dictionary like this.</p> <p>Starting with <code>Divakar's</code> <code>d</code> sample:</p> <pre><code>In [1189]: d={(1, 4): 120, (2, 2): 72, (2, 3): 100, (5, 2): 88} </code></pre> <p>Make an empty sparse matrix of the right shape and dtype:</p...
0
2016-08-02T21:29:29Z
[ "python", "numpy", "dictionary" ]
How to write multiprocessing python codes with dictionary and dataframe
38,730,023
<p>I spent couple hours on multiprocessing coding on Python. After I read codes on <a href="https://docs.python.org/2.7/library/multiprocessing.html" rel="nofollow">document</a>, I wrote codes below. My plan is to add values in two global dataframe together, and assign the result to a dictionary. </p> <pre><code>from...
0
2016-08-02T20:37:40Z
38,730,125
<p>Example here that you could adapt and which works:</p> <p><a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">https://docs.python.org/2/library/multiprocessing.html</a></p> <p>You have you use a manager object to be able to share memory between processes.</p> <p>In your example you cre...
0
2016-08-02T20:45:16Z
[ "python", "dictionary", "dataframe", "python-multiprocessing" ]
How to allocate memory to a C callback function with ctypes and threading
38,730,072
<p>I'm currently writing python bindings for a camera software. The commercial SDK only contains the documentation and DLL. I do not have the C code but I'll try to be as clear as possible, so please bear with me. </p> <p>I have all the library functions working but one: a callback function that acquires the pictures....
0
2016-08-02T20:41:17Z
38,761,040
<p>I'm not sure where you went wrong without a complete example. Did you declare <code>foo.argtypes</code>? Are you sure the functions are <code>__stdcall</code> for use with <code>WinDLL</code> and <code>WINFUNCTYPE</code>, or are they <code>__cdecl</code> and need <code>CDLL</code> and <code>CFUNCTYPE</code>?</p> ...
1
2016-08-04T07:28:52Z
[ "python", "c", "multithreading", "ctypes" ]
Parsing CSVs for only one value
38,730,174
<p>I am trying to parse data from CSV files. The files are in a folder and I want to extract data and write them to the db. However the csvs are not set up in a table format. I know how to import csvs into the db with the for each loop container, adding data flow tasks, and importing with OLE DB Destination. </p> <p>T...
-1
2016-08-02T20:49:04Z
39,028,356
<p>I'd try this:</p> <pre><code>filename = # from the from the path of the file you're parsing # define appropriate vars for row in csv_file: if row.find('Date saved') &gt; 0: row = row.replace('Date saved ') date_saved = row[0:row.find(' ')] row = row.replace(date_saved + ' ...
0
2016-08-18T22:18:56Z
[ "python", "csv", "parsing", "ssis" ]
Problems with parsing JSON for D3
38,730,227
<p>I am building an app with Flask and Python, and I want to pass some of my Python-generated results into JSON, so that they can be visualized with D3 under a container fluid. To do this, I am trying to use the Jinja method <code>var myjson = {{jsonDict|tojson }};</code>. Here <code>jsonDict</code> is a variable in my...
1
2016-08-02T20:51:57Z
38,749,565
<p>Because you are already passing your json to your client via your flask application there is no need to use d3's <code>d3.json()</code> method. <code>d3.json()</code> is essentially an <code>ajax</code> <code>GET</code> request which requests the file from the server. </p> <blockquote> <h1>d3.json(url[, callback]...
1
2016-08-03T16:55:26Z
[ "javascript", "python", "json", "d3.js", "flask" ]
Django admin: timezone display
38,730,230
<p>So i am making an app where you can find activities which happen at locations.</p> <p>On the django-admin page i want to be able to modify Activities (which works).</p> <p>However an activity has a starting time - i want this starting time to be in the same timezone as the location.</p> <p>So i want it to display...
0
2016-08-02T20:52:03Z
38,730,431
<p>"<em>So i want it to display the start time, on the activity admin page, in the same timezone as the location is in, but then when saved it should be converted to UTC time.</em>"</p> <p>According to Django's documentation on <strong>Time zone aware input in forms</strong> (<a href="https://docs.djangoproject.com/en...
1
2016-08-02T21:05:04Z
[ "python", "django", "django-admin" ]
Django admin: timezone display
38,730,230
<p>So i am making an app where you can find activities which happen at locations.</p> <p>On the django-admin page i want to be able to modify Activities (which works).</p> <p>However an activity has a starting time - i want this starting time to be in the same timezone as the location.</p> <p>So i want it to display...
0
2016-08-02T20:52:03Z
38,730,489
<p>Try to set <br> <code>USE_L10N = False</code> on settings.py:<br> <br> <a href="https://docs.djangoproject.com/en/1.9/ref/settings/#use-l10n" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/settings/#use-l10n</a></p>
0
2016-08-02T21:08:25Z
[ "python", "django", "django-admin" ]
How to put generator expressions as input to Python's join method?
38,730,265
<p>How do I put several generator expressions as input to Python's <code>join</code> method? I tried the following which don't work. Is there a difference when using Python 2.x and 3.x? My exact version is Python 2.7.12.</p> <pre><code>def productList(self, obj): return ", ".join([w.name for w in obj.someProducts...
1
2016-08-02T20:54:49Z
38,730,374
<p>If you want to display name and code, you just need to combine them, you don't need two generators.</p> <pre><code>', '.join(w.name + ':' + w.code for w in obj.someProducts.all()) </code></pre> <p>Or string formatting:</p> <pre><code>', '.join('{name}: {code}'.format(name=w.name, code=w.code) for w in obj.somePro...
2
2016-08-02T21:01:22Z
[ "python" ]
How to put generator expressions as input to Python's join method?
38,730,265
<p>How do I put several generator expressions as input to Python's <code>join</code> method? I tried the following which don't work. Is there a difference when using Python 2.x and 3.x? My exact version is Python 2.7.12.</p> <pre><code>def productList(self, obj): return ", ".join([w.name for w in obj.someProducts...
1
2016-08-02T20:54:49Z
38,730,401
<p>Give it a try:</p> <pre><code>', '.join('{}{}'.format(w.name, w.code) for w in obj.someProducts.all()) </code></pre> <p>I just made the w.name and w.code one string, that way you don't need 2 lists. Change the format as you wish.</p>
2
2016-08-02T21:02:55Z
[ "python" ]
Need help using M2Crypto and USB Token
38,730,319
<p>I am using M2Crypto (0.22.6rc4). I want to use <code>engine_pkcs11</code> from the OpenSC project and the Aladdin PKI client for token based authentication to encrypt and decrypt data.</p> <pre><code>from M2Crypto import Engine, m2, RSA, BIO slot_id = "slot_01" pin = "password" dynamic = Engine.load_dynamic_engine...
0
2016-08-02T20:58:26Z
39,989,300
<p>There is a bug in the M2Crypto wrapping of RSA private keys. A work around is use the low level M2Crypto API to directly access the private key object.</p> <pre><code>def decrypt(cipher_text): # Load the key using high level API engine = Engine.Engine('pkcs11') engine.init() key_slot = 'slot_1-id_0...
0
2016-10-12T01:49:32Z
[ "python", "encryption", "pkcs#11", "m2crypto", "opensc" ]
Two function one after the other when clicked pushbutton - Pyside
38,730,411
<p>I have a little problem with py pyside script. I make a setup wizard and I want to change my current widget in my stackedwidget then make the all installation of librairies etc...</p> <p>I've tried two solutions:</p> <p>The first is this one:</p> <pre><code>self.pushButton.clicked.connect(lambda: changepage(self,...
0
2016-08-02T21:03:43Z
38,731,348
<p>The slot connected to the signal is called <em>synchronously</em>, so the GUI will not be updated until it returns. There are lots of different ways to solve this, but you can try forcing an update like this:</p> <pre><code>def changepage(self, MainWindow): self.stackedWidget.setCurrentIndex(4) QtGui.qApp.p...
0
2016-08-02T22:15:56Z
[ "python", "qt", "pyside", "qstackedwidget" ]
OpenCV with Python - reading images in a loop
38,730,473
<p>I'm using OpenCV's <code>imread</code> function to read my images into Python, for further processing as a NumPy array later in the pipeline. I know that OpenCV uses BGR instead of RGB, and have accounted for it, where required. But one thing that stumps me is why I get these differing outputs for the following scen...
0
2016-08-02T21:07:24Z
38,730,638
<p>Extremely trivial solution. <code>np.empty</code> creates an array of dtype float by default. Changing this to uint8 as in the first case with OpenCV alone worked fine. </p>
0
2016-08-02T21:19:33Z
[ "python", "opencv", "matplotlib" ]
Change pytest capturing for one test
38,730,502
<p>Is it possible to change the capturing behavior in pytest for just one test — i.e., within the test script?</p> <p>I have a bunch of tests that I use with <a href="http://doc.pytest.org/en/latest/" rel="nofollow"><code>pytest</code></a>. There are several useful quantities that I like to print during some tests...
1
2016-08-02T21:09:44Z
38,733,664
<p>I've done it by manually redirecting <code>stderr</code>:</p> <pre><code>import os import sys import warnings import pytest def test(): stderr = sys.stderr sys.stderr = open(os.devnull, 'w') with pytest.warns(UserWarning): warnings.warn("Warning!", UserWarning) sys.stderr = stderr </code></...
1
2016-08-03T02:58:07Z
[ "python", "py.test" ]
Change pytest capturing for one test
38,730,502
<p>Is it possible to change the capturing behavior in pytest for just one test — i.e., within the test script?</p> <p>I have a bunch of tests that I use with <a href="http://doc.pytest.org/en/latest/" rel="nofollow"><code>pytest</code></a>. There are several useful quantities that I like to print during some tests...
1
2016-08-02T21:09:44Z
38,739,444
<p>With pytest 3.x there is an <a href="http://doc.pytest.org/en/features/capture.html#accessing-captured-output-from-a-test-function" rel="nofollow">easy way</a> to temporarily disable capturing (see the section about <code>capsys.disabled()</code>.</p> <p>There's also the <a href="https://github.com/fschulze/pytest-...
2
2016-08-03T09:19:21Z
[ "python", "py.test" ]
Google Drive API List Folders GET
38,730,532
<p>I am trying to query Google Drive for a certain file to find its url. Here is my code. The only thing I changed was my API key is substituted with AAAAAAAAAA</p> <pre><code> queryString = urllib.quote_plus("title = \'" + filename + "\'") parameters = {'key':'{AAAAAAAAAA}', 'q': queryString} inserted_file...
0
2016-08-02T21:11:34Z
38,749,836
<p><a href="https://developers.google.com/drive/v3/web/handle-errors#400_bad_request" rel="nofollow">400 error</a> response means the <code>value</code> supplied is invalid or the combination of provided fields is invalid. Its user error. This can mean that a required field or parameter has not been provided.</p> <p>I...
0
2016-08-03T17:11:19Z
[ "python", "get", "google-drive-sdk", "python-requests", "urllib" ]
Is there a specific range of unicode code points which can be checked for emojis?
38,730,560
<p>Do emojis occupy a well-defined unicode range?</p> <p>And, is there a definitive way to check whether a code point is an emoji in python 2.7?</p> <p>I cannot seem to find any information on this. A couple of sources have pointed to the range:</p> <pre><code>\U0001f600-\U0001f650 </code></pre> <p>But for example...
9
2016-08-02T21:13:36Z
38,730,797
<p><a href="https://pypi.python.org/pypi/regex" rel="nofollow">regex</a> supports matching by Unicode property, but unfortunately it does not (yet?) support the <a href="http://unicode.org/reports/tr51/#Data_Files" rel="nofollow">emoji-specific properties</a>. When it does, finding them will be as simple as:</p> <pre>...
4
2016-08-02T21:30:45Z
[ "python", "python-2.7", "unicode" ]
Reading live output from telnet connection in python
38,730,611
<p>I have an Arduino set up as a server. In Terminal (I use a Mac), one can connect to it, see the output, and close the connection as follows: </p> <pre><code>&gt; telnet HOST Trying 192.168.0.101... Connected to HOST. Escape character is '^]'. 0 , 25486 , 0.00 : 1 , 25754 , 0.00 : 2 , 26054 , 0.00 : 3 , 26320 , 0.00...
1
2016-08-02T21:17:32Z
38,731,450
<p>Can you work at a lower level, using the <a href="https://docs.python.org/3.5/library/socket.html" rel="nofollow"><code>socket</code> module</a>?</p> <pre><code>import socket s = socket.socket( socket.AF_INET, socket.SOCK_STREAM) s.connect(("192.168.0.101", 23)) while True: data = str(s.recv(1024),encoding...
0
2016-08-02T22:26:06Z
[ "python", "c++", "arduino", "telnet", "telnetlib" ]
How do I write the index for a list of lists
38,730,635
<p>I have a list of 3 lists each containing a random integer between 1 and 9:</p> <pre><code>lists= [[1,3,5],[2,4,6],[7,8,9]] </code></pre> <p>I ask the user to select any single digit number. I am making a program that finds the number one less than the user inputs and then decides if the next number in the list (a...
0
2016-08-02T21:19:04Z
38,730,704
<p>if your list is </p> <pre><code>lists= [[1,3,5],[2,4,6],[7,8,9]] </code></pre> <p>to access the "1" you would type: <code>lists[0][0]</code> to access the "8" you would type: <code>lists[2][1]</code></p> <p>*remember lists start their index at 0!!! :)</p>
2
2016-08-02T21:23:53Z
[ "python", "list", "syntax" ]
How do I write the index for a list of lists
38,730,635
<p>I have a list of 3 lists each containing a random integer between 1 and 9:</p> <pre><code>lists= [[1,3,5],[2,4,6],[7,8,9]] </code></pre> <p>I ask the user to select any single digit number. I am making a program that finds the number one less than the user inputs and then decides if the next number in the list (a...
0
2016-08-02T21:19:04Z
38,730,722
<pre><code>lists= [[1,3,5],[2,4,6],[7,8,9]] for x in lists: index = 0 for i in x: index += 1 if i == user_choice - 1: print(x[index]) else: (...) </code></pre>
0
2016-08-02T21:25:26Z
[ "python", "list", "syntax" ]