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
Have Pandas column containing lists, how to pivot unique list elements to columns?
39,459,321
<p>I wrote a web scraper to pull information from a table of products and build a dataframe. The data table has a Description column which contains a comma separated string of attributes describing the product. I want to create a column in the dataframe for every unique attribute and populate the row in that column with the attribute's substring. Example df below.</p> <pre><code>PRODUCTS DATE DESCRIPTION Product A 2016-9-12 Steel, Red, High Hardness Product B 2016-9-11 Blue, Lightweight, Steel Product C 2016-9-12 Red </code></pre> <p>I figure the first step is to split the description into a list.</p> <pre><code>In: df2 = df['DESCRIPTION'].str.split(',') Out: DESCRIPTION ['Steel', 'Red', 'High Hardness'] ['Blue', 'Lightweight', 'Steel'] ['Red'] </code></pre> <p>My desired output looks like the table below. The column names are not particularly important.</p> <pre><code>PRODUCTS DATE STEEL_COL RED_COL HIGH HARDNESS_COL BLUE COL LIGHTWEIGHT_COL Product A 2016-9-12 Steel Red High Hardness Product B 2016-9-11 Steel Blue Lightweight Product C 2016-9-12 Red </code></pre> <p>I believe the columns can be set up using a Pivot but I'm not sure the most Pythonic way to populate the columns after establishing them. Any help is appreciated.</p> <h2>UPDATE</h2> <p>Thank you very much for the answers. I selected @MaxU's response as correct since it seems slightly more flexible, but @piRSquared's gets a very similar result and may even be considered the more Pythonic approach. I tested both version and both do what I needed. Thanks!</p>
6
2016-09-12T21:50:30Z
39,459,814
<p>you can build up a sparse matrix:</p> <pre><code>In [27]: df Out[27]: PRODUCTS DATE DESCRIPTION 0 Product A 2016-9-12 Steel, Red, High Hardness 1 Product B 2016-9-11 Blue, Lightweight, Steel 2 Product C 2016-9-12 Red In [28]: (df.set_index(['PRODUCTS','DATE']) ....: .DESCRIPTION.str.split(',\s*', expand=True) ....: .stack() ....: .reset_index() ....: .pivot_table(index=['PRODUCTS','DATE'], columns=0, fill_value=0, aggfunc='size') ....: ) Out[28]: 0 Blue High Hardness Lightweight Red Steel PRODUCTS DATE Product A 2016-9-12 0 1 0 1 1 Product B 2016-9-11 1 0 1 0 1 Product C 2016-9-12 0 0 0 1 0 In [29]: (df.set_index(['PRODUCTS','DATE']) ....: .DESCRIPTION.str.split(',\s*', expand=True) ....: .stack() ....: .reset_index() ....: .pivot_table(index=['PRODUCTS','DATE'], columns=0, fill_value='', aggfunc='size') ....: ) Out[29]: 0 Blue High Hardness Lightweight Red Steel PRODUCTS DATE Product A 2016-9-12 1 1 1 Product B 2016-9-11 1 1 1 Product C 2016-9-12 1 </code></pre>
5
2016-09-12T22:41:19Z
[ "python", "pandas", "numpy", "dataframe", "pivot" ]
Have Pandas column containing lists, how to pivot unique list elements to columns?
39,459,321
<p>I wrote a web scraper to pull information from a table of products and build a dataframe. The data table has a Description column which contains a comma separated string of attributes describing the product. I want to create a column in the dataframe for every unique attribute and populate the row in that column with the attribute's substring. Example df below.</p> <pre><code>PRODUCTS DATE DESCRIPTION Product A 2016-9-12 Steel, Red, High Hardness Product B 2016-9-11 Blue, Lightweight, Steel Product C 2016-9-12 Red </code></pre> <p>I figure the first step is to split the description into a list.</p> <pre><code>In: df2 = df['DESCRIPTION'].str.split(',') Out: DESCRIPTION ['Steel', 'Red', 'High Hardness'] ['Blue', 'Lightweight', 'Steel'] ['Red'] </code></pre> <p>My desired output looks like the table below. The column names are not particularly important.</p> <pre><code>PRODUCTS DATE STEEL_COL RED_COL HIGH HARDNESS_COL BLUE COL LIGHTWEIGHT_COL Product A 2016-9-12 Steel Red High Hardness Product B 2016-9-11 Steel Blue Lightweight Product C 2016-9-12 Red </code></pre> <p>I believe the columns can be set up using a Pivot but I'm not sure the most Pythonic way to populate the columns after establishing them. Any help is appreciated.</p> <h2>UPDATE</h2> <p>Thank you very much for the answers. I selected @MaxU's response as correct since it seems slightly more flexible, but @piRSquared's gets a very similar result and may even be considered the more Pythonic approach. I tested both version and both do what I needed. Thanks!</p>
6
2016-09-12T21:50:30Z
39,460,028
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>pd.get_dummies</code></a></p> <pre><code>cols = ['PRODUCTS', 'DATE'] pd.get_dummies( df.set_index(cols).DESCRIPTION \ .str.split(',\s*', expand=True).stack() ).groupby(level=cols).sum().astype(int) </code></pre> <p><a href="http://i.stack.imgur.com/YZWfM.png" rel="nofollow"><img src="http://i.stack.imgur.com/YZWfM.png" alt="enter image description here"></a></p>
5
2016-09-12T23:09:04Z
[ "python", "pandas", "numpy", "dataframe", "pivot" ]
opening several txt files using while loop
39,459,322
<p>I have some txt files that their names have the following pattern: </p> <pre><code>arc.1.txt, arc.2.txt,...,arc.100.txt,..., arc.500.txt,...,arc.838.txt </code></pre> <p>I know that we can write a program using <code>for loop</code> to open the files one by one, if we now the total numbers of files. I want to know is it possible to use <code>While loop</code> without counting the number files to open them ? </p>
0
2016-09-12T21:50:34Z
39,459,351
<p>It is definitely possible to use a while loop assuming that the files are numbered in sequential order:</p> <pre><code>i = 0 while True: i += 1 filename = 'arc.%d.txt' % i try: with open(filename, 'r') as file_handle: ... except IOError: break </code></pre> <p>Though this becomes pretty ugly with all the nesting. You're probably better off getting the list of filenames using something like <a href="https://docs.python.org/2/library/glob.html#glob.glob" rel="nofollow"><code>glob.glob</code></a>.</p> <pre><code>from glob import glob filenames = glob('arc.*.txt') for filename in filenames: with open(filename) as file_handle: ... </code></pre> <p>There are some race conditions associated with this second approach -- If the file somehow gets deleted between when <code>glob</code> found it and when it actually is time to process the file then your program could have a bad day.</p>
3
2016-09-12T21:53:03Z
[ "python", "for-loop", "text", "while-loop" ]
opening several txt files using while loop
39,459,322
<p>I have some txt files that their names have the following pattern: </p> <pre><code>arc.1.txt, arc.2.txt,...,arc.100.txt,..., arc.500.txt,...,arc.838.txt </code></pre> <p>I know that we can write a program using <code>for loop</code> to open the files one by one, if we now the total numbers of files. I want to know is it possible to use <code>While loop</code> without counting the number files to open them ? </p>
0
2016-09-12T21:50:34Z
39,459,358
<pre><code>import glob for each_file in glob.glob("arc\.\d+\.txt"): print(each_file) </code></pre>
4
2016-09-12T21:53:27Z
[ "python", "for-loop", "text", "while-loop" ]
opening several txt files using while loop
39,459,322
<p>I have some txt files that their names have the following pattern: </p> <pre><code>arc.1.txt, arc.2.txt,...,arc.100.txt,..., arc.500.txt,...,arc.838.txt </code></pre> <p>I know that we can write a program using <code>for loop</code> to open the files one by one, if we now the total numbers of files. I want to know is it possible to use <code>While loop</code> without counting the number files to open them ? </p>
0
2016-09-12T21:50:34Z
39,459,374
<p>If you add them all to a list and then remove them one by one and set the while condition to while (name of list) > 0: then open the next file </p>
0
2016-09-12T21:55:01Z
[ "python", "for-loop", "text", "while-loop" ]
Python code works 20 times slower than Java. Is there a way to speed up Python?
39,459,386
<p>I wrote a program in Python and in Java to search for the smallest integer solution of the equation:</p> <p>a^5+b^5+c^5+d^5=e^5 (expected output is 133^5+110^5+84^5+27^5=144^5)</p> <p>Powers and roots are either computed directly ("direct calculation" method) or computed and stored in an array ("power lookup" method). Fifth powers are looked up like n5 = fifth_power[n]. Fifth power root is computed using a binary search in array 'fifth_power`.</p> <p>I am running it on NetBeans if it matters. It takes:</p> <pre><code>30. s (Python, direct) 20. s (Python, lookup) 5.6 s (Java, direct) 0.8 s (Java, lookup) </code></pre> <p>Is there a way to boost Python performance? I am not looking for better math (sieving of some kind). I am looking for better implementation of "for each combination of a,b,c,d compute some of their powers, check if the sum is a perfect power. If it is - print the result".</p> <p>Is it expected that Python runs some 20 times slower than Java? </p> <p>Python 3.5 </p> <p><a href="http://pastebin.com/qVthWGKm" rel="nofollow">http://pastebin.com/qVthWGKm</a></p> <pre><code>from array import * import math import time #PYTHON, BRUTEFORCE : ~30 s millis1 = int(round(time.time() * 1000)) keep_searching = True a=1 result="" while(keep_searching): a+=1 for b in range(1,a+1): for c in range(1,b+1): for d in range(1,c+1): sum=math.pow(a,5)+math.pow(b,5)+math.pow(c,5)+math.pow(d,5) root = math.pow(sum,0.2) e = round(root) e5 = math.pow(e,5) if(e5==sum): result="{}^5 + {}^5 + {}^5 + {}^5 = {}^5".format(int(a),int(b), int(c),int(d), int(e)) keep_searching = False millis2 = int(round(time.time() * 1000)) print(result) print("Found solution in {} ms".format(millis2-millis1)) #PYTHON, PRECOMPUTE POWERS: ~20 s millis3 = int(round(time.time() * 1000)) #fifth_power #175 is enough size=176 fifth_power = [None] * size for i in range(size): fifth_power[i]=long(math.pow(i,5)) millis4 = int(round(time.time() * 1000)) #returns value if it is a perfect power (32 returns 2) #returns -1 if between perfect powers, -2 if greater than max value in array, -3 if smaller than min value in array def check_perfect_power(number, min, max, fifth_power): current=int((min+max)/2) while(max&gt;=min): if(number==fifth_power[current]): return current elif(number&gt;fifth_power[current]): min=current+1 current=int((max+min)/2) else: max=current-1 current=int((max+min)/2) if(min&gt;=len(fifth_power)): return -2 if(max&lt;0): return -3 return -1 keep_searching = True a=0 result="" while(keep_searching): a+=1 for b in range(1,a+1): for c in range(1,b+1): for d in range(1,c+1): mymax=min(int(a*1.32)+1, size-1) e=check_perfect_power(fifth_power[a]+fifth_power[b]+fifth_power[c]+fifth_power[d], a, mymax, fifth_power) if(e&gt;0): result="{}^5 + {}^5 + {}^5 + {}^5 = {}^5".format(int(a),int(b), int(c),int(d), int(e)) keep_searching = False millis5 = int(round(time.time() * 1000)) print(result) print("Populated in {} ms, find solution in {} ms".format(millis4-millis3,millis5-millis4)) </code></pre> <p>Java 8: </p> <p><a href="http://pastebin.com/G4V3fHnD" rel="nofollow">http://pastebin.com/G4V3fHnD</a></p> <pre><code>import java.util.ArrayList; public class Eu514 { public static void main(String[] args) { bruteforce(); //Solution found by bruteforce in 5600 ms. prepopulate(); //Solution found by prepopulation in 761 ms. } public static void bruteforce(){ //JAVA BRUTEFORCE Long t2 = 0L; Long t1 = System.currentTimeMillis(); boolean keepSearching = true; int a = 0; long e = 0; String solution = ""; while (keepSearching) { a++; for (int b = 1; b &lt;= a; b++) { for (int c = 1; c &lt;= b; c++) { for (int d = 1; d &lt;= c; d++) { long sum = (long) (Math.pow(a, 5) + Math.pow(b, 5) + Math.pow(c, 5) + Math.pow(d, 5)); //sum=a^5+b^5+c^5+d^5 e = Math.round(Math.pow(sum, 0.2)); //e= sum^(1/5), rounded long e5 = (long) Math.pow(e,5); //e^5 if(e5==sum){ t2 = System.currentTimeMillis(); solution = a + "^5 + " + b + "^5 + " + c + "^5 + " + d + "^5 = " + e + "^5"; keepSearching = false; } } } } } long delta = ((t2-t1)); System.out.println(solution+"\nSolution found by bruteforce in "+delta+" ms."); } public static void prepopulate(){ //JAVA PREPOPULATE Long t2 = 0L; Long t1 = System.currentTimeMillis(); int size = 176; long[] powers = populatePowers(size); boolean keepSearching = true; int a = 0; int e = 0; String solution = ""; while (keepSearching) { a++; for (int b = 1; b &lt;= a; b++) { for (int c = 1; c &lt;= b; c++) { for (int d = 1; d &lt;= c; d++) { long sum = powers[a] + powers[b] + powers[c] + powers[d]; int max = (int) Math.min(size - 1, (a * 1.32 + 1)); e = checkIfPerfectPower(sum, a, max, powers); if (e &gt; 0) { t2 = System.currentTimeMillis(); solution = a + "^5 + " + b + "^5 + " + c + "^5 + " + d + "^5 = " + e + "^5"; keepSearching = false; } } } } } long delta = ((t2-t1)); System.out.println(solution+"\nSolution found by prepopulation in "+delta+" ms."); } public static long[] populatePowers(int max){ long[] powers = new long[max]; for (int i = 0; i &lt; powers.length; i++) { powers[i]=(long) Math.pow(i,5); } return powers; } public static int checkIfPerfectPower(long number, int min, int max, long[] arr){ int current =((min+max)/2); while(max&gt;=min){ if(number==arr[current]){ return current; }else if(number&gt;arr[current]){ min = current + 1; current = (max + min) / 2; }else{ max=current-1; current=(max+min)/2; } } if(min&gt;=arr.length) return -2; if(max&lt;0) return -3; return -1; } } </code></pre>
1
2016-09-12T21:56:05Z
39,459,872
<pre><code>from array import * import time import numpy as np #PYTHON, BRUTEFORCE : ~30 s millis1 = int(round(time.time() * 1000)) keep_searching = True a = 1 result = "" while(keep_searching): a += 1 a_pow = a ** 5 for b in xrange(1, a+1): b_pow = b ** 5 for c in xrange(1, b+1): c_pow = c ** 5 for d in xrange(1, c+1): d_pow = d ** 5 sum_pow = a_pow + b_pow + c_pow + d_pow root = sum_pow ** 0.2 e = round(root) e5 = e ** 5 if(e5 == sum_pow): result="{}^5 + {}^5 + {}^5 + {}^5 = {}^5".format(a, b, c, d, e) keep_searching = False millis2 = int(round(time.time() * 1000)) print(result) print("Found solution in {} ms".format(millis2-millis1)) </code></pre> <p>Python 2.7, with some code optimizations</p> <p>133^5 + 110^5 + 84^5 + 27^5 = 144.0^5 Found solution in 8333 ms</p> <p>It could be a little different from CPU to CPU.</p>
1
2016-09-12T22:49:09Z
[ "java", "python", "performance" ]
Python code works 20 times slower than Java. Is there a way to speed up Python?
39,459,386
<p>I wrote a program in Python and in Java to search for the smallest integer solution of the equation:</p> <p>a^5+b^5+c^5+d^5=e^5 (expected output is 133^5+110^5+84^5+27^5=144^5)</p> <p>Powers and roots are either computed directly ("direct calculation" method) or computed and stored in an array ("power lookup" method). Fifth powers are looked up like n5 = fifth_power[n]. Fifth power root is computed using a binary search in array 'fifth_power`.</p> <p>I am running it on NetBeans if it matters. It takes:</p> <pre><code>30. s (Python, direct) 20. s (Python, lookup) 5.6 s (Java, direct) 0.8 s (Java, lookup) </code></pre> <p>Is there a way to boost Python performance? I am not looking for better math (sieving of some kind). I am looking for better implementation of "for each combination of a,b,c,d compute some of their powers, check if the sum is a perfect power. If it is - print the result".</p> <p>Is it expected that Python runs some 20 times slower than Java? </p> <p>Python 3.5 </p> <p><a href="http://pastebin.com/qVthWGKm" rel="nofollow">http://pastebin.com/qVthWGKm</a></p> <pre><code>from array import * import math import time #PYTHON, BRUTEFORCE : ~30 s millis1 = int(round(time.time() * 1000)) keep_searching = True a=1 result="" while(keep_searching): a+=1 for b in range(1,a+1): for c in range(1,b+1): for d in range(1,c+1): sum=math.pow(a,5)+math.pow(b,5)+math.pow(c,5)+math.pow(d,5) root = math.pow(sum,0.2) e = round(root) e5 = math.pow(e,5) if(e5==sum): result="{}^5 + {}^5 + {}^5 + {}^5 = {}^5".format(int(a),int(b), int(c),int(d), int(e)) keep_searching = False millis2 = int(round(time.time() * 1000)) print(result) print("Found solution in {} ms".format(millis2-millis1)) #PYTHON, PRECOMPUTE POWERS: ~20 s millis3 = int(round(time.time() * 1000)) #fifth_power #175 is enough size=176 fifth_power = [None] * size for i in range(size): fifth_power[i]=long(math.pow(i,5)) millis4 = int(round(time.time() * 1000)) #returns value if it is a perfect power (32 returns 2) #returns -1 if between perfect powers, -2 if greater than max value in array, -3 if smaller than min value in array def check_perfect_power(number, min, max, fifth_power): current=int((min+max)/2) while(max&gt;=min): if(number==fifth_power[current]): return current elif(number&gt;fifth_power[current]): min=current+1 current=int((max+min)/2) else: max=current-1 current=int((max+min)/2) if(min&gt;=len(fifth_power)): return -2 if(max&lt;0): return -3 return -1 keep_searching = True a=0 result="" while(keep_searching): a+=1 for b in range(1,a+1): for c in range(1,b+1): for d in range(1,c+1): mymax=min(int(a*1.32)+1, size-1) e=check_perfect_power(fifth_power[a]+fifth_power[b]+fifth_power[c]+fifth_power[d], a, mymax, fifth_power) if(e&gt;0): result="{}^5 + {}^5 + {}^5 + {}^5 = {}^5".format(int(a),int(b), int(c),int(d), int(e)) keep_searching = False millis5 = int(round(time.time() * 1000)) print(result) print("Populated in {} ms, find solution in {} ms".format(millis4-millis3,millis5-millis4)) </code></pre> <p>Java 8: </p> <p><a href="http://pastebin.com/G4V3fHnD" rel="nofollow">http://pastebin.com/G4V3fHnD</a></p> <pre><code>import java.util.ArrayList; public class Eu514 { public static void main(String[] args) { bruteforce(); //Solution found by bruteforce in 5600 ms. prepopulate(); //Solution found by prepopulation in 761 ms. } public static void bruteforce(){ //JAVA BRUTEFORCE Long t2 = 0L; Long t1 = System.currentTimeMillis(); boolean keepSearching = true; int a = 0; long e = 0; String solution = ""; while (keepSearching) { a++; for (int b = 1; b &lt;= a; b++) { for (int c = 1; c &lt;= b; c++) { for (int d = 1; d &lt;= c; d++) { long sum = (long) (Math.pow(a, 5) + Math.pow(b, 5) + Math.pow(c, 5) + Math.pow(d, 5)); //sum=a^5+b^5+c^5+d^5 e = Math.round(Math.pow(sum, 0.2)); //e= sum^(1/5), rounded long e5 = (long) Math.pow(e,5); //e^5 if(e5==sum){ t2 = System.currentTimeMillis(); solution = a + "^5 + " + b + "^5 + " + c + "^5 + " + d + "^5 = " + e + "^5"; keepSearching = false; } } } } } long delta = ((t2-t1)); System.out.println(solution+"\nSolution found by bruteforce in "+delta+" ms."); } public static void prepopulate(){ //JAVA PREPOPULATE Long t2 = 0L; Long t1 = System.currentTimeMillis(); int size = 176; long[] powers = populatePowers(size); boolean keepSearching = true; int a = 0; int e = 0; String solution = ""; while (keepSearching) { a++; for (int b = 1; b &lt;= a; b++) { for (int c = 1; c &lt;= b; c++) { for (int d = 1; d &lt;= c; d++) { long sum = powers[a] + powers[b] + powers[c] + powers[d]; int max = (int) Math.min(size - 1, (a * 1.32 + 1)); e = checkIfPerfectPower(sum, a, max, powers); if (e &gt; 0) { t2 = System.currentTimeMillis(); solution = a + "^5 + " + b + "^5 + " + c + "^5 + " + d + "^5 = " + e + "^5"; keepSearching = false; } } } } } long delta = ((t2-t1)); System.out.println(solution+"\nSolution found by prepopulation in "+delta+" ms."); } public static long[] populatePowers(int max){ long[] powers = new long[max]; for (int i = 0; i &lt; powers.length; i++) { powers[i]=(long) Math.pow(i,5); } return powers; } public static int checkIfPerfectPower(long number, int min, int max, long[] arr){ int current =((min+max)/2); while(max&gt;=min){ if(number==arr[current]){ return current; }else if(number&gt;arr[current]){ min = current + 1; current = (max + min) / 2; }else{ max=current-1; current=(max+min)/2; } } if(min&gt;=arr.length) return -2; if(max&lt;0) return -3; return -1; } } </code></pre>
1
2016-09-12T21:56:05Z
39,460,548
<p>What about improving the java code?</p> <pre><code>int size = 200; long[] pow5 = new long[size]; for (int i = 1; i &lt; size; ++i) { long sqr = i * i; pow5[i] = sqr * sqr * i; } for (int a = 1; a &lt; size; ++a) { for (int b = 1; b &lt;= a; ++b) { for (int c = 1; c &lt;= b; ++c) { int e = a + 1; for (int d = 1; d &lt;= c; ++d) { long sum = pow5[a] + pow5[b] + pow5[c] + pow5[d]; while(pow5[e] &lt; sum){ e++; } if (pow5[e] == sum) { System.out.println(a + "^5 + " + b + "^5 + " + c + "^5 + " + d + "^5 = " + e + "^5"); return; } } } } } </code></pre>
1
2016-09-13T00:26:34Z
[ "java", "python", "performance" ]
python code not working after copied from windows to linux
39,459,440
<p>I just wrote a small program in python, which is:</p> <pre><code>#!/usr/bin/env python print "hello" </code></pre> <p>It works in windows. And when I type this code in linux, it works, too.</p> <p>But when I copy the python file from windows to linux in my VBox, this code doesn't work, and an error appears which is:<br/> : no such file or directory<br/>Why does that happen? And what should I do to fix it?</p>
0
2016-09-12T22:00:46Z
39,459,708
<p>Perhaps you get an error because of different line endings on windows and linux? Windows uses "\r\n" and Linux just "\n". </p> <p>You could write script that would get rid of "\r" on linux, for example:</p> <p>EDIT: I have realized that carriage returns are seen only in binary mode. So script should do something like this</p> <pre><code>with open('myscript.py', 'rb') as file: data = file.read() data = data.replace(b'\r\n', b'\n') with open('myscript.py', 'wb') as file: file.write(data) </code></pre>
0
2016-09-12T22:28:32Z
[ "python", "linux", "windows" ]
Comparing nested list Python
39,459,456
<p>I guess the code will most easily explain what I'm going for...</p> <pre><code>list1 = [("1", "Item 1"), ("2", "Item 2"), ("3", "Item 3"), ("4", "Item 4")] list2 = [("1", "Item 1"), ("2", "Item 2"), ("4", "Item 4")] newlist = [] for i,j in list1: if i not in list2[0]: entry = (i,j) newlist.append(entry) print(newlist) </code></pre> <p>if we call the nested tuples [i][j]</p> <p>I want to compare the [i] but once this has been done I want to keep the corresponding [j] value. </p> <p>I have found lots of information regarding nested tuples on the internet but most refer to finding a specific item. </p> <p>I did recently use an expression below, which worked perfectly, this seems very similar, but it just won't play ball.</p> <pre><code>for i,j in highscores: print("\tPlayer:\t", j, "\tScore: ", i) </code></pre> <p>Any help would be much apppreciated. </p>
1
2016-09-12T22:02:30Z
39,459,658
<p>If I understand correctly from your comment you would like to take as newlist: </p> <pre><code>newlist = [("3", "Item 3")] </code></pre> <p>You can do this using:</p> <p>1) list comprehension:</p> <pre><code>newlist = [item for item in list1 if item not in list2] print newlist </code></pre> <p>This will give you as a result:</p> <pre><code>[('3', 'Item 3')] </code></pre> <p>2) You could also use <a href="https://python-reference.readthedocs.io/en/latest/docs/sets/symmetric_difference.html" rel="nofollow">symmetric difference</a> like:</p> <pre><code>L = set(list1).symmetric_difference(list2) newlist = list(L) print newlist </code></pre> <p>This will also give you the same result!</p> <p>3) Finally you can use a lambda function like:</p> <pre><code>unique = lambda l1, l2: set(l1).difference(l2) x = unique(list1, list2) newlist = list(x) </code></pre> <p>This will also produce the same result!</p> <p>4) Oh, and last but not least, using simple set properties:</p> <pre><code>newlist = list((set(list1)-set(list2))) </code></pre>
2
2016-09-12T22:23:17Z
[ "python", "list", "nested" ]
Comparing nested list Python
39,459,456
<p>I guess the code will most easily explain what I'm going for...</p> <pre><code>list1 = [("1", "Item 1"), ("2", "Item 2"), ("3", "Item 3"), ("4", "Item 4")] list2 = [("1", "Item 1"), ("2", "Item 2"), ("4", "Item 4")] newlist = [] for i,j in list1: if i not in list2[0]: entry = (i,j) newlist.append(entry) print(newlist) </code></pre> <p>if we call the nested tuples [i][j]</p> <p>I want to compare the [i] but once this has been done I want to keep the corresponding [j] value. </p> <p>I have found lots of information regarding nested tuples on the internet but most refer to finding a specific item. </p> <p>I did recently use an expression below, which worked perfectly, this seems very similar, but it just won't play ball.</p> <pre><code>for i,j in highscores: print("\tPlayer:\t", j, "\tScore: ", i) </code></pre> <p>Any help would be much apppreciated. </p>
1
2016-09-12T22:02:30Z
39,459,851
<p>I think you just want to create a set of the first elements of list2, if you're only looking to compare the first element of the lists.</p> <pre><code>newlist = [] list2_keys = set(elem[0] for elem in list2) for entry in list1: if entry[0] not in list2_keys: newlist.append(entry) </code></pre>
1
2016-09-12T22:46:25Z
[ "python", "list", "nested" ]
Create new shapely polygon by subtracting the intersection with another polygon
39,459,496
<p>I have two shapely MultiPolygon instances (made of lon,lat points) that intersect at various parts. I'm trying to loop through, determine if there's an intersection between two polygons, and then create a new polygon that excludes that intersection. From the attached image, I basically don't want the red circle to overlap with the yellow contour, I want the edge to be exactly where the yellow contour starts.</p> <p>I've tried following the instructions <a href="http://gis.stackexchange.com/questions/11987/polygon-overlay-with-shapely">here</a> but it doesn't change my output at all, plus I don't want to merge them into one cascading union. I'm not getting any error messages, but when I add these MultiPolygons to a KML file (just raw text manipulation in python, no fancy program) they're still showing up as circles without any modifications. </p> <pre><code># multipol1 and multipol2 are my shapely MultiPolygons from shapely.ops import cascaded_union from itertools import combinations from shapely.geometry import Polygon,MultiPolygon outmulti = [] for pol in multipoly1: for pol2 in multipoly2: if pol.intersects(pol2)==True: # If they intersect, create a new polygon that is # essentially pol minus the intersection intersection = pol.intersection(pol2) nonoverlap = pol.difference(intersection) outmulti.append(nonoverlap) else: # Otherwise, just keep the initial polygon as it is. outmulti.append(pol) finalpol = MultiPolygon(outmulti) </code></pre> <p><a href="http://i.stack.imgur.com/Z1NyF.png" rel="nofollow"><img src="http://i.stack.imgur.com/Z1NyF.png" alt="Polygon Overlap"></a></p>
0
2016-09-12T22:06:49Z
39,459,906
<p>I guess you can use the <a href="http://toblerity.org/shapely/manual.html#object.symmetric_difference" rel="nofollow"><code>symmetric_difference</code></a> between theses two polygons, combined by the difference with the second polygon to achieve what you want to do (the <em>symmetric difference</em> will brings you the non-overlapping parts from the two polygons, on which are removed parts of the polygon 2 by the <em>difference</em>). I haven't tested but it might look like :</p> <pre><code># multipol1 and multipol2 are my shapely MultiPolygons from shapely.ops import cascaded_union from itertools import combinations from shapely.geometry import Polygon,MultiPolygon outmulti = [] for pol in multipoly1: for pol2 in multipoly2: if pol.intersects(pol2)==True: # If they intersect, create a new polygon that is # essentially pol minus the intersection nonoverlap = (pol.symmetric_difference(pol2)).difference(pol2) outmulti.append(nonoverlap) else: # Otherwise, just keep the initial polygon as it is. outmulti.append(pol) finalpol = MultiPolygon(outmulti) </code></pre>
1
2016-09-12T22:54:36Z
[ "python", "python-2.7", "polygon", "shapely" ]
How to integrate a python program into a kivy app
39,459,530
<p>I'm working on an app written in python with the kivy modules to develop a cross-platform app. Within this app I have a form which takes some numerical values. I would like these numerical values to be passed to another python program I've written, used to calculate some other values, and passed back to the app and returned to the user. The outside program is currently not recognizing that the values I'm trying to pass to it exist. Below is sample code from the 3 files I'm using, 2 for the app and 1 for the outside program. I apologize about the abundance of seemingly unused kivy modules being imported, I use them all in the full app.</p> <p>main.py</p> <pre><code>import kivy import flowcalc from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.dropdown import DropDown from kivy.uix.spinner import Spinner from kivy.uix.button import Button from kivy.base import runTouchApp from kivy.uix.textinput import TextInput from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty, ListProperty from kivy.uix.gridlayout import GridLayout from kivy.uix.scrollview import ScrollView from kivy.core.window import Window from kivy.uix.slider import Slider from kivy.uix.scatter import Scatter from kivy.uix.image import AsyncImage from kivy.uix.carousel import Carousel Builder.load_file('main.kv') #Declare Screens class FormScreen(Screen): pass class ResultsScreen(Screen): pass #Create the screen manager sm = ScreenManager() sm.add_widget(FormScreen(name = 'form')) sm.add_widget(ResultsScreen(name = 'results')) class TestApp(App): def build(self): return sm if __name__ == '__main__': TestApp().run() </code></pre> <p>main.kv</p> <pre><code>&lt;FormScreen&gt;: BoxLayout: orientation: 'vertical' AsyncImage: source: 'sample.png' size_hint: 1, None height: 50 GridLayout: cols: 2 Label: text: 'Company Industry' Label: text: 'Sample' Label: text: 'Company Name' TextInput: id: companyname Label: text: 'Company Location' TextInput: id: companylocation Label: text: 'Data1' TextInput: id: data1 Label: text: 'Data2' TextInput: id: data2 Label: text: 'Data3' TextInput: id: data3 Button: text: 'Submit' size_hint: 1, .1 on_press: root.manager.current = 'results' &lt;ResultsScreen&gt;: BoxLayout: orientation: 'vertical' AsyncImage: source: 'sample.png' size_hint: 1, None height: 50 Label: text: 'Results' size_hint: 1, .1 GridLayout: cols: 2 Label: text: 'Results 1' Label: text: results1 Label: text: 'Results 2' Label: text: results2 Label: text: 'Results 3' Label: text: results3 Label: text: 'Results 4' Label: text: results4 </code></pre> <p>otherprogram.py</p> <pre><code>data1float = float(data1.text) data2float = float(data2.text) data3float = float(data3.text) results1 = data1float + data2float results2 = data1float - data3float results3 = data2float * data3float results4 = 10 * data2float </code></pre>
0
2016-09-12T22:10:13Z
39,461,951
<p>As far as I understood you want the labels in your GridLayout in the last section of your code to get their texts from your python code. You could do something like this:</p> <pre><code>from otherprogram import results1, results2, results3, results4 class ResultsScreen(Screen): label1_text = results1 label2_text = results2 label3_text = results3 label4_text = results4 </code></pre> <p>then in your .kv file you could access these values by calling their root widgets attribute.</p> <pre><code> Label: text: root.label1_text </code></pre> <p>and so on.</p>
2
2016-09-13T03:51:31Z
[ "android", "python", "kivy", "kivy-language" ]
Extracting column labels of the cells meeting a given condition
39,459,541
<p>Suppose the data at hand is in the following form:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A':[1,10,20], 'B':[4,40,50], 'C':[10,11,12]}) </code></pre> <p>I can compute the minimum by row with:</p> <pre><code>df.min(axis=1) </code></pre> <p>which returns <code>1 10 12</code>.</p> <p>Instead of the values, I would like to create a pandas Series containing the column labels of the corresponding cells.</p> <p>That is, I would like to get <code>A A C</code>.</p> <p>Thanks for any suggestions. </p>
3
2016-09-12T22:11:14Z
39,459,585
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmin.html" rel="nofollow">idxmin(axis=1)</a> method:</p> <pre><code>In [8]: df.min(axis=1) Out[8]: 0 1 1 10 2 12 dtype: int64 In [9]: df.idxmin(axis=1) Out[9]: 0 A 1 A 2 C dtype: object In [11]: df.idxmin(axis=1).values Out[11]: array(['A', 'A', 'C'], dtype=object) </code></pre>
3
2016-09-12T22:15:22Z
[ "python", "pandas", "dataframe" ]
Default instance for Django model
39,459,559
<p>My questionis: is there anyway to create a default instance for class Language? Like this : </p> <pre><code>class Language(models. default_instance = Language(name="unknown") name = models.CharField(max_length=100) </code></pre> <p>so class Student can use this: </p> <pre><code>class Student(models.Model): name = models.CharField(max_length=50) language = models.ForeignKey(Language, default = Language.default_instance.pk ) </code></pre> <p>Thank you!</p>
0
2016-09-12T22:13:16Z
39,460,234
<p>You could set it by overriding the save method:</p> <pre><code>#your model class Student(models.Model): name = models.CharField(max_length=50) language = models.ForeignKey(Language) # override save def save(self,**args,**kwargs): if self.language is None: default_language = Language.get(pk=1) #set to default self.language = default_language super(Student,self).save(self,*args,**kwargs) # the 'real' save </code></pre> <p>See <a href="https://docs.djangoproject.com/en/1.10/topics/db/models/#overriding-model-methods" rel="nofollow">here</a> about overriding the save method.</p>
2
2016-09-12T23:35:19Z
[ "python", "django", "django-models" ]
How to verify text using Squish
39,459,668
<p>I am automating a windows application using Squish. I am trying to verify if the required text is displayed in a window after I make some changes in the GUI. I used object spy to get the object ID, but I am confused how to give a test verification point. The following Verification point says in the results window as 'True' and 'True' are equal. But I want it to be as, for example 4X and 4X are equal.</p> <pre><code>test.compare(findObject("{name ='textObjective'}").enabled, True) </code></pre> <p>Thank You!!</p>
0
2016-09-12T22:24:34Z
39,567,937
<p>Instead of the <code>enabled</code> property, you can also compare any other property - e.g. the <code>text</code>:</p> <pre><code>test.compare(findObject("{name ='textObjective'}").text, "4X") </code></pre>
0
2016-09-19T07:50:08Z
[ "python", "squish" ]
Sorting a Two Dimensional List in python using Insertion Sort
39,459,677
<p>So I want to sort a list of namedtuples using insertion sort in python, and here is my code.</p> <pre><code> def sortIt(tripods): for i in range(1, len(tripods)): tmp = tripods[i][3] k = i while k &gt; 0 and tmp &lt; tripods[k - 1][3]: tripods[k] = tripods[k - 1] k -= 1 tripods[k] = tmp </code></pre> <p>Whenever it runs it gives me a TypeError: int object is not suscriptable. Tripods is a list of namedTuples and the index 3 of the namedTuple is what I want the list to be ordered by. </p>
-1
2016-09-12T22:25:10Z
39,461,599
<pre><code>def sortIt(tripods): for i in range(1, len(tripods)): tmp = tripods[i] k = i while k &gt; 0 and tmp[3] &lt; tripods[k - 1][3]: tripods[k] = tripods[k - 1] k -= 1 tripods[k] = tmp </code></pre> <p>I have modified your code. You were assigning <code>tripods[i][3]</code> to tmp, which is a <code>int</code>. That's why the compiler warns you <code>int</code> is not suscriptable.</p>
0
2016-09-13T02:59:13Z
[ "python", "list", "sorting" ]
Space complexity of list creation
39,459,701
<p>Could someone explain me what is the space complexity of beyond program, and why is it?</p> <pre><code>def is_pal_per(str): s = [i for i in str] nums = [0] * 129 for i in s: nums[ord(i)] += 1 count = 0 for i in nums: if i != 0 and i / 2 == 0: count += 1 print count if count &gt; 1: return False else: return True </code></pre> <p>Actually, i'm interested in this lines of code. How does it influence on space complexity of above program?</p> <pre><code>s = [i for i in str] </code></pre> <p><code>nums = [0] * 129</code></p>
1
2016-09-12T22:27:13Z
39,459,729
<p>You have found the only two lines that allocate memory:</p> <pre><code>s = [i for i in str] nums = [0] * 129 </code></pre> <p>The first grows linearly with <code>len(str)</code>, the second is a constant. Therefore, the space complexity of your function is O(N), N=length of <code>str</code>.</p>
0
2016-09-12T22:30:57Z
[ "python", "algorithm", "python-2.7", "space-complexity" ]
Space complexity of list creation
39,459,701
<p>Could someone explain me what is the space complexity of beyond program, and why is it?</p> <pre><code>def is_pal_per(str): s = [i for i in str] nums = [0] * 129 for i in s: nums[ord(i)] += 1 count = 0 for i in nums: if i != 0 and i / 2 == 0: count += 1 print count if count &gt; 1: return False else: return True </code></pre> <p>Actually, i'm interested in this lines of code. How does it influence on space complexity of above program?</p> <pre><code>s = [i for i in str] </code></pre> <p><code>nums = [0] * 129</code></p>
1
2016-09-12T22:27:13Z
39,459,730
<p>I'm unclear where you're having trouble with this. <strong>s</strong> is simply a list of individual characters in <strong>str</strong>. The space consumption is <strong>len(s)</strong>.</p> <p><strong>nums</strong> is a constant size, dominated by the <strong>O(N)</strong> term.</p> <p>Is this code you wrote, or has this been handed to you? The programming style is highly <em>not</em> "Pythonic".</p> <hr> <p>As for your code, start with this collapse:</p> <pre><code>count = 0 for char in str: val = ord[char] + 1 if abs(val) == 1: count += 1 print count return count == 0 </code></pre> <p>First, I replaced your single-letter variables (<strong>s</strong> => <strong>char</strong>; <strong>i</strong> => <strong>val</strong>). Then I cut out <em>most</em> of the intermediate steps, leaving in a couple to help you read the code. Finally, I used a straightforward Boolean value to return, rather than the convoluted statement of the original.</p> <p>I did <em>not</em> use Python's counting methods -- that would shorten the function even more. By the way, do you <em>have</em> to print the count of unity values, or do you just need the Boolean return? If it's just the return value, you can make this even shorter.</p>
0
2016-09-12T22:31:04Z
[ "python", "algorithm", "python-2.7", "space-complexity" ]
Paths in python
39,459,716
<p>Consider a rectangular grid.</p> <p>I want a short and elegant way of generating a straight path from <code>[x0,y0]</code> to <code>[x1,y1]</code>, where either <code>x0=x1</code> or <code>y0 = y1</code>.</p> <p>For example, on input <code>[1,3], [3,3]</code> the output <code>[[1,3],[2,3],[3,3]</code> should be generated. Likewise if the input is <code>[3,3], [1,3]</code>.</p> <p>I have tried <code>[[i,j] for i in range(self.origin[0],self.end[0]+1) for j in range(self.origin[1], self.end[1]+1)]</code>, but it only works for the case where the input is ordered.</p>
0
2016-09-12T22:29:29Z
39,459,785
<p>Add the <strong>step</strong> argument to your range, deriving the sign of the start &amp; end difference:</p> <pre><code>x_dir = copysign(1, self.end[0] - self.origin[0]) ... for i in range(self.origin[0], self.end[0]+1, x_dir) ... </code></pre> <p>Do likewise for the y direction.</p>
1
2016-09-12T22:37:37Z
[ "python", "python-3.x" ]
Paths in python
39,459,716
<p>Consider a rectangular grid.</p> <p>I want a short and elegant way of generating a straight path from <code>[x0,y0]</code> to <code>[x1,y1]</code>, where either <code>x0=x1</code> or <code>y0 = y1</code>.</p> <p>For example, on input <code>[1,3], [3,3]</code> the output <code>[[1,3],[2,3],[3,3]</code> should be generated. Likewise if the input is <code>[3,3], [1,3]</code>.</p> <p>I have tried <code>[[i,j] for i in range(self.origin[0],self.end[0]+1) for j in range(self.origin[1], self.end[1]+1)]</code>, but it only works for the case where the input is ordered.</p>
0
2016-09-12T22:29:29Z
39,459,850
<p>Your question states that the solution from <code>x -&gt; y</code> should be the same as the solution <code>y -&gt; x</code>, i.e. we're only interested in defining the points on the path, not in any ordering of those points. If that's true, then simply find out which path has the smaller <code>x</code> (or <code>y</code>) and designate that as the origin.</p> <pre><code>origin = (3,3) dest = (1,3) origin, dest = sorted([origin, dest]) path = {(i,j) for i in range(origin[0], dest[0]+1) for j in range(origin[1], dest[1]+1)} # note that this is now a set comprehension, since it doesn't make any sense # to use a list of unique hashable items whose order is irrelevant </code></pre> <p>of course, this solves any obstructionless 2-D pathfinding. If you know that only one direction is changing, then only look in that direction.</p> <pre><code>origin, dest = sorted((origin, dest)) if origin[0] == dest[0]: # y is changing path = {(origin[0], j) for j in range(origin[1], dest[1]+1)} else: # x is changing path = {(i, origin[1]) for i in range(origin[0], dest[0]+1)} </code></pre>
3
2016-09-12T22:46:18Z
[ "python", "python-3.x" ]
Non decreasing sequences
39,459,775
<p>I am trying to write a simple python script that will find all the non-decreasing sequences made up of positive integers summing to 7. My code does not seem to work as it's supposed to no matter what I try. Here's what I have</p> <pre><code>components = [1,2,3,4,5,6,7] ans = [] def sumSeq(seq): sumA = 0 for i in seq: sumA += i return sumA def findSeq(seq): for x in components: if (x &lt; seq[-1]): continue newSeq = seq newSeq.append(x) sumA = sumSeq(newSeq) if (sumA &gt; 7): continue if (sumA == 7): ans.append(newSeq) findSeq(newSeq) findSeq([0]) print ans </code></pre>
0
2016-09-12T22:36:58Z
39,459,796
<pre><code>newSeq = seq </code></pre> <p>This line doesn't do what you think it does. Specifically, it does <em>not</em> create a new list. It merely creates a new name that refers to the existing list. Try:</p> <pre><code>newSeq = seq[:] </code></pre>
2
2016-09-12T22:38:52Z
[ "python", "sequence" ]
Non decreasing sequences
39,459,775
<p>I am trying to write a simple python script that will find all the non-decreasing sequences made up of positive integers summing to 7. My code does not seem to work as it's supposed to no matter what I try. Here's what I have</p> <pre><code>components = [1,2,3,4,5,6,7] ans = [] def sumSeq(seq): sumA = 0 for i in seq: sumA += i return sumA def findSeq(seq): for x in components: if (x &lt; seq[-1]): continue newSeq = seq newSeq.append(x) sumA = sumSeq(newSeq) if (sumA &gt; 7): continue if (sumA == 7): ans.append(newSeq) findSeq(newSeq) findSeq([0]) print ans </code></pre>
0
2016-09-12T22:36:58Z
39,459,864
<p>When you do the following assignment:</p> <pre><code>newSeq = seq </code></pre> <p>you actually bind a different name (newSeq) to the same object (seq), you do not create a new object with similar values. So as you change the contents of newSeq, you change the contents of seq, too, since they are both aliases of the same object stored in memory. As the Python documentation says:</p> <blockquote> <p>Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.</p> </blockquote> <p>So you have to change this line of code with:</p> <pre><code>newSeq = seq.copy() </code></pre>
2
2016-09-12T22:48:12Z
[ "python", "sequence" ]
Python: how to instal "requests"
39,459,799
<p>I have Python version 3.5.2. I am trying to use <code>requests</code> called through <code>import requests</code> but I get the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#26&gt;", line 1, in &lt;module&gt; import requests ImportError: No module named 'requests' </code></pre> <p>Reading some guides, I can see that I have to instal the module because it is not present in the system.</p> <p>So I downloaded the file but now I don't know what to do. I have read that I should instal it on the Terminal (I have a Mac). But I have never used the Terminal: what code should I used?</p>
-3
2016-09-12T22:39:13Z
39,460,030
<p>First check what version of python your shell will be running; sometimes the Python 3 executable is installed as <code>python3</code> in <code>/usr/bin</code> (or wherever else it could be installed; ie. <code>/usr/local/bin)</code>, but I've seen it as just plain <code>python</code> on some machines depending on how it was installed.</p> <pre><code>python --version </code></pre> <p>If you see <code>Python 3.5.2</code>; then run:</p> <pre><code>python -m pip install requests </code></pre> <p>If not; then try doing the same but with <code>python3</code> instead of <code>python</code>.</p>
1
2016-09-12T23:09:19Z
[ "python", "terminal", "python-requests" ]
How can I get all media from my own Instagram api?
39,459,809
<p>I want to get number of likes each photo or video got. Can I get all the media like count or just the last 20 of them?</p>
3
2016-09-12T22:40:39Z
39,459,924
<p>If you get your API access reviewed and approved by Instagram you will be able to get more than 20 photos using pagination.</p> <p>Check documentation here: <a href="https://www.instagram.com/developer/sandbox/" rel="nofollow">https://www.instagram.com/developer/sandbox/</a></p>
1
2016-09-12T22:57:07Z
[ "python", "instagram-api" ]
Django: 400 Error with Debug=False and ALLOWED_HOSTS=["*"]
39,459,819
<p>I'm trying to run a relatively simple Django server on python 3.5.3 on an Ubuntu DigitalOcean droplet. I'm using a Gunicorn server with nginx. The server runs fine when DEBUG=True in settings.py. But when I set it to False, I get a 400 error when trying to visit the page. I tried setting ALLOWED_HOSTS to ['*'], but I still get the same error. I've looked on a lot of forums and many questions on SO but none of the solutions have worked.</p> <p>EDIT: Gunicorn logs, from startup</p> <pre><code>[2016-09-13 00:02:01 +0000] [27160] [DEBUG] Current configuration: nworkers_changed: &lt;function NumWorkersChanged.nworkers_changed at 0x7f9ac58d3d90&gt; worker_class: sync pre_fork: &lt;function Prefork.pre_fork at 0x7f9ac58c8f28&gt; limit_request_fields: 100 statsd_host: None limit_request_field_size: 8190 default_proc_name: KivaWebsite.wsgi capture_output: False raw_env: [] pidfile: None pythonpath: None when_ready: &lt;function WhenReady.when_ready at 0x7f9ac58c8d90&gt; post_worker_init: &lt;function PostWorkerInit.post_worker_init at 0x7f9ac58d32f0&gt; pre_exec: &lt;function PreExec.pre_exec at 0x7f9ac58d37b8&gt; ca_certs: None syslog_prefix: None django_settings: None sendfile: None group: 0 limit_request_line: 4094 on_starting: &lt;function OnStarting.on_starting at 0x7f9ac58c8a60&gt; accesslog: None statsd_prefix: threads: 1 max_requests_jitter: 0 graceful_timeout: 30 cert_reqs: 0 proc_name: None spew: False loglevel: DEBUG pre_request: &lt;function PreRequest.pre_request at 0x7f9ac58d3950&gt; timeout: 30 worker_tmp_dir: None on_exit: &lt;function OnExit.on_exit at 0x7f9ac58d3f28&gt; tmp_upload_dir: None max_requests: 0 keepalive: 2 preload_app: False logger_class: gunicorn.glogging.Logger syslog_facility: user forwarded_allow_ips: ['127.0.0.1'] post_request: &lt;function PostRequest.post_request at 0x7f9ac58d3a60&gt; certfile: None bind: ['unix:/home/thomas/KivaWebsite/KivaWebsite.sock'] ssl_version: 3 access_log_format: %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" errorlog: logs2.log logconfig: None umask: 0 proxy_allow_ips: ['127.0.0.1'] reload: False check_config: False workers: 1 worker_connections: 1000 syslog_addr: udp://localhost:514 chdir: /home/thomas/KivaWebsite paste: None keyfile: None on_reload: &lt;function OnReload.on_reload at 0x7f9ac58c8bf8&gt; post_fork: &lt;function Postfork.post_fork at 0x7f9ac58d3158&gt; worker_int: &lt;function WorkerInt.worker_int at 0x7f9ac58d3488&gt; backlog: 2048 syslog: False worker_abort: &lt;function WorkerAbort.worker_abort at 0x7f9ac58d3620&gt; worker_exit: &lt;function WorkerExit.worker_exit at 0x7f9ac58d3bf8&gt; daemon: False user: 0 proxy_protocol: False config: None secure_scheme_headers: {'X-FORWARDED-SSL': 'on', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-PROTOCOL': 'ssl'} suppress_ragged_eofs: True do_handshake_on_connect: False ciphers: TLSv1 enable_stdio_inheritance: False [2016-09-13 00:02:01 +0000] [27160] [INFO] Starting gunicorn 19.6.0 [2016-09-13 00:02:01 +0000] [27160] [DEBUG] Arbiter booted [2016-09-13 00:02:01 +0000] [27160] [INFO] Listening at: unix:/home/thomas/KivaWebsite/KivaWebsite.sock (27160) [2016-09-13 00:02:01 +0000] [27160] [INFO] Using worker: sync [2016-09-13 00:02:01 +0000] [27163] [INFO] Booting worker with pid: 27163 [2016-09-13 00:02:01 +0000] [27160] [DEBUG] 1 workers [2016-09-13 00:02:25 +0000] [27163] [DEBUG] GET / </code></pre> <p>EDIT: Nginx logs show an error:</p> <pre><code>request: "GET / HTTP/1.1", upstream: "http://unix:/home/thomas/KivaWebsite/KivaWebsite.sock:/", host: "104.131.153.181" 2016/09/12 12:06:47 [crit] 22081#22081: *96 connect() to unix:/home/thomas/KivaWebsite/KivaWebsite.sock failed (2: No such file or directory) </code></pre> <p>However, I have checked and the file definitely exists. This is my nginx config file:</p> <pre><code>server { listen 80; server_name 104.131.153.181; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/thomas/KivaWebsite; } location / { include proxy_params; proxy_set_header Host $host; proxy_pass http://unix:/home/thomas/KivaWebsite/KivaWebsite.sock; } } </code></pre> <p>Is there anything wrong with it?</p>
3
2016-09-12T22:42:24Z
39,461,321
<p>Make sure that the config in nginx has the proper alias using absolute paths (ie: <code>/etc/nginx/sites-enabled</code>) It doesn't work if the alias was done with a relative path for whatever reason. </p> <p>This are the appropriate settings for nginx at the <code>location / {}</code> section:</p> <pre><code>proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; include uwsgi_params; proxy_pass http://unix:/home/thomas/KivaWebsite/KivaWebsite.sock; </code></pre>
1
2016-09-13T02:18:46Z
[ "python", "django", "nginx", "gunicorn", "digital-ocean" ]
beautifulsoup could not find class
39,459,947
<p>I tried to use bs4 to get the table from one NBA stat site.</p> <p>The website seems did not use the JavaScript.</p> <p>The <code>soup.prettify</code> print result looks normal, but I could not use <code>soup.find_all</code> to get the table I want. Here's the code I'm using:</p> <pre><code>import requests from bs4 import BeautifulSoup url = 'http://stats.nba.com/team/#!/1610612738/stats/' page = requests.get(url) html = page.content soup = BeautifulSoup(html, 'html.parser') tables = soup.find_all('table') </code></pre>
3
2016-09-12T23:00:27Z
39,460,304
<p>The website loads data with <a href="https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started" rel="nofollow">ajax</a>, and this data will not be available to you simply by getting page contents with BeautifulSoup. However, you probably don't need BeautifulSoup at all.</p> <p>If you're using Chrome, visit the website and go to your browser's dev tools, click on the network tab, click the XHR filter, then reload the page. You'll see a list of requests that were made: </p> <p><a href="http://i.stack.imgur.com/WHIUz.png" rel="nofollow"><img src="http://i.stack.imgur.com/WHIUz.png" alt="enter image description here"></a></p> <p>Click on those and see which ones you're interested in. Once you find the one you like, copy the url, and get the data with the requests library (you already included this in your code):</p> <pre><code>r = requests.get('http://stats.nba.com/stats/commonallplayers?IsOnlyCurrentSeason=0&amp;LeagueID=00&amp;Season=2016-17') data = r.json() </code></pre>
3
2016-09-12T23:46:51Z
[ "python", "python-3.x", "web-scraping", "beautifulsoup" ]
How can I fix my function?
39,460,031
<p>I am being told.. from comments to fix my function to make it look "cleaner". I've tried alot.. but i don't know how to use llambda to accomplish what I'm trying to do. My code works.. it just isn't what is being asked of me. </p> <p>Here is my code with suggestions on how to fix it.</p> <pre><code>def immutable_fibonacci(position): #define a lambda instead of def here def compute_fib (previousSeries, ignore): newList = previousSeries if len(newList) &lt; 2: # Do this outside and keep this function focused only on returning a new list with last element being sum of previous two elements newList.append(1) else: first = newList[-1] second = newList[-2] newList.append(first+second) return newList range=[None]*position return reduce(compute_fib, range, []) #Above is too much code. How about something like this: #next_series = lambda series,_ : (Use these instead of the above line) #return reduce(next_series, range(position - 2), [1, 1]) </code></pre> <p>Anything helps.. I am just confused on how I can implement these suggestions. </p> <p>Here is what I attempted.</p> <pre><code>def immutable_fibonacci(position): range=[None]*position next_series = lambda series, _ : series.append(series[-1] + series[-2]) return reduce(next_series, range(position - 2), [1, 1]) </code></pre>
-1
2016-09-12T23:09:29Z
39,460,412
<p>The <code>append</code> function returns None. You need to return a renewed array</p> <pre><code>next_series = lambda series: series + [series[-1] + series[-2]] </code></pre> <p>Also renaming <code>range</code> isn't serving any purpose.</p> <pre><code>def immutable_fibonacci(position): next_series = lambda series: series + [series[-1] + series[-2]] return reduce(next_series, range(position - 2), [1, 1]) </code></pre> <p>This is assuming you only call the function for positions >= 2. Conventionally fib(0) is 0 and fib(1) is 1.</p>
0
2016-09-13T00:02:06Z
[ "python", "function" ]
I have been learning python 3.5, and trying to get a string to reprint a user input variable?
39,460,040
<pre><code>print ("how old are you??"), age = input() print("How tall are you"), height = input() print("How much do you weigh"), weight = input() print("So, you're '%r' old, '%r' tall and weigh '%r' ") % ('age, height weight') </code></pre> <p>TypeError: unsupported operand type(s) for %: 'NoneType' and 'str</p>
1
2016-09-12T23:10:17Z
39,460,068
<p>Don't put your variables in quotes. Instead of </p> <pre><code>print("So, you're '%r' old, '%r' tall and weigh '%r' ") % ('age, height weight') </code></pre> <p>put</p> <pre><code>print("So, you're '%r' old, '%r' tall and weigh '%r' " % (age, height weight)) </code></pre>
2
2016-09-12T23:14:38Z
[ "python", "string", "user-input" ]
I have been learning python 3.5, and trying to get a string to reprint a user input variable?
39,460,040
<pre><code>print ("how old are you??"), age = input() print("How tall are you"), height = input() print("How much do you weigh"), weight = input() print("So, you're '%r' old, '%r' tall and weigh '%r' ") % ('age, height weight') </code></pre> <p>TypeError: unsupported operand type(s) for %: 'NoneType' and 'str</p>
1
2016-09-12T23:10:17Z
39,460,181
<p>As a bit of a fellow noob. A simple way of achieving this is asking your question while assigning the variable </p> <pre><code>age = input("how old are you??") height = input("How tall are you") weight = input("How much do you weigh") print("So, you're", age, "years old", height, "tall and weigh", weight) </code></pre>
0
2016-09-12T23:30:07Z
[ "python", "string", "user-input" ]
I have been learning python 3.5, and trying to get a string to reprint a user input variable?
39,460,040
<pre><code>print ("how old are you??"), age = input() print("How tall are you"), height = input() print("How much do you weigh"), weight = input() print("So, you're '%r' old, '%r' tall and weigh '%r' ") % ('age, height weight') </code></pre> <p>TypeError: unsupported operand type(s) for %: 'NoneType' and 'str</p>
1
2016-09-12T23:10:17Z
39,460,217
<pre><code>print ("how old are you??"), age = input() print("How tall are you"), height = input() print("How much do you weigh"), weight = input() print("So, you're '%r' old, '%r' tall and weigh '%r' " %(age, height, weight)) </code></pre> <p>If you put the variables in quotes it becomes a string. Also make sure each variable has a comma after it if you're going to add another variable.</p>
0
2016-09-12T23:33:22Z
[ "python", "string", "user-input" ]
Accessing the choices passed to argument in argparser?
39,460,102
<p>Is it possible to access the tuple of choices passed to an argument? If so, how do I go about it</p> <p>for example if I have </p> <pre><code>parser = argparse.ArgumentParser(description='choose location') parser.add_argument( "--location", choices=('here', 'there', 'anywhere') ) args = parser.parse_args() </code></pre> <p>can I access the tuple <code>('here', 'there', 'anywhere')</code>?</p>
7
2016-09-12T23:19:12Z
39,460,230
<p>It turns out that <code>parser.add_argument</code> actually returns the associated <code>Action</code>. You can pick the choices off of that:</p> <pre><code>&gt;&gt;&gt; import argparse &gt;&gt;&gt; parser = argparse.ArgumentParser(description='choose location') &gt;&gt;&gt; action = parser.add_argument( ... "--location", ... choices=('here', 'there', 'anywhere') ... ) &gt;&gt;&gt; action.choices ('here', 'there', 'anywhere') </code></pre> <p>Note that (AFAIK) this isn't documented anywhere and <em>may</em> be considered an "implementation detail" and therefore subject to change without notice, etc. etc.</p> <p>There also isn't any <em>publicly</em> accessible way to get at the actions stored on an <code>ArgumentParser</code> after they've been added. I believe that they are available as <code>parser._actions</code> if you're willing to go mucking about with implementation details (and assume any risks involved with that)...</p> <hr> <p>Your best bet is to probably create a constant for the location choices and then use that in your code:</p> <pre><code>LOCATION_CHOICES = ('here', 'there', 'anywhere') parser = argparse.ArgumentParser(description='choose location') parser.add_argument( "--location", choices=LOCATION_CHOICES ) args = parser.parse_args() # Use LOCATION_CHOICES down here... </code></pre>
7
2016-09-12T23:35:10Z
[ "python", "argparse" ]
Accessing the choices passed to argument in argparser?
39,460,102
<p>Is it possible to access the tuple of choices passed to an argument? If so, how do I go about it</p> <p>for example if I have </p> <pre><code>parser = argparse.ArgumentParser(description='choose location') parser.add_argument( "--location", choices=('here', 'there', 'anywhere') ) args = parser.parse_args() </code></pre> <p>can I access the tuple <code>('here', 'there', 'anywhere')</code>?</p>
7
2016-09-12T23:19:12Z
39,460,237
<p>There might be a better way, but I don't see any in the documentation. If you know the parser option you should be able to do:</p> <pre><code>parser = argparse.ArgumentParser() parser.add_argument("--location", choices=("here", "there", "everywhere")) storeaction = next(a for a in parser._actions if "--location" in a.option_strings) storeaction.choices # ('here', 'there', 'everywhere') </code></pre> <p>As in mgilson's answer, accessing the <code>_actions</code> attribute is undocumented and the underscored prefix means "Hey, you probably shouldn't be messing with me." Don't be surprised if this breaks between versions of Python.</p>
2
2016-09-12T23:35:50Z
[ "python", "argparse" ]
Accessing the choices passed to argument in argparser?
39,460,102
<p>Is it possible to access the tuple of choices passed to an argument? If so, how do I go about it</p> <p>for example if I have </p> <pre><code>parser = argparse.ArgumentParser(description='choose location') parser.add_argument( "--location", choices=('here', 'there', 'anywhere') ) args = parser.parse_args() </code></pre> <p>can I access the tuple <code>('here', 'there', 'anywhere')</code>?</p>
7
2016-09-12T23:19:12Z
39,460,941
<p>On the question of what <code>add_argument</code> returns, if you do any testing in an interactive session like <code>ipython</code>, the return stares you in the face:</p> <pre><code>In [73]: import argparse In [74]: parser=argparse.ArgumentParser() In [75]: parser.add_argument('foo',choices=['one','two','three']) Out[75]: _StoreAction(option_strings=[], dest='foo', nargs=None, const=None, default=None, type=None, choices=['one', 'two', 'three'], help=None, metavar=None) In [76]: _.choices Out[76]: ['one', 'two', 'three'] </code></pre> <p>Note that other methods like <code>add_argument_group</code>, <code>add_subparsers</code>, <code>add_parser</code>, <code>add_mutually_exclusive_group</code> all return objects that can be used. The fact that <code>add_argument</code> is not documented as returning an object is, I think, a documentation oversight. Usually users don't need to use it, but as a semi-developer I use it all the time. The documentation for <code>argparse</code> is not a formal specification of what the module can or can not do; it is more of an instruction manual, a step up from a tutorial, but clearly not a reference.</p> <p>The use of <code>parser._actions</code> is handy, but a step deeper into the guts. I have followed nearly all the bug/issues and can't think of any that would trigger a change in this. There's a big backlog of potential changes, but developers have been reduced to near-immobility over fears of creating backward compatibility issues. It is easier to change the documentation than to change the functionality of <code>argparse</code>.</p>
1
2016-09-13T01:25:50Z
[ "python", "argparse" ]
Python 3.x - How to get the directory where user installed package
39,460,193
<p>Suppose that I am building a Python package with the following folder tree:</p> <pre><code>main |-- setup.py |-- the_package |--globar_vars.py |--the_main_script.py </code></pre> <p>When the user performs anyway to install it, like:</p> <pre><code>sudo python setup.py install python setup.py install --user python setup.py install --prefix=/usr/local </code></pre> <p>Or well, using PIP:</p> <pre><code>pip install 'SomeProject' </code></pre> <p>I want that the folder where the package was installed be saved on the <code>global_vars.py</code>, in any variable, Eg:</p> <pre><code>globarl_vars.py #!/usr/bin/env python3 user_installed_pkg = '/some/path/where/the/package/was/installed' </code></pre> <p>There is someway to get it? Thanks in advance.</p>
2
2016-09-12T23:30:55Z
39,460,684
<pre><code>import wtv_module print(wtv_module.__file__) import os print(os.path.dirname(wtv_module.__file__)) </code></pre>
0
2016-09-13T00:48:24Z
[ "python", "installation", "packages" ]
Python 3.x - How to get the directory where user installed package
39,460,193
<p>Suppose that I am building a Python package with the following folder tree:</p> <pre><code>main |-- setup.py |-- the_package |--globar_vars.py |--the_main_script.py </code></pre> <p>When the user performs anyway to install it, like:</p> <pre><code>sudo python setup.py install python setup.py install --user python setup.py install --prefix=/usr/local </code></pre> <p>Or well, using PIP:</p> <pre><code>pip install 'SomeProject' </code></pre> <p>I want that the folder where the package was installed be saved on the <code>global_vars.py</code>, in any variable, Eg:</p> <pre><code>globarl_vars.py #!/usr/bin/env python3 user_installed_pkg = '/some/path/where/the/package/was/installed' </code></pre> <p>There is someway to get it? Thanks in advance.</p>
2
2016-09-12T23:30:55Z
39,460,715
<p>Assuming your <code>SomeProject</code> package is a <a href="https://packaging.python.org/distributing/" rel="nofollow">well-formed Python package</a> (which can be done using <a href="https://setuptools.readthedocs.io/en/latest/setuptools.html" rel="nofollow">setuptools</a>), a user can derive the location simply use the <a href="https://setuptools.readthedocs.io/en/latest/pkg_resources.html" rel="nofollow"><code>pkg_resources</code></a> module provided by <code>setuptools</code> package to get this information. For example:</p> <pre><code>&gt;&gt;&gt; from pkg_resources import working_set &gt;&gt;&gt; from pkg_resources import Requirement &gt;&gt;&gt; working_set.find(Requirement.parse('requests')) requests 2.2.1 (/usr/lib/python3/dist-packages) &gt;&gt;&gt; working_set.find(Requirement.parse('requests')).location '/usr/lib/python3/dist-packages' </code></pre> <p>However, the path returned could be something inside an egg which means it will not be a path directly usable through standard filesystem tools. You generally want to use the <a href="https://setuptools.readthedocs.io/en/latest/pkg_resources.html#resourcemanager-api" rel="nofollow">Resource manager API</a> to access resources in those cases.</p> <pre><code>&gt;&gt;&gt; import pkg_resources &gt;&gt;&gt; api_src = pkg_resources.resource_string('requests', 'api.py') &gt;&gt;&gt; api_src[:25] b'# -*- coding: utf-8 -*-\n\n' </code></pre>
1
2016-09-13T00:52:07Z
[ "python", "installation", "packages" ]
Python datetime difference between .localize and tzinfo
39,460,236
<p>Why do these two lines produce different results? </p> <pre><code>&gt;&gt;&gt; import pytz &gt;&gt;&gt; from datetime ipmort datetime &gt;&gt;&gt; local_tz = pytz.timezone("America/Los_Angeles") &gt;&gt;&gt; d1 = local_tz.localize(datetime(2015, 8, 1, 0, 0, 0, 0)) # line 1 &gt;&gt;&gt; d2 = datetime(2015, 8, 1, 0, 0, 0, 0, local_tz) # line 2 &gt;&gt;&gt; d1 == d2 False </code></pre> <p>What's the reason for the difference, and which should I use to localize a datetime?</p>
4
2016-09-12T23:35:36Z
39,460,268
<p>When you create <code>d2=datetime(2015, 8, 1, 0, 0, 0, 0, local_tz)</code> in this way. It does not handle daylight savings time correctly. But, <code>local_tz.localize()</code> does.</p> <p>d1 is </p> <pre><code>datetime.datetime(2015, 8, 1, 0, 0, tzinfo=&lt;DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST&gt;) </code></pre> <p>d2 is</p> <pre><code>datetime.datetime(2015, 8, 1, 0, 0, tzinfo=&lt;DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD&gt;) </code></pre> <p>You can see that they are not representing the same time.</p> <p><code>d2</code> way it's fine if you are gonna work with UTC. Because UTC does not have daylight savings time transitions to deal with. </p> <p>So, the correct way to handle timezone, it's using <code>local_tz.localize()</code></p>
5
2016-09-12T23:40:42Z
[ "python", "datetime", "timezone", "pytz" ]
How to resize a Splash Screen Image using Tkinter?
39,460,247
<p>I am working on a game for a school project and as a part of it a Splash Screen is to load to simulate the 'loading' of the game. I have the code and it does bring up the image, but what I want it to do is bring up the defined .gif file onto the screen. Here is the code:</p> <pre><code>import tkinter as tk root = tk.Tk() root.overrideredirect(True) width = root.winfo_screenwidth() height = root.winfo_screenheight() root.geometry('%dx%d+%d+%d' % (width*1, height*1, width*0, height*0)) image_file = "example.gif" image = tk.PhotoImage(file=image_file) canvas = tk.Canvas(root, height=height*1, width=width*1, bg="darkgrey") canvas.create_image(width*1/2, height*1/2, image=image) canvas.pack() root.after(5000, root.destroy) root.mainloop() </code></pre> <p>My only issue is that because the image is larger than the screen it does not fit as a whole image. How can I resize the image using this code so that any .gif image fits on the screen?</p> <p>P.S. Please do not make any real drastic changes to the code as this does what I want, value changes are ok.</p>
0
2016-09-12T23:38:18Z
39,460,974
<p>I recommend you to use <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>.<br> Here is the code: </p> <pre><code>from PIL import Image, ImageTk import Tkinter as tk root = tk.Tk() root.overrideredirect(True) width = root.winfo_screenwidth() height = root.winfo_screenheight() root.geometry('%dx%d+%d+%d' % (width*1, height*1, width*0, height*0)) image = Image.open(image_path) image = image.resize((width, height), Image.ANTIALIAS) image = ImageTk.PhotoImage(image) canvas = tk.Canvas(root, height=height*1, width=width*1, bg="darkgrey") canvas.create_image(width*1/2, height*1/2, image=image) canvas.pack() root.after(5000, root.destroy) root.mainloop() </code></pre> <p>You get the width and height from:</p> <pre><code>width = root.winfo_screenwidth() height = root.winfo_screenheight() </code></pre> <p>then call <strong>resize()</strong></p> <p>If you still want to use PhotoImage, you can try <strong>zoom(x, y)</strong> and <strong>subsample(x, y)</strong>. Here is the <a href="http://epydoc.sourceforge.net/stdlib/Tkinter.PhotoImage-class.html" rel="nofollow">doc</a>. By the way, It's not work on my computer...(python2.7 + win7)</p>
0
2016-09-13T01:29:46Z
[ "python", "canvas", "tkinter", "tkinter-canvas" ]
Find generic sub-lists within a list
39,460,277
<p>Just learning Python as my first coding language. Given a list with many possible sub-lists which have a variable number of elements, is there a way of using regex (or something similar) to identify which lists contain sub-lists with 1) the number of elements specified and 2) a given type of content in a certain order (including other sub-lists)? For example (in pseudocode):</p> <pre><code>list1 = [1, 4, 7, ["a", 5, "b"], 2, 4,7,"k",9] list2 = [1, 4, 7, ["a", "h", "b"], 2] list3 = [1, 4, 7, ["a", ["a", 6, "b"], "b"], 5, 3] list4 = [1, 4, 7, ["a", "b"], 3, 4] list5 = [1, 4, 7, ["a", 5, "b", 7], 3, 4] if ["a", ., "b"] in listx: # where "." stands for anything, even sub-lists print("yes") else: print("no") </code></pre> <p>list1, list2, and list3 should print "yes", but list4 and list5 should print "no".</p> <p>As a bonus, is there a way to return 1) the number of times that the specified generic sub-list is found and 2) where? For example, have list3 return "There are 2 ["a", ., "b"] sub-lists, which are list3[3] and list3[3][1]"</p> <p>I know I could convert the whole thing to a string and parse it, but this doesn't seem like a very elegant or efficient solution. Thank you!</p>
2
2016-09-12T23:42:45Z
39,460,342
<p>I agree that converting to string doesn't make any sense here, but regular expressions explicitly search strings so you're not looking for that either. You're looking for a recursive solution that tests for your rules, which are (essentially)</p> <blockquote> <p>somelist IS or CONTAINS a list that begins with the string "a", ends with the string "b", and has three or more elements.</p> </blockquote> <p>Codify that into:</p> <pre><code>def flat_pass(lst): return len(lst) &gt;= 3 and lst[0] == 'a' and lst[-1] == 'b' </code></pre> <p>Now you just have to recurse (to catch the "CONTAINS" part of the above rules)</p> <pre><code>def recurse_pass(lst): if len(lst) &gt;= 3 and lst[0] == 'a' and lst[-1] == 'b': # base case return True # otherwise, flow continues... for el in lst: if isinstance(el, list): # recursive case if recurse_pass(el): return True return False </code></pre>
3
2016-09-12T23:52:01Z
[ "python", "regex", "list", "recursion" ]
Tensorflow - adding L2 regularization loss simple example
39,460,338
<p>I am familiar with machine learning, but I am learning Tensorflow on my own by reading some slides from universities. Below I'm setting up the loss function for linear regression with only one feature. I'm adding an L2 loss to the total loss, but I am not sure if I'm doing it correctly:</p> <pre><code># Regularization reg_strength = 0.01 # Create the loss function. with tf.variable_scope("linear-regression"): W = tf.get_variable("W", shape=(1, 1), initializer=tf.contrib.layers.xavier_initializer()) b = tf.get_variable("b", shape=(1,), initializer=tf.constant_initializer(0.0)) yhat = tf.matmul(X, W) + b error_loss = tf.reduce_sum(((y - yhat)**2)/number_of_examples) #reg_loss = reg_strength * tf.nn.l2_loss(W) # reg 1 reg_loss = reg_strength * tf.reduce_sum(W**2) # reg 2 loss = error_loss + reg_loss # Set up the optimizer. opt_operation = tf.train.GradientDescentOptimizer(0.001).minimize(loss) </code></pre> <p>My specific questions are:</p> <ol> <li><p>I have two lines (commented as <code>reg 1</code> and <code>reg 2</code>) that compute the L2 loss of the weight <code>W</code>. The line marked with <code>reg 1</code> uses the Tensorflow built-in function. Are these two L2 implementations equivalent?</p></li> <li><p>Am I adding the regularization loss <code>reg_loss</code> correctly to the final loss function?</p></li> </ol>
2
2016-09-12T23:50:45Z
39,461,004
<p>Almost </p> <p><a href="https://github.com/tensorflow/tensorflow/blob/d42facc3cc9611f0c9722c81551a7404a0bd3f6b/tensorflow/core/kernels/l2loss_op.h#L32" rel="nofollow">According to the L2Loss operation code</a></p> <pre><code>output.device(d) = (input.square() * static_cast&lt;T&gt;(0.5)).sum(); </code></pre> <p>It multiplies also for 0.5 (or in other words it divides by <code>2</code>)</p>
1
2016-09-13T01:34:44Z
[ "python", "machine-learning", "tensorflow" ]
Tensorflow - adding L2 regularization loss simple example
39,460,338
<p>I am familiar with machine learning, but I am learning Tensorflow on my own by reading some slides from universities. Below I'm setting up the loss function for linear regression with only one feature. I'm adding an L2 loss to the total loss, but I am not sure if I'm doing it correctly:</p> <pre><code># Regularization reg_strength = 0.01 # Create the loss function. with tf.variable_scope("linear-regression"): W = tf.get_variable("W", shape=(1, 1), initializer=tf.contrib.layers.xavier_initializer()) b = tf.get_variable("b", shape=(1,), initializer=tf.constant_initializer(0.0)) yhat = tf.matmul(X, W) + b error_loss = tf.reduce_sum(((y - yhat)**2)/number_of_examples) #reg_loss = reg_strength * tf.nn.l2_loss(W) # reg 1 reg_loss = reg_strength * tf.reduce_sum(W**2) # reg 2 loss = error_loss + reg_loss # Set up the optimizer. opt_operation = tf.train.GradientDescentOptimizer(0.001).minimize(loss) </code></pre> <p>My specific questions are:</p> <ol> <li><p>I have two lines (commented as <code>reg 1</code> and <code>reg 2</code>) that compute the L2 loss of the weight <code>W</code>. The line marked with <code>reg 1</code> uses the Tensorflow built-in function. Are these two L2 implementations equivalent?</p></li> <li><p>Am I adding the regularization loss <code>reg_loss</code> correctly to the final loss function?</p></li> </ol>
2
2016-09-12T23:50:45Z
39,461,326
<blockquote> <p>Are these two L2 implementations equivalent?</p> </blockquote> <p>Almost, as @fabrizioM pointed out, you can see <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/nn.html#l2_loss" rel="nofollow">here</a> for the introduction to the l2_loss in TensorFlow docs. </p> <blockquote> <p>Am I adding the regularization loss reg_loss correctly to the final loss function?</p> </blockquote> <p>So far so good : )</p>
1
2016-09-13T02:19:39Z
[ "python", "machine-learning", "tensorflow" ]
python with open invalid argument windows
39,460,348
<pre><code>import datetime import os import sys import time if "ZLOG_FILE" not in globals(): global ZLOG_FILE script_dir = os.path.realpath(sys.argv[0]).replace(sys.argv[0], "") ZLOG_FILE = os.path.join(script_dir, "log", datetime.datetime.fromtimestamp(time.time()).strftime("%m-%d-%Y %H:%M:%S")) with open(ZLOG_FILE, "w"): pass def log(level, msg): with open(ZLOG_FILE, "a") as f: # Fix colors if level == "INFO": msg = "ESC[37m[INFO] " + msg elif level == "WARN": msg = "ESC[33m[WARN] " + msg elif level == "ERROR": msg = "ESC[31m[ERROR] " + msg if level != "ERROR": print(msg) else: sys.stderr.write(msg) f.write(msg) </code></pre> <p>I made this simple logging library that on the first import makes a new file with current time and date in a log directory in the same location as the main script being run. I get the following error however:</p> <pre><code>Traceback (most recent call last): File "test.py", line 1, in &lt;module&gt; import zlog File "C:\Users\zane\Desktop\zlog.py", line 10, in &lt;module&gt; with open(ZLOG_FILE, "w"): OSError: [Errno 22] Invalid argument: 'C:\\Users\\zane\\Desktop\\log\\09-12-2016 20:02:26' </code></pre> <p>What am I doing wrong?</p> <p>EDIT: Got rid of the script name with the script_dir variable, and fixed the formatting on the if statements. Im still getting an error though</p>
0
2016-09-12T23:52:57Z
39,460,476
<p>Windows cant use colons in file names, and I forgot to remove the main script from the path once I got the directory it was in</p>
0
2016-09-13T00:13:20Z
[ "python", "windows", "file" ]
How can I prevent unauthorized connections to my python socket server?
39,460,386
<p>I have a simple server written in python that opens and listens on a TCP socket:</p> <pre><code>import socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("", 4242)) server_socket.listen(5) print("TCPServer Waiting for client on port 4242") while 1: client_socket, address = server_socket.accept() print("I got a connection from ", address) while 1: data = client_socket.recv(512) if data: print(data) if not data: print("Closed Connection") break </code></pre> <p>and it works great!</p> <p>I am now left wondering... any rouge client can connect to my server if they know my IP and port. Given that my IP and port aren't crazy secure... how can I make sure that the only device that can connect to this TCP socket is my own device?</p> <p>Can I make some sort of key? Is that what SSL is about, I am having trouble understanding that. It seems like SSL just protects the data from being intercepted, but anyone can still connect and write to my listener?</p> <p>Thanks!</p>
0
2016-09-12T23:58:31Z
39,460,550
<p>You don't need SSL here. TSL and SSL are protocols that provide an encrypted communication over a network, so even if someone is 'listening' to that communication, they can't understand it.</p> <p>The accept() method returns a tuple (conn, <em>address</em>) (<a href="https://docs.python.org/2/library/socket.html" rel="nofollow">https://docs.python.org/2/library/socket.html</a>)</p> <p>You could choose to drop that connection (don't recive any data) if <em>address</em> doesn't match your IP address.</p> <pre><code>if address == your_ip # receive data </code></pre> <p>If you don't want to do it programmatically, under Linux, you could use some packet filtering tool like iptables.</p> <pre><code>$ iptables -I INPUT -p tcp --destination-port 4242 -s &lt;range_of_blocked_ip_addresses&gt; -j DROP </code></pre>
0
2016-09-13T00:26:49Z
[ "python", "sockets", "tcp" ]
SQLAlchemy: filtering on values stored in nested list of the JSONB field
39,460,387
<p>Lets say I have a model named <code>Item</code>, which contains a JSONB field <code>data</code>. One of the records has the following JSON object stored there:</p> <pre><code>{ "name": "hello", "nested_object": { "nested_name": "nested" }, "nested_list": [ { "nested_key": "one" }, { "nested_key": "two" } ] } </code></pre> <p>I can find this record by filtering on the <code>name</code> field as such:</p> <pre><code>Session().query(Item).filter(Item.data["name"] == "hello") </code></pre> <p>I can find this record by filtering on the nested object likewise as such:</p> <pre><code>Session().query(Item).filter(Item.data[("nested_object","nested_name")] == "hello") </code></pre> <p>However I am struggling to find a way to find this record by filtering on the value of the item stored within the nested list. In other words I want to find the record above if the user has provided value "one", and I know to look for it in the key <code>nested_key</code> within the <code>nested_list</code>.</p> <p>Is it possible to achieve this with SQLAlchemy filters available?</p>
0
2016-09-12T23:58:42Z
39,467,149
<p>SQLAlchemy's <a href="http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSONB" rel="nofollow"><code>JSONB</code></a> type has the <a href="http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSONB.Comparator.contains" rel="nofollow"><code>contains()</code></a> method for the <code>@&gt;</code> operator in Postgresql. <a href="https://www.postgresql.org/docs/9.5/static/functions-json.html" rel="nofollow">The <code>@&gt;</code> operator</a> is used to check if the left value contains the right JSON path/value entries at the top level. In your case</p> <pre><code>data @&gt; '{"nested_list": [{"nested_key": "one"}]}'::jsonb </code></pre> <p>Or in python</p> <pre><code>the_value = 'one' Session().query(Item).filter(Item.data.contains( {'nested_list': [{'nested_key': the_value}]} )) </code></pre> <p>The method converts your python structure to suitable JSON string for the database.</p>
0
2016-09-13T09:56:12Z
[ "python", "json", "postgresql", "sqlalchemy" ]
pync interacting with tweepy
39,460,426
<p>am python newbie here. What I am trying to do is to filter certain tweets using tweepy and its streaming function, and then push it alert me via pync.</p> <p>Using the notifier function, I've noticed that all is well when the notification is pure text. However the moment there is a url in there, I no longer see a notification.</p> <p>I've tried decoding/encoding it into utf-8/ascii suspecting it is an issue that has got to do with the format, and I've even tried using regex to just extract the part without the url, but nothing seems to work.</p> <p>An example of the tweet I am trying to push to myself would be:</p> <p>[Bukit Timah] Snorlax until 8:14:00AM at PIE <a href="http://maps.google.com/maps?q=1.336806,103.809445" rel="nofollow">http://maps.google.com/maps?q=1.336806,103.809445</a> … <a href="http://sgpokemap.com" rel="nofollow">http://sgpokemap.com</a> </p> <p>Would appreciate any help! If you need more information let me know!</p>
2
2016-09-13T00:04:16Z
39,460,683
<p>I've solved it myself! It seems like notifier cannot take in the character brackers [ and ]. All I did was to filter it out and it was A OK.</p>
0
2016-09-13T00:48:20Z
[ "python", "twitter", "tweepy" ]
Use python list IN postgresql query
39,460,508
<p>My question is very similar to <a href="http://stackoverflow.com/questions/283645/python-list-in-sql-query-as-parameter">this</a> but I have strings instead of integers in my list.</p> <p>My <code>python list</code>:<br></p> <pre><code>list = ['a', 'b'] #number of items varies from 1 to 6 </code></pre> <p>I want to use this list in Postgres query like this</p> <pre><code>select * from sample where sub in ('a', 'b'); </code></pre> <p>I can use <code>tuple(list)</code> to get <code>('a', 'b')</code>, this is not useful when length of my list became one. I am struggling to find a way to convert<br><br> <code>['a']</code> to <code>('a')</code> <br> <code>['a', 'b']</code> to <code>('a', 'b')</code><br><br> I tried </p> <pre><code>In[91]: myquery = "select * from sample where sub in (%s)" % ",".join(map(str,list)) In[92]: myquery Out[92]: 'select * from sample where sub in (a,b,c)' </code></pre> <p>But postgres expects</p> <pre><code>select * from sample where sub in ('a', 'b'); </code></pre>
0
2016-09-13T00:19:07Z
39,460,580
<p>Try ",".join(["'{0}'".format(s) for s in list]).</p>
-3
2016-09-13T00:31:38Z
[ "python", "postgresql" ]
Use python list IN postgresql query
39,460,508
<p>My question is very similar to <a href="http://stackoverflow.com/questions/283645/python-list-in-sql-query-as-parameter">this</a> but I have strings instead of integers in my list.</p> <p>My <code>python list</code>:<br></p> <pre><code>list = ['a', 'b'] #number of items varies from 1 to 6 </code></pre> <p>I want to use this list in Postgres query like this</p> <pre><code>select * from sample where sub in ('a', 'b'); </code></pre> <p>I can use <code>tuple(list)</code> to get <code>('a', 'b')</code>, this is not useful when length of my list became one. I am struggling to find a way to convert<br><br> <code>['a']</code> to <code>('a')</code> <br> <code>['a', 'b']</code> to <code>('a', 'b')</code><br><br> I tried </p> <pre><code>In[91]: myquery = "select * from sample where sub in (%s)" % ",".join(map(str,list)) In[92]: myquery Out[92]: 'select * from sample where sub in (a,b,c)' </code></pre> <p>But postgres expects</p> <pre><code>select * from sample where sub in ('a', 'b'); </code></pre>
0
2016-09-13T00:19:07Z
39,460,954
<p>I haven't used python's bindings to postgresql so I don't know if it is possible to bind a python list (or a tuple) to a placeholder in a query, but if it is, then you could use the <code>ANY</code> operator as follows:</p> <pre><code>SELECT * FROM sample WHERE sub = ANY (%s); </code></pre> <p>and bind the list the only parameter.</p>
1
2016-09-13T01:27:04Z
[ "python", "postgresql" ]
Use python list IN postgresql query
39,460,508
<p>My question is very similar to <a href="http://stackoverflow.com/questions/283645/python-list-in-sql-query-as-parameter">this</a> but I have strings instead of integers in my list.</p> <p>My <code>python list</code>:<br></p> <pre><code>list = ['a', 'b'] #number of items varies from 1 to 6 </code></pre> <p>I want to use this list in Postgres query like this</p> <pre><code>select * from sample where sub in ('a', 'b'); </code></pre> <p>I can use <code>tuple(list)</code> to get <code>('a', 'b')</code>, this is not useful when length of my list became one. I am struggling to find a way to convert<br><br> <code>['a']</code> to <code>('a')</code> <br> <code>['a', 'b']</code> to <code>('a', 'b')</code><br><br> I tried </p> <pre><code>In[91]: myquery = "select * from sample where sub in (%s)" % ",".join(map(str,list)) In[92]: myquery Out[92]: 'select * from sample where sub in (a,b,c)' </code></pre> <p>But postgres expects</p> <pre><code>select * from sample where sub in ('a', 'b'); </code></pre>
0
2016-09-13T00:19:07Z
39,461,021
<p>Use psycopg2 and it will handle this for you correctly for all sorts of edge cases you haven't thought of yet. For your specific problem see <strong><a href="http://initd.org/psycopg/docs/usage.html#adapt-tuple" rel="nofollow">http://initd.org/psycopg/docs/usage.html#adapt-tuple</a></strong></p>
1
2016-09-13T01:36:47Z
[ "python", "postgresql" ]
In ggplot for Python, using discrete X scale with geom_point()?
39,460,617
<p>The following example returns an error. It appears that using a discrete (not continuous) scale for the x-axis in ggplot in Python is not supported? </p> <pre><code>import pandas as pd import ggplot df = pd.DataFrame.from_dict({'a':['a','b','c'], 'percentage':[.1,.2,.3]}) p = ggplot.ggplot(data=df, aesthetics=ggplot.aes(x='a', y='percentage'))\ + ggplot.geom_point() print(p) </code></pre> <p>As mentioned, this returns: </p> <pre><code>Traceback (most recent call last): File "/Users/me/Library/Preferences/PyCharm2016.1/scratches/scratch_1.py", line 30, in &lt;module&gt; print(p) File "/Users/me/lib/python3.5/site-packages/ggplot/ggplot.py", line 116, in __repr__ self.make() File "/Users/me/lib/python3.5/site-packages/ggplot/ggplot.py", line 627, in make layer.plot(ax, facetgroup, self._aes, **kwargs) File "/Users/me/lib/python3.5/site-packages/ggplot/geoms/geom_point.py", line 60, in plot ax.scatter(x, y, **params) File "/Users/me/lib/python3.5/site-packages/matplotlib/__init__.py", line 1819, in inner return func(ax, *args, **kwargs) File "/Users/me/lib/python3.5/site-packages/matplotlib/axes/_axes.py", line 3838, in scatter x, y, s, c = cbook.delete_masked_points(x, y, s, c) File "/Users/me/lib/python3.5/site-packages/matplotlib/cbook.py", line 1848, in delete_masked_points raise ValueError("First argument must be a sequence") ValueError: First argument must be a sequence </code></pre> <p>Any workarounds for using <code>ggplot</code> with scatters on a discrete scale? </p>
2
2016-09-13T00:37:55Z
39,460,802
<p>One option is to generate a continuous series, and use the original variable as labels. But this seems like a painful workaround. </p> <pre><code>df = pd.DataFrame.from_dict( {'a':[0,1,2], 'a_name':['a','b','c'], 'percentage':[.1,.2,.3]}) p = ggplot.ggplot(data=df, aesthetics=ggplot.aes(x='a', y='percentage'))\ + ggplot.geom_point()\ + ggplot.scale_x_continuous(breaks=list(df['a']), labels=list(df['a_name'])) </code></pre>
0
2016-09-13T01:05:57Z
[ "python", "matplotlib", "ggplot2", "scatter", "python-ggplot" ]
Enabling or disabling checkbox with conditionals
39,460,728
<p>In my code i'm trying to disable the hi box when no is checked and enable it when yes is checked. I attempt to do this in the changed function. However when running the code and checking the yes box hi is still fine and when checking the yes only the yes box i get:</p> <p>Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python35-32\lib\idlelib\run.py", line 119, in main seq, request = rpc.request_queue.get(block=True, timeout=0.05) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python35-32\lib\queue.py", line 172, in get raise Empty queue.Empty</p> <p>During handling of the above exception, another exception occurred:</p> <p>Traceback (most recent call last): File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python35-32\lib\tkinter__init__.py", line 1550, in <strong>call</strong> return self.func(*args) File "C:\Users\Ahmed\Desktop\no_yes.py", line 13, in changed c3.config(state=ENABLE) NameError: name 'ENABLE' is not defined</p> <p>It might be me using idle and not importing the right thing (i have nothing modified or installed with idle just plain comes from python site) but Im thinking its the way i attempt to enable or disable the checkboxes in the changed function. Basically I want to know what to do to enable and disable the checkboxes upon meeting the proper requirements(disable if no selected, enable if only yes selected.)</p> <pre><code>#Import tkinter to make gui from tkinter import * from tkinter import ttk def changed(*args): value = b1.get() value2 = b2.get() value3 = b3.get() print (b3.get()=="1") if b1.get()==1: c3.config(state=DISABLED) elif b2.get() == "1" and (b1.get() == "1") == False: c3.config(state=ENABLE) elif b3.get() != "1": result.set("") elif b3.get() == "1": result.set("Hi!") #Sets title and creates gui root = Tk() root.title("Form") #Configures column and row settings and sets padding mainframe = ttk.Frame(root, padding="3 3 12 12") mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) b1 = StringVar() c1 = ttk.Checkbutton(mainframe, text='No', command=changed, variable=b1) c1.grid(column=1, row=1, sticky=(W, E)) b2 = StringVar() c2 = ttk.Checkbutton(mainframe, text='Yes', command=changed, variable=b2) c2.grid(column=2, row=1, sticky=(W, E)) b3 = StringVar() c3 = ttk.Checkbutton(mainframe, text='Hi', command=changed, variable=b3) c3.grid(column=2, row=2, sticky=(W, E)) result = StringVar() ttk.Label(mainframe, textvariable=result).grid(column=1, row=2, sticky=(W)) </code></pre>
0
2016-09-13T00:55:19Z
39,517,588
<p>Alright, so disabling and enabling goes like so:</p> <pre><code>button.state(['disabled']) # set the disabled flag, disabling the button button.state(['!disabled']) # clear the disabled flag button.instate(['disabled']) # return true if the button is disabled, else false button.instate(['!disabled']) # return true if the button is not disabled, else false button.instate(['!disabled'], cmd) # execute 'cmd' if the button is not disabled </code></pre>
0
2016-09-15T18:04:35Z
[ "python", "checkbox", "tkinter" ]
Return two responses in Flask/JavaScript
39,460,769
<p>I have a Flask/JavaScript application wherein I take a form's inputs and pass them to a Flask app to retrieve distance information from the GoogleMaps API and subsequently return the resulting JSON to JavaScript.This works fine for a single instance of an origin/destination. </p> <p>I want to receive two origin/destination inputs and return both to my JavaScript but cannot figure out how to do that. I'm still learning, but am under the impression I can't simply return two values in a single function so I'm hoping someone can take a look at what I have and tell me what the best approach would be to get the JSON for both back to JavaScript.</p> <pre><code>@app.route("/", methods=['GET', 'POST']) def home(): if request.method == 'POST': # form inputs origin = request.form.get('origin') destination = request.form.get('destination') current_home = request.form.get('current_home') future_home = request.form.get('future_home') # current traffic conditions set to now departure = int(time.time()) # params we pass to the url current_params = { 'origins': origin, 'destinations': destination, 'mode':'driving', 'units':'imperial', 'departure_time' : departure, 'traffic_model':'best_guess', 'avoid':'tolls' } future_params = { 'origins': future_home, 'destinations': destination, 'mode':'driving', 'units':'imperial', 'departure_time' : departure, 'traffic_model':'best_guess', 'avoid':'tolls' } # api call current_url = 'https://maps.googleapis.com/maps/api/distancematrix/json?'+ urllib.urlencode(current_params) future_url = 'https://maps.googleapis.com/maps/api/distancematrix/json?'+ urllib.urlencode(future_params) current_response = requests.get(current_url) future_response = requests.get(future_url) # return json return jsonify(current_response.json()) return jsonify(future_response.json()) return render_template('index.html') if __name__ == "__main__": app.run(debug=True) </code></pre>
0
2016-09-13T01:00:24Z
39,461,118
<p>You need to wrap both values in a dict and then return the dict.</p> <pre><code>payload = { "current_response": current_response, "future_response": future_response } return jsonify(payload) </code></pre>
0
2016-09-13T01:49:57Z
[ "javascript", "python", "json" ]
Numpy : Calculating the average of values between two indices
39,460,832
<p>I need to calculate the average of values that are between 2 indices. Lets say my indices are 3 and 10, and i would like to sum up all the values between them and divide by the number of values.</p> <p>Easiest way would be just using a for loop starting from 3, going until 10, summing 'em up, and dividing. This seems like a really non-pythonic way and considering the functionalities Numpy offers, i thought maybe there is a shorter way using some Numpy magic. Any suggestion is much appriciated</p>
2
2016-09-13T01:10:10Z
39,460,883
<p>To access all elements between two indices <code>i</code> and <code>j</code> you can use slicing:</p> <pre><code>slice_of_array = array[i: j+1] # use j if you DO NOT want index j included </code></pre> <p>and the average is calculated with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.average.html" rel="nofollow"><code>np.average</code></a>, but in your case you want to weight with the number of elements, so you can just use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html" rel="nofollow"><code>np.mean</code></a>:</p> <pre><code>import numpy as np mean_of_slice = np.mean(slice_of_array) </code></pre> <p>or all in one go (using your indices):</p> <pre><code>i = 3 j = 10 np.mean(array[i: j+1]) </code></pre>
2
2016-09-13T01:17:34Z
[ "python", "python-3.x", "numpy" ]
Numpy : Calculating the average of values between two indices
39,460,832
<p>I need to calculate the average of values that are between 2 indices. Lets say my indices are 3 and 10, and i would like to sum up all the values between them and divide by the number of values.</p> <p>Easiest way would be just using a for loop starting from 3, going until 10, summing 'em up, and dividing. This seems like a really non-pythonic way and considering the functionalities Numpy offers, i thought maybe there is a shorter way using some Numpy magic. Any suggestion is much appriciated</p>
2
2016-09-13T01:10:10Z
39,460,975
<pre><code>import numpy as np np.mean(yourarray[3:11]) </code></pre> <p>Assumed your array name is "yourarray" </p>
1
2016-09-13T01:29:47Z
[ "python", "python-3.x", "numpy" ]
Gunicorn, no module named 'myproject
39,460,892
<p>I'm installing a previously built website on a new server. I'm not the original developer.</p> <p>I've used Gunicorn + nginx in the past to keep the app alive (basically following <a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-14-04" rel="nofollow">this tutorial</a>), but am having problems with it here.</p> <p>I <code>source venv/bin/activate</code>, then <code>./manage.py runserver 0.0.0.0:8000</code> works well and everything is running as expected. I shut it down and run <code>gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application</code>, and get the following:</p> <pre><code>[2016-09-13 01:11:47 +0000] [15259] [INFO] Starting gunicorn 19.6.0 [2016-09-13 01:11:47 +0000] [15259] [INFO] Listening at: http://0.0.0.0:8000 (15259) [2016-09-13 01:11:47 +0000] [15259] [INFO] Using worker: sync [2016-09-13 01:11:47 +0000] [15262] [INFO] Booting worker with pid: 15262 [2016-09-13 01:11:47 +0000] [15262] [ERROR] Exception in worker process Traceback (most recent call last): File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker worker.init_process() File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi self.wsgi = self.app.wsgi() File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/var/www/myproject/venv/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app __import__(module) ImportError: No module named 'myproject.wsgi' [2016-09-13 01:11:47 +0000] [15262] [INFO] Worker exiting (pid: 15262) [2016-09-13 01:11:47 +0000] [15259] [INFO] Shutting down: Master [2016-09-13 01:11:47 +0000] [15259] [INFO] Reason: Worker failed to boot. </code></pre> <p>I believe it something to do with the structure of the whole application. Before, I've built apps with the basic structure of:</p> <pre><code>myproject ├── manage.py ├── myproject │   ├── urls.py │   ├── views.py │   ├── component1 │ │   ├── urls.py │ │   └── views.py │   ├── component2 │ │   ├── urls.py │ │   └── views.py ├── venv │   ├── bin │   └── ... </code></pre> <p>This one, instead, has a structure like:</p> <pre><code>myproject ├── apps │   ├── blog │ │   ├── urls.py │ │   ├── views.py │   │ └── ... │   ├── catalogue │ │   ├── urls.py │ │   ├── views.py │   │ └── ... │   ├── checkout │ │   ├── urls.py │ │   ├── views.py │   │ └── ... │   ├── core │ │   ├── urls.py │ │   ├── views.py │   │ └── ... │   ├── customer │   ├── dashboard │   └── __init__.py ├── __init__.py ├── manage.py ├── project_static │   ├── assets │   ├── bower_components │   └── js ├── public │   ├── emails │   ├── media │   └── static ├── settings │   ├── base.py │   ├── dev.py │   ├── __init__.py │   ├── local.py │   └── production.py ├── templates │   ├── base.html │   ├── basket │   ├── blog │   └── .... ├── urls.py ├── venv │   ├── bin │   ├── include │   ├── lib │   ├── pip-selfcheck.json │   └── share └── wsgi.py </code></pre> <p>So, there's no 'main' module running the show, which is what I expect gunicorn is looking for.</p> <p>any thoughts?</p> <p><strong>wsgi.py</strong>:</p> <pre><code>import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") application = get_wsgi_application() </code></pre>
0
2016-09-13T01:19:38Z
39,461,113
<p>Your error message is </p> <pre><code>ImportError: No module named 'myproject.wsgi' </code></pre> <p>You ran the app with</p> <pre><code>gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application </code></pre> <p>And wsgi.py has the line</p> <pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") </code></pre> <p>This is the disconnect. In order to recognize the project as <code>myproject.wsgi</code> the <em>parent</em> directory would have to be on the python path... running </p> <pre><code>cd .. &amp;&amp; gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application </code></pre> <p>Would eliminate that error. However, you would then get a different error because the wsgi.py file refers to <code>settings</code> instead of <code>myproject.settings</code>. This implies that the app was intended to be run from the root directory instead of one directory up. You can figure this out for sure by looking at the code- if it uses absolute imports, do they usually say <code>from myproject.app import ...</code> or <code>from app import ...</code>. If that guess is correct, your correct commmand is</p> <pre><code>gunicorn --bind 0.0.0.0:8000 wsgi:application </code></pre> <p>If the app does use <code>myproject</code> in all of the paths, you'll have to modify your PYTHONPATH to run it properly...</p> <pre><code>PYTHONPATH=`pwd`/.. gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application </code></pre>
1
2016-09-13T01:49:36Z
[ "python", "django", "nginx", "gunicorn" ]
Can't Query by Key in NDB
39,460,976
<p>I'm attempting to query an entity by key assuming ordering by key with ndb.</p> <p>the line is</p> <pre><code>query = User.query().filter(User.key &gt; ndb.Key('User', key_id)) </code></pre> <p>and it's throwing a server error: </p> <pre><code> File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/datastore_types.py", line 1443, in ValidatePropertyKey 'Incomplete key found for reference property %s.' % name) BadValueError: Incomplete key found for reference property __key__. </code></pre> <p>Is it just that I'm not allowed to query by key in this way? Other stack overflow posts seem to indicate that what i'm doing should be ok. I can't find anything online pertaining to the error text, and i'm not sure what else would be causing this error.</p> <p>Any help or insight is greatly appreciated.</p>
0
2016-09-13T01:30:01Z
39,461,251
<p>Try this</p> <pre><code>query = User.query().filter(User._key &gt; ndb.Key('User', key_id)) </code></pre>
0
2016-09-13T02:10:45Z
[ "python", "google-app-engine", "google-cloud-platform", "app-engine-ndb" ]
Python parse SQL and find relationships
39,460,980
<p>I've got a large list of SQL queries all in strings, they've been written for <a href="http://prestodb.io" rel="nofollow">Presto</a>, so kinda formatted for MySQL.</p> <p>I want to be able to tease out the table relationships written in some queries. </p> <p>Let's start with something simple:</p> <pre><code>SELECT e.object_id, count(*) FROM schema_name.elements AS e JOIN schema_name2.quotes AS q ON q.id = e.object_id WHERE e.object_type = 'something' GROUP BY e.object_id, q.query ORDER BY 2 desc; </code></pre> <p>Can clearly see where things join together, though there's aliases - so would need to scan through and find the aliases too - that's fine as the keyword "AS" is used.</p> <p>So I'd want to have returned a list of relationships for the query, each relationship would look something like this dict:</p> <pre><code>dict = {'SourceSchema': 'schema_name', 'SourceTable': "elements", 'SourceColumn': "object_id", 'TargetSchema': "schema_name2", 'TargetTable': "quotes", 'TargetColumn': "id"} </code></pre> <p>I can imagine that doing that is pretty easy, but stuff gets more complicated:</p> <pre><code>SELECT e.object_id, count(*) FROM schema_name.elements e LEFT JOIN schema_name2.quotes q ON q.id = cast(coalesce(nullif(e.object_id,''),'0') as bigint) WHERE e.object_type = 'something' GROUP BY e.object_id, q.query ORDER BY 2 desc; </code></pre> <p>3 things to note</p> <ul> <li>Missing "AS" reserved word - could make it harder to get</li> <li>When joining, there's a lot of stuff needed to parse the two tables together</li> <li>This isn't a simple "JOIN" it's a left join</li> </ul> <p>I'm wondering if there's some form of SQL Parsing library for Python that will allow me to tease out the relationships in some 4000 queries? And if not, then how could I do this efficiently? I'm guessing I might need to scan through queries, find the joins, find the alias, then look at how they're joined whilst taking into account a bunch of stop words that need to be discarded.</p>
1
2016-09-13T01:30:39Z
39,461,102
<p>With some minor changes to the select_parser.py (<a href="https://sourceforge.net/p/pyparsing/code/HEAD/tree/trunk/src/examples/select_parser.py" rel="nofollow">https://sourceforge.net/p/pyparsing/code/HEAD/tree/trunk/src/examples/select_parser.py</a>) that is part of the pyparsing examples, I get this after parsing your first example:</p> <pre><code>SELECT e.object_id, count(*) FROM schema_name.elements AS e JOIN schema_name2.quotes AS q ON q.id = e.object_id WHERE e.object_type = 'something' GROUP BY e.object_id, q.query ORDER BY 2 desc; ['SELECT', [['e.object_id'], ['count', '*']], 'FROM', [['schema_name', '.', 'elements'], 'AS', 'e', ['JOIN'], ['schema_name2', '.', 'quotes'], 'AS', 'q', ['ON', ['q.id', '=', 'e.object_id']]], 'WHERE', ['e.object_type', '=', 'something'], 'GROUP', 'BY', [['e.object_id'], ['q.query']], 'ORDER', 'BY', [['2', 'DESC']], ';'] - columns: [['e.object_id'], ['count', '*']] [0]: ['e.object_id'] [1]: ['count', '*'] - from: [[['schema_name', '.', 'elements'], 'AS', 'e', ['JOIN'], ['schema_name2', '.', 'quotes'], 'AS', 'q', ['ON', ['q.id', '=', 'e.object_id']]]] [0]: [['schema_name', '.', 'elements'], 'AS', 'e', ['JOIN'], ['schema_name2', '.', 'quotes'], 'AS', 'q', ['ON', ['q.id', '=', 'e.object_id']]] - table_alias: [['e'], ['q']] [0]: ['e'] [1]: ['q'] - order_by_terms: [['2', 'DESC']] [0]: ['2', 'DESC'] - direction: DESC - order_key: 2 - where_expr: ['e.object_type', '=', 'something'] </code></pre> <p>So it looks like this example might help you get started. It was written to the SELECT format for SQLite, so you'll need to expand some of the syntax.</p>
1
2016-09-13T01:48:09Z
[ "python", "sql", "parsing", "pyparsing", "sql-parser" ]
Mongo Update of Array Query using Upsert
39,461,017
<p>Given</p> <ol> <li>menuItems is a list ['foo', 'bar', 'fooz', 'ball'] and </li> <li>menudb collection has 3 records: 'foo', 'bar', 'fooz'</li> </ol> <p>When I run</p> <pre><code>menudb.update({"_id" : {"$in": menuItems}}, {"$addToSet": {"staleCount": 100}}, upsert=True) </code></pre> <p>Instead of creating a new record called 'ball', it creates a new record called 'ObjectId("57d730777bc6a465c9124111")'.</p> <p>Is there a way to make the newly created record's '_id' to be that from the list?</p> <p>=Thanks</p>
0
2016-09-13T01:36:16Z
39,461,148
<p>you can remove upsert if you do not want new item in the menudb collection. I seems like your id is objectId instead of string.</p> <p><a href="https://docs.mongodb.com/manual/reference/operator/query/in/" rel="nofollow">https://docs.mongodb.com/manual/reference/operator/query/in/</a></p> <p>you can verify if the _id foo exits in collection menudb.update({"_id" : "foo"}, {"$addToSet": {"staleCount": 100})</p>
0
2016-09-13T01:54:59Z
[ "python", "mongodb" ]
Assignment build in functions
39,461,146
<p>I found an example which make me curious:</p> <pre><code>int = float def parse_string(s): return int(s) print(parse_string('42')) </code></pre> <p>The returned result is <code>42.0</code>. Int and float are build in functions. How come that we can assign float to int (build in functions)? It seems to be wired to me. </p>
2
2016-09-13T01:54:35Z
39,461,824
<p>Python use references to objects.</p> <p>When you write <code>int = float</code>, you only change the <code>int</code> reference to point to the same object (a built-in function here) than the one pointed by <code>float</code> reference.</p> <p>You don't change the nature of <code>int</code> of course.</p> <p>You can restore the <code>int</code> reference by importing <strong><a href="https://docs.python.org/2/library/__builtin__.html" rel="nofollow">__builtin__</a></strong>:</p> <pre><code>import __builtin__ int = __builtin__.int </code></pre>
1
2016-09-13T03:33:47Z
[ "python" ]
looping the data using date variable in python
39,461,381
<p>I have the following dataframe with datetime, lon and lat variables. This data is collected for each second which means each date is repeated 60 times</p> <p>I am doing some calculations using lat, lon values and at the end I need to write this data to Postgres table.</p> <pre><code>2016-07-27 06:43:45 50.62 3.15 2016-07-27 06:43:46 50.67 3.22 2016-07-28 07:23:45 52.32 3.34 2016-07-28 07:24:46 52.67 3.45 </code></pre> <p>Currently I have 10 million records . It is taking longer time if I use whole dataframe for computing.</p> <p>How can I loop this for each date, write it to DB and clear the dataframe??</p> <p>I have converted the datetime variable to date format</p> <pre><code>df['date'] = df['datetime'].dt.date df = df.sort(['datetime']) my computation is df.loc[(df['lat'] &gt; 50.10) &amp; (df['lat'] &lt;= 50.62), 'var1'] = 1 df.loc[(df['lan'] &gt; 3.00) &amp; (df['lan'] &lt;= 3.20), 'var2'] = 1 </code></pre> <p>Writing it to DB</p> <pre><code>df.to_sql('Table1', engine,if_exists = "replace",index = False) </code></pre>
0
2016-09-13T02:28:13Z
39,463,413
<p>Have you considered using the <code>groupby()</code> function? You can use it to treat each 'date' as a seperate DataFrame and then run your computations. </p> <pre><code>for sub_df in df.groupby('date'): # your computations </code></pre>
1
2016-09-13T06:22:36Z
[ "python", "loops", "date", "pandas" ]
button in frames in python
39,461,394
<p><a href="http://i.stack.imgur.com/urPO6.png" rel="nofollow"><img src="http://i.stack.imgur.com/urPO6.png" alt="enter image description here"></a> Design of my game is something like this I need to develop Strategic tic tac toe(where in each block of tic tac toe we will find a tic tac toe)....so here i created 9 frames and each frame has 9 buttons... but when i click the button in any frame changes appear only in one frame ie; in (0,2) i know because its the last frame which is to be called..so i need help to rectify the problem...i tried but i did not get it thanks in advance Here's my code</p> <pre><code>from Tkinter import * root = Tk() root.title("Simple Design") root.geometry("300x300") class Design: count = 0 def __init__(self): self.duplicates = {} self.block = {} self.button = {} for i in range(3): for j in range(3): self.duplicates[i, j] = "." self.frame() def frame(self): for i, j in self.duplicates: self.block[i, j] = Frame(root, background="blue") self.block[i, j].grid(row=i, column=j, ipadx=5, ipady=2) self.button_create(self.block[i, j]) def button_create(self, frame): for i, j in self.duplicates: handler = lambda a=i, b=j: self.update(a, b) self.button[i, j] = Button(frame, command=handler, text=".", height=3, width=5) self.button[i, j].grid(row=i, column=j) def update(self, i, j): if (Design.count % 2 == 0): self.button[i, j]["text"] = "X" Design.count += 1 else: self.button[i, j]["text"] = "O" Design.count += 1 self.button[i, j]["state"] = "disabled" print (i, j) d = Design() # out of class root.mainloop() </code></pre>
1
2016-09-13T02:30:10Z
39,461,641
<p>There is a problem with your button handler: how can each button know its coordinates?</p> <p>Just replace:</p> <pre><code>handler = lambda a=i, b=j: self.update(a, b) </code></pre> <p>By:</p> <pre><code>handler = lambda: self.update(i, j) </code></pre> <p>There is also a bug in <code>frame</code> method: You iterate <code>duplicates</code> and then call <code>button_create</code> which again iterates <code>duplicates</code>. So buttons are redefined in the inner loop.</p> <p>You can change <code>button_create</code> like this:</p> <pre><code>def button_create(self, frame, i, j): handler = lambda: self.update(i, j) self.button[i, j] = Button(frame, command=handler, text=".", height=3, width=5) self.button[i, j].grid(row=i, column=j) </code></pre> <p>And then adapt the call in <code>frame</code> as follow:</p> <pre><code>def frame(self): for i, j in self.duplicates: self.block[i, j] = Frame(root, background="blue") self.block[i, j].grid(row=i, column=j, ipadx=5, ipady=2) self.button_create(self.block[i, j], i, j) </code></pre> <p>Also note that you ought to inherit <code>object</code> class to use new-style classes:</p> <pre><code>class Design(object): ... </code></pre> <p>Instead of a <code>if ... else</code>, you can use a mapping to calculate the symbol "X" or "O" in <code>update</code>:</p> <pre><code>def update(self, i, j): symbol = {0: "X", 1: "O"}[Design.count % 2] self.button[i, j]["text"] = symbol Design.count += 1 self.button[i, j]["state"] = "disabled" print (i, j) </code></pre> <p>Or simply:</p> <pre><code>symbol = "XO"[Design.count % 2] </code></pre>
0
2016-09-13T03:06:09Z
[ "python", "button", "tkinter", "frames" ]
Python serial.readline() not blocking
39,461,414
<p>I'm trying to use hardware serial port devices with Python, but I'm having timing issues. If I send an interrogation command to the device, it should respond with data. If I try to read the incoming data too quickly, it receives nothing.</p> <pre><code>import serial device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0) device.flushInput() device.write("command") response = device.readline() print response '' </code></pre> <p>The <code>readline()</code> command isn't blocking and waiting for a new line as it should. Is there a simple workaround?</p>
0
2016-09-13T02:33:54Z
39,461,487
<p>I couldn't add a commend so I will just add this as an answer. You can reference <a href="http://stackoverflow.com/questions/13017840/using-pyserial-is-it-possble-to-wait-for-data">this stackoverflow thread</a>. Someone attempted something similar to your question.</p> <p>Seems they put their data reading in a loop and continuously looped over it while data came in. You have to ask yourself one thing if you will take this approach, when will you stop collecting data and jump out of the loop? You can try and continue to read data, when you are already collecting, if nothing has come in for a few milliseconds, jump out and take that data and do what you want with it. </p> <p>You can also try something like:</p> <pre><code>While True: serial.flushInput() serial.write(command) incommingBYTES = serial.inWaiting() serial.read(incommingBYTES) #rest of the code down here </code></pre>
0
2016-09-13T02:44:08Z
[ "python", "blocking", "pyserial" ]
Installing BioPython and Numpy
39,461,473
<p>I am working with Python 2.7.11. I've working problems on Rosalind.com from scratch, but I decided to try using tools that are openly available- in order to start familiarizing myself with finding and using said packages and extensions. Good thing too, because I can't figure out how to get any of the third party extensions to python installed. </p> <p>Let's start with Numpy. Which this PDF I'm following to install Biopyton suggests I use. <a href="http://biopython.org/DIST/docs/install/Installation.pdf" rel="nofollow">http://biopython.org/DIST/docs/install/Installation.pdf</a></p> <p>I'm going in circles looking for isntruction. Everybody wants to send me to some other app that uses Numpy or Biopython, I installed Anaconda and then took it back off. </p> <p>I hear talk of using 'the terminal', which I think is just my windows command prompt. </p> <p>I've downloaded the files from the sources for both programs. Do I need to put the files somewhere special first? Before opening the cammand prompt and issuing a command roughly of the form "python setup install"?</p> <p>I placed both sets of files in my python folder, but then before trying to command prompt realized they both have setup files. </p> <p>I was looking for a executable setup file, but double-clicking on the setup files I downloaded doesn't seem to have served that purpose.</p> <p>Does anyone see what it missing here?</p>
0
2016-09-13T02:42:57Z
39,461,676
<p>So you need to install your modules into your python path. There is some (windows) documentation to that <a href="https://docs.python.org/2/using/windows.html" rel="nofollow">here</a> and <a href="https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7">here</a> but should be easily addressable from your interpreter. Can't really give you specific instructions without knowing what you're using. But once you set the path anything you put there will be accessible from your interpreter. Which note that all python programs can be treated as modules so if you want to create your own later put them in a similar place or add that path to your python path. </p>
0
2016-09-13T03:12:48Z
[ "python", "numpy", "installation-package", "installation-path" ]
Use of domain in search of One2many field in List view in Odoo-9
39,461,701
<p>i have One2many field <b>product_attributes</b> in <b>product.template</b> and <b>value</b> field in <b>product.attributes.custom</b></p> <pre><code>class ProductTemplateCus(models.Model): _inherit = 'product.template' product_attributes = fields.One2many('product.attributes.custom','product_id') class ProductAttributes(models.Model): _name = 'product.attributes.custom' value = fields.Char(string='Value') product_id = fields.Many2one('product.template',string='Product') </code></pre> <p>Product 1 <b>product_attributes</b> contains 2 values:</p> <pre><code>value= 'color: red' value= 'others: red' </code></pre> <p>product 2 <b>product_attributes</b> contains 2 values:</p> <pre><code>value= 'color: white' value= 'others: red' </code></pre> <p>I did like below in search xml:</p> <pre><code>&lt;field name="product_attributes" string="Color" filter_domain="['&amp;amp;',('product_attributes.value','ilike','color'),('product_attributes.value','ilike',self)]" /&gt; </code></pre> <p>So if <b>red</b> is searched, only product 1 containing both <b>color</b> and <b>red</b> should be shown. But I am unable to get result. I am getting both products.</p> <p>Is there any solution for this?</p>
0
2016-09-13T03:16:50Z
39,484,050
<p>AFAIK <code>search_domain</code> means nothing here. You should use <code>domain</code> instead.</p>
1
2016-09-14T06:45:11Z
[ "python", "listview", "openerp", "odoo-9" ]
Use of domain in search of One2many field in List view in Odoo-9
39,461,701
<p>i have One2many field <b>product_attributes</b> in <b>product.template</b> and <b>value</b> field in <b>product.attributes.custom</b></p> <pre><code>class ProductTemplateCus(models.Model): _inherit = 'product.template' product_attributes = fields.One2many('product.attributes.custom','product_id') class ProductAttributes(models.Model): _name = 'product.attributes.custom' value = fields.Char(string='Value') product_id = fields.Many2one('product.template',string='Product') </code></pre> <p>Product 1 <b>product_attributes</b> contains 2 values:</p> <pre><code>value= 'color: red' value= 'others: red' </code></pre> <p>product 2 <b>product_attributes</b> contains 2 values:</p> <pre><code>value= 'color: white' value= 'others: red' </code></pre> <p>I did like below in search xml:</p> <pre><code>&lt;field name="product_attributes" string="Color" filter_domain="['&amp;amp;',('product_attributes.value','ilike','color'),('product_attributes.value','ilike',self)]" /&gt; </code></pre> <p>So if <b>red</b> is searched, only product 1 containing both <b>color</b> and <b>red</b> should be shown. But I am unable to get result. I am getting both products.</p> <p>Is there any solution for this?</p>
0
2016-09-13T03:16:50Z
39,484,984
<p>There are a few types of domain for field in the search view:</p> <ul> <li><code>domain</code> - just like the domain on the field declaration in the python class, limits the records got from the database;</li> <li><code>filter_domain</code> - overrides the <code>name_search</code> method which would normally have only <code>('name', 'ilike', self)</code>.</li> </ul> <p>In your case, I believe, you need the <code>filter_domain</code>.</p> <hr> <p>Just a suggestion, you could add the <code>:</code> after the attribute name to differentiate between the attribute and its value, given that you use the same convention for all your attributes: <code>('product_attributes.value', 'ilike', 'color: ')</code></p> <p>The default operator between domains is <code>&amp;</code> and in this case can be omitted.</p>
1
2016-09-14T07:40:28Z
[ "python", "listview", "openerp", "odoo-9" ]
Use of domain in search of One2many field in List view in Odoo-9
39,461,701
<p>i have One2many field <b>product_attributes</b> in <b>product.template</b> and <b>value</b> field in <b>product.attributes.custom</b></p> <pre><code>class ProductTemplateCus(models.Model): _inherit = 'product.template' product_attributes = fields.One2many('product.attributes.custom','product_id') class ProductAttributes(models.Model): _name = 'product.attributes.custom' value = fields.Char(string='Value') product_id = fields.Many2one('product.template',string='Product') </code></pre> <p>Product 1 <b>product_attributes</b> contains 2 values:</p> <pre><code>value= 'color: red' value= 'others: red' </code></pre> <p>product 2 <b>product_attributes</b> contains 2 values:</p> <pre><code>value= 'color: white' value= 'others: red' </code></pre> <p>I did like below in search xml:</p> <pre><code>&lt;field name="product_attributes" string="Color" filter_domain="['&amp;amp;',('product_attributes.value','ilike','color'),('product_attributes.value','ilike',self)]" /&gt; </code></pre> <p>So if <b>red</b> is searched, only product 1 containing both <b>color</b> and <b>red</b> should be shown. But I am unable to get result. I am getting both products.</p> <p>Is there any solution for this?</p>
0
2016-09-13T03:16:50Z
39,524,315
<p>For solving my problem I used search function to get product ids which have selected attribute name and value only and included that in arguments in search function as</p> <pre><code>args += [['id', 'in', productids]] </code></pre> <p>I don't know if it was a right approach to do it. But it solved my problem.</p>
0
2016-09-16T05:32:27Z
[ "python", "listview", "openerp", "odoo-9" ]
How to remove empty separators from read files in Python?
39,461,705
<p>Here is my input file sample (z.txt)</p> <pre><code>&gt;qrst ABCDE-- 6 6 35 25 10 &gt;qqqq ABBDE-- 7 7 28 29 2 </code></pre> <p>I store the alpha and numeric in separate lists. Here is the output of numerics list #Output : ['', '6', '', '6', '35', '25', '10'] ['', '7', '', '7', '28', '29', '', '2']</p> <p>The output has an extra space when there are single digits because of the way the file has been created. Is there anyway to get rid of the '' (empty spaces)?</p>
1
2016-09-13T03:17:31Z
39,461,727
<p>You can take advantage of <code>filter</code> with <code>None</code> as function for that:</p> <pre><code>numbers = ['', '7', '', '7', '28', '29', '', '2'] numbers = filter(None, numbers) print numbers </code></pre> <p>See it in action here: <a href="https://eval.in/640707" rel="nofollow">https://eval.in/640707</a></p>
1
2016-09-13T03:20:37Z
[ "python", "input", "split", "emptydatatext" ]
How to remove empty separators from read files in Python?
39,461,705
<p>Here is my input file sample (z.txt)</p> <pre><code>&gt;qrst ABCDE-- 6 6 35 25 10 &gt;qqqq ABBDE-- 7 7 28 29 2 </code></pre> <p>I store the alpha and numeric in separate lists. Here is the output of numerics list #Output : ['', '6', '', '6', '35', '25', '10'] ['', '7', '', '7', '28', '29', '', '2']</p> <p>The output has an extra space when there are single digits because of the way the file has been created. Is there anyway to get rid of the '' (empty spaces)?</p>
1
2016-09-13T03:17:31Z
39,461,899
<p>A quick fix would be a conditional within a list comprehension:</p> <pre><code>In [4]: a = ['', '7', '', '7', '28', '29', '', '2'] In [5]: [i for i in a if i] Out[5]: ['7', '7', '28', '29', '2'] </code></pre> <p>List comprehensions are generally considered more pythonic than filter and map.</p>
0
2016-09-13T03:43:41Z
[ "python", "input", "split", "emptydatatext" ]
How to remove empty separators from read files in Python?
39,461,705
<p>Here is my input file sample (z.txt)</p> <pre><code>&gt;qrst ABCDE-- 6 6 35 25 10 &gt;qqqq ABBDE-- 7 7 28 29 2 </code></pre> <p>I store the alpha and numeric in separate lists. Here is the output of numerics list #Output : ['', '6', '', '6', '35', '25', '10'] ['', '7', '', '7', '28', '29', '', '2']</p> <p>The output has an extra space when there are single digits because of the way the file has been created. Is there anyway to get rid of the '' (empty spaces)?</p>
1
2016-09-13T03:17:31Z
39,462,009
<p>I guess there are many ways to do this. I prefer using regular expressions, although this might be slower if you have a large input file with tens of thousands of lines. For smaller files, it's okay. </p> <p>Few points:</p> <ol> <li><p>Use context manager (<code>with</code> statement) to open files. When the <code>with</code> statement ends, the file will automatically be closed.</p></li> <li><p>An alternative to <code>re.findall()</code> is <code>re.match()</code> or <code>re.search()</code>. Subsequent code will be slightly different.</p></li> <li><p>It <code>org</code>, <code>sequence</code> and <code>numbers</code> are related element-wise, I suggest you maintain a list of 3-element tuples instead. Of course, you have buffer the org field and add to the list of tuples when the next line is obtained.</p> <pre><code>import re org = [] sequence = [] numbers = [] with open('ddd', 'r') as f: for line in f.readlines(): line = line.strip() if re.search(r'^&gt;', line): org.append(line) else: m = re.findall(r'^([A-Z]+--)\s+(.*)\s+', line) if m: sequence.append(m[0][0]) numbers.append(map(int, m[0][1].split())) # convert from str to int print(org, sequence, numbers) </code></pre></li> </ol>
0
2016-09-13T03:58:53Z
[ "python", "input", "split", "emptydatatext" ]
How to remove empty separators from read files in Python?
39,461,705
<p>Here is my input file sample (z.txt)</p> <pre><code>&gt;qrst ABCDE-- 6 6 35 25 10 &gt;qqqq ABBDE-- 7 7 28 29 2 </code></pre> <p>I store the alpha and numeric in separate lists. Here is the output of numerics list #Output : ['', '6', '', '6', '35', '25', '10'] ['', '7', '', '7', '28', '29', '', '2']</p> <p>The output has an extra space when there are single digits because of the way the file has been created. Is there anyway to get rid of the '' (empty spaces)?</p>
1
2016-09-13T03:17:31Z
39,462,073
<p>If your input looks like this:</p> <pre><code>&gt;&gt;&gt; li=[' 6 6 35 25 10', ' 7 7 28 29 2'] </code></pre> <p>Just use <code>.split()</code> which will handle the repeated whitespace as a single delimiter:</p> <pre><code>&gt;&gt;&gt; [e.split() for e in li] [['6', '6', '35', '25', '10'], ['7', '7', '28', '29', '2']] </code></pre> <p>vs <code>.split(" ")</code>:</p> <pre><code>&gt;&gt;&gt; [e.split(" ") for e in li] [['', '6', '', '6', '', '35', '', '25', '', '10'], ['', '7', '7', '28', '', '29', '2']] </code></pre>
0
2016-09-13T04:08:03Z
[ "python", "input", "split", "emptydatatext" ]
NoReverseMatch Reverse for 'profile_user' with arguments '()' and keyword arguments '{}' not found
39,461,793
<p>Views.py</p> <pre><code>@login_required def profile_edit(request): profile, created = UserProfile.objects.get_or_create(user=request.user) form = UserProfileForm(request.POST or None, request.FILES or None, instance=profile) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('profile_user') context = { "title": 'Edit Profile', "form":form, } return render(request, 'profiles/userprofile_form.html', context) </code></pre> <p>main url there is no name space given and profile url is as follows. </p> <pre><code>url(r'^profile/(?P&lt;username&gt;[\w.@+-]+)$', profile_view, name='profile_user'), </code></pre> <p>Could anybody help to solve this please?</p>
0
2016-09-13T03:29:54Z
39,461,852
<p>Your url requires 1 parameter for username. But in <code>reverse()</code> you are not passing any parameter. Hence the error. Change the reverse call as</p> <pre><code>return redirect('profile_user', args=(instance.user.username,)) </code></pre>
0
2016-09-13T03:38:11Z
[ "python", "django" ]
NoReverseMatch Reverse for 'profile_user' with arguments '()' and keyword arguments '{}' not found
39,461,793
<p>Views.py</p> <pre><code>@login_required def profile_edit(request): profile, created = UserProfile.objects.get_or_create(user=request.user) form = UserProfileForm(request.POST or None, request.FILES or None, instance=profile) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('profile_user') context = { "title": 'Edit Profile', "form":form, } return render(request, 'profiles/userprofile_form.html', context) </code></pre> <p>main url there is no name space given and profile url is as follows. </p> <pre><code>url(r'^profile/(?P&lt;username&gt;[\w.@+-]+)$', profile_view, name='profile_user'), </code></pre> <p>Could anybody help to solve this please?</p>
0
2016-09-13T03:29:54Z
39,461,879
<p>Your URL requires a named argument <code>username</code>. You have to give it to <code>redirect()</code> as keyword argument. Example:</p> <pre><code>redirect('view-name', username='joe') </code></pre>
0
2016-09-13T03:41:24Z
[ "python", "django" ]
Connecting to Azure SQL with Python
39,461,850
<p>I am trying to connect to a SQL Database hosted in Windows Azure through MySQLdb with Python. </p> <p>I keep getting an error mysql_exceptions.OperationalError: (2001, 'Bad connection string.')</p> <p>This information works when connecting through .NET (vb, C#) but I am definitely not having any luck here. </p> <p>For below I used my server's name from azure then .database.windows.net Is this the correct way to go about this?</p> <p>Here is my code:</p> <pre><code>#!/usr/bin/python import MySQLdb conn = MySQLdb.connect(host="&lt;servername&gt;.database.windows.net", user="myUsername", passwd="myPassword", db="db_name") cursor = conn.cursor() </code></pre> <p>I have also tried using pyodbc with FreeTDS with no luck.</p>
0
2016-09-13T03:37:47Z
39,496,806
<p>@Kyle Moffat, what OS are you on? Here is how you can use pyodbc on Linux and Windows: <a href="https://msdn.microsoft.com/en-us/library/mt763261(v=sql.1).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/mt763261(v=sql.1).aspx</a></p> <p><strong>Windows:</strong></p> <ul> <li>Download and install Python</li> <li><p>Install the Microsoft ODBC Driver 11 or 13: </p> <ul> <li>v13: <a href="https://www.microsoft.com/en-us/download/details.aspx?id=50420" rel="nofollow">https://www.microsoft.com/en-us/download/details.aspx?id=50420</a> </li> <li>v11: <a href="https://www.microsoft.com/en-us/download/details.aspx?id=36434" rel="nofollow">https://www.microsoft.com/en-us/download/details.aspx?id=36434</a></li> </ul></li> <li><p>Open cmd.exe as an administrator</p></li> <li><p>Install pyodbc using pip - Python package manager</p> <pre><code>cd C:\Python27\Scripts&gt; pip install pyodbc </code></pre></li> </ul> <p><strong>Linux:</strong></p> <ul> <li><p>Open terminal Install Microsoft ODBC Driver 13 for Linux For Ubuntu 15.04 +</p> <pre><code> sudo su wget https://gallery.technet.microsoft.com/ODBC-Driver-13-for-Ubuntu-b87369f0/file/154097/2/installodbc.sh  sh installodbc.sh </code></pre></li> <li><p>For RedHat 6,7</p> <pre><code>sudo su wget https://gallery.technet.microsoft.com/ODBC-Driver-13-for-SQL-8d067754/file/153653/4/install.sh sh install.sh </code></pre></li> <li><p>Install pyodbc</p> <pre><code>sudo -H pip install pyodbc </code></pre></li> </ul> <p>Once you install the ODBC driver and pyodbc you can use this Python sample to connect to Azure SQL DB</p> <pre><code>import pyodbc server = 'tcp:myserver.database.windows.net' database = 'mydb' username = 'myusername' password = 'mypassword' cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password) cursor = cnxn.cursor() cursor.execute("SELECT @@version;") row = cursor.fetchone() while row: print row[0] row = cursor.fetchone() </code></pre> <p>If you are not able to install the ODBC Driver you can also try pymssql + FreeTDS</p> <pre><code>sudo apt-get install python sudo apt-get --assume-yes install freetds-dev freetds-bin sudo apt-get --assume-yes install python-dev python-pip sudo pip install pymssql==2.1.1 </code></pre> <p>Once you follow these steps, you can use the following code sample to connect: <a href="https://msdn.microsoft.com/en-us/library/mt715796(v=sql.1).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/mt715796(v=sql.1).aspx</a> </p>
3
2016-09-14T17:55:41Z
[ "python", "azure", "sql-azure" ]
Python Regex findall But Not Including the conditional string
39,461,865
<p>i have this string:</p> <p><code>The quick red fox jumped over the lazy brown dog lazy</code></p> <p>And i wrote this regex which gives me this:</p> <pre><code>s = The quick red fox jumped over the lazy brown dog lazy re.findall(r'[\s\w\S]*?(?=lazy)', ss) </code></pre> <p>which gives me below output:</p> <p><code>['The quick red fox jumped over the ', '', 'azy brown dog ', '']</code></p> <p>But i am trying to get the output like this:</p> <p><code>['The quick red fox jumped over the ']</code></p> <p>Which means the regex should give me everything till it encounters the first <code>lazy</code> instead of last one and i only want to use <code>findall</code>.</p>
0
2016-09-13T03:40:09Z
39,461,903
<p>Make the pattern <em>non-greedy</em> by adding a <code>?</code>:</p> <pre><code>&gt;&gt;&gt; m = re.search(r'[\s\w\S]*?(?=lazy)', s) # ^ &gt;&gt;&gt; m.group() 'The quick red fox jumped over the ' </code></pre>
0
2016-09-13T03:44:09Z
[ "python", "regex", "findall" ]
softlayer api:How to buy the bandwidth package, changes and upgrades
39,461,928
<p>I am a developer, recently I was doing development work on the softlayer api. Now I have a problem about bandwidth package api interface. Specific questions are as follows: 1. Bandwidth package can be replaced after purchasing finish? Where is the api ? 2. Where is the bandwidth package purchase and upgrade api?</p>
-3
2016-09-13T03:47:31Z
39,468,929
<p>you need to upgrade your server here some similar questions</p> <p><a href="http://stackoverflow.com/questions/35197429/modify-device-configuration/35209731#35209731">Modify Device Configuration</a></p> <p><a href="http://stackoverflow.com/questions/37782460/how-to-add-two-or-more-disk-to-softlayer-virtual-server-while-provisioning/37790825#37790825">How to add two or more disk to softlayer virtual server while provisioning</a></p> <p>you need just specify the price for the new bandwidth you want in the request</p> <p>Regards</p>
1
2016-09-13T11:30:02Z
[ "python", "api", "bandwidth", "softlayer" ]
Printing numbers from 1-100 as words in Python 3
39,461,937
<pre><code>List_of_numbers1to19 = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] List_of_numbers1to9 = List_of_numbers1to19[0:9] List_of_numberstens = ['twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] for i in List_of_numbers1to19: print(i) list_of_numbers21to99 = [] count = 19 tens_count = 0 for j in List_of_numberstens: for k in List_of_numbers1to9: if tens_count%10 == 0: #should print an iteration of List_of_numberstens tens_count +=1 tens_count +=1 print(j, k) </code></pre> <p>As you can see, this is getting messy :P So sorry for that. Basically I'm trying to print them using three different for-loops with a different index. I have tried slicing the list and indexing the list, but I keep getting output for the numbers multipliable by 10 as the full list of <code>List_of_numberstens</code>. </p> <p>I think it's clear what I'm trying to do here.</p> <p>Thanks in advance for your help!</p>
-1
2016-09-13T03:49:07Z
39,462,035
<p>I think you're overcomplicating the 20-100 case. From 20-100, numbers are very regular. (i.e. they come in the form <code>&lt;tens_place&gt; &lt;ones_place&gt;</code>).</p> <p>By using just one loop instead of nested loops makes the code simpler to follow. Now we just need to figure out what the tens place is, and what the ones place is.</p> <p>The tens place can be easily found by using integer division by 10. (we subtract 2 since the list starts with twenty).</p> <p>The ones place can similarly be found by using the modulo operator by 10. (we subtract 1 since the list starts with 1 and not 0).</p> <p>Finally we just take care of the case of the ones place being 0 separately by using an if statement (and just not print any ones place value).</p> <pre><code>List_of_numbers1to19 = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] List_of_numberstens = ['twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] for i in range(19): print(List_of_numbers1to19[i]) for i in range(20, 100): if i%10 == 0: #if multiple of ten only print tens place print(List_of_numberstens[i//10-2]) #20/10-2 = 0, 30/10-2 = 1, ... else: #if not, print tens and ones place print(List_of_numberstens[i//10-2] + ' ' + List_of_numbers1to19[i%10-1]) </code></pre>
1
2016-09-13T04:02:47Z
[ "python", "python-3.x", "numbers" ]
Printing numbers from 1-100 as words in Python 3
39,461,937
<pre><code>List_of_numbers1to19 = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] List_of_numbers1to9 = List_of_numbers1to19[0:9] List_of_numberstens = ['twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] for i in List_of_numbers1to19: print(i) list_of_numbers21to99 = [] count = 19 tens_count = 0 for j in List_of_numberstens: for k in List_of_numbers1to9: if tens_count%10 == 0: #should print an iteration of List_of_numberstens tens_count +=1 tens_count +=1 print(j, k) </code></pre> <p>As you can see, this is getting messy :P So sorry for that. Basically I'm trying to print them using three different for-loops with a different index. I have tried slicing the list and indexing the list, but I keep getting output for the numbers multipliable by 10 as the full list of <code>List_of_numberstens</code>. </p> <p>I think it's clear what I'm trying to do here.</p> <p>Thanks in advance for your help!</p>
-1
2016-09-13T03:49:07Z
39,462,267
<p>I know you already accepted an answer, but you particularly mentioned nested loops - which it doesn't use - and you're missing what's great about Python's iteration and not needing to do that kind of <code>i//10-2</code> and <code>print(j,k)</code> stuff to work out indexes into lists. </p> <p>Python's <code>for</code> loop iteration runs over the items in the list directly and you can just print them, so I answer:</p> <pre><code>digits = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] tens = ['twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] for word in digits + teens: print(word) for tens_word in tens: print(tens_word) # e.g. twenty for digits_word in digits: print(tens_word, digits_word) # e.g. twenty one print("one hundred") </code></pre> <p><a href="https://repl.it/D80Y">Try it online at repl.it</a></p>
5
2016-09-13T04:34:25Z
[ "python", "python-3.x", "numbers" ]
Kafka Consumer didn't receiving any messages from its Producer
39,461,979
<p>the following is my python coding for a kafka producer, I'm not sure is the messages able to be published to a Kafka Broker or not. Because the consumer side is didn't receiving any messages. My Consumer python program is working fine while i testing it using producer console command.</p> <pre><code>from __future__ import print_function import sys from pyspark import SparkContext from kafka import KafkaClient, SimpleProducer if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:spark-submit producer1.py &lt;input file&gt;", file=sys.stderr) exit(-1) sc = SparkContext(appName="PythonRegression") def sendkafka(messages): ## Set broker port kafka = KafkaClient("localhost:9092") producer = SimpleProducer(kafka, async=True, batch_send_every_n=5, batch_send_every_t=10) send_counts = 0 for message in messages: try: print(message) ## Set topic name and push messages to the Kafka Broker yield producer.send_messages('test', message.encode('utf-8')) except Exception, e: print("Error: %s" % str(e)) else: send_counts += 1 print("The count of prediction results which were sent IN THIS PARTITION is %d.\n" % send_counts) ## Connect and read the file. rawData = sc.textFile(sys.argv[1]) ## Find and skip the first row dataHeader = rawData.first() data = rawData.filter(lambda x: x != dataHeader) ## Collect the RDDs. sentRDD = data.mapPartitions(sendkafka) sentRDD.collect() ## Stop file connection sc.stop() </code></pre> <p>This is my "Consumer" python coding</p> <pre><code>from __future__ import print_function import sys from pyspark import SparkContext from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils if len(sys.argv) &lt; 3: print ("Program to pulls the messages from kafka brokers.") print("Usage: consume.py &lt;zk&gt; &lt;topic&gt;", file=sys.stderr) else: ## Flow ## Loads settings from system properties, for launching of spark-submit. sc = SparkContext(appName="PythonStreamingKafkaWordCount") ## Create a StreamingContext using an existing SparkContext. ssc = StreamingContext(sc, 10) ## Get everything after the python script name zkQuorum, topic = sys.argv[1:] ## Create an input stream that pulls messages from Kafka Brokers. kvs = KafkaUtils.createStream(ssc, zkQuorum, "spark-streaming-consumer", {topic: 1}) ## lines = kvs.map(lambda x: x[1]) ## Print the messages pulled from Kakfa Brokers lines.pprint() ## Save the pulled messages as file ## lines.saveAsTextFiles("OutputA") ## Start receiving data and processing it ssc.start() ## Allows the current process to wait for the termination of the context ssc.awaitTermination() </code></pre>
0
2016-09-13T03:55:25Z
39,482,762
<p>I usually debug such issues using kafka-console-consumer (part of Apache Kafka) to consume from the topic you tried producing to. If the console consumer gets messages, you know they arrived to Kafka.</p> <p>If you first run the producer, let it finish, and then start the consumer, then the issue may be that the consumer is starting from the end of the log and is waiting for additional messages. Either make sure you are starting the consumer first, or configure it to automatically start at the beginning (sorry, not sure how to do that with your Python client).</p>
0
2016-09-14T04:58:27Z
[ "python", "apache-spark", "apache-kafka", "spark-streaming", "python-kafka" ]
Kafka Consumer didn't receiving any messages from its Producer
39,461,979
<p>the following is my python coding for a kafka producer, I'm not sure is the messages able to be published to a Kafka Broker or not. Because the consumer side is didn't receiving any messages. My Consumer python program is working fine while i testing it using producer console command.</p> <pre><code>from __future__ import print_function import sys from pyspark import SparkContext from kafka import KafkaClient, SimpleProducer if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:spark-submit producer1.py &lt;input file&gt;", file=sys.stderr) exit(-1) sc = SparkContext(appName="PythonRegression") def sendkafka(messages): ## Set broker port kafka = KafkaClient("localhost:9092") producer = SimpleProducer(kafka, async=True, batch_send_every_n=5, batch_send_every_t=10) send_counts = 0 for message in messages: try: print(message) ## Set topic name and push messages to the Kafka Broker yield producer.send_messages('test', message.encode('utf-8')) except Exception, e: print("Error: %s" % str(e)) else: send_counts += 1 print("The count of prediction results which were sent IN THIS PARTITION is %d.\n" % send_counts) ## Connect and read the file. rawData = sc.textFile(sys.argv[1]) ## Find and skip the first row dataHeader = rawData.first() data = rawData.filter(lambda x: x != dataHeader) ## Collect the RDDs. sentRDD = data.mapPartitions(sendkafka) sentRDD.collect() ## Stop file connection sc.stop() </code></pre> <p>This is my "Consumer" python coding</p> <pre><code>from __future__ import print_function import sys from pyspark import SparkContext from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils if len(sys.argv) &lt; 3: print ("Program to pulls the messages from kafka brokers.") print("Usage: consume.py &lt;zk&gt; &lt;topic&gt;", file=sys.stderr) else: ## Flow ## Loads settings from system properties, for launching of spark-submit. sc = SparkContext(appName="PythonStreamingKafkaWordCount") ## Create a StreamingContext using an existing SparkContext. ssc = StreamingContext(sc, 10) ## Get everything after the python script name zkQuorum, topic = sys.argv[1:] ## Create an input stream that pulls messages from Kafka Brokers. kvs = KafkaUtils.createStream(ssc, zkQuorum, "spark-streaming-consumer", {topic: 1}) ## lines = kvs.map(lambda x: x[1]) ## Print the messages pulled from Kakfa Brokers lines.pprint() ## Save the pulled messages as file ## lines.saveAsTextFiles("OutputA") ## Start receiving data and processing it ssc.start() ## Allows the current process to wait for the termination of the context ssc.awaitTermination() </code></pre>
0
2016-09-13T03:55:25Z
39,485,368
<p>You can check the number of messages in the topic if they are increasing with Produce requests:</p> <pre><code>./bin/kafka-run-class.sh kafka.tools.GetOffsetShell \ --broker-list &lt;Kafka_broker_hostname&gt;:&lt;broker_port&gt; --topic Que1 \ --time -1 --offsets 1 | awk -F ":" '{sum += $3} END {print sum}' </code></pre> <p>If the number of messages are increasing, then it means the Producer is working fine.</p>
0
2016-09-14T08:02:41Z
[ "python", "apache-spark", "apache-kafka", "spark-streaming", "python-kafka" ]
Kafka Consumer didn't receiving any messages from its Producer
39,461,979
<p>the following is my python coding for a kafka producer, I'm not sure is the messages able to be published to a Kafka Broker or not. Because the consumer side is didn't receiving any messages. My Consumer python program is working fine while i testing it using producer console command.</p> <pre><code>from __future__ import print_function import sys from pyspark import SparkContext from kafka import KafkaClient, SimpleProducer if __name__ == "__main__": if len(sys.argv) != 2: print("Usage:spark-submit producer1.py &lt;input file&gt;", file=sys.stderr) exit(-1) sc = SparkContext(appName="PythonRegression") def sendkafka(messages): ## Set broker port kafka = KafkaClient("localhost:9092") producer = SimpleProducer(kafka, async=True, batch_send_every_n=5, batch_send_every_t=10) send_counts = 0 for message in messages: try: print(message) ## Set topic name and push messages to the Kafka Broker yield producer.send_messages('test', message.encode('utf-8')) except Exception, e: print("Error: %s" % str(e)) else: send_counts += 1 print("The count of prediction results which were sent IN THIS PARTITION is %d.\n" % send_counts) ## Connect and read the file. rawData = sc.textFile(sys.argv[1]) ## Find and skip the first row dataHeader = rawData.first() data = rawData.filter(lambda x: x != dataHeader) ## Collect the RDDs. sentRDD = data.mapPartitions(sendkafka) sentRDD.collect() ## Stop file connection sc.stop() </code></pre> <p>This is my "Consumer" python coding</p> <pre><code>from __future__ import print_function import sys from pyspark import SparkContext from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils if len(sys.argv) &lt; 3: print ("Program to pulls the messages from kafka brokers.") print("Usage: consume.py &lt;zk&gt; &lt;topic&gt;", file=sys.stderr) else: ## Flow ## Loads settings from system properties, for launching of spark-submit. sc = SparkContext(appName="PythonStreamingKafkaWordCount") ## Create a StreamingContext using an existing SparkContext. ssc = StreamingContext(sc, 10) ## Get everything after the python script name zkQuorum, topic = sys.argv[1:] ## Create an input stream that pulls messages from Kafka Brokers. kvs = KafkaUtils.createStream(ssc, zkQuorum, "spark-streaming-consumer", {topic: 1}) ## lines = kvs.map(lambda x: x[1]) ## Print the messages pulled from Kakfa Brokers lines.pprint() ## Save the pulled messages as file ## lines.saveAsTextFiles("OutputA") ## Start receiving data and processing it ssc.start() ## Allows the current process to wait for the termination of the context ssc.awaitTermination() </code></pre>
0
2016-09-13T03:55:25Z
39,606,786
<p>Alright I think there's something wrong with my local Zookeeper or Kafka, because I test it on another server it work perfectly. However , thanks for those who reply me ;)</p>
0
2016-09-21T02:54:32Z
[ "python", "apache-spark", "apache-kafka", "spark-streaming", "python-kafka" ]
NLTK sentiment vader: polarity_scores(text) not working
39,462,021
<p>I am trying to use <code>polarity_scores()</code> from the Vader sentiment analysis in NLTK, but it gives me error: </p> <blockquote> <p>polarity_scores() missing 1 required positional argument: 'text'</p> </blockquote> <p>I am totally a beginner in Python. Appreciate your help! </p> <pre><code>from nltk.sentiment.vader import SentimentIntensityAnalyzer as sid sentences=["hello","why is it not working?!"] for sentence in sentences: ss = sid.polarity_scores(sentence) </code></pre>
0
2016-09-13T04:00:17Z
39,462,068
<p><code>SentimentIntensityAnalyzer</code> is a class. You need to initialize an object of <code>SentimentIntensityAnalyzer</code> and call the <code>polarity_scores()</code> method on that.</p> <pre><code>from nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA sentences=["hello","why is it not working?!"] sid = SIA() for sentence in sentences: ss = sid.polarity_scores(sentence) </code></pre> <p>You may have to download the lexicon file if you haven't already</p> <pre><code>&gt;&gt;&gt; import nltk &gt;&gt;&gt; nltk.download() --------------------------------------------------------------------------- d) Download l) List u) Update c) Config h) Help q) Quit --------------------------------------------------------------------------- Downloader&gt; d vader_lexicon Downloader&gt; q </code></pre>
0
2016-09-13T04:07:14Z
[ "python", "nltk", "sentiment-analysis" ]
Index of each element within list of lists
39,462,049
<p>I have something like the following list of lists:</p> <pre><code>&gt;&gt;&gt; mylist=[['A','B','C'],['D','E'],['F','G','H']] </code></pre> <p>I want to construct a new list of lists where each element is a tuple where the first value indicates the index of that item within its sublist, and the second value is the original value.</p> <p>I can obtain this using the following code:</p> <pre><code>&gt;&gt;&gt; final_list=[] &gt;&gt;&gt; for sublist in mylist: ... slist=[] ... for i,element in enumerate(sublist): ... slist.append((i,element)) ... final_list.append(slist) ... &gt;&gt;&gt; &gt;&gt;&gt; final_list [[(0, 'A'), (1, 'B'), (2, 'C')], [(0, 'D'), (1, 'E')], [(0, 'F'), (1, 'G'), (2, 'H')]] &gt;&gt;&gt; </code></pre> <p>Is there a better or more concise way to do this using list comprehension?</p>
2
2016-09-13T04:05:03Z
39,462,103
<pre><code>final_list = [list(enumerate(l)) for l in mylist] </code></pre>
9
2016-09-13T04:10:33Z
[ "python", "list" ]
Keras model.predict won't accept input of size one (scalar number)
39,462,142
<p>I'm new to Keras and python, now I'm working on Keras to find a model of data and use that model.predict for optimization, however the model.predict can only take input as numpy array of at least 2 elements.</p> <p>My code is</p> <pre><code>import keras from keras.models import Sequential from keras.layers import Dense from keras.optimizers import SGD import numpy as np x = np.arange(-2,3.0,0.01) y = x**2 - 2*x + 1 model = Sequential() model.add(Dense(50, activation='sigmoid', input_dim=1, init='uniform')) model.add(Dense(1, activation='linear')) sgd = SGD(lr=0.05, decay=1e-6, momentum=0.9, nesterov=False) model.compile(loss='mean_squared_error', optimizer='sgd', metrics=['accuracy']) model.fit(x,y,nb_epoch=300, batch_size = 5,verbose = 0) </code></pre> <p>The code can fit fine, but if I try to use model.predict for a scalar number it gives me error</p> <pre><code>(Pdb) model.predict(0.0) *** Exception: Error when checking : data should be a Numpy array, or list/dict of Numpy arrays. Found: 0.0... </code></pre> <p>I force it to be numpy array but still failed, and it said the input needs to be 2 dimensions!!!</p> <pre><code>(Pdb) model.predict(np.asarray(0.0)) *** Exception: Error when checking : expected dense_input_1 to have 2 dimensions, but got array with shape () </code></pre> <p>but if I input two numbers then it gives me the answer</p> <pre><code>(Pdb) model.predict([0.0,0.0]) array([[ 1.07415712], [ 1.07415712]], dtype=float32) </code></pre> <p>I need the model.predict to take single number as input to use for optimization. I'm not sure any setting I use wrong. Please help, thanks.</p>
1
2016-09-13T04:15:37Z
39,529,769
<p>Try: </p> <pre><code>model.predict(np.asarray(0.0).reshape((1,1))) </code></pre> <p>In Keras first dimension is always connected with example number, so it must be provided.</p>
0
2016-09-16T10:55:56Z
[ "python", "keras" ]
Number guessing game: How can I accept input that says "guess =" before the number?
39,462,287
<pre><code>import random guess = input("What is your guess?") answer = random.randint(0,100) while guess != answer: try: guess = float(guess) if guess &gt; answer: print ("Your guess is too high!") elif guess &lt; answer: print ("Your guess is too low!") elif guess == answer: print ("Congratulations!") break guess = input("What is your guess?") continue except ValueError: print ("Bad input. Try again!") guess = input("What is your guess?") </code></pre> <p>So my code works except that when i enter for example: guess = 30, it seems the input as invalid...how can I make it so it accepts it as a correct guess?</p> <p>New to python here :) Thanks.</p>
0
2016-09-13T04:36:06Z
39,462,367
<p>I copied and pasted your code into Python 3.5, and....apart from needing to indent everything after the while statement it worked fine.</p> <p>Are you inputting just the number: 30</p> <p>...or "guess = 30"? Because that does cause a problem since it's not a number. You only need to input the number. :)</p> <p>If you want to accept "guess = 30" then:</p> <pre><code>import random import re ###&lt;-Add this guess = input("What is your guess?") answer = random.randint(0,100) while guess != answer: try: guess = re.sub("[^0-9]", "", guess) ###&lt;- Add this guess = float(guess) if guess &gt; answer: print ("Your guess is too high!") elif guess &lt; answer: print ("Your guess is too low!") elif guess == answer: print ("Congratulations!") break guess = input("What is your guess?") continue except ValueError: print ("Bad input. Try again!") guess = input("What is your guess?") </code></pre> <p>These two lines will use Regular Expressions to strip the input of any non numeric characters before processing.</p>
0
2016-09-13T04:47:13Z
[ "python", "python-3.x" ]
Number guessing game: How can I accept input that says "guess =" before the number?
39,462,287
<pre><code>import random guess = input("What is your guess?") answer = random.randint(0,100) while guess != answer: try: guess = float(guess) if guess &gt; answer: print ("Your guess is too high!") elif guess &lt; answer: print ("Your guess is too low!") elif guess == answer: print ("Congratulations!") break guess = input("What is your guess?") continue except ValueError: print ("Bad input. Try again!") guess = input("What is your guess?") </code></pre> <p>So my code works except that when i enter for example: guess = 30, it seems the input as invalid...how can I make it so it accepts it as a correct guess?</p> <p>New to python here :) Thanks.</p>
0
2016-09-13T04:36:06Z
39,462,482
<p>It depends on how much you have learnt in that class, but adding the following line should allow you to accept both <code>30</code> and <code>guess = 30</code> (or even <code>foo=bar=30</code>):</p> <pre><code>... while guess != answer: guess = guess.split('=')[-1] # Add this line try: guess = float(guess) ... </code></pre> <p>It simply splits the input using <code>=</code> as a delimiter and only uses the last part (<code>[-1]</code>).</p>
0
2016-09-13T05:01:18Z
[ "python", "python-3.x" ]
Number guessing game: How can I accept input that says "guess =" before the number?
39,462,287
<pre><code>import random guess = input("What is your guess?") answer = random.randint(0,100) while guess != answer: try: guess = float(guess) if guess &gt; answer: print ("Your guess is too high!") elif guess &lt; answer: print ("Your guess is too low!") elif guess == answer: print ("Congratulations!") break guess = input("What is your guess?") continue except ValueError: print ("Bad input. Try again!") guess = input("What is your guess?") </code></pre> <p>So my code works except that when i enter for example: guess = 30, it seems the input as invalid...how can I make it so it accepts it as a correct guess?</p> <p>New to python here :) Thanks.</p>
0
2016-09-13T04:36:06Z
39,462,551
<p>So I reordered your code:</p> <ul> <li><p>I narrowed <code>try/except</code> down to just the line which can cause the ValueError, because that makes it clear what particular error this <code>except</code> block is trying to handle - puts the error handling near the source of the error. This also makes a good reason to have <code>continue</code> because it now skips the "too high/too low" code, instead of in your code it does nothing.</p></li> <li><p>I changed the <code>while</code> loop condition so it says <code>while True:</code> to make it an infinite loop. In your code, <code>while guess != answer</code> implies that it will break when the guess is correct, you actually use <code>break</code> to exit the loop, so that is misleading. It would be sensible to use <code>while guess != answer</code> and not have <code>break</code> anywhere, but if you have to use <code>break</code> as part of the assignment then my code has some 'reason' to use it (breaking an infinite loop).</p></li> <li><p>I moved the <code>guess = input(...)</code> code inside the loop only, because it doesn't need to be duplicated at the top or inside the error handling. (Imagine if you had to change the text, 3 places is more annoying than 1 place).</p></li> <li><p>There are lots of ways to handle the <code>guess = 30</code> input. You could literally handle that, and only that, by looking for <code>if "guess = " in guess:</code> and then if that text matches, use <code>guess = guess.replace("guess = ", "")</code> to replace it away, leaving just the number. Or use regular expressions, as another answer has used to drop text and leave digits, or use string <code>split()</code>, as yet another answer has. My answer here has <code>filter()</code> which filters something using a test - in this case it tests if something is a number, and only allows numbers through, so it drops all the text. Same as the regex is doing, really, just a different approach.</p></li> </ul> <p>code:</p> <pre><code>import random answer = random.randint(0,100) while True: guess = input("What is your guess?") # filters out only the numbers # and makes them into a string, e.g. # 1) "guess = 30" # 2) [3,0] # 3) "30" guess = ''.join(filter(str.isdigit, guess)) try: guess = float(guess) except ValueError: print ("Bad input. Try again!") continue if guess &gt; answer: print ("Your guess is too high!") elif guess &lt; answer: print ("Your guess is too low!") else: print ("Congratulations!") break </code></pre> <p><a href="https://repl.it/D80v/1" rel="nofollow">Try it online at repl.it</a></p>
0
2016-09-13T05:09:36Z
[ "python", "python-3.x" ]
Unable to decorate a class method using Pint units
39,462,299
<p>Here's a very simple example in an effort to decorate a class method using Pint,</p> <pre><code>from pint import UnitRegistry ureg = UnitRegistry() Q_ = ureg.Quantity class Simple: def __init__(self): pass @ureg.wraps('m/s', (None, 'm/s'), True) def calculate(self, a, b): return a*b if __name__ == "__main__": c = Simple().calculate(1, Q_(10, 'm/s')) print c </code></pre> <p>This code results in the below ValueError.</p> <pre><code>Traceback (most recent call last): c = Simple().calculate(1, Q_(10, 'm/s')) File "build/bdist.macosx-10.11-intel/egg/pint/registry_helpers.py", line 167, in wrapper File "build/bdist.macosx-10.11-intel/egg/pint/registry_helpers.py", line 118, in _converter ValueError: A wrapped function using strict=True requires quantity for all arguments with not None units. (error found for m / s, 1) </code></pre> <p>It seems to me that the issue here may be with class instances being passed to the pint decorator. Would anyone have a solution for fixing this?</p>
2
2016-09-13T04:37:10Z
39,462,382
<p>I think the error message is pretty clear. <a href="https://pint.readthedocs.io/en/0.7.2/wrapping.html#strict-mode" rel="nofollow">In strict mode all arguments have to be given as <code>Quantity</code></a> yet you only give the second argument as such.</p> <p>You either give the first argument as a <code>Quantity</code> too</p> <pre><code>if __name__ == "__main__": c = Simple().calculate(Q_(1, 'm/s'), Q_(10, 'm/s')) print c </code></pre> <p>or you disable strict mode, which I believe is what you are looking for.</p> <pre><code> ... @ureg.wraps('m/s', (None, 'm/s'), False) def calculate(self, a, b): return a*b if __name__ == "__main__": c = Simple().calculate(1, Q_(10, 'm/s')) print c </code></pre>
1
2016-09-13T04:50:00Z
[ "python", "pint" ]
Unable to decorate a class method using Pint units
39,462,299
<p>Here's a very simple example in an effort to decorate a class method using Pint,</p> <pre><code>from pint import UnitRegistry ureg = UnitRegistry() Q_ = ureg.Quantity class Simple: def __init__(self): pass @ureg.wraps('m/s', (None, 'm/s'), True) def calculate(self, a, b): return a*b if __name__ == "__main__": c = Simple().calculate(1, Q_(10, 'm/s')) print c </code></pre> <p>This code results in the below ValueError.</p> <pre><code>Traceback (most recent call last): c = Simple().calculate(1, Q_(10, 'm/s')) File "build/bdist.macosx-10.11-intel/egg/pint/registry_helpers.py", line 167, in wrapper File "build/bdist.macosx-10.11-intel/egg/pint/registry_helpers.py", line 118, in _converter ValueError: A wrapped function using strict=True requires quantity for all arguments with not None units. (error found for m / s, 1) </code></pre> <p>It seems to me that the issue here may be with class instances being passed to the pint decorator. Would anyone have a solution for fixing this?</p>
2
2016-09-13T04:37:10Z
39,477,452
<p>Thanks for the answer. Keeping the strict mode, your first answer produces an output, i.e. make the first argument a pint Quantity too. However, the units of the output include a multiplication of the output unit specified in the wrapper and the units of the first argument too, which is incorrect. </p> <p>The solution is just to add another 'None' to the wrapper to account for the class instance, i.e.</p> <pre><code>@ureg.wraps('m/s', (None, None, 'm/s'), True) def calculate(self, a, b): return a*b </code></pre>
1
2016-09-13T19:16:58Z
[ "python", "pint" ]
reading data in tensorflow - TypeError("%s that don't all match." % prefix)
39,462,343
<p>I am trying to load the following data file (with 225805 rows) in tensor flow. The data file looks like this:</p> <pre><code>1,1,0.05,-1.05 1,1,0.1,-1.1 1,1,0.15,-1.15 1,1,0.2,-1.2 1,1,0.25,-1.25 1,1,0.3,-1.3 1,1,0.35,-1.35 </code></pre> <p>the code that reads the data is</p> <pre><code>import tensorflow as tf # read in data filename_queue = tf.train.string_input_producer(["~/input.data"]) reader = tf.TextLineReader() key, value = reader.read(filename_queue) record_defaults = [tf.constant([], dtype=tf.int32), # Column 1 tf.constant([], dtype=tf.int32), # Column 2 tf.constant([], dtype=tf.float32), # Column 3 tf.constant([], dtype=tf.float32)] # Column 4 col1, col2, col3, col4 = tf.decode_csv(value, record_defaults=record_defaults) features = tf.pack([col1, col2, col3]) with tf.Session() as sess: coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(225805): example, label = sess.run([features, col4]) coord.request_stop() coord.join(threads) </code></pre> <p>and this is the error I am getting</p> <pre><code>Traceback (most recent call last): File "dummy.py", line 16, in &lt;module&gt; features = tf.pack([col1, col2, col3]) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/array_ops.py", line 487, in pack return gen_array_ops._pack(values, axis=axis, name=name) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 1462, in _pack result = _op_def_lib.apply_op("Pack", values=values, axis=axis, name=name) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 437, in apply_op raise TypeError("%s that don't all match." % prefix) TypeError: Tensors in list passed to 'values' of 'Pack' Op have types [int32, int32, float32] that don't all match. </code></pre>
3
2016-09-13T04:43:31Z
39,462,574
<p>The <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/array_ops.html#pack" rel="nofollow"><code>tf.pack()</code></a> operator requires that all of the tensors passed to it have the same element type. In your program, the first two tensors have type <code>tf.int32</code>, while the third tensor has type <code>tf.float32</code>. The simplest solution is to cast the first two tensors to have type <code>tf.float32</code>, using the <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/array_ops.html#to_float" rel="nofollow"><code>tf.to_float()</code></a> operator:</p> <pre><code>features = tf.pack([tf.to_float(col1), tf.to_float(col2), col3]) </code></pre>
1
2016-09-13T05:12:21Z
[ "python", "tensorflow" ]
How to correct this for loop over tuple function in Python?
39,462,393
<p>Here is a program where each line was split into pairs using tuples, such that every alphabet had a corresponding numeric as A:6, B:6, C:35 ..etc If a value for less than 10, then the alphabets were converted to N. The following is the code. I find that my code does not loop over the tuple function in the last part of the code. It takes in only a single sequence and does not loop over the other</p> <pre><code>tutorial = open('c:/test/z.txt','r') ## Input file looks like &gt;qrst ABCDE-- 6 6 35 25 10 &gt;qqqq ABBDE-- 7 7 28 29 2 org = [] seqlist = [] seqstring = "" for line in tutorial: if line.startswith("&gt;"): if seqstring!= "": seqlist.append(seqstring) seqstring = "" org.append(line.rstrip("\n")) else: seqstring += line.rstrip("\n") seqlist.append(seqstring) l = seqlist #print l j = [] ll = len(seqlist) for i in range(0,ll): sq = l[i] sequence = sq.split(" ")[0] ## Stores only the alphabets qualities = sq.split(" ")[1:] ## Stores only the numeric qualities = filter(None, qualities) for sub in sequence: if sub == "-": ## If sequences have "-", it inserts a "0" in that position in corresponding number idx = list(sequence).index(sub) qualities.insert(idx,"0") # Error in the steps below pairs = [] for sub in l: print sub new_list = [] for x in range(len(sequence)): print x new_tuple = (sequence[x], qualities[x]) #Printing this step, notice that only one of the sequences is printed twice. ERROR print new_tuple if int(qualities[x]) &lt; 10: new_tuple = ("Z", qualities[x]) new_list.append(new_tuple) pairs.append(new_list) print pairs # When I print pairs it looks like this: [[('Z', '7'), ('Z', '7'), ('B', '28'), ('D', '29'), ('Z', '2'), ('Z', '0'), ('Z', '0')], [('Z', '7'), ('Z', '7'), ('B', '28'), ('D', '29'), ('Z', '2'), ('Z', '0'), ('Z', '0')]] # Sequence#2 is printed twice over. The first one is not taken in </code></pre>
0
2016-09-13T04:51:18Z
39,462,880
<pre><code>all_inputs = [] # &lt;---- add this for i in range(0,ll): sq = l[i] sequence = sq.split(" ")[0] ## Stores only the alphabets qualities = sq.split(" ")[1:] ## Stores only the numeric qualities = filter(None, qualities) for sub in sequence: if sub == "-": idx = list(sequence).index(sub) qualities.insert(idx,"0") # also add this *********************** all_inputs.append((sequence, qualities)) pairs = [] # change this ******************************* for sequence, qualities in all_inputs: print sub new_list = [] for x in range(len(sequence)): print x new_tuple = (sequence[x], qualities[x]) print new_tuple if int(qualities[x]) &lt; 10: new_tuple = ("Z", qualities[x]) new_list.append(new_tuple) pairs.append(new_list) print pairs </code></pre> <p>gives:</p> <pre><code>[[('Z', '6'), ('Z', '6'), ('C', '35'), ('D', '25'), ('E', '10'), ('Z', '0'), ('Z', '0')], [('Z', '7'), ('Z', '7'), ('B ', '28'), ('D', '29'), ('Z', '2'), ('Z', '0'), ('Z', '0')]] </code></pre>
0
2016-09-13T05:40:58Z
[ "python", "loops", "tuples" ]
Stacking arrays in numpy using vstack
39,462,433
<p><code>array1.shape</code> gives (180, ) <code>array2.shape</code> gives (180, 1)</p> <p>What's the difference between these two? And because of this difference I'm unable to stack them using</p> <pre><code>np.vstack((array2, array1)) </code></pre> <p>What changes should I make to array1 shape so that I can stack them up?</p>
2
2016-09-13T04:56:21Z
39,462,489
<p>Let's define some arrays:</p> <pre><code>&gt;&gt;&gt; x = np.zeros((4, 1)) &gt;&gt;&gt; y = np.zeros((4)) </code></pre> <p>As is, these arrays fail to stack:</p> <pre><code>&gt;&gt;&gt; np.vstack((x, y)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python3/dist-packages/numpy/core/shape_base.py", line 230, in vstack return _nx.concatenate([atleast_2d(_m) for _m in tup], 0) ValueError: all the input array dimensions except for the concatenation axis must match exactly </code></pre> <p>However, with a simple change, they will stack:</p> <pre><code>&gt;&gt;&gt; np.vstack((x, y[:, None])) array([[ 0.], [ 0.], [ 0.], [ 0.], [ 0.], [ 0.], [ 0.], [ 0.]]) </code></pre> <p>Alternatively:</p> <pre><code>&gt;&gt;&gt; np.vstack((x[:, 0], y)) array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]) </code></pre>
0
2016-09-13T05:02:07Z
[ "python", "numpy" ]
Stacking arrays in numpy using vstack
39,462,433
<p><code>array1.shape</code> gives (180, ) <code>array2.shape</code> gives (180, 1)</p> <p>What's the difference between these two? And because of this difference I'm unable to stack them using</p> <pre><code>np.vstack((array2, array1)) </code></pre> <p>What changes should I make to array1 shape so that I can stack them up?</p>
2
2016-09-13T04:56:21Z
39,462,663
<pre><code>In [81]: x1=np.ones((10,)); x2=np.ones((10,1)) </code></pre> <p>One array is 1d, the other 2d. <code>vertical</code> stack requires 2 dimensions, vertical and horizontal. So <code>np.vstack</code> passes each input through <code>np.atleast_2d</code>:</p> <pre><code>In [82]: np.atleast_2d(x1).shape Out[82]: (1, 10) </code></pre> <p>But now we have a (1,10) array and a (10,1) - they can't be joined in either axis.</p> <p>But if we reshape <code>x1</code> so it is <code>(10,1)</code>, then we can join it with <code>x2</code> in either direction:</p> <pre><code>In [83]: np.concatenate((x1[:,None],x2), axis=0).shape Out[83]: (20, 1) In [84]: np.concatenate((x1[:,None],x2), axis=1).shape Out[84]: (10, 2) </code></pre> <p>Print out the two arrays:</p> <pre><code>In [86]: x1 Out[86]: array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) In [87]: x2 Out[87]: array([[ 1.], [ 1.], [ 1.], [ 1.], [ 1.], [ 1.], [ 1.], [ 1.], [ 1.], [ 1.]]) </code></pre> <p>How can you concatenate those two shapes without some sort of adjustment?</p>
0
2016-09-13T05:22:15Z
[ "python", "numpy" ]
How to impute each categorical column in numpy array
39,462,449
<p>There are good solutions to impute panda dataframe. But since I am working mainly with numpy arrays, I have to create new panda DataFrame object, impute and then convert back to numpy array as follows:</p> <pre><code>nomDF=pd.DataFrame(x_nominal) #Convert np.array to pd.DataFrame nomDF=nomDF.apply(lambda x:x.fillna(x.value_counts().index[0])) #replace NaN with most frequent in each column x_nominal=nomDF.values #convert back pd.DataFrame to np.array </code></pre> <p>Is there a way to directly impute in numpy array?</p>
0
2016-09-13T04:57:56Z
39,462,695
<p>We could use <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.mstats.mode.html" rel="nofollow"><code>Scipy's mode</code></a> to get the highest value in each column. Leftover work would be to get the <code>NaN</code> indices and replace those in input array with the <code>mode</code> values by indexing. </p> <p>So, the implementation would look something like this -</p> <pre><code>from scipy.stats import mode R,C = np.where(np.isnan(x_nominal)) vals = mode(x_nominal,axis=0)[0].ravel() x_nominal[R,C] = vals[C] </code></pre> <p>Please note that for <code>pandas</code>, with <code>value_counts</code>, we would be choosing the highest value in case of many categories/elements with the same highest count. i.e. in tie situations. With <code>Scipy's mode</code>, it would be lowest one for such tie cases.</p> <p>If you are dealing with such mixed dtype of <code>strings</code> and <code>NaNs</code>, I would suggest few modifications, keeping the last step unchanged to make it work -</p> <pre><code>x_nominal_U3 = x_nominal.astype('U3') R,C = np.where(x_nominal_U3=='nan') vals = mode(x_nominal_U3,axis=0)[0].ravel() </code></pre> <p>This throws a warning for the mode calculation : <code>RuntimeWarning: The input array could not be properly checked for nan values. nan values will be ignored. "values. nan values will be ignored.", RuntimeWarning)</code>. But since, we actually want to ignore <code>NaNs</code> for that mode calculation, we should be okay there.</p>
1
2016-09-13T05:25:34Z
[ "python", "pandas", "numpy" ]
Pandas aggregate list in resample/groupby
39,462,522
<p>I have a dataframe in which each instance has a timestamp, an id and a list of numbers as follows: </p> <pre><code>timestamp | id | lists ---------------------------------- 2016-01-01 00:00:00 | 1 | [2, 10] 2016-01-01 05:00:00 | 1 | [9, 10, 3, 5] 2016-01-01 10:00:00 | 1 | [1, 10, 5] 2016-01-02 01:00:00 | 1 | [2, 6, 7] 2016-01-02 04:00:00 | 1 | [2, 6] 2016-01-01 02:00:00 | 2 | [0] 2016-01-01 08:00:00 | 2 | [10, 3, 2] 2016-01-01 14:00:00 | 2 | [0, 9, 3] 2016-01-02 03:00:00 | 2 | [0, 9, 2] </code></pre> <p>For each <em>id</em> I want to resample by day(and this is easy) and concatenate all the <em>lists</em> of the instances that happened in the same day. Resample + concat/sum does not work because resample removes all non-numeric columns (<a href="http://stackoverflow.com/questions/34257069/resampling-pandas-dataframe-is-deleting-column">see here</a>)</p> <p>I want to write something similar to this:</p> <pre><code>daily_data = data.groupby('id').resample('1D').concatenate() # .concatenate() does not exist </code></pre> <p>Result desired:</p> <pre><code>timestamp | id | lists ---------------------------------- 2016-01-01 | 1 | [2, 10, 9, 10, 3, 5, 1, 10, 5] 2016-01-02 | 1 | [2, 6, 7, 2, 6] 2016-01-01 | 2 | [0, 10, 3, 2] 2016-01-02 | 2 | [0, 9, 3, 0, 9, 2] </code></pre> <p>Here you can copy a script that generates the input I used for the description:</p> <pre><code>import pandas as pd from random import randint time = pd.to_datetime( ['2016-01-01 00:00:00', '2016-01-01 05:00:00', '2016-01-01 10:00:00', '2016-01-02 01:00:00', '2016-01-02 04:00:00', '2016-01-01 02:00:00', '2016-01-01 08:00:00', '2016-01-01 14:00:00', '2016-01-02 03:00:00' ] ) id_1 = [1] * 5 id_2 = [2] * 4 lists = [0] * 9 for i in range(9): l = [randint(0,10) for _ in range(randint(1,5) ) ] l = list(set(l)) lists[i] = l data = {'timestamp': time, 'id': id_1 + id_2, 'lists': lists} example = pd.DataFrame(data=data) </code></pre> <p>Bonus points if there is a way to optionally remove duplicates in the concatenated list.</p>
3
2016-09-13T05:06:12Z
39,463,226
<p>As pointed out by @jezrael, this only works in <strong><em>pandas version 0.18.1+</em></strong></p> <ul> <li><code>set_index</code> with <code>'timestamp'</code> to prep for later <code>resample</code></li> <li><code>groupby</code> <code>'id'</code> column and select <code>lists</code> columns</li> <li>after <code>resample</code>, <code>sum</code> of lists will concatenate them</li> <li><code>reset_index</code> to get columns in correct order</li> </ul> <hr> <pre><code>df.set_index('timestamp').groupby('id').lists.resample('D').sum() \ .reset_index('id').reset_index() </code></pre> <p><a href="http://i.stack.imgur.com/Zgilv.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zgilv.png" alt="enter image description here"></a></p>
6
2016-09-13T06:09:22Z
[ "python", "pandas", "dataframe" ]
Pandas aggregate list in resample/groupby
39,462,522
<p>I have a dataframe in which each instance has a timestamp, an id and a list of numbers as follows: </p> <pre><code>timestamp | id | lists ---------------------------------- 2016-01-01 00:00:00 | 1 | [2, 10] 2016-01-01 05:00:00 | 1 | [9, 10, 3, 5] 2016-01-01 10:00:00 | 1 | [1, 10, 5] 2016-01-02 01:00:00 | 1 | [2, 6, 7] 2016-01-02 04:00:00 | 1 | [2, 6] 2016-01-01 02:00:00 | 2 | [0] 2016-01-01 08:00:00 | 2 | [10, 3, 2] 2016-01-01 14:00:00 | 2 | [0, 9, 3] 2016-01-02 03:00:00 | 2 | [0, 9, 2] </code></pre> <p>For each <em>id</em> I want to resample by day(and this is easy) and concatenate all the <em>lists</em> of the instances that happened in the same day. Resample + concat/sum does not work because resample removes all non-numeric columns (<a href="http://stackoverflow.com/questions/34257069/resampling-pandas-dataframe-is-deleting-column">see here</a>)</p> <p>I want to write something similar to this:</p> <pre><code>daily_data = data.groupby('id').resample('1D').concatenate() # .concatenate() does not exist </code></pre> <p>Result desired:</p> <pre><code>timestamp | id | lists ---------------------------------- 2016-01-01 | 1 | [2, 10, 9, 10, 3, 5, 1, 10, 5] 2016-01-02 | 1 | [2, 6, 7, 2, 6] 2016-01-01 | 2 | [0, 10, 3, 2] 2016-01-02 | 2 | [0, 9, 3, 0, 9, 2] </code></pre> <p>Here you can copy a script that generates the input I used for the description:</p> <pre><code>import pandas as pd from random import randint time = pd.to_datetime( ['2016-01-01 00:00:00', '2016-01-01 05:00:00', '2016-01-01 10:00:00', '2016-01-02 01:00:00', '2016-01-02 04:00:00', '2016-01-01 02:00:00', '2016-01-01 08:00:00', '2016-01-01 14:00:00', '2016-01-02 03:00:00' ] ) id_1 = [1] * 5 id_2 = [2] * 4 lists = [0] * 9 for i in range(9): l = [randint(0,10) for _ in range(randint(1,5) ) ] l = list(set(l)) lists[i] = l data = {'timestamp': time, 'id': id_1 + id_2, 'lists': lists} example = pd.DataFrame(data=data) </code></pre> <p>Bonus points if there is a way to optionally remove duplicates in the concatenated list.</p>
3
2016-09-13T05:06:12Z
39,472,326
<p>for the unique count of each list item use list comprehension:</p> <pre><code>a = [list(set(l)) for l in df.lists] df.loc[:,'lists'] = a </code></pre>
0
2016-09-13T14:17:43Z
[ "python", "pandas", "dataframe" ]
how to run python files in windows command prompt?
39,462,632
<p>I want to run a python file in my command prompt but it does nothing. These are the screen shots of my program i am testing with and the output the command prompt gives me. <a href="http://i.stack.imgur.com/yHFIW.png" rel="nofollow"><img src="http://i.stack.imgur.com/yHFIW.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/Fz398.png" rel="nofollow"><img src="http://i.stack.imgur.com/Fz398.png" alt="enter image description here"></a></p>
-4
2016-09-13T05:19:06Z
39,462,781
<p>First set path of <code>python</code> <a href="http://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7">http://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows</a></p> <p>and run <code>python</code> file </p> <p><code>python filename.py</code></p> <p>command line argument with python</p> <p><code>python filename.py command-line argument</code></p>
1
2016-09-13T05:32:21Z
[ "python", "python-2.7", "command-line", "cmd", "command" ]
how to run python files in windows command prompt?
39,462,632
<p>I want to run a python file in my command prompt but it does nothing. These are the screen shots of my program i am testing with and the output the command prompt gives me. <a href="http://i.stack.imgur.com/yHFIW.png" rel="nofollow"><img src="http://i.stack.imgur.com/yHFIW.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/Fz398.png" rel="nofollow"><img src="http://i.stack.imgur.com/Fz398.png" alt="enter image description here"></a></p>
-4
2016-09-13T05:19:06Z
39,462,799
<p>You have to <code>install</code> <a href="https://www.python.org" rel="nofollow">Python</a> and add it to <a href="https://docs.python.org/2/using/windows.html" rel="nofollow">PATH</a> on <code>Windows</code>. After that you can try:</p> <pre><code>python `C:/pathToFolder/prog.py` </code></pre> <p>or go to the files directory and execute:</p> <pre><code>python prog.py </code></pre>
1
2016-09-13T05:33:37Z
[ "python", "python-2.7", "command-line", "cmd", "command" ]
how to run python files in windows command prompt?
39,462,632
<p>I want to run a python file in my command prompt but it does nothing. These are the screen shots of my program i am testing with and the output the command prompt gives me. <a href="http://i.stack.imgur.com/yHFIW.png" rel="nofollow"><img src="http://i.stack.imgur.com/yHFIW.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/Fz398.png" rel="nofollow"><img src="http://i.stack.imgur.com/Fz398.png" alt="enter image description here"></a></p>
-4
2016-09-13T05:19:06Z
39,463,070
<p>First go to the directory where your python script is present by using-</p> <pre><code>cd path/to/directory </code></pre> <p>then simply do:</p> <pre><code>python file_name.py </code></pre>
0
2016-09-13T05:57:38Z
[ "python", "python-2.7", "command-line", "cmd", "command" ]
RawPostDataException: You cannot access body after reading from request's data stream
39,462,717
<p>I am hosting a site on Google Cloud and I got everything to work beautifully and then all of the sudden I start getting this error..</p> <pre><code>01:16:22.222 Internal Server Error: /api/v1/auth/login/ (/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/exception.py:124) Traceback (most recent call last): File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 474, in dispatch response = self.handle_exception(exc) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 434, in handle_exception self.raise_uncaught_exception(exc) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 471, in dispatch response = handler(request, *args, **kwargs) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/authentication/views.py", line 42, in post data = json.loads(request.body) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/request.py", line 359, in __getattribute__ return getattr(self._request, attr) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/http/request.py", line 263, in body raise RawPostDataException("You cannot access body after reading from request's data stream") RawPostDataException: You cannot access body after reading from request's data stream </code></pre> <p>I have no clue what this means, and endless googling has not solved my case in anyway..</p> <p>Here's the code that is probably relevant:</p> <p><strong>views.py</strong></p> <pre><code>class LoginView(views.APIView): def post(self, request, format=None): data = json.loads(request.body) email = data.get('email', None) password = data.get('password', None) account = authenticate(email=email, password=password) if account is not None: if account.is_active: login(request, account) serialized = AccountSerializer(account) return Response(serialized.data) else: return Response({ 'status': 'Unauthorized', 'message': 'This account has been disabled.' }, status=status.HTTP_401_UNAUTHORIZED) else: return Response({ 'status': 'Unauthorized', 'message': 'Username/password combination invalid.' }, status=status.HTTP_401_UNAUTHORIZED) </code></pre> <p><strong>serializer.py</strong></p> <pre><code>class AccountSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) confirm_password = serializers.CharField(write_only=True, required=False) class Meta: model = Account fields = ('id', 'email', 'username', 'created_at', 'updated_at', 'full_name', 'password', 'confirm_password') read_only_fields = ('created_at', 'updated_at',) def create(self, validated_data): return Account.objects.create(**validated_data) def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.save() password = validated_data.get('password', None) confirm_password = validated_data.get('confirm_password', None) if password and confirm_password and password == confirm_password: instance.set_password(password) instance.save() update_session_auth_hash(self.context.get('request'), instance) return instance </code></pre>
0
2016-09-13T05:27:20Z
39,463,487
<p>This is occuring is because you are trying to access the data from <code>body</code></p> <p>use -> <code>data = json.loads(request.data)</code></p>
0
2016-09-13T06:27:42Z
[ "python", "django", "django-rest-framework" ]
RawPostDataException: You cannot access body after reading from request's data stream
39,462,717
<p>I am hosting a site on Google Cloud and I got everything to work beautifully and then all of the sudden I start getting this error..</p> <pre><code>01:16:22.222 Internal Server Error: /api/v1/auth/login/ (/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/exception.py:124) Traceback (most recent call last): File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 474, in dispatch response = self.handle_exception(exc) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 434, in handle_exception self.raise_uncaught_exception(exc) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/views.py", line 471, in dispatch response = handler(request, *args, **kwargs) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/authentication/views.py", line 42, in post data = json.loads(request.body) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/rest_framework/request.py", line 359, in __getattribute__ return getattr(self._request, attr) File "/base/data/home/apps/s~crs-portal/1.395605052160854207/lib/django/http/request.py", line 263, in body raise RawPostDataException("You cannot access body after reading from request's data stream") RawPostDataException: You cannot access body after reading from request's data stream </code></pre> <p>I have no clue what this means, and endless googling has not solved my case in anyway..</p> <p>Here's the code that is probably relevant:</p> <p><strong>views.py</strong></p> <pre><code>class LoginView(views.APIView): def post(self, request, format=None): data = json.loads(request.body) email = data.get('email', None) password = data.get('password', None) account = authenticate(email=email, password=password) if account is not None: if account.is_active: login(request, account) serialized = AccountSerializer(account) return Response(serialized.data) else: return Response({ 'status': 'Unauthorized', 'message': 'This account has been disabled.' }, status=status.HTTP_401_UNAUTHORIZED) else: return Response({ 'status': 'Unauthorized', 'message': 'Username/password combination invalid.' }, status=status.HTTP_401_UNAUTHORIZED) </code></pre> <p><strong>serializer.py</strong></p> <pre><code>class AccountSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) confirm_password = serializers.CharField(write_only=True, required=False) class Meta: model = Account fields = ('id', 'email', 'username', 'created_at', 'updated_at', 'full_name', 'password', 'confirm_password') read_only_fields = ('created_at', 'updated_at',) def create(self, validated_data): return Account.objects.create(**validated_data) def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.save() password = validated_data.get('password', None) confirm_password = validated_data.get('confirm_password', None) if password and confirm_password and password == confirm_password: instance.set_password(password) instance.save() update_session_auth_hash(self.context.get('request'), instance) return instance </code></pre>
0
2016-09-13T05:27:20Z
39,472,657
<p>hey thanks for the response but I figured it out! It wasn't working because I found a small bug where I am able to access the login page even though I am already logged in, so the error was caused by trying to login again. I fixed the issue by redirecting to home page if login page is tried to be reached</p>
0
2016-09-13T14:35:23Z
[ "python", "django", "django-rest-framework" ]
strange exceptions.SystemExit in Python 2.7
39,462,919
<p>Here is my code and error message, anyone have any ideas why there are such exception? Thanks.</p> <p><strong>Source Code</strong>,</p> <pre><code>import sys import tensorflow as tf def main(argv): print 'in main' def f(): # this method will call def main(argv) try: tf.app.run() except: print "tf.app.run error ", sys.exc_info() if __name__ == "__main__": f() </code></pre> <p><strong>Error Code</strong>,</p> <pre><code>in main tf.app.run error (&lt;type 'exceptions.SystemExit'&gt;, SystemExit(), &lt;traceback object at 0x10fa33f38&gt;) </code></pre>
0
2016-09-13T05:43:49Z
39,462,989
<p>It's coming from the <a href="https://docs.python.org/3/library/sys.html#sys.exit" rel="nofollow"><code>sys.exit()</code></a> call, about which the following is said:</p> <blockquote> <p>Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.</p> </blockquote> <p>In your case, <code>sys.exit</code> seems to be called from the function <a href="https://github.com/tensorflow/tensorflow/blob/f6990bffe06ac38f6cc4595eade32f0e0af4113d/tensorflow/python/platform/app.py#L30" rel="nofollow"><code>run()</code></a> unconditionally, so avoid intercepting <code>SystemExit</code>. </p> <p>If you want to handle all kinds of application-relevant exception, try catching <code>Exception</code> instead of the bare <code>except</code>, since <a href="https://docs.python.org/3/library/exceptions.html#SystemExit" rel="nofollow"><code>SystemExit</code></a>:</p> <blockquote> <p>...inherits from BaseException instead of Exception so that it is not accidentally caught by code that catches Exception. This allows the exception to properly propagate up and cause the interpreter to exit.</p> </blockquote>
1
2016-09-13T05:51:06Z
[ "python", "python-2.7", "exception", "tensorflow" ]
strange exceptions.SystemExit in Python 2.7
39,462,919
<p>Here is my code and error message, anyone have any ideas why there are such exception? Thanks.</p> <p><strong>Source Code</strong>,</p> <pre><code>import sys import tensorflow as tf def main(argv): print 'in main' def f(): # this method will call def main(argv) try: tf.app.run() except: print "tf.app.run error ", sys.exc_info() if __name__ == "__main__": f() </code></pre> <p><strong>Error Code</strong>,</p> <pre><code>in main tf.app.run error (&lt;type 'exceptions.SystemExit'&gt;, SystemExit(), &lt;traceback object at 0x10fa33f38&gt;) </code></pre>
0
2016-09-13T05:43:49Z
39,463,046
<p>This is expected behavior: <a href="https://github.com/tensorflow/tensorflow/blob/4f9a3a4def1d0e0bcc0c2ca4cd06d993024fd469/tensorflow/python/platform/app.py#L26" rel="nofollow"><code>tf.app.run()</code></a> passes the result of <code>main()</code> to <a href="https://docs.python.org/2/library/sys.html#sys.exit" rel="nofollow"><code>sys.exit()</code></a> (to make it easier to set an edit code), and <code>sys.exit()</code> raises an <a href="https://docs.python.org/2/library/exceptions.html#exceptions.SystemExit" rel="nofollow"><code>exceptions.SystemExit</code></a> exception.</p> <p>It's important to mention that using <code>tf.app.run()</code> is <strong>completely optional</strong>. Many TensorFlow scripts include it because it is more compatible with the Google Python coding style. However, if you need to customize the logic in your script, you are free to omit <code>tf.app.run()</code>. (The same applies to <code>tf.app.flags</code>.)</p>
1
2016-09-13T05:55:28Z
[ "python", "python-2.7", "exception", "tensorflow" ]